`,
- `div :matchesOwn(^\d+$)`,
- []string{
- `
01234567 89
`,
- `
567 `,
- },
- },
- {
- `
`,
- `[href#=(fina)]:not([href#=(\/\/[^\/]+untrusted)])`,
- []string{
- `
`,
- `
`,
- },
- },
- {
- `
`,
- `[href#=(^https:\/\/[^\/]*\/?news)]`,
- []string{
- `
`,
- },
- },
- {
- `
`,
- `:input`,
- []string{
- `
`,
- `
`,
- `
- Canada
- United States
- `,
- `
`,
- `
Sign up `,
- },
- },
- {
- ``,
- ":root",
- []string{
- "",
- },
- },
- {
- ``,
- "*:root",
- []string{
- "",
- },
- },
- {
- ``,
- "*:root:first-child",
- []string{},
- },
- {
- ``,
- "*:root:nth-child(1)",
- []string{},
- },
- {
- `
`,
- "a:not(:root)",
- []string{
- `
`,
- },
- },
-}
-
-func TestSelectors(t *testing.T) {
- for _, test := range selectorTests {
- s, err := Compile(test.selector)
- if err != nil {
- t.Errorf("error compiling %q: %s", test.selector, err)
- continue
- }
-
- doc, err := html.Parse(strings.NewReader(test.HTML))
- if err != nil {
- t.Errorf("error parsing %q: %s", test.HTML, err)
- continue
- }
-
- matches := s.MatchAll(doc)
- if len(matches) != len(test.results) {
- t.Errorf("selector %s wanted %d elements, got %d instead", test.selector, len(test.results), len(matches))
- continue
- }
-
- for i, m := range matches {
- got := nodeString(m)
- if got != test.results[i] {
- t.Errorf("selector %s wanted %s, got %s instead", test.selector, test.results[i], got)
- }
- }
-
- firstMatch := s.MatchFirst(doc)
- if len(test.results) == 0 {
- if firstMatch != nil {
- t.Errorf("MatchFirst: selector %s want nil, got %s", test.selector, nodeString(firstMatch))
- }
- } else {
- got := nodeString(firstMatch)
- if got != test.results[0] {
- t.Errorf("MatchFirst: selector %s want %s, got %s", test.selector, test.results[0], got)
- }
- }
- }
-}
diff --git a/vendor/github.com/asaskevich/govalidator/.travis.yml b/vendor/github.com/asaskevich/govalidator/.travis.yml
deleted file mode 100644
index e29f8ee..0000000
--- a/vendor/github.com/asaskevich/govalidator/.travis.yml
+++ /dev/null
@@ -1,14 +0,0 @@
-language: go
-
-go:
- - 1.1
- - 1.2
- - 1.3
- - 1.4
- - 1.5
- - 1.6
- - tip
-
-notifications:
- email:
- - bwatas@gmail.com
diff --git a/vendor/github.com/asaskevich/govalidator/LICENSE b/vendor/github.com/asaskevich/govalidator/LICENSE
deleted file mode 100644
index 2f9a31f..0000000
--- a/vendor/github.com/asaskevich/govalidator/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2014 Alex Saskevich
-
-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.
\ No newline at end of file
diff --git a/vendor/github.com/asaskevich/govalidator/README.md b/vendor/github.com/asaskevich/govalidator/README.md
deleted file mode 100644
index 9d2e135..0000000
--- a/vendor/github.com/asaskevich/govalidator/README.md
+++ /dev/null
@@ -1,423 +0,0 @@
-govalidator
-===========
-[](https://gitter.im/asaskevich/govalidator?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [](https://godoc.org/github.com/asaskevich/govalidator) [](https://coveralls.io/r/asaskevich/govalidator?branch=master) [](https://app.wercker.com/project/bykey/1ec990b09ea86c910d5f08b0e02c6043)
-[](https://travis-ci.org/asaskevich/govalidator) [](https://goreportcard.com/report/github.com/asaskevich/govalidator) [](http://go-search.org/view?id=github.com%2Fasaskevich%2Fgovalidator)
-
-A package of validators and sanitizers for strings, structs and collections. Based on [validator.js](https://github.com/chriso/validator.js).
-
-#### Installation
-Make sure that Go is installed on your computer.
-Type the following command in your terminal:
-
- go get github.com/asaskevich/govalidator
-
-or you can get specified release of the package with `gopkg.in`:
-
- go get gopkg.in/asaskevich/govalidator.v4
-
-After it the package is ready to use.
-
-
-#### Import package in your project
-Add following line in your `*.go` file:
-```go
-import "github.com/asaskevich/govalidator"
-```
-If you are unhappy to use long `govalidator`, you can do something like this:
-```go
-import (
- valid "github.com/asaskevich/govalidator"
-)
-```
-
-#### Activate behavior to require all fields have a validation tag by default
-`SetFieldsRequiredByDefault` causes validation to fail when struct fields do not include validations or are not explicitly marked as exempt (using `valid:"-"` or `valid:"email,optional"`). A good place to activate this is a package init function or the main() function.
-
-```go
-import "github.com/asaskevich/govalidator"
-
-func init() {
- govalidator.SetFieldsRequiredByDefault(true)
-}
-```
-
-Here's some code to explain it:
-```go
-// this struct definition will fail govalidator.ValidateStruct() (and the field values do not matter):
-type exampleStruct struct {
- Name string ``
- Email string `valid:"email"`
-}
-
-// this, however, will only fail when Email is empty or an invalid email address:
-type exampleStruct2 struct {
- Name string `valid:"-"`
- Email string `valid:"email"`
-}
-
-// lastly, this will only fail when Email is an invalid email address but not when it's empty:
-type exampleStruct2 struct {
- Name string `valid:"-"`
- Email string `valid:"email,optional"`
-}
-```
-
-#### Recent breaking changes (see [#123](https://github.com/asaskevich/govalidator/pull/123))
-##### Custom validator function signature
-A context was added as the second parameter, for structs this is the object being validated – this makes dependent validation possible.
-```go
-import "github.com/asaskevich/govalidator"
-
-// old signature
-func(i interface{}) bool
-
-// new signature
-func(i interface{}, o interface{}) bool
-```
-
-##### Adding a custom validator
-This was changed to prevent data races when accessing custom validators.
-```go
-import "github.com/asaskevich/govalidator"
-
-// before
-govalidator.CustomTypeTagMap["customByteArrayValidator"] = CustomTypeValidator(func(i interface{}, o interface{}) bool {
- // ...
-})
-
-// after
-govalidator.CustomTypeTagMap.Set("customByteArrayValidator", CustomTypeValidator(func(i interface{}, o interface{}) bool {
- // ...
-}))
-```
-
-#### List of functions:
-```go
-func Abs(value float64) float64
-func BlackList(str, chars string) string
-func ByteLength(str string, params ...string) bool
-func CamelCaseToUnderscore(str string) string
-func Contains(str, substring string) bool
-func Count(array []interface{}, iterator ConditionIterator) int
-func Each(array []interface{}, iterator Iterator)
-func ErrorByField(e error, field string) string
-func ErrorsByField(e error) map[string]string
-func Filter(array []interface{}, iterator ConditionIterator) []interface{}
-func Find(array []interface{}, iterator ConditionIterator) interface{}
-func GetLine(s string, index int) (string, error)
-func GetLines(s string) []string
-func InRange(value, left, right float64) bool
-func IsASCII(str string) bool
-func IsAlpha(str string) bool
-func IsAlphanumeric(str string) bool
-func IsBase64(str string) bool
-func IsByteLength(str string, min, max int) bool
-func IsCIDR(str string) bool
-func IsCreditCard(str string) bool
-func IsDNSName(str string) bool
-func IsDataURI(str string) bool
-func IsDialString(str string) bool
-func IsDivisibleBy(str, num string) bool
-func IsEmail(str string) bool
-func IsFilePath(str string) (bool, int)
-func IsFloat(str string) bool
-func IsFullWidth(str string) bool
-func IsHalfWidth(str string) bool
-func IsHexadecimal(str string) bool
-func IsHexcolor(str string) bool
-func IsHost(str string) bool
-func IsIP(str string) bool
-func IsIPv4(str string) bool
-func IsIPv6(str string) bool
-func IsISBN(str string, version int) bool
-func IsISBN10(str string) bool
-func IsISBN13(str string) bool
-func IsISO3166Alpha2(str string) bool
-func IsISO3166Alpha3(str string) bool
-func IsISO693Alpha2(str string) bool
-func IsISO693Alpha3b(str string) bool
-func IsISO4217(str string) bool
-func IsIn(str string, params ...string) bool
-func IsInt(str string) bool
-func IsJSON(str string) bool
-func IsLatitude(str string) bool
-func IsLongitude(str string) bool
-func IsLowerCase(str string) bool
-func IsMAC(str string) bool
-func IsMongoID(str string) bool
-func IsMultibyte(str string) bool
-func IsNatural(value float64) bool
-func IsNegative(value float64) bool
-func IsNonNegative(value float64) bool
-func IsNonPositive(value float64) bool
-func IsNull(str string) bool
-func IsNumeric(str string) bool
-func IsPort(str string) bool
-func IsPositive(value float64) bool
-func IsPrintableASCII(str string) bool
-func IsRFC3339(str string) bool
-func IsRGBcolor(str string) bool
-func IsRequestURI(rawurl string) bool
-func IsRequestURL(rawurl string) bool
-func IsSSN(str string) bool
-func IsSemver(str string) bool
-func IsTime(str string, format string) bool
-func IsURL(str string) bool
-func IsUTFDigit(str string) bool
-func IsUTFLetter(str string) bool
-func IsUTFLetterNumeric(str string) bool
-func IsUTFNumeric(str string) bool
-func IsUUID(str string) bool
-func IsUUIDv3(str string) bool
-func IsUUIDv4(str string) bool
-func IsUUIDv5(str string) bool
-func IsUpperCase(str string) bool
-func IsVariableWidth(str string) bool
-func IsWhole(value float64) bool
-func LeftTrim(str, chars string) string
-func Map(array []interface{}, iterator ResultIterator) []interface{}
-func Matches(str, pattern string) bool
-func NormalizeEmail(str string) (string, error)
-func PadBoth(str string, padStr string, padLen int) string
-func PadLeft(str string, padStr string, padLen int) string
-func PadRight(str string, padStr string, padLen int) string
-func Range(str string, params ...string) bool
-func RemoveTags(s string) string
-func ReplacePattern(str, pattern, replace string) string
-func Reverse(s string) string
-func RightTrim(str, chars string) string
-func RuneLength(str string, params ...string) bool
-func SafeFileName(str string) string
-func SetFieldsRequiredByDefault(value bool)
-func Sign(value float64) float64
-func StringLength(str string, params ...string) bool
-func StringMatches(s string, params ...string) bool
-func StripLow(str string, keepNewLines bool) string
-func ToBoolean(str string) (bool, error)
-func ToFloat(str string) (float64, error)
-func ToInt(str string) (int64, error)
-func ToJSON(obj interface{}) (string, error)
-func ToString(obj interface{}) string
-func Trim(str, chars string) string
-func Truncate(str string, length int, ending string) string
-func UnderscoreToCamelCase(s string) string
-func ValidateStruct(s interface{}) (bool, error)
-func WhiteList(str, chars string) string
-type ConditionIterator
-type CustomTypeValidator
-type Error
-func (e Error) Error() string
-type Errors
-func (es Errors) Error() string
-func (es Errors) Errors() []error
-type ISO3166Entry
-type Iterator
-type ParamValidator
-type ResultIterator
-type UnsupportedTypeError
-func (e *UnsupportedTypeError) Error() string
-type Validator
-```
-
-#### Examples
-###### IsURL
-```go
-println(govalidator.IsURL(`http://user@pass:domain.com/path/page`))
-```
-###### ToString
-```go
-type User struct {
- FirstName string
- LastName string
-}
-
-str := govalidator.ToString(&User{"John", "Juan"})
-println(str)
-```
-###### Each, Map, Filter, Count for slices
-Each iterates over the slice/array and calls Iterator for every item
-```go
-data := []interface{}{1, 2, 3, 4, 5}
-var fn govalidator.Iterator = func(value interface{}, index int) {
- println(value.(int))
-}
-govalidator.Each(data, fn)
-```
-```go
-data := []interface{}{1, 2, 3, 4, 5}
-var fn govalidator.ResultIterator = func(value interface{}, index int) interface{} {
- return value.(int) * 3
-}
-_ = govalidator.Map(data, fn) // result = []interface{}{1, 6, 9, 12, 15}
-```
-```go
-data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
-var fn govalidator.ConditionIterator = func(value interface{}, index int) bool {
- return value.(int)%2 == 0
-}
-_ = govalidator.Filter(data, fn) // result = []interface{}{2, 4, 6, 8, 10}
-_ = govalidator.Count(data, fn) // result = 5
-```
-###### ValidateStruct [#2](https://github.com/asaskevich/govalidator/pull/2)
-If you want to validate structs, you can use tag `valid` for any field in your structure. All validators used with this field in one tag are separated by comma. If you want to skip validation, place `-` in your tag. If you need a validator that is not on the list below, you can add it like this:
-```go
-govalidator.TagMap["duck"] = govalidator.Validator(func(str string) bool {
- return str == "duck"
-})
-```
-For completely custom validators (interface-based), see below.
-
-Here is a list of available validators for struct fields (validator - used function):
-```go
-"email": IsEmail,
-"url": IsURL,
-"dialstring": IsDialString,
-"requrl": IsRequestURL,
-"requri": IsRequestURI,
-"alpha": IsAlpha,
-"utfletter": IsUTFLetter,
-"alphanum": IsAlphanumeric,
-"utfletternum": IsUTFLetterNumeric,
-"numeric": IsNumeric,
-"utfnumeric": IsUTFNumeric,
-"utfdigit": IsUTFDigit,
-"hexadecimal": IsHexadecimal,
-"hexcolor": IsHexcolor,
-"rgbcolor": IsRGBcolor,
-"lowercase": IsLowerCase,
-"uppercase": IsUpperCase,
-"int": IsInt,
-"float": IsFloat,
-"null": IsNull,
-"uuid": IsUUID,
-"uuidv3": IsUUIDv3,
-"uuidv4": IsUUIDv4,
-"uuidv5": IsUUIDv5,
-"creditcard": IsCreditCard,
-"isbn10": IsISBN10,
-"isbn13": IsISBN13,
-"json": IsJSON,
-"multibyte": IsMultibyte,
-"ascii": IsASCII,
-"printableascii": IsPrintableASCII,
-"fullwidth": IsFullWidth,
-"halfwidth": IsHalfWidth,
-"variablewidth": IsVariableWidth,
-"base64": IsBase64,
-"datauri": IsDataURI,
-"ip": IsIP,
-"port": IsPort,
-"ipv4": IsIPv4,
-"ipv6": IsIPv6,
-"dns": IsDNSName,
-"host": IsHost,
-"mac": IsMAC,
-"latitude": IsLatitude,
-"longitude": IsLongitude,
-"ssn": IsSSN,
-"semver": IsSemver,
-"rfc3339": IsRFC3339,
-"ISO3166Alpha2": IsISO3166Alpha2,
-"ISO3166Alpha3": IsISO3166Alpha3,
-```
-Validators with parameters
-
-```go
-"range(min|max)": Range,
-"length(min|max)": ByteLength,
-"runelength(min|max)": RuneLength,
-"matches(pattern)": StringMatches,
-"in(string1|string2|...|stringN)": IsIn,
-```
-
-And here is small example of usage:
-```go
-type Post struct {
- Title string `valid:"alphanum,required"`
- Message string `valid:"duck,ascii"`
- AuthorIP string `valid:"ipv4"`
- Date string `valid:"-"`
-}
-post := &Post{
- Title: "My Example Post",
- Message: "duck",
- AuthorIP: "123.234.54.3",
-}
-
-// Add your own struct validation tags
-govalidator.TagMap["duck"] = govalidator.Validator(func(str string) bool {
- return str == "duck"
-})
-
-result, err := govalidator.ValidateStruct(post)
-if err != nil {
- println("error: " + err.Error())
-}
-println(result)
-```
-###### WhiteList
-```go
-// Remove all characters from string ignoring characters between "a" and "z"
-println(govalidator.WhiteList("a3a43a5a4a3a2a23a4a5a4a3a4", "a-z") == "aaaaaaaaaaaa")
-```
-
-###### Custom validation functions
-Custom validation using your own domain specific validators is also available - here's an example of how to use it:
-```go
-import "github.com/asaskevich/govalidator"
-
-type CustomByteArray [6]byte // custom types are supported and can be validated
-
-type StructWithCustomByteArray struct {
- ID CustomByteArray `valid:"customByteArrayValidator,customMinLengthValidator"` // multiple custom validators are possible as well and will be evaluated in sequence
- Email string `valid:"email"`
- CustomMinLength int `valid:"-"`
-}
-
-govalidator.CustomTypeTagMap.Set("customByteArrayValidator", CustomTypeValidator(func(i interface{}, context interface{}) bool {
- switch v := context.(type) { // you can type switch on the context interface being validated
- case StructWithCustomByteArray:
- // you can check and validate against some other field in the context,
- // return early or not validate against the context at all – your choice
- case SomeOtherType:
- // ...
- default:
- // expecting some other type? Throw/panic here or continue
- }
-
- switch v := i.(type) { // type switch on the struct field being validated
- case CustomByteArray:
- for _, e := range v { // this validator checks that the byte array is not empty, i.e. not all zeroes
- if e != 0 {
- return true
- }
- }
- }
- return false
-}))
-govalidator.CustomTypeTagMap.Set("customMinLengthValidator", CustomTypeValidator(func(i interface{}, context interface{}) bool {
- switch v := context.(type) { // this validates a field against the value in another field, i.e. dependent validation
- case StructWithCustomByteArray:
- return len(v.ID) >= v.CustomMinLength
- }
- return false
-}))
-```
-
-#### Notes
-Documentation is available here: [godoc.org](https://godoc.org/github.com/asaskevich/govalidator).
-Full information about code coverage is also available here: [govalidator on gocover.io](http://gocover.io/github.com/asaskevich/govalidator).
-
-#### Support
-If you do have a contribution for the package feel free to put up a Pull Request or open Issue.
-
-#### Special thanks to [contributors](https://github.com/asaskevich/govalidator/graphs/contributors)
-* [Daniel Lohse](https://github.com/annismckenzie)
-* [Attila Oláh](https://github.com/attilaolah)
-* [Daniel Korner](https://github.com/Dadie)
-* [Steven Wilkin](https://github.com/stevenwilkin)
-* [Deiwin Sarjas](https://github.com/deiwin)
-* [Noah Shibley](https://github.com/slugmobile)
-* [Nathan Davies](https://github.com/nathj07)
-* [Matt Sanford](https://github.com/mzsanford)
-* [Simon ccl1115](https://github.com/ccl1115)
diff --git a/vendor/github.com/asaskevich/govalidator/arrays.go b/vendor/github.com/asaskevich/govalidator/arrays.go
deleted file mode 100644
index 5bace26..0000000
--- a/vendor/github.com/asaskevich/govalidator/arrays.go
+++ /dev/null
@@ -1,58 +0,0 @@
-package govalidator
-
-// Iterator is the function that accepts element of slice/array and its index
-type Iterator func(interface{}, int)
-
-// ResultIterator is the function that accepts element of slice/array and its index and returns any result
-type ResultIterator func(interface{}, int) interface{}
-
-// ConditionIterator is the function that accepts element of slice/array and its index and returns boolean
-type ConditionIterator func(interface{}, int) bool
-
-// Each iterates over the slice and apply Iterator to every item
-func Each(array []interface{}, iterator Iterator) {
- for index, data := range array {
- iterator(data, index)
- }
-}
-
-// Map iterates over the slice and apply ResultIterator to every item. Returns new slice as a result.
-func Map(array []interface{}, iterator ResultIterator) []interface{} {
- var result = make([]interface{}, len(array))
- for index, data := range array {
- result[index] = iterator(data, index)
- }
- return result
-}
-
-// Find iterates over the slice and apply ConditionIterator to every item. Returns first item that meet ConditionIterator or nil otherwise.
-func Find(array []interface{}, iterator ConditionIterator) interface{} {
- for index, data := range array {
- if iterator(data, index) {
- return data
- }
- }
- return nil
-}
-
-// Filter iterates over the slice and apply ConditionIterator to every item. Returns new slice.
-func Filter(array []interface{}, iterator ConditionIterator) []interface{} {
- var result = make([]interface{}, 0)
- for index, data := range array {
- if iterator(data, index) {
- result = append(result, data)
- }
- }
- return result
-}
-
-// Count iterates over the slice and apply ConditionIterator to every item. Returns count of items that meets ConditionIterator.
-func Count(array []interface{}, iterator ConditionIterator) int {
- count := 0
- for index, data := range array {
- if iterator(data, index) {
- count = count + 1
- }
- }
- return count
-}
diff --git a/vendor/github.com/asaskevich/govalidator/arrays_test.go b/vendor/github.com/asaskevich/govalidator/arrays_test.go
deleted file mode 100644
index 1a9ac66..0000000
--- a/vendor/github.com/asaskevich/govalidator/arrays_test.go
+++ /dev/null
@@ -1,116 +0,0 @@
-package govalidator
-
-import "testing"
-
-func TestEach(t *testing.T) {
- // TODO Maybe refactor?
- t.Parallel()
- acc := 0
- data := []interface{}{1, 2, 3, 4, 5}
- var fn Iterator = func(value interface{}, index int) {
- acc = acc + value.(int)
- }
- Each(data, fn)
- if acc != 15 {
- t.Errorf("Expected Each(..) to be %v, got %v", 15, acc)
- }
-}
-
-func ExampleEach() {
- data := []interface{}{1, 2, 3, 4, 5}
- var fn Iterator = func(value interface{}, index int) {
- println(value.(int))
- }
- Each(data, fn)
-}
-
-func TestMap(t *testing.T) {
- // TODO Maybe refactor?
- t.Parallel()
- data := []interface{}{1, 2, 3, 4, 5}
- var fn ResultIterator = func(value interface{}, index int) interface{} {
- return value.(int) * 3
- }
- result := Map(data, fn)
- for i, d := range result {
- if d != fn(data[i], i) {
- t.Errorf("Expected Map(..) to be %v, got %v", fn(data[i], i), d)
- }
- }
-}
-
-func ExampleMap() {
- data := []interface{}{1, 2, 3, 4, 5}
- var fn ResultIterator = func(value interface{}, index int) interface{} {
- return value.(int) * 3
- }
- _ = Map(data, fn) // result = []interface{}{1, 6, 9, 12, 15}
-}
-
-func TestFind(t *testing.T) {
- // TODO Maybe refactor?
- t.Parallel()
- findElement := 96
- data := []interface{}{1, 2, 3, 4, findElement, 5}
- var fn1 ConditionIterator = func(value interface{}, index int) bool {
- return value.(int) == findElement
- }
- var fn2 ConditionIterator = func(value interface{}, index int) bool {
- value, _ = value.(string)
- return value == "govalidator"
- }
- val1 := Find(data, fn1)
- val2 := Find(data, fn2)
- if val1 != findElement {
- t.Errorf("Expected Find(..) to be %v, got %v", findElement, val1)
- }
- if val2 != nil {
- t.Errorf("Expected Find(..) to be %v, got %v", nil, val2)
- }
-}
-
-func TestFilter(t *testing.T) {
- // TODO Maybe refactor?
- t.Parallel()
- data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
- answer := []interface{}{2, 4, 6, 8, 10}
- var fn ConditionIterator = func(value interface{}, index int) bool {
- return value.(int)%2 == 0
- }
- result := Filter(data, fn)
- for i := range result {
- if result[i] != answer[i] {
- t.Errorf("Expected Filter(..) to be %v, got %v", answer[i], result[i])
- }
- }
-}
-
-func ExampleFilter() {
- data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
- var fn ConditionIterator = func(value interface{}, index int) bool {
- return value.(int)%2 == 0
- }
- _ = Filter(data, fn) // result = []interface{}{2, 4, 6, 8, 10}
-}
-
-func TestCount(t *testing.T) {
- // TODO Maybe refactor?
- t.Parallel()
- data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
- count := 5
- var fn ConditionIterator = func(value interface{}, index int) bool {
- return value.(int)%2 == 0
- }
- result := Count(data, fn)
- if result != count {
- t.Errorf("Expected Count(..) to be %v, got %v", count, result)
- }
-}
-
-func ExampleCount() {
- data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
- var fn ConditionIterator = func(value interface{}, index int) bool {
- return value.(int)%2 == 0
- }
- _ = Count(data, fn) // result = 5
-}
diff --git a/vendor/github.com/asaskevich/govalidator/converter.go b/vendor/github.com/asaskevich/govalidator/converter.go
deleted file mode 100644
index d69114c..0000000
--- a/vendor/github.com/asaskevich/govalidator/converter.go
+++ /dev/null
@@ -1,45 +0,0 @@
-package govalidator
-
-import (
- "encoding/json"
- "fmt"
- "strconv"
-)
-
-// ToString convert the input to a string.
-func ToString(obj interface{}) string {
- res := fmt.Sprintf("%v", obj)
- return string(res)
-}
-
-// ToJSON convert the input to a valid JSON string
-func ToJSON(obj interface{}) (string, error) {
- res, err := json.Marshal(obj)
- if err != nil {
- res = []byte("")
- }
- return string(res), err
-}
-
-// ToFloat convert the input string to a float, or 0.0 if the input is not a float.
-func ToFloat(str string) (float64, error) {
- res, err := strconv.ParseFloat(str, 64)
- if err != nil {
- res = 0.0
- }
- return res, err
-}
-
-// ToInt convert the input string to an integer, or 0 if the input is not an integer.
-func ToInt(str string) (int64, error) {
- res, err := strconv.ParseInt(str, 0, 64)
- if err != nil {
- res = 0
- }
- return res, err
-}
-
-// ToBoolean convert the input string to a boolean.
-func ToBoolean(str string) (bool, error) {
- return strconv.ParseBool(str)
-}
diff --git a/vendor/github.com/asaskevich/govalidator/converter_test.go b/vendor/github.com/asaskevich/govalidator/converter_test.go
deleted file mode 100644
index ecc457b..0000000
--- a/vendor/github.com/asaskevich/govalidator/converter_test.go
+++ /dev/null
@@ -1,78 +0,0 @@
-package govalidator
-
-import (
- "fmt"
- "testing"
-)
-
-func TestToInt(t *testing.T) {
- tests := []string{"1000", "-123", "abcdef", "100000000000000000000000000000000000000000000"}
- expected := []int64{1000, -123, 0, 0}
- for i := 0; i < len(tests); i++ {
- result, _ := ToInt(tests[i])
- if result != expected[i] {
- t.Log("Case ", i, ": expected ", expected[i], " when result is ", result)
- t.FailNow()
- }
- }
-}
-
-func TestToBoolean(t *testing.T) {
- tests := []string{"true", "1", "True", "false", "0", "abcdef"}
- expected := []bool{true, true, true, false, false, false}
- for i := 0; i < len(tests); i++ {
- res, _ := ToBoolean(tests[i])
- if res != expected[i] {
- t.Log("Case ", i, ": expected ", expected[i], " when result is ", res)
- t.FailNow()
- }
- }
-}
-
-func toString(t *testing.T, test interface{}, expected string) {
- res := ToString(test)
- if res != expected {
- t.Log("Case ToString: expected ", expected, " when result is ", res)
- t.FailNow()
- }
-}
-
-func TestToString(t *testing.T) {
- toString(t, "str123", "str123")
- toString(t, 123, "123")
- toString(t, 12.3, "12.3")
- toString(t, true, "true")
- toString(t, 1.5+10i, "(1.5+10i)")
- // Sprintf function not guarantee that maps with equal keys always will be equal in string representation
- //toString(t, struct{ Keys map[int]int }{Keys: map[int]int{1: 2, 3: 4}}, "{map[1:2 3:4]}")
-}
-
-func TestToFloat(t *testing.T) {
- tests := []string{"", "123", "-.01", "10.", "string", "1.23e3", ".23e10"}
- expected := []float64{0, 123, -0.01, 10.0, 0, 1230, 0.23e10}
- for i := 0; i < len(tests); i++ {
- res, _ := ToFloat(tests[i])
- if res != expected[i] {
- t.Log("Case ", i, ": expected ", expected[i], " when result is ", res)
- t.FailNow()
- }
- }
-}
-
-func TestToJSON(t *testing.T) {
- tests := []interface{}{"test", map[string]string{"a": "b", "b": "c"}, func() error { return fmt.Errorf("Error") }}
- expected := [][]string{
- {"\"test\"", "
"},
- {"{\"a\":\"b\",\"b\":\"c\"}", ""},
- {"", "json: unsupported type: func() error"},
- }
- for i, test := range tests {
- actual, err := ToJSON(test)
- if actual != expected[i][0] {
- t.Errorf("Expected toJSON(%v) to return '%v', got '%v'", test, expected[i][0], actual)
- }
- if fmt.Sprintf("%v", err) != expected[i][1] {
- t.Errorf("Expected error returned from toJSON(%v) to return '%v', got '%v'", test, expected[i][1], fmt.Sprintf("%v", err))
- }
- }
-}
diff --git a/vendor/github.com/asaskevich/govalidator/error.go b/vendor/github.com/asaskevich/govalidator/error.go
deleted file mode 100644
index 280b1c4..0000000
--- a/vendor/github.com/asaskevich/govalidator/error.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package govalidator
-
-// Errors is an array of multiple errors and conforms to the error interface.
-type Errors []error
-
-// Errors returns itself.
-func (es Errors) Errors() []error {
- return es
-}
-
-func (es Errors) Error() string {
- var err string
- for _, e := range es {
- err += e.Error() + ";"
- }
- return err
-}
-
-// Error encapsulates a name, an error and whether there's a custom error message or not.
-type Error struct {
- Name string
- Err error
- CustomErrorMessageExists bool
-}
-
-func (e Error) Error() string {
- if e.CustomErrorMessageExists {
- return e.Err.Error()
- }
- return e.Name + ": " + e.Err.Error()
-}
diff --git a/vendor/github.com/asaskevich/govalidator/error_test.go b/vendor/github.com/asaskevich/govalidator/error_test.go
deleted file mode 100644
index 274cc0d..0000000
--- a/vendor/github.com/asaskevich/govalidator/error_test.go
+++ /dev/null
@@ -1,29 +0,0 @@
-package govalidator
-
-import (
- "fmt"
- "testing"
-)
-
-func TestErrorsToString(t *testing.T) {
- t.Parallel()
- customErr := &Error{Name: "Custom Error Name", Err: fmt.Errorf("stdlib error")}
- customErrWithCustomErrorMessage := &Error{Name: "Custom Error Name 2", Err: fmt.Errorf("Bad stuff happened"), CustomErrorMessageExists: true}
-
- var tests = []struct {
- param1 Errors
- expected string
- }{
- {Errors{}, ""},
- {Errors{fmt.Errorf("Error 1")}, "Error 1;"},
- {Errors{fmt.Errorf("Error 1"), fmt.Errorf("Error 2")}, "Error 1;Error 2;"},
- {Errors{customErr, fmt.Errorf("Error 2")}, "Custom Error Name: stdlib error;Error 2;"},
- {Errors{fmt.Errorf("Error 123"), customErrWithCustomErrorMessage}, "Error 123;Bad stuff happened;"},
- }
- for _, test := range tests {
- actual := test.param1.Error()
- if actual != test.expected {
- t.Errorf("Expected Error() to return '%v', got '%v'", test.expected, actual)
- }
- }
-}
diff --git a/vendor/github.com/asaskevich/govalidator/numerics.go b/vendor/github.com/asaskevich/govalidator/numerics.go
deleted file mode 100644
index 5be281f..0000000
--- a/vendor/github.com/asaskevich/govalidator/numerics.go
+++ /dev/null
@@ -1,57 +0,0 @@
-package govalidator
-
-import "math"
-
-// Abs returns absolute value of number
-func Abs(value float64) float64 {
- return math.Abs(value)
-}
-
-// Sign returns signum of number: 1 in case of value > 0, -1 in case of value < 0, 0 otherwise
-func Sign(value float64) float64 {
- if value > 0 {
- return 1
- } else if value < 0 {
- return -1
- } else {
- return 0
- }
-}
-
-// IsNegative returns true if value < 0
-func IsNegative(value float64) bool {
- return value < 0
-}
-
-// IsPositive returns true if value > 0
-func IsPositive(value float64) bool {
- return value > 0
-}
-
-// IsNonNegative returns true if value >= 0
-func IsNonNegative(value float64) bool {
- return value >= 0
-}
-
-// IsNonPositive returns true if value <= 0
-func IsNonPositive(value float64) bool {
- return value <= 0
-}
-
-// InRange returns true if value lies between left and right border
-func InRange(value, left, right float64) bool {
- if left > right {
- left, right = right, left
- }
- return value >= left && value <= right
-}
-
-// IsWhole returns true if value is whole number
-func IsWhole(value float64) bool {
- return math.Remainder(value, 1) == 0
-}
-
-// IsNatural returns true if value is natural number (positive and whole)
-func IsNatural(value float64) bool {
- return IsWhole(value) && IsPositive(value)
-}
diff --git a/vendor/github.com/asaskevich/govalidator/numerics_test.go b/vendor/github.com/asaskevich/govalidator/numerics_test.go
deleted file mode 100644
index 1bad521..0000000
--- a/vendor/github.com/asaskevich/govalidator/numerics_test.go
+++ /dev/null
@@ -1,204 +0,0 @@
-package govalidator
-
-import "testing"
-
-func TestAbs(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param float64
- expected float64
- }{
- {0, 0},
- {-1, 1},
- {10, 10},
- {3.14, 3.14},
- {-96, 96},
- {-10e-12, 10e-12},
- }
- for _, test := range tests {
- actual := Abs(test.param)
- if actual != test.expected {
- t.Errorf("Expected Abs(%v) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestSign(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param float64
- expected float64
- }{
- {0, 0},
- {-1, -1},
- {10, 1},
- {3.14, 1},
- {-96, -1},
- {-10e-12, -1},
- }
- for _, test := range tests {
- actual := Sign(test.param)
- if actual != test.expected {
- t.Errorf("Expected Sign(%v) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsNegative(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param float64
- expected bool
- }{
- {0, false},
- {-1, true},
- {10, false},
- {3.14, false},
- {-96, true},
- {-10e-12, true},
- }
- for _, test := range tests {
- actual := IsNegative(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsNegative(%v) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsNonNegative(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param float64
- expected bool
- }{
- {0, true},
- {-1, false},
- {10, true},
- {3.14, true},
- {-96, false},
- {-10e-12, false},
- }
- for _, test := range tests {
- actual := IsNonNegative(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsNonNegative(%v) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsPositive(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param float64
- expected bool
- }{
- {0, false},
- {-1, false},
- {10, true},
- {3.14, true},
- {-96, false},
- {-10e-12, false},
- }
- for _, test := range tests {
- actual := IsPositive(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsPositive(%v) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsNonPositive(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param float64
- expected bool
- }{
- {0, true},
- {-1, true},
- {10, false},
- {3.14, false},
- {-96, true},
- {-10e-12, true},
- }
- for _, test := range tests {
- actual := IsNonPositive(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsNonPositive(%v) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsWhole(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param float64
- expected bool
- }{
- {0, true},
- {-1, true},
- {10, true},
- {3.14, false},
- {-96, true},
- {-10e-12, false},
- }
- for _, test := range tests {
- actual := IsWhole(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsWhole(%v) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsNatural(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param float64
- expected bool
- }{
- {0, false},
- {-1, false},
- {10, true},
- {3.14, false},
- {96, true},
- {-10e-12, false},
- }
- for _, test := range tests {
- actual := IsNatural(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsNatural(%v) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-func TestInRange(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param float64
- left float64
- right float64
- expected bool
- }{
- {0, 0, 0, true},
- {1, 0, 0, false},
- {-1, 0, 0, false},
- {0, -1, 1, true},
- {0, 0, 1, true},
- {0, -1, 0, true},
- {0, 0, -1, true},
- {0, 10, 5, false},
- }
- for _, test := range tests {
- actual := InRange(test.param, test.left, test.right)
- if actual != test.expected {
- t.Errorf("Expected InRange(%v, %v, %v) to be %v, got %v", test.param, test.left, test.right, test.expected, actual)
- }
- }
-}
diff --git a/vendor/github.com/asaskevich/govalidator/patterns.go b/vendor/github.com/asaskevich/govalidator/patterns.go
deleted file mode 100644
index 5297595..0000000
--- a/vendor/github.com/asaskevich/govalidator/patterns.go
+++ /dev/null
@@ -1,91 +0,0 @@
-package govalidator
-
-import "regexp"
-
-// Basic regular expressions for validating strings
-const (
- Email string = "^(((([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+(\\.([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|\\.|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.)+(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.?$"
- CreditCard string = "^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11})$"
- ISBN10 string = "^(?:[0-9]{9}X|[0-9]{10})$"
- ISBN13 string = "^(?:[0-9]{13})$"
- UUID3 string = "^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$"
- UUID4 string = "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
- UUID5 string = "^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
- UUID string = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
- Alpha string = "^[a-zA-Z]+$"
- Alphanumeric string = "^[a-zA-Z0-9]+$"
- Numeric string = "^[0-9]+$"
- Int string = "^(?:[-+]?(?:0|[1-9][0-9]*))$"
- Float string = "^(?:[-+]?(?:[0-9]+))?(?:\\.[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$"
- Hexadecimal string = "^[0-9a-fA-F]+$"
- Hexcolor string = "^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$"
- RGBcolor string = "^rgb\\(\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*\\)$"
- ASCII string = "^[\x00-\x7F]+$"
- Multibyte string = "[^\x00-\x7F]"
- FullWidth string = "[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]"
- HalfWidth string = "[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]"
- Base64 string = "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{4})$"
- PrintableASCII string = "^[\x20-\x7E]+$"
- DataURI string = "^data:.+\\/(.+);base64$"
- Latitude string = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$"
- Longitude string = "^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$"
- DNSName string = `^([a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62}){1}(\.[a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62})*[\._]?$`
- IP string = `(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))`
- URLSchema string = `((ftp|tcp|udp|wss?|https?):\/\/)`
- URLUsername string = `(\S+(:\S*)?@)`
- Hostname string = ``
- URLPath string = `((\/|\?|#)[^\s]*)`
- URLPort string = `(:(\d{1,5}))`
- URLIP string = `([1-9]\d?|1\d\d|2[01]\d|22[0-3])(\.(1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.([0-9]\d?|1\d\d|2[0-4]\d|25[0-4]))`
- URLSubdomain string = `((www\.)|([a-zA-Z0-9]([-\.][-\._a-zA-Z0-9]+)*))`
- URL string = `^` + URLSchema + `?` + URLUsername + `?` + `((` + URLIP + `|(\[` + IP + `\])|(([a-zA-Z0-9]([a-zA-Z0-9-_]+)?[a-zA-Z0-9]([-\.][a-zA-Z0-9]+)*)|(` + URLSubdomain + `?))?(([a-zA-Z\x{00a1}-\x{ffff}0-9]+-?-?)*[a-zA-Z\x{00a1}-\x{ffff}0-9]+)(?:\.([a-zA-Z\x{00a1}-\x{ffff}]{1,}))?))\.?` + URLPort + `?` + URLPath + `?$`
- SSN string = `^\d{3}[- ]?\d{2}[- ]?\d{4}$`
- WinPath string = `^[a-zA-Z]:\\(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*$`
- UnixPath string = `^(/[^/\x00]*)+/?$`
- Semver string = "^v?(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(-(0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(\\.(0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\\+[0-9a-zA-Z-]+(\\.[0-9a-zA-Z-]+)*)?$"
- tagName string = "valid"
-)
-
-// Used by IsFilePath func
-const (
- // Unknown is unresolved OS type
- Unknown = iota
- // Win is Windows type
- Win
- // Unix is *nix OS types
- Unix
-)
-
-var (
- rxEmail = regexp.MustCompile(Email)
- rxCreditCard = regexp.MustCompile(CreditCard)
- rxISBN10 = regexp.MustCompile(ISBN10)
- rxISBN13 = regexp.MustCompile(ISBN13)
- rxUUID3 = regexp.MustCompile(UUID3)
- rxUUID4 = regexp.MustCompile(UUID4)
- rxUUID5 = regexp.MustCompile(UUID5)
- rxUUID = regexp.MustCompile(UUID)
- rxAlpha = regexp.MustCompile(Alpha)
- rxAlphanumeric = regexp.MustCompile(Alphanumeric)
- rxNumeric = regexp.MustCompile(Numeric)
- rxInt = regexp.MustCompile(Int)
- rxFloat = regexp.MustCompile(Float)
- rxHexadecimal = regexp.MustCompile(Hexadecimal)
- rxHexcolor = regexp.MustCompile(Hexcolor)
- rxRGBcolor = regexp.MustCompile(RGBcolor)
- rxASCII = regexp.MustCompile(ASCII)
- rxPrintableASCII = regexp.MustCompile(PrintableASCII)
- rxMultibyte = regexp.MustCompile(Multibyte)
- rxFullWidth = regexp.MustCompile(FullWidth)
- rxHalfWidth = regexp.MustCompile(HalfWidth)
- rxBase64 = regexp.MustCompile(Base64)
- rxDataURI = regexp.MustCompile(DataURI)
- rxLatitude = regexp.MustCompile(Latitude)
- rxLongitude = regexp.MustCompile(Longitude)
- rxDNSName = regexp.MustCompile(DNSName)
- rxURL = regexp.MustCompile(URL)
- rxSSN = regexp.MustCompile(SSN)
- rxWinPath = regexp.MustCompile(WinPath)
- rxUnixPath = regexp.MustCompile(UnixPath)
- rxSemver = regexp.MustCompile(Semver)
-)
diff --git a/vendor/github.com/asaskevich/govalidator/types.go b/vendor/github.com/asaskevich/govalidator/types.go
deleted file mode 100644
index 9a5207c..0000000
--- a/vendor/github.com/asaskevich/govalidator/types.go
+++ /dev/null
@@ -1,613 +0,0 @@
-package govalidator
-
-import (
- "reflect"
- "regexp"
- "sync"
-)
-
-// Validator is a wrapper for a validator function that returns bool and accepts string.
-type Validator func(str string) bool
-
-// CustomTypeValidator is a wrapper for validator functions that returns bool and accepts any type.
-// The second parameter should be the context (in the case of validating a struct: the whole object being validated).
-type CustomTypeValidator func(i interface{}, o interface{}) bool
-
-// ParamValidator is a wrapper for validator functions that accepts additional parameters.
-type ParamValidator func(str string, params ...string) bool
-type tagOptionsMap map[string]string
-
-// UnsupportedTypeError is a wrapper for reflect.Type
-type UnsupportedTypeError struct {
- Type reflect.Type
-}
-
-// stringValues is a slice of reflect.Value holding *reflect.StringValue.
-// It implements the methods to sort by string.
-type stringValues []reflect.Value
-
-// ParamTagMap is a map of functions accept variants parameters
-var ParamTagMap = map[string]ParamValidator{
- "length": ByteLength,
- "range": Range,
- "runelength": RuneLength,
- "stringlength": StringLength,
- "matches": StringMatches,
- "in": isInRaw,
-}
-
-// ParamTagRegexMap maps param tags to their respective regexes.
-var ParamTagRegexMap = map[string]*regexp.Regexp{
- "range": regexp.MustCompile("^range\\((\\d+)\\|(\\d+)\\)$"),
- "length": regexp.MustCompile("^length\\((\\d+)\\|(\\d+)\\)$"),
- "runelength": regexp.MustCompile("^runelength\\((\\d+)\\|(\\d+)\\)$"),
- "stringlength": regexp.MustCompile("^stringlength\\((\\d+)\\|(\\d+)\\)$"),
- "in": regexp.MustCompile(`^in\((.*)\)`),
- "matches": regexp.MustCompile(`^matches\((.+)\)$`),
-}
-
-type customTypeTagMap struct {
- validators map[string]CustomTypeValidator
-
- sync.RWMutex
-}
-
-func (tm *customTypeTagMap) Get(name string) (CustomTypeValidator, bool) {
- tm.RLock()
- defer tm.RUnlock()
- v, ok := tm.validators[name]
- return v, ok
-}
-
-func (tm *customTypeTagMap) Set(name string, ctv CustomTypeValidator) {
- tm.Lock()
- defer tm.Unlock()
- tm.validators[name] = ctv
-}
-
-// CustomTypeTagMap is a map of functions that can be used as tags for ValidateStruct function.
-// Use this to validate compound or custom types that need to be handled as a whole, e.g.
-// `type UUID [16]byte` (this would be handled as an array of bytes).
-var CustomTypeTagMap = &customTypeTagMap{validators: make(map[string]CustomTypeValidator)}
-
-// TagMap is a map of functions, that can be used as tags for ValidateStruct function.
-var TagMap = map[string]Validator{
- "email": IsEmail,
- "url": IsURL,
- "dialstring": IsDialString,
- "requrl": IsRequestURL,
- "requri": IsRequestURI,
- "alpha": IsAlpha,
- "utfletter": IsUTFLetter,
- "alphanum": IsAlphanumeric,
- "utfletternum": IsUTFLetterNumeric,
- "numeric": IsNumeric,
- "utfnumeric": IsUTFNumeric,
- "utfdigit": IsUTFDigit,
- "hexadecimal": IsHexadecimal,
- "hexcolor": IsHexcolor,
- "rgbcolor": IsRGBcolor,
- "lowercase": IsLowerCase,
- "uppercase": IsUpperCase,
- "int": IsInt,
- "float": IsFloat,
- "null": IsNull,
- "uuid": IsUUID,
- "uuidv3": IsUUIDv3,
- "uuidv4": IsUUIDv4,
- "uuidv5": IsUUIDv5,
- "creditcard": IsCreditCard,
- "isbn10": IsISBN10,
- "isbn13": IsISBN13,
- "json": IsJSON,
- "multibyte": IsMultibyte,
- "ascii": IsASCII,
- "printableascii": IsPrintableASCII,
- "fullwidth": IsFullWidth,
- "halfwidth": IsHalfWidth,
- "variablewidth": IsVariableWidth,
- "base64": IsBase64,
- "datauri": IsDataURI,
- "ip": IsIP,
- "port": IsPort,
- "ipv4": IsIPv4,
- "ipv6": IsIPv6,
- "dns": IsDNSName,
- "host": IsHost,
- "mac": IsMAC,
- "latitude": IsLatitude,
- "longitude": IsLongitude,
- "ssn": IsSSN,
- "semver": IsSemver,
- "rfc3339": IsRFC3339,
- "ISO3166Alpha2": IsISO3166Alpha2,
- "ISO3166Alpha3": IsISO3166Alpha3,
- "ISO4217": IsISO4217,
-}
-
-// ISO3166Entry stores country codes
-type ISO3166Entry struct {
- EnglishShortName string
- FrenchShortName string
- Alpha2Code string
- Alpha3Code string
- Numeric string
-}
-
-//ISO3166List based on https://www.iso.org/obp/ui/#search/code/ Code Type "Officially Assigned Codes"
-var ISO3166List = []ISO3166Entry{
- {"Afghanistan", "Afghanistan (l')", "AF", "AFG", "004"},
- {"Albania", "Albanie (l')", "AL", "ALB", "008"},
- {"Antarctica", "Antarctique (l')", "AQ", "ATA", "010"},
- {"Algeria", "Algérie (l')", "DZ", "DZA", "012"},
- {"American Samoa", "Samoa américaines (les)", "AS", "ASM", "016"},
- {"Andorra", "Andorre (l')", "AD", "AND", "020"},
- {"Angola", "Angola (l')", "AO", "AGO", "024"},
- {"Antigua and Barbuda", "Antigua-et-Barbuda", "AG", "ATG", "028"},
- {"Azerbaijan", "Azerbaïdjan (l')", "AZ", "AZE", "031"},
- {"Argentina", "Argentine (l')", "AR", "ARG", "032"},
- {"Australia", "Australie (l')", "AU", "AUS", "036"},
- {"Austria", "Autriche (l')", "AT", "AUT", "040"},
- {"Bahamas (the)", "Bahamas (les)", "BS", "BHS", "044"},
- {"Bahrain", "Bahreïn", "BH", "BHR", "048"},
- {"Bangladesh", "Bangladesh (le)", "BD", "BGD", "050"},
- {"Armenia", "Arménie (l')", "AM", "ARM", "051"},
- {"Barbados", "Barbade (la)", "BB", "BRB", "052"},
- {"Belgium", "Belgique (la)", "BE", "BEL", "056"},
- {"Bermuda", "Bermudes (les)", "BM", "BMU", "060"},
- {"Bhutan", "Bhoutan (le)", "BT", "BTN", "064"},
- {"Bolivia (Plurinational State of)", "Bolivie (État plurinational de)", "BO", "BOL", "068"},
- {"Bosnia and Herzegovina", "Bosnie-Herzégovine (la)", "BA", "BIH", "070"},
- {"Botswana", "Botswana (le)", "BW", "BWA", "072"},
- {"Bouvet Island", "Bouvet (l'Île)", "BV", "BVT", "074"},
- {"Brazil", "Brésil (le)", "BR", "BRA", "076"},
- {"Belize", "Belize (le)", "BZ", "BLZ", "084"},
- {"British Indian Ocean Territory (the)", "Indien (le Territoire britannique de l'océan)", "IO", "IOT", "086"},
- {"Solomon Islands", "Salomon (Îles)", "SB", "SLB", "090"},
- {"Virgin Islands (British)", "Vierges britanniques (les Îles)", "VG", "VGB", "092"},
- {"Brunei Darussalam", "Brunéi Darussalam (le)", "BN", "BRN", "096"},
- {"Bulgaria", "Bulgarie (la)", "BG", "BGR", "100"},
- {"Myanmar", "Myanmar (le)", "MM", "MMR", "104"},
- {"Burundi", "Burundi (le)", "BI", "BDI", "108"},
- {"Belarus", "Bélarus (le)", "BY", "BLR", "112"},
- {"Cambodia", "Cambodge (le)", "KH", "KHM", "116"},
- {"Cameroon", "Cameroun (le)", "CM", "CMR", "120"},
- {"Canada", "Canada (le)", "CA", "CAN", "124"},
- {"Cabo Verde", "Cabo Verde", "CV", "CPV", "132"},
- {"Cayman Islands (the)", "Caïmans (les Îles)", "KY", "CYM", "136"},
- {"Central African Republic (the)", "République centrafricaine (la)", "CF", "CAF", "140"},
- {"Sri Lanka", "Sri Lanka", "LK", "LKA", "144"},
- {"Chad", "Tchad (le)", "TD", "TCD", "148"},
- {"Chile", "Chili (le)", "CL", "CHL", "152"},
- {"China", "Chine (la)", "CN", "CHN", "156"},
- {"Taiwan (Province of China)", "Taïwan (Province de Chine)", "TW", "TWN", "158"},
- {"Christmas Island", "Christmas (l'Île)", "CX", "CXR", "162"},
- {"Cocos (Keeling) Islands (the)", "Cocos (les Îles)/ Keeling (les Îles)", "CC", "CCK", "166"},
- {"Colombia", "Colombie (la)", "CO", "COL", "170"},
- {"Comoros (the)", "Comores (les)", "KM", "COM", "174"},
- {"Mayotte", "Mayotte", "YT", "MYT", "175"},
- {"Congo (the)", "Congo (le)", "CG", "COG", "178"},
- {"Congo (the Democratic Republic of the)", "Congo (la République démocratique du)", "CD", "COD", "180"},
- {"Cook Islands (the)", "Cook (les Îles)", "CK", "COK", "184"},
- {"Costa Rica", "Costa Rica (le)", "CR", "CRI", "188"},
- {"Croatia", "Croatie (la)", "HR", "HRV", "191"},
- {"Cuba", "Cuba", "CU", "CUB", "192"},
- {"Cyprus", "Chypre", "CY", "CYP", "196"},
- {"Czech Republic (the)", "tchèque (la République)", "CZ", "CZE", "203"},
- {"Benin", "Bénin (le)", "BJ", "BEN", "204"},
- {"Denmark", "Danemark (le)", "DK", "DNK", "208"},
- {"Dominica", "Dominique (la)", "DM", "DMA", "212"},
- {"Dominican Republic (the)", "dominicaine (la République)", "DO", "DOM", "214"},
- {"Ecuador", "Équateur (l')", "EC", "ECU", "218"},
- {"El Salvador", "El Salvador", "SV", "SLV", "222"},
- {"Equatorial Guinea", "Guinée équatoriale (la)", "GQ", "GNQ", "226"},
- {"Ethiopia", "Éthiopie (l')", "ET", "ETH", "231"},
- {"Eritrea", "Érythrée (l')", "ER", "ERI", "232"},
- {"Estonia", "Estonie (l')", "EE", "EST", "233"},
- {"Faroe Islands (the)", "Féroé (les Îles)", "FO", "FRO", "234"},
- {"Falkland Islands (the) [Malvinas]", "Falkland (les Îles)/Malouines (les Îles)", "FK", "FLK", "238"},
- {"South Georgia and the South Sandwich Islands", "Géorgie du Sud-et-les Îles Sandwich du Sud (la)", "GS", "SGS", "239"},
- {"Fiji", "Fidji (les)", "FJ", "FJI", "242"},
- {"Finland", "Finlande (la)", "FI", "FIN", "246"},
- {"Åland Islands", "Åland(les Îles)", "AX", "ALA", "248"},
- {"France", "France (la)", "FR", "FRA", "250"},
- {"French Guiana", "Guyane française (la )", "GF", "GUF", "254"},
- {"French Polynesia", "Polynésie française (la)", "PF", "PYF", "258"},
- {"French Southern Territories (the)", "Terres australes françaises (les)", "TF", "ATF", "260"},
- {"Djibouti", "Djibouti", "DJ", "DJI", "262"},
- {"Gabon", "Gabon (le)", "GA", "GAB", "266"},
- {"Georgia", "Géorgie (la)", "GE", "GEO", "268"},
- {"Gambia (the)", "Gambie (la)", "GM", "GMB", "270"},
- {"Palestine, State of", "Palestine, État de", "PS", "PSE", "275"},
- {"Germany", "Allemagne (l')", "DE", "DEU", "276"},
- {"Ghana", "Ghana (le)", "GH", "GHA", "288"},
- {"Gibraltar", "Gibraltar", "GI", "GIB", "292"},
- {"Kiribati", "Kiribati", "KI", "KIR", "296"},
- {"Greece", "Grèce (la)", "GR", "GRC", "300"},
- {"Greenland", "Groenland (le)", "GL", "GRL", "304"},
- {"Grenada", "Grenade (la)", "GD", "GRD", "308"},
- {"Guadeloupe", "Guadeloupe (la)", "GP", "GLP", "312"},
- {"Guam", "Guam", "GU", "GUM", "316"},
- {"Guatemala", "Guatemala (le)", "GT", "GTM", "320"},
- {"Guinea", "Guinée (la)", "GN", "GIN", "324"},
- {"Guyana", "Guyana (le)", "GY", "GUY", "328"},
- {"Haiti", "Haïti", "HT", "HTI", "332"},
- {"Heard Island and McDonald Islands", "Heard-et-Îles MacDonald (l'Île)", "HM", "HMD", "334"},
- {"Holy See (the)", "Saint-Siège (le)", "VA", "VAT", "336"},
- {"Honduras", "Honduras (le)", "HN", "HND", "340"},
- {"Hong Kong", "Hong Kong", "HK", "HKG", "344"},
- {"Hungary", "Hongrie (la)", "HU", "HUN", "348"},
- {"Iceland", "Islande (l')", "IS", "ISL", "352"},
- {"India", "Inde (l')", "IN", "IND", "356"},
- {"Indonesia", "Indonésie (l')", "ID", "IDN", "360"},
- {"Iran (Islamic Republic of)", "Iran (République Islamique d')", "IR", "IRN", "364"},
- {"Iraq", "Iraq (l')", "IQ", "IRQ", "368"},
- {"Ireland", "Irlande (l')", "IE", "IRL", "372"},
- {"Israel", "Israël", "IL", "ISR", "376"},
- {"Italy", "Italie (l')", "IT", "ITA", "380"},
- {"Côte d'Ivoire", "Côte d'Ivoire (la)", "CI", "CIV", "384"},
- {"Jamaica", "Jamaïque (la)", "JM", "JAM", "388"},
- {"Japan", "Japon (le)", "JP", "JPN", "392"},
- {"Kazakhstan", "Kazakhstan (le)", "KZ", "KAZ", "398"},
- {"Jordan", "Jordanie (la)", "JO", "JOR", "400"},
- {"Kenya", "Kenya (le)", "KE", "KEN", "404"},
- {"Korea (the Democratic People's Republic of)", "Corée (la République populaire démocratique de)", "KP", "PRK", "408"},
- {"Korea (the Republic of)", "Corée (la République de)", "KR", "KOR", "410"},
- {"Kuwait", "Koweït (le)", "KW", "KWT", "414"},
- {"Kyrgyzstan", "Kirghizistan (le)", "KG", "KGZ", "417"},
- {"Lao People's Democratic Republic (the)", "Lao, République démocratique populaire", "LA", "LAO", "418"},
- {"Lebanon", "Liban (le)", "LB", "LBN", "422"},
- {"Lesotho", "Lesotho (le)", "LS", "LSO", "426"},
- {"Latvia", "Lettonie (la)", "LV", "LVA", "428"},
- {"Liberia", "Libéria (le)", "LR", "LBR", "430"},
- {"Libya", "Libye (la)", "LY", "LBY", "434"},
- {"Liechtenstein", "Liechtenstein (le)", "LI", "LIE", "438"},
- {"Lithuania", "Lituanie (la)", "LT", "LTU", "440"},
- {"Luxembourg", "Luxembourg (le)", "LU", "LUX", "442"},
- {"Macao", "Macao", "MO", "MAC", "446"},
- {"Madagascar", "Madagascar", "MG", "MDG", "450"},
- {"Malawi", "Malawi (le)", "MW", "MWI", "454"},
- {"Malaysia", "Malaisie (la)", "MY", "MYS", "458"},
- {"Maldives", "Maldives (les)", "MV", "MDV", "462"},
- {"Mali", "Mali (le)", "ML", "MLI", "466"},
- {"Malta", "Malte", "MT", "MLT", "470"},
- {"Martinique", "Martinique (la)", "MQ", "MTQ", "474"},
- {"Mauritania", "Mauritanie (la)", "MR", "MRT", "478"},
- {"Mauritius", "Maurice", "MU", "MUS", "480"},
- {"Mexico", "Mexique (le)", "MX", "MEX", "484"},
- {"Monaco", "Monaco", "MC", "MCO", "492"},
- {"Mongolia", "Mongolie (la)", "MN", "MNG", "496"},
- {"Moldova (the Republic of)", "Moldova , République de", "MD", "MDA", "498"},
- {"Montenegro", "Monténégro (le)", "ME", "MNE", "499"},
- {"Montserrat", "Montserrat", "MS", "MSR", "500"},
- {"Morocco", "Maroc (le)", "MA", "MAR", "504"},
- {"Mozambique", "Mozambique (le)", "MZ", "MOZ", "508"},
- {"Oman", "Oman", "OM", "OMN", "512"},
- {"Namibia", "Namibie (la)", "NA", "NAM", "516"},
- {"Nauru", "Nauru", "NR", "NRU", "520"},
- {"Nepal", "Népal (le)", "NP", "NPL", "524"},
- {"Netherlands (the)", "Pays-Bas (les)", "NL", "NLD", "528"},
- {"Curaçao", "Curaçao", "CW", "CUW", "531"},
- {"Aruba", "Aruba", "AW", "ABW", "533"},
- {"Sint Maarten (Dutch part)", "Saint-Martin (partie néerlandaise)", "SX", "SXM", "534"},
- {"Bonaire, Sint Eustatius and Saba", "Bonaire, Saint-Eustache et Saba", "BQ", "BES", "535"},
- {"New Caledonia", "Nouvelle-Calédonie (la)", "NC", "NCL", "540"},
- {"Vanuatu", "Vanuatu (le)", "VU", "VUT", "548"},
- {"New Zealand", "Nouvelle-Zélande (la)", "NZ", "NZL", "554"},
- {"Nicaragua", "Nicaragua (le)", "NI", "NIC", "558"},
- {"Niger (the)", "Niger (le)", "NE", "NER", "562"},
- {"Nigeria", "Nigéria (le)", "NG", "NGA", "566"},
- {"Niue", "Niue", "NU", "NIU", "570"},
- {"Norfolk Island", "Norfolk (l'Île)", "NF", "NFK", "574"},
- {"Norway", "Norvège (la)", "NO", "NOR", "578"},
- {"Northern Mariana Islands (the)", "Mariannes du Nord (les Îles)", "MP", "MNP", "580"},
- {"United States Minor Outlying Islands (the)", "Îles mineures éloignées des États-Unis (les)", "UM", "UMI", "581"},
- {"Micronesia (Federated States of)", "Micronésie (États fédérés de)", "FM", "FSM", "583"},
- {"Marshall Islands (the)", "Marshall (Îles)", "MH", "MHL", "584"},
- {"Palau", "Palaos (les)", "PW", "PLW", "585"},
- {"Pakistan", "Pakistan (le)", "PK", "PAK", "586"},
- {"Panama", "Panama (le)", "PA", "PAN", "591"},
- {"Papua New Guinea", "Papouasie-Nouvelle-Guinée (la)", "PG", "PNG", "598"},
- {"Paraguay", "Paraguay (le)", "PY", "PRY", "600"},
- {"Peru", "Pérou (le)", "PE", "PER", "604"},
- {"Philippines (the)", "Philippines (les)", "PH", "PHL", "608"},
- {"Pitcairn", "Pitcairn", "PN", "PCN", "612"},
- {"Poland", "Pologne (la)", "PL", "POL", "616"},
- {"Portugal", "Portugal (le)", "PT", "PRT", "620"},
- {"Guinea-Bissau", "Guinée-Bissau (la)", "GW", "GNB", "624"},
- {"Timor-Leste", "Timor-Leste (le)", "TL", "TLS", "626"},
- {"Puerto Rico", "Porto Rico", "PR", "PRI", "630"},
- {"Qatar", "Qatar (le)", "QA", "QAT", "634"},
- {"Réunion", "Réunion (La)", "RE", "REU", "638"},
- {"Romania", "Roumanie (la)", "RO", "ROU", "642"},
- {"Russian Federation (the)", "Russie (la Fédération de)", "RU", "RUS", "643"},
- {"Rwanda", "Rwanda (le)", "RW", "RWA", "646"},
- {"Saint Barthélemy", "Saint-Barthélemy", "BL", "BLM", "652"},
- {"Saint Helena, Ascension and Tristan da Cunha", "Sainte-Hélène, Ascension et Tristan da Cunha", "SH", "SHN", "654"},
- {"Saint Kitts and Nevis", "Saint-Kitts-et-Nevis", "KN", "KNA", "659"},
- {"Anguilla", "Anguilla", "AI", "AIA", "660"},
- {"Saint Lucia", "Sainte-Lucie", "LC", "LCA", "662"},
- {"Saint Martin (French part)", "Saint-Martin (partie française)", "MF", "MAF", "663"},
- {"Saint Pierre and Miquelon", "Saint-Pierre-et-Miquelon", "PM", "SPM", "666"},
- {"Saint Vincent and the Grenadines", "Saint-Vincent-et-les Grenadines", "VC", "VCT", "670"},
- {"San Marino", "Saint-Marin", "SM", "SMR", "674"},
- {"Sao Tome and Principe", "Sao Tomé-et-Principe", "ST", "STP", "678"},
- {"Saudi Arabia", "Arabie saoudite (l')", "SA", "SAU", "682"},
- {"Senegal", "Sénégal (le)", "SN", "SEN", "686"},
- {"Serbia", "Serbie (la)", "RS", "SRB", "688"},
- {"Seychelles", "Seychelles (les)", "SC", "SYC", "690"},
- {"Sierra Leone", "Sierra Leone (la)", "SL", "SLE", "694"},
- {"Singapore", "Singapour", "SG", "SGP", "702"},
- {"Slovakia", "Slovaquie (la)", "SK", "SVK", "703"},
- {"Viet Nam", "Viet Nam (le)", "VN", "VNM", "704"},
- {"Slovenia", "Slovénie (la)", "SI", "SVN", "705"},
- {"Somalia", "Somalie (la)", "SO", "SOM", "706"},
- {"South Africa", "Afrique du Sud (l')", "ZA", "ZAF", "710"},
- {"Zimbabwe", "Zimbabwe (le)", "ZW", "ZWE", "716"},
- {"Spain", "Espagne (l')", "ES", "ESP", "724"},
- {"South Sudan", "Soudan du Sud (le)", "SS", "SSD", "728"},
- {"Sudan (the)", "Soudan (le)", "SD", "SDN", "729"},
- {"Western Sahara*", "Sahara occidental (le)*", "EH", "ESH", "732"},
- {"Suriname", "Suriname (le)", "SR", "SUR", "740"},
- {"Svalbard and Jan Mayen", "Svalbard et l'Île Jan Mayen (le)", "SJ", "SJM", "744"},
- {"Swaziland", "Swaziland (le)", "SZ", "SWZ", "748"},
- {"Sweden", "Suède (la)", "SE", "SWE", "752"},
- {"Switzerland", "Suisse (la)", "CH", "CHE", "756"},
- {"Syrian Arab Republic", "République arabe syrienne (la)", "SY", "SYR", "760"},
- {"Tajikistan", "Tadjikistan (le)", "TJ", "TJK", "762"},
- {"Thailand", "Thaïlande (la)", "TH", "THA", "764"},
- {"Togo", "Togo (le)", "TG", "TGO", "768"},
- {"Tokelau", "Tokelau (les)", "TK", "TKL", "772"},
- {"Tonga", "Tonga (les)", "TO", "TON", "776"},
- {"Trinidad and Tobago", "Trinité-et-Tobago (la)", "TT", "TTO", "780"},
- {"United Arab Emirates (the)", "Émirats arabes unis (les)", "AE", "ARE", "784"},
- {"Tunisia", "Tunisie (la)", "TN", "TUN", "788"},
- {"Turkey", "Turquie (la)", "TR", "TUR", "792"},
- {"Turkmenistan", "Turkménistan (le)", "TM", "TKM", "795"},
- {"Turks and Caicos Islands (the)", "Turks-et-Caïcos (les Îles)", "TC", "TCA", "796"},
- {"Tuvalu", "Tuvalu (les)", "TV", "TUV", "798"},
- {"Uganda", "Ouganda (l')", "UG", "UGA", "800"},
- {"Ukraine", "Ukraine (l')", "UA", "UKR", "804"},
- {"Macedonia (the former Yugoslav Republic of)", "Macédoine (l'ex‑République yougoslave de)", "MK", "MKD", "807"},
- {"Egypt", "Égypte (l')", "EG", "EGY", "818"},
- {"United Kingdom of Great Britain and Northern Ireland (the)", "Royaume-Uni de Grande-Bretagne et d'Irlande du Nord (le)", "GB", "GBR", "826"},
- {"Guernsey", "Guernesey", "GG", "GGY", "831"},
- {"Jersey", "Jersey", "JE", "JEY", "832"},
- {"Isle of Man", "Île de Man", "IM", "IMN", "833"},
- {"Tanzania, United Republic of", "Tanzanie, République-Unie de", "TZ", "TZA", "834"},
- {"United States of America (the)", "États-Unis d'Amérique (les)", "US", "USA", "840"},
- {"Virgin Islands (U.S.)", "Vierges des États-Unis (les Îles)", "VI", "VIR", "850"},
- {"Burkina Faso", "Burkina Faso (le)", "BF", "BFA", "854"},
- {"Uruguay", "Uruguay (l')", "UY", "URY", "858"},
- {"Uzbekistan", "Ouzbékistan (l')", "UZ", "UZB", "860"},
- {"Venezuela (Bolivarian Republic of)", "Venezuela (République bolivarienne du)", "VE", "VEN", "862"},
- {"Wallis and Futuna", "Wallis-et-Futuna", "WF", "WLF", "876"},
- {"Samoa", "Samoa (le)", "WS", "WSM", "882"},
- {"Yemen", "Yémen (le)", "YE", "YEM", "887"},
- {"Zambia", "Zambie (la)", "ZM", "ZMB", "894"},
-}
-
-// ISO4217List is the list of ISO currency codes
-var ISO4217List = []string{
- "AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", "AZN",
- "BAM", "BBD", "BDT", "BGN", "BHD", "BIF", "BMD", "BND", "BOB", "BOV", "BRL", "BSD", "BTN", "BWP", "BYN", "BZD",
- "CAD", "CDF", "CHE", "CHF", "CHW", "CLF", "CLP", "CNY", "COP", "COU", "CRC", "CUC", "CUP", "CVE", "CZK",
- "DJF", "DKK", "DOP", "DZD",
- "EGP", "ERN", "ETB", "EUR",
- "FJD", "FKP",
- "GBP", "GEL", "GHS", "GIP", "GMD", "GNF", "GTQ", "GYD",
- "HKD", "HNL", "HRK", "HTG", "HUF",
- "IDR", "ILS", "INR", "IQD", "IRR", "ISK",
- "JMD", "JOD", "JPY",
- "KES", "KGS", "KHR", "KMF", "KPW", "KRW", "KWD", "KYD", "KZT",
- "LAK", "LBP", "LKR", "LRD", "LSL", "LYD",
- "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRO", "MUR", "MVR", "MWK", "MXN", "MXV", "MYR", "MZN",
- "NAD", "NGN", "NIO", "NOK", "NPR", "NZD",
- "OMR",
- "PAB", "PEN", "PGK", "PHP", "PKR", "PLN", "PYG",
- "QAR",
- "RON", "RSD", "RUB", "RWF",
- "SAR", "SBD", "SCR", "SDG", "SEK", "SGD", "SHP", "SLL", "SOS", "SRD", "SSP", "STD", "SVC", "SYP", "SZL",
- "THB", "TJS", "TMT", "TND", "TOP", "TRY", "TTD", "TWD", "TZS",
- "UAH", "UGX", "USD", "USN", "UYI", "UYU", "UZS",
- "VEF", "VND", "VUV",
- "WST",
- "XAF", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XDR", "XOF", "XPD", "XPF", "XPT", "XSU", "XTS", "XUA", "XXX",
- "YER",
- "ZAR", "ZMW", "ZWL",
-}
-
-// ISO693Entry stores ISO language codes
-type ISO693Entry struct {
- Alpha3bCode string
- Alpha2Code string
- English string
-}
-
-//ISO693List based on http://data.okfn.org/data/core/language-codes/r/language-codes-3b2.json
-var ISO693List = []ISO693Entry{
- {Alpha3bCode: "aar", Alpha2Code: "aa", English: "Afar"},
- {Alpha3bCode: "abk", Alpha2Code: "ab", English: "Abkhazian"},
- {Alpha3bCode: "afr", Alpha2Code: "af", English: "Afrikaans"},
- {Alpha3bCode: "aka", Alpha2Code: "ak", English: "Akan"},
- {Alpha3bCode: "alb", Alpha2Code: "sq", English: "Albanian"},
- {Alpha3bCode: "amh", Alpha2Code: "am", English: "Amharic"},
- {Alpha3bCode: "ara", Alpha2Code: "ar", English: "Arabic"},
- {Alpha3bCode: "arg", Alpha2Code: "an", English: "Aragonese"},
- {Alpha3bCode: "arm", Alpha2Code: "hy", English: "Armenian"},
- {Alpha3bCode: "asm", Alpha2Code: "as", English: "Assamese"},
- {Alpha3bCode: "ava", Alpha2Code: "av", English: "Avaric"},
- {Alpha3bCode: "ave", Alpha2Code: "ae", English: "Avestan"},
- {Alpha3bCode: "aym", Alpha2Code: "ay", English: "Aymara"},
- {Alpha3bCode: "aze", Alpha2Code: "az", English: "Azerbaijani"},
- {Alpha3bCode: "bak", Alpha2Code: "ba", English: "Bashkir"},
- {Alpha3bCode: "bam", Alpha2Code: "bm", English: "Bambara"},
- {Alpha3bCode: "baq", Alpha2Code: "eu", English: "Basque"},
- {Alpha3bCode: "bel", Alpha2Code: "be", English: "Belarusian"},
- {Alpha3bCode: "ben", Alpha2Code: "bn", English: "Bengali"},
- {Alpha3bCode: "bih", Alpha2Code: "bh", English: "Bihari languages"},
- {Alpha3bCode: "bis", Alpha2Code: "bi", English: "Bislama"},
- {Alpha3bCode: "bos", Alpha2Code: "bs", English: "Bosnian"},
- {Alpha3bCode: "bre", Alpha2Code: "br", English: "Breton"},
- {Alpha3bCode: "bul", Alpha2Code: "bg", English: "Bulgarian"},
- {Alpha3bCode: "bur", Alpha2Code: "my", English: "Burmese"},
- {Alpha3bCode: "cat", Alpha2Code: "ca", English: "Catalan; Valencian"},
- {Alpha3bCode: "cha", Alpha2Code: "ch", English: "Chamorro"},
- {Alpha3bCode: "che", Alpha2Code: "ce", English: "Chechen"},
- {Alpha3bCode: "chi", Alpha2Code: "zh", English: "Chinese"},
- {Alpha3bCode: "chu", Alpha2Code: "cu", English: "Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic"},
- {Alpha3bCode: "chv", Alpha2Code: "cv", English: "Chuvash"},
- {Alpha3bCode: "cor", Alpha2Code: "kw", English: "Cornish"},
- {Alpha3bCode: "cos", Alpha2Code: "co", English: "Corsican"},
- {Alpha3bCode: "cre", Alpha2Code: "cr", English: "Cree"},
- {Alpha3bCode: "cze", Alpha2Code: "cs", English: "Czech"},
- {Alpha3bCode: "dan", Alpha2Code: "da", English: "Danish"},
- {Alpha3bCode: "div", Alpha2Code: "dv", English: "Divehi; Dhivehi; Maldivian"},
- {Alpha3bCode: "dut", Alpha2Code: "nl", English: "Dutch; Flemish"},
- {Alpha3bCode: "dzo", Alpha2Code: "dz", English: "Dzongkha"},
- {Alpha3bCode: "eng", Alpha2Code: "en", English: "English"},
- {Alpha3bCode: "epo", Alpha2Code: "eo", English: "Esperanto"},
- {Alpha3bCode: "est", Alpha2Code: "et", English: "Estonian"},
- {Alpha3bCode: "ewe", Alpha2Code: "ee", English: "Ewe"},
- {Alpha3bCode: "fao", Alpha2Code: "fo", English: "Faroese"},
- {Alpha3bCode: "fij", Alpha2Code: "fj", English: "Fijian"},
- {Alpha3bCode: "fin", Alpha2Code: "fi", English: "Finnish"},
- {Alpha3bCode: "fre", Alpha2Code: "fr", English: "French"},
- {Alpha3bCode: "fry", Alpha2Code: "fy", English: "Western Frisian"},
- {Alpha3bCode: "ful", Alpha2Code: "ff", English: "Fulah"},
- {Alpha3bCode: "geo", Alpha2Code: "ka", English: "Georgian"},
- {Alpha3bCode: "ger", Alpha2Code: "de", English: "German"},
- {Alpha3bCode: "gla", Alpha2Code: "gd", English: "Gaelic; Scottish Gaelic"},
- {Alpha3bCode: "gle", Alpha2Code: "ga", English: "Irish"},
- {Alpha3bCode: "glg", Alpha2Code: "gl", English: "Galician"},
- {Alpha3bCode: "glv", Alpha2Code: "gv", English: "Manx"},
- {Alpha3bCode: "gre", Alpha2Code: "el", English: "Greek, Modern (1453-)"},
- {Alpha3bCode: "grn", Alpha2Code: "gn", English: "Guarani"},
- {Alpha3bCode: "guj", Alpha2Code: "gu", English: "Gujarati"},
- {Alpha3bCode: "hat", Alpha2Code: "ht", English: "Haitian; Haitian Creole"},
- {Alpha3bCode: "hau", Alpha2Code: "ha", English: "Hausa"},
- {Alpha3bCode: "heb", Alpha2Code: "he", English: "Hebrew"},
- {Alpha3bCode: "her", Alpha2Code: "hz", English: "Herero"},
- {Alpha3bCode: "hin", Alpha2Code: "hi", English: "Hindi"},
- {Alpha3bCode: "hmo", Alpha2Code: "ho", English: "Hiri Motu"},
- {Alpha3bCode: "hrv", Alpha2Code: "hr", English: "Croatian"},
- {Alpha3bCode: "hun", Alpha2Code: "hu", English: "Hungarian"},
- {Alpha3bCode: "ibo", Alpha2Code: "ig", English: "Igbo"},
- {Alpha3bCode: "ice", Alpha2Code: "is", English: "Icelandic"},
- {Alpha3bCode: "ido", Alpha2Code: "io", English: "Ido"},
- {Alpha3bCode: "iii", Alpha2Code: "ii", English: "Sichuan Yi; Nuosu"},
- {Alpha3bCode: "iku", Alpha2Code: "iu", English: "Inuktitut"},
- {Alpha3bCode: "ile", Alpha2Code: "ie", English: "Interlingue; Occidental"},
- {Alpha3bCode: "ina", Alpha2Code: "ia", English: "Interlingua (International Auxiliary Language Association)"},
- {Alpha3bCode: "ind", Alpha2Code: "id", English: "Indonesian"},
- {Alpha3bCode: "ipk", Alpha2Code: "ik", English: "Inupiaq"},
- {Alpha3bCode: "ita", Alpha2Code: "it", English: "Italian"},
- {Alpha3bCode: "jav", Alpha2Code: "jv", English: "Javanese"},
- {Alpha3bCode: "jpn", Alpha2Code: "ja", English: "Japanese"},
- {Alpha3bCode: "kal", Alpha2Code: "kl", English: "Kalaallisut; Greenlandic"},
- {Alpha3bCode: "kan", Alpha2Code: "kn", English: "Kannada"},
- {Alpha3bCode: "kas", Alpha2Code: "ks", English: "Kashmiri"},
- {Alpha3bCode: "kau", Alpha2Code: "kr", English: "Kanuri"},
- {Alpha3bCode: "kaz", Alpha2Code: "kk", English: "Kazakh"},
- {Alpha3bCode: "khm", Alpha2Code: "km", English: "Central Khmer"},
- {Alpha3bCode: "kik", Alpha2Code: "ki", English: "Kikuyu; Gikuyu"},
- {Alpha3bCode: "kin", Alpha2Code: "rw", English: "Kinyarwanda"},
- {Alpha3bCode: "kir", Alpha2Code: "ky", English: "Kirghiz; Kyrgyz"},
- {Alpha3bCode: "kom", Alpha2Code: "kv", English: "Komi"},
- {Alpha3bCode: "kon", Alpha2Code: "kg", English: "Kongo"},
- {Alpha3bCode: "kor", Alpha2Code: "ko", English: "Korean"},
- {Alpha3bCode: "kua", Alpha2Code: "kj", English: "Kuanyama; Kwanyama"},
- {Alpha3bCode: "kur", Alpha2Code: "ku", English: "Kurdish"},
- {Alpha3bCode: "lao", Alpha2Code: "lo", English: "Lao"},
- {Alpha3bCode: "lat", Alpha2Code: "la", English: "Latin"},
- {Alpha3bCode: "lav", Alpha2Code: "lv", English: "Latvian"},
- {Alpha3bCode: "lim", Alpha2Code: "li", English: "Limburgan; Limburger; Limburgish"},
- {Alpha3bCode: "lin", Alpha2Code: "ln", English: "Lingala"},
- {Alpha3bCode: "lit", Alpha2Code: "lt", English: "Lithuanian"},
- {Alpha3bCode: "ltz", Alpha2Code: "lb", English: "Luxembourgish; Letzeburgesch"},
- {Alpha3bCode: "lub", Alpha2Code: "lu", English: "Luba-Katanga"},
- {Alpha3bCode: "lug", Alpha2Code: "lg", English: "Ganda"},
- {Alpha3bCode: "mac", Alpha2Code: "mk", English: "Macedonian"},
- {Alpha3bCode: "mah", Alpha2Code: "mh", English: "Marshallese"},
- {Alpha3bCode: "mal", Alpha2Code: "ml", English: "Malayalam"},
- {Alpha3bCode: "mao", Alpha2Code: "mi", English: "Maori"},
- {Alpha3bCode: "mar", Alpha2Code: "mr", English: "Marathi"},
- {Alpha3bCode: "may", Alpha2Code: "ms", English: "Malay"},
- {Alpha3bCode: "mlg", Alpha2Code: "mg", English: "Malagasy"},
- {Alpha3bCode: "mlt", Alpha2Code: "mt", English: "Maltese"},
- {Alpha3bCode: "mon", Alpha2Code: "mn", English: "Mongolian"},
- {Alpha3bCode: "nau", Alpha2Code: "na", English: "Nauru"},
- {Alpha3bCode: "nav", Alpha2Code: "nv", English: "Navajo; Navaho"},
- {Alpha3bCode: "nbl", Alpha2Code: "nr", English: "Ndebele, South; South Ndebele"},
- {Alpha3bCode: "nde", Alpha2Code: "nd", English: "Ndebele, North; North Ndebele"},
- {Alpha3bCode: "ndo", Alpha2Code: "ng", English: "Ndonga"},
- {Alpha3bCode: "nep", Alpha2Code: "ne", English: "Nepali"},
- {Alpha3bCode: "nno", Alpha2Code: "nn", English: "Norwegian Nynorsk; Nynorsk, Norwegian"},
- {Alpha3bCode: "nob", Alpha2Code: "nb", English: "Bokmål, Norwegian; Norwegian Bokmål"},
- {Alpha3bCode: "nor", Alpha2Code: "no", English: "Norwegian"},
- {Alpha3bCode: "nya", Alpha2Code: "ny", English: "Chichewa; Chewa; Nyanja"},
- {Alpha3bCode: "oci", Alpha2Code: "oc", English: "Occitan (post 1500); Provençal"},
- {Alpha3bCode: "oji", Alpha2Code: "oj", English: "Ojibwa"},
- {Alpha3bCode: "ori", Alpha2Code: "or", English: "Oriya"},
- {Alpha3bCode: "orm", Alpha2Code: "om", English: "Oromo"},
- {Alpha3bCode: "oss", Alpha2Code: "os", English: "Ossetian; Ossetic"},
- {Alpha3bCode: "pan", Alpha2Code: "pa", English: "Panjabi; Punjabi"},
- {Alpha3bCode: "per", Alpha2Code: "fa", English: "Persian"},
- {Alpha3bCode: "pli", Alpha2Code: "pi", English: "Pali"},
- {Alpha3bCode: "pol", Alpha2Code: "pl", English: "Polish"},
- {Alpha3bCode: "por", Alpha2Code: "pt", English: "Portuguese"},
- {Alpha3bCode: "pus", Alpha2Code: "ps", English: "Pushto; Pashto"},
- {Alpha3bCode: "que", Alpha2Code: "qu", English: "Quechua"},
- {Alpha3bCode: "roh", Alpha2Code: "rm", English: "Romansh"},
- {Alpha3bCode: "rum", Alpha2Code: "ro", English: "Romanian; Moldavian; Moldovan"},
- {Alpha3bCode: "run", Alpha2Code: "rn", English: "Rundi"},
- {Alpha3bCode: "rus", Alpha2Code: "ru", English: "Russian"},
- {Alpha3bCode: "sag", Alpha2Code: "sg", English: "Sango"},
- {Alpha3bCode: "san", Alpha2Code: "sa", English: "Sanskrit"},
- {Alpha3bCode: "sin", Alpha2Code: "si", English: "Sinhala; Sinhalese"},
- {Alpha3bCode: "slo", Alpha2Code: "sk", English: "Slovak"},
- {Alpha3bCode: "slv", Alpha2Code: "sl", English: "Slovenian"},
- {Alpha3bCode: "sme", Alpha2Code: "se", English: "Northern Sami"},
- {Alpha3bCode: "smo", Alpha2Code: "sm", English: "Samoan"},
- {Alpha3bCode: "sna", Alpha2Code: "sn", English: "Shona"},
- {Alpha3bCode: "snd", Alpha2Code: "sd", English: "Sindhi"},
- {Alpha3bCode: "som", Alpha2Code: "so", English: "Somali"},
- {Alpha3bCode: "sot", Alpha2Code: "st", English: "Sotho, Southern"},
- {Alpha3bCode: "spa", Alpha2Code: "es", English: "Spanish; Castilian"},
- {Alpha3bCode: "srd", Alpha2Code: "sc", English: "Sardinian"},
- {Alpha3bCode: "srp", Alpha2Code: "sr", English: "Serbian"},
- {Alpha3bCode: "ssw", Alpha2Code: "ss", English: "Swati"},
- {Alpha3bCode: "sun", Alpha2Code: "su", English: "Sundanese"},
- {Alpha3bCode: "swa", Alpha2Code: "sw", English: "Swahili"},
- {Alpha3bCode: "swe", Alpha2Code: "sv", English: "Swedish"},
- {Alpha3bCode: "tah", Alpha2Code: "ty", English: "Tahitian"},
- {Alpha3bCode: "tam", Alpha2Code: "ta", English: "Tamil"},
- {Alpha3bCode: "tat", Alpha2Code: "tt", English: "Tatar"},
- {Alpha3bCode: "tel", Alpha2Code: "te", English: "Telugu"},
- {Alpha3bCode: "tgk", Alpha2Code: "tg", English: "Tajik"},
- {Alpha3bCode: "tgl", Alpha2Code: "tl", English: "Tagalog"},
- {Alpha3bCode: "tha", Alpha2Code: "th", English: "Thai"},
- {Alpha3bCode: "tib", Alpha2Code: "bo", English: "Tibetan"},
- {Alpha3bCode: "tir", Alpha2Code: "ti", English: "Tigrinya"},
- {Alpha3bCode: "ton", Alpha2Code: "to", English: "Tonga (Tonga Islands)"},
- {Alpha3bCode: "tsn", Alpha2Code: "tn", English: "Tswana"},
- {Alpha3bCode: "tso", Alpha2Code: "ts", English: "Tsonga"},
- {Alpha3bCode: "tuk", Alpha2Code: "tk", English: "Turkmen"},
- {Alpha3bCode: "tur", Alpha2Code: "tr", English: "Turkish"},
- {Alpha3bCode: "twi", Alpha2Code: "tw", English: "Twi"},
- {Alpha3bCode: "uig", Alpha2Code: "ug", English: "Uighur; Uyghur"},
- {Alpha3bCode: "ukr", Alpha2Code: "uk", English: "Ukrainian"},
- {Alpha3bCode: "urd", Alpha2Code: "ur", English: "Urdu"},
- {Alpha3bCode: "uzb", Alpha2Code: "uz", English: "Uzbek"},
- {Alpha3bCode: "ven", Alpha2Code: "ve", English: "Venda"},
- {Alpha3bCode: "vie", Alpha2Code: "vi", English: "Vietnamese"},
- {Alpha3bCode: "vol", Alpha2Code: "vo", English: "Volapük"},
- {Alpha3bCode: "wel", Alpha2Code: "cy", English: "Welsh"},
- {Alpha3bCode: "wln", Alpha2Code: "wa", English: "Walloon"},
- {Alpha3bCode: "wol", Alpha2Code: "wo", English: "Wolof"},
- {Alpha3bCode: "xho", Alpha2Code: "xh", English: "Xhosa"},
- {Alpha3bCode: "yid", Alpha2Code: "yi", English: "Yiddish"},
- {Alpha3bCode: "yor", Alpha2Code: "yo", English: "Yoruba"},
- {Alpha3bCode: "zha", Alpha2Code: "za", English: "Zhuang; Chuang"},
- {Alpha3bCode: "zul", Alpha2Code: "zu", English: "Zulu"},
-}
diff --git a/vendor/github.com/asaskevich/govalidator/utils.go b/vendor/github.com/asaskevich/govalidator/utils.go
deleted file mode 100644
index 888c127..0000000
--- a/vendor/github.com/asaskevich/govalidator/utils.go
+++ /dev/null
@@ -1,262 +0,0 @@
-package govalidator
-
-import (
- "errors"
- "fmt"
- "html"
- "math"
- "path"
- "regexp"
- "strings"
- "unicode"
- "unicode/utf8"
-)
-
-// Contains check if the string contains the substring.
-func Contains(str, substring string) bool {
- return strings.Contains(str, substring)
-}
-
-// Matches check if string matches the pattern (pattern is regular expression)
-// In case of error return false
-func Matches(str, pattern string) bool {
- match, _ := regexp.MatchString(pattern, str)
- return match
-}
-
-// LeftTrim trim characters from the left-side of the input.
-// If second argument is empty, it's will be remove leading spaces.
-func LeftTrim(str, chars string) string {
- if chars == "" {
- return strings.TrimLeftFunc(str, unicode.IsSpace)
- }
- r, _ := regexp.Compile("^[" + chars + "]+")
- return r.ReplaceAllString(str, "")
-}
-
-// RightTrim trim characters from the right-side of the input.
-// If second argument is empty, it's will be remove spaces.
-func RightTrim(str, chars string) string {
- if chars == "" {
- return strings.TrimRightFunc(str, unicode.IsSpace)
- }
- r, _ := regexp.Compile("[" + chars + "]+$")
- return r.ReplaceAllString(str, "")
-}
-
-// Trim trim characters from both sides of the input.
-// If second argument is empty, it's will be remove spaces.
-func Trim(str, chars string) string {
- return LeftTrim(RightTrim(str, chars), chars)
-}
-
-// WhiteList remove characters that do not appear in the whitelist.
-func WhiteList(str, chars string) string {
- pattern := "[^" + chars + "]+"
- r, _ := regexp.Compile(pattern)
- return r.ReplaceAllString(str, "")
-}
-
-// BlackList remove characters that appear in the blacklist.
-func BlackList(str, chars string) string {
- pattern := "[" + chars + "]+"
- r, _ := regexp.Compile(pattern)
- return r.ReplaceAllString(str, "")
-}
-
-// StripLow remove characters with a numerical value < 32 and 127, mostly control characters.
-// If keep_new_lines is true, newline characters are preserved (\n and \r, hex 0xA and 0xD).
-func StripLow(str string, keepNewLines bool) string {
- chars := ""
- if keepNewLines {
- chars = "\x00-\x09\x0B\x0C\x0E-\x1F\x7F"
- } else {
- chars = "\x00-\x1F\x7F"
- }
- return BlackList(str, chars)
-}
-
-// ReplacePattern replace regular expression pattern in string
-func ReplacePattern(str, pattern, replace string) string {
- r, _ := regexp.Compile(pattern)
- return r.ReplaceAllString(str, replace)
-}
-
-// Escape replace <, >, & and " with HTML entities.
-var Escape = html.EscapeString
-
-func addSegment(inrune, segment []rune) []rune {
- if len(segment) == 0 {
- return inrune
- }
- if len(inrune) != 0 {
- inrune = append(inrune, '_')
- }
- inrune = append(inrune, segment...)
- return inrune
-}
-
-// UnderscoreToCamelCase converts from underscore separated form to camel case form.
-// Ex.: my_func => MyFunc
-func UnderscoreToCamelCase(s string) string {
- return strings.Replace(strings.Title(strings.Replace(strings.ToLower(s), "_", " ", -1)), " ", "", -1)
-}
-
-// CamelCaseToUnderscore converts from camel case form to underscore separated form.
-// Ex.: MyFunc => my_func
-func CamelCaseToUnderscore(str string) string {
- var output []rune
- var segment []rune
- for _, r := range str {
- if !unicode.IsLower(r) {
- output = addSegment(output, segment)
- segment = nil
- }
- segment = append(segment, unicode.ToLower(r))
- }
- output = addSegment(output, segment)
- return string(output)
-}
-
-// Reverse return reversed string
-func Reverse(s string) string {
- r := []rune(s)
- for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
- r[i], r[j] = r[j], r[i]
- }
- return string(r)
-}
-
-// GetLines split string by "\n" and return array of lines
-func GetLines(s string) []string {
- return strings.Split(s, "\n")
-}
-
-// GetLine return specified line of multiline string
-func GetLine(s string, index int) (string, error) {
- lines := GetLines(s)
- if index < 0 || index >= len(lines) {
- return "", errors.New("line index out of bounds")
- }
- return lines[index], nil
-}
-
-// RemoveTags remove all tags from HTML string
-func RemoveTags(s string) string {
- return ReplacePattern(s, "<[^>]*>", "")
-}
-
-// SafeFileName return safe string that can be used in file names
-func SafeFileName(str string) string {
- name := strings.ToLower(str)
- name = path.Clean(path.Base(name))
- name = strings.Trim(name, " ")
- separators, err := regexp.Compile(`[ &_=+:]`)
- if err == nil {
- name = separators.ReplaceAllString(name, "-")
- }
- legal, err := regexp.Compile(`[^[:alnum:]-.]`)
- if err == nil {
- name = legal.ReplaceAllString(name, "")
- }
- for strings.Contains(name, "--") {
- name = strings.Replace(name, "--", "-", -1)
- }
- return name
-}
-
-// NormalizeEmail canonicalize an email address.
-// The local part of the email address is lowercased for all domains; the hostname is always lowercased and
-// the local part of the email address is always lowercased for hosts that are known to be case-insensitive (currently only GMail).
-// Normalization follows special rules for known providers: currently, GMail addresses have dots removed in the local part and
-// are stripped of tags (e.g. some.one+tag@gmail.com becomes someone@gmail.com) and all @googlemail.com addresses are
-// normalized to @gmail.com.
-func NormalizeEmail(str string) (string, error) {
- if !IsEmail(str) {
- return "", fmt.Errorf("%s is not an email", str)
- }
- parts := strings.Split(str, "@")
- parts[0] = strings.ToLower(parts[0])
- parts[1] = strings.ToLower(parts[1])
- if parts[1] == "gmail.com" || parts[1] == "googlemail.com" {
- parts[1] = "gmail.com"
- parts[0] = strings.Split(ReplacePattern(parts[0], `\.`, ""), "+")[0]
- }
- return strings.Join(parts, "@"), nil
-}
-
-// Truncate a string to the closest length without breaking words.
-func Truncate(str string, length int, ending string) string {
- var aftstr, befstr string
- if len(str) > length {
- words := strings.Fields(str)
- before, present := 0, 0
- for i := range words {
- befstr = aftstr
- before = present
- aftstr = aftstr + words[i] + " "
- present = len(aftstr)
- if present > length && i != 0 {
- if (length - before) < (present - length) {
- return Trim(befstr, " /\\.,\"'#!?&@+-") + ending
- }
- return Trim(aftstr, " /\\.,\"'#!?&@+-") + ending
- }
- }
- }
-
- return str
-}
-
-// PadLeft pad left side of string if size of string is less then indicated pad length
-func PadLeft(str string, padStr string, padLen int) string {
- return buildPadStr(str, padStr, padLen, true, false)
-}
-
-// PadRight pad right side of string if size of string is less then indicated pad length
-func PadRight(str string, padStr string, padLen int) string {
- return buildPadStr(str, padStr, padLen, false, true)
-}
-
-// PadBoth pad sides of string if size of string is less then indicated pad length
-func PadBoth(str string, padStr string, padLen int) string {
- return buildPadStr(str, padStr, padLen, true, true)
-}
-
-// PadString either left, right or both sides, not the padding string can be unicode and more then one
-// character
-func buildPadStr(str string, padStr string, padLen int, padLeft bool, padRight bool) string {
-
- // When padded length is less then the current string size
- if padLen < utf8.RuneCountInString(str) {
- return str
- }
-
- padLen -= utf8.RuneCountInString(str)
-
- targetLen := padLen
-
- targetLenLeft := targetLen
- targetLenRight := targetLen
- if padLeft && padRight {
- targetLenLeft = padLen / 2
- targetLenRight = padLen - targetLenLeft
- }
-
- strToRepeatLen := utf8.RuneCountInString(padStr)
-
- repeatTimes := int(math.Ceil(float64(targetLen) / float64(strToRepeatLen)))
- repeatedString := strings.Repeat(padStr, repeatTimes)
-
- leftSide := ""
- if padLeft {
- leftSide = repeatedString[0:targetLenLeft]
- }
-
- rightSide := ""
- if padRight {
- rightSide = repeatedString[0:targetLenRight]
- }
-
- return leftSide + str + rightSide
-}
diff --git a/vendor/github.com/asaskevich/govalidator/utils_test.go b/vendor/github.com/asaskevich/govalidator/utils_test.go
deleted file mode 100644
index 154f315..0000000
--- a/vendor/github.com/asaskevich/govalidator/utils_test.go
+++ /dev/null
@@ -1,500 +0,0 @@
-package govalidator
-
-import (
- "reflect"
- "testing"
-)
-
-func TestContains(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param1 string
- param2 string
- expected bool
- }{
- {"abacada", "", true},
- {"abacada", "ritir", false},
- {"abacada", "a", true},
- {"abacada", "aca", true},
- }
- for _, test := range tests {
- actual := Contains(test.param1, test.param2)
- if actual != test.expected {
- t.Errorf("Expected Contains(%q,%q) to be %v, got %v", test.param1, test.param2, test.expected, actual)
- }
- }
-}
-
-func TestMatches(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param1 string
- param2 string
- expected bool
- }{
- {"123456789", "[0-9]+", true},
- {"abacada", "cab$", false},
- {"111222333", "((111|222|333)+)+", true},
- {"abacaba", "((123+]", false},
- }
- for _, test := range tests {
- actual := Matches(test.param1, test.param2)
- if actual != test.expected {
- t.Errorf("Expected Matches(%q,%q) to be %v, got %v", test.param1, test.param2, test.expected, actual)
- }
- }
-}
-
-func TestLeftTrim(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param1 string
- param2 string
- expected string
- }{
- {" \r\n\tfoo \r\n\t ", "", "foo \r\n\t "},
- {"010100201000", "01", "201000"},
- }
- for _, test := range tests {
- actual := LeftTrim(test.param1, test.param2)
- if actual != test.expected {
- t.Errorf("Expected LeftTrim(%q,%q) to be %v, got %v", test.param1, test.param2, test.expected, actual)
- }
- }
-}
-
-func TestRightTrim(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param1 string
- param2 string
- expected string
- }{
- {" \r\n\tfoo \r\n\t ", "", " \r\n\tfoo"},
- {"010100201000", "01", "0101002"},
- }
- for _, test := range tests {
- actual := RightTrim(test.param1, test.param2)
- if actual != test.expected {
- t.Errorf("Expected RightTrim(%q,%q) to be %v, got %v", test.param1, test.param2, test.expected, actual)
- }
- }
-}
-
-func TestTrim(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param1 string
- param2 string
- expected string
- }{
- {" \r\n\tfoo \r\n\t ", "", "foo"},
- {"010100201000", "01", "2"},
- {"1234567890987654321", "1-8", "909"},
- }
- for _, test := range tests {
- actual := Trim(test.param1, test.param2)
- if actual != test.expected {
- t.Errorf("Expected Trim(%q,%q) to be %v, got %v", test.param1, test.param2, test.expected, actual)
- }
- }
-}
-
-// This small example illustrate how to work with Trim function.
-func ExampleTrim() {
- // Remove from left and right spaces and "\r", "\n", "\t" characters
- println(Trim(" \r\r\ntext\r \t\n", "") == "text")
- // Remove from left and right characters that are between "1" and "8".
- // "1-8" is like full list "12345678".
- println(Trim("1234567890987654321", "1-8") == "909")
-}
-
-func TestWhiteList(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param1 string
- param2 string
- expected string
- }{
- {"abcdef", "abc", "abc"},
- {"aaaaaaaaaabbbbbbbbbb", "abc", "aaaaaaaaaabbbbbbbbbb"},
- {"a1b2c3", "abc", "abc"},
- {" ", "abc", ""},
- {"a3a43a5a4a3a2a23a4a5a4a3a4", "a-z", "aaaaaaaaaaaa"},
- }
- for _, test := range tests {
- actual := WhiteList(test.param1, test.param2)
- if actual != test.expected {
- t.Errorf("Expected WhiteList(%q,%q) to be %v, got %v", test.param1, test.param2, test.expected, actual)
- }
- }
-}
-
-// This small example illustrate how to work with WhiteList function.
-func ExampleWhiteList() {
- // Remove all characters from string ignoring characters between "a" and "z"
- println(WhiteList("a3a43a5a4a3a2a23a4a5a4a3a4", "a-z") == "aaaaaaaaaaaa")
-}
-
-func TestBlackList(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param1 string
- param2 string
- expected string
- }{
- {"abcdef", "abc", "def"},
- {"aaaaaaaaaabbbbbbbbbb", "abc", ""},
- {"a1b2c3", "abc", "123"},
- {" ", "abc", " "},
- {"a3a43a5a4a3a2a23a4a5a4a3a4", "a-z", "34354322345434"},
- }
- for _, test := range tests {
- actual := BlackList(test.param1, test.param2)
- if actual != test.expected {
- t.Errorf("Expected BlackList(%q,%q) to be %v, got %v", test.param1, test.param2, test.expected, actual)
- }
- }
-}
-
-func TestStripLow(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param1 string
- param2 bool
- expected string
- }{
- {"foo\x00", false, "foo"},
- {"\x7Ffoo\x02", false, "foo"},
- {"\x01\x09", false, ""},
- {"foo\x0A\x0D", false, "foo"},
- {"perch\u00e9", false, "perch\u00e9"},
- {"\u20ac", false, "\u20ac"},
- {"\u2206\x0A", false, "\u2206"},
- {"foo\x0A\x0D", true, "foo\x0A\x0D"},
- {"\x03foo\x0A\x0D", true, "foo\x0A\x0D"},
- }
- for _, test := range tests {
- actual := StripLow(test.param1, test.param2)
- if actual != test.expected {
- t.Errorf("Expected StripLow(%q,%t) to be %v, got %v", test.param1, test.param2, test.expected, actual)
- }
- }
-}
-
-func TestReplacePattern(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param1 string
- param2 string
- param3 string
- expected string
- }{
- {"ab123ba", "[0-9]+", "aca", "abacaba"},
- {"abacaba", "[0-9]+", "aca", "abacaba"},
- {"httpftp://github.comio", "(ftp|io)", "", "http://github.com"},
- {"aaaaaaaaaa", "a", "", ""},
- {"http123123ftp://git534543hub.comio", "(ftp|io|[0-9]+)", "", "http://github.com"},
- }
- for _, test := range tests {
- actual := ReplacePattern(test.param1, test.param2, test.param3)
- if actual != test.expected {
- t.Errorf("Expected ReplacePattern(%q,%q,%q) to be %v, got %v", test.param1, test.param2, test.param3, test.expected, actual)
- }
- }
-}
-
-// This small example illustrate how to work with ReplacePattern function.
-func ExampleReplacePattern() {
- // Replace in "http123123ftp://git534543hub.comio" following (pattern "(ftp|io|[0-9]+)"):
- // - Sequence "ftp".
- // - Sequence "io".
- // - Sequence of digits.
- // with empty string.
- println(ReplacePattern("http123123ftp://git534543hub.comio", "(ftp|io|[0-9]+)", "") == "http://github.com")
-}
-
-func TestEscape(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected string
- }{
- {` `, "<img alt="foo&bar">"},
- }
- for _, test := range tests {
- actual := Escape(test.param)
- if actual != test.expected {
- t.Errorf("Expected Escape(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestUnderscoreToCamelCase(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected string
- }{
- {"a_b_c", "ABC"},
- {"my_func", "MyFunc"},
- {"1ab_cd", "1abCd"},
- }
- for _, test := range tests {
- actual := UnderscoreToCamelCase(test.param)
- if actual != test.expected {
- t.Errorf("Expected UnderscoreToCamelCase(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestCamelCaseToUnderscore(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected string
- }{
- {"MyFunc", "my_func"},
- {"ABC", "a_b_c"},
- {"1B", "1_b"},
- }
- for _, test := range tests {
- actual := CamelCaseToUnderscore(test.param)
- if actual != test.expected {
- t.Errorf("Expected CamelCaseToUnderscore(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestReverse(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected string
- }{
- {"abc", "cba"},
- {"カタカナ", "ナカタカ"},
- }
- for _, test := range tests {
- actual := Reverse(test.param)
- if actual != test.expected {
- t.Errorf("Expected Reverse(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestGetLines(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected []string
- }{
- {"abc", []string{"abc"}},
- {"a\nb\nc", []string{"a", "b", "c"}},
- }
- for _, test := range tests {
- actual := GetLines(test.param)
- if !reflect.DeepEqual(actual, test.expected) {
- t.Errorf("Expected GetLines(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestGetLine(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param1 string
- param2 int
- expected string
- }{
- {"abc", 0, "abc"},
- {"a\nb\nc", 0, "a"},
- {"abc", -1, ""},
- {"abacaba\n", 1, ""},
- {"abc", 3, ""},
- }
- for _, test := range tests {
- actual, _ := GetLine(test.param1, test.param2)
- if actual != test.expected {
- t.Errorf("Expected GetLine(%q, %d) to be %v, got %v", test.param1, test.param2, test.expected, actual)
- }
- }
-}
-
-func TestRemoveTags(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected string
- }{
- {"abc", "abc"},
- {"", ""},
- {"", "Text"},
- {`Link `, "Link"},
- }
- for _, test := range tests {
- actual := RemoveTags(test.param)
- if actual != test.expected {
- t.Errorf("Expected RemoveTags(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestSafeFileName(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected string
- }{
- {"abc", "abc"},
- {"123456789 '_-?ASDF@£$%£%^é.html", "123456789-asdf.html"},
- {"ReadMe.md", "readme.md"},
- {"file:///c:/test.go", "test.go"},
- {"../../../Hello World!.txt", "hello-world.txt"},
- }
- for _, test := range tests {
- actual := SafeFileName(test.param)
- if actual != test.expected {
- t.Errorf("Expected SafeFileName(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestNormalizeEmail(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected string
- }{
- {`test@me.com`, `test@me.com`},
- {`some.name@gmail.com`, `somename@gmail.com`},
- {`some.name@googlemail.com`, `somename@gmail.com`},
- {`some.name+extension@gmail.com`, `somename@gmail.com`},
- {`some.name+extension@googlemail.com`, `somename@gmail.com`},
- {`some.name.middlename+extension@gmail.com`, `somenamemiddlename@gmail.com`},
- {`some.name.middlename+extension@googlemail.com`, `somenamemiddlename@gmail.com`},
- {`some.name.midd.lena.me.+extension@gmail.com`, `somenamemiddlename@gmail.com`},
- {`some.name.midd.lena.me.+extension@googlemail.com`, `somenamemiddlename@gmail.com`},
- {`some.name+extension@unknown.com`, `some.name+extension@unknown.com`},
- {`hans@m端ller.com`, `hans@m端ller.com`},
- {`hans`, ``},
- }
- for _, test := range tests {
- actual, err := NormalizeEmail(test.param)
- if actual != test.expected {
- t.Errorf("Expected NormalizeEmail(%q) to be %v, got %v, err %v", test.param, test.expected, actual, err)
- }
- }
-}
-
-func TestTruncate(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param1 string
- param2 int
- param3 string
- expected string
- }{
- {`Lorem ipsum dolor sit amet, consectetur adipiscing elit.`, 25, `...`, `Lorem ipsum dolor sit amet...`},
- {`Measuring programming progress by lines of code is like measuring aircraft building progress by weight.`, 35, ` new born babies!`, `Measuring programming progress by new born babies!`},
- {`Testestestestestestestestestest testestestestestestestestest`, 7, `...`, `Testestestestestestestestestest...`},
- {`Testing`, 7, `...`, `Testing`},
- }
- for _, test := range tests {
- actual := Truncate(test.param1, test.param2, test.param3)
- if actual != test.expected {
- t.Errorf("Expected Truncate(%q, %d, %q) to be %v, got %v", test.param1, test.param2, test.param3, test.expected, actual)
- }
- }
-}
-
-func TestPadLeft(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param1 string
- param2 string
- param3 int
- expected string
- }{
- {"こんにちは", "xyz", 12, "xyzxyzxこんにちは"},
- {"こんにちは", "xyz", 11, "xyzxyzこんにちは"},
- {"abc", "x", 5, "xxabc"},
- {"abc", "xyz", 5, "xyabc"},
- {"abcde", "xyz", 5, "abcde"},
- {"abcde", "xyz", 4, "abcde"},
- }
- for _, test := range tests {
- actual := PadLeft(test.param1, test.param2, test.param3)
- if actual != test.expected {
- t.Errorf("Expected PadLeft(%q,%q,%q) to be %v, got %v", test.param1, test.param2, test.param3, test.expected, actual)
- }
- }
-}
-
-func TestPadRight(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param1 string
- param2 string
- param3 int
- expected string
- }{
- {"こんにちは", "xyz", 12, "こんにちはxyzxyzx"},
- {"こんにちは", "xyz", 11, "こんにちはxyzxyz"},
- {"abc", "x", 5, "abcxx"},
- {"abc", "xyz", 5, "abcxy"},
- {"abcde", "xyz", 5, "abcde"},
- {"abcde", "xyz", 4, "abcde"},
- }
- for _, test := range tests {
- actual := PadRight(test.param1, test.param2, test.param3)
- if actual != test.expected {
- t.Errorf("Expected PadRight(%q,%q,%q) to be %v, got %v", test.param1, test.param2, test.param3, test.expected, actual)
- }
- }
-}
-
-func TestPadBoth(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param1 string
- param2 string
- param3 int
- expected string
- }{
- {"こんにちは", "xyz", 12, "xyzこんにちはxyzx"},
- {"こんにちは", "xyz", 11, "xyzこんにちはxyz"},
- {"abc", "x", 5, "xabcx"},
- {"abc", "xyz", 5, "xabcx"},
- {"abcde", "xyz", 5, "abcde"},
- {"abcde", "xyz", 4, "abcde"},
- }
- for _, test := range tests {
- actual := PadBoth(test.param1, test.param2, test.param3)
- if actual != test.expected {
- t.Errorf("Expected PadBoth(%q,%q,%q) to be %v, got %v", test.param1, test.param2, test.param3, test.expected, actual)
- }
- }
-}
diff --git a/vendor/github.com/asaskevich/govalidator/validator.go b/vendor/github.com/asaskevich/govalidator/validator.go
deleted file mode 100644
index b699e44..0000000
--- a/vendor/github.com/asaskevich/govalidator/validator.go
+++ /dev/null
@@ -1,1044 +0,0 @@
-// Package govalidator is package of validators and sanitizers for strings, structs and collections.
-package govalidator
-
-import (
- "encoding/json"
- "fmt"
- "net"
- "net/url"
- "reflect"
- "regexp"
- "sort"
- "strconv"
- "strings"
- "time"
- "unicode"
- "unicode/utf8"
-)
-
-var (
- fieldsRequiredByDefault bool
- notNumberRegexp = regexp.MustCompile("[^0-9]+")
- whiteSpacesAndMinus = regexp.MustCompile("[\\s-]+")
-)
-
-const maxURLRuneCount = 2083
-const minURLRuneCount = 3
-
-// SetFieldsRequiredByDefault causes validation to fail when struct fields
-// do not include validations or are not explicitly marked as exempt (using `valid:"-"` or `valid:"email,optional"`).
-// This struct definition will fail govalidator.ValidateStruct() (and the field values do not matter):
-// type exampleStruct struct {
-// Name string ``
-// Email string `valid:"email"`
-// This, however, will only fail when Email is empty or an invalid email address:
-// type exampleStruct2 struct {
-// Name string `valid:"-"`
-// Email string `valid:"email"`
-// Lastly, this will only fail when Email is an invalid email address but not when it's empty:
-// type exampleStruct2 struct {
-// Name string `valid:"-"`
-// Email string `valid:"email,optional"`
-func SetFieldsRequiredByDefault(value bool) {
- fieldsRequiredByDefault = value
-}
-
-// IsEmail check if the string is an email.
-func IsEmail(str string) bool {
- // TODO uppercase letters are not supported
- return rxEmail.MatchString(str)
-}
-
-// IsURL check if the string is an URL.
-func IsURL(str string) bool {
- if str == "" || utf8.RuneCountInString(str) >= maxURLRuneCount || len(str) <= minURLRuneCount || strings.HasPrefix(str, ".") {
- return false
- }
- u, err := url.Parse(str)
- if err != nil {
- return false
- }
- if strings.HasPrefix(u.Host, ".") {
- return false
- }
- if u.Host == "" && (u.Path != "" && !strings.Contains(u.Path, ".")) {
- return false
- }
- return rxURL.MatchString(str)
-
-}
-
-// IsRequestURL check if the string rawurl, assuming
-// it was received in an HTTP request, is a valid
-// URL confirm to RFC 3986
-func IsRequestURL(rawurl string) bool {
- url, err := url.ParseRequestURI(rawurl)
- if err != nil {
- return false //Couldn't even parse the rawurl
- }
- if len(url.Scheme) == 0 {
- return false //No Scheme found
- }
- return true
-}
-
-// IsRequestURI check if the string rawurl, assuming
-// it was received in an HTTP request, is an
-// absolute URI or an absolute path.
-func IsRequestURI(rawurl string) bool {
- _, err := url.ParseRequestURI(rawurl)
- return err == nil
-}
-
-// IsAlpha check if the string contains only letters (a-zA-Z). Empty string is valid.
-func IsAlpha(str string) bool {
- if IsNull(str) {
- return true
- }
- return rxAlpha.MatchString(str)
-}
-
-//IsUTFLetter check if the string contains only unicode letter characters.
-//Similar to IsAlpha but for all languages. Empty string is valid.
-func IsUTFLetter(str string) bool {
- if IsNull(str) {
- return true
- }
-
- for _, c := range str {
- if !unicode.IsLetter(c) {
- return false
- }
- }
- return true
-
-}
-
-// IsAlphanumeric check if the string contains only letters and numbers. Empty string is valid.
-func IsAlphanumeric(str string) bool {
- if IsNull(str) {
- return true
- }
- return rxAlphanumeric.MatchString(str)
-}
-
-// IsUTFLetterNumeric check if the string contains only unicode letters and numbers. Empty string is valid.
-func IsUTFLetterNumeric(str string) bool {
- if IsNull(str) {
- return true
- }
- for _, c := range str {
- if !unicode.IsLetter(c) && !unicode.IsNumber(c) { //letters && numbers are ok
- return false
- }
- }
- return true
-
-}
-
-// IsNumeric check if the string contains only numbers. Empty string is valid.
-func IsNumeric(str string) bool {
- if IsNull(str) {
- return true
- }
- return rxNumeric.MatchString(str)
-}
-
-// IsUTFNumeric check if the string contains only unicode numbers of any kind.
-// Numbers can be 0-9 but also Fractions ¾,Roman Ⅸ and Hangzhou 〩. Empty string is valid.
-func IsUTFNumeric(str string) bool {
- if IsNull(str) {
- return true
- }
- if strings.IndexAny(str, "+-") > 0 {
- return false
- }
- if len(str) > 1 {
- str = strings.TrimPrefix(str, "-")
- str = strings.TrimPrefix(str, "+")
- }
- for _, c := range str {
- if unicode.IsNumber(c) == false { //numbers && minus sign are ok
- return false
- }
- }
- return true
-
-}
-
-// IsUTFDigit check if the string contains only unicode radix-10 decimal digits. Empty string is valid.
-func IsUTFDigit(str string) bool {
- if IsNull(str) {
- return true
- }
- if strings.IndexAny(str, "+-") > 0 {
- return false
- }
- if len(str) > 1 {
- str = strings.TrimPrefix(str, "-")
- str = strings.TrimPrefix(str, "+")
- }
- for _, c := range str {
- if !unicode.IsDigit(c) { //digits && minus sign are ok
- return false
- }
- }
- return true
-
-}
-
-// IsHexadecimal check if the string is a hexadecimal number.
-func IsHexadecimal(str string) bool {
- return rxHexadecimal.MatchString(str)
-}
-
-// IsHexcolor check if the string is a hexadecimal color.
-func IsHexcolor(str string) bool {
- return rxHexcolor.MatchString(str)
-}
-
-// IsRGBcolor check if the string is a valid RGB color in form rgb(RRR, GGG, BBB).
-func IsRGBcolor(str string) bool {
- return rxRGBcolor.MatchString(str)
-}
-
-// IsLowerCase check if the string is lowercase. Empty string is valid.
-func IsLowerCase(str string) bool {
- if IsNull(str) {
- return true
- }
- return str == strings.ToLower(str)
-}
-
-// IsUpperCase check if the string is uppercase. Empty string is valid.
-func IsUpperCase(str string) bool {
- if IsNull(str) {
- return true
- }
- return str == strings.ToUpper(str)
-}
-
-// IsInt check if the string is an integer. Empty string is valid.
-func IsInt(str string) bool {
- if IsNull(str) {
- return true
- }
- return rxInt.MatchString(str)
-}
-
-// IsFloat check if the string is a float.
-func IsFloat(str string) bool {
- return str != "" && rxFloat.MatchString(str)
-}
-
-// IsDivisibleBy check if the string is a number that's divisible by another.
-// If second argument is not valid integer or zero, it's return false.
-// Otherwise, if first argument is not valid integer or zero, it's return true (Invalid string converts to zero).
-func IsDivisibleBy(str, num string) bool {
- f, _ := ToFloat(str)
- p := int64(f)
- q, _ := ToInt(num)
- if q == 0 {
- return false
- }
- return (p == 0) || (p%q == 0)
-}
-
-// IsNull check if the string is null.
-func IsNull(str string) bool {
- return len(str) == 0
-}
-
-// IsByteLength check if the string's length (in bytes) falls in a range.
-func IsByteLength(str string, min, max int) bool {
- return len(str) >= min && len(str) <= max
-}
-
-// IsUUIDv3 check if the string is a UUID version 3.
-func IsUUIDv3(str string) bool {
- return rxUUID3.MatchString(str)
-}
-
-// IsUUIDv4 check if the string is a UUID version 4.
-func IsUUIDv4(str string) bool {
- return rxUUID4.MatchString(str)
-}
-
-// IsUUIDv5 check if the string is a UUID version 5.
-func IsUUIDv5(str string) bool {
- return rxUUID5.MatchString(str)
-}
-
-// IsUUID check if the string is a UUID (version 3, 4 or 5).
-func IsUUID(str string) bool {
- return rxUUID.MatchString(str)
-}
-
-// IsCreditCard check if the string is a credit card.
-func IsCreditCard(str string) bool {
- sanitized := notNumberRegexp.ReplaceAllString(str, "")
- if !rxCreditCard.MatchString(sanitized) {
- return false
- }
- var sum int64
- var digit string
- var tmpNum int64
- var shouldDouble bool
- for i := len(sanitized) - 1; i >= 0; i-- {
- digit = sanitized[i:(i + 1)]
- tmpNum, _ = ToInt(digit)
- if shouldDouble {
- tmpNum *= 2
- if tmpNum >= 10 {
- sum += ((tmpNum % 10) + 1)
- } else {
- sum += tmpNum
- }
- } else {
- sum += tmpNum
- }
- shouldDouble = !shouldDouble
- }
-
- if sum%10 == 0 {
- return true
- }
- return false
-}
-
-// IsISBN10 check if the string is an ISBN version 10.
-func IsISBN10(str string) bool {
- return IsISBN(str, 10)
-}
-
-// IsISBN13 check if the string is an ISBN version 13.
-func IsISBN13(str string) bool {
- return IsISBN(str, 13)
-}
-
-// IsISBN check if the string is an ISBN (version 10 or 13).
-// If version value is not equal to 10 or 13, it will be check both variants.
-func IsISBN(str string, version int) bool {
- sanitized := whiteSpacesAndMinus.ReplaceAllString(str, "")
- var checksum int32
- var i int32
- if version == 10 {
- if !rxISBN10.MatchString(sanitized) {
- return false
- }
- for i = 0; i < 9; i++ {
- checksum += (i + 1) * int32(sanitized[i]-'0')
- }
- if sanitized[9] == 'X' {
- checksum += 10 * 10
- } else {
- checksum += 10 * int32(sanitized[9]-'0')
- }
- if checksum%11 == 0 {
- return true
- }
- return false
- } else if version == 13 {
- if !rxISBN13.MatchString(sanitized) {
- return false
- }
- factor := []int32{1, 3}
- for i = 0; i < 12; i++ {
- checksum += factor[i%2] * int32(sanitized[i]-'0')
- }
- if (int32(sanitized[12]-'0'))-((10-(checksum%10))%10) == 0 {
- return true
- }
- return false
- }
- return IsISBN(str, 10) || IsISBN(str, 13)
-}
-
-// IsJSON check if the string is valid JSON (note: uses json.Unmarshal).
-func IsJSON(str string) bool {
- var js json.RawMessage
- return json.Unmarshal([]byte(str), &js) == nil
-}
-
-// IsMultibyte check if the string contains one or more multibyte chars. Empty string is valid.
-func IsMultibyte(str string) bool {
- if IsNull(str) {
- return true
- }
- return rxMultibyte.MatchString(str)
-}
-
-// IsASCII check if the string contains ASCII chars only. Empty string is valid.
-func IsASCII(str string) bool {
- if IsNull(str) {
- return true
- }
- return rxASCII.MatchString(str)
-}
-
-// IsPrintableASCII check if the string contains printable ASCII chars only. Empty string is valid.
-func IsPrintableASCII(str string) bool {
- if IsNull(str) {
- return true
- }
- return rxPrintableASCII.MatchString(str)
-}
-
-// IsFullWidth check if the string contains any full-width chars. Empty string is valid.
-func IsFullWidth(str string) bool {
- if IsNull(str) {
- return true
- }
- return rxFullWidth.MatchString(str)
-}
-
-// IsHalfWidth check if the string contains any half-width chars. Empty string is valid.
-func IsHalfWidth(str string) bool {
- if IsNull(str) {
- return true
- }
- return rxHalfWidth.MatchString(str)
-}
-
-// IsVariableWidth check if the string contains a mixture of full and half-width chars. Empty string is valid.
-func IsVariableWidth(str string) bool {
- if IsNull(str) {
- return true
- }
- return rxHalfWidth.MatchString(str) && rxFullWidth.MatchString(str)
-}
-
-// IsBase64 check if a string is base64 encoded.
-func IsBase64(str string) bool {
- return rxBase64.MatchString(str)
-}
-
-// IsFilePath check is a string is Win or Unix file path and returns it's type.
-func IsFilePath(str string) (bool, int) {
- if rxWinPath.MatchString(str) {
- //check windows path limit see:
- // http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath
- if len(str[3:]) > 32767 {
- return false, Win
- }
- return true, Win
- } else if rxUnixPath.MatchString(str) {
- return true, Unix
- }
- return false, Unknown
-}
-
-// IsDataURI checks if a string is base64 encoded data URI such as an image
-func IsDataURI(str string) bool {
- dataURI := strings.Split(str, ",")
- if !rxDataURI.MatchString(dataURI[0]) {
- return false
- }
- return IsBase64(dataURI[1])
-}
-
-// IsISO3166Alpha2 checks if a string is valid two-letter country code
-func IsISO3166Alpha2(str string) bool {
- for _, entry := range ISO3166List {
- if str == entry.Alpha2Code {
- return true
- }
- }
- return false
-}
-
-// IsISO3166Alpha3 checks if a string is valid three-letter country code
-func IsISO3166Alpha3(str string) bool {
- for _, entry := range ISO3166List {
- if str == entry.Alpha3Code {
- return true
- }
- }
- return false
-}
-
-// IsISO693Alpha2 checks if a string is valid two-letter language code
-func IsISO693Alpha2(str string) bool {
- for _, entry := range ISO693List {
- if str == entry.Alpha2Code {
- return true
- }
- }
- return false
-}
-
-// IsISO693Alpha3b checks if a string is valid three-letter language code
-func IsISO693Alpha3b(str string) bool {
- for _, entry := range ISO693List {
- if str == entry.Alpha3bCode {
- return true
- }
- }
- return false
-}
-
-// IsDNSName will validate the given string as a DNS name
-func IsDNSName(str string) bool {
- if str == "" || len(strings.Replace(str, ".", "", -1)) > 255 {
- // constraints already violated
- return false
- }
- return !IsIP(str) && rxDNSName.MatchString(str)
-}
-
-// IsDialString validates the given string for usage with the various Dial() functions
-func IsDialString(str string) bool {
-
- if h, p, err := net.SplitHostPort(str); err == nil && h != "" && p != "" && (IsDNSName(h) || IsIP(h)) && IsPort(p) {
- return true
- }
-
- return false
-}
-
-// IsIP checks if a string is either IP version 4 or 6.
-func IsIP(str string) bool {
- return net.ParseIP(str) != nil
-}
-
-// IsPort checks if a string represents a valid port
-func IsPort(str string) bool {
- if i, err := strconv.Atoi(str); err == nil && i > 0 && i < 65536 {
- return true
- }
- return false
-}
-
-// IsIPv4 check if the string is an IP version 4.
-func IsIPv4(str string) bool {
- ip := net.ParseIP(str)
- return ip != nil && strings.Contains(str, ".")
-}
-
-// IsIPv6 check if the string is an IP version 6.
-func IsIPv6(str string) bool {
- ip := net.ParseIP(str)
- return ip != nil && strings.Contains(str, ":")
-}
-
-// IsCIDR check if the string is an valid CIDR notiation (IPV4 & IPV6)
-func IsCIDR(str string) bool {
- _, _, err := net.ParseCIDR(str)
- return err == nil
-}
-
-// IsMAC check if a string is valid MAC address.
-// Possible MAC formats:
-// 01:23:45:67:89:ab
-// 01:23:45:67:89:ab:cd:ef
-// 01-23-45-67-89-ab
-// 01-23-45-67-89-ab-cd-ef
-// 0123.4567.89ab
-// 0123.4567.89ab.cdef
-func IsMAC(str string) bool {
- _, err := net.ParseMAC(str)
- return err == nil
-}
-
-// IsHost checks if the string is a valid IP (both v4 and v6) or a valid DNS name
-func IsHost(str string) bool {
- return IsIP(str) || IsDNSName(str)
-}
-
-// IsMongoID check if the string is a valid hex-encoded representation of a MongoDB ObjectId.
-func IsMongoID(str string) bool {
- return rxHexadecimal.MatchString(str) && (len(str) == 24)
-}
-
-// IsLatitude check if a string is valid latitude.
-func IsLatitude(str string) bool {
- return rxLatitude.MatchString(str)
-}
-
-// IsLongitude check if a string is valid longitude.
-func IsLongitude(str string) bool {
- return rxLongitude.MatchString(str)
-}
-
-func toJSONName(tag string) string {
- if tag == "" {
- return ""
- }
-
- // JSON name always comes first. If there's no options then split[0] is
- // JSON name, if JSON name is not set, then split[0] is an empty string.
- split := strings.SplitN(tag, ",", 2)
- return split[0]
-}
-
-// ValidateStruct use tags for fields.
-// result will be equal to `false` if there are any errors.
-func ValidateStruct(s interface{}) (bool, error) {
- if s == nil {
- return true, nil
- }
- result := true
- var err error
- val := reflect.ValueOf(s)
- if val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr {
- val = val.Elem()
- }
- // we only accept structs
- if val.Kind() != reflect.Struct {
- return false, fmt.Errorf("function only accepts structs; got %s", val.Kind())
- }
- var errs Errors
- for i := 0; i < val.NumField(); i++ {
- valueField := val.Field(i)
- typeField := val.Type().Field(i)
- if typeField.PkgPath != "" {
- continue // Private field
- }
- structResult := true
- if valueField.Kind() == reflect.Struct && typeField.Tag.Get(tagName) != "-" {
- var err error
- structResult, err = ValidateStruct(valueField.Interface())
- if err != nil {
- errs = append(errs, err)
- }
- }
- resultField, err2 := typeCheck(valueField, typeField, val, nil)
- if err2 != nil {
-
- // Replace structure name with JSON name if there is a tag on the variable
- jsonTag := toJSONName(typeField.Tag.Get("json"))
- if jsonTag != "" {
- switch jsonError := err2.(type) {
- case Error:
- jsonError.Name = jsonTag
- err2 = jsonError
- case Errors:
- err2 = jsonError
- }
- }
-
- errs = append(errs, err2)
- }
- result = result && resultField && structResult
- }
- if len(errs) > 0 {
- err = errs
- }
- return result, err
-}
-
-// parseTagIntoMap parses a struct tag `valid:required~Some error message,length(2|3)` into map[string]string{"required": "Some error message", "length(2|3)": ""}
-func parseTagIntoMap(tag string) tagOptionsMap {
- optionsMap := make(tagOptionsMap)
- options := strings.SplitN(tag, ",", -1)
- for _, option := range options {
- validationOptions := strings.Split(option, "~")
- if !isValidTag(validationOptions[0]) {
- continue
- }
- if len(validationOptions) == 2 {
- optionsMap[validationOptions[0]] = validationOptions[1]
- } else {
- optionsMap[validationOptions[0]] = ""
- }
- }
- return optionsMap
-}
-
-func isValidTag(s string) bool {
- if s == "" {
- return false
- }
- for _, c := range s {
- switch {
- case strings.ContainsRune("\\'\"!#$%&()*+-./:<=>?@[]^_{|}~ ", c):
- // Backslash and quote chars are reserved, but
- // otherwise any punctuation chars are allowed
- // in a tag name.
- default:
- if !unicode.IsLetter(c) && !unicode.IsDigit(c) {
- return false
- }
- }
- }
- return true
-}
-
-// IsSSN will validate the given string as a U.S. Social Security Number
-func IsSSN(str string) bool {
- if str == "" || len(str) != 11 {
- return false
- }
- return rxSSN.MatchString(str)
-}
-
-// IsSemver check if string is valid semantic version
-func IsSemver(str string) bool {
- return rxSemver.MatchString(str)
-}
-
-// IsTime check if string is valid according to given format
-func IsTime(str string, format string) bool {
- _, err := time.Parse(format, str)
- return err == nil
-}
-
-// IsRFC3339 check if string is valid timestamp value according to RFC3339
-func IsRFC3339(str string) bool {
- return IsTime(str, time.RFC3339)
-}
-
-// IsISO4217 check if string is valid ISO currency code
-func IsISO4217(str string) bool {
- for _, currency := range ISO4217List {
- if str == currency {
- return true
- }
- }
-
- return false
-}
-
-// ByteLength check string's length
-func ByteLength(str string, params ...string) bool {
- if len(params) == 2 {
- min, _ := ToInt(params[0])
- max, _ := ToInt(params[1])
- return len(str) >= int(min) && len(str) <= int(max)
- }
-
- return false
-}
-
-// RuneLength check string's length
-// Alias for StringLength
-func RuneLength(str string, params ...string) bool {
- return StringLength(str, params...)
-}
-
-// StringMatches checks if a string matches a given pattern.
-func StringMatches(s string, params ...string) bool {
- if len(params) == 1 {
- pattern := params[0]
- return Matches(s, pattern)
- }
- return false
-}
-
-// StringLength check string's length (including multi byte strings)
-func StringLength(str string, params ...string) bool {
-
- if len(params) == 2 {
- strLength := utf8.RuneCountInString(str)
- min, _ := ToInt(params[0])
- max, _ := ToInt(params[1])
- return strLength >= int(min) && strLength <= int(max)
- }
-
- return false
-}
-
-// Range check string's length
-func Range(str string, params ...string) bool {
- if len(params) == 2 {
- value, _ := ToFloat(str)
- min, _ := ToFloat(params[0])
- max, _ := ToFloat(params[1])
- return InRange(value, min, max)
- }
-
- return false
-}
-
-func isInRaw(str string, params ...string) bool {
- if len(params) == 1 {
- rawParams := params[0]
-
- parsedParams := strings.Split(rawParams, "|")
-
- return IsIn(str, parsedParams...)
- }
-
- return false
-}
-
-// IsIn check if string str is a member of the set of strings params
-func IsIn(str string, params ...string) bool {
- for _, param := range params {
- if str == param {
- return true
- }
- }
-
- return false
-}
-
-func checkRequired(v reflect.Value, t reflect.StructField, options tagOptionsMap) (bool, error) {
- if requiredOption, isRequired := options["required"]; isRequired {
- if len(requiredOption) > 0 {
- return false, Error{t.Name, fmt.Errorf(requiredOption), true}
- }
- return false, Error{t.Name, fmt.Errorf("non zero value required"), false}
- } else if _, isOptional := options["optional"]; fieldsRequiredByDefault && !isOptional {
- return false, Error{t.Name, fmt.Errorf("All fields are required to at least have one validation defined"), false}
- }
- // not required and empty is valid
- return true, nil
-}
-
-func typeCheck(v reflect.Value, t reflect.StructField, o reflect.Value, options tagOptionsMap) (isValid bool, resultErr error) {
- if !v.IsValid() {
- return false, nil
- }
-
- tag := t.Tag.Get(tagName)
-
- // Check if the field should be ignored
- switch tag {
- case "":
- if !fieldsRequiredByDefault {
- return true, nil
- }
- return false, Error{t.Name, fmt.Errorf("All fields are required to at least have one validation defined"), false}
- case "-":
- return true, nil
- }
-
- isRootType := false
- if options == nil {
- isRootType = true
- options = parseTagIntoMap(tag)
- }
-
- if isEmptyValue(v) {
- // an empty value is not validated, check only required
- return checkRequired(v, t, options)
- }
-
- var customTypeErrors Errors
- for validatorName, customErrorMessage := range options {
- if validatefunc, ok := CustomTypeTagMap.Get(validatorName); ok {
- delete(options, validatorName)
-
- if result := validatefunc(v.Interface(), o.Interface()); !result {
- if len(customErrorMessage) > 0 {
- customTypeErrors = append(customTypeErrors, Error{Name: t.Name, Err: fmt.Errorf(customErrorMessage), CustomErrorMessageExists: true})
- continue
- }
- customTypeErrors = append(customTypeErrors, Error{Name: t.Name, Err: fmt.Errorf("%s does not validate as %s", fmt.Sprint(v), validatorName), CustomErrorMessageExists: false})
- }
- }
- }
-
- if len(customTypeErrors.Errors()) > 0 {
- return false, customTypeErrors
- }
-
- if isRootType {
- // Ensure that we've checked the value by all specified validators before report that the value is valid
- defer func() {
- delete(options, "optional")
- delete(options, "required")
-
- if isValid && resultErr == nil && len(options) != 0 {
- for validator := range options {
- isValid = false
- resultErr = Error{t.Name, fmt.Errorf(
- "The following validator is invalid or can't be applied to the field: %q", validator), false}
- return
- }
- }
- }()
- }
-
- switch v.Kind() {
- case reflect.Bool,
- reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
- reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
- reflect.Float32, reflect.Float64,
- reflect.String:
- // for each tag option check the map of validator functions
- for validatorSpec, customErrorMessage := range options {
- var negate bool
- validator := validatorSpec
- customMsgExists := len(customErrorMessage) > 0
-
- // Check whether the tag looks like '!something' or 'something'
- if validator[0] == '!' {
- validator = validator[1:]
- negate = true
- }
-
- // Check for param validators
- for key, value := range ParamTagRegexMap {
- ps := value.FindStringSubmatch(validator)
- if len(ps) == 0 {
- continue
- }
-
- validatefunc, ok := ParamTagMap[key]
- if !ok {
- continue
- }
-
- delete(options, validatorSpec)
-
- switch v.Kind() {
- case reflect.String:
- field := fmt.Sprint(v) // make value into string, then validate with regex
- if result := validatefunc(field, ps[1:]...); (!result && !negate) || (result && negate) {
- if customMsgExists {
- return false, Error{t.Name, fmt.Errorf(customErrorMessage), customMsgExists}
- }
- if negate {
- return false, Error{t.Name, fmt.Errorf("%s does validate as %s", field, validator), customMsgExists}
- }
- return false, Error{t.Name, fmt.Errorf("%s does not validate as %s", field, validator), customMsgExists}
- }
- default:
- // type not yet supported, fail
- return false, Error{t.Name, fmt.Errorf("Validator %s doesn't support kind %s", validator, v.Kind()), false}
- }
- }
-
- if validatefunc, ok := TagMap[validator]; ok {
- delete(options, validatorSpec)
-
- switch v.Kind() {
- case reflect.String:
- field := fmt.Sprint(v) // make value into string, then validate with regex
- if result := validatefunc(field); !result && !negate || result && negate {
- if customMsgExists {
- return false, Error{t.Name, fmt.Errorf(customErrorMessage), customMsgExists}
- }
- if negate {
- return false, Error{t.Name, fmt.Errorf("%s does validate as %s", field, validator), customMsgExists}
- }
- return false, Error{t.Name, fmt.Errorf("%s does not validate as %s", field, validator), customMsgExists}
- }
- default:
- //Not Yet Supported Types (Fail here!)
- err := fmt.Errorf("Validator %s doesn't support kind %s for value %v", validator, v.Kind(), v)
- return false, Error{t.Name, err, false}
- }
- }
- }
- return true, nil
- case reflect.Map:
- if v.Type().Key().Kind() != reflect.String {
- return false, &UnsupportedTypeError{v.Type()}
- }
- var sv stringValues
- sv = v.MapKeys()
- sort.Sort(sv)
- result := true
- for _, k := range sv {
- resultItem, err := ValidateStruct(v.MapIndex(k).Interface())
- if err != nil {
- return false, err
- }
- result = result && resultItem
- }
- return result, nil
- case reflect.Slice, reflect.Array:
- result := true
- for i := 0; i < v.Len(); i++ {
- var resultItem bool
- var err error
- if v.Index(i).Kind() != reflect.Struct {
- resultItem, err = typeCheck(v.Index(i), t, o, options)
- if err != nil {
- return false, err
- }
- } else {
- resultItem, err = ValidateStruct(v.Index(i).Interface())
- if err != nil {
- return false, err
- }
- }
- result = result && resultItem
- }
- return result, nil
- case reflect.Interface:
- // If the value is an interface then encode its element
- if v.IsNil() {
- return true, nil
- }
- return ValidateStruct(v.Interface())
- case reflect.Ptr:
- // If the value is a pointer then check its element
- if v.IsNil() {
- return true, nil
- }
- return typeCheck(v.Elem(), t, o, options)
- case reflect.Struct:
- return ValidateStruct(v.Interface())
- default:
- return false, &UnsupportedTypeError{v.Type()}
- }
-}
-
-func isEmptyValue(v reflect.Value) bool {
- switch v.Kind() {
- case reflect.String, reflect.Array:
- return v.Len() == 0
- case reflect.Map, reflect.Slice:
- return v.Len() == 0 || v.IsNil()
- case reflect.Bool:
- return !v.Bool()
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- return v.Int() == 0
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
- return v.Uint() == 0
- case reflect.Float32, reflect.Float64:
- return v.Float() == 0
- case reflect.Interface, reflect.Ptr:
- return v.IsNil()
- }
-
- return reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface())
-}
-
-// ErrorByField returns error for specified field of the struct
-// validated by ValidateStruct or empty string if there are no errors
-// or this field doesn't exists or doesn't have any errors.
-func ErrorByField(e error, field string) string {
- if e == nil {
- return ""
- }
- return ErrorsByField(e)[field]
-}
-
-// ErrorsByField returns map of errors of the struct validated
-// by ValidateStruct or empty map if there are no errors.
-func ErrorsByField(e error) map[string]string {
- m := make(map[string]string)
- if e == nil {
- return m
- }
- // prototype for ValidateStruct
-
- switch e.(type) {
- case Error:
- m[e.(Error).Name] = e.(Error).Err.Error()
- case Errors:
- for _, item := range e.(Errors).Errors() {
- n := ErrorsByField(item)
- for k, v := range n {
- m[k] = v
- }
- }
- }
-
- return m
-}
-
-// Error returns string equivalent for reflect.Type
-func (e *UnsupportedTypeError) Error() string {
- return "validator: unsupported type: " + e.Type.String()
-}
-
-func (sv stringValues) Len() int { return len(sv) }
-func (sv stringValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] }
-func (sv stringValues) Less(i, j int) bool { return sv.get(i) < sv.get(j) }
-func (sv stringValues) get(i int) string { return sv[i].String() }
diff --git a/vendor/github.com/asaskevich/govalidator/validator_test.go b/vendor/github.com/asaskevich/govalidator/validator_test.go
deleted file mode 100644
index 3537232..0000000
--- a/vendor/github.com/asaskevich/govalidator/validator_test.go
+++ /dev/null
@@ -1,2864 +0,0 @@
-package govalidator
-
-import (
- "fmt"
- "strings"
- "testing"
- "time"
-)
-
-func init() {
- CustomTypeTagMap.Set("customFalseValidator", CustomTypeValidator(func(i interface{}, o interface{}) bool {
- return false
- }))
- CustomTypeTagMap.Set("customTrueValidator", CustomTypeValidator(func(i interface{}, o interface{}) bool {
- return true
- }))
-}
-
-func TestIsAlpha(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"\n", false},
- {"\r", false},
- {"Ⅸ", false},
- {"", true},
- {" fooo ", false},
- {"abc!!!", false},
- {"abc1", false},
- {"abc〩", false},
- {"abc", true},
- {"소주", false},
- {"ABC", true},
- {"FoObAr", true},
- {"소aBC", false},
- {"소", false},
- {"달기&Co.", false},
- {"〩Hours", false},
- {"\ufff0", false},
- {"\u0070", true}, //UTF-8(ASCII): p
- {"\u0026", false}, //UTF-8(ASCII): &
- {"\u0030", false}, //UTF-8(ASCII): 0
- {"123", false},
- {"0123", false},
- {"-00123", false},
- {"0", false},
- {"-0", false},
- {"123.123", false},
- {" ", false},
- {".", false},
- {"-1¾", false},
- {"1¾", false},
- {"〥〩", false},
- {"모자", false},
- {"ix", true},
- {"۳۵۶۰", false},
- {"1--", false},
- {"1-1", false},
- {"-", false},
- {"--", false},
- {"1++", false},
- {"1+1", false},
- {"+", false},
- {"++", false},
- {"+1", false},
- }
- for _, test := range tests {
- actual := IsAlpha(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsAlpha(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsUTFLetter(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"\n", false},
- {"\r", false},
- {"Ⅸ", false},
- {"", true},
- {" fooo ", false},
- {"abc!!!", false},
- {"abc1", false},
- {"abc〩", false},
- {"", true},
- {"abc", true},
- {"소주", true},
- {"ABC", true},
- {"FoObAr", true},
- {"소aBC", true},
- {"소", true},
- {"달기&Co.", false},
- {"〩Hours", false},
- {"\ufff0", false},
- {"\u0070", true}, //UTF-8(ASCII): p
- {"\u0026", false}, //UTF-8(ASCII): &
- {"\u0030", false}, //UTF-8(ASCII): 0
- {"123", false},
- {"0123", false},
- {"-00123", false},
- {"0", false},
- {"-0", false},
- {"123.123", false},
- {" ", false},
- {".", false},
- {"-1¾", false},
- {"1¾", false},
- {"〥〩", false},
- {"모자", true},
- {"ix", true},
- {"۳۵۶۰", false},
- {"1--", false},
- {"1-1", false},
- {"-", false},
- {"--", false},
- {"1++", false},
- {"1+1", false},
- {"+", false},
- {"++", false},
- {"+1", false},
- }
- for _, test := range tests {
- actual := IsUTFLetter(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsUTFLetter(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsAlphanumeric(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"\n", false},
- {"\r", false},
- {"Ⅸ", false},
- {"", true},
- {" fooo ", false},
- {"abc!!!", false},
- {"abc123", true},
- {"ABC111", true},
- {"abc1", true},
- {"abc〩", false},
- {"abc", true},
- {"소주", false},
- {"ABC", true},
- {"FoObAr", true},
- {"소aBC", false},
- {"소", false},
- {"달기&Co.", false},
- {"〩Hours", false},
- {"\ufff0", false},
- {"\u0070", true}, //UTF-8(ASCII): p
- {"\u0026", false}, //UTF-8(ASCII): &
- {"\u0030", true}, //UTF-8(ASCII): 0
- {"123", true},
- {"0123", true},
- {"-00123", false},
- {"0", true},
- {"-0", false},
- {"123.123", false},
- {" ", false},
- {".", false},
- {"-1¾", false},
- {"1¾", false},
- {"〥〩", false},
- {"모자", false},
- {"ix", true},
- {"۳۵۶۰", false},
- {"1--", false},
- {"1-1", false},
- {"-", false},
- {"--", false},
- {"1++", false},
- {"1+1", false},
- {"+", false},
- {"++", false},
- {"+1", false},
- }
- for _, test := range tests {
- actual := IsAlphanumeric(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsAlphanumeric(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsUTFLetterNumeric(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"\n", false},
- {"\r", false},
- {"Ⅸ", true},
- {"", true},
- {" fooo ", false},
- {"abc!!!", false},
- {"abc1", true},
- {"abc〩", true},
- {"abc", true},
- {"소주", true},
- {"ABC", true},
- {"FoObAr", true},
- {"소aBC", true},
- {"소", true},
- {"달기&Co.", false},
- {"〩Hours", true},
- {"\ufff0", false},
- {"\u0070", true}, //UTF-8(ASCII): p
- {"\u0026", false}, //UTF-8(ASCII): &
- {"\u0030", true}, //UTF-8(ASCII): 0
- {"123", true},
- {"0123", true},
- {"-00123", false},
- {"0", true},
- {"-0", false},
- {"123.123", false},
- {" ", false},
- {".", false},
- {"-1¾", false},
- {"1¾", true},
- {"〥〩", true},
- {"모자", true},
- {"ix", true},
- {"۳۵۶۰", true},
- {"1--", false},
- {"1-1", false},
- {"-", false},
- {"--", false},
- {"1++", false},
- {"1+1", false},
- {"+", false},
- {"++", false},
- {"+1", false},
- }
- for _, test := range tests {
- actual := IsUTFLetterNumeric(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsUTFLetterNumeric(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsNumeric(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"\n", false},
- {"\r", false},
- {"Ⅸ", false},
- {"", true},
- {" fooo ", false},
- {"abc!!!", false},
- {"abc1", false},
- {"abc〩", false},
- {"abc", false},
- {"소주", false},
- {"ABC", false},
- {"FoObAr", false},
- {"소aBC", false},
- {"소", false},
- {"달기&Co.", false},
- {"〩Hours", false},
- {"\ufff0", false},
- {"\u0070", false}, //UTF-8(ASCII): p
- {"\u0026", false}, //UTF-8(ASCII): &
- {"\u0030", true}, //UTF-8(ASCII): 0
- {"123", true},
- {"0123", true},
- {"-00123", false},
- {"+00123", false},
- {"0", true},
- {"-0", false},
- {"123.123", false},
- {" ", false},
- {".", false},
- {"12𐅪3", false},
- {"-1¾", false},
- {"1¾", false},
- {"〥〩", false},
- {"모자", false},
- {"ix", false},
- {"۳۵۶۰", false},
- {"1--", false},
- {"1-1", false},
- {"-", false},
- {"--", false},
- {"1++", false},
- {"1+1", false},
- {"+", false},
- {"++", false},
- {"+1", false},
- }
- for _, test := range tests {
- actual := IsNumeric(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsNumeric(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsUTFNumeric(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"\n", false},
- {"\r", false},
- {"Ⅸ", true},
- {"", true},
- {" fooo ", false},
- {"abc!!!", false},
- {"abc1", false},
- {"abc〩", false},
- {"abc", false},
- {"소주", false},
- {"ABC", false},
- {"FoObAr", false},
- {"소aBC", false},
- {"소", false},
- {"달기&Co.", false},
- {"〩Hours", false},
- {"\ufff0", false},
- {"\u0070", false}, //UTF-8(ASCII): p
- {"\u0026", false}, //UTF-8(ASCII): &
- {"\u0030", true}, //UTF-8(ASCII): 0
- {"123", true},
- {"0123", true},
- {"-00123", true},
- {"0", true},
- {"-0", true},
- {"--0", false},
- {"-0-", false},
- {"123.123", false},
- {" ", false},
- {".", false},
- {"12𐅪3", true},
- {"-1¾", true},
- {"1¾", true},
- {"〥〩", true},
- {"모자", false},
- {"ix", false},
- {"۳۵۶۰", true},
- {"1++", false},
- {"1+1", false},
- {"+", false},
- {"++", false},
- {"+1", true},
- }
- for _, test := range tests {
- actual := IsUTFNumeric(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsUTFNumeric(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsUTFDigit(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
-
- {"\n", false},
- {"\r", false},
- {"Ⅸ", false},
- {"", true},
- {" fooo ", false},
- {"abc!!!", false},
- {"abc1", false},
- {"abc〩", false},
- {"abc", false},
- {"소주", false},
- {"ABC", false},
- {"FoObAr", false},
- {"소aBC", false},
- {"소", false},
- {"달기&Co.", false},
- {"〩Hours", false},
- {"\ufff0", false},
- {"\u0070", false}, //UTF-8(ASCII): p
- {"\u0026", false}, //UTF-8(ASCII): &
- {"\u0030", true}, //UTF-8(ASCII): 0
- {"123", true},
- {"0123", true},
- {"-00123", true},
- {"0", true},
- {"-0", true},
- {"--0", false},
- {"-0-", false},
- {"123.123", false},
- {" ", false},
- {".", false},
- {"12𐅪3", false},
- {"1483920", true},
- {"", true},
- {"۳۵۶۰", true},
- {"-29", true},
- {"-1¾", false},
- {"1¾", false},
- {"〥〩", false},
- {"모자", false},
- {"ix", false},
- {"۳۵۶۰", true},
- {"1++", false},
- {"1+1", false},
- {"+", false},
- {"++", false},
- {"+1", true},
- }
- for _, test := range tests {
- actual := IsUTFDigit(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsUTFDigit(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsLowerCase(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"", true},
- {"abc123", true},
- {"abc", true},
- {"a b c", true},
- {"abcß", true},
- {"abcẞ", false},
- {"ABCẞ", false},
- {"tr竪s 端ber", true},
- {"fooBar", false},
- {"123ABC", false},
- {"ABC123", false},
- {"ABC", false},
- {"S T R", false},
- {"fooBar", false},
- {"abacaba123", true},
- }
- for _, test := range tests {
- actual := IsLowerCase(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsLowerCase(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsUpperCase(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"", true},
- {"abc123", false},
- {"abc", false},
- {"a b c", false},
- {"abcß", false},
- {"abcẞ", false},
- {"ABCẞ", true},
- {"tr竪s 端ber", false},
- {"fooBar", false},
- {"123ABC", true},
- {"ABC123", true},
- {"ABC", true},
- {"S T R", true},
- {"fooBar", false},
- {"abacaba123", false},
- }
- for _, test := range tests {
- actual := IsUpperCase(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsUpperCase(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsInt(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"-2147483648", true}, //Signed 32 Bit Min Int
- {"2147483647", true}, //Signed 32 Bit Max Int
- {"-2147483649", true}, //Signed 32 Bit Min Int - 1
- {"2147483648", true}, //Signed 32 Bit Max Int + 1
- {"4294967295", true}, //Unsigned 32 Bit Max Int
- {"4294967296", true}, //Unsigned 32 Bit Max Int + 1
- {"-9223372036854775808", true}, //Signed 64 Bit Min Int
- {"9223372036854775807", true}, //Signed 64 Bit Max Int
- {"-9223372036854775809", true}, //Signed 64 Bit Min Int - 1
- {"9223372036854775808", true}, //Signed 64 Bit Max Int + 1
- {"18446744073709551615", true}, //Unsigned 64 Bit Max Int
- {"18446744073709551616", true}, //Unsigned 64 Bit Max Int + 1
- {"", true},
- {"123", true},
- {"0", true},
- {"-0", true},
- {"+0", true},
- {"01", false},
- {"123.123", false},
- {" ", false},
- {"000", false},
- }
- for _, test := range tests {
- actual := IsInt(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsInt(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsEmail(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"foo@bar.com", true},
- {"x@x.x", true},
- {"foo@bar.com.au", true},
- {"foo+bar@bar.com", true},
- {"foo@bar.coffee", true},
- {"foo@bar.coffee..coffee", false},
- {"foo@bar.bar.coffee", true},
- {"foo@bar.中文网", true},
- {"invalidemail@", false},
- {"invalid.com", false},
- {"@invalid.com", false},
- {"test|123@m端ller.com", true},
- {"hans@m端ller.com", true},
- {"hans.m端ller@test.com", true},
- {"NathAn.daVIeS@DomaIn.cOM", true},
- {"NATHAN.DAVIES@DOMAIN.CO.UK", true},
- }
- for _, test := range tests {
- actual := IsEmail(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsEmail(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsURL(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"http://foo.bar#com", true},
- {"http://foobar.com", true},
- {"https://foobar.com", true},
- {"foobar.com", true},
- {"http://foobar.coffee/", true},
- {"http://foobar.中文网/", true},
- {"http://foobar.org/", true},
- {"http://foobar.ORG", true},
- {"http://foobar.org:8080/", true},
- {"ftp://foobar.ru/", true},
- {"ftp.foo.bar", true},
- {"http://user:pass@www.foobar.com/", true},
- {"http://user:pass@www.foobar.com/path/file", true},
- {"http://127.0.0.1/", true},
- {"http://duckduckgo.com/?q=%2F", true},
- {"http://localhost:3000/", true},
- {"http://foobar.com/?foo=bar#baz=qux", true},
- {"http://foobar.com?foo=bar", true},
- {"http://www.xn--froschgrn-x9a.net/", true},
- {"http://foobar.com/a-", true},
- {"http://foobar.پاکستان/", true},
- {"http://foobar.c_o_m", false},
- {"", false},
- {"xyz://foobar.com", false},
- // {"invalid.", false}, is it false like "localhost."?
- {".com", false},
- {"rtmp://foobar.com", false},
- {"http://www.foo_bar.com/", false},
- {"http://localhost:3000/", true},
- {"http://foobar.com#baz=qux", true},
- {"http://foobar.com/t$-_.+!*\\'(),", true},
- {"http://www.foobar.com/~foobar", true},
- {"http://www.-foobar.com/", false},
- {"http://www.foo---bar.com/", false},
- {"http://r6---snnvoxuioq6.googlevideo.com", true},
- {"mailto:someone@example.com", true},
- {"irc://irc.server.org/channel", false},
- {"irc://#channel@network", true},
- {"/abs/test/dir", false},
- {"./rel/test/dir", false},
- {"http://foo^bar.org", false},
- {"http://foo&*bar.org", false},
- {"http://foo&bar.org", false},
- {"http://foo bar.org", false},
- {"http://foo.bar.org", true},
- {"http://www.foo.bar.org", true},
- {"http://www.foo.co.uk", true},
- {"foo", false},
- {"http://.foo.com", false},
- {"http://,foo.com", false},
- {",foo.com", false},
- {"http://myservice.:9093/", true},
- // according to issues #62 #66
- {"https://pbs.twimg.com/profile_images/560826135676588032/j8fWrmYY_normal.jpeg", true},
- // according to #125
- {"http://prometheus-alertmanager.service.q:9093", true},
- {"https://www.logn-123-123.url.with.sigle.letter.d:12345/url/path/foo?bar=zzz#user", true},
- {"http://me.example.com", true},
- {"http://www.me.example.com", true},
- {"https://farm6.static.flickr.com", true},
- {"https://zh.wikipedia.org/wiki/Wikipedia:%E9%A6%96%E9%A1%B5", true},
- {"google", false},
- // According to #87
- {"http://hyphenated-host-name.example.co.in", true},
- {"http://cant-end-with-hyphen-.example.com", false},
- {"http://-cant-start-with-hyphen.example.com", false},
- {"http://www.domain-can-have-dashes.com", true},
- {"http://m.abcd.com/test.html", true},
- {"http://m.abcd.com/a/b/c/d/test.html?args=a&b=c", true},
- {"http://[::1]:9093", true},
- {"http://[::1]:909388", false},
- {"1200::AB00:1234::2552:7777:1313", false},
- {"http://[2001:db8:a0b:12f0::1]/index.html", true},
- {"http://[1200:0000:AB00:1234:0000:2552:7777:1313]", true},
- {"http://user:pass@[::1]:9093/a/b/c/?a=v#abc", true},
- {"https://127.0.0.1/a/b/c?a=v&c=11d", true},
- {"https://foo_bar.example.com", true},
- {"http://foo_bar.example.com", true},
- {"http://foo_bar_fizz_buzz.example.com", true},
- {"http://_cant_start_with_underescore", false},
- {"http://cant_end_with_underescore_", false},
- {"foo_bar.example.com", true},
- {"foo_bar_fizz_buzz.example.com", true},
- {"http://hello_world.example.com", true},
- }
- for _, test := range tests {
- actual := IsURL(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsURL(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsRequestURL(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"http://foo.bar/#com", true},
- {"http://foobar.com", true},
- {"https://foobar.com", true},
- {"foobar.com", false},
- {"http://foobar.coffee/", true},
- {"http://foobar.中文网/", true},
- {"http://foobar.org/", true},
- {"http://foobar.org:8080/", true},
- {"ftp://foobar.ru/", true},
- {"http://user:pass@www.foobar.com/", true},
- {"http://127.0.0.1/", true},
- {"http://duckduckgo.com/?q=%2F", true},
- {"http://localhost:3000/", true},
- {"http://foobar.com/?foo=bar#baz=qux", true},
- {"http://foobar.com?foo=bar", true},
- {"http://www.xn--froschgrn-x9a.net/", true},
- {"", false},
- {"xyz://foobar.com", true},
- {"invalid.", false},
- {".com", false},
- {"rtmp://foobar.com", true},
- {"http://www.foo_bar.com/", true},
- {"http://localhost:3000/", true},
- {"http://foobar.com/#baz=qux", true},
- {"http://foobar.com/t$-_.+!*\\'(),", true},
- {"http://www.foobar.com/~foobar", true},
- {"http://www.-foobar.com/", true},
- {"http://www.foo---bar.com/", true},
- {"mailto:someone@example.com", true},
- {"irc://irc.server.org/channel", true},
- {"irc://#channel@network", true},
- {"/abs/test/dir", false},
- {"./rel/test/dir", false},
- }
- for _, test := range tests {
- actual := IsRequestURL(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsRequestURL(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsRequestURI(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"http://foo.bar/#com", true},
- {"http://foobar.com", true},
- {"https://foobar.com", true},
- {"foobar.com", false},
- {"http://foobar.coffee/", true},
- {"http://foobar.中文网/", true},
- {"http://foobar.org/", true},
- {"http://foobar.org:8080/", true},
- {"ftp://foobar.ru/", true},
- {"http://user:pass@www.foobar.com/", true},
- {"http://127.0.0.1/", true},
- {"http://duckduckgo.com/?q=%2F", true},
- {"http://localhost:3000/", true},
- {"http://foobar.com/?foo=bar#baz=qux", true},
- {"http://foobar.com?foo=bar", true},
- {"http://www.xn--froschgrn-x9a.net/", true},
- {"xyz://foobar.com", true},
- {"invalid.", false},
- {".com", false},
- {"rtmp://foobar.com", true},
- {"http://www.foo_bar.com/", true},
- {"http://localhost:3000/", true},
- {"http://foobar.com/#baz=qux", true},
- {"http://foobar.com/t$-_.+!*\\'(),", true},
- {"http://www.foobar.com/~foobar", true},
- {"http://www.-foobar.com/", true},
- {"http://www.foo---bar.com/", true},
- {"mailto:someone@example.com", true},
- {"irc://irc.server.org/channel", true},
- {"irc://#channel@network", true},
- {"/abs/test/dir", true},
- {"./rel/test/dir", false},
- }
- for _, test := range tests {
- actual := IsRequestURI(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsRequestURI(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsFloat(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {" ", false},
- {"-.123", false},
- {"abacaba", false},
- {"1f", false},
- {"-1f", false},
- {"+1f", false},
- {"123", true},
- {"123.", true},
- {"123.123", true},
- {"-123.123", true},
- {"+123.123", true},
- {"0.123", true},
- {"-0.123", true},
- {"+0.123", true},
- {".0", true},
- {"01.123", true},
- {"-0.22250738585072011e-307", true},
- {"+0.22250738585072011e-307", true},
- }
- for _, test := range tests {
- actual := IsFloat(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsFloat(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsHexadecimal(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"abcdefg", false},
- {"", false},
- {"..", false},
- {"deadBEEF", true},
- {"ff0044", true},
- }
- for _, test := range tests {
- actual := IsHexadecimal(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsHexadecimal(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsHexcolor(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"#ff", false},
- {"fff0", false},
- {"#ff12FG", false},
- {"CCccCC", true},
- {"fff", true},
- {"#f00", true},
- }
- for _, test := range tests {
- actual := IsHexcolor(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsHexcolor(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsRGBcolor(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"rgb(0,31,255)", true},
- {"rgb(1,349,275)", false},
- {"rgb(01,31,255)", false},
- {"rgb(0.6,31,255)", false},
- {"rgba(0,31,255)", false},
- {"rgb(0, 31, 255)", true},
- }
- for _, test := range tests {
- actual := IsRGBcolor(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsRGBcolor(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsNull(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"abacaba", false},
- {"", true},
- }
- for _, test := range tests {
- actual := IsNull(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsNull(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsDivisibleBy(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param1 string
- param2 string
- expected bool
- }{
- {"4", "2", true},
- {"100", "10", true},
- {"", "1", true},
- {"123", "foo", false},
- {"123", "0", false},
- }
- for _, test := range tests {
- actual := IsDivisibleBy(test.param1, test.param2)
- if actual != test.expected {
- t.Errorf("Expected IsDivisibleBy(%q, %q) to be %v, got %v", test.param1, test.param2, test.expected, actual)
- }
- }
-}
-
-// This small example illustrate how to work with IsDivisibleBy function.
-func ExampleIsDivisibleBy() {
- println("1024 is divisible by 64: ", IsDivisibleBy("1024", "64"))
-}
-
-func TestIsByteLength(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param1 string
- param2 int
- param3 int
- expected bool
- }{
- {"abacaba", 100, -1, false},
- {"abacaba", 1, 3, false},
- {"abacaba", 1, 7, true},
- {"abacaba", 0, 8, true},
- {"\ufff0", 1, 1, false},
- }
- for _, test := range tests {
- actual := IsByteLength(test.param1, test.param2, test.param3)
- if actual != test.expected {
- t.Errorf("Expected IsByteLength(%q, %q, %q) to be %v, got %v", test.param1, test.param2, test.param3, test.expected, actual)
- }
- }
-}
-
-func TestIsJSON(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"145", true},
- {"asdf", false},
- {"123:f00", false},
- {"{\"Name\":\"Alice\",\"Body\":\"Hello\",\"Time\":1294706395881547000}", true},
- {"{}", true},
- {"{\"Key\":{\"Key\":{\"Key\":123}}}", true},
- {"[]", true},
- {"null", true},
- }
- for _, test := range tests {
- actual := IsJSON(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsJSON(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsMultibyte(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"abc", false},
- {"123", false},
- {"<>@;.-=", false},
- {"ひらがな・カタカナ、.漢字", true},
- {"あいうえお foobar", true},
- {"test@example.com", true},
- {"test@example.com", true},
- {"1234abcDExyz", true},
- {"カタカナ", true},
- }
- for _, test := range tests {
- actual := IsMultibyte(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsMultibyte(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsASCII(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"", true},
- {"foobar", false},
- {"xyz098", false},
- {"123456", false},
- {"カタカナ", false},
- {"foobar", true},
- {"0987654321", true},
- {"test@example.com", true},
- {"1234abcDEF", true},
- {"", true},
- }
- for _, test := range tests {
- actual := IsASCII(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsASCII(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsPrintableASCII(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"", true},
- {"foobar", false},
- {"xyz098", false},
- {"123456", false},
- {"カタカナ", false},
- {"foobar", true},
- {"0987654321", true},
- {"test@example.com", true},
- {"1234abcDEF", true},
- {"newline\n", false},
- {"\x19test\x7F", false},
- }
- for _, test := range tests {
- actual := IsPrintableASCII(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsPrintableASCII(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsFullWidth(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"", true},
- {"abc", false},
- {"abc123", false},
- {"!\"#$%&()<>/+=-_? ~^|.,@`{}[]", false},
- {"ひらがな・カタカナ、.漢字", true},
- {"3ー0 a@com", true},
- {"Fカタカナ゙ᆲ", true},
- {"Good=Parts", true},
- {"", true},
- }
- for _, test := range tests {
- actual := IsFullWidth(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsFullWidth(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsHalfWidth(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"", true},
- {"あいうえお", false},
- {"0011", false},
- {"!\"#$%&()<>/+=-_? ~^|.,@`{}[]", true},
- {"l-btn_02--active", true},
- {"abc123い", true},
- {"カタカナ゙ᆲ←", true},
- {"", true},
- }
- for _, test := range tests {
- actual := IsHalfWidth(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsHalfWidth(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsVariableWidth(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"", true},
- {"ひらがなカタカナ漢字ABCDE", true},
- {"3ー0123", true},
- {"Fカタカナ゙ᆲ", true},
- {"", true},
- {"Good=Parts", true},
- {"abc", false},
- {"abc123", false},
- {"!\"#$%&()<>/+=-_? ~^|.,@`{}[]", false},
- {"ひらがな・カタカナ、.漢字", false},
- {"123456", false},
- {"カタカナ゙ᆲ", false},
- }
- for _, test := range tests {
- actual := IsVariableWidth(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsVariableWidth(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsUUID(t *testing.T) {
- t.Parallel()
-
- // Tests without version
- var tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"xxxa987fbc9-4bed-3078-cf07-9141ba07c9f3", false},
- {"a987fbc9-4bed-3078-cf07-9141ba07c9f3xxx", false},
- {"a987fbc94bed3078cf079141ba07c9f3", false},
- {"934859", false},
- {"987fbc9-4bed-3078-cf07a-9141ba07c9f3", false},
- {"aaaaaaaa-1111-1111-aaag-111111111111", false},
- {"a987fbc9-4bed-3078-cf07-9141ba07c9f3", true},
- }
- for _, test := range tests {
- actual := IsUUID(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsUUID(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-
- // UUID ver. 3
- tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"412452646", false},
- {"xxxa987fbc9-4bed-3078-cf07-9141ba07c9f3", false},
- {"a987fbc9-4bed-4078-8f07-9141ba07c9f3", false},
- {"a987fbc9-4bed-3078-cf07-9141ba07c9f3", true},
- }
- for _, test := range tests {
- actual := IsUUIDv3(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsUUIDv3(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-
- // UUID ver. 4
- tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"xxxa987fbc9-4bed-3078-cf07-9141ba07c9f3", false},
- {"a987fbc9-4bed-5078-af07-9141ba07c9f3", false},
- {"934859", false},
- {"57b73598-8764-4ad0-a76a-679bb6640eb1", true},
- {"625e63f3-58f5-40b7-83a1-a72ad31acffb", true},
- }
- for _, test := range tests {
- actual := IsUUIDv4(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsUUIDv4(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-
- // UUID ver. 5
- tests = []struct {
- param string
- expected bool
- }{
-
- {"", false},
- {"xxxa987fbc9-4bed-3078-cf07-9141ba07c9f3", false},
- {"9c858901-8a57-4791-81fe-4c455b099bc9", false},
- {"a987fbc9-4bed-3078-cf07-9141ba07c9f3", false},
- {"987fbc97-4bed-5078-af07-9141ba07c9f3", true},
- {"987fbc97-4bed-5078-9f07-9141ba07c9f3", true},
- }
- for _, test := range tests {
- actual := IsUUIDv5(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsUUIDv5(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsCreditCard(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"foo", false},
- {"5398228707871528", false},
- {"375556917985515", true},
- {"36050234196908", true},
- {"4716461583322103", true},
- {"4716-2210-5188-5662", true},
- {"4929 7226 5379 7141", true},
- {"5398228707871527", true},
- }
- for _, test := range tests {
- actual := IsCreditCard(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsCreditCard(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsISBN(t *testing.T) {
- t.Parallel()
-
- // Without version
- var tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"foo", false},
- {"3836221195", true},
- {"1-61729-085-8", true},
- {"3 423 21412 0", true},
- {"3 401 01319 X", true},
- {"9784873113685", true},
- {"978-4-87311-368-5", true},
- {"978 3401013190", true},
- {"978-3-8362-2119-1", true},
- }
- for _, test := range tests {
- actual := IsISBN(test.param, -1)
- if actual != test.expected {
- t.Errorf("Expected IsISBN(%q, -1) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-
- // ISBN 10
- tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"foo", false},
- {"3423214121", false},
- {"978-3836221191", false},
- {"3-423-21412-1", false},
- {"3 423 21412 1", false},
- {"3836221195", true},
- {"1-61729-085-8", true},
- {"3 423 21412 0", true},
- {"3 401 01319 X", true},
- }
- for _, test := range tests {
- actual := IsISBN10(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsISBN10(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-
- // ISBN 13
- tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"foo", false},
- {"3-8362-2119-5", false},
- {"01234567890ab", false},
- {"978 3 8362 2119 0", false},
- {"9784873113685", true},
- {"978-4-87311-368-5", true},
- {"978 3401013190", true},
- {"978-3-8362-2119-1", true},
- }
- for _, test := range tests {
- actual := IsISBN13(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsISBN13(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsDataURI(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"data:image/png;base64,TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4=", true},
- {"data:text/plain;base64,Vml2YW11cyBmZXJtZW50dW0gc2VtcGVyIHBvcnRhLg==", true},
- {"image/gif;base64,U3VzcGVuZGlzc2UgbGVjdHVzIGxlbw==", false},
- {"data:image/gif;base64,MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuMPNS1Ufof9EW/M98FNw" +
- "UAKrwflsqVxaxQjBQnHQmiI7Vac40t8x7pIb8gLGV6wL7sBTJiPovJ0V7y7oc0Ye" +
- "rhKh0Rm4skP2z/jHwwZICgGzBvA0rH8xlhUiTvcwDCJ0kc+fh35hNt8srZQM4619" +
- "FTgB66Xmp4EtVyhpQV+t02g6NzK72oZI0vnAvqhpkxLeLiMCyrI416wHm5Tkukhx" +
- "QmcL2a6hNOyu0ixX/x2kSFXApEnVrJ+/IxGyfyw8kf4N2IZpW5nEP847lpfj0SZZ" +
- "Fwrd1mnfnDbYohX2zRptLy2ZUn06Qo9pkG5ntvFEPo9bfZeULtjYzIl6K8gJ2uGZ" + "HQIDAQAB", true},
- {"data:image/png;base64,12345", false},
- {"", false},
- {"data:text,:;base85,U3VzcGVuZGlzc2UgbGVjdHVzIGxlbw==", false},
- }
- for _, test := range tests {
- actual := IsDataURI(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsDataURI(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsBase64(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4=", true},
- {"Vml2YW11cyBmZXJtZW50dW0gc2VtcGVyIHBvcnRhLg==", true},
- {"U3VzcGVuZGlzc2UgbGVjdHVzIGxlbw==", true},
- {"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuMPNS1Ufof9EW/M98FNw" +
- "UAKrwflsqVxaxQjBQnHQmiI7Vac40t8x7pIb8gLGV6wL7sBTJiPovJ0V7y7oc0Ye" +
- "rhKh0Rm4skP2z/jHwwZICgGzBvA0rH8xlhUiTvcwDCJ0kc+fh35hNt8srZQM4619" +
- "FTgB66Xmp4EtVyhpQV+t02g6NzK72oZI0vnAvqhpkxLeLiMCyrI416wHm5Tkukhx" +
- "QmcL2a6hNOyu0ixX/x2kSFXApEnVrJ+/IxGyfyw8kf4N2IZpW5nEP847lpfj0SZZ" +
- "Fwrd1mnfnDbYohX2zRptLy2ZUn06Qo9pkG5ntvFEPo9bfZeULtjYzIl6K8gJ2uGZ" + "HQIDAQAB", true},
- {"12345", false},
- {"", false},
- {"Vml2YW11cyBmZXJtZtesting123", false},
- }
- for _, test := range tests {
- actual := IsBase64(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsBase64(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsISO3166Alpha2(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"ABCD", false},
- {"A", false},
- {"AC", false},
- {"AP", false},
- {"GER", false},
- {"NU", true},
- {"DE", true},
- {"JP", true},
- {"JPN", false},
- {"ZWE", false},
- {"GER", false},
- {"DEU", false},
- }
- for _, test := range tests {
- actual := IsISO3166Alpha2(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsISO3166Alpha2(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsISO3166Alpha3(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"ABCD", false},
- {"A", false},
- {"AC", false},
- {"AP", false},
- {"NU", false},
- {"DE", false},
- {"JP", false},
- {"ZWE", true},
- {"JPN", true},
- {"GER", false},
- {"DEU", true},
- }
- for _, test := range tests {
- actual := IsISO3166Alpha3(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsISO3166Alpha3(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsISO693Alpha2(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"abcd", false},
- {"a", false},
- {"ac", false},
- {"ap", false},
- {"de", true},
- {"DE", false},
- {"mk", true},
- {"mac", false},
- {"sw", true},
- {"SW", false},
- {"ger", false},
- {"deu", false},
- }
- for _, test := range tests {
- actual := IsISO693Alpha2(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsISO693Alpha2(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsISO693Alpha3b(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"abcd", false},
- {"a", false},
- {"ac", false},
- {"ap", false},
- {"de", false},
- {"DE", false},
- {"mkd", false},
- {"mac", true},
- {"sw", false},
- {"SW", false},
- {"ger", true},
- {"deu", false},
- }
- for _, test := range tests {
- actual := IsISO693Alpha3b(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsISO693Alpha3b(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsIP(t *testing.T) {
- t.Parallel()
-
- // Without version
- var tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"127.0.0.1", true},
- {"0.0.0.0", true},
- {"255.255.255.255", true},
- {"1.2.3.4", true},
- {"::1", true},
- {"2001:db8:0000:1:1:1:1:1", true},
- {"300.0.0.0", false},
- }
- for _, test := range tests {
- actual := IsIP(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsIP(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-
- // IPv4
- tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"127.0.0.1", true},
- {"0.0.0.0", true},
- {"255.255.255.255", true},
- {"1.2.3.4", true},
- {"::1", false},
- {"2001:db8:0000:1:1:1:1:1", false},
- {"300.0.0.0", false},
- }
- for _, test := range tests {
- actual := IsIPv4(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsIPv4(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-
- // IPv6
- tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"127.0.0.1", false},
- {"0.0.0.0", false},
- {"255.255.255.255", false},
- {"1.2.3.4", false},
- {"::1", true},
- {"2001:db8:0000:1:1:1:1:1", true},
- {"300.0.0.0", false},
- }
- for _, test := range tests {
- actual := IsIPv6(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsIPv6(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsPort(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"1", true},
- {"65535", true},
- {"0", false},
- {"65536", false},
- {"65538", false},
- }
-
- for _, test := range tests {
- actual := IsPort(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsPort(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsDNSName(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"localhost", true},
- {"a.bc", true},
- {"a.b.", true},
- {"a.b..", false},
- {"localhost.local", true},
- {"localhost.localdomain.intern", true},
- {"l.local.intern", true},
- {"ru.link.n.svpncloud.com", true},
- {"-localhost", false},
- {"localhost.-localdomain", false},
- {"localhost.localdomain.-int", false},
- {"_localhost", true},
- {"localhost._localdomain", true},
- {"localhost.localdomain._int", true},
- {"lÖcalhost", false},
- {"localhost.lÖcaldomain", false},
- {"localhost.localdomain.üntern", false},
- {"__", true},
- {"localhost/", false},
- {"127.0.0.1", false},
- {"[::1]", false},
- {"50.50.50.50", false},
- {"localhost.localdomain.intern:65535", false},
- {"漢字汉字", false},
- {"www.jubfvq1v3p38i51622y0dvmdk1mymowjyeu26gbtw9andgynj1gg8z3msb1kl5z6906k846pj3sulm4kiyk82ln5teqj9nsht59opr0cs5ssltx78lfyvml19lfq1wp4usbl0o36cmiykch1vywbttcus1p9yu0669h8fj4ll7a6bmop505908s1m83q2ec2qr9nbvql2589adma3xsq2o38os2z3dmfh2tth4is4ixyfasasasefqwe4t2ub2fz1rme.de", false},
- }
-
- for _, test := range tests {
- actual := IsDNSName(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsDNS(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsHost(t *testing.T) {
- t.Parallel()
- var tests = []struct {
- param string
- expected bool
- }{
- {"localhost", true},
- {"localhost.localdomain", true},
- {"2001:db8:0000:1:1:1:1:1", true},
- {"::1", true},
- {"play.golang.org", true},
- {"localhost.localdomain.intern:65535", false},
- {"-[::1]", false},
- {"-localhost", false},
- {".localhost", false},
- }
- for _, test := range tests {
- actual := IsHost(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsHost(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-
-}
-
-func TestIsDialString(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"localhost.local:1", true},
- {"localhost.localdomain:9090", true},
- {"localhost.localdomain.intern:65535", true},
- {"127.0.0.1:30000", true},
- {"[::1]:80", true},
- {"[1200::AB00:1234::2552:7777:1313]:22", false},
- {"-localhost:1", false},
- {"localhost.-localdomain:9090", false},
- {"localhost.localdomain.-int:65535", false},
- {"localhost.loc:100000", false},
- {"漢字汉字:2", false},
- {"www.jubfvq1v3p38i51622y0dvmdk1mymowjyeu26gbtw9andgynj1gg8z3msb1kl5z6906k846pj3sulm4kiyk82ln5teqj9nsht59opr0cs5ssltx78lfyvml19lfq1wp4usbl0o36cmiykch1vywbttcus1p9yu0669h8fj4ll7a6bmop505908s1m83q2ec2qr9nbvql2589adma3xsq2o38os2z3dmfh2tth4is4ixyfasasasefqwe4t2ub2fz1rme.de:20000", false},
- }
-
- for _, test := range tests {
- actual := IsDialString(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsDialString(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsMAC(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"3D:F2:C9:A6:B3:4F", true},
- {"3D-F2-C9-A6-B3:4F", false},
- {"123", false},
- {"", false},
- {"abacaba", false},
- }
- for _, test := range tests {
- actual := IsMAC(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsMAC(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestFilePath(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- osType int
- }{
- {"c:\\" + strings.Repeat("a", 32767), true, Win}, //See http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath
- {"c:\\" + strings.Repeat("a", 32768), false, Win},
- {"c:\\path\\file (x86)\bar", true, Win},
- {"c:\\path\\file", true, Win},
- {"c:\\path\\file:exe", false, Unknown},
- {"C:\\", true, Win},
- {"c:\\path\\file\\", true, Win},
- {"c:/path/file/", false, Unknown},
- {"/path/file/", true, Unix},
- {"/path/file:SAMPLE/", true, Unix},
- {"/path/file:/.txt", true, Unix},
- {"/path", true, Unix},
- {"/path/__bc/file.txt", true, Unix},
- {"/path/a--ac/file.txt", true, Unix},
- {"/_path/file.txt", true, Unix},
- {"/path/__bc/file.txt", true, Unix},
- {"/path/a--ac/file.txt", true, Unix},
- {"/__path/--file.txt", true, Unix},
- {"/path/a bc", true, Unix},
- }
- for _, test := range tests {
- actual, osType := IsFilePath(test.param)
- if actual != test.expected || osType != test.osType {
- t.Errorf("Expected IsFilePath(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsLatitude(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"-90.000", true},
- {"+90", true},
- {"47.1231231", true},
- {"+99.9", false},
- {"108", false},
- }
- for _, test := range tests {
- actual := IsLatitude(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsLatitude(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsLongitude(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"-180.000", true},
- {"180.1", false},
- {"+73.234", true},
- {"+382.3811", false},
- {"23.11111111", true},
- }
- for _, test := range tests {
- actual := IsLongitude(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsLongitude(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsSSN(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"00-90-8787", false},
- {"66690-76", false},
- {"191 60 2869", true},
- {"191-60-2869", true},
- }
- for _, test := range tests {
- actual := IsSSN(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsSSN(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsMongoID(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"507f1f77bcf86cd799439011", true},
- {"507f1f77bcf86cd7994390", false},
- {"507f1f77bcf86cd79943901z", false},
- {"507f1f77bcf86cd799439011 ", false},
- {"", false},
- }
- for _, test := range tests {
- actual := IsMongoID(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsMongoID(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsSemver(t *testing.T) {
- t.Parallel()
- var tests = []struct {
- param string
- expected bool
- }{
- {"v1.0.0", true},
- {"1.0.0", true},
- {"1.1.01", false},
- {"1.01.0", false},
- {"01.1.0", false},
- {"v1.1.01", false},
- {"v1.01.0", false},
- {"v01.1.0", false},
- {"1.0.0-alpha", true},
- {"1.0.0-alpha.1", true},
- {"1.0.0-0.3.7", true},
- {"1.0.0-0.03.7", false},
- {"1.0.0-00.3.7", false},
- {"1.0.0-x.7.z.92", true},
- {"1.0.0-alpha+001", true},
- {"1.0.0+20130313144700", true},
- {"1.0.0-beta+exp.sha.5114f85", true},
- {"1.0.0-beta+exp.sha.05114f85", true},
- {"1.0.0-+beta", false},
- {"1.0.0-b+-9+eta", false},
- {"v+1.8.0-b+-9+eta", false},
- }
- for _, test := range tests {
- actual := IsSemver(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsSemver(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsTime(t *testing.T) {
- t.Parallel()
- var tests = []struct {
- param string
- format string
- expected bool
- }{
- {"2016-12-31 11:00", time.RFC3339, false},
- {"2016-12-31 11:00:00", time.RFC3339, false},
- {"2016-12-31T11:00", time.RFC3339, false},
- {"2016-12-31T11:00:00", time.RFC3339, false},
- {"2016-12-31T11:00:00Z", time.RFC3339, true},
- {"2016-12-31T11:00:00+01:00", time.RFC3339, true},
- {"2016-12-31T11:00:00-01:00", time.RFC3339, true},
- {"2016-12-31T11:00:00.05Z", time.RFC3339, true},
- {"2016-12-31T11:00:00.05-01:00", time.RFC3339, true},
- {"2016-12-31T11:00:00.05+01:00", time.RFC3339, true},
- }
- for _, test := range tests {
- actual := IsTime(test.param, test.format)
- if actual != test.expected {
- t.Errorf("Expected IsTime(%q, time.RFC3339) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsRFC3339(t *testing.T) {
- t.Parallel()
- var tests = []struct {
- param string
- expected bool
- }{
- {"2016-12-31 11:00", false},
- {"2016-12-31 11:00:00", false},
- {"2016-12-31T11:00", false},
- {"2016-12-31T11:00:00", false},
- {"2016-12-31T11:00:00Z", true},
- {"2016-12-31T11:00:00+01:00", true},
- {"2016-12-31T11:00:00-01:00", true},
- {"2016-12-31T11:00:00.05Z", true},
- {"2016-12-31T11:00:00.05-01:00", true},
- {"2016-12-31T11:00:00.05+01:00", true},
- }
- for _, test := range tests {
- actual := IsRFC3339(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsRFC3339(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestIsISO4217(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"", false},
- {"ABCD", false},
- {"A", false},
- {"ZZZ", false},
- {"usd", false},
- {"USD", true},
- }
- for _, test := range tests {
- actual := IsISO4217(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsISO4217(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestByteLength(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- value string
- min string
- max string
- expected bool
- }{
- {"123456", "0", "100", true},
- {"1239999", "0", "0", false},
- {"1239asdfasf99", "100", "200", false},
- {"1239999asdff29", "10", "30", true},
- {"你", "0", "1", false},
- }
- for _, test := range tests {
- actual := ByteLength(test.value, test.min, test.max)
- if actual != test.expected {
- t.Errorf("Expected ByteLength(%s, %s, %s) to be %v, got %v", test.value, test.min, test.max, test.expected, actual)
- }
- }
-}
-
-func TestRuneLength(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- value string
- min string
- max string
- expected bool
- }{
- {"123456", "0", "100", true},
- {"1239999", "0", "0", false},
- {"1239asdfasf99", "100", "200", false},
- {"1239999asdff29", "10", "30", true},
- {"你", "0", "1", true},
- }
- for _, test := range tests {
- actual := RuneLength(test.value, test.min, test.max)
- if actual != test.expected {
- t.Errorf("Expected RuneLength(%s, %s, %s) to be %v, got %v", test.value, test.min, test.max, test.expected, actual)
- }
- }
-}
-
-func TestStringLength(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- value string
- min string
- max string
- expected bool
- }{
- {"123456", "0", "100", true},
- {"1239999", "0", "0", false},
- {"1239asdfasf99", "100", "200", false},
- {"1239999asdff29", "10", "30", true},
- {"あいうえお", "0", "5", true},
- {"あいうえおか", "0", "5", false},
- {"あいうえお", "0", "0", false},
- {"あいうえ", "5", "10", false},
- }
- for _, test := range tests {
- actual := StringLength(test.value, test.min, test.max)
- if actual != test.expected {
- t.Errorf("Expected StringLength(%s, %s, %s) to be %v, got %v", test.value, test.min, test.max, test.expected, actual)
- }
- }
-}
-
-func TestIsIn(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- value string
- params []string
- expected bool
- }{
- {"PRESENT", []string{"PRESENT"}, true},
- {"PRESENT", []string{"PRESENT", "PRÉSENTE", "NOTABSENT"}, true},
- {"PRÉSENTE", []string{"PRESENT", "PRÉSENTE", "NOTABSENT"}, true},
- {"PRESENT", []string{}, false},
- {"PRESENT", nil, false},
- {"ABSENT", []string{"PRESENT", "PRÉSENTE", "NOTABSENT"}, false},
- {"", []string{"PRESENT", "PRÉSENTE", "NOTABSENT"}, false},
- }
- for _, test := range tests {
- actual := IsIn(test.value, test.params...)
- if actual != test.expected {
- t.Errorf("Expected IsIn(%s, %v) to be %v, got %v", test.value, test.params, test.expected, actual)
- }
- }
-}
-
-type Address struct {
- Street string `valid:"-"`
- Zip string `json:"zip" valid:"numeric,required"`
-}
-
-type User struct {
- Name string `valid:"required"`
- Email string `valid:"required,email"`
- Password string `valid:"required"`
- Age int `valid:"required,numeric,@#\u0000"`
- Home *Address
- Work []Address
-}
-
-type UserValid struct {
- Name string `valid:"required"`
- Email string `valid:"required,email"`
- Password string `valid:"required"`
- Age int `valid:"required"`
- Home *Address
- Work []Address `valid:"required"`
-}
-
-type PrivateStruct struct {
- privateField string `valid:"required,alpha,d_k"`
- NonZero int
- ListInt []int
- ListString []string `valid:"alpha"`
- Work [2]Address
- Home Address
- Map map[string]Address
-}
-
-type NegationStruct struct {
- NotInt string `valid:"!int"`
- Int string `valid:"int"`
-}
-
-type LengthStruct struct {
- Length string `valid:"length(10|20)"`
-}
-
-type StringLengthStruct struct {
- Length string `valid:"stringlength(10|20)"`
-}
-
-type StringMatchesStruct struct {
- StringMatches string `valid:"matches(^[0-9]{3}$)"`
-}
-
-// TODO: this testcase should be fixed
-// type StringMatchesComplexStruct struct {
-// StringMatches string `valid:"matches(^\\$\\([\"']\\w+[\"']\\)$)"`
-// }
-
-type IsInStruct struct {
- IsIn string `valid:"in(PRESENT|PRÉSENTE|NOTABSENT)"`
-}
-
-type Post struct {
- Title string `valid:"alpha,required"`
- Message string `valid:"ascii"`
- AuthorIP string `valid:"ipv4"`
-}
-
-type MissingValidationDeclarationStruct struct {
- Name string ``
- Email string `valid:"required,email"`
-}
-
-type FieldsRequiredByDefaultButExemptStruct struct {
- Name string `valid:"-"`
- Email string `valid:"email"`
-}
-
-type FieldsRequiredByDefaultButExemptOrOptionalStruct struct {
- Name string `valid:"-"`
- Email string `valid:"optional,email"`
-}
-
-type MessageWithSeveralFieldsStruct struct {
- Title string `valid:"length(1|10)"`
- Body string `valid:"length(1|10)"`
-}
-
-func TestValidateMissingValidationDeclarationStruct(t *testing.T) {
- var tests = []struct {
- param MissingValidationDeclarationStruct
- expected bool
- }{
- {MissingValidationDeclarationStruct{}, false},
- {MissingValidationDeclarationStruct{Name: "TEST", Email: "test@example.com"}, false},
- }
- SetFieldsRequiredByDefault(true)
- for _, test := range tests {
- actual, err := ValidateStruct(test.param)
- if actual != test.expected {
- t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual)
- if err != nil {
- t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err)
- }
- }
- }
- SetFieldsRequiredByDefault(false)
-}
-
-func TestFieldsRequiredByDefaultButExemptStruct(t *testing.T) {
- var tests = []struct {
- param FieldsRequiredByDefaultButExemptStruct
- expected bool
- }{
- {FieldsRequiredByDefaultButExemptStruct{}, false},
- {FieldsRequiredByDefaultButExemptStruct{Name: "TEST"}, false},
- {FieldsRequiredByDefaultButExemptStruct{Email: ""}, false},
- {FieldsRequiredByDefaultButExemptStruct{Email: "test@example.com"}, true},
- }
- SetFieldsRequiredByDefault(true)
- for _, test := range tests {
- actual, err := ValidateStruct(test.param)
- if actual != test.expected {
- t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual)
- if err != nil {
- t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err)
- }
- }
- }
- SetFieldsRequiredByDefault(false)
-}
-
-func TestFieldsRequiredByDefaultButExemptOrOptionalStruct(t *testing.T) {
- var tests = []struct {
- param FieldsRequiredByDefaultButExemptOrOptionalStruct
- expected bool
- }{
- {FieldsRequiredByDefaultButExemptOrOptionalStruct{}, true},
- {FieldsRequiredByDefaultButExemptOrOptionalStruct{Name: "TEST"}, true},
- {FieldsRequiredByDefaultButExemptOrOptionalStruct{Email: ""}, true},
- {FieldsRequiredByDefaultButExemptOrOptionalStruct{Email: "test@example.com"}, true},
- {FieldsRequiredByDefaultButExemptOrOptionalStruct{Email: "test@example"}, false},
- }
- SetFieldsRequiredByDefault(true)
- for _, test := range tests {
- actual, err := ValidateStruct(test.param)
- if actual != test.expected {
- t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual)
- if err != nil {
- t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err)
- }
- }
- }
- SetFieldsRequiredByDefault(false)
-}
-
-func TestInvalidValidator(t *testing.T) {
- type InvalidStruct struct {
- Field int `valid:"someInvalidValidator"`
- }
-
- invalidStruct := InvalidStruct{1}
- if valid, err := ValidateStruct(&invalidStruct); valid || err == nil ||
- err.Error() != `Field: The following validator is invalid or can't be applied to the field: "someInvalidValidator";` {
- t.Errorf("Got an unexpected result for struct with invalid validator: %t %s", valid, err)
- }
-}
-
-func TestCustomValidator(t *testing.T) {
- type ValidStruct struct {
- Field int `valid:"customTrueValidator"`
- }
-
- type InvalidStruct struct {
- Field int `valid:"customFalseValidator~Custom validator error"`
- }
-
- type StructWithCustomAndBuiltinValidator struct {
- Field int `valid:"customTrueValidator,required"`
- }
-
- if valid, err := ValidateStruct(&ValidStruct{Field: 1}); !valid || err != nil {
- t.Errorf("Got an unexpected result for struct with custom always true validator: %t %s", valid, err)
- }
-
- if valid, err := ValidateStruct(&InvalidStruct{Field: 1}); valid || err == nil || err.Error() != "Custom validator error;;" {
- t.Errorf("Got an unexpected result for struct with custom always false validator: %t %s", valid, err)
- }
-
- mixedStruct := StructWithCustomAndBuiltinValidator{}
- if valid, err := ValidateStruct(&mixedStruct); valid || err == nil || err.Error() != "Field: non zero value required;" {
- t.Errorf("Got an unexpected result for invalid struct with custom and built-in validators: %t %s", valid, err)
- }
-
- mixedStruct.Field = 1
- if valid, err := ValidateStruct(&mixedStruct); !valid || err != nil {
- t.Errorf("Got an unexpected result for valid struct with custom and built-in validators: %t %s", valid, err)
- }
-}
-
-type CustomByteArray [6]byte
-
-type StructWithCustomByteArray struct {
- ID CustomByteArray `valid:"customByteArrayValidator,customMinLengthValidator"`
- Email string `valid:"email"`
- CustomMinLength int `valid:"-"`
-}
-
-func TestStructWithCustomByteArray(t *testing.T) {
- t.Parallel()
-
- // add our custom byte array validator that fails when the byte array is pristine (all zeroes)
- CustomTypeTagMap.Set("customByteArrayValidator", CustomTypeValidator(func(i interface{}, o interface{}) bool {
- switch v := o.(type) {
- case StructWithCustomByteArray:
- if len(v.Email) > 0 {
- if v.Email != "test@example.com" {
- t.Errorf("v.Email should have been 'test@example.com' but was '%s'", v.Email)
- }
- }
- default:
- t.Errorf("Context object passed to custom validator should have been a StructWithCustomByteArray but was %T (%+v)", o, o)
- }
-
- switch v := i.(type) {
- case CustomByteArray:
- for _, e := range v { // check if v is empty, i.e. all zeroes
- if e != 0 {
- return true
- }
- }
- }
- return false
- }))
- CustomTypeTagMap.Set("customMinLengthValidator", CustomTypeValidator(func(i interface{}, o interface{}) bool {
- switch v := o.(type) {
- case StructWithCustomByteArray:
- return len(v.ID) >= v.CustomMinLength
- }
- return false
- }))
- testCustomByteArray := CustomByteArray{'1', '2', '3', '4', '5', '6'}
- var tests = []struct {
- param StructWithCustomByteArray
- expected bool
- }{
- {StructWithCustomByteArray{}, false},
- {StructWithCustomByteArray{Email: "test@example.com"}, false},
- {StructWithCustomByteArray{ID: testCustomByteArray, Email: "test@example.com"}, true},
- {StructWithCustomByteArray{ID: testCustomByteArray, Email: "test@example.com", CustomMinLength: 7}, false},
- }
- SetFieldsRequiredByDefault(true)
- for _, test := range tests {
- actual, err := ValidateStruct(test.param)
- if actual != test.expected {
- t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual)
- if err != nil {
- t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err)
- }
- }
- }
- SetFieldsRequiredByDefault(false)
-}
-
-func TestValidateNegationStruct(t *testing.T) {
- var tests = []struct {
- param NegationStruct
- expected bool
- }{
- {NegationStruct{"a1", "11"}, true},
- {NegationStruct{"email@email.email", "11"}, true},
- {NegationStruct{"123456----", "11"}, true},
- {NegationStruct{"::1", "11"}, true},
- {NegationStruct{"123.123", "11"}, true},
- {NegationStruct{"a1", "a1"}, false},
- {NegationStruct{"11", "a1"}, false},
- {NegationStruct{"11", "11"}, false},
- }
- for _, test := range tests {
- actual, err := ValidateStruct(test.param)
- if actual != test.expected {
- t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual)
- if err != nil {
- t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err)
- }
- }
- }
-}
-
-func TestLengthStruct(t *testing.T) {
- var tests = []struct {
- param interface{}
- expected bool
- }{
- {LengthStruct{"11111"}, false},
- {LengthStruct{"11111111111111111110000000000000000"}, false},
- {LengthStruct{"11dfffdf0099"}, true},
- }
-
- for _, test := range tests {
- actual, err := ValidateStruct(test.param)
- if actual != test.expected {
- t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual)
- if err != nil {
- t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err)
- }
- }
- }
-}
-
-func TestStringLengthStruct(t *testing.T) {
- var tests = []struct {
- param interface{}
- expected bool
- }{
- {StringLengthStruct{"11111"}, false},
- {StringLengthStruct{"11111111111111111110000000000000000"}, false},
- {StringLengthStruct{"11dfffdf0099"}, true},
- {StringLengthStruct{"あいうえお"}, false},
- {StringLengthStruct{"あいうえおかきくけこ"}, true},
- {StringLengthStruct{"あいうえおかきくけこさしすせそたちつてと"}, true},
- {StringLengthStruct{"あいうえおかきくけこさしすせそたちつてとな"}, false},
- }
-
- for _, test := range tests {
- actual, err := ValidateStruct(test.param)
- if actual != test.expected {
- t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual)
- if err != nil {
- t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err)
- }
- }
- }
-}
-
-func TestStringMatchesStruct(t *testing.T) {
- var tests = []struct {
- param interface{}
- expected bool
- }{
- {StringMatchesStruct{"123"}, true},
- {StringMatchesStruct{"123456"}, false},
- {StringMatchesStruct{"123abcd"}, false},
- }
-
- for _, test := range tests {
- actual, err := ValidateStruct(test.param)
- if actual != test.expected {
- t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual)
- if err != nil {
- t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err)
- }
- }
- }
-}
-
-func TestIsInStruct(t *testing.T) {
- var tests = []struct {
- param interface{}
- expected bool
- }{
- {IsInStruct{"PRESENT"}, true},
- {IsInStruct{""}, true},
- {IsInStruct{" "}, false},
- {IsInStruct{"ABSENT"}, false},
- }
-
- for _, test := range tests {
- actual, err := ValidateStruct(test.param)
- if actual != test.expected {
- t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual)
- if err != nil {
- t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err)
- }
- }
- }
-}
-
-func TestRequiredIsInStruct(t *testing.T) {
- type RequiredIsInStruct struct {
- IsIn string `valid:"in(PRESENT|PRÉSENTE|NOTABSENT),required"`
- }
-
- var tests = []struct {
- param interface{}
- expected bool
- }{
- {RequiredIsInStruct{"PRESENT"}, true},
- {RequiredIsInStruct{""}, false},
- {RequiredIsInStruct{" "}, false},
- {RequiredIsInStruct{"ABSENT"}, false},
- }
-
- for _, test := range tests {
- actual, err := ValidateStruct(test.param)
- if actual != test.expected {
- t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual)
- if err != nil {
- t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err)
- }
- }
- }
-}
-
-func TestEmptyRequiredIsInStruct(t *testing.T) {
- type EmptyRequiredIsInStruct struct {
- IsIn string `valid:"in(),required"`
- }
-
- var tests = []struct {
- param interface{}
- expected bool
- }{
- {EmptyRequiredIsInStruct{"PRESENT"}, false},
- {EmptyRequiredIsInStruct{""}, false},
- {EmptyRequiredIsInStruct{" "}, false},
- {EmptyRequiredIsInStruct{"ABSENT"}, false},
- }
-
- for _, test := range tests {
- actual, err := ValidateStruct(test.param)
- if actual != test.expected {
- t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual)
- if err != nil {
- t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err)
- }
- }
- }
-}
-
-func TestFunkyIsInStruct(t *testing.T) {
- type FunkyIsInStruct struct {
- IsIn string `valid:"in(PRESENT|| |PRÉSENTE|NOTABSENT)"`
- }
-
- var tests = []struct {
- param interface{}
- expected bool
- }{
- {FunkyIsInStruct{"PRESENT"}, true},
- {FunkyIsInStruct{""}, true},
- {FunkyIsInStruct{" "}, true},
- {FunkyIsInStruct{"ABSENT"}, false},
- }
-
- for _, test := range tests {
- actual, err := ValidateStruct(test.param)
- if actual != test.expected {
- t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual)
- if err != nil {
- t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err)
- }
- }
- }
-}
-
-// TODO: test case broken
-// func TestStringMatchesComplexStruct(t *testing.T) {
-// var tests = []struct {
-// param interface{}
-// expected bool
-// }{
-// {StringMatchesComplexStruct{"$()"}, false},
-// {StringMatchesComplexStruct{"$('AZERTY')"}, true},
-// {StringMatchesComplexStruct{`$("AZERTY")`}, true},
-// {StringMatchesComplexStruct{`$("")`}, false},
-// {StringMatchesComplexStruct{"AZERTY"}, false},
-// {StringMatchesComplexStruct{"$AZERTY"}, false},
-// }
-
-// for _, test := range tests {
-// actual, err := ValidateStruct(test.param)
-// if actual != test.expected {
-// t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual)
-// if err != nil {
-// t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err)
-// }
-// }
-// }
-// }
-
-func TestValidateStruct(t *testing.T) {
-
- var tests = []struct {
- param interface{}
- expected bool
- }{
- {User{"John", "john@yahoo.com", "123G#678", 20, &Address{"Street", "123456"}, []Address{{"Street", "123456"}, {"Street", "123456"}}}, false},
- {User{"John", "john!yahoo.com", "12345678", 20, &Address{"Street", "ABC456D89"}, []Address{{"Street", "ABC456D89"}, {"Street", "123456"}}}, false},
- {User{"John", "", "12345", 0, &Address{"Street", "123456789"}, []Address{{"Street", "ABC456D89"}, {"Street", "123456"}}}, false},
- {UserValid{"John", "john@yahoo.com", "123G#678", 20, &Address{"Street", "123456"}, []Address{{"Street", "123456"}, {"Street", "123456"}}}, true},
- {UserValid{"John", "john!yahoo.com", "12345678", 20, &Address{"Street", "ABC456D89"}, []Address{}}, false},
- {UserValid{"John", "john!yahoo.com", "12345678", 20, &Address{"Street", "ABC456D89"}, []Address{{"Street", "ABC456D89"}, {"Street", "123456"}}}, false},
- {UserValid{"John", "", "12345", 0, &Address{"Street", "123456789"}, []Address{{"Street", "ABC456D89"}, {"Street", "123456"}}}, false},
- {nil, true},
- {User{"John", "john@yahoo.com", "123G#678", 0, &Address{"Street", "123456"}, []Address{}}, false},
- {"im not a struct", false},
- }
- for _, test := range tests {
- actual, err := ValidateStruct(test.param)
- if actual != test.expected {
- t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual)
- if err != nil {
- t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err)
- }
- }
- }
-
- TagMap["d_k"] = Validator(func(str string) bool {
- return str == "d_k"
- })
- result, err := ValidateStruct(PrivateStruct{"d_k", 0, []int{1, 2}, []string{"hi", "super"}, [2]Address{{"Street", "123456"},
- {"Street", "123456"}}, Address{"Street", "123456"}, map[string]Address{"address": {"Street", "123456"}}})
- if result != true {
- t.Log("Case ", 6, ": expected ", true, " when result is ", result)
- t.Error(err)
- t.FailNow()
- }
-}
-
-type testByteArray [8]byte
-type testByteMap map[byte]byte
-type testByteSlice []byte
-
-func TestRequired(t *testing.T) {
-
- testString := "foobar"
- var tests = []struct {
- param interface{}
- expected bool
- }{
- {
- struct {
- Pointer *string `valid:"required"`
- }{},
- false,
- },
- {
- struct {
- Pointer *string `valid:"required"`
- }{
- Pointer: &testString,
- },
- true,
- },
- {
- struct {
- Addr Address `valid:"required"`
- }{},
- false,
- },
- {
- struct {
- Addr Address `valid:"required"`
- }{
- Addr: Address{"", "123"},
- },
- true,
- },
- {
- struct {
- Pointer *Address `valid:"required"`
- }{},
- false,
- },
- {
- struct {
- Pointer *Address `valid:"required"`
- }{
- Pointer: &Address{"", "123"},
- },
- true,
- },
- {
- struct {
- TestByteArray testByteArray `valid:"required"`
- }{},
- false,
- },
- {
- struct {
- TestByteArray testByteArray `valid:"required"`
- }{
- testByteArray{},
- },
- false,
- },
- {
- struct {
- TestByteArray testByteArray `valid:"required"`
- }{
- testByteArray{'1', '2', '3', '4', '5', '6', '7', 'A'},
- },
- true,
- },
- {
- struct {
- TestByteMap testByteMap `valid:"required"`
- }{},
- false,
- },
- {
- struct {
- TestByteSlice testByteSlice `valid:"required"`
- }{},
- false,
- },
- }
- for _, test := range tests {
- actual, err := ValidateStruct(test.param)
- if actual != test.expected {
- t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual)
- if err != nil {
- t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err)
- }
- }
- }
-}
-
-func TestErrorByField(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected string
- }{
- {"message", ""},
- {"Message", ""},
- {"title", ""},
- {"Title", "My123 does not validate as alpha"},
- {"AuthorIP", "123 does not validate as ipv4"},
- }
- post := &Post{"My123", "duck13126", "123"}
- _, err := ValidateStruct(post)
-
- for _, test := range tests {
- actual := ErrorByField(err, test.param)
- if actual != test.expected {
- t.Errorf("Expected ErrorByField(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestErrorsByField(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected string
- }{
- {"Title", "My123 does not validate as alpha"},
- {"AuthorIP", "123 does not validate as ipv4"},
- }
- post := &Post{Title: "My123", Message: "duck13126", AuthorIP: "123"}
- _, err := ValidateStruct(post)
- errs := ErrorsByField(err)
- if len(errs) != 2 {
- t.Errorf("There should only be 2 errors but got %v", len(errs))
- }
-
- for _, test := range tests {
- if actual, ok := errs[test.param]; !ok || actual != test.expected {
- t.Errorf("Expected ErrorsByField(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-
- tests = []struct {
- param string
- expected string
- }{
- {"Title", ";:;message;:; does not validate as length(1|10)"},
- {"Body", ";:;message;:; does not validate as length(1|10)"},
- }
-
- message := &MessageWithSeveralFieldsStruct{Title: ";:;message;:;", Body: ";:;message;:;"}
- _, err = ValidateStruct(message)
- errs = ErrorsByField(err)
- if len(errs) != 2 {
- t.Errorf("There should only be 2 errors but got %v", len(errs))
- }
-
- for _, test := range tests {
- if actual, ok := errs[test.param]; !ok || actual != test.expected {
- t.Errorf("Expected ErrorsByField(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-
- tests = []struct {
- param string
- expected string
- }{
- {"CustomField", "An error occurred"},
- }
-
- err = Error{"CustomField", fmt.Errorf("An error occurred"), false}
- errs = ErrorsByField(err)
-
- if len(errs) != 1 {
- t.Errorf("There should only be 1 errors but got %v", len(errs))
- }
-
- for _, test := range tests {
- if actual, ok := errs[test.param]; !ok || actual != test.expected {
- t.Errorf("Expected ErrorsByField(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-
- type StructWithCustomValidation struct {
- Email string `valid:"email"`
- ID string `valid:"falseValidation"`
- }
-
- CustomTypeTagMap.Set("falseValidation", CustomTypeValidator(func(i interface{}, o interface{}) bool {
- return false
- }))
-
- tests = []struct {
- param string
- expected string
- }{
- {"Email", "My123 does not validate as email"},
- {"ID", "duck13126 does not validate as falseValidation"},
- }
- s := &StructWithCustomValidation{Email: "My123", ID: "duck13126"}
- _, err = ValidateStruct(s)
- errs = ErrorsByField(err)
- if len(errs) != 2 {
- t.Errorf("There should only be 2 errors but got %v", len(errs))
- }
-
- for _, test := range tests {
- if actual, ok := errs[test.param]; !ok || actual != test.expected {
- t.Errorf("Expected ErrorsByField(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestValidateStructPointers(t *testing.T) {
- // Struct which uses pointers for values
- type UserWithPointers struct {
- Name *string `valid:"-"`
- Email *string `valid:"email"`
- FavoriteFood *string `valid:"length(0|32)"`
- Nerd *bool `valid:"-"`
- }
-
- var tests = []struct {
- param string
- expected string
- }{
- {"Name", ""},
- {"Email", "invalid does not validate as email"},
- {"FavoriteFood", ""},
- {"Nerd", ""},
- }
-
- name := "Herman"
- email := "invalid"
- food := "Pizza"
- nerd := true
- user := &UserWithPointers{&name, &email, &food, &nerd}
- _, err := ValidateStruct(user)
-
- for _, test := range tests {
- actual := ErrorByField(err, test.param)
- if actual != test.expected {
- t.Errorf("Expected ErrorByField(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func ExampleValidateStruct() {
- type Post struct {
- Title string `valid:"alphanum,required"`
- Message string `valid:"duck,ascii"`
- AuthorIP string `valid:"ipv4"`
- }
- post := &Post{"My Example Post", "duck", "123.234.54.3"}
-
- //Add your own struct validation tags
- TagMap["duck"] = Validator(func(str string) bool {
- return str == "duck"
- })
-
- result, err := ValidateStruct(post)
- if err != nil {
- println("error: " + err.Error())
- }
- println(result)
-}
-
-func TestIsCIDR(t *testing.T) {
- t.Parallel()
-
- var tests = []struct {
- param string
- expected bool
- }{
- {"193.168.3.20/7", true},
- {"2001:db8::/32", true},
- {"2001:0db8:85a3:0000:0000:8a2e:0370:7334/64", true},
- {"193.138.3.20/60", false},
- {"500.323.2.23/43", false},
- {"", false},
- }
- for _, test := range tests {
- actual := IsCIDR(test.param)
- if actual != test.expected {
- t.Errorf("Expected IsCIDR(%q) to be %v, got %v", test.param, test.expected, actual)
- }
- }
-}
-
-func TestOptionalCustomValidators(t *testing.T) {
-
- CustomTypeTagMap.Set("f2", CustomTypeValidator(func(i interface{}, o interface{}) bool {
- return false
- }))
-
- var val struct {
- WithCustomError string `valid:"f2~boom,optional"`
- WithoutCustomError string `valid:"f2,optional"`
- OptionalFirst string `valid:"optional,f2"`
- }
-
- ok, err := ValidateStruct(val)
-
- if err != nil {
- t.Errorf("Expected nil err with optional validation, got %v", err)
- }
-
- if !ok {
- t.Error("Expected validation to return true, got false")
- }
-}
-
-func TestJSONValidator(t *testing.T) {
-
- var val struct {
- WithJSONName string `json:"with_json_name" valid:"-,required"`
- WithoutJSONName string `valid:"-,required"`
- WithJSONOmit string `json:"with_other_json_name,omitempty" valid:"-,required"`
- WithJSONOption string `json:",omitempty" valid:"-,required"`
- }
-
- _, err := ValidateStruct(val)
-
- if err == nil {
- t.Error("Expected error but got no error")
- }
-
- if Contains(err.Error(), "WithJSONName") {
- t.Errorf("Expected error message to contain with_json_name but actual error is: %s", err.Error())
- }
-
- if Contains(err.Error(), "WithoutJSONName") == false {
- t.Errorf("Expected error message to contain WithoutJSONName but actual error is: %s", err.Error())
- }
-
- if Contains(err.Error(), "omitempty") {
- t.Errorf("Expected error message to not contain ',omitempty' but actual error is: %s", err.Error())
- }
-}
diff --git a/vendor/github.com/asaskevich/govalidator/wercker.yml b/vendor/github.com/asaskevich/govalidator/wercker.yml
deleted file mode 100644
index cac7a5f..0000000
--- a/vendor/github.com/asaskevich/govalidator/wercker.yml
+++ /dev/null
@@ -1,15 +0,0 @@
-box: golang
-build:
- steps:
- - setup-go-workspace
-
- - script:
- name: go get
- code: |
- go version
- go get -t ./...
-
- - script:
- name: go test
- code: |
- go test -race ./...
diff --git a/vendor/github.com/dgrijalva/jwt-go/.gitignore b/vendor/github.com/dgrijalva/jwt-go/.gitignore
deleted file mode 100644
index 80bed65..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/.gitignore
+++ /dev/null
@@ -1,4 +0,0 @@
-.DS_Store
-bin
-
-
diff --git a/vendor/github.com/dgrijalva/jwt-go/.travis.yml b/vendor/github.com/dgrijalva/jwt-go/.travis.yml
deleted file mode 100644
index 1027f56..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/.travis.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-language: go
-
-script:
- - go vet ./...
- - go test -v ./...
-
-go:
- - 1.3
- - 1.4
- - 1.5
- - 1.6
- - 1.7
- - tip
diff --git a/vendor/github.com/dgrijalva/jwt-go/LICENSE b/vendor/github.com/dgrijalva/jwt-go/LICENSE
deleted file mode 100644
index df83a9c..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/LICENSE
+++ /dev/null
@@ -1,8 +0,0 @@
-Copyright (c) 2012 Dave Grijalva
-
-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.
-
diff --git a/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md b/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md
deleted file mode 100644
index 7fc1f79..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md
+++ /dev/null
@@ -1,97 +0,0 @@
-## Migration Guide from v2 -> v3
-
-Version 3 adds several new, frequently requested features. To do so, it introduces a few breaking changes. We've worked to keep these as minimal as possible. This guide explains the breaking changes and how you can quickly update your code.
-
-### `Token.Claims` is now an interface type
-
-The most requested feature from the 2.0 verison of this library was the ability to provide a custom type to the JSON parser for claims. This was implemented by introducing a new interface, `Claims`, to replace `map[string]interface{}`. We also included two concrete implementations of `Claims`: `MapClaims` and `StandardClaims`.
-
-`MapClaims` is an alias for `map[string]interface{}` with built in validation behavior. It is the default claims type when using `Parse`. The usage is unchanged except you must type cast the claims property.
-
-The old example for parsing a token looked like this..
-
-```go
- if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil {
- fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"])
- }
-```
-
-is now directly mapped to...
-
-```go
- if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil {
- claims := token.Claims.(jwt.MapClaims)
- fmt.Printf("Token for user %v expires %v", claims["user"], claims["exp"])
- }
-```
-
-`StandardClaims` is designed to be embedded in your custom type. You can supply a custom claims type with the new `ParseWithClaims` function. Here's an example of using a custom claims type.
-
-```go
- type MyCustomClaims struct {
- User string
- *StandardClaims
- }
-
- if token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, keyLookupFunc); err == nil {
- claims := token.Claims.(*MyCustomClaims)
- fmt.Printf("Token for user %v expires %v", claims.User, claims.StandardClaims.ExpiresAt)
- }
-```
-
-### `ParseFromRequest` has been moved
-
-To keep this library focused on the tokens without becoming overburdened with complex request processing logic, `ParseFromRequest` and its new companion `ParseFromRequestWithClaims` have been moved to a subpackage, `request`. The method signatues have also been augmented to receive a new argument: `Extractor`.
-
-`Extractors` do the work of picking the token string out of a request. The interface is simple and composable.
-
-This simple parsing example:
-
-```go
- if token, err := jwt.ParseFromRequest(tokenString, req, keyLookupFunc); err == nil {
- fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"])
- }
-```
-
-is directly mapped to:
-
-```go
- if token, err := request.ParseFromRequest(req, request.OAuth2Extractor, keyLookupFunc); err == nil {
- claims := token.Claims.(jwt.MapClaims)
- fmt.Printf("Token for user %v expires %v", claims["user"], claims["exp"])
- }
-```
-
-There are several concrete `Extractor` types provided for your convenience:
-
-* `HeaderExtractor` will search a list of headers until one contains content.
-* `ArgumentExtractor` will search a list of keys in request query and form arguments until one contains content.
-* `MultiExtractor` will try a list of `Extractors` in order until one returns content.
-* `AuthorizationHeaderExtractor` will look in the `Authorization` header for a `Bearer` token.
-* `OAuth2Extractor` searches the places an OAuth2 token would be specified (per the spec): `Authorization` header and `access_token` argument
-* `PostExtractionFilter` wraps an `Extractor`, allowing you to process the content before it's parsed. A simple example is stripping the `Bearer ` text from a header
-
-
-### RSA signing methods no longer accept `[]byte` keys
-
-Due to a [critical vulnerability](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/), we've decided the convenience of accepting `[]byte` instead of `rsa.PublicKey` or `rsa.PrivateKey` isn't worth the risk of misuse.
-
-To replace this behavior, we've added two helper methods: `ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error)` and `ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error)`. These are just simple helpers for unpacking PEM encoded PKCS1 and PKCS8 keys. If your keys are encoded any other way, all you need to do is convert them to the `crypto/rsa` package's types.
-
-```go
- func keyLookupFunc(*Token) (interface{}, error) {
- // Don't forget to validate the alg is what you expect:
- if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
- return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
- }
-
- // Look up key
- key, err := lookupPublicKey(token.Header["kid"])
- if err != nil {
- return nil, err
- }
-
- // Unpack key from PEM encoded PKCS8
- return jwt.ParseRSAPublicKeyFromPEM(key)
- }
-```
diff --git a/vendor/github.com/dgrijalva/jwt-go/README.md b/vendor/github.com/dgrijalva/jwt-go/README.md
deleted file mode 100644
index 25aec48..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/README.md
+++ /dev/null
@@ -1,85 +0,0 @@
-A [go](http://www.golang.org) (or 'golang' for search engine friendliness) implementation of [JSON Web Tokens](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html)
-
-[](https://travis-ci.org/dgrijalva/jwt-go)
-
-**BREAKING CHANGES:*** Version 3.0.0 is here. It includes _a lot_ of changes including a few that break the API. We've tried to break as few things as possible, so there should just be a few type signature changes. A full list of breaking changes is available in `VERSION_HISTORY.md`. See `MIGRATION_GUIDE.md` for more information on updating your code.
-
-**NOTICE:** It's important that you [validate the `alg` presented is what you expect](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/). This library attempts to make it easy to do the right thing by requiring key types match the expected alg, but you should take the extra step to verify it in your usage. See the examples provided.
-
-
-## What the heck is a JWT?
-
-JWT.io has [a great introduction](https://jwt.io/introduction) to JSON Web Tokens.
-
-In short, it's a signed JSON object that does something useful (for example, authentication). It's commonly used for `Bearer` tokens in Oauth 2. A token is made of three parts, separated by `.`'s. The first two parts are JSON objects, that have been [base64url](http://tools.ietf.org/html/rfc4648) encoded. The last part is the signature, encoded the same way.
-
-The first part is called the header. It contains the necessary information for verifying the last part, the signature. For example, which encryption method was used for signing and what key was used.
-
-The part in the middle is the interesting bit. It's called the Claims and contains the actual stuff you care about. Refer to [the RFC](http://self-issued.info/docs/draft-jones-json-web-token.html) for information about reserved keys and the proper way to add your own.
-
-## What's in the box?
-
-This library supports the parsing and verification as well as the generation and signing of JWTs. Current supported signing algorithms are HMAC SHA, RSA, RSA-PSS, and ECDSA, though hooks are present for adding your own.
-
-## Examples
-
-See [the project documentation](https://godoc.org/github.com/dgrijalva/jwt-go) for examples of usage:
-
-* [Simple example of parsing and validating a token](https://godoc.org/github.com/dgrijalva/jwt-go#example-Parse--Hmac)
-* [Simple example of building and signing a token](https://godoc.org/github.com/dgrijalva/jwt-go#example-New--Hmac)
-* [Directory of Examples](https://godoc.org/github.com/dgrijalva/jwt-go#pkg-examples)
-
-## Extensions
-
-This library publishes all the necessary components for adding your own signing methods. Simply implement the `SigningMethod` interface and register a factory method using `RegisterSigningMethod`.
-
-Here's an example of an extension that integrates with the Google App Engine signing tools: https://github.com/someone1/gcp-jwt-go
-
-## Compliance
-
-This library was last reviewed to comply with [RTF 7519](http://www.rfc-editor.org/info/rfc7519) dated May 2015 with a few notable differences:
-
-* In order to protect against accidental use of [Unsecured JWTs](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#UnsecuredJWT), tokens using `alg=none` will only be accepted if the constant `jwt.UnsafeAllowNoneSignatureType` is provided as the key.
-
-## Project Status & Versioning
-
-This library is considered production ready. Feedback and feature requests are appreciated. The API should be considered stable. There should be very few backwards-incompatible changes outside of major version updates (and only with good reason).
-
-This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull requests will land on `master`. Periodically, versions will be tagged from `master`. You can find all the releases on [the project releases page](https://github.com/dgrijalva/jwt-go/releases).
-
-While we try to make it obvious when we make breaking changes, there isn't a great mechanism for pushing announcements out to users. You may want to use this alternative package include: `gopkg.in/dgrijalva/jwt-go.v2`. It will do the right thing WRT semantic versioning.
-
-## Usage Tips
-
-### Signing vs Encryption
-
-A token is simply a JSON object that is signed by its author. this tells you exactly two things about the data:
-
-* The author of the token was in the possession of the signing secret
-* The data has not been modified since it was signed
-
-It's important to know that JWT does not provide encryption, which means anyone who has access to the token can read its contents. If you need to protect (encrypt) the data, there is a companion spec, `JWE`, that provides this functionality. JWE is currently outside the scope of this library.
-
-### Choosing a Signing Method
-
-There are several signing methods available, and you should probably take the time to learn about the various options before choosing one. The principal design decision is most likely going to be symmetric vs asymmetric.
-
-Symmetric signing methods, such as HSA, use only a single secret. This is probably the simplest signing method to use since any `[]byte` can be used as a valid secret. They are also slightly computationally faster to use, though this rarely is enough to matter. Symmetric signing methods work the best when both producers and consumers of tokens are trusted, or even the same system. Since the same secret is used to both sign and validate tokens, you can't easily distribute the key for validation.
-
-Asymmetric signing methods, such as RSA, use different keys for signing and verifying tokens. This makes it possible to produce tokens with a private key, and allow any consumer to access the public key for verification.
-
-### JWT and OAuth
-
-It's worth mentioning that OAuth and JWT are not the same thing. A JWT token is simply a signed JSON object. It can be used anywhere such a thing is useful. There is some confusion, though, as JWT is the most common type of bearer token used in OAuth2 authentication.
-
-Without going too far down the rabbit hole, here's a description of the interaction of these technologies:
-
-* OAuth is a protocol for allowing an identity provider to be separate from the service a user is logging in to. For example, whenever you use Facebook to log into a different service (Yelp, Spotify, etc), you are using OAuth.
-* OAuth defines several options for passing around authentication data. One popular method is called a "bearer token". A bearer token is simply a string that _should_ only be held by an authenticated user. Thus, simply presenting this token proves your identity. You can probably derive from here why a JWT might make a good bearer token.
-* Because bearer tokens are used for authentication, it's important they're kept secret. This is why transactions that use bearer tokens typically happen over SSL.
-
-## More
-
-Documentation can be found [on godoc.org](http://godoc.org/github.com/dgrijalva/jwt-go).
-
-The command line utility included in this project (cmd/jwt) provides a straightforward example of token creation and parsing as well as a useful tool for debugging your own integration. You'll also find several implementation examples in the documentation.
diff --git a/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md b/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md
deleted file mode 100644
index c21551f..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md
+++ /dev/null
@@ -1,111 +0,0 @@
-## `jwt-go` Version History
-
-#### 3.1.0
-
-* Improvements to `jwt` command line tool
-* Added `SkipClaimsValidation` option to `Parser`
-* Documentation updates
-
-#### 3.0.0
-
-* **Compatibility Breaking Changes**: See MIGRATION_GUIDE.md for tips on updating your code
- * Dropped support for `[]byte` keys when using RSA signing methods. This convenience feature could contribute to security vulnerabilities involving mismatched key types with signing methods.
- * `ParseFromRequest` has been moved to `request` subpackage and usage has changed
- * The `Claims` property on `Token` is now type `Claims` instead of `map[string]interface{}`. The default value is type `MapClaims`, which is an alias to `map[string]interface{}`. This makes it possible to use a custom type when decoding claims.
-* Other Additions and Changes
- * Added `Claims` interface type to allow users to decode the claims into a custom type
- * Added `ParseWithClaims`, which takes a third argument of type `Claims`. Use this function instead of `Parse` if you have a custom type you'd like to decode into.
- * Dramatically improved the functionality and flexibility of `ParseFromRequest`, which is now in the `request` subpackage
- * Added `ParseFromRequestWithClaims` which is the `FromRequest` equivalent of `ParseWithClaims`
- * Added new interface type `Extractor`, which is used for extracting JWT strings from http requests. Used with `ParseFromRequest` and `ParseFromRequestWithClaims`.
- * Added several new, more specific, validation errors to error type bitmask
- * Moved examples from README to executable example files
- * Signing method registry is now thread safe
- * Added new property to `ValidationError`, which contains the raw error returned by calls made by parse/verify (such as those returned by keyfunc or json parser)
-
-#### 2.7.0
-
-This will likely be the last backwards compatible release before 3.0.0, excluding essential bug fixes.
-
-* Added new option `-show` to the `jwt` command that will just output the decoded token without verifying
-* Error text for expired tokens includes how long it's been expired
-* Fixed incorrect error returned from `ParseRSAPublicKeyFromPEM`
-* Documentation updates
-
-#### 2.6.0
-
-* Exposed inner error within ValidationError
-* Fixed validation errors when using UseJSONNumber flag
-* Added several unit tests
-
-#### 2.5.0
-
-* Added support for signing method none. You shouldn't use this. The API tries to make this clear.
-* Updated/fixed some documentation
-* Added more helpful error message when trying to parse tokens that begin with `BEARER `
-
-#### 2.4.0
-
-* Added new type, Parser, to allow for configuration of various parsing parameters
- * You can now specify a list of valid signing methods. Anything outside this set will be rejected.
- * You can now opt to use the `json.Number` type instead of `float64` when parsing token JSON
-* Added support for [Travis CI](https://travis-ci.org/dgrijalva/jwt-go)
-* Fixed some bugs with ECDSA parsing
-
-#### 2.3.0
-
-* Added support for ECDSA signing methods
-* Added support for RSA PSS signing methods (requires go v1.4)
-
-#### 2.2.0
-
-* Gracefully handle a `nil` `Keyfunc` being passed to `Parse`. Result will now be the parsed token and an error, instead of a panic.
-
-#### 2.1.0
-
-Backwards compatible API change that was missed in 2.0.0.
-
-* The `SignedString` method on `Token` now takes `interface{}` instead of `[]byte`
-
-#### 2.0.0
-
-There were two major reasons for breaking backwards compatibility with this update. The first was a refactor required to expand the width of the RSA and HMAC-SHA signing implementations. There will likely be no required code changes to support this change.
-
-The second update, while unfortunately requiring a small change in integration, is required to open up this library to other signing methods. Not all keys used for all signing methods have a single standard on-disk representation. Requiring `[]byte` as the type for all keys proved too limiting. Additionally, this implementation allows for pre-parsed tokens to be reused, which might matter in an application that parses a high volume of tokens with a small set of keys. Backwards compatibilty has been maintained for passing `[]byte` to the RSA signing methods, but they will also accept `*rsa.PublicKey` and `*rsa.PrivateKey`.
-
-It is likely the only integration change required here will be to change `func(t *jwt.Token) ([]byte, error)` to `func(t *jwt.Token) (interface{}, error)` when calling `Parse`.
-
-* **Compatibility Breaking Changes**
- * `SigningMethodHS256` is now `*SigningMethodHMAC` instead of `type struct`
- * `SigningMethodRS256` is now `*SigningMethodRSA` instead of `type struct`
- * `KeyFunc` now returns `interface{}` instead of `[]byte`
- * `SigningMethod.Sign` now takes `interface{}` instead of `[]byte` for the key
- * `SigningMethod.Verify` now takes `interface{}` instead of `[]byte` for the key
-* Renamed type `SigningMethodHS256` to `SigningMethodHMAC`. Specific sizes are now just instances of this type.
- * Added public package global `SigningMethodHS256`
- * Added public package global `SigningMethodHS384`
- * Added public package global `SigningMethodHS512`
-* Renamed type `SigningMethodRS256` to `SigningMethodRSA`. Specific sizes are now just instances of this type.
- * Added public package global `SigningMethodRS256`
- * Added public package global `SigningMethodRS384`
- * Added public package global `SigningMethodRS512`
-* Moved sample private key for HMAC tests from an inline value to a file on disk. Value is unchanged.
-* Refactored the RSA implementation to be easier to read
-* Exposed helper methods `ParseRSAPrivateKeyFromPEM` and `ParseRSAPublicKeyFromPEM`
-
-#### 1.0.2
-
-* Fixed bug in parsing public keys from certificates
-* Added more tests around the parsing of keys for RS256
-* Code refactoring in RS256 implementation. No functional changes
-
-#### 1.0.1
-
-* Fixed panic if RS256 signing method was passed an invalid key
-
-#### 1.0.0
-
-* First versioned release
-* API stabilized
-* Supports creating, signing, parsing, and validating JWT tokens
-* Supports RS256 and HS256 signing methods
\ No newline at end of file
diff --git a/vendor/github.com/dgrijalva/jwt-go/claims.go b/vendor/github.com/dgrijalva/jwt-go/claims.go
deleted file mode 100644
index f0228f0..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/claims.go
+++ /dev/null
@@ -1,134 +0,0 @@
-package jwt
-
-import (
- "crypto/subtle"
- "fmt"
- "time"
-)
-
-// For a type to be a Claims object, it must just have a Valid method that determines
-// if the token is invalid for any supported reason
-type Claims interface {
- Valid() error
-}
-
-// Structured version of Claims Section, as referenced at
-// https://tools.ietf.org/html/rfc7519#section-4.1
-// See examples for how to use this with your own claim types
-type StandardClaims struct {
- Audience string `json:"aud,omitempty"`
- ExpiresAt int64 `json:"exp,omitempty"`
- Id string `json:"jti,omitempty"`
- IssuedAt int64 `json:"iat,omitempty"`
- Issuer string `json:"iss,omitempty"`
- NotBefore int64 `json:"nbf,omitempty"`
- Subject string `json:"sub,omitempty"`
-}
-
-// Validates time based claims "exp, iat, nbf".
-// There is no accounting for clock skew.
-// As well, if any of the above claims are not in the token, it will still
-// be considered a valid claim.
-func (c StandardClaims) Valid() error {
- vErr := new(ValidationError)
- now := TimeFunc().Unix()
-
- // The claims below are optional, by default, so if they are set to the
- // default value in Go, let's not fail the verification for them.
- if c.VerifyExpiresAt(now, false) == false {
- delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0))
- vErr.Inner = fmt.Errorf("token is expired by %v", delta)
- vErr.Errors |= ValidationErrorExpired
- }
-
- if c.VerifyIssuedAt(now, false) == false {
- vErr.Inner = fmt.Errorf("Token used before issued")
- vErr.Errors |= ValidationErrorIssuedAt
- }
-
- if c.VerifyNotBefore(now, false) == false {
- vErr.Inner = fmt.Errorf("token is not valid yet")
- vErr.Errors |= ValidationErrorNotValidYet
- }
-
- if vErr.valid() {
- return nil
- }
-
- return vErr
-}
-
-// Compares the aud claim against cmp.
-// If required is false, this method will return true if the value matches or is unset
-func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool {
- return verifyAud(c.Audience, cmp, req)
-}
-
-// Compares the exp claim against cmp.
-// If required is false, this method will return true if the value matches or is unset
-func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool {
- return verifyExp(c.ExpiresAt, cmp, req)
-}
-
-// Compares the iat claim against cmp.
-// If required is false, this method will return true if the value matches or is unset
-func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool {
- return verifyIat(c.IssuedAt, cmp, req)
-}
-
-// Compares the iss claim against cmp.
-// If required is false, this method will return true if the value matches or is unset
-func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool {
- return verifyIss(c.Issuer, cmp, req)
-}
-
-// Compares the nbf claim against cmp.
-// If required is false, this method will return true if the value matches or is unset
-func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool {
- return verifyNbf(c.NotBefore, cmp, req)
-}
-
-// ----- helpers
-
-func verifyAud(aud string, cmp string, required bool) bool {
- if aud == "" {
- return !required
- }
- if subtle.ConstantTimeCompare([]byte(aud), []byte(cmp)) != 0 {
- return true
- } else {
- return false
- }
-}
-
-func verifyExp(exp int64, now int64, required bool) bool {
- if exp == 0 {
- return !required
- }
- return now <= exp
-}
-
-func verifyIat(iat int64, now int64, required bool) bool {
- if iat == 0 {
- return !required
- }
- return now >= iat
-}
-
-func verifyIss(iss string, cmp string, required bool) bool {
- if iss == "" {
- return !required
- }
- if subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0 {
- return true
- } else {
- return false
- }
-}
-
-func verifyNbf(nbf int64, now int64, required bool) bool {
- if nbf == 0 {
- return !required
- }
- return now >= nbf
-}
diff --git a/vendor/github.com/dgrijalva/jwt-go/doc.go b/vendor/github.com/dgrijalva/jwt-go/doc.go
deleted file mode 100644
index a86dc1a..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/doc.go
+++ /dev/null
@@ -1,4 +0,0 @@
-// Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html
-//
-// See README.md for more info.
-package jwt
diff --git a/vendor/github.com/dgrijalva/jwt-go/ecdsa.go b/vendor/github.com/dgrijalva/jwt-go/ecdsa.go
deleted file mode 100644
index 2f59a22..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/ecdsa.go
+++ /dev/null
@@ -1,147 +0,0 @@
-package jwt
-
-import (
- "crypto"
- "crypto/ecdsa"
- "crypto/rand"
- "errors"
- "math/big"
-)
-
-var (
- // Sadly this is missing from crypto/ecdsa compared to crypto/rsa
- ErrECDSAVerification = errors.New("crypto/ecdsa: verification error")
-)
-
-// Implements the ECDSA family of signing methods signing methods
-type SigningMethodECDSA struct {
- Name string
- Hash crypto.Hash
- KeySize int
- CurveBits int
-}
-
-// Specific instances for EC256 and company
-var (
- SigningMethodES256 *SigningMethodECDSA
- SigningMethodES384 *SigningMethodECDSA
- SigningMethodES512 *SigningMethodECDSA
-)
-
-func init() {
- // ES256
- SigningMethodES256 = &SigningMethodECDSA{"ES256", crypto.SHA256, 32, 256}
- RegisterSigningMethod(SigningMethodES256.Alg(), func() SigningMethod {
- return SigningMethodES256
- })
-
- // ES384
- SigningMethodES384 = &SigningMethodECDSA{"ES384", crypto.SHA384, 48, 384}
- RegisterSigningMethod(SigningMethodES384.Alg(), func() SigningMethod {
- return SigningMethodES384
- })
-
- // ES512
- SigningMethodES512 = &SigningMethodECDSA{"ES512", crypto.SHA512, 66, 521}
- RegisterSigningMethod(SigningMethodES512.Alg(), func() SigningMethod {
- return SigningMethodES512
- })
-}
-
-func (m *SigningMethodECDSA) Alg() string {
- return m.Name
-}
-
-// Implements the Verify method from SigningMethod
-// For this verify method, key must be an ecdsa.PublicKey struct
-func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error {
- var err error
-
- // Decode the signature
- var sig []byte
- if sig, err = DecodeSegment(signature); err != nil {
- return err
- }
-
- // Get the key
- var ecdsaKey *ecdsa.PublicKey
- switch k := key.(type) {
- case *ecdsa.PublicKey:
- ecdsaKey = k
- default:
- return ErrInvalidKeyType
- }
-
- if len(sig) != 2*m.KeySize {
- return ErrECDSAVerification
- }
-
- r := big.NewInt(0).SetBytes(sig[:m.KeySize])
- s := big.NewInt(0).SetBytes(sig[m.KeySize:])
-
- // Create hasher
- if !m.Hash.Available() {
- return ErrHashUnavailable
- }
- hasher := m.Hash.New()
- hasher.Write([]byte(signingString))
-
- // Verify the signature
- if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus == true {
- return nil
- } else {
- return ErrECDSAVerification
- }
-}
-
-// Implements the Sign method from SigningMethod
-// For this signing method, key must be an ecdsa.PrivateKey struct
-func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error) {
- // Get the key
- var ecdsaKey *ecdsa.PrivateKey
- switch k := key.(type) {
- case *ecdsa.PrivateKey:
- ecdsaKey = k
- default:
- return "", ErrInvalidKeyType
- }
-
- // Create the hasher
- if !m.Hash.Available() {
- return "", ErrHashUnavailable
- }
-
- hasher := m.Hash.New()
- hasher.Write([]byte(signingString))
-
- // Sign the string and return r, s
- if r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, hasher.Sum(nil)); err == nil {
- curveBits := ecdsaKey.Curve.Params().BitSize
-
- if m.CurveBits != curveBits {
- return "", ErrInvalidKey
- }
-
- keyBytes := curveBits / 8
- if curveBits%8 > 0 {
- keyBytes += 1
- }
-
- // We serialize the outpus (r and s) into big-endian byte arrays and pad
- // them with zeros on the left to make sure the sizes work out. Both arrays
- // must be keyBytes long, and the output must be 2*keyBytes long.
- rBytes := r.Bytes()
- rBytesPadded := make([]byte, keyBytes)
- copy(rBytesPadded[keyBytes-len(rBytes):], rBytes)
-
- sBytes := s.Bytes()
- sBytesPadded := make([]byte, keyBytes)
- copy(sBytesPadded[keyBytes-len(sBytes):], sBytes)
-
- out := append(rBytesPadded, sBytesPadded...)
-
- return EncodeSegment(out), nil
- } else {
- return "", err
- }
-}
diff --git a/vendor/github.com/dgrijalva/jwt-go/ecdsa_test.go b/vendor/github.com/dgrijalva/jwt-go/ecdsa_test.go
deleted file mode 100644
index 753047b..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/ecdsa_test.go
+++ /dev/null
@@ -1,100 +0,0 @@
-package jwt_test
-
-import (
- "crypto/ecdsa"
- "io/ioutil"
- "strings"
- "testing"
-
- "github.com/dgrijalva/jwt-go"
-)
-
-var ecdsaTestData = []struct {
- name string
- keys map[string]string
- tokenString string
- alg string
- claims map[string]interface{}
- valid bool
-}{
- {
- "Basic ES256",
- map[string]string{"private": "test/ec256-private.pem", "public": "test/ec256-public.pem"},
- "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJmb28iOiJiYXIifQ.feG39E-bn8HXAKhzDZq7yEAPWYDhZlwTn3sePJnU9VrGMmwdXAIEyoOnrjreYlVM_Z4N13eK9-TmMTWyfKJtHQ",
- "ES256",
- map[string]interface{}{"foo": "bar"},
- true,
- },
- {
- "Basic ES384",
- map[string]string{"private": "test/ec384-private.pem", "public": "test/ec384-public.pem"},
- "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzM4NCJ9.eyJmb28iOiJiYXIifQ.ngAfKMbJUh0WWubSIYe5GMsA-aHNKwFbJk_wq3lq23aPp8H2anb1rRILIzVR0gUf4a8WzDtrzmiikuPWyCS6CN4-PwdgTk-5nehC7JXqlaBZU05p3toM3nWCwm_LXcld",
- "ES384",
- map[string]interface{}{"foo": "bar"},
- true,
- },
- {
- "Basic ES512",
- map[string]string{"private": "test/ec512-private.pem", "public": "test/ec512-public.pem"},
- "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzUxMiJ9.eyJmb28iOiJiYXIifQ.AAU0TvGQOcdg2OvrwY73NHKgfk26UDekh9Prz-L_iWuTBIBqOFCWwwLsRiHB1JOddfKAls5do1W0jR_F30JpVd-6AJeTjGKA4C1A1H6gIKwRY0o_tFDIydZCl_lMBMeG5VNFAjO86-WCSKwc3hqaGkq1MugPRq_qrF9AVbuEB4JPLyL5",
- "ES512",
- map[string]interface{}{"foo": "bar"},
- true,
- },
- {
- "basic ES256 invalid: foo => bar",
- map[string]string{"private": "test/ec256-private.pem", "public": "test/ec256-public.pem"},
- "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.MEQCIHoSJnmGlPaVQDqacx_2XlXEhhqtWceVopjomc2PJLtdAiAUTeGPoNYxZw0z8mgOnnIcjoxRuNDVZvybRZF3wR1l8W",
- "ES256",
- map[string]interface{}{"foo": "bar"},
- false,
- },
-}
-
-func TestECDSAVerify(t *testing.T) {
- for _, data := range ecdsaTestData {
- var err error
-
- key, _ := ioutil.ReadFile(data.keys["public"])
-
- var ecdsaKey *ecdsa.PublicKey
- if ecdsaKey, err = jwt.ParseECPublicKeyFromPEM(key); err != nil {
- t.Errorf("Unable to parse ECDSA public key: %v", err)
- }
-
- parts := strings.Split(data.tokenString, ".")
-
- method := jwt.GetSigningMethod(data.alg)
- err = method.Verify(strings.Join(parts[0:2], "."), parts[2], ecdsaKey)
- if data.valid && err != nil {
- t.Errorf("[%v] Error while verifying key: %v", data.name, err)
- }
- if !data.valid && err == nil {
- t.Errorf("[%v] Invalid key passed validation", data.name)
- }
- }
-}
-
-func TestECDSASign(t *testing.T) {
- for _, data := range ecdsaTestData {
- var err error
- key, _ := ioutil.ReadFile(data.keys["private"])
-
- var ecdsaKey *ecdsa.PrivateKey
- if ecdsaKey, err = jwt.ParseECPrivateKeyFromPEM(key); err != nil {
- t.Errorf("Unable to parse ECDSA private key: %v", err)
- }
-
- if data.valid {
- parts := strings.Split(data.tokenString, ".")
- method := jwt.GetSigningMethod(data.alg)
- sig, err := method.Sign(strings.Join(parts[0:2], "."), ecdsaKey)
- if err != nil {
- t.Errorf("[%v] Error signing token: %v", data.name, err)
- }
- if sig == parts[2] {
- t.Errorf("[%v] Identical signatures\nbefore:\n%v\nafter:\n%v", data.name, parts[2], sig)
- }
- }
- }
-}
diff --git a/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go b/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go
deleted file mode 100644
index d19624b..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go
+++ /dev/null
@@ -1,67 +0,0 @@
-package jwt
-
-import (
- "crypto/ecdsa"
- "crypto/x509"
- "encoding/pem"
- "errors"
-)
-
-var (
- ErrNotECPublicKey = errors.New("Key is not a valid ECDSA public key")
- ErrNotECPrivateKey = errors.New("Key is not a valid ECDSA private key")
-)
-
-// Parse PEM encoded Elliptic Curve Private Key Structure
-func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) {
- var err error
-
- // Parse PEM block
- var block *pem.Block
- if block, _ = pem.Decode(key); block == nil {
- return nil, ErrKeyMustBePEMEncoded
- }
-
- // Parse the key
- var parsedKey interface{}
- if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil {
- return nil, err
- }
-
- var pkey *ecdsa.PrivateKey
- var ok bool
- if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok {
- return nil, ErrNotECPrivateKey
- }
-
- return pkey, nil
-}
-
-// Parse PEM encoded PKCS1 or PKCS8 public key
-func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) {
- var err error
-
- // Parse PEM block
- var block *pem.Block
- if block, _ = pem.Decode(key); block == nil {
- return nil, ErrKeyMustBePEMEncoded
- }
-
- // Parse the key
- var parsedKey interface{}
- if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
- if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
- parsedKey = cert.PublicKey
- } else {
- return nil, err
- }
- }
-
- var pkey *ecdsa.PublicKey
- var ok bool
- if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok {
- return nil, ErrNotECPublicKey
- }
-
- return pkey, nil
-}
diff --git a/vendor/github.com/dgrijalva/jwt-go/errors.go b/vendor/github.com/dgrijalva/jwt-go/errors.go
deleted file mode 100644
index 1c93024..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/errors.go
+++ /dev/null
@@ -1,59 +0,0 @@
-package jwt
-
-import (
- "errors"
-)
-
-// Error constants
-var (
- ErrInvalidKey = errors.New("key is invalid")
- ErrInvalidKeyType = errors.New("key is of invalid type")
- ErrHashUnavailable = errors.New("the requested hash function is unavailable")
-)
-
-// The errors that might occur when parsing and validating a token
-const (
- ValidationErrorMalformed uint32 = 1 << iota // Token is malformed
- ValidationErrorUnverifiable // Token could not be verified because of signing problems
- ValidationErrorSignatureInvalid // Signature validation failed
-
- // Standard Claim validation errors
- ValidationErrorAudience // AUD validation failed
- ValidationErrorExpired // EXP validation failed
- ValidationErrorIssuedAt // IAT validation failed
- ValidationErrorIssuer // ISS validation failed
- ValidationErrorNotValidYet // NBF validation failed
- ValidationErrorId // JTI validation failed
- ValidationErrorClaimsInvalid // Generic claims validation error
-)
-
-// Helper for constructing a ValidationError with a string error message
-func NewValidationError(errorText string, errorFlags uint32) *ValidationError {
- return &ValidationError{
- text: errorText,
- Errors: errorFlags,
- }
-}
-
-// The error from Parse if token is not valid
-type ValidationError struct {
- Inner error // stores the error returned by external dependencies, i.e.: KeyFunc
- Errors uint32 // bitfield. see ValidationError... constants
- text string // errors that do not have a valid error just have text
-}
-
-// Validation error is an error type
-func (e ValidationError) Error() string {
- if e.Inner != nil {
- return e.Inner.Error()
- } else if e.text != "" {
- return e.text
- } else {
- return "token is invalid"
- }
-}
-
-// No errors
-func (e *ValidationError) valid() bool {
- return e.Errors == 0
-}
diff --git a/vendor/github.com/dgrijalva/jwt-go/example_test.go b/vendor/github.com/dgrijalva/jwt-go/example_test.go
deleted file mode 100644
index ae8b788..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/example_test.go
+++ /dev/null
@@ -1,114 +0,0 @@
-package jwt_test
-
-import (
- "fmt"
- "github.com/dgrijalva/jwt-go"
- "time"
-)
-
-// Example (atypical) using the StandardClaims type by itself to parse a token.
-// The StandardClaims type is designed to be embedded into your custom types
-// to provide standard validation features. You can use it alone, but there's
-// no way to retrieve other fields after parsing.
-// See the CustomClaimsType example for intended usage.
-func ExampleNewWithClaims_standardClaims() {
- mySigningKey := []byte("AllYourBase")
-
- // Create the Claims
- claims := &jwt.StandardClaims{
- ExpiresAt: 15000,
- Issuer: "test",
- }
-
- token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
- ss, err := token.SignedString(mySigningKey)
- fmt.Printf("%v %v", ss, err)
- //Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.QsODzZu3lUZMVdhbO76u3Jv02iYCvEHcYVUI1kOWEU0
-}
-
-// Example creating a token using a custom claims type. The StandardClaim is embedded
-// in the custom type to allow for easy encoding, parsing and validation of standard claims.
-func ExampleNewWithClaims_customClaimsType() {
- mySigningKey := []byte("AllYourBase")
-
- type MyCustomClaims struct {
- Foo string `json:"foo"`
- jwt.StandardClaims
- }
-
- // Create the Claims
- claims := MyCustomClaims{
- "bar",
- jwt.StandardClaims{
- ExpiresAt: 15000,
- Issuer: "test",
- },
- }
-
- token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
- ss, err := token.SignedString(mySigningKey)
- fmt.Printf("%v %v", ss, err)
- //Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c
-}
-
-// Example creating a token using a custom claims type. The StandardClaim is embedded
-// in the custom type to allow for easy encoding, parsing and validation of standard claims.
-func ExampleParseWithClaims_customClaimsType() {
- tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"
-
- type MyCustomClaims struct {
- Foo string `json:"foo"`
- jwt.StandardClaims
- }
-
- // sample token is expired. override time so it parses as valid
- at(time.Unix(0, 0), func() {
- token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
- return []byte("AllYourBase"), nil
- })
-
- if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
- fmt.Printf("%v %v", claims.Foo, claims.StandardClaims.ExpiresAt)
- } else {
- fmt.Println(err)
- }
- })
-
- // Output: bar 15000
-}
-
-// Override time value for tests. Restore default value after.
-func at(t time.Time, f func()) {
- jwt.TimeFunc = func() time.Time {
- return t
- }
- f()
- jwt.TimeFunc = time.Now
-}
-
-// An example of parsing the error types using bitfield checks
-func ExampleParse_errorChecking() {
- // Token from another example. This token is expired
- var tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"
-
- token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
- return []byte("AllYourBase"), nil
- })
-
- if token.Valid {
- fmt.Println("You look nice today")
- } else if ve, ok := err.(*jwt.ValidationError); ok {
- if ve.Errors&jwt.ValidationErrorMalformed != 0 {
- fmt.Println("That's not even a token")
- } else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
- // Token is either expired or not active yet
- fmt.Println("Timing is everything")
- } else {
- fmt.Println("Couldn't handle this token:", err)
- }
- } else {
- fmt.Println("Couldn't handle this token:", err)
- }
-
- // Output: Timing is everything
-}
diff --git a/vendor/github.com/dgrijalva/jwt-go/hmac.go b/vendor/github.com/dgrijalva/jwt-go/hmac.go
deleted file mode 100644
index c229919..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/hmac.go
+++ /dev/null
@@ -1,94 +0,0 @@
-package jwt
-
-import (
- "crypto"
- "crypto/hmac"
- "errors"
-)
-
-// Implements the HMAC-SHA family of signing methods signing methods
-type SigningMethodHMAC struct {
- Name string
- Hash crypto.Hash
-}
-
-// Specific instances for HS256 and company
-var (
- SigningMethodHS256 *SigningMethodHMAC
- SigningMethodHS384 *SigningMethodHMAC
- SigningMethodHS512 *SigningMethodHMAC
- ErrSignatureInvalid = errors.New("signature is invalid")
-)
-
-func init() {
- // HS256
- SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256}
- RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod {
- return SigningMethodHS256
- })
-
- // HS384
- SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384}
- RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod {
- return SigningMethodHS384
- })
-
- // HS512
- SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512}
- RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod {
- return SigningMethodHS512
- })
-}
-
-func (m *SigningMethodHMAC) Alg() string {
- return m.Name
-}
-
-// Verify the signature of HSXXX tokens. Returns nil if the signature is valid.
-func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error {
- // Verify the key is the right type
- keyBytes, ok := key.([]byte)
- if !ok {
- return ErrInvalidKeyType
- }
-
- // Decode signature, for comparison
- sig, err := DecodeSegment(signature)
- if err != nil {
- return err
- }
-
- // Can we use the specified hashing method?
- if !m.Hash.Available() {
- return ErrHashUnavailable
- }
-
- // This signing method is symmetric, so we validate the signature
- // by reproducing the signature from the signing string and key, then
- // comparing that against the provided signature.
- hasher := hmac.New(m.Hash.New, keyBytes)
- hasher.Write([]byte(signingString))
- if !hmac.Equal(sig, hasher.Sum(nil)) {
- return ErrSignatureInvalid
- }
-
- // No validation errors. Signature is good.
- return nil
-}
-
-// Implements the Sign method from SigningMethod for this signing method.
-// Key must be []byte
-func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error) {
- if keyBytes, ok := key.([]byte); ok {
- if !m.Hash.Available() {
- return "", ErrHashUnavailable
- }
-
- hasher := hmac.New(m.Hash.New, keyBytes)
- hasher.Write([]byte(signingString))
-
- return EncodeSegment(hasher.Sum(nil)), nil
- }
-
- return "", ErrInvalidKey
-}
diff --git a/vendor/github.com/dgrijalva/jwt-go/hmac_example_test.go b/vendor/github.com/dgrijalva/jwt-go/hmac_example_test.go
deleted file mode 100644
index 0027831..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/hmac_example_test.go
+++ /dev/null
@@ -1,66 +0,0 @@
-package jwt_test
-
-import (
- "fmt"
- "github.com/dgrijalva/jwt-go"
- "io/ioutil"
- "time"
-)
-
-// For HMAC signing method, the key can be any []byte. It is recommended to generate
-// a key using crypto/rand or something equivalent. You need the same key for signing
-// and validating.
-var hmacSampleSecret []byte
-
-func init() {
- // Load sample key data
- if keyData, e := ioutil.ReadFile("test/hmacTestKey"); e == nil {
- hmacSampleSecret = keyData
- } else {
- panic(e)
- }
-}
-
-// Example creating, signing, and encoding a JWT token using the HMAC signing method
-func ExampleNew_hmac() {
- // Create a new token object, specifying signing method and the claims
- // you would like it to contain.
- token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
- "foo": "bar",
- "nbf": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(),
- })
-
- // Sign and get the complete encoded token as a string using the secret
- tokenString, err := token.SignedString(hmacSampleSecret)
-
- fmt.Println(tokenString, err)
- // Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU
-}
-
-// Example parsing and validating a token using the HMAC signing method
-func ExampleParse_hmac() {
- // sample token string taken from the New example
- tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU"
-
- // Parse takes the token string and a function for looking up the key. The latter is especially
- // useful if you use multiple keys for your application. The standard is to use 'kid' in the
- // head of the token to identify which key to use, but the parsed token (head and claims) is provided
- // to the callback, providing flexibility.
- token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
- // Don't forget to validate the alg is what you expect:
- if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
- return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
- }
-
- // hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
- return hmacSampleSecret, nil
- })
-
- if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
- fmt.Println(claims["foo"], claims["nbf"])
- } else {
- fmt.Println(err)
- }
-
- // Output: bar 1.4444784e+09
-}
diff --git a/vendor/github.com/dgrijalva/jwt-go/hmac_test.go b/vendor/github.com/dgrijalva/jwt-go/hmac_test.go
deleted file mode 100644
index c7e114f..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/hmac_test.go
+++ /dev/null
@@ -1,91 +0,0 @@
-package jwt_test
-
-import (
- "github.com/dgrijalva/jwt-go"
- "io/ioutil"
- "strings"
- "testing"
-)
-
-var hmacTestData = []struct {
- name string
- tokenString string
- alg string
- claims map[string]interface{}
- valid bool
-}{
- {
- "web sample",
- "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk",
- "HS256",
- map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true},
- true,
- },
- {
- "HS384",
- "eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9.eyJleHAiOjEuMzAwODE5MzhlKzA5LCJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZSwiaXNzIjoiam9lIn0.KWZEuOD5lbBxZ34g7F-SlVLAQ_r5KApWNWlZIIMyQVz5Zs58a7XdNzj5_0EcNoOy",
- "HS384",
- map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true},
- true,
- },
- {
- "HS512",
- "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjEuMzAwODE5MzhlKzA5LCJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZSwiaXNzIjoiam9lIn0.CN7YijRX6Aw1n2jyI2Id1w90ja-DEMYiWixhYCyHnrZ1VfJRaFQz1bEbjjA5Fn4CLYaUG432dEYmSbS4Saokmw",
- "HS512",
- map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true},
- true,
- },
- {
- "web sample: invalid",
- "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXo",
- "HS256",
- map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true},
- false,
- },
-}
-
-// Sample data from http://tools.ietf.org/html/draft-jones-json-web-signature-04#appendix-A.1
-var hmacTestKey, _ = ioutil.ReadFile("test/hmacTestKey")
-
-func TestHMACVerify(t *testing.T) {
- for _, data := range hmacTestData {
- parts := strings.Split(data.tokenString, ".")
-
- method := jwt.GetSigningMethod(data.alg)
- err := method.Verify(strings.Join(parts[0:2], "."), parts[2], hmacTestKey)
- if data.valid && err != nil {
- t.Errorf("[%v] Error while verifying key: %v", data.name, err)
- }
- if !data.valid && err == nil {
- t.Errorf("[%v] Invalid key passed validation", data.name)
- }
- }
-}
-
-func TestHMACSign(t *testing.T) {
- for _, data := range hmacTestData {
- if data.valid {
- parts := strings.Split(data.tokenString, ".")
- method := jwt.GetSigningMethod(data.alg)
- sig, err := method.Sign(strings.Join(parts[0:2], "."), hmacTestKey)
- if err != nil {
- t.Errorf("[%v] Error signing token: %v", data.name, err)
- }
- if sig != parts[2] {
- t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", data.name, sig, parts[2])
- }
- }
- }
-}
-
-func BenchmarkHS256Signing(b *testing.B) {
- benchmarkSigning(b, jwt.SigningMethodHS256, hmacTestKey)
-}
-
-func BenchmarkHS384Signing(b *testing.B) {
- benchmarkSigning(b, jwt.SigningMethodHS384, hmacTestKey)
-}
-
-func BenchmarkHS512Signing(b *testing.B) {
- benchmarkSigning(b, jwt.SigningMethodHS512, hmacTestKey)
-}
diff --git a/vendor/github.com/dgrijalva/jwt-go/http_example_test.go b/vendor/github.com/dgrijalva/jwt-go/http_example_test.go
deleted file mode 100644
index 82e9c50..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/http_example_test.go
+++ /dev/null
@@ -1,216 +0,0 @@
-package jwt_test
-
-// Example HTTP auth using asymmetric crypto/RSA keys
-// This is based on a (now outdated) example at https://gist.github.com/cryptix/45c33ecf0ae54828e63b
-
-import (
- "bytes"
- "crypto/rsa"
- "fmt"
- "github.com/dgrijalva/jwt-go"
- "github.com/dgrijalva/jwt-go/request"
- "io"
- "io/ioutil"
- "log"
- "net"
- "net/http"
- "net/url"
- "strings"
- "time"
-)
-
-// location of the files used for signing and verification
-const (
- privKeyPath = "test/sample_key" // openssl genrsa -out app.rsa keysize
- pubKeyPath = "test/sample_key.pub" // openssl rsa -in app.rsa -pubout > app.rsa.pub
-)
-
-var (
- verifyKey *rsa.PublicKey
- signKey *rsa.PrivateKey
- serverPort int
- // storing sample username/password pairs
- // don't do this on a real server
- users = map[string]string{
- "test": "known",
- }
-)
-
-// read the key files before starting http handlers
-func init() {
- signBytes, err := ioutil.ReadFile(privKeyPath)
- fatal(err)
-
- signKey, err = jwt.ParseRSAPrivateKeyFromPEM(signBytes)
- fatal(err)
-
- verifyBytes, err := ioutil.ReadFile(pubKeyPath)
- fatal(err)
-
- verifyKey, err = jwt.ParseRSAPublicKeyFromPEM(verifyBytes)
- fatal(err)
-
- http.HandleFunc("/authenticate", authHandler)
- http.HandleFunc("/restricted", restrictedHandler)
-
- // Setup listener
- listener, err := net.ListenTCP("tcp", &net.TCPAddr{})
- serverPort = listener.Addr().(*net.TCPAddr).Port
-
- log.Println("Listening...")
- go func() {
- fatal(http.Serve(listener, nil))
- }()
-}
-
-var start func()
-
-func fatal(err error) {
- if err != nil {
- log.Fatal(err)
- }
-}
-
-// Define some custom types were going to use within our tokens
-type CustomerInfo struct {
- Name string
- Kind string
-}
-
-type CustomClaimsExample struct {
- *jwt.StandardClaims
- TokenType string
- CustomerInfo
-}
-
-func Example_getTokenViaHTTP() {
- // See func authHandler for an example auth handler that produces a token
- res, err := http.PostForm(fmt.Sprintf("http://localhost:%v/authenticate", serverPort), url.Values{
- "user": {"test"},
- "pass": {"known"},
- })
- if err != nil {
- fatal(err)
- }
-
- if res.StatusCode != 200 {
- fmt.Println("Unexpected status code", res.StatusCode)
- }
-
- // Read the token out of the response body
- buf := new(bytes.Buffer)
- io.Copy(buf, res.Body)
- res.Body.Close()
- tokenString := strings.TrimSpace(buf.String())
-
- // Parse the token
- token, err := jwt.ParseWithClaims(tokenString, &CustomClaimsExample{}, func(token *jwt.Token) (interface{}, error) {
- // since we only use the one private key to sign the tokens,
- // we also only use its public counter part to verify
- return verifyKey, nil
- })
- fatal(err)
-
- claims := token.Claims.(*CustomClaimsExample)
- fmt.Println(claims.CustomerInfo.Name)
-
- //Output: test
-}
-
-func Example_useTokenViaHTTP() {
-
- // Make a sample token
- // In a real world situation, this token will have been acquired from
- // some other API call (see Example_getTokenViaHTTP)
- token, err := createToken("foo")
- fatal(err)
-
- // Make request. See func restrictedHandler for example request processor
- req, err := http.NewRequest("GET", fmt.Sprintf("http://localhost:%v/restricted", serverPort), nil)
- fatal(err)
- req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", token))
- res, err := http.DefaultClient.Do(req)
- fatal(err)
-
- // Read the response body
- buf := new(bytes.Buffer)
- io.Copy(buf, res.Body)
- res.Body.Close()
- fmt.Println(buf.String())
-
- // Output: Welcome, foo
-}
-
-func createToken(user string) (string, error) {
- // create a signer for rsa 256
- t := jwt.New(jwt.GetSigningMethod("RS256"))
-
- // set our claims
- t.Claims = &CustomClaimsExample{
- &jwt.StandardClaims{
- // set the expire time
- // see http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-20#section-4.1.4
- ExpiresAt: time.Now().Add(time.Minute * 1).Unix(),
- },
- "level1",
- CustomerInfo{user, "human"},
- }
-
- // Creat token string
- return t.SignedString(signKey)
-}
-
-// reads the form values, checks them and creates the token
-func authHandler(w http.ResponseWriter, r *http.Request) {
- // make sure its post
- if r.Method != "POST" {
- w.WriteHeader(http.StatusBadRequest)
- fmt.Fprintln(w, "No POST", r.Method)
- return
- }
-
- user := r.FormValue("user")
- pass := r.FormValue("pass")
-
- log.Printf("Authenticate: user[%s] pass[%s]\n", user, pass)
-
- // check values
- if user != "test" || pass != "known" {
- w.WriteHeader(http.StatusForbidden)
- fmt.Fprintln(w, "Wrong info")
- return
- }
-
- tokenString, err := createToken(user)
- if err != nil {
- w.WriteHeader(http.StatusInternalServerError)
- fmt.Fprintln(w, "Sorry, error while Signing Token!")
- log.Printf("Token Signing error: %v\n", err)
- return
- }
-
- w.Header().Set("Content-Type", "application/jwt")
- w.WriteHeader(http.StatusOK)
- fmt.Fprintln(w, tokenString)
-}
-
-// only accessible with a valid token
-func restrictedHandler(w http.ResponseWriter, r *http.Request) {
- // Get token from request
- token, err := request.ParseFromRequestWithClaims(r, request.OAuth2Extractor, &CustomClaimsExample{}, func(token *jwt.Token) (interface{}, error) {
- // since we only use the one private key to sign the tokens,
- // we also only use its public counter part to verify
- return verifyKey, nil
- })
-
- // If the token is missing or invalid, return error
- if err != nil {
- w.WriteHeader(http.StatusUnauthorized)
- fmt.Fprintln(w, "Invalid token:", err)
- return
- }
-
- // Token is valid
- fmt.Fprintln(w, "Welcome,", token.Claims.(*CustomClaimsExample).Name)
- return
-}
diff --git a/vendor/github.com/dgrijalva/jwt-go/map_claims.go b/vendor/github.com/dgrijalva/jwt-go/map_claims.go
deleted file mode 100644
index 291213c..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/map_claims.go
+++ /dev/null
@@ -1,94 +0,0 @@
-package jwt
-
-import (
- "encoding/json"
- "errors"
- // "fmt"
-)
-
-// Claims type that uses the map[string]interface{} for JSON decoding
-// This is the default claims type if you don't supply one
-type MapClaims map[string]interface{}
-
-// Compares the aud claim against cmp.
-// If required is false, this method will return true if the value matches or is unset
-func (m MapClaims) VerifyAudience(cmp string, req bool) bool {
- aud, _ := m["aud"].(string)
- return verifyAud(aud, cmp, req)
-}
-
-// Compares the exp claim against cmp.
-// If required is false, this method will return true if the value matches or is unset
-func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool {
- switch exp := m["exp"].(type) {
- case float64:
- return verifyExp(int64(exp), cmp, req)
- case json.Number:
- v, _ := exp.Int64()
- return verifyExp(v, cmp, req)
- }
- return req == false
-}
-
-// Compares the iat claim against cmp.
-// If required is false, this method will return true if the value matches or is unset
-func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool {
- switch iat := m["iat"].(type) {
- case float64:
- return verifyIat(int64(iat), cmp, req)
- case json.Number:
- v, _ := iat.Int64()
- return verifyIat(v, cmp, req)
- }
- return req == false
-}
-
-// Compares the iss claim against cmp.
-// If required is false, this method will return true if the value matches or is unset
-func (m MapClaims) VerifyIssuer(cmp string, req bool) bool {
- iss, _ := m["iss"].(string)
- return verifyIss(iss, cmp, req)
-}
-
-// Compares the nbf claim against cmp.
-// If required is false, this method will return true if the value matches or is unset
-func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool {
- switch nbf := m["nbf"].(type) {
- case float64:
- return verifyNbf(int64(nbf), cmp, req)
- case json.Number:
- v, _ := nbf.Int64()
- return verifyNbf(v, cmp, req)
- }
- return req == false
-}
-
-// Validates time based claims "exp, iat, nbf".
-// There is no accounting for clock skew.
-// As well, if any of the above claims are not in the token, it will still
-// be considered a valid claim.
-func (m MapClaims) Valid() error {
- vErr := new(ValidationError)
- now := TimeFunc().Unix()
-
- if m.VerifyExpiresAt(now, false) == false {
- vErr.Inner = errors.New("Token is expired")
- vErr.Errors |= ValidationErrorExpired
- }
-
- if m.VerifyIssuedAt(now, false) == false {
- vErr.Inner = errors.New("Token used before issued")
- vErr.Errors |= ValidationErrorIssuedAt
- }
-
- if m.VerifyNotBefore(now, false) == false {
- vErr.Inner = errors.New("Token is not valid yet")
- vErr.Errors |= ValidationErrorNotValidYet
- }
-
- if vErr.valid() {
- return nil
- }
-
- return vErr
-}
diff --git a/vendor/github.com/dgrijalva/jwt-go/none.go b/vendor/github.com/dgrijalva/jwt-go/none.go
deleted file mode 100644
index f04d189..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/none.go
+++ /dev/null
@@ -1,52 +0,0 @@
-package jwt
-
-// Implements the none signing method. This is required by the spec
-// but you probably should never use it.
-var SigningMethodNone *signingMethodNone
-
-const UnsafeAllowNoneSignatureType unsafeNoneMagicConstant = "none signing method allowed"
-
-var NoneSignatureTypeDisallowedError error
-
-type signingMethodNone struct{}
-type unsafeNoneMagicConstant string
-
-func init() {
- SigningMethodNone = &signingMethodNone{}
- NoneSignatureTypeDisallowedError = NewValidationError("'none' signature type is not allowed", ValidationErrorSignatureInvalid)
-
- RegisterSigningMethod(SigningMethodNone.Alg(), func() SigningMethod {
- return SigningMethodNone
- })
-}
-
-func (m *signingMethodNone) Alg() string {
- return "none"
-}
-
-// Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key
-func (m *signingMethodNone) Verify(signingString, signature string, key interface{}) (err error) {
- // Key must be UnsafeAllowNoneSignatureType to prevent accidentally
- // accepting 'none' signing method
- if _, ok := key.(unsafeNoneMagicConstant); !ok {
- return NoneSignatureTypeDisallowedError
- }
- // If signing method is none, signature must be an empty string
- if signature != "" {
- return NewValidationError(
- "'none' signing method with non-empty signature",
- ValidationErrorSignatureInvalid,
- )
- }
-
- // Accept 'none' signing method.
- return nil
-}
-
-// Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key
-func (m *signingMethodNone) Sign(signingString string, key interface{}) (string, error) {
- if _, ok := key.(unsafeNoneMagicConstant); ok {
- return "", nil
- }
- return "", NoneSignatureTypeDisallowedError
-}
diff --git a/vendor/github.com/dgrijalva/jwt-go/none_test.go b/vendor/github.com/dgrijalva/jwt-go/none_test.go
deleted file mode 100644
index 29a69ef..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/none_test.go
+++ /dev/null
@@ -1,72 +0,0 @@
-package jwt_test
-
-import (
- "github.com/dgrijalva/jwt-go"
- "strings"
- "testing"
-)
-
-var noneTestData = []struct {
- name string
- tokenString string
- alg string
- key interface{}
- claims map[string]interface{}
- valid bool
-}{
- {
- "Basic",
- "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.",
- "none",
- jwt.UnsafeAllowNoneSignatureType,
- map[string]interface{}{"foo": "bar"},
- true,
- },
- {
- "Basic - no key",
- "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.",
- "none",
- nil,
- map[string]interface{}{"foo": "bar"},
- false,
- },
- {
- "Signed",
- "eyJhbGciOiJSUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.W-jEzRfBigtCWsinvVVuldiuilzVdU5ty0MvpLaSaqK9PlAWWlDQ1VIQ_qSKzwL5IXaZkvZFJXT3yL3n7OUVu7zCNJzdwznbC8Z-b0z2lYvcklJYi2VOFRcGbJtXUqgjk2oGsiqUMUMOLP70TTefkpsgqDxbRh9CDUfpOJgW-dU7cmgaoswe3wjUAUi6B6G2YEaiuXC0XScQYSYVKIzgKXJV8Zw-7AN_DBUI4GkTpsvQ9fVVjZM9csQiEXhYekyrKu1nu_POpQonGd8yqkIyXPECNmmqH5jH4sFiF67XhD7_JpkvLziBpI-uh86evBUadmHhb9Otqw3uV3NTaXLzJw",
- "none",
- jwt.UnsafeAllowNoneSignatureType,
- map[string]interface{}{"foo": "bar"},
- false,
- },
-}
-
-func TestNoneVerify(t *testing.T) {
- for _, data := range noneTestData {
- parts := strings.Split(data.tokenString, ".")
-
- method := jwt.GetSigningMethod(data.alg)
- err := method.Verify(strings.Join(parts[0:2], "."), parts[2], data.key)
- if data.valid && err != nil {
- t.Errorf("[%v] Error while verifying key: %v", data.name, err)
- }
- if !data.valid && err == nil {
- t.Errorf("[%v] Invalid key passed validation", data.name)
- }
- }
-}
-
-func TestNoneSign(t *testing.T) {
- for _, data := range noneTestData {
- if data.valid {
- parts := strings.Split(data.tokenString, ".")
- method := jwt.GetSigningMethod(data.alg)
- sig, err := method.Sign(strings.Join(parts[0:2], "."), data.key)
- if err != nil {
- t.Errorf("[%v] Error signing token: %v", data.name, err)
- }
- if sig != parts[2] {
- t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", data.name, sig, parts[2])
- }
- }
- }
-}
diff --git a/vendor/github.com/dgrijalva/jwt-go/parser.go b/vendor/github.com/dgrijalva/jwt-go/parser.go
deleted file mode 100644
index 7bf1c4e..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/parser.go
+++ /dev/null
@@ -1,131 +0,0 @@
-package jwt
-
-import (
- "bytes"
- "encoding/json"
- "fmt"
- "strings"
-)
-
-type Parser struct {
- ValidMethods []string // If populated, only these methods will be considered valid
- UseJSONNumber bool // Use JSON Number format in JSON decoder
- SkipClaimsValidation bool // Skip claims validation during token parsing
-}
-
-// Parse, validate, and return a token.
-// keyFunc will receive the parsed token and should return the key for validating.
-// If everything is kosher, err will be nil
-func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
- return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc)
-}
-
-func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) {
- parts := strings.Split(tokenString, ".")
- if len(parts) != 3 {
- return nil, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed)
- }
-
- var err error
- token := &Token{Raw: tokenString}
-
- // parse Header
- var headerBytes []byte
- if headerBytes, err = DecodeSegment(parts[0]); err != nil {
- if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") {
- return token, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed)
- }
- return token, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
- }
- if err = json.Unmarshal(headerBytes, &token.Header); err != nil {
- return token, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
- }
-
- // parse Claims
- var claimBytes []byte
- token.Claims = claims
-
- if claimBytes, err = DecodeSegment(parts[1]); err != nil {
- return token, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
- }
- dec := json.NewDecoder(bytes.NewBuffer(claimBytes))
- if p.UseJSONNumber {
- dec.UseNumber()
- }
- // JSON Decode. Special case for map type to avoid weird pointer behavior
- if c, ok := token.Claims.(MapClaims); ok {
- err = dec.Decode(&c)
- } else {
- err = dec.Decode(&claims)
- }
- // Handle decode error
- if err != nil {
- return token, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
- }
-
- // Lookup signature method
- if method, ok := token.Header["alg"].(string); ok {
- if token.Method = GetSigningMethod(method); token.Method == nil {
- return token, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable)
- }
- } else {
- return token, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable)
- }
-
- // Verify signing method is in the required set
- if p.ValidMethods != nil {
- var signingMethodValid = false
- var alg = token.Method.Alg()
- for _, m := range p.ValidMethods {
- if m == alg {
- signingMethodValid = true
- break
- }
- }
- if !signingMethodValid {
- // signing method is not in the listed set
- return token, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid)
- }
- }
-
- // Lookup key
- var key interface{}
- if keyFunc == nil {
- // keyFunc was not provided. short circuiting validation
- return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable)
- }
- if key, err = keyFunc(token); err != nil {
- // keyFunc returned an error
- return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable}
- }
-
- vErr := &ValidationError{}
-
- // Validate Claims
- if !p.SkipClaimsValidation {
- if err := token.Claims.Valid(); err != nil {
-
- // If the Claims Valid returned an error, check if it is a validation error,
- // If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set
- if e, ok := err.(*ValidationError); !ok {
- vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid}
- } else {
- vErr = e
- }
- }
- }
-
- // Perform validation
- token.Signature = parts[2]
- if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil {
- vErr.Inner = err
- vErr.Errors |= ValidationErrorSignatureInvalid
- }
-
- if vErr.valid() {
- token.Valid = true
- return token, nil
- }
-
- return token, vErr
-}
diff --git a/vendor/github.com/dgrijalva/jwt-go/parser_test.go b/vendor/github.com/dgrijalva/jwt-go/parser_test.go
deleted file mode 100644
index f8ad6f9..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/parser_test.go
+++ /dev/null
@@ -1,261 +0,0 @@
-package jwt_test
-
-import (
- "crypto/rsa"
- "encoding/json"
- "fmt"
- "reflect"
- "testing"
- "time"
-
- "github.com/dgrijalva/jwt-go"
- "github.com/dgrijalva/jwt-go/test"
-)
-
-var keyFuncError error = fmt.Errorf("error loading key")
-
-var (
- jwtTestDefaultKey *rsa.PublicKey
- defaultKeyFunc jwt.Keyfunc = func(t *jwt.Token) (interface{}, error) { return jwtTestDefaultKey, nil }
- emptyKeyFunc jwt.Keyfunc = func(t *jwt.Token) (interface{}, error) { return nil, nil }
- errorKeyFunc jwt.Keyfunc = func(t *jwt.Token) (interface{}, error) { return nil, keyFuncError }
- nilKeyFunc jwt.Keyfunc = nil
-)
-
-func init() {
- jwtTestDefaultKey = test.LoadRSAPublicKeyFromDisk("test/sample_key.pub")
-}
-
-var jwtTestData = []struct {
- name string
- tokenString string
- keyfunc jwt.Keyfunc
- claims jwt.Claims
- valid bool
- errors uint32
- parser *jwt.Parser
-}{
- {
- "basic",
- "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
- defaultKeyFunc,
- jwt.MapClaims{"foo": "bar"},
- true,
- 0,
- nil,
- },
- {
- "basic expired",
- "", // autogen
- defaultKeyFunc,
- jwt.MapClaims{"foo": "bar", "exp": float64(time.Now().Unix() - 100)},
- false,
- jwt.ValidationErrorExpired,
- nil,
- },
- {
- "basic nbf",
- "", // autogen
- defaultKeyFunc,
- jwt.MapClaims{"foo": "bar", "nbf": float64(time.Now().Unix() + 100)},
- false,
- jwt.ValidationErrorNotValidYet,
- nil,
- },
- {
- "expired and nbf",
- "", // autogen
- defaultKeyFunc,
- jwt.MapClaims{"foo": "bar", "nbf": float64(time.Now().Unix() + 100), "exp": float64(time.Now().Unix() - 100)},
- false,
- jwt.ValidationErrorNotValidYet | jwt.ValidationErrorExpired,
- nil,
- },
- {
- "basic invalid",
- "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.EhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
- defaultKeyFunc,
- jwt.MapClaims{"foo": "bar"},
- false,
- jwt.ValidationErrorSignatureInvalid,
- nil,
- },
- {
- "basic nokeyfunc",
- "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
- nilKeyFunc,
- jwt.MapClaims{"foo": "bar"},
- false,
- jwt.ValidationErrorUnverifiable,
- nil,
- },
- {
- "basic nokey",
- "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
- emptyKeyFunc,
- jwt.MapClaims{"foo": "bar"},
- false,
- jwt.ValidationErrorSignatureInvalid,
- nil,
- },
- {
- "basic errorkey",
- "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
- errorKeyFunc,
- jwt.MapClaims{"foo": "bar"},
- false,
- jwt.ValidationErrorUnverifiable,
- nil,
- },
- {
- "invalid signing method",
- "",
- defaultKeyFunc,
- jwt.MapClaims{"foo": "bar"},
- false,
- jwt.ValidationErrorSignatureInvalid,
- &jwt.Parser{ValidMethods: []string{"HS256"}},
- },
- {
- "valid signing method",
- "",
- defaultKeyFunc,
- jwt.MapClaims{"foo": "bar"},
- true,
- 0,
- &jwt.Parser{ValidMethods: []string{"RS256", "HS256"}},
- },
- {
- "JSON Number",
- "",
- defaultKeyFunc,
- jwt.MapClaims{"foo": json.Number("123.4")},
- true,
- 0,
- &jwt.Parser{UseJSONNumber: true},
- },
- {
- "Standard Claims",
- "",
- defaultKeyFunc,
- &jwt.StandardClaims{
- ExpiresAt: time.Now().Add(time.Second * 10).Unix(),
- },
- true,
- 0,
- &jwt.Parser{UseJSONNumber: true},
- },
- {
- "JSON Number - basic expired",
- "", // autogen
- defaultKeyFunc,
- jwt.MapClaims{"foo": "bar", "exp": json.Number(fmt.Sprintf("%v", time.Now().Unix()-100))},
- false,
- jwt.ValidationErrorExpired,
- &jwt.Parser{UseJSONNumber: true},
- },
- {
- "JSON Number - basic nbf",
- "", // autogen
- defaultKeyFunc,
- jwt.MapClaims{"foo": "bar", "nbf": json.Number(fmt.Sprintf("%v", time.Now().Unix()+100))},
- false,
- jwt.ValidationErrorNotValidYet,
- &jwt.Parser{UseJSONNumber: true},
- },
- {
- "JSON Number - expired and nbf",
- "", // autogen
- defaultKeyFunc,
- jwt.MapClaims{"foo": "bar", "nbf": json.Number(fmt.Sprintf("%v", time.Now().Unix()+100)), "exp": json.Number(fmt.Sprintf("%v", time.Now().Unix()-100))},
- false,
- jwt.ValidationErrorNotValidYet | jwt.ValidationErrorExpired,
- &jwt.Parser{UseJSONNumber: true},
- },
- {
- "SkipClaimsValidation during token parsing",
- "", // autogen
- defaultKeyFunc,
- jwt.MapClaims{"foo": "bar", "nbf": json.Number(fmt.Sprintf("%v", time.Now().Unix()+100))},
- true,
- 0,
- &jwt.Parser{UseJSONNumber: true, SkipClaimsValidation: true},
- },
-}
-
-func TestParser_Parse(t *testing.T) {
- privateKey := test.LoadRSAPrivateKeyFromDisk("test/sample_key")
-
- // Iterate over test data set and run tests
- for _, data := range jwtTestData {
- // If the token string is blank, use helper function to generate string
- if data.tokenString == "" {
- data.tokenString = test.MakeSampleToken(data.claims, privateKey)
- }
-
- // Parse the token
- var token *jwt.Token
- var err error
- var parser = data.parser
- if parser == nil {
- parser = new(jwt.Parser)
- }
- // Figure out correct claims type
- switch data.claims.(type) {
- case jwt.MapClaims:
- token, err = parser.ParseWithClaims(data.tokenString, jwt.MapClaims{}, data.keyfunc)
- case *jwt.StandardClaims:
- token, err = parser.ParseWithClaims(data.tokenString, &jwt.StandardClaims{}, data.keyfunc)
- }
-
- // Verify result matches expectation
- if !reflect.DeepEqual(data.claims, token.Claims) {
- t.Errorf("[%v] Claims mismatch. Expecting: %v Got: %v", data.name, data.claims, token.Claims)
- }
-
- if data.valid && err != nil {
- t.Errorf("[%v] Error while verifying token: %T:%v", data.name, err, err)
- }
-
- if !data.valid && err == nil {
- t.Errorf("[%v] Invalid token passed validation", data.name)
- }
-
- if (err == nil && !token.Valid) || (err != nil && token.Valid) {
- t.Errorf("[%v] Inconsistent behavior between returned error and token.Valid", data.name)
- }
-
- if data.errors != 0 {
- if err == nil {
- t.Errorf("[%v] Expecting error. Didn't get one.", data.name)
- } else {
-
- ve := err.(*jwt.ValidationError)
- // compare the bitfield part of the error
- if e := ve.Errors; e != data.errors {
- t.Errorf("[%v] Errors don't match expectation. %v != %v", data.name, e, data.errors)
- }
-
- if err.Error() == keyFuncError.Error() && ve.Inner != keyFuncError {
- t.Errorf("[%v] Inner error does not match expectation. %v != %v", data.name, ve.Inner, keyFuncError)
- }
- }
- }
- if data.valid && token.Signature == "" {
- t.Errorf("[%v] Signature is left unpopulated after parsing", data.name)
- }
- }
-}
-
-// Helper method for benchmarking various methods
-func benchmarkSigning(b *testing.B, method jwt.SigningMethod, key interface{}) {
- t := jwt.New(method)
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- if _, err := t.SignedString(key); err != nil {
- b.Fatal(err)
- }
- }
- })
-
-}
diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa.go b/vendor/github.com/dgrijalva/jwt-go/rsa.go
deleted file mode 100644
index 0ae0b19..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/rsa.go
+++ /dev/null
@@ -1,100 +0,0 @@
-package jwt
-
-import (
- "crypto"
- "crypto/rand"
- "crypto/rsa"
-)
-
-// Implements the RSA family of signing methods signing methods
-type SigningMethodRSA struct {
- Name string
- Hash crypto.Hash
-}
-
-// Specific instances for RS256 and company
-var (
- SigningMethodRS256 *SigningMethodRSA
- SigningMethodRS384 *SigningMethodRSA
- SigningMethodRS512 *SigningMethodRSA
-)
-
-func init() {
- // RS256
- SigningMethodRS256 = &SigningMethodRSA{"RS256", crypto.SHA256}
- RegisterSigningMethod(SigningMethodRS256.Alg(), func() SigningMethod {
- return SigningMethodRS256
- })
-
- // RS384
- SigningMethodRS384 = &SigningMethodRSA{"RS384", crypto.SHA384}
- RegisterSigningMethod(SigningMethodRS384.Alg(), func() SigningMethod {
- return SigningMethodRS384
- })
-
- // RS512
- SigningMethodRS512 = &SigningMethodRSA{"RS512", crypto.SHA512}
- RegisterSigningMethod(SigningMethodRS512.Alg(), func() SigningMethod {
- return SigningMethodRS512
- })
-}
-
-func (m *SigningMethodRSA) Alg() string {
- return m.Name
-}
-
-// Implements the Verify method from SigningMethod
-// For this signing method, must be an rsa.PublicKey structure.
-func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error {
- var err error
-
- // Decode the signature
- var sig []byte
- if sig, err = DecodeSegment(signature); err != nil {
- return err
- }
-
- var rsaKey *rsa.PublicKey
- var ok bool
-
- if rsaKey, ok = key.(*rsa.PublicKey); !ok {
- return ErrInvalidKeyType
- }
-
- // Create hasher
- if !m.Hash.Available() {
- return ErrHashUnavailable
- }
- hasher := m.Hash.New()
- hasher.Write([]byte(signingString))
-
- // Verify the signature
- return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig)
-}
-
-// Implements the Sign method from SigningMethod
-// For this signing method, must be an rsa.PrivateKey structure.
-func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) {
- var rsaKey *rsa.PrivateKey
- var ok bool
-
- // Validate type of key
- if rsaKey, ok = key.(*rsa.PrivateKey); !ok {
- return "", ErrInvalidKey
- }
-
- // Create the hasher
- if !m.Hash.Available() {
- return "", ErrHashUnavailable
- }
-
- hasher := m.Hash.New()
- hasher.Write([]byte(signingString))
-
- // Sign the string and return the encoded bytes
- if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil {
- return EncodeSegment(sigBytes), nil
- } else {
- return "", err
- }
-}
diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go b/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go
deleted file mode 100644
index 10ee9db..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go
+++ /dev/null
@@ -1,126 +0,0 @@
-// +build go1.4
-
-package jwt
-
-import (
- "crypto"
- "crypto/rand"
- "crypto/rsa"
-)
-
-// Implements the RSAPSS family of signing methods signing methods
-type SigningMethodRSAPSS struct {
- *SigningMethodRSA
- Options *rsa.PSSOptions
-}
-
-// Specific instances for RS/PS and company
-var (
- SigningMethodPS256 *SigningMethodRSAPSS
- SigningMethodPS384 *SigningMethodRSAPSS
- SigningMethodPS512 *SigningMethodRSAPSS
-)
-
-func init() {
- // PS256
- SigningMethodPS256 = &SigningMethodRSAPSS{
- &SigningMethodRSA{
- Name: "PS256",
- Hash: crypto.SHA256,
- },
- &rsa.PSSOptions{
- SaltLength: rsa.PSSSaltLengthAuto,
- Hash: crypto.SHA256,
- },
- }
- RegisterSigningMethod(SigningMethodPS256.Alg(), func() SigningMethod {
- return SigningMethodPS256
- })
-
- // PS384
- SigningMethodPS384 = &SigningMethodRSAPSS{
- &SigningMethodRSA{
- Name: "PS384",
- Hash: crypto.SHA384,
- },
- &rsa.PSSOptions{
- SaltLength: rsa.PSSSaltLengthAuto,
- Hash: crypto.SHA384,
- },
- }
- RegisterSigningMethod(SigningMethodPS384.Alg(), func() SigningMethod {
- return SigningMethodPS384
- })
-
- // PS512
- SigningMethodPS512 = &SigningMethodRSAPSS{
- &SigningMethodRSA{
- Name: "PS512",
- Hash: crypto.SHA512,
- },
- &rsa.PSSOptions{
- SaltLength: rsa.PSSSaltLengthAuto,
- Hash: crypto.SHA512,
- },
- }
- RegisterSigningMethod(SigningMethodPS512.Alg(), func() SigningMethod {
- return SigningMethodPS512
- })
-}
-
-// Implements the Verify method from SigningMethod
-// For this verify method, key must be an rsa.PublicKey struct
-func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interface{}) error {
- var err error
-
- // Decode the signature
- var sig []byte
- if sig, err = DecodeSegment(signature); err != nil {
- return err
- }
-
- var rsaKey *rsa.PublicKey
- switch k := key.(type) {
- case *rsa.PublicKey:
- rsaKey = k
- default:
- return ErrInvalidKey
- }
-
- // Create hasher
- if !m.Hash.Available() {
- return ErrHashUnavailable
- }
- hasher := m.Hash.New()
- hasher.Write([]byte(signingString))
-
- return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, m.Options)
-}
-
-// Implements the Sign method from SigningMethod
-// For this signing method, key must be an rsa.PrivateKey struct
-func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (string, error) {
- var rsaKey *rsa.PrivateKey
-
- switch k := key.(type) {
- case *rsa.PrivateKey:
- rsaKey = k
- default:
- return "", ErrInvalidKeyType
- }
-
- // Create the hasher
- if !m.Hash.Available() {
- return "", ErrHashUnavailable
- }
-
- hasher := m.Hash.New()
- hasher.Write([]byte(signingString))
-
- // Sign the string and return the encoded bytes
- if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil {
- return EncodeSegment(sigBytes), nil
- } else {
- return "", err
- }
-}
diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa_pss_test.go b/vendor/github.com/dgrijalva/jwt-go/rsa_pss_test.go
deleted file mode 100644
index 9045aaf..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/rsa_pss_test.go
+++ /dev/null
@@ -1,96 +0,0 @@
-// +build go1.4
-
-package jwt_test
-
-import (
- "crypto/rsa"
- "io/ioutil"
- "strings"
- "testing"
-
- "github.com/dgrijalva/jwt-go"
-)
-
-var rsaPSSTestData = []struct {
- name string
- tokenString string
- alg string
- claims map[string]interface{}
- valid bool
-}{
- {
- "Basic PS256",
- "eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.PPG4xyDVY8ffp4CcxofNmsTDXsrVG2npdQuibLhJbv4ClyPTUtR5giNSvuxo03kB6I8VXVr0Y9X7UxhJVEoJOmULAwRWaUsDnIewQa101cVhMa6iR8X37kfFoiZ6NkS-c7henVkkQWu2HtotkEtQvN5hFlk8IevXXPmvZlhQhwzB1sGzGYnoi1zOfuL98d3BIjUjtlwii5w6gYG2AEEzp7HnHCsb3jIwUPdq86Oe6hIFjtBwduIK90ca4UqzARpcfwxHwVLMpatKask00AgGVI0ysdk0BLMjmLutquD03XbThHScC2C2_Pp4cHWgMzvbgLU2RYYZcZRKr46QeNgz9w",
- "PS256",
- map[string]interface{}{"foo": "bar"},
- true,
- },
- {
- "Basic PS384",
- "eyJhbGciOiJQUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.w7-qqgj97gK4fJsq_DCqdYQiylJjzWONvD0qWWWhqEOFk2P1eDULPnqHRnjgTXoO4HAw4YIWCsZPet7nR3Xxq4ZhMqvKW8b7KlfRTb9cH8zqFvzMmybQ4jv2hKc3bXYqVow3AoR7hN_CWXI3Dv6Kd2X5xhtxRHI6IL39oTVDUQ74LACe-9t4c3QRPuj6Pq1H4FAT2E2kW_0KOc6EQhCLWEhm2Z2__OZskDC8AiPpP8Kv4k2vB7l0IKQu8Pr4RcNBlqJdq8dA5D3hk5TLxP8V5nG1Ib80MOMMqoS3FQvSLyolFX-R_jZ3-zfq6Ebsqr0yEb0AH2CfsECF7935Pa0FKQ",
- "PS384",
- map[string]interface{}{"foo": "bar"},
- true,
- },
- {
- "Basic PS512",
- "eyJhbGciOiJQUzUxMiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.GX1HWGzFaJevuSLavqqFYaW8_TpvcjQ8KfC5fXiSDzSiT9UD9nB_ikSmDNyDILNdtjZLSvVKfXxZJqCfefxAtiozEDDdJthZ-F0uO4SPFHlGiXszvKeodh7BuTWRI2wL9-ZO4mFa8nq3GMeQAfo9cx11i7nfN8n2YNQ9SHGovG7_T_AvaMZB_jT6jkDHpwGR9mz7x1sycckEo6teLdHRnH_ZdlHlxqknmyTu8Odr5Xh0sJFOL8BepWbbvIIn-P161rRHHiDWFv6nhlHwZnVzjx7HQrWSGb6-s2cdLie9QL_8XaMcUpjLkfOMKkDOfHo6AvpL7Jbwi83Z2ZTHjJWB-A",
- "PS512",
- map[string]interface{}{"foo": "bar"},
- true,
- },
- {
- "basic PS256 invalid: foo => bar",
- "eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.PPG4xyDVY8ffp4CcxofNmsTDXsrVG2npdQuibLhJbv4ClyPTUtR5giNSvuxo03kB6I8VXVr0Y9X7UxhJVEoJOmULAwRWaUsDnIewQa101cVhMa6iR8X37kfFoiZ6NkS-c7henVkkQWu2HtotkEtQvN5hFlk8IevXXPmvZlhQhwzB1sGzGYnoi1zOfuL98d3BIjUjtlwii5w6gYG2AEEzp7HnHCsb3jIwUPdq86Oe6hIFjtBwduIK90ca4UqzARpcfwxHwVLMpatKask00AgGVI0ysdk0BLMjmLutquD03XbThHScC2C2_Pp4cHWgMzvbgLU2RYYZcZRKr46QeNgz9W",
- "PS256",
- map[string]interface{}{"foo": "bar"},
- false,
- },
-}
-
-func TestRSAPSSVerify(t *testing.T) {
- var err error
-
- key, _ := ioutil.ReadFile("test/sample_key.pub")
- var rsaPSSKey *rsa.PublicKey
- if rsaPSSKey, err = jwt.ParseRSAPublicKeyFromPEM(key); err != nil {
- t.Errorf("Unable to parse RSA public key: %v", err)
- }
-
- for _, data := range rsaPSSTestData {
- parts := strings.Split(data.tokenString, ".")
-
- method := jwt.GetSigningMethod(data.alg)
- err := method.Verify(strings.Join(parts[0:2], "."), parts[2], rsaPSSKey)
- if data.valid && err != nil {
- t.Errorf("[%v] Error while verifying key: %v", data.name, err)
- }
- if !data.valid && err == nil {
- t.Errorf("[%v] Invalid key passed validation", data.name)
- }
- }
-}
-
-func TestRSAPSSSign(t *testing.T) {
- var err error
-
- key, _ := ioutil.ReadFile("test/sample_key")
- var rsaPSSKey *rsa.PrivateKey
- if rsaPSSKey, err = jwt.ParseRSAPrivateKeyFromPEM(key); err != nil {
- t.Errorf("Unable to parse RSA private key: %v", err)
- }
-
- for _, data := range rsaPSSTestData {
- if data.valid {
- parts := strings.Split(data.tokenString, ".")
- method := jwt.GetSigningMethod(data.alg)
- sig, err := method.Sign(strings.Join(parts[0:2], "."), rsaPSSKey)
- if err != nil {
- t.Errorf("[%v] Error signing token: %v", data.name, err)
- }
- if sig == parts[2] {
- t.Errorf("[%v] Signatures shouldn't match\nnew:\n%v\noriginal:\n%v", data.name, sig, parts[2])
- }
- }
- }
-}
diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa_test.go b/vendor/github.com/dgrijalva/jwt-go/rsa_test.go
deleted file mode 100644
index 2e0f785..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/rsa_test.go
+++ /dev/null
@@ -1,176 +0,0 @@
-package jwt_test
-
-import (
- "github.com/dgrijalva/jwt-go"
- "io/ioutil"
- "strings"
- "testing"
-)
-
-var rsaTestData = []struct {
- name string
- tokenString string
- alg string
- claims map[string]interface{}
- valid bool
-}{
- {
- "Basic RS256",
- "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
- "RS256",
- map[string]interface{}{"foo": "bar"},
- true,
- },
- {
- "Basic RS384",
- "eyJhbGciOiJSUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.W-jEzRfBigtCWsinvVVuldiuilzVdU5ty0MvpLaSaqK9PlAWWlDQ1VIQ_qSKzwL5IXaZkvZFJXT3yL3n7OUVu7zCNJzdwznbC8Z-b0z2lYvcklJYi2VOFRcGbJtXUqgjk2oGsiqUMUMOLP70TTefkpsgqDxbRh9CDUfpOJgW-dU7cmgaoswe3wjUAUi6B6G2YEaiuXC0XScQYSYVKIzgKXJV8Zw-7AN_DBUI4GkTpsvQ9fVVjZM9csQiEXhYekyrKu1nu_POpQonGd8yqkIyXPECNmmqH5jH4sFiF67XhD7_JpkvLziBpI-uh86evBUadmHhb9Otqw3uV3NTaXLzJw",
- "RS384",
- map[string]interface{}{"foo": "bar"},
- true,
- },
- {
- "Basic RS512",
- "eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.zBlLlmRrUxx4SJPUbV37Q1joRcI9EW13grnKduK3wtYKmDXbgDpF1cZ6B-2Jsm5RB8REmMiLpGms-EjXhgnyh2TSHE-9W2gA_jvshegLWtwRVDX40ODSkTb7OVuaWgiy9y7llvcknFBTIg-FnVPVpXMmeV_pvwQyhaz1SSwSPrDyxEmksz1hq7YONXhXPpGaNbMMeDTNP_1oj8DZaqTIL9TwV8_1wb2Odt_Fy58Ke2RVFijsOLdnyEAjt2n9Mxihu9i3PhNBkkxa2GbnXBfq3kzvZ_xxGGopLdHhJjcGWXO-NiwI9_tiu14NRv4L2xC0ItD9Yz68v2ZIZEp_DuzwRQ",
- "RS512",
- map[string]interface{}{"foo": "bar"},
- true,
- },
- {
- "basic invalid: foo => bar",
- "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.EhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
- "RS256",
- map[string]interface{}{"foo": "bar"},
- false,
- },
-}
-
-func TestRSAVerify(t *testing.T) {
- keyData, _ := ioutil.ReadFile("test/sample_key.pub")
- key, _ := jwt.ParseRSAPublicKeyFromPEM(keyData)
-
- for _, data := range rsaTestData {
- parts := strings.Split(data.tokenString, ".")
-
- method := jwt.GetSigningMethod(data.alg)
- err := method.Verify(strings.Join(parts[0:2], "."), parts[2], key)
- if data.valid && err != nil {
- t.Errorf("[%v] Error while verifying key: %v", data.name, err)
- }
- if !data.valid && err == nil {
- t.Errorf("[%v] Invalid key passed validation", data.name)
- }
- }
-}
-
-func TestRSASign(t *testing.T) {
- keyData, _ := ioutil.ReadFile("test/sample_key")
- key, _ := jwt.ParseRSAPrivateKeyFromPEM(keyData)
-
- for _, data := range rsaTestData {
- if data.valid {
- parts := strings.Split(data.tokenString, ".")
- method := jwt.GetSigningMethod(data.alg)
- sig, err := method.Sign(strings.Join(parts[0:2], "."), key)
- if err != nil {
- t.Errorf("[%v] Error signing token: %v", data.name, err)
- }
- if sig != parts[2] {
- t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", data.name, sig, parts[2])
- }
- }
- }
-}
-
-func TestRSAVerifyWithPreParsedPrivateKey(t *testing.T) {
- key, _ := ioutil.ReadFile("test/sample_key.pub")
- parsedKey, err := jwt.ParseRSAPublicKeyFromPEM(key)
- if err != nil {
- t.Fatal(err)
- }
- testData := rsaTestData[0]
- parts := strings.Split(testData.tokenString, ".")
- err = jwt.SigningMethodRS256.Verify(strings.Join(parts[0:2], "."), parts[2], parsedKey)
- if err != nil {
- t.Errorf("[%v] Error while verifying key: %v", testData.name, err)
- }
-}
-
-func TestRSAWithPreParsedPrivateKey(t *testing.T) {
- key, _ := ioutil.ReadFile("test/sample_key")
- parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key)
- if err != nil {
- t.Fatal(err)
- }
- testData := rsaTestData[0]
- parts := strings.Split(testData.tokenString, ".")
- sig, err := jwt.SigningMethodRS256.Sign(strings.Join(parts[0:2], "."), parsedKey)
- if err != nil {
- t.Errorf("[%v] Error signing token: %v", testData.name, err)
- }
- if sig != parts[2] {
- t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", testData.name, sig, parts[2])
- }
-}
-
-func TestRSAKeyParsing(t *testing.T) {
- key, _ := ioutil.ReadFile("test/sample_key")
- pubKey, _ := ioutil.ReadFile("test/sample_key.pub")
- badKey := []byte("All your base are belong to key")
-
- // Test parsePrivateKey
- if _, e := jwt.ParseRSAPrivateKeyFromPEM(key); e != nil {
- t.Errorf("Failed to parse valid private key: %v", e)
- }
-
- if k, e := jwt.ParseRSAPrivateKeyFromPEM(pubKey); e == nil {
- t.Errorf("Parsed public key as valid private key: %v", k)
- }
-
- if k, e := jwt.ParseRSAPrivateKeyFromPEM(badKey); e == nil {
- t.Errorf("Parsed invalid key as valid private key: %v", k)
- }
-
- // Test parsePublicKey
- if _, e := jwt.ParseRSAPublicKeyFromPEM(pubKey); e != nil {
- t.Errorf("Failed to parse valid public key: %v", e)
- }
-
- if k, e := jwt.ParseRSAPublicKeyFromPEM(key); e == nil {
- t.Errorf("Parsed private key as valid public key: %v", k)
- }
-
- if k, e := jwt.ParseRSAPublicKeyFromPEM(badKey); e == nil {
- t.Errorf("Parsed invalid key as valid private key: %v", k)
- }
-
-}
-
-func BenchmarkRS256Signing(b *testing.B) {
- key, _ := ioutil.ReadFile("test/sample_key")
- parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key)
- if err != nil {
- b.Fatal(err)
- }
-
- benchmarkSigning(b, jwt.SigningMethodRS256, parsedKey)
-}
-
-func BenchmarkRS384Signing(b *testing.B) {
- key, _ := ioutil.ReadFile("test/sample_key")
- parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key)
- if err != nil {
- b.Fatal(err)
- }
-
- benchmarkSigning(b, jwt.SigningMethodRS384, parsedKey)
-}
-
-func BenchmarkRS512Signing(b *testing.B) {
- key, _ := ioutil.ReadFile("test/sample_key")
- parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key)
- if err != nil {
- b.Fatal(err)
- }
-
- benchmarkSigning(b, jwt.SigningMethodRS512, parsedKey)
-}
diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go b/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go
deleted file mode 100644
index 213a90d..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go
+++ /dev/null
@@ -1,69 +0,0 @@
-package jwt
-
-import (
- "crypto/rsa"
- "crypto/x509"
- "encoding/pem"
- "errors"
-)
-
-var (
- ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key")
- ErrNotRSAPrivateKey = errors.New("Key is not a valid RSA private key")
- ErrNotRSAPublicKey = errors.New("Key is not a valid RSA public key")
-)
-
-// Parse PEM encoded PKCS1 or PKCS8 private key
-func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) {
- var err error
-
- // Parse PEM block
- var block *pem.Block
- if block, _ = pem.Decode(key); block == nil {
- return nil, ErrKeyMustBePEMEncoded
- }
-
- var parsedKey interface{}
- if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil {
- if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil {
- return nil, err
- }
- }
-
- var pkey *rsa.PrivateKey
- var ok bool
- if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok {
- return nil, ErrNotRSAPrivateKey
- }
-
- return pkey, nil
-}
-
-// Parse PEM encoded PKCS1 or PKCS8 public key
-func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
- var err error
-
- // Parse PEM block
- var block *pem.Block
- if block, _ = pem.Decode(key); block == nil {
- return nil, ErrKeyMustBePEMEncoded
- }
-
- // Parse the key
- var parsedKey interface{}
- if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
- if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
- parsedKey = cert.PublicKey
- } else {
- return nil, err
- }
- }
-
- var pkey *rsa.PublicKey
- var ok bool
- if pkey, ok = parsedKey.(*rsa.PublicKey); !ok {
- return nil, ErrNotRSAPublicKey
- }
-
- return pkey, nil
-}
diff --git a/vendor/github.com/dgrijalva/jwt-go/signing_method.go b/vendor/github.com/dgrijalva/jwt-go/signing_method.go
deleted file mode 100644
index ed1f212..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/signing_method.go
+++ /dev/null
@@ -1,35 +0,0 @@
-package jwt
-
-import (
- "sync"
-)
-
-var signingMethods = map[string]func() SigningMethod{}
-var signingMethodLock = new(sync.RWMutex)
-
-// Implement SigningMethod to add new methods for signing or verifying tokens.
-type SigningMethod interface {
- Verify(signingString, signature string, key interface{}) error // Returns nil if signature is valid
- Sign(signingString string, key interface{}) (string, error) // Returns encoded signature or error
- Alg() string // returns the alg identifier for this method (example: 'HS256')
-}
-
-// Register the "alg" name and a factory function for signing method.
-// This is typically done during init() in the method's implementation
-func RegisterSigningMethod(alg string, f func() SigningMethod) {
- signingMethodLock.Lock()
- defer signingMethodLock.Unlock()
-
- signingMethods[alg] = f
-}
-
-// Get a signing method from an "alg" string
-func GetSigningMethod(alg string) (method SigningMethod) {
- signingMethodLock.RLock()
- defer signingMethodLock.RUnlock()
-
- if methodF, ok := signingMethods[alg]; ok {
- method = methodF()
- }
- return
-}
diff --git a/vendor/github.com/dgrijalva/jwt-go/token.go b/vendor/github.com/dgrijalva/jwt-go/token.go
deleted file mode 100644
index d637e08..0000000
--- a/vendor/github.com/dgrijalva/jwt-go/token.go
+++ /dev/null
@@ -1,108 +0,0 @@
-package jwt
-
-import (
- "encoding/base64"
- "encoding/json"
- "strings"
- "time"
-)
-
-// TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time).
-// You can override it to use another time value. This is useful for testing or if your
-// server uses a different time zone than your tokens.
-var TimeFunc = time.Now
-
-// Parse methods use this callback function to supply
-// the key for verification. The function receives the parsed,
-// but unverified Token. This allows you to use properties in the
-// Header of the token (such as `kid`) to identify which key to use.
-type Keyfunc func(*Token) (interface{}, error)
-
-// A JWT Token. Different fields will be used depending on whether you're
-// creating or parsing/verifying a token.
-type Token struct {
- Raw string // The raw token. Populated when you Parse a token
- Method SigningMethod // The signing method used or to be used
- Header map[string]interface{} // The first segment of the token
- Claims Claims // The second segment of the token
- Signature string // The third segment of the token. Populated when you Parse a token
- Valid bool // Is the token valid? Populated when you Parse/Verify a token
-}
-
-// Create a new Token. Takes a signing method
-func New(method SigningMethod) *Token {
- return NewWithClaims(method, MapClaims{})
-}
-
-func NewWithClaims(method SigningMethod, claims Claims) *Token {
- return &Token{
- Header: map[string]interface{}{
- "typ": "JWT",
- "alg": method.Alg(),
- },
- Claims: claims,
- Method: method,
- }
-}
-
-// Get the complete, signed token
-func (t *Token) SignedString(key interface{}) (string, error) {
- var sig, sstr string
- var err error
- if sstr, err = t.SigningString(); err != nil {
- return "", err
- }
- if sig, err = t.Method.Sign(sstr, key); err != nil {
- return "", err
- }
- return strings.Join([]string{sstr, sig}, "."), nil
-}
-
-// Generate the signing string. This is the
-// most expensive part of the whole deal. Unless you
-// need this for something special, just go straight for
-// the SignedString.
-func (t *Token) SigningString() (string, error) {
- var err error
- parts := make([]string, 2)
- for i, _ := range parts {
- var jsonValue []byte
- if i == 0 {
- if jsonValue, err = json.Marshal(t.Header); err != nil {
- return "", err
- }
- } else {
- if jsonValue, err = json.Marshal(t.Claims); err != nil {
- return "", err
- }
- }
-
- parts[i] = EncodeSegment(jsonValue)
- }
- return strings.Join(parts, "."), nil
-}
-
-// Parse, validate, and return a token.
-// keyFunc will receive the parsed token and should return the key for validating.
-// If everything is kosher, err will be nil
-func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
- return new(Parser).Parse(tokenString, keyFunc)
-}
-
-func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) {
- return new(Parser).ParseWithClaims(tokenString, claims, keyFunc)
-}
-
-// Encode JWT specific base64url encoding with padding stripped
-func EncodeSegment(seg []byte) string {
- return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=")
-}
-
-// Decode JWT specific base64url encoding with padding stripped
-func DecodeSegment(seg string) ([]byte, error) {
- if l := len(seg) % 4; l > 0 {
- seg += strings.Repeat("=", 4-l)
- }
-
- return base64.URLEncoding.DecodeString(seg)
-}
diff --git a/vendor/github.com/fsnotify/fsnotify/.editorconfig b/vendor/github.com/fsnotify/fsnotify/.editorconfig
deleted file mode 100644
index ba49e3c..0000000
--- a/vendor/github.com/fsnotify/fsnotify/.editorconfig
+++ /dev/null
@@ -1,5 +0,0 @@
-root = true
-
-[*]
-indent_style = tab
-indent_size = 4
diff --git a/vendor/github.com/fsnotify/fsnotify/.gitignore b/vendor/github.com/fsnotify/fsnotify/.gitignore
deleted file mode 100644
index 4cd0cba..0000000
--- a/vendor/github.com/fsnotify/fsnotify/.gitignore
+++ /dev/null
@@ -1,6 +0,0 @@
-# Setup a Global .gitignore for OS and editor generated files:
-# https://help.github.com/articles/ignoring-files
-# git config --global core.excludesfile ~/.gitignore_global
-
-.vagrant
-*.sublime-project
diff --git a/vendor/github.com/fsnotify/fsnotify/.travis.yml b/vendor/github.com/fsnotify/fsnotify/.travis.yml
deleted file mode 100644
index 3a5c933..0000000
--- a/vendor/github.com/fsnotify/fsnotify/.travis.yml
+++ /dev/null
@@ -1,28 +0,0 @@
-sudo: false
-language: go
-
-go:
- - 1.6.3
- - tip
-
-matrix:
- allow_failures:
- - go: tip
-
-before_script:
- - go get -u github.com/golang/lint/golint
-
-script:
- - go test -v --race ./...
-
-after_script:
- - test -z "$(gofmt -s -l -w . | tee /dev/stderr)"
- - test -z "$(golint ./... | tee /dev/stderr)"
- - go vet ./...
-
-os:
- - linux
- - osx
-
-notifications:
- email: false
diff --git a/vendor/github.com/fsnotify/fsnotify/AUTHORS b/vendor/github.com/fsnotify/fsnotify/AUTHORS
deleted file mode 100644
index 0a5bf8f..0000000
--- a/vendor/github.com/fsnotify/fsnotify/AUTHORS
+++ /dev/null
@@ -1,46 +0,0 @@
-# Names should be added to this file as
-# Name or Organization
-# The email address is not required for organizations.
-
-# You can update this list using the following command:
-#
-# $ git shortlog -se | awk '{print $2 " " $3 " " $4}'
-
-# Please keep the list sorted.
-
-Adrien Bustany
-Amit Krishnan
-Bjørn Erik Pedersen
-Bruno Bigras
-Caleb Spare
-Case Nelson
-Chris Howey
-Christoffer Buchholz
-Daniel Wagner-Hall
-Dave Cheney
-Evan Phoenix
-Francisco Souza
-Hari haran
-John C Barstow
-Kelvin Fo
-Ken-ichirou MATSUZAWA
-Matt Layher
-Nathan Youngman
-Patrick
-Paul Hammond
-Pawel Knap
-Pieter Droogendijk
-Pursuit92
-Riku Voipio
-Rob Figueiredo
-Slawek Ligus
-Soge Zhang
-Tiffany Jernigan
-Tilak Sharma
-Travis Cline
-Tudor Golubenco
-Yukang
-bronze1man
-debrando
-henrikedwards
-铁哥
diff --git a/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md b/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md
deleted file mode 100644
index 40d7660..0000000
--- a/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md
+++ /dev/null
@@ -1,307 +0,0 @@
-# Changelog
-
-## v1.4.2 / 2016-10-10
-
-* Linux: use InotifyInit1 with IN_CLOEXEC to stop leaking a file descriptor to a child process when using fork/exec [#178](https://github.com/fsnotify/fsnotify/pull/178) (thanks @pattyshack)
-
-## v1.4.1 / 2016-10-04
-
-* Fix flaky inotify stress test on Linux [#177](https://github.com/fsnotify/fsnotify/pull/177) (thanks @pattyshack)
-
-## v1.4.0 / 2016-10-01
-
-* add a String() method to Event.Op [#165](https://github.com/fsnotify/fsnotify/pull/165) (thanks @oozie)
-
-## v1.3.1 / 2016-06-28
-
-* Windows: fix for double backslash when watching the root of a drive [#151](https://github.com/fsnotify/fsnotify/issues/151) (thanks @brunoqc)
-
-## v1.3.0 / 2016-04-19
-
-* Support linux/arm64 by [patching](https://go-review.googlesource.com/#/c/21971/) x/sys/unix and switching to to it from syscall (thanks @suihkulokki) [#135](https://github.com/fsnotify/fsnotify/pull/135)
-
-## v1.2.10 / 2016-03-02
-
-* Fix golint errors in windows.go [#121](https://github.com/fsnotify/fsnotify/pull/121) (thanks @tiffanyfj)
-
-## v1.2.9 / 2016-01-13
-
-kqueue: Fix logic for CREATE after REMOVE [#111](https://github.com/fsnotify/fsnotify/pull/111) (thanks @bep)
-
-## v1.2.8 / 2015-12-17
-
-* kqueue: fix race condition in Close [#105](https://github.com/fsnotify/fsnotify/pull/105) (thanks @djui for reporting the issue and @ppknap for writing a failing test)
-* inotify: fix race in test
-* enable race detection for continuous integration (Linux, Mac, Windows)
-
-## v1.2.5 / 2015-10-17
-
-* inotify: use epoll_create1 for arm64 support (requires Linux 2.6.27 or later) [#100](https://github.com/fsnotify/fsnotify/pull/100) (thanks @suihkulokki)
-* inotify: fix path leaks [#73](https://github.com/fsnotify/fsnotify/pull/73) (thanks @chamaken)
-* kqueue: watch for rename events on subdirectories [#83](https://github.com/fsnotify/fsnotify/pull/83) (thanks @guotie)
-* kqueue: avoid infinite loops from symlinks cycles [#101](https://github.com/fsnotify/fsnotify/pull/101) (thanks @illicitonion)
-
-## v1.2.1 / 2015-10-14
-
-* kqueue: don't watch named pipes [#98](https://github.com/fsnotify/fsnotify/pull/98) (thanks @evanphx)
-
-## v1.2.0 / 2015-02-08
-
-* inotify: use epoll to wake up readEvents [#66](https://github.com/fsnotify/fsnotify/pull/66) (thanks @PieterD)
-* inotify: closing watcher should now always shut down goroutine [#63](https://github.com/fsnotify/fsnotify/pull/63) (thanks @PieterD)
-* kqueue: close kqueue after removing watches, fixes [#59](https://github.com/fsnotify/fsnotify/issues/59)
-
-## v1.1.1 / 2015-02-05
-
-* inotify: Retry read on EINTR [#61](https://github.com/fsnotify/fsnotify/issues/61) (thanks @PieterD)
-
-## v1.1.0 / 2014-12-12
-
-* kqueue: rework internals [#43](https://github.com/fsnotify/fsnotify/pull/43)
- * add low-level functions
- * only need to store flags on directories
- * less mutexes [#13](https://github.com/fsnotify/fsnotify/issues/13)
- * done can be an unbuffered channel
- * remove calls to os.NewSyscallError
-* More efficient string concatenation for Event.String() [#52](https://github.com/fsnotify/fsnotify/pull/52) (thanks @mdlayher)
-* kqueue: fix regression in rework causing subdirectories to be watched [#48](https://github.com/fsnotify/fsnotify/issues/48)
-* kqueue: cleanup internal watch before sending remove event [#51](https://github.com/fsnotify/fsnotify/issues/51)
-
-## v1.0.4 / 2014-09-07
-
-* kqueue: add dragonfly to the build tags.
-* Rename source code files, rearrange code so exported APIs are at the top.
-* Add done channel to example code. [#37](https://github.com/fsnotify/fsnotify/pull/37) (thanks @chenyukang)
-
-## v1.0.3 / 2014-08-19
-
-* [Fix] Windows MOVED_TO now translates to Create like on BSD and Linux. [#36](https://github.com/fsnotify/fsnotify/issues/36)
-
-## v1.0.2 / 2014-08-17
-
-* [Fix] Missing create events on OS X. [#14](https://github.com/fsnotify/fsnotify/issues/14) (thanks @zhsso)
-* [Fix] Make ./path and path equivalent. (thanks @zhsso)
-
-## v1.0.0 / 2014-08-15
-
-* [API] Remove AddWatch on Windows, use Add.
-* Improve documentation for exported identifiers. [#30](https://github.com/fsnotify/fsnotify/issues/30)
-* Minor updates based on feedback from golint.
-
-## dev / 2014-07-09
-
-* Moved to [github.com/fsnotify/fsnotify](https://github.com/fsnotify/fsnotify).
-* Use os.NewSyscallError instead of returning errno (thanks @hariharan-uno)
-
-## dev / 2014-07-04
-
-* kqueue: fix incorrect mutex used in Close()
-* Update example to demonstrate usage of Op.
-
-## dev / 2014-06-28
-
-* [API] Don't set the Write Op for attribute notifications [#4](https://github.com/fsnotify/fsnotify/issues/4)
-* Fix for String() method on Event (thanks Alex Brainman)
-* Don't build on Plan 9 or Solaris (thanks @4ad)
-
-## dev / 2014-06-21
-
-* Events channel of type Event rather than *Event.
-* [internal] use syscall constants directly for inotify and kqueue.
-* [internal] kqueue: rename events to kevents and fileEvent to event.
-
-## dev / 2014-06-19
-
-* Go 1.3+ required on Windows (uses syscall.ERROR_MORE_DATA internally).
-* [internal] remove cookie from Event struct (unused).
-* [internal] Event struct has the same definition across every OS.
-* [internal] remove internal watch and removeWatch methods.
-
-## dev / 2014-06-12
-
-* [API] Renamed Watch() to Add() and RemoveWatch() to Remove().
-* [API] Pluralized channel names: Events and Errors.
-* [API] Renamed FileEvent struct to Event.
-* [API] Op constants replace methods like IsCreate().
-
-## dev / 2014-06-12
-
-* Fix data race on kevent buffer (thanks @tilaks) [#98](https://github.com/howeyc/fsnotify/pull/98)
-
-## dev / 2014-05-23
-
-* [API] Remove current implementation of WatchFlags.
- * current implementation doesn't take advantage of OS for efficiency
- * provides little benefit over filtering events as they are received, but has extra bookkeeping and mutexes
- * no tests for the current implementation
- * not fully implemented on Windows [#93](https://github.com/howeyc/fsnotify/issues/93#issuecomment-39285195)
-
-## v0.9.3 / 2014-12-31
-
-* kqueue: cleanup internal watch before sending remove event [#51](https://github.com/fsnotify/fsnotify/issues/51)
-
-## v0.9.2 / 2014-08-17
-
-* [Backport] Fix missing create events on OS X. [#14](https://github.com/fsnotify/fsnotify/issues/14) (thanks @zhsso)
-
-## v0.9.1 / 2014-06-12
-
-* Fix data race on kevent buffer (thanks @tilaks) [#98](https://github.com/howeyc/fsnotify/pull/98)
-
-## v0.9.0 / 2014-01-17
-
-* IsAttrib() for events that only concern a file's metadata [#79][] (thanks @abustany)
-* [Fix] kqueue: fix deadlock [#77][] (thanks @cespare)
-* [NOTICE] Development has moved to `code.google.com/p/go.exp/fsnotify` in preparation for inclusion in the Go standard library.
-
-## v0.8.12 / 2013-11-13
-
-* [API] Remove FD_SET and friends from Linux adapter
-
-## v0.8.11 / 2013-11-02
-
-* [Doc] Add Changelog [#72][] (thanks @nathany)
-* [Doc] Spotlight and double modify events on OS X [#62][] (reported by @paulhammond)
-
-## v0.8.10 / 2013-10-19
-
-* [Fix] kqueue: remove file watches when parent directory is removed [#71][] (reported by @mdwhatcott)
-* [Fix] kqueue: race between Close and readEvents [#70][] (reported by @bernerdschaefer)
-* [Doc] specify OS-specific limits in README (thanks @debrando)
-
-## v0.8.9 / 2013-09-08
-
-* [Doc] Contributing (thanks @nathany)
-* [Doc] update package path in example code [#63][] (thanks @paulhammond)
-* [Doc] GoCI badge in README (Linux only) [#60][]
-* [Doc] Cross-platform testing with Vagrant [#59][] (thanks @nathany)
-
-## v0.8.8 / 2013-06-17
-
-* [Fix] Windows: handle `ERROR_MORE_DATA` on Windows [#49][] (thanks @jbowtie)
-
-## v0.8.7 / 2013-06-03
-
-* [API] Make syscall flags internal
-* [Fix] inotify: ignore event changes
-* [Fix] race in symlink test [#45][] (reported by @srid)
-* [Fix] tests on Windows
-* lower case error messages
-
-## v0.8.6 / 2013-05-23
-
-* kqueue: Use EVT_ONLY flag on Darwin
-* [Doc] Update README with full example
-
-## v0.8.5 / 2013-05-09
-
-* [Fix] inotify: allow monitoring of "broken" symlinks (thanks @tsg)
-
-## v0.8.4 / 2013-04-07
-
-* [Fix] kqueue: watch all file events [#40][] (thanks @ChrisBuchholz)
-
-## v0.8.3 / 2013-03-13
-
-* [Fix] inoitfy/kqueue memory leak [#36][] (reported by @nbkolchin)
-* [Fix] kqueue: use fsnFlags for watching a directory [#33][] (reported by @nbkolchin)
-
-## v0.8.2 / 2013-02-07
-
-* [Doc] add Authors
-* [Fix] fix data races for map access [#29][] (thanks @fsouza)
-
-## v0.8.1 / 2013-01-09
-
-* [Fix] Windows path separators
-* [Doc] BSD License
-
-## v0.8.0 / 2012-11-09
-
-* kqueue: directory watching improvements (thanks @vmirage)
-* inotify: add `IN_MOVED_TO` [#25][] (requested by @cpisto)
-* [Fix] kqueue: deleting watched directory [#24][] (reported by @jakerr)
-
-## v0.7.4 / 2012-10-09
-
-* [Fix] inotify: fixes from https://codereview.appspot.com/5418045/ (ugorji)
-* [Fix] kqueue: preserve watch flags when watching for delete [#21][] (reported by @robfig)
-* [Fix] kqueue: watch the directory even if it isn't a new watch (thanks @robfig)
-* [Fix] kqueue: modify after recreation of file
-
-## v0.7.3 / 2012-09-27
-
-* [Fix] kqueue: watch with an existing folder inside the watched folder (thanks @vmirage)
-* [Fix] kqueue: no longer get duplicate CREATE events
-
-## v0.7.2 / 2012-09-01
-
-* kqueue: events for created directories
-
-## v0.7.1 / 2012-07-14
-
-* [Fix] for renaming files
-
-## v0.7.0 / 2012-07-02
-
-* [Feature] FSNotify flags
-* [Fix] inotify: Added file name back to event path
-
-## v0.6.0 / 2012-06-06
-
-* kqueue: watch files after directory created (thanks @tmc)
-
-## v0.5.1 / 2012-05-22
-
-* [Fix] inotify: remove all watches before Close()
-
-## v0.5.0 / 2012-05-03
-
-* [API] kqueue: return errors during watch instead of sending over channel
-* kqueue: match symlink behavior on Linux
-* inotify: add `DELETE_SELF` (requested by @taralx)
-* [Fix] kqueue: handle EINTR (reported by @robfig)
-* [Doc] Godoc example [#1][] (thanks @davecheney)
-
-## v0.4.0 / 2012-03-30
-
-* Go 1 released: build with go tool
-* [Feature] Windows support using winfsnotify
-* Windows does not have attribute change notifications
-* Roll attribute notifications into IsModify
-
-## v0.3.0 / 2012-02-19
-
-* kqueue: add files when watch directory
-
-## v0.2.0 / 2011-12-30
-
-* update to latest Go weekly code
-
-## v0.1.0 / 2011-10-19
-
-* kqueue: add watch on file creation to match inotify
-* kqueue: create file event
-* inotify: ignore `IN_IGNORED` events
-* event String()
-* linux: common FileEvent functions
-* initial commit
-
-[#79]: https://github.com/howeyc/fsnotify/pull/79
-[#77]: https://github.com/howeyc/fsnotify/pull/77
-[#72]: https://github.com/howeyc/fsnotify/issues/72
-[#71]: https://github.com/howeyc/fsnotify/issues/71
-[#70]: https://github.com/howeyc/fsnotify/issues/70
-[#63]: https://github.com/howeyc/fsnotify/issues/63
-[#62]: https://github.com/howeyc/fsnotify/issues/62
-[#60]: https://github.com/howeyc/fsnotify/issues/60
-[#59]: https://github.com/howeyc/fsnotify/issues/59
-[#49]: https://github.com/howeyc/fsnotify/issues/49
-[#45]: https://github.com/howeyc/fsnotify/issues/45
-[#40]: https://github.com/howeyc/fsnotify/issues/40
-[#36]: https://github.com/howeyc/fsnotify/issues/36
-[#33]: https://github.com/howeyc/fsnotify/issues/33
-[#29]: https://github.com/howeyc/fsnotify/issues/29
-[#25]: https://github.com/howeyc/fsnotify/issues/25
-[#24]: https://github.com/howeyc/fsnotify/issues/24
-[#21]: https://github.com/howeyc/fsnotify/issues/21
diff --git a/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md b/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md
deleted file mode 100644
index 6a81ba4..0000000
--- a/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md
+++ /dev/null
@@ -1,77 +0,0 @@
-# Contributing
-
-## Issues
-
-* Request features and report bugs using the [GitHub Issue Tracker](https://github.com/fsnotify/fsnotify/issues).
-* Please indicate the platform you are using fsnotify on.
-* A code example to reproduce the problem is appreciated.
-
-## Pull Requests
-
-### Contributor License Agreement
-
-fsnotify is derived from code in the [golang.org/x/exp](https://godoc.org/golang.org/x/exp) package and it may be included [in the standard library](https://github.com/fsnotify/fsnotify/issues/1) in the future. Therefore fsnotify carries the same [LICENSE](https://github.com/fsnotify/fsnotify/blob/master/LICENSE) as Go. Contributors retain their copyright, so you need to fill out a short form before we can accept your contribution: [Google Individual Contributor License Agreement](https://developers.google.com/open-source/cla/individual).
-
-Please indicate that you have signed the CLA in your pull request.
-
-### How fsnotify is Developed
-
-* Development is done on feature branches.
-* Tests are run on BSD, Linux, OS X and Windows.
-* Pull requests are reviewed and [applied to master][am] using [hub][].
- * Maintainers may modify or squash commits rather than asking contributors to.
-* To issue a new release, the maintainers will:
- * Update the CHANGELOG
- * Tag a version, which will become available through gopkg.in.
-
-### How to Fork
-
-For smooth sailing, always use the original import path. Installing with `go get` makes this easy.
-
-1. Install from GitHub (`go get -u github.com/fsnotify/fsnotify`)
-2. Create your feature branch (`git checkout -b my-new-feature`)
-3. Ensure everything works and the tests pass (see below)
-4. Commit your changes (`git commit -am 'Add some feature'`)
-
-Contribute upstream:
-
-1. Fork fsnotify on GitHub
-2. Add your remote (`git remote add fork git@github.com:mycompany/repo.git`)
-3. Push to the branch (`git push fork my-new-feature`)
-4. Create a new Pull Request on GitHub
-
-This workflow is [thoroughly explained by Katrina Owen](https://splice.com/blog/contributing-open-source-git-repositories-go/).
-
-### Testing
-
-fsnotify uses build tags to compile different code on Linux, BSD, OS X, and Windows.
-
-Before doing a pull request, please do your best to test your changes on multiple platforms, and list which platforms you were able/unable to test on.
-
-To aid in cross-platform testing there is a Vagrantfile for Linux and BSD.
-
-* Install [Vagrant](http://www.vagrantup.com/) and [VirtualBox](https://www.virtualbox.org/)
-* Setup [Vagrant Gopher](https://github.com/nathany/vagrant-gopher) in your `src` folder.
-* Run `vagrant up` from the project folder. You can also setup just one box with `vagrant up linux` or `vagrant up bsd` (note: the BSD box doesn't support Windows hosts at this time, and NFS may prompt for your host OS password)
-* Once setup, you can run the test suite on a given OS with a single command `vagrant ssh linux -c 'cd fsnotify/fsnotify; go test'`.
-* When you're done, you will want to halt or destroy the Vagrant boxes.
-
-Notice: fsnotify file system events won't trigger in shared folders. The tests get around this limitation by using the /tmp directory.
-
-Right now there is no equivalent solution for Windows and OS X, but there are Windows VMs [freely available from Microsoft](http://www.modern.ie/en-us/virtualization-tools#downloads).
-
-### Maintainers
-
-Help maintaining fsnotify is welcome. To be a maintainer:
-
-* Submit a pull request and sign the CLA as above.
-* You must be able to run the test suite on Mac, Windows, Linux and BSD.
-
-To keep master clean, the fsnotify project uses the "apply mail" workflow outlined in Nathaniel Talbott's post ["Merge pull request" Considered Harmful][am]. This requires installing [hub][].
-
-All code changes should be internal pull requests.
-
-Releases are tagged using [Semantic Versioning](http://semver.org/).
-
-[hub]: https://github.com/github/hub
-[am]: http://blog.spreedly.com/2014/06/24/merge-pull-request-considered-harmful/#.VGa5yZPF_Zs
diff --git a/vendor/github.com/fsnotify/fsnotify/LICENSE b/vendor/github.com/fsnotify/fsnotify/LICENSE
deleted file mode 100644
index f21e540..0000000
--- a/vendor/github.com/fsnotify/fsnotify/LICENSE
+++ /dev/null
@@ -1,28 +0,0 @@
-Copyright (c) 2012 The Go Authors. All rights reserved.
-Copyright (c) 2012 fsnotify Authors. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- * Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
- * Neither the name of Google Inc. nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/vendor/github.com/fsnotify/fsnotify/README.md b/vendor/github.com/fsnotify/fsnotify/README.md
deleted file mode 100644
index 3c891e3..0000000
--- a/vendor/github.com/fsnotify/fsnotify/README.md
+++ /dev/null
@@ -1,50 +0,0 @@
-# File system notifications for Go
-
-[](https://godoc.org/github.com/fsnotify/fsnotify) [](https://goreportcard.com/report/github.com/fsnotify/fsnotify)
-
-fsnotify utilizes [golang.org/x/sys](https://godoc.org/golang.org/x/sys) rather than `syscall` from the standard library. Ensure you have the latest version installed by running:
-
-```console
-go get -u golang.org/x/sys/...
-```
-
-Cross platform: Windows, Linux, BSD and OS X.
-
-|Adapter |OS |Status |
-|----------|----------|----------|
-|inotify |Linux 2.6.27 or later, Android\*|Supported [](https://travis-ci.org/fsnotify/fsnotify)|
-|kqueue |BSD, OS X, iOS\*|Supported [](https://travis-ci.org/fsnotify/fsnotify)|
-|ReadDirectoryChangesW|Windows|Supported [](https://ci.appveyor.com/project/NathanYoungman/fsnotify/branch/master)|
-|FSEvents |OS X |[Planned](https://github.com/fsnotify/fsnotify/issues/11)|
-|FEN |Solaris 11 |[In Progress](https://github.com/fsnotify/fsnotify/issues/12)|
-|fanotify |Linux 2.6.37+ | |
-|USN Journals |Windows |[Maybe](https://github.com/fsnotify/fsnotify/issues/53)|
-|Polling |*All* |[Maybe](https://github.com/fsnotify/fsnotify/issues/9)|
-
-\* Android and iOS are untested.
-
-Please see [the documentation](https://godoc.org/github.com/fsnotify/fsnotify) for usage. Consult the [Wiki](https://github.com/fsnotify/fsnotify/wiki) for the FAQ and further information.
-
-## API stability
-
-fsnotify is a fork of [howeyc/fsnotify](https://godoc.org/github.com/howeyc/fsnotify) with a new API as of v1.0. The API is based on [this design document](http://goo.gl/MrYxyA).
-
-All [releases](https://github.com/fsnotify/fsnotify/releases) are tagged based on [Semantic Versioning](http://semver.org/). Further API changes are [planned](https://github.com/fsnotify/fsnotify/milestones), and will be tagged with a new major revision number.
-
-Go 1.6 supports dependencies located in the `vendor/` folder. Unless you are creating a library, it is recommended that you copy fsnotify into `vendor/github.com/fsnotify/fsnotify` within your project, and likewise for `golang.org/x/sys`.
-
-## Contributing
-
-Please refer to [CONTRIBUTING][] before opening an issue or pull request.
-
-## Example
-
-See [example_test.go](https://github.com/fsnotify/fsnotify/blob/master/example_test.go).
-
-[contributing]: https://github.com/fsnotify/fsnotify/blob/master/CONTRIBUTING.md
-
-## Related Projects
-
-* [notify](https://github.com/rjeczalik/notify)
-* [fsevents](https://github.com/fsnotify/fsevents)
-
diff --git a/vendor/github.com/fsnotify/fsnotify/example_test.go b/vendor/github.com/fsnotify/fsnotify/example_test.go
deleted file mode 100644
index 700502c..0000000
--- a/vendor/github.com/fsnotify/fsnotify/example_test.go
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright 2012 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.
-
-// +build !plan9
-
-package fsnotify_test
-
-import (
- "log"
-
- "github.com/fsnotify/fsnotify"
-)
-
-func ExampleNewWatcher() {
- watcher, err := fsnotify.NewWatcher()
- if err != nil {
- log.Fatal(err)
- }
- defer watcher.Close()
-
- done := make(chan bool)
- go func() {
- for {
- select {
- case event := <-watcher.Events:
- log.Println("event:", event)
- if event.Op&fsnotify.Write == fsnotify.Write {
- log.Println("modified file:", event.Name)
- }
- case err := <-watcher.Errors:
- log.Println("error:", err)
- }
- }
- }()
-
- err = watcher.Add("/tmp/foo")
- if err != nil {
- log.Fatal(err)
- }
- <-done
-}
diff --git a/vendor/github.com/fsnotify/fsnotify/fen.go b/vendor/github.com/fsnotify/fsnotify/fen.go
deleted file mode 100644
index ced39cb..0000000
--- a/vendor/github.com/fsnotify/fsnotify/fen.go
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright 2010 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.
-
-// +build solaris
-
-package fsnotify
-
-import (
- "errors"
-)
-
-// Watcher watches a set of files, delivering events to a channel.
-type Watcher struct {
- Events chan Event
- Errors chan error
-}
-
-// NewWatcher establishes a new watcher with the underlying OS and begins waiting for events.
-func NewWatcher() (*Watcher, error) {
- return nil, errors.New("FEN based watcher not yet supported for fsnotify\n")
-}
-
-// Close removes all watches and closes the events channel.
-func (w *Watcher) Close() error {
- return nil
-}
-
-// Add starts watching the named file or directory (non-recursively).
-func (w *Watcher) Add(name string) error {
- return nil
-}
-
-// Remove stops watching the the named file or directory (non-recursively).
-func (w *Watcher) Remove(name string) error {
- return nil
-}
diff --git a/vendor/github.com/fsnotify/fsnotify/fsnotify.go b/vendor/github.com/fsnotify/fsnotify/fsnotify.go
deleted file mode 100644
index e7f55fe..0000000
--- a/vendor/github.com/fsnotify/fsnotify/fsnotify.go
+++ /dev/null
@@ -1,62 +0,0 @@
-// Copyright 2012 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.
-
-// +build !plan9
-
-// Package fsnotify provides a platform-independent interface for file system notifications.
-package fsnotify
-
-import (
- "bytes"
- "fmt"
-)
-
-// Event represents a single file system notification.
-type Event struct {
- Name string // Relative path to the file or directory.
- Op Op // File operation that triggered the event.
-}
-
-// Op describes a set of file operations.
-type Op uint32
-
-// These are the generalized file operations that can trigger a notification.
-const (
- Create Op = 1 << iota
- Write
- Remove
- Rename
- Chmod
-)
-
-func (op Op) String() string {
- // Use a buffer for efficient string concatenation
- var buffer bytes.Buffer
-
- if op&Create == Create {
- buffer.WriteString("|CREATE")
- }
- if op&Remove == Remove {
- buffer.WriteString("|REMOVE")
- }
- if op&Write == Write {
- buffer.WriteString("|WRITE")
- }
- if op&Rename == Rename {
- buffer.WriteString("|RENAME")
- }
- if op&Chmod == Chmod {
- buffer.WriteString("|CHMOD")
- }
- if buffer.Len() == 0 {
- return ""
- }
- return buffer.String()[1:] // Strip leading pipe
-}
-
-// String returns a string representation of the event in the form
-// "file: REMOVE|WRITE|..."
-func (e Event) String() string {
- return fmt.Sprintf("%q: %s", e.Name, e.Op.String())
-}
diff --git a/vendor/github.com/fsnotify/fsnotify/fsnotify_test.go b/vendor/github.com/fsnotify/fsnotify/fsnotify_test.go
deleted file mode 100644
index 9d6d72a..0000000
--- a/vendor/github.com/fsnotify/fsnotify/fsnotify_test.go
+++ /dev/null
@@ -1,40 +0,0 @@
-// 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.
-
-// +build !plan9
-
-package fsnotify
-
-import "testing"
-
-func TestEventStringWithValue(t *testing.T) {
- for opMask, expectedString := range map[Op]string{
- Chmod | Create: `"/usr/someFile": CREATE|CHMOD`,
- Rename: `"/usr/someFile": RENAME`,
- Remove: `"/usr/someFile": REMOVE`,
- Write | Chmod: `"/usr/someFile": WRITE|CHMOD`,
- } {
- event := Event{Name: "/usr/someFile", Op: opMask}
- if event.String() != expectedString {
- t.Fatalf("Expected %s, got: %v", expectedString, event.String())
- }
-
- }
-}
-
-func TestEventOpStringWithValue(t *testing.T) {
- expectedOpString := "WRITE|CHMOD"
- event := Event{Name: "someFile", Op: Write | Chmod}
- if event.Op.String() != expectedOpString {
- t.Fatalf("Expected %s, got: %v", expectedOpString, event.Op.String())
- }
-}
-
-func TestEventOpStringWithNoValue(t *testing.T) {
- expectedOpString := ""
- event := Event{Name: "testFile", Op: 0}
- if event.Op.String() != expectedOpString {
- t.Fatalf("Expected %s, got: %v", expectedOpString, event.Op.String())
- }
-}
diff --git a/vendor/github.com/fsnotify/fsnotify/inotify.go b/vendor/github.com/fsnotify/fsnotify/inotify.go
deleted file mode 100644
index f3b74c5..0000000
--- a/vendor/github.com/fsnotify/fsnotify/inotify.go
+++ /dev/null
@@ -1,325 +0,0 @@
-// Copyright 2010 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.
-
-// +build linux
-
-package fsnotify
-
-import (
- "errors"
- "fmt"
- "io"
- "os"
- "path/filepath"
- "strings"
- "sync"
- "unsafe"
-
- "golang.org/x/sys/unix"
-)
-
-// Watcher watches a set of files, delivering events to a channel.
-type Watcher struct {
- Events chan Event
- Errors chan error
- mu sync.Mutex // Map access
- cv *sync.Cond // sync removing on rm_watch with IN_IGNORE
- fd int
- poller *fdPoller
- watches map[string]*watch // Map of inotify watches (key: path)
- paths map[int]string // Map of watched paths (key: watch descriptor)
- done chan struct{} // Channel for sending a "quit message" to the reader goroutine
- doneResp chan struct{} // Channel to respond to Close
-}
-
-// NewWatcher establishes a new watcher with the underlying OS and begins waiting for events.
-func NewWatcher() (*Watcher, error) {
- // Create inotify fd
- fd, errno := unix.InotifyInit1(unix.IN_CLOEXEC)
- if fd == -1 {
- return nil, errno
- }
- // Create epoll
- poller, err := newFdPoller(fd)
- if err != nil {
- unix.Close(fd)
- return nil, err
- }
- w := &Watcher{
- fd: fd,
- poller: poller,
- watches: make(map[string]*watch),
- paths: make(map[int]string),
- Events: make(chan Event),
- Errors: make(chan error),
- done: make(chan struct{}),
- doneResp: make(chan struct{}),
- }
- w.cv = sync.NewCond(&w.mu)
-
- go w.readEvents()
- return w, nil
-}
-
-func (w *Watcher) isClosed() bool {
- select {
- case <-w.done:
- return true
- default:
- return false
- }
-}
-
-// Close removes all watches and closes the events channel.
-func (w *Watcher) Close() error {
- if w.isClosed() {
- return nil
- }
-
- // Send 'close' signal to goroutine, and set the Watcher to closed.
- close(w.done)
-
- // Wake up goroutine
- w.poller.wake()
-
- // Wait for goroutine to close
- <-w.doneResp
-
- return nil
-}
-
-// Add starts watching the named file or directory (non-recursively).
-func (w *Watcher) Add(name string) error {
- name = filepath.Clean(name)
- if w.isClosed() {
- return errors.New("inotify instance already closed")
- }
-
- const agnosticEvents = unix.IN_MOVED_TO | unix.IN_MOVED_FROM |
- unix.IN_CREATE | unix.IN_ATTRIB | unix.IN_MODIFY |
- unix.IN_MOVE_SELF | unix.IN_DELETE | unix.IN_DELETE_SELF
-
- var flags uint32 = agnosticEvents
-
- w.mu.Lock()
- watchEntry, found := w.watches[name]
- w.mu.Unlock()
- if found {
- watchEntry.flags |= flags
- flags |= unix.IN_MASK_ADD
- }
- wd, errno := unix.InotifyAddWatch(w.fd, name, flags)
- if wd == -1 {
- return errno
- }
-
- w.mu.Lock()
- w.watches[name] = &watch{wd: uint32(wd), flags: flags}
- w.paths[wd] = name
- w.mu.Unlock()
-
- return nil
-}
-
-// Remove stops watching the named file or directory (non-recursively).
-func (w *Watcher) Remove(name string) error {
- name = filepath.Clean(name)
-
- // Fetch the watch.
- w.mu.Lock()
- defer w.mu.Unlock()
- watch, ok := w.watches[name]
-
- // Remove it from inotify.
- if !ok {
- return fmt.Errorf("can't remove non-existent inotify watch for: %s", name)
- }
- // inotify_rm_watch will return EINVAL if the file has been deleted;
- // the inotify will already have been removed.
- // watches and pathes are deleted in ignoreLinux() implicitly and asynchronously
- // by calling inotify_rm_watch() below. e.g. readEvents() goroutine receives IN_IGNORE
- // so that EINVAL means that the wd is being rm_watch()ed or its file removed
- // by another thread and we have not received IN_IGNORE event.
- success, errno := unix.InotifyRmWatch(w.fd, watch.wd)
- if success == -1 {
- // TODO: Perhaps it's not helpful to return an error here in every case.
- // the only two possible errors are:
- // EBADF, which happens when w.fd is not a valid file descriptor of any kind.
- // EINVAL, which is when fd is not an inotify descriptor or wd is not a valid watch descriptor.
- // Watch descriptors are invalidated when they are removed explicitly or implicitly;
- // explicitly by inotify_rm_watch, implicitly when the file they are watching is deleted.
- return errno
- }
-
- // wait until ignoreLinux() deleting maps
- exists := true
- for exists {
- w.cv.Wait()
- _, exists = w.watches[name]
- }
-
- return nil
-}
-
-type watch struct {
- wd uint32 // Watch descriptor (as returned by the inotify_add_watch() syscall)
- flags uint32 // inotify flags of this watch (see inotify(7) for the list of valid flags)
-}
-
-// readEvents reads from the inotify file descriptor, converts the
-// received events into Event objects and sends them via the Events channel
-func (w *Watcher) readEvents() {
- var (
- buf [unix.SizeofInotifyEvent * 4096]byte // Buffer for a maximum of 4096 raw events
- n int // Number of bytes read with read()
- errno error // Syscall errno
- ok bool // For poller.wait
- )
-
- defer close(w.doneResp)
- defer close(w.Errors)
- defer close(w.Events)
- defer unix.Close(w.fd)
- defer w.poller.close()
-
- for {
- // See if we have been closed.
- if w.isClosed() {
- return
- }
-
- ok, errno = w.poller.wait()
- if errno != nil {
- select {
- case w.Errors <- errno:
- case <-w.done:
- return
- }
- continue
- }
-
- if !ok {
- continue
- }
-
- n, errno = unix.Read(w.fd, buf[:])
- // If a signal interrupted execution, see if we've been asked to close, and try again.
- // http://man7.org/linux/man-pages/man7/signal.7.html :
- // "Before Linux 3.8, reads from an inotify(7) file descriptor were not restartable"
- if errno == unix.EINTR {
- continue
- }
-
- // unix.Read might have been woken up by Close. If so, we're done.
- if w.isClosed() {
- return
- }
-
- if n < unix.SizeofInotifyEvent {
- var err error
- if n == 0 {
- // If EOF is received. This should really never happen.
- err = io.EOF
- } else if n < 0 {
- // If an error occurred while reading.
- err = errno
- } else {
- // Read was too short.
- err = errors.New("notify: short read in readEvents()")
- }
- select {
- case w.Errors <- err:
- case <-w.done:
- return
- }
- continue
- }
-
- var offset uint32
- // We don't know how many events we just read into the buffer
- // While the offset points to at least one whole event...
- for offset <= uint32(n-unix.SizeofInotifyEvent) {
- // Point "raw" to the event in the buffer
- raw := (*unix.InotifyEvent)(unsafe.Pointer(&buf[offset]))
-
- mask := uint32(raw.Mask)
- nameLen := uint32(raw.Len)
- // If the event happened to the watched directory or the watched file, the kernel
- // doesn't append the filename to the event, but we would like to always fill the
- // the "Name" field with a valid filename. We retrieve the path of the watch from
- // the "paths" map.
- w.mu.Lock()
- name := w.paths[int(raw.Wd)]
- w.mu.Unlock()
- if nameLen > 0 {
- // Point "bytes" at the first byte of the filename
- bytes := (*[unix.PathMax]byte)(unsafe.Pointer(&buf[offset+unix.SizeofInotifyEvent]))
- // The filename is padded with NULL bytes. TrimRight() gets rid of those.
- name += "/" + strings.TrimRight(string(bytes[0:nameLen]), "\000")
- }
-
- event := newEvent(name, mask)
-
- // Send the events that are not ignored on the events channel
- if !event.ignoreLinux(w, raw.Wd, mask) {
- select {
- case w.Events <- event:
- case <-w.done:
- return
- }
- }
-
- // Move to the next event in the buffer
- offset += unix.SizeofInotifyEvent + nameLen
- }
- }
-}
-
-// Certain types of events can be "ignored" and not sent over the Events
-// channel. Such as events marked ignore by the kernel, or MODIFY events
-// against files that do not exist.
-func (e *Event) ignoreLinux(w *Watcher, wd int32, mask uint32) bool {
- // Ignore anything the inotify API says to ignore
- if mask&unix.IN_IGNORED == unix.IN_IGNORED {
- w.mu.Lock()
- defer w.mu.Unlock()
- name := w.paths[int(wd)]
- delete(w.paths, int(wd))
- delete(w.watches, name)
- w.cv.Broadcast()
- return true
- }
-
- // If the event is not a DELETE or RENAME, the file must exist.
- // Otherwise the event is ignored.
- // *Note*: this was put in place because it was seen that a MODIFY
- // event was sent after the DELETE. This ignores that MODIFY and
- // assumes a DELETE will come or has come if the file doesn't exist.
- if !(e.Op&Remove == Remove || e.Op&Rename == Rename) {
- _, statErr := os.Lstat(e.Name)
- return os.IsNotExist(statErr)
- }
- return false
-}
-
-// newEvent returns an platform-independent Event based on an inotify mask.
-func newEvent(name string, mask uint32) Event {
- e := Event{Name: name}
- if mask&unix.IN_CREATE == unix.IN_CREATE || mask&unix.IN_MOVED_TO == unix.IN_MOVED_TO {
- e.Op |= Create
- }
- if mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF || mask&unix.IN_DELETE == unix.IN_DELETE {
- e.Op |= Remove
- }
- if mask&unix.IN_MODIFY == unix.IN_MODIFY {
- e.Op |= Write
- }
- if mask&unix.IN_MOVE_SELF == unix.IN_MOVE_SELF || mask&unix.IN_MOVED_FROM == unix.IN_MOVED_FROM {
- e.Op |= Rename
- }
- if mask&unix.IN_ATTRIB == unix.IN_ATTRIB {
- e.Op |= Chmod
- }
- return e
-}
diff --git a/vendor/github.com/fsnotify/fsnotify/inotify_poller.go b/vendor/github.com/fsnotify/fsnotify/inotify_poller.go
deleted file mode 100644
index cc7db4b..0000000
--- a/vendor/github.com/fsnotify/fsnotify/inotify_poller.go
+++ /dev/null
@@ -1,187 +0,0 @@
-// Copyright 2015 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.
-
-// +build linux
-
-package fsnotify
-
-import (
- "errors"
-
- "golang.org/x/sys/unix"
-)
-
-type fdPoller struct {
- fd int // File descriptor (as returned by the inotify_init() syscall)
- epfd int // Epoll file descriptor
- pipe [2]int // Pipe for waking up
-}
-
-func emptyPoller(fd int) *fdPoller {
- poller := new(fdPoller)
- poller.fd = fd
- poller.epfd = -1
- poller.pipe[0] = -1
- poller.pipe[1] = -1
- return poller
-}
-
-// Create a new inotify poller.
-// This creates an inotify handler, and an epoll handler.
-func newFdPoller(fd int) (*fdPoller, error) {
- var errno error
- poller := emptyPoller(fd)
- defer func() {
- if errno != nil {
- poller.close()
- }
- }()
- poller.fd = fd
-
- // Create epoll fd
- poller.epfd, errno = unix.EpollCreate1(0)
- if poller.epfd == -1 {
- return nil, errno
- }
- // Create pipe; pipe[0] is the read end, pipe[1] the write end.
- errno = unix.Pipe2(poller.pipe[:], unix.O_NONBLOCK)
- if errno != nil {
- return nil, errno
- }
-
- // Register inotify fd with epoll
- event := unix.EpollEvent{
- Fd: int32(poller.fd),
- Events: unix.EPOLLIN,
- }
- errno = unix.EpollCtl(poller.epfd, unix.EPOLL_CTL_ADD, poller.fd, &event)
- if errno != nil {
- return nil, errno
- }
-
- // Register pipe fd with epoll
- event = unix.EpollEvent{
- Fd: int32(poller.pipe[0]),
- Events: unix.EPOLLIN,
- }
- errno = unix.EpollCtl(poller.epfd, unix.EPOLL_CTL_ADD, poller.pipe[0], &event)
- if errno != nil {
- return nil, errno
- }
-
- return poller, nil
-}
-
-// Wait using epoll.
-// Returns true if something is ready to be read,
-// false if there is not.
-func (poller *fdPoller) wait() (bool, error) {
- // 3 possible events per fd, and 2 fds, makes a maximum of 6 events.
- // I don't know whether epoll_wait returns the number of events returned,
- // or the total number of events ready.
- // I decided to catch both by making the buffer one larger than the maximum.
- events := make([]unix.EpollEvent, 7)
- for {
- n, errno := unix.EpollWait(poller.epfd, events, -1)
- if n == -1 {
- if errno == unix.EINTR {
- continue
- }
- return false, errno
- }
- if n == 0 {
- // If there are no events, try again.
- continue
- }
- if n > 6 {
- // This should never happen. More events were returned than should be possible.
- return false, errors.New("epoll_wait returned more events than I know what to do with")
- }
- ready := events[:n]
- epollhup := false
- epollerr := false
- epollin := false
- for _, event := range ready {
- if event.Fd == int32(poller.fd) {
- if event.Events&unix.EPOLLHUP != 0 {
- // This should not happen, but if it does, treat it as a wakeup.
- epollhup = true
- }
- if event.Events&unix.EPOLLERR != 0 {
- // If an error is waiting on the file descriptor, we should pretend
- // something is ready to read, and let unix.Read pick up the error.
- epollerr = true
- }
- if event.Events&unix.EPOLLIN != 0 {
- // There is data to read.
- epollin = true
- }
- }
- if event.Fd == int32(poller.pipe[0]) {
- if event.Events&unix.EPOLLHUP != 0 {
- // Write pipe descriptor was closed, by us. This means we're closing down the
- // watcher, and we should wake up.
- }
- if event.Events&unix.EPOLLERR != 0 {
- // If an error is waiting on the pipe file descriptor.
- // This is an absolute mystery, and should never ever happen.
- return false, errors.New("Error on the pipe descriptor.")
- }
- if event.Events&unix.EPOLLIN != 0 {
- // This is a regular wakeup, so we have to clear the buffer.
- err := poller.clearWake()
- if err != nil {
- return false, err
- }
- }
- }
- }
-
- if epollhup || epollerr || epollin {
- return true, nil
- }
- return false, nil
- }
-}
-
-// Close the write end of the poller.
-func (poller *fdPoller) wake() error {
- buf := make([]byte, 1)
- n, errno := unix.Write(poller.pipe[1], buf)
- if n == -1 {
- if errno == unix.EAGAIN {
- // Buffer is full, poller will wake.
- return nil
- }
- return errno
- }
- return nil
-}
-
-func (poller *fdPoller) clearWake() error {
- // You have to be woken up a LOT in order to get to 100!
- buf := make([]byte, 100)
- n, errno := unix.Read(poller.pipe[0], buf)
- if n == -1 {
- if errno == unix.EAGAIN {
- // Buffer is empty, someone else cleared our wake.
- return nil
- }
- return errno
- }
- return nil
-}
-
-// Close all poller file descriptors, but not the one passed to it.
-func (poller *fdPoller) close() {
- if poller.pipe[1] != -1 {
- unix.Close(poller.pipe[1])
- }
- if poller.pipe[0] != -1 {
- unix.Close(poller.pipe[0])
- }
- if poller.epfd != -1 {
- unix.Close(poller.epfd)
- }
-}
diff --git a/vendor/github.com/fsnotify/fsnotify/inotify_poller_test.go b/vendor/github.com/fsnotify/fsnotify/inotify_poller_test.go
deleted file mode 100644
index 26623ef..0000000
--- a/vendor/github.com/fsnotify/fsnotify/inotify_poller_test.go
+++ /dev/null
@@ -1,229 +0,0 @@
-// Copyright 2015 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.
-
-// +build linux
-
-package fsnotify
-
-import (
- "testing"
- "time"
-
- "golang.org/x/sys/unix"
-)
-
-type testFd [2]int
-
-func makeTestFd(t *testing.T) testFd {
- var tfd testFd
- errno := unix.Pipe(tfd[:])
- if errno != nil {
- t.Fatalf("Failed to create pipe: %v", errno)
- }
- return tfd
-}
-
-func (tfd testFd) fd() int {
- return tfd[0]
-}
-
-func (tfd testFd) closeWrite(t *testing.T) {
- errno := unix.Close(tfd[1])
- if errno != nil {
- t.Fatalf("Failed to close write end of pipe: %v", errno)
- }
-}
-
-func (tfd testFd) put(t *testing.T) {
- buf := make([]byte, 10)
- _, errno := unix.Write(tfd[1], buf)
- if errno != nil {
- t.Fatalf("Failed to write to pipe: %v", errno)
- }
-}
-
-func (tfd testFd) get(t *testing.T) {
- buf := make([]byte, 10)
- _, errno := unix.Read(tfd[0], buf)
- if errno != nil {
- t.Fatalf("Failed to read from pipe: %v", errno)
- }
-}
-
-func (tfd testFd) close() {
- unix.Close(tfd[1])
- unix.Close(tfd[0])
-}
-
-func makePoller(t *testing.T) (testFd, *fdPoller) {
- tfd := makeTestFd(t)
- poller, err := newFdPoller(tfd.fd())
- if err != nil {
- t.Fatalf("Failed to create poller: %v", err)
- }
- return tfd, poller
-}
-
-func TestPollerWithBadFd(t *testing.T) {
- _, err := newFdPoller(-1)
- if err != unix.EBADF {
- t.Fatalf("Expected EBADF, got: %v", err)
- }
-}
-
-func TestPollerWithData(t *testing.T) {
- tfd, poller := makePoller(t)
- defer tfd.close()
- defer poller.close()
-
- tfd.put(t)
- ok, err := poller.wait()
- if err != nil {
- t.Fatalf("poller failed: %v", err)
- }
- if !ok {
- t.Fatalf("expected poller to return true")
- }
- tfd.get(t)
-}
-
-func TestPollerWithWakeup(t *testing.T) {
- tfd, poller := makePoller(t)
- defer tfd.close()
- defer poller.close()
-
- err := poller.wake()
- if err != nil {
- t.Fatalf("wake failed: %v", err)
- }
- ok, err := poller.wait()
- if err != nil {
- t.Fatalf("poller failed: %v", err)
- }
- if ok {
- t.Fatalf("expected poller to return false")
- }
-}
-
-func TestPollerWithClose(t *testing.T) {
- tfd, poller := makePoller(t)
- defer tfd.close()
- defer poller.close()
-
- tfd.closeWrite(t)
- ok, err := poller.wait()
- if err != nil {
- t.Fatalf("poller failed: %v", err)
- }
- if !ok {
- t.Fatalf("expected poller to return true")
- }
-}
-
-func TestPollerWithWakeupAndData(t *testing.T) {
- tfd, poller := makePoller(t)
- defer tfd.close()
- defer poller.close()
-
- tfd.put(t)
- err := poller.wake()
- if err != nil {
- t.Fatalf("wake failed: %v", err)
- }
-
- // both data and wakeup
- ok, err := poller.wait()
- if err != nil {
- t.Fatalf("poller failed: %v", err)
- }
- if !ok {
- t.Fatalf("expected poller to return true")
- }
-
- // data is still in the buffer, wakeup is cleared
- ok, err = poller.wait()
- if err != nil {
- t.Fatalf("poller failed: %v", err)
- }
- if !ok {
- t.Fatalf("expected poller to return true")
- }
-
- tfd.get(t)
- // data is gone, only wakeup now
- err = poller.wake()
- if err != nil {
- t.Fatalf("wake failed: %v", err)
- }
- ok, err = poller.wait()
- if err != nil {
- t.Fatalf("poller failed: %v", err)
- }
- if ok {
- t.Fatalf("expected poller to return false")
- }
-}
-
-func TestPollerConcurrent(t *testing.T) {
- tfd, poller := makePoller(t)
- defer tfd.close()
- defer poller.close()
-
- oks := make(chan bool)
- live := make(chan bool)
- defer close(live)
- go func() {
- defer close(oks)
- for {
- ok, err := poller.wait()
- if err != nil {
- t.Fatalf("poller failed: %v", err)
- }
- oks <- ok
- if !<-live {
- return
- }
- }
- }()
-
- // Try a write
- select {
- case <-time.After(50 * time.Millisecond):
- case <-oks:
- t.Fatalf("poller did not wait")
- }
- tfd.put(t)
- if !<-oks {
- t.Fatalf("expected true")
- }
- tfd.get(t)
- live <- true
-
- // Try a wakeup
- select {
- case <-time.After(50 * time.Millisecond):
- case <-oks:
- t.Fatalf("poller did not wait")
- }
- err := poller.wake()
- if err != nil {
- t.Fatalf("wake failed: %v", err)
- }
- if <-oks {
- t.Fatalf("expected false")
- }
- live <- true
-
- // Try a close
- select {
- case <-time.After(50 * time.Millisecond):
- case <-oks:
- t.Fatalf("poller did not wait")
- }
- tfd.closeWrite(t)
- if !<-oks {
- t.Fatalf("expected true")
- }
- tfd.get(t)
-}
diff --git a/vendor/github.com/fsnotify/fsnotify/inotify_test.go b/vendor/github.com/fsnotify/fsnotify/inotify_test.go
deleted file mode 100644
index a4bb202..0000000
--- a/vendor/github.com/fsnotify/fsnotify/inotify_test.go
+++ /dev/null
@@ -1,360 +0,0 @@
-// Copyright 2015 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.
-
-// +build linux
-
-package fsnotify
-
-import (
- "fmt"
- "os"
- "path/filepath"
- "strings"
- "testing"
- "time"
-)
-
-func TestInotifyCloseRightAway(t *testing.T) {
- w, err := NewWatcher()
- if err != nil {
- t.Fatalf("Failed to create watcher")
- }
-
- // Close immediately; it won't even reach the first unix.Read.
- w.Close()
-
- // Wait for the close to complete.
- <-time.After(50 * time.Millisecond)
- isWatcherReallyClosed(t, w)
-}
-
-func TestInotifyCloseSlightlyLater(t *testing.T) {
- w, err := NewWatcher()
- if err != nil {
- t.Fatalf("Failed to create watcher")
- }
-
- // Wait until readEvents has reached unix.Read, and Close.
- <-time.After(50 * time.Millisecond)
- w.Close()
-
- // Wait for the close to complete.
- <-time.After(50 * time.Millisecond)
- isWatcherReallyClosed(t, w)
-}
-
-func TestInotifyCloseSlightlyLaterWithWatch(t *testing.T) {
- testDir := tempMkdir(t)
- defer os.RemoveAll(testDir)
-
- w, err := NewWatcher()
- if err != nil {
- t.Fatalf("Failed to create watcher")
- }
- w.Add(testDir)
-
- // Wait until readEvents has reached unix.Read, and Close.
- <-time.After(50 * time.Millisecond)
- w.Close()
-
- // Wait for the close to complete.
- <-time.After(50 * time.Millisecond)
- isWatcherReallyClosed(t, w)
-}
-
-func TestInotifyCloseAfterRead(t *testing.T) {
- testDir := tempMkdir(t)
- defer os.RemoveAll(testDir)
-
- w, err := NewWatcher()
- if err != nil {
- t.Fatalf("Failed to create watcher")
- }
-
- err = w.Add(testDir)
- if err != nil {
- t.Fatalf("Failed to add .")
- }
-
- // Generate an event.
- os.Create(filepath.Join(testDir, "somethingSOMETHINGsomethingSOMETHING"))
-
- // Wait for readEvents to read the event, then close the watcher.
- <-time.After(50 * time.Millisecond)
- w.Close()
-
- // Wait for the close to complete.
- <-time.After(50 * time.Millisecond)
- isWatcherReallyClosed(t, w)
-}
-
-func isWatcherReallyClosed(t *testing.T, w *Watcher) {
- select {
- case err, ok := <-w.Errors:
- if ok {
- t.Fatalf("w.Errors is not closed; readEvents is still alive after closing (error: %v)", err)
- }
- default:
- t.Fatalf("w.Errors would have blocked; readEvents is still alive!")
- }
-
- select {
- case _, ok := <-w.Events:
- if ok {
- t.Fatalf("w.Events is not closed; readEvents is still alive after closing")
- }
- default:
- t.Fatalf("w.Events would have blocked; readEvents is still alive!")
- }
-}
-
-func TestInotifyCloseCreate(t *testing.T) {
- testDir := tempMkdir(t)
- defer os.RemoveAll(testDir)
-
- w, err := NewWatcher()
- if err != nil {
- t.Fatalf("Failed to create watcher: %v", err)
- }
- defer w.Close()
-
- err = w.Add(testDir)
- if err != nil {
- t.Fatalf("Failed to add testDir: %v", err)
- }
- h, err := os.Create(filepath.Join(testDir, "testfile"))
- if err != nil {
- t.Fatalf("Failed to create file in testdir: %v", err)
- }
- h.Close()
- select {
- case _ = <-w.Events:
- case err := <-w.Errors:
- t.Fatalf("Error from watcher: %v", err)
- case <-time.After(50 * time.Millisecond):
- t.Fatalf("Took too long to wait for event")
- }
-
- // At this point, we've received one event, so the goroutine is ready.
- // It's also blocking on unix.Read.
- // Now we try to swap the file descriptor under its nose.
- w.Close()
- w, err = NewWatcher()
- defer w.Close()
- if err != nil {
- t.Fatalf("Failed to create second watcher: %v", err)
- }
-
- <-time.After(50 * time.Millisecond)
- err = w.Add(testDir)
- if err != nil {
- t.Fatalf("Error adding testDir again: %v", err)
- }
-}
-
-// This test verifies the watcher can keep up with file creations/deletions
-// when under load.
-func TestInotifyStress(t *testing.T) {
- maxNumToCreate := 1000
-
- testDir := tempMkdir(t)
- defer os.RemoveAll(testDir)
- testFilePrefix := filepath.Join(testDir, "testfile")
-
- w, err := NewWatcher()
- if err != nil {
- t.Fatalf("Failed to create watcher: %v", err)
- }
- defer w.Close()
-
- err = w.Add(testDir)
- if err != nil {
- t.Fatalf("Failed to add testDir: %v", err)
- }
-
- doneChan := make(chan struct{})
- // The buffer ensures that the file generation goroutine is never blocked.
- errChan := make(chan error, 2*maxNumToCreate)
-
- go func() {
- for i := 0; i < maxNumToCreate; i++ {
- testFile := fmt.Sprintf("%s%d", testFilePrefix, i)
-
- handle, err := os.Create(testFile)
- if err != nil {
- errChan <- fmt.Errorf("Create failed: %v", err)
- continue
- }
-
- err = handle.Close()
- if err != nil {
- errChan <- fmt.Errorf("Close failed: %v", err)
- continue
- }
- }
-
- // If we delete a newly created file too quickly, inotify will skip the
- // create event and only send the delete event.
- time.Sleep(100 * time.Millisecond)
-
- for i := 0; i < maxNumToCreate; i++ {
- testFile := fmt.Sprintf("%s%d", testFilePrefix, i)
- err = os.Remove(testFile)
- if err != nil {
- errChan <- fmt.Errorf("Remove failed: %v", err)
- }
- }
-
- close(doneChan)
- }()
-
- creates := 0
- removes := 0
-
- finished := false
- after := time.After(10 * time.Second)
- for !finished {
- select {
- case <-after:
- t.Fatalf("Not done")
- case <-doneChan:
- finished = true
- case err := <-errChan:
- t.Fatalf("Got an error from file creator goroutine: %v", err)
- case err := <-w.Errors:
- t.Fatalf("Got an error from watcher: %v", err)
- case evt := <-w.Events:
- if !strings.HasPrefix(evt.Name, testFilePrefix) {
- t.Fatalf("Got an event for an unknown file: %s", evt.Name)
- }
- if evt.Op == Create {
- creates++
- }
- if evt.Op == Remove {
- removes++
- }
- }
- }
-
- // Drain remaining events from channels
- count := 0
- for count < 10 {
- select {
- case err := <-errChan:
- t.Fatalf("Got an error from file creator goroutine: %v", err)
- case err := <-w.Errors:
- t.Fatalf("Got an error from watcher: %v", err)
- case evt := <-w.Events:
- if !strings.HasPrefix(evt.Name, testFilePrefix) {
- t.Fatalf("Got an event for an unknown file: %s", evt.Name)
- }
- if evt.Op == Create {
- creates++
- }
- if evt.Op == Remove {
- removes++
- }
- count = 0
- default:
- count++
- // Give the watcher chances to fill the channels.
- time.Sleep(time.Millisecond)
- }
- }
-
- if creates-removes > 1 || creates-removes < -1 {
- t.Fatalf("Creates and removes should not be off by more than one: %d creates, %d removes", creates, removes)
- }
- if creates < 50 {
- t.Fatalf("Expected at least 50 creates, got %d", creates)
- }
-}
-
-func TestInotifyRemoveTwice(t *testing.T) {
- testDir := tempMkdir(t)
- defer os.RemoveAll(testDir)
- testFile := filepath.Join(testDir, "testfile")
-
- handle, err := os.Create(testFile)
- if err != nil {
- t.Fatalf("Create failed: %v", err)
- }
- handle.Close()
-
- w, err := NewWatcher()
- if err != nil {
- t.Fatalf("Failed to create watcher: %v", err)
- }
- defer w.Close()
-
- err = w.Add(testFile)
- if err != nil {
- t.Fatalf("Failed to add testFile: %v", err)
- }
-
- err = os.Remove(testFile)
- if err != nil {
- t.Fatalf("Failed to remove testFile: %v", err)
- }
-
- err = w.Remove(testFile)
- if err == nil {
- t.Fatalf("no error on removing invalid file")
- }
- s1 := fmt.Sprintf("%s", err)
-
- err = w.Remove(testFile)
- if err == nil {
- t.Fatalf("no error on removing invalid file")
- }
- s2 := fmt.Sprintf("%s", err)
-
- if s1 != s2 {
- t.Fatalf("receive different error - %s / %s", s1, s2)
- }
-}
-
-func TestInotifyInnerMapLength(t *testing.T) {
- testDir := tempMkdir(t)
- defer os.RemoveAll(testDir)
- testFile := filepath.Join(testDir, "testfile")
-
- handle, err := os.Create(testFile)
- if err != nil {
- t.Fatalf("Create failed: %v", err)
- }
- handle.Close()
-
- w, err := NewWatcher()
- if err != nil {
- t.Fatalf("Failed to create watcher: %v", err)
- }
- defer w.Close()
-
- err = w.Add(testFile)
- if err != nil {
- t.Fatalf("Failed to add testFile: %v", err)
- }
- go func() {
- for err := range w.Errors {
- t.Fatalf("error received: %s", err)
- }
- }()
-
- err = os.Remove(testFile)
- if err != nil {
- t.Fatalf("Failed to remove testFile: %v", err)
- }
- _ = <-w.Events // consume Remove event
- <-time.After(50 * time.Millisecond) // wait IN_IGNORE propagated
-
- w.mu.Lock()
- defer w.mu.Unlock()
- if len(w.watches) != 0 {
- t.Fatalf("Expected watches len is 0, but got: %d, %v", len(w.watches), w.watches)
- }
- if len(w.paths) != 0 {
- t.Fatalf("Expected paths len is 0, but got: %d, %v", len(w.paths), w.paths)
- }
-}
diff --git a/vendor/github.com/fsnotify/fsnotify/integration_darwin_test.go b/vendor/github.com/fsnotify/fsnotify/integration_darwin_test.go
deleted file mode 100644
index 5564554..0000000
--- a/vendor/github.com/fsnotify/fsnotify/integration_darwin_test.go
+++ /dev/null
@@ -1,147 +0,0 @@
-// 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 fsnotify
-
-import (
- "os"
- "path/filepath"
- "testing"
- "time"
-
- "golang.org/x/sys/unix"
-)
-
-// testExchangedataForWatcher tests the watcher with the exchangedata operation on OS X.
-//
-// This is widely used for atomic saves on OS X, e.g. TextMate and in Apple's NSDocument.
-//
-// See https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man2/exchangedata.2.html
-// Also see: https://github.com/textmate/textmate/blob/cd016be29489eba5f3c09b7b70b06da134dda550/Frameworks/io/src/swap_file_data.cc#L20
-func testExchangedataForWatcher(t *testing.T, watchDir bool) {
- // Create directory to watch
- testDir1 := tempMkdir(t)
-
- // For the intermediate file
- testDir2 := tempMkdir(t)
-
- defer os.RemoveAll(testDir1)
- defer os.RemoveAll(testDir2)
-
- resolvedFilename := "TestFsnotifyEvents.file"
-
- // TextMate does:
- //
- // 1. exchangedata (intermediate, resolved)
- // 2. unlink intermediate
- //
- // Let's try to simulate that:
- resolved := filepath.Join(testDir1, resolvedFilename)
- intermediate := filepath.Join(testDir2, resolvedFilename+"~")
-
- // Make sure we create the file before we start watching
- createAndSyncFile(t, resolved)
-
- watcher := newWatcher(t)
-
- // Test both variants in isolation
- if watchDir {
- addWatch(t, watcher, testDir1)
- } else {
- addWatch(t, watcher, resolved)
- }
-
- // Receive errors on the error channel on a separate goroutine
- go func() {
- for err := range watcher.Errors {
- t.Fatalf("error received: %s", err)
- }
- }()
-
- // Receive events on the event channel on a separate goroutine
- eventstream := watcher.Events
- var removeReceived counter
- var createReceived counter
-
- done := make(chan bool)
-
- go func() {
- for event := range eventstream {
- // Only count relevant events
- if event.Name == filepath.Clean(resolved) {
- if event.Op&Remove == Remove {
- removeReceived.increment()
- }
- if event.Op&Create == Create {
- createReceived.increment()
- }
- }
- t.Logf("event received: %s", event)
- }
- done <- true
- }()
-
- // Repeat to make sure the watched file/directory "survives" the REMOVE/CREATE loop.
- for i := 1; i <= 3; i++ {
- // The intermediate file is created in a folder outside the watcher
- createAndSyncFile(t, intermediate)
-
- // 1. Swap
- if err := unix.Exchangedata(intermediate, resolved, 0); err != nil {
- t.Fatalf("[%d] exchangedata failed: %s", i, err)
- }
-
- time.Sleep(50 * time.Millisecond)
-
- // 2. Delete the intermediate file
- err := os.Remove(intermediate)
-
- if err != nil {
- t.Fatalf("[%d] remove %s failed: %s", i, intermediate, err)
- }
-
- time.Sleep(50 * time.Millisecond)
-
- }
-
- // We expect this event to be received almost immediately, but let's wait 500 ms to be sure
- time.Sleep(500 * time.Millisecond)
-
- // The events will be (CHMOD + REMOVE + CREATE) X 2. Let's focus on the last two:
- if removeReceived.value() < 3 {
- t.Fatal("fsnotify remove events have not been received after 500 ms")
- }
-
- if createReceived.value() < 3 {
- t.Fatal("fsnotify create events have not been received after 500 ms")
- }
-
- watcher.Close()
- t.Log("waiting for the event channel to become closed...")
- select {
- case <-done:
- t.Log("event channel closed")
- case <-time.After(2 * time.Second):
- t.Fatal("event stream was not closed after 2 seconds")
- }
-}
-
-// TestExchangedataInWatchedDir test exchangedata operation on file in watched dir.
-func TestExchangedataInWatchedDir(t *testing.T) {
- testExchangedataForWatcher(t, true)
-}
-
-// TestExchangedataInWatchedDir test exchangedata operation on watched file.
-func TestExchangedataInWatchedFile(t *testing.T) {
- testExchangedataForWatcher(t, false)
-}
-
-func createAndSyncFile(t *testing.T, filepath string) {
- f1, err := os.OpenFile(filepath, os.O_WRONLY|os.O_CREATE, 0666)
- if err != nil {
- t.Fatalf("creating %s failed: %s", filepath, err)
- }
- f1.Sync()
- f1.Close()
-}
diff --git a/vendor/github.com/fsnotify/fsnotify/integration_test.go b/vendor/github.com/fsnotify/fsnotify/integration_test.go
deleted file mode 100644
index 8b7e9d3..0000000
--- a/vendor/github.com/fsnotify/fsnotify/integration_test.go
+++ /dev/null
@@ -1,1237 +0,0 @@
-// Copyright 2010 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.
-
-// +build !plan9,!solaris
-
-package fsnotify
-
-import (
- "io/ioutil"
- "os"
- "os/exec"
- "path"
- "path/filepath"
- "runtime"
- "sync/atomic"
- "testing"
- "time"
-)
-
-// An atomic counter
-type counter struct {
- val int32
-}
-
-func (c *counter) increment() {
- atomic.AddInt32(&c.val, 1)
-}
-
-func (c *counter) value() int32 {
- return atomic.LoadInt32(&c.val)
-}
-
-func (c *counter) reset() {
- atomic.StoreInt32(&c.val, 0)
-}
-
-// tempMkdir makes a temporary directory
-func tempMkdir(t *testing.T) string {
- dir, err := ioutil.TempDir("", "fsnotify")
- if err != nil {
- t.Fatalf("failed to create test directory: %s", err)
- }
- return dir
-}
-
-// tempMkFile makes a temporary file.
-func tempMkFile(t *testing.T, dir string) string {
- f, err := ioutil.TempFile(dir, "fsnotify")
- if err != nil {
- t.Fatalf("failed to create test file: %v", err)
- }
- defer f.Close()
- return f.Name()
-}
-
-// newWatcher initializes an fsnotify Watcher instance.
-func newWatcher(t *testing.T) *Watcher {
- watcher, err := NewWatcher()
- if err != nil {
- t.Fatalf("NewWatcher() failed: %s", err)
- }
- return watcher
-}
-
-// addWatch adds a watch for a directory
-func addWatch(t *testing.T, watcher *Watcher, dir string) {
- if err := watcher.Add(dir); err != nil {
- t.Fatalf("watcher.Add(%q) failed: %s", dir, err)
- }
-}
-
-func TestFsnotifyMultipleOperations(t *testing.T) {
- watcher := newWatcher(t)
-
- // Receive errors on the error channel on a separate goroutine
- go func() {
- for err := range watcher.Errors {
- t.Fatalf("error received: %s", err)
- }
- }()
-
- // Create directory to watch
- testDir := tempMkdir(t)
- defer os.RemoveAll(testDir)
-
- // Create directory that's not watched
- testDirToMoveFiles := tempMkdir(t)
- defer os.RemoveAll(testDirToMoveFiles)
-
- testFile := filepath.Join(testDir, "TestFsnotifySeq.testfile")
- testFileRenamed := filepath.Join(testDirToMoveFiles, "TestFsnotifySeqRename.testfile")
-
- addWatch(t, watcher, testDir)
-
- // Receive events on the event channel on a separate goroutine
- eventstream := watcher.Events
- var createReceived, modifyReceived, deleteReceived, renameReceived counter
- done := make(chan bool)
- go func() {
- for event := range eventstream {
- // Only count relevant events
- if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) {
- t.Logf("event received: %s", event)
- if event.Op&Remove == Remove {
- deleteReceived.increment()
- }
- if event.Op&Write == Write {
- modifyReceived.increment()
- }
- if event.Op&Create == Create {
- createReceived.increment()
- }
- if event.Op&Rename == Rename {
- renameReceived.increment()
- }
- } else {
- t.Logf("unexpected event received: %s", event)
- }
- }
- done <- true
- }()
-
- // Create a file
- // This should add at least one event to the fsnotify event queue
- var f *os.File
- f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666)
- if err != nil {
- t.Fatalf("creating test file failed: %s", err)
- }
- f.Sync()
-
- time.Sleep(time.Millisecond)
- f.WriteString("data")
- f.Sync()
- f.Close()
-
- time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete
-
- if err := testRename(testFile, testFileRenamed); err != nil {
- t.Fatalf("rename failed: %s", err)
- }
-
- // Modify the file outside of the watched dir
- f, err = os.Open(testFileRenamed)
- if err != nil {
- t.Fatalf("open test renamed file failed: %s", err)
- }
- f.WriteString("data")
- f.Sync()
- f.Close()
-
- time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete
-
- // Recreate the file that was moved
- f, err = os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666)
- if err != nil {
- t.Fatalf("creating test file failed: %s", err)
- }
- f.Close()
- time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete
-
- // We expect this event to be received almost immediately, but let's wait 500 ms to be sure
- time.Sleep(500 * time.Millisecond)
- cReceived := createReceived.value()
- if cReceived != 2 {
- t.Fatalf("incorrect number of create events received after 500 ms (%d vs %d)", cReceived, 2)
- }
- mReceived := modifyReceived.value()
- if mReceived != 1 {
- t.Fatalf("incorrect number of modify events received after 500 ms (%d vs %d)", mReceived, 1)
- }
- dReceived := deleteReceived.value()
- rReceived := renameReceived.value()
- if dReceived+rReceived != 1 {
- t.Fatalf("incorrect number of rename+delete events received after 500 ms (%d vs %d)", rReceived+dReceived, 1)
- }
-
- // Try closing the fsnotify instance
- t.Log("calling Close()")
- watcher.Close()
- t.Log("waiting for the event channel to become closed...")
- select {
- case <-done:
- t.Log("event channel closed")
- case <-time.After(2 * time.Second):
- t.Fatal("event stream was not closed after 2 seconds")
- }
-}
-
-func TestFsnotifyMultipleCreates(t *testing.T) {
- watcher := newWatcher(t)
-
- // Receive errors on the error channel on a separate goroutine
- go func() {
- for err := range watcher.Errors {
- t.Fatalf("error received: %s", err)
- }
- }()
-
- // Create directory to watch
- testDir := tempMkdir(t)
- defer os.RemoveAll(testDir)
-
- testFile := filepath.Join(testDir, "TestFsnotifySeq.testfile")
-
- addWatch(t, watcher, testDir)
-
- // Receive events on the event channel on a separate goroutine
- eventstream := watcher.Events
- var createReceived, modifyReceived, deleteReceived counter
- done := make(chan bool)
- go func() {
- for event := range eventstream {
- // Only count relevant events
- if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) {
- t.Logf("event received: %s", event)
- if event.Op&Remove == Remove {
- deleteReceived.increment()
- }
- if event.Op&Create == Create {
- createReceived.increment()
- }
- if event.Op&Write == Write {
- modifyReceived.increment()
- }
- } else {
- t.Logf("unexpected event received: %s", event)
- }
- }
- done <- true
- }()
-
- // Create a file
- // This should add at least one event to the fsnotify event queue
- var f *os.File
- f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666)
- if err != nil {
- t.Fatalf("creating test file failed: %s", err)
- }
- f.Sync()
-
- time.Sleep(time.Millisecond)
- f.WriteString("data")
- f.Sync()
- f.Close()
-
- time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete
-
- os.Remove(testFile)
-
- time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete
-
- // Recreate the file
- f, err = os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666)
- if err != nil {
- t.Fatalf("creating test file failed: %s", err)
- }
- f.Close()
- time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete
-
- // Modify
- f, err = os.OpenFile(testFile, os.O_WRONLY, 0666)
- if err != nil {
- t.Fatalf("creating test file failed: %s", err)
- }
- f.Sync()
-
- time.Sleep(time.Millisecond)
- f.WriteString("data")
- f.Sync()
- f.Close()
-
- time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete
-
- // Modify
- f, err = os.OpenFile(testFile, os.O_WRONLY, 0666)
- if err != nil {
- t.Fatalf("creating test file failed: %s", err)
- }
- f.Sync()
-
- time.Sleep(time.Millisecond)
- f.WriteString("data")
- f.Sync()
- f.Close()
-
- time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete
-
- // We expect this event to be received almost immediately, but let's wait 500 ms to be sure
- time.Sleep(500 * time.Millisecond)
- cReceived := createReceived.value()
- if cReceived != 2 {
- t.Fatalf("incorrect number of create events received after 500 ms (%d vs %d)", cReceived, 2)
- }
- mReceived := modifyReceived.value()
- if mReceived < 3 {
- t.Fatalf("incorrect number of modify events received after 500 ms (%d vs atleast %d)", mReceived, 3)
- }
- dReceived := deleteReceived.value()
- if dReceived != 1 {
- t.Fatalf("incorrect number of rename+delete events received after 500 ms (%d vs %d)", dReceived, 1)
- }
-
- // Try closing the fsnotify instance
- t.Log("calling Close()")
- watcher.Close()
- t.Log("waiting for the event channel to become closed...")
- select {
- case <-done:
- t.Log("event channel closed")
- case <-time.After(2 * time.Second):
- t.Fatal("event stream was not closed after 2 seconds")
- }
-}
-
-func TestFsnotifyDirOnly(t *testing.T) {
- watcher := newWatcher(t)
-
- // Create directory to watch
- testDir := tempMkdir(t)
- defer os.RemoveAll(testDir)
-
- // Create a file before watching directory
- // This should NOT add any events to the fsnotify event queue
- testFileAlreadyExists := filepath.Join(testDir, "TestFsnotifyEventsExisting.testfile")
- {
- var f *os.File
- f, err := os.OpenFile(testFileAlreadyExists, os.O_WRONLY|os.O_CREATE, 0666)
- if err != nil {
- t.Fatalf("creating test file failed: %s", err)
- }
- f.Sync()
- f.Close()
- }
-
- addWatch(t, watcher, testDir)
-
- // Receive errors on the error channel on a separate goroutine
- go func() {
- for err := range watcher.Errors {
- t.Fatalf("error received: %s", err)
- }
- }()
-
- testFile := filepath.Join(testDir, "TestFsnotifyDirOnly.testfile")
-
- // Receive events on the event channel on a separate goroutine
- eventstream := watcher.Events
- var createReceived, modifyReceived, deleteReceived counter
- done := make(chan bool)
- go func() {
- for event := range eventstream {
- // Only count relevant events
- if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) || event.Name == filepath.Clean(testFileAlreadyExists) {
- t.Logf("event received: %s", event)
- if event.Op&Remove == Remove {
- deleteReceived.increment()
- }
- if event.Op&Write == Write {
- modifyReceived.increment()
- }
- if event.Op&Create == Create {
- createReceived.increment()
- }
- } else {
- t.Logf("unexpected event received: %s", event)
- }
- }
- done <- true
- }()
-
- // Create a file
- // This should add at least one event to the fsnotify event queue
- var f *os.File
- f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666)
- if err != nil {
- t.Fatalf("creating test file failed: %s", err)
- }
- f.Sync()
-
- time.Sleep(time.Millisecond)
- f.WriteString("data")
- f.Sync()
- f.Close()
-
- time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete
-
- os.Remove(testFile)
- os.Remove(testFileAlreadyExists)
-
- // We expect this event to be received almost immediately, but let's wait 500 ms to be sure
- time.Sleep(500 * time.Millisecond)
- cReceived := createReceived.value()
- if cReceived != 1 {
- t.Fatalf("incorrect number of create events received after 500 ms (%d vs %d)", cReceived, 1)
- }
- mReceived := modifyReceived.value()
- if mReceived != 1 {
- t.Fatalf("incorrect number of modify events received after 500 ms (%d vs %d)", mReceived, 1)
- }
- dReceived := deleteReceived.value()
- if dReceived != 2 {
- t.Fatalf("incorrect number of delete events received after 500 ms (%d vs %d)", dReceived, 2)
- }
-
- // Try closing the fsnotify instance
- t.Log("calling Close()")
- watcher.Close()
- t.Log("waiting for the event channel to become closed...")
- select {
- case <-done:
- t.Log("event channel closed")
- case <-time.After(2 * time.Second):
- t.Fatal("event stream was not closed after 2 seconds")
- }
-}
-
-func TestFsnotifyDeleteWatchedDir(t *testing.T) {
- watcher := newWatcher(t)
- defer watcher.Close()
-
- // Create directory to watch
- testDir := tempMkdir(t)
- defer os.RemoveAll(testDir)
-
- // Create a file before watching directory
- testFileAlreadyExists := filepath.Join(testDir, "TestFsnotifyEventsExisting.testfile")
- {
- var f *os.File
- f, err := os.OpenFile(testFileAlreadyExists, os.O_WRONLY|os.O_CREATE, 0666)
- if err != nil {
- t.Fatalf("creating test file failed: %s", err)
- }
- f.Sync()
- f.Close()
- }
-
- addWatch(t, watcher, testDir)
-
- // Add a watch for testFile
- addWatch(t, watcher, testFileAlreadyExists)
-
- // Receive errors on the error channel on a separate goroutine
- go func() {
- for err := range watcher.Errors {
- t.Fatalf("error received: %s", err)
- }
- }()
-
- // Receive events on the event channel on a separate goroutine
- eventstream := watcher.Events
- var deleteReceived counter
- go func() {
- for event := range eventstream {
- // Only count relevant events
- if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFileAlreadyExists) {
- t.Logf("event received: %s", event)
- if event.Op&Remove == Remove {
- deleteReceived.increment()
- }
- } else {
- t.Logf("unexpected event received: %s", event)
- }
- }
- }()
-
- os.RemoveAll(testDir)
-
- // We expect this event to be received almost immediately, but let's wait 500 ms to be sure
- time.Sleep(500 * time.Millisecond)
- dReceived := deleteReceived.value()
- if dReceived < 2 {
- t.Fatalf("did not receive at least %d delete events, received %d after 500 ms", 2, dReceived)
- }
-}
-
-func TestFsnotifySubDir(t *testing.T) {
- watcher := newWatcher(t)
-
- // Create directory to watch
- testDir := tempMkdir(t)
- defer os.RemoveAll(testDir)
-
- testFile1 := filepath.Join(testDir, "TestFsnotifyFile1.testfile")
- testSubDir := filepath.Join(testDir, "sub")
- testSubDirFile := filepath.Join(testDir, "sub/TestFsnotifyFile1.testfile")
-
- // Receive errors on the error channel on a separate goroutine
- go func() {
- for err := range watcher.Errors {
- t.Fatalf("error received: %s", err)
- }
- }()
-
- // Receive events on the event channel on a separate goroutine
- eventstream := watcher.Events
- var createReceived, deleteReceived counter
- done := make(chan bool)
- go func() {
- for event := range eventstream {
- // Only count relevant events
- if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testSubDir) || event.Name == filepath.Clean(testFile1) {
- t.Logf("event received: %s", event)
- if event.Op&Create == Create {
- createReceived.increment()
- }
- if event.Op&Remove == Remove {
- deleteReceived.increment()
- }
- } else {
- t.Logf("unexpected event received: %s", event)
- }
- }
- done <- true
- }()
-
- addWatch(t, watcher, testDir)
-
- // Create sub-directory
- if err := os.Mkdir(testSubDir, 0777); err != nil {
- t.Fatalf("failed to create test sub-directory: %s", err)
- }
-
- // Create a file
- var f *os.File
- f, err := os.OpenFile(testFile1, os.O_WRONLY|os.O_CREATE, 0666)
- if err != nil {
- t.Fatalf("creating test file failed: %s", err)
- }
- f.Sync()
- f.Close()
-
- // Create a file (Should not see this! we are not watching subdir)
- var fs *os.File
- fs, err = os.OpenFile(testSubDirFile, os.O_WRONLY|os.O_CREATE, 0666)
- if err != nil {
- t.Fatalf("creating test file failed: %s", err)
- }
- fs.Sync()
- fs.Close()
-
- time.Sleep(200 * time.Millisecond)
-
- // Make sure receive deletes for both file and sub-directory
- os.RemoveAll(testSubDir)
- os.Remove(testFile1)
-
- // We expect this event to be received almost immediately, but let's wait 500 ms to be sure
- time.Sleep(500 * time.Millisecond)
- cReceived := createReceived.value()
- if cReceived != 2 {
- t.Fatalf("incorrect number of create events received after 500 ms (%d vs %d)", cReceived, 2)
- }
- dReceived := deleteReceived.value()
- if dReceived != 2 {
- t.Fatalf("incorrect number of delete events received after 500 ms (%d vs %d)", dReceived, 2)
- }
-
- // Try closing the fsnotify instance
- t.Log("calling Close()")
- watcher.Close()
- t.Log("waiting for the event channel to become closed...")
- select {
- case <-done:
- t.Log("event channel closed")
- case <-time.After(2 * time.Second):
- t.Fatal("event stream was not closed after 2 seconds")
- }
-}
-
-func TestFsnotifyRename(t *testing.T) {
- watcher := newWatcher(t)
-
- // Create directory to watch
- testDir := tempMkdir(t)
- defer os.RemoveAll(testDir)
-
- addWatch(t, watcher, testDir)
-
- // Receive errors on the error channel on a separate goroutine
- go func() {
- for err := range watcher.Errors {
- t.Fatalf("error received: %s", err)
- }
- }()
-
- testFile := filepath.Join(testDir, "TestFsnotifyEvents.testfile")
- testFileRenamed := filepath.Join(testDir, "TestFsnotifyEvents.testfileRenamed")
-
- // Receive events on the event channel on a separate goroutine
- eventstream := watcher.Events
- var renameReceived counter
- done := make(chan bool)
- go func() {
- for event := range eventstream {
- // Only count relevant events
- if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) || event.Name == filepath.Clean(testFileRenamed) {
- if event.Op&Rename == Rename {
- renameReceived.increment()
- }
- t.Logf("event received: %s", event)
- } else {
- t.Logf("unexpected event received: %s", event)
- }
- }
- done <- true
- }()
-
- // Create a file
- // This should add at least one event to the fsnotify event queue
- var f *os.File
- f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666)
- if err != nil {
- t.Fatalf("creating test file failed: %s", err)
- }
- f.Sync()
-
- f.WriteString("data")
- f.Sync()
- f.Close()
-
- // Add a watch for testFile
- addWatch(t, watcher, testFile)
-
- if err := testRename(testFile, testFileRenamed); err != nil {
- t.Fatalf("rename failed: %s", err)
- }
-
- // We expect this event to be received almost immediately, but let's wait 500 ms to be sure
- time.Sleep(500 * time.Millisecond)
- if renameReceived.value() == 0 {
- t.Fatal("fsnotify rename events have not been received after 500 ms")
- }
-
- // Try closing the fsnotify instance
- t.Log("calling Close()")
- watcher.Close()
- t.Log("waiting for the event channel to become closed...")
- select {
- case <-done:
- t.Log("event channel closed")
- case <-time.After(2 * time.Second):
- t.Fatal("event stream was not closed after 2 seconds")
- }
-
- os.Remove(testFileRenamed)
-}
-
-func TestFsnotifyRenameToCreate(t *testing.T) {
- watcher := newWatcher(t)
-
- // Create directory to watch
- testDir := tempMkdir(t)
- defer os.RemoveAll(testDir)
-
- // Create directory to get file
- testDirFrom := tempMkdir(t)
- defer os.RemoveAll(testDirFrom)
-
- addWatch(t, watcher, testDir)
-
- // Receive errors on the error channel on a separate goroutine
- go func() {
- for err := range watcher.Errors {
- t.Fatalf("error received: %s", err)
- }
- }()
-
- testFile := filepath.Join(testDirFrom, "TestFsnotifyEvents.testfile")
- testFileRenamed := filepath.Join(testDir, "TestFsnotifyEvents.testfileRenamed")
-
- // Receive events on the event channel on a separate goroutine
- eventstream := watcher.Events
- var createReceived counter
- done := make(chan bool)
- go func() {
- for event := range eventstream {
- // Only count relevant events
- if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) || event.Name == filepath.Clean(testFileRenamed) {
- if event.Op&Create == Create {
- createReceived.increment()
- }
- t.Logf("event received: %s", event)
- } else {
- t.Logf("unexpected event received: %s", event)
- }
- }
- done <- true
- }()
-
- // Create a file
- // This should add at least one event to the fsnotify event queue
- var f *os.File
- f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666)
- if err != nil {
- t.Fatalf("creating test file failed: %s", err)
- }
- f.Sync()
- f.Close()
-
- if err := testRename(testFile, testFileRenamed); err != nil {
- t.Fatalf("rename failed: %s", err)
- }
-
- // We expect this event to be received almost immediately, but let's wait 500 ms to be sure
- time.Sleep(500 * time.Millisecond)
- if createReceived.value() == 0 {
- t.Fatal("fsnotify create events have not been received after 500 ms")
- }
-
- // Try closing the fsnotify instance
- t.Log("calling Close()")
- watcher.Close()
- t.Log("waiting for the event channel to become closed...")
- select {
- case <-done:
- t.Log("event channel closed")
- case <-time.After(2 * time.Second):
- t.Fatal("event stream was not closed after 2 seconds")
- }
-
- os.Remove(testFileRenamed)
-}
-
-func TestFsnotifyRenameToOverwrite(t *testing.T) {
- switch runtime.GOOS {
- case "plan9", "windows":
- t.Skipf("skipping test on %q (os.Rename over existing file does not create event).", runtime.GOOS)
- }
-
- watcher := newWatcher(t)
-
- // Create directory to watch
- testDir := tempMkdir(t)
- defer os.RemoveAll(testDir)
-
- // Create directory to get file
- testDirFrom := tempMkdir(t)
- defer os.RemoveAll(testDirFrom)
-
- testFile := filepath.Join(testDirFrom, "TestFsnotifyEvents.testfile")
- testFileRenamed := filepath.Join(testDir, "TestFsnotifyEvents.testfileRenamed")
-
- // Create a file
- var fr *os.File
- fr, err := os.OpenFile(testFileRenamed, os.O_WRONLY|os.O_CREATE, 0666)
- if err != nil {
- t.Fatalf("creating test file failed: %s", err)
- }
- fr.Sync()
- fr.Close()
-
- addWatch(t, watcher, testDir)
-
- // Receive errors on the error channel on a separate goroutine
- go func() {
- for err := range watcher.Errors {
- t.Fatalf("error received: %s", err)
- }
- }()
-
- // Receive events on the event channel on a separate goroutine
- eventstream := watcher.Events
- var eventReceived counter
- done := make(chan bool)
- go func() {
- for event := range eventstream {
- // Only count relevant events
- if event.Name == filepath.Clean(testFileRenamed) {
- eventReceived.increment()
- t.Logf("event received: %s", event)
- } else {
- t.Logf("unexpected event received: %s", event)
- }
- }
- done <- true
- }()
-
- // Create a file
- // This should add at least one event to the fsnotify event queue
- var f *os.File
- f, err = os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666)
- if err != nil {
- t.Fatalf("creating test file failed: %s", err)
- }
- f.Sync()
- f.Close()
-
- if err := testRename(testFile, testFileRenamed); err != nil {
- t.Fatalf("rename failed: %s", err)
- }
-
- // We expect this event to be received almost immediately, but let's wait 500 ms to be sure
- time.Sleep(500 * time.Millisecond)
- if eventReceived.value() == 0 {
- t.Fatal("fsnotify events have not been received after 500 ms")
- }
-
- // Try closing the fsnotify instance
- t.Log("calling Close()")
- watcher.Close()
- t.Log("waiting for the event channel to become closed...")
- select {
- case <-done:
- t.Log("event channel closed")
- case <-time.After(2 * time.Second):
- t.Fatal("event stream was not closed after 2 seconds")
- }
-
- os.Remove(testFileRenamed)
-}
-
-func TestRemovalOfWatch(t *testing.T) {
- // Create directory to watch
- testDir := tempMkdir(t)
- defer os.RemoveAll(testDir)
-
- // Create a file before watching directory
- testFileAlreadyExists := filepath.Join(testDir, "TestFsnotifyEventsExisting.testfile")
- {
- var f *os.File
- f, err := os.OpenFile(testFileAlreadyExists, os.O_WRONLY|os.O_CREATE, 0666)
- if err != nil {
- t.Fatalf("creating test file failed: %s", err)
- }
- f.Sync()
- f.Close()
- }
-
- watcher := newWatcher(t)
- defer watcher.Close()
-
- addWatch(t, watcher, testDir)
- if err := watcher.Remove(testDir); err != nil {
- t.Fatalf("Could not remove the watch: %v\n", err)
- }
-
- go func() {
- select {
- case ev := <-watcher.Events:
- t.Fatalf("We received event: %v\n", ev)
- case <-time.After(500 * time.Millisecond):
- t.Log("No event received, as expected.")
- }
- }()
-
- time.Sleep(200 * time.Millisecond)
- // Modify the file outside of the watched dir
- f, err := os.Open(testFileAlreadyExists)
- if err != nil {
- t.Fatalf("Open test file failed: %s", err)
- }
- f.WriteString("data")
- f.Sync()
- f.Close()
- if err := os.Chmod(testFileAlreadyExists, 0700); err != nil {
- t.Fatalf("chmod failed: %s", err)
- }
- time.Sleep(400 * time.Millisecond)
-}
-
-func TestFsnotifyAttrib(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("attributes don't work on Windows.")
- }
-
- watcher := newWatcher(t)
-
- // Create directory to watch
- testDir := tempMkdir(t)
- defer os.RemoveAll(testDir)
-
- // Receive errors on the error channel on a separate goroutine
- go func() {
- for err := range watcher.Errors {
- t.Fatalf("error received: %s", err)
- }
- }()
-
- testFile := filepath.Join(testDir, "TestFsnotifyAttrib.testfile")
-
- // Receive events on the event channel on a separate goroutine
- eventstream := watcher.Events
- // The modifyReceived counter counts IsModify events that are not IsAttrib,
- // and the attribReceived counts IsAttrib events (which are also IsModify as
- // a consequence).
- var modifyReceived counter
- var attribReceived counter
- done := make(chan bool)
- go func() {
- for event := range eventstream {
- // Only count relevant events
- if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) {
- if event.Op&Write == Write {
- modifyReceived.increment()
- }
- if event.Op&Chmod == Chmod {
- attribReceived.increment()
- }
- t.Logf("event received: %s", event)
- } else {
- t.Logf("unexpected event received: %s", event)
- }
- }
- done <- true
- }()
-
- // Create a file
- // This should add at least one event to the fsnotify event queue
- var f *os.File
- f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666)
- if err != nil {
- t.Fatalf("creating test file failed: %s", err)
- }
- f.Sync()
-
- f.WriteString("data")
- f.Sync()
- f.Close()
-
- // Add a watch for testFile
- addWatch(t, watcher, testFile)
-
- if err := os.Chmod(testFile, 0700); err != nil {
- t.Fatalf("chmod failed: %s", err)
- }
-
- // We expect this event to be received almost immediately, but let's wait 500 ms to be sure
- // Creating/writing a file changes also the mtime, so IsAttrib should be set to true here
- time.Sleep(500 * time.Millisecond)
- if modifyReceived.value() != 0 {
- t.Fatal("received an unexpected modify event when creating a test file")
- }
- if attribReceived.value() == 0 {
- t.Fatal("fsnotify attribute events have not received after 500 ms")
- }
-
- // Modifying the contents of the file does not set the attrib flag (although eg. the mtime
- // might have been modified).
- modifyReceived.reset()
- attribReceived.reset()
-
- f, err = os.OpenFile(testFile, os.O_WRONLY, 0)
- if err != nil {
- t.Fatalf("reopening test file failed: %s", err)
- }
-
- f.WriteString("more data")
- f.Sync()
- f.Close()
-
- time.Sleep(500 * time.Millisecond)
-
- if modifyReceived.value() != 1 {
- t.Fatal("didn't receive a modify event after changing test file contents")
- }
-
- if attribReceived.value() != 0 {
- t.Fatal("did receive an unexpected attrib event after changing test file contents")
- }
-
- modifyReceived.reset()
- attribReceived.reset()
-
- // Doing a chmod on the file should trigger an event with the "attrib" flag set (the contents
- // of the file are not changed though)
- if err := os.Chmod(testFile, 0600); err != nil {
- t.Fatalf("chmod failed: %s", err)
- }
-
- time.Sleep(500 * time.Millisecond)
-
- if attribReceived.value() != 1 {
- t.Fatal("didn't receive an attribute change after 500ms")
- }
-
- // Try closing the fsnotify instance
- t.Log("calling Close()")
- watcher.Close()
- t.Log("waiting for the event channel to become closed...")
- select {
- case <-done:
- t.Log("event channel closed")
- case <-time.After(1e9):
- t.Fatal("event stream was not closed after 1 second")
- }
-
- os.Remove(testFile)
-}
-
-func TestFsnotifyClose(t *testing.T) {
- watcher := newWatcher(t)
- watcher.Close()
-
- var done int32
- go func() {
- watcher.Close()
- atomic.StoreInt32(&done, 1)
- }()
-
- time.Sleep(50e6) // 50 ms
- if atomic.LoadInt32(&done) == 0 {
- t.Fatal("double Close() test failed: second Close() call didn't return")
- }
-
- testDir := tempMkdir(t)
- defer os.RemoveAll(testDir)
-
- if err := watcher.Add(testDir); err == nil {
- t.Fatal("expected error on Watch() after Close(), got nil")
- }
-}
-
-func TestFsnotifyFakeSymlink(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("symlinks don't work on Windows.")
- }
-
- watcher := newWatcher(t)
-
- // Create directory to watch
- testDir := tempMkdir(t)
- defer os.RemoveAll(testDir)
-
- var errorsReceived counter
- // Receive errors on the error channel on a separate goroutine
- go func() {
- for errors := range watcher.Errors {
- t.Logf("Received error: %s", errors)
- errorsReceived.increment()
- }
- }()
-
- // Count the CREATE events received
- var createEventsReceived, otherEventsReceived counter
- go func() {
- for ev := range watcher.Events {
- t.Logf("event received: %s", ev)
- if ev.Op&Create == Create {
- createEventsReceived.increment()
- } else {
- otherEventsReceived.increment()
- }
- }
- }()
-
- addWatch(t, watcher, testDir)
-
- if err := os.Symlink(filepath.Join(testDir, "zzz"), filepath.Join(testDir, "zzznew")); err != nil {
- t.Fatalf("Failed to create bogus symlink: %s", err)
- }
- t.Logf("Created bogus symlink")
-
- // We expect this event to be received almost immediately, but let's wait 500 ms to be sure
- time.Sleep(500 * time.Millisecond)
-
- // Should not be error, just no events for broken links (watching nothing)
- if errorsReceived.value() > 0 {
- t.Fatal("fsnotify errors have been received.")
- }
- if otherEventsReceived.value() > 0 {
- t.Fatal("fsnotify other events received on the broken link")
- }
-
- // Except for 1 create event (for the link itself)
- if createEventsReceived.value() == 0 {
- t.Fatal("fsnotify create events were not received after 500 ms")
- }
- if createEventsReceived.value() > 1 {
- t.Fatal("fsnotify more create events received than expected")
- }
-
- // Try closing the fsnotify instance
- t.Log("calling Close()")
- watcher.Close()
-}
-
-func TestCyclicSymlink(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("symlinks don't work on Windows.")
- }
-
- watcher := newWatcher(t)
-
- testDir := tempMkdir(t)
- defer os.RemoveAll(testDir)
-
- link := path.Join(testDir, "link")
- if err := os.Symlink(".", link); err != nil {
- t.Fatalf("could not make symlink: %v", err)
- }
- addWatch(t, watcher, testDir)
-
- var createEventsReceived counter
- go func() {
- for ev := range watcher.Events {
- if ev.Op&Create == Create {
- createEventsReceived.increment()
- }
- }
- }()
-
- if err := os.Remove(link); err != nil {
- t.Fatalf("Error removing link: %v", err)
- }
-
- // It would be nice to be able to expect a delete event here, but kqueue has
- // no way for us to get events on symlinks themselves, because opening them
- // opens an fd to the file to which they point.
-
- if err := ioutil.WriteFile(link, []byte("foo"), 0700); err != nil {
- t.Fatalf("could not make symlink: %v", err)
- }
-
- // We expect this event to be received almost immediately, but let's wait 500 ms to be sure
- time.Sleep(500 * time.Millisecond)
-
- if got := createEventsReceived.value(); got == 0 {
- t.Errorf("want at least 1 create event got %v", got)
- }
-
- watcher.Close()
-}
-
-// TestConcurrentRemovalOfWatch tests that concurrent calls to RemoveWatch do not race.
-// See https://codereview.appspot.com/103300045/
-// go test -test.run=TestConcurrentRemovalOfWatch -test.cpu=1,1,1,1,1 -race
-func TestConcurrentRemovalOfWatch(t *testing.T) {
- if runtime.GOOS != "darwin" {
- t.Skip("regression test for race only present on darwin")
- }
-
- // Create directory to watch
- testDir := tempMkdir(t)
- defer os.RemoveAll(testDir)
-
- // Create a file before watching directory
- testFileAlreadyExists := filepath.Join(testDir, "TestFsnotifyEventsExisting.testfile")
- {
- var f *os.File
- f, err := os.OpenFile(testFileAlreadyExists, os.O_WRONLY|os.O_CREATE, 0666)
- if err != nil {
- t.Fatalf("creating test file failed: %s", err)
- }
- f.Sync()
- f.Close()
- }
-
- watcher := newWatcher(t)
- defer watcher.Close()
-
- addWatch(t, watcher, testDir)
-
- // Test that RemoveWatch can be invoked concurrently, with no data races.
- removed1 := make(chan struct{})
- go func() {
- defer close(removed1)
- watcher.Remove(testDir)
- }()
- removed2 := make(chan struct{})
- go func() {
- close(removed2)
- watcher.Remove(testDir)
- }()
- <-removed1
- <-removed2
-}
-
-func TestClose(t *testing.T) {
- // Regression test for #59 bad file descriptor from Close
- testDir := tempMkdir(t)
- defer os.RemoveAll(testDir)
-
- watcher := newWatcher(t)
- if err := watcher.Add(testDir); err != nil {
- t.Fatalf("Expected no error on Add, got %v", err)
- }
- err := watcher.Close()
- if err != nil {
- t.Fatalf("Expected no error on Close, got %v.", err)
- }
-}
-
-// TestRemoveWithClose tests if one can handle Remove events and, at the same
-// time, close Watcher object without any data races.
-func TestRemoveWithClose(t *testing.T) {
- testDir := tempMkdir(t)
- defer os.RemoveAll(testDir)
-
- const fileN = 200
- tempFiles := make([]string, 0, fileN)
- for i := 0; i < fileN; i++ {
- tempFiles = append(tempFiles, tempMkFile(t, testDir))
- }
- watcher := newWatcher(t)
- if err := watcher.Add(testDir); err != nil {
- t.Fatalf("Expected no error on Add, got %v", err)
- }
- startC, stopC := make(chan struct{}), make(chan struct{})
- errC := make(chan error)
- go func() {
- for {
- select {
- case <-watcher.Errors:
- case <-watcher.Events:
- case <-stopC:
- return
- }
- }
- }()
- go func() {
- <-startC
- for _, fileName := range tempFiles {
- os.Remove(fileName)
- }
- }()
- go func() {
- <-startC
- errC <- watcher.Close()
- }()
- close(startC)
- defer close(stopC)
- if err := <-errC; err != nil {
- t.Fatalf("Expected no error on Close, got %v.", err)
- }
-}
-
-func testRename(file1, file2 string) error {
- switch runtime.GOOS {
- case "windows", "plan9":
- return os.Rename(file1, file2)
- default:
- cmd := exec.Command("mv", file1, file2)
- return cmd.Run()
- }
-}
diff --git a/vendor/github.com/fsnotify/fsnotify/kqueue.go b/vendor/github.com/fsnotify/fsnotify/kqueue.go
deleted file mode 100644
index c2b4acb..0000000
--- a/vendor/github.com/fsnotify/fsnotify/kqueue.go
+++ /dev/null
@@ -1,503 +0,0 @@
-// Copyright 2010 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.
-
-// +build freebsd openbsd netbsd dragonfly darwin
-
-package fsnotify
-
-import (
- "errors"
- "fmt"
- "io/ioutil"
- "os"
- "path/filepath"
- "sync"
- "time"
-
- "golang.org/x/sys/unix"
-)
-
-// Watcher watches a set of files, delivering events to a channel.
-type Watcher struct {
- Events chan Event
- Errors chan error
- done chan bool // Channel for sending a "quit message" to the reader goroutine
-
- kq int // File descriptor (as returned by the kqueue() syscall).
-
- mu sync.Mutex // Protects access to watcher data
- watches map[string]int // Map of watched file descriptors (key: path).
- externalWatches map[string]bool // Map of watches added by user of the library.
- dirFlags map[string]uint32 // Map of watched directories to fflags used in kqueue.
- paths map[int]pathInfo // Map file descriptors to path names for processing kqueue events.
- fileExists map[string]bool // Keep track of if we know this file exists (to stop duplicate create events).
- isClosed bool // Set to true when Close() is first called
-}
-
-type pathInfo struct {
- name string
- isDir bool
-}
-
-// NewWatcher establishes a new watcher with the underlying OS and begins waiting for events.
-func NewWatcher() (*Watcher, error) {
- kq, err := kqueue()
- if err != nil {
- return nil, err
- }
-
- w := &Watcher{
- kq: kq,
- watches: make(map[string]int),
- dirFlags: make(map[string]uint32),
- paths: make(map[int]pathInfo),
- fileExists: make(map[string]bool),
- externalWatches: make(map[string]bool),
- Events: make(chan Event),
- Errors: make(chan error),
- done: make(chan bool),
- }
-
- go w.readEvents()
- return w, nil
-}
-
-// Close removes all watches and closes the events channel.
-func (w *Watcher) Close() error {
- w.mu.Lock()
- if w.isClosed {
- w.mu.Unlock()
- return nil
- }
- w.isClosed = true
- w.mu.Unlock()
-
- // copy paths to remove while locked
- w.mu.Lock()
- var pathsToRemove = make([]string, 0, len(w.watches))
- for name := range w.watches {
- pathsToRemove = append(pathsToRemove, name)
- }
- w.mu.Unlock()
- // unlock before calling Remove, which also locks
-
- var err error
- for _, name := range pathsToRemove {
- if e := w.Remove(name); e != nil && err == nil {
- err = e
- }
- }
-
- // Send "quit" message to the reader goroutine:
- w.done <- true
-
- return nil
-}
-
-// Add starts watching the named file or directory (non-recursively).
-func (w *Watcher) Add(name string) error {
- w.mu.Lock()
- w.externalWatches[name] = true
- w.mu.Unlock()
- _, err := w.addWatch(name, noteAllEvents)
- return err
-}
-
-// Remove stops watching the the named file or directory (non-recursively).
-func (w *Watcher) Remove(name string) error {
- name = filepath.Clean(name)
- w.mu.Lock()
- watchfd, ok := w.watches[name]
- w.mu.Unlock()
- if !ok {
- return fmt.Errorf("can't remove non-existent kevent watch for: %s", name)
- }
-
- const registerRemove = unix.EV_DELETE
- if err := register(w.kq, []int{watchfd}, registerRemove, 0); err != nil {
- return err
- }
-
- unix.Close(watchfd)
-
- w.mu.Lock()
- isDir := w.paths[watchfd].isDir
- delete(w.watches, name)
- delete(w.paths, watchfd)
- delete(w.dirFlags, name)
- w.mu.Unlock()
-
- // Find all watched paths that are in this directory that are not external.
- if isDir {
- var pathsToRemove []string
- w.mu.Lock()
- for _, path := range w.paths {
- wdir, _ := filepath.Split(path.name)
- if filepath.Clean(wdir) == name {
- if !w.externalWatches[path.name] {
- pathsToRemove = append(pathsToRemove, path.name)
- }
- }
- }
- w.mu.Unlock()
- for _, name := range pathsToRemove {
- // Since these are internal, not much sense in propagating error
- // to the user, as that will just confuse them with an error about
- // a path they did not explicitly watch themselves.
- w.Remove(name)
- }
- }
-
- return nil
-}
-
-// Watch all events (except NOTE_EXTEND, NOTE_LINK, NOTE_REVOKE)
-const noteAllEvents = unix.NOTE_DELETE | unix.NOTE_WRITE | unix.NOTE_ATTRIB | unix.NOTE_RENAME
-
-// keventWaitTime to block on each read from kevent
-var keventWaitTime = durationToTimespec(100 * time.Millisecond)
-
-// addWatch adds name to the watched file set.
-// The flags are interpreted as described in kevent(2).
-// Returns the real path to the file which was added, if any, which may be different from the one passed in the case of symlinks.
-func (w *Watcher) addWatch(name string, flags uint32) (string, error) {
- var isDir bool
- // Make ./name and name equivalent
- name = filepath.Clean(name)
-
- w.mu.Lock()
- if w.isClosed {
- w.mu.Unlock()
- return "", errors.New("kevent instance already closed")
- }
- watchfd, alreadyWatching := w.watches[name]
- // We already have a watch, but we can still override flags.
- if alreadyWatching {
- isDir = w.paths[watchfd].isDir
- }
- w.mu.Unlock()
-
- if !alreadyWatching {
- fi, err := os.Lstat(name)
- if err != nil {
- return "", err
- }
-
- // Don't watch sockets.
- if fi.Mode()&os.ModeSocket == os.ModeSocket {
- return "", nil
- }
-
- // Don't watch named pipes.
- if fi.Mode()&os.ModeNamedPipe == os.ModeNamedPipe {
- return "", nil
- }
-
- // Follow Symlinks
- // Unfortunately, Linux can add bogus symlinks to watch list without
- // issue, and Windows can't do symlinks period (AFAIK). To maintain
- // consistency, we will act like everything is fine. There will simply
- // be no file events for broken symlinks.
- // Hence the returns of nil on errors.
- if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
- name, err = filepath.EvalSymlinks(name)
- if err != nil {
- return "", nil
- }
-
- w.mu.Lock()
- _, alreadyWatching = w.watches[name]
- w.mu.Unlock()
-
- if alreadyWatching {
- return name, nil
- }
-
- fi, err = os.Lstat(name)
- if err != nil {
- return "", nil
- }
- }
-
- watchfd, err = unix.Open(name, openMode, 0700)
- if watchfd == -1 {
- return "", err
- }
-
- isDir = fi.IsDir()
- }
-
- const registerAdd = unix.EV_ADD | unix.EV_CLEAR | unix.EV_ENABLE
- if err := register(w.kq, []int{watchfd}, registerAdd, flags); err != nil {
- unix.Close(watchfd)
- return "", err
- }
-
- if !alreadyWatching {
- w.mu.Lock()
- w.watches[name] = watchfd
- w.paths[watchfd] = pathInfo{name: name, isDir: isDir}
- w.mu.Unlock()
- }
-
- if isDir {
- // Watch the directory if it has not been watched before,
- // or if it was watched before, but perhaps only a NOTE_DELETE (watchDirectoryFiles)
- w.mu.Lock()
-
- watchDir := (flags&unix.NOTE_WRITE) == unix.NOTE_WRITE &&
- (!alreadyWatching || (w.dirFlags[name]&unix.NOTE_WRITE) != unix.NOTE_WRITE)
- // Store flags so this watch can be updated later
- w.dirFlags[name] = flags
- w.mu.Unlock()
-
- if watchDir {
- if err := w.watchDirectoryFiles(name); err != nil {
- return "", err
- }
- }
- }
- return name, nil
-}
-
-// readEvents reads from kqueue and converts the received kevents into
-// Event values that it sends down the Events channel.
-func (w *Watcher) readEvents() {
- eventBuffer := make([]unix.Kevent_t, 10)
-
- for {
- // See if there is a message on the "done" channel
- select {
- case <-w.done:
- err := unix.Close(w.kq)
- if err != nil {
- w.Errors <- err
- }
- close(w.Events)
- close(w.Errors)
- return
- default:
- }
-
- // Get new events
- kevents, err := read(w.kq, eventBuffer, &keventWaitTime)
- // EINTR is okay, the syscall was interrupted before timeout expired.
- if err != nil && err != unix.EINTR {
- w.Errors <- err
- continue
- }
-
- // Flush the events we received to the Events channel
- for len(kevents) > 0 {
- kevent := &kevents[0]
- watchfd := int(kevent.Ident)
- mask := uint32(kevent.Fflags)
- w.mu.Lock()
- path := w.paths[watchfd]
- w.mu.Unlock()
- event := newEvent(path.name, mask)
-
- if path.isDir && !(event.Op&Remove == Remove) {
- // Double check to make sure the directory exists. This can happen when
- // we do a rm -fr on a recursively watched folders and we receive a
- // modification event first but the folder has been deleted and later
- // receive the delete event
- if _, err := os.Lstat(event.Name); os.IsNotExist(err) {
- // mark is as delete event
- event.Op |= Remove
- }
- }
-
- if event.Op&Rename == Rename || event.Op&Remove == Remove {
- w.Remove(event.Name)
- w.mu.Lock()
- delete(w.fileExists, event.Name)
- w.mu.Unlock()
- }
-
- if path.isDir && event.Op&Write == Write && !(event.Op&Remove == Remove) {
- w.sendDirectoryChangeEvents(event.Name)
- } else {
- // Send the event on the Events channel
- w.Events <- event
- }
-
- if event.Op&Remove == Remove {
- // Look for a file that may have overwritten this.
- // For example, mv f1 f2 will delete f2, then create f2.
- if path.isDir {
- fileDir := filepath.Clean(event.Name)
- w.mu.Lock()
- _, found := w.watches[fileDir]
- w.mu.Unlock()
- if found {
- // make sure the directory exists before we watch for changes. When we
- // do a recursive watch and perform rm -fr, the parent directory might
- // have gone missing, ignore the missing directory and let the
- // upcoming delete event remove the watch from the parent directory.
- if _, err := os.Lstat(fileDir); err == nil {
- w.sendDirectoryChangeEvents(fileDir)
- }
- }
- } else {
- filePath := filepath.Clean(event.Name)
- if fileInfo, err := os.Lstat(filePath); err == nil {
- w.sendFileCreatedEventIfNew(filePath, fileInfo)
- }
- }
- }
-
- // Move to next event
- kevents = kevents[1:]
- }
- }
-}
-
-// newEvent returns an platform-independent Event based on kqueue Fflags.
-func newEvent(name string, mask uint32) Event {
- e := Event{Name: name}
- if mask&unix.NOTE_DELETE == unix.NOTE_DELETE {
- e.Op |= Remove
- }
- if mask&unix.NOTE_WRITE == unix.NOTE_WRITE {
- e.Op |= Write
- }
- if mask&unix.NOTE_RENAME == unix.NOTE_RENAME {
- e.Op |= Rename
- }
- if mask&unix.NOTE_ATTRIB == unix.NOTE_ATTRIB {
- e.Op |= Chmod
- }
- return e
-}
-
-func newCreateEvent(name string) Event {
- return Event{Name: name, Op: Create}
-}
-
-// watchDirectoryFiles to mimic inotify when adding a watch on a directory
-func (w *Watcher) watchDirectoryFiles(dirPath string) error {
- // Get all files
- files, err := ioutil.ReadDir(dirPath)
- if err != nil {
- return err
- }
-
- for _, fileInfo := range files {
- filePath := filepath.Join(dirPath, fileInfo.Name())
- filePath, err = w.internalWatch(filePath, fileInfo)
- if err != nil {
- return err
- }
-
- w.mu.Lock()
- w.fileExists[filePath] = true
- w.mu.Unlock()
- }
-
- return nil
-}
-
-// sendDirectoryEvents searches the directory for newly created files
-// and sends them over the event channel. This functionality is to have
-// the BSD version of fsnotify match Linux inotify which provides a
-// create event for files created in a watched directory.
-func (w *Watcher) sendDirectoryChangeEvents(dirPath string) {
- // Get all files
- files, err := ioutil.ReadDir(dirPath)
- if err != nil {
- w.Errors <- err
- }
-
- // Search for new files
- for _, fileInfo := range files {
- filePath := filepath.Join(dirPath, fileInfo.Name())
- err := w.sendFileCreatedEventIfNew(filePath, fileInfo)
-
- if err != nil {
- return
- }
- }
-}
-
-// sendFileCreatedEvent sends a create event if the file isn't already being tracked.
-func (w *Watcher) sendFileCreatedEventIfNew(filePath string, fileInfo os.FileInfo) (err error) {
- w.mu.Lock()
- _, doesExist := w.fileExists[filePath]
- w.mu.Unlock()
- if !doesExist {
- // Send create event
- w.Events <- newCreateEvent(filePath)
- }
-
- // like watchDirectoryFiles (but without doing another ReadDir)
- filePath, err = w.internalWatch(filePath, fileInfo)
- if err != nil {
- return err
- }
-
- w.mu.Lock()
- w.fileExists[filePath] = true
- w.mu.Unlock()
-
- return nil
-}
-
-func (w *Watcher) internalWatch(name string, fileInfo os.FileInfo) (string, error) {
- if fileInfo.IsDir() {
- // mimic Linux providing delete events for subdirectories
- // but preserve the flags used if currently watching subdirectory
- w.mu.Lock()
- flags := w.dirFlags[name]
- w.mu.Unlock()
-
- flags |= unix.NOTE_DELETE | unix.NOTE_RENAME
- return w.addWatch(name, flags)
- }
-
- // watch file to mimic Linux inotify
- return w.addWatch(name, noteAllEvents)
-}
-
-// kqueue creates a new kernel event queue and returns a descriptor.
-func kqueue() (kq int, err error) {
- kq, err = unix.Kqueue()
- if kq == -1 {
- return kq, err
- }
- return kq, nil
-}
-
-// register events with the queue
-func register(kq int, fds []int, flags int, fflags uint32) error {
- changes := make([]unix.Kevent_t, len(fds))
-
- for i, fd := range fds {
- // SetKevent converts int to the platform-specific types:
- unix.SetKevent(&changes[i], fd, unix.EVFILT_VNODE, flags)
- changes[i].Fflags = fflags
- }
-
- // register the events
- success, err := unix.Kevent(kq, changes, nil, nil)
- if success == -1 {
- return err
- }
- return nil
-}
-
-// read retrieves pending events, or waits until an event occurs.
-// A timeout of nil blocks indefinitely, while 0 polls the queue.
-func read(kq int, events []unix.Kevent_t, timeout *unix.Timespec) ([]unix.Kevent_t, error) {
- n, err := unix.Kevent(kq, nil, events, timeout)
- if err != nil {
- return nil, err
- }
- return events[0:n], nil
-}
-
-// durationToTimespec prepares a timeout value
-func durationToTimespec(d time.Duration) unix.Timespec {
- return unix.NsecToTimespec(d.Nanoseconds())
-}
diff --git a/vendor/github.com/fsnotify/fsnotify/open_mode_bsd.go b/vendor/github.com/fsnotify/fsnotify/open_mode_bsd.go
deleted file mode 100644
index 7d8de14..0000000
--- a/vendor/github.com/fsnotify/fsnotify/open_mode_bsd.go
+++ /dev/null
@@ -1,11 +0,0 @@
-// Copyright 2013 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.
-
-// +build freebsd openbsd netbsd dragonfly
-
-package fsnotify
-
-import "golang.org/x/sys/unix"
-
-const openMode = unix.O_NONBLOCK | unix.O_RDONLY
diff --git a/vendor/github.com/fsnotify/fsnotify/open_mode_darwin.go b/vendor/github.com/fsnotify/fsnotify/open_mode_darwin.go
deleted file mode 100644
index 9139e17..0000000
--- a/vendor/github.com/fsnotify/fsnotify/open_mode_darwin.go
+++ /dev/null
@@ -1,12 +0,0 @@
-// Copyright 2013 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.
-
-// +build darwin
-
-package fsnotify
-
-import "golang.org/x/sys/unix"
-
-// note: this constant is not defined on BSD
-const openMode = unix.O_EVTONLY
diff --git a/vendor/github.com/fsnotify/fsnotify/windows.go b/vendor/github.com/fsnotify/fsnotify/windows.go
deleted file mode 100644
index 09436f3..0000000
--- a/vendor/github.com/fsnotify/fsnotify/windows.go
+++ /dev/null
@@ -1,561 +0,0 @@
-// Copyright 2011 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.
-
-// +build windows
-
-package fsnotify
-
-import (
- "errors"
- "fmt"
- "os"
- "path/filepath"
- "runtime"
- "sync"
- "syscall"
- "unsafe"
-)
-
-// Watcher watches a set of files, delivering events to a channel.
-type Watcher struct {
- Events chan Event
- Errors chan error
- isClosed bool // Set to true when Close() is first called
- mu sync.Mutex // Map access
- port syscall.Handle // Handle to completion port
- watches watchMap // Map of watches (key: i-number)
- input chan *input // Inputs to the reader are sent on this channel
- quit chan chan<- error
-}
-
-// NewWatcher establishes a new watcher with the underlying OS and begins waiting for events.
-func NewWatcher() (*Watcher, error) {
- port, e := syscall.CreateIoCompletionPort(syscall.InvalidHandle, 0, 0, 0)
- if e != nil {
- return nil, os.NewSyscallError("CreateIoCompletionPort", e)
- }
- w := &Watcher{
- port: port,
- watches: make(watchMap),
- input: make(chan *input, 1),
- Events: make(chan Event, 50),
- Errors: make(chan error),
- quit: make(chan chan<- error, 1),
- }
- go w.readEvents()
- return w, nil
-}
-
-// Close removes all watches and closes the events channel.
-func (w *Watcher) Close() error {
- if w.isClosed {
- return nil
- }
- w.isClosed = true
-
- // Send "quit" message to the reader goroutine
- ch := make(chan error)
- w.quit <- ch
- if err := w.wakeupReader(); err != nil {
- return err
- }
- return <-ch
-}
-
-// Add starts watching the named file or directory (non-recursively).
-func (w *Watcher) Add(name string) error {
- if w.isClosed {
- return errors.New("watcher already closed")
- }
- in := &input{
- op: opAddWatch,
- path: filepath.Clean(name),
- flags: sysFSALLEVENTS,
- reply: make(chan error),
- }
- w.input <- in
- if err := w.wakeupReader(); err != nil {
- return err
- }
- return <-in.reply
-}
-
-// Remove stops watching the the named file or directory (non-recursively).
-func (w *Watcher) Remove(name string) error {
- in := &input{
- op: opRemoveWatch,
- path: filepath.Clean(name),
- reply: make(chan error),
- }
- w.input <- in
- if err := w.wakeupReader(); err != nil {
- return err
- }
- return <-in.reply
-}
-
-const (
- // Options for AddWatch
- sysFSONESHOT = 0x80000000
- sysFSONLYDIR = 0x1000000
-
- // Events
- sysFSACCESS = 0x1
- sysFSALLEVENTS = 0xfff
- sysFSATTRIB = 0x4
- sysFSCLOSE = 0x18
- sysFSCREATE = 0x100
- sysFSDELETE = 0x200
- sysFSDELETESELF = 0x400
- sysFSMODIFY = 0x2
- sysFSMOVE = 0xc0
- sysFSMOVEDFROM = 0x40
- sysFSMOVEDTO = 0x80
- sysFSMOVESELF = 0x800
-
- // Special events
- sysFSIGNORED = 0x8000
- sysFSQOVERFLOW = 0x4000
-)
-
-func newEvent(name string, mask uint32) Event {
- e := Event{Name: name}
- if mask&sysFSCREATE == sysFSCREATE || mask&sysFSMOVEDTO == sysFSMOVEDTO {
- e.Op |= Create
- }
- if mask&sysFSDELETE == sysFSDELETE || mask&sysFSDELETESELF == sysFSDELETESELF {
- e.Op |= Remove
- }
- if mask&sysFSMODIFY == sysFSMODIFY {
- e.Op |= Write
- }
- if mask&sysFSMOVE == sysFSMOVE || mask&sysFSMOVESELF == sysFSMOVESELF || mask&sysFSMOVEDFROM == sysFSMOVEDFROM {
- e.Op |= Rename
- }
- if mask&sysFSATTRIB == sysFSATTRIB {
- e.Op |= Chmod
- }
- return e
-}
-
-const (
- opAddWatch = iota
- opRemoveWatch
-)
-
-const (
- provisional uint64 = 1 << (32 + iota)
-)
-
-type input struct {
- op int
- path string
- flags uint32
- reply chan error
-}
-
-type inode struct {
- handle syscall.Handle
- volume uint32
- index uint64
-}
-
-type watch struct {
- ov syscall.Overlapped
- ino *inode // i-number
- path string // Directory path
- mask uint64 // Directory itself is being watched with these notify flags
- names map[string]uint64 // Map of names being watched and their notify flags
- rename string // Remembers the old name while renaming a file
- buf [4096]byte
-}
-
-type indexMap map[uint64]*watch
-type watchMap map[uint32]indexMap
-
-func (w *Watcher) wakeupReader() error {
- e := syscall.PostQueuedCompletionStatus(w.port, 0, 0, nil)
- if e != nil {
- return os.NewSyscallError("PostQueuedCompletionStatus", e)
- }
- return nil
-}
-
-func getDir(pathname string) (dir string, err error) {
- attr, e := syscall.GetFileAttributes(syscall.StringToUTF16Ptr(pathname))
- if e != nil {
- return "", os.NewSyscallError("GetFileAttributes", e)
- }
- if attr&syscall.FILE_ATTRIBUTE_DIRECTORY != 0 {
- dir = pathname
- } else {
- dir, _ = filepath.Split(pathname)
- dir = filepath.Clean(dir)
- }
- return
-}
-
-func getIno(path string) (ino *inode, err error) {
- h, e := syscall.CreateFile(syscall.StringToUTF16Ptr(path),
- syscall.FILE_LIST_DIRECTORY,
- syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE,
- nil, syscall.OPEN_EXISTING,
- syscall.FILE_FLAG_BACKUP_SEMANTICS|syscall.FILE_FLAG_OVERLAPPED, 0)
- if e != nil {
- return nil, os.NewSyscallError("CreateFile", e)
- }
- var fi syscall.ByHandleFileInformation
- if e = syscall.GetFileInformationByHandle(h, &fi); e != nil {
- syscall.CloseHandle(h)
- return nil, os.NewSyscallError("GetFileInformationByHandle", e)
- }
- ino = &inode{
- handle: h,
- volume: fi.VolumeSerialNumber,
- index: uint64(fi.FileIndexHigh)<<32 | uint64(fi.FileIndexLow),
- }
- return ino, nil
-}
-
-// Must run within the I/O thread.
-func (m watchMap) get(ino *inode) *watch {
- if i := m[ino.volume]; i != nil {
- return i[ino.index]
- }
- return nil
-}
-
-// Must run within the I/O thread.
-func (m watchMap) set(ino *inode, watch *watch) {
- i := m[ino.volume]
- if i == nil {
- i = make(indexMap)
- m[ino.volume] = i
- }
- i[ino.index] = watch
-}
-
-// Must run within the I/O thread.
-func (w *Watcher) addWatch(pathname string, flags uint64) error {
- dir, err := getDir(pathname)
- if err != nil {
- return err
- }
- if flags&sysFSONLYDIR != 0 && pathname != dir {
- return nil
- }
- ino, err := getIno(dir)
- if err != nil {
- return err
- }
- w.mu.Lock()
- watchEntry := w.watches.get(ino)
- w.mu.Unlock()
- if watchEntry == nil {
- if _, e := syscall.CreateIoCompletionPort(ino.handle, w.port, 0, 0); e != nil {
- syscall.CloseHandle(ino.handle)
- return os.NewSyscallError("CreateIoCompletionPort", e)
- }
- watchEntry = &watch{
- ino: ino,
- path: dir,
- names: make(map[string]uint64),
- }
- w.mu.Lock()
- w.watches.set(ino, watchEntry)
- w.mu.Unlock()
- flags |= provisional
- } else {
- syscall.CloseHandle(ino.handle)
- }
- if pathname == dir {
- watchEntry.mask |= flags
- } else {
- watchEntry.names[filepath.Base(pathname)] |= flags
- }
- if err = w.startRead(watchEntry); err != nil {
- return err
- }
- if pathname == dir {
- watchEntry.mask &= ^provisional
- } else {
- watchEntry.names[filepath.Base(pathname)] &= ^provisional
- }
- return nil
-}
-
-// Must run within the I/O thread.
-func (w *Watcher) remWatch(pathname string) error {
- dir, err := getDir(pathname)
- if err != nil {
- return err
- }
- ino, err := getIno(dir)
- if err != nil {
- return err
- }
- w.mu.Lock()
- watch := w.watches.get(ino)
- w.mu.Unlock()
- if watch == nil {
- return fmt.Errorf("can't remove non-existent watch for: %s", pathname)
- }
- if pathname == dir {
- w.sendEvent(watch.path, watch.mask&sysFSIGNORED)
- watch.mask = 0
- } else {
- name := filepath.Base(pathname)
- w.sendEvent(filepath.Join(watch.path, name), watch.names[name]&sysFSIGNORED)
- delete(watch.names, name)
- }
- return w.startRead(watch)
-}
-
-// Must run within the I/O thread.
-func (w *Watcher) deleteWatch(watch *watch) {
- for name, mask := range watch.names {
- if mask&provisional == 0 {
- w.sendEvent(filepath.Join(watch.path, name), mask&sysFSIGNORED)
- }
- delete(watch.names, name)
- }
- if watch.mask != 0 {
- if watch.mask&provisional == 0 {
- w.sendEvent(watch.path, watch.mask&sysFSIGNORED)
- }
- watch.mask = 0
- }
-}
-
-// Must run within the I/O thread.
-func (w *Watcher) startRead(watch *watch) error {
- if e := syscall.CancelIo(watch.ino.handle); e != nil {
- w.Errors <- os.NewSyscallError("CancelIo", e)
- w.deleteWatch(watch)
- }
- mask := toWindowsFlags(watch.mask)
- for _, m := range watch.names {
- mask |= toWindowsFlags(m)
- }
- if mask == 0 {
- if e := syscall.CloseHandle(watch.ino.handle); e != nil {
- w.Errors <- os.NewSyscallError("CloseHandle", e)
- }
- w.mu.Lock()
- delete(w.watches[watch.ino.volume], watch.ino.index)
- w.mu.Unlock()
- return nil
- }
- e := syscall.ReadDirectoryChanges(watch.ino.handle, &watch.buf[0],
- uint32(unsafe.Sizeof(watch.buf)), false, mask, nil, &watch.ov, 0)
- if e != nil {
- err := os.NewSyscallError("ReadDirectoryChanges", e)
- if e == syscall.ERROR_ACCESS_DENIED && watch.mask&provisional == 0 {
- // Watched directory was probably removed
- if w.sendEvent(watch.path, watch.mask&sysFSDELETESELF) {
- if watch.mask&sysFSONESHOT != 0 {
- watch.mask = 0
- }
- }
- err = nil
- }
- w.deleteWatch(watch)
- w.startRead(watch)
- return err
- }
- return nil
-}
-
-// readEvents reads from the I/O completion port, converts the
-// received events into Event objects and sends them via the Events channel.
-// Entry point to the I/O thread.
-func (w *Watcher) readEvents() {
- var (
- n, key uint32
- ov *syscall.Overlapped
- )
- runtime.LockOSThread()
-
- for {
- e := syscall.GetQueuedCompletionStatus(w.port, &n, &key, &ov, syscall.INFINITE)
- watch := (*watch)(unsafe.Pointer(ov))
-
- if watch == nil {
- select {
- case ch := <-w.quit:
- w.mu.Lock()
- var indexes []indexMap
- for _, index := range w.watches {
- indexes = append(indexes, index)
- }
- w.mu.Unlock()
- for _, index := range indexes {
- for _, watch := range index {
- w.deleteWatch(watch)
- w.startRead(watch)
- }
- }
- var err error
- if e := syscall.CloseHandle(w.port); e != nil {
- err = os.NewSyscallError("CloseHandle", e)
- }
- close(w.Events)
- close(w.Errors)
- ch <- err
- return
- case in := <-w.input:
- switch in.op {
- case opAddWatch:
- in.reply <- w.addWatch(in.path, uint64(in.flags))
- case opRemoveWatch:
- in.reply <- w.remWatch(in.path)
- }
- default:
- }
- continue
- }
-
- switch e {
- case syscall.ERROR_MORE_DATA:
- if watch == nil {
- w.Errors <- errors.New("ERROR_MORE_DATA has unexpectedly null lpOverlapped buffer")
- } else {
- // The i/o succeeded but the buffer is full.
- // In theory we should be building up a full packet.
- // In practice we can get away with just carrying on.
- n = uint32(unsafe.Sizeof(watch.buf))
- }
- case syscall.ERROR_ACCESS_DENIED:
- // Watched directory was probably removed
- w.sendEvent(watch.path, watch.mask&sysFSDELETESELF)
- w.deleteWatch(watch)
- w.startRead(watch)
- continue
- case syscall.ERROR_OPERATION_ABORTED:
- // CancelIo was called on this handle
- continue
- default:
- w.Errors <- os.NewSyscallError("GetQueuedCompletionPort", e)
- continue
- case nil:
- }
-
- var offset uint32
- for {
- if n == 0 {
- w.Events <- newEvent("", sysFSQOVERFLOW)
- w.Errors <- errors.New("short read in readEvents()")
- break
- }
-
- // Point "raw" to the event in the buffer
- raw := (*syscall.FileNotifyInformation)(unsafe.Pointer(&watch.buf[offset]))
- buf := (*[syscall.MAX_PATH]uint16)(unsafe.Pointer(&raw.FileName))
- name := syscall.UTF16ToString(buf[:raw.FileNameLength/2])
- fullname := filepath.Join(watch.path, name)
-
- var mask uint64
- switch raw.Action {
- case syscall.FILE_ACTION_REMOVED:
- mask = sysFSDELETESELF
- case syscall.FILE_ACTION_MODIFIED:
- mask = sysFSMODIFY
- case syscall.FILE_ACTION_RENAMED_OLD_NAME:
- watch.rename = name
- case syscall.FILE_ACTION_RENAMED_NEW_NAME:
- if watch.names[watch.rename] != 0 {
- watch.names[name] |= watch.names[watch.rename]
- delete(watch.names, watch.rename)
- mask = sysFSMOVESELF
- }
- }
-
- sendNameEvent := func() {
- if w.sendEvent(fullname, watch.names[name]&mask) {
- if watch.names[name]&sysFSONESHOT != 0 {
- delete(watch.names, name)
- }
- }
- }
- if raw.Action != syscall.FILE_ACTION_RENAMED_NEW_NAME {
- sendNameEvent()
- }
- if raw.Action == syscall.FILE_ACTION_REMOVED {
- w.sendEvent(fullname, watch.names[name]&sysFSIGNORED)
- delete(watch.names, name)
- }
- if w.sendEvent(fullname, watch.mask&toFSnotifyFlags(raw.Action)) {
- if watch.mask&sysFSONESHOT != 0 {
- watch.mask = 0
- }
- }
- if raw.Action == syscall.FILE_ACTION_RENAMED_NEW_NAME {
- fullname = filepath.Join(watch.path, watch.rename)
- sendNameEvent()
- }
-
- // Move to the next event in the buffer
- if raw.NextEntryOffset == 0 {
- break
- }
- offset += raw.NextEntryOffset
-
- // Error!
- if offset >= n {
- w.Errors <- errors.New("Windows system assumed buffer larger than it is, events have likely been missed.")
- break
- }
- }
-
- if err := w.startRead(watch); err != nil {
- w.Errors <- err
- }
- }
-}
-
-func (w *Watcher) sendEvent(name string, mask uint64) bool {
- if mask == 0 {
- return false
- }
- event := newEvent(name, uint32(mask))
- select {
- case ch := <-w.quit:
- w.quit <- ch
- case w.Events <- event:
- }
- return true
-}
-
-func toWindowsFlags(mask uint64) uint32 {
- var m uint32
- if mask&sysFSACCESS != 0 {
- m |= syscall.FILE_NOTIFY_CHANGE_LAST_ACCESS
- }
- if mask&sysFSMODIFY != 0 {
- m |= syscall.FILE_NOTIFY_CHANGE_LAST_WRITE
- }
- if mask&sysFSATTRIB != 0 {
- m |= syscall.FILE_NOTIFY_CHANGE_ATTRIBUTES
- }
- if mask&(sysFSMOVE|sysFSCREATE|sysFSDELETE) != 0 {
- m |= syscall.FILE_NOTIFY_CHANGE_FILE_NAME | syscall.FILE_NOTIFY_CHANGE_DIR_NAME
- }
- return m
-}
-
-func toFSnotifyFlags(action uint32) uint64 {
- switch action {
- case syscall.FILE_ACTION_ADDED:
- return sysFSCREATE
- case syscall.FILE_ACTION_REMOVED:
- return sysFSDELETE
- case syscall.FILE_ACTION_MODIFIED:
- return sysFSMODIFY
- case syscall.FILE_ACTION_RENAMED_OLD_NAME:
- return sysFSMOVEDFROM
- case syscall.FILE_ACTION_RENAMED_NEW_NAME:
- return sysFSMOVEDTO
- }
- return 0
-}
diff --git a/vendor/github.com/go-chi/chi/.gitignore b/vendor/github.com/go-chi/chi/.gitignore
deleted file mode 100644
index ba22c99..0000000
--- a/vendor/github.com/go-chi/chi/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-.idea
-*.sw?
-.vscode
diff --git a/vendor/github.com/go-chi/chi/.travis.yml b/vendor/github.com/go-chi/chi/.travis.yml
deleted file mode 100644
index e9d2f4e..0000000
--- a/vendor/github.com/go-chi/chi/.travis.yml
+++ /dev/null
@@ -1,19 +0,0 @@
-language: go
-
-go:
- - 1.7.x
- - 1.8.x
- - 1.9.x
- - tip
-
-install:
- - go get -u golang.org/x/tools/cmd/goimports
- - go get -u github.com/golang/lint/golint
-
-script:
- - go get -d -t ./...
- - go vet ./...
- - golint ./...
- - go test ./...
- - >
- goimports -d -e ./ | grep '.*' && { echo; echo "Aborting due to non-empty goimports output."; exit 1; } || :
diff --git a/vendor/github.com/go-chi/chi/CHANGELOG.md b/vendor/github.com/go-chi/chi/CHANGELOG.md
deleted file mode 100644
index a43ce29..0000000
--- a/vendor/github.com/go-chi/chi/CHANGELOG.md
+++ /dev/null
@@ -1,102 +0,0 @@
-# Changelog
-
-## v3.3.0 (2017-10-10)
-
-- New chi.RegisterMethod(method) to add support for custom HTTP methods, see _examples/custom-method for usage
-- Deprecated LINK and UNLINK methods from the default list, please use `chi.RegisterMethod("LINK")` and `chi.RegisterMethod("UNLINK")` in an `init()` function
-
-
-## v3.2.1 (2017-08-31)
-
-- Add new `Match(rctx *Context, method, path string) bool` method to `Routes` interface
- and `Mux`. Match searches the mux's routing tree for a handler that matches the method/path
-- Add new `RouteMethod` to `*Context`
-- Add new `Routes` pointer to `*Context`
-- Add new `middleware.GetHead` to route missing HEAD requests to GET handler
-- Updated benchmarks (see README)
-
-
-## v3.1.5 (2017-08-02)
-
-- Setup golint and go vet for the project
-- As per golint, we've redefined `func ServerBaseContext(h http.Handler, baseCtx context.Context) http.Handler`
- to `func ServerBaseContext(baseCtx context.Context, h http.Handler) http.Handler`
-
-
-## v3.1.0 (2017-07-10)
-
-- Fix a few minor issues after v3 release
-- Move `docgen` sub-pkg to https://github.com/go-chi/docgen
-- Move `render` sub-pkg to https://github.com/go-chi/render
-- Add new `URLFormat` handler to chi/middleware sub-pkg to make working with url mime
- suffixes easier, ie. parsing `/articles/1.json` and `/articles/1.xml`. See comments in
- https://github.com/go-chi/chi/blob/master/middleware/url_format.go for example usage.
-
-
-## v3.0.0 (2017-06-21)
-
-- Major update to chi library with many exciting updates, but also some *breaking changes*
-- URL parameter syntax changed from `/:id` to `/{id}` for even more flexible routing, such as
- `/articles/{month}-{day}-{year}-{slug}`, `/articles/{id}`, and `/articles/{id}.{ext}` on the
- same router
-- Support for regexp for routing patterns, in the form of `/{paramKey:regExp}` for example:
- `r.Get("/articles/{name:[a-z]+}", h)` and `chi.URLParam(r, "name")`
-- Add `Method` and `MethodFunc` to `chi.Router` to allow routing definitions such as
- `r.Method("GET", "/", h)` which provides a cleaner interface for custom handlers like
- in `_examples/custom-handler`
-- Deprecating `mux#FileServer` helper function. Instead, we encourage users to create their
- own using file handler with the stdlib, see `_examples/fileserver` for an example
-- Add support for LINK/UNLINK http methods via `r.Method()` and `r.MethodFunc()`
-- Moved the chi project to its own organization, to allow chi-related community packages to
- be easily discovered and supported, at: https://github.com/go-chi
-- *NOTE:* please update your import paths to `"github.com/go-chi/chi"`
-- *NOTE:* chi v2 is still available at https://github.com/go-chi/chi/tree/v2
-
-
-## v2.1.0 (2017-03-30)
-
-- Minor improvements and update to the chi core library
-- Introduced a brand new `chi/render` sub-package to complete the story of building
- APIs to offer a pattern for managing well-defined request / response payloads. Please
- check out the updated `_examples/rest` example for how it works.
-- Added `MethodNotAllowed(h http.HandlerFunc)` to chi.Router interface
-
-
-## v2.0.0 (2017-01-06)
-
-- After many months of v2 being in an RC state with many companies and users running it in
- production, the inclusion of some improvements to the middlewares, we are very pleased to
- announce v2.0.0 of chi.
-
-
-## v2.0.0-rc1 (2016-07-26)
-
-- Huge update! chi v2 is a large refactor targetting Go 1.7+. As of Go 1.7, the popular
- community `"net/context"` package has been included in the standard library as `"context"` and
- utilized by `"net/http"` and `http.Request` to managing deadlines, cancelation signals and other
- request-scoped values. We're very excited about the new context addition and are proud to
- introduce chi v2, a minimal and powerful routing package for building large HTTP services,
- with zero external dependencies. Chi focuses on idiomatic design and encourages the use of
- stdlib HTTP handlers and middlwares.
-- chi v2 deprecates its `chi.Handler` interface and requires `http.Handler` or `http.HandlerFunc`
-- chi v2 stores URL routing parameters and patterns in the standard request context: `r.Context()`
-- chi v2 lower-level routing context is accessible by `chi.RouteContext(r.Context()) *chi.Context`,
- which provides direct access to URL routing parameters, the routing path and the matching
- routing patterns.
-- Users upgrading from chi v1 to v2, need to:
- 1. Update the old chi.Handler signature, `func(ctx context.Context, w http.ResponseWriter, r *http.Request)` to
- the standard http.Handler: `func(w http.ResponseWriter, r *http.Request)`
- 2. Use `chi.URLParam(r *http.Request, paramKey string) string`
- or `URLParamFromCtx(ctx context.Context, paramKey string) string` to access a url parameter value
-
-
-## v1.0.0 (2016-07-01)
-
-- Released chi v1 stable https://github.com/go-chi/chi/tree/v1.0.0 for Go 1.6 and older.
-
-
-## v0.9.0 (2016-03-31)
-
-- Reuse context objects via sync.Pool for zero-allocation routing [#33](https://github.com/go-chi/chi/pull/33)
-- BREAKING NOTE: due to subtle API changes, previously `chi.URLParams(ctx)["id"]` used to access url parameters
- has changed to: `chi.URLParam(ctx, "id")`
diff --git a/vendor/github.com/go-chi/chi/CONTRIBUTING.md b/vendor/github.com/go-chi/chi/CONTRIBUTING.md
deleted file mode 100644
index c0ac2df..0000000
--- a/vendor/github.com/go-chi/chi/CONTRIBUTING.md
+++ /dev/null
@@ -1,31 +0,0 @@
-# Contributing
-
-## Prerequisites
-
-1. [Install Go][go-install].
-2. Download the sources and switch the working directory:
-
- ```bash
- go get -u -d github.com/go-chi/chi
- cd $GOPATH/src/github.com/go-chi/chi
- ```
-
-## Submitting a Pull Request
-
-A typical workflow is:
-
-1. [Fork the repository.][fork] [This tip maybe also helpful.][go-fork-tip]
-2. [Create a topic branch.][branch]
-3. Add tests for your change.
-4. Run `go test`. If your tests pass, return to the step 3.
-5. Implement the change and ensure the steps from the previous step pass.
-6. Run `goimports -w .`, to ensure the new code conforms to Go formatting guideline.
-7. [Add, commit and push your changes.][git-help]
-8. [Submit a pull request.][pull-req]
-
-[go-install]: https://golang.org/doc/install
-[go-fork-tip]: http://blog.campoy.cat/2014/03/github-and-go-forking-pull-requests-and.html
-[fork]: https://help.github.com/articles/fork-a-repo
-[branch]: http://learn.github.com/p/branching.html
-[git-help]: https://guides.github.com
-[pull-req]: https://help.github.com/articles/using-pull-requests
diff --git a/vendor/github.com/go-chi/chi/LICENSE b/vendor/github.com/go-chi/chi/LICENSE
deleted file mode 100644
index d99f02f..0000000
--- a/vendor/github.com/go-chi/chi/LICENSE
+++ /dev/null
@@ -1,20 +0,0 @@
-Copyright (c) 2015-present Peter Kieltyka (https://github.com/pkieltyka), Google Inc.
-
-MIT License
-
-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.
diff --git a/vendor/github.com/go-chi/chi/README.md b/vendor/github.com/go-chi/chi/README.md
deleted file mode 100644
index 6429169..0000000
--- a/vendor/github.com/go-chi/chi/README.md
+++ /dev/null
@@ -1,440 +0,0 @@
-#
-
-
-[![GoDoc Widget]][GoDoc] [![Travis Widget]][Travis]
-
-`chi` is a lightweight, idiomatic and composable router for building Go 1.7+ HTTP services. It's
-especially good at helping you write large REST API services that are kept maintainable as your
-project grows and changes. `chi` is built on the new `context` package introduced in Go 1.7 to
-handle signaling, cancelation and request-scoped values across a handler chain.
-
-The focus of the project has been to seek out an elegant and comfortable design for writing
-REST API servers, written during the development of the Pressly API service that powers our
-public API service, which in turn powers all of our client-side applications.
-
-The key considerations of chi's design are: project structure, maintainability, standard http
-handlers (stdlib-only), developer productivity, and deconstructing a large system into many small
-parts. The core router `github.com/go-chi/chi` is quite small (less than 1000 LOC), but we've also
-included some useful/optional subpackages: [middleware](/middleware), [render](https://github.com/go-chi/render) and [docgen](https://github.com/go-chi/docgen). We hope you enjoy it too!
-
-## Install
-
-`go get -u github.com/go-chi/chi`
-
-
-## Features
-
-* **Lightweight** - cloc'd in ~1000 LOC for the chi router
-* **Fast** - yes, see [benchmarks](#benchmarks)
-* **100% compatible with net/http** - use any http or middleware pkg in the ecosystem that is also compatible with `net/http`
-* **Designed for modular/composable APIs** - middlewares, inline middlewares, route groups and subrouter mounting
-* **Context control** - built on new `context` package, providing value chaining, cancelations and timeouts
-* **Robust** - in production at Pressly, CloudFlare, Heroku, 99Designs, and many others (see [discussion](https://github.com/go-chi/chi/issues/91))
-* **Doc generation** - `docgen` auto-generates routing documentation from your source to JSON or Markdown
-* **No external dependencies** - plain ol' Go 1.7+ stdlib + net/http
-
-
-## Examples
-
-* [rest](https://github.com/go-chi/chi/blob/master/_examples/rest/main.go) - REST APIs made easy, productive and maintainable
-* [logging](https://github.com/go-chi/chi/blob/master/_examples/logging/main.go) - Easy structured logging for any backend
-* [limits](https://github.com/go-chi/chi/blob/master/_examples/limits/main.go) - Timeouts and Throttling
-* [todos-resource](https://github.com/go-chi/chi/blob/master/_examples/todos-resource/main.go) - Struct routers/handlers, an example of another code layout style
-* [versions](https://github.com/go-chi/chi/blob/master/_examples/versions/main.go) - Demo of `chi/render` subpkg
-* [fileserver](https://github.com/go-chi/chi/blob/master/_examples/fileserver/main.go) - Easily serve static files
-* [graceful](https://github.com/go-chi/chi/blob/master/_examples/graceful/main.go) - Graceful context signaling and server shutdown
-
-
-**As easy as:**
-
-```go
-package main
-
-import (
- "net/http"
- "github.com/go-chi/chi"
-)
-
-func main() {
- r := chi.NewRouter()
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("welcome"))
- })
- http.ListenAndServe(":3000", r)
-}
-```
-
-**REST Preview:**
-
-Here is a little preview of how routing looks like with chi. Also take a look at the generated routing docs
-in JSON ([routes.json](https://github.com/go-chi/chi/blob/master/_examples/rest/routes.json)) and in
-Markdown ([routes.md](https://github.com/go-chi/chi/blob/master/_examples/rest/routes.md)).
-
-I highly recommend reading the source of the [examples](#examples) listed above, they will show you all the features
-of chi and serve as a good form of documentation.
-
-```go
-import (
- //...
- "context"
- "github.com/go-chi/chi"
- "github.com/go-chi/chi/middleware"
-)
-
-func main() {
- r := chi.NewRouter()
-
- // A good base middleware stack
- r.Use(middleware.RequestID)
- r.Use(middleware.RealIP)
- r.Use(middleware.Logger)
- r.Use(middleware.Recoverer)
-
- // Set a timeout value on the request context (ctx), that will signal
- // through ctx.Done() that the request has timed out and further
- // processing should be stopped.
- r.Use(middleware.Timeout(60 * time.Second))
-
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("hi"))
- })
-
- // RESTy routes for "articles" resource
- r.Route("/articles", func(r chi.Router) {
- r.With(paginate).Get("/", listArticles) // GET /articles
- r.With(paginate).Get("/{month}-{day}-{year}", listArticlesByDate) // GET /articles/01-16-2017
-
- r.Post("/", createArticle) // POST /articles
- r.Get("/search", searchArticles) // GET /articles/search
-
- // Regexp url parameters:
- r.Get("/{articleSlug:[a-z-]+}", getArticleBySlug) // GET /articles/home-is-toronto
-
- // Subrouters:
- r.Route("/{articleID}", func(r chi.Router) {
- r.Use(ArticleCtx)
- r.Get("/", getArticle) // GET /articles/123
- r.Put("/", updateArticle) // PUT /articles/123
- r.Delete("/", deleteArticle) // DELETE /articles/123
- })
- })
-
- // Mount the admin sub-router
- r.Mount("/admin", adminRouter())
-
- http.ListenAndServe(":3333", r)
-}
-
-func ArticleCtx(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- articleID := chi.URLParam(r, "articleID")
- article, err := dbGetArticle(articleID)
- if err != nil {
- http.Error(w, http.StatusText(404), 404)
- return
- }
- ctx := context.WithValue(r.Context(), "article", article)
- next.ServeHTTP(w, r.WithContext(ctx))
- })
-}
-
-func getArticle(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- article, ok := ctx.Value("article").(*Article)
- if !ok {
- http.Error(w, http.StatusText(422), 422)
- return
- }
- w.Write([]byte(fmt.Sprintf("title:%s", article.Title)))
-}
-
-// A completely separate router for administrator routes
-func adminRouter() http.Handler {
- r := chi.NewRouter()
- r.Use(AdminOnly)
- r.Get("/", adminIndex)
- r.Get("/accounts", adminListAccounts)
- return r
-}
-
-func AdminOnly(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- perm, ok := ctx.Value("acl.permission").(YourPermissionType)
- if !ok || !perm.IsAdmin() {
- http.Error(w, http.StatusText(403), 403)
- return
- }
- next.ServeHTTP(w, r)
- })
-}
-```
-
-
-## Router design
-
-chi's router is based on a kind of [Patricia Radix trie](https://en.wikipedia.org/wiki/Radix_tree).
-The router is fully compatible with `net/http`.
-
-Built on top of the tree is the `Router` interface:
-
-```go
-// Router consisting of the core routing methods used by chi's Mux,
-// using only the standard net/http.
-type Router interface {
- http.Handler
- Routes
-
- // Use appends one of more middlewares onto the Router stack.
- Use(middlewares ...func(http.Handler) http.Handler)
-
- // With adds inline middlewares for an endpoint handler.
- With(middlewares ...func(http.Handler) http.Handler) Router
-
- // Group adds a new inline-Router along the current routing
- // path, with a fresh middleware stack for the inline-Router.
- Group(fn func(r Router)) Router
-
- // Route mounts a sub-Router along a `pattern`` string.
- Route(pattern string, fn func(r Router)) Router
-
- // Mount attaches another http.Handler along ./pattern/*
- Mount(pattern string, h http.Handler)
-
- // Handle and HandleFunc adds routes for `pattern` that matches
- // all HTTP methods.
- Handle(pattern string, h http.Handler)
- HandleFunc(pattern string, h http.HandlerFunc)
-
- // Method and MethodFunc adds routes for `pattern` that matches
- // the `method` HTTP method.
- Method(method, pattern string, h http.Handler)
- MethodFunc(method, pattern string, h http.HandlerFunc)
-
- // HTTP-method routing along `pattern`
- Connect(pattern string, h http.HandlerFunc)
- Delete(pattern string, h http.HandlerFunc)
- Get(pattern string, h http.HandlerFunc)
- Head(pattern string, h http.HandlerFunc)
- Options(pattern string, h http.HandlerFunc)
- Patch(pattern string, h http.HandlerFunc)
- Post(pattern string, h http.HandlerFunc)
- Put(pattern string, h http.HandlerFunc)
- Trace(pattern string, h http.HandlerFunc)
-
- // NotFound defines a handler to respond whenever a route could
- // not be found.
- NotFound(h http.HandlerFunc)
-
- // MethodNotAllowed defines a handler to respond whenever a method is
- // not allowed.
- MethodNotAllowed(h http.HandlerFunc)
-}
-
-// Routes interface adds two methods for router traversal, which is also
-// used by the `docgen` subpackage to generation documentation for Routers.
-type Routes interface {
- // Routes returns the routing tree in an easily traversable structure.
- Routes() []Route
-
- // Middlewares returns the list of middlewares in use by the router.
- Middlewares() Middlewares
-
- // Match searches the routing tree for a handler that matches
- // the method/path - similar to routing a http request, but without
- // executing the handler thereafter.
- Match(rctx *Context, method, path string) bool
-}
-```
-
-Each routing method accepts a URL `pattern` and chain of `handlers`. The URL pattern
-supports named params (ie. `/users/{userID}`) and wildcards (ie. `/admin/*`). URL parameters
-can be fetched at runtime by calling `chi.URLParam(r, "userID")` for named parameters
-and `chi.URLParam(r, "*")` for a wildcard parameter.
-
-
-### Middleware handlers
-
-chi's middlewares are just stdlib net/http middleware handlers. There is nothing special
-about them, which means the router and all the tooling is designed to be compatible and
-friendly with any middleware in the community. This offers much better extensibility and reuse
-of packages and is at the heart of chi's purpose.
-
-Here is an example of a standard net/http middleware handler using the new request context
-available in Go 1.7+. This middleware sets a hypothetical user identifier on the request
-context and calls the next handler in the chain.
-
-```go
-// HTTP middleware setting a value on the request context
-func MyMiddleware(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- ctx := context.WithValue(r.Context(), "user", "123")
- next.ServeHTTP(w, r.WithContext(ctx))
- })
-}
-```
-
-
-### Request handlers
-
-chi uses standard net/http request handlers. This little snippet is an example of a http.Handler
-func that reads a user identifier from the request context - hypothetically, identifying
-the user sending an authenticated request, validated+set by a previous middleware handler.
-
-```go
-// HTTP handler accessing data from the request context.
-func MyRequestHandler(w http.ResponseWriter, r *http.Request) {
- user := r.Context().Value("user").(string)
- w.Write([]byte(fmt.Sprintf("hi %s", user)))
-}
-```
-
-
-### URL parameters
-
-chi's router parses and stores URL parameters right onto the request context. Here is
-an example of how to access URL params in your net/http handlers. And of course, middlewares
-are able to access the same information.
-
-```go
-// HTTP handler accessing the url routing parameters.
-func MyRequestHandler(w http.ResponseWriter, r *http.Request) {
- userID := chi.URLParam(r, "userID") // from a route like /users/{userID}
-
- ctx := r.Context()
- key := ctx.Value("key").(string)
-
- w.Write([]byte(fmt.Sprintf("hi %v, %v", userID, key)))
-}
-```
-
-
-## Middlewares
-
-chi comes equipped with an optional `middleware` package, providing a suite of standard
-`net/http` middlewares. Please note, any middleware in the ecosystem that is also compatible
-with `net/http` can be used with chi's mux.
-
-### Core middlewares
-
------------------------------------------------------------------------------------------------------------
-| chi/middlware Handler | description |
-|:----------------------|:---------------------------------------------------------------------------------
-| Compress | Gzip compression for clients that accept compressed responses |
-| GetHead | Automatically route undefined HEAD requests to GET handlers |
-| Heartbeat | Monitoring endpoint to check the servers pulse |
-| Logger | Logs the start and end of each request with the elapsed processing time |
-| NoCache | Sets response headers to prevent clients from caching |
-| Profiler | Easily attach net/http/pprof to your routers |
-| RealIP | Sets a http.Request's RemoteAddr to either X-Forwarded-For or X-Real-IP |
-| Recoverer | Gracefully absorb panics and prints the stack trace |
-| RequestID | Injects a request ID into the context of each request |
-| RedirectSlashes | Redirect slashes on routing paths |
-| StripSlashes | Strip slashes on routing paths |
-| Throttle | Puts a ceiling on the number of concurrent requests |
-| Timeout | Signals to the request context when the timeout deadline is reached |
-| URLFormat | Parse extension from url and put it on request context |
-| WithValue | Short-hand middleware to set a key/value on the request context |
------------------------------------------------------------------------------------------------------------
-
-### Auxiliary middlewares & packages
-
-Please see https://github.com/go-chi for additional packages.
-
--------------------------------------------------------------------------------------------------------------
-| package | description |
-|:---------------------------------------------------|:------------------------------------------------------
-| [cors](https://github.com/go-chi/cors) | Cross-origin resource sharing (CORS) |
-| [jwtauth](https://github.com/go-chi/jwtauth) | JWT authentication |
-| [hostrouter](https://github.com/go-chi/hostrouter) | Domain/host based request routing |
-| [httpcoala](https://github.com/go-chi/httpcoala) | HTTP request coalescer |
-| [chi-authz](https://github.com/casbin/chi-authz) | Request ACL via https://github.com/hsluoyz/casbin |
--------------------------------------------------------------------------------------------------------------
-
-please [submit a PR](./CONTRIBUTING.md) if you'd like to include a link to a chi-compatible middleware
-
-
-## context?
-
-`context` is a tiny pkg that provides simple interface to signal context across call stacks
-and goroutines. It was originally written by [Sameer Ajmani](https://github.com/Sajmani)
-and is available in stdlib since go1.7.
-
-Learn more at https://blog.golang.org/context
-
-and..
-* Docs: https://golang.org/pkg/context
-* Source: https://github.com/golang/go/tree/master/src/context
-
-
-## Benchmarks
-
-The benchmark suite: https://github.com/pkieltyka/go-http-routing-benchmark
-
-Results as of Aug 31, 2017 on Go 1.9.0
-
-```shell
-BenchmarkChi_Param 3000000 607 ns/op 432 B/op 3 allocs/op
-BenchmarkChi_Param5 2000000 935 ns/op 432 B/op 3 allocs/op
-BenchmarkChi_Param20 1000000 1944 ns/op 432 B/op 3 allocs/op
-BenchmarkChi_ParamWrite 2000000 664 ns/op 432 B/op 3 allocs/op
-BenchmarkChi_GithubStatic 2000000 627 ns/op 432 B/op 3 allocs/op
-BenchmarkChi_GithubParam 2000000 847 ns/op 432 B/op 3 allocs/op
-BenchmarkChi_GithubAll 10000 175556 ns/op 87700 B/op 609 allocs/op
-BenchmarkChi_GPlusStatic 3000000 566 ns/op 432 B/op 3 allocs/op
-BenchmarkChi_GPlusParam 2000000 652 ns/op 432 B/op 3 allocs/op
-BenchmarkChi_GPlus2Params 2000000 767 ns/op 432 B/op 3 allocs/op
-BenchmarkChi_GPlusAll 200000 9794 ns/op 5616 B/op 39 allocs/op
-BenchmarkChi_ParseStatic 3000000 590 ns/op 432 B/op 3 allocs/op
-BenchmarkChi_ParseParam 2000000 656 ns/op 432 B/op 3 allocs/op
-BenchmarkChi_Parse2Params 2000000 715 ns/op 432 B/op 3 allocs/op
-BenchmarkChi_ParseAll 100000 18045 ns/op 11232 B/op 78 allocs/op
-BenchmarkChi_StaticAll 10000 108871 ns/op 67827 B/op 471 allocs/op
-```
-
-Comparison with other routers: https://gist.github.com/pkieltyka/c089f309abeb179cfc4deaa519956d8c
-
-NOTE: the allocs in the benchmark above are from the calls to http.Request's
-`WithContext(context.Context)` method that clones the http.Request, sets the `Context()`
-on the duplicated (alloc'd) request and returns it the new request object. This is just
-how setting context on a request in Go 1.7+ works.
-
-
-## Credits
-
-* Carl Jackson for https://github.com/zenazn/goji
- * Parts of chi's thinking comes from goji, and chi's middleware package
- sources from goji.
-* Armon Dadgar for https://github.com/armon/go-radix
-* Contributions: [@VojtechVitek](https://github.com/VojtechVitek)
-
-We'll be more than happy to see [your contributions](./CONTRIBUTING.md)!
-
-
-## Beyond REST
-
-chi is just a http router that lets you decompose request handling into many smaller layers.
-Many companies including Pressly.com (of course) use chi to write REST services for their public
-APIs. But, REST is just a convention for managing state via HTTP, and there's a lot of other pieces
-required to write a complete client-server system or network of microservices.
-
-Looking ahead beyond REST, I also recommend some newer works in the field coming from
-[gRPC](https://github.com/grpc/grpc-go), [NATS](https://nats.io), [go-kit](https://github.com/go-kit/kit)
-and even [graphql](https://github.com/graphql-go/graphql). They're all pretty cool with their
-own unique approaches and benefits. Specifically, I'd look at gRPC since it makes client-server
-communication feel like a single program on a single computer, no need to hand-write a client library
-and the request/response payloads are typed contracts. NATS is pretty amazing too as a super
-fast and lightweight pub-sub transport that can speak protobufs, with nice service discovery -
-an excellent combination with gRPC.
-
-
-## License
-
-Copyright (c) 2015-present [Peter Kieltyka](https://github.com/pkieltyka)
-
-Licensed under [MIT License](./LICENSE)
-
-[GoDoc]: https://godoc.org/github.com/go-chi/chi
-[GoDoc Widget]: https://godoc.org/github.com/go-chi/chi?status.svg
-[Travis]: https://travis-ci.org/go-chi/chi
-[Travis Widget]: https://travis-ci.org/go-chi/chi.svg?branch=master
diff --git a/vendor/github.com/go-chi/chi/chain.go b/vendor/github.com/go-chi/chi/chain.go
deleted file mode 100644
index 88e6846..0000000
--- a/vendor/github.com/go-chi/chi/chain.go
+++ /dev/null
@@ -1,49 +0,0 @@
-package chi
-
-import "net/http"
-
-// Chain returns a Middlewares type from a slice of middleware handlers.
-func Chain(middlewares ...func(http.Handler) http.Handler) Middlewares {
- return Middlewares(middlewares)
-}
-
-// Handler builds and returns a http.Handler from the chain of middlewares,
-// with `h http.Handler` as the final handler.
-func (mws Middlewares) Handler(h http.Handler) http.Handler {
- return &ChainHandler{mws, h, chain(mws, h)}
-}
-
-// HandlerFunc builds and returns a http.Handler from the chain of middlewares,
-// with `h http.Handler` as the final handler.
-func (mws Middlewares) HandlerFunc(h http.HandlerFunc) http.Handler {
- return &ChainHandler{mws, h, chain(mws, h)}
-}
-
-// ChainHandler is a http.Handler with support for handler composition and
-// execution.
-type ChainHandler struct {
- Middlewares Middlewares
- Endpoint http.Handler
- chain http.Handler
-}
-
-func (c *ChainHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- c.chain.ServeHTTP(w, r)
-}
-
-// chain builds a http.Handler composed of an inline middleware stack and endpoint
-// handler in the order they are passed.
-func chain(middlewares []func(http.Handler) http.Handler, endpoint http.Handler) http.Handler {
- // Return ahead of time if there aren't any middlewares for the chain
- if len(middlewares) == 0 {
- return endpoint
- }
-
- // Wrap the end handler with the middleware chain
- h := middlewares[len(middlewares)-1](endpoint)
- for i := len(middlewares) - 2; i >= 0; i-- {
- h = middlewares[i](h)
- }
-
- return h
-}
diff --git a/vendor/github.com/go-chi/chi/chi.go b/vendor/github.com/go-chi/chi/chi.go
deleted file mode 100644
index 393e433..0000000
--- a/vendor/github.com/go-chi/chi/chi.go
+++ /dev/null
@@ -1,108 +0,0 @@
-//
-// Package chi is a small, idiomatic and composable router for building HTTP services.
-//
-// chi requires Go 1.7 or newer.
-//
-// Example:
-// package main
-//
-// import (
-// "net/http"
-//
-// "github.com/go-chi/chi"
-// "github.com/go-chi/chi/middleware"
-// )
-//
-// func main() {
-// r := chi.NewRouter()
-// r.Use(middleware.Logger)
-// r.Use(middleware.Recoverer)
-//
-// r.Get("/", func(w http.ResponseWriter, r *http.Request) {
-// w.Write([]byte("root."))
-// })
-//
-// http.ListenAndServe(":3333", r)
-// }
-//
-// See github.com/go-chi/chi/_examples/ for more in-depth examples.
-//
-package chi
-
-import "net/http"
-
-// NewRouter returns a new Mux object that implements the Router interface.
-func NewRouter() *Mux {
- return NewMux()
-}
-
-// Router consisting of the core routing methods used by chi's Mux,
-// using only the standard net/http.
-type Router interface {
- http.Handler
- Routes
-
- // Use appends one of more middlewares onto the Router stack.
- Use(middlewares ...func(http.Handler) http.Handler)
-
- // With adds inline middlewares for an endpoint handler.
- With(middlewares ...func(http.Handler) http.Handler) Router
-
- // Group adds a new inline-Router along the current routing
- // path, with a fresh middleware stack for the inline-Router.
- Group(fn func(r Router)) Router
-
- // Route mounts a sub-Router along a `pattern`` string.
- Route(pattern string, fn func(r Router)) Router
-
- // Mount attaches another http.Handler along ./pattern/*
- Mount(pattern string, h http.Handler)
-
- // Handle and HandleFunc adds routes for `pattern` that matches
- // all HTTP methods.
- Handle(pattern string, h http.Handler)
- HandleFunc(pattern string, h http.HandlerFunc)
-
- // Method and MethodFunc adds routes for `pattern` that matches
- // the `method` HTTP method.
- Method(method, pattern string, h http.Handler)
- MethodFunc(method, pattern string, h http.HandlerFunc)
-
- // HTTP-method routing along `pattern`
- Connect(pattern string, h http.HandlerFunc)
- Delete(pattern string, h http.HandlerFunc)
- Get(pattern string, h http.HandlerFunc)
- Head(pattern string, h http.HandlerFunc)
- Options(pattern string, h http.HandlerFunc)
- Patch(pattern string, h http.HandlerFunc)
- Post(pattern string, h http.HandlerFunc)
- Put(pattern string, h http.HandlerFunc)
- Trace(pattern string, h http.HandlerFunc)
-
- // NotFound defines a handler to respond whenever a route could
- // not be found.
- NotFound(h http.HandlerFunc)
-
- // MethodNotAllowed defines a handler to respond whenever a method is
- // not allowed.
- MethodNotAllowed(h http.HandlerFunc)
-}
-
-// Routes interface adds two methods for router traversal, which is also
-// used by the `docgen` subpackage to generation documentation for Routers.
-type Routes interface {
- // Routes returns the routing tree in an easily traversable structure.
- Routes() []Route
-
- // Middlewares returns the list of middlewares in use by the router.
- Middlewares() Middlewares
-
- // Match searches the routing tree for a handler that matches
- // the method/path - similar to routing a http request, but without
- // executing the handler thereafter.
- Match(rctx *Context, method, path string) bool
-}
-
-// Middlewares type is a slice of standard middleware handlers with methods
-// to compose middleware chains and http.Handler's.
-type Middlewares []func(http.Handler) http.Handler
diff --git a/vendor/github.com/go-chi/chi/context.go b/vendor/github.com/go-chi/chi/context.go
deleted file mode 100644
index 30c5afe..0000000
--- a/vendor/github.com/go-chi/chi/context.go
+++ /dev/null
@@ -1,161 +0,0 @@
-package chi
-
-import (
- "context"
- "net"
- "net/http"
- "strings"
-)
-
-var (
- // RouteCtxKey is the context.Context key to store the request context.
- RouteCtxKey = &contextKey{"RouteContext"}
-)
-
-// Context is the default routing context set on the root node of a
-// request context to track route patterns, URL parameters and
-// an optional routing path.
-type Context struct {
- Routes Routes
-
- // Routing path/method override used during the route search.
- // See Mux#routeHTTP method.
- RoutePath string
- RouteMethod string
-
- // Routing pattern stack throughout the lifecycle of the request,
- // across all connected routers. It is a record of all matching
- // patterns across a stack of sub-routers.
- RoutePatterns []string
-
- // URLParams are the stack of routeParams captured during the
- // routing lifecycle across a stack of sub-routers.
- URLParams RouteParams
-
- // The endpoint routing pattern that matched the request URI path
- // or `RoutePath` of the current sub-router. This value will update
- // during the lifecycle of a request passing through a stack of
- // sub-routers.
- routePattern string
-
- // Route parameters matched for the current sub-router. It is
- // intentionally unexported so it cant be tampered.
- routeParams RouteParams
-
- // methodNotAllowed hint
- methodNotAllowed bool
-}
-
-// NewRouteContext returns a new routing Context object.
-func NewRouteContext() *Context {
- return &Context{}
-}
-
-// Reset a routing context to its initial state.
-func (x *Context) Reset() {
- x.Routes = nil
- x.RoutePath = ""
- x.RouteMethod = ""
- x.RoutePatterns = x.RoutePatterns[:0]
- x.URLParams.Keys = x.URLParams.Keys[:0]
- x.URLParams.Values = x.URLParams.Values[:0]
-
- x.routePattern = ""
- x.routeParams.Keys = x.routeParams.Keys[:0]
- x.routeParams.Values = x.routeParams.Values[:0]
- x.methodNotAllowed = false
-}
-
-// URLParam returns the corresponding URL parameter value from the request
-// routing context.
-func (x *Context) URLParam(key string) string {
- for k := len(x.URLParams.Keys) - 1; k >= 0; k-- {
- if x.URLParams.Keys[k] == key {
- return x.URLParams.Values[k]
- }
- }
- return ""
-}
-
-// RoutePattern builds the routing pattern string for the particular
-// request, at the particular point during routing. This means, the value
-// will change throughout the execution of a request in a router. That is
-// why its advised to only use this value after calling the next handler.
-//
-// For example,
-//
-// func Instrument(next http.Handler) http.Handler {
-// return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
-// next.ServeHTTP(w, r)
-// routePattern := chi.RouteContext(r.Context()).RoutePattern()
-// measure(w, r, routePattern)
-// })
-// }
-func (x *Context) RoutePattern() string {
- routePattern := strings.Join(x.RoutePatterns, "")
- return strings.Replace(routePattern, "/*/", "/", -1)
-}
-
-// RouteContext returns chi's routing Context object from a
-// http.Request Context.
-func RouteContext(ctx context.Context) *Context {
- return ctx.Value(RouteCtxKey).(*Context)
-}
-
-// URLParam returns the url parameter from a http.Request object.
-func URLParam(r *http.Request, key string) string {
- if rctx := RouteContext(r.Context()); rctx != nil {
- return rctx.URLParam(key)
- }
- return ""
-}
-
-// URLParamFromCtx returns the url parameter from a http.Request Context.
-func URLParamFromCtx(ctx context.Context, key string) string {
- if rctx := RouteContext(ctx); rctx != nil {
- return rctx.URLParam(key)
- }
- return ""
-}
-
-// RouteParams is a structure to track URL routing parameters efficiently.
-type RouteParams struct {
- Keys, Values []string
-}
-
-// Add will append a URL parameter to the end of the route param
-func (s *RouteParams) Add(key, value string) {
- (*s).Keys = append((*s).Keys, key)
- (*s).Values = append((*s).Values, value)
-}
-
-// ServerBaseContext wraps an http.Handler to set the request context to the
-// `baseCtx`.
-func ServerBaseContext(baseCtx context.Context, h http.Handler) http.Handler {
- fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- baseCtx := baseCtx
-
- // Copy over default net/http server context keys
- if v, ok := ctx.Value(http.ServerContextKey).(*http.Server); ok {
- baseCtx = context.WithValue(baseCtx, http.ServerContextKey, v)
- }
- if v, ok := ctx.Value(http.LocalAddrContextKey).(net.Addr); ok {
- baseCtx = context.WithValue(baseCtx, http.LocalAddrContextKey, v)
- }
-
- h.ServeHTTP(w, r.WithContext(baseCtx))
- })
- return fn
-}
-
-// contextKey is a value for use with context.WithValue. It's used as
-// a pointer so it fits in an interface{} without allocation. This technique
-// for defining context keys was copied from Go 1.7's new use of context in net/http.
-type contextKey struct {
- name string
-}
-
-func (k *contextKey) String() string {
- return "chi context value " + k.name
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/closenotify17.go b/vendor/github.com/go-chi/chi/middleware/closenotify17.go
deleted file mode 100644
index 95802b1..0000000
--- a/vendor/github.com/go-chi/chi/middleware/closenotify17.go
+++ /dev/null
@@ -1,42 +0,0 @@
-// +build go1.7,!go1.8
-
-package middleware
-
-import (
- "context"
- "net/http"
-)
-
-// CloseNotify is a middleware that cancels ctx when the underlying
-// connection has gone away. It can be used to cancel long operations
-// on the server when the client disconnects before the response is ready.
-//
-// Note: this behaviour is standard in Go 1.8+, so the middleware does nothing
-// on 1.8+ and exists just for backwards compatibility.
-func CloseNotify(next http.Handler) http.Handler {
- fn := func(w http.ResponseWriter, r *http.Request) {
- cn, ok := w.(http.CloseNotifier)
- if !ok {
- panic("chi/middleware: CloseNotify expects http.ResponseWriter to implement http.CloseNotifier interface")
- }
- closeNotifyCh := cn.CloseNotify()
-
- ctx, cancel := context.WithCancel(r.Context())
- defer cancel()
-
- go func() {
- select {
- case <-ctx.Done():
- return
- case <-closeNotifyCh:
- cancel()
- return
- }
- }()
-
- r = r.WithContext(ctx)
- next.ServeHTTP(w, r)
- }
-
- return http.HandlerFunc(fn)
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/closenotify18.go b/vendor/github.com/go-chi/chi/middleware/closenotify18.go
deleted file mode 100644
index 4f0d73c..0000000
--- a/vendor/github.com/go-chi/chi/middleware/closenotify18.go
+++ /dev/null
@@ -1,17 +0,0 @@
-// +build go1.8 appengine
-
-package middleware
-
-import (
- "net/http"
-)
-
-// CloseNotify is a middleware that cancels ctx when the underlying
-// connection has gone away. It can be used to cancel long operations
-// on the server when the client disconnects before the response is ready.
-//
-// Note: this behaviour is standard in Go 1.8+, so the middleware does nothing
-// on 1.8+ and exists just for backwards compatibility.
-func CloseNotify(next http.Handler) http.Handler {
- return next
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/compress.go b/vendor/github.com/go-chi/chi/middleware/compress.go
deleted file mode 100644
index 006ad48..0000000
--- a/vendor/github.com/go-chi/chi/middleware/compress.go
+++ /dev/null
@@ -1,212 +0,0 @@
-package middleware
-
-import (
- "bufio"
- "compress/flate"
- "compress/gzip"
- "errors"
- "io"
- "net"
- "net/http"
- "strings"
-)
-
-type encoding int
-
-const (
- encodingNone encoding = iota
- encodingGzip
- encodingDeflate
-)
-
-var defaultContentTypes = map[string]struct{}{
- "text/html": struct{}{},
- "text/css": struct{}{},
- "text/plain": struct{}{},
- "text/javascript": struct{}{},
- "application/javascript": struct{}{},
- "application/x-javascript": struct{}{},
- "application/json": struct{}{},
- "application/atom+xml": struct{}{},
- "application/rss+xml": struct{}{},
-}
-
-// DefaultCompress is a middleware that compresses response
-// body of predefined content types to a data format based
-// on Accept-Encoding request header. It uses a default
-// compression level.
-func DefaultCompress(next http.Handler) http.Handler {
- return Compress(flate.DefaultCompression)(next)
-}
-
-// Compress is a middleware that compresses response
-// body of a given content types to a data format based
-// on Accept-Encoding request header. It uses a given
-// compression level.
-func Compress(level int, types ...string) func(next http.Handler) http.Handler {
- contentTypes := defaultContentTypes
- if len(types) > 0 {
- contentTypes = make(map[string]struct{}, len(types))
- for _, t := range types {
- contentTypes[t] = struct{}{}
- }
- }
-
- return func(next http.Handler) http.Handler {
- fn := func(w http.ResponseWriter, r *http.Request) {
- mcw := &maybeCompressResponseWriter{
- ResponseWriter: w,
- w: w,
- contentTypes: contentTypes,
- encoding: selectEncoding(r.Header),
- level: level,
- }
- defer mcw.Close()
-
- next.ServeHTTP(mcw, r)
- }
-
- return http.HandlerFunc(fn)
- }
-}
-
-func selectEncoding(h http.Header) encoding {
- enc := h.Get("Accept-Encoding")
-
- switch {
- // TODO:
- // case "br": // Brotli, experimental. Firefox 2016, to-be-in Chromium.
- // case "lzma": // Opera.
- // case "sdch": // Chrome, Android. Gzip output + dictionary header.
-
- case strings.Contains(enc, "gzip"):
- // TODO: Exception for old MSIE browsers that can't handle non-HTML?
- // https://zoompf.com/blog/2012/02/lose-the-wait-http-compression
- return encodingGzip
-
- case strings.Contains(enc, "deflate"):
- // HTTP 1.1 "deflate" (RFC 2616) stands for DEFLATE data (RFC 1951)
- // wrapped with zlib (RFC 1950). The zlib wrapper uses Adler-32
- // checksum compared to CRC-32 used in "gzip" and thus is faster.
- //
- // But.. some old browsers (MSIE, Safari 5.1) incorrectly expect
- // raw DEFLATE data only, without the mentioned zlib wrapper.
- // Because of this major confusion, most modern browsers try it
- // both ways, first looking for zlib headers.
- // Quote by Mark Adler: http://stackoverflow.com/a/9186091/385548
- //
- // The list of browsers having problems is quite big, see:
- // http://zoompf.com/blog/2012/02/lose-the-wait-http-compression
- // https://web.archive.org/web/20120321182910/http://www.vervestudios.co/projects/compression-tests/results
- //
- // That's why we prefer gzip over deflate. It's just more reliable
- // and not significantly slower than gzip.
- return encodingDeflate
-
- // NOTE: Not implemented, intentionally:
- // case "compress": // LZW. Deprecated.
- // case "bzip2": // Too slow on-the-fly.
- // case "zopfli": // Too slow on-the-fly.
- // case "xz": // Too slow on-the-fly.
- }
-
- return encodingNone
-}
-
-type maybeCompressResponseWriter struct {
- http.ResponseWriter
- w io.Writer
- encoding encoding
- contentTypes map[string]struct{}
- level int
- wroteHeader bool
-}
-
-func (w *maybeCompressResponseWriter) WriteHeader(code int) {
- if w.wroteHeader {
- return
- }
- w.wroteHeader = true
- defer w.ResponseWriter.WriteHeader(code)
-
- // Already compressed data?
- if w.ResponseWriter.Header().Get("Content-Encoding") != "" {
- return
- }
- // The content-length after compression is unknown
- w.ResponseWriter.Header().Del("Content-Length")
-
- // Parse the first part of the Content-Type response header.
- contentType := ""
- parts := strings.Split(w.ResponseWriter.Header().Get("Content-Type"), ";")
- if len(parts) > 0 {
- contentType = parts[0]
- }
-
- // Is the content type compressable?
- if _, ok := w.contentTypes[contentType]; !ok {
- return
- }
-
- // Select the compress writer.
- switch w.encoding {
- case encodingGzip:
- gw, err := gzip.NewWriterLevel(w.ResponseWriter, w.level)
- if err != nil {
- w.w = w.ResponseWriter
- return
- }
- w.w = gw
- w.ResponseWriter.Header().Set("Content-Encoding", "gzip")
-
- case encodingDeflate:
- dw, err := flate.NewWriter(w.ResponseWriter, w.level)
- if err != nil {
- w.w = w.ResponseWriter
- return
- }
- w.w = dw
- w.ResponseWriter.Header().Set("Content-Encoding", "deflate")
- }
-}
-
-func (w *maybeCompressResponseWriter) Write(p []byte) (int, error) {
- if !w.wroteHeader {
- w.WriteHeader(http.StatusOK)
- }
-
- return w.w.Write(p)
-}
-
-func (w *maybeCompressResponseWriter) Flush() {
- if f, ok := w.w.(http.Flusher); ok {
- f.Flush()
- }
-}
-
-func (w *maybeCompressResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
- if hj, ok := w.w.(http.Hijacker); ok {
- return hj.Hijack()
- }
- return nil, nil, errors.New("chi/middleware: http.Hijacker is unavailable on the writer")
-}
-
-func (w *maybeCompressResponseWriter) CloseNotify() <-chan bool {
- if cn, ok := w.w.(http.CloseNotifier); ok {
- return cn.CloseNotify()
- }
-
- // If the underlying writer does not implement http.CloseNotifier, return
- // a channel that never receives a value. The semantics here is that the
- // client never disconnnects before the request is processed by the
- // http.Handler, which is close enough to the default behavior (when
- // CloseNotify() is not even called).
- return make(chan bool, 1)
-}
-
-func (w *maybeCompressResponseWriter) Close() error {
- if c, ok := w.w.(io.WriteCloser); ok {
- return c.Close()
- }
- return errors.New("chi/middleware: io.WriteCloser is unavailable on the writer")
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/compress18.go b/vendor/github.com/go-chi/chi/middleware/compress18.go
deleted file mode 100644
index 0048f7d..0000000
--- a/vendor/github.com/go-chi/chi/middleware/compress18.go
+++ /dev/null
@@ -1,15 +0,0 @@
-// +build go1.8 appengine
-
-package middleware
-
-import (
- "errors"
- "net/http"
-)
-
-func (w *maybeCompressResponseWriter) Push(target string, opts *http.PushOptions) error {
- if ps, ok := w.w.(http.Pusher); ok {
- return ps.Push(target, opts)
- }
- return errors.New("chi/middleware: http.Pusher is unavailable on the writer")
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/get_head.go b/vendor/github.com/go-chi/chi/middleware/get_head.go
deleted file mode 100644
index 32b8dbb..0000000
--- a/vendor/github.com/go-chi/chi/middleware/get_head.go
+++ /dev/null
@@ -1,38 +0,0 @@
-package middleware
-
-import (
- "net/http"
-
- "github.com/go-chi/chi"
-)
-
-func GetHead(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.Method == "HEAD" {
- rctx := chi.RouteContext(r.Context())
- routePath := rctx.RoutePath
- if routePath == "" {
- if r.URL.RawPath != "" {
- routePath = r.URL.RawPath
- } else {
- routePath = r.URL.Path
- }
- }
-
- // Temporary routing context to look-ahead before routing the request
- tctx := chi.NewRouteContext()
-
- // Attempt to find a HEAD handler for the routing path, if not found, traverse
- // the router as through its a GET route, but proceed with the request
- // with the HEAD method.
- if !rctx.Routes.Match(tctx, "HEAD", routePath) {
- rctx.RouteMethod = "GET"
- rctx.RoutePath = routePath
- next.ServeHTTP(w, r)
- return
- }
- }
-
- next.ServeHTTP(w, r)
- })
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/get_head_test.go b/vendor/github.com/go-chi/chi/middleware/get_head_test.go
deleted file mode 100644
index edfeb5b..0000000
--- a/vendor/github.com/go-chi/chi/middleware/get_head_test.go
+++ /dev/null
@@ -1,66 +0,0 @@
-package middleware
-
-import (
- "net/http"
- "net/http/httptest"
- "testing"
-
- "github.com/go-chi/chi"
-)
-
-func TestGetHead(t *testing.T) {
- r := chi.NewRouter()
- r.Use(GetHead)
- r.Get("/hi", func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("X-Test", "yes")
- w.Write([]byte("bye"))
- })
- r.Route("/articles", func(r chi.Router) {
- r.Get("/{id}", func(w http.ResponseWriter, r *http.Request) {
- id := chi.URLParam(r, "id")
- w.Header().Set("X-Article", id)
- w.Write([]byte("article:" + id))
- })
- })
- r.Route("/users", func(r chi.Router) {
- r.Head("/{id}", func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("X-User", "-")
- w.Write([]byte("user"))
- })
- r.Get("/{id}", func(w http.ResponseWriter, r *http.Request) {
- id := chi.URLParam(r, "id")
- w.Header().Set("X-User", id)
- w.Write([]byte("user:" + id))
- })
- })
-
- ts := httptest.NewServer(r)
- defer ts.Close()
-
- if _, body := testRequest(t, ts, "GET", "/hi", nil); body != "bye" {
- t.Fatalf(body)
- }
- if req, body := testRequest(t, ts, "HEAD", "/hi", nil); body != "" || req.Header.Get("X-Test") != "yes" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "GET", "/", nil); body != "404 page not found\n" {
- t.Fatalf(body)
- }
- if req, body := testRequest(t, ts, "HEAD", "/", nil); body != "" || req.StatusCode != 404 {
- t.Fatalf(body)
- }
-
- if _, body := testRequest(t, ts, "GET", "/articles/5", nil); body != "article:5" {
- t.Fatalf(body)
- }
- if req, body := testRequest(t, ts, "HEAD", "/articles/5", nil); body != "" || req.Header.Get("X-Article") != "5" {
- t.Fatalf("expecting X-Article header '5' but got '%s'", req.Header.Get("X-Article"))
- }
-
- if _, body := testRequest(t, ts, "GET", "/users/1", nil); body != "user:1" {
- t.Fatalf(body)
- }
- if req, body := testRequest(t, ts, "HEAD", "/users/1", nil); body != "" || req.Header.Get("X-User") != "-" {
- t.Fatalf("expecting X-User header '-' but got '%s'", req.Header.Get("X-User"))
- }
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/heartbeat.go b/vendor/github.com/go-chi/chi/middleware/heartbeat.go
deleted file mode 100644
index fe822fb..0000000
--- a/vendor/github.com/go-chi/chi/middleware/heartbeat.go
+++ /dev/null
@@ -1,26 +0,0 @@
-package middleware
-
-import (
- "net/http"
- "strings"
-)
-
-// Heartbeat endpoint middleware useful to setting up a path like
-// `/ping` that load balancers or uptime testing external services
-// can make a request before hitting any routes. It's also convenient
-// to place this above ACL middlewares as well.
-func Heartbeat(endpoint string) func(http.Handler) http.Handler {
- f := func(h http.Handler) http.Handler {
- fn := func(w http.ResponseWriter, r *http.Request) {
- if r.Method == "GET" && strings.EqualFold(r.URL.Path, endpoint) {
- w.Header().Set("Content-Type", "text/plain")
- w.WriteHeader(http.StatusOK)
- w.Write([]byte("."))
- return
- }
- h.ServeHTTP(w, r)
- }
- return http.HandlerFunc(fn)
- }
- return f
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/logger.go b/vendor/github.com/go-chi/chi/middleware/logger.go
deleted file mode 100644
index 99fac03..0000000
--- a/vendor/github.com/go-chi/chi/middleware/logger.go
+++ /dev/null
@@ -1,154 +0,0 @@
-package middleware
-
-import (
- "bytes"
- "context"
- "log"
- "net/http"
- "os"
- "time"
-)
-
-var (
- // LogEntryCtxKey is the context.Context key to store the request log entry.
- LogEntryCtxKey = &contextKey{"LogEntry"}
-
- // DefaultLogger is called by the Logger middleware handler to log each request.
- // Its made a package-level variable so that it can be reconfigured for custom
- // logging configurations.
- DefaultLogger = RequestLogger(&DefaultLogFormatter{Logger: log.New(os.Stdout, "", log.LstdFlags)})
-)
-
-// Logger is a middleware that logs the start and end of each request, along
-// with some useful data about what was requested, what the response status was,
-// and how long it took to return. When standard output is a TTY, Logger will
-// print in color, otherwise it will print in black and white. Logger prints a
-// request ID if one is provided.
-//
-// Alternatively, look at https://github.com/pressly/lg and the `lg.RequestLogger`
-// middleware pkg.
-func Logger(next http.Handler) http.Handler {
- return DefaultLogger(next)
-}
-
-// RequestLogger returns a logger handler using a custom LogFormatter.
-func RequestLogger(f LogFormatter) func(next http.Handler) http.Handler {
- return func(next http.Handler) http.Handler {
- fn := func(w http.ResponseWriter, r *http.Request) {
- entry := f.NewLogEntry(r)
- ww := NewWrapResponseWriter(w, r.ProtoMajor)
-
- t1 := time.Now()
- defer func() {
- entry.Write(ww.Status(), ww.BytesWritten(), time.Since(t1))
- }()
-
- next.ServeHTTP(ww, WithLogEntry(r, entry))
- }
- return http.HandlerFunc(fn)
- }
-}
-
-// LogFormatter initiates the beginning of a new LogEntry per request.
-// See DefaultLogFormatter for an example implementation.
-type LogFormatter interface {
- NewLogEntry(r *http.Request) LogEntry
-}
-
-// LogEntry records the final log when a request completes.
-// See defaultLogEntry for an example implementation.
-type LogEntry interface {
- Write(status, bytes int, elapsed time.Duration)
- Panic(v interface{}, stack []byte)
-}
-
-// GetLogEntry returns the in-context LogEntry for a request.
-func GetLogEntry(r *http.Request) LogEntry {
- entry, _ := r.Context().Value(LogEntryCtxKey).(LogEntry)
- return entry
-}
-
-// WithLogEntry sets the in-context LogEntry for a request.
-func WithLogEntry(r *http.Request, entry LogEntry) *http.Request {
- r = r.WithContext(context.WithValue(r.Context(), LogEntryCtxKey, entry))
- return r
-}
-
-// LoggerInterface accepts printing to stdlib logger or compatible logger.
-type LoggerInterface interface {
- Print(v ...interface{})
-}
-
-// DefaultLogFormatter is a simple logger that implements a LogFormatter.
-type DefaultLogFormatter struct {
- Logger LoggerInterface
-}
-
-// NewLogEntry creates a new LogEntry for the request.
-func (l *DefaultLogFormatter) NewLogEntry(r *http.Request) LogEntry {
- entry := &defaultLogEntry{
- DefaultLogFormatter: l,
- request: r,
- buf: &bytes.Buffer{},
- }
-
- reqID := GetReqID(r.Context())
- if reqID != "" {
- cW(entry.buf, nYellow, "[%s] ", reqID)
- }
- cW(entry.buf, nCyan, "\"")
- cW(entry.buf, bMagenta, "%s ", r.Method)
-
- scheme := "http"
- if r.TLS != nil {
- scheme = "https"
- }
- cW(entry.buf, nCyan, "%s://%s%s %s\" ", scheme, r.Host, r.RequestURI, r.Proto)
-
- entry.buf.WriteString("from ")
- entry.buf.WriteString(r.RemoteAddr)
- entry.buf.WriteString(" - ")
-
- return entry
-}
-
-type defaultLogEntry struct {
- *DefaultLogFormatter
- request *http.Request
- buf *bytes.Buffer
-}
-
-func (l *defaultLogEntry) Write(status, bytes int, elapsed time.Duration) {
- switch {
- case status < 200:
- cW(l.buf, bBlue, "%03d", status)
- case status < 300:
- cW(l.buf, bGreen, "%03d", status)
- case status < 400:
- cW(l.buf, bCyan, "%03d", status)
- case status < 500:
- cW(l.buf, bYellow, "%03d", status)
- default:
- cW(l.buf, bRed, "%03d", status)
- }
-
- cW(l.buf, bBlue, " %dB", bytes)
-
- l.buf.WriteString(" in ")
- if elapsed < 500*time.Millisecond {
- cW(l.buf, nGreen, "%s", elapsed)
- } else if elapsed < 5*time.Second {
- cW(l.buf, nYellow, "%s", elapsed)
- } else {
- cW(l.buf, nRed, "%s", elapsed)
- }
-
- l.Logger.Print(l.buf.String())
-}
-
-func (l *defaultLogEntry) Panic(v interface{}, stack []byte) {
- panicEntry := l.NewLogEntry(l.request).(*defaultLogEntry)
- cW(panicEntry.buf, bRed, "panic: %+v", v)
- l.Logger.Print(panicEntry.buf.String())
- l.Logger.Print(string(stack))
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/middleware.go b/vendor/github.com/go-chi/chi/middleware/middleware.go
deleted file mode 100644
index be6a44f..0000000
--- a/vendor/github.com/go-chi/chi/middleware/middleware.go
+++ /dev/null
@@ -1,12 +0,0 @@
-package middleware
-
-// contextKey is a value for use with context.WithValue. It's used as
-// a pointer so it fits in an interface{} without allocation. This technique
-// for defining context keys was copied from Go 1.7's new use of context in net/http.
-type contextKey struct {
- name string
-}
-
-func (k *contextKey) String() string {
- return "chi/middleware context value " + k.name
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/middleware18_test.go b/vendor/github.com/go-chi/chi/middleware/middleware18_test.go
deleted file mode 100644
index 0a697ad..0000000
--- a/vendor/github.com/go-chi/chi/middleware/middleware18_test.go
+++ /dev/null
@@ -1,77 +0,0 @@
-// +build go1.8
-
-package middleware
-
-import (
- "crypto/tls"
- "io"
- "net/http"
- "testing"
- "time"
-
- "golang.org/x/net/http2"
-)
-
-// NOTE: we must import `golang.org/x/net/http2` in order to explicitly enable
-// http2 transports for certain tests. The runtime pkg does not have this dependency
-// though as the transport configuration happens under the hood on go 1.7+.
-
-func TestWrapWriterHTTP2(t *testing.T) {
- handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- _, cn := w.(http.CloseNotifier)
- if !cn {
- t.Fatal("request should have been a http.CloseNotifier")
- }
- _, fl := w.(http.Flusher)
- if !fl {
- t.Fatal("request should have been a http.Flusher")
- }
- _, hj := w.(http.Hijacker)
- if hj {
- t.Fatal("request should not have been a http.Hijacker")
- }
- _, rf := w.(io.ReaderFrom)
- if rf {
- t.Fatal("request should not have been a io.ReaderFrom")
- }
- _, ps := w.(http.Pusher)
- if !ps {
- t.Fatal("request should have been a http.Pusher")
- }
-
- w.Write([]byte("OK"))
- })
-
- wmw := func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- next.ServeHTTP(NewWrapResponseWriter(w, r.ProtoMajor), r)
- })
- }
-
- server := http.Server{
- Addr: ":7072",
- Handler: wmw(handler),
- }
- // By serving over TLS, we get HTTP2 requests
- go server.ListenAndServeTLS(testdataDir+"/cert.pem", testdataDir+"/key.pem")
- defer server.Close()
- // We need the server to start before making the request
- time.Sleep(100 * time.Millisecond)
-
- client := &http.Client{
- Transport: &http2.Transport{
- TLSClientConfig: &tls.Config{
- // The certificates we are using are self signed
- InsecureSkipVerify: true,
- },
- },
- }
-
- resp, err := client.Get("https://localhost:7072")
- if err != nil {
- t.Fatalf("could not get server: %v", err)
- }
- if resp.StatusCode != 200 {
- t.Fatalf("non 200 response: %v", resp.StatusCode)
- }
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/middleware_test.go b/vendor/github.com/go-chi/chi/middleware/middleware_test.go
deleted file mode 100644
index e004b29..0000000
--- a/vendor/github.com/go-chi/chi/middleware/middleware_test.go
+++ /dev/null
@@ -1,64 +0,0 @@
-package middleware
-
-import (
- "io"
- "io/ioutil"
- "net/http"
- "net/http/httptest"
- "path"
- "reflect"
- "runtime"
- "testing"
-)
-
-// NOTE: we must import `golang.org/x/net/http2` in order to explicitly enable
-// http2 transports for certain tests. The runtime pkg does not have this dependency
-// though as the transport configuration happens under the hood on go 1.7+.
-
-var testdataDir string
-
-func init() {
- _, filename, _, _ := runtime.Caller(0)
- testdataDir = path.Join(path.Dir(filename), "/../testdata")
-}
-
-func testRequest(t *testing.T, ts *httptest.Server, method, path string, body io.Reader) (*http.Response, string) {
- req, err := http.NewRequest(method, ts.URL+path, body)
- if err != nil {
- t.Fatal(err)
- return nil, ""
- }
-
- resp, err := http.DefaultClient.Do(req)
- if err != nil {
- t.Fatal(err)
- return nil, ""
- }
-
- respBody, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- t.Fatal(err)
- return nil, ""
- }
- defer resp.Body.Close()
-
- return resp, string(respBody)
-}
-
-func assertNoError(t *testing.T, err error) {
- if err != nil {
- t.Fatalf("expecting no error")
- }
-}
-
-func assertError(t *testing.T, err error) {
- if err == nil {
- t.Fatalf("expecting error")
- }
-}
-
-func assertEqual(t *testing.T, a, b interface{}) {
- if !reflect.DeepEqual(a, b) {
- t.Fatalf("expecting values to be equal but got: '%v' and '%v'", a, b)
- }
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/nocache.go b/vendor/github.com/go-chi/chi/middleware/nocache.go
deleted file mode 100644
index e5819dd..0000000
--- a/vendor/github.com/go-chi/chi/middleware/nocache.go
+++ /dev/null
@@ -1,58 +0,0 @@
-package middleware
-
-// Ported from Goji's middleware, source:
-// https://github.com/zenazn/goji/tree/master/web/middleware
-
-import (
- "net/http"
- "time"
-)
-
-// Unix epoch time
-var epoch = time.Unix(0, 0).Format(time.RFC1123)
-
-// Taken from https://github.com/mytrile/nocache
-var noCacheHeaders = map[string]string{
- "Expires": epoch,
- "Cache-Control": "no-cache, no-store, must-revalidate, private, max-age=0",
- "Pragma": "no-cache",
- "X-Accel-Expires": "0",
-}
-
-var etagHeaders = []string{
- "ETag",
- "If-Modified-Since",
- "If-Match",
- "If-None-Match",
- "If-Range",
- "If-Unmodified-Since",
-}
-
-// NoCache is a simple piece of middleware that sets a number of HTTP headers to prevent
-// a router (or subrouter) from being cached by an upstream proxy and/or client.
-//
-// As per http://wiki.nginx.org/HttpProxyModule - NoCache sets:
-// Expires: Thu, 01 Jan 1970 00:00:00 UTC
-// Cache-Control: no-cache, private, max-age=0
-// X-Accel-Expires: 0
-// Pragma: no-cache (for HTTP/1.0 proxies/clients)
-func NoCache(h http.Handler) http.Handler {
- fn := func(w http.ResponseWriter, r *http.Request) {
-
- // Delete any ETag headers that may have been set
- for _, v := range etagHeaders {
- if r.Header.Get(v) != "" {
- r.Header.Del(v)
- }
- }
-
- // Set our NoCache headers
- for k, v := range noCacheHeaders {
- w.Header().Set(k, v)
- }
-
- h.ServeHTTP(w, r)
- }
-
- return http.HandlerFunc(fn)
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/profiler.go b/vendor/github.com/go-chi/chi/middleware/profiler.go
deleted file mode 100644
index 620717e..0000000
--- a/vendor/github.com/go-chi/chi/middleware/profiler.go
+++ /dev/null
@@ -1,59 +0,0 @@
-package middleware
-
-import (
- "expvar"
- "fmt"
- "net/http"
- "net/http/pprof"
-
- "github.com/go-chi/chi"
-)
-
-// Profiler is a convenient subrouter used for mounting net/http/pprof. ie.
-//
-// func MyService() http.Handler {
-// r := chi.NewRouter()
-// // ..middlewares
-// r.Mount("/debug", middleware.Profiler())
-// // ..routes
-// return r
-// }
-func Profiler() http.Handler {
- r := chi.NewRouter()
- r.Use(NoCache)
-
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- http.Redirect(w, r, r.RequestURI+"/pprof/", 301)
- })
- r.HandleFunc("/pprof", func(w http.ResponseWriter, r *http.Request) {
- http.Redirect(w, r, r.RequestURI+"/", 301)
- })
-
- r.HandleFunc("/pprof/", pprof.Index)
- r.HandleFunc("/pprof/cmdline", pprof.Cmdline)
- r.HandleFunc("/pprof/profile", pprof.Profile)
- r.HandleFunc("/pprof/symbol", pprof.Symbol)
- r.HandleFunc("/pprof/trace", pprof.Trace)
- r.Handle("/pprof/block", pprof.Handler("block"))
- r.Handle("/pprof/heap", pprof.Handler("heap"))
- r.Handle("/pprof/goroutine", pprof.Handler("goroutine"))
- r.Handle("/pprof/threadcreate", pprof.Handler("threadcreate"))
- r.HandleFunc("/vars", expVars)
-
- return r
-}
-
-// Replicated from expvar.go as not public.
-func expVars(w http.ResponseWriter, r *http.Request) {
- first := true
- w.Header().Set("Content-Type", "application/json")
- fmt.Fprintf(w, "{\n")
- expvar.Do(func(kv expvar.KeyValue) {
- if !first {
- fmt.Fprintf(w, ",\n")
- }
- first = false
- fmt.Fprintf(w, "%q: %s", kv.Key, kv.Value)
- })
- fmt.Fprintf(w, "\n}\n")
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/realip.go b/vendor/github.com/go-chi/chi/middleware/realip.go
deleted file mode 100644
index e9addbe..0000000
--- a/vendor/github.com/go-chi/chi/middleware/realip.go
+++ /dev/null
@@ -1,54 +0,0 @@
-package middleware
-
-// Ported from Goji's middleware, source:
-// https://github.com/zenazn/goji/tree/master/web/middleware
-
-import (
- "net/http"
- "strings"
-)
-
-var xForwardedFor = http.CanonicalHeaderKey("X-Forwarded-For")
-var xRealIP = http.CanonicalHeaderKey("X-Real-IP")
-
-// RealIP is a middleware that sets a http.Request's RemoteAddr to the results
-// of parsing either the X-Forwarded-For header or the X-Real-IP header (in that
-// order).
-//
-// This middleware should be inserted fairly early in the middleware stack to
-// ensure that subsequent layers (e.g., request loggers) which examine the
-// RemoteAddr will see the intended value.
-//
-// You should only use this middleware if you can trust the headers passed to
-// you (in particular, the two headers this middleware uses), for example
-// because you have placed a reverse proxy like HAProxy or nginx in front of
-// Goji. If your reverse proxies are configured to pass along arbitrary header
-// values from the client, or if you use this middleware without a reverse
-// proxy, malicious clients will be able to make you very sad (or, depending on
-// how you're using RemoteAddr, vulnerable to an attack of some sort).
-func RealIP(h http.Handler) http.Handler {
- fn := func(w http.ResponseWriter, r *http.Request) {
- if rip := realIP(r); rip != "" {
- r.RemoteAddr = rip
- }
- h.ServeHTTP(w, r)
- }
-
- return http.HandlerFunc(fn)
-}
-
-func realIP(r *http.Request) string {
- var ip string
-
- if xff := r.Header.Get(xForwardedFor); xff != "" {
- i := strings.Index(xff, ", ")
- if i == -1 {
- i = len(xff)
- }
- ip = xff[:i]
- } else if xrip := r.Header.Get(xRealIP); xrip != "" {
- ip = xrip
- }
-
- return ip
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/realip_test.go b/vendor/github.com/go-chi/chi/middleware/realip_test.go
deleted file mode 100644
index 8470073..0000000
--- a/vendor/github.com/go-chi/chi/middleware/realip_test.go
+++ /dev/null
@@ -1,57 +0,0 @@
-package middleware
-
-import (
- "net/http"
- "net/http/httptest"
- "testing"
-
- "github.com/go-chi/chi"
-)
-
-func TestXRealIP(t *testing.T) {
- req, _ := http.NewRequest("GET", "/", nil)
- req.Header.Add("X-Real-IP", "100.100.100.100")
- w := httptest.NewRecorder()
-
- r := chi.NewRouter()
- r.Use(RealIP)
-
- realIP := ""
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- realIP = r.RemoteAddr
- w.Write([]byte("Hello World"))
- })
- r.ServeHTTP(w, req)
-
- if w.Code != 200 {
- t.Fatal("Response Code should be 200")
- }
-
- if realIP != "100.100.100.100" {
- t.Fatal("Test get real IP error.")
- }
-}
-
-func TestXForwardForIP(t *testing.T) {
- req, _ := http.NewRequest("GET", "/", nil)
- req.Header.Add("X-Forwarded-For", "100.100.100.100")
- w := httptest.NewRecorder()
-
- r := chi.NewRouter()
- r.Use(RealIP)
-
- realIP := ""
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- realIP = r.RemoteAddr
- w.Write([]byte("Hello World"))
- })
- r.ServeHTTP(w, req)
-
- if w.Code != 200 {
- t.Fatal("Response Code should be 200")
- }
-
- if realIP != "100.100.100.100" {
- t.Fatal("Test get real IP error.")
- }
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/recoverer.go b/vendor/github.com/go-chi/chi/middleware/recoverer.go
deleted file mode 100644
index 57fc3eb..0000000
--- a/vendor/github.com/go-chi/chi/middleware/recoverer.go
+++ /dev/null
@@ -1,39 +0,0 @@
-package middleware
-
-// The original work was derived from Goji's middleware, source:
-// https://github.com/zenazn/goji/tree/master/web/middleware
-
-import (
- "fmt"
- "net/http"
- "os"
- "runtime/debug"
-)
-
-// Recoverer is a middleware that recovers from panics, logs the panic (and a
-// backtrace), and returns a HTTP 500 (Internal Server Error) status if
-// possible. Recoverer prints a request ID if one is provided.
-//
-// Alternatively, look at https://github.com/pressly/lg middleware pkgs.
-func Recoverer(next http.Handler) http.Handler {
- fn := func(w http.ResponseWriter, r *http.Request) {
- defer func() {
- if rvr := recover(); rvr != nil {
-
- logEntry := GetLogEntry(r)
- if logEntry != nil {
- logEntry.Panic(rvr, debug.Stack())
- } else {
- fmt.Fprintf(os.Stderr, "Panic: %+v\n", rvr)
- debug.PrintStack()
- }
-
- http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
- }
- }()
-
- next.ServeHTTP(w, r)
- }
-
- return http.HandlerFunc(fn)
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/request_id.go b/vendor/github.com/go-chi/chi/middleware/request_id.go
deleted file mode 100644
index 4574bde..0000000
--- a/vendor/github.com/go-chi/chi/middleware/request_id.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package middleware
-
-// Ported from Goji's middleware, source:
-// https://github.com/zenazn/goji/tree/master/web/middleware
-
-import (
- "context"
- "crypto/rand"
- "encoding/base64"
- "fmt"
- "net/http"
- "os"
- "strings"
- "sync/atomic"
-)
-
-// Key to use when setting the request ID.
-type ctxKeyRequestID int
-
-// RequestIDKey is the key that holds th unique request ID in a request context.
-const RequestIDKey ctxKeyRequestID = 0
-
-var prefix string
-var reqid uint64
-
-// A quick note on the statistics here: we're trying to calculate the chance that
-// two randomly generated base62 prefixes will collide. We use the formula from
-// http://en.wikipedia.org/wiki/Birthday_problem
-//
-// P[m, n] \approx 1 - e^{-m^2/2n}
-//
-// We ballpark an upper bound for $m$ by imagining (for whatever reason) a server
-// that restarts every second over 10 years, for $m = 86400 * 365 * 10 = 315360000$
-//
-// For a $k$ character base-62 identifier, we have $n(k) = 62^k$
-//
-// Plugging this in, we find $P[m, n(10)] \approx 5.75%$, which is good enough for
-// our purposes, and is surely more than anyone would ever need in practice -- a
-// process that is rebooted a handful of times a day for a hundred years has less
-// than a millionth of a percent chance of generating two colliding IDs.
-
-func init() {
- hostname, err := os.Hostname()
- if hostname == "" || err != nil {
- hostname = "localhost"
- }
- var buf [12]byte
- var b64 string
- for len(b64) < 10 {
- rand.Read(buf[:])
- b64 = base64.StdEncoding.EncodeToString(buf[:])
- b64 = strings.NewReplacer("+", "", "/", "").Replace(b64)
- }
-
- prefix = fmt.Sprintf("%s/%s", hostname, b64[0:10])
-}
-
-// RequestID is a middleware that injects a request ID into the context of each
-// request. A request ID is a string of the form "host.example.com/random-0001",
-// where "random" is a base62 random string that uniquely identifies this go
-// process, and where the last number is an atomically incremented request
-// counter.
-func RequestID(next http.Handler) http.Handler {
- fn := func(w http.ResponseWriter, r *http.Request) {
- myid := atomic.AddUint64(&reqid, 1)
- ctx := r.Context()
- ctx = context.WithValue(ctx, RequestIDKey, fmt.Sprintf("%s-%06d", prefix, myid))
- next.ServeHTTP(w, r.WithContext(ctx))
- }
- return http.HandlerFunc(fn)
-}
-
-// GetReqID returns a request ID from the given context if one is present.
-// Returns the empty string if a request ID cannot be found.
-func GetReqID(ctx context.Context) string {
- if ctx == nil {
- return ""
- }
- if reqID, ok := ctx.Value(RequestIDKey).(string); ok {
- return reqID
- }
- return ""
-}
-
-// NextRequestID generates the next request ID in the sequence.
-func NextRequestID() uint64 {
- return atomic.AddUint64(&reqid, 1)
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/strip.go b/vendor/github.com/go-chi/chi/middleware/strip.go
deleted file mode 100644
index 8f19766..0000000
--- a/vendor/github.com/go-chi/chi/middleware/strip.go
+++ /dev/null
@@ -1,48 +0,0 @@
-package middleware
-
-import (
- "net/http"
-
- "github.com/go-chi/chi"
-)
-
-// StripSlashes is a middleware that will match request paths with a trailing
-// slash, strip it from the path and continue routing through the mux, if a route
-// matches, then it will serve the handler.
-func StripSlashes(next http.Handler) http.Handler {
- fn := func(w http.ResponseWriter, r *http.Request) {
- var path string
- rctx := chi.RouteContext(r.Context())
- if rctx.RoutePath != "" {
- path = rctx.RoutePath
- } else {
- path = r.URL.Path
- }
- if len(path) > 1 && path[len(path)-1] == '/' {
- rctx.RoutePath = path[:len(path)-1]
- }
- next.ServeHTTP(w, r)
- }
- return http.HandlerFunc(fn)
-}
-
-// RedirectSlashes is a middleware that will match request paths with a trailing
-// slash and redirect to the same path, less the trailing slash.
-func RedirectSlashes(next http.Handler) http.Handler {
- fn := func(w http.ResponseWriter, r *http.Request) {
- var path string
- rctx := chi.RouteContext(r.Context())
- if rctx.RoutePath != "" {
- path = rctx.RoutePath
- } else {
- path = r.URL.Path
- }
- if len(path) > 1 && path[len(path)-1] == '/' {
- path = path[:len(path)-1]
- http.Redirect(w, r, path, 301)
- return
- }
- next.ServeHTTP(w, r)
- }
- return http.HandlerFunc(fn)
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/strip_test.go b/vendor/github.com/go-chi/chi/middleware/strip_test.go
deleted file mode 100644
index f54479e..0000000
--- a/vendor/github.com/go-chi/chi/middleware/strip_test.go
+++ /dev/null
@@ -1,138 +0,0 @@
-package middleware
-
-import (
- "net/http"
- "net/http/httptest"
- "testing"
-
- "github.com/go-chi/chi"
-)
-
-func TestStripSlashes(t *testing.T) {
- r := chi.NewRouter()
-
- // This middleware must be mounted at the top level of the router, not at the end-handler
- // because then it'll be too late and will end up in a 404
- r.Use(StripSlashes)
-
- r.NotFound(func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(404)
- w.Write([]byte("nothing here"))
- })
-
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("root"))
- })
-
- r.Route("/accounts/{accountID}", func(r chi.Router) {
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- accountID := chi.URLParam(r, "accountID")
- w.Write([]byte(accountID))
- })
- })
-
- ts := httptest.NewServer(r)
- defer ts.Close()
-
- if _, resp := testRequest(t, ts, "GET", "/", nil); resp != "root" {
- t.Fatalf(resp)
- }
- if _, resp := testRequest(t, ts, "GET", "//", nil); resp != "root" {
- t.Fatalf(resp)
- }
- if _, resp := testRequest(t, ts, "GET", "/accounts/admin", nil); resp != "admin" {
- t.Fatalf(resp)
- }
- if _, resp := testRequest(t, ts, "GET", "/accounts/admin/", nil); resp != "admin" {
- t.Fatalf(resp)
- }
- if _, resp := testRequest(t, ts, "GET", "/nothing-here", nil); resp != "nothing here" {
- t.Fatalf(resp)
- }
-}
-
-func TestStripSlashesInRoute(t *testing.T) {
- r := chi.NewRouter()
-
- r.NotFound(func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(404)
- w.Write([]byte("nothing here"))
- })
-
- r.Get("/hi", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("hi"))
- })
-
- r.Route("/accounts/{accountID}", func(r chi.Router) {
- r.Use(StripSlashes)
- r.Get("/query", func(w http.ResponseWriter, r *http.Request) {
- accountID := chi.URLParam(r, "accountID")
- w.Write([]byte(accountID))
- })
- })
-
- ts := httptest.NewServer(r)
- defer ts.Close()
-
- if _, resp := testRequest(t, ts, "GET", "/hi", nil); resp != "hi" {
- t.Fatalf(resp)
- }
- if _, resp := testRequest(t, ts, "GET", "/hi/", nil); resp != "nothing here" {
- t.Fatalf(resp)
- }
- if _, resp := testRequest(t, ts, "GET", "/accounts/admin/query", nil); resp != "admin" {
- t.Fatalf(resp)
- }
- if _, resp := testRequest(t, ts, "GET", "/accounts/admin/query/", nil); resp != "admin" {
- t.Fatalf(resp)
- }
-}
-
-func TestRedirectSlashes(t *testing.T) {
- r := chi.NewRouter()
-
- // This middleware must be mounted at the top level of the router, not at the end-handler
- // because then it'll be too late and will end up in a 404
- r.Use(RedirectSlashes)
-
- r.NotFound(func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(404)
- w.Write([]byte("nothing here"))
- })
-
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("root"))
- })
-
- r.Route("/accounts/{accountID}", func(r chi.Router) {
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- accountID := chi.URLParam(r, "accountID")
- w.Write([]byte(accountID))
- })
- })
-
- ts := httptest.NewServer(r)
- defer ts.Close()
-
- if req, resp := testRequest(t, ts, "GET", "/", nil); resp != "root" && req.StatusCode != 200 {
- t.Fatalf(resp)
- }
-
- // NOTE: the testRequest client will follow the redirection..
- if req, resp := testRequest(t, ts, "GET", "//", nil); resp != "root" && req.StatusCode != 200 {
- t.Fatalf(resp)
- }
-
- if req, resp := testRequest(t, ts, "GET", "/accounts/admin", nil); resp != "admin" && req.StatusCode != 200 {
- t.Fatalf(resp)
- }
-
- // NOTE: the testRequest client will follow the redirection..
- if req, resp := testRequest(t, ts, "GET", "/accounts/admin/", nil); resp != "admin" && req.StatusCode != 200 {
- t.Fatalf(resp)
- }
-
- if req, resp := testRequest(t, ts, "GET", "/nothing-here", nil); resp != "nothing here" && req.StatusCode != 200 {
- t.Fatalf(resp)
- }
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/terminal.go b/vendor/github.com/go-chi/chi/middleware/terminal.go
deleted file mode 100644
index 79930a2..0000000
--- a/vendor/github.com/go-chi/chi/middleware/terminal.go
+++ /dev/null
@@ -1,63 +0,0 @@
-package middleware
-
-// Ported from Goji's middleware, source:
-// https://github.com/zenazn/goji/tree/master/web/middleware
-
-import (
- "fmt"
- "io"
- "os"
-)
-
-var (
- // Normal colors
- nBlack = []byte{'\033', '[', '3', '0', 'm'}
- nRed = []byte{'\033', '[', '3', '1', 'm'}
- nGreen = []byte{'\033', '[', '3', '2', 'm'}
- nYellow = []byte{'\033', '[', '3', '3', 'm'}
- nBlue = []byte{'\033', '[', '3', '4', 'm'}
- nMagenta = []byte{'\033', '[', '3', '5', 'm'}
- nCyan = []byte{'\033', '[', '3', '6', 'm'}
- nWhite = []byte{'\033', '[', '3', '7', 'm'}
- // Bright colors
- bBlack = []byte{'\033', '[', '3', '0', ';', '1', 'm'}
- bRed = []byte{'\033', '[', '3', '1', ';', '1', 'm'}
- bGreen = []byte{'\033', '[', '3', '2', ';', '1', 'm'}
- bYellow = []byte{'\033', '[', '3', '3', ';', '1', 'm'}
- bBlue = []byte{'\033', '[', '3', '4', ';', '1', 'm'}
- bMagenta = []byte{'\033', '[', '3', '5', ';', '1', 'm'}
- bCyan = []byte{'\033', '[', '3', '6', ';', '1', 'm'}
- bWhite = []byte{'\033', '[', '3', '7', ';', '1', 'm'}
-
- reset = []byte{'\033', '[', '0', 'm'}
-)
-
-var isTTY bool
-
-func init() {
- // This is sort of cheating: if stdout is a character device, we assume
- // that means it's a TTY. Unfortunately, there are many non-TTY
- // character devices, but fortunately stdout is rarely set to any of
- // them.
- //
- // We could solve this properly by pulling in a dependency on
- // code.google.com/p/go.crypto/ssh/terminal, for instance, but as a
- // heuristic for whether to print in color or in black-and-white, I'd
- // really rather not.
- fi, err := os.Stdout.Stat()
- if err == nil {
- m := os.ModeDevice | os.ModeCharDevice
- isTTY = fi.Mode()&m == m
- }
-}
-
-// colorWrite
-func cW(w io.Writer, color []byte, s string, args ...interface{}) {
- if isTTY {
- w.Write(color)
- }
- fmt.Fprintf(w, s, args...)
- if isTTY {
- w.Write(reset)
- }
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/throttle.go b/vendor/github.com/go-chi/chi/middleware/throttle.go
deleted file mode 100644
index d935e2c..0000000
--- a/vendor/github.com/go-chi/chi/middleware/throttle.go
+++ /dev/null
@@ -1,101 +0,0 @@
-package middleware
-
-import (
- "net/http"
- "time"
-)
-
-const (
- errCapacityExceeded = "Server capacity exceeded."
- errTimedOut = "Timed out while waiting for a pending request to complete."
- errContextCanceled = "Context was canceled."
-)
-
-var (
- defaultBacklogTimeout = time.Second * 60
-)
-
-// Throttle is a middleware that limits number of currently processed requests
-// at a time.
-func Throttle(limit int) func(http.Handler) http.Handler {
- return ThrottleBacklog(limit, 0, defaultBacklogTimeout)
-}
-
-// ThrottleBacklog is a middleware that limits number of currently processed
-// requests at a time and provides a backlog for holding a finite number of
-// pending requests.
-func ThrottleBacklog(limit int, backlogLimit int, backlogTimeout time.Duration) func(http.Handler) http.Handler {
- if limit < 1 {
- panic("chi/middleware: Throttle expects limit > 0")
- }
-
- if backlogLimit < 0 {
- panic("chi/middleware: Throttle expects backlogLimit to be positive")
- }
-
- t := throttler{
- tokens: make(chan token, limit),
- backlogTokens: make(chan token, limit+backlogLimit),
- backlogTimeout: backlogTimeout,
- }
-
- // Filling tokens.
- for i := 0; i < limit+backlogLimit; i++ {
- if i < limit {
- t.tokens <- token{}
- }
- t.backlogTokens <- token{}
- }
-
- fn := func(h http.Handler) http.Handler {
- t.h = h
- return &t
- }
-
- return fn
-}
-
-// token represents a request that is being processed.
-type token struct{}
-
-// throttler limits number of currently processed requests at a time.
-type throttler struct {
- h http.Handler
- tokens chan token
- backlogTokens chan token
- backlogTimeout time.Duration
-}
-
-// ServeHTTP is the primary throttler request handler
-func (t *throttler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- select {
- case <-ctx.Done():
- http.Error(w, errContextCanceled, http.StatusServiceUnavailable)
- return
- case btok := <-t.backlogTokens:
- timer := time.NewTimer(t.backlogTimeout)
-
- defer func() {
- t.backlogTokens <- btok
- }()
-
- select {
- case <-timer.C:
- http.Error(w, errTimedOut, http.StatusServiceUnavailable)
- return
- case <-ctx.Done():
- http.Error(w, errContextCanceled, http.StatusServiceUnavailable)
- return
- case tok := <-t.tokens:
- defer func() {
- t.tokens <- tok
- }()
- t.h.ServeHTTP(w, r)
- }
- return
- default:
- http.Error(w, errCapacityExceeded, http.StatusServiceUnavailable)
- return
- }
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/throttle_test.go b/vendor/github.com/go-chi/chi/middleware/throttle_test.go
deleted file mode 100644
index 626397e..0000000
--- a/vendor/github.com/go-chi/chi/middleware/throttle_test.go
+++ /dev/null
@@ -1,204 +0,0 @@
-package middleware
-
-import (
- "io/ioutil"
- "net/http"
- "net/http/httptest"
- "strings"
- "sync"
- "testing"
- "time"
-
- "github.com/go-chi/chi"
-)
-
-var testContent = []byte("Hello world!")
-
-func TestThrottleBacklog(t *testing.T) {
- r := chi.NewRouter()
-
- r.Use(ThrottleBacklog(10, 50, time.Second*10))
-
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(http.StatusOK)
- time.Sleep(time.Second * 1) // Expensive operation.
- w.Write(testContent)
- })
-
- server := httptest.NewServer(r)
- defer server.Close()
-
- client := http.Client{
- Timeout: time.Second * 5, // Maximum waiting time.
- }
-
- var wg sync.WaitGroup
-
- // The throttler proccesses 10 consecutive requests, each one of those
- // requests lasts 1s. The maximum number of requests this can possible serve
- // before the clients time out (5s) is 40.
- for i := 0; i < 40; i++ {
- wg.Add(1)
- go func(i int) {
- defer wg.Done()
-
- res, err := client.Get(server.URL)
- assertNoError(t, err)
-
- assertEqual(t, http.StatusOK, res.StatusCode)
- buf, err := ioutil.ReadAll(res.Body)
- assertNoError(t, err)
- assertEqual(t, testContent, buf)
- }(i)
- }
-
- wg.Wait()
-}
-
-func TestThrottleClientTimeout(t *testing.T) {
- r := chi.NewRouter()
-
- r.Use(ThrottleBacklog(10, 50, time.Second*10))
-
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(http.StatusOK)
- time.Sleep(time.Second * 5) // Expensive operation.
- w.Write(testContent)
- })
-
- server := httptest.NewServer(r)
- defer server.Close()
-
- client := http.Client{
- Timeout: time.Second * 3, // Maximum waiting time.
- }
-
- var wg sync.WaitGroup
-
- for i := 0; i < 10; i++ {
- wg.Add(1)
- go func(i int) {
- defer wg.Done()
- _, err := client.Get(server.URL)
- assertError(t, err)
- }(i)
- }
-
- wg.Wait()
-}
-
-func TestThrottleTriggerGatewayTimeout(t *testing.T) {
- r := chi.NewRouter()
-
- r.Use(ThrottleBacklog(50, 100, time.Second*5))
-
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(http.StatusOK)
- time.Sleep(time.Second * 10) // Expensive operation.
- w.Write(testContent)
- })
-
- server := httptest.NewServer(r)
- defer server.Close()
-
- client := http.Client{
- Timeout: time.Second * 60, // Maximum waiting time.
- }
-
- var wg sync.WaitGroup
-
- // These requests will be processed normally until they finish.
- for i := 0; i < 50; i++ {
- wg.Add(1)
- go func(i int) {
- defer wg.Done()
-
- res, err := client.Get(server.URL)
- assertNoError(t, err)
- assertEqual(t, http.StatusOK, res.StatusCode)
-
- }(i)
- }
-
- time.Sleep(time.Second * 1)
-
- // These requests will wait for the first batch to complete but it will take
- // too much time, so they will eventually receive a timeout error.
- for i := 0; i < 50; i++ {
- wg.Add(1)
- go func(i int) {
- defer wg.Done()
-
- res, err := client.Get(server.URL)
- assertNoError(t, err)
-
- buf, err := ioutil.ReadAll(res.Body)
- assertNoError(t, err)
- assertEqual(t, http.StatusServiceUnavailable, res.StatusCode)
- assertEqual(t, errTimedOut, strings.TrimSpace(string(buf)))
-
- }(i)
- }
-
- wg.Wait()
-}
-
-func TestThrottleMaximum(t *testing.T) {
- r := chi.NewRouter()
-
- r.Use(ThrottleBacklog(50, 50, time.Second*5))
-
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(http.StatusOK)
- time.Sleep(time.Second * 2) // Expensive operation.
- w.Write(testContent)
- })
-
- server := httptest.NewServer(r)
- defer server.Close()
-
- client := http.Client{
- Timeout: time.Second * 60, // Maximum waiting time.
- }
-
- var wg sync.WaitGroup
-
- for i := 0; i < 100; i++ {
- wg.Add(1)
- go func(i int) {
- defer wg.Done()
-
- res, err := client.Get(server.URL)
- assertNoError(t, err)
- assertEqual(t, http.StatusOK, res.StatusCode)
-
- buf, err := ioutil.ReadAll(res.Body)
- assertNoError(t, err)
- assertEqual(t, testContent, buf)
-
- }(i)
- }
-
- // Wait less time than what the server takes to reply.
- time.Sleep(time.Second * 1)
-
- // At this point the server is still processing, all the following request
- // will be beyond the server capacity.
- for i := 0; i < 100; i++ {
- wg.Add(1)
- go func(i int) {
- defer wg.Done()
-
- res, err := client.Get(server.URL)
- assertNoError(t, err)
-
- buf, err := ioutil.ReadAll(res.Body)
- assertNoError(t, err)
- assertEqual(t, http.StatusServiceUnavailable, res.StatusCode)
- assertEqual(t, errCapacityExceeded, strings.TrimSpace(string(buf)))
-
- }(i)
- }
-
- wg.Wait()
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/timeout.go b/vendor/github.com/go-chi/chi/middleware/timeout.go
deleted file mode 100644
index 5cabf1f..0000000
--- a/vendor/github.com/go-chi/chi/middleware/timeout.go
+++ /dev/null
@@ -1,48 +0,0 @@
-package middleware
-
-import (
- "context"
- "net/http"
- "time"
-)
-
-// Timeout is a middleware that cancels ctx after a given timeout and return
-// a 504 Gateway Timeout error to the client.
-//
-// It's required that you select the ctx.Done() channel to check for the signal
-// if the context has reached its deadline and return, otherwise the timeout
-// signal will be just ignored.
-//
-// ie. a route/handler may look like:
-//
-// r.Get("/long", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
-// processTime := time.Duration(rand.Intn(4)+1) * time.Second
-//
-// select {
-// case <-ctx.Done():
-// return
-//
-// case <-time.After(processTime):
-// // The above channel simulates some hard work.
-// }
-//
-// w.Write([]byte("done"))
-// })
-//
-func Timeout(timeout time.Duration) func(next http.Handler) http.Handler {
- return func(next http.Handler) http.Handler {
- fn := func(w http.ResponseWriter, r *http.Request) {
- ctx, cancel := context.WithTimeout(r.Context(), timeout)
- defer func() {
- cancel()
- if ctx.Err() == context.DeadlineExceeded {
- w.WriteHeader(http.StatusGatewayTimeout)
- }
- }()
-
- r = r.WithContext(ctx)
- next.ServeHTTP(w, r)
- }
- return http.HandlerFunc(fn)
- }
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/url_format.go b/vendor/github.com/go-chi/chi/middleware/url_format.go
deleted file mode 100644
index 5749e4f..0000000
--- a/vendor/github.com/go-chi/chi/middleware/url_format.go
+++ /dev/null
@@ -1,72 +0,0 @@
-package middleware
-
-import (
- "context"
- "net/http"
- "strings"
-
- "github.com/go-chi/chi"
-)
-
-var (
- // URLFormatCtxKey is the context.Context key to store the URL format data
- // for a request.
- URLFormatCtxKey = &contextKey{"URLFormat"}
-)
-
-// URLFormat is a middleware that parses the url extension from a request path and stores it
-// on the context as a string under the key `middleware.URLFormatCtxKey`. The middleware will
-// trim the suffix from the routing path and continue routing.
-//
-// Routers should not include a url parameter for the suffix when using this middleware.
-//
-// Sample usage.. for url paths: `/articles/1`, `/articles/1.json` and `/articles/1.xml`
-//
-// func routes() http.Handler {
-// r := chi.NewRouter()
-// r.Use(middleware.URLFormat)
-//
-// r.Get("/articles/{id}", ListArticles)
-//
-// return r
-// }
-//
-// func ListArticles(w http.ResponseWriter, r *http.Request) {
-// urlFormat, _ := r.Context().Value(middleware.URLFormatCtxKey).(string)
-//
-// switch urlFormat {
-// case "json":
-// render.JSON(w, r, articles)
-// case "xml:"
-// render.XML(w, r, articles)
-// default:
-// render.JSON(w, r, articles)
-// }
-// }
-//
-func URLFormat(next http.Handler) http.Handler {
- fn := func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
-
- var format string
- path := r.URL.Path
-
- if strings.Index(path, ".") > 0 {
- base := strings.LastIndex(path, "/")
- idx := strings.Index(path[base:], ".")
-
- if idx > 0 {
- idx += base
- format = path[idx+1:]
-
- rctx := chi.RouteContext(r.Context())
- rctx.RoutePath = path[:idx]
- }
- }
-
- r = r.WithContext(context.WithValue(ctx, URLFormatCtxKey, format))
-
- next.ServeHTTP(w, r)
- }
- return http.HandlerFunc(fn)
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/value.go b/vendor/github.com/go-chi/chi/middleware/value.go
deleted file mode 100644
index fbbd039..0000000
--- a/vendor/github.com/go-chi/chi/middleware/value.go
+++ /dev/null
@@ -1,17 +0,0 @@
-package middleware
-
-import (
- "context"
- "net/http"
-)
-
-// WithValue is a middleware that sets a given key/value in a context chain.
-func WithValue(key interface{}, val interface{}) func(next http.Handler) http.Handler {
- return func(next http.Handler) http.Handler {
- fn := func(w http.ResponseWriter, r *http.Request) {
- r = r.WithContext(context.WithValue(r.Context(), key, val))
- next.ServeHTTP(w, r)
- }
- return http.HandlerFunc(fn)
- }
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/wrap_writer.go b/vendor/github.com/go-chi/chi/middleware/wrap_writer.go
deleted file mode 100644
index 5d1c286..0000000
--- a/vendor/github.com/go-chi/chi/middleware/wrap_writer.go
+++ /dev/null
@@ -1,148 +0,0 @@
-package middleware
-
-// The original work was derived from Goji's middleware, source:
-// https://github.com/zenazn/goji/tree/master/web/middleware
-
-import (
- "bufio"
- "io"
- "net"
- "net/http"
-)
-
-// WrapResponseWriter is a proxy around an http.ResponseWriter that allows you to hook
-// into various parts of the response process.
-type WrapResponseWriter interface {
- http.ResponseWriter
- // Status returns the HTTP status of the request, or 0 if one has not
- // yet been sent.
- Status() int
- // BytesWritten returns the total number of bytes sent to the client.
- BytesWritten() int
- // Tee causes the response body to be written to the given io.Writer in
- // addition to proxying the writes through. Only one io.Writer can be
- // tee'd to at once: setting a second one will overwrite the first.
- // Writes will be sent to the proxy before being written to this
- // io.Writer. It is illegal for the tee'd writer to be modified
- // concurrently with writes.
- Tee(io.Writer)
- // Unwrap returns the original proxied target.
- Unwrap() http.ResponseWriter
-}
-
-// basicWriter wraps a http.ResponseWriter that implements the minimal
-// http.ResponseWriter interface.
-type basicWriter struct {
- http.ResponseWriter
- wroteHeader bool
- code int
- bytes int
- tee io.Writer
-}
-
-func (b *basicWriter) WriteHeader(code int) {
- if !b.wroteHeader {
- b.code = code
- b.wroteHeader = true
- b.ResponseWriter.WriteHeader(code)
- }
-}
-func (b *basicWriter) Write(buf []byte) (int, error) {
- b.WriteHeader(http.StatusOK)
- n, err := b.ResponseWriter.Write(buf)
- if b.tee != nil {
- _, err2 := b.tee.Write(buf[:n])
- // Prefer errors generated by the proxied writer.
- if err == nil {
- err = err2
- }
- }
- b.bytes += n
- return n, err
-}
-func (b *basicWriter) maybeWriteHeader() {
- if !b.wroteHeader {
- b.WriteHeader(http.StatusOK)
- }
-}
-func (b *basicWriter) Status() int {
- return b.code
-}
-func (b *basicWriter) BytesWritten() int {
- return b.bytes
-}
-func (b *basicWriter) Tee(w io.Writer) {
- b.tee = w
-}
-func (b *basicWriter) Unwrap() http.ResponseWriter {
- return b.ResponseWriter
-}
-
-type flushWriter struct {
- basicWriter
-}
-
-func (f *flushWriter) Flush() {
- fl := f.basicWriter.ResponseWriter.(http.Flusher)
- fl.Flush()
-}
-
-var _ http.Flusher = &flushWriter{}
-
-// httpFancyWriter is a HTTP writer that additionally satisfies http.CloseNotifier,
-// http.Flusher, http.Hijacker, and io.ReaderFrom. It exists for the common case
-// of wrapping the http.ResponseWriter that package http gives you, in order to
-// make the proxied object support the full method set of the proxied object.
-type httpFancyWriter struct {
- basicWriter
-}
-
-func (f *httpFancyWriter) CloseNotify() <-chan bool {
- cn := f.basicWriter.ResponseWriter.(http.CloseNotifier)
- return cn.CloseNotify()
-}
-func (f *httpFancyWriter) Flush() {
- fl := f.basicWriter.ResponseWriter.(http.Flusher)
- fl.Flush()
-}
-func (f *httpFancyWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
- hj := f.basicWriter.ResponseWriter.(http.Hijacker)
- return hj.Hijack()
-}
-func (f *httpFancyWriter) ReadFrom(r io.Reader) (int64, error) {
- if f.basicWriter.tee != nil {
- n, err := io.Copy(&f.basicWriter, r)
- f.basicWriter.bytes += int(n)
- return n, err
- }
- rf := f.basicWriter.ResponseWriter.(io.ReaderFrom)
- f.basicWriter.maybeWriteHeader()
- n, err := rf.ReadFrom(r)
- f.basicWriter.bytes += int(n)
- return n, err
-}
-
-var _ http.CloseNotifier = &httpFancyWriter{}
-var _ http.Flusher = &httpFancyWriter{}
-var _ http.Hijacker = &httpFancyWriter{}
-var _ io.ReaderFrom = &httpFancyWriter{}
-
-// http2FancyWriter is a HTTP2 writer that additionally satisfies http.CloseNotifier,
-// http.Flusher, and io.ReaderFrom. It exists for the common case
-// of wrapping the http.ResponseWriter that package http gives you, in order to
-// make the proxied object support the full method set of the proxied object.
-type http2FancyWriter struct {
- basicWriter
-}
-
-func (f *http2FancyWriter) CloseNotify() <-chan bool {
- cn := f.basicWriter.ResponseWriter.(http.CloseNotifier)
- return cn.CloseNotify()
-}
-func (f *http2FancyWriter) Flush() {
- fl := f.basicWriter.ResponseWriter.(http.Flusher)
- fl.Flush()
-}
-
-var _ http.CloseNotifier = &http2FancyWriter{}
-var _ http.Flusher = &http2FancyWriter{}
diff --git a/vendor/github.com/go-chi/chi/middleware/wrap_writer17.go b/vendor/github.com/go-chi/chi/middleware/wrap_writer17.go
deleted file mode 100644
index c60df60..0000000
--- a/vendor/github.com/go-chi/chi/middleware/wrap_writer17.go
+++ /dev/null
@@ -1,34 +0,0 @@
-// +build go1.7,!go1.8
-
-package middleware
-
-import (
- "io"
- "net/http"
-)
-
-// NewWrapResponseWriter wraps an http.ResponseWriter, returning a proxy that allows you to
-// hook into various parts of the response process.
-func NewWrapResponseWriter(w http.ResponseWriter, protoMajor int) WrapResponseWriter {
- _, cn := w.(http.CloseNotifier)
- _, fl := w.(http.Flusher)
-
- bw := basicWriter{ResponseWriter: w}
-
- if protoMajor == 2 {
- if cn && fl {
- return &http2FancyWriter{bw}
- }
- } else {
- _, hj := w.(http.Hijacker)
- _, rf := w.(io.ReaderFrom)
- if cn && fl && hj && rf {
- return &httpFancyWriter{bw}
- }
- }
- if fl {
- return &flushWriter{bw}
- }
-
- return &bw
-}
diff --git a/vendor/github.com/go-chi/chi/middleware/wrap_writer18.go b/vendor/github.com/go-chi/chi/middleware/wrap_writer18.go
deleted file mode 100644
index 115c2d4..0000000
--- a/vendor/github.com/go-chi/chi/middleware/wrap_writer18.go
+++ /dev/null
@@ -1,41 +0,0 @@
-// +build go1.8 appengine
-
-package middleware
-
-import (
- "io"
- "net/http"
-)
-
-// NewWrapResponseWriter wraps an http.ResponseWriter, returning a proxy that allows you to
-// hook into various parts of the response process.
-func NewWrapResponseWriter(w http.ResponseWriter, protoMajor int) WrapResponseWriter {
- _, cn := w.(http.CloseNotifier)
- _, fl := w.(http.Flusher)
-
- bw := basicWriter{ResponseWriter: w}
-
- if protoMajor == 2 {
- _, ps := w.(http.Pusher)
- if cn && fl && ps {
- return &http2FancyWriter{bw}
- }
- } else {
- _, hj := w.(http.Hijacker)
- _, rf := w.(io.ReaderFrom)
- if cn && fl && hj && rf {
- return &httpFancyWriter{bw}
- }
- }
- if fl {
- return &flushWriter{bw}
- }
-
- return &bw
-}
-
-func (f *http2FancyWriter) Push(target string, opts *http.PushOptions) error {
- return f.basicWriter.ResponseWriter.(http.Pusher).Push(target, opts)
-}
-
-var _ http.Pusher = &http2FancyWriter{}
diff --git a/vendor/github.com/go-chi/chi/mux.go b/vendor/github.com/go-chi/chi/mux.go
deleted file mode 100644
index ee6af83..0000000
--- a/vendor/github.com/go-chi/chi/mux.go
+++ /dev/null
@@ -1,462 +0,0 @@
-package chi
-
-import (
- "context"
- "fmt"
- "net/http"
- "strings"
- "sync"
-)
-
-var _ Router = &Mux{}
-
-// Mux is a simple HTTP route multiplexer that parses a request path,
-// records any URL params, and executes an end handler. It implements
-// the http.Handler interface and is friendly with the standard library.
-//
-// Mux is designed to be fast, minimal and offer a powerful API for building
-// modular and composable HTTP services with a large set of handlers. It's
-// particularly useful for writing large REST API services that break a handler
-// into many smaller parts composed of middlewares and end handlers.
-type Mux struct {
- // The radix trie router
- tree *node
-
- // The middleware stack
- middlewares []func(http.Handler) http.Handler
-
- // Controls the behaviour of middleware chain generation when a mux
- // is registered as an inline group inside another mux.
- inline bool
- parent *Mux
-
- // The computed mux handler made of the chained middleware stack and
- // the tree router
- handler http.Handler
-
- // Routing context pool
- pool sync.Pool
-
- // Custom route not found handler
- notFoundHandler http.HandlerFunc
-
- // Custom method not allowed handler
- methodNotAllowedHandler http.HandlerFunc
-}
-
-// NewMux returns a newly initialized Mux object that implements the Router
-// interface.
-func NewMux() *Mux {
- mux := &Mux{tree: &node{}}
- mux.pool.New = func() interface{} {
- return NewRouteContext()
- }
- return mux
-}
-
-// ServeHTTP is the single method of the http.Handler interface that makes
-// Mux interoperable with the standard library. It uses a sync.Pool to get and
-// reuse routing contexts for each request.
-func (mx *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- // Ensure the mux has some routes defined on the mux
- if mx.handler == nil {
- panic("chi: attempting to route to a mux with no handlers.")
- }
-
- // Check if a routing context already exists from a parent router.
- rctx, _ := r.Context().Value(RouteCtxKey).(*Context)
- if rctx != nil {
- mx.handler.ServeHTTP(w, r)
- return
- }
-
- // Fetch a RouteContext object from the sync pool, and call the computed
- // mx.handler that is comprised of mx.middlewares + mx.routeHTTP.
- // Once the request is finished, reset the routing context and put it back
- // into the pool for reuse from another request.
- rctx = mx.pool.Get().(*Context)
- rctx.Reset()
- rctx.Routes = mx
- r = r.WithContext(context.WithValue(r.Context(), RouteCtxKey, rctx))
- mx.handler.ServeHTTP(w, r)
- mx.pool.Put(rctx)
-}
-
-// Use appends a middleware handler to the Mux middleware stack.
-//
-// The middleware stack for any Mux will execute before searching for a matching
-// route to a specific handler, which provides opportunity to respond early,
-// change the course of the request execution, or set request-scoped values for
-// the next http.Handler.
-func (mx *Mux) Use(middlewares ...func(http.Handler) http.Handler) {
- if mx.handler != nil {
- panic("chi: all middlewares must be defined before routes on a mux")
- }
- mx.middlewares = append(mx.middlewares, middlewares...)
-}
-
-// Handle adds the route `pattern` that matches any http method to
-// execute the `handler` http.Handler.
-func (mx *Mux) Handle(pattern string, handler http.Handler) {
- mx.handle(mALL, pattern, handler)
-}
-
-// HandleFunc adds the route `pattern` that matches any http method to
-// execute the `handlerFn` http.HandlerFunc.
-func (mx *Mux) HandleFunc(pattern string, handlerFn http.HandlerFunc) {
- mx.handle(mALL, pattern, handlerFn)
-}
-
-// Method adds the route `pattern` that matches `method` http method to
-// execute the `handler` http.Handler.
-func (mx *Mux) Method(method, pattern string, handler http.Handler) {
- m, ok := methodMap[strings.ToUpper(method)]
- if !ok {
- panic(fmt.Sprintf("chi: '%s' http method is not supported.", method))
- }
- mx.handle(m, pattern, handler)
-}
-
-// MethodFunc adds the route `pattern` that matches `method` http method to
-// execute the `handlerFn` http.HandlerFunc.
-func (mx *Mux) MethodFunc(method, pattern string, handlerFn http.HandlerFunc) {
- mx.Method(method, pattern, handlerFn)
-}
-
-// Connect adds the route `pattern` that matches a CONNECT http method to
-// execute the `handlerFn` http.HandlerFunc.
-func (mx *Mux) Connect(pattern string, handlerFn http.HandlerFunc) {
- mx.handle(mCONNECT, pattern, handlerFn)
-}
-
-// Delete adds the route `pattern` that matches a DELETE http method to
-// execute the `handlerFn` http.HandlerFunc.
-func (mx *Mux) Delete(pattern string, handlerFn http.HandlerFunc) {
- mx.handle(mDELETE, pattern, handlerFn)
-}
-
-// Get adds the route `pattern` that matches a GET http method to
-// execute the `handlerFn` http.HandlerFunc.
-func (mx *Mux) Get(pattern string, handlerFn http.HandlerFunc) {
- mx.handle(mGET, pattern, handlerFn)
-}
-
-// Head adds the route `pattern` that matches a HEAD http method to
-// execute the `handlerFn` http.HandlerFunc.
-func (mx *Mux) Head(pattern string, handlerFn http.HandlerFunc) {
- mx.handle(mHEAD, pattern, handlerFn)
-}
-
-// Options adds the route `pattern` that matches a OPTIONS http method to
-// execute the `handlerFn` http.HandlerFunc.
-func (mx *Mux) Options(pattern string, handlerFn http.HandlerFunc) {
- mx.handle(mOPTIONS, pattern, handlerFn)
-}
-
-// Patch adds the route `pattern` that matches a PATCH http method to
-// execute the `handlerFn` http.HandlerFunc.
-func (mx *Mux) Patch(pattern string, handlerFn http.HandlerFunc) {
- mx.handle(mPATCH, pattern, handlerFn)
-}
-
-// Post adds the route `pattern` that matches a POST http method to
-// execute the `handlerFn` http.HandlerFunc.
-func (mx *Mux) Post(pattern string, handlerFn http.HandlerFunc) {
- mx.handle(mPOST, pattern, handlerFn)
-}
-
-// Put adds the route `pattern` that matches a PUT http method to
-// execute the `handlerFn` http.HandlerFunc.
-func (mx *Mux) Put(pattern string, handlerFn http.HandlerFunc) {
- mx.handle(mPUT, pattern, handlerFn)
-}
-
-// Trace adds the route `pattern` that matches a TRACE http method to
-// execute the `handlerFn` http.HandlerFunc.
-func (mx *Mux) Trace(pattern string, handlerFn http.HandlerFunc) {
- mx.handle(mTRACE, pattern, handlerFn)
-}
-
-// NotFound sets a custom http.HandlerFunc for routing paths that could
-// not be found. The default 404 handler is `http.NotFound`.
-func (mx *Mux) NotFound(handlerFn http.HandlerFunc) {
- // Build NotFound handler chain
- m := mx
- hFn := handlerFn
- if mx.inline && mx.parent != nil {
- m = mx.parent
- hFn = Chain(mx.middlewares...).HandlerFunc(hFn).ServeHTTP
- }
-
- // Update the notFoundHandler from this point forward
- m.notFoundHandler = hFn
- m.updateSubRoutes(func(subMux *Mux) {
- if subMux.notFoundHandler == nil {
- subMux.NotFound(hFn)
- }
- })
-}
-
-// MethodNotAllowed sets a custom http.HandlerFunc for routing paths where the
-// method is unresolved. The default handler returns a 405 with an empty body.
-func (mx *Mux) MethodNotAllowed(handlerFn http.HandlerFunc) {
- // Build MethodNotAllowed handler chain
- m := mx
- hFn := handlerFn
- if mx.inline && mx.parent != nil {
- m = mx.parent
- hFn = Chain(mx.middlewares...).HandlerFunc(hFn).ServeHTTP
- }
-
- // Update the methodNotAllowedHandler from this point forward
- m.methodNotAllowedHandler = hFn
- m.updateSubRoutes(func(subMux *Mux) {
- if subMux.methodNotAllowedHandler == nil {
- subMux.MethodNotAllowed(hFn)
- }
- })
-}
-
-// With adds inline middlewares for an endpoint handler.
-func (mx *Mux) With(middlewares ...func(http.Handler) http.Handler) Router {
- // Similarly as in handle(), we must build the mux handler once further
- // middleware registration isn't allowed for this stack, like now.
- if !mx.inline && mx.handler == nil {
- mx.buildRouteHandler()
- }
-
- // Copy middlewares from parent inline muxs
- var mws Middlewares
- if mx.inline {
- mws = make(Middlewares, len(mx.middlewares))
- copy(mws, mx.middlewares)
- }
- mws = append(mws, middlewares...)
-
- im := &Mux{inline: true, parent: mx, tree: mx.tree, middlewares: mws}
- return im
-}
-
-// Group creates a new inline-Mux with a fresh middleware stack. It's useful
-// for a group of handlers along the same routing path that use an additional
-// set of middlewares. See _examples/.
-func (mx *Mux) Group(fn func(r Router)) Router {
- im := mx.With().(*Mux)
- if fn != nil {
- fn(im)
- }
- return im
-}
-
-// Route creates a new Mux with a fresh middleware stack and mounts it
-// along the `pattern` as a subrouter. Effectively, this is a short-hand
-// call to Mount. See _examples/.
-func (mx *Mux) Route(pattern string, fn func(r Router)) Router {
- subRouter := NewRouter()
- if fn != nil {
- fn(subRouter)
- }
- mx.Mount(pattern, subRouter)
- return subRouter
-}
-
-// Mount attaches another http.Handler or chi Router as a subrouter along a routing
-// path. It's very useful to split up a large API as many independent routers and
-// compose them as a single service using Mount. See _examples/.
-//
-// Note that Mount() simply sets a wildcard along the `pattern` that will continue
-// routing at the `handler`, which in most cases is another chi.Router. As a result,
-// if you define two Mount() routes on the exact same pattern the mount will panic.
-func (mx *Mux) Mount(pattern string, handler http.Handler) {
- // Provide runtime safety for ensuring a pattern isn't mounted on an existing
- // routing pattern.
- if mx.tree.findPattern(pattern+"*") || mx.tree.findPattern(pattern+"/*") {
- panic(fmt.Sprintf("chi: attempting to Mount() a handler on an existing path, '%s'", pattern))
- }
-
- // Assign sub-Router's with the parent not found & method not allowed handler if not specified.
- subr, ok := handler.(*Mux)
- if ok && subr.notFoundHandler == nil && mx.notFoundHandler != nil {
- subr.NotFound(mx.notFoundHandler)
- }
- if ok && subr.methodNotAllowedHandler == nil && mx.methodNotAllowedHandler != nil {
- subr.MethodNotAllowed(mx.methodNotAllowedHandler)
- }
-
- // Wrap the sub-router in a handlerFunc to scope the request path for routing.
- mountHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- rctx := RouteContext(r.Context())
- rctx.RoutePath = mx.nextRoutePath(rctx)
- handler.ServeHTTP(w, r)
- })
-
- if pattern == "" || pattern[len(pattern)-1] != '/' {
- notFoundHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- mx.NotFoundHandler().ServeHTTP(w, r)
- })
-
- mx.handle(mALL|mSTUB, pattern, mountHandler)
- mx.handle(mALL|mSTUB, pattern+"/", notFoundHandler)
- pattern += "/"
- }
-
- method := mALL
- subroutes, _ := handler.(Routes)
- if subroutes != nil {
- method |= mSTUB
- }
- n := mx.handle(method, pattern+"*", mountHandler)
-
- if subroutes != nil {
- n.subroutes = subroutes
- }
-}
-
-// Routes returns a slice of routing information from the tree,
-// useful for traversing available routes of a router.
-func (mx *Mux) Routes() []Route {
- return mx.tree.routes()
-}
-
-// Middlewares returns a slice of middleware handler functions.
-func (mx *Mux) Middlewares() Middlewares {
- return mx.middlewares
-}
-
-// Match searches the routing tree for a handler that matches the method/path.
-// It's similar to routing a http request, but without executing the handler
-// thereafter.
-//
-// Note: the *Context state is updated during execution, so manage
-// the state carefully or make a NewRouteContext().
-func (mx *Mux) Match(rctx *Context, method, path string) bool {
- m, ok := methodMap[method]
- if !ok {
- return false
- }
-
- node, _, h := mx.tree.FindRoute(rctx, m, path)
-
- if node != nil && node.subroutes != nil {
- rctx.RoutePath = mx.nextRoutePath(rctx)
- return node.subroutes.Match(rctx, method, rctx.RoutePath)
- }
-
- return h != nil
-}
-
-// NotFoundHandler returns the default Mux 404 responder whenever a route
-// cannot be found.
-func (mx *Mux) NotFoundHandler() http.HandlerFunc {
- if mx.notFoundHandler != nil {
- return mx.notFoundHandler
- }
- return http.NotFound
-}
-
-// MethodNotAllowedHandler returns the default Mux 405 responder whenever
-// a method cannot be resolved for a route.
-func (mx *Mux) MethodNotAllowedHandler() http.HandlerFunc {
- if mx.methodNotAllowedHandler != nil {
- return mx.methodNotAllowedHandler
- }
- return methodNotAllowedHandler
-}
-
-// buildRouteHandler builds the single mux handler that is a chain of the middleware
-// stack, as defined by calls to Use(), and the tree router (Mux) itself. After this
-// point, no other middlewares can be registered on this Mux's stack. But you can still
-// compose additional middlewares via Group()'s or using a chained middleware handler.
-func (mx *Mux) buildRouteHandler() {
- mx.handler = chain(mx.middlewares, http.HandlerFunc(mx.routeHTTP))
-}
-
-// handle registers a http.Handler in the routing tree for a particular http method
-// and routing pattern.
-func (mx *Mux) handle(method methodTyp, pattern string, handler http.Handler) *node {
- if len(pattern) == 0 || pattern[0] != '/' {
- panic(fmt.Sprintf("chi: routing pattern must begin with '/' in '%s'", pattern))
- }
-
- // Build the final routing handler for this Mux.
- if !mx.inline && mx.handler == nil {
- mx.buildRouteHandler()
- }
-
- // Build endpoint handler with inline middlewares for the route
- var h http.Handler
- if mx.inline {
- mx.handler = http.HandlerFunc(mx.routeHTTP)
- h = Chain(mx.middlewares...).Handler(handler)
- } else {
- h = handler
- }
-
- // Add the endpoint to the tree and return the node
- return mx.tree.InsertRoute(method, pattern, h)
-}
-
-// routeHTTP routes a http.Request through the Mux routing tree to serve
-// the matching handler for a particular http method.
-func (mx *Mux) routeHTTP(w http.ResponseWriter, r *http.Request) {
- // Grab the route context object
- rctx := r.Context().Value(RouteCtxKey).(*Context)
-
- // The request routing path
- routePath := rctx.RoutePath
- if routePath == "" {
- if r.URL.RawPath != "" {
- routePath = r.URL.RawPath
- } else {
- routePath = r.URL.Path
- }
- }
-
- // Check if method is supported by chi
- if rctx.RouteMethod == "" {
- rctx.RouteMethod = r.Method
- }
- method, ok := methodMap[rctx.RouteMethod]
- if !ok {
- mx.MethodNotAllowedHandler().ServeHTTP(w, r)
- return
- }
-
- // Find the route
- if _, _, h := mx.tree.FindRoute(rctx, method, routePath); h != nil {
- h.ServeHTTP(w, r)
- return
- }
- if rctx.methodNotAllowed {
- mx.MethodNotAllowedHandler().ServeHTTP(w, r)
- } else {
- mx.NotFoundHandler().ServeHTTP(w, r)
- }
-}
-
-func (mx *Mux) nextRoutePath(rctx *Context) string {
- routePath := "/"
- nx := len(rctx.routeParams.Keys) - 1 // index of last param in list
- if nx >= 0 && rctx.routeParams.Keys[nx] == "*" && len(rctx.routeParams.Values) > nx {
- routePath += rctx.routeParams.Values[nx]
- }
- return routePath
-}
-
-// Recursively update data on child routers.
-func (mx *Mux) updateSubRoutes(fn func(subMux *Mux)) {
- for _, r := range mx.tree.routes() {
- subMux, ok := r.SubRoutes.(*Mux)
- if !ok {
- continue
- }
- fn(subMux)
- }
-}
-
-// methodNotAllowedHandler is a helper function to respond with a 405,
-// method not allowed.
-func methodNotAllowedHandler(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(405)
- w.Write(nil)
-}
diff --git a/vendor/github.com/go-chi/chi/mux_test.go b/vendor/github.com/go-chi/chi/mux_test.go
deleted file mode 100644
index 58d039c..0000000
--- a/vendor/github.com/go-chi/chi/mux_test.go
+++ /dev/null
@@ -1,1626 +0,0 @@
-package chi
-
-import (
- "bytes"
- "context"
- "fmt"
- "io"
- "io/ioutil"
- "net"
- "net/http"
- "net/http/httptest"
- "os"
- "sync"
- "testing"
- "time"
-)
-
-func TestMuxBasic(t *testing.T) {
- var count uint64
- countermw := func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- count++
- next.ServeHTTP(w, r)
- })
- }
-
- usermw := func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- ctx = context.WithValue(ctx, ctxKey{"user"}, "peter")
- r = r.WithContext(ctx)
- next.ServeHTTP(w, r)
- })
- }
-
- exmw := func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- ctx := context.WithValue(r.Context(), ctxKey{"ex"}, "a")
- r = r.WithContext(ctx)
- next.ServeHTTP(w, r)
- })
- }
-
- logbuf := bytes.NewBufferString("")
- logmsg := "logmw test"
- logmw := func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- logbuf.WriteString(logmsg)
- next.ServeHTTP(w, r)
- })
- }
-
- cxindex := func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- user := ctx.Value(ctxKey{"user"}).(string)
- w.WriteHeader(200)
- w.Write([]byte(fmt.Sprintf("hi %s", user)))
- }
-
- ping := func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(200)
- w.Write([]byte("."))
- }
-
- headPing := func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("X-Ping", "1")
- w.WriteHeader(200)
- }
-
- createPing := func(w http.ResponseWriter, r *http.Request) {
- // create ....
- w.WriteHeader(201)
- }
-
- pingAll := func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(200)
- w.Write([]byte("ping all"))
- }
-
- pingAll2 := func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(200)
- w.Write([]byte("ping all2"))
- }
-
- pingOne := func(w http.ResponseWriter, r *http.Request) {
- idParam := URLParam(r, "id")
- w.WriteHeader(200)
- w.Write([]byte(fmt.Sprintf("ping one id: %s", idParam)))
- }
-
- pingWoop := func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(200)
- w.Write([]byte("woop." + URLParam(r, "iidd")))
- }
-
- catchAll := func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(200)
- w.Write([]byte("catchall"))
- }
-
- m := NewRouter()
- m.Use(countermw)
- m.Use(usermw)
- m.Use(exmw)
- m.Use(logmw)
- m.Get("/", cxindex)
- m.Method("GET", "/ping", http.HandlerFunc(ping))
- m.MethodFunc("GET", "/pingall", pingAll)
- m.MethodFunc("get", "/ping/all", pingAll)
- m.Get("/ping/all2", pingAll2)
-
- m.Head("/ping", headPing)
- m.Post("/ping", createPing)
- m.Get("/ping/{id}", pingWoop)
- m.Get("/ping/{id}", pingOne) // expected to overwrite to pingOne handler
- m.Get("/ping/{iidd}/woop", pingWoop)
- m.HandleFunc("/admin/*", catchAll)
- // m.Post("/admin/*", catchAll)
-
- ts := httptest.NewServer(m)
- defer ts.Close()
-
- // GET /
- if _, body := testRequest(t, ts, "GET", "/", nil); body != "hi peter" {
- t.Fatalf(body)
- }
- tlogmsg, _ := logbuf.ReadString(0)
- if tlogmsg != logmsg {
- t.Error("expecting log message from middleware:", logmsg)
- }
-
- // GET /ping
- if _, body := testRequest(t, ts, "GET", "/ping", nil); body != "." {
- t.Fatalf(body)
- }
-
- // GET /pingall
- if _, body := testRequest(t, ts, "GET", "/pingall", nil); body != "ping all" {
- t.Fatalf(body)
- }
-
- // GET /ping/all
- if _, body := testRequest(t, ts, "GET", "/ping/all", nil); body != "ping all" {
- t.Fatalf(body)
- }
-
- // GET /ping/all2
- if _, body := testRequest(t, ts, "GET", "/ping/all2", nil); body != "ping all2" {
- t.Fatalf(body)
- }
-
- // GET /ping/123
- if _, body := testRequest(t, ts, "GET", "/ping/123", nil); body != "ping one id: 123" {
- t.Fatalf(body)
- }
-
- // GET /ping/allan
- if _, body := testRequest(t, ts, "GET", "/ping/allan", nil); body != "ping one id: allan" {
- t.Fatalf(body)
- }
-
- // GET /ping/1/woop
- if _, body := testRequest(t, ts, "GET", "/ping/1/woop", nil); body != "woop.1" {
- t.Fatalf(body)
- }
-
- // HEAD /ping
- resp, err := http.Head(ts.URL + "/ping")
- if err != nil {
- t.Fatal(err)
- }
- if resp.StatusCode != 200 {
- t.Error("head failed, should be 200")
- }
- if resp.Header.Get("X-Ping") == "" {
- t.Error("expecting X-Ping header")
- }
-
- // GET /admin/catch-this
- if _, body := testRequest(t, ts, "GET", "/admin/catch-thazzzzz", nil); body != "catchall" {
- t.Fatalf(body)
- }
-
- // POST /admin/catch-this
- resp, err = http.Post(ts.URL+"/admin/casdfsadfs", "text/plain", bytes.NewReader([]byte{}))
- if err != nil {
- t.Fatal(err)
- }
-
- body, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- t.Fatal(err)
- }
- defer resp.Body.Close()
-
- if resp.StatusCode != 200 {
- t.Error("POST failed, should be 200")
- }
-
- if string(body) != "catchall" {
- t.Error("expecting response body: 'catchall'")
- }
-
- // Custom http method DIE /ping/1/woop
- if resp, body := testRequest(t, ts, "DIE", "/ping/1/woop", nil); body != "" || resp.StatusCode != 405 {
- t.Fatalf(fmt.Sprintf("expecting 405 status and empty body, got %d '%s'", resp.StatusCode, body))
- }
-}
-
-func TestMuxMounts(t *testing.T) {
- r := NewRouter()
-
- r.Get("/{hash}", func(w http.ResponseWriter, r *http.Request) {
- v := URLParam(r, "hash")
- w.Write([]byte(fmt.Sprintf("/%s", v)))
- })
-
- r.Route("/{hash}/share", func(r Router) {
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- v := URLParam(r, "hash")
- w.Write([]byte(fmt.Sprintf("/%s/share", v)))
- })
- r.Get("/{network}", func(w http.ResponseWriter, r *http.Request) {
- v := URLParam(r, "hash")
- n := URLParam(r, "network")
- w.Write([]byte(fmt.Sprintf("/%s/share/%s", v, n)))
- })
- })
-
- m := NewRouter()
- m.Mount("/sharing", r)
-
- ts := httptest.NewServer(m)
- defer ts.Close()
-
- if _, body := testRequest(t, ts, "GET", "/sharing/aBc", nil); body != "/aBc" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "GET", "/sharing/aBc/share", nil); body != "/aBc/share" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "GET", "/sharing/aBc/share/twitter", nil); body != "/aBc/share/twitter" {
- t.Fatalf(body)
- }
-}
-
-func TestMuxPlain(t *testing.T) {
- r := NewRouter()
- r.Get("/hi", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("bye"))
- })
- r.NotFound(func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(404)
- w.Write([]byte("nothing here"))
- })
-
- ts := httptest.NewServer(r)
- defer ts.Close()
-
- if _, body := testRequest(t, ts, "GET", "/hi", nil); body != "bye" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "GET", "/nothing-here", nil); body != "nothing here" {
- t.Fatalf(body)
- }
-}
-
-func TestMuxEmptyRoutes(t *testing.T) {
- mux := NewRouter()
-
- apiRouter := NewRouter()
- // oops, we forgot to declare any route handlers
-
- mux.Handle("/api*", apiRouter)
-
- if _, body := testHandler(t, mux, "GET", "/", nil); body != "404 page not found\n" {
- t.Fatalf(body)
- }
-
- func() {
- defer func() {
- if r := recover(); r != nil {
- if r != `chi: attempting to route to a mux with no handlers.` {
- t.Fatalf("expecting empty route panic")
- }
- }
- }()
-
- _, body := testHandler(t, mux, "GET", "/api", nil)
- t.Fatalf("oops, we are expecting a panic instead of getting resp: %s", body)
- }()
-
- func() {
- defer func() {
- if r := recover(); r != nil {
- if r != `chi: attempting to route to a mux with no handlers.` {
- t.Fatalf("expecting empty route panic")
- }
- }
- }()
-
- _, body := testHandler(t, mux, "GET", "/api/abc", nil)
- t.Fatalf("oops, we are expecting a panic instead of getting resp: %s", body)
- }()
-}
-
-// Test a mux that routes a trailing slash, see also middleware/strip_test.go
-// for an example of using a middleware to handle trailing slashes.
-func TestMuxTrailingSlash(t *testing.T) {
- r := NewRouter()
- r.NotFound(func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(404)
- w.Write([]byte("nothing here"))
- })
-
- subRoutes := NewRouter()
- indexHandler := func(w http.ResponseWriter, r *http.Request) {
- accountID := URLParam(r, "accountID")
- w.Write([]byte(accountID))
- }
- subRoutes.Get("/", indexHandler)
-
- r.Mount("/accounts/{accountID}", subRoutes)
- r.Get("/accounts/{accountID}/", indexHandler)
-
- ts := httptest.NewServer(r)
- defer ts.Close()
-
- if _, body := testRequest(t, ts, "GET", "/accounts/admin", nil); body != "admin" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "GET", "/accounts/admin/", nil); body != "admin" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "GET", "/nothing-here", nil); body != "nothing here" {
- t.Fatalf(body)
- }
-}
-
-func TestMuxNestedNotFound(t *testing.T) {
- r := NewRouter()
-
- r.Use(func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- r = r.WithContext(context.WithValue(r.Context(), ctxKey{"mw"}, "mw"))
- next.ServeHTTP(w, r)
- })
- })
-
- r.Get("/hi", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("bye"))
- })
-
- r.With(func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- r = r.WithContext(context.WithValue(r.Context(), ctxKey{"with"}, "with"))
- next.ServeHTTP(w, r)
- })
- }).NotFound(func(w http.ResponseWriter, r *http.Request) {
- chkMw := r.Context().Value(ctxKey{"mw"}).(string)
- chkWith := r.Context().Value(ctxKey{"with"}).(string)
- w.WriteHeader(404)
- w.Write([]byte(fmt.Sprintf("root 404 %s %s", chkMw, chkWith)))
- })
-
- sr1 := NewRouter()
-
- sr1.Get("/sub", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("sub"))
- })
- sr1.Group(func(sr1 Router) {
- sr1.Use(func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- r = r.WithContext(context.WithValue(r.Context(), ctxKey{"mw2"}, "mw2"))
- next.ServeHTTP(w, r)
- })
- })
- sr1.NotFound(func(w http.ResponseWriter, r *http.Request) {
- chkMw2 := r.Context().Value(ctxKey{"mw2"}).(string)
- w.WriteHeader(404)
- w.Write([]byte(fmt.Sprintf("sub 404 %s", chkMw2)))
- })
- })
-
- sr2 := NewRouter()
- sr2.Get("/sub", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("sub2"))
- })
-
- r.Mount("/admin1", sr1)
- r.Mount("/admin2", sr2)
-
- ts := httptest.NewServer(r)
- defer ts.Close()
-
- if _, body := testRequest(t, ts, "GET", "/hi", nil); body != "bye" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "GET", "/nothing-here", nil); body != "root 404 mw with" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "GET", "/admin1/sub", nil); body != "sub" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "GET", "/admin1/nope", nil); body != "sub 404 mw2" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "GET", "/admin2/sub", nil); body != "sub2" {
- t.Fatalf(body)
- }
-
- // Not found pages should bubble up to the root.
- if _, body := testRequest(t, ts, "GET", "/admin2/nope", nil); body != "root 404 mw with" {
- t.Fatalf(body)
- }
-}
-
-func TestMuxNestedMethodNotAllowed(t *testing.T) {
- r := NewRouter()
- r.Get("/root", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("root"))
- })
- r.MethodNotAllowed(func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(405)
- w.Write([]byte("root 405"))
- })
-
- sr1 := NewRouter()
- sr1.Get("/sub1", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("sub1"))
- })
- sr1.MethodNotAllowed(func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(405)
- w.Write([]byte("sub1 405"))
- })
-
- sr2 := NewRouter()
- sr2.Get("/sub2", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("sub2"))
- })
-
- r.Mount("/prefix1", sr1)
- r.Mount("/prefix2", sr2)
-
- ts := httptest.NewServer(r)
- defer ts.Close()
-
- if _, body := testRequest(t, ts, "GET", "/root", nil); body != "root" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "PUT", "/root", nil); body != "root 405" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "GET", "/prefix1/sub1", nil); body != "sub1" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "PUT", "/prefix1/sub1", nil); body != "sub1 405" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "GET", "/prefix2/sub2", nil); body != "sub2" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "PUT", "/prefix2/sub2", nil); body != "root 405" {
- t.Fatalf(body)
- }
-}
-
-func TestMuxComplicatedNotFound(t *testing.T) {
- // sub router with groups
- sub := NewRouter()
- sub.Route("/resource", func(r Router) {
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("private get"))
- })
- })
-
- // Root router with groups
- r := NewRouter()
- r.Get("/auth", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("auth get"))
- })
- r.Route("/public", func(r Router) {
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("public get"))
- })
- })
- r.Mount("/private", sub)
- r.NotFound(func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("custom not-found"))
- })
-
- ts := httptest.NewServer(r)
- defer ts.Close()
-
- // check that we didn't broke correct routes
- if _, body := testRequest(t, ts, "GET", "/auth", nil); body != "auth get" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "GET", "/public", nil); body != "public get" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "GET", "/private/resource", nil); body != "private get" {
- t.Fatalf(body)
- }
- // check custom not-found on all levels
- if _, body := testRequest(t, ts, "GET", "/nope", nil); body != "custom not-found" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "GET", "/public/nope", nil); body != "custom not-found" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "GET", "/private/nope", nil); body != "custom not-found" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "GET", "/private/resource/nope", nil); body != "custom not-found" {
- t.Fatalf(body)
- }
- // check custom not-found on trailing slash routes
- if _, body := testRequest(t, ts, "GET", "/auth/", nil); body != "custom not-found" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "GET", "/public/", nil); body != "custom not-found" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "GET", "/private/", nil); body != "custom not-found" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "GET", "/private/resource/", nil); body != "custom not-found" {
- t.Fatalf(body)
- }
-}
-
-func TestMuxWith(t *testing.T) {
- var cmwInit1, cmwHandler1 uint64
- var cmwInit2, cmwHandler2 uint64
- mw1 := func(next http.Handler) http.Handler {
- cmwInit1++
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- cmwHandler1++
- r = r.WithContext(context.WithValue(r.Context(), ctxKey{"inline1"}, "yes"))
- next.ServeHTTP(w, r)
- })
- }
- mw2 := func(next http.Handler) http.Handler {
- cmwInit2++
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- cmwHandler2++
- r = r.WithContext(context.WithValue(r.Context(), ctxKey{"inline2"}, "yes"))
- next.ServeHTTP(w, r)
- })
- }
-
- r := NewRouter()
- r.Get("/hi", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("bye"))
- })
- r.With(mw1).With(mw2).Get("/inline", func(w http.ResponseWriter, r *http.Request) {
- v1 := r.Context().Value(ctxKey{"inline1"}).(string)
- v2 := r.Context().Value(ctxKey{"inline2"}).(string)
- w.Write([]byte(fmt.Sprintf("inline %s %s", v1, v2)))
- })
-
- ts := httptest.NewServer(r)
- defer ts.Close()
-
- if _, body := testRequest(t, ts, "GET", "/hi", nil); body != "bye" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "GET", "/inline", nil); body != "inline yes yes" {
- t.Fatalf(body)
- }
- if cmwInit1 != 1 {
- t.Fatalf("expecting cmwInit1 to be 1, got %d", cmwInit1)
- }
- if cmwHandler1 != 1 {
- t.Fatalf("expecting cmwHandler1 to be 1, got %d", cmwHandler1)
- }
- if cmwInit2 != 1 {
- t.Fatalf("expecting cmwInit2 to be 1, got %d", cmwInit2)
- }
- if cmwHandler2 != 1 {
- t.Fatalf("expecting cmwHandler2 to be 1, got %d", cmwHandler2)
- }
-}
-
-func TestMuxMiddlewareStack(t *testing.T) {
- var stdmwInit, stdmwHandler uint64
- stdmw := func(next http.Handler) http.Handler {
- stdmwInit++
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- stdmwHandler++
- next.ServeHTTP(w, r)
- })
- }
- _ = stdmw
-
- var ctxmwInit, ctxmwHandler uint64
- ctxmw := func(next http.Handler) http.Handler {
- ctxmwInit++
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- ctxmwHandler++
- ctx := r.Context()
- ctx = context.WithValue(ctx, ctxKey{"count.ctxmwHandler"}, ctxmwHandler)
- r = r.WithContext(ctx)
- next.ServeHTTP(w, r)
- })
- }
-
- var inCtxmwInit, inCtxmwHandler uint64
- inCtxmw := func(next http.Handler) http.Handler {
- inCtxmwInit++
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- inCtxmwHandler++
- next.ServeHTTP(w, r)
- })
- }
-
- r := NewRouter()
- r.Use(stdmw)
- r.Use(ctxmw)
- r.Use(func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.URL.Path == "/ping" {
- w.Write([]byte("pong"))
- return
- }
- next.ServeHTTP(w, r)
- })
- })
-
- var handlerCount uint64
-
- r.With(inCtxmw).Get("/", func(w http.ResponseWriter, r *http.Request) {
- handlerCount++
- ctx := r.Context()
- ctxmwHandlerCount := ctx.Value(ctxKey{"count.ctxmwHandler"}).(uint64)
- w.Write([]byte(fmt.Sprintf("inits:%d reqs:%d ctxValue:%d", ctxmwInit, handlerCount, ctxmwHandlerCount)))
- })
-
- r.Get("/hi", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("wooot"))
- })
-
- ts := httptest.NewServer(r)
- defer ts.Close()
-
- testRequest(t, ts, "GET", "/", nil)
- testRequest(t, ts, "GET", "/", nil)
- var body string
- _, body = testRequest(t, ts, "GET", "/", nil)
- if body != "inits:1 reqs:3 ctxValue:3" {
- t.Fatalf("got: '%s'", body)
- }
-
- _, body = testRequest(t, ts, "GET", "/ping", nil)
- if body != "pong" {
- t.Fatalf("got: '%s'", body)
- }
-}
-
-func TestMuxRouteGroups(t *testing.T) {
- var stdmwInit, stdmwHandler uint64
-
- stdmw := func(next http.Handler) http.Handler {
- stdmwInit++
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- stdmwHandler++
- next.ServeHTTP(w, r)
- })
- }
-
- var stdmwInit2, stdmwHandler2 uint64
- stdmw2 := func(next http.Handler) http.Handler {
- stdmwInit2++
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- stdmwHandler2++
- next.ServeHTTP(w, r)
- })
- }
-
- r := NewRouter()
- r.Group(func(r Router) {
- r.Use(stdmw)
- r.Get("/group", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("root group"))
- })
- })
- r.Group(func(r Router) {
- r.Use(stdmw2)
- r.Get("/group2", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("root group2"))
- })
- })
-
- ts := httptest.NewServer(r)
- defer ts.Close()
-
- // GET /group
- _, body := testRequest(t, ts, "GET", "/group", nil)
- if body != "root group" {
- t.Fatalf("got: '%s'", body)
- }
- if stdmwInit != 1 || stdmwHandler != 1 {
- t.Logf("stdmw counters failed, should be 1:1, got %d:%d", stdmwInit, stdmwHandler)
- }
-
- // GET /group2
- _, body = testRequest(t, ts, "GET", "/group2", nil)
- if body != "root group2" {
- t.Fatalf("got: '%s'", body)
- }
- if stdmwInit2 != 1 || stdmwHandler2 != 1 {
- t.Fatalf("stdmw2 counters failed, should be 1:1, got %d:%d", stdmwInit2, stdmwHandler2)
- }
-}
-
-func TestMuxBig(t *testing.T) {
- r := bigMux()
-
- ts := httptest.NewServer(r)
- defer ts.Close()
-
- var body, expected string
-
- _, body = testRequest(t, ts, "GET", "/favicon.ico", nil)
- if body != "fav" {
- t.Fatalf("got '%s'", body)
- }
- _, body = testRequest(t, ts, "GET", "/hubs/4/view", nil)
- if body != "/hubs/4/view reqid:1 session:anonymous" {
- t.Fatalf("got '%v'", body)
- }
- _, body = testRequest(t, ts, "GET", "/hubs/4/view/index.html", nil)
- if body != "/hubs/4/view/index.html reqid:1 session:anonymous" {
- t.Fatalf("got '%s'", body)
- }
- _, body = testRequest(t, ts, "POST", "/hubs/ethereumhub/view/index.html", nil)
- if body != "/hubs/ethereumhub/view/index.html reqid:1 session:anonymous" {
- t.Fatalf("got '%s'", body)
- }
- _, body = testRequest(t, ts, "GET", "/", nil)
- if body != "/ reqid:1 session:elvis" {
- t.Fatalf("got '%s'", body)
- }
- _, body = testRequest(t, ts, "GET", "/suggestions", nil)
- if body != "/suggestions reqid:1 session:elvis" {
- t.Fatalf("got '%s'", body)
- }
- _, body = testRequest(t, ts, "GET", "/woot/444/hiiii", nil)
- if body != "/woot/444/hiiii" {
- t.Fatalf("got '%s'", body)
- }
- _, body = testRequest(t, ts, "GET", "/hubs/123", nil)
- expected = "/hubs/123 reqid:1 session:elvis"
- if body != expected {
- t.Fatalf("expected:%s got:%s", expected, body)
- }
- _, body = testRequest(t, ts, "GET", "/hubs/123/touch", nil)
- if body != "/hubs/123/touch reqid:1 session:elvis" {
- t.Fatalf("got '%s'", body)
- }
- _, body = testRequest(t, ts, "GET", "/hubs/123/webhooks", nil)
- if body != "/hubs/123/webhooks reqid:1 session:elvis" {
- t.Fatalf("got '%s'", body)
- }
- _, body = testRequest(t, ts, "GET", "/hubs/123/posts", nil)
- if body != "/hubs/123/posts reqid:1 session:elvis" {
- t.Fatalf("got '%s'", body)
- }
- _, body = testRequest(t, ts, "GET", "/folders", nil)
- if body != "404 page not found\n" {
- t.Fatalf("got '%s'", body)
- }
- _, body = testRequest(t, ts, "GET", "/folders/", nil)
- if body != "/folders/ reqid:1 session:elvis" {
- t.Fatalf("got '%s'", body)
- }
- _, body = testRequest(t, ts, "GET", "/folders/public", nil)
- if body != "/folders/public reqid:1 session:elvis" {
- t.Fatalf("got '%s'", body)
- }
- _, body = testRequest(t, ts, "GET", "/folders/nothing", nil)
- if body != "404 page not found\n" {
- t.Fatalf("got '%s'", body)
- }
-}
-
-func bigMux() Router {
- var r, sr1, sr2, sr3, sr4, sr5, sr6 *Mux
- r = NewRouter()
- r.Use(func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- ctx := context.WithValue(r.Context(), ctxKey{"requestID"}, "1")
- next.ServeHTTP(w, r.WithContext(ctx))
- })
- })
- r.Use(func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- next.ServeHTTP(w, r)
- })
- })
- r.Group(func(r Router) {
- r.Use(func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- ctx := context.WithValue(r.Context(), ctxKey{"session.user"}, "anonymous")
- next.ServeHTTP(w, r.WithContext(ctx))
- })
- })
- r.Get("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("fav"))
- })
- r.Get("/hubs/{hubID}/view", func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- s := fmt.Sprintf("/hubs/%s/view reqid:%s session:%s", URLParam(r, "hubID"),
- ctx.Value(ctxKey{"requestID"}), ctx.Value(ctxKey{"session.user"}))
- w.Write([]byte(s))
- })
- r.Get("/hubs/{hubID}/view/*", func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- s := fmt.Sprintf("/hubs/%s/view/%s reqid:%s session:%s", URLParamFromCtx(ctx, "hubID"),
- URLParam(r, "*"), ctx.Value(ctxKey{"requestID"}), ctx.Value(ctxKey{"session.user"}))
- w.Write([]byte(s))
- })
- r.Post("/hubs/{hubSlug}/view/*", func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- s := fmt.Sprintf("/hubs/%s/view/%s reqid:%s session:%s", URLParamFromCtx(ctx, "hubSlug"),
- URLParam(r, "*"), ctx.Value(ctxKey{"requestID"}), ctx.Value(ctxKey{"session.user"}))
- w.Write([]byte(s))
- })
- })
- r.Group(func(r Router) {
- r.Use(func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- ctx := context.WithValue(r.Context(), ctxKey{"session.user"}, "elvis")
- next.ServeHTTP(w, r.WithContext(ctx))
- })
- })
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- s := fmt.Sprintf("/ reqid:%s session:%s", ctx.Value(ctxKey{"requestID"}), ctx.Value(ctxKey{"session.user"}))
- w.Write([]byte(s))
- })
- r.Get("/suggestions", func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- s := fmt.Sprintf("/suggestions reqid:%s session:%s", ctx.Value(ctxKey{"requestID"}), ctx.Value(ctxKey{"session.user"}))
- w.Write([]byte(s))
- })
-
- r.Get("/woot/{wootID}/*", func(w http.ResponseWriter, r *http.Request) {
- s := fmt.Sprintf("/woot/%s/%s", URLParam(r, "wootID"), URLParam(r, "*"))
- w.Write([]byte(s))
- })
-
- r.Route("/hubs", func(r Router) {
- sr1 = r.(*Mux)
- r.Route("/{hubID}", func(r Router) {
- sr2 = r.(*Mux)
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- s := fmt.Sprintf("/hubs/%s reqid:%s session:%s",
- URLParam(r, "hubID"), ctx.Value(ctxKey{"requestID"}), ctx.Value(ctxKey{"session.user"}))
- w.Write([]byte(s))
- })
- r.Get("/touch", func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- s := fmt.Sprintf("/hubs/%s/touch reqid:%s session:%s", URLParam(r, "hubID"),
- ctx.Value(ctxKey{"requestID"}), ctx.Value(ctxKey{"session.user"}))
- w.Write([]byte(s))
- })
-
- sr3 = NewRouter()
- sr3.Get("/", func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- s := fmt.Sprintf("/hubs/%s/webhooks reqid:%s session:%s", URLParam(r, "hubID"),
- ctx.Value(ctxKey{"requestID"}), ctx.Value(ctxKey{"session.user"}))
- w.Write([]byte(s))
- })
- sr3.Route("/{webhookID}", func(r Router) {
- sr4 = r.(*Mux)
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- s := fmt.Sprintf("/hubs/%s/webhooks/%s reqid:%s session:%s", URLParam(r, "hubID"),
- URLParam(r, "webhookID"), ctx.Value(ctxKey{"requestID"}), ctx.Value(ctxKey{"session.user"}))
- w.Write([]byte(s))
- })
- })
-
- r.Mount("/webhooks", Chain(func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{"hook"}, true)))
- })
- }).Handler(sr3))
-
- r.Route("/posts", func(r Router) {
- sr5 = r.(*Mux)
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- s := fmt.Sprintf("/hubs/%s/posts reqid:%s session:%s", URLParam(r, "hubID"),
- ctx.Value(ctxKey{"requestID"}), ctx.Value(ctxKey{"session.user"}))
- w.Write([]byte(s))
- })
- })
- })
- })
-
- r.Route("/folders/", func(r Router) {
- sr6 = r.(*Mux)
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- s := fmt.Sprintf("/folders/ reqid:%s session:%s",
- ctx.Value(ctxKey{"requestID"}), ctx.Value(ctxKey{"session.user"}))
- w.Write([]byte(s))
- })
- r.Get("/public", func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- s := fmt.Sprintf("/folders/public reqid:%s session:%s",
- ctx.Value(ctxKey{"requestID"}), ctx.Value(ctxKey{"session.user"}))
- w.Write([]byte(s))
- })
- })
- })
-
- return r
-}
-
-func TestMuxSubroutesBasic(t *testing.T) {
- hIndex := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("index"))
- })
- hArticlesList := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("articles-list"))
- })
- hSearchArticles := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("search-articles"))
- })
- hGetArticle := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte(fmt.Sprintf("get-article:%s", URLParam(r, "id"))))
- })
- hSyncArticle := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte(fmt.Sprintf("sync-article:%s", URLParam(r, "id"))))
- })
-
- r := NewRouter()
- var rr1, rr2 *Mux
- r.Get("/", hIndex)
- r.Route("/articles", func(r Router) {
- rr1 = r.(*Mux)
- r.Get("/", hArticlesList)
- r.Get("/search", hSearchArticles)
- r.Route("/{id}", func(r Router) {
- rr2 = r.(*Mux)
- r.Get("/", hGetArticle)
- r.Get("/sync", hSyncArticle)
- })
- })
-
- // log.Println("~~~~~~~~~")
- // log.Println("~~~~~~~~~")
- // debugPrintTree(0, 0, r.tree, 0)
- // log.Println("~~~~~~~~~")
- // log.Println("~~~~~~~~~")
-
- // log.Println("~~~~~~~~~")
- // log.Println("~~~~~~~~~")
- // debugPrintTree(0, 0, rr1.tree, 0)
- // log.Println("~~~~~~~~~")
- // log.Println("~~~~~~~~~")
-
- // log.Println("~~~~~~~~~")
- // log.Println("~~~~~~~~~")
- // debugPrintTree(0, 0, rr2.tree, 0)
- // log.Println("~~~~~~~~~")
- // log.Println("~~~~~~~~~")
-
- ts := httptest.NewServer(r)
- defer ts.Close()
-
- var body, expected string
-
- _, body = testRequest(t, ts, "GET", "/", nil)
- expected = "index"
- if body != expected {
- t.Fatalf("expected:%s got:%s", expected, body)
- }
- _, body = testRequest(t, ts, "GET", "/articles", nil)
- expected = "articles-list"
- if body != expected {
- t.Fatalf("expected:%s got:%s", expected, body)
- }
- _, body = testRequest(t, ts, "GET", "/articles/search", nil)
- expected = "search-articles"
- if body != expected {
- t.Fatalf("expected:%s got:%s", expected, body)
- }
- _, body = testRequest(t, ts, "GET", "/articles/123", nil)
- expected = "get-article:123"
- if body != expected {
- t.Fatalf("expected:%s got:%s", expected, body)
- }
- _, body = testRequest(t, ts, "GET", "/articles/123/sync", nil)
- expected = "sync-article:123"
- if body != expected {
- t.Fatalf("expected:%s got:%s", expected, body)
- }
-}
-
-func TestMuxSubroutes(t *testing.T) {
- hHubView1 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("hub1"))
- })
- hHubView2 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("hub2"))
- })
- hHubView3 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("hub3"))
- })
- hAccountView1 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("account1"))
- })
- hAccountView2 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("account2"))
- })
-
- r := NewRouter()
- r.Get("/hubs/{hubID}/view", hHubView1)
- r.Get("/hubs/{hubID}/view/*", hHubView2)
-
- sr := NewRouter()
- sr.Get("/", hHubView3)
- r.Mount("/hubs/{hubID}/users", sr)
-
- sr3 := NewRouter()
- sr3.Get("/", hAccountView1)
- sr3.Get("/hi", hAccountView2)
-
- var sr2 *Mux
- r.Route("/accounts/{accountID}", func(r Router) {
- sr2 = r.(*Mux)
- // r.Get("/", hAccountView1)
- r.Mount("/", sr3)
- })
-
- // This is the same as the r.Route() call mounted on sr2
- // sr2 := NewRouter()
- // sr2.Mount("/", sr3)
- // r.Mount("/accounts/{accountID}", sr2)
-
- ts := httptest.NewServer(r)
- defer ts.Close()
-
- var body, expected string
- var resp *http.Response
-
- _, body = testRequest(t, ts, "GET", "/hubs/123/view", nil)
- expected = "hub1"
- if body != expected {
- t.Fatalf("expected:%s got:%s", expected, body)
- }
- _, body = testRequest(t, ts, "GET", "/hubs/123/view/index.html", nil)
- expected = "hub2"
- if body != expected {
- t.Fatalf("expected:%s got:%s", expected, body)
- }
- _, body = testRequest(t, ts, "GET", "/hubs/123/users", nil)
- expected = "hub3"
- if body != expected {
- t.Fatalf("expected:%s got:%s", expected, body)
- }
- resp, body = testRequest(t, ts, "GET", "/hubs/123/users/", nil)
- expected = "404 page not found\n"
- if resp.StatusCode != 404 || body != expected {
- t.Fatalf("expected:%s got:%s", expected, body)
- }
- _, body = testRequest(t, ts, "GET", "/accounts/44", nil)
- expected = "account1"
- if body != expected {
- t.Fatalf("request:%s expected:%s got:%s", "GET /accounts/44", expected, body)
- }
- _, body = testRequest(t, ts, "GET", "/accounts/44/hi", nil)
- expected = "account2"
- if body != expected {
- t.Fatalf("expected:%s got:%s", expected, body)
- }
-
- // Test that we're building the routingPatterns properly
- router := r
- req, _ := http.NewRequest("GET", "/accounts/44/hi", nil)
-
- rctx := NewRouteContext()
- req = req.WithContext(context.WithValue(req.Context(), RouteCtxKey, rctx))
-
- w := httptest.NewRecorder()
- router.ServeHTTP(w, req)
-
- body = string(w.Body.Bytes())
- expected = "account2"
- if body != expected {
- t.Fatalf("expected:%s got:%s", expected, body)
- }
-
- routePatterns := rctx.RoutePatterns
- if len(rctx.RoutePatterns) != 3 {
- t.Fatalf("expected 3 routing patterns, got:%d", len(rctx.RoutePatterns))
- }
- expected = "/accounts/{accountID}/*"
- if routePatterns[0] != expected {
- t.Fatalf("routePattern, expected:%s got:%s", expected, routePatterns[0])
- }
- expected = "/*"
- if routePatterns[1] != expected {
- t.Fatalf("routePattern, expected:%s got:%s", expected, routePatterns[1])
- }
- expected = "/hi"
- if routePatterns[2] != expected {
- t.Fatalf("routePattern, expected:%s got:%s", expected, routePatterns[2])
- }
-
-}
-
-func TestSingleHandler(t *testing.T) {
- h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- name := URLParam(r, "name")
- w.Write([]byte("hi " + name))
- })
-
- r, _ := http.NewRequest("GET", "/", nil)
- rctx := NewRouteContext()
- r = r.WithContext(context.WithValue(r.Context(), RouteCtxKey, rctx))
- rctx.URLParams.Add("name", "joe")
-
- w := httptest.NewRecorder()
- h.ServeHTTP(w, r)
-
- body := string(w.Body.Bytes())
- expected := "hi joe"
- if body != expected {
- t.Fatalf("expected:%s got:%s", expected, body)
- }
-}
-
-// TODO: a Router wrapper test..
-//
-// type ACLMux struct {
-// *Mux
-// XX string
-// }
-//
-// func NewACLMux() *ACLMux {
-// return &ACLMux{Mux: NewRouter(), XX: "hihi"}
-// }
-//
-// // TODO: this should be supported...
-// func TestWoot(t *testing.T) {
-// var r Router = NewRouter()
-//
-// var r2 Router = NewACLMux() //NewRouter()
-// r2.Get("/hi", func(w http.ResponseWriter, r *http.Request) {
-// w.Write([]byte("hi"))
-// })
-//
-// r.Mount("/", r2)
-// }
-
-func TestServeHTTPExistingContext(t *testing.T) {
- r := NewRouter()
- r.Get("/hi", func(w http.ResponseWriter, r *http.Request) {
- s, _ := r.Context().Value(ctxKey{"testCtx"}).(string)
- w.Write([]byte(s))
- })
- r.NotFound(func(w http.ResponseWriter, r *http.Request) {
- s, _ := r.Context().Value(ctxKey{"testCtx"}).(string)
- w.WriteHeader(404)
- w.Write([]byte(s))
- })
-
- testcases := []struct {
- Method string
- Path string
- Ctx context.Context
- ExpectedStatus int
- ExpectedBody string
- }{
- {
- Method: "GET",
- Path: "/hi",
- Ctx: context.WithValue(context.Background(), ctxKey{"testCtx"}, "hi ctx"),
- ExpectedStatus: 200,
- ExpectedBody: "hi ctx",
- },
- {
- Method: "GET",
- Path: "/hello",
- Ctx: context.WithValue(context.Background(), ctxKey{"testCtx"}, "nothing here ctx"),
- ExpectedStatus: 404,
- ExpectedBody: "nothing here ctx",
- },
- }
-
- for _, tc := range testcases {
- resp := httptest.NewRecorder()
- req, err := http.NewRequest(tc.Method, tc.Path, nil)
- if err != nil {
- t.Fatalf("%v", err)
- }
- req = req.WithContext(tc.Ctx)
- r.ServeHTTP(resp, req)
- b, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- t.Fatalf("%v", err)
- }
- if resp.Code != tc.ExpectedStatus {
- t.Fatalf("%v != %v", tc.ExpectedStatus, resp.Code)
- }
- if string(b) != tc.ExpectedBody {
- t.Fatalf("%s != %s", tc.ExpectedBody, b)
- }
- }
-}
-
-func TestNestedGroups(t *testing.T) {
- handlerPrintCounter := func(w http.ResponseWriter, r *http.Request) {
- counter, _ := r.Context().Value(ctxKey{"counter"}).(int)
- w.Write([]byte(fmt.Sprintf("%v", counter)))
- }
-
- mwIncreaseCounter := func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- counter, _ := ctx.Value(ctxKey{"counter"}).(int)
- counter++
- ctx = context.WithValue(ctx, ctxKey{"counter"}, counter)
- next.ServeHTTP(w, r.WithContext(ctx))
- })
- }
-
- // Each route represents value of its counter (number of applied middlewares).
- r := NewRouter() // counter == 0
- r.Get("/0", handlerPrintCounter)
- r.Group(func(r Router) {
- r.Use(mwIncreaseCounter) // counter == 1
- r.Get("/1", handlerPrintCounter)
-
- // r.Handle(GET, "/2", Chain(mwIncreaseCounter).HandlerFunc(handlerPrintCounter))
- r.With(mwIncreaseCounter).Get("/2", handlerPrintCounter)
-
- r.Group(func(r Router) {
- r.Use(mwIncreaseCounter, mwIncreaseCounter) // counter == 3
- r.Get("/3", handlerPrintCounter)
- })
- r.Route("/", func(r Router) {
- r.Use(mwIncreaseCounter, mwIncreaseCounter) // counter == 3
-
- // r.Handle(GET, "/4", Chain(mwIncreaseCounter).HandlerFunc(handlerPrintCounter))
- r.With(mwIncreaseCounter).Get("/4", handlerPrintCounter)
-
- r.Group(func(r Router) {
- r.Use(mwIncreaseCounter, mwIncreaseCounter) // counter == 5
- r.Get("/5", handlerPrintCounter)
- // r.Handle(GET, "/6", Chain(mwIncreaseCounter).HandlerFunc(handlerPrintCounter))
- r.With(mwIncreaseCounter).Get("/6", handlerPrintCounter)
-
- })
- })
- })
-
- ts := httptest.NewServer(r)
- defer ts.Close()
-
- for _, route := range []string{"0", "1", "2", "3", "4", "5", "6"} {
- if _, body := testRequest(t, ts, "GET", "/"+route, nil); body != route {
- t.Errorf("expected %v, got %v", route, body)
- }
- }
-}
-
-func TestMiddlewarePanicOnLateUse(t *testing.T) {
- handler := func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("hello\n"))
- }
-
- mw := func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- next.ServeHTTP(w, r)
- })
- }
-
- defer func() {
- if recover() == nil {
- t.Error("expected panic()")
- }
- }()
-
- r := NewRouter()
- r.Get("/", handler)
- r.Use(mw) // Too late to apply middleware, we're expecting panic().
-}
-
-func TestMountingExistingPath(t *testing.T) {
- handler := func(w http.ResponseWriter, r *http.Request) {}
-
- defer func() {
- if recover() == nil {
- t.Error("expected panic()")
- }
- }()
-
- r := NewRouter()
- r.Get("/", handler)
- r.Mount("/hi", http.HandlerFunc(handler))
- r.Mount("/hi", http.HandlerFunc(handler))
-}
-
-func TestMountingSimilarPattern(t *testing.T) {
- r := NewRouter()
- r.Get("/hi", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("bye"))
- })
-
- r2 := NewRouter()
- r2.Get("/", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("foobar"))
- })
-
- r3 := NewRouter()
- r3.Get("/", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("foo"))
- })
-
- r.Mount("/foobar", r2)
- r.Mount("/foo", r3)
-
- ts := httptest.NewServer(r)
- defer ts.Close()
-
- if _, body := testRequest(t, ts, "GET", "/hi", nil); body != "bye" {
- t.Fatalf(body)
- }
-}
-
-func TestMuxMissingParams(t *testing.T) {
- r := NewRouter()
- r.Get(`/user/{userId:\d+}`, func(w http.ResponseWriter, r *http.Request) {
- userID := URLParam(r, "userId")
- w.Write([]byte(fmt.Sprintf("userId = '%s'", userID)))
- })
- r.NotFound(func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(404)
- w.Write([]byte("nothing here"))
- })
-
- ts := httptest.NewServer(r)
- defer ts.Close()
-
- if _, body := testRequest(t, ts, "GET", "/user/123", nil); body != "userId = '123'" {
- t.Fatalf(body)
- }
- if _, body := testRequest(t, ts, "GET", "/user/", nil); body != "nothing here" {
- t.Fatalf(body)
- }
-}
-
-func TestMuxContextIsThreadSafe(t *testing.T) {
- router := NewRouter()
- router.Get("/{id}", func(w http.ResponseWriter, r *http.Request) {
- ctx, cancel := context.WithTimeout(r.Context(), 1*time.Millisecond)
- defer cancel()
-
- <-ctx.Done()
- })
-
- wg := sync.WaitGroup{}
-
- for i := 0; i < 100; i++ {
- wg.Add(1)
- go func() {
- defer wg.Done()
- for j := 0; j < 10000; j++ {
- w := httptest.NewRecorder()
- r, err := http.NewRequest("GET", "/ok", nil)
- if err != nil {
- t.Fatal(err)
- }
-
- ctx, cancel := context.WithCancel(r.Context())
- r = r.WithContext(ctx)
-
- go func() {
- cancel()
- }()
- router.ServeHTTP(w, r)
- }
- }()
- }
- wg.Wait()
-}
-
-func TestEscapedURLParams(t *testing.T) {
- m := NewRouter()
- m.Get("/api/{identifier}/{region}/{size}/{rotation}/*", func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(200)
- rctx := RouteContext(r.Context())
- if rctx == nil {
- t.Error("no context")
- return
- }
- identifier := URLParam(r, "identifier")
- if identifier != "http:%2f%2fexample.com%2fimage.png" {
- t.Errorf("identifier path parameter incorrect %s", identifier)
- return
- }
- region := URLParam(r, "region")
- if region != "full" {
- t.Errorf("region path parameter incorrect %s", region)
- return
- }
- size := URLParam(r, "size")
- if size != "max" {
- t.Errorf("size path parameter incorrect %s", size)
- return
- }
- rotation := URLParam(r, "rotation")
- if rotation != "0" {
- t.Errorf("rotation path parameter incorrect %s", rotation)
- return
- }
- w.Write([]byte("success"))
- })
-
- ts := httptest.NewServer(m)
- defer ts.Close()
-
- if _, body := testRequest(t, ts, "GET", "/api/http:%2f%2fexample.com%2fimage.png/full/max/0/color.png", nil); body != "success" {
- t.Fatalf(body)
- }
-}
-
-func TestMuxMatch(t *testing.T) {
- r := NewRouter()
- r.Get("/hi", func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("X-Test", "yes")
- w.Write([]byte("bye"))
- })
- r.Route("/articles", func(r Router) {
- r.Get("/{id}", func(w http.ResponseWriter, r *http.Request) {
- id := URLParam(r, "id")
- w.Header().Set("X-Article", id)
- w.Write([]byte("article:" + id))
- })
- })
- r.Route("/users", func(r Router) {
- r.Head("/{id}", func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("X-User", "-")
- w.Write([]byte("user"))
- })
- r.Get("/{id}", func(w http.ResponseWriter, r *http.Request) {
- id := URLParam(r, "id")
- w.Header().Set("X-User", id)
- w.Write([]byte("user:" + id))
- })
- })
-
- tctx := NewRouteContext()
-
- tctx.Reset()
- if r.Match(tctx, "GET", "/users/1") == false {
- t.Fatal("expecting to find match for route:", "GET", "/users/1")
- }
-
- tctx.Reset()
- if r.Match(tctx, "HEAD", "/articles/10") == true {
- t.Fatal("not expecting to find match for route:", "HEAD", "/articles/10")
- }
-}
-
-func TestServerBaseContext(t *testing.T) {
- r := NewRouter()
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- baseYes := r.Context().Value(ctxKey{"base"}).(string)
- if _, ok := r.Context().Value(http.ServerContextKey).(*http.Server); !ok {
- panic("missing server context")
- }
- if _, ok := r.Context().Value(http.LocalAddrContextKey).(net.Addr); !ok {
- panic("missing local addr context")
- }
- w.Write([]byte(baseYes))
- })
-
- // Setup http Server with a base context
- ctx := context.WithValue(context.Background(), ctxKey{"base"}, "yes")
- ts := httptest.NewServer(ServerBaseContext(ctx, r))
- defer ts.Close()
-
- if _, body := testRequest(t, ts, "GET", "/", nil); body != "yes" {
- t.Fatalf(body)
- }
-}
-
-func testRequest(t *testing.T, ts *httptest.Server, method, path string, body io.Reader) (*http.Response, string) {
- req, err := http.NewRequest(method, ts.URL+path, body)
- if err != nil {
- t.Fatal(err)
- return nil, ""
- }
-
- resp, err := http.DefaultClient.Do(req)
- if err != nil {
- t.Fatal(err)
- return nil, ""
- }
-
- respBody, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- t.Fatal(err)
- return nil, ""
- }
- defer resp.Body.Close()
-
- return resp, string(respBody)
-}
-
-func testHandler(t *testing.T, h http.Handler, method, path string, body io.Reader) (*http.Response, string) {
- r, _ := http.NewRequest(method, path, body)
- w := httptest.NewRecorder()
- h.ServeHTTP(w, r)
- return w.Result(), string(w.Body.Bytes())
-}
-
-type testFileSystem struct {
- open func(name string) (http.File, error)
-}
-
-func (fs *testFileSystem) Open(name string) (http.File, error) {
- return fs.open(name)
-}
-
-type testFile struct {
- name string
- contents []byte
-}
-
-func (tf *testFile) Close() error {
- return nil
-}
-
-func (tf *testFile) Read(p []byte) (n int, err error) {
- copy(p, tf.contents)
- return len(p), nil
-}
-
-func (tf *testFile) Seek(offset int64, whence int) (int64, error) {
- return 0, nil
-}
-
-func (tf *testFile) Readdir(count int) ([]os.FileInfo, error) {
- stat, _ := tf.Stat()
- return []os.FileInfo{stat}, nil
-}
-
-func (tf *testFile) Stat() (os.FileInfo, error) {
- return &testFileInfo{tf.name, int64(len(tf.contents))}, nil
-}
-
-type testFileInfo struct {
- name string
- size int64
-}
-
-func (tfi *testFileInfo) Name() string { return tfi.name }
-func (tfi *testFileInfo) Size() int64 { return tfi.size }
-func (tfi *testFileInfo) Mode() os.FileMode { return 0755 }
-func (tfi *testFileInfo) ModTime() time.Time { return time.Now() }
-func (tfi *testFileInfo) IsDir() bool { return false }
-func (tfi *testFileInfo) Sys() interface{} { return nil }
-
-type ctxKey struct {
- name string
-}
-
-func (k ctxKey) String() string {
- return "context value " + k.name
-}
-
-func BenchmarkMux(b *testing.B) {
- h1 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- h2 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- h3 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- h4 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- h5 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- h6 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
-
- mx := NewRouter()
- mx.Get("/", h1)
- mx.Get("/hi", h2)
- mx.Get("/sup/{id}/and/{this}", h3)
-
- mx.Route("/sharing/{hash}", func(mx Router) {
- mx.Get("/", h4) // subrouter-1
- mx.Get("/{network}", h5) // subrouter-1
- mx.Get("/twitter", h5)
- mx.Route("/direct", func(mx Router) {
- mx.Get("/", h6) // subrouter-2
- })
- })
-
- routes := []string{
- "/",
- "/sup/123/and/this",
- "/sharing/aBc", // subrouter-1
- "/sharing/aBc/twitter", // subrouter-1
- "/sharing/aBc/direct", // subrouter-2
- }
-
- for _, path := range routes {
- b.Run("route:"+path, func(b *testing.B) {
- w := httptest.NewRecorder()
- r, _ := http.NewRequest("GET", path, nil)
-
- b.ReportAllocs()
- b.ResetTimer()
-
- for i := 0; i < b.N; i++ {
- mx.ServeHTTP(w, r)
- }
- })
- }
-}
diff --git a/vendor/github.com/go-chi/chi/tree.go b/vendor/github.com/go-chi/chi/tree.go
deleted file mode 100644
index 966d1c7..0000000
--- a/vendor/github.com/go-chi/chi/tree.go
+++ /dev/null
@@ -1,842 +0,0 @@
-package chi
-
-// Radix tree implementation below is a based on the original work by
-// Armon Dadgar in https://github.com/armon/go-radix/blob/master/radix.go
-// (MIT licensed). It's been heavily modified for use as a HTTP routing tree.
-
-import (
- "fmt"
- "math"
- "net/http"
- "regexp"
- "sort"
- "strconv"
- "strings"
-)
-
-type methodTyp int
-
-const (
- mSTUB methodTyp = 1 << iota
- mCONNECT
- mDELETE
- mGET
- mHEAD
- mOPTIONS
- mPATCH
- mPOST
- mPUT
- mTRACE
-)
-
-var mALL methodTyp = mCONNECT | mDELETE | mGET | mHEAD |
- mOPTIONS | mPATCH | mPOST | mPUT | mTRACE
-
-var methodMap = map[string]methodTyp{
- "CONNECT": mCONNECT,
- "DELETE": mDELETE,
- "GET": mGET,
- "HEAD": mHEAD,
- "OPTIONS": mOPTIONS,
- "PATCH": mPATCH,
- "POST": mPOST,
- "PUT": mPUT,
- "TRACE": mTRACE,
-}
-
-func RegisterMethod(method string) {
- if method == "" {
- return
- }
- method = strings.ToUpper(method)
- if _, ok := methodMap[method]; ok {
- return
- }
- n := len(methodMap)
- if n > strconv.IntSize {
- panic(fmt.Sprintf("chi: max number of methods reached (%d)", strconv.IntSize))
- }
- mt := methodTyp(math.Exp2(float64(n)))
- methodMap[method] = mt
- mALL |= mt
-}
-
-type nodeTyp uint8
-
-const (
- ntStatic nodeTyp = iota // /home
- ntRegexp // /{id:[0-9]+}
- ntParam // /{user}
- ntCatchAll // /api/v1/*
-)
-
-type node struct {
- // node type: static, regexp, param, catchAll
- typ nodeTyp
-
- // first byte of the prefix
- label byte
-
- // first byte of the child prefix
- tail byte
-
- // prefix is the common prefix we ignore
- prefix string
-
- // regexp matcher for regexp nodes
- rex *regexp.Regexp
-
- // HTTP handler endpoints on the leaf node
- endpoints endpoints
-
- // subroutes on the leaf node
- subroutes Routes
-
- // child nodes should be stored in-order for iteration,
- // in groups of the node type.
- children [ntCatchAll + 1]nodes
-}
-
-// endpoints is a mapping of http method constants to handlers
-// for a given route.
-type endpoints map[methodTyp]*endpoint
-
-type endpoint struct {
- // endpoint handler
- handler http.Handler
-
- // pattern is the routing pattern for handler nodes
- pattern string
-
- // parameter keys recorded on handler nodes
- paramKeys []string
-}
-
-func (s endpoints) Value(method methodTyp) *endpoint {
- mh, ok := s[method]
- if !ok {
- mh = &endpoint{}
- s[method] = mh
- }
- return mh
-}
-
-func (n *node) InsertRoute(method methodTyp, pattern string, handler http.Handler) *node {
- var parent *node
- search := pattern
-
- for {
- // Handle key exhaustion
- if len(search) == 0 {
- // Insert or update the node's leaf handler
- n.setEndpoint(method, handler, pattern)
- return n
- }
-
- // We're going to be searching for a wild node next,
- // in this case, we need to get the tail
- var label = search[0]
- var segTail byte
- var segEndIdx int
- var segTyp nodeTyp
- var segRexpat string
- if label == '{' || label == '*' {
- segTyp, _, segRexpat, segTail, _, segEndIdx = patNextSegment(search)
- }
-
- var prefix string
- if segTyp == ntRegexp {
- prefix = segRexpat
- }
-
- // Look for the edge to attach to
- parent = n
- n = n.getEdge(segTyp, label, segTail, prefix)
-
- // No edge, create one
- if n == nil {
- child := &node{label: label, tail: segTail, prefix: search}
- hn := parent.addChild(child, search)
- hn.setEndpoint(method, handler, pattern)
-
- return hn
- }
-
- // Found an edge to match the pattern
-
- if n.typ > ntStatic {
- // We found a param node, trim the param from the search path and continue.
- // This param/wild pattern segment would already be on the tree from a previous
- // call to addChild when creating a new node.
- search = search[segEndIdx:]
- continue
- }
-
- // Static nodes fall below here.
- // Determine longest prefix of the search key on match.
- commonPrefix := longestPrefix(search, n.prefix)
- if commonPrefix == len(n.prefix) {
- // the common prefix is as long as the current node's prefix we're attempting to insert.
- // keep the search going.
- search = search[commonPrefix:]
- continue
- }
-
- // Split the node
- child := &node{
- typ: ntStatic,
- prefix: search[:commonPrefix],
- }
- parent.replaceChild(search[0], segTail, child)
-
- // Restore the existing node
- n.label = n.prefix[commonPrefix]
- n.prefix = n.prefix[commonPrefix:]
- child.addChild(n, n.prefix)
-
- // If the new key is a subset, set the method/handler on this node and finish.
- search = search[commonPrefix:]
- if len(search) == 0 {
- child.setEndpoint(method, handler, pattern)
- return child
- }
-
- // Create a new edge for the node
- subchild := &node{
- typ: ntStatic,
- label: search[0],
- prefix: search,
- }
- hn := child.addChild(subchild, search)
- hn.setEndpoint(method, handler, pattern)
- return hn
- }
-}
-
-// addChild appends the new `child` node to the tree using the `pattern` as the trie key.
-// For a URL router like chi's, we split the static, param, regexp and wildcard segments
-// into different nodes. In addition, addChild will recursively call itself until every
-// pattern segment is added to the url pattern tree as individual nodes, depending on type.
-func (n *node) addChild(child *node, prefix string) *node {
- search := prefix
-
- // handler leaf node added to the tree is the child.
- // this may be overridden later down the flow
- hn := child
-
- // Parse next segment
- segTyp, _, segRexpat, segTail, segStartIdx, segEndIdx := patNextSegment(search)
-
- // Add child depending on next up segment
- switch segTyp {
-
- case ntStatic:
- // Search prefix is all static (that is, has no params in path)
- // noop
-
- default:
- // Search prefix contains a param, regexp or wildcard
-
- if segTyp == ntRegexp {
- rex, err := regexp.Compile(segRexpat)
- if err != nil {
- panic(fmt.Sprintf("chi: invalid regexp pattern '%s' in route param", segRexpat))
- }
- child.prefix = segRexpat
- child.rex = rex
- }
-
- if segStartIdx == 0 {
- // Route starts with a param
- child.typ = segTyp
-
- if segTyp == ntCatchAll {
- segStartIdx = -1
- } else {
- segStartIdx = segEndIdx
- }
- if segStartIdx < 0 {
- segStartIdx = len(search)
- }
- child.tail = segTail // for params, we set the tail
-
- if segStartIdx != len(search) {
- // add static edge for the remaining part, split the end.
- // its not possible to have adjacent param nodes, so its certainly
- // going to be a static node next.
-
- search = search[segStartIdx:] // advance search position
-
- nn := &node{
- typ: ntStatic,
- label: search[0],
- prefix: search,
- }
- hn = child.addChild(nn, search)
- }
-
- } else if segStartIdx > 0 {
- // Route has some param
-
- // starts with a static segment
- child.typ = ntStatic
- child.prefix = search[:segStartIdx]
- child.rex = nil
-
- // add the param edge node
- search = search[segStartIdx:]
-
- nn := &node{
- typ: segTyp,
- label: search[0],
- tail: segTail,
- }
- hn = child.addChild(nn, search)
-
- }
- }
-
- n.children[child.typ] = append(n.children[child.typ], child)
- n.children[child.typ].Sort()
- return hn
-}
-
-func (n *node) replaceChild(label, tail byte, child *node) {
- for i := 0; i < len(n.children[child.typ]); i++ {
- if n.children[child.typ][i].label == label && n.children[child.typ][i].tail == tail {
- n.children[child.typ][i] = child
- n.children[child.typ][i].label = label
- n.children[child.typ][i].tail = tail
- return
- }
- }
- panic("chi: replacing missing child")
-}
-
-func (n *node) getEdge(ntyp nodeTyp, label, tail byte, prefix string) *node {
- nds := n.children[ntyp]
- for i := 0; i < len(nds); i++ {
- if nds[i].label == label && nds[i].tail == tail {
- if ntyp == ntRegexp && nds[i].prefix != prefix {
- continue
- }
- return nds[i]
- }
- }
- return nil
-}
-
-func (n *node) setEndpoint(method methodTyp, handler http.Handler, pattern string) {
- // Set the handler for the method type on the node
- if n.endpoints == nil {
- n.endpoints = make(endpoints, 0)
- }
-
- paramKeys := patParamKeys(pattern)
-
- if method&mSTUB == mSTUB {
- n.endpoints.Value(mSTUB).handler = handler
- }
- if method&mALL == mALL {
- h := n.endpoints.Value(mALL)
- h.handler = handler
- h.pattern = pattern
- h.paramKeys = paramKeys
- for _, m := range methodMap {
- h := n.endpoints.Value(m)
- h.handler = handler
- h.pattern = pattern
- h.paramKeys = paramKeys
- }
- } else {
- h := n.endpoints.Value(method)
- h.handler = handler
- h.pattern = pattern
- h.paramKeys = paramKeys
- }
-}
-
-func (n *node) FindRoute(rctx *Context, method methodTyp, path string) (*node, endpoints, http.Handler) {
- // Reset the context routing pattern and params
- rctx.routePattern = ""
- rctx.routeParams.Keys = rctx.routeParams.Keys[:0]
- rctx.routeParams.Values = rctx.routeParams.Values[:0]
-
- // Find the routing handlers for the path
- rn := n.findRoute(rctx, method, path)
- if rn == nil {
- return nil, nil, nil
- }
-
- // Record the routing params in the request lifecycle
- rctx.URLParams.Keys = append(rctx.URLParams.Keys, rctx.routeParams.Keys...)
- rctx.URLParams.Values = append(rctx.URLParams.Values, rctx.routeParams.Values...)
-
- // Record the routing pattern in the request lifecycle
- if rn.endpoints[method].pattern != "" {
- rctx.routePattern = rn.endpoints[method].pattern
- rctx.RoutePatterns = append(rctx.RoutePatterns, rctx.routePattern)
- }
-
- return rn, rn.endpoints, rn.endpoints[method].handler
-}
-
-// Recursive edge traversal by checking all nodeTyp groups along the way.
-// It's like searching through a multi-dimensional radix trie.
-func (n *node) findRoute(rctx *Context, method methodTyp, path string) *node {
- nn := n
- search := path
-
- for t, nds := range nn.children {
- ntyp := nodeTyp(t)
- if len(nds) == 0 {
- continue
- }
-
- var xn *node
- xsearch := search
-
- var label byte
- if search != "" {
- label = search[0]
- }
-
- switch ntyp {
- case ntStatic:
- xn = nds.findEdge(label)
- if xn == nil || !strings.HasPrefix(xsearch, xn.prefix) {
- continue
- }
- xsearch = xsearch[len(xn.prefix):]
-
- case ntParam, ntRegexp:
- // short-circuit and return no matching route for empty param values
- if xsearch == "" {
- continue
- }
-
- // serially loop through each node grouped by the tail delimiter
- for idx := 0; idx < len(nds); idx++ {
- xn = nds[idx]
-
- // label for param nodes is the delimiter byte
- p := strings.IndexByte(xsearch, xn.tail)
-
- if p <= 0 {
- if xn.tail == '/' {
- p = len(xsearch)
- } else {
- continue
- }
- }
-
- if ntyp == ntRegexp && xn.rex != nil {
- if xn.rex.Match([]byte(xsearch[:p])) == false {
- continue
- }
- } else if strings.IndexByte(xsearch[:p], '/') != -1 {
- // avoid a match across path segments
- continue
- }
-
- rctx.routeParams.Values = append(rctx.routeParams.Values, xsearch[:p])
- xsearch = xsearch[p:]
- break
- }
-
- default:
- // catch-all nodes
- rctx.routeParams.Values = append(rctx.routeParams.Values, search)
- xn = nds[0]
- xsearch = ""
- }
-
- if xn == nil {
- continue
- }
-
- // did we find it yet?
- if len(xsearch) == 0 {
- if xn.isLeaf() {
- h, _ := xn.endpoints[method]
- if h != nil && h.handler != nil {
- rctx.routeParams.Keys = append(rctx.routeParams.Keys, h.paramKeys...)
- return xn
- }
-
- // flag that the routing context found a route, but not a corresponding
- // supported method
- rctx.methodNotAllowed = true
- }
- }
-
- // recursively find the next node..
- fin := xn.findRoute(rctx, method, xsearch)
- if fin != nil {
- return fin
- }
-
- // Did not find final handler, let's remove the param here if it was set
- if xn.typ > ntStatic {
- if len(rctx.routeParams.Values) > 0 {
- rctx.routeParams.Values = rctx.routeParams.Values[:len(rctx.routeParams.Values)-1]
- }
- }
-
- }
-
- return nil
-}
-
-func (n *node) findEdge(ntyp nodeTyp, label byte) *node {
- nds := n.children[ntyp]
- num := len(nds)
- idx := 0
-
- switch ntyp {
- case ntStatic, ntParam, ntRegexp:
- i, j := 0, num-1
- for i <= j {
- idx = i + (j-i)/2
- if label > nds[idx].label {
- i = idx + 1
- } else if label < nds[idx].label {
- j = idx - 1
- } else {
- i = num // breaks cond
- }
- }
- if nds[idx].label != label {
- return nil
- }
- return nds[idx]
-
- default: // catch all
- return nds[idx]
- }
-}
-
-func (n *node) isEmpty() bool {
- for _, nds := range n.children {
- if len(nds) > 0 {
- return false
- }
- }
- return true
-}
-
-func (n *node) isLeaf() bool {
- return n.endpoints != nil
-}
-
-func (n *node) findPattern(pattern string) bool {
- nn := n
- for _, nds := range nn.children {
- if len(nds) == 0 {
- continue
- }
-
- n = nn.findEdge(nds[0].typ, pattern[0])
- if n == nil {
- continue
- }
-
- var idx int
- var xpattern string
-
- switch n.typ {
- case ntStatic:
- idx = longestPrefix(pattern, n.prefix)
- if idx < len(n.prefix) {
- continue
- }
-
- case ntParam, ntRegexp:
- idx = strings.IndexByte(pattern, '}') + 1
-
- case ntCatchAll:
- idx = longestPrefix(pattern, "*")
-
- default:
- panic("chi: unknown node type")
- }
-
- xpattern = pattern[idx:]
- if len(xpattern) == 0 {
- return true
- }
-
- return n.findPattern(xpattern)
- }
- return false
-}
-
-func (n *node) routes() []Route {
- rts := []Route{}
-
- n.walk(func(eps endpoints, subroutes Routes) bool {
- if eps[mSTUB] != nil && eps[mSTUB].handler != nil && subroutes == nil {
- return false
- }
-
- // Group methodHandlers by unique patterns
- pats := make(map[string]endpoints, 0)
-
- for mt, h := range eps {
- if h.pattern == "" {
- continue
- }
- p, ok := pats[h.pattern]
- if !ok {
- p = endpoints{}
- pats[h.pattern] = p
- }
- p[mt] = h
- }
-
- for p, mh := range pats {
- hs := make(map[string]http.Handler, 0)
- if mh[mALL] != nil && mh[mALL].handler != nil {
- hs["*"] = mh[mALL].handler
- }
-
- for mt, h := range mh {
- if h.handler == nil {
- continue
- }
- m := methodTypString(mt)
- if m == "" {
- continue
- }
- hs[m] = h.handler
- }
-
- rt := Route{p, hs, subroutes}
- rts = append(rts, rt)
- }
-
- return false
- })
-
- return rts
-}
-
-func (n *node) walk(fn func(eps endpoints, subroutes Routes) bool) bool {
- // Visit the leaf values if any
- if (n.endpoints != nil || n.subroutes != nil) && fn(n.endpoints, n.subroutes) {
- return true
- }
-
- // Recurse on the children
- for _, ns := range n.children {
- for _, cn := range ns {
- if cn.walk(fn) {
- return true
- }
- }
- }
- return false
-}
-
-// patNextSegment returns the next segment details from a pattern:
-// node type, param key, regexp string, param tail byte, param starting index, param ending index
-func patNextSegment(pattern string) (nodeTyp, string, string, byte, int, int) {
- ps := strings.Index(pattern, "{")
- ws := strings.Index(pattern, "*")
-
- if ps < 0 && ws < 0 {
- return ntStatic, "", "", 0, 0, len(pattern) // we return the entire thing
- }
-
- // Sanity check
- if ps >= 0 && ws >= 0 && ws < ps {
- panic("chi: wildcard '*' must be the last pattern in a route, otherwise use a '{param}'")
- }
-
- var tail byte = '/' // Default endpoint tail to / byte
-
- if ps >= 0 {
- // Param/Regexp pattern is next
- nt := ntParam
-
- // Read to closing } taking into account opens and closes in curl count (cc)
- cc := 0
- pe := ps
- for i, c := range pattern[ps:] {
- if c == '{' {
- cc++
- } else if c == '}' {
- cc--
- if cc == 0 {
- pe = ps + i
- break
- }
- }
- }
- if pe == ps {
- panic("chi: route param closing delimiter '}' is missing")
- }
-
- key := pattern[ps+1 : pe]
- pe++ // set end to next position
-
- if pe < len(pattern) {
- tail = pattern[pe]
- }
-
- var rexpat string
- if idx := strings.Index(key, ":"); idx >= 0 {
- nt = ntRegexp
- rexpat = key[idx+1:]
- key = key[:idx]
- }
-
- if len(rexpat) > 0 {
- if rexpat[0] != '^' {
- rexpat = "^" + rexpat
- }
- if rexpat[len(rexpat)-1] != '$' {
- rexpat = rexpat + "$"
- }
- }
-
- return nt, key, rexpat, tail, ps, pe
- }
-
- // Wildcard pattern as finale
- // TODO: should we panic if there is stuff after the * ???
- return ntCatchAll, "*", "", 0, ws, len(pattern)
-}
-
-func patParamKeys(pattern string) []string {
- pat := pattern
- paramKeys := []string{}
- for {
- ptyp, paramKey, _, _, _, e := patNextSegment(pat)
- if ptyp == ntStatic {
- return paramKeys
- }
- for i := 0; i < len(paramKeys); i++ {
- if paramKeys[i] == paramKey {
- panic(fmt.Sprintf("chi: routing pattern '%s' contains duplicate param key, '%s'", pattern, paramKey))
- }
- }
- paramKeys = append(paramKeys, paramKey)
- pat = pat[e:]
- }
-}
-
-// longestPrefix finds the length of the shared prefix
-// of two strings
-func longestPrefix(k1, k2 string) int {
- max := len(k1)
- if l := len(k2); l < max {
- max = l
- }
- var i int
- for i = 0; i < max; i++ {
- if k1[i] != k2[i] {
- break
- }
- }
- return i
-}
-
-func methodTypString(method methodTyp) string {
- for s, t := range methodMap {
- if method == t {
- return s
- }
- }
- return ""
-}
-
-type nodes []*node
-
-// Sort the list of nodes by label
-func (ns nodes) Sort() { sort.Sort(ns); ns.tailSort() }
-func (ns nodes) Len() int { return len(ns) }
-func (ns nodes) Swap(i, j int) { ns[i], ns[j] = ns[j], ns[i] }
-func (ns nodes) Less(i, j int) bool { return ns[i].label < ns[j].label }
-
-// tailSort pushes nodes with '/' as the tail to the end of the list for param nodes.
-// The list order determines the traversal order.
-func (ns nodes) tailSort() {
- for i := len(ns) - 1; i >= 0; i-- {
- if ns[i].typ > ntStatic && ns[i].tail == '/' {
- ns.Swap(i, len(ns)-1)
- return
- }
- }
-}
-
-func (ns nodes) findEdge(label byte) *node {
- num := len(ns)
- idx := 0
- i, j := 0, num-1
- for i <= j {
- idx = i + (j-i)/2
- if label > ns[idx].label {
- i = idx + 1
- } else if label < ns[idx].label {
- j = idx - 1
- } else {
- i = num // breaks cond
- }
- }
- if ns[idx].label != label {
- return nil
- }
- return ns[idx]
-}
-
-// Route describes the details of a routing handler.
-type Route struct {
- Pattern string
- Handlers map[string]http.Handler
- SubRoutes Routes
-}
-
-// WalkFunc is the type of the function called for each method and route visited by Walk.
-type WalkFunc func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error
-
-// Walk walks any router tree that implements Routes interface.
-func Walk(r Routes, walkFn WalkFunc) error {
- return walk(r, walkFn, "")
-}
-
-func walk(r Routes, walkFn WalkFunc, parentRoute string, parentMw ...func(http.Handler) http.Handler) error {
- for _, route := range r.Routes() {
- mws := make([]func(http.Handler) http.Handler, len(parentMw))
- copy(mws, parentMw)
- mws = append(mws, r.Middlewares()...)
-
- if route.SubRoutes != nil {
- if err := walk(route.SubRoutes, walkFn, parentRoute+route.Pattern, mws...); err != nil {
- return err
- }
- continue
- }
-
- for method, handler := range route.Handlers {
- if method == "*" {
- // Ignore a "catchAll" method, since we pass down all the specific methods for each route.
- continue
- }
-
- fullRoute := parentRoute + route.Pattern
-
- if chain, ok := handler.(*ChainHandler); ok {
- if err := walkFn(method, fullRoute, chain.Endpoint, append(mws, chain.Middlewares...)...); err != nil {
- return err
- }
- } else {
- if err := walkFn(method, fullRoute, handler, mws...); err != nil {
- return err
- }
- }
- }
- }
-
- return nil
-}
diff --git a/vendor/github.com/go-chi/chi/tree_test.go b/vendor/github.com/go-chi/chi/tree_test.go
deleted file mode 100644
index 89a835c..0000000
--- a/vendor/github.com/go-chi/chi/tree_test.go
+++ /dev/null
@@ -1,467 +0,0 @@
-package chi
-
-import (
- "fmt"
- "log"
- "net/http"
- "testing"
-)
-
-func TestTree(t *testing.T) {
- hStub := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hIndex := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hFavicon := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hArticleList := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hArticleNear := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hArticleShow := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hArticleShowRelated := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hArticleShowOpts := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hArticleSlug := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hArticleByUser := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hUserList := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hUserShow := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hAdminCatchall := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hAdminAppShow := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hAdminAppShowCatchall := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hUserProfile := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hUserSuper := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hUserAll := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hHubView1 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hHubView2 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hHubView3 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
-
- tr := &node{}
-
- tr.InsertRoute(mGET, "/", hIndex)
- tr.InsertRoute(mGET, "/favicon.ico", hFavicon)
-
- tr.InsertRoute(mGET, "/pages/*", hStub)
-
- tr.InsertRoute(mGET, "/article", hArticleList)
- tr.InsertRoute(mGET, "/article/", hArticleList)
-
- tr.InsertRoute(mGET, "/article/near", hArticleNear)
- tr.InsertRoute(mGET, "/article/{id}", hStub)
- tr.InsertRoute(mGET, "/article/{id}", hArticleShow)
- tr.InsertRoute(mGET, "/article/{id}", hArticleShow) // duplicate will have no effect
- tr.InsertRoute(mGET, "/article/@{user}", hArticleByUser)
-
- tr.InsertRoute(mGET, "/article/{sup}/{opts}", hArticleShowOpts)
- tr.InsertRoute(mGET, "/article/{id}/{opts}", hArticleShowOpts) // overwrite above route, latest wins
-
- tr.InsertRoute(mGET, "/article/{iffd}/edit", hStub)
- tr.InsertRoute(mGET, "/article/{id}//related", hArticleShowRelated)
- tr.InsertRoute(mGET, "/article/slug/{month}/-/{day}/{year}", hArticleSlug)
-
- tr.InsertRoute(mGET, "/admin/user", hUserList)
- tr.InsertRoute(mGET, "/admin/user/", hStub) // will get replaced by next route
- tr.InsertRoute(mGET, "/admin/user/", hUserList)
-
- tr.InsertRoute(mGET, "/admin/user//{id}", hUserShow)
- tr.InsertRoute(mGET, "/admin/user/{id}", hUserShow)
-
- tr.InsertRoute(mGET, "/admin/apps/{id}", hAdminAppShow)
- tr.InsertRoute(mGET, "/admin/apps/{id}/*ff", hAdminAppShowCatchall) // TODO: ALLOWED...? prob not.. panic..?
-
- tr.InsertRoute(mGET, "/admin/*ff", hStub) // catchall segment will get replaced by next route
- tr.InsertRoute(mGET, "/admin/*", hAdminCatchall)
-
- tr.InsertRoute(mGET, "/users/{userID}/profile", hUserProfile)
- tr.InsertRoute(mGET, "/users/super/*", hUserSuper)
- tr.InsertRoute(mGET, "/users/*", hUserAll)
-
- tr.InsertRoute(mGET, "/hubs/{hubID}/view", hHubView1)
- tr.InsertRoute(mGET, "/hubs/{hubID}/view/*", hHubView2)
- sr := NewRouter()
- sr.Get("/users", hHubView3)
- tr.InsertRoute(mGET, "/hubs/{hubID}/*", sr)
- tr.InsertRoute(mGET, "/hubs/{hubID}/users", hHubView3)
-
- tests := []struct {
- r string // input request path
- h http.Handler // output matched handler
- k []string // output param keys
- v []string // output param values
- }{
- {r: "/", h: hIndex, k: []string{}, v: []string{}},
- {r: "/favicon.ico", h: hFavicon, k: []string{}, v: []string{}},
-
- {r: "/pages", h: nil, k: []string{}, v: []string{}},
- {r: "/pages/", h: hStub, k: []string{"*"}, v: []string{""}},
- {r: "/pages/yes", h: hStub, k: []string{"*"}, v: []string{"yes"}},
-
- {r: "/article", h: hArticleList, k: []string{}, v: []string{}},
- {r: "/article/", h: hArticleList, k: []string{}, v: []string{}},
- {r: "/article/near", h: hArticleNear, k: []string{}, v: []string{}},
- {r: "/article/neard", h: hArticleShow, k: []string{"id"}, v: []string{"neard"}},
- {r: "/article/123", h: hArticleShow, k: []string{"id"}, v: []string{"123"}},
- {r: "/article/123/456", h: hArticleShowOpts, k: []string{"id", "opts"}, v: []string{"123", "456"}},
- {r: "/article/@peter", h: hArticleByUser, k: []string{"user"}, v: []string{"peter"}},
- {r: "/article/22//related", h: hArticleShowRelated, k: []string{"id"}, v: []string{"22"}},
- {r: "/article/111/edit", h: hStub, k: []string{"iffd"}, v: []string{"111"}},
- {r: "/article/slug/sept/-/4/2015", h: hArticleSlug, k: []string{"month", "day", "year"}, v: []string{"sept", "4", "2015"}},
- {r: "/article/:id", h: hArticleShow, k: []string{"id"}, v: []string{":id"}},
-
- {r: "/admin/user", h: hUserList, k: []string{}, v: []string{}},
- {r: "/admin/user/", h: hUserList, k: []string{}, v: []string{}},
- {r: "/admin/user/1", h: hUserShow, k: []string{"id"}, v: []string{"1"}},
- {r: "/admin/user//1", h: hUserShow, k: []string{"id"}, v: []string{"1"}},
- {r: "/admin/hi", h: hAdminCatchall, k: []string{"*"}, v: []string{"hi"}},
- {r: "/admin/lots/of/:fun", h: hAdminCatchall, k: []string{"*"}, v: []string{"lots/of/:fun"}},
- {r: "/admin/apps/333", h: hAdminAppShow, k: []string{"id"}, v: []string{"333"}},
- {r: "/admin/apps/333/woot", h: hAdminAppShowCatchall, k: []string{"id", "*"}, v: []string{"333", "woot"}},
-
- {r: "/hubs/123/view", h: hHubView1, k: []string{"hubID"}, v: []string{"123"}},
- {r: "/hubs/123/view/index.html", h: hHubView2, k: []string{"hubID", "*"}, v: []string{"123", "index.html"}},
- {r: "/hubs/123/users", h: hHubView3, k: []string{"hubID"}, v: []string{"123"}},
-
- {r: "/users/123/profile", h: hUserProfile, k: []string{"userID"}, v: []string{"123"}},
- {r: "/users/super/123/okay/yes", h: hUserSuper, k: []string{"*"}, v: []string{"123/okay/yes"}},
- {r: "/users/123/okay/yes", h: hUserAll, k: []string{"*"}, v: []string{"123/okay/yes"}},
- }
-
- // log.Println("~~~~~~~~~")
- // log.Println("~~~~~~~~~")
- // debugPrintTree(0, 0, tr, 0)
- // log.Println("~~~~~~~~~")
- // log.Println("~~~~~~~~~")
-
- for i, tt := range tests {
- rctx := NewRouteContext()
-
- _, handlers, _ := tr.FindRoute(rctx, mGET, tt.r)
-
- var handler http.Handler
- if methodHandler, ok := handlers[mGET]; ok {
- handler = methodHandler.handler
- }
-
- paramKeys := rctx.routeParams.Keys
- paramValues := rctx.routeParams.Values
-
- if fmt.Sprintf("%v", tt.h) != fmt.Sprintf("%v", handler) {
- t.Errorf("input [%d]: find '%s' expecting handler:%v , got:%v", i, tt.r, tt.h, handler)
- }
- if !stringSliceEqual(tt.k, paramKeys) {
- t.Errorf("input [%d]: find '%s' expecting paramKeys:(%d)%v , got:(%d)%v", i, tt.r, len(tt.k), tt.k, len(paramKeys), paramKeys)
- }
- if !stringSliceEqual(tt.v, paramValues) {
- t.Errorf("input [%d]: find '%s' expecting paramValues:(%d)%v , got:(%d)%v", i, tt.r, len(tt.v), tt.v, len(paramValues), paramValues)
- }
- }
-}
-
-func TestTreeMoar(t *testing.T) {
- hStub := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hStub1 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hStub2 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hStub3 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hStub4 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hStub5 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hStub6 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hStub7 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hStub8 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hStub9 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hStub10 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hStub11 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hStub12 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hStub13 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hStub14 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hStub15 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hStub16 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
-
- // TODO: panic if we see {id}{x} because we're missing a delimiter, its not possible.
- // also {:id}* is not possible.
-
- tr := &node{}
-
- tr.InsertRoute(mGET, "/articlefun", hStub5)
- tr.InsertRoute(mGET, "/articles/{id}", hStub)
- tr.InsertRoute(mDELETE, "/articles/{slug}", hStub8)
- tr.InsertRoute(mGET, "/articles/search", hStub1)
- tr.InsertRoute(mGET, "/articles/{id}:delete", hStub8)
- tr.InsertRoute(mGET, "/articles/{iidd}!sup", hStub4)
- tr.InsertRoute(mGET, "/articles/{id}:{op}", hStub3)
- tr.InsertRoute(mGET, "/articles/{id}:{op}", hStub2) // this route sets a new handler for the above route
- tr.InsertRoute(mGET, "/articles/{slug:^[a-z]+}/posts", hStub) // up to tail '/' will only match if contents match the rex
- tr.InsertRoute(mGET, "/articles/{id}/posts/{pid}", hStub6) // /articles/123/posts/1
- tr.InsertRoute(mGET, "/articles/{id}/posts/{month}/{day}/{year}/{slug}", hStub7) // /articles/123/posts/09/04/1984/juice
- tr.InsertRoute(mGET, "/articles/{id}.json", hStub10)
- tr.InsertRoute(mGET, "/articles/{id}/data.json", hStub11)
- tr.InsertRoute(mGET, "/articles/files/{file}.{ext}", hStub12)
- tr.InsertRoute(mPUT, "/articles/me", hStub13)
-
- // TODO: make a separate test case for this one..
- // tr.InsertRoute(mGET, "/articles/{id}/{id}", hStub1) // panic expected, we're duplicating param keys
-
- tr.InsertRoute(mGET, "/pages/*ff", hStub) // TODO: panic, allow it..?
- tr.InsertRoute(mGET, "/pages/*", hStub9)
-
- tr.InsertRoute(mGET, "/users/{id}", hStub14)
- tr.InsertRoute(mGET, "/users/{id}/settings/{key}", hStub15)
- tr.InsertRoute(mGET, "/users/{id}/settings/*", hStub16)
-
- tests := []struct {
- m methodTyp // input request http method
- r string // input request path
- h http.Handler // output matched handler
- k []string // output param keys
- v []string // output param values
- }{
- {m: mGET, r: "/articles/search", h: hStub1, k: []string{}, v: []string{}},
- {m: mGET, r: "/articlefun", h: hStub5, k: []string{}, v: []string{}},
- {m: mGET, r: "/articles/123", h: hStub, k: []string{"id"}, v: []string{"123"}},
- {m: mDELETE, r: "/articles/123mm", h: hStub8, k: []string{"slug"}, v: []string{"123mm"}},
- {m: mGET, r: "/articles/789:delete", h: hStub8, k: []string{"id"}, v: []string{"789"}},
- {m: mGET, r: "/articles/789!sup", h: hStub4, k: []string{"iidd"}, v: []string{"789"}},
- {m: mGET, r: "/articles/123:sync", h: hStub2, k: []string{"id", "op"}, v: []string{"123", "sync"}},
- {m: mGET, r: "/articles/456/posts/1", h: hStub6, k: []string{"id", "pid"}, v: []string{"456", "1"}},
- {m: mGET, r: "/articles/456/posts/09/04/1984/juice", h: hStub7, k: []string{"id", "month", "day", "year", "slug"}, v: []string{"456", "09", "04", "1984", "juice"}},
- {m: mGET, r: "/articles/456.json", h: hStub10, k: []string{"id"}, v: []string{"456"}},
- {m: mGET, r: "/articles/456/data.json", h: hStub11, k: []string{"id"}, v: []string{"456"}},
-
- {m: mGET, r: "/articles/files/file.zip", h: hStub12, k: []string{"file", "ext"}, v: []string{"file", "zip"}},
- {m: mGET, r: "/articles/files/photos.tar.gz", h: hStub12, k: []string{"file", "ext"}, v: []string{"photos", "tar.gz"}},
- {m: mGET, r: "/articles/files/photos.tar.gz", h: hStub12, k: []string{"file", "ext"}, v: []string{"photos", "tar.gz"}},
-
- {m: mPUT, r: "/articles/me", h: hStub13, k: []string{}, v: []string{}},
- {m: mGET, r: "/articles/me", h: hStub, k: []string{"id"}, v: []string{"me"}},
- {m: mGET, r: "/pages", h: nil, k: []string{}, v: []string{}},
- {m: mGET, r: "/pages/", h: hStub9, k: []string{"*"}, v: []string{""}},
- {m: mGET, r: "/pages/yes", h: hStub9, k: []string{"*"}, v: []string{"yes"}},
-
- {m: mGET, r: "/users/1", h: hStub14, k: []string{"id"}, v: []string{"1"}},
- {m: mGET, r: "/users/", h: nil, k: []string{}, v: []string{}},
- {m: mGET, r: "/users/2/settings/password", h: hStub15, k: []string{"id", "key"}, v: []string{"2", "password"}},
- {m: mGET, r: "/users/2/settings/", h: hStub16, k: []string{"id", "*"}, v: []string{"2", ""}},
- }
-
- // log.Println("~~~~~~~~~")
- // log.Println("~~~~~~~~~")
- // debugPrintTree(0, 0, tr, 0)
- // log.Println("~~~~~~~~~")
- // log.Println("~~~~~~~~~")
-
- for i, tt := range tests {
- rctx := NewRouteContext()
-
- _, handlers, _ := tr.FindRoute(rctx, tt.m, tt.r)
-
- var handler http.Handler
- if methodHandler, ok := handlers[tt.m]; ok {
- handler = methodHandler.handler
- }
-
- paramKeys := rctx.routeParams.Keys
- paramValues := rctx.routeParams.Values
-
- if fmt.Sprintf("%v", tt.h) != fmt.Sprintf("%v", handler) {
- t.Errorf("input [%d]: find '%s' expecting handler:%v , got:%v", i, tt.r, tt.h, handler)
- }
- if !stringSliceEqual(tt.k, paramKeys) {
- t.Errorf("input [%d]: find '%s' expecting paramKeys:(%d)%v , got:(%d)%v", i, tt.r, len(tt.k), tt.k, len(paramKeys), paramKeys)
- }
- if !stringSliceEqual(tt.v, paramValues) {
- t.Errorf("input [%d]: find '%s' expecting paramValues:(%d)%v , got:(%d)%v", i, tt.r, len(tt.v), tt.v, len(paramValues), paramValues)
- }
- }
-}
-
-func TestTreeRegexp(t *testing.T) {
- hStub1 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hStub2 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hStub3 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hStub4 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hStub5 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hStub6 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hStub7 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
-
- tr := &node{}
- tr.InsertRoute(mGET, "/articles/{rid:^[0-9]{5,6}}", hStub7)
- tr.InsertRoute(mGET, "/articles/{zid:^0[0-9]+}", hStub3)
- tr.InsertRoute(mGET, "/articles/{name:^@[a-z]+}/posts", hStub4)
- tr.InsertRoute(mGET, "/articles/{op:^[0-9]+}/run", hStub5)
- tr.InsertRoute(mGET, "/articles/{id:^[0-9]+}", hStub1)
- tr.InsertRoute(mGET, "/articles/{id:^[1-9]+}-{aux}", hStub6)
- tr.InsertRoute(mGET, "/articles/{slug}", hStub2)
-
- // log.Println("~~~~~~~~~")
- // log.Println("~~~~~~~~~")
- // debugPrintTree(0, 0, tr, 0)
- // log.Println("~~~~~~~~~")
- // log.Println("~~~~~~~~~")
-
- tests := []struct {
- r string // input request path
- h http.Handler // output matched handler
- k []string // output param keys
- v []string // output param values
- }{
- {r: "/articles", h: nil, k: []string{}, v: []string{}},
- {r: "/articles/12345", h: hStub7, k: []string{"rid"}, v: []string{"12345"}},
- {r: "/articles/123", h: hStub1, k: []string{"id"}, v: []string{"123"}},
- {r: "/articles/how-to-build-a-router", h: hStub2, k: []string{"slug"}, v: []string{"how-to-build-a-router"}},
- {r: "/articles/0456", h: hStub3, k: []string{"zid"}, v: []string{"0456"}},
- {r: "/articles/@pk/posts", h: hStub4, k: []string{"name"}, v: []string{"@pk"}},
- {r: "/articles/1/run", h: hStub5, k: []string{"op"}, v: []string{"1"}},
- {r: "/articles/1122", h: hStub1, k: []string{"id"}, v: []string{"1122"}},
- {r: "/articles/1122-yes", h: hStub6, k: []string{"id", "aux"}, v: []string{"1122", "yes"}},
- }
-
- for i, tt := range tests {
- rctx := NewRouteContext()
-
- _, handlers, _ := tr.FindRoute(rctx, mGET, tt.r)
-
- var handler http.Handler
- if methodHandler, ok := handlers[mGET]; ok {
- handler = methodHandler.handler
- }
-
- paramKeys := rctx.routeParams.Keys
- paramValues := rctx.routeParams.Values
-
- if fmt.Sprintf("%v", tt.h) != fmt.Sprintf("%v", handler) {
- t.Errorf("input [%d]: find '%s' expecting handler:%v , got:%v", i, tt.r, tt.h, handler)
- }
- if !stringSliceEqual(tt.k, paramKeys) {
- t.Errorf("input [%d]: find '%s' expecting paramKeys:(%d)%v , got:(%d)%v", i, tt.r, len(tt.k), tt.k, len(paramKeys), paramKeys)
- }
- if !stringSliceEqual(tt.v, paramValues) {
- t.Errorf("input [%d]: find '%s' expecting paramValues:(%d)%v , got:(%d)%v", i, tt.r, len(tt.v), tt.v, len(paramValues), paramValues)
- }
- }
-}
-
-func TestTreeRegexMatchWholeParam(t *testing.T) {
- hStub1 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
-
- rctx := NewRouteContext()
- tr := &node{}
- tr.InsertRoute(mGET, "/{id:[0-9]+}", hStub1)
-
- tests := []struct {
- url string
- expectedHandler http.Handler
- }{
- {url: "/13", expectedHandler: hStub1},
- {url: "/a13", expectedHandler: nil},
- {url: "/13.jpg", expectedHandler: nil},
- {url: "/a13.jpg", expectedHandler: nil},
- }
-
- for _, tc := range tests {
- _, _, handler := tr.FindRoute(rctx, mGET, tc.url)
- if fmt.Sprintf("%v", tc.expectedHandler) != fmt.Sprintf("%v", handler) {
- t.Errorf("expecting handler:%v , got:%v", tc.expectedHandler, handler)
- }
- }
-}
-
-func TestTreeFindPattern(t *testing.T) {
- hStub1 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hStub2 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- hStub3 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
-
- tr := &node{}
- tr.InsertRoute(mGET, "/pages/*", hStub1)
- tr.InsertRoute(mGET, "/articles/{id}/*", hStub2)
- tr.InsertRoute(mGET, "/articles/{slug}/{uid}/*", hStub3)
-
- if tr.findPattern("/pages") != false {
- t.Errorf("find /pages failed")
- }
- if tr.findPattern("/pages*") != false {
- t.Errorf("find /pages* failed - should be nil")
- }
- if tr.findPattern("/pages/*") == false {
- t.Errorf("find /pages/* failed")
- }
- if tr.findPattern("/articles/{id}/*") == false {
- t.Errorf("find /articles/{id}/* failed")
- }
- if tr.findPattern("/articles/{something}/*") == false {
- t.Errorf("find /articles/{something}/* failed")
- }
- if tr.findPattern("/articles/{slug}/{uid}/*") == false {
- t.Errorf("find /articles/{slug}/{uid}/* failed")
- }
-}
-
-func debugPrintTree(parent int, i int, n *node, label byte) bool {
- numEdges := 0
- for _, nds := range n.children {
- numEdges += len(nds)
- }
-
- // if n.handlers != nil {
- // log.Printf("[node %d parent:%d] typ:%d prefix:%s label:%s tail:%s numEdges:%d isLeaf:%v handler:%v pat:%s keys:%v\n", i, parent, n.typ, n.prefix, string(label), string(n.tail), numEdges, n.isLeaf(), n.handlers, n.pattern, n.paramKeys)
- // } else {
- // log.Printf("[node %d parent:%d] typ:%d prefix:%s label:%s tail:%s numEdges:%d isLeaf:%v pat:%s keys:%v\n", i, parent, n.typ, n.prefix, string(label), string(n.tail), numEdges, n.isLeaf(), n.pattern, n.paramKeys)
- // }
- if n.endpoints != nil {
- log.Printf("[node %d parent:%d] typ:%d prefix:%s label:%s tail:%s numEdges:%d isLeaf:%v handler:%v\n", i, parent, n.typ, n.prefix, string(label), string(n.tail), numEdges, n.isLeaf(), n.endpoints)
- } else {
- log.Printf("[node %d parent:%d] typ:%d prefix:%s label:%s tail:%s numEdges:%d isLeaf:%v\n", i, parent, n.typ, n.prefix, string(label), string(n.tail), numEdges, n.isLeaf())
- }
- parent = i
- for _, nds := range n.children {
- for _, e := range nds {
- i++
- if debugPrintTree(parent, i, e, e.label) {
- return true
- }
- }
- }
- return false
-}
-
-func stringSliceEqual(a, b []string) bool {
- if len(a) != len(b) {
- return false
- }
- for i := range a {
- if b[i] != a[i] {
- return false
- }
- }
- return true
-}
-
-func BenchmarkTreeGet(b *testing.B) {
- h1 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
- h2 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
-
- tr := &node{}
- tr.InsertRoute(mGET, "/", h1)
- tr.InsertRoute(mGET, "/ping", h2)
- tr.InsertRoute(mGET, "/pingall", h2)
- tr.InsertRoute(mGET, "/ping/{id}", h2)
- tr.InsertRoute(mGET, "/ping/{id}/woop", h2)
- tr.InsertRoute(mGET, "/ping/{id}/{opt}", h2)
- tr.InsertRoute(mGET, "/pinggggg", h2)
- tr.InsertRoute(mGET, "/hello", h1)
-
- mctx := NewRouteContext()
-
- b.ReportAllocs()
- b.ResetTimer()
-
- for i := 0; i < b.N; i++ {
- mctx.Reset()
- tr.FindRoute(mctx, mGET, "/ping/123/456")
- }
-}
-
-func TestWalker(t *testing.T) {
- r := bigMux()
-
- // Walk the muxBig router tree.
- if err := Walk(r, func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
- t.Logf("%v %v", method, route)
-
- return nil
- }); err != nil {
- t.Error(err)
- }
-}
diff --git a/vendor/github.com/go-chi/cors/README.md b/vendor/github.com/go-chi/cors/README.md
deleted file mode 100644
index 6e865be..0000000
--- a/vendor/github.com/go-chi/cors/README.md
+++ /dev/null
@@ -1,32 +0,0 @@
-# CORS net/http middleware
-
-(fork of github.com/rs/cors)
-
-## Usage
-
-```go
-func main() {
- r := chi.NewRouter()
-
- // Basic CORS
- // for more ideas, see: https://developer.github.com/v3/#cross-origin-resource-sharing
- cors := cors.New(cors.Options{
- // AllowedOrigins: []string{"https://foo.com"}, // Use this to allow specific origin hosts
- AllowedOrigins: []string{"*"},
- // AllowOriginFunc: func(r *http.Request, origin string) bool { return true },
- AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
- AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
- ExposedHeaders: []string{"Link"},
- AllowCredentials: true,
- MaxAge: 300, // Maximum value not ignored by any of major browsers
- })
- r.Use(cors.Handler)
-
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("welcome"))
- })
-
- http.ListenAndServe(":3000", r)
-}
-```
-
diff --git a/vendor/github.com/go-chi/cors/cors.go b/vendor/github.com/go-chi/cors/cors.go
deleted file mode 100644
index d85d86c..0000000
--- a/vendor/github.com/go-chi/cors/cors.go
+++ /dev/null
@@ -1,369 +0,0 @@
-// cors package is net/http handler to handle CORS related requests
-// as defined by http://www.w3.org/TR/cors/
-//
-// You can configure it by passing an option struct to cors.New:
-//
-// c := cors.New(cors.Options{
-// AllowedOrigins: []string{"foo.com"},
-// AllowedMethods: []string{"GET", "POST", "DELETE"},
-// AllowCredentials: true,
-// })
-//
-// Then insert the handler in the chain:
-//
-// handler = c.Handler(handler)
-//
-// See Options documentation for more options.
-//
-// The resulting handler is a standard net/http handler.
-package cors
-
-import (
- "log"
- "net/http"
- "os"
- "strconv"
- "strings"
-)
-
-// Options is a configuration container to setup the CORS middleware.
-type Options struct {
- // AllowedOrigins is a list of origins a cross-domain request can be executed from.
- // If the special "*" value is present in the list, all origins will be allowed.
- // An origin may contain a wildcard (*) to replace 0 or more characters
- // (i.e.: http://*.domain.com). Usage of wildcards implies a small performance penality.
- // Only one wildcard can be used per origin.
- // Default value is ["*"]
- AllowedOrigins []string
-
- // AllowOriginFunc is a custom function to validate the origin. It take the origin
- // as argument and returns true if allowed or false otherwise. If this option is
- // set, the content of AllowedOrigins is ignored.
- AllowOriginFunc func(r *http.Request, origin string) bool
-
- // AllowedMethods is a list of methods the client is allowed to use with
- // cross-domain requests. Default value is simple methods (GET and POST)
- AllowedMethods []string
-
- // AllowedHeaders is list of non simple headers the client is allowed to use with
- // cross-domain requests.
- // If the special "*" value is present in the list, all headers will be allowed.
- // Default value is [] but "Origin" is always appended to the list.
- AllowedHeaders []string
-
- // ExposedHeaders indicates which headers are safe to expose to the API of a CORS
- // API specification
- ExposedHeaders []string
-
- // AllowCredentials indicates whether the request can include user credentials like
- // cookies, HTTP authentication or client side SSL certificates.
- AllowCredentials bool
-
- // MaxAge indicates how long (in seconds) the results of a preflight request
- // can be cached
- MaxAge int
-
- // OptionsPassthrough instructs preflight to let other potential next handlers to
- // process the OPTIONS method. Turn this on if your application handles OPTIONS.
- OptionsPassthrough bool
-
- // Debugging flag adds additional output to debug server side CORS issues
- Debug bool
-}
-
-// Cors http handler
-type Cors struct {
- // Debug logger
- log *log.Logger
-
- // Set to true when allowed origins contains a "*"
- allowedOriginsAll bool
-
- // Normalized list of plain allowed origins
- allowedOrigins []string
-
- // List of allowed origins containing wildcards
- allowedWOrigins []wildcard
-
- // Optional origin validator function
- allowOriginFunc func(r *http.Request, origin string) bool
-
- // Set to true when allowed headers contains a "*"
- allowedHeadersAll bool
-
- // Normalized list of allowed headers
- allowedHeaders []string
-
- // Normalized list of allowed methods
- allowedMethods []string
-
- // Normalized list of exposed headers
- exposedHeaders []string
- allowCredentials bool
- maxAge int
- optionPassthrough bool
-}
-
-// New creates a new Cors handler with the provided options.
-func New(options Options) *Cors {
- c := &Cors{
- exposedHeaders: convert(options.ExposedHeaders, http.CanonicalHeaderKey),
- allowOriginFunc: options.AllowOriginFunc,
- allowCredentials: options.AllowCredentials,
- maxAge: options.MaxAge,
- optionPassthrough: options.OptionsPassthrough,
- }
- if options.Debug {
- c.log = log.New(os.Stdout, "[cors] ", log.LstdFlags)
- }
-
- // Normalize options
- // Note: for origins and methods matching, the spec requires a case-sensitive matching.
- // As it may error prone, we chose to ignore the spec here.
-
- // Allowed Origins
- if len(options.AllowedOrigins) == 0 {
- // Default is all origins
- c.allowedOriginsAll = true
- } else {
- c.allowedOrigins = []string{}
- c.allowedWOrigins = []wildcard{}
- for _, origin := range options.AllowedOrigins {
- // Normalize
- origin = strings.ToLower(origin)
- if origin == "*" {
- // If "*" is present in the list, turn the whole list into a match all
- c.allowedOriginsAll = true
- c.allowedOrigins = nil
- c.allowedWOrigins = nil
- break
- } else if i := strings.IndexByte(origin, '*'); i >= 0 {
- // Split the origin in two: start and end string without the *
- w := wildcard{origin[0:i], origin[i+1 : len(origin)]}
- c.allowedWOrigins = append(c.allowedWOrigins, w)
- } else {
- c.allowedOrigins = append(c.allowedOrigins, origin)
- }
- }
- }
-
- // Allowed Headers
- if len(options.AllowedHeaders) == 0 {
- // Use sensible defaults
- c.allowedHeaders = []string{"Origin", "Accept", "Content-Type"}
- } else {
- // Origin is always appended as some browsers will always request for this header at preflight
- c.allowedHeaders = convert(append(options.AllowedHeaders, "Origin"), http.CanonicalHeaderKey)
- for _, h := range options.AllowedHeaders {
- if h == "*" {
- c.allowedHeadersAll = true
- c.allowedHeaders = nil
- break
- }
- }
- }
-
- // Allowed Methods
- if len(options.AllowedMethods) == 0 {
- // Default is spec's "simple" methods
- c.allowedMethods = []string{"GET", "POST"}
- } else {
- c.allowedMethods = convert(options.AllowedMethods, strings.ToUpper)
- }
-
- return c
-}
-
-// Default creates a new Cors handler with default options
-func Default() *Cors {
- return New(Options{})
-}
-
-// Handler apply the CORS specification on the request, and add relevant CORS headers
-// as necessary.
-func (c *Cors) Handler(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.Method == "OPTIONS" {
- c.logf("Handler: Preflight request")
- c.handlePreflight(w, r)
- // Preflight requests are standalone and should stop the chain as some other
- // middleware may not handle OPTIONS requests correctly. One typical example
- // is authentication middleware ; OPTIONS requests won't carry authentication
- // headers (see #1)
- if c.optionPassthrough {
- next.ServeHTTP(w, r)
- }
- } else {
- c.logf("Handler: Actual request")
- c.handleActualRequest(w, r)
- next.ServeHTTP(w, r)
- }
- })
-}
-
-// handlePreflight handles pre-flight CORS requests
-func (c *Cors) handlePreflight(w http.ResponseWriter, r *http.Request) {
- headers := w.Header()
- origin := r.Header.Get("Origin")
-
- if r.Method != "OPTIONS" {
- c.logf("Preflight aborted: %s!=OPTIONS", r.Method)
- return
- }
- // Always set Vary headers
- // see https://github.com/rs/cors/issues/10,
- // https://github.com/rs/cors/commit/dbdca4d95feaa7511a46e6f1efb3b3aa505bc43f#commitcomment-12352001
- headers.Add("Vary", "Origin")
- headers.Add("Vary", "Access-Control-Request-Method")
- headers.Add("Vary", "Access-Control-Request-Headers")
-
- if origin == "" {
- c.logf("Preflight aborted: empty origin")
- return
- }
- if !c.isOriginAllowed(r, origin) {
- c.logf("Preflight aborted: origin '%s' not allowed", origin)
- return
- }
-
- reqMethod := r.Header.Get("Access-Control-Request-Method")
- if !c.isMethodAllowed(reqMethod) {
- c.logf("Preflight aborted: method '%s' not allowed", reqMethod)
- return
- }
- reqHeaders := parseHeaderList(r.Header.Get("Access-Control-Request-Headers"))
- if !c.areHeadersAllowed(reqHeaders) {
- c.logf("Preflight aborted: headers '%v' not allowed", reqHeaders)
- return
- }
- headers.Set("Access-Control-Allow-Origin", origin)
- // Spec says: Since the list of methods can be unbounded, simply returning the method indicated
- // by Access-Control-Request-Method (if supported) can be enough
- headers.Set("Access-Control-Allow-Methods", strings.ToUpper(reqMethod))
- if len(reqHeaders) > 0 {
-
- // Spec says: Since the list of headers can be unbounded, simply returning supported headers
- // from Access-Control-Request-Headers can be enough
- headers.Set("Access-Control-Allow-Headers", strings.Join(reqHeaders, ", "))
- }
- if c.allowCredentials {
- headers.Set("Access-Control-Allow-Credentials", "true")
- }
- if c.maxAge > 0 {
- headers.Set("Access-Control-Max-Age", strconv.Itoa(c.maxAge))
- }
- c.logf("Preflight response headers: %v", headers)
-}
-
-// handleActualRequest handles simple cross-origin requests, actual request or redirects
-func (c *Cors) handleActualRequest(w http.ResponseWriter, r *http.Request) {
- headers := w.Header()
- origin := r.Header.Get("Origin")
-
- if r.Method == "OPTIONS" {
- c.logf("Actual request no headers added: method == %s", r.Method)
- return
- }
- // Always set Vary, see https://github.com/rs/cors/issues/10
- headers.Add("Vary", "Origin")
- if origin == "" {
- c.logf("Actual request no headers added: missing origin")
- return
- }
- if !c.isOriginAllowed(r, origin) {
- c.logf("Actual request no headers added: origin '%s' not allowed", origin)
- return
- }
-
- // Note that spec does define a way to specifically disallow a simple method like GET or
- // POST. Access-Control-Allow-Methods is only used for pre-flight requests and the
- // spec doesn't instruct to check the allowed methods for simple cross-origin requests.
- // We think it's a nice feature to be able to have control on those methods though.
- if !c.isMethodAllowed(r.Method) {
- if c.log != nil {
- c.logf("Actual request no headers added: method '%s' not allowed",
- r.Method)
- }
-
- return
- }
- headers.Set("Access-Control-Allow-Origin", origin)
- if len(c.exposedHeaders) > 0 {
- headers.Set("Access-Control-Expose-Headers", strings.Join(c.exposedHeaders, ", "))
- }
- if c.allowCredentials {
- headers.Set("Access-Control-Allow-Credentials", "true")
- }
- c.logf("Actual response added headers: %v", headers)
-}
-
-// convenience method. checks if debugging is turned on before printing
-func (c *Cors) logf(format string, a ...interface{}) {
- if c.log != nil {
- c.log.Printf(format, a...)
- }
-}
-
-// isOriginAllowed checks if a given origin is allowed to perform cross-domain requests
-// on the endpoint
-func (c *Cors) isOriginAllowed(r *http.Request, origin string) bool {
- if c.allowOriginFunc != nil {
- return c.allowOriginFunc(r, origin)
- }
- if c.allowedOriginsAll {
- return true
- }
- origin = strings.ToLower(origin)
- for _, o := range c.allowedOrigins {
- if o == origin {
- return true
- }
- }
- for _, w := range c.allowedWOrigins {
- if w.match(origin) {
- return true
- }
- }
- return false
-}
-
-// isMethodAllowed checks if a given method can be used as part of a cross-domain request
-// on the endpoing
-func (c *Cors) isMethodAllowed(method string) bool {
- if len(c.allowedMethods) == 0 {
- // If no method allowed, always return false, even for preflight request
- return false
- }
- method = strings.ToUpper(method)
- if method == "OPTIONS" {
- // Always allow preflight requests
- return true
- }
- for _, m := range c.allowedMethods {
- if m == method {
- return true
- }
- }
- return false
-}
-
-// areHeadersAllowed checks if a given list of headers are allowed to used within
-// a cross-domain request.
-func (c *Cors) areHeadersAllowed(requestedHeaders []string) bool {
- if c.allowedHeadersAll || len(requestedHeaders) == 0 {
- return true
- }
- for _, header := range requestedHeaders {
- header = http.CanonicalHeaderKey(header)
- found := false
- for _, h := range c.allowedHeaders {
- if h == header {
- found = true
- }
- }
- if !found {
- return false
- }
- }
- return true
-}
diff --git a/vendor/github.com/go-chi/cors/utils.go b/vendor/github.com/go-chi/cors/utils.go
deleted file mode 100644
index cd24831..0000000
--- a/vendor/github.com/go-chi/cors/utils.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package cors
-
-import "strings"
-
-const toLower = 'a' - 'A'
-
-type converter func(string) string
-
-type wildcard struct {
- prefix string
- suffix string
-}
-
-func (w wildcard) match(s string) bool {
- return len(s) >= len(w.prefix+w.suffix) && strings.HasPrefix(s, w.prefix) && strings.HasSuffix(s, w.suffix)
-}
-
-// convert converts a list of string using the passed converter function
-func convert(s []string, c converter) []string {
- out := []string{}
- for _, i := range s {
- out = append(out, c(i))
- }
- return out
-}
-
-// parseHeaderList tokenize + normalize a string containing a list of headers
-func parseHeaderList(headerList string) []string {
- l := len(headerList)
- h := make([]byte, 0, l)
- upper := true
- // Estimate the number headers in order to allocate the right splice size
- t := 0
- for i := 0; i < l; i++ {
- if headerList[i] == ',' {
- t++
- }
- }
- headers := make([]string, 0, t)
- for i := 0; i < l; i++ {
- b := headerList[i]
- if b >= 'a' && b <= 'z' {
- if upper {
- h = append(h, b-toLower)
- } else {
- h = append(h, b)
- }
- } else if b >= 'A' && b <= 'Z' {
- if !upper {
- h = append(h, b+toLower)
- } else {
- h = append(h, b)
- }
- } else if b == '-' || (b >= '0' && b <= '9') {
- h = append(h, b)
- }
-
- if b == ' ' || b == ',' || i == l-1 {
- if len(h) > 0 {
- // Flush the found header
- headers = append(headers, string(h))
- h = h[:0]
- upper = true
- }
- } else {
- upper = b == '-'
- }
- }
- return headers
-}
diff --git a/vendor/github.com/go-chi/docgen/.travis.yml b/vendor/github.com/go-chi/docgen/.travis.yml
deleted file mode 100644
index a026204..0000000
--- a/vendor/github.com/go-chi/docgen/.travis.yml
+++ /dev/null
@@ -1,15 +0,0 @@
-language: go
-
-go:
- - 1.7.x
- - 1.8.x
- - tip
-
-install:
- - go get -u golang.org/x/tools/cmd/goimports
-
-script:
- - go get -d -t ./...
- - go test ./...
- - >
- goimports -d -e ./ | grep '.*' && { echo; echo "Aborting due to non-empty goimports output."; exit 1; } || :
diff --git a/vendor/github.com/go-chi/docgen/LICENSE b/vendor/github.com/go-chi/docgen/LICENSE
deleted file mode 100644
index 4344db7..0000000
--- a/vendor/github.com/go-chi/docgen/LICENSE
+++ /dev/null
@@ -1,20 +0,0 @@
-Copyright (c) 2016-Present https://github.com/go-chi authors
-
-MIT License
-
-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.
diff --git a/vendor/github.com/go-chi/docgen/builder.go b/vendor/github.com/go-chi/docgen/builder.go
deleted file mode 100644
index 7b396a3..0000000
--- a/vendor/github.com/go-chi/docgen/builder.go
+++ /dev/null
@@ -1,127 +0,0 @@
-package docgen
-
-import (
- "errors"
- "fmt"
- "net/http"
- "os"
- "path/filepath"
- "strings"
-
- "github.com/go-chi/chi"
-)
-
-func BuildDoc(r chi.Routes) (Doc, error) {
- d := Doc{}
-
- goPath := os.Getenv("GOPATH")
- if goPath == "" {
- return d, errors.New("docgen: unable to determine your $GOPATH")
- }
-
- // Walk and generate the router docs
- d.Router = buildDocRouter(r)
- return d, nil
-}
-
-func buildDocRouter(r chi.Routes) DocRouter {
- rts := r
- dr := DocRouter{Middlewares: []DocMiddleware{}}
- drts := DocRoutes{}
- dr.Routes = drts
-
- for _, mw := range rts.Middlewares() {
- dmw := DocMiddleware{
- FuncInfo: buildFuncInfo(mw),
- }
- dr.Middlewares = append(dr.Middlewares, dmw)
- }
-
- for _, rt := range rts.Routes() {
- drt := DocRoute{Pattern: rt.Pattern, Handlers: DocHandlers{}}
-
- if rt.SubRoutes != nil {
- subRoutes := rt.SubRoutes
- subDrts := buildDocRouter(subRoutes)
- drt.Router = &subDrts
-
- } else {
- hall := rt.Handlers["*"]
- for method, h := range rt.Handlers {
- if method != "*" && hall != nil && fmt.Sprintf("%v", hall) == fmt.Sprintf("%v", h) {
- continue
- }
-
- dh := DocHandler{Method: method, Middlewares: []DocMiddleware{}}
-
- var endpoint http.Handler
- chain, _ := h.(*chi.ChainHandler)
-
- if chain != nil {
- for _, mw := range chain.Middlewares {
- dh.Middlewares = append(dh.Middlewares, DocMiddleware{
- FuncInfo: buildFuncInfo(mw),
- })
- }
- endpoint = chain.Endpoint
- } else {
- endpoint = h
- }
-
- dh.FuncInfo = buildFuncInfo(endpoint)
-
- drt.Handlers[method] = dh
- }
- }
-
- drts[rt.Pattern] = drt
- }
-
- return dr
-}
-
-func buildFuncInfo(i interface{}) FuncInfo {
- fi := FuncInfo{}
- frame := getCallerFrame(i)
- goPathSrc := filepath.Join(os.Getenv("GOPATH"), "src")
-
- if frame == nil {
- fi.Unresolvable = true
- return fi
- }
-
- pkgName := getPkgName(frame.File)
- if pkgName == "chi" {
- fi.Unresolvable = true
- }
- funcPath := frame.Func.Name()
-
- idx := strings.Index(funcPath, "/"+pkgName)
- if idx > 0 {
- fi.Pkg = funcPath[:idx+1+len(pkgName)]
- fi.Func = funcPath[idx+2+len(pkgName):]
- } else {
- fi.Func = funcPath
- }
-
- if strings.Index(fi.Func, ".func") > 0 {
- fi.Anonymous = true
- }
-
- fi.File = frame.File
- fi.Line = frame.Line
- if filepath.HasPrefix(fi.File, goPathSrc) {
- fi.File = fi.File[len(goPathSrc)+1:]
- }
-
- // Check if file info is unresolvable
- if !strings.Contains(funcPath, pkgName) {
- fi.Unresolvable = true
- }
-
- if !fi.Unresolvable {
- fi.Comment = getFuncComment(frame.File, frame.Line)
- }
-
- return fi
-}
diff --git a/vendor/github.com/go-chi/docgen/docgen.go b/vendor/github.com/go-chi/docgen/docgen.go
deleted file mode 100644
index 66d5a36..0000000
--- a/vendor/github.com/go-chi/docgen/docgen.go
+++ /dev/null
@@ -1,64 +0,0 @@
-package docgen
-
-import (
- "encoding/json"
- "fmt"
-
- "github.com/go-chi/chi"
-)
-
-type Doc struct {
- Router DocRouter `json:"router"`
-}
-
-type DocRouter struct {
- Middlewares []DocMiddleware `json:"middlewares"`
- Routes DocRoutes `json:"routes"`
-}
-
-type DocMiddleware struct {
- FuncInfo
-}
-
-type DocRoute struct {
- Pattern string `json:"-"`
- Handlers DocHandlers `json:"handlers,omitempty"`
- Router *DocRouter `json:"router,omitempty"`
-}
-
-type DocRoutes map[string]DocRoute // Pattern : DocRoute
-
-type DocHandler struct {
- Middlewares []DocMiddleware `json:"middlewares"`
- Method string `json:"method"`
- FuncInfo
-}
-
-type DocHandlers map[string]DocHandler // Method : DocHandler
-
-func PrintRoutes(r chi.Routes) {
- var printRoutes func(parentPattern string, r chi.Routes)
- printRoutes = func(parentPattern string, r chi.Routes) {
- rts := r.Routes()
- for _, rt := range rts {
- if rt.SubRoutes == nil {
- fmt.Println(parentPattern + rt.Pattern)
- } else {
- pat := rt.Pattern
-
- subRoutes := rt.SubRoutes
- printRoutes(parentPattern+pat, subRoutes)
- }
- }
- }
- printRoutes("", r)
-}
-
-func JSONRoutesDoc(r chi.Routes) string {
- doc, _ := BuildDoc(r)
- v, err := json.MarshalIndent(doc, "", " ")
- if err != nil {
- panic(err)
- }
- return string(v)
-}
diff --git a/vendor/github.com/go-chi/docgen/docgen_test.go b/vendor/github.com/go-chi/docgen/docgen_test.go
deleted file mode 100644
index a7d2802..0000000
--- a/vendor/github.com/go-chi/docgen/docgen_test.go
+++ /dev/null
@@ -1,181 +0,0 @@
-package docgen_test
-
-import (
- "context"
- "fmt"
- "net/http"
- "testing"
-
- "github.com/go-chi/chi"
- "github.com/go-chi/docgen"
-)
-
-// RequestID comment goes here.
-func RequestID(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- ctx := context.WithValue(r.Context(), "requestID", "1")
- next.ServeHTTP(w, r.WithContext(ctx))
- })
-}
-
-func hubIndexHandler(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- s := fmt.Sprintf("/hubs/%s reqid:%s session:%s",
- chi.URLParam(r, "hubID"), ctx.Value("requestID"), ctx.Value("session.user"))
- w.Write([]byte(s))
-}
-
-// Generate docs for the MuxBig from chi/mux_test.go
-func TestMuxBig(t *testing.T) {
- var r, sr1, sr2, sr3, sr4, sr5, sr6 *chi.Mux
- r = chi.NewRouter()
- r.Use(RequestID)
-
- // Some inline middleware, 1
- // We just love Go's ast tools
- r.Use(func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- next.ServeHTTP(w, r)
- })
- })
- r.Group(func(r chi.Router) {
- r.Use(func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- ctx := context.WithValue(r.Context(), "session.user", "anonymous")
- next.ServeHTTP(w, r.WithContext(ctx))
- })
- })
- r.Get("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("fav"))
- })
- r.Get("/hubs/{hubID}/view", func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- s := fmt.Sprintf("/hubs/%s/view reqid:%s session:%s", chi.URLParam(r, "hubID"),
- ctx.Value("requestID"), ctx.Value("session.user"))
- w.Write([]byte(s))
- })
- r.Get("/hubs/{hubID}/view/*", func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- s := fmt.Sprintf("/hubs/%s/view/%s reqid:%s session:%s", chi.URLParamFromCtx(ctx, "hubID"),
- chi.URLParam(r, "*"), ctx.Value("requestID"), ctx.Value("session.user"))
- w.Write([]byte(s))
- })
- })
- r.Group(func(r chi.Router) {
- r.Use(func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- ctx := context.WithValue(r.Context(), "session.user", "elvis")
- next.ServeHTTP(w, r.WithContext(ctx))
- })
- })
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- s := fmt.Sprintf("/ reqid:%s session:%s", ctx.Value("requestID"), ctx.Value("session.user"))
- w.Write([]byte(s))
- })
- r.Get("/suggestions", func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- s := fmt.Sprintf("/suggestions reqid:%s session:%s", ctx.Value("requestID"), ctx.Value("session.user"))
- w.Write([]byte(s))
- })
-
- r.Get("/woot/{wootID}/*", func(w http.ResponseWriter, r *http.Request) {
- s := fmt.Sprintf("/woot/%s/%s", chi.URLParam(r, "wootID"), chi.URLParam(r, "*"))
- w.Write([]byte(s))
- })
-
- r.Route("/hubs", func(r chi.Router) {
- sr1 = r.(*chi.Mux)
- r.Use(func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- next.ServeHTTP(w, r)
- })
- })
- r.Route("/{hubID}", func(r chi.Router) {
- sr2 = r.(*chi.Mux)
- r.Get("/", hubIndexHandler)
- r.Get("/touch", func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- s := fmt.Sprintf("/hubs/%s/touch reqid:%s session:%s", chi.URLParam(r, "hubID"),
- ctx.Value("requestID"), ctx.Value("session.user"))
- w.Write([]byte(s))
- })
-
- sr3 = chi.NewRouter()
- sr3.Get("/", func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- s := fmt.Sprintf("/hubs/%s/webhooks reqid:%s session:%s", chi.URLParam(r, "hubID"),
- ctx.Value("requestID"), ctx.Value("session.user"))
- w.Write([]byte(s))
- })
- sr3.Route("/{webhookID}", func(r chi.Router) {
- sr4 = r.(*chi.Mux)
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- s := fmt.Sprintf("/hubs/%s/webhooks/%s reqid:%s session:%s", chi.URLParam(r, "hubID"),
- chi.URLParam(r, "webhookID"), ctx.Value("requestID"), ctx.Value("session.user"))
- w.Write([]byte(s))
- })
- })
-
- // TODO: /webooks is not coming up as a subrouter here...
- // we kind of want to wrap a Router... ?
- // perhaps add .Router() to the middleware inline thing..
- // and use that always.. or, can detect in that method..
- r.Mount("/webhooks", chi.Chain(func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), "hook", true)))
- })
- }).Handler(sr3))
-
- // HMMMM.. only let Mount() for just a Router..?
- // r.Mount("/webhooks", Use(...).Router(sr3))
- // ... could this work even....?
-
- // HMMMMMMMMMMMMMMMMMMMMMMMM...
- // even if Mount() were to record all subhandlers mounted, we still couldn't get at the
- // routes
-
- r.Route("/posts", func(r chi.Router) {
- sr5 = r.(*chi.Mux)
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- s := fmt.Sprintf("/hubs/%s/posts reqid:%s session:%s", chi.URLParam(r, "hubID"),
- ctx.Value("requestID"), ctx.Value("session.user"))
- w.Write([]byte(s))
- })
- })
- })
- })
-
- r.Route("/folders/", func(r chi.Router) {
- sr6 = r.(*chi.Mux)
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- s := fmt.Sprintf("/folders/ reqid:%s session:%s",
- ctx.Value("requestID"), ctx.Value("session.user"))
- w.Write([]byte(s))
- })
- r.Get("/public", func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- s := fmt.Sprintf("/folders/public reqid:%s session:%s",
- ctx.Value("requestID"), ctx.Value("session.user"))
- w.Write([]byte(s))
- })
- r.Get("/in", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}).ServeHTTP)
-
- r.With(func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), "search", true)))
- })
- }).Get("/search", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("searching.."))
- })
- })
- })
-
- fmt.Println(docgen.JSONRoutesDoc(r))
-
- // docgen.PrintRoutes(r)
-
-}
diff --git a/vendor/github.com/go-chi/docgen/funcinfo.go b/vendor/github.com/go-chi/docgen/funcinfo.go
deleted file mode 100644
index 66612da..0000000
--- a/vendor/github.com/go-chi/docgen/funcinfo.go
+++ /dev/null
@@ -1,113 +0,0 @@
-package docgen
-
-import (
- "go/parser"
- "go/token"
- "os"
- "path/filepath"
- "reflect"
- "runtime"
- "strings"
-)
-
-type FuncInfo struct {
- Pkg string `json:"pkg"`
- Func string `json:"func"`
- Comment string `json:"comment"`
- File string `json:"file,omitempty"`
- Line int `json:"line,omitempty"`
- Anonymous bool `json:"anonymous,omitempty"`
- Unresolvable bool `json:"unresolvable,omitempty"`
-}
-
-func GetFuncInfo(i interface{}) FuncInfo {
- fi := FuncInfo{}
- frame := getCallerFrame(i)
- goPathSrc := filepath.Join(os.Getenv("GOPATH"), "src")
-
- if frame == nil {
- fi.Unresolvable = true
- return fi
- }
-
- pkgName := getPkgName(frame.File)
- if pkgName == "chi" {
- fi.Unresolvable = true
- }
- funcPath := frame.Func.Name()
-
- idx := strings.Index(funcPath, "/"+pkgName)
- if idx > 0 {
- fi.Pkg = funcPath[:idx+1+len(pkgName)]
- fi.Func = funcPath[idx+2+len(pkgName):]
- } else {
- fi.Func = funcPath
- }
-
- if strings.Index(fi.Func, ".func") > 0 {
- fi.Anonymous = true
- }
-
- fi.File = frame.File
- fi.Line = frame.Line
- if filepath.HasPrefix(fi.File, goPathSrc) {
- fi.File = fi.File[len(goPathSrc)+1:]
- }
-
- // Check if file info is unresolvable
- if strings.Index(funcPath, pkgName) < 0 {
- fi.Unresolvable = true
- }
-
- if !fi.Unresolvable {
- fi.Comment = getFuncComment(frame.File, frame.Line)
- }
-
- return fi
-}
-
-func getCallerFrame(i interface{}) *runtime.Frame {
- pc := reflect.ValueOf(i).Pointer()
- frames := runtime.CallersFrames([]uintptr{pc})
- if frames == nil {
- return nil
- }
- frame, _ := frames.Next()
- if frame.Entry == 0 {
- return nil
- }
- return &frame
-}
-
-func getPkgName(file string) string {
- fset := token.NewFileSet()
- astFile, err := parser.ParseFile(fset, file, nil, parser.PackageClauseOnly)
- if err != nil {
- return ""
- }
- if astFile.Name == nil {
- return ""
- }
- return astFile.Name.Name
-}
-
-func getFuncComment(file string, line int) string {
- fset := token.NewFileSet()
-
- astFile, err := parser.ParseFile(fset, file, nil, parser.ParseComments)
- if err != nil {
- return ""
- }
-
- if len(astFile.Comments) == 0 {
- return ""
- }
-
- for _, cmt := range astFile.Comments {
- if fset.Position(cmt.End()).Line+1 == line {
- return cmt.Text()
- }
- }
-
- return ""
-}
diff --git a/vendor/github.com/go-chi/docgen/markdown.go b/vendor/github.com/go-chi/docgen/markdown.go
deleted file mode 100644
index ec4371e..0000000
--- a/vendor/github.com/go-chi/docgen/markdown.go
+++ /dev/null
@@ -1,211 +0,0 @@
-package docgen
-
-import (
- "bytes"
- "errors"
- "fmt"
- "sort"
- "strings"
-
- "github.com/go-chi/chi"
-)
-
-type MarkdownDoc struct {
- Opts MarkdownOpts
- Router chi.Router
- Doc Doc
- Routes map[string]DocRouter // Pattern : DocRouter
-
- buf *bytes.Buffer
-}
-
-type MarkdownOpts struct {
- // ProjectPath is the base Go import path of the project
- ProjectPath string
-
- // Intro text included at the top of the generated markdown file.
- Intro string
-
- // ForceRelativeLinks to be relative even if they're not on github
- ForceRelativeLinks bool
-
- // URLMap allows specifying a map of package import paths to their link sources
- // Used for mapping vendored dependencies to their upstream sources
- // For example:
- // map[string]string{"github.com/my/package/vendor/go-chi/chi/": "https://github.com/go-chi/chi/blob/master/"}
- URLMap map[string]string
-}
-
-func MarkdownRoutesDoc(r chi.Router, opts MarkdownOpts) string {
- md := &MarkdownDoc{Router: r, Opts: opts}
- if err := md.Generate(); err != nil {
- return fmt.Sprintf("ERROR: %s\n", err.Error())
- }
- return md.String()
-}
-
-func (md *MarkdownDoc) String() string {
- return md.buf.String()
-}
-
-func (md *MarkdownDoc) Generate() error {
- if md.Router == nil {
- return errors.New("docgen: router is nil")
- }
-
- doc, err := BuildDoc(md.Router)
- if err != nil {
- return err
- }
-
- md.Doc = doc
- md.buf = &bytes.Buffer{}
- md.Routes = make(map[string]DocRouter)
-
- md.WriteIntro()
- md.WriteRoutes()
-
- return nil
-}
-
-func (md *MarkdownDoc) WriteIntro() {
- pkgName := md.Opts.ProjectPath
- md.buf.WriteString(fmt.Sprintf("# %s\n\n", pkgName))
-
- intro := md.Opts.Intro
- md.buf.WriteString(fmt.Sprintf("%s\n\n", intro))
-}
-
-func (md *MarkdownDoc) WriteRoutes() {
- md.buf.WriteString(fmt.Sprintf("## Routes\n\n"))
-
- var buildRoutesMap func(parentPattern string, ar, nr, dr *DocRouter)
- buildRoutesMap = func(parentPattern string, ar, nr, dr *DocRouter) {
-
- nr.Middlewares = append(nr.Middlewares, dr.Middlewares...)
-
- for pat, rt := range dr.Routes {
- pattern := parentPattern + pat
-
- nr.Routes = DocRoutes{}
-
- if rt.Router != nil {
- nnr := &DocRouter{}
- nr.Routes[pat] = DocRoute{
- Pattern: pat,
- Handlers: rt.Handlers,
- Router: nnr,
- }
- buildRoutesMap(pattern, ar, nnr, rt.Router)
-
- } else if len(rt.Handlers) > 0 {
- nr.Routes[pat] = DocRoute{
- Pattern: pat,
- Handlers: rt.Handlers,
- Router: nil,
- }
-
- // Remove the trailing slash if the handler is a subroute for "/"
- routeKey := pattern
- if pat == "/" && len(routeKey) > 1 {
- routeKey = routeKey[:len(routeKey)-1]
- }
- md.Routes[routeKey] = copyDocRouter(*ar)
-
- } else {
- panic("not possible")
- }
- }
-
- }
-
- // Build a route tree that consists of the full route pattern
- // and the part of the tree for just that specific route, stored
- // in routes map on the markdown struct. This is the structure we
- // are going to render to markdown.
- dr := md.Doc.Router
- ar := DocRouter{}
- buildRoutesMap("", &ar, &ar, &dr)
-
- // Generate the markdown to render the above structure
- var printRouter func(depth int, dr DocRouter)
- printRouter = func(depth int, dr DocRouter) {
-
- tabs := ""
- for i := 0; i < depth; i++ {
- tabs += "\t"
- }
-
- // Middlewares
- for _, mw := range dr.Middlewares {
- md.buf.WriteString(fmt.Sprintf("%s- [%s](%s)\n", tabs, mw.Func, md.githubSourceURL(mw.File, mw.Line)))
- }
-
- // Routes
- for _, rt := range dr.Routes {
- md.buf.WriteString(fmt.Sprintf("%s- **%s**\n", tabs, rt.Pattern))
-
- if rt.Router != nil {
- printRouter(depth+1, *rt.Router)
- } else {
- for meth, dh := range rt.Handlers {
- md.buf.WriteString(fmt.Sprintf("%s\t- _%s_\n", tabs, meth))
-
- // Handler middlewares
- for _, mw := range dh.Middlewares {
- md.buf.WriteString(fmt.Sprintf("%s\t\t- [%s](%s)\n", tabs, mw.Func, md.githubSourceURL(mw.File, mw.Line)))
- }
-
- // Handler endpoint
- md.buf.WriteString(fmt.Sprintf("%s\t\t- [%s](%s)\n", tabs, dh.Func, md.githubSourceURL(dh.File, dh.Line)))
- }
- }
- }
- }
-
- routePaths := []string{}
- for pat := range md.Routes {
- routePaths = append(routePaths, pat)
- }
- sort.Strings(routePaths)
-
- for _, pat := range routePaths {
- dr := md.Routes[pat]
- md.buf.WriteString(fmt.Sprintf("\n"))
- md.buf.WriteString(fmt.Sprintf("`%s` \n", pat))
- md.buf.WriteString(fmt.Sprintf("\n"))
- printRouter(0, dr)
- md.buf.WriteString(fmt.Sprintf("\n"))
- md.buf.WriteString(fmt.Sprintf(" \n"))
- }
-
- md.buf.WriteString(fmt.Sprintf("\n"))
- md.buf.WriteString(fmt.Sprintf("Total # of routes: %d\n", len(md.Routes)))
-
- // TODO: total number of handlers..
-}
-
-func (md *MarkdownDoc) githubSourceURL(file string, line int) string {
- // Currently, we only automatically link to source for github projects
- if strings.Index(file, "github.com/") != 0 && !md.Opts.ForceRelativeLinks {
- return ""
- }
- if md.Opts.ProjectPath == "" {
- return ""
- }
- for pkg, url := range md.Opts.URLMap {
- if idx := strings.Index(file, pkg); idx >= 0 {
- pos := idx + len(pkg)
- url = strings.TrimRight(url, "/")
- filepath := strings.TrimLeft(file[pos:], "/")
- return fmt.Sprintf("%s/%s#L%d", url, filepath, line)
- }
- }
- if idx := strings.Index(file, md.Opts.ProjectPath); idx >= 0 {
- // relative
- pos := idx + len(md.Opts.ProjectPath)
- return fmt.Sprintf("%s#L%d", file[pos:], line)
- }
- // absolute
- return fmt.Sprintf("https://%s#L%d", file, line)
-}
diff --git a/vendor/github.com/go-chi/docgen/util.go b/vendor/github.com/go-chi/docgen/util.go
deleted file mode 100644
index 03a2758..0000000
--- a/vendor/github.com/go-chi/docgen/util.go
+++ /dev/null
@@ -1,37 +0,0 @@
-package docgen
-
-func copyDocRouter(dr DocRouter) DocRouter {
- var cloneRouter func(dr DocRouter) DocRouter
- var cloneRoutes func(drt DocRoutes) DocRoutes
-
- cloneRoutes = func(drts DocRoutes) DocRoutes {
- rts := DocRoutes{}
-
- for pat, drt := range drts {
- rt := DocRoute{Pattern: drt.Pattern}
- if len(drt.Handlers) > 0 {
- rt.Handlers = DocHandlers{}
- for meth, dh := range drt.Handlers {
- rt.Handlers[meth] = dh
- }
- }
- if drt.Router != nil {
- rr := cloneRouter(*drt.Router)
- rt.Router = &rr
- }
- rts[pat] = rt
- }
-
- return rts
- }
-
- cloneRouter = func(dr DocRouter) DocRouter {
- cr := DocRouter{}
- cr.Middlewares = make([]DocMiddleware, len(dr.Middlewares))
- copy(cr.Middlewares, dr.Middlewares)
- cr.Routes = cloneRoutes(dr.Routes)
- return cr
- }
-
- return cloneRouter(dr)
-}
diff --git a/vendor/github.com/go-chi/jwtauth/.gitignore b/vendor/github.com/go-chi/jwtauth/.gitignore
deleted file mode 100644
index 498781e..0000000
--- a/vendor/github.com/go-chi/jwtauth/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-vendor/
-Gopkg.lock
-.idea/
\ No newline at end of file
diff --git a/vendor/github.com/go-chi/jwtauth/.travis.yml b/vendor/github.com/go-chi/jwtauth/.travis.yml
deleted file mode 100644
index a026204..0000000
--- a/vendor/github.com/go-chi/jwtauth/.travis.yml
+++ /dev/null
@@ -1,15 +0,0 @@
-language: go
-
-go:
- - 1.7.x
- - 1.8.x
- - tip
-
-install:
- - go get -u golang.org/x/tools/cmd/goimports
-
-script:
- - go get -d -t ./...
- - go test ./...
- - >
- goimports -d -e ./ | grep '.*' && { echo; echo "Aborting due to non-empty goimports output."; exit 1; } || :
diff --git a/vendor/github.com/go-chi/jwtauth/Gopkg.toml b/vendor/github.com/go-chi/jwtauth/Gopkg.toml
deleted file mode 100644
index b495b7b..0000000
--- a/vendor/github.com/go-chi/jwtauth/Gopkg.toml
+++ /dev/null
@@ -1,6 +0,0 @@
-[[constraint]]
- name = "github.com/dgrijalva/jwt-go"
- version = "^3.1.0"
-[[constraint]]
- name = "github.com/go-chi/chi"
- version = "^3.0.0"
diff --git a/vendor/github.com/go-chi/jwtauth/LICENSE b/vendor/github.com/go-chi/jwtauth/LICENSE
deleted file mode 100644
index 767cb9d..0000000
--- a/vendor/github.com/go-chi/jwtauth/LICENSE
+++ /dev/null
@@ -1,20 +0,0 @@
-Copyright (c) 2015-Present https://github.com/go-chi authors
-
-MIT License
-
-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.
diff --git a/vendor/github.com/go-chi/jwtauth/README.md b/vendor/github.com/go-chi/jwtauth/README.md
deleted file mode 100644
index 3ce4b3d..0000000
--- a/vendor/github.com/go-chi/jwtauth/README.md
+++ /dev/null
@@ -1,115 +0,0 @@
-jwtauth - JWT authentication middleware for Go HTTP services
-============================================================
-[![GoDoc Widget]][GoDoc]
-
-The `jwtauth` http middleware package provides a simple way to verify a JWT token
-from a http request and send the result down the request context (`context.Context`).
-
-Please note, `jwtauth` works with any Go http router, but resides under the go-chi group
-for maintenance and organization - its only 3rd party dependency is the underlying jwt library
-"github.com/dgrijalva/jwt-go".
-
-This package uses the new `context` package in Go 1.7 stdlib and [net/http#Request.Context](https://golang.org/pkg/net/http/#Request.Context) to pass values between handler chains.
-
-In a complete JWT-authentication flow, you'll first capture the token from a http
-request, decode it, verify it and then validate that its correctly signed and hasn't
-expired - the `jwtauth.Verifier` middleware handler takes care of all of that. The
-`jwtauth.Verifier` will set the context values on keys `jwtauth.TokenCtxKey` and
-`jwtauth.ErrorCtxKey`.
-
-Next, it's up to an authentication handler to respond or continue processing after the
-`jwtauth.Verifier`. The `jwtauth.Authenticator` middleware responds with a 401 Unauthorized
-plain-text payload for all unverified tokens and passes the good ones through. You can
-also copy the Authenticator and customize it to handle invalid tokens to better fit
-your flow (ie. with a JSON error response body).
-
-By default, the `Verifier` will search for a JWT token in a http request, in the order:
-
-1. 'jwt' URI query parameter
-2. 'Authorization: BEARER T' request header
-3. 'jwt' Cookie value
-
-The first JWT string that is found as a query parameter, authorization header
-or cookie header is then decoded by the `jwt-go` library and a *jwt.Token
-object is set on the request context. In the case of a signature decoding error
-the Verifier will also set the error on the request context.
-
-The Verifier always calls the next http handler in sequence, which can either
-be the generic `jwtauth.Authenticator` middleware or your own custom handler
-which checks the request context jwt token and error to prepare a custom
-http response.
-
-Note: jwtauth supports custom verification sequences for finding a token
-from a request by using the `Verify` middleware instantiator directly. The default
-`Verifier` is instantiated by calling `Verify(ja, TokenFromQuery, TokenFromHeader, TokenFromCookie)`.
-
-
-# Usage
-
-See the full [example](https://github.com/go-chi/jwtauth/blob/master/_example/main.go).
-
-```go
-package main
-
-import (
- "fmt"
- "net/http"
-
- "github.com/go-chi/chi"
- "github.com/go-chi/jwtauth"
-)
-
-var tokenAuth *jwtauth.JwtAuth
-
-func init() {
- tokenAuth = jwtauth.New("HS256", []byte("secret"), nil)
-
- // For debugging/example purposes, we generate and print
- // a sample jwt token with claims `user_id:123` here:
- _, tokenString, _ := tokenAuth.Encode(jwtauth.Claims{"user_id": 123})
- fmt.Printf("DEBUG: a sample jwt is %s\n\n", tokenString)
-}
-
-func main() {
- addr := ":3333"
- fmt.Printf("Starting server on %v\n", addr)
- http.ListenAndServe(addr, router())
-}
-
-func router() http.Handler {
- r := chi.NewRouter()
-
- // Protected routes
- r.Group(func(r chi.Router) {
- // Seek, verify and validate JWT tokens
- r.Use(jwtauth.Verifier(tokenAuth))
-
- // Handle valid / invalid tokens. In this example, we use
- // the provided authenticator middleware, but you can write your
- // own very easily, look at the Authenticator method in jwtauth.go
- // and tweak it, its not scary.
- r.Use(jwtauth.Authenticator)
-
- r.Get("/admin", func(w http.ResponseWriter, r *http.Request) {
- _, claims, _ := jwtauth.FromContext(r.Context())
- w.Write([]byte(fmt.Sprintf("protected area. hi %v", claims["user_id"])))
- })
- })
-
- // Public routes
- r.Group(func(r chi.Router) {
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("welcome anonymous"))
- })
- })
-
- return r
-}
-```
-
-# LICENSE
-
-[MIT](/LICENSE)
-
-[GoDoc]: https://godoc.org/github.com/go-chi/jwtauth
-[GoDoc Widget]: https://godoc.org/github.com/go-chi/jwtauth?status.svg
diff --git a/vendor/github.com/go-chi/jwtauth/jwtauth.go b/vendor/github.com/go-chi/jwtauth/jwtauth.go
deleted file mode 100644
index 57aa592..0000000
--- a/vendor/github.com/go-chi/jwtauth/jwtauth.go
+++ /dev/null
@@ -1,322 +0,0 @@
-package jwtauth
-
-import (
- "context"
- "encoding/json"
- "errors"
- "net/http"
- "strings"
- "time"
-
- "github.com/dgrijalva/jwt-go"
-)
-
-var (
- TokenCtxKey = &contextKey{"Token"}
- ErrorCtxKey = &contextKey{"Error"}
-)
-
-var (
- ErrUnauthorized = errors.New("jwtauth: token is unauthorized")
- ErrExpired = errors.New("jwtauth: token is expired")
-)
-
-var (
- // TokenFromCookie tries to retreive the token string from a cookie named
- // "jwt".
- TokenFromCookie = func(r *http.Request) string {
- cookie, err := r.Cookie("jwt")
- if err != nil {
- return ""
- }
- return cookie.Value
- }
- // TokenFromHeader tries to retreive the token string from the
- // "Authorization" reqeust header: "Authorization: BEARER T".
- TokenFromHeader = func(r *http.Request) string {
- // Get token from authorization header.
- bearer := r.Header.Get("Authorization")
- if len(bearer) > 7 && strings.ToUpper(bearer[0:6]) == "BEARER" {
- return bearer[7:]
- }
- return ""
- }
- // TokenFromQuery tries to retreive the token string from the "jwt" URI
- // query parameter.
- TokenFromQuery = func(r *http.Request) string {
- // Get token from query param named "jwt".
- return r.URL.Query().Get("jwt")
- }
-)
-
-type JwtAuth struct {
- signKey interface{}
- verifyKey interface{}
- signer jwt.SigningMethod
- parser *jwt.Parser
-}
-
-// New creates a JwtAuth authenticator instance that provides middleware handlers
-// and encoding/decoding functions for JWT signing.
-func New(alg string, signKey interface{}, verifyKey interface{}) *JwtAuth {
- return NewWithParser(alg, &jwt.Parser{}, signKey, verifyKey)
-}
-
-// NewWithParser is the same as New, except it supports custom parser settings
-// introduced in jwt-go/v2.4.0.
-//
-// We explicitly toggle `SkipClaimsValidation` in the `jwt-go` parser so that
-// we can control when the claims are validated - in our case, by the Verifier
-// http middleware handler.
-func NewWithParser(alg string, parser *jwt.Parser, signKey interface{}, verifyKey interface{}) *JwtAuth {
- parser.SkipClaimsValidation = true
- return &JwtAuth{
- signKey: signKey,
- verifyKey: verifyKey,
- signer: jwt.GetSigningMethod(alg),
- parser: parser,
- }
-}
-
-// Verifier http middleware handler will verify a JWT string from a http request.
-//
-// Verifier will search for a JWT token in a http request, in the order:
-// 1. 'jwt' URI query parameter
-// 2. 'Authorization: BEARER T' request header
-// 3. Cookie 'jwt' value
-//
-// The first JWT string that is found as a query parameter, authorization header
-// or cookie header is then decoded by the `jwt-go` library and a *jwt.Token
-// object is set on the request context. In the case of a signature decoding error
-// the Verifier will also set the error on the request context.
-//
-// The Verifier always calls the next http handler in sequence, which can either
-// be the generic `jwtauth.Authenticator` middleware or your own custom handler
-// which checks the request context jwt token and error to prepare a custom
-// http response.
-func Verifier(ja *JwtAuth) func(http.Handler) http.Handler {
- return func(next http.Handler) http.Handler {
- return Verify(ja, TokenFromQuery, TokenFromHeader, TokenFromCookie)(next)
- }
-}
-
-func Verify(ja *JwtAuth, findTokenFns ...func(r *http.Request) string) func(http.Handler) http.Handler {
- return func(next http.Handler) http.Handler {
- hfn := func(w http.ResponseWriter, r *http.Request) {
- ctx := r.Context()
- token, err := VerifyRequest(ja, r, findTokenFns...)
- ctx = NewContext(ctx, token, err)
- next.ServeHTTP(w, r.WithContext(ctx))
- }
- return http.HandlerFunc(hfn)
- }
-}
-
-func VerifyRequest(ja *JwtAuth, r *http.Request, findTokenFns ...func(r *http.Request) string) (*jwt.Token, error) {
- var tokenStr string
- var err error
-
- // Extract token string from the request by calling token find functions in
- // the order they where provided. Further extraction stops if a function
- // returns a non-empty string.
- for _, fn := range findTokenFns {
- tokenStr = fn(r)
- if tokenStr != "" {
- break
- }
- }
-
- // TODO: what other kinds of validations should we do / error messages?
-
- // Verify the token
- token, err := ja.Decode(tokenStr)
- if err != nil {
- switch err.Error() {
- case "token is expired":
- err = ErrExpired
- }
- return token, err
- }
-
- if token == nil || !token.Valid || token.Method != ja.signer {
- err = ErrUnauthorized
- return token, err
- }
-
- // Check expiry via "exp" claim
- if IsExpired(token) {
- err = ErrExpired
- return token, err
- }
-
- // Valid!
- return token, nil
-}
-
-func (ja *JwtAuth) Encode(claims Claims) (t *jwt.Token, tokenString string, err error) {
- t = jwt.New(ja.signer)
- t.Claims = claims
- tokenString, err = t.SignedString(ja.signKey)
- t.Raw = tokenString
- return
-}
-
-func (ja *JwtAuth) Decode(tokenString string) (t *jwt.Token, err error) {
- // Decode the tokenString, but avoid using custom Claims via jwt-go's
- // ParseWithClaims as the jwt-go types will cause some glitches, so easier
- // to decode as MapClaims then wrap the underlying map[string]interface{}
- // to our Claims type
- t, err = ja.parser.Parse(tokenString, ja.keyFunc)
- if err != nil {
- return nil, err
- }
- return
-}
-
-func (ja *JwtAuth) keyFunc(t *jwt.Token) (interface{}, error) {
- if ja.verifyKey != nil {
- return ja.verifyKey, nil
- } else {
- return ja.signKey, nil
- }
-}
-
-// Authenticator is a default authentication middleware to enforce access from the
-// Verifier middleware request context values. The Authenticator sends a 401 Unauthorized
-// response for any unverified tokens and passes the good ones through. It's just fine
-// until you decide to write something similar and customize your client response.
-func Authenticator(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- token, _, err := FromContext(r.Context())
-
- if err != nil {
- http.Error(w, http.StatusText(401), 401)
- return
- }
-
- if token == nil || !token.Valid {
- http.Error(w, http.StatusText(401), 401)
- return
- }
-
- // Token is authenticated, pass it through
- next.ServeHTTP(w, r)
- })
-}
-
-func NewContext(ctx context.Context, t *jwt.Token, err error) context.Context {
- ctx = context.WithValue(ctx, TokenCtxKey, t)
- ctx = context.WithValue(ctx, ErrorCtxKey, err)
- return ctx
-}
-
-func FromContext(ctx context.Context) (*jwt.Token, Claims, error) {
- token, _ := ctx.Value(TokenCtxKey).(*jwt.Token)
-
- var claims Claims
- if token != nil {
- tokenClaims, ok := token.Claims.(jwt.MapClaims)
- if !ok {
- panic("jwtauth: expecting jwt.MapClaims")
- }
- claims = Claims(tokenClaims)
- } else {
- claims = Claims{}
- }
-
- err, _ := ctx.Value(ErrorCtxKey).(error)
-
- return token, claims, err
-}
-
-func IsExpired(t *jwt.Token) bool {
- claims, ok := t.Claims.(jwt.MapClaims)
- if !ok {
- panic("jwtauth: expecting jwt.MapClaims")
- }
-
- if expv, ok := claims["exp"]; ok {
- var exp int64
- switch v := expv.(type) {
- case float64:
- exp = int64(v)
- case int64:
- exp = v
- case json.Number:
- exp, _ = v.Int64()
- default:
- }
-
- if exp < EpochNow() {
- return true
- }
- }
-
- return false
-}
-
-// Claims is a convenience type to manage a JWT claims hash.
-type Claims map[string]interface{}
-
-// NOTE: as of v3.0 of jwt-go, Valid() interface method is called to verify
-// the claims. However, the current design we test these claims in the
-// Verifier middleware, so we skip this step.
-func (c Claims) Valid() error {
- return nil
-}
-
-func (c Claims) Set(k string, v interface{}) Claims {
- c[k] = v
- return c
-}
-
-func (c Claims) Get(k string) (interface{}, bool) {
- v, ok := c[k]
- return v, ok
-}
-
-// Set issued at ("iat") to specified time in the claims
-func (c Claims) SetIssuedAt(tm time.Time) Claims {
- c["iat"] = tm.UTC().Unix()
- return c
-}
-
-// Set issued at ("iat") to present time in the claims
-func (c Claims) SetIssuedNow() Claims {
- c["iat"] = EpochNow()
- return c
-}
-
-// Set expiry ("exp") in the claims and return itself so it can be chained
-func (c Claims) SetExpiry(tm time.Time) Claims {
- c["exp"] = tm.UTC().Unix()
- return c
-}
-
-// Set expiry ("exp") in the claims to some duration from the present time
-// and return itself so it can be chained
-func (c Claims) SetExpiryIn(tm time.Duration) Claims {
- c["exp"] = ExpireIn(tm)
- return c
-}
-
-// Helper function that returns the NumericDate time value used by the spec
-func EpochNow() int64 {
- return time.Now().UTC().Unix()
-}
-
-// Helper function to return calculated time in the future for "exp" claim.
-func ExpireIn(tm time.Duration) int64 {
- return EpochNow() + int64(tm.Seconds())
-}
-
-// contextKey is a value for use with context.WithValue. It's used as
-// a pointer so it fits in an interface{} without allocation. This technique
-// for defining context keys was copied from Go 1.7's new use of context in net/http.
-type contextKey struct {
- name string
-}
-
-func (k *contextKey) String() string {
- return "jwtauth context value " + k.name
-}
diff --git a/vendor/github.com/go-chi/jwtauth/jwtauth_test.go b/vendor/github.com/go-chi/jwtauth/jwtauth_test.go
deleted file mode 100644
index 094d722..0000000
--- a/vendor/github.com/go-chi/jwtauth/jwtauth_test.go
+++ /dev/null
@@ -1,301 +0,0 @@
-package jwtauth_test
-
-import (
- "crypto/x509"
- "encoding/pem"
- "fmt"
- "io"
- "io/ioutil"
- "log"
- "net/http"
- "net/http/httptest"
- "reflect"
- "testing"
- "time"
-
- "github.com/dgrijalva/jwt-go"
- "github.com/go-chi/chi"
- "github.com/go-chi/jwtauth"
-)
-
-var (
- TokenAuthHS256 *jwtauth.JwtAuth
- TokenSecret = []byte("secretpass")
-
- TokenAuthRS256 *jwtauth.JwtAuth
-
- PrivateKeyRS256String = `-----BEGIN RSA PRIVATE KEY-----
-MIIBOwIBAAJBALxo3PCjFw4QjgOX06QCJIJBnXXNiEYwDLxxa5/7QyH6y77nCRQy
-J3x3UwF9rUD0RCsp4sNdX5kOQ9PUyHyOtCUCAwEAAQJARjFLHtuj2zmPrwcBcjja
-IS0Q3LKV8pA0LoCS+CdD+4QwCxeKFq0yEMZtMvcQOfqo9x9oAywFClMSlLRyl7ng
-gQIhAOyerGbcdQxxwjwGpLS61Mprf4n2HzjwISg20cEEH1tfAiEAy9dXmgQpDPir
-C6Q9QdLXpNgSB+o5CDqfor7TTyTCovsCIQDNCfpu795luDYN+dvD2JoIBfrwu9v2
-ZO72f/pm/YGGlQIgUdRXyW9kH13wJFNBeBwxD27iBiVj0cbe8NFUONBUBmMCIQCN
-jVK4eujt1lm/m60TlEhaWBC3p+3aPT2TqFPUigJ3RQ==
------END RSA PRIVATE KEY-----
-`
-
- PublicKeyRS256String = `-----BEGIN PUBLIC KEY-----
-MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALxo3PCjFw4QjgOX06QCJIJBnXXNiEYw
-DLxxa5/7QyH6y77nCRQyJ3x3UwF9rUD0RCsp4sNdX5kOQ9PUyHyOtCUCAwEAAQ==
------END PUBLIC KEY-----
-`
-)
-
-func init() {
- TokenAuthHS256 = jwtauth.New("HS256", TokenSecret, nil)
-}
-
-//
-// Tests
-//
-
-func TestSimpleRSA(t *testing.T) {
- privateKeyBlock, _ := pem.Decode([]byte(PrivateKeyRS256String))
-
- privateKey, err := x509.ParsePKCS1PrivateKey(privateKeyBlock.Bytes)
-
- if err != nil {
- t.Fatalf(err.Error())
- }
-
- publicKeyBlock, _ := pem.Decode([]byte(PublicKeyRS256String))
-
- publicKey, err := x509.ParsePKIXPublicKey(publicKeyBlock.Bytes)
-
- if err != nil {
- t.Fatalf(err.Error())
- }
-
- TokenAuthRS256 = jwtauth.New("RS256", privateKey, publicKey)
-
- claims := jwtauth.Claims{
- "key": "val",
- "key2": "val2",
- "key3": "val3",
- }
-
- _, tokenString, err := TokenAuthRS256.Encode(claims)
-
- if err != nil {
- t.Fatalf("Failed to encode claims %s\n", err.Error())
- }
-
- token, err := TokenAuthRS256.Decode(tokenString)
-
- if err != nil {
- t.Fatalf("Failed to decode token string %s\n", err.Error())
- }
-
- if !reflect.DeepEqual(claims, jwtauth.Claims(token.Claims.(jwt.MapClaims))) {
- t.Fatalf("The decoded claims don't match the original ones\n")
- }
-}
-
-func TestSimple(t *testing.T) {
- r := chi.NewRouter()
-
- r.Use(jwtauth.Verifier(TokenAuthHS256), jwtauth.Authenticator)
-
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("welcome"))
- })
-
- ts := httptest.NewServer(r)
- defer ts.Close()
-
- // sending unauthorized requests
- if status, resp := testRequest(t, ts, "GET", "/", nil, nil); status != 401 || resp != "Unauthorized\n" {
- t.Fatalf(resp)
- }
-
- h := http.Header{}
- h.Set("Authorization", "BEARER "+newJwtToken([]byte("wrong"), map[string]interface{}{}))
- if status, resp := testRequest(t, ts, "GET", "/", h, nil); status != 401 || resp != "Unauthorized\n" {
- t.Fatalf(resp)
- }
- h.Set("Authorization", "BEARER asdf")
- if status, resp := testRequest(t, ts, "GET", "/", h, nil); status != 401 || resp != "Unauthorized\n" {
- t.Fatalf(resp)
- }
- // wrong token secret and wrong alg
- h.Set("Authorization", "BEARER "+newJwt512Token([]byte("wrong"), map[string]interface{}{}))
- if status, resp := testRequest(t, ts, "GET", "/", h, nil); status != 401 || resp != "Unauthorized\n" {
- t.Fatalf(resp)
- }
- // correct token secret but wrong alg
- h.Set("Authorization", "BEARER "+newJwt512Token(TokenSecret, map[string]interface{}{}))
- if status, resp := testRequest(t, ts, "GET", "/", h, nil); status != 401 || resp != "Unauthorized\n" {
- t.Fatalf(resp)
- }
-
- // sending authorized requests
- if status, resp := testRequest(t, ts, "GET", "/", newAuthHeader(), nil); status != 200 || resp != "welcome" {
- t.Fatalf(resp)
- }
-}
-
-func TestMore(t *testing.T) {
- r := chi.NewRouter()
-
- // Protected routes
- r.Group(func(r chi.Router) {
- r.Use(jwtauth.Verifier(TokenAuthHS256))
-
- authenticator := func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- token, _, err := jwtauth.FromContext(r.Context())
-
- if err != nil {
- switch err {
- default:
- http.Error(w, http.StatusText(401), 401)
- return
- case jwtauth.ErrExpired:
- http.Error(w, "expired", 401)
- return
- case jwtauth.ErrUnauthorized:
- http.Error(w, http.StatusText(401), 401)
- return
- case nil:
- // no error
- }
- }
-
- if token == nil || !token.Valid {
- http.Error(w, http.StatusText(401), 401)
- return
- }
-
- // Token is authenticated, pass it through
- next.ServeHTTP(w, r)
- })
- }
- r.Use(authenticator)
-
- r.Get("/admin", func(w http.ResponseWriter, r *http.Request) {
- _, claims, err := jwtauth.FromContext(r.Context())
-
- if err != nil {
- w.Write([]byte(fmt.Sprintf("error! %v", err)))
- return
- }
-
- w.Write([]byte(fmt.Sprintf("protected, user:%v", claims["user_id"])))
- })
- })
-
- // Public routes
- r.Group(func(r chi.Router) {
- r.Get("/", func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("welcome"))
- })
- })
-
- ts := httptest.NewServer(r)
- defer ts.Close()
-
- // sending unauthorized requests
- if status, resp := testRequest(t, ts, "GET", "/admin", nil, nil); status != 401 || resp != "Unauthorized\n" {
- t.Fatalf(resp)
- }
-
- h := http.Header{}
- h.Set("Authorization", "BEARER "+newJwtToken([]byte("wrong"), map[string]interface{}{}))
- if status, resp := testRequest(t, ts, "GET", "/admin", h, nil); status != 401 || resp != "Unauthorized\n" {
- t.Fatalf(resp)
- }
- h.Set("Authorization", "BEARER asdf")
- if status, resp := testRequest(t, ts, "GET", "/admin", h, nil); status != 401 || resp != "Unauthorized\n" {
- t.Fatalf(resp)
- }
- // wrong token secret and wrong alg
- h.Set("Authorization", "BEARER "+newJwt512Token([]byte("wrong"), map[string]interface{}{}))
- if status, resp := testRequest(t, ts, "GET", "/admin", h, nil); status != 401 || resp != "Unauthorized\n" {
- t.Fatalf(resp)
- }
- // correct token secret but wrong alg
- h.Set("Authorization", "BEARER "+newJwt512Token(TokenSecret, map[string]interface{}{}))
- if status, resp := testRequest(t, ts, "GET", "/admin", h, nil); status != 401 || resp != "Unauthorized\n" {
- t.Fatalf(resp)
- }
-
- h = newAuthHeader((jwtauth.Claims{}).Set("exp", jwtauth.EpochNow()-1000))
- if status, resp := testRequest(t, ts, "GET", "/admin", h, nil); status != 401 || resp != "expired\n" {
- t.Fatalf(resp)
- }
-
- // sending authorized requests
- if status, resp := testRequest(t, ts, "GET", "/", nil, nil); status != 200 || resp != "welcome" {
- t.Fatalf(resp)
- }
-
- h = newAuthHeader((jwtauth.Claims{"user_id": 31337}).SetExpiryIn(5 * time.Minute))
- if status, resp := testRequest(t, ts, "GET", "/admin", h, nil); status != 200 || resp != "protected, user:31337" {
- t.Fatalf(resp)
- }
-}
-
-//
-// Test helper functions
-//
-
-func testRequest(t *testing.T, ts *httptest.Server, method, path string, header http.Header, body io.Reader) (int, string) {
- req, err := http.NewRequest(method, ts.URL+path, body)
- if err != nil {
- t.Fatal(err)
- return 0, ""
- }
-
- if header != nil {
- for k, v := range header {
- req.Header.Set(k, v[0])
- }
- }
-
- resp, err := http.DefaultClient.Do(req)
- if err != nil {
- t.Fatal(err)
- return 0, ""
- }
-
- respBody, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- t.Fatal(err)
- return 0, ""
- }
- defer resp.Body.Close()
-
- return resp.StatusCode, string(respBody)
-}
-
-func newJwtToken(secret []byte, claims ...jwtauth.Claims) string {
- token := jwt.New(jwt.GetSigningMethod("HS256"))
- if len(claims) > 0 {
- token.Claims = claims[0]
- }
- tokenStr, err := token.SignedString(secret)
- if err != nil {
- log.Fatal(err)
- }
- return tokenStr
-}
-
-func newJwt512Token(secret []byte, claims ...jwtauth.Claims) string {
- // use-case: when token is signed with a different alg than expected
- token := jwt.New(jwt.GetSigningMethod("HS512"))
- if len(claims) > 0 {
- token.Claims = claims[0]
- }
- tokenStr, err := token.SignedString(secret)
- if err != nil {
- log.Fatal(err)
- }
- return tokenStr
-}
-
-func newAuthHeader(claims ...jwtauth.Claims) http.Header {
- h := http.Header{}
- h.Set("Authorization", "BEARER "+newJwtToken(TokenSecret, claims...))
- return h
-}
diff --git a/vendor/github.com/go-chi/render/.travis.yml b/vendor/github.com/go-chi/render/.travis.yml
deleted file mode 100644
index a026204..0000000
--- a/vendor/github.com/go-chi/render/.travis.yml
+++ /dev/null
@@ -1,15 +0,0 @@
-language: go
-
-go:
- - 1.7.x
- - 1.8.x
- - tip
-
-install:
- - go get -u golang.org/x/tools/cmd/goimports
-
-script:
- - go get -d -t ./...
- - go test ./...
- - >
- goimports -d -e ./ | grep '.*' && { echo; echo "Aborting due to non-empty goimports output."; exit 1; } || :
diff --git a/vendor/github.com/go-chi/render/LICENSE b/vendor/github.com/go-chi/render/LICENSE
deleted file mode 100644
index 4344db7..0000000
--- a/vendor/github.com/go-chi/render/LICENSE
+++ /dev/null
@@ -1,20 +0,0 @@
-Copyright (c) 2016-Present https://github.com/go-chi authors
-
-MIT License
-
-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.
diff --git a/vendor/github.com/go-chi/render/README.md b/vendor/github.com/go-chi/render/README.md
deleted file mode 100644
index 068e0bf..0000000
--- a/vendor/github.com/go-chi/render/README.md
+++ /dev/null
@@ -1,24 +0,0 @@
-# render
-
-The `render` package helps manage HTTP request / response payloads.
-
-Every well-designed, robust and maintainable Web Service / REST API also needs
-well-*defined* request and response payloads. Together with the endpoint handlers,
-the request and response payloads make up the contract between your server and the
-clients calling on it.
-
-Typically in a REST API application, you will have your data models (objects/structs)
-that hold lower-level runtime application state, and at times you need to assemble,
-decorate, hide or transform the representation before responding to a client. That
-server output (response payload) structure, is also likely the input structure to
-another handler on the server.
-
-This is where `render` comes in - offering a few simple helpers and interfaces to
-provide a simple pattern for managing payload encoding and decoding.
-
-We've also combined it with some helpers for responding to content types and parsing
-request bodies. Please have a look at the [rest](https://github.com/go-chi/chi/blob/master/_examples/rest/main.go)
-example which uses the latest chi/render sub-pkg.
-
-All feedback is welcome, thank you!
-
diff --git a/vendor/github.com/go-chi/render/content_type.go b/vendor/github.com/go-chi/render/content_type.go
deleted file mode 100644
index f2bbb42..0000000
--- a/vendor/github.com/go-chi/render/content_type.go
+++ /dev/null
@@ -1,84 +0,0 @@
-package render
-
-import (
- "context"
- "net/http"
- "strings"
-)
-
-var (
- ContentTypeCtxKey = &contextKey{"ContentType"}
-)
-
-// ContentType is an enumeration of common HTTP content types.
-type ContentType int
-
-// ContentTypes handled by this package.
-const (
- ContentTypeUnknown = iota
- ContentTypePlainText
- ContentTypeHTML
- ContentTypeJSON
- ContentTypeXML
- ContentTypeForm
- ContentTypeEventStream
-)
-
-func GetContentType(s string) ContentType {
- s = strings.TrimSpace(strings.Split(s, ";")[0])
- switch s {
- case "text/plain":
- return ContentTypePlainText
- case "text/html", "application/xhtml+xml":
- return ContentTypeHTML
- case "application/json", "text/javascript":
- return ContentTypeJSON
- case "text/xml", "application/xml":
- return ContentTypeXML
- case "application/x-www-form-urlencoded":
- return ContentTypeForm
- case "text/event-stream":
- return ContentTypeEventStream
- default:
- return ContentTypeUnknown
- }
-}
-
-// SetContentType is a middleware that forces response Content-Type.
-func SetContentType(contentType ContentType) func(next http.Handler) http.Handler {
- return func(next http.Handler) http.Handler {
- fn := func(w http.ResponseWriter, r *http.Request) {
- r = r.WithContext(context.WithValue(r.Context(), ContentTypeCtxKey, contentType))
- next.ServeHTTP(w, r)
- }
- return http.HandlerFunc(fn)
- }
-}
-
-// GetRequestContentType is a helper function that returns ContentType based on
-// context or request headers.
-func GetRequestContentType(r *http.Request) ContentType {
- if contentType, ok := r.Context().Value(ContentTypeCtxKey).(ContentType); ok {
- return contentType
- }
- return GetContentType(r.Header.Get("Content-Type"))
-}
-
-func GetAcceptedContentType(r *http.Request) ContentType {
- if contentType, ok := r.Context().Value(ContentTypeCtxKey).(ContentType); ok {
- return contentType
- }
-
- var contentType ContentType
-
- // Parse request Accept header.
- fields := strings.Split(r.Header.Get("Accept"), ",")
- if len(fields) > 0 {
- contentType = GetContentType(strings.TrimSpace(fields[0]))
- }
-
- if contentType == ContentTypeUnknown {
- contentType = ContentTypePlainText
- }
- return contentType
-}
diff --git a/vendor/github.com/go-chi/render/decoder.go b/vendor/github.com/go-chi/render/decoder.go
deleted file mode 100644
index 849c56b..0000000
--- a/vendor/github.com/go-chi/render/decoder.go
+++ /dev/null
@@ -1,44 +0,0 @@
-package render
-
-import (
- "encoding/json"
- "encoding/xml"
- "errors"
- "io"
- "io/ioutil"
- "net/http"
-)
-
-// Decode is a package-level variable set to our default Decoder. We do this
-// because it allows you to set render.Decode to another function with the
-// same function signature, while also utilizing the render.Decoder() function
-// itself. Effectively, allowing you to easily add your own logic to the package
-// defaults. For example, maybe you want to impose a limit on the number of
-// bytes allowed to be read from the request body.
-var Decode = DefaultDecoder
-
-func DefaultDecoder(r *http.Request, v interface{}) error {
- var err error
-
- switch GetRequestContentType(r) {
- case ContentTypeJSON:
- err = DecodeJSON(r.Body, v)
- case ContentTypeXML:
- err = DecodeXML(r.Body, v)
- // case ContentTypeForm: // TODO
- default:
- err = errors.New("render: unable to automatically decode the request content type")
- }
-
- return err
-}
-
-func DecodeJSON(r io.Reader, v interface{}) error {
- defer io.Copy(ioutil.Discard, r)
- return json.NewDecoder(r).Decode(v)
-}
-
-func DecodeXML(r io.Reader, v interface{}) error {
- defer io.Copy(ioutil.Discard, r)
- return xml.NewDecoder(r).Decode(v)
-}
diff --git a/vendor/github.com/go-chi/render/render.go b/vendor/github.com/go-chi/render/render.go
deleted file mode 100644
index 98c8c7b..0000000
--- a/vendor/github.com/go-chi/render/render.go
+++ /dev/null
@@ -1,134 +0,0 @@
-package render
-
-import (
- "net/http"
- "reflect"
-)
-
-// Renderer interface for managing response payloads.
-type Renderer interface {
- Render(w http.ResponseWriter, r *http.Request) error
-}
-
-// Binder interface for managing request payloads.
-type Binder interface {
- Bind(r *http.Request) error
-}
-
-// Bind decodes a request body and executes the Binder method of the
-// payload structure.
-func Bind(r *http.Request, v Binder) error {
- if err := Decode(r, v); err != nil {
- return err
- }
- return binder(r, v)
-}
-
-// Render renders a single payload and respond to the client request.
-func Render(w http.ResponseWriter, r *http.Request, v Renderer) error {
- if err := renderer(w, r, v); err != nil {
- return err
- }
- Respond(w, r, v)
- return nil
-}
-
-// RenderList renders a slice of payloads and responds to the client request.
-func RenderList(w http.ResponseWriter, r *http.Request, l []Renderer) error {
- for _, v := range l {
- if err := renderer(w, r, v); err != nil {
- return err
- }
- }
- Respond(w, r, l)
- return nil
-}
-
-// Executed top-down
-func renderer(w http.ResponseWriter, r *http.Request, v Renderer) error {
- rv := reflect.ValueOf(v)
- if rv.Kind() == reflect.Ptr {
- rv = rv.Elem()
- }
-
- // We call it top-down.
- if err := v.Render(w, r); err != nil {
- return err
- }
-
- // We're done if the Renderer isn't a struct object
- if rv.Kind() != reflect.Struct {
- return nil
- }
-
- // For structs, we call Render on each field that implements Renderer
- for i := 0; i < rv.NumField(); i++ {
- f := rv.Field(i)
- if f.Type().Implements(rendererType) {
-
- if f.IsNil() {
- continue
- }
-
- fv := f.Interface().(Renderer)
- if err := renderer(w, r, fv); err != nil {
- return err
- }
-
- }
- }
-
- return nil
-}
-
-// Executed bottom-up
-func binder(r *http.Request, v Binder) error {
- rv := reflect.ValueOf(v)
- if rv.Kind() == reflect.Ptr {
- rv = rv.Elem()
- }
-
- // Call Binder on non-struct types right away
- if rv.Kind() != reflect.Struct {
- return v.Bind(r)
- }
-
- // For structs, we call Bind on each field that implements Binder
- for i := 0; i < rv.NumField(); i++ {
- f := rv.Field(i)
- if f.Type().Implements(binderType) {
-
- if f.IsNil() {
- continue
- }
-
- fv := f.Interface().(Binder)
- if err := binder(r, fv); err != nil {
- return err
- }
- }
- }
-
- // We call it bottom-up
- if err := v.Bind(r); err != nil {
- return err
- }
-
- return nil
-}
-
-var (
- rendererType = reflect.TypeOf(new(Renderer)).Elem()
- binderType = reflect.TypeOf(new(Binder)).Elem()
-)
-
-// contextKey is a value for use with context.WithValue. It's used as
-// a pointer so it fits in an interface{} without allocation. This technique
-// for defining context keys was copied from Go 1.7's new use of context in net/http.
-type contextKey struct {
- name string
-}
-
-func (k *contextKey) String() string {
- return "chi render context value " + k.name
-}
diff --git a/vendor/github.com/go-chi/render/responder.go b/vendor/github.com/go-chi/render/responder.go
deleted file mode 100644
index 049b7af..0000000
--- a/vendor/github.com/go-chi/render/responder.go
+++ /dev/null
@@ -1,228 +0,0 @@
-package render
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "encoding/xml"
- "fmt"
- "net/http"
- "reflect"
-)
-
-// M is a convenience alias for quickly building a map structure that is going
-// out to a responder. Just a short-hand.
-type M map[string]interface{}
-
-// Respond is a package-level variable set to our default Responder. We do this
-// because it allows you to set render.Respond to another function with the
-// same function signature, while also utilizing the render.Responder() function
-// itself. Effectively, allowing you to easily add your own logic to the package
-// defaults. For example, maybe you want to test if v is an error and respond
-// differently, or log something before you respond.
-var Respond = DefaultResponder
-
-// StatusCtxKey is a context key to record a future HTTP response status code.
-var StatusCtxKey = &contextKey{"Status"}
-
-// Status sets a HTTP response status code hint into request context at any point
-// during the request life-cycle. Before the Responder sends its response header
-// it will check the StatusCtxKey
-func Status(r *http.Request, status int) {
- *r = *r.WithContext(context.WithValue(r.Context(), StatusCtxKey, status))
-}
-
-// Respond handles streaming JSON and XML responses, automatically setting the
-// Content-Type based on request headers. It will default to a JSON response.
-func DefaultResponder(w http.ResponseWriter, r *http.Request, v interface{}) {
- if v != nil {
- switch reflect.TypeOf(v).Kind() {
- case reflect.Chan:
- switch GetAcceptedContentType(r) {
- case ContentTypeEventStream:
- channelEventStream(w, r, v)
- return
- default:
- v = channelIntoSlice(w, r, v)
- }
- }
- }
-
- // Format response based on request Accept header.
- switch GetAcceptedContentType(r) {
- case ContentTypeJSON:
- JSON(w, r, v)
- case ContentTypeXML:
- XML(w, r, v)
- default:
- JSON(w, r, v)
- }
-}
-
-// PlainText writes a string to the response, setting the Content-Type as
-// text/plain.
-func PlainText(w http.ResponseWriter, r *http.Request, v string) {
- w.Header().Set("Content-Type", "text/plain; charset=utf-8")
- if status, ok := r.Context().Value(StatusCtxKey).(int); ok {
- w.WriteHeader(status)
- }
- w.Write([]byte(v))
-}
-
-// Data writes raw bytes to the response, setting the Content-Type as
-// application/octet-stream.
-func Data(w http.ResponseWriter, r *http.Request, v []byte) {
- w.Header().Set("Content-Type", "application/octet-stream")
- if status, ok := r.Context().Value(StatusCtxKey).(int); ok {
- w.WriteHeader(status)
- }
- w.Write(v)
-}
-
-// HTML writes a string to the response, setting the Content-Type as text/html.
-func HTML(w http.ResponseWriter, r *http.Request, v string) {
- w.Header().Set("Content-Type", "text/html; charset=utf-8")
- if status, ok := r.Context().Value(StatusCtxKey).(int); ok {
- w.WriteHeader(status)
- }
- w.Write([]byte(v))
-}
-
-// JSON marshals 'v' to JSON, automatically escaping HTML and setting the
-// Content-Type as application/json.
-func JSON(w http.ResponseWriter, r *http.Request, v interface{}) {
- buf := &bytes.Buffer{}
- enc := json.NewEncoder(buf)
- enc.SetEscapeHTML(true)
- if err := enc.Encode(v); err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
- }
-
- w.Header().Set("Content-Type", "application/json")
- if status, ok := r.Context().Value(StatusCtxKey).(int); ok {
- w.WriteHeader(status)
- }
- w.Write(buf.Bytes())
-}
-
-// XML marshals 'v' to JSON, setting the Content-Type as application/xml. It
-// will automatically prepend a generic XML header (see encoding/xml.Header) if
-// one is not found in the first 100 bytes of 'v'.
-func XML(w http.ResponseWriter, r *http.Request, v interface{}) {
- b, err := xml.Marshal(v)
- if err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
- }
-
- w.Header().Set("Content-Type", "application/xml; charset=utf-8")
- if status, ok := r.Context().Value(StatusCtxKey).(int); ok {
- w.WriteHeader(status)
- }
-
- // Try to find 100 {
- findHeaderUntil = 100
- }
- if !bytes.Contains(b[:findHeaderUntil], []byte(" 0 {
- s += "; "
- }
- if errs, ok := es[key].(Errors); ok {
- s += fmt.Sprintf("%v: (%v)", key, errs)
- } else {
- s += fmt.Sprintf("%v: %v", key, es[key].Error())
- }
- }
- return s + "."
-}
-
-// MarshalJSON converts the Errors into a valid JSON.
-func (es Errors) MarshalJSON() ([]byte, error) {
- errs := map[string]interface{}{}
- for key, err := range es {
- if ms, ok := err.(json.Marshaler); ok {
- errs[key] = ms
- } else {
- errs[key] = err.Error()
- }
- }
- return json.Marshal(errs)
-}
-
-// Filter removes all nils from Errors and returns back the updated Errors as an error.
-// If the length of Errors becomes 0, it will return nil.
-func (es Errors) Filter() error {
- for key, value := range es {
- if value == nil {
- delete(es, key)
- }
- }
- if len(es) == 0 {
- return nil
- }
- return es
-}
diff --git a/vendor/github.com/go-ozzo/ozzo-validation/error_test.go b/vendor/github.com/go-ozzo/ozzo-validation/error_test.go
deleted file mode 100644
index e7ba997..0000000
--- a/vendor/github.com/go-ozzo/ozzo-validation/error_test.go
+++ /dev/null
@@ -1,70 +0,0 @@
-// Copyright 2016 Qiang Xue. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package validation
-
-import (
- "errors"
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-func TestNewInternalError(t *testing.T) {
- err := NewInternalError(errors.New("abc"))
- if assert.NotNil(t, err.InternalError()) {
- assert.Equal(t, "abc", err.InternalError().Error())
- }
-}
-
-func TestErrors_Error(t *testing.T) {
- errs := Errors{
- "B": errors.New("B1"),
- "C": errors.New("C1"),
- "A": errors.New("A1"),
- }
- assert.Equal(t, "A: A1; B: B1; C: C1.", errs.Error())
-
- errs = Errors{
- "B": errors.New("B1"),
- }
- assert.Equal(t, "B: B1.", errs.Error())
-
- errs = Errors{}
- assert.Equal(t, "", errs.Error())
-}
-
-func TestErrors_MarshalMessage(t *testing.T) {
- errs := Errors{
- "A": errors.New("A1"),
- "B": Errors{
- "2": errors.New("B1"),
- },
- }
- errsJSON, err := errs.MarshalJSON()
- assert.Nil(t, err)
- assert.Equal(t, "{\"A\":\"A1\",\"B\":{\"2\":\"B1\"}}", string(errsJSON))
-}
-
-func TestErrors_Filter(t *testing.T) {
- errs := Errors{
- "B": errors.New("B1"),
- "C": nil,
- "A": errors.New("A1"),
- }
- err := errs.Filter()
- assert.Equal(t, 2, len(errs))
- if assert.NotNil(t, err) {
- assert.Equal(t, "A: A1; B: B1.", err.Error())
- }
-
- errs = Errors{}
- assert.Nil(t, errs.Filter())
-
- errs = Errors{
- "B": nil,
- "C": nil,
- }
- assert.Nil(t, errs.Filter())
-}
diff --git a/vendor/github.com/go-ozzo/ozzo-validation/example_test.go b/vendor/github.com/go-ozzo/ozzo-validation/example_test.go
deleted file mode 100644
index c16face..0000000
--- a/vendor/github.com/go-ozzo/ozzo-validation/example_test.go
+++ /dev/null
@@ -1,130 +0,0 @@
-package validation_test
-
-import (
- "fmt"
- "regexp"
-
- "github.com/go-ozzo/ozzo-validation"
- "github.com/go-ozzo/ozzo-validation/is"
-)
-
-type Address struct {
- Street string
- City string
- State string
- Zip string
-}
-
-type Customer struct {
- Name string
- Gender string
- Email string
- Address Address
-}
-
-func (a Address) Validate() error {
- return validation.ValidateStruct(&a,
- // Street cannot be empty, and the length must between 5 and 50
- validation.Field(&a.Street, validation.Required, validation.Length(5, 50)),
- // City cannot be empty, and the length must between 5 and 50
- validation.Field(&a.City, validation.Required, validation.Length(5, 50)),
- // State cannot be empty, and must be a string consisting of two letters in upper case
- validation.Field(&a.State, validation.Required, validation.Match(regexp.MustCompile("^[A-Z]{2}$"))),
- // State cannot be empty, and must be a string consisting of five digits
- validation.Field(&a.Zip, validation.Required, validation.Match(regexp.MustCompile("^[0-9]{5}$"))),
- )
-}
-
-func (c Customer) Validate() error {
- return validation.ValidateStruct(&c,
- // Name cannot be empty, and the length must be between 5 and 20.
- validation.Field(&c.Name, validation.Required, validation.Length(5, 20)),
- // Gender is optional, and should be either "Female" or "Male".
- validation.Field(&c.Gender, validation.In("Female", "Male")),
- // Email cannot be empty and should be in a valid email format.
- validation.Field(&c.Email, validation.Required, is.Email),
- // Validate Address using its own validation rules
- validation.Field(&c.Address),
- )
-}
-
-func Example() {
- c := Customer{
- Name: "Qiang Xue",
- Email: "q",
- Address: Address{
- Street: "123 Main Street",
- City: "Unknown",
- State: "Virginia",
- Zip: "12345",
- },
- }
-
- err := c.Validate()
- fmt.Println(err)
- // Output:
- // Address: (State: must be in a valid format.); Email: must be a valid email address.
-}
-
-func Example_second() {
- data := "example"
- err := validation.Validate(data,
- validation.Required, // not empty
- validation.Length(5, 100), // length between 5 and 100
- is.URL, // is a valid URL
- )
- fmt.Println(err)
- // Output:
- // must be a valid URL
-}
-
-func Example_third() {
- addresses := []Address{
- {State: "MD", Zip: "12345"},
- {Street: "123 Main St", City: "Vienna", State: "VA", Zip: "12345"},
- {City: "Unknown", State: "NC", Zip: "123"},
- }
- err := validation.Validate(addresses)
- fmt.Println(err)
- // Output:
- // 0: (City: cannot be blank; Street: cannot be blank.); 2: (Street: cannot be blank; Zip: must be in a valid format.).
-}
-
-func Example_four() {
- c := Customer{
- Name: "Qiang Xue",
- Email: "q",
- Address: Address{
- State: "Virginia",
- },
- }
-
- err := validation.Errors{
- "name": validation.Validate(c.Name, validation.Required, validation.Length(5, 20)),
- "email": validation.Validate(c.Name, validation.Required, is.Email),
- "zip": validation.Validate(c.Address.Zip, validation.Required, validation.Match(regexp.MustCompile("^[0-9]{5}$"))),
- }.Filter()
- fmt.Println(err)
- // Output:
- // email: must be a valid email address; zip: cannot be blank.
-}
-
-func Example_five() {
- type Employee struct {
- Name string
- }
-
- type Manager struct {
- Employee
- Level int
- }
-
- m := Manager{}
- err := validation.ValidateStruct(&m,
- validation.Field(&m.Name, validation.Required),
- validation.Field(&m.Level, validation.Required),
- )
- fmt.Println(err)
- // Output:
- // Level: cannot be blank; Name: cannot be blank.
-}
\ No newline at end of file
diff --git a/vendor/github.com/go-ozzo/ozzo-validation/in.go b/vendor/github.com/go-ozzo/ozzo-validation/in.go
deleted file mode 100644
index 9673dd0..0000000
--- a/vendor/github.com/go-ozzo/ozzo-validation/in.go
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright 2016 Qiang Xue. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package validation
-
-import "errors"
-
-// In returns a validation rule that checks if a value can be found in the given list of values.
-// Note that the value being checked and the possible range of values must be of the same type.
-// An empty value is considered valid. Use the Required rule to make sure a value is not empty.
-func In(values ...interface{}) *inRule {
- return &inRule{
- elements: values,
- message: "must be a valid value",
- }
-}
-
-type inRule struct {
- elements []interface{}
- message string
-}
-
-// Validate checks if the given value is valid or not.
-func (r *inRule) Validate(value interface{}) error {
- value, isNil := Indirect(value)
- if isNil || IsEmpty(value) {
- return nil
- }
-
- for _, e := range r.elements {
- if e == value {
- return nil
- }
- }
- return errors.New(r.message)
-}
-
-// Error sets the error message for the rule.
-func (r *inRule) Error(message string) *inRule {
- r.message = message
- return r
-}
diff --git a/vendor/github.com/go-ozzo/ozzo-validation/in_test.go b/vendor/github.com/go-ozzo/ozzo-validation/in_test.go
deleted file mode 100644
index ad0c87b..0000000
--- a/vendor/github.com/go-ozzo/ozzo-validation/in_test.go
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2016 Qiang Xue. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package validation
-
-import (
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-func TestIn(t *testing.T) {
- var v int = 1
- var v2 *int
- tests := []struct {
- tag string
- values []interface{}
- value interface{}
- err string
- }{
- {"t0", []interface{}{1, 2}, 0, ""},
- {"t1", []interface{}{1, 2}, 1, ""},
- {"t2", []interface{}{1, 2}, 2, ""},
- {"t3", []interface{}{1, 2}, 3, "must be a valid value"},
- {"t4", []interface{}{}, 3, "must be a valid value"},
- {"t5", []interface{}{1, 2}, "1", "must be a valid value"},
- {"t6", []interface{}{1, 2}, &v, ""},
- {"t7", []interface{}{1, 2}, v2, ""},
- }
-
- for _, test := range tests {
- r := In(test.values...)
- err := r.Validate(test.value)
- assertError(t, test.err, err, test.tag)
- }
-}
-
-func Test_inRule_Error(t *testing.T) {
- r := In(1, 2, 3)
- assert.Equal(t, "must be a valid value", r.message)
- r.Error("123")
- assert.Equal(t, "123", r.message)
-}
diff --git a/vendor/github.com/go-ozzo/ozzo-validation/is/rules.go b/vendor/github.com/go-ozzo/ozzo-validation/is/rules.go
deleted file mode 100644
index ffbeef8..0000000
--- a/vendor/github.com/go-ozzo/ozzo-validation/is/rules.go
+++ /dev/null
@@ -1,138 +0,0 @@
-// Copyright 2016 Qiang Xue. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-// Package is provides a list of commonly used string validation rules.
-package is
-
-import (
- "regexp"
- "unicode"
-
- "github.com/asaskevich/govalidator"
- "github.com/go-ozzo/ozzo-validation"
-)
-
-var (
- // Email validates if a string is an email or not.
- Email = validation.NewStringRule(govalidator.IsEmail, "must be a valid email address")
- // URL validates if a string is a valid URL
- URL = validation.NewStringRule(govalidator.IsURL, "must be a valid URL")
- // RequestURL validates if a string is a valid request URL
- RequestURL = validation.NewStringRule(govalidator.IsRequestURL, "must be a valid request URL")
- // RequestURI validates if a string is a valid request URI
- RequestURI = validation.NewStringRule(govalidator.IsRequestURI, "must be a valid request URI")
- // Alpha validates if a string contains English letters only (a-zA-Z)
- Alpha = validation.NewStringRule(govalidator.IsAlpha, "must contain English letters only")
- // Digit validates if a string contains digits only (0-9)
- Digit = validation.NewStringRule(isDigit, "must contain digits only")
- // Alphanumeric validates if a string contains English letters and digits only (a-zA-Z0-9)
- Alphanumeric = validation.NewStringRule(govalidator.IsAlphanumeric, "must contain English letters and digits only")
- // UTFLetter validates if a string contains unicode letters only
- UTFLetter = validation.NewStringRule(govalidator.IsUTFLetter, "must contain unicode letter characters only")
- // UTFDigit validates if a string contains unicode decimal digits only
- UTFDigit = validation.NewStringRule(govalidator.IsUTFDigit, "must contain unicode decimal digits only")
- // UTFLetterNumeric validates if a string contains unicode letters and numbers only
- UTFLetterNumeric = validation.NewStringRule(govalidator.IsUTFLetterNumeric, "must contain unicode letters and numbers only")
- // UTFNumeric validates if a string contains unicode number characters (category N) only
- UTFNumeric = validation.NewStringRule(isUTFNumeric, "must contain unicode number characters only")
- // LowerCase validates if a string contains lower case unicode letters only
- LowerCase = validation.NewStringRule(govalidator.IsLowerCase, "must be in lower case")
- // UpperCase validates if a string contains upper case unicode letters only
- UpperCase = validation.NewStringRule(govalidator.IsUpperCase, "must be in upper case")
- // Hexadecimal validates if a string is a valid hexadecimal number
- Hexadecimal = validation.NewStringRule(govalidator.IsHexadecimal, "must be a valid hexadecimal number")
- // HexColor validates if a string is a valid hexadecimal color code
- HexColor = validation.NewStringRule(govalidator.IsHexcolor, "must be a valid hexadecimal color code")
- // RGBColor validates if a string is a valid RGB color in the form of rgb(R, G, B)
- RGBColor = validation.NewStringRule(govalidator.IsRGBcolor, "must be a valid RGB color code")
- // Int validates if a string is a valid integer number
- Int = validation.NewStringRule(govalidator.IsInt, "must be an integer number")
- // Float validates if a string is a floating point number
- Float = validation.NewStringRule(govalidator.IsFloat, "must be a floating point number")
- // UUIDv3 validates if a string is a valid version 3 UUID
- UUIDv3 = validation.NewStringRule(govalidator.IsUUIDv3, "must be a valid UUID v3")
- // UUIDv4 validates if a string is a valid version 4 UUID
- UUIDv4 = validation.NewStringRule(govalidator.IsUUIDv4, "must be a valid UUID v4")
- // UUIDv5 validates if a string is a valid version 5 UUID
- UUIDv5 = validation.NewStringRule(govalidator.IsUUIDv5, "must be a valid UUID v5")
- // UUID validates if a string is a valid UUID
- UUID = validation.NewStringRule(govalidator.IsUUID, "must be a valid UUID")
- // CreditCard validates if a string is a valid credit card number
- CreditCard = validation.NewStringRule(govalidator.IsCreditCard, "must be a valid credit card number")
- // ISBN10 validates if a string is an ISBN version 10
- ISBN10 = validation.NewStringRule(govalidator.IsISBN10, "must be a valid ISBN-10")
- // ISBN13 validates if a string is an ISBN version 13
- ISBN13 = validation.NewStringRule(govalidator.IsISBN13, "must be a valid ISBN-13")
- // ISBN validates if a string is an ISBN (either version 10 or 13)
- ISBN = validation.NewStringRule(isISBN, "must be a valid ISBN")
- // JSON validates if a string is in valid JSON format
- JSON = validation.NewStringRule(govalidator.IsJSON, "must be in valid JSON format")
- // ASCII validates if a string contains ASCII characters only
- ASCII = validation.NewStringRule(govalidator.IsASCII, "must contain ASCII characters only")
- // PrintableASCII validates if a string contains printable ASCII characters only
- PrintableASCII = validation.NewStringRule(govalidator.IsPrintableASCII, "must contain printable ASCII characters only")
- // Multibyte validates if a string contains multibyte characters
- Multibyte = validation.NewStringRule(govalidator.IsMultibyte, "must contain multibyte characters")
- // FullWidth validates if a string contains full-width characters
- FullWidth = validation.NewStringRule(govalidator.IsFullWidth, "must contain full-width characters")
- // HalfWidth validates if a string contains half-width characters
- HalfWidth = validation.NewStringRule(govalidator.IsHalfWidth, "must contain half-width characters")
- // VariableWidth validates if a string contains both full-width and half-width characters
- VariableWidth = validation.NewStringRule(govalidator.IsVariableWidth, "must contain both full-width and half-width characters")
- // Base64 validates if a string is encoded in Base64
- Base64 = validation.NewStringRule(govalidator.IsBase64, "must be encoded in Base64")
- // DataURI validates if a string is a valid base64-encoded data URI
- DataURI = validation.NewStringRule(govalidator.IsDataURI, "must be a Base64-encoded data URI")
- // CountryCode2 validates if a string is a valid ISO3166 Alpha 2 country code
- CountryCode2 = validation.NewStringRule(govalidator.IsISO3166Alpha2, "must be a valid two-letter country code")
- // CountryCode3 validates if a string is a valid ISO3166 Alpha 3 country code
- CountryCode3 = validation.NewStringRule(govalidator.IsISO3166Alpha3, "must be a valid three-letter country code")
- // DialString validates if a string is a valid dial string that can be passed to Dial()
- DialString = validation.NewStringRule(govalidator.IsDialString, "must be a valid dial string")
- // MAC validates if a string is a MAC address
- MAC = validation.NewStringRule(govalidator.IsMAC, "must be a valid MAC address")
- // IP validates if a string is a valid IP address (either version 4 or 6)
- IP = validation.NewStringRule(govalidator.IsIP, "must be a valid IP address")
- // IPv4 validates if a string is a valid version 4 IP address
- IPv4 = validation.NewStringRule(govalidator.IsIPv4, "must be a valid IPv4 address")
- // IPv6 validates if a string is a valid version 6 IP address
- IPv6 = validation.NewStringRule(govalidator.IsIPv6, "must be a valid IPv6 address")
- // DNSName validates if a string is valid DNS name
- DNSName = validation.NewStringRule(govalidator.IsDNSName, "must be a valid DNS name")
- // Host validates if a string is a valid IP (both v4 and v6) or a valid DNS name
- Host = validation.NewStringRule(govalidator.IsHost, "must be a valid IP address or DNS name")
- // Port validates if a string is a valid port number
- Port = validation.NewStringRule(govalidator.IsPort, "must be a valid port number")
- // MongoID validates if a string is a valid Mongo ID
- MongoID = validation.NewStringRule(govalidator.IsMongoID, "must be a valid hex-encoded MongoDB ObjectId")
- // Latitude validates if a string is a valid latitude
- Latitude = validation.NewStringRule(govalidator.IsLatitude, "must be a valid latitude")
- // Longitude validates if a string is a valid longitude
- Longitude = validation.NewStringRule(govalidator.IsLongitude, "must be a valid longitude")
- // SSN validates if a string is a social security number (SSN)
- SSN = validation.NewStringRule(govalidator.IsSSN, "must be a valid social security number")
- // Semver validates if a string is a valid semantic version
- Semver = validation.NewStringRule(govalidator.IsSemver, "must be a valid semantic version")
-)
-
-var (
- reDigit = regexp.MustCompile("^[0-9]+$")
-)
-
-func isISBN(value string) bool {
- return govalidator.IsISBN(value, 10) || govalidator.IsISBN(value, 13)
-}
-
-func isDigit(value string) bool {
- return reDigit.MatchString(value)
-}
-
-func isUTFNumeric(value string) bool {
- for _, c := range value {
- if unicode.IsNumber(c) == false {
- return false
- }
- }
- return true
-}
diff --git a/vendor/github.com/go-ozzo/ozzo-validation/is/rules_test.go b/vendor/github.com/go-ozzo/ozzo-validation/is/rules_test.go
deleted file mode 100644
index 7b332bb..0000000
--- a/vendor/github.com/go-ozzo/ozzo-validation/is/rules_test.go
+++ /dev/null
@@ -1,94 +0,0 @@
-// Copyright 2016 Qiang Xue. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package is
-
-import (
- "testing"
-
- "github.com/go-ozzo/ozzo-validation"
- "github.com/stretchr/testify/assert"
-)
-
-func TestAll(t *testing.T) {
- tests := []struct {
- tag string
- rule validation.Rule
- valid, invalid string
- err string
- }{
- {"Email", Email, "test@example.com", "example.com", "must be a valid email address"},
- {"URL", URL, "http://example.com", "examplecom", "must be a valid URL"},
- {"RequestURL", RequestURL, "http://example.com", "examplecom", "must be a valid request URL"},
- {"RequestURI", RequestURI, "http://example.com", "examplecom", "must be a valid request URI"},
- {"Alpha", Alpha, "abcd", "ab12", "must contain English letters only"},
- {"Digit", Digit, "123", "12ab", "must contain digits only"},
- {"Alphanumeric", Alphanumeric, "abc123", "abc.123", "must contain English letters and digits only"},
- {"UTFLetter", UTFLetter, "abc", "123", "must contain unicode letter characters only"},
- {"UTFDigit", UTFDigit, "123", "abc", "must contain unicode decimal digits only"},
- {"UTFNumeric", UTFNumeric, "123", "abc.123", "must contain unicode number characters only"},
- {"UTFLetterNumeric", UTFLetterNumeric, "abc123", "abc.123", "must contain unicode letters and numbers only"},
- {"LowerCase", LowerCase, "abc", "Abc", "must be in lower case"},
- {"UpperCase", UpperCase, "ABC", "ABc", "must be in upper case"},
- {"IP", IP, "74.125.19.99", "74.125.19.999", "must be a valid IP address"},
- {"IPv4", IPv4, "74.125.19.99", "2001:4860:0:2001::68", "must be a valid IPv4 address"},
- {"IPv6", IPv6, "2001:4860:0:2001::68", "74.125.19.99", "must be a valid IPv6 address"},
- {"MAC", MAC, "0123.4567.89ab", "74.125.19.99", "must be a valid MAC address"},
- {"DNSName", DNSName, "example.com", "abc%", "must be a valid DNS name"},
- {"Host", Host, "example.com", "abc%", "must be a valid IP address or DNS name"},
- {"Port", Port, "123", "99999", "must be a valid port number"},
- {"Latitude", Latitude, "23.123", "100", "must be a valid latitude"},
- {"Longitude", Longitude, "123.123", "abc", "must be a valid longitude"},
- {"SSN", SSN, "100-00-1000", "100-0001000", "must be a valid social security number"},
- {"Semver", Semver, "1.0.0", "1.0.0.0", "must be a valid semantic version"},
- {"ISBN", ISBN, "1-61729-085-8", "1-61729-085-81", "must be a valid ISBN"},
- {"ISBN10", ISBN10, "1-61729-085-8", "1-61729-085-81", "must be a valid ISBN-10"},
- {"ISBN13", ISBN13, "978-4-87311-368-5", "978-4-87311-368-a", "must be a valid ISBN-13"},
- {"UUID", UUID, "a987fbc9-4bed-3078-cf07-9141ba07c9f1", "a987fbc9-4bed-3078-cf07-9141ba07c9f3a", "must be a valid UUID"},
- {"UUIDv3", UUIDv3, "b987fbc9-4bed-3078-cf07-9141ba07c9f3", "b987fbc9-4bed-4078-cf07-9141ba07c9f3", "must be a valid UUID v3"},
- {"UUIDv4", UUIDv4, "57b73598-8764-4ad0-a76a-679bb6640eb1", "b987fbc9-4bed-3078-cf07-9141ba07c9f3", "must be a valid UUID v4"},
- {"UUIDv5", UUIDv5, "987fbc97-4bed-5078-af07-9141ba07c9f3", "b987fbc9-4bed-3078-cf07-9141ba07c9f3", "must be a valid UUID v5"},
- {"MongoID", MongoID, "507f1f77bcf86cd799439011", "507f1f77bcf86cd79943901", "must be a valid hex-encoded MongoDB ObjectId"},
- {"CreditCard", CreditCard, "375556917985515", "375556917985516", "must be a valid credit card number"},
- {"JSON", JSON, "[1, 2]", "[1, 2,]", "must be in valid JSON format"},
- {"ASCII", ASCII, "abc", "aabc", "must contain ASCII characters only"},
- {"PrintableASCII", PrintableASCII, "abc", "aabc", "must contain printable ASCII characters only"},
- {"CountryCode2", CountryCode2, "US", "XY", "must be a valid two-letter country code"},
- {"CountryCode3", CountryCode3, "USA", "XYZ", "must be a valid three-letter country code"},
- {"DialString", DialString, "localhost.local:1", "localhost.loc:100000", "must be a valid dial string"},
- {"DataURI", DataURI, "data:image/png;base64,TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4=", "image/gif;base64,U3VzcGVuZGlzc2UgbGVjdHVzIGxlbw==", "must be a Base64-encoded data URI"},
- {"Base64", Base64, "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4=", "image", "must be encoded in Base64"},
- {"Multibyte", Multibyte, "abc", "abc", "must contain multibyte characters"},
- {"FullWidth", FullWidth, "3ー0", "abc", "must contain full-width characters"},
- {"HalfWidth", HalfWidth, "abc123い", "0011", "must contain half-width characters"},
- {"VariableWidth", VariableWidth, "3ー0123", "abc", "must contain both full-width and half-width characters"},
- {"Hexadecimal", Hexadecimal, "FEF", "FTF", "must be a valid hexadecimal number"},
- {"HexColor", HexColor, "F00", "FTF", "must be a valid hexadecimal color code"},
- {"RGBColor", RGBColor, "rgb(100, 200, 1)", "abc", "must be a valid RGB color code"},
- {"Int", Int, "100", "1.1", "must be an integer number"},
- {"Float", Float, "1.1", "a.1", "must be a floating point number"},
- {"VariableWidth", VariableWidth, "", "", ""},
- }
-
- for _, test := range tests {
- err := test.rule.Validate("")
- assert.Nil(t, err, test.tag)
- err = test.rule.Validate(test.valid)
- assert.Nil(t, err, test.tag)
- err = test.rule.Validate(&test.valid)
- assert.Nil(t, err, test.tag)
- err = test.rule.Validate(test.invalid)
- assertError(t, test.err, err, test.tag)
- err = test.rule.Validate(&test.invalid)
- assertError(t, test.err, err, test.tag)
- }
-}
-
-func assertError(t *testing.T, expected string, err error, tag string) {
- if expected == "" {
- assert.Nil(t, err, tag)
- } else if assert.NotNil(t, err, tag) {
- assert.Equal(t, expected, err.Error(), tag)
- }
-}
diff --git a/vendor/github.com/go-ozzo/ozzo-validation/length.go b/vendor/github.com/go-ozzo/ozzo-validation/length.go
deleted file mode 100644
index 752df45..0000000
--- a/vendor/github.com/go-ozzo/ozzo-validation/length.go
+++ /dev/null
@@ -1,77 +0,0 @@
-// Copyright 2016 Qiang Xue. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package validation
-
-import (
- "errors"
- "fmt"
- "unicode/utf8"
-)
-
-// Length returns a validation rule that checks if a value's length is within the specified range.
-// If max is 0, it means there is no upper bound for the length.
-// This rule should only be used for validating strings, slices, maps, and arrays.
-// An empty value is considered valid. Use the Required rule to make sure a value is not empty.
-func Length(min, max int) *lengthRule {
- message := "the value must be empty"
- if min == 0 && max > 0 {
- message = fmt.Sprintf("the length must be no more than %v", max)
- } else if min > 0 && max == 0 {
- message = fmt.Sprintf("the length must be no less than %v", min)
- } else if min > 0 && max > 0 {
- message = fmt.Sprintf("the length must be between %v and %v", min, max)
- }
- return &lengthRule{
- min: min,
- max: max,
- message: message,
- }
-}
-
-// RuneLength returns a validation rule that checks if a string's rune length is within the specified range.
-// If max is 0, it means there is no upper bound for the length.
-// This rule should only be used for validating strings, slices, maps, and arrays.
-// An empty value is considered valid. Use the Required rule to make sure a value is not empty.
-// If the value being validated is not a string, the rule works the same as Length.
-func RuneLength(min, max int) *lengthRule {
- r := Length(min, max)
- r.rune = true
- return r
-}
-
-type lengthRule struct {
- min, max int
- message string
- rune bool
-}
-
-// Validate checks if the given value is valid or not.
-func (v *lengthRule) Validate(value interface{}) error {
- value, isNil := Indirect(value)
- if isNil || IsEmpty(value) {
- return nil
- }
-
- var (
- l int
- err error
- )
- if s, ok := value.(string); ok && v.rune {
- l = utf8.RuneCountInString(s)
- } else if l, err = LengthOfValue(value); err != nil {
- return err
- }
-
- if v.min > 0 && l < v.min || v.max > 0 && l > v.max {
- return errors.New(v.message)
- }
- return nil
-}
-
-// Error sets the error message for the rule.
-func (v *lengthRule) Error(message string) *lengthRule {
- v.message = message
- return v
-}
diff --git a/vendor/github.com/go-ozzo/ozzo-validation/length_test.go b/vendor/github.com/go-ozzo/ozzo-validation/length_test.go
deleted file mode 100644
index 5eda731..0000000
--- a/vendor/github.com/go-ozzo/ozzo-validation/length_test.go
+++ /dev/null
@@ -1,90 +0,0 @@
-// Copyright 2016 Qiang Xue. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package validation
-
-import (
- "database/sql"
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-func TestLength(t *testing.T) {
- var v *string
- tests := []struct {
- tag string
- min, max int
- value interface{}
- err string
- }{
- {"t1", 2, 4, "abc", ""},
- {"t2", 2, 4, "", ""},
- {"t3", 2, 4, "abcdf", "the length must be between 2 and 4"},
- {"t4", 0, 4, "ab", ""},
- {"t5", 0, 4, "abcde", "the length must be no more than 4"},
- {"t6", 2, 0, "ab", ""},
- {"t7", 2, 0, "a", "the length must be no less than 2"},
- {"t8", 2, 0, v, ""},
- {"t9", 2, 0, 123, "cannot get the length of int"},
- {"t10", 2, 4, sql.NullString{String: "abc", Valid: true}, ""},
- {"t11", 2, 4, sql.NullString{String: "", Valid: true}, ""},
- {"t12", 2, 4, &sql.NullString{String: "abc", Valid: true}, ""},
- }
-
- for _, test := range tests {
- r := Length(test.min, test.max)
- err := r.Validate(test.value)
- assertError(t, test.err, err, test.tag)
- }
-}
-
-func TestRuneLength(t *testing.T) {
- var v *string
- tests := []struct {
- tag string
- min, max int
- value interface{}
- err string
- }{
- {"t1", 2, 4, "abc", ""},
- {"t1.1", 2, 3, "💥💥", ""},
- {"t1.2", 2, 3, "💥💥💥", ""},
- {"t1.3", 2, 3, "💥", "the length must be between 2 and 3"},
- {"t1.4", 2, 3, "💥💥💥💥", "the length must be between 2 and 3"},
- {"t2", 2, 4, "", ""},
- {"t3", 2, 4, "abcdf", "the length must be between 2 and 4"},
- {"t4", 0, 4, "ab", ""},
- {"t5", 0, 4, "abcde", "the length must be no more than 4"},
- {"t6", 2, 0, "ab", ""},
- {"t7", 2, 0, "a", "the length must be no less than 2"},
- {"t8", 2, 0, v, ""},
- {"t9", 2, 0, 123, "cannot get the length of int"},
- {"t10", 2, 4, sql.NullString{String: "abc", Valid: true}, ""},
- {"t11", 2, 4, sql.NullString{String: "", Valid: true}, ""},
- {"t12", 2, 4, &sql.NullString{String: "abc", Valid: true}, ""},
- {"t13", 2, 3, &sql.NullString{String: "💥💥", Valid: true}, ""},
- {"t14", 2, 3, &sql.NullString{String: "💥", Valid: true}, "the length must be between 2 and 3"},
- }
-
- for _, test := range tests {
- r := RuneLength(test.min, test.max)
- err := r.Validate(test.value)
- assertError(t, test.err, err, test.tag)
- }
-}
-
-func Test_lengthRule_Error(t *testing.T) {
- r := Length(10, 20)
- assert.Equal(t, "the length must be between 10 and 20", r.message)
-
- r = Length(0, 20)
- assert.Equal(t, "the length must be no more than 20", r.message)
-
- r = Length(10, 0)
- assert.Equal(t, "the length must be no less than 10", r.message)
-
- r.Error("123")
- assert.Equal(t, "123", r.message)
-}
diff --git a/vendor/github.com/go-ozzo/ozzo-validation/match.go b/vendor/github.com/go-ozzo/ozzo-validation/match.go
deleted file mode 100644
index 02aa4fb..0000000
--- a/vendor/github.com/go-ozzo/ozzo-validation/match.go
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright 2016 Qiang Xue. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package validation
-
-import (
- "errors"
- "regexp"
-)
-
-// Match returns a validation rule that checks if a value matches the specified regular expression.
-// This rule should only be used for validating strings and byte slices, or a validation error will be reported.
-// An empty value is considered valid. Use the Required rule to make sure a value is not empty.
-func Match(re *regexp.Regexp) *matchRule {
- return &matchRule{
- re: re,
- message: "must be in a valid format",
- }
-}
-
-type matchRule struct {
- re *regexp.Regexp
- message string
-}
-
-// Validate checks if the given value is valid or not.
-func (v *matchRule) Validate(value interface{}) error {
- value, isNil := Indirect(value)
- if isNil {
- return nil
- }
-
- isString, str, isBytes, bs := StringOrBytes(value)
- if isString && (str == "" || v.re.MatchString(str)) {
- return nil
- } else if isBytes && (len(bs) == 0 || v.re.Match(bs)) {
- return nil
- }
- return errors.New(v.message)
-}
-
-// Error sets the error message for the rule.
-func (v *matchRule) Error(message string) *matchRule {
- v.message = message
- return v
-}
diff --git a/vendor/github.com/go-ozzo/ozzo-validation/match_test.go b/vendor/github.com/go-ozzo/ozzo-validation/match_test.go
deleted file mode 100644
index 98075e6..0000000
--- a/vendor/github.com/go-ozzo/ozzo-validation/match_test.go
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2016 Qiang Xue. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package validation
-
-import (
- "regexp"
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-func TestMatch(t *testing.T) {
- var v2 *string
- tests := []struct {
- tag string
- re string
- value interface{}
- err string
- }{
- {"t1", "[a-z]+", "abc", ""},
- {"t2", "[a-z]+", "", ""},
- {"t3", "[a-z]+", v2, ""},
- {"t4", "[a-z]+", "123", "must be in a valid format"},
- {"t5", "[a-z]+", []byte("abc"), ""},
- {"t6", "[a-z]+", []byte("123"), "must be in a valid format"},
- {"t7", "[a-z]+", []byte(""), ""},
- {"t8", "[a-z]+", nil, ""},
- }
-
- for _, test := range tests {
- r := Match(regexp.MustCompile(test.re))
- err := r.Validate(test.value)
- assertError(t, test.err, err, test.tag)
- }
-}
-
-func Test_matchRule_Error(t *testing.T) {
- r := Match(regexp.MustCompile("[a-z]+"))
- assert.Equal(t, "must be in a valid format", r.message)
- r.Error("123")
- assert.Equal(t, "123", r.message)
-}
diff --git a/vendor/github.com/go-ozzo/ozzo-validation/minmax.go b/vendor/github.com/go-ozzo/ozzo-validation/minmax.go
deleted file mode 100644
index 952bd1c..0000000
--- a/vendor/github.com/go-ozzo/ozzo-validation/minmax.go
+++ /dev/null
@@ -1,177 +0,0 @@
-// Copyright 2016 Qiang Xue. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package validation
-
-import (
- "errors"
- "fmt"
- "reflect"
- "time"
-)
-
-type thresholdRule struct {
- threshold interface{}
- operator int
- message string
-}
-
-const (
- greaterThan = iota
- greaterEqualThan
- lessThan
- lessEqualThan
-)
-
-// Min is a validation rule that checks if a value is greater or equal than the specified value.
-// By calling Exclusive, the rule will check if the value is strictly greater than the specified value.
-// Note that the value being checked and the threshold value must be of the same type.
-// Only int, uint, float and time.Time types are supported.
-// An empty value is considered valid. Please use the Required rule to make sure a value is not empty.
-func Min(min interface{}) *thresholdRule {
- return &thresholdRule{
- threshold: min,
- operator: greaterEqualThan,
- message: fmt.Sprintf("must be no less than %v", min),
- }
-}
-
-// Max is a validation rule that checks if a value is less or equal than the specified value.
-// By calling Exclusive, the rule will check if the value is strictly less than the specified value.
-// Note that the value being checked and the threshold value must be of the same type.
-// Only int, uint, float and time.Time types are supported.
-// An empty value is considered valid. Please use the Required rule to make sure a value is not empty.
-func Max(max interface{}) *thresholdRule {
- return &thresholdRule{
- threshold: max,
- operator: lessEqualThan,
- message: fmt.Sprintf("must be no greater than %v", max),
- }
-}
-
-// Exclusive sets the comparison to exclude the boundary value.
-func (r *thresholdRule) Exclusive() *thresholdRule {
- if r.operator == greaterEqualThan {
- r.operator = greaterThan
- r.message = fmt.Sprintf("must be greater than %v", r.threshold)
- } else if r.operator == lessEqualThan {
- r.operator = lessThan
- r.message = fmt.Sprintf("must be less than %v", r.threshold)
- }
- return r
-}
-
-// Validate checks if the given value is valid or not.
-func (r *thresholdRule) Validate(value interface{}) error {
- value, isNil := Indirect(value)
- if isNil || IsEmpty(value) {
- return nil
- }
-
- rv := reflect.ValueOf(r.threshold)
- switch rv.Kind() {
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- v, err := ToInt(value)
- if err != nil {
- return err
- }
- if r.compareInt(rv.Int(), v) {
- return nil
- }
-
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
- v, err := ToUint(value)
- if err != nil {
- return err
- }
- if r.compareUint(rv.Uint(), v) {
- return nil
- }
-
- case reflect.Float32, reflect.Float64:
- v, err := ToFloat(value)
- if err != nil {
- return err
- }
- if r.compareFloat(rv.Float(), v) {
- return nil
- }
-
- case reflect.Struct:
- t, ok := r.threshold.(time.Time)
- if !ok {
- return fmt.Errorf("type not supported: %v", rv.Type())
- }
- v, ok := value.(time.Time)
- if !ok {
- return fmt.Errorf("cannot convert %v to time.Time", reflect.TypeOf(value))
- }
- if v.IsZero() || r.compareTime(t, v) {
- return nil
- }
-
- default:
- return fmt.Errorf("type not supported: %v", rv.Type())
- }
-
- return errors.New(r.message)
-}
-
-// Error sets the error message for the rule.
-func (r *thresholdRule) Error(message string) *thresholdRule {
- r.message = message
- return r
-}
-
-func (r *thresholdRule) compareInt(threshold, value int64) bool {
- switch r.operator {
- case greaterThan:
- return value > threshold
- case greaterEqualThan:
- return value >= threshold
- case lessThan:
- return value < threshold
- default:
- return value <= threshold
- }
-}
-
-func (r *thresholdRule) compareUint(threshold, value uint64) bool {
- switch r.operator {
- case greaterThan:
- return value > threshold
- case greaterEqualThan:
- return value >= threshold
- case lessThan:
- return value < threshold
- default:
- return value <= threshold
- }
-}
-
-func (r *thresholdRule) compareFloat(threshold, value float64) bool {
- switch r.operator {
- case greaterThan:
- return value > threshold
- case greaterEqualThan:
- return value >= threshold
- case lessThan:
- return value < threshold
- default:
- return value <= threshold
- }
-}
-
-func (r *thresholdRule) compareTime(threshold, value time.Time) bool {
- switch r.operator {
- case greaterThan:
- return value.After(threshold)
- case greaterEqualThan:
- return value.After(threshold) || value.Equal(threshold)
- case lessThan:
- return value.Before(threshold)
- default:
- return value.Before(threshold) || value.Equal(threshold)
- }
-}
diff --git a/vendor/github.com/go-ozzo/ozzo-validation/minmax_test.go b/vendor/github.com/go-ozzo/ozzo-validation/minmax_test.go
deleted file mode 100644
index 562757f..0000000
--- a/vendor/github.com/go-ozzo/ozzo-validation/minmax_test.go
+++ /dev/null
@@ -1,137 +0,0 @@
-// Copyright 2016 Qiang Xue. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package validation
-
-import (
- "testing"
-
- "github.com/stretchr/testify/assert"
- "time"
-)
-
-func TestMin(t *testing.T) {
- date0 := time.Time{}
- date20000101 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
- date20001201 := time.Date(2000, 12, 1, 0, 0, 0, 0, time.UTC)
- date20000601 := time.Date(2000, 6, 1, 0, 0, 0, 0, time.UTC)
-
- tests := []struct {
- tag string
- threshold interface{}
- exclusive bool
- value interface{}
- err string
- }{
- // int cases
- {"t1.1", 1, false, 1, ""},
- {"t1.2", 1, false, 2, ""},
- {"t1.3", 1, false, -1, "must be no less than 1"},
- {"t1.4", 1, false, 0, ""},
- {"t1.5", 1, true, 1, "must be greater than 1"},
- {"t1.6", 1, false, "1", "cannot convert string to int64"},
- {"t1.7", "1", false, 1, "type not supported: string"},
- // uint cases
- {"t2.1", uint(2), false, uint(2), ""},
- {"t2.2", uint(2), false, uint(3), ""},
- {"t2.3", uint(2), false, uint(1), "must be no less than 2"},
- {"t2.4", uint(2), false, uint(0), ""},
- {"t2.5", uint(2), true, uint(2), "must be greater than 2"},
- {"t2.6", uint(2), false, "1", "cannot convert string to uint64"},
- // float cases
- {"t3.1", float64(2), false, float64(2), ""},
- {"t3.2", float64(2), false, float64(3), ""},
- {"t3.3", float64(2), false, float64(1), "must be no less than 2"},
- {"t3.4", float64(2), false, float64(0), ""},
- {"t3.5", float64(2), true, float64(2), "must be greater than 2"},
- {"t3.6", float64(2), false, "1", "cannot convert string to float64"},
- // Time cases
- {"t4.1", date20000601, false, date20000601, ""},
- {"t4.2", date20000601, false, date20001201, ""},
- {"t4.3", date20000601, false, date20000101, "must be no less than 2000-06-01 00:00:00 +0000 UTC"},
- {"t4.4", date20000601, false, date0, ""},
- {"t4.5", date20000601, true, date20000601, "must be greater than 2000-06-01 00:00:00 +0000 UTC"},
- {"t4.6", date20000601, true, 1, "cannot convert int to time.Time"},
- {"t4.7", struct{}{}, false, 1, "type not supported: struct {}"},
- }
-
- for _, test := range tests {
- r := Min(test.threshold)
- if test.exclusive {
- r.Exclusive()
- }
- err := r.Validate(test.value)
- assertError(t, test.err, err, test.tag)
- }
-}
-
-func TestMinError(t *testing.T) {
- r := Min(10)
- assert.Equal(t, "must be no less than 10", r.message)
-
- r.Error("123")
- assert.Equal(t, "123", r.message)
-}
-
-func TestMax(t *testing.T) {
- date0 := time.Time{}
- date20000101 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
- date20001201 := time.Date(2000, 12, 1, 0, 0, 0, 0, time.UTC)
- date20000601 := time.Date(2000, 6, 1, 0, 0, 0, 0, time.UTC)
-
- tests := []struct {
- tag string
- threshold interface{}
- exclusive bool
- value interface{}
- err string
- }{
- // int cases
- {"t1.1", 2, false, 2, ""},
- {"t1.2", 2, false, 1, ""},
- {"t1.3", 2, false, 3, "must be no greater than 2"},
- {"t1.4", 2, false, 0, ""},
- {"t1.5", 2, true, 2, "must be less than 2"},
- {"t1.6", 2, false, "1", "cannot convert string to int64"},
- {"t1.7", "1", false, 1, "type not supported: string"},
- // uint cases
- {"t2.1", uint(2), false, uint(2), ""},
- {"t2.2", uint(2), false, uint(1), ""},
- {"t2.3", uint(2), false, uint(3), "must be no greater than 2"},
- {"t2.4", uint(2), false, uint(0), ""},
- {"t2.5", uint(2), true, uint(2), "must be less than 2"},
- {"t2.6", uint(2), false, "1", "cannot convert string to uint64"},
- // float cases
- {"t3.1", float64(2), false, float64(2), ""},
- {"t3.2", float64(2), false, float64(1), ""},
- {"t3.3", float64(2), false, float64(3), "must be no greater than 2"},
- {"t3.4", float64(2), false, float64(0), ""},
- {"t3.5", float64(2), true, float64(2), "must be less than 2"},
- {"t3.6", float64(2), false, "1", "cannot convert string to float64"},
- // Time cases
- {"t4.1", date20000601, false, date20000601, ""},
- {"t4.2", date20000601, false, date20000101, ""},
- {"t4.3", date20000601, false, date20001201, "must be no greater than 2000-06-01 00:00:00 +0000 UTC"},
- {"t4.4", date20000601, false, date0, ""},
- {"t4.5", date20000601, true, date20000601, "must be less than 2000-06-01 00:00:00 +0000 UTC"},
- {"t4.6", date20000601, true, 1, "cannot convert int to time.Time"},
- }
-
- for _, test := range tests {
- r := Max(test.threshold)
- if test.exclusive {
- r.Exclusive()
- }
- err := r.Validate(test.value)
- assertError(t, test.err, err, test.tag)
- }
-}
-
-func TestMaxError(t *testing.T) {
- r := Max(10)
- assert.Equal(t, "must be no greater than 10", r.message)
-
- r.Error("123")
- assert.Equal(t, "123", r.message)
-}
diff --git a/vendor/github.com/go-ozzo/ozzo-validation/not_nil.go b/vendor/github.com/go-ozzo/ozzo-validation/not_nil.go
deleted file mode 100644
index 6cfca12..0000000
--- a/vendor/github.com/go-ozzo/ozzo-validation/not_nil.go
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright 2016 Qiang Xue. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package validation
-
-import "errors"
-
-// NotNil is a validation rule that checks if a value is not nil.
-// NotNil only handles types including interface, pointer, slice, and map.
-// All other types are considered valid.
-var NotNil = ¬NilRule{message: "is required"}
-
-type notNilRule struct {
- message string
-}
-
-// Validate checks if the given value is valid or not.
-func (r *notNilRule) Validate(value interface{}) error {
- _, isNil := Indirect(value)
- if isNil {
- return errors.New(r.message)
- }
- return nil
-}
-
-// Error sets the error message for the rule.
-func (r *notNilRule) Error(message string) *notNilRule {
- return ¬NilRule{
- message: message,
- }
-}
diff --git a/vendor/github.com/go-ozzo/ozzo-validation/not_nil_test.go b/vendor/github.com/go-ozzo/ozzo-validation/not_nil_test.go
deleted file mode 100644
index 4821da5..0000000
--- a/vendor/github.com/go-ozzo/ozzo-validation/not_nil_test.go
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright 2016 Qiang Xue. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package validation
-
-import (
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-type MyInterface interface {
- Hello()
-}
-
-func TestNotNil(t *testing.T) {
- var v1 []int
- var v2 map[string]int
- var v3 *int
- var v4 interface{}
- var v5 MyInterface
- tests := []struct {
- tag string
- value interface{}
- err string
- }{
- {"t1", v1, "is required"},
- {"t2", v2, "is required"},
- {"t3", v3, "is required"},
- {"t4", v4, "is required"},
- {"t5", v5, "is required"},
- {"t6", "", ""},
- {"t7", 0, ""},
- }
-
- for _, test := range tests {
- r := NotNil
- err := r.Validate(test.value)
- assertError(t, test.err, err, test.tag)
- }
-}
-
-func Test_notNilRule_Error(t *testing.T) {
- r := NotNil
- assert.Equal(t, "is required", r.message)
- r2 := r.Error("123")
- assert.Equal(t, "is required", r.message)
- assert.Equal(t, "123", r2.message)
-}
diff --git a/vendor/github.com/go-ozzo/ozzo-validation/required.go b/vendor/github.com/go-ozzo/ozzo-validation/required.go
deleted file mode 100644
index ef9558e..0000000
--- a/vendor/github.com/go-ozzo/ozzo-validation/required.go
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright 2016 Qiang Xue. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package validation
-
-import "errors"
-
-// Required is a validation rule that checks if a value is not empty.
-// A value is considered not empty if
-// - integer, float: not zero
-// - bool: true
-// - string, array, slice, map: len() > 0
-// - interface, pointer: not nil and the referenced value is not empty
-// - any other types
-var Required = &requiredRule{message: "cannot be blank", skipNil: false}
-
-// NilOrNotEmpty checks if a value is a nil pointer or a value that is not empty.
-// NilOrNotEmpty differs from Required in that it treats a nil pointer as valid.
-var NilOrNotEmpty = &requiredRule{message: "cannot be blank", skipNil: true}
-
-type requiredRule struct {
- message string
- skipNil bool
-}
-
-// Validate checks if the given value is valid or not.
-func (v *requiredRule) Validate(value interface{}) error {
- value, isNil := Indirect(value)
- if v.skipNil && !isNil && IsEmpty(value) || !v.skipNil && (isNil || IsEmpty(value)) {
- return errors.New(v.message)
- }
- return nil
-}
-
-// Error sets the error message for the rule.
-func (v *requiredRule) Error(message string) *requiredRule {
- return &requiredRule{
- message: message,
- skipNil: v.skipNil,
- }
-}
diff --git a/vendor/github.com/go-ozzo/ozzo-validation/required_test.go b/vendor/github.com/go-ozzo/ozzo-validation/required_test.go
deleted file mode 100644
index c85e412..0000000
--- a/vendor/github.com/go-ozzo/ozzo-validation/required_test.go
+++ /dev/null
@@ -1,75 +0,0 @@
-// Copyright 2016 Qiang Xue. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package validation
-
-import (
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-func TestRequired(t *testing.T) {
- s1 := "123"
- s2 := ""
- tests := []struct {
- tag string
- value interface{}
- err string
- }{
- {"t1", 123, ""},
- {"t2", "", "cannot be blank"},
- {"t3", &s1, ""},
- {"t4", &s2, "cannot be blank"},
- {"t5", nil, "cannot be blank"},
- }
-
- for _, test := range tests {
- r := Required
- err := r.Validate(test.value)
- assertError(t, test.err, err, test.tag)
- }
-}
-
-func TestNilOrNotEmpty(t *testing.T) {
- s1 := "123"
- s2 := ""
- tests := []struct {
- tag string
- value interface{}
- err string
- }{
- {"t1", 123, ""},
- {"t2", "", "cannot be blank"},
- {"t3", &s1, ""},
- {"t4", &s2, "cannot be blank"},
- {"t5", nil, ""},
- }
-
- for _, test := range tests {
- r := NilOrNotEmpty
- err := r.Validate(test.value)
- assertError(t, test.err, err, test.tag)
- }
-}
-
-func Test_requiredRule_Error(t *testing.T) {
- r := Required
- assert.Equal(t, "cannot be blank", r.message)
- assert.False(t, r.skipNil)
- r2 := r.Error("123")
- assert.Equal(t, "cannot be blank", r.message)
- assert.False(t, r.skipNil)
- assert.Equal(t, "123", r2.message)
- assert.False(t, r2.skipNil)
-
- r = NilOrNotEmpty
- assert.Equal(t, "cannot be blank", r.message)
- assert.True(t, r.skipNil)
- r2 = r.Error("123")
- assert.Equal(t, "cannot be blank", r.message)
- assert.True(t, r.skipNil)
- assert.Equal(t, "123", r2.message)
- assert.True(t, r2.skipNil)
-}
diff --git a/vendor/github.com/go-ozzo/ozzo-validation/string.go b/vendor/github.com/go-ozzo/ozzo-validation/string.go
deleted file mode 100644
index e8f2a5e..0000000
--- a/vendor/github.com/go-ozzo/ozzo-validation/string.go
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright 2016 Qiang Xue. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package validation
-
-import "errors"
-
-type stringValidator func(string) bool
-
-// StringRule is a rule that checks a string variable using a specified stringValidator.
-type StringRule struct {
- validate stringValidator
- message string
-}
-
-// NewStringRule creates a new validation rule using a function that takes a string value and returns a bool.
-// The rule returned will use the function to check if a given string or byte slice is valid or not.
-// An empty value is considered to be valid. Please use the Required rule to make sure a value is not empty.
-func NewStringRule(validator stringValidator, message string) *StringRule {
- return &StringRule{
- validate: validator,
- message: message,
- }
-}
-
-// Error sets the error message for the rule.
-func (v *StringRule) Error(message string) *StringRule {
- return NewStringRule(v.validate, message)
-}
-
-// Validate checks if the given value is valid or not.
-func (v *StringRule) Validate(value interface{}) error {
- value, isNil := Indirect(value)
- if isNil || IsEmpty(value) {
- return nil
- }
-
- str, err := EnsureString(value)
- if err != nil {
- return err
- }
-
- if v.validate(str) {
- return nil
- }
- return errors.New(v.message)
-}
diff --git a/vendor/github.com/go-ozzo/ozzo-validation/string_test.go b/vendor/github.com/go-ozzo/ozzo-validation/string_test.go
deleted file mode 100644
index 80da228..0000000
--- a/vendor/github.com/go-ozzo/ozzo-validation/string_test.go
+++ /dev/null
@@ -1,106 +0,0 @@
-// Copyright 2016 Qiang Xue. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package validation
-
-import (
- "database/sql"
- "testing"
-
- "reflect"
-
- "github.com/stretchr/testify/assert"
-)
-
-func validateMe(s string) bool {
- return s == "me"
-}
-
-func TestNewStringRule(t *testing.T) {
- v := NewStringRule(validateMe, "abc")
- assert.NotNil(t, v.validate)
- assert.Equal(t, "abc", v.message)
-}
-
-func TestStringValidator_Error(t *testing.T) {
- v := NewStringRule(validateMe, "abc")
- assert.Equal(t, "abc", v.message)
- v2 := v.Error("correct")
- assert.Equal(t, "correct", v2.message)
- assert.Equal(t, "abc", v.message)
-}
-
-func TestStringValidator_Validate(t *testing.T) {
- v := NewStringRule(validateMe, "wrong")
-
- value := "me"
-
- err := v.Validate(value)
- assert.Nil(t, err)
-
- err = v.Validate(&value)
- assert.Nil(t, err)
-
- value = ""
-
- err = v.Validate(value)
- assert.Nil(t, err)
-
- err = v.Validate(&value)
- assert.Nil(t, err)
-
- nullValue := sql.NullString{String: "me", Valid: true}
- err = v.Validate(nullValue)
- assert.Nil(t, err)
-
- nullValue = sql.NullString{String: "", Valid: true}
- err = v.Validate(nullValue)
- assert.Nil(t, err)
-
- var s *string
- err = v.Validate(s)
- assert.Nil(t, err)
-
- err = v.Validate("not me")
- if assert.NotNil(t, err) {
- assert.Equal(t, "wrong", err.Error())
- }
-
- err = v.Validate(100)
- if assert.NotNil(t, err) {
- assert.NotEqual(t, "wrong", err.Error())
- }
-
- v2 := v.Error("Wrong!")
- err = v2.Validate("not me")
- if assert.NotNil(t, err) {
- assert.Equal(t, "Wrong!", err.Error())
- }
-}
-
-func TestGetErrorFieldName(t *testing.T) {
- type A struct {
- T0 string
- T1 string `json:"t1"`
- T2 string `json:"t2,omitempty"`
- T3 string `json:",omitempty"`
- T4 string `json:"t4,x1,omitempty"`
- }
- tests := []struct {
- tag string
- field string
- name string
- }{
- {"t1", "T0", "T0"},
- {"t2", "T1", "t1"},
- {"t3", "T2", "t2"},
- {"t4", "T3", "T3"},
- {"t5", "T4", "t4"},
- }
- a := reflect.TypeOf(A{})
- for _, test := range tests {
- field, _ := a.FieldByName(test.field)
- assert.Equal(t, test.name, getErrorFieldName(&field), test.tag)
- }
-}
diff --git a/vendor/github.com/go-ozzo/ozzo-validation/struct.go b/vendor/github.com/go-ozzo/ozzo-validation/struct.go
deleted file mode 100644
index 2d3a19c..0000000
--- a/vendor/github.com/go-ozzo/ozzo-validation/struct.go
+++ /dev/null
@@ -1,154 +0,0 @@
-// Copyright 2016 Qiang Xue. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package validation
-
-import (
- "errors"
- "fmt"
- "reflect"
- "strings"
-)
-
-var (
- // StructPointerError is the error that a struct being validated is not specified as a pointer.
- StructPointerError = errors.New("only a pointer to a struct can be validated")
-)
-
-type (
- // FieldPointerError is the error that a field is not specified as a pointer.
- FieldPointerError int
-
- // FieldNotFoundError is the error that a field cannot be found in the struct.
- FieldNotFoundError int
-
- // FieldRules represents a rule set associated with a struct field.
- FieldRules struct {
- fieldPtr interface{}
- rules []Rule
- }
-)
-
-// Error returns the error string of FieldPointerError.
-func (e FieldPointerError) Error() string {
- return fmt.Sprintf("field #%v must be specified as a pointer", int(e))
-}
-
-// Error returns the error string of FieldNotFoundError.
-func (e FieldNotFoundError) Error() string {
- return fmt.Sprintf("field #%v cannot be found in the struct", int(e))
-}
-
-// ValidateStruct validates a struct by checking the specified struct fields against the corresponding validation rules.
-// Note that the struct being validated must be specified as a pointer to it. If the pointer is nil, it is considered valid.
-// Use Field() to specify struct fields that need to be validated. Each Field() call specifies a single field which
-// should be specified as a pointer to the field. A field can be associated with multiple rules.
-// For example,
-//
-// value := struct {
-// Name string
-// Value string
-// }{"name", "demo"}
-// err := validation.ValidateStruct(&value,
-// validation.Field(&a.Name, validation.Required),
-// validation.Field(&a.Value, validation.Required, validation.Length(5, 10)),
-// )
-// fmt.Println(err)
-// // Value: the length must be between 5 and 10.
-//
-// An error will be returned if validation fails.
-func ValidateStruct(structPtr interface{}, fields ...*FieldRules) error {
- value := reflect.ValueOf(structPtr)
- if value.Kind() != reflect.Ptr || !value.IsNil() && value.Elem().Kind() != reflect.Struct {
- // must be a pointer to a struct
- return NewInternalError(StructPointerError)
- }
- if value.IsNil() {
- // treat a nil struct pointer as valid
- return nil
- }
- value = value.Elem()
-
- errs := Errors{}
-
- for i, fr := range fields {
- fv := reflect.ValueOf(fr.fieldPtr)
- if fv.Kind() != reflect.Ptr {
- return NewInternalError(FieldPointerError(i))
- }
- ft := findStructField(value, fv)
- if ft == nil {
- return NewInternalError(FieldNotFoundError(i))
- }
- if err := Validate(fv.Elem().Interface(), fr.rules...); err != nil {
- if ie, ok := err.(InternalError); ok && ie.InternalError() != nil{
- return err
- }
- if ft.Anonymous {
- // merge errors from anonymous struct field
- if es, ok := err.(Errors); ok {
- for name, value := range es {
- errs[name] = value
- }
- continue
- }
- }
- errs[getErrorFieldName(ft)] = err
- }
- }
-
- if len(errs) > 0 {
- return errs
- }
- return nil
-}
-
-// Field specifies a struct field and the corresponding validation rules.
-// The struct field must be specified as a pointer to it.
-func Field(fieldPtr interface{}, rules ...Rule) *FieldRules {
- return &FieldRules{
- fieldPtr: fieldPtr,
- rules: rules,
- }
-}
-
-// findStructField looks for a field in the given struct.
-// The field being looked for should be a pointer to the actual struct field.
-// If found, the field info will be returned. Otherwise, nil will be returned.
-func findStructField(structValue reflect.Value, fieldValue reflect.Value) *reflect.StructField {
- ptr := fieldValue.Pointer()
- for i := structValue.NumField() - 1; i >= 0; i-- {
- sf := structValue.Type().Field(i)
- if ptr == structValue.Field(i).UnsafeAddr() {
- // do additional type comparison because it's possible that the address of
- // an embedded struct is the same as the first field of the embedded struct
- if sf.Type == fieldValue.Elem().Type() {
- return &sf
- }
- }
- if sf.Anonymous {
- // delve into anonymous struct to look for the field
- fi := structValue.Field(i)
- if sf.Type.Kind() == reflect.Ptr {
- fi = fi.Elem()
- }
- if fi.Kind() == reflect.Struct {
- if f := findStructField(fi, fieldValue); f != nil {
- return f
- }
- }
- }
- }
- return nil
-}
-
-// getErrorFieldName returns the name that should be used to represent the validation error of a struct field.
-func getErrorFieldName(f *reflect.StructField) string {
- if tag := f.Tag.Get(ErrorTag); tag != "" {
- if cps := strings.SplitN(tag, ",", 2); cps[0] != "" {
- return cps[0]
- }
- }
- return f.Name
-}
diff --git a/vendor/github.com/go-ozzo/ozzo-validation/struct_test.go b/vendor/github.com/go-ozzo/ozzo-validation/struct_test.go
deleted file mode 100644
index 97c7a4f..0000000
--- a/vendor/github.com/go-ozzo/ozzo-validation/struct_test.go
+++ /dev/null
@@ -1,137 +0,0 @@
-// Copyright 2016 Qiang Xue. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package validation
-
-import (
- "reflect"
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-type Struct1 struct {
- Field1 int
- Field2 *int
- Field3 []int
- Field4 [4]int
- field5 int
- Struct2
- S1 *Struct2
- S2 Struct2
-}
-
-type Struct2 struct {
- Field21 string
- Field22 string
-}
-
-type Struct3 struct {
- *Struct2
- S1 string
-}
-
-func TestFindStructField(t *testing.T) {
- var s1 Struct1
- v1 := reflect.ValueOf(&s1).Elem()
- assert.NotNil(t, findStructField(v1, reflect.ValueOf(&s1.Field1)))
- assert.Nil(t, findStructField(v1, reflect.ValueOf(s1.Field2)))
- assert.NotNil(t, findStructField(v1, reflect.ValueOf(&s1.Field2)))
- assert.Nil(t, findStructField(v1, reflect.ValueOf(s1.Field3)))
- assert.NotNil(t, findStructField(v1, reflect.ValueOf(&s1.Field3)))
- assert.NotNil(t, findStructField(v1, reflect.ValueOf(&s1.Field4)))
- assert.NotNil(t, findStructField(v1, reflect.ValueOf(&s1.field5)))
- assert.NotNil(t, findStructField(v1, reflect.ValueOf(&s1.Struct2)))
- assert.Nil(t, findStructField(v1, reflect.ValueOf(s1.S1)))
- assert.NotNil(t, findStructField(v1, reflect.ValueOf(&s1.S1)))
- assert.NotNil(t, findStructField(v1, reflect.ValueOf(&s1.Field21)))
- assert.NotNil(t, findStructField(v1, reflect.ValueOf(&s1.Field22)))
- assert.NotNil(t, findStructField(v1, reflect.ValueOf(&s1.Struct2.Field22)))
- s2 := reflect.ValueOf(&s1.Struct2).Elem()
- assert.NotNil(t, findStructField(s2, reflect.ValueOf(&s1.Field21)))
- assert.NotNil(t, findStructField(s2, reflect.ValueOf(&s1.Struct2.Field21)))
- assert.NotNil(t, findStructField(s2, reflect.ValueOf(&s1.Struct2.Field22)))
- s3 := Struct3{
- Struct2: &Struct2{},
- }
- v3 := reflect.ValueOf(&s3).Elem()
- assert.NotNil(t, findStructField(v3, reflect.ValueOf(&s3.Struct2)))
- assert.NotNil(t, findStructField(v3, reflect.ValueOf(&s3.Field21)))
-}
-
-func TestValidateStruct(t *testing.T) {
- var m0 *Model1
- m1 := Model1{A: "abc", B: "xyz", c: "abc", G: "xyz"}
- m2 := Model1{E: String123("xyz")}
- m3 := Model2{}
- m4 := Model2{M3: Model3{A: "abc"}, Model3: Model3{A: "abc"}}
- m5 := Model2{Model3: Model3{A: "internal"}}
- tests := []struct {
- tag string
- model interface{}
- rules []*FieldRules
- err string
- }{
- // empty rules
- {"t1.1", &m1, []*FieldRules{}, ""},
- {"t1.2", &m1, []*FieldRules{Field(&m1.A), Field(&m1.B)}, ""},
- // normal rules
- {"t2.1", &m1, []*FieldRules{Field(&m1.A, &validateAbc{}), Field(&m1.B, &validateXyz{})}, ""},
- {"t2.2", &m1, []*FieldRules{Field(&m1.A, &validateXyz{}), Field(&m1.B, &validateAbc{})}, "A: error xyz; B: error abc."},
- {"t2.3", &m1, []*FieldRules{Field(&m1.A, &validateXyz{}), Field(&m1.c, &validateXyz{})}, "A: error xyz; c: error xyz."},
- {"t2.4", &m1, []*FieldRules{Field(&m1.D, Length(0, 5))}, ""},
- {"t2.5", &m1, []*FieldRules{Field(&m1.F, Length(0, 5))}, ""},
- // non-struct pointer
- {"t3.1", m1, []*FieldRules{}, StructPointerError.Error()},
- {"t3.2", nil, []*FieldRules{}, StructPointerError.Error()},
- {"t3.3", m0, []*FieldRules{}, ""},
- {"t3.4", &m0, []*FieldRules{}, StructPointerError.Error()},
- // invalid field spec
- {"t4.1", &m1, []*FieldRules{Field(m1)}, FieldPointerError(0).Error()},
- {"t4.2", &m1, []*FieldRules{Field(&m1)}, FieldNotFoundError(0).Error()},
- // struct tag
- {"t5.1", &m1, []*FieldRules{Field(&m1.G, &validateAbc{})}, "g: error abc."},
- // validatable field
- {"t6.1", &m2, []*FieldRules{Field(&m2.E)}, "E: error 123."},
- {"t6.2", &m2, []*FieldRules{Field(&m2.E, Skip)}, ""},
- // Required, NotNil
- {"t7.1", &m2, []*FieldRules{Field(&m2.F, Required)}, "F: cannot be blank."},
- {"t7.2", &m2, []*FieldRules{Field(&m2.F, NotNil)}, "F: is required."},
- {"t7.3", &m2, []*FieldRules{Field(&m2.E, Required, Skip)}, ""},
- {"t7.4", &m2, []*FieldRules{Field(&m2.E, NotNil, Skip)}, ""},
- // embedded structs
- {"t8.1", &m3, []*FieldRules{Field(&m3.M3, Skip)}, ""},
- {"t8.2", &m3, []*FieldRules{Field(&m3.M3)}, "M3: (A: error abc.)."},
- {"t8.3", &m3, []*FieldRules{Field(&m3.Model3, Skip)}, ""},
- {"t8.4", &m3, []*FieldRules{Field(&m3.Model3)}, "A: error abc."},
- {"t8.5", &m4, []*FieldRules{Field(&m4.M3)}, ""},
- {"t8.6", &m4, []*FieldRules{Field(&m4.Model3)}, ""},
- {"t8.7", &m3, []*FieldRules{Field(&m3.A, Required), Field(&m3.B, Required)}, "A: cannot be blank; B: cannot be blank."},
- {"t8.8", &m3, []*FieldRules{Field(&m4.A, Required)}, "field #0 cannot be found in the struct"},
- // internal error
- {"t9.1", &m5, []*FieldRules{Field(&m5.A, &validateAbc{}), Field(&m5.B, Required), Field(&m5.A, &validateInternalError{})}, "error internal"},
- }
- for _, test := range tests {
- err := ValidateStruct(test.model, test.rules...)
- assertError(t, test.err, err, test.tag)
- }
-
- // embedded struct
- err := Validate(&m3)
- if assert.NotNil(t, err) {
- assert.Equal(t, "A: error abc.", err.Error())
- }
-
- a := struct {
- Name string
- Value string
- }{"name", "demo"}
- err = ValidateStruct(&a,
- Field(&a.Name, Required),
- Field(&a.Value, Required, Length(5, 10)),
- )
- if assert.NotNil(t, err) {
- assert.Equal(t, "Value: the length must be between 5 and 10.", err.Error())
- }
-}
diff --git a/vendor/github.com/go-ozzo/ozzo-validation/util.go b/vendor/github.com/go-ozzo/ozzo-validation/util.go
deleted file mode 100644
index 2c1c588..0000000
--- a/vendor/github.com/go-ozzo/ozzo-validation/util.go
+++ /dev/null
@@ -1,157 +0,0 @@
-// Copyright 2016 Qiang Xue. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package validation
-
-import (
- "database/sql/driver"
- "errors"
- "fmt"
- "reflect"
-)
-
-var (
- bytesType = reflect.TypeOf([]byte(nil))
- valuerType = reflect.TypeOf((*driver.Valuer)(nil)).Elem()
-)
-
-// EnsureString ensures the given value is a string.
-// If the value is a byte slice, it will be typecast into a string.
-// An error is returned otherwise.
-func EnsureString(value interface{}) (string, error) {
- v := reflect.ValueOf(value)
- if v.Kind() == reflect.String {
- return v.String(), nil
- }
- if v.Type() == bytesType {
- return string(v.Interface().([]byte)), nil
- }
- return "", errors.New("must be either a string or byte slice")
-}
-
-// StringOrBytes typecasts a value into a string or byte slice.
-// Boolean flags are returned to indicate if the typecasting succeeds or not.
-func StringOrBytes(value interface{}) (isString bool, str string, isBytes bool, bs []byte) {
- v := reflect.ValueOf(value)
- if v.Kind() == reflect.String {
- str = v.String()
- isString = true
- } else if v.Kind() == reflect.Slice && v.Type() == bytesType {
- bs = v.Interface().([]byte)
- isBytes = true
- }
- return
-}
-
-// LengthOfValue returns the length of a value that is a string, slice, map, or array.
-// An error is returned for all other types.
-func LengthOfValue(value interface{}) (int, error) {
- v := reflect.ValueOf(value)
- switch v.Kind() {
- case reflect.String, reflect.Slice, reflect.Map, reflect.Array:
- return v.Len(), nil
- }
- return 0, fmt.Errorf("cannot get the length of %v", v.Kind())
-}
-
-// ToInt converts the given value to an int64.
-// An error is returned for all incompatible types.
-func ToInt(value interface{}) (int64, error) {
- v := reflect.ValueOf(value)
- switch v.Kind() {
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- return v.Int(), nil
- }
- return 0, fmt.Errorf("cannot convert %v to int64", v.Kind())
-}
-
-// ToUint converts the given value to an uint64.
-// An error is returned for all incompatible types.
-func ToUint(value interface{}) (uint64, error) {
- v := reflect.ValueOf(value)
- switch v.Kind() {
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
- return v.Uint(), nil
- }
- return 0, fmt.Errorf("cannot convert %v to uint64", v.Kind())
-}
-
-// ToFloat converts the given value to a float64.
-// An error is returned for all incompatible types.
-func ToFloat(value interface{}) (float64, error) {
- v := reflect.ValueOf(value)
- switch v.Kind() {
- case reflect.Float32, reflect.Float64:
- return v.Float(), nil
- }
- return 0, fmt.Errorf("cannot convert %v to float64", v.Kind())
-}
-
-// IsEmpty checks if a value is empty or not.
-// A value is considered empty if
-// - integer, float: zero
-// - bool: false
-// - string, array: len() == 0
-// - slice, map: nil or len() == 0
-// - interface, pointer: nil or the referenced value is empty
-func IsEmpty(value interface{}) bool {
- v := reflect.ValueOf(value)
- switch v.Kind() {
- case reflect.String, reflect.Array, reflect.Map, reflect.Slice:
- return v.Len() == 0
- case reflect.Bool:
- return !v.Bool()
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- return v.Int() == 0
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
- return v.Uint() == 0
- case reflect.Float32, reflect.Float64:
- return v.Float() == 0
- case reflect.Invalid:
- return true
- case reflect.Interface, reflect.Ptr:
- if v.IsNil() {
- return true
- }
- return IsEmpty(v.Elem().Interface())
- }
-
- return false
-}
-
-// Indirect returns the value that the given interface or pointer references to.
-// If the value implements driver.Valuer, it will deal with the value returned by
-// the Value() method instead. A boolean value is also returned to indicate if
-// the value is nil or not (only applicable to interface, pointer, map, and slice).
-// If the value is neither an interface nor a pointer, it will be returned back.
-func Indirect(value interface{}) (interface{}, bool) {
- rv := reflect.ValueOf(value)
- kind := rv.Kind()
- switch kind {
- case reflect.Invalid:
- return nil, true
- case reflect.Ptr, reflect.Interface:
- if rv.IsNil() {
- return nil, true
- }
- return Indirect(rv.Elem().Interface())
- case reflect.Slice, reflect.Map, reflect.Func, reflect.Chan:
- if rv.IsNil() {
- return nil, true
- }
- }
-
- if rv.Type().Implements(valuerType) {
- return indirectValuer(value.(driver.Valuer))
- }
-
- return value, false
-}
-
-func indirectValuer(valuer driver.Valuer) (interface{}, bool) {
- if value, err := valuer.Value(); value != nil && err == nil {
- return Indirect(value)
- }
- return nil, true
-}
diff --git a/vendor/github.com/go-ozzo/ozzo-validation/util_test.go b/vendor/github.com/go-ozzo/ozzo-validation/util_test.go
deleted file mode 100644
index 28a6d51..0000000
--- a/vendor/github.com/go-ozzo/ozzo-validation/util_test.go
+++ /dev/null
@@ -1,293 +0,0 @@
-// Copyright 2016 Qiang Xue. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package validation
-
-import (
- "testing"
-
- "database/sql"
-
- "github.com/stretchr/testify/assert"
-)
-
-func TestEnsureString(t *testing.T) {
- str := "abc"
- bytes := []byte("abc")
-
- tests := []struct {
- tag string
- value interface{}
- expected string
- hasError bool
- }{
- {"t1", "abc", "abc", false},
- {"t2", &str, "", true},
- {"t3", bytes, "abc", false},
- {"t4", &bytes, "", true},
- {"t5", 100, "", true},
- }
- for _, test := range tests {
- s, err := EnsureString(test.value)
- if test.hasError {
- assert.NotNil(t, err, test.tag)
- } else {
- assert.Nil(t, err, test.tag)
- assert.Equal(t, test.expected, s, test.tag)
- }
- }
-}
-
-type MyString string
-
-func TestStringOrBytes(t *testing.T) {
- str := "abc"
- bytes := []byte("abc")
- var str2 string
- var bytes2 []byte
- var str3 MyString = "abc"
- var str4 *string
-
- tests := []struct {
- tag string
- value interface{}
- str string
- bs []byte
- isString bool
- isBytes bool
- }{
- {"t1", str, "abc", nil, true, false},
- {"t2", &str, "", nil, false, false},
- {"t3", bytes, "", []byte("abc"), false, true},
- {"t4", &bytes, "", nil, false, false},
- {"t5", 100, "", nil, false, false},
- {"t6", str2, "", nil, true, false},
- {"t7", &str2, "", nil, false, false},
- {"t8", bytes2, "", nil, false, true},
- {"t9", &bytes2, "", nil, false, false},
- {"t10", str3, "abc", nil, true, false},
- {"t11", &str3, "", nil, false, false},
- {"t12", str4, "", nil, false, false},
- }
- for _, test := range tests {
- isString, str, isBytes, bs := StringOrBytes(test.value)
- assert.Equal(t, test.str, str, test.tag)
- assert.Equal(t, test.bs, bs, test.tag)
- assert.Equal(t, test.isString, isString, test.tag)
- assert.Equal(t, test.isBytes, isBytes, test.tag)
- }
-}
-
-func TestLengthOfValue(t *testing.T) {
- var a [3]int
-
- tests := []struct {
- tag string
- value interface{}
- length int
- err string
- }{
- {"t1", "abc", 3, ""},
- {"t2", []int{1, 2}, 2, ""},
- {"t3", map[string]int{"A": 1, "B": 2}, 2, ""},
- {"t4", a, 3, ""},
- {"t5", &a, 0, "cannot get the length of ptr"},
- {"t6", 123, 0, "cannot get the length of int"},
- }
-
- for _, test := range tests {
- l, err := LengthOfValue(test.value)
- assert.Equal(t, test.length, l, test.tag)
- assertError(t, test.err, err, test.tag)
- }
-}
-
-func TestToInt(t *testing.T) {
- var a int
-
- tests := []struct {
- tag string
- value interface{}
- result int64
- err string
- }{
- {"t1", 1, 1, ""},
- {"t2", int8(1), 1, ""},
- {"t3", int16(1), 1, ""},
- {"t4", int32(1), 1, ""},
- {"t5", int64(1), 1, ""},
- {"t6", &a, 0, "cannot convert ptr to int64"},
- {"t7", uint(1), 0, "cannot convert uint to int64"},
- {"t8", float64(1), 0, "cannot convert float64 to int64"},
- {"t9", "abc", 0, "cannot convert string to int64"},
- {"t10", []int{1, 2}, 0, "cannot convert slice to int64"},
- {"t11", map[string]int{"A": 1}, 0, "cannot convert map to int64"},
- }
-
- for _, test := range tests {
- l, err := ToInt(test.value)
- assert.Equal(t, test.result, l, test.tag)
- assertError(t, test.err, err, test.tag)
- }
-}
-
-func TestToUint(t *testing.T) {
- var a int
- var b uint
-
- tests := []struct {
- tag string
- value interface{}
- result uint64
- err string
- }{
- {"t1", uint(1), 1, ""},
- {"t2", uint8(1), 1, ""},
- {"t3", uint16(1), 1, ""},
- {"t4", uint32(1), 1, ""},
- {"t5", uint64(1), 1, ""},
- {"t6", 1, 0, "cannot convert int to uint64"},
- {"t7", &a, 0, "cannot convert ptr to uint64"},
- {"t8", &b, 0, "cannot convert ptr to uint64"},
- {"t9", float64(1), 0, "cannot convert float64 to uint64"},
- {"t10", "abc", 0, "cannot convert string to uint64"},
- {"t11", []int{1, 2}, 0, "cannot convert slice to uint64"},
- {"t12", map[string]int{"A": 1}, 0, "cannot convert map to uint64"},
- }
-
- for _, test := range tests {
- l, err := ToUint(test.value)
- assert.Equal(t, test.result, l, test.tag)
- assertError(t, test.err, err, test.tag)
- }
-}
-
-func TestToFloat(t *testing.T) {
- var a int
- var b uint
-
- tests := []struct {
- tag string
- value interface{}
- result float64
- err string
- }{
- {"t1", float32(1), 1, ""},
- {"t2", float64(1), 1, ""},
- {"t3", 1, 0, "cannot convert int to float64"},
- {"t4", uint(1), 0, "cannot convert uint to float64"},
- {"t5", &a, 0, "cannot convert ptr to float64"},
- {"t6", &b, 0, "cannot convert ptr to float64"},
- {"t7", "abc", 0, "cannot convert string to float64"},
- {"t8", []int{1, 2}, 0, "cannot convert slice to float64"},
- {"t9", map[string]int{"A": 1}, 0, "cannot convert map to float64"},
- }
-
- for _, test := range tests {
- l, err := ToFloat(test.value)
- assert.Equal(t, test.result, l, test.tag)
- assertError(t, test.err, err, test.tag)
- }
-}
-
-func TestIsEmpty(t *testing.T) {
- var s1 string
- var s2 string = "a"
- var s3 *string
- s4 := struct{}{}
- tests := []struct {
- tag string
- value interface{}
- empty bool
- }{
- // nil
- {"t0", nil, true},
- // string
- {"t1.1", "", true},
- {"t1.2", "1", false},
- {"t1.3", MyString(""), true},
- {"t1.4", MyString("1"), false},
- // slice
- {"t2.1", []byte(""), true},
- {"t2.2", []byte("1"), false},
- // map
- {"t3.1", map[string]int{}, true},
- {"t3.2", map[string]int{"a": 1}, false},
- // bool
- {"t4.1", false, true},
- {"t4.2", true, false},
- // int
- {"t5.1", int(0), true},
- {"t5.2", int8(0), true},
- {"t5.3", int16(0), true},
- {"t5.4", int32(0), true},
- {"t5.5", int64(0), true},
- {"t5.6", int(1), false},
- {"t5.7", int8(1), false},
- {"t5.8", int16(1), false},
- {"t5.9", int32(1), false},
- {"t5.10", int64(1), false},
- // uint
- {"t6.1", uint(0), true},
- {"t6.2", uint8(0), true},
- {"t6.3", uint16(0), true},
- {"t6.4", uint32(0), true},
- {"t6.5", uint64(0), true},
- {"t6.6", uint(1), false},
- {"t6.7", uint8(1), false},
- {"t6.8", uint16(1), false},
- {"t6.9", uint32(1), false},
- {"t6.10", uint64(1), false},
- // float
- {"t7.1", float32(0), true},
- {"t7.2", float64(0), true},
- {"t7.3", float32(1), false},
- {"t7.4", float64(1), false},
- // interface, ptr
- {"t8.1", &s1, true},
- {"t8.2", &s2, false},
- {"t8.3", s3, true},
- // struct
- {"t9.1", s4, false},
- {"t9.2", &s4, false},
- }
-
- for _, test := range tests {
- empty := IsEmpty(test.value)
- assert.Equal(t, test.empty, empty, test.tag)
- }
-}
-
-func TestIndirect(t *testing.T) {
- var a int = 100
- var b *int
- var c *sql.NullInt64
-
- tests := []struct {
- tag string
- value interface{}
- result interface{}
- isNil bool
- }{
- {"t1", 100, 100, false},
- {"t2", &a, 100, false},
- {"t3", b, nil, true},
- {"t4", nil, nil, true},
- {"t5", sql.NullInt64{Int64: 0, Valid: false}, nil, true},
- {"t6", sql.NullInt64{Int64: 1, Valid: false}, nil, true},
- {"t7", &sql.NullInt64{Int64: 0, Valid: false}, nil, true},
- {"t8", &sql.NullInt64{Int64: 1, Valid: false}, nil, true},
- {"t9", sql.NullInt64{Int64: 0, Valid: true}, int64(0), false},
- {"t10", sql.NullInt64{Int64: 1, Valid: true}, int64(1), false},
- {"t11", &sql.NullInt64{Int64: 0, Valid: true}, int64(0), false},
- {"t12", &sql.NullInt64{Int64: 1, Valid: true}, int64(1), false},
- {"t13", c, nil, true},
- }
-
- for _, test := range tests {
- result, isNil := Indirect(test.value)
- assert.Equal(t, test.result, result, test.tag)
- assert.Equal(t, test.isNil, isNil, test.tag)
- }
-}
diff --git a/vendor/github.com/go-ozzo/ozzo-validation/validation.go b/vendor/github.com/go-ozzo/ozzo-validation/validation.go
deleted file mode 100644
index 1633258..0000000
--- a/vendor/github.com/go-ozzo/ozzo-validation/validation.go
+++ /dev/null
@@ -1,133 +0,0 @@
-// Copyright 2016 Qiang Xue. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-// Package validation provides configurable and extensible rules for validating data of various types.
-package validation
-
-import (
- "fmt"
- "reflect"
- "strconv"
-)
-
-type (
- // Validatable is the interface indicating the type implementing it supports data validation.
- Validatable interface {
- // Validate validates the data and returns an error if validation fails.
- Validate() error
- }
-
- // Rule represents a validation rule.
- Rule interface {
- // Validate validates a value and returns a value if validation fails.
- Validate(value interface{}) error
- }
-
- // RuleFunc represents a validator function.
- // You may wrap it as a Rule by calling By().
- RuleFunc func(value interface{}) error
-)
-
-var (
- // ErrorTag is the struct tag name used to customize the error field name for a struct field.
- ErrorTag = "json"
-
- // Skip is a special validation rule that indicates all rules following it should be skipped.
- Skip = &skipRule{}
-
- validatableType = reflect.TypeOf((*Validatable)(nil)).Elem()
-)
-
-// Validate validates the given value and returns the validation error, if any.
-//
-// Validate performs validation using the following steps:
-// - validate the value against the rules passed in as parameters
-// - if the value is a map and the map values implement `Validatable`, call `Validate` of every map value
-// - if the value is a slice or array whose values implement `Validatable`, call `Validate` of every element
-func Validate(value interface{}, rules ...Rule) error {
- for _, rule := range rules {
- if _, ok := rule.(*skipRule); ok {
- return nil
- }
- if err := rule.Validate(value); err != nil {
- return err
- }
- }
-
- rv := reflect.ValueOf(value)
- if (rv.Kind() == reflect.Ptr || rv.Kind() == reflect.Interface) && rv.IsNil() {
- return nil
- }
-
- if v, ok := value.(Validatable); ok {
- return v.Validate()
- }
-
- switch rv.Kind() {
- case reflect.Map:
- if rv.Type().Elem().Implements(validatableType) {
- return validateMap(rv)
- }
- case reflect.Slice, reflect.Array:
- if rv.Type().Elem().Implements(validatableType) {
- return validateSlice(rv)
- }
- case reflect.Ptr, reflect.Interface:
- return Validate(rv.Elem().Interface())
- }
-
- return nil
-}
-
-// validateMap validates a map of validatable elements
-func validateMap(rv reflect.Value) error {
- errs := Errors{}
- for _, key := range rv.MapKeys() {
- if mv := rv.MapIndex(key).Interface(); mv != nil {
- if err := mv.(Validatable).Validate(); err != nil {
- errs[fmt.Sprintf("%v", key.Interface())] = err
- }
- }
- }
- if len(errs) > 0 {
- return errs
- }
- return nil
-}
-
-// validateMap validates a slice/array of validatable elements
-func validateSlice(rv reflect.Value) error {
- errs := Errors{}
- l := rv.Len()
- for i := 0; i < l; i++ {
- if ev := rv.Index(i).Interface(); ev != nil {
- if err := ev.(Validatable).Validate(); err != nil {
- errs[strconv.Itoa(i)] = err
- }
- }
- }
- if len(errs) > 0 {
- return errs
- }
- return nil
-}
-
-type skipRule struct{}
-
-func (r *skipRule) Validate(interface{}) error {
- return nil
-}
-
-type inlineRule struct {
- f RuleFunc
-}
-
-func (r *inlineRule) Validate(value interface{}) error {
- return r.f(value)
-}
-
-// By wraps a RuleFunc into a Rule.
-func By(f RuleFunc) Rule {
- return &inlineRule{f}
-}
diff --git a/vendor/github.com/go-ozzo/ozzo-validation/validation_test.go b/vendor/github.com/go-ozzo/ozzo-validation/validation_test.go
deleted file mode 100644
index 27ac6cb..0000000
--- a/vendor/github.com/go-ozzo/ozzo-validation/validation_test.go
+++ /dev/null
@@ -1,145 +0,0 @@
-// Copyright 2016 Qiang Xue. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package validation
-
-import (
- "errors"
- "strings"
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-func TestValidate(t *testing.T) {
- slice := []String123{String123("abc"), String123("123"), String123("xyz")}
- mp := map[string]String123{"c": String123("abc"), "b": String123("123"), "a": String123("xyz")}
- tests := []struct {
- tag string
- value interface{}
- err string
- }{
- {"t1", 123, ""},
- {"t2", String123("123"), ""},
- {"t3", String123("abc"), "error 123"},
- {"t4", []String123{}, ""},
- {"t5", slice, "0: error 123; 2: error 123."},
- {"t6", &slice, "0: error 123; 2: error 123."},
- {"t7", mp, "a: error 123; c: error 123."},
- {"t8", &mp, "a: error 123; c: error 123."},
- {"t9", map[string]String123{}, ""},
- }
- for _, test := range tests {
- err := Validate(test.value)
- assertError(t, test.err, err, test.tag)
- }
-
- // with rules
- err := Validate("123", &validateAbc{}, &validateXyz{})
- if assert.NotNil(t, err) {
- assert.Equal(t, "error abc", err.Error())
- }
- err = Validate("abc", &validateAbc{}, &validateXyz{})
- if assert.NotNil(t, err) {
- assert.Equal(t, "error xyz", err.Error())
- }
- err = Validate("abcxyz", &validateAbc{}, &validateXyz{})
- assert.Nil(t, err)
-
- err = Validate("123", &validateAbc{}, Skip, &validateXyz{})
- if assert.NotNil(t, err) {
- assert.Equal(t, "error abc", err.Error())
- }
- err = Validate("abc", &validateAbc{}, Skip, &validateXyz{})
- assert.Nil(t, err)
-}
-
-func TestBy(t *testing.T) {
- abcRule := By(func(value interface{}) error {
- s, _ := value.(string)
- if s != "abc" {
- return errors.New("must be abc")
- }
- return nil
- })
- assert.Nil(t, Validate("abc", abcRule))
- err := Validate("xyz", abcRule)
- if assert.NotNil(t, err) {
- assert.Equal(t, "must be abc", err.Error())
- }
-}
-
-func Test_skipRule_Validate(t *testing.T) {
- assert.Nil(t, Skip.Validate(100))
-}
-
-func assertError(t *testing.T, expected string, err error, tag string) {
- if expected == "" {
- assert.Nil(t, err, tag)
- } else if assert.NotNil(t, err, tag) {
- assert.Equal(t, expected, err.Error(), tag)
- }
-}
-
-type validateAbc struct{}
-
-func (v *validateAbc) Validate(obj interface{}) error {
- if !strings.Contains(obj.(string), "abc") {
- return errors.New("error abc")
- }
- return nil
-}
-
-type validateXyz struct{}
-
-func (v *validateXyz) Validate(obj interface{}) error {
- if !strings.Contains(obj.(string), "xyz") {
- return errors.New("error xyz")
- }
- return nil
-}
-
-type validateInternalError struct{}
-
-func (v *validateInternalError) Validate(obj interface{}) error {
- if strings.Contains(obj.(string), "internal") {
- return NewInternalError(errors.New("error internal"))
- }
- return nil
-}
-
-type Model1 struct {
- A string
- B string
- c string
- D *string
- E String123
- F *String123
- G string `json:"g"`
-}
-
-type String123 string
-
-func (s String123) Validate() error {
- if !strings.Contains(string(s), "123") {
- return errors.New("error 123")
- }
- return nil
-}
-
-type Model2 struct {
- Model3
- M3 Model3
- B string
-}
-
-type Model3 struct {
- A string
-}
-
-func (m Model3) Validate() error {
- return ValidateStruct(&m,
- Field(&m.A, &validateAbc{}),
- )
-}
diff --git a/vendor/github.com/go-pg/migrations/.travis.yml b/vendor/github.com/go-pg/migrations/.travis.yml
deleted file mode 100644
index c24530b..0000000
--- a/vendor/github.com/go-pg/migrations/.travis.yml
+++ /dev/null
@@ -1,23 +0,0 @@
-sudo: false
-language: go
-
-services:
-- postgresql
-
-addons:
- postgresql: "9.4"
-
-go:
- - 1.7
- - 1.8
- - 1.9
- - tip
-
-matrix:
- allow_failures:
- - go: tip
-
-install:
- - go get github.com/go-pg/pg
- - go get github.com/onsi/ginkgo
- - go get github.com/onsi/gomega
diff --git a/vendor/github.com/go-pg/migrations/Makefile b/vendor/github.com/go-pg/migrations/Makefile
deleted file mode 100644
index b342b00..0000000
--- a/vendor/github.com/go-pg/migrations/Makefile
+++ /dev/null
@@ -1,3 +0,0 @@
-all:
- go test ./...
- go test ./... -short -race
diff --git a/vendor/github.com/go-pg/migrations/README.md b/vendor/github.com/go-pg/migrations/README.md
deleted file mode 100644
index 6ef69cb..0000000
--- a/vendor/github.com/go-pg/migrations/README.md
+++ /dev/null
@@ -1,6 +0,0 @@
-# SQL migrations for Golang and PostgreSQL
-
-[](https://travis-ci.org/go-pg/migrations)
-[](https://godoc.org/github.com/go-pg/migrations)
-
-This package allows you to run migrations on your PostgreSQL database using [Golang Postgres client](https://github.com/go-pg/pg). See [example](example) for details.
diff --git a/vendor/github.com/go-pg/migrations/db.go b/vendor/github.com/go-pg/migrations/db.go
deleted file mode 100644
index 39f17c2..0000000
--- a/vendor/github.com/go-pg/migrations/db.go
+++ /dev/null
@@ -1,79 +0,0 @@
-package migrations
-
-import (
- "io"
- "strings"
-
- "github.com/go-pg/pg"
- "github.com/go-pg/pg/orm"
- "github.com/go-pg/pg/types"
-)
-
-var tableName = "gopg_migrations"
-
-func SetTableName(name string) {
- tableName = name
-}
-
-type DB interface {
- Exec(query interface{}, params ...interface{}) (orm.Result, error)
- ExecOne(query interface{}, params ...interface{}) (orm.Result, error)
- Query(model, query interface{}, params ...interface{}) (orm.Result, error)
- QueryOne(model, query interface{}, params ...interface{}) (orm.Result, error)
-
- Model(model ...interface{}) *orm.Query
- Select(model interface{}) error
- Insert(model ...interface{}) error
- Update(model ...interface{}) error
- Delete(model interface{}) error
- CreateTable(model interface{}, opt *orm.CreateTableOptions) error
- DropTable(model interface{}, opt *orm.DropTableOptions) error
-
- CopyFrom(r io.Reader, query interface{}, params ...interface{}) (orm.Result, error)
- CopyTo(w io.Writer, query interface{}, params ...interface{}) (orm.Result, error)
-
- FormatQuery(dst []byte, query string, params ...interface{}) []byte
-}
-
-func getTableName() types.ValueAppender {
- return pg.Q(tableName)
-}
-
-func Version(db DB) (int64, error) {
- var version int64
- _, err := db.QueryOne(pg.Scan(&version), `
- SELECT version FROM ? ORDER BY id DESC LIMIT 1
- `, getTableName())
- if err != nil {
- if err == pg.ErrNoRows {
- return 0, nil
- }
- return 0, err
- }
- return version, nil
-}
-
-func SetVersion(db DB, version int64) error {
- _, err := db.Exec(`
- INSERT INTO ? (version, created_at) VALUES (?, now())
- `, getTableName(), version)
- return err
-}
-
-func createTables(db DB) error {
- if ind := strings.IndexByte(tableName, '.'); ind >= 0 {
- _, err := db.Exec(`CREATE SCHEMA IF NOT EXISTS ?`, pg.Q(tableName[:ind]))
- if err != nil {
- return err
- }
- }
-
- _, err := db.Exec(`
- CREATE TABLE IF NOT EXISTS ? (
- id serial,
- version bigint,
- created_at timestamptz
- )
- `, getTableName())
- return err
-}
diff --git a/vendor/github.com/go-pg/migrations/db_test.go b/vendor/github.com/go-pg/migrations/db_test.go
deleted file mode 100644
index 43f49f2..0000000
--- a/vendor/github.com/go-pg/migrations/db_test.go
+++ /dev/null
@@ -1,161 +0,0 @@
-package migrations_test
-
-import (
- "fmt"
- "testing"
-
- "github.com/go-pg/migrations"
-
- "github.com/go-pg/pg"
-)
-
-func connectDB() *pg.DB {
- db := pg.Connect(&pg.Options{
- User: "postgres",
- })
-
- _, err := db.Exec("DROP TABLE IF EXISTS gopg_migrations")
- if err != nil {
- panic(err)
- }
-
- return db
-}
-
-func TestVersion(t *testing.T) {
- db := connectDB()
-
- _, _, err := migrations.Run(db, "init")
- if err != nil {
- t.Fatalf("init failed: %s", err)
- }
-
- version, err := migrations.Version(db)
- if err != nil {
- t.Fatalf("Version failed: %s", err)
- }
- if version != 0 {
- t.Fatalf("got version %d, wanted 0", version)
- }
-
- if err := migrations.SetVersion(db, 999); err != nil {
- t.Fatalf("SetVersion failed: %s", err)
- }
-
- version, err = migrations.Version(db)
- if err != nil {
- t.Fatalf("Version failed: %s", err)
- }
- if version != 999 {
- t.Fatalf("got version %d, wanted %d", version)
- }
-}
-
-func TestUpDown(t *testing.T) {
- db := connectDB()
-
- _, _, err := migrations.Run(db, "init")
- if err != nil {
- t.Fatalf("init failed: %s", err)
- }
-
- migrations.Set([]migrations.Migration{
- {Version: 2, Up: doNothing, Down: doNothing},
- {Version: 1, Up: doNothing, Down: doNothing},
- {Version: 3, Up: doNothing, Down: doNothing},
- })
- oldVersion, newVersion, err := migrations.Run(db, "up")
- if err != nil {
- t.Fatal(err)
- }
- if oldVersion != 0 {
- t.Fatalf("got %d, wanted 0", oldVersion)
- }
- if newVersion != 3 {
- t.Fatalf("got %d, wanted 3", newVersion)
- }
-
- version, err := migrations.Version(db)
- if err != nil {
- t.Fatal(err)
- }
- if version != 3 {
- t.Fatalf("got version %d, wanted 3", version)
- }
-
- for i := 2; i >= -5; i-- {
- wantOldVersion := int64(i + 1)
- wantNewVersion := int64(i)
- if wantNewVersion < 0 {
- wantOldVersion = 0
- wantNewVersion = 0
- }
-
- oldVersion, newVersion, err = migrations.Run(db, "down")
- if err != nil {
- t.Fatal(err)
- }
- if oldVersion != wantOldVersion {
- t.Fatalf("got %d, wanted %d", oldVersion, wantOldVersion)
- }
- if newVersion != wantNewVersion {
- t.Fatalf("got %d, wanted %d", newVersion, wantNewVersion)
- }
-
- version, err = migrations.Version(db)
- if err != nil {
- t.Fatal(err)
- }
- if version != wantNewVersion {
- t.Fatalf("got version %d, wanted %d", version, wantNewVersion)
- }
- }
-}
-
-func TestSetVersion(t *testing.T) {
- db := connectDB()
-
- _, _, err := migrations.Run(db, "init")
- if err != nil {
- t.Fatalf("init failed: %s", err)
- }
-
- migrations.Set([]migrations.Migration{
- {Version: 1, Up: doPanic, Down: doPanic},
- {Version: 2, Up: doPanic, Down: doPanic},
- {Version: 3, Up: doPanic, Down: doPanic},
- })
-
- for i := 0; i < 5; i++ {
- wantOldVersion := int64(i)
- wantNewVersion := int64(i + 1)
-
- oldVersion, newVersion, err := migrations.Run(
- db, "set_version", fmt.Sprint(wantNewVersion))
- if err != nil {
- t.Fatal(err)
- }
- if oldVersion != wantOldVersion {
- t.Fatalf("got %d, wanted %d", oldVersion, wantOldVersion)
- }
- if newVersion != wantNewVersion {
- t.Fatalf("got %d, wanted %d", newVersion, wantNewVersion)
- }
-
- version, err := migrations.Version(db)
- if err != nil {
- t.Fatal(err)
- }
- if version != wantNewVersion {
- t.Fatalf("got version %d, wanted %d", version, wantNewVersion)
- }
- }
-}
-
-func doNothing(db migrations.DB) error {
- return nil
-}
-
-func doPanic(db migrations.DB) error {
- panic("this migration should not be run")
-}
diff --git a/vendor/github.com/go-pg/migrations/export_test.go b/vendor/github.com/go-pg/migrations/export_test.go
deleted file mode 100644
index 3f31dff..0000000
--- a/vendor/github.com/go-pg/migrations/export_test.go
+++ /dev/null
@@ -1,5 +0,0 @@
-package migrations
-
-func Set(ms []Migration) {
- allMigrations = ms
-}
diff --git a/vendor/github.com/go-pg/migrations/migrations.go b/vendor/github.com/go-pg/migrations/migrations.go
deleted file mode 100644
index 8d8653c..0000000
--- a/vendor/github.com/go-pg/migrations/migrations.go
+++ /dev/null
@@ -1,265 +0,0 @@
-package migrations
-
-import (
- "errors"
- "fmt"
- "io/ioutil"
- "os"
- "path"
- "path/filepath"
- "regexp"
- "runtime"
- "sort"
- "strconv"
- "strings"
-)
-
-var allMigrations []Migration
-
-type Migration struct {
- Version int64
- Up func(DB) error
- Down func(DB) error
-}
-
-func (m *Migration) String() string {
- return strconv.FormatInt(m.Version, 10)
-}
-
-// Register registers new database migration. Must be called
-// from file with name like "1_initialize_db.go", where:
-// - 1 - migration version;
-// - initialize_db - comment.
-func Register(up, down func(DB) error) error {
- _, file, _, _ := runtime.Caller(1)
- version, err := extractVersion(file)
- if err != nil {
- return err
- }
-
- allMigrations = append(allMigrations, Migration{
- Version: version,
- Up: up,
- Down: down,
- })
- return nil
-}
-
-// Run runs command on the db. Supported commands are:
-// - init - creates gopg_migrations table.
-// - up - runs all available migrations.
-// - down - reverts last migration.
-// - reset - reverts all migrations.
-// - version - prints current db version.
-// - set_version - sets db version without running migrations.
-func Run(db DB, a ...string) (oldVersion, newVersion int64, err error) {
- // Make a copy so there are no side effects of sorting.
- migrations := make([]Migration, len(allMigrations))
- copy(migrations, allMigrations)
- return RunMigrations(db, migrations, a...)
-}
-
-// RunMigrations is like Run, but accepts list of migrations.
-func RunMigrations(db DB, migrations []Migration, a ...string) (oldVersion, newVersion int64, err error) {
- sortMigrations(migrations)
-
- var cmd string
- if len(a) > 0 {
- cmd = a[0]
- }
-
- if cmd == "init" {
- err = createTables(db)
- if err != nil {
- return
- }
- cmd = "version"
- }
-
- oldVersion, err = Version(db)
- if err != nil {
- return
- }
- newVersion = oldVersion
-
- switch cmd {
- case "create":
- if len(a) < 2 {
- fmt.Println("Please enter migration description")
- return
- }
-
- var version int64
- if len(migrations) > 0 {
- version = migrations[len(migrations)-1].Version
- }
-
- filename := fmtMigrationFilename(version+1, strings.Join(a[1:], "_"))
- err = createMigrationFile(filename)
- if err != nil {
- return
- }
-
- fmt.Println("created migration", filename)
- return
- case "version":
- return
- case "up", "":
- for i := range migrations {
- m := &migrations[i]
- if m.Version <= oldVersion {
- continue
- }
- err = m.Up(db)
- if err != nil {
- return
- }
- newVersion = m.Version
- err = SetVersion(db, newVersion)
- if err != nil {
- return
- }
- }
- return
- case "down":
- newVersion, err = down(db, migrations, oldVersion)
- return
- case "reset":
- version := oldVersion
- for {
- newVersion, err = down(db, migrations, version)
- if err != nil || newVersion == version {
- return
- }
- version = newVersion
- }
- case "set_version":
- if len(a) < 2 {
- err = fmt.Errorf("set_version requires version as 2nd arg, e.g. set_version 42")
- return
- }
-
- newVersion, err = strconv.ParseInt(a[1], 10, 64)
- if err != nil {
- return
- }
- err = SetVersion(db, newVersion)
- return
- default:
- err = fmt.Errorf("unsupported command: %q", cmd)
- return
- }
-}
-
-func down(db DB, migrations []Migration, oldVersion int64) (newVersion int64, err error) {
- if oldVersion == 0 {
- return
- }
-
- var m *Migration
- for i := len(migrations) - 1; i >= 0; i-- {
- mm := &migrations[i]
- if mm.Version <= oldVersion {
- m = mm
- break
- }
- }
- if m == nil {
- err = fmt.Errorf("migration %d not found\n", oldVersion)
- return
- }
-
- if m.Down != nil {
- err = m.Down(db)
- if err != nil {
- return
- }
- }
-
- newVersion = m.Version - 1
- err = SetVersion(db, newVersion)
- return
-}
-
-func extractVersion(name string) (int64, error) {
- base := filepath.Base(name)
-
- if ext := filepath.Ext(base); ext != ".go" {
- return 0, fmt.Errorf("can not extract version from %q", base)
- }
-
- idx := strings.IndexByte(base, '_')
- if idx == -1 {
- return 0, fmt.Errorf("can not extract version from %q", base)
- }
-
- n, err := strconv.ParseInt(base[:idx], 10, 64)
- if err != nil {
- return 0, err
- }
-
- if n <= 0 {
- return 0, errors.New("version must be greater than zero")
- }
-
- return n, nil
-}
-
-type migrationSorter []Migration
-
-func (ms migrationSorter) Len() int {
- return len(ms)
-}
-
-func (ms migrationSorter) Swap(i, j int) {
- ms[i], ms[j] = ms[j], ms[i]
-}
-
-func (ms migrationSorter) Less(i, j int) bool {
- return ms[i].Version < ms[j].Version
-}
-
-func sortMigrations(migrations []Migration) {
- ms := migrationSorter(migrations)
- sort.Sort(ms)
-}
-
-var migrationNameRE = regexp.MustCompile(`[^a-z0-9]+`)
-
-func fmtMigrationFilename(version int64, descr string) string {
- descr = strings.ToLower(descr)
- descr = migrationNameRE.ReplaceAllString(descr, "_")
- return fmt.Sprintf("%d_%s.go", version, descr)
-}
-
-func createMigrationFile(filename string) error {
- basepath, err := os.Getwd()
- if err != nil {
- return err
- }
- filename = path.Join(basepath, filename)
-
- _, err = os.Stat(filename)
- if !os.IsNotExist(err) {
- return fmt.Errorf("file=%q already exists (%s)", filename, err)
- }
-
- return ioutil.WriteFile(filename, migrationTemplate, 0644)
-}
-
-var migrationTemplate = []byte(`package main
-
-import (
- "github.com/go-pg/migrations"
-)
-
-func init() {
- migrations.Register(func(db migrations.DB) error {
- _, err := db.Exec("")
- return err
- }, func(db migrations.DB) error {
- _, err := db.Exec("")
- return err
- })
-}
-`)
diff --git a/vendor/github.com/go-pg/pg/.travis.yml b/vendor/github.com/go-pg/pg/.travis.yml
deleted file mode 100644
index 3bbfe79..0000000
--- a/vendor/github.com/go-pg/pg/.travis.yml
+++ /dev/null
@@ -1,24 +0,0 @@
-dist: trusty
-
-language: go
-
-addons:
- postgresql: "9.6"
-
-go:
- - 1.7
- - 1.8
- - tip
-
-matrix:
- allow_failures:
- - go: tip
-
-before_install:
- - psql -U postgres -c "CREATE EXTENSION hstore"
-
-install:
- - go get github.com/jinzhu/inflection
- - go get gopkg.in/check.v1
- - go get github.com/onsi/ginkgo
- - go get github.com/onsi/gomega
diff --git a/vendor/github.com/go-pg/pg/CHANGELOG.md b/vendor/github.com/go-pg/pg/CHANGELOG.md
deleted file mode 100644
index 0eeba1b..0000000
--- a/vendor/github.com/go-pg/pg/CHANGELOG.md
+++ /dev/null
@@ -1,33 +0,0 @@
-# Changelog
-
-## v6
-
- - `types.Result` is renamed to `orm.Result`.
- - Added `OnQueryProcessed` event that can be used to log / report queries timing. Query logger is removed.
- - `orm.URLValues` is renamed to `orm.URLFilters`. It no longer adds ORDER clause.
- - `orm.Pager` is renamed to `orm.Pagination`.
- - Support for net.IP and net.IPNet.
- - Support for context.Context.
- - Bulk/multi updates.
- - Query.WhereGroup for enclosing conditions in paretheses.
-
-## v5
-
- - All fields are nullable by default. `,null` tag is replaced with `,notnull`.
- - `Result.Affected` renamed to `Result.RowsAffected`.
- - Added `Result.RowsReturned`.
- - `Create` renamed to `Insert`, `BeforeCreate` to `BeforeInsert`, `AfterCreate` to `AfterInsert`.
- - Indexed placeholders support, e.g. `db.Exec("SELECT ?0 + ?0", 1)`.
- - Named placeholders are evaluated when query is executed.
- - Added Update and Delete hooks.
- - Order reworked to quote column names. OrderExpr added to bypass Order quoting restrictions.
- - Group reworked to quote column names. GroupExpr added to bypass Group quoting restrictions.
-
-## v4
-
- - `Options.Host` and `Options.Port` merged into `Options.Addr`.
- - Added `Options.MaxRetries`. Now queries are not retried by default.
- - `LoadInto` renamed to `Scan`, `ColumnLoader` renamed to `ColumnScanner`, LoadColumn renamed to ScanColumn, `NewRecord() interface{}` changed to `NewModel() ColumnScanner`, `AppendQuery(dst []byte) []byte` changed to `AppendValue(dst []byte, quote bool) ([]byte, error)`.
- - Structs, maps and slices are marshalled to JSON by default.
- - Added support for scanning slices, .e.g. scanning `[]int`.
- - Added object relational mapping.
diff --git a/vendor/github.com/go-pg/pg/LICENSE b/vendor/github.com/go-pg/pg/LICENSE
deleted file mode 100644
index 7751509..0000000
--- a/vendor/github.com/go-pg/pg/LICENSE
+++ /dev/null
@@ -1,24 +0,0 @@
-Copyright (c) 2013 github.com/go-pg/pg Authors. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- * Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/vendor/github.com/go-pg/pg/Makefile b/vendor/github.com/go-pg/pg/Makefile
deleted file mode 100644
index 161c4fd..0000000
--- a/vendor/github.com/go-pg/pg/Makefile
+++ /dev/null
@@ -1,4 +0,0 @@
-all:
- go test ./...
- go test ./... -short -race
- go vet
diff --git a/vendor/github.com/go-pg/pg/README.md b/vendor/github.com/go-pg/pg/README.md
deleted file mode 100644
index c219ad5..0000000
--- a/vendor/github.com/go-pg/pg/README.md
+++ /dev/null
@@ -1,155 +0,0 @@
-# PostgreSQL client and ORM for Golang
-
-[](https://travis-ci.org/go-pg/pg)
-[](https://godoc.org/github.com/go-pg/pg)
-
-## Features:
-
-- Basic types: integers, floats, string, bool, time.Time, net.IP, net.IPNet.
-- sql.NullBool, sql.NullString, sql.NullInt64, sql.NullFloat64 and [pg.NullTime](http://godoc.org/github.com/go-pg/pg#NullTime).
-- [sql.Scanner](http://golang.org/pkg/database/sql/#Scanner) and [sql/driver.Valuer](http://golang.org/pkg/database/sql/driver/#Valuer) interfaces.
-- Structs, maps and arrays are marshalled as JSON by default.
-- PostgreSQL multidimensional Arrays using [array tag](https://godoc.org/github.com/go-pg/pg#example-DB-Model-PostgresArrayStructTag) and [Array wrapper](https://godoc.org/github.com/go-pg/pg#example-Array).
-- Hstore using [hstore tag](https://godoc.org/github.com/go-pg/pg#example-DB-Model-HstoreStructTag) and [Hstore wrapper](https://godoc.org/github.com/go-pg/pg#example-Hstore).
-- All struct fields are nullable by default and zero values (empty string, 0, zero time) are marshalled as SQL `NULL`. `sql:",notnull"` tag is used to reverse this behaviour.
-- [Transactions](http://godoc.org/github.com/go-pg/pg#example-DB-Begin).
-- [Prepared statements](http://godoc.org/github.com/go-pg/pg#example-DB-Prepare).
-- [Notifications](http://godoc.org/github.com/go-pg/pg#example-Listener) using `LISTEN` and `NOTIFY`.
-- [Copying data](http://godoc.org/github.com/go-pg/pg#example-DB-CopyFrom) using `COPY FROM` and `COPY TO`.
-- [Timeouts](http://godoc.org/github.com/go-pg/pg#Options).
-- Automatic connection pooling with [circuit breaker](https://en.wikipedia.org/wiki/Circuit_breaker_design_pattern) support.
-- Queries retries on network errors.
-- Working with models using [ORM](https://godoc.org/github.com/go-pg/pg#example-DB-Model) and [SQL](https://godoc.org/github.com/go-pg/pg#example-DB-Query).
-- Scanning variables using [ORM](https://godoc.org/github.com/go-pg/pg#example-DB-Select-SomeColumnsIntoVars) and [SQL](https://godoc.org/github.com/go-pg/pg#example-Scan).
-- [SelectOrInsert](https://godoc.org/github.com/go-pg/pg#example-DB-Insert-SelectOrInsert) using on-conflict.
-- [INSERT ... ON CONFLICT DO UPDATE](https://godoc.org/github.com/go-pg/pg#example-DB-Insert-OnConflictDoUpdate) using ORM.
-- Bulk/batch [inserts](https://godoc.org/github.com/go-pg/pg#example-DB-Insert-BulkInsert) and [updates](https://godoc.org/github.com/go-pg/pg#example-DB-Update-BulkUpdate).
-- Common table expressions using [WITH](https://godoc.org/github.com/go-pg/pg#example-DB-Select-With) and [WrapWith](https://godoc.org/github.com/go-pg/pg#example-DB-Select-WrapWith).
-- [CountEstimate](https://godoc.org/github.com/go-pg/pg#example-DB-Model-CountEstimate) using `EXPLAIN` to get [estimated number of matching rows](https://wiki.postgresql.org/wiki/Count_estimate).
-- ORM supports [has one](https://godoc.org/github.com/go-pg/pg#example-DB-Model-HasOne), [belongs to](https://godoc.org/github.com/go-pg/pg#example-DB-Model-BelongsTo), [has many](https://godoc.org/github.com/go-pg/pg#example-DB-Model-HasMany), and [many to many](https://godoc.org/github.com/go-pg/pg#example-DB-Model-ManyToMany) with composite/multi-column primary keys.
-- [Creating tables from structs](https://godoc.org/github.com/go-pg/pg#example-DB-CreateTable).
-- [Pagination](https://godoc.org/github.com/go-pg/pg/orm#Pagination) and [URL filters](https://godoc.org/github.com/go-pg/pg/orm#URLFilters) helpers.
-- [Migrations](https://github.com/go-pg/migrations).
-- [Sharding](https://github.com/go-pg/sharding).
-
-## Get Started
-
-- [Wiki](https://github.com/go-pg/pg/wiki)
-- [API docs](http://godoc.org/github.com/go-pg/pg)
-- [Examples](http://godoc.org/github.com/go-pg/pg#pkg-examples)
-
-## Look & Feel
-
-```go
-package pg_test
-
-import (
- "fmt"
-
- "github.com/go-pg/pg"
-)
-
-type User struct {
- Id int64
- Name string
- Emails []string
-}
-
-func (u User) String() string {
- return fmt.Sprintf("User<%d %s %v>", u.Id, u.Name, u.Emails)
-}
-
-type Story struct {
- Id int64
- Title string
- AuthorId int64
- Author *User
-}
-
-func (s Story) String() string {
- return fmt.Sprintf("Story<%d %s %s>", s.Id, s.Title, s.Author)
-}
-
-func ExampleDB_Model() {
- db := pg.Connect(&pg.Options{
- User: "postgres",
- })
-
- err := createSchema(db)
- if err != nil {
- panic(err)
- }
-
- user1 := &User{
- Name: "admin",
- Emails: []string{"admin1@admin", "admin2@admin"},
- }
- err = db.Insert(user1)
- if err != nil {
- panic(err)
- }
-
- err = db.Insert(&User{
- Name: "root",
- Emails: []string{"root1@root", "root2@root"},
- })
- if err != nil {
- panic(err)
- }
-
- story1 := &Story{
- Title: "Cool story",
- AuthorId: user1.Id,
- }
- err = db.Insert(story1)
- if err != nil {
- panic(err)
- }
-
- // Select user by primary key.
- user := User{Id: user1.Id}
- err = db.Select(&user)
- if err != nil {
- panic(err)
- }
-
- // Select all users.
- var users []User
- err = db.Model(&users).Select()
- if err != nil {
- panic(err)
- }
-
- // Select story and associated author in one query.
- var story Story
- err = db.Model(&story).
- Column("story.*", "Author").
- Where("story.id = ?", story1.Id).
- Select()
- if err != nil {
- panic(err)
- }
-
- fmt.Println(user)
- fmt.Println(users)
- fmt.Println(story)
- // Output: User<1 admin [admin1@admin admin2@admin]>
- // [User<1 admin [admin1@admin admin2@admin]> User<2 root [root1@root root2@root]>]
- // Story<1 Cool story User<1 admin [admin1@admin admin2@admin]>>
-}
-
-func createSchema(db *pg.DB) error {
- for _, model := range []interface{}{&User{}, &Story{}} {
- err := db.CreateTable(model, nil)
- if err != nil {
- return err
- }
- }
- return nil
-}
-```
-
-## See also
-
-- [Golang msgpack](https://github.com/vmihailenco/msgpack)
-- [Golang message task queue](https://github.com/go-msgqueue/msgqueue)
diff --git a/vendor/github.com/go-pg/pg/bench_test.go b/vendor/github.com/go-pg/pg/bench_test.go
deleted file mode 100644
index 000345f..0000000
--- a/vendor/github.com/go-pg/pg/bench_test.go
+++ /dev/null
@@ -1,548 +0,0 @@
-package pg_test
-
-import (
- "fmt"
- "math/rand"
- "strconv"
- "sync"
- "testing"
- "time"
-
- "github.com/go-pg/pg"
- "github.com/go-pg/pg/orm"
-)
-
-func benchmarkDB() *pg.DB {
- return pg.Connect(&pg.Options{
- User: "postgres",
- Database: "postgres",
- DialTimeout: 30 * time.Second,
- ReadTimeout: 10 * time.Second,
- WriteTimeout: 10 * time.Second,
- PoolSize: 10,
- PoolTimeout: 30 * time.Second,
- })
-}
-
-func BenchmarkQueryRowsGopgDiscard(b *testing.B) {
- seedDB()
-
- db := benchmarkDB()
- defer db.Close()
-
- b.ResetTimer()
-
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- _, err := db.Query(pg.Discard, `SELECT * FROM records LIMIT 100`)
- if err != nil {
- b.Fatal(err)
- }
- }
- })
-}
-
-func BenchmarkQueryRowsGopgOptimized(b *testing.B) {
- seedDB()
-
- db := benchmarkDB()
- defer db.Close()
-
- b.ResetTimer()
-
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- var rs OptRecords
- _, err := db.Query(&rs, `SELECT * FROM records LIMIT 100`)
- if err != nil {
- b.Fatal(err)
- }
- if len(rs.C) != 100 {
- b.Fatalf("got %d, wanted 100", len(rs.C))
- }
- }
- })
-}
-
-func BenchmarkQueryRowsGopgReflect(b *testing.B) {
- seedDB()
-
- db := benchmarkDB()
- defer db.Close()
-
- b.ResetTimer()
-
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- var rs []Record
- _, err := db.Query(&rs, `SELECT * FROM records LIMIT 100`)
- if err != nil {
- b.Fatal(err)
- }
- if len(rs) != 100 {
- b.Fatalf("got %d, wanted 100", len(rs))
- }
- }
- })
-}
-
-func BenchmarkQueryRowsGopgORM(b *testing.B) {
- seedDB()
-
- db := benchmarkDB()
- defer db.Close()
-
- b.ResetTimer()
-
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- var rs []Record
- err := db.Model(&rs).Limit(100).Select()
- if err != nil {
- b.Fatal(err)
- }
- if len(rs) != 100 {
- b.Fatalf("got %d, wanted 100", len(rs))
- }
- }
- })
-}
-
-func BenchmarkModelHasOneGopg(b *testing.B) {
- seedDB()
-
- db := benchmarkDB()
- defer db.Close()
-
- b.ResetTimer()
-
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- var books []Book
- err := db.Model(&books).Column("book.*", "Author").Limit(100).Select()
- if err != nil {
- b.Fatal(err)
- }
-
- if len(books) != 100 {
- b.Fatalf("got %d, wanted 100", len(books))
- }
- }
- })
-}
-
-func BenchmarkModelHasManyGopg(b *testing.B) {
- seedDB()
-
- db := benchmarkDB()
- defer db.Close()
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- var books []Book
- err := db.Model(&books).Column("book.*", "Translations").Limit(100).Select()
- if err != nil {
- b.Fatal(err)
- }
-
- if len(books) != 100 {
- b.Fatalf("got %d, wanted 100", len(books))
- }
- for _, book := range books {
- if len(book.Translations) != 10 {
- b.Fatalf("got %d, wanted 10", len(book.Translations))
- }
- }
- }
- })
-}
-
-func BenchmarkModelHasMany2ManyGopg(b *testing.B) {
- seedDB()
-
- db := benchmarkDB()
- defer db.Close()
-
- b.ResetTimer()
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- var books []Book
- err := db.Model(&books).
- Column("book.*", "Genres").
- Limit(100).
- Select()
-
- if err != nil {
- b.Fatal(err)
- }
-
- if len(books) != 100 {
- b.Fatalf("got %d, wanted 100", len(books))
- }
- for _, book := range books {
- if len(book.Genres) != 10 {
- b.Fatalf("got %d, wanted 10", len(book.Genres))
- }
- }
- }
- })
-}
-
-func BenchmarkQueryRow(b *testing.B) {
- db := benchmarkDB()
- defer db.Close()
-
- b.ResetTimer()
-
- for i := 0; i < b.N; i++ {
- var dst numLoader
- _, err := db.QueryOne(&dst, `SELECT ?::bigint AS num`, 1)
- if err != nil {
- b.Fatal(err)
- }
- if dst.Num != 1 {
- b.Fatalf("got %d, wanted 1", dst.Num)
- }
- }
-}
-
-func BenchmarkQueryRowStmt(b *testing.B) {
- db := benchmarkDB()
- defer db.Close()
-
- stmt, err := db.Prepare(`SELECT $1::bigint AS num`)
- if err != nil {
- b.Fatal(err)
- }
- defer stmt.Close()
-
- b.ResetTimer()
-
- for i := 0; i < b.N; i++ {
- var dst numLoader
- _, err := stmt.QueryOne(&dst, 1)
- if err != nil {
- b.Fatal(err)
- }
- if dst.Num != 1 {
- b.Fatalf("got %d, wanted 1", dst.Num)
- }
- }
-}
-
-func BenchmarkQueryRowScan(b *testing.B) {
- db := benchmarkDB()
- defer db.Close()
-
- b.ResetTimer()
-
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- var n int64
- _, err := db.QueryOne(pg.Scan(&n), `SELECT ? AS num`, 1)
- if err != nil {
- b.Fatal(err)
- }
- if n != 1 {
- b.Fatalf("got %d, wanted 1", n)
- }
- }
- })
-}
-
-func BenchmarkQueryRowStmtScan(b *testing.B) {
- db := benchmarkDB()
- defer db.Close()
-
- stmt, err := db.Prepare(`SELECT $1::bigint AS num`)
- if err != nil {
- b.Fatal(err)
- }
- defer stmt.Close()
-
- b.ResetTimer()
-
- for i := 0; i < b.N; i++ {
- var n int64
- _, err := stmt.QueryOne(pg.Scan(&n), 1)
- if err != nil {
- b.Fatal(err)
- }
- if n != 1 {
- b.Fatalf("got %d, wanted 1", n)
- }
- }
-}
-
-func BenchmarkExec(b *testing.B) {
- db := benchmarkDB()
- defer db.Close()
-
- qs := []string{
- `DROP TABLE IF EXISTS exec_test`,
- `CREATE TABLE exec_test(id bigint, name varchar(500))`,
- }
- for _, q := range qs {
- _, err := db.Exec(q)
- if err != nil {
- b.Fatal(err)
- }
- }
-
- b.ResetTimer()
-
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- _, err := db.Exec(`INSERT INTO exec_test (id, name) VALUES (?, ?)`, 1, "hello world")
- if err != nil {
- b.Fatal(err)
- }
- }
- })
-}
-
-func BenchmarkExecWithError(b *testing.B) {
- db := benchmarkDB()
- defer db.Close()
-
- qs := []string{
- `DROP TABLE IF EXISTS exec_with_error_test`,
- `CREATE TABLE exec_with_error_test(id bigint PRIMARY KEY, name varchar(500))`,
- }
- for _, q := range qs {
- _, err := db.Exec(q)
- if err != nil {
- b.Fatal(err)
- }
- }
-
- _, err := db.Exec(`
- INSERT INTO exec_with_error_test(id, name) VALUES(?, ?)
- `, 1, "hello world")
- if err != nil {
- b.Fatal(err)
- }
-
- b.ResetTimer()
-
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- _, err := db.Exec(`INSERT INTO exec_with_error_test(id) VALUES(?)`, 1)
- if err == nil {
- b.Fatalf("got nil error, expected integrity violation")
- } else if pgErr, ok := err.(pg.Error); !ok || !pgErr.IntegrityViolation() {
- b.Fatalf("got %s, expected integrity violation", err)
- }
- }
- })
-}
-
-func BenchmarkExecStmt(b *testing.B) {
- db := benchmarkDB()
- defer db.Close()
-
- _, err := db.Exec(`CREATE TEMP TABLE statement_exec(id bigint, name varchar(500))`)
- if err != nil {
- b.Fatal(err)
- }
-
- stmt, err := db.Prepare(`INSERT INTO statement_exec (id, name) VALUES ($1, $2)`)
- if err != nil {
- b.Fatal(err)
- }
- defer stmt.Close()
-
- b.ResetTimer()
-
- for i := 0; i < b.N; i++ {
- _, err := stmt.Exec(1, "hello world")
- if err != nil {
- b.Fatal(err)
- }
- }
-}
-
-var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
-
-func randSeq(n int) string {
- b := make([]rune, n)
- for i := range b {
- b[i] = letters[rand.Intn(len(letters))]
- }
- return string(b)
-}
-
-type Record struct {
- Num1, Num2, Num3 int64
- Str1, Str2, Str3 string
-}
-
-func (r *Record) GetNum1() int64 {
- return r.Num1
-}
-
-func (r *Record) GetNum2() int64 {
- return r.Num2
-}
-
-func (r *Record) GetNum3() int64 {
- return r.Num3
-}
-
-func (r *Record) GetStr1() string {
- return r.Str1
-}
-
-func (r *Record) GetStr2() string {
- return r.Str2
-}
-
-func (r *Record) GetStr3() string {
- return r.Str3
-}
-
-type OptRecord struct {
- Num1, Num2, Num3 int64
- Str1, Str2, Str3 string
-}
-
-var _ orm.ColumnScanner = (*OptRecord)(nil)
-
-func (r *OptRecord) ScanColumn(colIdx int, colName string, b []byte) error {
- var err error
- switch colName {
- case "num1":
- r.Num1, err = strconv.ParseInt(string(b), 10, 64)
- case "num2":
- r.Num2, err = strconv.ParseInt(string(b), 10, 64)
- case "num3":
- r.Num3, err = strconv.ParseInt(string(b), 10, 64)
- case "str1":
- r.Str1 = string(b)
- case "str2":
- r.Str2 = string(b)
- case "str3":
- r.Str3 = string(b)
- default:
- return fmt.Errorf("unknown column: %q", colName)
- }
- return err
-}
-
-type OptRecords struct {
- C []OptRecord
-}
-
-func (rs *OptRecords) NewModel() orm.ColumnScanner {
- rs.C = append(rs.C, OptRecord{})
- return &rs.C[len(rs.C)-1]
-}
-
-func (OptRecords) AddModel(_ orm.ColumnScanner) error {
- return nil
-}
-
-func (OptRecords) AfterSelect(_ orm.DB) error {
- return nil
-}
-
-var seedDBOnce sync.Once
-
-func seedDB() {
- seedDBOnce.Do(func() {
- if err := _seedDB(); err != nil {
- panic(err)
- }
- })
-}
-
-func _seedDB() error {
- db := benchmarkDB()
- defer db.Close()
-
- _, err := db.Exec(`DROP TABLE IF EXISTS records`)
- if err != nil {
- return err
- }
-
- _, err = db.Exec(`
- CREATE TABLE records(
- num1 serial,
- num2 serial,
- num3 serial,
- str1 text,
- str2 text,
- str3 text
- )
- `)
- if err != nil {
- return err
- }
-
- for i := 0; i < 1000; i++ {
- _, err := db.Exec(`
- INSERT INTO records (str1, str2, str3) VALUES (?, ?, ?)
- `, randSeq(100), randSeq(200), randSeq(300))
- if err != nil {
- return err
- }
- }
-
- err = createTestSchema(db)
- if err != nil {
- return err
- }
-
- for i := 1; i < 100; i++ {
- genre := Genre{
- Id: i,
- Name: fmt.Sprintf("genre %d", i),
- }
- err = db.Insert(&genre)
- if err != nil {
- return err
- }
-
- author := Author{
- ID: i,
- Name: fmt.Sprintf("author %d", i),
- }
- err = db.Insert(&author)
- if err != nil {
- return err
- }
- }
-
- for i := 1; i <= 1000; i++ {
- err = db.Insert(&Book{
- Id: i,
- Title: fmt.Sprintf("book %d", i),
- AuthorID: rand.Intn(99) + 1,
- CreatedAt: time.Now(),
- })
- if err != nil {
- return err
- }
-
- for j := 1; j <= 10; j++ {
- err = db.Insert(&BookGenre{
- BookId: i,
- GenreId: rand.Intn(99) + 1,
- })
- if err != nil {
- return err
- }
-
- err = db.Insert(&Translation{
- BookId: i,
- Lang: fmt.Sprintf("%d", j),
- })
- if err != nil {
- return err
- }
- }
- }
-
- return nil
-}
diff --git a/vendor/github.com/go-pg/pg/conv_test.go b/vendor/github.com/go-pg/pg/conv_test.go
deleted file mode 100644
index 68c00b8..0000000
--- a/vendor/github.com/go-pg/pg/conv_test.go
+++ /dev/null
@@ -1,444 +0,0 @@
-package pg_test
-
-import (
- "database/sql"
- "database/sql/driver"
- "encoding/json"
- "fmt"
- "math"
- "net"
- "reflect"
- "testing"
- "time"
-
- "github.com/go-pg/pg"
- "github.com/go-pg/pg/orm"
- "github.com/go-pg/pg/types"
-)
-
-type JSONMap map[string]interface{}
-
-func (m *JSONMap) Scan(b interface{}) error {
- if b == nil {
- *m = nil
- return nil
- }
- return json.Unmarshal(b.([]byte), m)
-}
-
-func (m JSONMap) Value() (driver.Value, error) {
- b, err := json.Marshal(m)
- if err != nil {
- return nil, err
- }
- return string(b), nil
-}
-
-type (
- StringSlice []string
- IntSlice []int
- Int64Slice []int64
- Float64Slice []float64
-)
-
-type Struct struct {
- Foo string
-}
-
-type conversionTest struct {
- i int
- src, dst, wanted interface{}
- pgtype string
-
- wanterr string
- wantnil bool
- wantzero bool
-}
-
-func unwrap(v interface{}) interface{} {
- if arr, ok := v.(*types.Array); ok {
- return arr.Value()
- }
- if hstore, ok := v.(*types.Hstore); ok {
- return hstore.Value()
- }
- return v
-}
-
-func deref(vi interface{}) interface{} {
- v := reflect.ValueOf(vi)
- for v.Kind() == reflect.Ptr {
- v = v.Elem()
- }
- if v.IsValid() {
- return v.Interface()
- }
- return nil
-}
-
-func zero(v interface{}) interface{} {
- return reflect.Zero(reflect.ValueOf(v).Elem().Type()).Interface()
-}
-
-func (test *conversionTest) String() string {
- return fmt.Sprintf("#%d src=%#v dst=%#v", test.i, test.src, test.dst)
-}
-
-func (test *conversionTest) Assert(t *testing.T, err error) {
- if test.wanterr != "" {
- if err == nil || err.Error() != test.wanterr {
- t.Fatalf("got error %q, wanted %q (%s)", err, test.wanterr, test)
- }
- return
- }
-
- if err != nil {
- t.Fatalf("got error %q, wanted nil (%s)", err, test)
- }
-
- dst := reflect.Indirect(reflect.ValueOf(unwrap(test.dst))).Interface()
-
- if test.wantnil {
- dstValue := reflect.ValueOf(dst)
- if !dstValue.IsValid() {
- return
- }
- if dstValue.IsNil() {
- return
- }
- t.Fatalf("got %#v, wanted nil (%s)", dst, test)
- return
- }
-
- // Remove any intermediate pointers to compare values.
- dst = deref(unwrap(dst))
- src := deref(unwrap(test.src))
-
- if test.wantzero {
- dstValue := reflect.ValueOf(dst)
- switch dstValue.Kind() {
- case reflect.Slice, reflect.Map:
- if dstValue.IsNil() {
- t.Fatalf("got nil, wanted zero value")
- }
- if dstValue.Len() != 0 {
- t.Fatalf("got %d items, wanted 0", dstValue.Len())
- }
- default:
- zero := zero(test.dst)
- if dst != zero {
- t.Fatalf("%#v != %#v (%s)", dst, zero, test)
- }
- }
- return
- }
-
- if dstTime, ok := dst.(time.Time); ok {
- srcTime := src.(time.Time)
- if dstTime.Unix() != srcTime.Unix() {
- t.Fatalf("%#v != %#v", dstTime, srcTime)
- }
- return
- }
-
- if dstTimes, ok := dst.([]time.Time); ok {
- srcTimes := src.([]time.Time)
- for i, dstTime := range dstTimes {
- srcTime := srcTimes[i]
- if dstTime.Unix() != srcTime.Unix() {
- t.Fatalf("%#v != %#v", dstTime, srcTime)
- }
- }
- return
- }
-
- wanted := test.wanted
- if wanted == nil {
- wanted = src
- }
- if !reflect.DeepEqual(dst, wanted) {
- t.Fatalf("%#v != %#v (%s)", dst, wanted, test)
- }
-}
-
-func conversionTests() []conversionTest {
- return []conversionTest{
- {src: nil, dst: nil, wanterr: "pg: Scan(nil)"},
- {src: nil, dst: new(uintptr), wanterr: "pg: Scan(unsupported uintptr)"},
-
- {src: nil, dst: true, pgtype: "bool", wanterr: "pg: Scan(non-pointer bool)"},
- {src: nil, dst: new(*bool), pgtype: "bool", wantnil: true},
- {src: nil, dst: new(bool), pgtype: "bool", wantzero: true},
- {src: true, dst: new(bool), pgtype: "bool"},
- {src: true, dst: new(*bool), pgtype: "bool"},
- {src: 1, dst: new(bool), wanted: true},
-
- {src: nil, dst: "", pgtype: "text", wanterr: "pg: Scan(non-pointer string)"},
- {src: nil, dst: new(string), pgtype: "text", wantzero: true},
- {src: nil, dst: new(*string), pgtype: "text", wantnil: true},
- {src: "hello world", dst: new(string), pgtype: "text"},
- {src: "hello world", dst: new(*string), pgtype: "text"},
- {src: "'\"\000", dst: new(string), wanted: `'"`, pgtype: "text"},
-
- {src: nil, dst: []byte(nil), pgtype: "bytea", wanterr: "pg: Scan(non-pointer []uint8)"},
- {src: nil, dst: new([]byte), pgtype: "bytea", wantnil: true},
- {src: []byte("hello world\000"), dst: new([]byte), pgtype: "bytea"},
- {src: []byte{}, dst: new([]byte), pgtype: "bytea", wantzero: true},
-
- {src: nil, dst: int8(0), pgtype: "smallint", wanterr: "pg: Scan(non-pointer int8)"},
- {src: nil, dst: new(int8), pgtype: "smallint", wantzero: true},
- {src: int8(math.MaxInt8), dst: new(int8), pgtype: "smallint"},
- {src: int8(math.MaxInt8), dst: new(*int8), pgtype: "smallint"},
- {src: int8(math.MinInt8), dst: new(int8), pgtype: "smallint"},
-
- {src: nil, dst: int16(0), pgtype: "smallint", wanterr: "pg: Scan(non-pointer int16)"},
- {src: nil, dst: new(int16), pgtype: "smallint", wantzero: true},
- {src: int16(math.MaxInt16), dst: new(int16), pgtype: "smallint"},
- {src: int16(math.MaxInt16), dst: new(*int16), pgtype: "smallint"},
- {src: int16(math.MinInt16), dst: new(int16), pgtype: "smallint"},
-
- {src: nil, dst: int32(0), pgtype: "int", wanterr: "pg: Scan(non-pointer int32)"},
- {src: nil, dst: new(int32), pgtype: "int", wantzero: true},
- {src: int32(math.MaxInt32), dst: new(int32), pgtype: "int"},
- {src: int32(math.MaxInt32), dst: new(*int32), pgtype: "int"},
- {src: int32(math.MinInt32), dst: new(int32), pgtype: "int"},
-
- {src: nil, dst: int64(0), pgtype: "bigint", wanterr: "pg: Scan(non-pointer int64)"},
- {src: nil, dst: new(int64), pgtype: "bigint", wantzero: true},
- {src: int64(math.MaxInt64), dst: new(int64), pgtype: "bigint"},
- {src: int64(math.MaxInt64), dst: new(*int64), pgtype: "bigint"},
- {src: int64(math.MinInt64), dst: new(int64), pgtype: "bigint"},
-
- {src: nil, dst: int(0), pgtype: "bigint", wanterr: "pg: Scan(non-pointer int)"},
- {src: nil, dst: new(int), pgtype: "bigint", wantzero: true},
- {src: int(math.MaxInt64), dst: new(int), pgtype: "bigint"},
- {src: int(math.MaxInt64), dst: new(*int), pgtype: "bigint"},
- {src: int(math.MinInt32), dst: new(int), pgtype: "bigint"},
-
- {src: nil, dst: uint8(0), pgtype: "smallint", wanterr: "pg: Scan(non-pointer uint8)"},
- {src: nil, dst: new(uint8), pgtype: "smallint", wantzero: true},
- {src: uint8(math.MaxUint8), dst: new(uint8), pgtype: "smallint"},
- {src: uint8(math.MaxUint8), dst: new(*uint8), pgtype: "smallint"},
-
- {src: nil, dst: uint16(0), pgtype: "smallint", wanterr: "pg: Scan(non-pointer uint16)"},
- {src: nil, dst: new(uint16), pgtype: "smallint", wantzero: true},
- {src: uint16(math.MaxUint16), dst: new(uint16), pgtype: "int"},
- {src: uint16(math.MaxUint16), dst: new(*uint16), pgtype: "int"},
-
- {src: nil, dst: uint32(0), pgtype: "bigint", wanterr: "pg: Scan(non-pointer uint32)"},
- {src: nil, dst: new(uint32), pgtype: "bigint", wantzero: true},
- {src: uint32(math.MaxUint32), dst: new(uint32), pgtype: "bigint"},
- {src: uint32(math.MaxUint32), dst: new(*uint32), pgtype: "bigint"},
-
- {src: nil, dst: uint64(0), pgtype: "bigint", wanterr: "pg: Scan(non-pointer uint64)"},
- {src: nil, dst: new(uint64), pgtype: "bigint", wantzero: true},
- {src: uint64(math.MaxUint64), dst: new(uint64)},
- {src: uint64(math.MaxUint64), dst: new(*uint64)},
- {src: uint64(math.MaxUint32), dst: new(uint64), pgtype: "bigint"},
-
- {src: nil, dst: uint(0), pgtype: "smallint", wanterr: "pg: Scan(non-pointer uint)"},
- {src: nil, dst: new(uint), pgtype: "bigint", wantzero: true},
- {src: uint(math.MaxUint64), dst: new(uint)},
- {src: uint(math.MaxUint64), dst: new(*uint)},
- {src: uint(math.MaxUint32), dst: new(uint), pgtype: "bigint"},
-
- {src: nil, dst: float32(0), pgtype: "decimal", wanterr: "pg: Scan(non-pointer float32)"},
- {src: nil, dst: new(float32), pgtype: "decimal", wantzero: true},
- {src: float32(math.MaxFloat32), dst: new(float32), pgtype: "decimal"},
- {src: float32(math.MaxFloat32), dst: new(*float32), pgtype: "decimal"},
- {src: float32(math.SmallestNonzeroFloat32), dst: new(float32), pgtype: "decimal"},
-
- {src: nil, dst: float64(0), pgtype: "decimal", wanterr: "pg: Scan(non-pointer float64)"},
- {src: nil, dst: new(float64), pgtype: "decimal", wantzero: true},
- {src: float64(math.MaxFloat64), dst: new(float64), pgtype: "decimal"},
- {src: float64(math.MaxFloat64), dst: new(*float64), pgtype: "decimal"},
- {src: float64(math.SmallestNonzeroFloat64), dst: new(float64), pgtype: "decimal"},
-
- {src: nil, dst: []int(nil), pgtype: "jsonb", wanterr: "pg: Scan(non-pointer []int)"},
- {src: nil, dst: new([]int), pgtype: "jsonb", wantnil: true},
- {src: []int(nil), dst: new([]int), pgtype: "jsonb", wantnil: true},
- {src: []int{}, dst: new([]int), pgtype: "jsonb", wantzero: true},
- {src: []int{1, 2, 3}, dst: new([]int), pgtype: "jsonb"},
- {src: IntSlice{1, 2, 3}, dst: new(IntSlice), pgtype: "jsonb"},
-
- {src: nil, dst: pg.Array([]int(nil)), pgtype: "int[]", wanterr: "pg: Scan(non-pointer []int)"},
- {src: pg.Array([]int(nil)), dst: pg.Array(new([]int)), pgtype: "int[]", wantnil: true},
- {src: pg.Array([]int{}), dst: pg.Array(new([]int)), pgtype: "int[]"},
- {src: pg.Array([]int{1, 2, 3}), dst: pg.Array(new([]int)), pgtype: "int[]"},
-
- {src: nil, dst: pg.Array([]int64(nil)), pgtype: "bigint[]", wanterr: "pg: Scan(non-pointer []int64)"},
- {src: nil, dst: pg.Array(new([]int64)), pgtype: "bigint[]", wantnil: true},
- {src: pg.Array([]int64(nil)), dst: pg.Array(new([]int64)), pgtype: "bigint[]", wantnil: true},
- {src: pg.Array([]int64{}), dst: pg.Array(new([]int64)), pgtype: "bigint[]"},
- {src: pg.Array([]int64{1, 2, 3}), dst: pg.Array(new([]int64)), pgtype: "bigint[]"},
-
- {src: nil, dst: pg.Array([]float64(nil)), pgtype: "decimal[]", wanterr: "pg: Scan(non-pointer []float64)"},
- {src: nil, dst: pg.Array(new([]float64)), pgtype: "decimal[]", wantnil: true},
- {src: pg.Array([]float64(nil)), dst: pg.Array(new([]float64)), pgtype: "decimal[]", wantnil: true},
- {src: pg.Array([]float64{}), dst: pg.Array(new([]float64)), pgtype: "decimal[]"},
- {src: pg.Array([]float64{1.1, 2.22, 3.333}), dst: pg.Array(new([]float64)), pgtype: "decimal[]"},
-
- {src: nil, dst: pg.Array([]string(nil)), pgtype: "text[]", wanterr: "pg: Scan(non-pointer []string)"},
- {src: nil, dst: pg.Array(new([]string)), pgtype: "text[]", wantnil: true},
- {src: pg.Array([]string(nil)), dst: pg.Array(new([]string)), pgtype: "text[]", wantnil: true},
- {src: pg.Array([]string{}), dst: pg.Array(new([]string)), pgtype: "text[]"},
- {src: pg.Array([]string{"one", "two", "three"}), dst: pg.Array(new([]string)), pgtype: "text[]"},
- {src: pg.Array([]string{`'"{}`}), dst: pg.Array(new([]string)), pgtype: "text[]"},
-
- {src: nil, dst: pg.Array([][]string(nil)), pgtype: "text[][]", wanterr: "pg: Scan(non-pointer [][]string)"},
- {src: nil, dst: pg.Array(new([][]string)), pgtype: "text[][]", wantnil: true},
- {src: pg.Array([][]string(nil)), dst: pg.Array(new([]string)), pgtype: "text[][]", wantnil: true},
- {src: pg.Array([][]string{}), dst: pg.Array(new([][]string)), pgtype: "text[][]"},
- {src: pg.Array([][]string{{"one", "two"}, {"three", "four"}}), dst: pg.Array(new([][]string)), pgtype: "text[][]"},
- {src: pg.Array([][]string{{`'"\{}`}}), dst: pg.Array(new([][]string)), pgtype: "text[][]"},
-
- {src: nil, dst: pg.Hstore(map[string]string(nil)), pgtype: "hstore", wanterr: "pg: Scan(non-pointer map[string]string)"},
- {src: nil, dst: pg.Hstore(new(map[string]string)), pgtype: "hstore", wantnil: true},
- {src: pg.Hstore(map[string]string(nil)), dst: pg.Hstore(new(map[string]string)), pgtype: "hstore", wantnil: true},
- {src: pg.Hstore(map[string]string{}), dst: pg.Hstore(new(map[string]string)), pgtype: "hstore"},
- {src: pg.Hstore(map[string]string{"foo": "bar"}), dst: pg.Hstore(new(map[string]string)), pgtype: "hstore"},
- {src: pg.Hstore(map[string]string{`'"\{}=>`: `'"\{}=>`}), dst: pg.Hstore(new(map[string]string)), pgtype: "hstore"},
-
- {src: nil, dst: sql.NullBool{}, pgtype: "bool", wanterr: "pg: Scan(non-pointer sql.NullBool)"},
- {src: nil, dst: new(*sql.NullBool), pgtype: "bool", wantnil: true},
- {src: nil, dst: new(sql.NullBool), pgtype: "bool", wanted: sql.NullBool{}},
- {src: &sql.NullBool{}, dst: new(sql.NullBool), pgtype: "bool"},
- {src: &sql.NullBool{Valid: true}, dst: new(sql.NullBool), pgtype: "bool"},
- {src: &sql.NullBool{Valid: true, Bool: true}, dst: new(sql.NullBool), pgtype: "bool"},
-
- {src: &sql.NullString{}, dst: new(sql.NullString), pgtype: "text"},
- {src: &sql.NullString{Valid: true}, dst: new(sql.NullString), pgtype: "text"},
- {src: &sql.NullString{Valid: true, String: "foo"}, dst: new(sql.NullString), pgtype: "text"},
-
- {src: &sql.NullInt64{}, dst: new(sql.NullInt64), pgtype: "bigint"},
- {src: &sql.NullInt64{Valid: true}, dst: new(sql.NullInt64), pgtype: "bigint"},
- {src: &sql.NullInt64{Valid: true, Int64: math.MaxInt64}, dst: new(sql.NullInt64), pgtype: "bigint"},
-
- {src: &sql.NullFloat64{}, dst: new(sql.NullFloat64), pgtype: "decimal"},
- {src: &sql.NullFloat64{Valid: true}, dst: new(sql.NullFloat64), pgtype: "decimal"},
- {src: &sql.NullFloat64{Valid: true, Float64: math.MaxFloat64}, dst: new(sql.NullFloat64), pgtype: "decimal"},
-
- {src: nil, dst: customStrSlice{}, wanterr: "pg: Scan(non-pointer pg_test.customStrSlice)"},
- {src: nil, dst: new(customStrSlice), wantnil: true},
- {src: nil, dst: new(*customStrSlice), wantnil: true},
- {src: customStrSlice{}, dst: new(customStrSlice), wantzero: true},
- {src: customStrSlice{"one", "two"}, dst: new(customStrSlice)},
-
- {src: nil, dst: time.Time{}, wanterr: "pg: Scan(non-pointer time.Time)"},
- {src: nil, dst: new(time.Time), pgtype: "timestamptz", wantzero: true},
- {src: nil, dst: new(*time.Time), pgtype: "timestamptz", wantnil: true},
- {src: time.Now(), dst: new(time.Time), pgtype: "timestamptz"},
- {src: time.Now(), dst: new(*time.Time), pgtype: "timestamptz"},
- {src: time.Now().UTC(), dst: new(time.Time), pgtype: "timestamptz"},
- {src: time.Time{}, dst: new(time.Time), pgtype: "timestamptz"},
-
- {src: nil, dst: pg.Array([]time.Time(nil)), pgtype: "timestamptz[]", wanterr: "pg: Scan(non-pointer []time.Time)"},
- {src: nil, dst: pg.Array(new([]time.Time)), pgtype: "timestamptz[]", wantnil: true},
- {src: pg.Array([]time.Time(nil)), dst: pg.Array(new([]time.Time)), pgtype: "timestamptz[]", wantnil: true},
- {src: pg.Array([]time.Time{}), dst: pg.Array(new([]time.Time)), pgtype: "timestamptz[]"},
- {src: pg.Array([]time.Time{time.Now(), time.Now(), time.Now()}), dst: pg.Array(new([]time.Time)), pgtype: "timestamptz[]"},
-
- {src: nil, dst: pg.Ints{}, wanterr: "pg: Scan(non-pointer pg.Ints)"},
- {src: 1, dst: new(pg.Ints), wanted: pg.Ints{1}},
-
- {src: nil, dst: pg.Strings{}, wanterr: "pg: Scan(non-pointer pg.Strings)"},
- {src: "hello", dst: new(pg.Strings), wanted: pg.Strings{"hello"}},
-
- {src: nil, dst: pg.IntSet{}, wanterr: "pg: Scan(non-pointer pg.IntSet)"},
- {src: 1, dst: new(pg.IntSet), wanted: pg.IntSet{1: struct{}{}}},
-
- {src: nil, dst: JSONMap{}, pgtype: "json", wanterr: "pg: Scan(non-pointer pg_test.JSONMap)"},
- {src: nil, dst: new(JSONMap), pgtype: "json", wantnil: true},
- {src: nil, dst: new(*JSONMap), pgtype: "json", wantnil: true},
- {src: JSONMap{}, dst: new(JSONMap), pgtype: "json"},
- {src: JSONMap{}, dst: new(*JSONMap), pgtype: "json"},
- {src: JSONMap{"foo": "bar"}, dst: new(JSONMap), pgtype: "json"},
- {src: `{"foo": "bar"}`, dst: new(JSONMap), pgtype: "json", wanted: JSONMap{"foo": "bar"}},
-
- {src: nil, dst: Struct{}, pgtype: "json", wanterr: "pg: Scan(non-pointer pg_test.Struct)"},
- {src: nil, dst: new(*Struct), pgtype: "json", wantnil: true},
- {src: nil, dst: new(Struct), pgtype: "json", wantzero: true},
- {src: Struct{}, dst: new(Struct), pgtype: "json"},
- {src: Struct{Foo: "bar"}, dst: new(Struct), pgtype: "json"},
- {src: `{"foo": "bar"}`, dst: new(Struct), wanted: Struct{Foo: "bar"}},
-
- {src: nil, dst: new(net.IP), wanted: net.IP(nil), pgtype: "inet"},
- {src: net.ParseIP("127.0.0.1"), dst: new(net.IP), pgtype: "inet"},
- {src: net.ParseIP("::10.2.3.4"), dst: new(net.IP), pgtype: "inet"},
- {src: net.ParseIP("::ffff:10.4.3.2"), dst: new(net.IP), pgtype: "inet"},
-
- {src: nil, dst: (*net.IPNet)(nil), pgtype: "cidr", wanterr: "pg: Scan(non-pointer *net.IPNet)"},
- {src: nil, dst: new(net.IPNet), wanted: net.IPNet{}, pgtype: "cidr"},
- {src: nil, dst: mustParseCIDR("192.168.100.128/25"), wanted: net.IPNet{}, pgtype: "cidr"},
- {src: mustParseCIDR("192.168.100.128/25"), dst: new(net.IPNet), pgtype: "cidr"},
- {src: mustParseCIDR("2001:4f8:3:ba::/64"), dst: new(net.IPNet), pgtype: "cidr"},
- {src: mustParseCIDR("2001:4f8:3:ba:2e0:81ff:fe22:d1f1/128"), dst: new(net.IPNet), pgtype: "cidr"},
- }
-}
-
-func TestConversion(t *testing.T) {
- db := pg.Connect(pgOptions())
-
- for i, test := range conversionTests() {
- test.i = i
-
- var scanner orm.ColumnScanner
- if v, ok := test.dst.(orm.ColumnScanner); ok {
- scanner = v
- } else {
- scanner = pg.Scan(test.dst)
- }
-
- _, err := db.QueryOne(scanner, "SELECT (?) AS dst", test.src)
- test.Assert(t, err)
- }
-
- for i, test := range conversionTests() {
- test.i = i
-
- var scanner orm.ColumnScanner
- if v, ok := test.dst.(orm.ColumnScanner); ok {
- scanner = v
- } else {
- scanner = pg.Scan(test.dst)
- }
-
- err := db.Model().ColumnExpr("(?) AS dst", test.src).Select(scanner)
- test.Assert(t, err)
- }
-
- for i, test := range conversionTests() {
- test.i = i
-
- if test.pgtype == "" {
- continue
- }
-
- stmt, err := db.Prepare(fmt.Sprintf("SELECT ($1::%s) AS dst", test.pgtype))
- if err != nil {
- t.Fatal(err)
- }
-
- var scanner orm.ColumnScanner
- if v, ok := test.dst.(orm.ColumnScanner); ok {
- scanner = v
- } else {
- scanner = pg.Scan(test.dst)
- }
-
- _, err = stmt.QueryOne(scanner, test.src)
- test.Assert(t, err)
-
- if err := stmt.Close(); err != nil {
- t.Fatal(err)
- }
- }
-}
-
-func mustParseCIDR(s string) *net.IPNet {
- _, ipnet, err := net.ParseCIDR(s)
- if err != nil {
- panic(err)
- }
- return ipnet
-}
diff --git a/vendor/github.com/go-pg/pg/db.go b/vendor/github.com/go-pg/pg/db.go
deleted file mode 100644
index dcc1897..0000000
--- a/vendor/github.com/go-pg/pg/db.go
+++ /dev/null
@@ -1,428 +0,0 @@
-package pg
-
-import (
- "fmt"
- "io"
- "time"
-
- "github.com/go-pg/pg/internal"
- "github.com/go-pg/pg/internal/pool"
- "github.com/go-pg/pg/orm"
-)
-
-// Connect connects to a database using provided options.
-//
-// The returned DB is safe for concurrent use by multiple goroutines
-// and maintains its own connection pool.
-func Connect(opt *Options) *DB {
- opt.init()
- return &DB{
- opt: opt,
- pool: newConnPool(opt),
- }
-}
-
-var _ orm.DB = (*DB)(nil)
-
-func (db *DB) String() string {
- return fmt.Sprintf("DB", db.opt.Addr, db.fmter)
-}
-
-// Options returns read-only Options that were used to connect to the DB.
-func (db *DB) Options() *Options {
- return db.opt
-}
-
-type PoolStats pool.Stats
-
-// PoolStats returns connection pool stats.
-func (db *DB) PoolStats() *PoolStats {
- stats := db.pool.Stats()
- return (*PoolStats)(stats)
-}
-
-// WithTimeout returns a DB that uses d as the read/write timeout.
-func (db *DB) WithTimeout(d time.Duration) *DB {
- newopt := *db.opt
- newopt.ReadTimeout = d
- newopt.WriteTimeout = d
-
- return &DB{
- opt: &newopt,
- pool: db.pool,
- fmter: db.fmter,
-
- queryProcessedHooks: copyQueryProcessedHooks(db.queryProcessedHooks),
- }
-}
-
-// WithParam returns a DB that replaces the param with the value in queries.
-func (db *DB) WithParam(param string, value interface{}) *DB {
- return &DB{
- opt: db.opt,
- pool: db.pool,
- fmter: db.fmter.WithParam(param, value),
-
- queryProcessedHooks: copyQueryProcessedHooks(db.queryProcessedHooks),
- }
-}
-
-func (db *DB) retryBackoff(retry int) time.Duration {
- return internal.RetryBackoff(retry, db.opt.MinRetryBackoff, db.opt.MaxRetryBackoff)
-}
-
-func (db *DB) conn() (*pool.Conn, error) {
- cn, _, err := db.pool.Get()
- if err != nil {
- return nil, err
- }
-
- cn.SetTimeout(db.opt.ReadTimeout, db.opt.WriteTimeout)
-
- if cn.InitedAt.IsZero() {
- cn.InitedAt = time.Now()
- if err := db.initConn(cn); err != nil {
- _ = db.pool.Remove(cn)
- return nil, err
- }
- }
-
- return cn, nil
-}
-
-func (db *DB) initConn(cn *pool.Conn) error {
- if db.opt.TLSConfig != nil {
- if err := enableSSL(cn, db.opt.TLSConfig); err != nil {
- return err
- }
- }
-
- err := startup(cn, db.opt.User, db.opt.Password, db.opt.Database)
- if err != nil {
- return err
- }
-
- if db.opt.OnConnect != nil {
- dbConn := &DB{
- opt: db.opt,
- pool: pool.NewSingleConnPool(cn),
- fmter: db.fmter,
- }
- return db.opt.OnConnect(dbConn)
- }
-
- return nil
-}
-
-func (db *DB) freeConn(cn *pool.Conn, err error) error {
- if !isBadConn(err, false) {
- return db.pool.Put(cn)
- }
- return db.pool.Remove(cn)
-}
-
-func (db *DB) shouldRetry(err error) bool {
- if err == nil {
- return false
- }
- if pgerr, ok := err.(Error); ok {
- switch pgerr.Field('C') {
- case "40001": // serialization_failure
- return true
- case "55000": // attempted to delete invisible tuple
- return true
- case "57014": // statement_timeout
- return db.opt.RetryStatementTimeout
- default:
- return false
- }
- }
- return isNetworkError(err)
-}
-
-// Close closes the database client, releasing any open resources.
-//
-// It is rare to Close a DB, as the DB handle is meant to be
-// long-lived and shared between many goroutines.
-func (db *DB) Close() error {
- return db.pool.Close()
-}
-
-// Exec executes a query ignoring returned rows. The params are for any
-// placeholders in the query.
-func (db *DB) Exec(query interface{}, params ...interface{}) (res orm.Result, err error) {
- for attempt := 0; attempt <= db.opt.MaxRetries; attempt++ {
- var cn *pool.Conn
-
- if attempt >= 1 {
- time.Sleep(db.retryBackoff(attempt - 1))
- }
-
- cn, err = db.conn()
- if err != nil {
- continue
- }
-
- start := time.Now()
- res, err = db.simpleQuery(cn, query, params...)
- db.freeConn(cn, err)
- db.queryProcessed(db, start, query, params, attempt, res, err)
-
- if !db.shouldRetry(err) {
- break
- }
- }
- return res, err
-}
-
-// ExecOne acts like Exec, but query must affect only one row. It
-// returns ErrNoRows error when query returns zero rows or
-// ErrMultiRows when query returns multiple rows.
-func (db *DB) ExecOne(query interface{}, params ...interface{}) (orm.Result, error) {
- res, err := db.Exec(query, params...)
- if err != nil {
- return nil, err
- }
-
- if err := internal.AssertOneRow(res.RowsAffected()); err != nil {
- return nil, err
- }
- return res, nil
-}
-
-// Query executes a query that returns rows, typically a SELECT.
-// The params are for any placeholders in the query.
-func (db *DB) Query(model, query interface{}, params ...interface{}) (res orm.Result, err error) {
- for attempt := 0; attempt <= db.opt.MaxRetries; attempt++ {
- var cn *pool.Conn
-
- if attempt >= 1 {
- time.Sleep(db.retryBackoff(attempt - 1))
- }
-
- cn, err = db.conn()
- if err != nil {
- continue
- }
-
- start := time.Now()
- res, err = db.simpleQueryData(cn, model, query, params...)
- db.freeConn(cn, err)
- db.queryProcessed(db, start, query, params, attempt, res, err)
-
- if !db.shouldRetry(err) {
- break
- }
- }
- if err != nil {
- return nil, err
- }
-
- if mod := res.Model(); mod != nil && res.RowsReturned() > 0 {
- if err = mod.AfterQuery(db); err != nil {
- return res, err
- }
- }
-
- return res, nil
-}
-
-// QueryOne acts like Query, but query must return only one row. It
-// returns ErrNoRows error when query returns zero rows or
-// ErrMultiRows when query returns multiple rows.
-func (db *DB) QueryOne(model, query interface{}, params ...interface{}) (orm.Result, error) {
- res, err := db.Query(model, query, params...)
- if err != nil {
- return nil, err
- }
-
- if err := internal.AssertOneRow(res.RowsAffected()); err != nil {
- return nil, err
- }
- return res, nil
-}
-
-// Listen listens for notifications sent with NOTIFY command.
-func (db *DB) Listen(channels ...string) *Listener {
- ln := &Listener{
- db: db,
- }
- _ = ln.Listen(channels...)
- return ln
-}
-
-// CopyFrom copies data from reader to a table.
-func (db *DB) CopyFrom(r io.Reader, query interface{}, params ...interface{}) (orm.Result, error) {
- cn, err := db.conn()
- if err != nil {
- return nil, err
- }
-
- res, err := db.copyFrom(cn, r, query, params...)
- db.freeConn(cn, err)
- return res, err
-}
-
-func (db *DB) copyFrom(cn *pool.Conn, r io.Reader, query interface{}, params ...interface{}) (orm.Result, error) {
- if err := writeQueryMsg(cn.Writer, db, query, params...); err != nil {
- return nil, err
- }
-
- if err := cn.FlushWriter(); err != nil {
- return nil, err
- }
-
- if err := readCopyInResponse(cn); err != nil {
- return nil, err
- }
-
- for {
- if err := writeCopyData(cn.Writer, r); err != nil {
- if err == io.EOF {
- break
- }
- return nil, err
- }
-
- if err := cn.FlushWriter(); err != nil {
- return nil, err
- }
- }
-
- writeCopyDone(cn.Writer)
- if err := cn.FlushWriter(); err != nil {
- return nil, err
- }
-
- return readReadyForQuery(cn)
-}
-
-// CopyTo copies data from a table to writer.
-func (db *DB) CopyTo(w io.Writer, query interface{}, params ...interface{}) (orm.Result, error) {
- cn, err := db.conn()
- if err != nil {
- return nil, err
- }
-
- res, err := db.copyTo(cn, w, query, params...)
- if err != nil {
- db.freeConn(cn, err)
- return nil, err
- }
-
- db.pool.Put(cn)
- return res, nil
-}
-
-func (db *DB) copyTo(cn *pool.Conn, w io.Writer, query interface{}, params ...interface{}) (orm.Result, error) {
- if err := writeQueryMsg(cn.Writer, db, query, params...); err != nil {
- return nil, err
- }
-
- if err := cn.FlushWriter(); err != nil {
- return nil, err
- }
-
- if err := readCopyOutResponse(cn); err != nil {
- return nil, err
- }
-
- return readCopyData(cn, w)
-}
-
-// Model returns new query for the model.
-func (db *DB) Model(model ...interface{}) *orm.Query {
- return orm.NewQuery(db, model...)
-}
-
-// Select selects the model by primary key.
-func (db *DB) Select(model interface{}) error {
- return orm.Select(db, model)
-}
-
-// Insert inserts the model updating primary keys if they are empty.
-func (db *DB) Insert(model ...interface{}) error {
- return orm.Insert(db, model...)
-}
-
-// Update updates the model by primary key.
-func (db *DB) Update(model ...interface{}) error {
- return orm.Update(db, model...)
-}
-
-// Delete deletes the model by primary key.
-func (db *DB) Delete(model interface{}) error {
- return orm.Delete(db, model)
-}
-
-// CreateTable creates table for the model. It recognizes following field tags:
-// - notnull - sets NOT NULL constraint.
-// - unique - sets UNIQUE constraint.
-// - default:value - sets default value.
-func (db *DB) CreateTable(model interface{}, opt *orm.CreateTableOptions) error {
- _, err := orm.CreateTable(db, model, opt)
- return err
-}
-
-// DropTable drops table for the model.
-func (db *DB) DropTable(model interface{}, opt *orm.DropTableOptions) error {
- _, err := orm.DropTable(db, model, opt)
- return err
-}
-
-func (db *DB) FormatQuery(dst []byte, query string, params ...interface{}) []byte {
- return db.fmter.Append(dst, query, params...)
-}
-
-func (db *DB) cancelRequest(processId, secretKey int32) error {
- cn, err := db.pool.NewConn()
- if err != nil {
- return err
- }
-
- writeCancelRequestMsg(cn.Writer, processId, secretKey)
- if err = cn.FlushWriter(); err != nil {
- return err
- }
- cn.Close()
-
- return nil
-}
-
-func (db *DB) simpleQuery(
- cn *pool.Conn, query interface{}, params ...interface{},
-) (orm.Result, error) {
- if err := writeQueryMsg(cn.Writer, db, query, params...); err != nil {
- return nil, err
- }
-
- if err := cn.FlushWriter(); err != nil {
- return nil, err
- }
-
- res, err := readSimpleQuery(cn)
- if err != nil {
- return nil, err
- }
-
- return res, nil
-}
-
-func (db *DB) simpleQueryData(
- cn *pool.Conn, model, query interface{}, params ...interface{},
-) (orm.Result, error) {
- if err := writeQueryMsg(cn.Writer, db, query, params...); err != nil {
- return nil, err
- }
-
- if err := cn.FlushWriter(); err != nil {
- return nil, err
- }
-
- res, err := readSimpleQueryData(cn, model)
- if err != nil {
- return nil, err
- }
-
- return res, nil
-}
diff --git a/vendor/github.com/go-pg/pg/db_context.go b/vendor/github.com/go-pg/pg/db_context.go
deleted file mode 100644
index 088a179..0000000
--- a/vendor/github.com/go-pg/pg/db_context.go
+++ /dev/null
@@ -1,39 +0,0 @@
-// +build go1.7
-
-package pg
-
-import (
- "context"
-
- "github.com/go-pg/pg/internal/pool"
- "github.com/go-pg/pg/orm"
-)
-
-// DB is a database handle representing a pool of zero or more
-// underlying connections. It's safe for concurrent use by multiple
-// goroutines.
-type DB struct {
- opt *Options
- pool pool.Pooler
- fmter orm.Formatter
-
- queryProcessedHooks []queryProcessedHook
-
- ctx context.Context
-}
-
-func (db *DB) Context() context.Context {
- if db.ctx != nil {
- return db.ctx
- }
- return context.Background()
-}
-
-func (db *DB) WithContext(ctx context.Context) *DB {
- if ctx == nil {
- panic("nil context")
- }
- cp := *db
- cp.ctx = ctx
- return &cp
-}
diff --git a/vendor/github.com/go-pg/pg/db_no_context.go b/vendor/github.com/go-pg/pg/db_no_context.go
deleted file mode 100644
index d92d31f..0000000
--- a/vendor/github.com/go-pg/pg/db_no_context.go
+++ /dev/null
@@ -1,19 +0,0 @@
-// +build !go1.7
-
-package pg
-
-import (
- "github.com/go-pg/pg/internal/pool"
- "github.com/go-pg/pg/orm"
-)
-
-// DB is a database handle representing a pool of zero or more
-// underlying connections. It's safe for concurrent use by multiple
-// goroutines.
-type DB struct {
- opt *Options
- pool pool.Pooler
- fmter orm.Formatter
-
- queryProcessedHooks []queryProcessedHook
-}
diff --git a/vendor/github.com/go-pg/pg/db_test.go b/vendor/github.com/go-pg/pg/db_test.go
deleted file mode 100644
index b57eb77..0000000
--- a/vendor/github.com/go-pg/pg/db_test.go
+++ /dev/null
@@ -1,1529 +0,0 @@
-package pg_test
-
-import (
- "bytes"
- "crypto/tls"
- "database/sql"
- "fmt"
- "net"
- "testing"
- "time"
-
- "github.com/go-pg/pg"
- "github.com/go-pg/pg/orm"
-
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-)
-
-func TestGinkgo(t *testing.T) {
- RegisterFailHandler(Fail)
- RunSpecs(t, "pg")
-}
-
-func pgOptions() *pg.Options {
- return &pg.Options{
- User: "postgres",
- Database: "postgres",
-
- TLSConfig: &tls.Config{
- InsecureSkipVerify: true,
- },
-
- MaxRetries: 1,
- MinRetryBackoff: -1,
-
- DialTimeout: 30 * time.Second,
- ReadTimeout: 10 * time.Second,
- WriteTimeout: 10 * time.Second,
-
- PoolSize: 10,
- PoolTimeout: 30 * time.Second,
- IdleTimeout: 10 * time.Second,
- MaxAge: 10 * time.Second,
- IdleCheckFrequency: 100 * time.Millisecond,
- }
-}
-
-func TestDBString(t *testing.T) {
- db := pg.Connect(pgOptions())
- wanted := `DB`
- if db.String() != wanted {
- t.Fatalf("got %q, wanted %q", db.String(), wanted)
- }
-
- db = db.WithParam("param1", "value1").WithParam("param2", 2)
- wanted = `DB`
- if db.String() != wanted {
- t.Fatalf("got %q, wanted %q", db.String(), wanted)
- }
-}
-
-func TestOnConnect(t *testing.T) {
- opt := pgOptions()
- opt.OnConnect = func(db *pg.DB) error {
- _, err := db.Exec("SET application_name = 'myapp'")
- return err
- }
- db := pg.Connect(opt)
-
- var name string
- _, err := db.QueryOne(pg.Scan(&name), "SHOW application_name")
- if err != nil {
- t.Fatal(err)
- }
- if name != "myapp" {
- t.Fatalf(`got %q, wanted "myapp"`, name)
- }
-}
-
-func TestEmptyQuery(t *testing.T) {
- db := pg.Connect(pgOptions())
-
- assert := func(err error) {
- if err == nil {
- t.Fatal("error expected")
- }
- if err.Error() != "pg: query is empty" {
- t.Fatal(err)
- }
- }
-
- _, err := db.Exec("")
- assert(err)
-
- _, err = db.Query(pg.Discard, "")
- assert(err)
-
- stmt, err := db.Prepare("")
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = stmt.Exec()
- assert(err)
-}
-
-var _ = Describe("DB", func() {
- var db *pg.DB
- var tx *pg.Tx
-
- BeforeEach(func() {
- db = pg.Connect(pgOptions())
-
- var err error
- tx, err = db.Begin()
- Expect(err).NotTo(HaveOccurred())
- })
-
- AfterEach(func() {
- Expect(db.Close()).NotTo(HaveOccurred())
- })
-
- Describe("Query", func() {
- It("does not return an error when there are no results", func() {
- _, err := db.Query(pg.Discard, "SELECT 1 WHERE 1 = 2")
- Expect(err).NotTo(HaveOccurred())
- })
-
- It("does not return an error when there are no results", func() {
- _, err := tx.Query(pg.Discard, "SELECT 1 WHERE 1 = 2")
- Expect(err).NotTo(HaveOccurred())
- })
- })
-
- Describe("QueryOne", func() {
- It("returns pg.ErrNoRows when there are no results", func() {
- _, err := db.QueryOne(pg.Discard, "SELECT 1 WHERE 1 = 2")
- Expect(err).To(Equal(pg.ErrNoRows))
- })
-
- It("returns pg.ErrNoRows when there are no results", func() {
- _, err := tx.QueryOne(pg.Discard, "SELECT 1 WHERE 1 = 2")
- Expect(err).To(Equal(pg.ErrNoRows))
- })
- })
-
- Describe("Exec", func() {
- It("does not return an error when there are no results", func() {
- _, err := db.Exec("SELECT 1 WHERE 1 = 2")
- Expect(err).NotTo(HaveOccurred())
- })
-
- It("does not return an error when there are no results", func() {
- _, err := tx.Exec("SELECT 1 WHERE 1 = 2")
- Expect(err).NotTo(HaveOccurred())
- })
- })
-
- Describe("ExecOne", func() {
- It("returns pg.ErrNoRows when there are no results", func() {
- _, err := db.ExecOne("SELECT 1 WHERE 1 = 2")
- Expect(err).To(Equal(pg.ErrNoRows))
- })
-
- It("returns pg.ErrNoRows when there are no results", func() {
- _, err := tx.ExecOne("SELECT 1 WHERE 1 = 2")
- Expect(err).To(Equal(pg.ErrNoRows))
- })
- })
-})
-
-var _ = Describe("Time", func() {
- var tests = []struct {
- str string
- wanted time.Time
- }{
- {"0001-01-01 00:00:00+00", time.Time{}},
- {"0000-01-01 00:00:00+00", time.Date(0, time.January, 1, 0, 0, 0, 0, time.UTC)},
-
- {"2001-02-03", time.Date(2001, time.February, 3, 0, 0, 0, 0, time.UTC)},
- {"2001-02-03 04:05:06", time.Date(2001, time.February, 3, 4, 5, 6, 0, time.Local)},
- {"2001-02-03 04:05:06.000001", time.Date(2001, time.February, 3, 4, 5, 6, 1000, time.Local)},
- {"2001-02-03 04:05:06.00001", time.Date(2001, time.February, 3, 4, 5, 6, 10000, time.Local)},
- {"2001-02-03 04:05:06.0001", time.Date(2001, time.February, 3, 4, 5, 6, 100000, time.Local)},
- {"2001-02-03 04:05:06.001", time.Date(2001, time.February, 3, 4, 5, 6, 1000000, time.Local)},
- {"2001-02-03 04:05:06.01", time.Date(2001, time.February, 3, 4, 5, 6, 10000000, time.Local)},
- {"2001-02-03 04:05:06.1", time.Date(2001, time.February, 3, 4, 5, 6, 100000000, time.Local)},
- {"2001-02-03 04:05:06.12", time.Date(2001, time.February, 3, 4, 5, 6, 120000000, time.Local)},
- {"2001-02-03 04:05:06.123", time.Date(2001, time.February, 3, 4, 5, 6, 123000000, time.Local)},
- {"2001-02-03 04:05:06.1234", time.Date(2001, time.February, 3, 4, 5, 6, 123400000, time.Local)},
- {"2001-02-03 04:05:06.12345", time.Date(2001, time.February, 3, 4, 5, 6, 123450000, time.Local)},
- {"2001-02-03 04:05:06.123456", time.Date(2001, time.February, 3, 4, 5, 6, 123456000, time.Local)},
- {"2001-02-03 04:05:06.123-07", time.Date(2001, time.February, 3, 4, 5, 6, 123000000, time.FixedZone("", -7*60*60))},
- {"2001-02-03 04:05:06-07", time.Date(2001, time.February, 3, 4, 5, 6, 0, time.FixedZone("", -7*60*60))},
- {"2001-02-03 04:05:06-07:42", time.Date(2001, time.February, 3, 4, 5, 6, 0, time.FixedZone("", -(7*60*60+42*60)))},
- {"2001-02-03 04:05:06-07:30:09", time.Date(2001, time.February, 3, 4, 5, 6, 0, time.FixedZone("", -(7*60*60+30*60+9)))},
- {"2001-02-03 04:05:06+07", time.Date(2001, time.February, 3, 4, 5, 6, 0, time.FixedZone("", 7*60*60))},
- }
-
- var db *pg.DB
-
- BeforeEach(func() {
- db = pg.Connect(pgOptions())
- })
-
- AfterEach(func() {
- Expect(db.Close()).NotTo(HaveOccurred())
- })
-
- It("is formatted correctly", func() {
- for i, test := range tests {
- var tm time.Time
- _, err := db.QueryOne(pg.Scan(&tm), "SELECT ?", test.wanted)
- Expect(err).NotTo(HaveOccurred())
- Expect(tm.Unix()).To(
- Equal(test.wanted.Unix()),
- "#%d str=%q wanted=%q", i, test.str, test.wanted,
- )
- }
- })
-
- It("is parsed correctly", func() {
- for i, test := range tests {
- var tm time.Time
- _, err := db.QueryOne(pg.Scan(&tm), "SELECT ?", test.str)
- Expect(err).NotTo(HaveOccurred())
- Expect(tm.Unix()).To(
- Equal(test.wanted.Unix()),
- "#%d str=%q wanted=%q", i, test.str, test.wanted,
- )
- }
- })
-})
-
-var _ = Describe("slice model", func() {
- type value struct {
- Id int
- }
-
- var db *pg.DB
-
- BeforeEach(func() {
- db = pg.Connect(pgOptions())
- })
-
- AfterEach(func() {
- Expect(db.Close()).NotTo(HaveOccurred())
- })
-
- It("does not error when there are no rows", func() {
- var ints []int
- _, err := db.Query(&ints, "SELECT generate_series(1, 0)")
- Expect(err).NotTo(HaveOccurred())
- Expect(ints).To(BeZero())
- })
-
- It("does not error when there are no rows", func() {
- var slice []value
- _, err := db.Query(&slice, "SELECT generate_series(1, 0)")
- Expect(err).NotTo(HaveOccurred())
- Expect(slice).To(BeZero())
- })
-
- It("does not error when there are no rows", func() {
- var slice []*value
- _, err := db.Query(&slice, "SELECT generate_series(1, 0)")
- Expect(err).NotTo(HaveOccurred())
- Expect(slice).To(BeZero())
- })
-
- It("supports slice of structs", func() {
- var slice []value
- _, err := db.Query(&slice, `SELECT generate_series(1, 3) AS id`)
- Expect(err).NotTo(HaveOccurred())
- Expect(slice).To(Equal([]value{{1}, {2}, {3}}))
- })
-
- It("supports slice of pointers", func() {
- var slice []*value
- _, err := db.Query(&slice, `SELECT generate_series(1, 3) AS id`)
- Expect(err).NotTo(HaveOccurred())
- Expect(slice).To(Equal([]*value{{1}, {2}, {3}}))
- })
-
- It("supports Ints", func() {
- var ints pg.Ints
- _, err := db.Query(&ints, `SELECT generate_series(1, 3)`)
- Expect(err).NotTo(HaveOccurred())
- Expect(ints).To(Equal(pg.Ints{1, 2, 3}))
- })
-
- It("supports slice of ints", func() {
- var ints []int
- _, err := db.Query(&ints, `SELECT generate_series(1, 3)`)
- Expect(err).NotTo(HaveOccurred())
- Expect(ints).To(Equal([]int{1, 2, 3}))
- })
-
- It("supports slice of time.Time", func() {
- var times []time.Time
- _, err := db.Query(×, `
- WITH data (time) AS (VALUES (clock_timestamp()), (clock_timestamp()))
- SELECT time FROM data
- `)
- Expect(err).NotTo(HaveOccurred())
- Expect(times).To(HaveLen(2))
- })
-
- It("resets slice", func() {
- ints := []int{1, 2, 3}
- _, err := db.Query(&ints, `SELECT 1`)
- Expect(err).NotTo(HaveOccurred())
- Expect(ints).To(Equal([]int{1}))
- })
-
- It("resets slice when there are no results", func() {
- ints := []int{1, 2, 3}
- _, err := db.Query(&ints, `SELECT 1 WHERE FALSE`)
- Expect(err).NotTo(HaveOccurred())
- Expect(ints).To(BeEmpty())
- })
-})
-
-var _ = Describe("read/write timeout", func() {
- var db *pg.DB
-
- BeforeEach(func() {
- opt := pgOptions()
- opt.ReadTimeout = time.Millisecond
- db = pg.Connect(opt)
- })
-
- AfterEach(func() {
- Expect(db.Close()).NotTo(HaveOccurred())
- })
-
- It("slow query timeouts", func() {
- _, err := db.Exec(`SELECT pg_sleep(1)`)
- Expect(err.(net.Error).Timeout()).To(BeTrue())
- })
-
- Context("WithTimeout", func() {
- It("slow query passes", func() {
- _, err := db.WithTimeout(time.Minute).Exec(`SELECT pg_sleep(1)`)
- Expect(err).NotTo(HaveOccurred())
- })
- })
-})
-
-var _ = Describe("CopyFrom/CopyTo", func() {
- const n = 1000000
- var db *pg.DB
-
- BeforeEach(func() {
- db = pg.Connect(pgOptions())
-
- qs := []string{
- "CREATE TEMP TABLE copy_src(n int)",
- "CREATE TEMP TABLE copy_dst(n int)",
- fmt.Sprintf("INSERT INTO copy_src SELECT generate_series(1, %d)", n),
- }
- for _, q := range qs {
- _, err := db.Exec(q)
- Expect(err).NotTo(HaveOccurred())
- }
- })
-
- AfterEach(func() {
- err := db.Close()
- Expect(err).NotTo(HaveOccurred())
- })
-
- It("copies data from a table and to a table", func() {
- var buf bytes.Buffer
- res, err := db.CopyTo(&buf, "COPY copy_src TO STDOUT")
- Expect(err).NotTo(HaveOccurred())
- Expect(res.RowsAffected()).To(Equal(n))
-
- res, err = db.CopyFrom(&buf, "COPY copy_dst FROM STDIN")
- Expect(err).NotTo(HaveOccurred())
- Expect(res.RowsAffected()).To(Equal(n))
-
- st := db.PoolStats()
- Expect(st.Hits).To(Equal(uint32(4)))
- Expect(st.Misses).To(Equal(uint32(1)))
- Expect(st.Timeouts).To(Equal(uint32(0)))
- Expect(st.TotalConns).To(Equal(uint32(1)))
- Expect(st.FreeConns).To(Equal(uint32(1)))
-
- var count int
- _, err = db.QueryOne(pg.Scan(&count), "SELECT count(*) FROM copy_dst")
- Expect(err).NotTo(HaveOccurred())
- Expect(count).To(Equal(n))
- })
-
- It("copies corrupted data to a table", func() {
- buf := bytes.NewBufferString("corrupted,data\nrow,two\r\nrow three")
- res, err := db.CopyFrom(buf, "COPY copy_dst FROM STDIN WITH FORMAT csv")
- Expect(err).To(MatchError(`ERROR #42601 syntax error at or near "FORMAT" (addr="127.0.0.1:5432")`))
- Expect(res).To(BeNil())
-
- st := db.Pool().Stats()
- Expect(st.Hits).To(Equal(uint32(3)))
- Expect(st.Misses).To(Equal(uint32(1)))
- Expect(st.Timeouts).To(Equal(uint32(0)))
- Expect(st.TotalConns).To(Equal(uint32(1)))
- Expect(st.FreeConns).To(Equal(uint32(1)))
-
- var count int
- _, err = db.QueryOne(pg.Scan(&count), "SELECT count(*) FROM copy_dst")
- Expect(err).NotTo(HaveOccurred())
- Expect(count).To(Equal(0))
- })
-})
-
-var _ = Describe("CountEstimate", func() {
- var db *pg.DB
-
- BeforeEach(func() {
- db = pg.Connect(pgOptions())
- })
-
- It("works", func() {
- count, err := db.Model().
- TableExpr("generate_series(1, 10)").
- CountEstimate(1000)
- Expect(err).NotTo(HaveOccurred())
- Expect(count).To(Equal(10))
- })
-
- It("works when there are no results", func() {
- count, err := db.Model().
- TableExpr("generate_series(1, 0)").
- CountEstimate(1000)
- Expect(err).NotTo(HaveOccurred())
- Expect(count).To(Equal(0))
- })
-
- It("works with GROUP", func() {
- count, err := db.Model().
- TableExpr("generate_series(1, 10)").
- Group("generate_series").
- CountEstimate(1000)
- Expect(err).NotTo(HaveOccurred())
- Expect(count).To(Equal(10))
- })
-
- It("works with GROUP when there are no results", func() {
- count, err := db.Model().
- TableExpr("generate_series(1, 0)").
- Group("generate_series").
- CountEstimate(1000)
- Expect(err).NotTo(HaveOccurred())
- Expect(count).To(Equal(0))
- })
-})
-
-var _ = Describe("DB nulls", func() {
- var db *pg.DB
-
- BeforeEach(func() {
- db = pg.Connect(pgOptions())
-
- _, err := db.Exec("CREATE TEMP TABLE tests (id int, value int)")
- Expect(err).To(BeNil())
- })
-
- AfterEach(func() {
- err := db.Close()
- Expect(err).NotTo(HaveOccurred())
- })
-
- Describe("sql.NullInt64", func() {
- type Test struct {
- Id int
- Value sql.NullInt64
- }
-
- It("inserts null value", func() {
- ins := Test{
- Id: 1,
- }
- err := db.Insert(&ins)
- Expect(err).NotTo(HaveOccurred())
-
- sel := Test{
- Id: 1,
- }
- err = db.Select(&sel)
- Expect(err).NotTo(HaveOccurred())
- Expect(sel.Value.Valid).To(BeFalse())
- })
-
- It("inserts non-null value", func() {
- ins := Test{
- Id: 1,
- Value: sql.NullInt64{
- Int64: 2,
- Valid: true,
- },
- }
- err := db.Insert(&ins)
- Expect(err).NotTo(HaveOccurred())
-
- sel := Test{
- Id: 1,
- }
- err = db.Select(&sel)
- Expect(err).NotTo(HaveOccurred())
- Expect(sel.Value.Valid).To(BeTrue())
- Expect(sel.Value.Int64).To(Equal(int64(2)))
- })
- })
-
- Context("nil ptr", func() {
- type Test struct {
- Id int
- Value *int
- }
-
- It("inserts null value", func() {
- ins := Test{
- Id: 1,
- }
- err := db.Insert(&ins)
- Expect(err).NotTo(HaveOccurred())
-
- sel := Test{
- Id: 1,
- }
- err = db.Select(&sel)
- Expect(err).NotTo(HaveOccurred())
- Expect(sel.Value).To(BeNil())
- })
-
- It("inserts non-null value", func() {
- value := 2
- ins := Test{
- Id: 1,
- Value: &value,
- }
- err := db.Insert(&ins)
- Expect(err).NotTo(HaveOccurred())
-
- sel := Test{
- Id: 1,
- }
- err = db.Select(&sel)
- Expect(err).NotTo(HaveOccurred())
- Expect(sel.Value).NotTo(BeNil())
- Expect(*sel.Value).To(Equal(2))
- })
- })
-})
-
-var _ = Describe("DB.Select", func() {
- var db *pg.DB
-
- BeforeEach(func() {
- db = pg.Connect(pgOptions())
-
- qs := []string{
- `CREATE TEMP TABLE tests (col bytea)`,
- fmt.Sprintf(`INSERT INTO tests VALUES ('\x%x')`, []byte("bytes")),
- }
- for _, q := range qs {
- _, err := db.Exec(q)
- Expect(err).NotTo(HaveOccurred())
- }
- })
-
- AfterEach(func() {
- err := db.Close()
- Expect(err).NotTo(HaveOccurred())
- })
-
- It("selects bytea", func() {
- var col []byte
- err := db.Model().Table("tests").Column("col").Select(pg.Scan(&col))
- Expect(err).NotTo(HaveOccurred())
- })
-})
-
-var _ = Describe("DB.Insert", func() {
- var db *pg.DB
-
- BeforeEach(func() {
- db = pg.Connect(pgOptions())
- })
-
- AfterEach(func() {
- err := db.Close()
- Expect(err).NotTo(HaveOccurred())
- })
-
- It("returns an error on nil", func() {
- err := db.Insert(nil)
- Expect(err).To(MatchError("pg: Model(nil)"))
- })
-
- It("returns an errors if value is not settable", func() {
- err := db.Insert(1)
- Expect(err).To(MatchError("pg: Model(non-pointer int)"))
- })
-
- It("returns an errors if value is not supported", func() {
- var v int
- err := db.Insert(&v)
- Expect(err).To(MatchError("pg: Model(unsupported int)"))
- })
-})
-
-var _ = Describe("DB.Update", func() {
- var db *pg.DB
-
- BeforeEach(func() {
- db = pg.Connect(pgOptions())
- })
-
- AfterEach(func() {
- err := db.Close()
- Expect(err).NotTo(HaveOccurred())
- })
-
- It("returns an error on nil", func() {
- err := db.Update(nil)
- Expect(err).To(MatchError("pg: Model(nil)"))
- })
-
- It("returns an error if there are no pks", func() {
- type Test struct{}
- var test Test
- err := db.Update(&test)
- Expect(err).To(MatchError(`model=Test does not have primary keys`))
- })
-})
-
-var _ = Describe("DB.Delete", func() {
- var db *pg.DB
-
- BeforeEach(func() {
- db = pg.Connect(pgOptions())
- })
-
- AfterEach(func() {
- err := db.Close()
- Expect(err).NotTo(HaveOccurred())
- })
-
- It("returns an error on nil", func() {
- err := db.Delete(nil)
- Expect(err).To(MatchError("pg: Model(nil)"))
- })
-
- It("returns an error if there are no pks", func() {
- type Test struct{}
- var test Test
- err := db.Delete(&test)
- Expect(err).To(MatchError(`model=Test does not have primary keys`))
- })
-})
-
-var _ = Describe("errors", func() {
- var db *pg.DB
-
- BeforeEach(func() {
- db = pg.Connect(pgOptions())
- })
-
- AfterEach(func() {
- err := db.Close()
- Expect(err).NotTo(HaveOccurred())
- })
-
- It("unknown column error", func() {
- type Test struct {
- Col1 int
- }
-
- var test Test
- _, err := db.QueryOne(&test, "SELECT 1 AS col1, 2 AS col2")
- Expect(err).To(MatchError("pg: can't find column=col2 in model=Test"))
- Expect(test.Col1).To(Equal(1))
- })
-
- It("Scan error", func() {
- var n1 int
- _, err := db.QueryOne(pg.Scan(&n1), "SELECT 1, 2")
- Expect(err).To(MatchError(`pg: no Scan var for column index=1 name="?column?"`))
- Expect(n1).To(Equal(1))
- })
-})
-
-type Genre struct {
- // tableName is an optional field that specifies custom table name and alias.
- // By default go-pg generates table name and alias from struct name.
- tableName struct{} `sql:"genres,alias:genre"` // default values are the same
-
- Id int // Id is automatically detected as primary key
- Name string
- Rating int `sql:"-"` // - is used to ignore field
-
- Books []Book `pg:"many2many:book_genres"` // many to many relation
-
- ParentId int
- Subgenres []Genre `pg:"fk:Parent"` // fk specifies prefix for foreign key (ParentId)
-}
-
-func (g Genre) String() string {
- return fmt.Sprintf("Genre", g.Id, g.Name)
-}
-
-type Image struct {
- Id int
- Path string
-}
-
-type Author struct {
- ID int // both "Id" and "ID" are detected as primary key
- Name string `sql:",unique"`
- Books []*Book // has many relation
-
- AvatarId int
- Avatar Image
-}
-
-func (a Author) String() string {
- return fmt.Sprintf("Author", a.ID, a.Name)
-}
-
-type BookGenre struct {
- tableName struct{} `sql:"alias:bg"` // custom table alias
-
- BookId int `sql:",pk"` // pk tag is used to mark field as primary key
- Book *Book
- GenreId int `sql:",pk"`
- Genre *Genre
-
- Genre_Rating int // belongs to and is copied to Genre model
-}
-
-type Book struct {
- Id int
- Title string
- AuthorID int
- Author Author // has one relation
- EditorID int
- Editor *Author // has one relation
- CreatedAt time.Time
-
- Genres []Genre `pg:"many2many:book_genres"` // many to many relation
- Translations []Translation // has many relation
- Comments []Comment `pg:"polymorphic:Trackable"` // has many polymorphic relation
-}
-
-func (b Book) String() string {
- return fmt.Sprintf("Book", b.Id, b.Title)
-}
-
-func (b *Book) BeforeInsert(db orm.DB) error {
- if b.CreatedAt.IsZero() {
- b.CreatedAt = time.Now()
- }
- return nil
-}
-
-// BookWithCommentCount is like Book model, but has additional CommentCount
-// field that is used to select data into it. The use of `pg:",override"` tag
-// is essential here and it overrides internal model properties such as table name.
-type BookWithCommentCount struct {
- Book `pg:",override"`
-
- CommentCount int
-}
-
-type Translation struct {
- tableName struct{} `sql:",alias:tr"` // custom table alias
-
- Id int
- BookId int
- Book *Book // has one relation
- Lang string
-
- Comments []Comment `pg:",polymorphic:Trackable"` // has many polymorphic relation
-}
-
-type Comment struct {
- TrackableId int // Book.Id or Translation.Id
- TrackableType string // "Book" or "Translation"
- Text string
-}
-
-func createTestSchema(db *pg.DB) error {
- tables := []interface{}{
- &Image{},
- &Author{},
- &Book{},
- &Genre{},
- &BookGenre{},
- &Translation{},
- &Comment{},
- }
- for _, table := range tables {
- err := db.DropTable(table, &orm.DropTableOptions{
- IfExists: true,
- Cascade: true,
- })
- if err != nil {
- return err
- }
-
- err = db.CreateTable(table, nil)
- if err != nil {
- return err
- }
- }
- return nil
-}
-
-var _ = Describe("ORM", func() {
- var db *pg.DB
-
- BeforeEach(func() {
- db = pg.Connect(pgOptions())
-
- err := createTestSchema(db)
- Expect(err).NotTo(HaveOccurred())
-
- genres := []Genre{{
- Id: 1,
- Name: "genre 1",
- }, {
- Id: 2,
- Name: "genre 2",
- }, {
- Id: 3,
- Name: "subgenre 1",
- ParentId: 1,
- }, {
- Id: 4,
- Name: "subgenre 2",
- ParentId: 1,
- }}
- err = db.Insert(&genres)
- Expect(err).NotTo(HaveOccurred())
- Expect(genres).To(HaveLen(4))
-
- images := []Image{{
- Id: 1,
- Path: "/path/to/1.jpg",
- }, {
- Id: 2,
- Path: "/path/to/2.jpg",
- }, {
- Id: 3,
- Path: "/path/to/3.jpg",
- }}
- err = db.Insert(&images)
- Expect(err).NotTo(HaveOccurred())
- Expect(images).To(HaveLen(3))
-
- authors := []Author{{
- ID: 10,
- Name: "author 1",
- AvatarId: images[0].Id,
- }, {
- ID: 11,
- Name: "author 2",
- AvatarId: images[1].Id,
- }, Author{
- ID: 12,
- Name: "author 3",
- AvatarId: images[2].Id,
- }}
- err = db.Insert(&authors)
- Expect(err).NotTo(HaveOccurred())
- Expect(authors).To(HaveLen(3))
-
- books := []Book{{
- Id: 100,
- Title: "book 1",
- AuthorID: 10,
- EditorID: 11,
- }, {
- Id: 101,
- Title: "book 2",
- AuthorID: 10,
- EditorID: 12,
- }, Book{
- Id: 102,
- Title: "book 3",
- AuthorID: 11,
- EditorID: 11,
- }}
- err = db.Insert(&books)
- Expect(err).NotTo(HaveOccurred())
- Expect(books).To(HaveLen(3))
- for _, book := range books {
- Expect(book.CreatedAt).To(BeTemporally("~", time.Now(), time.Second))
- }
-
- bookGenres := []BookGenre{{
- BookId: 100,
- GenreId: 1,
- Genre_Rating: 999,
- }, {
- BookId: 100,
- GenreId: 2,
- Genre_Rating: 9999,
- }, {
- BookId: 101,
- GenreId: 1,
- Genre_Rating: 99999,
- }}
- err = db.Insert(&bookGenres)
- Expect(err).NotTo(HaveOccurred())
- Expect(bookGenres).To(HaveLen(3))
-
- translations := []Translation{{
- Id: 1000,
- BookId: 100,
- Lang: "ru",
- }, {
- Id: 1001,
- BookId: 100,
- Lang: "md",
- }, {
- Id: 1002,
- BookId: 101,
- Lang: "ua",
- }}
- err = db.Insert(&translations)
- Expect(err).NotTo(HaveOccurred())
- Expect(translations).To(HaveLen(3))
-
- comments := []Comment{{
- TrackableId: 100,
- TrackableType: "Book",
- Text: "comment1",
- }, {
- TrackableId: 100,
- TrackableType: "Book",
- Text: "comment2",
- }, {
- TrackableId: 1000,
- TrackableType: "Translation",
- Text: "comment3",
- }}
- err = db.Insert(&comments)
- Expect(err).NotTo(HaveOccurred())
- Expect(comments).To(HaveLen(3))
- })
-
- It("multi updates", func() {
- books := []Book{{
- Id: 100,
- Title: " suffix",
- }, {
- Id: 101,
- }}
- res, err := db.Model(&books).
- Set("title = book.title || COALESCE(_data.title, '')").
- Update()
- Expect(err).NotTo(HaveOccurred())
- Expect(res.RowsAffected()).To(Equal(2))
-
- books = nil
- err = db.Model(&books).Column("id", "title").Order("id").Select()
- Expect(err).NotTo(HaveOccurred())
- Expect(books).To(Equal([]Book{{
- Id: 100,
- Title: "book 1 suffix",
- }, {
- Id: 101,
- Title: "book 2",
- }, {
- Id: 102,
- Title: "book 3",
- }}))
- })
-
- Describe("struct model", func() {
- It("fetches Book relations", func() {
- var book Book
- err := db.Model(&book).
- Column(
- "book.id",
- "Author", "Author.Avatar", "Editor", "Editor.Avatar",
- "Genres", "Comments", "Translations", "Translations.Comments",
- ).
- First()
- Expect(err).NotTo(HaveOccurred())
- Expect(book).To(Equal(Book{
- Id: 100,
- Title: "",
- Author: Author{
- ID: 10,
- Name: "author 1",
- AvatarId: 1,
- Avatar: Image{
- Id: 1,
- Path: "/path/to/1.jpg",
- },
- },
- Editor: &Author{
- ID: 11,
- Name: "author 2",
- AvatarId: 2,
- Avatar: Image{
- Id: 2,
- Path: "/path/to/2.jpg",
- },
- },
- CreatedAt: time.Time{},
- Genres: []Genre{
- {Id: 1, Name: "genre 1", Rating: 999},
- {Id: 2, Name: "genre 2", Rating: 9999},
- },
- Translations: []Translation{{
- Id: 1000,
- BookId: 100,
- Lang: "ru",
- Comments: []Comment{
- {TrackableId: 1000, TrackableType: "Translation", Text: "comment3"},
- },
- }, {
- Id: 1001,
- BookId: 100,
- Lang: "md",
- Comments: nil,
- }},
- Comments: []Comment{
- {TrackableId: 100, TrackableType: "Book", Text: "comment1"},
- {TrackableId: 100, TrackableType: "Book", Text: "comment2"},
- },
- }))
- })
-
- It("fetches Author relations", func() {
- var author Author
- err := db.Model(&author).
- Column(
- "author.*",
- "Books.id", "Books.author_id", "Books.editor_id",
- "Books.Author", "Books.Editor",
- "Books.Translations",
- ).
- First()
- Expect(err).NotTo(HaveOccurred())
- Expect(author).To(Equal(Author{
- ID: 10,
- Name: "author 1",
- AvatarId: 1,
- Books: []*Book{{
- Id: 100,
- Title: "",
- AuthorID: 10,
- Author: Author{ID: 10, Name: "author 1", AvatarId: 1},
- EditorID: 11,
- Editor: &Author{ID: 11, Name: "author 2", AvatarId: 2},
- CreatedAt: time.Time{},
- Genres: nil,
- Translations: []Translation{
- {Id: 1000, BookId: 100, Book: nil, Lang: "ru", Comments: nil},
- {Id: 1001, BookId: 100, Book: nil, Lang: "md", Comments: nil},
- },
- }, {
- Id: 101,
- Title: "",
- AuthorID: 10,
- Author: Author{ID: 10, Name: "author 1", AvatarId: 1},
- EditorID: 12,
- Editor: &Author{ID: 12, Name: "author 3", AvatarId: 3},
- CreatedAt: time.Time{},
- Genres: nil,
- Translations: []Translation{
- {Id: 1002, BookId: 101, Book: nil, Lang: "ua", Comments: nil},
- },
- }},
- }))
- })
-
- It("fetches Genre relations", func() {
- var genre Genre
- err := db.Model(&genre).
- Column("genre.*", "Books.id", "Books.Translations").
- First()
- Expect(err).NotTo(HaveOccurred())
- Expect(genre).To(Equal(Genre{
- Id: 1,
- Name: "genre 1",
- Rating: 0,
- Books: []Book{{
- Id: 100,
- Translations: []Translation{
- {Id: 1000, BookId: 100, Book: nil, Lang: "ru", Comments: nil},
- {Id: 1001, BookId: 100, Book: nil, Lang: "md", Comments: nil},
- },
- }, {
- Id: 101,
- Translations: []Translation{
- {Id: 1002, BookId: 101, Book: nil, Lang: "ua", Comments: nil},
- },
- }},
- ParentId: 0,
- Subgenres: nil,
- }))
- })
-
- It("fetches Translation relation", func() {
- var translation Translation
- err := db.Model(&translation).
- Column("tr.*", "Book.id", "Book.Author", "Book.Editor").
- First()
- Expect(err).NotTo(HaveOccurred())
- Expect(translation).To(Equal(Translation{
- Id: 1000,
- BookId: 100,
- Book: &Book{
- Id: 100,
- Author: Author{ID: 10, Name: "author 1", AvatarId: 1},
- Editor: &Author{ID: 11, Name: "author 2", AvatarId: 2},
- },
- Lang: "ru",
- }))
- })
-
- It("works when there are no results", func() {
- var book Book
- err := db.Model(&book).
- Column("book.*", "Author", "Genres", "Comments").
- Where("1 = 2").
- Select()
- Expect(err).To(Equal(pg.ErrNoRows))
- })
-
- It("supports overriding", func() {
- var book BookWithCommentCount
- err := db.Model(&book).
- Column("book.id", "Author", "Genres").
- ColumnExpr(`(SELECT COUNT(*) FROM comments WHERE trackable_type = 'Book' AND trackable_id = book.id) AS comment_count`).
- First()
- Expect(err).NotTo(HaveOccurred())
- Expect(book).To(Equal(BookWithCommentCount{
- Book: Book{
- Id: 100,
- Author: Author{ID: 10, Name: "author 1", AvatarId: 1},
- Genres: []Genre{
- {Id: 1, Name: "genre 1", Rating: 999},
- {Id: 2, Name: "genre 2", Rating: 9999},
- },
- },
- CommentCount: 2,
- }))
- })
- })
-
- Describe("slice model", func() {
- It("fetches Book relations", func() {
- var books []Book
- err := db.Model(&books).
- Column(
- "book.id",
- "Author", "Author.Avatar", "Editor", "Editor.Avatar",
- "Genres", "Comments", "Translations", "Translations.Comments",
- ).
- OrderExpr("book.id ASC").
- Select()
- Expect(err).NotTo(HaveOccurred())
- Expect(books).To(Equal([]Book{{
- Id: 100,
- Title: "",
- AuthorID: 0,
- Author: Author{
- ID: 10,
- Name: "author 1",
- AvatarId: 1,
- Avatar: Image{
- Id: 1,
- Path: "/path/to/1.jpg",
- },
- },
- EditorID: 0,
- Editor: &Author{
- ID: 11,
- Name: "author 2",
- AvatarId: 2,
- Avatar: Image{
- Id: 2,
- Path: "/path/to/2.jpg",
- },
- },
- Genres: []Genre{
- {Id: 1, Name: "genre 1", Rating: 999},
- {Id: 2, Name: "genre 2", Rating: 9999},
- },
- Translations: []Translation{{
- Id: 1000,
- BookId: 100,
- Lang: "ru",
- Comments: []Comment{
- {TrackableId: 1000, TrackableType: "Translation", Text: "comment3"},
- },
- }, {
- Id: 1001,
- BookId: 100,
- Lang: "md",
- Comments: nil,
- }},
- Comments: []Comment{
- {TrackableId: 100, TrackableType: "Book", Text: "comment1"},
- {TrackableId: 100, TrackableType: "Book", Text: "comment2"},
- },
- }, {
- Id: 101,
- Title: "",
- AuthorID: 0,
- Author: Author{
- ID: 10,
- Name: "author 1",
- AvatarId: 1,
- Avatar: Image{
- Id: 1,
- Path: "/path/to/1.jpg",
- },
- },
- EditorID: 0,
- Editor: &Author{
- ID: 12,
- Name: "author 3",
- AvatarId: 3,
- Avatar: Image{
- Id: 3,
- Path: "/path/to/3.jpg",
- },
- },
- Genres: []Genre{
- {Id: 1, Name: "genre 1", Rating: 99999},
- },
- Translations: []Translation{
- {Id: 1002, BookId: 101, Lang: "ua"},
- },
- }, {
- Id: 102,
- Title: "",
- AuthorID: 0,
- Author: Author{
- ID: 11,
- Name: "author 2",
- AvatarId: 2,
- Avatar: Image{
- Id: 2,
- Path: "/path/to/2.jpg",
- },
- },
- EditorID: 0,
- Editor: &Author{
- ID: 11,
- Name: "author 2",
- AvatarId: 2,
- Avatar: Image{
- Id: 2,
- Path: "/path/to/2.jpg",
- },
- },
- }}))
- })
-
- It("fetches Genre relations", func() {
- var genres []Genre
- err := db.Model(&genres).
- Column("genre.*", "Subgenres", "Books.id", "Books.Translations").
- Where("genre.parent_id IS NULL").
- OrderExpr("genre.id").
- Select()
- Expect(err).NotTo(HaveOccurred())
- Expect(genres).To(Equal([]Genre{{
- Id: 1,
- Name: "genre 1",
- Rating: 0,
- Books: []Book{{
- Id: 100,
- Translations: []Translation{
- {Id: 1000, BookId: 100, Book: nil, Lang: "ru", Comments: nil},
- {Id: 1001, BookId: 100, Book: nil, Lang: "md", Comments: nil},
- },
- }, {
- Id: 101,
- Translations: []Translation{
- {Id: 1002, BookId: 101, Book: nil, Lang: "ua", Comments: nil},
- },
- }},
- ParentId: 0,
- Subgenres: []Genre{
- {Id: 3, Name: "subgenre 1", Rating: 0, Books: nil, ParentId: 1, Subgenres: nil},
- {Id: 4, Name: "subgenre 2", Rating: 0, Books: nil, ParentId: 1, Subgenres: nil},
- },
- }, {
- Id: 2,
- Name: "genre 2",
- Rating: 0,
- Books: []Book{{
- Id: 100,
- Translations: []Translation{
- {Id: 1000, BookId: 100, Book: nil, Lang: "ru", Comments: nil},
- {Id: 1001, BookId: 100, Book: nil, Lang: "md", Comments: nil},
- },
- }},
- ParentId: 0,
- Subgenres: nil,
- },
- }))
- })
-
- It("fetches Translation relation", func() {
- var translations []Translation
- err := db.Model(&translations).
- Column("tr.*", "Book.id", "Book.Author", "Book.Editor").
- Select()
- Expect(err).NotTo(HaveOccurred())
- Expect(translations).To(Equal([]Translation{{
- Id: 1000,
- BookId: 100,
- Book: &Book{
- Id: 100,
- Author: Author{ID: 10, Name: "author 1", AvatarId: 1},
- Editor: &Author{ID: 11, Name: "author 2", AvatarId: 2},
- },
- Lang: "ru",
- }, {
- Id: 1001,
- BookId: 100,
- Book: &Book{
- Id: 100,
- Author: Author{ID: 10, Name: "author 1", AvatarId: 1},
- Editor: &Author{ID: 11, Name: "author 2", AvatarId: 2},
- },
- Lang: "md",
- }, {
- Id: 1002,
- BookId: 101,
- Book: &Book{
- Id: 101,
- Author: Author{ID: 10, Name: "author 1", AvatarId: 1},
- Editor: &Author{ID: 12, Name: "author 3", AvatarId: 3},
- },
- Lang: "ua",
- }}))
- })
-
- It("works when there are no results", func() {
- var books []Book
- err := db.Model(&books).
- Column("book.*", "Author", "Genres", "Comments").
- Where("1 = 2").
- Select()
- Expect(err).NotTo(HaveOccurred())
- Expect(books).To(BeNil())
- })
-
- It("supports overriding", func() {
- var books []BookWithCommentCount
- err := db.Model(&books).
- Column("book.id", "Author", "Genres").
- ColumnExpr(`(SELECT COUNT(*) FROM comments WHERE trackable_type = 'Book' AND trackable_id = book.id) AS comment_count`).
- OrderExpr("id ASC").
- Select()
- Expect(err).NotTo(HaveOccurred())
- Expect(books).To(Equal([]BookWithCommentCount{{
- Book: Book{
- Id: 100,
- Author: Author{ID: 10, Name: "author 1", AvatarId: 1},
- Genres: []Genre{
- {Id: 1, Name: "genre 1", Rating: 999},
- {Id: 2, Name: "genre 2", Rating: 9999},
- },
- },
- CommentCount: 2,
- }, {
- Book: Book{
- Id: 101,
- Author: Author{ID: 10, Name: "author 1", AvatarId: 1},
- Genres: []Genre{
- {Id: 1, Name: "genre 1", Rating: 99999},
- },
- },
- CommentCount: 0,
- }, {
- Book: Book{
- Id: 102,
- Author: Author{ID: 11, Name: "author 2", AvatarId: 2},
- },
- CommentCount: 0,
- }}))
- })
- })
-
- Describe("fetches Book relations", func() {
- It("supports HasOne, HasMany, HasMany2Many", func() {
- var books []*Book
- err := db.Model(&books).
- Column("book.id", "Author", "Editor", "Translations", "Genres").
- OrderExpr("book.id ASC").
- Select()
- Expect(err).NotTo(HaveOccurred())
- Expect(books).To(HaveLen(3))
- })
-
- It("fetches Genre relations", func() {
- var genres []*Genre
- err := db.Model(&genres).
- Column("genre.*", "Subgenres", "Books.id", "Books.Translations").
- Where("genre.parent_id IS NULL").
- OrderExpr("genre.id").
- Select()
- Expect(err).NotTo(HaveOccurred())
- Expect(genres).To(HaveLen(2))
- })
-
- It("fetches Translation relations", func() {
- var translations []*Translation
- err := db.Model(&translations).
- Column("tr.*", "Book.id", "Book.Author", "Book.Editor").
- Select()
- Expect(err).NotTo(HaveOccurred())
- Expect(translations).To(HaveLen(3))
- })
-
- It("works when there are no results", func() {
- var books []*Book
- err := db.Model(&books).
- Column("book.*", "Author", "Genres", "Comments").
- Where("1 = 2").
- Select()
- Expect(err).NotTo(HaveOccurred())
- Expect(books).To(BeNil())
- })
-
- It("supports overriding", func() {
- var books []*BookWithCommentCount
- err := db.Model(&books).
- Column("book.id", "Author").
- ColumnExpr(`(SELECT COUNT(*) FROM comments WHERE trackable_type = 'Book' AND trackable_id = book.id) AS comment_count`).
- OrderExpr("id ASC").
- Select()
- Expect(err).NotTo(HaveOccurred())
- Expect(books).To(HaveLen(3))
- })
- })
-
- It("filters by HasOne", func() {
- var books []Book
- err := db.Model(&books).
- Column("book.id", "Author._").
- Where("author.id = 10").
- OrderExpr("book.id ASC").
- Select()
- Expect(err).NotTo(HaveOccurred())
- Expect(books).To(Equal([]Book{{
- Id: 100,
- }, {
- Id: 101,
- }}))
- })
-
- It("supports filtering HasMany", func() {
- var book Book
- err := db.Model(&book).
- Column("book.id", "Translations").
- Relation("Translations", func(q *orm.Query) (*orm.Query, error) {
- return q.Where("lang = 'ru'"), nil
- }).
- First()
- Expect(err).NotTo(HaveOccurred())
- Expect(book).To(Equal(Book{
- Id: 100,
- Translations: []Translation{
- {Id: 1000, BookId: 100, Lang: "ru"},
- },
- }))
- })
-
- It("supports filtering HasMany2Many", func() {
- var book Book
- err := db.Model(&book).
- Column("book.id", "Genres").
- Relation("Genres", func(q *orm.Query) (*orm.Query, error) {
- return q.Where("genre__rating > 999"), nil
- }).
- First()
- Expect(err).NotTo(HaveOccurred())
- Expect(book).To(Equal(Book{
- Id: 100,
- Genres: []Genre{
- {Id: 2, Name: "genre 2", Rating: 9999},
- },
- }))
- })
-
- It("deletes book returning title", func() {
- book := &Book{
- Id: 100,
- }
- res, err := db.Model(book).Returning("title").Delete()
- Expect(err).NotTo(HaveOccurred())
- Expect(res.RowsAffected()).To(Equal(1))
- Expect(book).To(Equal(&Book{
- Id: 100,
- Title: "book 1",
- }))
- })
-
- It("deletes books returning id", func() {
- var ids []int
- res, err := db.Model(&Book{}).Where("TRUE").Returning("id").Delete(&ids)
- Expect(err).NotTo(HaveOccurred())
- Expect(res.RowsAffected()).To(Equal(3))
- Expect(ids).To(Equal([]int{100, 101, 102}))
- })
-
- It("supports Exec & Query", func() {
- _, err := db.Model(&Book{}).Exec("DROP TABLE ?TableName CASCADE")
- Expect(err).NotTo(HaveOccurred())
-
- var num int
- _, err = db.Model(&Book{}).QueryOne(pg.Scan(&num), "SELECT 1 FROM ?TableName")
- Expect(err).To(MatchError(`ERROR #42P01 relation "books" does not exist (addr="127.0.0.1:5432")`))
- })
-})
diff --git a/vendor/github.com/go-pg/pg/doc.go b/vendor/github.com/go-pg/pg/doc.go
deleted file mode 100644
index f1d8eb1..0000000
--- a/vendor/github.com/go-pg/pg/doc.go
+++ /dev/null
@@ -1,4 +0,0 @@
-/*
-Package github.com/go-pg/pg implements a PostgreSQL client.
-*/
-package pg
diff --git a/vendor/github.com/go-pg/pg/error.go b/vendor/github.com/go-pg/pg/error.go
deleted file mode 100644
index bf2a9a9..0000000
--- a/vendor/github.com/go-pg/pg/error.go
+++ /dev/null
@@ -1,44 +0,0 @@
-package pg
-
-import (
- "io"
- "net"
-
- "github.com/go-pg/pg/internal"
-)
-
-var ErrNoRows = internal.ErrNoRows
-var ErrMultiRows = internal.ErrMultiRows
-
-type Error interface {
- Field(byte) string
- IntegrityViolation() bool
-}
-
-var _ Error = (*internal.PGError)(nil)
-
-func isBadConn(err error, allowTimeout bool) bool {
- if err == nil {
- return false
- }
- if _, ok := err.(internal.Error); ok {
- return false
- }
- if pgErr, ok := err.(Error); ok && pgErr.Field('S') != "FATAL" {
- return false
- }
- if allowTimeout {
- if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
- return false
- }
- }
- return true
-}
-
-func isNetworkError(err error) bool {
- if err == io.EOF {
- return true
- }
- _, ok := err.(net.Error)
- return ok
-}
diff --git a/vendor/github.com/go-pg/pg/example_array_test.go b/vendor/github.com/go-pg/pg/example_array_test.go
deleted file mode 100644
index 3d6fe13..0000000
--- a/vendor/github.com/go-pg/pg/example_array_test.go
+++ /dev/null
@@ -1,49 +0,0 @@
-package pg_test
-
-import (
- "fmt"
-
- "github.com/go-pg/pg"
-)
-
-func ExampleDB_Model_postgresArrayStructTag() {
- type Item struct {
- Id int64
- Emails []string `pg:",array"` // marshalled as PostgreSQL array
- Numbers [][]int `pg:",array"` // marshalled as PostgreSQL array
- }
-
- _, err := db.Exec(`CREATE TEMP TABLE items (id serial, emails text[], numbers int[][])`)
- if err != nil {
- panic(err)
- }
- defer db.Exec("DROP TABLE items")
-
- item1 := Item{
- Id: 1,
- Emails: []string{"one@example.com", "two@example.com"},
- Numbers: [][]int{{1, 2}, {3, 4}},
- }
- if err := db.Insert(&item1); err != nil {
- panic(err)
- }
-
- var item Item
- err = db.Model(&item).Where("id = ?", 1).Select()
- if err != nil {
- panic(err)
- }
- fmt.Println(item)
- // Output: {1 [one@example.com two@example.com] [[1 2] [3 4]]}
-}
-
-func ExampleArray() {
- src := []string{"one@example.com", "two@example.com"}
- var dst []string
- _, err := db.QueryOne(pg.Scan(pg.Array(&dst)), `SELECT ?`, pg.Array(src))
- if err != nil {
- panic(err)
- }
- fmt.Println(dst)
- // Output: [one@example.com two@example.com]
-}
diff --git a/vendor/github.com/go-pg/pg/example_hstore_test.go b/vendor/github.com/go-pg/pg/example_hstore_test.go
deleted file mode 100644
index a3c9609..0000000
--- a/vendor/github.com/go-pg/pg/example_hstore_test.go
+++ /dev/null
@@ -1,47 +0,0 @@
-package pg_test
-
-import (
- "fmt"
-
- "github.com/go-pg/pg"
-)
-
-func ExampleDB_Model_hstoreStructTag() {
- type Item struct {
- Id int64
- Attrs map[string]string `pg:",hstore"` // marshalled as PostgreSQL hstore
- }
-
- _, err := db.Exec(`CREATE TEMP TABLE items (id serial, attrs hstore)`)
- if err != nil {
- panic(err)
- }
- defer db.Exec("DROP TABLE items")
-
- item1 := Item{
- Id: 1,
- Attrs: map[string]string{"hello": "world"},
- }
- if err := db.Insert(&item1); err != nil {
- panic(err)
- }
-
- var item Item
- err = db.Model(&item).Where("id = ?", 1).Select()
- if err != nil {
- panic(err)
- }
- fmt.Println(item)
- // Output: {1 map[hello:world]}
-}
-
-func ExampleHstore() {
- src := map[string]string{"hello": "world"}
- var dst map[string]string
- _, err := db.QueryOne(pg.Scan(pg.Hstore(&dst)), `SELECT ?`, pg.Hstore(src))
- if err != nil {
- panic(err)
- }
- fmt.Println(dst)
- // Output: map[hello:world]
-}
diff --git a/vendor/github.com/go-pg/pg/example_model_test.go b/vendor/github.com/go-pg/pg/example_model_test.go
deleted file mode 100644
index 96bf6d2..0000000
--- a/vendor/github.com/go-pg/pg/example_model_test.go
+++ /dev/null
@@ -1,996 +0,0 @@
-package pg_test
-
-import (
- "database/sql"
- "fmt"
- "time"
-
- "github.com/go-pg/pg"
- "github.com/go-pg/pg/orm"
-)
-
-func modelDB() *pg.DB {
- db := pg.Connect(&pg.Options{
- User: "postgres",
- })
-
- err := createTestSchema(db)
- if err != nil {
- panic(err)
- }
-
- err = db.Insert(&Author{
- Name: "author 1",
- })
- if err != nil {
- panic(err)
- }
-
- books := []Book{{
- Title: "book 1",
- AuthorID: 1,
- EditorID: 11,
- }, {
- Title: "book 2",
- AuthorID: 1,
- EditorID: 12,
- }, {
- Title: "book 3",
- AuthorID: 11,
- EditorID: 11,
- CreatedAt: time.Now(),
- }}
- err = db.Insert(&books)
- if err != nil {
- panic(err)
- }
-
- for i := 0; i < 2; i++ {
- genre := Genre{
- Name: fmt.Sprintf("genre %d", i+1),
- }
- err = db.Insert(&genre)
- if err != nil {
- panic(err)
- }
-
- err = db.Insert(&BookGenre{
- BookId: 1,
- GenreId: genre.Id,
- })
- if err != nil {
- panic(err)
- }
- }
-
- // For CountEstimate.
- _, err = db.Exec("VACUUM")
- if err != nil {
- panic(err)
- }
-
- return db
-}
-
-func ExampleDB_Insert() {
- db := modelDB()
-
- book := Book{
- Title: "new book",
- AuthorID: 1,
- }
-
- err := db.Insert(&book)
- if err != nil {
- panic(err)
- }
- fmt.Println(book)
- // Output: Book
-
- err = db.Delete(&book)
- if err != nil {
- panic(err)
- }
-}
-
-func ExampleDB_Insert_bulkInsert() {
- db := modelDB()
-
- book1 := Book{
- Title: "new book 1",
- }
- book2 := Book{
- Title: "new book 2",
- }
- err := db.Insert(&book1, &book2)
- if err != nil {
- panic(err)
- }
- fmt.Println(book1, book2)
- // Output: Book Book
-
- for _, book := range []*Book{&book1, &book2} {
- err := db.Delete(book)
- if err != nil {
- panic(err)
- }
- }
-}
-
-func ExampleDB_Insert_bulkInsertSlice() {
- db := modelDB()
-
- books := []Book{{
- Title: "new book 1",
- }, {
- Title: "new book 2",
- }}
- err := db.Insert(&books)
- if err != nil {
- panic(err)
- }
- fmt.Println(books)
- // Output: [Book Book]
-
- for i := range books {
- err := db.Delete(&books[i])
- if err != nil {
- panic(err)
- }
- }
-}
-
-func ExampleDB_Insert_onConflictDoNothing() {
- db := modelDB()
-
- book := Book{
- Id: 100,
- Title: "book 100",
- }
-
- for i := 0; i < 2; i++ {
- res, err := db.Model(&book).OnConflict("DO NOTHING").Insert()
- if err != nil {
- panic(err)
- }
- if res.RowsAffected() > 0 {
- fmt.Println("created")
- } else {
- fmt.Println("did nothing")
- }
- }
-
- err := db.Delete(&book)
- if err != nil {
- panic(err)
- }
-
- // Output: created
- // did nothing
-}
-
-func ExampleDB_Insert_onConflictDoUpdate() {
- db := modelDB()
-
- var book *Book
- for i := 0; i < 2; i++ {
- book = &Book{
- Id: 100,
- Title: fmt.Sprintf("title version #%d", i),
- }
- _, err := db.Model(book).
- OnConflict("(id) DO UPDATE").
- Set("title = EXCLUDED.title").
- Insert()
- if err != nil {
- panic(err)
- }
-
- err = db.Select(book)
- if err != nil {
- panic(err)
- }
- fmt.Println(book)
- }
-
- err := db.Delete(book)
- if err != nil {
- panic(err)
- }
-
- // Output: Book
- // Book
-}
-
-func ExampleDB_Insert_selectOrInsert() {
- db := modelDB()
-
- author := Author{
- Name: "R. Scott Bakker",
- }
- created, err := db.Model(&author).
- Column("id").
- Where("name = ?name").
- OnConflict("DO NOTHING"). // OnConflict is optional
- Returning("id").
- SelectOrInsert()
- if err != nil {
- panic(err)
- }
- fmt.Println(created, author)
- // Output: true Author
-}
-
-func ExampleDB_Select() {
- db := modelDB()
-
- book := Book{
- Id: 1,
- }
- err := db.Select(&book)
- if err != nil {
- panic(err)
- }
- fmt.Println(book)
- // Output: Book
-}
-
-func ExampleDB_Select_firstRow() {
- db := modelDB()
-
- var firstBook Book
- err := db.Model(&firstBook).First()
- if err != nil {
- panic(err)
- }
- fmt.Println(firstBook)
- // Output: Book
-}
-
-func ExampleDB_Select_lastRow() {
- db := modelDB()
-
- var lastBook Book
- err := db.Model(&lastBook).Last()
- if err != nil {
- panic(err)
- }
- fmt.Println(lastBook)
- // Output: Book
-}
-
-func ExampleDB_Select_allColumns() {
- db := modelDB()
-
- var book Book
- err := db.Model(&book).Column("book.*").First()
- if err != nil {
- panic(err)
- }
- fmt.Println(book, book.AuthorID)
- // Output: Book 1
-}
-
-func ExampleDB_Select_someColumns() {
- db := modelDB()
-
- var book Book
- err := db.Model(&book).
- Column("book.id", "book.title").
- OrderExpr("book.id ASC").
- Limit(1).
- Select()
- if err != nil {
- panic(err)
- }
-
- fmt.Println(book)
- // Output: Book
-}
-
-func ExampleDB_Select_someColumnsIntoVars() {
- db := modelDB()
-
- var id int
- var title string
- err := db.Model(&Book{}).
- Column("book.id", "book.title").
- OrderExpr("book.id ASC").
- Limit(1).
- Select(&id, &title)
- if err != nil {
- panic(err)
- }
-
- fmt.Println(id, title)
- // Output: 1 book 1
-}
-
-func ExampleDB_Select_whereIn() {
- db := modelDB()
-
- var books []Book
- err := db.Model(&books).WhereIn("id IN (?)", 1, 2).Select()
- if err != nil {
- panic(err)
- }
- fmt.Println(books)
- // Output: [Book Book]
-}
-
-func ExampleDB_Select_whereGroup() {
- db := modelDB()
-
- var books []Book
- err := db.Model(&books).
- WhereGroup(func(q *orm.Query) (*orm.Query, error) {
- q = q.WhereOr("id = 1").
- WhereOr("id = 2")
- return q, nil
- }).
- Where("title IS NOT NULL").
- Select()
- if err != nil {
- panic(err)
- }
- fmt.Println(books)
- // Output: [Book Book]
-}
-
-func ExampleDB_Select_sqlExpression() {
- db := modelDB()
-
- var ids []int
- err := db.Model(&Book{}).
- ColumnExpr("array_agg(book.id)").
- Select(pg.Array(&ids))
- if err != nil {
- panic(err)
- }
- fmt.Println(ids)
- // Output: [1 2 3]
-}
-
-func ExampleDB_Select_groupBy() {
- db := modelDB()
-
- var res []struct {
- AuthorId int
- BookCount int
- }
-
- err := db.Model(&Book{}).
- Column("author_id").
- ColumnExpr("count(*) AS book_count").
- Group("author_id").
- OrderExpr("book_count DESC").
- Select(&res)
- if err != nil {
- panic(err)
- }
- fmt.Println("len", len(res))
- fmt.Printf("author %d has %d books\n", res[0].AuthorId, res[0].BookCount)
- fmt.Printf("author %d has %d books\n", res[1].AuthorId, res[1].BookCount)
- // Output: len 2
- // author 1 has 2 books
- // author 11 has 1 books
-}
-
-func ExampleDB_Select_with() {
- authorBooks := db.Model(&Book{}).Where("author_id = ?", 1)
-
- var books []Book
- err := db.Model().
- With("author_books", authorBooks).
- Table("author_books").
- Select(&books)
- if err != nil {
- panic(err)
- }
- fmt.Println(books)
- // Output: [Book Book]
-}
-
-func ExampleDB_Select_wrapWith() {
- // WITH author_books AS (
- // SELECT * books WHERE author_id = 1
- // )
- // SELECT * FROM author_books
- var books []Book
- err := db.Model(&books).
- Where("author_id = ?", 1).
- WrapWith("author_books").
- Table("author_books").
- Select(&books)
- if err != nil {
- panic(err)
- }
- fmt.Println(books)
- // Output: [Book Book]
-}
-
-func ExampleDB_Select_applyFunc() {
- db := modelDB()
-
- var authorId int
- var editorId int
-
- filter := func(q *orm.Query) (*orm.Query, error) {
- if authorId != 0 {
- q = q.Where("author_id = ?", authorId)
- }
- if editorId != 0 {
- q = q.Where("editor_id = ?", editorId)
- }
- return q, nil
- }
-
- var books []Book
- authorId = 1
- err := db.Model(&books).
- Apply(filter).
- Select()
- if err != nil {
- panic(err)
- }
- fmt.Println(books)
- // Output: [Book Book]
-}
-
-func ExampleDB_Model_count() {
- db := modelDB()
-
- count, err := db.Model(&Book{}).Count()
- if err != nil {
- panic(err)
- }
-
- fmt.Println(count)
- // Output: 3
-}
-
-func ExampleDB_Model_countEstimate() {
- db := modelDB()
-
- count, err := db.Model(&Book{}).CountEstimate(0)
- if err != nil {
- panic(err)
- }
-
- fmt.Println(count)
- // Output: 3
-}
-
-func ExampleDB_Model_selectAndCount() {
- db := modelDB()
-
- var books []Book
- count, err := db.Model(&books).OrderExpr("id ASC").Limit(2).SelectAndCount()
- if err != nil {
- panic(err)
- }
-
- fmt.Println(count)
- fmt.Println(books)
- // Output: 3
- // [Book Book]
-}
-
-func ExampleDB_Model_nullEmptyValue() {
- type Example struct {
- Hello string
- }
-
- var str sql.NullString
- _, err := db.QueryOne(pg.Scan(&str), "SELECT ?hello", &Example{Hello: ""})
- if err != nil {
- panic(err)
- }
- fmt.Println(str.Valid)
- // Output: false
-}
-
-func ExampleDB_Model_hasOne() {
- type Profile struct {
- Id int
- Lang string
- }
-
- // User has one profile.
- type User struct {
- Id int
- Name string
- ProfileId int
- Profile *Profile
- }
-
- db := connect()
- defer db.Close()
-
- qs := []string{
- "CREATE TEMP TABLE users (id int, name text, profile_id int)",
- "CREATE TEMP TABLE profiles (id int, lang text)",
- "INSERT INTO users VALUES (1, 'user 1', 1), (2, 'user 2', 2)",
- "INSERT INTO profiles VALUES (1, 'en'), (2, 'ru')",
- }
- for _, q := range qs {
- _, err := db.Exec(q)
- if err != nil {
- panic(err)
- }
- }
-
- // Select users joining their profiles with following query:
- //
- // SELECT
- // "user".*,
- // "profile"."id" AS "profile__id",
- // "profile"."lang" AS "profile__lang",
- // "profile"."user_id" AS "profile__user_id"
- // FROM "users" AS "user"
- // LEFT JOIN "profiles" AS "profile" ON "profile"."user_id" = "user"."id"
-
- var users []User
- err := db.Model(&users).
- Column("user.*", "Profile").
- Select()
- if err != nil {
- panic(err)
- }
-
- fmt.Println(len(users), "results")
- fmt.Println(users[0].Id, users[0].Name, users[0].Profile)
- fmt.Println(users[1].Id, users[1].Name, users[1].Profile)
- // Output: 2 results
- // 1 user 1 &{1 en}
- // 2 user 2 &{2 ru}
-}
-
-func ExampleDB_Model_belongsTo() {
- // Profile belongs to User.
- type Profile struct {
- Id int
- Lang string
- UserId int
- }
-
- type User struct {
- Id int
- Name string
- Profile *Profile
- }
-
- db := connect()
- defer db.Close()
-
- qs := []string{
- "CREATE TEMP TABLE users (id int, name text)",
- "CREATE TEMP TABLE profiles (id int, lang text, user_id int)",
- "INSERT INTO users VALUES (1, 'user 1'), (2, 'user 2')",
- "INSERT INTO profiles VALUES (1, 'en', 1), (2, 'ru', 2)",
- }
- for _, q := range qs {
- _, err := db.Exec(q)
- if err != nil {
- panic(err)
- }
- }
-
- // Select users joining their profiles with following query:
- //
- // SELECT
- // "user".*,
- // "profile"."id" AS "profile__id",
- // "profile"."lang" AS "profile__lang"
- // FROM "users" AS "user"
- // LEFT JOIN "profiles" AS "profile" ON "profile"."id" = "user"."profile_id"
-
- var users []User
- err := db.Model(&users).
- Column("user.*", "Profile").
- Select()
- if err != nil {
- panic(err)
- }
-
- fmt.Println(len(users), "results")
- fmt.Println(users[0].Id, users[0].Name, users[0].Profile)
- fmt.Println(users[1].Id, users[1].Name, users[1].Profile)
- // Output: 2 results
- // 1 user 1 &{1 en 1}
- // 2 user 2 &{2 ru 2}
-}
-
-func ExampleDB_Model_hasMany() {
- type Profile struct {
- Id int
- Lang string
- Active bool
- UserId int
- }
-
- // User has many profiles.
- type User struct {
- Id int
- Name string
- Profiles []*Profile
- }
-
- db := connect()
- defer db.Close()
-
- qs := []string{
- "CREATE TEMP TABLE users (id int, name text)",
- "CREATE TEMP TABLE profiles (id int, lang text, active bool, user_id int)",
- "INSERT INTO users VALUES (1, 'user 1')",
- "INSERT INTO profiles VALUES (1, 'en', TRUE, 1), (2, 'ru', TRUE, 1), (3, 'md', FALSE, 1)",
- }
- for _, q := range qs {
- _, err := db.Exec(q)
- if err != nil {
- panic(err)
- }
- }
-
- // Select user and all his active profiles with following queries:
- //
- // SELECT "user".* FROM "users" AS "user" ORDER BY "user"."id" LIMIT 1
- //
- // SELECT "profile".* FROM "profiles" AS "profile"
- // WHERE (active IS TRUE) AND (("profile"."user_id") IN ((1)))
-
- var user User
- err := db.Model(&user).
- Column("user.*", "Profiles").
- Relation("Profiles", func(q *orm.Query) (*orm.Query, error) {
- return q.Where("active IS TRUE"), nil
- }).
- First()
- if err != nil {
- panic(err)
- }
- fmt.Println(user.Id, user.Name, user.Profiles[0], user.Profiles[1])
- // Output: 1 user 1 &{1 en true 1} &{2 ru true 1}
-}
-
-func ExampleDB_Model_hasManySelf() {
- type Item struct {
- Id int
- Items []Item `pg:",fk:Parent"`
- ParentId int
- }
-
- db := connect()
- defer db.Close()
-
- qs := []string{
- "CREATE TEMP TABLE items (id int, parent_id int)",
- "INSERT INTO items VALUES (1, NULL), (2, 1), (3, 1)",
- }
- for _, q := range qs {
- _, err := db.Exec(q)
- if err != nil {
- panic(err)
- }
- }
-
- // Select item and all subitems with following queries:
- //
- // SELECT "item".* FROM "items" AS "item" ORDER BY "item"."id" LIMIT 1
- //
- // SELECT "item".* FROM "items" AS "item" WHERE (("item"."parent_id") IN ((1)))
-
- var item Item
- err := db.Model(&item).Column("item.*", "Items").First()
- if err != nil {
- panic(err)
- }
- fmt.Println("Item", item.Id)
- fmt.Println("Subitems", item.Items[0].Id, item.Items[1].Id)
- // Output: Item 1
- // Subitems 2 3
-}
-
-func ExampleDB_Model_manyToMany() {
- type Item struct {
- Id int
- Items []Item `pg:",many2many:item_to_items,joinFK:Sub"`
- }
-
- db := connect()
- defer db.Close()
-
- qs := []string{
- "CREATE TEMP TABLE items (id int)",
- "CREATE TEMP TABLE item_to_items (item_id int, sub_id int)",
- "INSERT INTO items VALUES (1), (2), (3)",
- "INSERT INTO item_to_items VALUES (1, 2), (1, 3)",
- }
- for _, q := range qs {
- _, err := db.Exec(q)
- if err != nil {
- panic(err)
- }
- }
-
- // Select item and all subitems with following queries:
- //
- // SELECT "item".* FROM "items" AS "item" ORDER BY "item"."id" LIMIT 1
- //
- // SELECT * FROM "items" AS "item"
- // JOIN "item_to_items" ON ("item_to_items"."item_id") IN ((1))
- // WHERE ("item"."id" = "item_to_items"."sub_id")
-
- var item Item
- err := db.Model(&item).Column("item.*", "Items").First()
- if err != nil {
- panic(err)
- }
- fmt.Println("Item", item.Id)
- fmt.Println("Subitems", item.Items[0].Id, item.Items[1].Id)
- // Output: Item 1
- // Subitems 2 3
-}
-
-func ExampleDB_Update() {
- db := modelDB()
-
- book := &Book{Id: 1}
- err := db.Select(book)
- if err != nil {
- panic(err)
- }
-
- book.Title = "updated book 1"
- err = db.Update(book)
- if err != nil {
- panic(err)
- }
-
- err = db.Select(book)
- if err != nil {
- panic(err)
- }
-
- fmt.Println(book)
- // Output: Book
-}
-
-func ExampleDB_Update_notNull() {
- db := modelDB()
-
- book := &Book{
- Id: 1,
- Title: "updated book 1",
- }
- _, err := db.Model(book).UpdateNotNull()
- if err != nil {
- panic(err)
- }
-
- book = new(Book)
- err = db.Model(book).Where("id = ?", 1).Select()
- if err != nil {
- panic(err)
- }
-
- fmt.Println(book)
- // Output: Book
-}
-
-func ExampleDB_Update_someColumns() {
- db := modelDB()
-
- book := Book{
- Id: 1,
- Title: "updated book 1", // only this column is going to be updated
- AuthorID: 2,
- }
- _, err := db.Model(&book).Column("title").Returning("*").Update()
- if err != nil {
- panic(err)
- }
-
- fmt.Println(book, book.AuthorID)
- // Output: Book 1
-}
-
-func ExampleDB_Update_someColumns2() {
- db := modelDB()
-
- book := Book{
- Id: 1,
- Title: "updated book 1",
- AuthorID: 2, // this column will not be updated
- }
- _, err := db.Model(&book).Set("title = ?title").Returning("*").Update()
- if err != nil {
- panic(err)
- }
-
- fmt.Println(book, book.AuthorID)
- // Output: Book 1
-}
-
-func ExampleDB_Update_setValues() {
- db := modelDB()
-
- var book Book
- _, err := db.Model(&book).
- Set("title = concat(?, title, ?)", "prefix ", " suffix").
- Where("id = ?", 1).
- Returning("*").
- Update()
- if err != nil {
- panic(err)
- }
-
- fmt.Println(book)
- // Output: Book
-}
-
-func ExampleDB_Update_bulkUpdate() {
- db := modelDB()
-
- book1 := &Book{
- Id: 1,
- Title: "updated book 1",
- }
- book2 := &Book{
- Id: 2,
- Title: "updated book 2",
- }
-
- // UPDATE "books" AS "book"
- // SET "title" = _data."title"
- // FROM (VALUES ('updated book 1', 1), ('updated book 2', 2)) AS _data("title", "id")
- // WHERE "book"."id" = _data."id"
- _, err := db.Model(book1, book2).Column("title").Update()
- if err != nil {
- panic(err)
- }
-
- var books []Book
- err = db.Model(&books).Order("id").Select()
- if err != nil {
- panic(err)
- }
-
- fmt.Println(books)
- // Output: [Book Book Book]
-}
-
-func ExampleDB_Update_bulkUpdateSlice() {
- db := modelDB()
-
- books := []Book{{
- Id: 1,
- Title: "updated book 1",
- }, {
- Id: 2,
- Title: "updated book 2",
- }}
-
- // UPDATE "books" AS "book"
- // SET "title" = _data."title"
- // FROM (VALUES ('updated book 1', 1), ('updated book 2', 2)) AS _data("title", "id")
- // WHERE "book"."id" = _data."id"
- _, err := db.Model(&books).Column("title").Update()
- if err != nil {
- panic(err)
- }
-
- books = nil
- err = db.Model(&books).Order("id").Select()
- if err != nil {
- panic(err)
- }
-
- fmt.Println(books)
- // Output: [Book Book Book]
-}
-
-func ExampleDB_Delete() {
- db := modelDB()
-
- book := Book{
- Title: "title 1",
- AuthorID: 1,
- }
- err := db.Insert(&book)
- if err != nil {
- panic(err)
- }
-
- err = db.Delete(&book)
- if err != nil {
- panic(err)
- }
-
- err = db.Select(&book)
- fmt.Println(err)
- // Output: pg: no rows in result set
-}
-
-func ExampleDB_Delete_multipleRows() {
- db := modelDB()
-
- ids := pg.In([]int{1, 2, 3})
- res, err := db.Model(&Book{}).Where("id IN (?)", ids).Delete()
- if err != nil {
- panic(err)
- }
- fmt.Println("deleted", res.RowsAffected())
-
- count, err := db.Model(&Book{}).Count()
- if err != nil {
- panic(err)
- }
- fmt.Println("left", count)
-
- // Output: deleted 3
- // left 0
-}
-
-func ExampleQ() {
- db := modelDB()
-
- cond := fmt.Sprintf("id = %d", 1)
-
- var book Book
- err := db.Model(&book).Where("?", pg.Q(cond)).Select()
- if err != nil {
- panic(err)
- }
- fmt.Println(book)
- // Output: Book
-}
-
-func ExampleF() {
- db := modelDB()
-
- var book Book
- err := db.Model(&book).Where("? = 1", pg.F("id")).Select()
- if err != nil {
- panic(err)
- }
- fmt.Println(book)
- // Output: Book
-}
-
-func ExampleDB_jsonUseNumber() {
- type Event struct {
- Id int
- Data map[string]interface{} `pg:",json_use_number"`
- }
-
- db := pg.Connect(pgOptions())
- defer db.Close()
-
- err := db.CreateTable((*Event)(nil), &orm.CreateTableOptions{
- Temp: true,
- })
- if err != nil {
- panic(err)
- }
-
- event := &Event{
- Data: map[string]interface{}{
- "price": 1.23,
- },
- }
- err = db.Insert(event)
- if err != nil {
- panic(err)
- }
-
- event2 := new(Event)
- err = db.Model(event2).Where("id = ?", event.Id).Select()
- if err != nil {
- panic(err)
- }
-
- // Check that price is decoded as json.Number.
- fmt.Printf("%T", event2.Data["price"])
- // Output: json.Number
-}
diff --git a/vendor/github.com/go-pg/pg/example_placeholders_test.go b/vendor/github.com/go-pg/pg/example_placeholders_test.go
deleted file mode 100644
index 203082e..0000000
--- a/vendor/github.com/go-pg/pg/example_placeholders_test.go
+++ /dev/null
@@ -1,80 +0,0 @@
-package pg_test
-
-import (
- "fmt"
-
- "github.com/go-pg/pg"
-)
-
-type Params struct {
- X int
- Y int
-}
-
-func (p *Params) Sum() int {
- return p.X + p.Y
-}
-
-// go-pg recognizes `?` in queries as placeholders and replaces them
-// with parameters when queries are executed. `?` can be escaped with backslash.
-// Parameters are escaped before replacing according to PostgreSQL rules.
-// Specifically:
-// - all parameters are properly quoted against SQL injections;
-// - null byte is removed;
-// - JSON/JSONB gets `\u0000` escaped as `\\u0000`.
-func Example_placeholders() {
- var num int
-
- // Simple params.
- _, err := db.Query(pg.Scan(&num), "SELECT ?", 42)
- if err != nil {
- panic(err)
- }
- fmt.Println("simple:", num)
-
- // Indexed params.
- _, err = db.Query(pg.Scan(&num), "SELECT ?0 + ?0", 1)
- if err != nil {
- panic(err)
- }
- fmt.Println("indexed:", num)
-
- // Named params.
- params := &Params{
- X: 1,
- Y: 1,
- }
- _, err = db.Query(pg.Scan(&num), "SELECT ?x + ?y + ?Sum", params)
- if err != nil {
- panic(err)
- }
- fmt.Println("named:", num)
-
- // Global params.
- _, err = db.WithParam("z", 1).Query(pg.Scan(&num), "SELECT ?x + ?y + ?z", params)
- if err != nil {
- panic(err)
- }
- fmt.Println("global:", num)
-
- // Model params.
- var tableName, tableAlias, columns string
- _, err = db.Model(&Params{}).Query(
- pg.Scan(&tableName, &tableAlias, &columns),
- "SELECT '?TableName', '?TableAlias', '?Columns'",
- )
- if err != nil {
- panic(err)
- }
- fmt.Println("table name:", tableName)
- fmt.Println("table alias:", tableAlias)
- fmt.Println("columns:", columns)
-
- // Output: simple: 42
- // indexed: 2
- // named: 4
- // global: 3
- // table name: "params"
- // table alias: "params"
- // columns: "x", "y"
-}
diff --git a/vendor/github.com/go-pg/pg/example_test.go b/vendor/github.com/go-pg/pg/example_test.go
deleted file mode 100644
index e14f437..0000000
--- a/vendor/github.com/go-pg/pg/example_test.go
+++ /dev/null
@@ -1,284 +0,0 @@
-package pg_test
-
-import (
- "bytes"
- "fmt"
- "strings"
- "time"
-
- "github.com/go-pg/pg"
- "github.com/go-pg/pg/orm"
-)
-
-var db *pg.DB
-
-func init() {
- db = connect()
-}
-
-func connect() *pg.DB {
- return pg.Connect(pgOptions())
-}
-
-func ExampleConnect() {
- db := pg.Connect(&pg.Options{
- User: "postgres",
- Password: "",
- Database: "postgres",
- })
-
- var n int
- _, err := db.QueryOne(pg.Scan(&n), "SELECT 1")
- if err != nil {
- panic(err)
- }
- fmt.Println(n)
-
- err = db.Close()
- if err != nil {
- panic(err)
- }
-
- // Output: 1
-}
-
-func ExampleDB_QueryOne() {
- var user struct {
- Name string
- }
-
- res, err := db.QueryOne(&user, `
- WITH users (name) AS (VALUES (?))
- SELECT * FROM users
- `, "admin")
- if err != nil {
- panic(err)
- }
- fmt.Println(res.RowsAffected())
- fmt.Println(user)
- // Output: 1
- // {admin}
-}
-
-func ExampleDB_QueryOne_returning_id() {
- _, err := db.Exec(`CREATE TEMP TABLE users(id serial, name varchar(500))`)
- if err != nil {
- panic(err)
- }
-
- var user struct {
- Id int32
- Name string
- }
- user.Name = "admin"
-
- _, err = db.QueryOne(&user, `
- INSERT INTO users (name) VALUES (?name) RETURNING id
- `, &user)
- if err != nil {
- panic(err)
- }
- fmt.Println(user)
- // Output: {1 admin}
-}
-
-func ExampleDB_Exec() {
- res, err := db.Exec(`CREATE TEMP TABLE test()`)
- fmt.Println(res.RowsAffected(), err)
- // Output: -1
-}
-
-func ExampleListener() {
- ln := db.Listen("mychan")
- defer ln.Close()
-
- ch := ln.Channel()
-
- go func() {
- time.Sleep(time.Millisecond)
- _, err := db.Exec("NOTIFY mychan, ?", "hello world")
- if err != nil {
- panic(err)
- }
- }()
-
- notif := <-ch
- fmt.Println(notif)
- // Output: &{mychan hello world}
-}
-
-func txExample() *pg.DB {
- db := pg.Connect(&pg.Options{
- User: "postgres",
- })
-
- queries := []string{
- `DROP TABLE IF EXISTS tx_test`,
- `CREATE TABLE tx_test(counter int)`,
- `INSERT INTO tx_test (counter) VALUES (0)`,
- }
- for _, q := range queries {
- _, err := db.Exec(q)
- if err != nil {
- panic(err)
- }
- }
-
- return db
-}
-
-func ExampleDB_Begin() {
- db := txExample()
-
- tx, err := db.Begin()
- if err != nil {
- panic(err)
- }
-
- var counter int
- _, err = tx.QueryOne(pg.Scan(&counter), `SELECT counter FROM tx_test`)
- if err != nil {
- tx.Rollback()
- panic(err)
- }
-
- counter++
-
- _, err = tx.Exec(`UPDATE tx_test SET counter = ?`, counter)
- if err != nil {
- tx.Rollback()
- panic(err)
- }
-
- err = tx.Commit()
- if err != nil {
- panic(err)
- }
-
- fmt.Println(counter)
- // Output: 1
-}
-
-func ExampleDB_RunInTransaction() {
- db := txExample()
-
- var counter int
- // Transaction is automatically rollbacked on error.
- err := db.RunInTransaction(func(tx *pg.Tx) error {
- _, err := tx.QueryOne(pg.Scan(&counter), `SELECT counter FROM tx_test`)
- if err != nil {
- return err
- }
-
- counter++
-
- _, err = tx.Exec(`UPDATE tx_test SET counter = ?`, counter)
- return err
- })
- if err != nil {
- panic(err)
- }
-
- fmt.Println(counter)
- // Output: 1
-}
-
-func ExampleDB_Prepare() {
- stmt, err := db.Prepare(`SELECT $1::text, $2::text`)
- if err != nil {
- panic(err)
- }
-
- var s1, s2 string
- _, err = stmt.QueryOne(pg.Scan(&s1, &s2), "foo", "bar")
- if err != nil {
- panic(err)
- }
- fmt.Println(s1, s2)
- // Output: foo bar
-}
-
-func ExampleDB_CreateTable() {
- type Model struct {
- Id int
- Name string
- }
-
- err := db.CreateTable(&Model{}, &orm.CreateTableOptions{
- Temp: true, // create temp table
- })
- if err != nil {
- panic(err)
- }
-
- var info []struct {
- ColumnName string
- DataType string
- }
- _, err = db.Query(&info, `
- SELECT column_name, data_type
- FROM information_schema.columns
- WHERE table_name = 'models'
- `)
- if err != nil {
- panic(err)
- }
- fmt.Println(info)
- // Output: [{id bigint} {name text}]
-}
-
-func ExampleInts() {
- var nums pg.Ints
- _, err := db.Query(&nums, `SELECT generate_series(0, 10)`)
- fmt.Println(nums, err)
- // Output: [0 1 2 3 4 5 6 7 8 9 10]
-}
-
-func ExampleStrings() {
- var strs pg.Strings
- _, err := db.Query(&strs, `
- WITH users AS (VALUES ('foo'), ('bar')) SELECT * FROM users
- `)
- fmt.Println(strs, err)
- // Output: [foo bar]
-}
-
-func ExampleDB_CopyFrom() {
- _, err := db.Exec(`CREATE TEMP TABLE words(word text, len int)`)
- if err != nil {
- panic(err)
- }
-
- r := strings.NewReader("hello,5\nfoo,3\n")
- _, err = db.CopyFrom(r, `COPY words FROM STDIN WITH CSV`)
- if err != nil {
- panic(err)
- }
-
- var buf bytes.Buffer
- _, err = db.CopyTo(&buf, `COPY words TO STDOUT WITH CSV`)
- if err != nil {
- panic(err)
- }
- fmt.Println(buf.String())
- // Output: hello,5
- // foo,3
-}
-
-func ExampleDB_WithTimeout() {
- var count int
- // Use bigger timeout since this query is known to be slow.
- _, err := db.WithTimeout(time.Minute).QueryOne(pg.Scan(&count), `
- SELECT count(*) FROM big_table
- `)
- if err != nil {
- panic(err)
- }
-}
-
-func ExampleScan() {
- var s1, s2 string
- _, err := db.QueryOne(pg.Scan(&s1, &s2), `SELECT ?, ?`, "foo", "bar")
- fmt.Println(s1, s2, err)
- // Output: foo bar
-}
diff --git a/vendor/github.com/go-pg/pg/exampledb_model_test.go b/vendor/github.com/go-pg/pg/exampledb_model_test.go
deleted file mode 100644
index 720a9d6..0000000
--- a/vendor/github.com/go-pg/pg/exampledb_model_test.go
+++ /dev/null
@@ -1,109 +0,0 @@
-package pg_test
-
-import (
- "fmt"
-
- "github.com/go-pg/pg"
- "github.com/go-pg/pg/orm"
-)
-
-type User struct {
- Id int64
- Name string
- Emails []string
-}
-
-func (u User) String() string {
- return fmt.Sprintf("User<%d %s %v>", u.Id, u.Name, u.Emails)
-}
-
-type Story struct {
- Id int64
- Title string
- AuthorId int64
- Author *User
-}
-
-func (s Story) String() string {
- return fmt.Sprintf("Story<%d %s %s>", s.Id, s.Title, s.Author)
-}
-
-func ExampleDB_Model() {
- db := pg.Connect(&pg.Options{
- User: "postgres",
- })
-
- err := createSchema(db)
- if err != nil {
- panic(err)
- }
-
- user1 := &User{
- Name: "admin",
- Emails: []string{"admin1@admin", "admin2@admin"},
- }
- err = db.Insert(user1)
- if err != nil {
- panic(err)
- }
-
- err = db.Insert(&User{
- Name: "root",
- Emails: []string{"root1@root", "root2@root"},
- })
- if err != nil {
- panic(err)
- }
-
- story1 := &Story{
- Title: "Cool story",
- AuthorId: user1.Id,
- }
- err = db.Insert(story1)
- if err != nil {
- panic(err)
- }
-
- // Select user by primary key.
- user := User{Id: user1.Id}
- err = db.Select(&user)
- if err != nil {
- panic(err)
- }
-
- // Select all users.
- var users []User
- err = db.Model(&users).Select()
- if err != nil {
- panic(err)
- }
-
- // Select story and associated author in one query.
- var story Story
- err = db.Model(&story).
- Column("story.*", "Author").
- Where("story.id = ?", story1.Id).
- Select()
- if err != nil {
- panic(err)
- }
-
- fmt.Println(user)
- fmt.Println(users)
- fmt.Println(story)
- // Output: User<1 admin [admin1@admin admin2@admin]>
- // [User<1 admin [admin1@admin admin2@admin]> User<2 root [root1@root root2@root]>]
- // Story<1 Cool story User<1 admin [admin1@admin admin2@admin]>>
-}
-
-func createSchema(db *pg.DB) error {
- for _, model := range []interface{}{&User{}, &Story{}} {
- err := db.CreateTable(model, &orm.CreateTableOptions{
- Temp: true,
- })
- if err != nil {
- return err
- }
- }
- return nil
-}
diff --git a/vendor/github.com/go-pg/pg/exampledb_query_test.go b/vendor/github.com/go-pg/pg/exampledb_query_test.go
deleted file mode 100644
index 75d557b..0000000
--- a/vendor/github.com/go-pg/pg/exampledb_query_test.go
+++ /dev/null
@@ -1,109 +0,0 @@
-package pg_test
-
-import (
- "fmt"
-
- "github.com/go-pg/pg"
-)
-
-func CreateUser(db *pg.DB, user *User) error {
- _, err := db.QueryOne(user, `
- INSERT INTO users (name, emails) VALUES (?name, ?emails)
- RETURNING id
- `, user)
- return err
-}
-
-func GetUser(db *pg.DB, id int64) (*User, error) {
- var user User
- _, err := db.QueryOne(&user, `SELECT * FROM users WHERE id = ?`, id)
- return &user, err
-}
-
-func GetUsers(db *pg.DB) ([]User, error) {
- var users []User
- _, err := db.Query(&users, `SELECT * FROM users`)
- return users, err
-}
-
-func GetUsersByIds(db *pg.DB, ids []int64) ([]User, error) {
- var users []User
- _, err := db.Query(&users, `SELECT * FROM users WHERE id IN (?)`, pg.In(ids))
- return users, err
-}
-
-func CreateStory(db *pg.DB, story *Story) error {
- _, err := db.QueryOne(story, `
- INSERT INTO stories (title, author_id) VALUES (?title, ?author_id)
- RETURNING id
- `, story)
- return err
-}
-
-// GetStory returns story with associated author.
-func GetStory(db *pg.DB, id int64) (*Story, error) {
- var story Story
- _, err := db.QueryOne(&story, `
- SELECT s.*,
- u.id AS author__id, u.name AS author__name, u.emails AS author__emails
- FROM stories AS s, users AS u
- WHERE s.id = ? AND u.id = s.author_id
- `, id)
- return &story, err
-}
-
-func ExampleDB_Query() {
- db := pg.Connect(&pg.Options{
- User: "postgres",
- })
-
- err := createSchema(db)
- if err != nil {
- panic(err)
- }
-
- user1 := &User{
- Name: "admin",
- Emails: []string{"admin1@admin", "admin2@admin"},
- }
- err = CreateUser(db, user1)
- if err != nil {
- panic(err)
- }
-
- err = CreateUser(db, &User{
- Name: "root",
- Emails: []string{"root1@root", "root2@root"},
- })
- if err != nil {
- panic(err)
- }
-
- story1 := &Story{
- Title: "Cool story",
- AuthorId: user1.Id,
- }
- err = CreateStory(db, story1)
-
- user, err := GetUser(db, user1.Id)
- if err != nil {
- panic(err)
- }
-
- users, err := GetUsers(db)
- if err != nil {
- panic(err)
- }
-
- story, err := GetStory(db, story1.Id)
- if err != nil {
- panic(err)
- }
-
- fmt.Println(user)
- fmt.Println(users)
- fmt.Println(story)
- // Output: User<1 admin [admin1@admin admin2@admin]>
- // [User<1 admin [admin1@admin admin2@admin]> User<2 root [root1@root root2@root]>]
- // Story<1 Cool story User<1 admin [admin1@admin admin2@admin]>>
-}
diff --git a/vendor/github.com/go-pg/pg/export_test.go b/vendor/github.com/go-pg/pg/export_test.go
deleted file mode 100644
index b2f2101..0000000
--- a/vendor/github.com/go-pg/pg/export_test.go
+++ /dev/null
@@ -1,11 +0,0 @@
-package pg
-
-import "github.com/go-pg/pg/internal/pool"
-
-func (db *DB) Pool() pool.Pooler {
- return db.pool
-}
-
-func (ln *Listener) CurrentConn() *pool.Conn {
- return ln.cn
-}
diff --git a/vendor/github.com/go-pg/pg/hook.go b/vendor/github.com/go-pg/pg/hook.go
deleted file mode 100644
index ff6723b..0000000
--- a/vendor/github.com/go-pg/pg/hook.go
+++ /dev/null
@@ -1,145 +0,0 @@
-package pg
-
-import (
- "fmt"
- "runtime"
- "strings"
- "time"
-
- "github.com/go-pg/pg/orm"
-)
-
-type dummyDB struct {
- orm.DB
-}
-
-var _ orm.DB = dummyDB{}
-
-func (dummyDB) FormatQuery(dst []byte, query string, params ...interface{}) []byte {
- return append(dst, query...)
-}
-
-type QueryProcessedEvent struct {
- StartTime time.Time
- Func string
- File string
- Line int
-
- DB orm.DB
- Query interface{}
- Params []interface{}
- Attempt int
- Result orm.Result
- Error error
-}
-
-func (ev *QueryProcessedEvent) UnformattedQuery() (string, error) {
- b, err := queryString(ev.Query)
- if err != nil {
- return "", err
- }
- return string(b), nil
-}
-
-func (ev *QueryProcessedEvent) FormattedQuery() (string, error) {
- b, err := appendQuery(nil, ev.DB, ev.Query, ev.Params...)
- if err != nil {
- return "", err
- }
- return string(b), nil
-}
-
-func queryString(query interface{}) ([]byte, error) {
- switch query := query.(type) {
- case orm.QueryAppender:
- query = query.Copy()
- query.Query().DB(dummyDB{})
- return query.AppendQuery(nil)
- case string:
- return dummyDB{}.FormatQuery(nil, query), nil
- default:
- return nil, fmt.Errorf("pg: can't append %T", query)
- }
-}
-
-type queryProcessedHook func(*QueryProcessedEvent)
-
-// OnQueryProcessed calls the fn with QueryProcessedEvent
-// when query is processed.
-func (db *DB) OnQueryProcessed(fn func(*QueryProcessedEvent)) {
- db.queryProcessedHooks = append(db.queryProcessedHooks, fn)
-}
-
-func (db *DB) queryProcessed(
- ormDB orm.DB,
- start time.Time,
- query interface{},
- params []interface{},
- attempt int,
- res orm.Result,
- err error,
-) {
- if len(db.queryProcessedHooks) == 0 {
- return
- }
-
- funcName, file, line := fileLine(2)
- event := &QueryProcessedEvent{
- StartTime: start,
- Func: funcName,
- File: file,
- Line: line,
-
- DB: ormDB,
- Query: query,
- Params: params,
- Attempt: attempt,
- Result: res,
- Error: err,
- }
- for _, hook := range db.queryProcessedHooks {
- hook(event)
- }
-}
-
-const packageName = "github.com/go-pg/pg"
-
-func fileLine(depth int) (string, string, int) {
- for i := depth; ; i++ {
- pc, file, line, ok := runtime.Caller(i)
- if !ok {
- break
- }
- if strings.Contains(file, packageName) {
- continue
- }
- _, funcName := packageFuncName(pc)
- return funcName, file, line
- }
- return "", "", 0
-}
-
-func packageFuncName(pc uintptr) (string, string) {
- f := runtime.FuncForPC(pc)
- if f == nil {
- return "", ""
- }
-
- packageName := ""
- funcName := f.Name()
-
- if ind := strings.LastIndex(funcName, "/"); ind > 0 {
- packageName += funcName[:ind+1]
- funcName = funcName[ind+1:]
- }
- if ind := strings.Index(funcName, "."); ind > 0 {
- packageName += funcName[:ind]
- funcName = funcName[ind+1:]
- }
-
- return packageName, funcName
-}
-
-func copyQueryProcessedHooks(s []queryProcessedHook) []queryProcessedHook {
- return s[:len(s):len(s)]
-}
diff --git a/vendor/github.com/go-pg/pg/hook_test.go b/vendor/github.com/go-pg/pg/hook_test.go
deleted file mode 100644
index 90384dd..0000000
--- a/vendor/github.com/go-pg/pg/hook_test.go
+++ /dev/null
@@ -1,236 +0,0 @@
-package pg_test
-
-import (
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-
- "github.com/go-pg/pg"
- "github.com/go-pg/pg/orm"
-)
-
-type HookTest struct {
- Id int
- Value string
-
- afterQuery int
- afterSelect int
-
- beforeInsert int
- afterInsert int
-
- beforeUpdate int
- afterUpdate int
-
- beforeDelete int
- afterDelete int
-}
-
-func (t *HookTest) AfterQuery(db orm.DB) error {
- t.afterQuery++
- return nil
-}
-
-func (t *HookTest) AfterSelect(db orm.DB) error {
- t.afterSelect++
- return nil
-}
-
-func (t *HookTest) BeforeInsert(db orm.DB) error {
- t.beforeInsert++
- return nil
-}
-
-func (t *HookTest) AfterInsert(db orm.DB) error {
- t.afterInsert++
- return nil
-}
-
-func (t *HookTest) BeforeUpdate(db orm.DB) error {
- t.beforeUpdate++
- return nil
-}
-
-func (t *HookTest) AfterUpdate(db orm.DB) error {
- t.afterUpdate++
- return nil
-}
-
-func (t *HookTest) BeforeDelete(db orm.DB) error {
- t.beforeDelete++
- return nil
-}
-
-func (t *HookTest) AfterDelete(db orm.DB) error {
- t.afterDelete++
- return nil
-}
-
-var _ = Describe("HookTest", func() {
- var db *pg.DB
-
- BeforeEach(func() {
- db = pg.Connect(pgOptions())
-
- qs := []string{
- "CREATE TEMP TABLE hook_tests (id int, value text)",
- "INSERT INTO hook_tests VALUES (1, '')",
- }
- for _, q := range qs {
- _, err := db.Exec(q)
- Expect(err).NotTo(HaveOccurred())
- }
- })
-
- AfterEach(func() {
- Expect(db.Close()).NotTo(HaveOccurred())
- })
-
- It("calls AfterQuery for struct", func() {
- var hook HookTest
- _, err := db.QueryOne(&hook, "SELECT 1 AS id")
- Expect(err).NotTo(HaveOccurred())
- Expect(hook.afterQuery).To(Equal(1))
- Expect(hook.afterSelect).To(Equal(0))
- })
-
- It("calls AfterQuery and AfterSelect for struct model", func() {
- var hook HookTest
- err := db.Model(&hook).Select()
- Expect(err).NotTo(HaveOccurred())
- Expect(hook.afterQuery).To(Equal(1))
- Expect(hook.afterSelect).To(Equal(1))
- })
-
- It("calls AfterQuery for slice", func() {
- var hooks []HookTest
- _, err := db.Query(&hooks, "SELECT 1 AS id")
- Expect(err).NotTo(HaveOccurred())
- Expect(hooks).To(HaveLen(1))
- Expect(hooks[0].afterQuery).To(Equal(1))
- Expect(hooks[0].afterSelect).To(Equal(0))
- })
-
- It("calls AfterQuery and AfterSelect for slice model", func() {
- var hooks []HookTest
- err := db.Model(&hooks).Select()
- Expect(err).NotTo(HaveOccurred())
- Expect(hooks).To(HaveLen(1))
- Expect(hooks[0].afterQuery).To(Equal(1))
- Expect(hooks[0].afterSelect).To(Equal(1))
- })
-
- It("calls BeforeInsert and AfterInsert", func() {
- hook := HookTest{
- Id: 1,
- Value: "value",
- }
- err := db.Insert(&hook)
- Expect(err).NotTo(HaveOccurred())
- Expect(hook.afterQuery).To(Equal(0))
- Expect(hook.beforeInsert).To(Equal(1))
- Expect(hook.afterInsert).To(Equal(1))
- })
-
- It("calls BeforeUpdate and AfterUpdate", func() {
- hook := HookTest{
- Id: 1,
- }
- err := db.Update(&hook)
- Expect(err).NotTo(HaveOccurred())
- Expect(hook.afterQuery).To(Equal(0))
- Expect(hook.beforeUpdate).To(Equal(1))
- Expect(hook.afterUpdate).To(Equal(1))
- })
-
- It("calls BeforeDelete and AfterDelete", func() {
- hook := HookTest{
- Id: 1,
- }
- err := db.Delete(&hook)
- Expect(err).NotTo(HaveOccurred())
- Expect(hook.afterQuery).To(Equal(0))
- Expect(hook.beforeDelete).To(Equal(1))
- Expect(hook.afterDelete).To(Equal(1))
- })
-})
-
-var _ = Describe("OnQueryProcessed", func() {
- var db *pg.DB
- var count int
-
- BeforeEach(func() {
- db = pg.Connect(pgOptions())
- count = 0
- })
-
- Describe("Query/Exec", func() {
- BeforeEach(func() {
- db.OnQueryProcessed(func(event *pg.QueryProcessedEvent) {
- Expect(event.StartTime).NotTo(BeZero())
- Expect(event.Func).NotTo(BeZero())
- Expect(event.File).NotTo(BeZero())
- Expect(event.Line).NotTo(BeZero())
- Expect(event.DB).To(Equal(db))
- Expect(event.Query).To(Equal("SELECT ?"))
- Expect(event.Params).To(Equal([]interface{}{1}))
- Expect(event.Result).NotTo(BeNil())
- Expect(event.Error).NotTo(HaveOccurred())
-
- q, err := event.UnformattedQuery()
- Expect(err).NotTo(HaveOccurred())
- Expect(q).To(Equal("SELECT ?"))
-
- q, err = event.FormattedQuery()
- Expect(err).NotTo(HaveOccurred())
- Expect(q).To(Equal("SELECT 1"))
-
- count++
- })
- })
-
- It("is called for Query", func() {
- _, err := db.Query(pg.Discard, "SELECT ?", 1)
- Expect(err).NotTo(HaveOccurred())
- Expect(count).To(Equal(1))
- })
-
- It("is called for Exec", func() {
- _, err := db.Exec("SELECT ?", 1)
- Expect(err).NotTo(HaveOccurred())
- Expect(count).To(Equal(1))
- })
- })
-
- Describe("Model", func() {
- BeforeEach(func() {
- db.OnQueryProcessed(func(event *pg.QueryProcessedEvent) {
- Expect(event.StartTime).NotTo(BeZero())
- Expect(event.Func).NotTo(BeZero())
- Expect(event.File).NotTo(BeZero())
- Expect(event.Line).NotTo(BeZero())
- Expect(event.DB).To(Equal(db))
- Expect(event.Query).NotTo(BeNil())
- Expect(event.Params).To(HaveLen(1))
- Expect(event.Error).NotTo(HaveOccurred())
- Expect(event.Result).NotTo(BeNil())
-
- q, err := event.UnformattedQuery()
- Expect(err).NotTo(HaveOccurred())
- Expect(q).To(Equal("SELECT ?"))
-
- q, err = event.FormattedQuery()
- Expect(err).NotTo(HaveOccurred())
- Expect(q).To(Equal("SELECT 1"))
-
- count++
- })
- })
-
- It("is called for Model", func() {
- var n int
- err := db.Model().ColumnExpr("?", 1).Select(&n)
- Expect(err).NotTo(HaveOccurred())
- Expect(count).To(Equal(1))
- })
- })
-})
diff --git a/vendor/github.com/go-pg/pg/internal/error.go b/vendor/github.com/go-pg/pg/internal/error.go
deleted file mode 100644
index 0107ee9..0000000
--- a/vendor/github.com/go-pg/pg/internal/error.go
+++ /dev/null
@@ -1,62 +0,0 @@
-package internal
-
-import (
- "errors"
- "fmt"
-)
-
-var ErrNoRows = errors.New("pg: no rows in result set")
-var ErrMultiRows = errors.New("pg: multiple rows in result set")
-
-type Error struct {
- s string
-}
-
-func Errorf(s string, args ...interface{}) Error {
- return Error{s: fmt.Sprintf(s, args...)}
-}
-
-func (err Error) Error() string {
- return err.s
-}
-
-type PGError struct {
- m map[byte]string
-}
-
-func NewPGError(m map[byte]string) PGError {
- return PGError{
- m: m,
- }
-}
-
-func (err PGError) Field(k byte) string {
- return err.m[k]
-}
-
-func (err PGError) IntegrityViolation() bool {
- switch err.Field('C') {
- case "23000", "23001", "23502", "23503", "23505", "23514", "23P01":
- return true
- default:
- return false
- }
-}
-
-func (err PGError) Error() string {
- return fmt.Sprintf(
- "%s #%s %s (addr=%q)",
- err.Field('S'), err.Field('C'), err.Field('M'), err.Field('a'),
- )
-}
-
-func AssertOneRow(l int) error {
- switch {
- case l == 0:
- return ErrNoRows
- case l > 1:
- return ErrMultiRows
- default:
- return nil
- }
-}
diff --git a/vendor/github.com/go-pg/pg/internal/internal.go b/vendor/github.com/go-pg/pg/internal/internal.go
deleted file mode 100644
index ad3fc3c..0000000
--- a/vendor/github.com/go-pg/pg/internal/internal.go
+++ /dev/null
@@ -1,24 +0,0 @@
-package internal
-
-import (
- "math/rand"
- "time"
-)
-
-// Retry backoff with jitter sleep to prevent overloaded conditions during intervals
-// https://www.awsarchitectureblog.com/2015/03/backoff.html
-func RetryBackoff(retry int, minBackoff, maxBackoff time.Duration) time.Duration {
- if retry < 0 {
- retry = 0
- }
-
- backoff := minBackoff << uint(retry)
- if backoff > maxBackoff || backoff < minBackoff {
- backoff = maxBackoff
- }
-
- if backoff == 0 {
- return 0
- }
- return time.Duration(rand.Int63n(int64(backoff)))
-}
diff --git a/vendor/github.com/go-pg/pg/internal/log.go b/vendor/github.com/go-pg/pg/internal/log.go
deleted file mode 100644
index fd14222..0000000
--- a/vendor/github.com/go-pg/pg/internal/log.go
+++ /dev/null
@@ -1,15 +0,0 @@
-package internal
-
-import (
- "fmt"
- "log"
-)
-
-var Logger *log.Logger
-
-func Logf(s string, args ...interface{}) {
- if Logger == nil {
- return
- }
- Logger.Output(2, fmt.Sprintf(s, args...))
-}
diff --git a/vendor/github.com/go-pg/pg/internal/parser/array_parser.go b/vendor/github.com/go-pg/pg/internal/parser/array_parser.go
deleted file mode 100644
index 70b3e6e..0000000
--- a/vendor/github.com/go-pg/pg/internal/parser/array_parser.go
+++ /dev/null
@@ -1,80 +0,0 @@
-package parser
-
-import (
- "bytes"
- "fmt"
-)
-
-type ArrayParser struct {
- *Parser
-
- stickyErr error
-}
-
-func NewArrayParser(b []byte) *ArrayParser {
- var err error
- if len(b) < 2 || b[0] != '{' || b[len(b)-1] != '}' {
- err = fmt.Errorf("pg: can't parse array: %s", string(b))
- } else {
- b = b[1 : len(b)-1]
- }
- return &ArrayParser{
- Parser: New(b),
-
- stickyErr: err,
- }
-}
-
-func (p *ArrayParser) NextElem() ([]byte, error) {
- if p.stickyErr != nil {
- return nil, p.stickyErr
- }
-
- switch c := p.Peek(); c {
- case '"':
- p.Advance()
- b := p.readSubstring()
- p.Skip(',')
- return b, nil
- case '{':
- b := p.readElem()
- if b != nil {
- b = append(b, '}')
- }
- p.Skip(',')
- return b, nil
- default:
- b, _ := p.ReadSep(',')
- if bytes.Equal(b, pgNull) {
- b = nil
- }
- return b, nil
- }
-}
-
-func (p *ArrayParser) readElem() []byte {
- var b []byte
- for p.Valid() {
- c := p.Read()
- switch c {
- case '"':
- b = append(b, '"')
- for {
- bb, ok := p.ReadSep('"')
- b = append(b, bb...)
- stop := len(b) > 0 && b[len(b)-1] != '\\'
- if ok {
- b = append(b, '"')
- }
- if stop {
- break
- }
- }
- case '}':
- return b
- default:
- b = append(b, c)
- }
- }
- return b
-}
diff --git a/vendor/github.com/go-pg/pg/internal/parser/array_parser_test.go b/vendor/github.com/go-pg/pg/internal/parser/array_parser_test.go
deleted file mode 100644
index 274ed74..0000000
--- a/vendor/github.com/go-pg/pg/internal/parser/array_parser_test.go
+++ /dev/null
@@ -1,55 +0,0 @@
-package parser_test
-
-import (
- "testing"
-
- "github.com/go-pg/pg/internal/parser"
-)
-
-var arrayTests = []struct {
- s string
- els []string
-}{
- {`{"\\"}`, []string{`\`}},
- {`{"''"}`, []string{`'`}},
- {`{{"''\"{}"}}`, []string{`{"''\"{}"}`}},
- {`{"''\"{}"}`, []string{`'"{}`}},
-
- {"{1,2}", []string{"1", "2"}},
- {"{1,NULL}", []string{"1", ""}},
- {`{"1","2"}`, []string{"1", "2"}},
- {`{"{1}","{2}"}`, []string{"{1}", "{2}"}},
-
- {"{{1,2},{3}}", []string{"{1,2}", "{3}"}},
-}
-
-func TestArrayParser(t *testing.T) {
- for testi, test := range arrayTests {
- p := parser.NewArrayParser([]byte(test.s))
-
- var got []string
- for p.Valid() {
- b, err := p.NextElem()
- if err != nil {
- t.Fatal(err)
- }
- got = append(got, string(b))
- }
-
- if len(got) != len(test.els) {
- t.Fatalf(
- "#%d got %d elements, wanted %d (got=%#v wanted=%#v)",
- testi, len(got), len(test.els), got, test.els,
- )
- }
-
- for i, el := range got {
- if el != test.els[i] {
- t.Fatalf(
- "#%d el #%d does not match: %q != %q (got=%#v wanted=%#v)",
- testi, i, el, test.els[i], got, test.els,
- )
- }
- }
- }
-}
diff --git a/vendor/github.com/go-pg/pg/internal/parser/hstore_parser.go b/vendor/github.com/go-pg/pg/internal/parser/hstore_parser.go
deleted file mode 100644
index f51561b..0000000
--- a/vendor/github.com/go-pg/pg/internal/parser/hstore_parser.go
+++ /dev/null
@@ -1,40 +0,0 @@
-package parser
-
-import "fmt"
-
-type HstoreParser struct {
- *Parser
-}
-
-func NewHstoreParser(b []byte) *HstoreParser {
- return &HstoreParser{
- Parser: New(b),
- }
-}
-
-func (p *HstoreParser) NextKey() ([]byte, error) {
- if p.Skip(',') {
- p.Skip(' ')
- }
-
- if !p.Skip('"') {
- return nil, fmt.Errorf("pg: can't parse hstore key: %q", p.Bytes())
- }
-
- key := p.readSubstring()
- if !(p.Skip('=') && p.Skip('>')) {
- return nil, fmt.Errorf("pg: can't parse hstore key: %q", p.Bytes())
- }
-
- return key, nil
-}
-
-func (p *HstoreParser) NextValue() ([]byte, error) {
- if !p.Skip('"') {
- return nil, fmt.Errorf("pg: can't parse hstore value: %q", p.Bytes())
- }
-
- value := p.readSubstring()
- p.SkipBytes([]byte(", "))
- return value, nil
-}
diff --git a/vendor/github.com/go-pg/pg/internal/parser/hstore_parser_test.go b/vendor/github.com/go-pg/pg/internal/parser/hstore_parser_test.go
deleted file mode 100644
index 2db35e5..0000000
--- a/vendor/github.com/go-pg/pg/internal/parser/hstore_parser_test.go
+++ /dev/null
@@ -1,57 +0,0 @@
-package parser_test
-
-import (
- "testing"
-
- "github.com/go-pg/pg/internal/parser"
-)
-
-var hstoreTests = []struct {
- s string
- m map[string]string
-}{
- {`""=>""`, map[string]string{"": ""}},
- {`"k''k"=>"k''k"`, map[string]string{"k'k": "k'k"}},
- {`"k\"k"=>"k\"k"`, map[string]string{`k"k`: `k"k`}},
- {`"k\k"=>"k\k"`, map[string]string{`k\k`: `k\k`}},
-
- {`"foo"=>"bar"`, map[string]string{"foo": "bar"}},
- {`"foo"=>"bar","k"=>"v"`, map[string]string{"foo": "bar", "k": "v"}},
-}
-
-func TestHstoreParser(t *testing.T) {
- for testi, test := range hstoreTests {
- p := parser.NewHstoreParser([]byte(test.s))
-
- got := make(map[string]string)
- for p.Valid() {
- key, err := p.NextKey()
- if err != nil {
- t.Fatal(err)
- }
-
- value, err := p.NextValue()
- if err != nil {
- t.Fatal(err)
- }
-
- got[string(key)] = string(value)
- }
-
- if len(got) != len(test.m) {
- t.Fatalf(
- "#%d got %d elements, wanted %d (got=%#v wanted=%#v)",
- testi, len(got), len(test.m), got, test.m,
- )
- }
-
- for k, v := range got {
- if v != test.m[k] {
- t.Fatalf(
- "#%d el %q does not match: %q != %q (got=%#v wanted=%#v)",
- testi, k, v, test.m[k], got, test.m,
- )
- }
- }
- }
-}
diff --git a/vendor/github.com/go-pg/pg/internal/parser/parser.go b/vendor/github.com/go-pg/pg/internal/parser/parser.go
deleted file mode 100644
index 77f3f52..0000000
--- a/vendor/github.com/go-pg/pg/internal/parser/parser.go
+++ /dev/null
@@ -1,153 +0,0 @@
-package parser
-
-import (
- "bytes"
- "strconv"
-
- "github.com/go-pg/pg/internal"
-)
-
-type Parser struct {
- b []byte
-}
-
-func New(b []byte) *Parser {
- return &Parser{
- b: b,
- }
-}
-
-func NewString(s string) *Parser {
- return New(internal.StringToBytes(s))
-}
-
-func (p *Parser) Bytes() []byte {
- return p.b
-}
-
-func (p *Parser) Valid() bool {
- return len(p.b) > 0
-}
-
-func (p *Parser) Read() byte {
- if p.Valid() {
- c := p.b[0]
- p.Skip(c)
- return c
- }
- return 0
-}
-
-func (p *Parser) Peek() byte {
- if p.Valid() {
- return p.b[0]
- }
- return 0
-}
-
-func (p *Parser) Advance() {
- p.b = p.b[1:]
-}
-
-func (p *Parser) Skip(c byte) bool {
- if p.Peek() == c {
- p.Advance()
- return true
- }
- return false
-}
-
-func (p *Parser) SkipBytes(b []byte) bool {
- if len(b) > len(p.b) {
- return false
- }
- if !bytes.Equal(p.b[:len(b)], b) {
- return false
- }
- p.b = p.b[len(b):]
- return true
-}
-
-func (p *Parser) ReadSep(c byte) ([]byte, bool) {
- ind := bytes.IndexByte(p.b, c)
- if ind == -1 {
- b := p.b
- p.b = p.b[len(p.b):]
- return b, false
- }
-
- b := p.b[:ind]
- p.b = p.b[ind+1:]
- return b, true
-}
-
-func (p *Parser) ReadIdentifier() (s string, numeric bool) {
- end := len(p.b)
- numeric = true
- for i, ch := range p.b {
- if isNum(ch) {
- continue
- }
- if isAlpha(ch) || ch == '_' {
- numeric = false
- continue
- }
- end = i
- break
- }
- if end <= 0 {
- return "", false
- }
- b := p.b[:end]
- p.b = p.b[end:]
- return internal.BytesToString(b), numeric
-}
-
-func (p *Parser) ReadNumber() int {
- end := len(p.b)
- for i, ch := range p.b {
- if !isNum(ch) {
- end = i
- break
- }
- }
- if end <= 0 {
- return 0
- }
- n, _ := strconv.Atoi(string(p.b[:end]))
- p.b = p.b[end:]
- return n
-}
-
-func (p *Parser) readSubstring() []byte {
- var b []byte
- for p.Valid() {
- c := p.Read()
- switch c {
- case '\\':
- switch p.Peek() {
- case '\\':
- b = append(b, '\\')
- p.Advance()
- case '"':
- b = append(b, '"')
- p.Advance()
- default:
- b = append(b, c)
- }
- case '\'':
- switch p.Peek() {
- case '\'':
- b = append(b, '\'')
- p.Skip(c)
- default:
- b = append(b, c)
- }
- case '"':
- return b
- default:
- b = append(b, c)
- }
- }
- return b
-}
diff --git a/vendor/github.com/go-pg/pg/internal/parser/util.go b/vendor/github.com/go-pg/pg/internal/parser/util.go
deleted file mode 100644
index 23844e3..0000000
--- a/vendor/github.com/go-pg/pg/internal/parser/util.go
+++ /dev/null
@@ -1,15 +0,0 @@
-package parser
-
-var pgNull = []byte("NULL")
-
-func isNum(c byte) bool {
- return c >= '0' && c <= '9'
-}
-
-func isAlpha(c byte) bool {
- return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
-}
-
-func isAlnum(c byte) bool {
- return isAlpha(c) || isNum(c)
-}
diff --git a/vendor/github.com/go-pg/pg/internal/pool/bench_test.go b/vendor/github.com/go-pg/pg/internal/pool/bench_test.go
deleted file mode 100644
index cbcbf12..0000000
--- a/vendor/github.com/go-pg/pg/internal/pool/bench_test.go
+++ /dev/null
@@ -1,80 +0,0 @@
-package pool_test
-
-import (
- "testing"
- "time"
-
- "github.com/go-pg/pg/internal/pool"
-)
-
-func benchmarkPoolGetPut(b *testing.B, poolSize int) {
- connPool := pool.NewConnPool(&pool.Options{
- Dialer: dummyDialer,
- PoolSize: poolSize,
- PoolTimeout: time.Second,
- IdleTimeout: time.Hour,
- IdleCheckFrequency: time.Hour,
- })
-
- b.ResetTimer()
-
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- cn, _, err := connPool.Get()
- if err != nil {
- b.Fatal(err)
- }
- if err = connPool.Put(cn); err != nil {
- b.Fatal(err)
- }
- }
- })
-}
-
-func BenchmarkPoolGetPut10Conns(b *testing.B) {
- benchmarkPoolGetPut(b, 10)
-}
-
-func BenchmarkPoolGetPut100Conns(b *testing.B) {
- benchmarkPoolGetPut(b, 100)
-}
-
-func BenchmarkPoolGetPut1000Conns(b *testing.B) {
- benchmarkPoolGetPut(b, 1000)
-}
-
-func benchmarkPoolGetRemove(b *testing.B, poolSize int) {
- connPool := pool.NewConnPool(&pool.Options{
- Dialer: dummyDialer,
- PoolSize: poolSize,
- PoolTimeout: time.Second,
- IdleTimeout: time.Hour,
- IdleCheckFrequency: time.Hour,
- })
-
- b.ResetTimer()
-
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- cn, _, err := connPool.Get()
- if err != nil {
- b.Fatal(err)
- }
- if err := connPool.Remove(cn); err != nil {
- b.Fatal(err)
- }
- }
- })
-}
-
-func BenchmarkPoolGetRemove10Conns(b *testing.B) {
- benchmarkPoolGetRemove(b, 10)
-}
-
-func BenchmarkPoolGetRemove100Conns(b *testing.B) {
- benchmarkPoolGetRemove(b, 100)
-}
-
-func BenchmarkPoolGetRemove1000Conns(b *testing.B) {
- benchmarkPoolGetRemove(b, 1000)
-}
diff --git a/vendor/github.com/go-pg/pg/internal/pool/conn.go b/vendor/github.com/go-pg/pg/internal/pool/conn.go
deleted file mode 100644
index 26fced5..0000000
--- a/vendor/github.com/go-pg/pg/internal/pool/conn.go
+++ /dev/null
@@ -1,106 +0,0 @@
-package pool
-
-import (
- "bufio"
- "encoding/hex"
- "fmt"
- "io"
- "net"
- "strconv"
- "time"
-)
-
-var noDeadline = time.Time{}
-
-type Conn struct {
- netConn net.Conn
-
- Reader *bufio.Reader
- readBuf []byte
- Columns [][]byte
-
- Writer *WriteBuffer
-
- InitedAt time.Time
- UsedAt time.Time
-
- ProcessId int32
- SecretKey int32
-
- _lastId int64
-}
-
-func NewConn(netConn net.Conn) *Conn {
- cn := &Conn{
- Reader: bufio.NewReader(netConn),
- readBuf: make([]byte, 0, 512),
-
- Writer: NewWriteBuffer(),
-
- UsedAt: time.Now(),
- }
- cn.SetNetConn(netConn)
- return cn
-}
-
-func (cn *Conn) RemoteAddr() net.Addr {
- return cn.netConn.RemoteAddr()
-}
-
-func (cn *Conn) SetNetConn(netConn net.Conn) {
- cn.netConn = netConn
- cn.Reader.Reset(netConn)
-}
-
-func (cn *Conn) NetConn() net.Conn {
- return cn.netConn
-}
-
-func (cn *Conn) NextId() string {
- cn._lastId++
- return strconv.FormatInt(cn._lastId, 10)
-}
-
-func (cn *Conn) SetTimeout(rt, wt time.Duration) {
- cn.UsedAt = time.Now()
- if rt > 0 {
- cn.netConn.SetReadDeadline(cn.UsedAt.Add(rt))
- } else {
- cn.netConn.SetReadDeadline(noDeadline)
- }
- if wt > 0 {
- cn.netConn.SetWriteDeadline(cn.UsedAt.Add(wt))
- } else {
- cn.netConn.SetWriteDeadline(noDeadline)
- }
-}
-
-func (cn *Conn) ReadN(n int) ([]byte, error) {
- if d := n - cap(cn.readBuf); d > 0 {
- cn.readBuf = cn.readBuf[:cap(cn.readBuf)]
- cn.readBuf = append(cn.readBuf, make([]byte, d)...)
- } else {
- cn.readBuf = cn.readBuf[:n]
- }
- _, err := io.ReadFull(cn.Reader, cn.readBuf)
- return cn.readBuf, err
-}
-
-func (cn *Conn) FlushWriter() error {
- _, err := cn.netConn.Write(cn.Writer.Bytes)
- cn.Writer.Reset()
- return err
-}
-
-func (cn *Conn) Close() error {
- return cn.netConn.Close()
-}
-
-func (cn *Conn) CheckHealth() error {
- if cn.Reader.Buffered() != 0 {
- b, _ := cn.Reader.Peek(cn.Reader.Buffered())
- err := fmt.Errorf("connection has unread data:\n%s", hex.Dump(b))
- return err
- }
- return nil
-}
diff --git a/vendor/github.com/go-pg/pg/internal/pool/main_test.go b/vendor/github.com/go-pg/pg/internal/pool/main_test.go
deleted file mode 100644
index 43afe3f..0000000
--- a/vendor/github.com/go-pg/pg/internal/pool/main_test.go
+++ /dev/null
@@ -1,35 +0,0 @@
-package pool_test
-
-import (
- "net"
- "sync"
- "testing"
-
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-)
-
-func TestGinkgoSuite(t *testing.T) {
- RegisterFailHandler(Fail)
- RunSpecs(t, "pool")
-}
-
-func perform(n int, cbs ...func(int)) {
- var wg sync.WaitGroup
- for _, cb := range cbs {
- for i := 0; i < n; i++ {
- wg.Add(1)
- go func(cb func(int), i int) {
- defer GinkgoRecover()
- defer wg.Done()
-
- cb(i)
- }(cb, i)
- }
- }
- wg.Wait()
-}
-
-func dummyDialer() (net.Conn, error) {
- return &net.TCPConn{}, nil
-}
diff --git a/vendor/github.com/go-pg/pg/internal/pool/pool.go b/vendor/github.com/go-pg/pg/internal/pool/pool.go
deleted file mode 100644
index ac67886..0000000
--- a/vendor/github.com/go-pg/pg/internal/pool/pool.go
+++ /dev/null
@@ -1,384 +0,0 @@
-package pool
-
-import (
- "errors"
- "net"
- "sync"
- "sync/atomic"
- "time"
-
- "github.com/go-pg/pg/internal"
-)
-
-var ErrClosed = errors.New("pg: database is closed")
-var ErrPoolTimeout = errors.New("pg: connection pool timeout")
-
-var timers = sync.Pool{
- New: func() interface{} {
- t := time.NewTimer(time.Hour)
- t.Stop()
- return t
- },
-}
-
-// Stats contains pool state information and accumulated stats.
-type Stats struct {
- Hits uint32 // number of times free connection was found in the pool
- Misses uint32 // number of times free connection was NOT found in the pool
- Timeouts uint32 // number of times a wait timeout occurred
-
- TotalConns uint32 // number of total connections in the pool
- FreeConns uint32 // number of free connections in the pool
- StaleConns uint32 // number of stale connections removed from the pool
-}
-
-type Pooler interface {
- NewConn() (*Conn, error)
- CloseConn(*Conn) error
-
- Get() (*Conn, bool, error)
- Put(*Conn) error
- Remove(*Conn) error
-
- Len() int
- FreeLen() int
- Stats() *Stats
-
- Close() error
-}
-
-type Options struct {
- Dialer func() (net.Conn, error)
- OnClose func(*Conn) error
-
- PoolSize int
- PoolTimeout time.Duration
- IdleTimeout time.Duration
- IdleCheckFrequency time.Duration
- MaxAge time.Duration
-}
-
-type ConnPool struct {
- opt *Options
-
- dialErrorsNum uint32 // atomic
-
- lastDialErrorMu sync.RWMutex
- lastDialError error
-
- queue chan struct{}
-
- connsMu sync.Mutex
- conns []*Conn
-
- freeConnsMu sync.Mutex
- freeConns []*Conn
-
- stats Stats
-
- _closed uint32 // atomic
-}
-
-var _ Pooler = (*ConnPool)(nil)
-
-func NewConnPool(opt *Options) *ConnPool {
- p := &ConnPool{
- opt: opt,
-
- queue: make(chan struct{}, opt.PoolSize),
- conns: make([]*Conn, 0, opt.PoolSize),
- freeConns: make([]*Conn, 0, opt.PoolSize),
- }
-
- if opt.IdleTimeout > 0 && opt.IdleCheckFrequency > 0 {
- go p.reaper(opt.IdleCheckFrequency)
- }
-
- return p
-}
-
-func (p *ConnPool) NewConn() (*Conn, error) {
- if p.closed() {
- return nil, ErrClosed
- }
-
- if atomic.LoadUint32(&p.dialErrorsNum) >= uint32(p.opt.PoolSize) {
- return nil, p.getLastDialError()
- }
-
- netConn, err := p.opt.Dialer()
- if err != nil {
- p.setLastDialError(err)
- if atomic.AddUint32(&p.dialErrorsNum, 1) == uint32(p.opt.PoolSize) {
- go p.tryDial()
- }
- return nil, err
- }
- atomic.StoreUint32(&p.dialErrorsNum, 0)
-
- cn := NewConn(netConn)
- p.connsMu.Lock()
- p.conns = append(p.conns, cn)
- p.connsMu.Unlock()
-
- return cn, nil
-}
-
-func (p *ConnPool) tryDial() {
- for {
- if p.closed() {
- return
- }
-
- conn, err := p.opt.Dialer()
- if err != nil {
- p.setLastDialError(err)
- time.Sleep(time.Second)
- continue
- }
-
- atomic.StoreUint32(&p.dialErrorsNum, 0)
- _ = conn.Close()
- return
- }
-}
-
-func (p *ConnPool) setLastDialError(err error) {
- p.lastDialErrorMu.Lock()
- p.lastDialError = err
- p.lastDialErrorMu.Unlock()
-}
-
-func (p *ConnPool) getLastDialError() error {
- p.lastDialErrorMu.RLock()
- err := p.lastDialError
- p.lastDialErrorMu.RUnlock()
- return err
-}
-
-func (p *ConnPool) isStaleConn(cn *Conn) bool {
- if p.opt.IdleTimeout == 0 && p.opt.MaxAge == 0 {
- return false
- }
-
- now := time.Now()
- if p.opt.IdleTimeout > 0 && now.Sub(cn.UsedAt) >= p.opt.IdleTimeout {
- return true
- }
- if p.opt.MaxAge > 0 && now.Sub(cn.InitedAt) >= p.opt.MaxAge {
- return true
- }
-
- return false
-}
-
-func (p *ConnPool) popFree() *Conn {
- if len(p.freeConns) == 0 {
- return nil
- }
-
- idx := len(p.freeConns) - 1
- cn := p.freeConns[idx]
- p.freeConns = p.freeConns[:idx]
- return cn
-}
-
-// Get returns existed connection from the pool or creates a new one.
-func (p *ConnPool) Get() (*Conn, bool, error) {
- if p.closed() {
- return nil, false, ErrClosed
- }
-
- select {
- case p.queue <- struct{}{}:
- default:
- timer := timers.Get().(*time.Timer)
- timer.Reset(p.opt.PoolTimeout)
-
- select {
- case p.queue <- struct{}{}:
- if !timer.Stop() {
- <-timer.C
- }
- timers.Put(timer)
- case <-timer.C:
- timers.Put(timer)
- atomic.AddUint32(&p.stats.Timeouts, 1)
- return nil, false, ErrPoolTimeout
- }
- }
-
- for {
- p.freeConnsMu.Lock()
- cn := p.popFree()
- p.freeConnsMu.Unlock()
-
- if cn == nil {
- break
- }
-
- if p.isStaleConn(cn) {
- p.CloseConn(cn)
- continue
- }
-
- atomic.AddUint32(&p.stats.Hits, 1)
- return cn, false, nil
- }
-
- atomic.AddUint32(&p.stats.Misses, 1)
-
- newcn, err := p.NewConn()
- if err != nil {
- <-p.queue
- return nil, false, err
- }
-
- return newcn, true, nil
-}
-
-func (p *ConnPool) Put(cn *Conn) error {
- if e := cn.CheckHealth(); e != nil {
- internal.Logf(e.Error())
- return p.Remove(cn)
- }
- p.freeConnsMu.Lock()
- p.freeConns = append(p.freeConns, cn)
- p.freeConnsMu.Unlock()
- <-p.queue
- return nil
-}
-
-func (p *ConnPool) Remove(cn *Conn) error {
- _ = p.CloseConn(cn)
- <-p.queue
- return nil
-}
-
-func (p *ConnPool) CloseConn(cn *Conn) error {
- p.connsMu.Lock()
- for i, c := range p.conns {
- if c == cn {
- p.conns = append(p.conns[:i], p.conns[i+1:]...)
- break
- }
- }
- p.connsMu.Unlock()
-
- return p.closeConn(cn)
-}
-
-func (p *ConnPool) closeConn(cn *Conn) error {
- if p.opt.OnClose != nil {
- _ = p.opt.OnClose(cn)
- }
- return cn.Close()
-}
-
-// Len returns total number of connections.
-func (p *ConnPool) Len() int {
- p.connsMu.Lock()
- l := len(p.conns)
- p.connsMu.Unlock()
- return l
-}
-
-// FreeLen returns number of free connections.
-func (p *ConnPool) FreeLen() int {
- p.freeConnsMu.Lock()
- l := len(p.freeConns)
- p.freeConnsMu.Unlock()
- return l
-}
-
-func (p *ConnPool) Stats() *Stats {
- return &Stats{
- Hits: atomic.LoadUint32(&p.stats.Hits),
- Misses: atomic.LoadUint32(&p.stats.Misses),
- Timeouts: atomic.LoadUint32(&p.stats.Timeouts),
- TotalConns: uint32(p.Len()),
- FreeConns: uint32(p.FreeLen()),
- }
-}
-
-func (p *ConnPool) closed() bool {
- return atomic.LoadUint32(&p._closed) == 1
-}
-
-func (p *ConnPool) Close() error {
- if !atomic.CompareAndSwapUint32(&p._closed, 0, 1) {
- return ErrClosed
- }
-
- p.connsMu.Lock()
- var firstErr error
- for _, cn := range p.conns {
- if cn == nil {
- continue
- }
- if err := p.closeConn(cn); err != nil && firstErr == nil {
- firstErr = err
- }
- }
- p.conns = nil
- p.connsMu.Unlock()
-
- p.freeConnsMu.Lock()
- p.freeConns = nil
- p.freeConnsMu.Unlock()
-
- return firstErr
-}
-
-func (p *ConnPool) reapStaleConn() bool {
- if len(p.freeConns) == 0 {
- return false
- }
-
- cn := p.freeConns[0]
- if !p.isStaleConn(cn) {
- return false
- }
-
- _ = p.CloseConn(cn)
- p.freeConns = append(p.freeConns[:0], p.freeConns[1:]...)
-
- return true
-}
-
-func (p *ConnPool) ReapStaleConns() (int, error) {
- var n int
- for {
- p.queue <- struct{}{}
- p.freeConnsMu.Lock()
-
- reaped := p.reapStaleConn()
-
- p.freeConnsMu.Unlock()
- <-p.queue
-
- if reaped {
- n++
- } else {
- break
- }
- }
- return n, nil
-}
-
-func (p *ConnPool) reaper(frequency time.Duration) {
- ticker := time.NewTicker(frequency)
- defer ticker.Stop()
-
- for _ = range ticker.C {
- if p.closed() {
- break
- }
- n, err := p.ReapStaleConns()
- if err != nil {
- internal.Logf("ReapStaleConns failed: %s", err)
- continue
- }
- atomic.AddUint32(&p.stats.StaleConns, uint32(n))
- }
-}
diff --git a/vendor/github.com/go-pg/pg/internal/pool/pool_single.go b/vendor/github.com/go-pg/pg/internal/pool/pool_single.go
deleted file mode 100644
index ff91279..0000000
--- a/vendor/github.com/go-pg/pg/internal/pool/pool_single.go
+++ /dev/null
@@ -1,55 +0,0 @@
-package pool
-
-type SingleConnPool struct {
- cn *Conn
-}
-
-var _ Pooler = (*SingleConnPool)(nil)
-
-func NewSingleConnPool(cn *Conn) *SingleConnPool {
- return &SingleConnPool{
- cn: cn,
- }
-}
-
-func (p *SingleConnPool) NewConn() (*Conn, error) {
- panic("not implemented")
-}
-
-func (p *SingleConnPool) CloseConn(*Conn) error {
- panic("not implemented")
-}
-
-func (p *SingleConnPool) Get() (*Conn, bool, error) {
- return p.cn, false, nil
-}
-
-func (p *SingleConnPool) Put(cn *Conn) error {
- if p.cn != cn {
- panic("p.cn != cn")
- }
- return nil
-}
-
-func (p *SingleConnPool) Remove(cn *Conn) error {
- if p.cn != cn {
- panic("p.cn != cn")
- }
- return nil
-}
-
-func (p *SingleConnPool) Len() int {
- return 1
-}
-
-func (p *SingleConnPool) FreeLen() int {
- return 0
-}
-
-func (p *SingleConnPool) Stats() *Stats {
- return nil
-}
-
-func (p *SingleConnPool) Close() error {
- return nil
-}
diff --git a/vendor/github.com/go-pg/pg/internal/pool/pool_test.go b/vendor/github.com/go-pg/pg/internal/pool/pool_test.go
deleted file mode 100644
index af686e0..0000000
--- a/vendor/github.com/go-pg/pg/internal/pool/pool_test.go
+++ /dev/null
@@ -1,255 +0,0 @@
-package pool_test
-
-import (
- "testing"
- "time"
-
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-
- "github.com/go-pg/pg/internal/pool"
-)
-
-var _ = Describe("ConnPool", func() {
- var connPool *pool.ConnPool
-
- BeforeEach(func() {
- connPool = pool.NewConnPool(&pool.Options{
- Dialer: dummyDialer,
- PoolSize: 10,
- PoolTimeout: time.Hour,
- IdleTimeout: time.Millisecond,
- IdleCheckFrequency: time.Millisecond,
- })
- })
-
- AfterEach(func() {
- connPool.Close()
- })
-
- It("should unblock client when conn is removed", func() {
- // Reserve one connection.
- cn, _, err := connPool.Get()
- Expect(err).NotTo(HaveOccurred())
-
- // Reserve all other connections.
- var cns []*pool.Conn
- for i := 0; i < 9; i++ {
- cn, _, err := connPool.Get()
- Expect(err).NotTo(HaveOccurred())
- cns = append(cns, cn)
- }
-
- started := make(chan bool, 1)
- done := make(chan bool, 1)
- go func() {
- defer GinkgoRecover()
-
- started <- true
- _, _, err := connPool.Get()
- Expect(err).NotTo(HaveOccurred())
- done <- true
-
- err = connPool.Put(cn)
- Expect(err).NotTo(HaveOccurred())
- }()
- <-started
-
- // Check that Get is blocked.
- select {
- case <-done:
- Fail("Get is not blocked")
- default:
- // ok
- }
-
- err = connPool.Remove(cn)
- Expect(err).NotTo(HaveOccurred())
-
- // Check that Ping is unblocked.
- select {
- case <-done:
- // ok
- case <-time.After(time.Second):
- Fail("Get is not unblocked")
- }
-
- for _, cn := range cns {
- err = connPool.Put(cn)
- Expect(err).NotTo(HaveOccurred())
- }
- })
-})
-
-var _ = Describe("conns reaper", func() {
- const idleTimeout = time.Minute
- const maxAge = time.Hour
-
- var connPool *pool.ConnPool
- var conns, staleConns, closedConns []*pool.Conn
-
- assert := func(typ string) {
- BeforeEach(func() {
- closedConns = nil
- connPool = pool.NewConnPool(&pool.Options{
- Dialer: dummyDialer,
- PoolSize: 10,
- PoolTimeout: time.Second,
- IdleTimeout: idleTimeout,
- MaxAge: maxAge,
- IdleCheckFrequency: time.Hour,
- OnClose: func(cn *pool.Conn) error {
- closedConns = append(closedConns, cn)
- return nil
- },
- })
-
- conns = nil
-
- // add stale connections
- staleConns = nil
- for i := 0; i < 3; i++ {
- cn, _, err := connPool.Get()
- Expect(err).NotTo(HaveOccurred())
- switch typ {
- case "idle":
- cn.UsedAt = time.Now().Add(-2 * idleTimeout)
- case "aged":
- cn.InitedAt = time.Now().Add(-2 * maxAge)
- }
- conns = append(conns, cn)
- staleConns = append(staleConns, cn)
- }
-
- // add fresh connections
- for i := 0; i < 3; i++ {
- cn, _, err := connPool.Get()
- Expect(err).NotTo(HaveOccurred())
- conns = append(conns, cn)
- }
-
- for _, cn := range conns {
- if cn.InitedAt.IsZero() {
- cn.InitedAt = time.Now()
- }
- Expect(connPool.Put(cn)).NotTo(HaveOccurred())
- }
-
- Expect(connPool.Len()).To(Equal(6))
- Expect(connPool.FreeLen()).To(Equal(6))
-
- n, err := connPool.ReapStaleConns()
- Expect(err).NotTo(HaveOccurred())
- Expect(n).To(Equal(3))
- })
-
- AfterEach(func() {
- _ = connPool.Close()
- Expect(connPool.Len()).To(Equal(0))
- Expect(connPool.FreeLen()).To(Equal(0))
- Expect(len(closedConns)).To(Equal(len(conns)))
- Expect(closedConns).To(ConsistOf(conns))
- })
-
- It("reaps stale connections", func() {
- Expect(connPool.Len()).To(Equal(3))
- Expect(connPool.FreeLen()).To(Equal(3))
- })
-
- It("does not reap fresh connections", func() {
- n, err := connPool.ReapStaleConns()
- Expect(err).NotTo(HaveOccurred())
- Expect(n).To(Equal(0))
- })
-
- It("stale connections are closed", func() {
- Expect(len(closedConns)).To(Equal(len(staleConns)))
- Expect(closedConns).To(ConsistOf(staleConns))
- })
-
- It("pool is functional", func() {
- for j := 0; j < 3; j++ {
- var freeCns []*pool.Conn
- for i := 0; i < 3; i++ {
- cn, _, err := connPool.Get()
- Expect(err).NotTo(HaveOccurred())
- Expect(cn).NotTo(BeNil())
- freeCns = append(freeCns, cn)
- }
-
- Expect(connPool.Len()).To(Equal(3))
- Expect(connPool.FreeLen()).To(Equal(0))
-
- cn, _, err := connPool.Get()
- Expect(err).NotTo(HaveOccurred())
- Expect(cn).NotTo(BeNil())
- conns = append(conns, cn)
-
- Expect(connPool.Len()).To(Equal(4))
- Expect(connPool.FreeLen()).To(Equal(0))
-
- err = connPool.Remove(cn)
- Expect(err).NotTo(HaveOccurred())
-
- Expect(connPool.Len()).To(Equal(3))
- Expect(connPool.FreeLen()).To(Equal(0))
-
- for _, cn := range freeCns {
- err := connPool.Put(cn)
- Expect(err).NotTo(HaveOccurred())
- }
-
- Expect(connPool.Len()).To(Equal(3))
- Expect(connPool.FreeLen()).To(Equal(3))
- }
- })
- }
-
- assert("idle")
- assert("aged")
-})
-
-var _ = Describe("race", func() {
- var connPool *pool.ConnPool
- var C, N int
-
- BeforeEach(func() {
- C, N = 10, 1000
- if testing.Short() {
- C = 4
- N = 100
- }
- })
-
- AfterEach(func() {
- connPool.Close()
- })
-
- It("does not happen on Get, Put, and Remove", func() {
- connPool = pool.NewConnPool(&pool.Options{
- Dialer: dummyDialer,
- PoolSize: 10,
- PoolTimeout: time.Minute,
- IdleTimeout: time.Millisecond,
- IdleCheckFrequency: time.Millisecond,
- })
-
- perform(C, func(id int) {
- for i := 0; i < N; i++ {
- cn, _, err := connPool.Get()
- Expect(err).NotTo(HaveOccurred())
- if err == nil {
- Expect(connPool.Put(cn)).NotTo(HaveOccurred())
- }
- }
- }, func(id int) {
- for i := 0; i < N; i++ {
- cn, _, err := connPool.Get()
- Expect(err).NotTo(HaveOccurred())
- if err == nil {
- Expect(connPool.Remove(cn)).NotTo(HaveOccurred())
- }
- }
- })
- })
-})
diff --git a/vendor/github.com/go-pg/pg/internal/pool/write_buffer.go b/vendor/github.com/go-pg/pg/internal/pool/write_buffer.go
deleted file mode 100644
index f9ba997..0000000
--- a/vendor/github.com/go-pg/pg/internal/pool/write_buffer.go
+++ /dev/null
@@ -1,90 +0,0 @@
-package pool
-
-import (
- "encoding/binary"
- "io"
-)
-
-type WriteBuffer struct {
- Bytes []byte
-
- msgStart, paramStart int
-}
-
-func NewWriteBuffer() *WriteBuffer {
- return &WriteBuffer{
- Bytes: make([]byte, 0, 4096),
- }
-}
-
-func (buf *WriteBuffer) StartMessage(c byte) {
- if c == 0 {
- buf.msgStart = len(buf.Bytes)
- buf.Bytes = append(buf.Bytes, 0, 0, 0, 0)
- } else {
- buf.msgStart = len(buf.Bytes) + 1
- buf.Bytes = append(buf.Bytes, c, 0, 0, 0, 0)
- }
-}
-
-func (buf *WriteBuffer) FinishMessage() {
- binary.BigEndian.PutUint32(
- buf.Bytes[buf.msgStart:], uint32(len(buf.Bytes)-buf.msgStart))
-}
-
-func (buf *WriteBuffer) StartParam() {
- buf.paramStart = len(buf.Bytes)
- buf.Bytes = append(buf.Bytes, 0, 0, 0, 0)
-}
-
-func (buf *WriteBuffer) FinishParam() {
- binary.BigEndian.PutUint32(
- buf.Bytes[buf.paramStart:], uint32(len(buf.Bytes)-buf.paramStart-4))
-}
-
-var nullParamLength = int32(-1)
-
-func (buf *WriteBuffer) FinishNullParam() {
- binary.BigEndian.PutUint32(
- buf.Bytes[buf.paramStart:], uint32(nullParamLength))
-}
-
-func (buf *WriteBuffer) Write(b []byte) (int, error) {
- buf.Bytes = append(buf.Bytes, b...)
- return len(b), nil
-}
-
-func (buf *WriteBuffer) WriteInt16(num int16) {
- buf.Bytes = append(buf.Bytes, 0, 0)
- binary.BigEndian.PutUint16(buf.Bytes[len(buf.Bytes)-2:], uint16(num))
-}
-
-func (buf *WriteBuffer) WriteInt32(num int32) {
- buf.Bytes = append(buf.Bytes, 0, 0, 0, 0)
- binary.BigEndian.PutUint32(buf.Bytes[len(buf.Bytes)-4:], uint32(num))
-}
-
-func (buf *WriteBuffer) WriteString(s string) {
- buf.Bytes = append(buf.Bytes, s...)
- buf.Bytes = append(buf.Bytes, 0)
-}
-
-func (buf *WriteBuffer) WriteBytes(b []byte) {
- buf.Bytes = append(buf.Bytes, b...)
- buf.Bytes = append(buf.Bytes, 0)
-}
-
-func (buf *WriteBuffer) WriteByte(c byte) error {
- buf.Bytes = append(buf.Bytes, c)
- return nil
-}
-
-func (buf *WriteBuffer) Reset() {
- buf.Bytes = buf.Bytes[:0]
-}
-
-func (buf *WriteBuffer) ReadFrom(r io.Reader) (int64, error) {
- n, err := r.Read(buf.Bytes[len(buf.Bytes):cap(buf.Bytes)])
- buf.Bytes = buf.Bytes[:len(buf.Bytes)+int(n)]
- return int64(n), err
-}
diff --git a/vendor/github.com/go-pg/pg/internal/safe.go b/vendor/github.com/go-pg/pg/internal/safe.go
deleted file mode 100644
index 870fe54..0000000
--- a/vendor/github.com/go-pg/pg/internal/safe.go
+++ /dev/null
@@ -1,11 +0,0 @@
-// +build appengine
-
-package internal
-
-func BytesToString(b []byte) string {
- return string(b)
-}
-
-func StringToBytes(s string) []byte {
- return []byte(s)
-}
diff --git a/vendor/github.com/go-pg/pg/internal/underscore.go b/vendor/github.com/go-pg/pg/internal/underscore.go
deleted file mode 100644
index 4df2681..0000000
--- a/vendor/github.com/go-pg/pg/internal/underscore.go
+++ /dev/null
@@ -1,73 +0,0 @@
-package internal
-
-func isUpper(c byte) bool {
- return c >= 'A' && c <= 'Z'
-}
-
-func isLower(c byte) bool {
- return !isUpper(c)
-}
-
-func toUpper(c byte) byte {
- return c - 32
-}
-
-func toLower(c byte) byte {
- return c + 32
-}
-
-// Underscore converts "CamelCasedString" to "camel_cased_string".
-func Underscore(s string) string {
- r := make([]byte, 0, len(s))
- for i := 0; i < len(s); i++ {
- c := s[i]
- if isUpper(c) {
- if i > 0 && i+1 < len(s) && (isLower(s[i-1]) || isLower(s[i+1])) {
- r = append(r, '_', toLower(c))
- } else {
- r = append(r, toLower(c))
- }
- } else {
- r = append(r, c)
- }
- }
- return string(r)
-}
-
-func ToUpper(s string) string {
- if isUpperString(s) {
- return s
- }
-
- b := make([]byte, len(s))
- for i := range b {
- c := s[i]
- if c >= 'a' && c <= 'z' {
- c -= 'a' - 'A'
- }
- b[i] = c
- }
- return string(b)
-}
-
-func isUpperString(s string) bool {
- for i := 0; i < len(s); i++ {
- c := s[i]
- if c >= 'a' && c <= 'z' {
- return false
- }
- }
- return true
-}
-
-func ToExported(s string) string {
- if len(s) == 0 {
- return s
- }
- if c := s[0]; isLower(c) {
- b := []byte(s)
- b[0] = toUpper(c)
- return string(b)
- }
- return s
-}
diff --git a/vendor/github.com/go-pg/pg/internal/underscore_test.go b/vendor/github.com/go-pg/pg/internal/underscore_test.go
deleted file mode 100644
index 99fbf39..0000000
--- a/vendor/github.com/go-pg/pg/internal/underscore_test.go
+++ /dev/null
@@ -1,23 +0,0 @@
-package internal_test
-
-import (
- "testing"
-
- "github.com/go-pg/pg/internal"
-)
-
-func TestUnderscore(t *testing.T) {
- tests := []struct {
- s, wanted string
- }{
- {"Megacolumn", "megacolumn"},
- {"MegaColumn", "mega_column"},
- {"MegaColumn_Id", "mega_column__id"},
- {"MegaColumn_id", "mega_column_id"},
- }
- for _, v := range tests {
- if got := internal.Underscore(v.s); got != v.wanted {
- t.Errorf("got %q, wanted %q", got, v.wanted)
- }
- }
-}
diff --git a/vendor/github.com/go-pg/pg/internal/unsafe.go b/vendor/github.com/go-pg/pg/internal/unsafe.go
deleted file mode 100644
index c18b25c..0000000
--- a/vendor/github.com/go-pg/pg/internal/unsafe.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// +build !appengine
-
-package internal
-
-import (
- "reflect"
- "unsafe"
-)
-
-func BytesToString(b []byte) string {
- bytesHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b))
- strHeader := reflect.StringHeader{
- Data: bytesHeader.Data,
- Len: bytesHeader.Len,
- }
- return *(*string)(unsafe.Pointer(&strHeader))
-}
-
-func StringToBytes(s string) []byte {
- sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
- bh := reflect.SliceHeader{
- Data: sh.Data,
- Len: sh.Len,
- Cap: sh.Len,
- }
- return *(*[]byte)(unsafe.Pointer(&bh))
-}
diff --git a/vendor/github.com/go-pg/pg/internal/util.go b/vendor/github.com/go-pg/pg/internal/util.go
deleted file mode 100644
index 67393d8..0000000
--- a/vendor/github.com/go-pg/pg/internal/util.go
+++ /dev/null
@@ -1,21 +0,0 @@
-package internal
-
-import "reflect"
-
-func SliceNextElem(v reflect.Value) reflect.Value {
- if v.Len() < v.Cap() {
- v.Set(v.Slice(0, v.Len()+1))
- return v.Index(v.Len() - 1)
- }
-
- elemType := v.Type().Elem()
-
- if elemType.Kind() == reflect.Ptr {
- elem := reflect.New(elemType.Elem())
- v.Set(reflect.Append(v, elem))
- return elem.Elem()
- }
-
- v.Set(reflect.Append(v, reflect.Zero(elemType)))
- return v.Index(v.Len() - 1)
-}
diff --git a/vendor/github.com/go-pg/pg/listener.go b/vendor/github.com/go-pg/pg/listener.go
deleted file mode 100644
index a2acdac..0000000
--- a/vendor/github.com/go-pg/pg/listener.go
+++ /dev/null
@@ -1,221 +0,0 @@
-package pg
-
-import (
- "errors"
- "sync"
- "time"
-
- "github.com/go-pg/pg/internal"
- "github.com/go-pg/pg/internal/pool"
- "github.com/go-pg/pg/types"
-)
-
-var errListenerClosed = errors.New("pg: listener is closed")
-
-// A notification received with LISTEN command.
-type Notification struct {
- Channel string
- Payload string
-}
-
-// Listener listens for notifications sent with NOTIFY command.
-// It's NOT safe for concurrent use by multiple goroutines
-// except the Channel API.
-type Listener struct {
- db *DB
-
- channels []string
-
- mu sync.Mutex
- cn *pool.Conn
- closed bool
-}
-
-func (ln *Listener) conn(readTimeout time.Duration) (*pool.Conn, error) {
- ln.mu.Lock()
- cn, err := ln._conn(readTimeout)
- ln.mu.Unlock()
- if err != nil {
- if err == pool.ErrClosed {
- _ = ln.Close()
- return nil, errListenerClosed
- }
- return nil, err
- }
-
- cn.SetTimeout(readTimeout, ln.db.opt.WriteTimeout)
- return cn, nil
-}
-
-func (ln *Listener) _conn(readTimeout time.Duration) (*pool.Conn, error) {
- if ln.closed {
- return nil, errListenerClosed
- }
-
- if ln.cn != nil {
- return ln.cn, nil
- }
-
- cn, err := ln.db.pool.NewConn()
- if err != nil {
- return nil, err
- }
-
- if cn.InitedAt.IsZero() {
- if err := ln.db.initConn(cn); err != nil {
- _ = ln.db.pool.CloseConn(cn)
- return nil, err
- }
- cn.InitedAt = time.Now()
- }
-
- if len(ln.channels) > 0 {
- if err := ln.listen(cn, ln.channels...); err != nil {
- _ = ln.db.pool.CloseConn(cn)
- return nil, err
- }
- }
-
- ln.cn = cn
- return cn, nil
-}
-
-func (ln *Listener) freeConn(cn *pool.Conn, err error) {
- if !isBadConn(err, true) {
- return
- }
-
- ln.mu.Lock()
- if cn == ln.cn {
- _ = ln.closeConn(err)
- }
- ln.mu.Unlock()
-}
-
-func (ln *Listener) closeConn(reason error) error {
- if !ln.closed {
- internal.Logf("pg: discarding bad listener connection: %s", reason)
- }
-
- err := ln.db.pool.CloseConn(ln.cn)
- ln.cn = nil
- return err
-}
-
-// Close closes the listener, releasing any open resources.
-func (ln *Listener) Close() error {
- ln.mu.Lock()
- defer ln.mu.Unlock()
-
- if ln.closed {
- return errListenerClosed
- }
- ln.closed = true
- if ln.cn != nil {
- return ln.closeConn(errListenerClosed)
- }
- return nil
-}
-
-// Channel returns a channel for concurrently receiving notifications.
-// The channel is closed with Listener.
-func (ln *Listener) Channel() <-chan *Notification {
- ch := make(chan *Notification, 100)
- go func() {
- for {
- channel, payload, err := ln.ReceiveTimeout(5 * time.Second)
- if err != nil {
- if err == errListenerClosed {
- break
- }
- continue
- }
- ch <- &Notification{channel, payload}
- }
- close(ch)
- }()
- return ch
-}
-
-// Listen starts listening for notifications on channels.
-func (ln *Listener) Listen(channels ...string) error {
- cn, err := ln.conn(ln.db.opt.ReadTimeout)
- if err != nil {
- return err
- }
-
- if err := ln.listen(cn, channels...); err != nil {
- if err != nil {
- ln.freeConn(cn, err)
- }
- return err
- }
-
- ln.channels = appendIfNotExists(ln.channels, channels...)
- return nil
-}
-
-func (ln *Listener) listen(cn *pool.Conn, channels ...string) error {
- for _, channel := range channels {
- if err := writeQueryMsg(cn.Writer, ln.db, "LISTEN ?", pgChan(channel)); err != nil {
- return err
- }
- }
- return cn.FlushWriter()
-}
-
-// Receive indefinitely waits for a notification.
-func (ln *Listener) Receive() (channel string, payload string, err error) {
- return ln.ReceiveTimeout(0)
-}
-
-// ReceiveTimeout waits for a notification until timeout is reached.
-func (ln *Listener) ReceiveTimeout(timeout time.Duration) (channel, payload string, err error) {
- cn, err := ln.conn(timeout)
- if err != nil {
- return "", "", err
- }
-
- channel, payload, err = readNotification(cn)
- if err != nil {
- ln.freeConn(cn, err)
- return "", "", err
- }
-
- return channel, payload, nil
-}
-
-func appendIfNotExists(ss []string, es ...string) []string {
-loop:
- for _, e := range es {
- for _, s := range ss {
- if s == e {
- continue loop
- }
- }
- ss = append(ss, e)
- }
- return ss
-}
-
-type pgChan string
-
-var _ types.ValueAppender = pgChan("")
-
-func (ch pgChan) AppendValue(b []byte, quote int) ([]byte, error) {
- if quote == 0 {
- return append(b, ch...), nil
- }
-
- b = append(b, '"')
- for _, c := range []byte(ch) {
- if c == '"' {
- b = append(b, '"', '"')
- } else {
- b = append(b, c)
- }
- }
- b = append(b, '"')
-
- return b, nil
-}
diff --git a/vendor/github.com/go-pg/pg/listener_test.go b/vendor/github.com/go-pg/pg/listener_test.go
deleted file mode 100644
index 9ab2daa..0000000
--- a/vendor/github.com/go-pg/pg/listener_test.go
+++ /dev/null
@@ -1,189 +0,0 @@
-package pg_test
-
-import (
- "net"
- "time"
-
- "github.com/go-pg/pg"
-
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-)
-
-var _ = Context("Listener", func() {
- var db *pg.DB
- var ln *pg.Listener
-
- BeforeEach(func() {
- opt := pgOptions()
- opt.PoolSize = 2
- opt.PoolTimeout = time.Second
-
- db = pg.Connect(opt)
-
- ln = db.Listen("test.channel")
- })
-
- var _ = AfterEach(func() {
- _ = ln.Close()
-
- _ = db.Close()
- })
-
- It("reuses connection", func() {
- for i := 0; i < 100; i++ {
- _, _, err := ln.ReceiveTimeout(time.Nanosecond)
- Expect(err).To(HaveOccurred())
- Expect(err.Error()).To(MatchRegexp(".+ i/o timeout"))
- }
-
- st := db.PoolStats()
- Expect(st.Hits).To(Equal(uint32(0)))
- Expect(st.Misses).To(Equal(uint32(0)))
- Expect(st.Timeouts).To(Equal(uint32(0)))
- Expect(st.TotalConns).To(Equal(uint32(1)))
- Expect(st.FreeConns).To(Equal(uint32(0)))
- })
-
- It("listens for notifications", func() {
- wait := make(chan struct{}, 2)
- go func() {
- defer GinkgoRecover()
-
- wait <- struct{}{}
- channel, payload, err := ln.Receive()
- Expect(err).NotTo(HaveOccurred())
- Expect(channel).To(Equal("test.channel"))
- Expect(payload).To(Equal(""))
- wait <- struct{}{}
- }()
-
- select {
- case <-wait:
- // ok
- case <-time.After(3 * time.Second):
- Fail("timeout")
- }
-
- _, err := db.Exec(`NOTIFY "test.channel"`)
- Expect(err).NotTo(HaveOccurred())
-
- select {
- case <-wait:
- // ok
- case <-time.After(3 * time.Second):
- Fail("timeout")
- }
- })
-
- It("is closed when DB is closed", func() {
- wait := make(chan struct{}, 2)
-
- go func() {
- defer GinkgoRecover()
-
- wait <- struct{}{}
- _, _, err := ln.Receive()
-
- Expect(err.Error()).To(SatisfyAny(
- Equal("EOF"),
- MatchRegexp(`use of closed (file or )?network connection$`),
- ))
- wait <- struct{}{}
- }()
-
- select {
- case <-wait:
- // ok
- case <-time.After(time.Second):
- Fail("timeout")
- }
-
- select {
- case <-wait:
- Fail("Receive is not blocked")
- case <-time.After(time.Second):
- // ok
- }
-
- Expect(db.Close()).To(BeNil())
-
- select {
- case <-wait:
- // ok
- case <-time.After(3 * time.Second):
- Fail("Listener is not closed")
- }
-
- _, _, err := ln.Receive()
- Expect(err).To(MatchError("pg: listener is closed"))
-
- err = ln.Close()
- Expect(err).To(MatchError("pg: listener is closed"))
- })
-
- It("returns an error on timeout", func() {
- channel, payload, err := ln.ReceiveTimeout(time.Second)
- Expect(err.(net.Error).Timeout()).To(BeTrue())
- Expect(channel).To(Equal(""))
- Expect(payload).To(Equal(""))
- })
-
- It("reconnects on listen error", func() {
- cn := ln.CurrentConn()
- Expect(cn).NotTo(BeNil())
- cn.SetNetConn(&badConn{})
-
- err := ln.Listen("test_channel2")
- Expect(err).Should(MatchError("bad connection"))
-
- err = ln.Listen("test_channel2")
- Expect(err).NotTo(HaveOccurred())
- })
-
- It("reconnects on receive error", func() {
- cn := ln.CurrentConn()
- Expect(cn).NotTo(BeNil())
- cn.SetNetConn(&badConn{})
-
- _, _, err := ln.ReceiveTimeout(time.Second)
- Expect(err).Should(MatchError("bad connection"))
-
- _, _, err = ln.ReceiveTimeout(time.Second)
- Expect(err.(net.Error).Timeout()).To(BeTrue())
-
- wait := make(chan struct{}, 2)
- go func() {
- defer GinkgoRecover()
-
- wait <- struct{}{}
- _, _, err := ln.Receive()
- Expect(err).NotTo(HaveOccurred())
- wait <- struct{}{}
- }()
-
- select {
- case <-wait:
- // ok
- case <-time.After(3 * time.Second):
- Fail("timeout")
- }
-
- select {
- case <-wait:
- Fail("Receive is not blocked")
- case <-time.After(time.Second):
- // ok
- }
-
- _, err = db.Exec(`NOTIFY "test.channel"`)
- Expect(err).NotTo(HaveOccurred())
-
- select {
- case <-wait:
- // ok
- case <-time.After(3 * time.Second):
- Fail("timeout")
- }
- })
-})
diff --git a/vendor/github.com/go-pg/pg/loader_test.go b/vendor/github.com/go-pg/pg/loader_test.go
deleted file mode 100644
index 78540d9..0000000
--- a/vendor/github.com/go-pg/pg/loader_test.go
+++ /dev/null
@@ -1,180 +0,0 @@
-package pg_test
-
-import (
- "errors"
-
- "github.com/go-pg/pg"
- "github.com/go-pg/pg/orm"
-
- . "gopkg.in/check.v1"
-)
-
-type LoaderTest struct {
- db *pg.DB
-}
-
-var _ = Suite(&LoaderTest{})
-
-func (t *LoaderTest) SetUpTest(c *C) {
- t.db = pg.Connect(pgOptions())
-}
-
-func (t *LoaderTest) TearDownTest(c *C) {
- c.Assert(t.db.Close(), IsNil)
-}
-
-type numLoader struct {
- Num int
-}
-
-type embeddedLoader struct {
- *numLoader
- Num2 int
-}
-
-type multipleLoader struct {
- One struct {
- Num int
- }
- Num int
-}
-
-func (t *LoaderTest) TestQuery(c *C) {
- var dst numLoader
- _, err := t.db.Query(&dst, "SELECT 1 AS num")
- c.Assert(err, IsNil)
- c.Assert(dst.Num, Equals, 1)
-}
-
-func (t *LoaderTest) TestQueryNull(c *C) {
- var dst numLoader
- _, err := t.db.Query(&dst, "SELECT NULL AS num")
- c.Assert(err, IsNil)
- c.Assert(dst.Num, Equals, 0)
-}
-
-func (t *LoaderTest) TestQueryEmbeddedStruct(c *C) {
- src := &embeddedLoader{
- numLoader: &numLoader{
- Num: 1,
- },
- Num2: 2,
- }
- dst := &embeddedLoader{
- numLoader: &numLoader{},
- }
- _, err := t.db.QueryOne(dst, "SELECT ?num AS num, ?num2 as num2", src)
- c.Assert(err, IsNil)
- c.Assert(dst, DeepEquals, src)
-}
-
-func (t *LoaderTest) TestQueryNestedStructs(c *C) {
- src := &multipleLoader{}
- src.One.Num = 1
- src.Num = 2
- dst := &multipleLoader{}
- _, err := t.db.QueryOne(dst, `SELECT ?one__num AS one__num, ?num as num`, src)
- c.Assert(err, IsNil)
- c.Assert(dst, DeepEquals, src)
-}
-
-func (t *LoaderTest) TestQueryStmt(c *C) {
- stmt, err := t.db.Prepare("SELECT 1 AS num")
- c.Assert(err, IsNil)
- defer stmt.Close()
-
- dst := &numLoader{}
- _, err = stmt.Query(dst)
- c.Assert(err, IsNil)
- c.Assert(dst.Num, Equals, 1)
-}
-
-func (t *LoaderTest) TestQueryInts(c *C) {
- var ids pg.Ints
- _, err := t.db.Query(&ids, "SELECT s.num AS num FROM generate_series(0, 10) AS s(num)")
- c.Assert(err, IsNil)
- c.Assert(ids, DeepEquals, pg.Ints{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
-}
-
-func (t *LoaderTest) TestQueryInts2(c *C) {
- var ints pg.Ints
- _, err := t.db.Query(&ints, "SELECT * FROM generate_series(1, 1000000)")
- c.Assert(err, IsNil)
- c.Assert(ints, HasLen, 1000000)
-}
-
-func (t *LoaderTest) TestQueryStrings(c *C) {
- var strings pg.Strings
- _, err := t.db.Query(&strings, "SELECT 'hello'")
- c.Assert(err, IsNil)
- c.Assert(strings, DeepEquals, pg.Strings{"hello"})
-}
-
-type errLoader string
-
-var _ orm.Model = errLoader("")
-
-func (errLoader) Init() error {
- return nil
-}
-
-func (m errLoader) NewModel() orm.ColumnScanner {
- return m
-}
-
-func (errLoader) AddModel(_ orm.ColumnScanner) error {
- return nil
-}
-
-func (errLoader) AfterQuery(_ orm.DB) error {
- return nil
-}
-
-func (errLoader) AfterSelect(_ orm.DB) error {
- return nil
-}
-
-func (errLoader) BeforeInsert(_ orm.DB) error {
- return nil
-}
-
-func (errLoader) AfterInsert(_ orm.DB) error {
- return nil
-}
-
-func (errLoader) BeforeUpdate(_ orm.DB) error {
- return nil
-}
-
-func (errLoader) AfterUpdate(_ orm.DB) error {
- return nil
-}
-
-func (errLoader) BeforeDelete(_ orm.DB) error {
- return nil
-}
-
-func (errLoader) AfterDelete(_ orm.DB) error {
- return nil
-}
-
-func (m errLoader) ScanColumn(int, string, []byte) error {
- return errors.New(string(m))
-}
-
-func (t *LoaderTest) TestLoaderError(c *C) {
- tx, err := t.db.Begin()
- c.Assert(err, IsNil)
- defer tx.Rollback()
-
- loader := errLoader("my error")
- _, err = tx.QueryOne(loader, "SELECT 1, 2")
- c.Assert(err.Error(), Equals, "my error")
-
- // Verify that client is still functional.
- var n1, n2 int
- _, err = tx.QueryOne(pg.Scan(&n1, &n2), "SELECT 1, 2")
- c.Assert(err, IsNil)
- c.Assert(n1, Equals, 1)
- c.Assert(n2, Equals, 2)
-}
diff --git a/vendor/github.com/go-pg/pg/main_test.go b/vendor/github.com/go-pg/pg/main_test.go
deleted file mode 100644
index bd4acd2..0000000
--- a/vendor/github.com/go-pg/pg/main_test.go
+++ /dev/null
@@ -1,230 +0,0 @@
-package pg_test
-
-import (
- "bytes"
- "database/sql/driver"
- "net"
- "strings"
- "sync"
- "sync/atomic"
- "testing"
- "time"
-
- "github.com/go-pg/pg"
-
- . "github.com/onsi/ginkgo"
- . "gopkg.in/check.v1"
-)
-
-func TestUnixSocket(t *testing.T) {
- opt := pgOptions()
- opt.Network = "unix"
- opt.Addr = "/var/run/postgresql/.s.PGSQL.5432"
- opt.TLSConfig = nil
- db := pg.Connect(opt)
- defer db.Close()
-
- _, err := db.Exec("SELECT 'test_unix_socket'")
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestGocheck(t *testing.T) { TestingT(t) }
-
-var _ = Suite(&DBTest{})
-
-type DBTest struct {
- db *pg.DB
-}
-
-func (t *DBTest) SetUpTest(c *C) {
- t.db = pg.Connect(pgOptions())
-}
-
-func (t *DBTest) TearDownTest(c *C) {
- c.Assert(t.db.Close(), IsNil)
-}
-
-func (t *DBTest) TestQueryZeroRows(c *C) {
- res, err := t.db.Query(pg.Discard, "SELECT 1 WHERE 1 != 1")
- c.Assert(err, IsNil)
- c.Assert(res.RowsAffected(), Equals, 0)
-}
-
-func (t *DBTest) TestQueryOneErrNoRows(c *C) {
- _, err := t.db.QueryOne(pg.Discard, "SELECT 1 WHERE 1 != 1")
- c.Assert(err, Equals, pg.ErrNoRows)
-}
-
-func (t *DBTest) TestQueryOneErrMultiRows(c *C) {
- _, err := t.db.QueryOne(pg.Discard, "SELECT generate_series(0, 1)")
- c.Assert(err, Equals, pg.ErrMultiRows)
-}
-
-func (t *DBTest) TestExecOne(c *C) {
- res, err := t.db.ExecOne("SELECT 'test_exec_one'")
- c.Assert(err, IsNil)
- c.Assert(res.RowsAffected(), Equals, 1)
-}
-
-func (t *DBTest) TestExecOneErrNoRows(c *C) {
- _, err := t.db.ExecOne("SELECT 1 WHERE 1 != 1")
- c.Assert(err, Equals, pg.ErrNoRows)
-}
-
-func (t *DBTest) TestExecOneErrMultiRows(c *C) {
- _, err := t.db.ExecOne("SELECT generate_series(0, 1)")
- c.Assert(err, Equals, pg.ErrMultiRows)
-}
-
-func (t *DBTest) TestScan(c *C) {
- var dst int
- _, err := t.db.QueryOne(pg.Scan(&dst), "SELECT 1")
- c.Assert(err, IsNil)
- c.Assert(dst, Equals, 1)
-}
-
-func (t *DBTest) TestExec(c *C) {
- res, err := t.db.Exec("CREATE TEMP TABLE test(id serial PRIMARY KEY)")
- c.Assert(err, IsNil)
- c.Assert(res.RowsAffected(), Equals, -1)
-
- res, err = t.db.Exec("INSERT INTO test VALUES (1)")
- c.Assert(err, IsNil)
- c.Assert(res.RowsAffected(), Equals, 1)
-}
-
-func (t *DBTest) TestStatementExec(c *C) {
- res, err := t.db.Exec("CREATE TEMP TABLE test(id serial PRIMARY KEY)")
- c.Assert(err, IsNil)
- c.Assert(res.RowsAffected(), Equals, -1)
-
- stmt, err := t.db.Prepare("INSERT INTO test VALUES($1)")
- c.Assert(err, IsNil)
- defer stmt.Close()
-
- res, err = stmt.Exec(1)
- c.Assert(err, IsNil)
- c.Assert(res.RowsAffected(), Equals, 1)
-}
-
-func (t *DBTest) TestLargeWriteRead(c *C) {
- src := bytes.Repeat([]byte{0x1}, 1e6)
- var dst []byte
- _, err := t.db.QueryOne(pg.Scan(&dst), "SELECT ?", src)
- c.Assert(err, IsNil)
- c.Assert(dst, DeepEquals, src)
-}
-
-func (t *DBTest) TestIntegrityError(c *C) {
- _, err := t.db.Exec("DO $$BEGIN RAISE unique_violation USING MESSAGE='foo'; END$$;")
- c.Assert(err.(pg.Error).IntegrityViolation(), Equals, true)
-}
-
-type customStrSlice []string
-
-func (s customStrSlice) Value() (driver.Value, error) {
- return strings.Join(s, "\n"), nil
-}
-
-func (s *customStrSlice) Scan(v interface{}) error {
- if v == nil {
- *s = nil
- return nil
- }
-
- b := v.([]byte)
-
- if len(b) == 0 {
- *s = []string{}
- return nil
- }
-
- *s = strings.Split(string(b), "\n")
- return nil
-}
-
-func (t *DBTest) TestScannerValueOnStruct(c *C) {
- src := customStrSlice{"foo", "bar"}
- dst := struct{ Dst customStrSlice }{}
- _, err := t.db.QueryOne(&dst, "SELECT ? AS dst", src)
- c.Assert(err, IsNil)
- c.Assert(dst.Dst, DeepEquals, src)
-}
-
-//------------------------------------------------------------------------------
-
-type badConnError string
-
-func (e badConnError) Error() string { return string(e) }
-func (e badConnError) Timeout() bool { return false }
-func (e badConnError) Temporary() bool { return false }
-
-type badConn struct {
- net.TCPConn
-
- readDelay, writeDelay time.Duration
- readErr, writeErr error
-}
-
-var _ net.Conn = &badConn{}
-
-func (cn *badConn) Read([]byte) (int, error) {
- if cn.readDelay != 0 {
- time.Sleep(cn.readDelay)
- }
- if cn.readErr != nil {
- return 0, cn.readErr
- }
- return 0, badConnError("bad connection")
-}
-
-func (cn *badConn) Write([]byte) (int, error) {
- if cn.writeDelay != 0 {
- time.Sleep(cn.writeDelay)
- }
- if cn.writeErr != nil {
- return 0, cn.writeErr
- }
- return 0, badConnError("bad connection")
-}
-
-func perform(n int, cbs ...func(int)) {
- var wg sync.WaitGroup
- for _, cb := range cbs {
- for i := 0; i < n; i++ {
- wg.Add(1)
- go func(cb func(int), i int) {
- defer GinkgoRecover()
- defer wg.Done()
-
- cb(i)
- }(cb, i)
- }
- }
- wg.Wait()
-}
-
-func eventually(fn func() error, timeout time.Duration) (err error) {
- done := make(chan struct{})
- var exit int32
- go func() {
- for atomic.LoadInt32(&exit) == 0 {
- err = fn()
- if err == nil {
- close(done)
- return
- }
- time.Sleep(timeout / 100)
- }
- }()
-
- select {
- case <-done:
- return nil
- case <-time.After(timeout):
- atomic.StoreInt32(&exit, 1)
- return err
- }
-}
diff --git a/vendor/github.com/go-pg/pg/messages.go b/vendor/github.com/go-pg/pg/messages.go
deleted file mode 100644
index a38b2b4..0000000
--- a/vendor/github.com/go-pg/pg/messages.go
+++ /dev/null
@@ -1,1112 +0,0 @@
-package pg
-
-import (
- "bufio"
- "crypto/md5"
- "crypto/tls"
- "encoding/binary"
- "encoding/hex"
- "errors"
- "fmt"
- "io"
-
- "github.com/go-pg/pg/internal"
- "github.com/go-pg/pg/internal/pool"
- "github.com/go-pg/pg/orm"
- "github.com/go-pg/pg/types"
-)
-
-const (
- commandCompleteMsg = 'C'
- errorResponseMsg = 'E'
- noticeResponseMsg = 'N'
- parameterStatusMsg = 'S'
- authenticationOKMsg = 'R'
- backendKeyDataMsg = 'K'
- noDataMsg = 'n'
- passwordMessageMsg = 'p'
- terminateMsg = 'X'
-
- notificationResponseMsg = 'A'
-
- describeMsg = 'D'
- parameterDescriptionMsg = 't'
-
- queryMsg = 'Q'
- readyForQueryMsg = 'Z'
- emptyQueryResponseMsg = 'I'
- rowDescriptionMsg = 'T'
- dataRowMsg = 'D'
-
- parseMsg = 'P'
- parseCompleteMsg = '1'
-
- bindMsg = 'B'
- bindCompleteMsg = '2'
-
- executeMsg = 'E'
-
- syncMsg = 'S'
- flushMsg = 'H'
-
- closeMsg = 'C'
- closeCompleteMsg = '3'
-
- copyInResponseMsg = 'G'
- copyOutResponseMsg = 'H'
- copyDataMsg = 'd'
- copyDoneMsg = 'c'
-)
-
-var errEmptyQuery = internal.Errorf("pg: query is empty")
-
-func startup(cn *pool.Conn, user, password, database string) error {
- writeStartupMsg(cn.Writer, user, database)
- if err := cn.FlushWriter(); err != nil {
- return err
- }
-
- for {
- c, msgLen, err := readMessageType(cn)
- if err != nil {
- return err
- }
- switch c {
- case backendKeyDataMsg:
- processId, err := readInt32(cn)
- if err != nil {
- return err
- }
- secretKey, err := readInt32(cn)
- if err != nil {
- return err
- }
- cn.ProcessId = processId
- cn.SecretKey = secretKey
- case parameterStatusMsg:
- if err := logParameterStatus(cn, msgLen); err != nil {
- return err
- }
- case authenticationOKMsg:
- if err := authenticate(cn, user, password); err != nil {
- return err
- }
- case readyForQueryMsg:
- _, err := cn.ReadN(msgLen)
- return err
- case errorResponseMsg:
- e, err := readError(cn)
- if err != nil {
- return err
- }
- return e
- default:
- return fmt.Errorf("pg: unknown startup message response: %q", c)
- }
- }
-}
-
-var errSSLNotSupported = errors.New("pg: SSL is not enabled on the server")
-
-func enableSSL(cn *pool.Conn, tlsConf *tls.Config) error {
- writeSSLMsg(cn.Writer)
- if err := cn.FlushWriter(); err != nil {
- return err
- }
-
- c, err := cn.Reader.ReadByte()
- if err != nil {
- return err
- }
- if c != 'S' {
- return errSSLNotSupported
- }
-
- cn.SetNetConn(tls.Client(cn.NetConn(), tlsConf))
- return nil
-}
-
-func authenticate(cn *pool.Conn, user, password string) error {
- num, err := readInt32(cn)
- if err != nil {
- return err
- }
- switch num {
- case 0:
- return nil
- case 3:
- writePasswordMsg(cn.Writer, password)
- if err := cn.FlushWriter(); err != nil {
- return err
- }
-
- c, _, err := readMessageType(cn)
- if err != nil {
- return err
- }
- switch c {
- case authenticationOKMsg:
- num, err := readInt32(cn)
- if err != nil {
- return err
- }
- if num != 0 {
- return fmt.Errorf("pg: unexpected authentication code: %d", num)
- }
- return nil
- case errorResponseMsg:
- e, err := readError(cn)
- if err != nil {
- return err
- }
- return e
- default:
- return fmt.Errorf("pg: unknown password message response: %q", c)
- }
- case 5:
- b, err := cn.ReadN(4)
- if err != nil {
- return err
- }
-
- secret := "md5" + md5s(md5s(password+user)+string(b))
- writePasswordMsg(cn.Writer, secret)
- if err := cn.FlushWriter(); err != nil {
- return err
- }
-
- c, _, err := readMessageType(cn)
- if err != nil {
- return err
- }
- switch c {
- case authenticationOKMsg:
- num, err := readInt32(cn)
- if err != nil {
- return err
- }
- if num != 0 {
- return fmt.Errorf("pg: unexpected authentication code: %d", num)
- }
- return nil
- case errorResponseMsg:
- e, err := readError(cn)
- if err != nil {
- return err
- }
- return e
- default:
- return fmt.Errorf("pg: unknown password message response: %q", c)
- }
- default:
- return fmt.Errorf("pg: unknown authentication message response: %d", num)
- }
-}
-
-func md5s(s string) string {
- h := md5.New()
- h.Write([]byte(s))
- return hex.EncodeToString(h.Sum(nil))
-}
-
-func writeStartupMsg(buf *pool.WriteBuffer, user, database string) {
- buf.StartMessage(0)
- buf.WriteInt32(196608)
- buf.WriteString("user")
- buf.WriteString(user)
- buf.WriteString("database")
- buf.WriteString(database)
- buf.WriteString("")
- buf.FinishMessage()
-}
-
-func writeSSLMsg(buf *pool.WriteBuffer) {
- buf.StartMessage(0)
- buf.WriteInt32(80877103)
- buf.FinishMessage()
-}
-
-func writePasswordMsg(buf *pool.WriteBuffer, password string) {
- buf.StartMessage(passwordMessageMsg)
- buf.WriteString(password)
- buf.FinishMessage()
-}
-
-func writeFlushMsg(buf *pool.WriteBuffer) {
- buf.StartMessage(flushMsg)
- buf.FinishMessage()
-}
-
-func writeCancelRequestMsg(buf *pool.WriteBuffer, processId, secretKey int32) {
- buf.StartMessage(0)
- buf.WriteInt32(80877102)
- buf.WriteInt32(processId)
- buf.WriteInt32(secretKey)
- buf.FinishMessage()
-}
-
-func writeQueryMsg(buf *pool.WriteBuffer, fmter orm.QueryFormatter, query interface{}, params ...interface{}) error {
- buf.StartMessage(queryMsg)
- bytes, err := appendQuery(buf.Bytes, fmter, query, params...)
- if err != nil {
- buf.Reset()
- return err
- }
- buf.Bytes = bytes
- buf.WriteByte(0x0)
- buf.FinishMessage()
- return nil
-}
-
-func appendQuery(dst []byte, fmter orm.QueryFormatter, query interface{}, params ...interface{}) ([]byte, error) {
- switch query := query.(type) {
- case orm.QueryAppender:
- return query.AppendQuery(dst)
- case string:
- return fmter.FormatQuery(dst, query, params...), nil
- default:
- return nil, fmt.Errorf("pg: can't append %T", query)
- }
-}
-
-func writeSyncMsg(buf *pool.WriteBuffer) {
- buf.StartMessage(syncMsg)
- buf.FinishMessage()
-}
-
-func writeParseDescribeSyncMsg(buf *pool.WriteBuffer, name, q string) {
- buf.StartMessage(parseMsg)
- buf.WriteString(name)
- buf.WriteString(q)
- buf.WriteInt16(0)
- buf.FinishMessage()
-
- buf.StartMessage(describeMsg)
- buf.WriteByte('S')
- buf.WriteString(name)
- buf.FinishMessage()
-
- writeSyncMsg(buf)
-}
-
-func readParseDescribeSync(cn *pool.Conn) ([][]byte, error) {
- var columns [][]byte
- for {
- c, msgLen, err := readMessageType(cn)
- if err != nil {
- return nil, err
- }
- switch c {
- case parseCompleteMsg:
- _, err := cn.ReadN(msgLen)
- if err != nil {
- return nil, err
- }
- case rowDescriptionMsg: // Response to the DESCRIBE message.
- columns, err = readRowDescription(cn, nil)
- if err != nil {
- return nil, err
- }
- case parameterDescriptionMsg: // Response to the DESCRIBE message.
- _, err := cn.ReadN(msgLen)
- if err != nil {
- return nil, err
- }
- case noDataMsg: // Response to the DESCRIBE message.
- _, err := cn.ReadN(msgLen)
- if err != nil {
- return nil, err
- }
- case readyForQueryMsg:
- _, err := cn.ReadN(msgLen)
- return columns, err
- case errorResponseMsg:
- e, err := readError(cn)
- if err != nil {
- return nil, err
- }
- return nil, e
- case noticeResponseMsg:
- if err := logNotice(cn, msgLen); err != nil {
- return nil, err
- }
- case parameterStatusMsg:
- if err := logParameterStatus(cn, msgLen); err != nil {
- return nil, err
- }
- default:
- return nil, fmt.Errorf("pg: readParseDescribeSync: unexpected message %#x", c)
- }
- }
-}
-
-// Writes BIND, EXECUTE and SYNC messages.
-func writeBindExecuteMsg(buf *pool.WriteBuffer, name string, params ...interface{}) error {
- buf.StartMessage(bindMsg)
- buf.WriteString("")
- buf.WriteString(name)
- buf.WriteInt16(0)
- buf.WriteInt16(int16(len(params)))
- for _, param := range params {
- buf.StartParam()
- bytes := types.Append(buf.Bytes, param, 0)
- if bytes != nil {
- buf.Bytes = bytes
- buf.FinishParam()
- } else {
- buf.FinishNullParam()
- }
- }
- buf.WriteInt16(0)
- buf.FinishMessage()
-
- buf.StartMessage(executeMsg)
- buf.WriteString("")
- buf.WriteInt32(0)
- buf.FinishMessage()
-
- writeSyncMsg(buf)
-
- return nil
-}
-
-func writeCloseMsg(buf *pool.WriteBuffer, name string) {
- buf.StartMessage(closeMsg)
- buf.WriteByte('S')
- buf.WriteString(name)
- buf.FinishMessage()
-}
-
-func readCloseCompleteMsg(cn *pool.Conn) error {
- for {
- c, msgLen, err := readMessageType(cn)
- if err != nil {
- return err
- }
- switch c {
- case closeCompleteMsg:
- _, err := cn.ReadN(msgLen)
- return err
- case errorResponseMsg:
- e, err := readError(cn)
- if err != nil {
- return err
- }
- return e
- case noticeResponseMsg:
- if err := logNotice(cn, msgLen); err != nil {
- return err
- }
- case parameterStatusMsg:
- if err := logParameterStatus(cn, msgLen); err != nil {
- return err
- }
- default:
- return fmt.Errorf("pg: readCloseCompleteMsg: unexpected message %#x", c)
- }
- }
-}
-
-func readSimpleQuery(cn *pool.Conn) (*result, error) {
- var res result
- var firstErr error
- for {
- c, msgLen, err := readMessageType(cn)
- if err != nil {
- return nil, err
- }
-
- switch c {
- case commandCompleteMsg:
- b, err := cn.ReadN(msgLen)
- if err != nil {
- return nil, err
- }
- if err := res.parse(b); err != nil && firstErr == nil {
- firstErr = err
- }
- case readyForQueryMsg:
- _, err := cn.ReadN(msgLen)
- if err != nil {
- return nil, err
- }
- if firstErr != nil {
- return nil, firstErr
- }
- return &res, nil
- case rowDescriptionMsg:
- _, err := cn.ReadN(msgLen)
- if err != nil {
- return nil, err
- }
- case dataRowMsg:
- _, err := cn.ReadN(msgLen)
- if err != nil {
- return nil, err
- }
- res.returned++
- case errorResponseMsg:
- e, err := readError(cn)
- if err != nil {
- return nil, err
- }
- if firstErr == nil {
- firstErr = e
- }
- case emptyQueryResponseMsg:
- if firstErr == nil {
- firstErr = errEmptyQuery
- }
- case noticeResponseMsg:
- if err := logNotice(cn, msgLen); err != nil {
- return nil, err
- }
- case parameterStatusMsg:
- if err := logParameterStatus(cn, msgLen); err != nil {
- return nil, err
- }
- default:
- return nil, fmt.Errorf("pg: readSimpleQuery: unexpected message %#x", c)
- }
- }
-}
-
-func readExtQuery(cn *pool.Conn) (*result, error) {
- var res result
- var firstErr error
- for {
- c, msgLen, err := readMessageType(cn)
- if err != nil {
- return nil, err
- }
-
- switch c {
- case bindCompleteMsg:
- _, err := cn.ReadN(msgLen)
- if err != nil {
- return nil, err
- }
- case dataRowMsg:
- _, err := cn.ReadN(msgLen)
- if err != nil {
- return nil, err
- }
- res.returned++
- case commandCompleteMsg: // Response to the EXECUTE message.
- b, err := cn.ReadN(msgLen)
- if err != nil {
- return nil, err
- }
- if err := res.parse(b); err != nil && firstErr == nil {
- firstErr = err
- }
- case readyForQueryMsg: // Response to the SYNC message.
- _, err := cn.ReadN(msgLen)
- if err != nil {
- return nil, err
- }
- if firstErr != nil {
- return nil, firstErr
- }
- return &res, nil
- case errorResponseMsg:
- e, err := readError(cn)
- if err != nil {
- return nil, err
- }
- if firstErr == nil {
- firstErr = e
- }
- case emptyQueryResponseMsg:
- if firstErr == nil {
- firstErr = errEmptyQuery
- }
- case noticeResponseMsg:
- if err := logNotice(cn, msgLen); err != nil {
- return nil, err
- }
- case parameterStatusMsg:
- if err := logParameterStatus(cn, msgLen); err != nil {
- return nil, err
- }
- default:
- return nil, fmt.Errorf("pg: readExtQuery: unexpected message %#x", c)
- }
- }
-}
-
-func readRowDescription(cn *pool.Conn, columns [][]byte) ([][]byte, error) {
- colNum, err := readInt16(cn)
- if err != nil {
- return nil, err
- }
-
- columns = setByteSliceLen(columns, int(colNum))
- for i := 0; i < int(colNum); i++ {
- columns[i], err = readBytes(cn, columns[i][:0])
- if err != nil {
- return nil, err
- }
- if _, err := cn.ReadN(18); err != nil {
- return nil, err
- }
- }
-
- return columns, nil
-}
-
-func setByteSliceLen(b [][]byte, n int) [][]byte {
- if n <= cap(b) {
- return b[:n]
- }
- b = b[:cap(b)]
- b = append(b, make([][]byte, n-cap(b))...)
- return b
-}
-
-func readDataRow(cn *pool.Conn, scanner orm.ColumnScanner, columns [][]byte) error {
- colNum, err := readInt16(cn)
- if err != nil {
- return err
- }
-
- var firstErr error
- for colIdx := int16(0); colIdx < colNum; colIdx++ {
- l, err := readInt32(cn)
- if err != nil {
- return err
- }
-
- var b []byte
- if l != -1 { // NULL
- b, err = cn.ReadN(int(l))
- if err != nil {
- return err
- }
- }
-
- column := internal.BytesToString(columns[colIdx])
- if err := scanner.ScanColumn(int(colIdx), column, b); err != nil && firstErr == nil {
- firstErr = internal.Errorf(err.Error())
- }
-
- }
-
- return firstErr
-}
-
-func newModel(mod interface{}) (orm.Model, error) {
- m, ok := mod.(orm.Model)
- if ok {
- return m, m.Init()
- }
-
- m, err := orm.NewModel(mod)
- if err != nil {
- return nil, err
- }
- return m, m.Init()
-}
-
-func readSimpleQueryData(cn *pool.Conn, mod interface{}) (*result, error) {
- var res result
- var firstErr error
- for {
- c, msgLen, err := readMessageType(cn)
- if err != nil {
- return nil, err
- }
-
- switch c {
- case rowDescriptionMsg:
- cn.Columns, err = readRowDescription(cn, cn.Columns[:0])
- if err != nil {
- return nil, err
- }
-
- if res.model == nil {
- var err error
- res.model, err = newModel(mod)
- if err != nil {
- if firstErr == nil {
- firstErr = err
- }
- res.model = Discard
- }
- }
- case dataRowMsg:
- m := res.model.NewModel()
- if err := readDataRow(cn, m, cn.Columns); err != nil {
- if firstErr == nil {
- firstErr = err
- }
- } else if err := res.model.AddModel(m); err != nil {
- if firstErr == nil {
- firstErr = err
- }
- }
-
- res.returned++
- case commandCompleteMsg:
- b, err := cn.ReadN(msgLen)
- if err != nil {
- return nil, err
- }
- if err := res.parse(b); err != nil && firstErr == nil {
- firstErr = err
- }
- case readyForQueryMsg:
- _, err := cn.ReadN(msgLen)
- if err != nil {
- return nil, err
- }
- if firstErr != nil {
- return nil, firstErr
- }
- return &res, nil
- case errorResponseMsg:
- e, err := readError(cn)
- if err != nil {
- return nil, err
- }
- if firstErr == nil {
- firstErr = e
- }
- case emptyQueryResponseMsg:
- if firstErr == nil {
- firstErr = errEmptyQuery
- }
- case noticeResponseMsg:
- if err := logNotice(cn, msgLen); err != nil {
- return nil, err
- }
- case parameterStatusMsg:
- if err := logParameterStatus(cn, msgLen); err != nil {
- return nil, err
- }
- default:
- return nil, fmt.Errorf("pg: readSimpleQueryData: unexpected message %#x", c)
- }
- }
-}
-
-func readExtQueryData(cn *pool.Conn, mod interface{}, columns [][]byte) (*result, error) {
- var res result
- var firstErr error
- for {
- c, msgLen, err := readMessageType(cn)
- if err != nil {
- return nil, err
- }
-
- switch c {
- case bindCompleteMsg:
- _, err := cn.ReadN(msgLen)
- if err != nil {
- return nil, err
- }
- case dataRowMsg:
- if res.model == nil {
- var err error
- res.model, err = newModel(mod)
- if err != nil {
- if firstErr == nil {
- firstErr = err
- }
- res.model = Discard
- }
- }
-
- m := res.model.NewModel()
- if err := readDataRow(cn, m, columns); err != nil {
- if firstErr == nil {
- firstErr = err
- }
- } else if err := res.model.AddModel(m); err != nil {
- if firstErr == nil {
- firstErr = err
- }
- }
-
- res.returned++
- case commandCompleteMsg: // Response to the EXECUTE message.
- b, err := cn.ReadN(msgLen)
- if err != nil {
- return nil, err
- }
- if err := res.parse(b); err != nil && firstErr == nil {
- firstErr = err
- }
- case readyForQueryMsg: // Response to the SYNC message.
- _, err := cn.ReadN(msgLen)
- if err != nil {
- return nil, err
- }
- if firstErr != nil {
- return nil, firstErr
- }
- return &res, nil
- case errorResponseMsg:
- e, err := readError(cn)
- if err != nil {
- return nil, err
- }
- if firstErr == nil {
- firstErr = e
- }
- case noticeResponseMsg:
- if err := logNotice(cn, msgLen); err != nil {
- return nil, err
- }
- case parameterStatusMsg:
- if err := logParameterStatus(cn, msgLen); err != nil {
- return nil, err
- }
- default:
- return nil, fmt.Errorf("pg: readExtQueryData: unexpected message %#x", c)
- }
- }
-}
-
-func readCopyInResponse(cn *pool.Conn) error {
- var firstErr error
- for {
- c, msgLen, err := readMessageType(cn)
- if err != nil {
- return err
- }
-
- switch c {
- case copyInResponseMsg:
- _, err := cn.ReadN(msgLen)
- return err
- case errorResponseMsg:
- e, err := readError(cn)
- if err != nil {
- return err
- }
- if firstErr == nil {
- firstErr = e
- }
- case readyForQueryMsg:
- _, err := cn.ReadN(msgLen)
- if err != nil {
- return err
- }
- return firstErr
- case noticeResponseMsg:
- if err := logNotice(cn, msgLen); err != nil {
- return err
- }
- case parameterStatusMsg:
- if err := logParameterStatus(cn, msgLen); err != nil {
- return err
- }
- default:
- return fmt.Errorf("pg: readCopyInResponse: unexpected message %#x", c)
- }
- }
-}
-
-func readCopyOutResponse(cn *pool.Conn) error {
- var firstErr error
- for {
- c, msgLen, err := readMessageType(cn)
- if err != nil {
- return err
- }
-
- switch c {
- case copyOutResponseMsg:
- _, err := cn.ReadN(msgLen)
- return err
- case errorResponseMsg:
- e, err := readError(cn)
- if err != nil {
- return err
- }
- if firstErr == nil {
- firstErr = e
- }
- case readyForQueryMsg:
- _, err := cn.ReadN(msgLen)
- if err != nil {
- return err
- }
- return firstErr
- case noticeResponseMsg:
- if err := logNotice(cn, msgLen); err != nil {
- return err
- }
- case parameterStatusMsg:
- if err := logParameterStatus(cn, msgLen); err != nil {
- return err
- }
- default:
- return fmt.Errorf("pg: readCopyOutResponse: unexpected message %#x", c)
- }
- }
-}
-
-func readCopyData(cn *pool.Conn, w io.Writer) (*result, error) {
- var res result
- var firstErr error
- for {
- c, msgLen, err := readMessageType(cn)
- if err != nil {
- return nil, err
- }
-
- switch c {
- case copyDataMsg:
- b, err := cn.ReadN(msgLen)
- if err != nil {
- return nil, err
- }
-
- _, err = w.Write(b)
- if err != nil {
- return nil, err
- }
- case copyDoneMsg:
- _, err := cn.ReadN(msgLen)
- if err != nil {
- return nil, err
- }
- case commandCompleteMsg:
- b, err := cn.ReadN(msgLen)
- if err != nil {
- return nil, err
- }
- if err := res.parse(b); err != nil && firstErr == nil {
- firstErr = err
- }
- case readyForQueryMsg:
- _, err := cn.ReadN(msgLen)
- if err != nil {
- return nil, err
- }
- if firstErr != nil {
- return nil, firstErr
- }
- return &res, nil
- case errorResponseMsg:
- e, err := readError(cn)
- if err != nil {
- return nil, err
- }
- return nil, e
- case noticeResponseMsg:
- if err := logNotice(cn, msgLen); err != nil {
- return nil, err
- }
- case parameterStatusMsg:
- if err := logParameterStatus(cn, msgLen); err != nil {
- return nil, err
- }
- default:
- return nil, fmt.Errorf("pg: readCopyData: unexpected message %#x", c)
- }
- }
-}
-
-func writeCopyData(buf *pool.WriteBuffer, r io.Reader) error {
- buf.StartMessage(copyDataMsg)
- _, err := buf.ReadFrom(r)
- buf.FinishMessage()
- return err
-}
-
-func writeCopyDone(buf *pool.WriteBuffer) {
- buf.StartMessage(copyDoneMsg)
- buf.FinishMessage()
-}
-
-func readReadyForQuery(cn *pool.Conn) (*result, error) {
- var res result
- var firstErr error
- for {
- c, msgLen, err := readMessageType(cn)
- if err != nil {
- return nil, err
- }
-
- switch c {
- case commandCompleteMsg:
- b, err := cn.ReadN(msgLen)
- if err != nil {
- return nil, err
- }
- if err := res.parse(b); err != nil && firstErr == nil {
- firstErr = err
- }
- case readyForQueryMsg:
- _, err := cn.ReadN(msgLen)
- if err != nil {
- return nil, err
- }
- if firstErr != nil {
- return nil, firstErr
- }
- return &res, nil
- case errorResponseMsg:
- e, err := readError(cn)
- if err != nil {
- return nil, err
- }
- if firstErr == nil {
- firstErr = e
- }
- case noticeResponseMsg:
- if err := logNotice(cn, msgLen); err != nil {
- return nil, err
- }
- case parameterStatusMsg:
- if err := logParameterStatus(cn, msgLen); err != nil {
- return nil, err
- }
- default:
- return nil, fmt.Errorf("pg: readReadyForQueryOrError: unexpected message %#x", c)
- }
- }
-}
-
-func readNotification(cn *pool.Conn) (channel, payload string, err error) {
- for {
- c, msgLen, err := readMessageType(cn)
- if err != nil {
- return "", "", err
- }
-
- switch c {
- case commandCompleteMsg:
- _, err := cn.ReadN(msgLen)
- if err != nil {
- return "", "", err
- }
- case readyForQueryMsg:
- _, err := cn.ReadN(msgLen)
- if err != nil {
- return "", "", err
- }
- case errorResponseMsg:
- e, err := readError(cn)
- if err != nil {
- return "", "", err
- }
- return "", "", e
- case noticeResponseMsg:
- if err := logNotice(cn, msgLen); err != nil {
- return "", "", err
- }
- case notificationResponseMsg:
- _, err := readInt32(cn)
- if err != nil {
- return "", "", err
- }
- channel, err = readString(cn)
- if err != nil {
- return "", "", err
- }
- payload, err = readString(cn)
- if err != nil {
- return "", "", err
- }
- return channel, payload, nil
- default:
- return "", "", fmt.Errorf("pg: unexpected message %q", c)
- }
- }
-}
-
-var terminateMessage = []byte{terminateMsg, 0, 0, 0, 4}
-
-func terminateConn(cn *pool.Conn) error {
- // Don't use cn.Buf because it is racy with user code.
- _, err := cn.NetConn().Write(terminateMessage)
- return err
-}
-
-//------------------------------------------------------------------------------
-
-func readInt16(cn *pool.Conn) (int16, error) {
- b, err := cn.ReadN(2)
- if err != nil {
- return 0, err
- }
- return int16(binary.BigEndian.Uint16(b)), nil
-}
-
-func readInt32(cn *pool.Conn) (int32, error) {
- b, err := cn.ReadN(4)
- if err != nil {
- return 0, err
- }
- return int32(binary.BigEndian.Uint32(b)), nil
-}
-
-func readString(cn *pool.Conn) (string, error) {
- s, err := cn.Reader.ReadString(0)
- if err != nil {
- return "", err
- }
- return s[:len(s)-1], nil
-}
-
-func readBytes(cn *pool.Conn, b []byte) ([]byte, error) {
- for {
- line, err := cn.Reader.ReadSlice(0)
- if err != nil && err != bufio.ErrBufferFull {
- return nil, err
- }
- b = append(b, line...)
- if err == nil {
- break
- }
- }
- return b[:len(b)-1], nil
-}
-
-func readError(cn *pool.Conn) (error, error) {
- m := map[byte]string{
- 'a': cn.RemoteAddr().String(),
- }
- for {
- c, err := cn.Reader.ReadByte()
- if err != nil {
- return nil, err
- }
- if c == 0 {
- break
- }
- s, err := readString(cn)
- if err != nil {
- return nil, err
- }
- m[c] = s
- }
-
- return internal.NewPGError(m), nil
-}
-
-func readMessageType(cn *pool.Conn) (byte, int, error) {
- c, err := cn.Reader.ReadByte()
- if err != nil {
- return 0, 0, err
- }
- l, err := readInt32(cn)
- if err != nil {
- return 0, 0, err
- }
- return c, int(l) - 4, nil
-}
-
-func logNotice(cn *pool.Conn, msgLen int) error {
- _, err := cn.ReadN(msgLen)
- return err
-}
-
-func logParameterStatus(cn *pool.Conn, msgLen int) error {
- _, err := cn.ReadN(msgLen)
- return err
-}
diff --git a/vendor/github.com/go-pg/pg/options.go b/vendor/github.com/go-pg/pg/options.go
deleted file mode 100644
index 5d0e406..0000000
--- a/vendor/github.com/go-pg/pg/options.go
+++ /dev/null
@@ -1,219 +0,0 @@
-package pg
-
-import (
- "crypto/tls"
- "errors"
- "fmt"
- "net"
- "net/url"
- "runtime"
- "strings"
- "time"
-
- "github.com/go-pg/pg/internal/pool"
-)
-
-// Database connection options.
-type Options struct {
- // Network type, either tcp or unix.
- // Default is tcp.
- Network string
- // TCP host:port or Unix socket depending on Network.
- Addr string
-
- // Dialer creates new network connection and has priority over
- // Network and Addr options.
- Dialer func(network, addr string) (net.Conn, error)
-
- // Hook that is called when new connection is established.
- OnConnect func(*DB) error
-
- User string
- Password string
- Database string
-
- // TLS config for secure connections.
- TLSConfig *tls.Config
-
- // Maximum number of retries before giving up.
- // Default is to not retry failed queries.
- MaxRetries int
- // Whether to retry queries cancelled because of statement_timeout.
- RetryStatementTimeout bool
- // Minimum backoff between each retry.
- // Default is 250 milliseconds; -1 disables backoff.
- MinRetryBackoff time.Duration
- // Maximum backoff between each retry.
- // Default is 4 seconds; -1 disables backoff.
- MaxRetryBackoff time.Duration
-
- // Dial timeout for establishing new connections.
- // Default is 5 seconds.
- DialTimeout time.Duration
-
- // Timeout for socket reads. If reached, commands will fail
- // with a timeout instead of blocking.
- ReadTimeout time.Duration
- // Timeout for socket writes. If reached, commands will fail
- // with a timeout instead of blocking.
- WriteTimeout time.Duration
-
- // Maximum number of socket connections.
- // Default is 10 connections per every CPU as reported by runtime.NumCPU.
- PoolSize int
- // Time for which client waits for free connection if all
- // connections are busy before returning an error.
- // Default is 5 seconds.
- PoolTimeout time.Duration
- // Time after which client closes idle connections.
- // Default is to not close idle connections.
- IdleTimeout time.Duration
- // Connection age at which client retires (closes) the connection.
- // Primarily useful with proxies like HAProxy.
- // Default is to not close aged connections.
- MaxAge time.Duration
- // Frequency of idle checks.
- // Default is 1 minute.
- IdleCheckFrequency time.Duration
-}
-
-func (opt *Options) init() {
- if opt.Network == "" {
- opt.Network = "tcp"
- }
-
- if opt.Addr == "" {
- switch opt.Network {
- case "tcp":
- opt.Addr = "localhost:5432"
- case "unix":
- opt.Addr = "/var/run/postgresql/.s.PGSQL.5432"
- }
- }
-
- if opt.PoolSize == 0 {
- opt.PoolSize = 10 * runtime.NumCPU()
- }
-
- if opt.PoolTimeout == 0 {
- if opt.ReadTimeout != 0 {
- opt.PoolTimeout = opt.ReadTimeout + time.Second
- } else {
- opt.PoolTimeout = 30 * time.Second
- }
- }
-
- if opt.DialTimeout == 0 {
- opt.DialTimeout = 5 * time.Second
- }
-
- if opt.IdleCheckFrequency == 0 {
- opt.IdleCheckFrequency = time.Minute
- }
-
- switch opt.MinRetryBackoff {
- case -1:
- opt.MinRetryBackoff = 0
- case 0:
- opt.MinRetryBackoff = 250 * time.Millisecond
- }
- switch opt.MaxRetryBackoff {
- case -1:
- opt.MaxRetryBackoff = 0
- case 0:
- opt.MaxRetryBackoff = 4 * time.Second
- }
-}
-
-// ParseURL parses an URL into options that can be used to connect to PostgreSQL.
-func ParseURL(sURL string) (*Options, error) {
- parsedUrl, err := url.Parse(sURL)
- if err != nil {
- return nil, err
- }
-
- // scheme
- if parsedUrl.Scheme != "postgres" {
- return nil, errors.New("pg: invalid scheme: " + parsedUrl.Scheme)
- }
-
- // host and port
- options := &Options{
- Addr: parsedUrl.Host,
- }
- if !strings.Contains(options.Addr, ":") {
- options.Addr = options.Addr + ":5432"
- }
-
- // username and password
- if parsedUrl.User != nil {
- options.User = parsedUrl.User.Username()
-
- if password, ok := parsedUrl.User.Password(); ok {
- options.Password = password
- }
- }
-
- if options.User == "" {
- options.User = "postgres"
- }
-
- // database
- if len(strings.Trim(parsedUrl.Path, "/")) > 0 {
- options.Database = parsedUrl.Path[1:]
- } else {
- return nil, errors.New("pg: database name not provided")
- }
-
- // ssl mode
- query, err := url.ParseQuery(parsedUrl.RawQuery)
- if err != nil {
- return nil, err
- }
-
- if sslMode, ok := query["sslmode"]; ok && len(sslMode) > 0 {
- switch sslMode[0] {
- case "allow":
- fallthrough
- case "prefer":
- options.TLSConfig = &tls.Config{InsecureSkipVerify: true}
- case "disable":
- options.TLSConfig = nil
- default:
- return nil, errors.New(fmt.Sprintf("pg: sslmode '%v' is not supported", sslMode[0]))
- }
- } else {
- options.TLSConfig = &tls.Config{InsecureSkipVerify: true}
- }
-
- delete(query, "sslmode")
- if len(query) > 0 {
- return nil, errors.New("pg: options other than 'sslmode' are not supported")
- }
-
- return options, nil
-}
-
-func (opt *Options) getDialer() func() (net.Conn, error) {
- if opt.Dialer != nil {
- return func() (net.Conn, error) {
- return opt.Dialer(opt.Network, opt.Addr)
- }
- }
- return func() (net.Conn, error) {
- return net.DialTimeout(opt.Network, opt.Addr, opt.DialTimeout)
- }
-}
-
-func newConnPool(opt *Options) *pool.ConnPool {
- return pool.NewConnPool(&pool.Options{
- Dialer: opt.getDialer(),
- PoolSize: opt.PoolSize,
- PoolTimeout: opt.PoolTimeout,
- IdleTimeout: opt.IdleTimeout,
- IdleCheckFrequency: opt.IdleCheckFrequency,
- OnClose: func(cn *pool.Conn) error {
- return terminateConn(cn)
- },
- })
-}
diff --git a/vendor/github.com/go-pg/pg/options_test.go b/vendor/github.com/go-pg/pg/options_test.go
deleted file mode 100644
index b8cca3e..0000000
--- a/vendor/github.com/go-pg/pg/options_test.go
+++ /dev/null
@@ -1,177 +0,0 @@
-// +build go1.7
-
-package pg
-
-import (
- "errors"
- "testing"
-)
-
-func TestParseURL(t *testing.T) {
- cases := []struct {
- url string
- addr string
- user string
- password string
- database string
- tls bool
- err error
- }{
- {
- "postgres://vasya:pupkin@somewhere.at.amazonaws.com:5432/postgres",
- "somewhere.at.amazonaws.com:5432",
- "vasya",
- "pupkin",
- "postgres",
- true,
- nil,
- },
- {
- "postgres://vasya:pupkin@somewhere.at.amazonaws.com:5432/postgres?sslmode=allow",
- "somewhere.at.amazonaws.com:5432",
- "vasya",
- "pupkin",
- "postgres",
- true,
- nil,
- },
- {
- "postgres://vasya:pupkin@somewhere.at.amazonaws.com:5432/postgres?sslmode=prefer",
- "somewhere.at.amazonaws.com:5432",
- "vasya",
- "pupkin",
- "postgres",
- true,
- nil,
- },
- {
- "postgres://vasya:pupkin@somewhere.at.amazonaws.com:5432/postgres?sslmode=require",
- "somewhere.at.amazonaws.com:5432",
- "vasya",
- "pupkin",
- "postgres",
- true,
- errors.New("pg: sslmode 'require' is not supported"),
- },
- {
- "postgres://vasya:pupkin@somewhere.at.amazonaws.com:5432/postgres?sslmode=verify-ca",
- "somewhere.at.amazonaws.com:5432",
- "vasya",
- "pupkin",
- "postgres",
- true,
- errors.New("pg: sslmode 'verify-ca' is not supported"),
- },
- {
- "postgres://vasya:pupkin@somewhere.at.amazonaws.com:5432/postgres?sslmode=verify-full",
- "somewhere.at.amazonaws.com:5432",
- "vasya",
- "pupkin",
- "postgres",
- true,
- errors.New("pg: sslmode 'verify-full' is not supported"),
- },
- {
- "postgres://vasya:pupkin@somewhere.at.amazonaws.com:5432/postgres?sslmode=disable",
- "somewhere.at.amazonaws.com:5432",
- "vasya",
- "pupkin",
- "postgres",
- false,
- nil,
- },
- {
- "postgres://vasya:pupkin@somewhere.at.amazonaws.com:5432/",
- "somewhere.at.amazonaws.com:5432",
- "vasya",
- "pupkin",
- "",
- true,
- errors.New("pg: database name not provided"),
- },
- {
- "postgres://vasya:pupkin@somewhere.at.amazonaws.com/postgres",
- "somewhere.at.amazonaws.com:5432",
- "vasya",
- "pupkin",
- "postgres",
- true,
- nil,
- },
- {
- "postgres://vasya:pupkin@somewhere.at.amazonaws.com:5432/postgres?abc=123",
- "somewhere.at.amazonaws.com:5432",
- "vasya",
- "pupkin",
- "postgres",
- true,
- errors.New("pg: options other than 'sslmode' are not supported"),
- },
- {
- "postgres://vasya@somewhere.at.amazonaws.com:5432/postgres",
- "somewhere.at.amazonaws.com:5432",
- "vasya",
- "",
- "postgres",
- true,
- nil,
- },
- {
- "postgres://somewhere.at.amazonaws.com:5432/postgres",
- "somewhere.at.amazonaws.com:5432",
- "postgres",
- "",
- "postgres",
- true,
- nil,
- },
- {
- "http://google.com/test",
- "google.com:5432",
- "postgres",
- "",
- "test",
- true,
- errors.New("pg: invalid scheme: http"),
- },
- }
-
- for _, c := range cases {
- t.Run(c.url, func(t *testing.T) {
- o, err := ParseURL(c.url)
- if c.err == nil && err != nil {
- t.Fatalf("unexpected error: '%q'", err)
- return
- }
- if c.err != nil && err != nil {
- if c.err.Error() != err.Error() {
- t.Fatalf("expected error %q, want %q", err, c.err)
- }
- return
- }
- if c.err != nil && err == nil {
- t.Errorf("expected error %q, got nothing", c.err)
- }
- if o.Addr != c.addr {
- t.Errorf("addr: got %q, want %q", o.Addr, c.addr)
- }
- if o.User != c.user {
- t.Errorf("user: got %q, want %q", o.User, c.user)
- }
- if o.Password != c.password {
- t.Errorf("password: got %q, want %q", o.Password, c.password)
- }
- if o.Database != c.database {
- t.Errorf("database: got %q, want %q", o.Database, c.database)
- }
-
- if c.tls {
- if o.TLSConfig == nil {
- t.Error("got nil TLSConfig, expected a TLSConfig")
- } else if !o.TLSConfig.InsecureSkipVerify {
- t.Error("must set InsecureSkipVerify to true in TLSConfig, got false")
- }
- }
- })
- }
-}
diff --git a/vendor/github.com/go-pg/pg/orm/count_estimate.go b/vendor/github.com/go-pg/pg/orm/count_estimate.go
deleted file mode 100644
index f0139ac..0000000
--- a/vendor/github.com/go-pg/pg/orm/count_estimate.go
+++ /dev/null
@@ -1,120 +0,0 @@
-package orm
-
-import (
- "fmt"
- "sync"
-
- "github.com/go-pg/pg/internal"
-)
-
-// Placeholder that is replaced with count(*).
-const placeholder = `'_go_pg_placeholder'`
-
-// https://wiki.postgresql.org/wiki/Count_estimate
-var pgCountEstimateFunc = fmt.Sprintf(`
-CREATE OR REPLACE FUNCTION _go_pg_count_estimate_v2(query text, threshold int)
-RETURNS int AS $$
-DECLARE
- rec record;
- nrows int;
-BEGIN
- FOR rec IN EXECUTE 'EXPLAIN ' || query LOOP
- nrows := substring(rec."QUERY PLAN" FROM ' rows=(\d+)');
- EXIT WHEN nrows IS NOT NULL;
- END LOOP;
-
- -- Return the estimation if there are too many rows.
- IF nrows > threshold THEN
- RETURN nrows;
- END IF;
-
- -- Otherwise execute real count query.
- query := replace(query, 'SELECT '%s'', 'SELECT count(*)');
- EXECUTE query INTO nrows;
-
- IF nrows IS NULL THEN
- nrows := 0;
- END IF;
-
- RETURN nrows;
-END;
-$$ LANGUAGE plpgsql;
-`, placeholder)
-
-// CountEstimate uses EXPLAIN to get estimated number of rows matching the query.
-// If that number is bigger than the threshold it returns the estimation.
-// Otherwise it executes another query using count aggregate function and
-// returns the result.
-//
-// Based on https://wiki.postgresql.org/wiki/Count_estimate
-func (q *Query) CountEstimate(threshold int) (int, error) {
- if q.stickyErr != nil {
- return 0, q.stickyErr
- }
-
- query, err := q.countSelectQuery(placeholder).AppendQuery(nil)
- if err != nil {
- return 0, err
- }
-
- for i := 0; i < 3; i++ {
- var count int
- _, err = q.db.QueryOne(
- Scan(&count),
- "SELECT _go_pg_count_estimate_v2(?, ?)",
- string(query), threshold,
- )
- if err != nil {
- if pgerr, ok := err.(internal.PGError); ok && pgerr.Field('C') == "42883" {
- // undefined_function
- if err := q.createCountEstimateFunc(); err != nil {
- return 0, err
- }
- continue
- }
- }
- return count, err
- }
-
- return 0, err
-}
-
-func (q *Query) createCountEstimateFunc() error {
- _, err := q.db.Exec(pgCountEstimateFunc)
- return err
-}
-
-// SelectAndCountEstimate runs Select and CountEstimate in two goroutines,
-// waits for them to finish and returns the result.
-func (q *Query) SelectAndCountEstimate(threshold int, values ...interface{}) (count int, err error) {
- if q.stickyErr != nil {
- return 0, q.stickyErr
- }
-
- var wg sync.WaitGroup
- wg.Add(2)
- var mu sync.Mutex
-
- go func() {
- defer wg.Done()
- if e := q.Select(values...); e != nil {
- mu.Lock()
- err = e
- mu.Unlock()
- }
- }()
-
- go func() {
- defer wg.Done()
- var e error
- count, e = q.CountEstimate(threshold)
- if e != nil {
- mu.Lock()
- err = e
- mu.Unlock()
- }
- }()
-
- wg.Wait()
- return count, err
-}
diff --git a/vendor/github.com/go-pg/pg/orm/create_table.go b/vendor/github.com/go-pg/pg/orm/create_table.go
deleted file mode 100644
index 42058bf..0000000
--- a/vendor/github.com/go-pg/pg/orm/create_table.go
+++ /dev/null
@@ -1,122 +0,0 @@
-package orm
-
-import (
- "errors"
- "strconv"
-)
-
-type CreateTableOptions struct {
- Temp bool
- IfNotExists bool
- Varchar int // replaces PostgreSQL data type `text` with `varchar(n)`
- FKConstraints bool // whether to create foreign key constraints
-}
-
-func CreateTable(db DB, model interface{}, opt *CreateTableOptions) (Result, error) {
- return NewQuery(db, model).CreateTable(opt)
-}
-
-type createTableQuery struct {
- q *Query
- opt *CreateTableOptions
-}
-
-func (q createTableQuery) Copy() QueryAppender {
- return q
-}
-
-func (q createTableQuery) Query() *Query {
- return q.q
-}
-
-func (q createTableQuery) AppendQuery(b []byte) ([]byte, error) {
- if q.q.stickyErr != nil {
- return nil, q.q.stickyErr
- }
- if q.q.model == nil {
- return nil, errors.New("pg: Model is nil")
- }
-
- table := q.q.model.Table()
-
- b = append(b, "CREATE "...)
- if q.opt != nil && q.opt.Temp {
- b = append(b, "TEMP "...)
- }
- b = append(b, "TABLE "...)
- if q.opt != nil && q.opt.IfNotExists {
- b = append(b, "IF NOT EXISTS "...)
- }
- b = q.q.appendTableName(b)
- b = append(b, " ("...)
-
- for i, field := range table.Fields {
- b = append(b, field.Column...)
- b = append(b, " "...)
- if q.opt != nil && q.opt.Varchar > 0 &&
- field.SQLType == "text" && !field.HasFlag(customTypeFlag) {
- b = append(b, "varchar("...)
- b = strconv.AppendInt(b, int64(q.opt.Varchar), 10)
- b = append(b, ")"...)
- } else {
- b = append(b, field.SQLType...)
- }
- if field.HasFlag(NotNullFlag) {
- b = append(b, " NOT NULL"...)
- }
- if field.HasFlag(UniqueFlag) {
- b = append(b, " UNIQUE"...)
- }
- if field.Default != "" {
- b = append(b, " DEFAULT "...)
- b = append(b, field.Default...)
- }
-
- if i != len(table.Fields)-1 {
- b = append(b, ", "...)
- }
- }
-
- b = appendPKConstraint(b, table.PKs)
-
- if q.opt != nil && q.opt.FKConstraints {
- for _, rel := range table.Relations {
- b = q.appendFKConstraint(b, table, rel)
- }
- }
-
- b = append(b, ")"...)
-
- return b, nil
-}
-
-func appendPKConstraint(b []byte, pks []*Field) []byte {
- if len(pks) == 0 {
- return b
- }
-
- b = append(b, ", PRIMARY KEY ("...)
- b = appendColumns(b, pks)
- b = append(b, ")"...)
- return b
-}
-
-func (q createTableQuery) appendFKConstraint(b []byte, table *Table, rel *Relation) []byte {
- if rel.Type != HasOneRelation {
- return b
- }
-
- b = append(b, ", FOREIGN KEY ("...)
- b = appendColumns(b, rel.FKs)
- b = append(b, ")"...)
-
- b = append(b, " REFERENCES "...)
- b = q.q.FormatQuery(b, string(rel.JoinTable.Name))
- b = append(b, " ("...)
- b = appendColumns(b, rel.JoinTable.PKs)
- b = append(b, ")"...)
-
- b = append(b, " ON DELETE CASCADE"...)
-
- return b
-}
diff --git a/vendor/github.com/go-pg/pg/orm/create_table_test.go b/vendor/github.com/go-pg/pg/orm/create_table_test.go
deleted file mode 100644
index 0c78588..0000000
--- a/vendor/github.com/go-pg/pg/orm/create_table_test.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package orm
-
-import (
- "database/sql"
- "time"
-
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-)
-
-type CreateTableModel struct {
- Id int
- Int8 int8
- Uint8 uint8
- Int16 int16
- Uint16 uint16
- Int32 int32
- Uint32 uint32
- Int64 int64
- Uint64 uint64
- Float32 float32
- Float64 float64
- Decimal float64 `sql:"type:'decimal(10,10)'"`
- ByteSlice []byte
- ByteArray [32]byte
- String string `sql:"default:'D\\'Angelo'"`
- Varchar string `sql:",type:varchar(500)"`
- Time time.Time `sql:"default:now()"`
- NotNull int `sql:",notnull"`
- Unique int `sql:",unique"`
- NullBool sql.NullBool
- NullFloat64 sql.NullFloat64
- NullInt64 sql.NullInt64
- NullString sql.NullString
- Slice []int
- SliceArray []int `pg:",array"`
- Map map[int]int
- Struct struct{}
-}
-
-type CreateTableWithoutPKModel struct {
- String string
-}
-
-var _ = Describe("CreateTable", func() {
- It("creates new table", func() {
- q := NewQuery(nil, &CreateTableModel{})
-
- b, err := createTableQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`CREATE TABLE "create_table_models" ("id" bigserial, "int8" smallint, "uint8" smallint, "int16" smallint, "uint16" integer, "int32" integer, "uint32" bigint, "int64" bigint, "uint64" decimal, "float32" real, "float64" double precision, "decimal" decimal(10,10), "byte_slice" bytea, "byte_array" bytea, "string" text DEFAULT 'D''Angelo', "varchar" varchar(500), "time" timestamptz DEFAULT now(), "not_null" bigint NOT NULL, "unique" bigint UNIQUE, "null_bool" boolean, "null_float64" double precision, "null_int64" bigint, "null_string" text, "slice" jsonb, "slice_array" bigint[], "map" jsonb, "struct" jsonb, PRIMARY KEY ("id"))`))
- })
-
- It("creates new table without primary key", func() {
- q := NewQuery(nil, &CreateTableWithoutPKModel{})
-
- b, err := createTableQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`CREATE TABLE "create_table_without_pk_models" ("string" text)`))
- })
-
- It("creates new table with Varchar=255", func() {
- q := NewQuery(nil, &CreateTableWithoutPKModel{})
-
- opt := &CreateTableOptions{Varchar: 255}
- b, err := createTableQuery{q: q, opt: opt}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`CREATE TABLE "create_table_without_pk_models" ("string" varchar(255))`))
- })
-})
diff --git a/vendor/github.com/go-pg/pg/orm/delete.go b/vendor/github.com/go-pg/pg/orm/delete.go
deleted file mode 100644
index 1a98865..0000000
--- a/vendor/github.com/go-pg/pg/orm/delete.go
+++ /dev/null
@@ -1,61 +0,0 @@
-package orm
-
-import "github.com/go-pg/pg/internal"
-
-func Delete(db DB, model interface{}) error {
- res, err := NewQuery(db, model).Delete()
- if err != nil {
- return err
- }
- return internal.AssertOneRow(res.RowsAffected())
-}
-
-type deleteQuery struct {
- q *Query
-}
-
-var _ QueryAppender = (*deleteQuery)(nil)
-
-func (q deleteQuery) Copy() QueryAppender {
- return deleteQuery{
- q: q.q.Copy(),
- }
-}
-
-func (q deleteQuery) Query() *Query {
- return q.q
-}
-
-func (q deleteQuery) AppendQuery(b []byte) ([]byte, error) {
- if q.q.stickyErr != nil {
- return nil, q.q.stickyErr
- }
-
- var err error
-
- if len(q.q.with) > 0 {
- b, err = q.q.appendWith(b)
- if err != nil {
- return nil, err
- }
- }
-
- b = append(b, "DELETE FROM "...)
- b = q.q.appendFirstTableWithAlias(b)
-
- if q.q.hasOtherTables() {
- b = append(b, " USING "...)
- b = q.q.appendOtherTables(b)
- }
-
- b, err = q.q.mustAppendWhere(b)
- if err != nil {
- return nil, err
- }
-
- if len(q.q.returning) > 0 {
- b = q.q.appendReturning(b)
- }
-
- return b, nil
-}
diff --git a/vendor/github.com/go-pg/pg/orm/delete_test.go b/vendor/github.com/go-pg/pg/orm/delete_test.go
deleted file mode 100644
index 66d8379..0000000
--- a/vendor/github.com/go-pg/pg/orm/delete_test.go
+++ /dev/null
@@ -1,22 +0,0 @@
-package orm
-
-import (
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-)
-
-type DeleteTest struct{}
-
-var _ = Describe("Delete", func() {
- It("supports WITH", func() {
- q := NewQuery(nil, &DeleteTest{}).
- WrapWith("wrapper").
- Model(&DeleteTest{}).
- Table("wrapper").
- Where("delete_test.id = wrapper.id")
-
- b, err := deleteQuery{q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`WITH "wrapper" AS (SELECT FROM "delete_tests" AS "delete_test") DELETE FROM "delete_tests" AS "delete_test" USING "wrapper" WHERE (delete_test.id = wrapper.id)`))
- })
-})
diff --git a/vendor/github.com/go-pg/pg/orm/drop_table.go b/vendor/github.com/go-pg/pg/orm/drop_table.go
deleted file mode 100644
index b268783..0000000
--- a/vendor/github.com/go-pg/pg/orm/drop_table.go
+++ /dev/null
@@ -1,45 +0,0 @@
-package orm
-
-import "errors"
-
-type DropTableOptions struct {
- IfExists bool
- Cascade bool
-}
-
-func DropTable(db DB, model interface{}, opt *DropTableOptions) (Result, error) {
- return NewQuery(db, model).DropTable(opt)
-}
-
-type dropTableQuery struct {
- q *Query
- opt *DropTableOptions
-}
-
-func (q dropTableQuery) Copy() QueryAppender {
- return q
-}
-
-func (q dropTableQuery) Query() *Query {
- return q.q
-}
-
-func (q dropTableQuery) AppendQuery(b []byte) ([]byte, error) {
- if q.q.stickyErr != nil {
- return nil, q.q.stickyErr
- }
- if q.q.model == nil {
- return nil, errors.New("pg: Model is nil")
- }
-
- b = append(b, "DROP TABLE "...)
- if q.opt != nil && q.opt.IfExists {
- b = append(b, "IF EXISTS "...)
- }
- b = q.q.appendTableName(b)
- if q.opt != nil && q.opt.Cascade {
- b = append(b, " CASCADE"...)
- }
-
- return b, nil
-}
diff --git a/vendor/github.com/go-pg/pg/orm/drop_table_test.go b/vendor/github.com/go-pg/pg/orm/drop_table_test.go
deleted file mode 100644
index 269d8d0..0000000
--- a/vendor/github.com/go-pg/pg/orm/drop_table_test.go
+++ /dev/null
@@ -1,29 +0,0 @@
-package orm
-
-import (
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-)
-
-type DropTableModel struct{}
-
-var _ = Describe("CreateTable", func() {
- It("drops table", func() {
- q := NewQuery(nil, &DropTableModel{})
-
- b, err := dropTableQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`DROP TABLE "drop_table_models"`))
- })
-
- It("drops table if exists", func() {
- q := NewQuery(nil, &DropTableModel{})
-
- b, err := dropTableQuery{
- q: q,
- opt: &DropTableOptions{IfExists: true},
- }.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`DROP TABLE IF EXISTS "drop_table_models"`))
- })
-})
diff --git a/vendor/github.com/go-pg/pg/orm/field.go b/vendor/github.com/go-pg/pg/orm/field.go
deleted file mode 100644
index 71f5ebd..0000000
--- a/vendor/github.com/go-pg/pg/orm/field.go
+++ /dev/null
@@ -1,95 +0,0 @@
-package orm
-
-import (
- "reflect"
-
- "github.com/go-pg/pg/types"
-)
-
-const (
- PrimaryKeyFlag = uint8(1) << iota
- ForeignKeyFlag
- NotNullFlag
- UniqueFlag
- ArrayFlag
- customTypeFlag
-)
-
-type Field struct {
- Type reflect.Type
-
- GoName string // struct field name, e.g. Id
- SQLName string // SQL name, .e.g. id
- Column types.Q // escaped SQL name, e.g. "id"
- SQLType string
- Index []int
- Default types.Q
-
- flags uint8
-
- append types.AppenderFunc
- scan types.ScannerFunc
-
- isZero func(reflect.Value) bool
-}
-
-func (f *Field) Copy() *Field {
- copy := *f
- copy.Index = copy.Index[:len(f.Index):len(f.Index)]
- return ©
-}
-
-func (f *Field) SetFlag(flag uint8) {
- f.flags |= flag
-}
-
-func (f *Field) HasFlag(flag uint8) bool {
- return f.flags&flag != 0
-}
-
-func (f *Field) Value(strct reflect.Value) reflect.Value {
- return strct.FieldByIndex(f.Index)
-}
-
-func (f *Field) IsZero(strct reflect.Value) bool {
- fv := f.Value(strct)
- return f.isZero(fv)
-}
-
-func (f *Field) OmitZero(strct reflect.Value) bool {
- return !f.HasFlag(NotNullFlag) && f.isZero(f.Value(strct))
-}
-
-func (f *Field) AppendValue(b []byte, strct reflect.Value, quote int) []byte {
- fv := f.Value(strct)
- if !f.HasFlag(NotNullFlag) && f.isZero(fv) {
- return types.AppendNull(b, quote)
- }
- return f.append(b, fv, quote)
-}
-
-func (f *Field) ScanValue(strct reflect.Value, b []byte) error {
- fv := fieldByIndex(strct, f.Index)
- return f.scan(fv, b)
-}
-
-type Method struct {
- Index int
-
- flags int8
-
- appender func([]byte, reflect.Value, int) []byte
-}
-
-func (m *Method) Has(flag int8) bool {
- return m.flags&flag != 0
-}
-
-func (m *Method) Value(strct reflect.Value) reflect.Value {
- return strct.Method(m.Index).Call(nil)[0]
-}
-
-func (m *Method) AppendValue(dst []byte, strct reflect.Value, quote int) []byte {
- mv := m.Value(strct)
- return m.appender(dst, mv, quote)
-}
diff --git a/vendor/github.com/go-pg/pg/orm/format.go b/vendor/github.com/go-pg/pg/orm/format.go
deleted file mode 100644
index 4cd2a61..0000000
--- a/vendor/github.com/go-pg/pg/orm/format.go
+++ /dev/null
@@ -1,281 +0,0 @@
-package orm
-
-import (
- "bytes"
- "fmt"
- "sort"
- "strconv"
- "strings"
-
- "github.com/go-pg/pg/internal/parser"
- "github.com/go-pg/pg/types"
-)
-
-var formatter Formatter
-
-type FormatAppender interface {
- AppendFormat([]byte, QueryFormatter) []byte
-}
-
-type sepFormatAppender interface {
- FormatAppender
- AppendSep([]byte) []byte
-}
-
-//------------------------------------------------------------------------------
-
-type queryParamsAppender struct {
- query string
- params []interface{}
-}
-
-var _ FormatAppender = (*queryParamsAppender)(nil)
-
-func Q(query string, params ...interface{}) queryParamsAppender {
- return queryParamsAppender{query, params}
-}
-
-func (q queryParamsAppender) AppendFormat(b []byte, f QueryFormatter) []byte {
- return f.FormatQuery(b, q.query, q.params...)
-}
-
-func (q queryParamsAppender) AppendValue(b []byte, quote int) ([]byte, error) {
- return q.AppendFormat(b, formatter), nil
-}
-
-//------------------------------------------------------------------------------
-
-type whereGroupAppender struct {
- sep string
- where []sepFormatAppender
-}
-
-var _ FormatAppender = (*whereAppender)(nil)
-var _ sepFormatAppender = (*whereAppender)(nil)
-
-func (q whereGroupAppender) AppendSep(b []byte) []byte {
- return append(b, q.sep...)
-}
-
-func (q whereGroupAppender) AppendFormat(b []byte, f QueryFormatter) []byte {
- b = append(b, '(')
- for i, app := range q.where {
- if i > 0 {
- b = append(b, ' ')
- b = app.AppendSep(b)
- b = append(b, ' ')
- }
- b = app.AppendFormat(b, f)
- }
- b = append(b, ')')
- return b
-}
-
-//------------------------------------------------------------------------------
-
-type whereAppender struct {
- sep string
- where string
- params []interface{}
-}
-
-var _ FormatAppender = (*whereAppender)(nil)
-var _ sepFormatAppender = (*whereAppender)(nil)
-
-func (q whereAppender) AppendSep(b []byte) []byte {
- return append(b, q.sep...)
-}
-
-func (q whereAppender) AppendFormat(b []byte, f QueryFormatter) []byte {
- b = append(b, '(')
- b = f.FormatQuery(b, q.where, q.params...)
- b = append(b, ')')
- return b
-}
-
-//------------------------------------------------------------------------------
-
-type fieldAppender struct {
- field string
-}
-
-var _ FormatAppender = (*fieldAppender)(nil)
-
-func (a fieldAppender) AppendFormat(b []byte, f QueryFormatter) []byte {
- return types.AppendField(b, a.field, 1)
-}
-
-//------------------------------------------------------------------------------
-
-type Formatter struct {
- namedParams map[string]interface{}
-}
-
-func (f Formatter) String() string {
- if len(f.namedParams) == 0 {
- return ""
- }
-
- var keys []string
- for k, _ := range f.namedParams {
- keys = append(keys, k)
- }
- sort.Strings(keys)
-
- var ss []string
- for _, k := range keys {
- ss = append(ss, fmt.Sprintf("%s=%v", k, f.namedParams[k]))
- }
- return " " + strings.Join(ss, " ")
-}
-
-func (f Formatter) copy() Formatter {
- var cp Formatter
- for param, value := range f.namedParams {
- cp.SetParam(param, value)
- }
- return cp
-}
-
-func (f *Formatter) SetParam(param string, value interface{}) {
- if f.namedParams == nil {
- f.namedParams = make(map[string]interface{})
- }
- f.namedParams[param] = value
-}
-
-func (f *Formatter) WithParam(param string, value interface{}) Formatter {
- cp := f.copy()
- cp.SetParam(param, value)
- return cp
-}
-
-func (f Formatter) Append(dst []byte, src string, params ...interface{}) []byte {
- if (params == nil && f.namedParams == nil) || strings.IndexByte(src, '?') == -1 {
- return append(dst, src...)
- }
- return f.append(dst, parser.NewString(src), params)
-}
-
-func (f Formatter) AppendBytes(dst, src []byte, params ...interface{}) []byte {
- if (params == nil && f.namedParams == nil) || bytes.IndexByte(src, '?') == -1 {
- return append(dst, src...)
- }
- return f.append(dst, parser.New(src), params)
-}
-
-func (f Formatter) FormatQuery(dst []byte, query string, params ...interface{}) []byte {
- return f.Append(dst, query, params...)
-}
-
-func (f Formatter) append(dst []byte, p *parser.Parser, params []interface{}) []byte {
- var paramsIndex int
- var namedParamsOnce bool
- var tableParams *tableParams
- var model tableModel
-
- if len(params) > 0 {
- var ok bool
- model, ok = params[len(params)-1].(tableModel)
- if ok {
- params = params[:len(params)-1]
- }
- }
-
- for p.Valid() {
- b, ok := p.ReadSep('?')
- if !ok {
- dst = append(dst, b...)
- continue
- }
- if len(b) > 0 && b[len(b)-1] == '\\' {
- dst = append(dst, b[:len(b)-1]...)
- dst = append(dst, '?')
- continue
- }
- dst = append(dst, b...)
-
- if id, numeric := p.ReadIdentifier(); id != "" {
- if numeric {
- idx, err := strconv.Atoi(id)
- if err != nil {
- goto restore_param
- }
-
- if idx >= len(params) {
- goto restore_param
- }
-
- dst = f.appendParam(dst, params[idx])
- continue
- }
-
- if f.namedParams != nil {
- if param, ok := f.namedParams[id]; ok {
- dst = f.appendParam(dst, param)
- continue
- }
- }
-
- if !namedParamsOnce && len(params) > 0 {
- namedParamsOnce = true
- if len(params) > 0 {
- tableParams, ok = newTableParams(params[len(params)-1])
- if ok {
- params = params[:len(params)-1]
- }
- }
- }
-
- if tableParams != nil {
- dst, ok = tableParams.AppendParam(dst, f, id)
- if ok {
- continue
- }
- }
-
- if model != nil {
- dst, ok = model.AppendParam(dst, f, id)
- if ok {
- continue
- }
- }
-
- restore_param:
- dst = append(dst, '?')
- dst = append(dst, id...)
- continue
- }
-
- if paramsIndex >= len(params) {
- dst = append(dst, '?')
- continue
- }
-
- param := params[paramsIndex]
- paramsIndex++
-
- dst = f.appendParam(dst, param)
- }
-
- return dst
-}
-
-type queryAppender interface {
- AppendQuery(dst []byte) ([]byte, error)
-}
-
-func (f Formatter) appendParam(b []byte, param interface{}) []byte {
- switch param := param.(type) {
- case queryAppender:
- bb, err := param.AppendQuery(b)
- if err != nil {
- return types.AppendError(b, err)
- }
- return bb
- case FormatAppender:
- return param.AppendFormat(b, f)
- default:
- return types.Append(b, param, 1)
- }
-}
diff --git a/vendor/github.com/go-pg/pg/orm/format_test.go b/vendor/github.com/go-pg/pg/orm/format_test.go
deleted file mode 100644
index 4a87bdf..0000000
--- a/vendor/github.com/go-pg/pg/orm/format_test.go
+++ /dev/null
@@ -1,203 +0,0 @@
-package orm_test
-
-import (
- "database/sql/driver"
- "errors"
- "fmt"
- "math"
- "testing"
-
- "github.com/go-pg/pg/orm"
- "github.com/go-pg/pg/types"
-)
-
-type ValuerError string
-
-func (e ValuerError) Value() (driver.Value, error) {
- return nil, errors.New(string(e))
-}
-
-type StructFormatter struct {
- tableName struct{} `sql:"my_name,alias:my_alias"`
-
- String string
- NotNull string `sql:",notnull"`
- Iface interface{}
-}
-
-func (StructFormatter) Method() string {
- return "method_value"
-}
-
-func (StructFormatter) MethodParam() types.Q {
- return types.Q("?string")
-}
-
-func (StructFormatter) MethodWithArgs(string) string {
- return "method_value"
-}
-
-func (StructFormatter) MethodWithCompositeReturn() (string, string) {
- return "method_value1", "method_value2"
-}
-
-type EmbeddedStructFormatter struct {
- *StructFormatter
-}
-
-func (EmbeddedStructFormatter) Method2() string {
- return "method_value2"
-}
-
-type params []interface{}
-type paramsMap map[string]interface{}
-
-type formatTest struct {
- q string
- params params
- paramsMap paramsMap
- wanted string
-}
-
-var (
- structv = &StructFormatter{
- String: "string_value",
- Iface: "iface_value",
- }
- embeddedStructv = &EmbeddedStructFormatter{structv}
-)
-
-var formatTests = []formatTest{
- {q: "?", params: params{ValuerError("error")}, wanted: "?!(error)"},
-
- {q: "?", wanted: "?"},
- {q: "? ? ?", params: params{"foo", "bar"}, wanted: "'foo' 'bar' ?"},
- {q: "?0 ?1", params: params{"foo", "bar"}, wanted: "'foo' 'bar'"},
- {q: "?0 ?1 ?2", params: params{"foo", "bar"}, wanted: "'foo' 'bar' ?2"},
- {q: "?0 ?1 ?0", params: params{"foo", "bar"}, wanted: "'foo' 'bar' 'foo'"},
-
- {q: "one ?foo two", wanted: "one ?foo two"},
- {q: "one ?foo two", params: params{structv}, wanted: "one ?foo two"},
- {q: "one ?MethodWithArgs two", params: params{structv}, wanted: "one ?MethodWithArgs two"},
- {q: "one ?MethodWithCompositeReturn two", params: params{structv}, wanted: "one ?MethodWithCompositeReturn two"},
-
- {q: "?", params: params{uint64(math.MaxUint64)}, wanted: "18446744073709551615"},
- {q: "?", params: params{orm.Q("query")}, wanted: "query"},
- {q: "?", params: params{types.F("field")}, wanted: `"field"`},
- {q: "?", params: params{structv}, wanted: `'{"String":"string_value","NotNull":"","Iface":"iface_value"}'`},
-
- {q: `\? ?`, params: params{1}, wanted: "? 1"},
- {q: `?`, params: params{types.Q(`\?`)}, wanted: `\?`},
- {q: `?`, params: params{types.Q(`\\?`)}, wanted: `\\?`},
- {q: `?`, params: params{types.Q(`\?param`)}, wanted: `\?param`},
-
- {q: "?string", params: params{structv}, wanted: `'string_value'`},
- {q: "?iface", params: params{structv}, wanted: `'iface_value'`},
- {q: "?string", params: params{&StructFormatter{}}, wanted: `NULL`},
- {
- q: "? ?string ?",
- params: params{"one", "two", structv},
- wanted: "'one' 'string_value' 'two'",
- },
- {
- q: "?string ?Method",
- params: params{structv},
- wanted: "'string_value' 'method_value'",
- },
- {
- q: "?string ?Method ?Method2",
- params: params{embeddedStructv},
- wanted: "'string_value' 'method_value' 'method_value2'",
- },
-
- {
- q: "?string",
- params: params{structv},
- paramsMap: paramsMap{"string": "my_value"},
- wanted: "'my_value'",
- },
- {
- q: "?",
- params: params{types.Q("?string")},
- paramsMap: paramsMap{"string": "my_value"},
- wanted: "?string",
- },
- {
- q: "?",
- params: params{types.F("?string")},
- paramsMap: paramsMap{"string": types.Q("my_value")},
- wanted: `"?string"`,
- },
- {
- q: "?",
- params: params{orm.Q("?string")},
- paramsMap: paramsMap{"string": "my_value"},
- wanted: "'my_value'",
- },
- {
- q: "?MethodParam",
- params: params{structv},
- paramsMap: paramsMap{"string": "my_value"},
- wanted: "?string",
- },
-}
-
-func TestFormatQuery(t *testing.T) {
- for _, test := range formatTests {
- var f orm.Formatter
- for k, v := range test.paramsMap {
- f.SetParam(k, v)
- }
-
- got := f.Append(nil, test.q, test.params...)
- if string(got) != test.wanted {
- t.Fatalf(
- "got %q, wanted %q (q=%q params=%v paramsMap=%v)",
- got, test.wanted, test.q, test.params, test.paramsMap,
- )
- }
- }
-}
-
-func BenchmarkFormatQueryWithoutParams(b *testing.B) {
- for i := 0; i < b.N; i++ {
- _ = orm.Q("SELECT * FROM my_table WHERE id = 1")
- }
-}
-
-func BenchmarkFormatQuery1Param(b *testing.B) {
- for i := 0; i < b.N; i++ {
- _ = orm.Q("SELECT * FROM my_table WHERE id = ?", 1)
- }
-}
-
-func BenchmarkFormatQuery10Params(b *testing.B) {
- for i := 0; i < b.N; i++ {
- _ = orm.Q(
- "SELECT * FROM my_table WHERE id IN (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
- )
- }
-}
-
-func BenchmarkFormatQuerySprintf(b *testing.B) {
- for i := 0; i < b.N; i++ {
- _ = fmt.Sprintf("SELECT * FROM my_table WHERE id = %d", 1)
- }
-}
-
-func BenchmarkFormatQueryStructParam(b *testing.B) {
- param := StructFormatter{
- String: "1",
- }
- for i := 0; i < b.N; i++ {
- _ = orm.Q("SELECT * FROM my_table WHERE id = ?string", param)
- }
-}
-
-func BenchmarkFormatQueryStructMethod(b *testing.B) {
- param := StructFormatter{}
- for i := 0; i < b.N; i++ {
- _ = orm.Q("SELECT * FROM my_table WHERE id = ?Method", ¶m)
- }
-}
diff --git a/vendor/github.com/go-pg/pg/orm/hook.go b/vendor/github.com/go-pg/pg/orm/hook.go
deleted file mode 100644
index 9e3d6a6..0000000
--- a/vendor/github.com/go-pg/pg/orm/hook.go
+++ /dev/null
@@ -1,180 +0,0 @@
-package orm
-
-import "reflect"
-
-const (
- AfterQueryHookFlag = uint8(1) << iota
- AfterSelectHookFlag
- BeforeInsertHookFlag
- AfterInsertHookFlag
- BeforeUpdateHookFlag
- AfterUpdateHookFlag
- BeforeDeleteHookFlag
- AfterDeleteHookFlag
-)
-
-type hookStubs struct{}
-
-func (hookStubs) Init() error {
- return nil
-}
-
-func (hookStubs) AfterQuery(_ DB) error {
- return nil
-}
-
-func (hookStubs) AfterSelect(_ DB) error {
- return nil
-}
-
-func (hookStubs) BeforeInsert(_ DB) error {
- return nil
-}
-
-func (hookStubs) AfterInsert(_ DB) error {
- return nil
-}
-
-func (hookStubs) BeforeUpdate(_ DB) error {
- return nil
-}
-
-func (hookStubs) AfterUpdate(_ DB) error {
- return nil
-}
-
-func (hookStubs) BeforeDelete(_ DB) error {
- return nil
-}
-
-func (hookStubs) AfterDelete(_ DB) error {
- return nil
-}
-
-func callHookSlice(slice reflect.Value, ptr bool, db DB, hook func(reflect.Value, DB) error) error {
- var firstErr error
- for i := 0; i < slice.Len(); i++ {
- var err error
- if ptr {
- err = hook(slice.Index(i), db)
- } else {
- err = hook(slice.Index(i).Addr(), db)
- }
- if err != nil && firstErr == nil {
- firstErr = err
- }
- }
- return firstErr
-}
-
-type afterQueryHook interface {
- AfterQuery(db DB) error
-}
-
-var afterQueryHookType = reflect.TypeOf((*afterQueryHook)(nil)).Elem()
-
-func callAfterQueryHook(v reflect.Value, db DB) error {
- return v.Interface().(afterQueryHook).AfterQuery(db)
-}
-
-func callAfterQueryHookSlice(slice reflect.Value, ptr bool, db DB) error {
- return callHookSlice(slice, ptr, db, callAfterQueryHook)
-}
-
-type afterSelectHook interface {
- AfterSelect(db DB) error
-}
-
-var afterSelectHookType = reflect.TypeOf((*afterSelectHook)(nil)).Elem()
-
-func callAfterSelectHook(v reflect.Value, db DB) error {
- return v.Interface().(afterSelectHook).AfterSelect(db)
-}
-
-func callAfterSelectHookSlice(slice reflect.Value, ptr bool, db DB) error {
- return callHookSlice(slice, ptr, db, callAfterSelectHook)
-}
-
-type beforeInsertHook interface {
- BeforeInsert(db DB) error
-}
-
-var beforeInsertHookType = reflect.TypeOf((*beforeInsertHook)(nil)).Elem()
-
-func callBeforeInsertHook(v reflect.Value, db DB) error {
- return v.Interface().(beforeInsertHook).BeforeInsert(db)
-}
-
-func callBeforeInsertHookSlice(slice reflect.Value, ptr bool, db DB) error {
- return callHookSlice(slice, ptr, db, callBeforeInsertHook)
-}
-
-type afterInsertHook interface {
- AfterInsert(db DB) error
-}
-
-var afterInsertHookType = reflect.TypeOf((*afterInsertHook)(nil)).Elem()
-
-func callAfterInsertHook(v reflect.Value, db DB) error {
- return v.Interface().(afterInsertHook).AfterInsert(db)
-}
-
-func callAfterInsertHookSlice(slice reflect.Value, ptr bool, db DB) error {
- return callHookSlice(slice, ptr, db, callAfterInsertHook)
-}
-
-type beforeUpdateHook interface {
- BeforeUpdate(db DB) error
-}
-
-var beforeUpdateHookType = reflect.TypeOf((*beforeUpdateHook)(nil)).Elem()
-
-func callBeforeUpdateHook(v reflect.Value, db DB) error {
- return v.Interface().(beforeUpdateHook).BeforeUpdate(db)
-}
-
-func callBeforeUpdateHookSlice(slice reflect.Value, ptr bool, db DB) error {
- return callHookSlice(slice, ptr, db, callBeforeUpdateHook)
-}
-
-type afterUpdateHook interface {
- AfterUpdate(db DB) error
-}
-
-var afterUpdateHookType = reflect.TypeOf((*afterUpdateHook)(nil)).Elem()
-
-func callAfterUpdateHook(v reflect.Value, db DB) error {
- return v.Interface().(afterUpdateHook).AfterUpdate(db)
-}
-
-func callAfterUpdateHookSlice(slice reflect.Value, ptr bool, db DB) error {
- return callHookSlice(slice, ptr, db, callAfterUpdateHook)
-}
-
-type beforeDeleteHook interface {
- BeforeDelete(db DB) error
-}
-
-var beforeDeleteHookType = reflect.TypeOf((*beforeDeleteHook)(nil)).Elem()
-
-func callBeforeDeleteHook(v reflect.Value, db DB) error {
- return v.Interface().(beforeDeleteHook).BeforeDelete(db)
-}
-
-func callBeforeDeleteHookSlice(slice reflect.Value, ptr bool, db DB) error {
- return callHookSlice(slice, ptr, db, callBeforeDeleteHook)
-}
-
-type afterDeleteHook interface {
- AfterDelete(db DB) error
-}
-
-var afterDeleteHookType = reflect.TypeOf((*afterDeleteHook)(nil)).Elem()
-
-func callAfterDeleteHook(v reflect.Value, db DB) error {
- return v.Interface().(afterDeleteHook).AfterDelete(db)
-}
-
-func callAfterDeleteHookSlice(slice reflect.Value, ptr bool, db DB) error {
- return callHookSlice(slice, ptr, db, callAfterDeleteHook)
-}
diff --git a/vendor/github.com/go-pg/pg/orm/inflection.go b/vendor/github.com/go-pg/pg/orm/inflection.go
deleted file mode 100644
index 9ff8bd6..0000000
--- a/vendor/github.com/go-pg/pg/orm/inflection.go
+++ /dev/null
@@ -1,17 +0,0 @@
-package orm
-
-import (
- "github.com/jinzhu/inflection"
-)
-
-var tableNameInflector func(string) string
-
-func init() {
- SetTableNameInflector(inflection.Plural)
-}
-
-// SetTableNameInflector overrides the default func that pluralizes
-// model name to get table name, e.g. my_article becomes my_articles.
-func SetTableNameInflector(fn func(string) string) {
- tableNameInflector = fn
-}
diff --git a/vendor/github.com/go-pg/pg/orm/insert.go b/vendor/github.com/go-pg/pg/orm/insert.go
deleted file mode 100644
index c5b5534..0000000
--- a/vendor/github.com/go-pg/pg/orm/insert.go
+++ /dev/null
@@ -1,144 +0,0 @@
-package orm
-
-import (
- "errors"
- "reflect"
-)
-
-func Insert(db DB, v ...interface{}) error {
- _, err := NewQuery(db, v...).Insert()
- return err
-}
-
-type insertQuery struct {
- q *Query
- returningFields []*Field
-}
-
-var _ QueryAppender = (*insertQuery)(nil)
-
-func (q insertQuery) Copy() QueryAppender {
- return insertQuery{
- q: q.q.Copy(),
- }
-}
-
-func (q insertQuery) Query() *Query {
- return q.q
-}
-
-func (q insertQuery) AppendQuery(b []byte) ([]byte, error) {
- if q.q.stickyErr != nil {
- return nil, q.q.stickyErr
- }
- if q.q.model == nil {
- return nil, errors.New("pg: Model is nil")
- }
-
- table := q.q.model.Table()
- value := q.q.model.Value()
- var err error
-
- if len(q.q.with) > 0 {
- b, err = q.q.appendWith(b)
- if err != nil {
- return nil, err
- }
- }
-
- b = append(b, "INSERT INTO "...)
- if q.q.onConflict != nil {
- b = q.q.appendFirstTableWithAlias(b)
- } else {
- b = q.q.appendFirstTable(b)
- }
-
- if q.q.hasOtherTables() && q.q.columns != nil {
- b = append(b, " ("...)
- b = q.q.appendColumns(b)
- b = append(b, ")"...)
- b = append(b, " SELECT * FROM "...)
- b = q.q.appendOtherTables(b)
- } else {
- fields, err := q.q.getFields()
- if err != nil {
- return nil, err
- }
-
- if len(fields) == 0 {
- fields = table.Fields
- }
-
- b = append(b, " ("...)
- b = appendColumns(b, fields)
- b = append(b, ") VALUES ("...)
- if value.Kind() == reflect.Struct {
- b = q.appendValues(b, fields, value)
- } else {
- for i := 0; i < value.Len(); i++ {
- el := value.Index(i)
- if el.Kind() == reflect.Interface {
- el = el.Elem()
- }
- b = q.appendValues(b, fields, reflect.Indirect(el))
- if i != value.Len()-1 {
- b = append(b, "), ("...)
- }
- }
- }
- b = append(b, ")"...)
- }
-
- if q.q.onConflict != nil {
- b = append(b, " ON CONFLICT "...)
- b = q.q.onConflict.AppendFormat(b, q.q)
-
- if q.q.onConflictDoUpdate() {
- if len(q.q.set) > 0 {
- b = q.q.appendSet(b)
- }
-
- if len(q.q.updWhere) > 0 {
- b = q.q.appendUpdWhere(b)
- }
- }
- }
-
- if len(q.q.returning) > 0 {
- b = q.q.appendReturning(b)
- } else if len(q.returningFields) > 0 {
- b = q.appendReturningFields(b, q.returningFields)
- }
-
- return b, nil
-}
-
-func (q *insertQuery) appendValues(b []byte, fields []*Field, v reflect.Value) []byte {
- for i, f := range fields {
- if i > 0 {
- b = append(b, ", "...)
- }
- if f.OmitZero(v) {
- b = append(b, "DEFAULT"...)
- q.addReturningField(f)
- } else {
- b = f.AppendValue(b, v, 1)
- }
- }
- return b
-}
-
-func (ins *insertQuery) addReturningField(field *Field) {
- for _, f := range ins.returningFields {
- if f == field {
- return
- }
- }
- ins.returningFields = append(ins.returningFields, field)
-}
-
-func (insertQuery) appendReturningFields(b []byte, fields []*Field) []byte {
- b = append(b, " RETURNING "...)
- b = appendColumns(b, fields)
- return b
-}
diff --git a/vendor/github.com/go-pg/pg/orm/insert_test.go b/vendor/github.com/go-pg/pg/orm/insert_test.go
deleted file mode 100644
index 91e05d6..0000000
--- a/vendor/github.com/go-pg/pg/orm/insert_test.go
+++ /dev/null
@@ -1,140 +0,0 @@
-package orm
-
-import (
- "github.com/go-pg/pg/types"
-
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-)
-
-type InsertTest struct {
- Id int
- Value string
-}
-
-type EmbeddingTest struct {
- tableName struct{} `sql:"name"`
-
- Id int
- Field int
-}
-
-type EmbeddedInsertTest struct {
- tableName struct{} `sql:"my_name"`
- EmbeddingTest
- Field2 int
-}
-
-type OverrideInsertTest struct {
- EmbeddingTest `pg:",override"`
- Field2 int
-}
-
-type InsertNullTest struct {
- F1 int
- F2 int `sql:",notnull"`
- F3 int `sql:",pk"`
- F4 int `sql:",pk,notnull"`
-}
-
-type InsertQTest struct {
- Geo types.Q
- Func types.ValueAppender
-}
-
-var _ = Describe("Insert", func() {
- It("supports Column", func() {
- model := &InsertTest{
- Id: 1,
- Value: "hello",
- }
- q := NewQuery(nil, model).Column("id")
-
- b, err := insertQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`INSERT INTO "insert_tests" ("id") VALUES (1)`))
- })
-
- It("multi inserts", func() {
- q := NewQuery(nil, &InsertTest{
- Id: 1,
- Value: "hello",
- }, &InsertTest{
- Id: 2,
- })
-
- b, err := insertQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`INSERT INTO "insert_tests" ("id", "value") VALUES (1, 'hello'), (2, DEFAULT) RETURNING "value"`))
- })
-
- It("supports ON CONFLICT DO UPDATE", func() {
- q := NewQuery(nil, &InsertTest{}).
- Where("1 = 1").
- OnConflict("(unq1) DO UPDATE").
- Set("count1 = count1 + 1").
- Where("2 = 2")
-
- b, err := insertQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`INSERT INTO "insert_tests" AS "insert_test" ("id", "value") VALUES (DEFAULT, DEFAULT) ON CONFLICT (unq1) DO UPDATE SET count1 = count1 + 1 WHERE (2 = 2) RETURNING "id", "value"`))
- })
-
- It("supports ON CONFLICT DO NOTHING", func() {
- q := NewQuery(nil, &InsertTest{}).
- OnConflict("(unq1) DO NOTHING").
- Set("count1 = count1 + 1").
- Where("cond1 IS TRUE")
-
- b, err := insertQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`INSERT INTO "insert_tests" AS "insert_test" ("id", "value") VALUES (DEFAULT, DEFAULT) ON CONFLICT (unq1) DO NOTHING RETURNING "id", "value"`))
- })
-
- It("supports custom table name on embedded struct", func() {
- q := NewQuery(nil, &EmbeddedInsertTest{})
-
- b, err := insertQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`INSERT INTO my_name ("id", "field", "field2") VALUES (DEFAULT, DEFAULT, DEFAULT) RETURNING "id", "field", "field2"`))
- })
-
- It("overrides table name with embedded struct", func() {
- q := NewQuery(nil, &OverrideInsertTest{})
-
- b, err := insertQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`INSERT INTO name ("id", "field", "field2") VALUES (DEFAULT, DEFAULT, DEFAULT) RETURNING "id", "field", "field2"`))
- })
-
- It("supports notnull", func() {
- q := NewQuery(nil, &InsertNullTest{})
-
- b, err := insertQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`INSERT INTO "insert_null_tests" ("f1", "f2", "f3", "f4") VALUES (DEFAULT, 0, DEFAULT, 0) RETURNING "f1", "f3"`))
- })
-
- It("inserts types.Q", func() {
- q := NewQuery(nil, &InsertQTest{
- Geo: types.Q("ST_GeomFromText('POLYGON((75.150000 29.530000, 77.000000 29.000000, 77.600000 29.500000, 75.150000 29.530000))')"),
- Func: Q("my_func(?)", "param"),
- })
-
- b, err := insertQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`INSERT INTO "insert_q_tests" ("geo", "func") VALUES (ST_GeomFromText('POLYGON((75.150000 29.530000, 77.000000 29.000000, 77.600000 29.500000, 75.150000 29.530000))'), my_func('param'))`))
- })
-
- It("supports FROM", func() {
- q := NewQuery(nil, &InsertTest{})
- q = q.WrapWith("data").
- TableExpr("dst").
- ColumnExpr("dst_col1, dst_col2").
- TableExpr("data")
-
- b, err := insertQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`WITH "data" AS (SELECT "insert_test"."id", "insert_test"."value" FROM "insert_tests" AS "insert_test") INSERT INTO dst (dst_col1, dst_col2) SELECT * FROM data`))
- })
-})
diff --git a/vendor/github.com/go-pg/pg/orm/join.go b/vendor/github.com/go-pg/pg/orm/join.go
deleted file mode 100644
index 59468c2..0000000
--- a/vendor/github.com/go-pg/pg/orm/join.go
+++ /dev/null
@@ -1,278 +0,0 @@
-package orm
-
-import (
- "github.com/go-pg/pg/internal"
- "github.com/go-pg/pg/types"
-)
-
-type join struct {
- Parent *join
- BaseModel tableModel
- JoinModel tableModel
- Rel *Relation
- ApplyQuery func(*Query) (*Query, error)
-
- Columns []string
-}
-
-func (j *join) Select(db DB) error {
- switch j.Rel.Type {
- case HasManyRelation:
- return j.selectMany(db)
- case Many2ManyRelation:
- return j.selectM2M(db)
- }
- panic("not reached")
-}
-
-func (j *join) selectMany(db DB) error {
- q, err := j.manyQuery(db)
- if err != nil {
- return err
- }
- return q.Select()
-}
-
-func (j *join) manyQuery(db DB) (*Query, error) {
- root := j.JoinModel.Root()
- index := j.JoinModel.ParentIndex()
-
- manyModel := newManyModel(j)
- q := NewQuery(db, manyModel)
- if j.ApplyQuery != nil {
- var err error
- q, err = j.ApplyQuery(q)
- if err != nil {
- return nil, err
- }
- }
-
- q.columns = append(q.columns, hasManyColumnsAppender{j})
-
- baseTable := j.BaseModel.Table()
- var where []byte
- where = append(where, "("...)
- where = columns(where, j.JoinModel.Table().Alias, "", j.Rel.FKs)
- where = append(where, ") IN ("...)
- where = appendChildValues(where, root, index, baseTable.PKs)
- where = append(where, ")"...)
- q = q.Where(internal.BytesToString(where))
-
- if j.Rel.Polymorphic {
- q = q.Where(
- `? IN (?, ?)`,
- types.F(j.Rel.BasePrefix+"type"),
- baseTable.ModelName, baseTable.TypeName,
- )
- }
-
- return q, nil
-}
-
-func (j *join) selectM2M(db DB) error {
- q, err := j.m2mQuery(db)
- if err != nil {
- return err
- }
- return q.Select()
-}
-
-func (j *join) m2mQuery(db DB) (*Query, error) {
- m2mModel := newM2MModel(j)
- q := NewQuery(db, m2mModel)
- if j.ApplyQuery != nil {
- var err error
- q, err = j.ApplyQuery(q)
- if err != nil {
- return nil, err
- }
- }
-
- q.columns = append(q.columns, hasManyColumnsAppender{j})
-
- index := j.JoinModel.ParentIndex()
- baseTable := j.BaseModel.Table()
- var join []byte
- join = append(join, "JOIN "...)
- if db != nil {
- join = db.FormatQuery(join, string(j.Rel.M2MTableName))
- } else {
- join = append(join, j.Rel.M2MTableName...)
- }
- join = append(join, " AS "...)
- join = append(join, j.Rel.M2MTableAlias...)
- join = append(join, " ON ("...)
- join = columns(join, j.Rel.M2MTableAlias, j.Rel.BasePrefix, baseTable.PKs)
- join = append(join, ") IN ("...)
- join = appendChildValues(join, j.BaseModel.Root(), index, baseTable.PKs)
- join = append(join, ")"...)
- q = q.Join(internal.BytesToString(join))
-
- joinAlias := j.JoinModel.Table().Alias
- for _, pk := range j.JoinModel.Table().PKs {
- q = q.Where(
- "?.? = ?.?",
- joinAlias, pk.Column,
- j.Rel.M2MTableAlias, types.F(j.Rel.JoinPrefix+pk.SQLName),
- )
- }
-
- return q, nil
-}
-
-func (j *join) hasParent() bool {
- if j.Parent != nil {
- switch j.Parent.Rel.Type {
- case HasOneRelation, BelongsToRelation:
- return true
- }
- }
- return false
-}
-
-func (j *join) appendAlias(b []byte) []byte {
- b = append(b, '"')
- b = appendAlias(b, j, true)
- b = append(b, '"')
- return b
-}
-
-func (j *join) appendAliasColumn(b []byte, column string) []byte {
- b = append(b, '"')
- b = appendAlias(b, j, true)
- b = append(b, "__"...)
- b = types.AppendField(b, column, 2)
- b = append(b, '"')
- return b
-}
-
-func (j *join) appendBaseAlias(b []byte) []byte {
- if j.hasParent() {
- b = append(b, '"')
- b = appendAlias(b, j.Parent, true)
- b = append(b, '"')
- return b
- }
- return append(b, j.BaseModel.Table().Alias...)
-}
-
-func appendAlias(b []byte, j *join, topLevel bool) []byte {
- if j.hasParent() {
- b = appendAlias(b, j.Parent, topLevel)
- topLevel = false
- }
- if !topLevel {
- b = append(b, "__"...)
- }
- b = append(b, j.Rel.Field.SQLName...)
- return b
-}
-
-func (j *join) appendHasOneColumns(b []byte) []byte {
- if j.Columns == nil {
- for i, f := range j.JoinModel.Table().Fields {
- if i > 0 {
- b = append(b, ", "...)
- }
- b = j.appendAlias(b)
- b = append(b, '.')
- b = append(b, f.Column...)
- b = append(b, " AS "...)
- b = j.appendAliasColumn(b, f.SQLName)
- }
- return b
- }
-
- for i, column := range j.Columns {
- if i > 0 {
- b = append(b, ", "...)
- }
- b = j.appendAlias(b)
- b = append(b, '.')
- b = types.AppendField(b, column, 1)
- b = append(b, " AS "...)
- b = j.appendAliasColumn(b, column)
- }
-
- return b
-}
-
-func (j *join) appendHasOneJoin(db DB, b []byte) []byte {
- b = append(b, "LEFT JOIN "...)
- if db != nil {
- b = db.FormatQuery(b, string(j.JoinModel.Table().Name))
- } else {
- b = append(b, j.JoinModel.Table().Name...)
- }
- b = append(b, " AS "...)
- b = j.appendAlias(b)
-
- b = append(b, " ON "...)
- if j.Rel.Type == HasOneRelation {
- joinTable := j.Rel.JoinTable
- for i, fk := range j.Rel.FKs {
- if i > 0 {
- b = append(b, " AND "...)
- }
- b = j.appendAlias(b)
- b = append(b, '.')
- b = append(b, joinTable.PKs[i].Column...)
- b = append(b, " = "...)
- b = j.appendBaseAlias(b)
- b = append(b, '.')
- b = append(b, fk.Column...)
- }
- } else {
- baseTable := j.BaseModel.Table()
- for i, fk := range j.Rel.FKs {
- if i > 0 {
- b = append(b, " AND "...)
- }
- b = j.appendAlias(b)
- b = append(b, '.')
- b = append(b, fk.Column...)
- b = append(b, " = "...)
- b = j.appendBaseAlias(b)
- b = append(b, '.')
- b = append(b, baseTable.PKs[i].Column...)
- }
- }
-
- return b
-}
-
-type hasManyColumnsAppender struct {
- *join
-}
-
-func (q hasManyColumnsAppender) AppendFormat(b []byte, f QueryFormatter) []byte {
- if q.Rel.M2MTableAlias != "" {
- b = append(b, q.Rel.M2MTableAlias...)
- b = append(b, ".*, "...)
- }
-
- joinTable := q.JoinModel.Table()
-
- if q.Columns == nil {
- for i, f := range joinTable.Fields {
- if i > 0 {
- b = append(b, ", "...)
- }
- b = append(b, joinTable.Alias...)
- b = append(b, '.')
- b = append(b, f.Column...)
- }
- return b
- }
-
- for i, column := range q.Columns {
- if i > 0 {
- b = append(b, ", "...)
- }
- b = append(b, joinTable.Alias...)
- b = append(b, '.')
- b = types.AppendField(b, column, 1)
- }
-
- return b
-}
diff --git a/vendor/github.com/go-pg/pg/orm/join_test.go b/vendor/github.com/go-pg/pg/orm/join_test.go
deleted file mode 100644
index 088084f..0000000
--- a/vendor/github.com/go-pg/pg/orm/join_test.go
+++ /dev/null
@@ -1,51 +0,0 @@
-package orm
-
-import (
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-)
-
-type JoinTest struct {
- tableName struct{} `sql:"JoinTest,alias:JoinTest"`
-
- Id int
-
- HasOne *HasOne
- HasOneId int
-
- BelongsTo *BelongsTo
-}
-
-type HasOne struct {
- tableName struct{} `sql:"HasOne,alias:HasOne"`
-
- Id int
-
- HasOne *HasOne
- HasOneId int
-}
-
-type BelongsTo struct {
- tableName struct{} `sql:"BelongsTo,alias:BelongsTo"`
-
- Id int
- JoinTestId int
-}
-
-var _ = Describe("Select", func() {
- It("supports has one", func() {
- q := NewQuery(nil, &JoinTest{}).Relation("HasOne.HasOne", nil)
-
- b, err := selectQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`SELECT JoinTest."id", JoinTest."has_one_id", "has_one"."id" AS "has_one__id", "has_one"."has_one_id" AS "has_one__has_one_id", "has_one__has_one"."id" AS "has_one__has_one__id", "has_one__has_one"."has_one_id" AS "has_one__has_one__has_one_id" FROM JoinTest AS JoinTest LEFT JOIN HasOne AS "has_one" ON "has_one"."id" = JoinTest."has_one_id" LEFT JOIN HasOne AS "has_one__has_one" ON "has_one__has_one"."id" = "has_one"."has_one_id"`))
- })
-
- It("supports belongs to", func() {
- q := NewQuery(nil, &JoinTest{}).Relation("BelongsTo", nil)
-
- b, err := selectQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`SELECT JoinTest."id", JoinTest."has_one_id", "belongs_to"."id" AS "belongs_to__id", "belongs_to"."join_test_id" AS "belongs_to__join_test_id" FROM JoinTest AS JoinTest LEFT JOIN BelongsTo AS "belongs_to" ON "belongs_to"."join_test_id" = JoinTest."id"`))
- })
-})
diff --git a/vendor/github.com/go-pg/pg/orm/main_test.go b/vendor/github.com/go-pg/pg/orm/main_test.go
deleted file mode 100644
index d98b36a..0000000
--- a/vendor/github.com/go-pg/pg/orm/main_test.go
+++ /dev/null
@@ -1,13 +0,0 @@
-package orm_test
-
-import (
- "testing"
-
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-)
-
-func TestGinkgo(t *testing.T) {
- RegisterFailHandler(Fail)
- RunSpecs(t, "ORM")
-}
diff --git a/vendor/github.com/go-pg/pg/orm/model.go b/vendor/github.com/go-pg/pg/orm/model.go
deleted file mode 100644
index 9fc267a..0000000
--- a/vendor/github.com/go-pg/pg/orm/model.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package orm
-
-import (
- "database/sql"
- "errors"
- "fmt"
- "reflect"
-
- "github.com/go-pg/pg/types"
-)
-
-type useQueryOne interface {
- useQueryOne() bool
-}
-
-type Model interface {
- ColumnScanner
-
- Init() error
-
- // NewModel returns ColumnScanner that is used to scan columns
- // from the current row.
- NewModel() ColumnScanner
-
- // AddModel adds ColumnScanner to the Collection.
- AddModel(ColumnScanner) error
-
- AfterQuery(DB) error
- AfterSelect(DB) error
-
- BeforeInsert(DB) error
- AfterInsert(DB) error
-
- BeforeUpdate(DB) error
- AfterUpdate(DB) error
-
- BeforeDelete(DB) error
- AfterDelete(DB) error
-}
-
-func NewModel(values ...interface{}) (Model, error) {
- if len(values) > 1 {
- return Scan(values...), nil
- }
-
- v0 := values[0]
- switch v0 := v0.(type) {
- case Model:
- return v0, nil
- case sql.Scanner:
- return Scan(v0), nil
- }
-
- v := reflect.ValueOf(v0)
- if !v.IsValid() {
- return nil, errors.New("pg: Model(nil)")
- }
- if v.Kind() != reflect.Ptr {
- return nil, fmt.Errorf("pg: Model(non-pointer %T)", v0)
- }
- v = v.Elem()
-
- switch v.Kind() {
- case reflect.Struct:
- return newStructTableModelValue(v), nil
- case reflect.Slice:
- typ := v.Type()
- structType := indirectType(typ.Elem())
- if structType.Kind() == reflect.Struct && structType != timeType {
- m := sliceTableModel{
- structTableModel: structTableModel{
- table: Tables.Get(structType),
- root: v,
- },
- slice: v,
- }
- m.init(typ)
- return &m, nil
- } else {
- return &sliceModel{
- slice: v,
- scan: types.Scanner(structType),
- }, nil
- }
- }
-
- return Scan(v0), nil
-}
diff --git a/vendor/github.com/go-pg/pg/orm/model_discard.go b/vendor/github.com/go-pg/pg/orm/model_discard.go
deleted file mode 100644
index 62a9f2f..0000000
--- a/vendor/github.com/go-pg/pg/orm/model_discard.go
+++ /dev/null
@@ -1,19 +0,0 @@
-package orm
-
-type Discard struct {
- hookStubs
-}
-
-var _ Model = (*Discard)(nil)
-
-func (d Discard) NewModel() ColumnScanner {
- return d
-}
-
-func (Discard) AddModel(_ ColumnScanner) error {
- return nil
-}
-
-func (Discard) ScanColumn(colIdx int, colName string, b []byte) error {
- return nil
-}
diff --git a/vendor/github.com/go-pg/pg/orm/model_scan.go b/vendor/github.com/go-pg/pg/orm/model_scan.go
deleted file mode 100644
index 8908f5b..0000000
--- a/vendor/github.com/go-pg/pg/orm/model_scan.go
+++ /dev/null
@@ -1,42 +0,0 @@
-package orm
-
-import (
- "fmt"
-
- "github.com/go-pg/pg/types"
-)
-
-type valuesModel struct {
- hookStubs
- values []interface{}
-}
-
-var _ Model = valuesModel{}
-
-func Scan(values ...interface{}) valuesModel {
- return valuesModel{
- values: values,
- }
-}
-
-func (valuesModel) useQueryOne() bool {
- return true
-}
-
-func (m valuesModel) NewModel() ColumnScanner {
- return m
-}
-
-func (valuesModel) AddModel(_ ColumnScanner) error {
- return nil
-}
-
-func (m valuesModel) ScanColumn(colIdx int, colName string, b []byte) error {
- if colIdx >= len(m.values) {
- return fmt.Errorf(
- "pg: no Scan var for column index=%d name=%q",
- colIdx, colName,
- )
- }
- return types.Scan(m.values[colIdx], b)
-}
diff --git a/vendor/github.com/go-pg/pg/orm/model_slice.go b/vendor/github.com/go-pg/pg/orm/model_slice.go
deleted file mode 100644
index d2df758..0000000
--- a/vendor/github.com/go-pg/pg/orm/model_slice.go
+++ /dev/null
@@ -1,35 +0,0 @@
-package orm
-
-import (
- "reflect"
-
- "github.com/go-pg/pg/internal"
-)
-
-type sliceModel struct {
- hookStubs
- slice reflect.Value
- scan func(reflect.Value, []byte) error
-}
-
-var _ Model = (*sliceModel)(nil)
-
-func (m *sliceModel) Init() error {
- if m.slice.IsValid() && m.slice.Len() > 0 {
- m.slice.Set(m.slice.Slice(0, 0))
- }
- return nil
-}
-
-func (m *sliceModel) NewModel() ColumnScanner {
- return m
-}
-
-func (sliceModel) AddModel(_ ColumnScanner) error {
- return nil
-}
-
-func (m *sliceModel) ScanColumn(colIdx int, _ string, b []byte) error {
- v := internal.SliceNextElem(m.slice)
- return m.scan(v, b)
-}
diff --git a/vendor/github.com/go-pg/pg/orm/model_table.go b/vendor/github.com/go-pg/pg/orm/model_table.go
deleted file mode 100644
index 1cb2434..0000000
--- a/vendor/github.com/go-pg/pg/orm/model_table.go
+++ /dev/null
@@ -1,107 +0,0 @@
-package orm
-
-import (
- "errors"
- "fmt"
- "reflect"
-)
-
-type tableModel interface {
- Model
-
- Table() *Table
- Relation() *Relation
- AppendParam([]byte, QueryFormatter, string) ([]byte, bool)
-
- Join(string, func(*Query) (*Query, error)) (bool, *join)
- GetJoin(string) *join
- GetJoins() []join
- AddJoin(join) *join
-
- Root() reflect.Value
- Index() []int
- ParentIndex() []int
- Mount(reflect.Value)
- Value() reflect.Value
-
- scanColumn(int, string, []byte) (bool, error)
-}
-
-func newTableModel(value interface{}) (tableModel, error) {
- if value, ok := value.(tableModel); ok {
- return value, nil
- }
-
- v := reflect.ValueOf(value)
- if !v.IsValid() {
- return nil, errors.New("pg: Model(nil)")
- }
- if v.Kind() != reflect.Ptr {
- return nil, fmt.Errorf("pg: Model(non-pointer %T)", value)
- }
-
- if v.IsNil() {
- typ := v.Type().Elem()
- if typ.Kind() == reflect.Struct {
- return newStructTableModelType(typ), nil
- }
- return nil, errors.New("pg: Model(nil)")
- }
-
- return newTableModelValue(v.Elem())
-}
-
-func newTableModelValue(v reflect.Value) (tableModel, error) {
- switch v.Kind() {
- case reflect.Struct:
- return newStructTableModelValue(v), nil
- case reflect.Slice:
- structType := sliceElemType(v)
- if structType.Kind() == reflect.Struct {
- m := sliceTableModel{
- structTableModel: structTableModel{
- table: Tables.Get(structType),
- root: v,
- },
- slice: v,
- }
- m.init(v.Type())
- return &m, nil
- }
- }
-
- return nil, fmt.Errorf("pg: Model(unsupported %s)", v.Type())
-}
-
-func newTableModelIndex(root reflect.Value, index []int, rel *Relation) (tableModel, error) {
- typ := typeByIndex(root.Type(), index)
-
- if typ.Kind() == reflect.Struct {
- return &structTableModel{
- table: Tables.Get(typ),
- rel: rel,
-
- root: root,
- index: index,
- }, nil
- }
-
- if typ.Kind() == reflect.Slice {
- structType := indirectType(typ.Elem())
- if structType.Kind() == reflect.Struct {
- m := sliceTableModel{
- structTableModel: structTableModel{
- table: Tables.Get(structType),
- rel: rel,
-
- root: root,
- index: index,
- },
- }
- m.init(typ)
- return &m, nil
- }
- }
-
- return nil, fmt.Errorf("pg: NewModel(%s)", typ)
-}
diff --git a/vendor/github.com/go-pg/pg/orm/model_table_m2m.go b/vendor/github.com/go-pg/pg/orm/model_table_m2m.go
deleted file mode 100644
index b603af2..0000000
--- a/vendor/github.com/go-pg/pg/orm/model_table_m2m.go
+++ /dev/null
@@ -1,120 +0,0 @@
-package orm
-
-import (
- "fmt"
- "reflect"
-)
-
-type m2mModel struct {
- *sliceTableModel
- baseTable *Table
- rel *Relation
-
- buf []byte
- dstValues map[string][]reflect.Value
- columns map[string]string
-}
-
-var _ tableModel = (*m2mModel)(nil)
-
-func newM2MModel(join *join) *m2mModel {
- baseTable := join.BaseModel.Table()
- joinModel := join.JoinModel.(*sliceTableModel)
- dstValues := dstValues(joinModel, baseTable.PKs)
- m := &m2mModel{
- sliceTableModel: joinModel,
- baseTable: baseTable,
- rel: join.Rel,
-
- dstValues: dstValues,
- columns: make(map[string]string),
- }
- if !m.sliceOfPtr {
- m.strct = reflect.New(m.table.Type).Elem()
- }
- return m
-}
-
-func (m *m2mModel) NewModel() ColumnScanner {
- if m.sliceOfPtr {
- m.strct = reflect.New(m.table.Type).Elem()
- } else {
- m.strct.Set(m.table.zeroStruct)
- }
- m.structInited = false
- m.structTableModel.NewModel()
- return m
-}
-
-func (m *m2mModel) AddModel(model ColumnScanner) error {
- m.buf = modelIdMap(m.buf[:0], m.columns, m.rel.BasePrefix, m.baseTable.PKs)
- dstValues, ok := m.dstValues[string(m.buf)]
- if !ok {
- return fmt.Errorf("pg: can't find dst value for model id=%q", m.buf)
- }
-
- for _, v := range dstValues {
- if m.sliceOfPtr {
- v.Set(reflect.Append(v, m.strct.Addr()))
- } else {
- v.Set(reflect.Append(v, m.strct))
- }
- }
-
- return nil
-}
-
-func (m *m2mModel) AfterQuery(db DB) error {
- if !m.rel.JoinTable.HasFlag(AfterQueryHookFlag) {
- return nil
- }
-
- var retErr error
- for _, slices := range m.dstValues {
- for _, slice := range slices {
- err := callAfterQueryHookSlice(slice, m.sliceOfPtr, db)
- if err != nil && retErr == nil {
- retErr = err
- }
- }
- }
- return retErr
-}
-
-func (m *m2mModel) AfterSelect(db DB) error {
- return nil
-}
-
-func (m *m2mModel) BeforeInsert(db DB) error {
- return nil
-}
-
-func (m *m2mModel) AfterInsert(db DB) error {
- return nil
-}
-
-func (m *m2mModel) BeforeUpdate(db DB) error {
- return nil
-}
-
-func (m *m2mModel) AfterUpdate(db DB) error {
- return nil
-}
-
-func (m *m2mModel) BeforeDelete(db DB) error {
- return nil
-}
-
-func (m *m2mModel) AfterDelete(db DB) error {
- return nil
-}
-
-func (m *m2mModel) ScanColumn(colIdx int, colName string, b []byte) error {
- ok, err := m.sliceTableModel.scanColumn(colIdx, colName, b)
- if ok {
- return err
- }
-
- m.columns[colName] = string(b)
- return nil
-}
diff --git a/vendor/github.com/go-pg/pg/orm/model_table_many.go b/vendor/github.com/go-pg/pg/orm/model_table_many.go
deleted file mode 100644
index f151e01..0000000
--- a/vendor/github.com/go-pg/pg/orm/model_table_many.go
+++ /dev/null
@@ -1,105 +0,0 @@
-package orm
-
-import (
- "fmt"
- "reflect"
-)
-
-type manyModel struct {
- *sliceTableModel
- rel *Relation
-
- buf []byte
- dstValues map[string][]reflect.Value
-}
-
-var _ tableModel = (*manyModel)(nil)
-
-func newManyModel(j *join) *manyModel {
- joinModel := j.JoinModel.(*sliceTableModel)
- dstValues := dstValues(joinModel, j.BaseModel.Table().PKs)
- m := manyModel{
- sliceTableModel: joinModel,
- rel: j.Rel,
-
- dstValues: dstValues,
- }
- if !m.sliceOfPtr {
- m.strct = reflect.New(m.table.Type).Elem()
- }
- return &m
-}
-
-func (m *manyModel) NewModel() ColumnScanner {
- if m.sliceOfPtr {
- m.strct = reflect.New(m.table.Type).Elem()
- } else {
- m.strct.Set(m.table.zeroStruct)
- }
- m.structInited = false
- m.structTableModel.NewModel()
- return m
-}
-
-func (m *manyModel) AddModel(model ColumnScanner) error {
- m.buf = modelId(m.buf[:0], m.strct, m.rel.FKs)
- dstValues, ok := m.dstValues[string(m.buf)]
- if !ok {
- return fmt.Errorf("pg: can't find dst value for model id=%q", m.buf)
- }
-
- for _, v := range dstValues {
- if m.sliceOfPtr {
- v.Set(reflect.Append(v, m.strct.Addr()))
- } else {
- v.Set(reflect.Append(v, m.strct))
- }
- }
-
- return nil
-}
-
-func (m *manyModel) AfterQuery(db DB) error {
- if !m.rel.JoinTable.HasFlag(AfterQueryHookFlag) {
- return nil
- }
-
- var retErr error
- for _, slices := range m.dstValues {
- for _, slice := range slices {
- err := callAfterQueryHookSlice(slice, m.sliceOfPtr, db)
- if err != nil && retErr == nil {
- retErr = err
- }
- }
- }
- return retErr
-}
-
-func (m *manyModel) AfterSelect(db DB) error {
- return nil
-}
-
-func (m *manyModel) BeforeInsert(db DB) error {
- return nil
-}
-
-func (m *manyModel) AfterInsert(db DB) error {
- return nil
-}
-
-func (m *manyModel) BeforeUpdate(db DB) error {
- return nil
-}
-
-func (m *manyModel) AfterUpdate(db DB) error {
- return nil
-}
-
-func (m *manyModel) BeforeDelete(db DB) error {
- return nil
-}
-
-func (m *manyModel) AfterDelete(db DB) error {
- return nil
-}
diff --git a/vendor/github.com/go-pg/pg/orm/model_table_slice.go b/vendor/github.com/go-pg/pg/orm/model_table_slice.go
deleted file mode 100644
index 474270b..0000000
--- a/vendor/github.com/go-pg/pg/orm/model_table_slice.go
+++ /dev/null
@@ -1,128 +0,0 @@
-package orm
-
-import "reflect"
-
-type sliceTableModel struct {
- structTableModel
-
- slice reflect.Value
- sliceOfPtr bool
-}
-
-var _ tableModel = (*sliceTableModel)(nil)
-
-func (m *sliceTableModel) init(sliceType reflect.Type) {
- switch sliceType.Elem().Kind() {
- case reflect.Ptr, reflect.Interface:
- m.sliceOfPtr = true
- }
-}
-
-func (sliceTableModel) useQueryOne() {}
-
-func (m *sliceTableModel) Join(name string, apply func(*Query) (*Query, error)) (bool, *join) {
- return m.join(m.Value(), name, apply)
-}
-
-func (m *sliceTableModel) Bind(bind reflect.Value) {
- m.slice = bind.Field(m.index[len(m.index)-1])
-}
-
-func (m *sliceTableModel) Value() reflect.Value {
- return m.slice
-}
-
-func (m *sliceTableModel) Init() error {
- if m.slice.IsValid() && m.slice.Len() > 0 {
- m.slice.Set(m.slice.Slice(0, 0))
- }
- return nil
-}
-
-func (m *sliceTableModel) NewModel() ColumnScanner {
- m.strct = m.nextElem()
- m.structInited = false
- m.structTableModel.NewModel()
- return m
-}
-
-func (m *sliceTableModel) AfterQuery(db DB) error {
- if !m.table.HasFlag(AfterQueryHookFlag) {
- return nil
- }
- return callAfterQueryHookSlice(m.slice, m.sliceOfPtr, db)
-}
-
-func (m *sliceTableModel) AfterSelect(db DB) error {
- if !m.table.HasFlag(AfterSelectHookFlag) {
- return nil
- }
- return callAfterSelectHookSlice(m.slice, m.sliceOfPtr, db)
-}
-
-func (m *sliceTableModel) BeforeInsert(db DB) error {
- if !m.table.HasFlag(BeforeInsertHookFlag) {
- return nil
- }
- return callBeforeInsertHookSlice(m.slice, m.sliceOfPtr, db)
-}
-
-func (m *sliceTableModel) AfterInsert(db DB) error {
- if !m.table.HasFlag(AfterInsertHookFlag) {
- return nil
- }
- return callAfterInsertHookSlice(m.slice, m.sliceOfPtr, db)
-}
-
-func (m *sliceTableModel) BeforeUpdate(db DB) error {
- if !m.table.HasFlag(BeforeUpdateHookFlag) {
- return nil
- }
- return callBeforeUpdateHookSlice(m.slice, m.sliceOfPtr, db)
-}
-
-func (m *sliceTableModel) AfterUpdate(db DB) error {
- if !m.table.HasFlag(AfterUpdateHookFlag) {
- return nil
- }
- return callAfterUpdateHookSlice(m.slice, m.sliceOfPtr, db)
-}
-
-func (m *sliceTableModel) BeforeDelete(db DB) error {
- if !m.table.HasFlag(BeforeDeleteHookFlag) {
- return nil
- }
- return callBeforeDeleteHookSlice(m.slice, m.sliceOfPtr, db)
-}
-
-func (m *sliceTableModel) AfterDelete(db DB) error {
- if !m.table.HasFlag(AfterDeleteHookFlag) {
- return nil
- }
- return callAfterDeleteHookSlice(m.slice, m.sliceOfPtr, db)
-}
-
-func (m *sliceTableModel) nextElem() reflect.Value {
- if m.slice.Len() < m.slice.Cap() {
- m.slice.Set(m.slice.Slice(0, m.slice.Len()+1))
- elem := m.slice.Index(m.slice.Len() - 1)
- if m.sliceOfPtr {
- if elem.IsNil() {
- elem.Set(reflect.New(elem.Type().Elem()))
- }
- return elem.Elem()
- } else {
- return elem
- }
- }
-
- if m.sliceOfPtr {
- elem := reflect.New(m.table.Type)
- m.slice.Set(reflect.Append(m.slice, elem))
- return elem.Elem()
-
- } else {
- m.slice.Set(reflect.Append(m.slice, m.table.zeroStruct))
- return m.slice.Index(m.slice.Len() - 1)
- }
-}
diff --git a/vendor/github.com/go-pg/pg/orm/model_table_struct.go b/vendor/github.com/go-pg/pg/orm/model_table_struct.go
deleted file mode 100644
index 2d3470d..0000000
--- a/vendor/github.com/go-pg/pg/orm/model_table_struct.go
+++ /dev/null
@@ -1,314 +0,0 @@
-package orm
-
-import (
- "fmt"
- "reflect"
- "strings"
-)
-
-type structTableModel struct {
- table *Table
- rel *Relation
- joins []join
-
- root reflect.Value
- index []int
-
- strct reflect.Value
- structInited bool
-}
-
-var _ tableModel = (*structTableModel)(nil)
-
-func newStructTableModelValue(v reflect.Value) *structTableModel {
- return &structTableModel{
- table: Tables.Get(v.Type()),
- root: v,
- strct: v,
- }
-}
-
-func newStructTableModelType(typ reflect.Type) *structTableModel {
- return &structTableModel{
- table: Tables.Get(typ),
- }
-}
-
-func (structTableModel) useQueryOne() bool {
- return true
-}
-
-func (m *structTableModel) Table() *Table {
- return m.table
-}
-
-func (m *structTableModel) Relation() *Relation {
- return m.rel
-}
-
-func (m *structTableModel) AppendParam(b []byte, f QueryFormatter, name string) ([]byte, bool) {
- b, ok := m.table.AppendParam(b, m.strct, name)
- if ok {
- return b, true
- }
-
- switch name {
- case "TableName":
- b = f.FormatQuery(b, string(m.table.Name))
- return b, true
- case "TableAlias":
- b = append(b, m.table.Alias...)
- return b, true
- case "Columns":
- b = appendColumns(b, m.table.Fields)
- return b, true
- }
-
- return b, false
-}
-
-func (m *structTableModel) Root() reflect.Value {
- return m.root
-}
-
-func (m *structTableModel) Index() []int {
- return m.index
-}
-
-func (m *structTableModel) ParentIndex() []int {
- return m.index[:len(m.index)-len(m.rel.Field.Index)]
-}
-
-func (m *structTableModel) Value() reflect.Value {
- return m.strct
-}
-
-func (m *structTableModel) Mount(host reflect.Value) {
- m.strct = host.FieldByIndex(m.rel.Field.Index)
- m.structInited = false
-}
-
-func (m *structTableModel) initStruct() {
- if m.structInited {
- return
- }
- m.structInited = true
-
- if m.strct.Kind() == reflect.Interface {
- m.strct = m.strct.Elem()
- }
- if m.strct.Kind() == reflect.Ptr {
- if m.strct.IsNil() {
- m.strct.Set(reflect.New(m.strct.Type().Elem()))
- m.strct = m.strct.Elem()
- } else {
- m.strct = m.strct.Elem()
- }
- }
- m.mountJoins()
-}
-
-func (m *structTableModel) mountJoins() {
- for i := range m.joins {
- j := &m.joins[i]
- switch j.Rel.Type {
- case HasOneRelation, BelongsToRelation:
- j.JoinModel.Mount(m.strct)
- }
- }
-}
-
-func (structTableModel) Init() error {
- return nil
-}
-
-func (m *structTableModel) NewModel() ColumnScanner {
- m.initStruct()
- return m
-}
-
-func (m *structTableModel) AddModel(_ ColumnScanner) error {
- return nil
-}
-
-func (m *structTableModel) AfterQuery(db DB) error {
- if !m.table.HasFlag(AfterQueryHookFlag) {
- return nil
- }
- return callAfterQueryHook(m.strct.Addr(), db)
-}
-
-func (m *structTableModel) AfterSelect(db DB) error {
- if !m.table.HasFlag(AfterSelectHookFlag) {
- return nil
- }
- return callAfterSelectHook(m.strct.Addr(), db)
-}
-
-func (m *structTableModel) BeforeInsert(db DB) error {
- if !m.table.HasFlag(BeforeInsertHookFlag) {
- return nil
- }
- return callBeforeInsertHook(m.strct.Addr(), db)
-}
-
-func (m *structTableModel) AfterInsert(db DB) error {
- if !m.table.HasFlag(AfterInsertHookFlag) {
- return nil
- }
- return callAfterInsertHook(m.strct.Addr(), db)
-}
-
-func (m *structTableModel) BeforeUpdate(db DB) error {
- if !m.table.HasFlag(BeforeUpdateHookFlag) {
- return nil
- }
- return callBeforeUpdateHook(m.strct.Addr(), db)
-}
-
-func (m *structTableModel) AfterUpdate(db DB) error {
- if !m.table.HasFlag(AfterUpdateHookFlag) {
- return nil
- }
- return callAfterUpdateHook(m.strct.Addr(), db)
-}
-
-func (m *structTableModel) BeforeDelete(db DB) error {
- if !m.table.HasFlag(BeforeDeleteHookFlag) {
- return nil
- }
- return callBeforeDeleteHook(m.strct.Addr(), db)
-}
-
-func (m *structTableModel) AfterDelete(db DB) error {
- if !m.table.HasFlag(AfterDeleteHookFlag) {
- return nil
- }
- return callAfterDeleteHook(m.strct.Addr(), db)
-}
-
-func (m *structTableModel) ScanColumn(colIdx int, colName string, b []byte) error {
- ok, err := m.scanColumn(colIdx, colName, b)
- if ok {
- return err
- }
- return fmt.Errorf("pg: can't find column=%s in model=%s", colName, m.table.Type.Name())
-}
-
-func (m *structTableModel) scanColumn(colIdx int, colName string, b []byte) (bool, error) {
- m.initStruct()
-
- joinName, fieldName := splitColumn(colName)
- if joinName != "" {
- if join := m.GetJoin(joinName); join != nil {
- return join.JoinModel.scanColumn(colIdx, fieldName, b)
- }
- if m.table.ModelName == joinName {
- return m.scanColumn(colIdx, fieldName, b)
- }
- }
-
- field, ok := m.table.FieldsMap[colName]
- if !ok {
- return false, nil
- }
-
- return true, field.ScanValue(m.strct, b)
-}
-
-func (m *structTableModel) GetJoin(name string) *join {
- for i := range m.joins {
- j := &m.joins[i]
- if j.Rel.Field.GoName == name || j.Rel.Field.SQLName == name {
- return j
- }
- }
- return nil
-}
-
-func (m *structTableModel) GetJoins() []join {
- return m.joins
-}
-
-func (m *structTableModel) AddJoin(j join) *join {
- m.joins = append(m.joins, j)
- return &m.joins[len(m.joins)-1]
-}
-
-func (m *structTableModel) Join(name string, apply func(*Query) (*Query, error)) (bool, *join) {
- return m.join(m.Value(), name, apply)
-}
-
-func (m *structTableModel) join(
- bind reflect.Value, name string, apply func(*Query) (*Query, error),
-) (bool, *join) {
- path := strings.Split(name, ".")
- index := make([]int, 0, len(path))
-
- currJoin := join{
- BaseModel: m,
- JoinModel: m,
- }
- var created bool
- var lastJoin *join
- var hasColumnName bool
-
- for _, name := range path {
- rel, ok := currJoin.JoinModel.Table().Relations[name]
- if !ok {
- hasColumnName = true
- break
- }
- currJoin.Rel = rel
- index = append(index, rel.Field.Index...)
-
- if j := currJoin.JoinModel.GetJoin(name); j != nil {
- currJoin.BaseModel = j.BaseModel
- currJoin.JoinModel = j.JoinModel
-
- created = false
- lastJoin = j
- } else {
- model, err := newTableModelIndex(bind, index, rel)
- if err != nil {
- return false, nil
- }
-
- currJoin.Parent = lastJoin
- currJoin.BaseModel = currJoin.JoinModel
- currJoin.JoinModel = model
-
- created = true
- lastJoin = currJoin.BaseModel.AddJoin(currJoin)
- }
- }
-
- // No joins with such name.
- if lastJoin == nil {
- return false, nil
- }
- if apply != nil {
- lastJoin.ApplyQuery = apply
- }
-
- if hasColumnName {
- column := path[len(path)-1]
- if column == "_" {
- if lastJoin.Columns == nil {
- lastJoin.Columns = make([]string, 0)
- }
- } else {
- lastJoin.Columns = append(lastJoin.Columns, column)
- }
- }
-
- return created, lastJoin
-}
-
-func splitColumn(s string) (string, string) {
- ind := strings.Index(s, "__")
- if ind == -1 {
- return "", s
- }
- return s[:ind], s[ind+2:]
-}
diff --git a/vendor/github.com/go-pg/pg/orm/orm.go b/vendor/github.com/go-pg/pg/orm/orm.go
deleted file mode 100644
index 7f78f6f..0000000
--- a/vendor/github.com/go-pg/pg/orm/orm.go
+++ /dev/null
@@ -1,41 +0,0 @@
-package orm
-
-import "io"
-
-// ColumnScanner is used to scan column values.
-type ColumnScanner interface {
- // Scan assigns a column value from a row.
- //
- // An error should be returned if the value can not be stored
- // without loss of information.
- ScanColumn(colIdx int, colName string, b []byte) error
-}
-
-type QueryAppender interface {
- Copy() QueryAppender
- Query() *Query
- AppendQuery(dst []byte) ([]byte, error)
-}
-
-type QueryFormatter interface {
- FormatQuery(b []byte, query string, params ...interface{}) []byte
-}
-
-// DB is a common interface for pg.DB and pg.Tx types.
-type DB interface {
- Model(model ...interface{}) *Query
- Select(model interface{}) error
- Insert(model ...interface{}) error
- Update(model ...interface{}) error
- Delete(model interface{}) error
-
- Exec(query interface{}, params ...interface{}) (Result, error)
- ExecOne(query interface{}, params ...interface{}) (Result, error)
- Query(coll, query interface{}, params ...interface{}) (Result, error)
- QueryOne(model, query interface{}, params ...interface{}) (Result, error)
-
- CopyFrom(r io.Reader, query interface{}, params ...interface{}) (Result, error)
- CopyTo(w io.Writer, query interface{}, params ...interface{}) (Result, error)
-
- QueryFormatter
-}
diff --git a/vendor/github.com/go-pg/pg/orm/query.go b/vendor/github.com/go-pg/pg/orm/query.go
deleted file mode 100644
index 20b428d..0000000
--- a/vendor/github.com/go-pg/pg/orm/query.go
+++ /dev/null
@@ -1,1001 +0,0 @@
-package orm
-
-import (
- "errors"
- "fmt"
- "io"
- "reflect"
- "strings"
- "sync"
- "time"
-
- "github.com/go-pg/pg/internal"
- "github.com/go-pg/pg/types"
-)
-
-type withQuery struct {
- name string
- query *Query
-}
-
-type Query struct {
- db DB
- stickyErr error
-
- model tableModel
- ignoreModel bool
-
- with []withQuery
- tables []FormatAppender
- columns []FormatAppender
- set []FormatAppender
- where []sepFormatAppender
- updWhere []sepFormatAppender
- joins []FormatAppender
- group []FormatAppender
- having []queryParamsAppender
- order []FormatAppender
- onConflict *queryParamsAppender
- returning []queryParamsAppender
- limit int
- offset int
- selFor FormatAppender
-}
-
-var _ queryAppender = (*Query)(nil)
-
-func NewQuery(db DB, model ...interface{}) *Query {
- return (&Query{}).DB(db).Model(model...)
-}
-
-// New returns new zero Query binded to the current db and model.
-func (q *Query) New() *Query {
- return &Query{
- db: q.db,
- model: q.model,
- ignoreModel: true,
- }
-}
-
-func (q *Query) AppendQuery(b []byte) ([]byte, error) {
- return selectQuery{q: q}.AppendQuery(b)
-}
-
-// Copy returns copy of the Query.
-func (q *Query) Copy() *Query {
- copy := &Query{
- db: q.db,
- stickyErr: q.stickyErr,
-
- model: q.model,
- ignoreModel: q.ignoreModel,
-
- tables: q.tables[:len(q.tables):len(q.tables)],
- columns: q.columns[:len(q.columns):len(q.columns)],
- set: q.set[:len(q.set):len(q.set)],
- where: q.where[:len(q.where):len(q.where)],
- updWhere: q.updWhere[:len(q.updWhere):len(q.updWhere)],
- joins: q.joins[:len(q.joins):len(q.joins)],
- group: q.group[:len(q.group):len(q.group)],
- having: q.having[:len(q.having):len(q.having)],
- order: q.order[:len(q.order):len(q.order)],
- onConflict: q.onConflict,
- returning: q.returning[:len(q.returning):len(q.returning)],
- limit: q.limit,
- offset: q.offset,
- }
- for _, with := range q.with {
- copy = copy.With(with.name, with.query.Copy())
- }
- return copy
-}
-
-func (q *Query) err(err error) *Query {
- if q.stickyErr == nil {
- q.stickyErr = err
- }
- return q
-}
-
-func (q *Query) DB(db DB) *Query {
- q.db = db
- for _, with := range q.with {
- with.query.db = db
- }
- return q
-}
-
-func (q *Query) Model(model ...interface{}) *Query {
- var err error
- switch l := len(model); {
- case l == 0:
- q.model = nil
- case l == 1:
- q.model, err = newTableModel(model[0])
- case l > 1:
- q.model, err = newTableModel(&model)
- }
- if err != nil {
- q = q.err(err)
- }
- if q.ignoreModel {
- q.ignoreModel = false
- }
- return q
-}
-
-// With adds subq as common table expression with the given name.
-func (q *Query) With(name string, subq *Query) *Query {
- q.with = append(q.with, withQuery{name, subq})
- return q
-}
-
-// WrapWith creates new Query and adds to it current query as
-// common table expression with the given name.
-func (q *Query) WrapWith(name string) *Query {
- wrapper := q.New()
- wrapper.with = q.with
- q.with = nil
- wrapper = wrapper.With(name, q)
- return wrapper
-}
-
-func (q *Query) Table(tables ...string) *Query {
- for _, table := range tables {
- q.tables = append(q.tables, fieldAppender{table})
- }
- return q
-}
-
-func (q *Query) TableExpr(expr string, params ...interface{}) *Query {
- q.tables = append(q.tables, queryParamsAppender{expr, params})
- return q
-}
-
-// Column adds column to the Query quoting it according to PostgreSQL rules.
-// ColumnExpr can be used to bypass quoting restriction.
-func (q *Query) Column(columns ...string) *Query {
- for _, column := range columns {
- if column == "_" {
- if q.columns == nil {
- q.columns = make([]FormatAppender, 0)
- }
- continue
- }
-
- if q.model != nil {
- if _, j := q.model.Join(column, nil); j != nil {
- continue
- }
- }
-
- q.columns = append(q.columns, fieldAppender{column})
- }
- return q
-}
-
-// ColumnExpr adds column expression to the Query.
-func (q *Query) ColumnExpr(expr string, params ...interface{}) *Query {
- q.columns = append(q.columns, queryParamsAppender{expr, params})
- return q
-}
-
-func (q *Query) getFields() ([]*Field, error) {
- return q._getFields(false)
-}
-
-func (q *Query) getDataFields() ([]*Field, error) {
- return q._getFields(true)
-}
-
-func (q *Query) _getFields(omitPKs bool) ([]*Field, error) {
- table := q.model.Table()
-
- var columns []*Field
- for _, col := range q.columns {
- f, ok := col.(fieldAppender)
- if !ok {
- continue
- }
-
- field, err := table.GetField(f.field)
- if err != nil {
- return nil, err
- }
-
- if omitPKs && field.HasFlag(PrimaryKeyFlag) {
- continue
- }
-
- columns = append(columns, field)
- }
- return columns, nil
-}
-
-func (q *Query) Relation(name string, apply func(*Query) (*Query, error)) *Query {
- if _, j := q.model.Join(name, apply); j == nil {
- return q.err(fmt.Errorf(
- "model=%s does not have relation=%s",
- q.model.Table().Type.Name(), name,
- ))
- }
- return q
-}
-
-func (q *Query) Set(set string, params ...interface{}) *Query {
- q.set = append(q.set, queryParamsAppender{set, params})
- return q
-}
-
-func (q *Query) Where(where string, params ...interface{}) *Query {
- q.addWhere(&whereAppender{
- sep: "AND",
- where: where,
- params: params,
- })
- return q
-}
-
-func (q *Query) WhereOr(where string, params ...interface{}) *Query {
- q.addWhere(&whereAppender{
- sep: "OR",
- where: where,
- params: params,
- })
- return q
-}
-
-// WhereGroup encloses conditions added in the function in parentheses.
-//
-// q.Where("TRUE").
-// WhereGroup(func(q *orm.Query) (*orm.Query, error)) {
-// q = q.WhereOr("FALSE").WhereOr("TRUE").
-// return q, nil
-// })
-//
-// generates
-//
-// WHERE TRUE AND (FALSE OR TRUE)
-func (q *Query) WhereGroup(fn func(*Query) (*Query, error)) *Query {
- return q.whereGroup("AND", fn)
-}
-
-// WhereOrGroup encloses conditions added in the function in parentheses.
-//
-// q.Where("TRUE").
-// WhereOrGroup(func(q *orm.Query) (*orm.Query, error)) {
-// q = q.Where("FALSE").Where("TRUE").
-// return q, nil
-// })
-//
-// generates
-//
-// WHERE TRUE OR (FALSE AND TRUE)
-func (q *Query) WhereOrGroup(fn func(*Query) (*Query, error)) *Query {
- return q.whereGroup("OR", fn)
-}
-
-func (q *Query) whereGroup(conj string, fn func(*Query) (*Query, error)) *Query {
- saved := q.where
- q.where = nil
-
- newq, err := fn(q)
- if err != nil {
- q.err(err)
- return q
- }
-
- f := whereGroupAppender{
- sep: conj,
- where: newq.where,
- }
- newq.where = saved
- newq.addWhere(f)
-
- return newq
-}
-
-// WhereIn is a shortcut for Where and pg.In to work with IN operator:
-//
-// WhereIn("id IN (?)", 1, 2, 3)
-func (q *Query) WhereIn(where string, params ...interface{}) *Query {
- return q.Where(where, types.In(params))
-}
-
-func (q *Query) addWhere(f sepFormatAppender) {
- if q.onConflictDoUpdate() {
- q.updWhere = append(q.updWhere, f)
- } else {
- q.where = append(q.where, f)
- }
-}
-
-func (q *Query) Join(join string, params ...interface{}) *Query {
- q.joins = append(q.joins, queryParamsAppender{join, params})
- return q
-}
-
-func (q *Query) Group(columns ...string) *Query {
- for _, column := range columns {
- q.group = append(q.group, fieldAppender{column})
- }
- return q
-}
-
-func (q *Query) GroupExpr(group string, params ...interface{}) *Query {
- q.group = append(q.group, queryParamsAppender{group, params})
- return q
-}
-
-func (q *Query) Having(having string, params ...interface{}) *Query {
- q.having = append(q.having, queryParamsAppender{having, params})
- return q
-}
-
-// Order adds sort order to the Query quoting column name.
-// OrderExpr can be used to bypass quoting restriction.
-func (q *Query) Order(orders ...string) *Query {
-loop:
- for _, order := range orders {
- ind := strings.Index(order, " ")
- if ind != -1 {
- field := order[:ind]
- sort := order[ind+1:]
- switch internal.ToUpper(sort) {
- case "ASC", "DESC", "ASC NULLS FIRST", "DESC NULLS FIRST",
- "ASC NULLS LAST", "DESC NULLS LAST":
- q = q.OrderExpr("? ?", types.F(field), types.Q(sort))
- continue loop
- }
- }
-
- q.order = append(q.order, fieldAppender{order})
- }
- return q
-}
-
-// Order adds sort order to the Query.
-func (q *Query) OrderExpr(order string, params ...interface{}) *Query {
- q.order = append(q.order, queryParamsAppender{order, params})
- return q
-}
-
-func (q *Query) Limit(n int) *Query {
- q.limit = n
- return q
-}
-
-func (q *Query) Offset(n int) *Query {
- q.offset = n
- return q
-}
-
-func (q *Query) OnConflict(s string, params ...interface{}) *Query {
- q.onConflict = &queryParamsAppender{s, params}
- return q
-}
-
-func (q *Query) onConflictDoUpdate() bool {
- return q.onConflict != nil &&
- strings.HasSuffix(q.onConflict.query, "DO UPDATE")
-}
-
-func (q *Query) Returning(s string, params ...interface{}) *Query {
- q.returning = append(q.returning, queryParamsAppender{s, params})
- return q
-}
-
-func (q *Query) For(s string, params ...interface{}) *Query {
- q.selFor = queryParamsAppender{s, params}
- return q
-}
-
-// Apply calls the fn passing the Query as an argument.
-func (q *Query) Apply(fn func(*Query) (*Query, error)) *Query {
- qq, err := fn(q)
- if err != nil {
- q.err(err)
- return q
- }
- return qq
-}
-
-// Count returns number of rows matching the query using count aggregate function.
-func (q *Query) Count() (int, error) {
- if q.stickyErr != nil {
- return 0, q.stickyErr
- }
-
- var count int
- _, err := q.db.QueryOne(
- Scan(&count),
- q.countSelectQuery("count(*)"),
- q.model,
- )
- return count, err
-}
-
-func (q *Query) countSelectQuery(column string) selectQuery {
- return selectQuery{
- q: q,
- count: column,
- }
-}
-
-// First selects the first row.
-func (q *Query) First() error {
- err := q.model.Table().checkPKs()
- if err != nil {
- return err
- }
-
- b := columns(nil, q.model.Table().Alias, "", q.model.Table().PKs)
- return q.OrderExpr(internal.BytesToString(b)).Limit(1).Select()
-}
-
-// Last selects the last row.
-func (q *Query) Last() error {
- err := q.model.Table().checkPKs()
- if err != nil {
- return err
- }
-
- b := columns(nil, q.model.Table().Alias, "", q.model.Table().PKs)
- b = append(b, " DESC"...)
- return q.OrderExpr(internal.BytesToString(b)).Limit(1).Select()
-}
-
-// Select selects the model.
-func (q *Query) Select(values ...interface{}) error {
- if q.stickyErr != nil {
- return q.stickyErr
- }
-
- model, err := q.newModel(values...)
- if err != nil {
- return err
- }
-
- res, err := q.query(model, selectQuery{q: q})
- if err != nil {
- return err
- }
-
- if res.RowsReturned() > 0 {
- if q.model != nil {
- if err := q.selectJoins(q.model.GetJoins()); err != nil {
- return err
- }
- }
- if err := model.AfterSelect(q.db); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func (q *Query) newModel(values ...interface{}) (Model, error) {
- if len(values) > 0 {
- return NewModel(values...)
- }
- return q.model, nil
-}
-
-func (q *Query) query(model Model, query interface{}) (Result, error) {
- if _, ok := model.(useQueryOne); ok {
- return q.db.QueryOne(model, query, q.model)
- }
- return q.db.Query(model, query, q.model)
-}
-
-// SelectAndCount runs Select and Count in two goroutines,
-// waits for them to finish and returns the result.
-func (q *Query) SelectAndCount(values ...interface{}) (count int, err error) {
- if q.stickyErr != nil {
- return 0, q.stickyErr
- }
-
- var wg sync.WaitGroup
- wg.Add(2)
- var mu sync.Mutex
-
- go func() {
- defer wg.Done()
- if e := q.Select(values...); e != nil {
- mu.Lock()
- err = e
- mu.Unlock()
- }
- }()
-
- go func() {
- defer wg.Done()
- var e error
- count, e = q.Count()
- if e != nil {
- mu.Lock()
- err = e
- mu.Unlock()
- }
- }()
-
- wg.Wait()
- return count, err
-}
-
-func (q *Query) forEachHasOneJoin(fn func(*join)) {
- if q.model == nil {
- return
- }
- q._forEachHasOneJoin(fn, q.model.GetJoins())
-}
-
-func (q *Query) _forEachHasOneJoin(fn func(*join), joins []join) {
- for i := range joins {
- j := &joins[i]
- switch j.Rel.Type {
- case HasOneRelation, BelongsToRelation:
- fn(j)
- q._forEachHasOneJoin(fn, j.JoinModel.GetJoins())
- }
- }
-}
-
-func (q *Query) selectJoins(joins []join) error {
- var err error
- for i := range joins {
- j := &joins[i]
- if j.Rel.Type == HasOneRelation || j.Rel.Type == BelongsToRelation {
- err = q.selectJoins(j.JoinModel.GetJoins())
- } else {
- err = j.Select(q.db)
- }
- if err != nil {
- return err
- }
- }
- return nil
-}
-
-// Insert inserts the model.
-func (q *Query) Insert(values ...interface{}) (Result, error) {
- if q.stickyErr != nil {
- return nil, q.stickyErr
- }
-
- model, err := q.newModel(values...)
- if err != nil {
- return nil, err
- }
-
- if q.model != nil {
- if err := q.model.BeforeInsert(q.db); err != nil {
- return nil, err
- }
- }
-
- res, err := q.db.Query(model, insertQuery{q: q}, q.model)
- if err != nil {
- return nil, err
- }
-
- if q.model != nil {
- if err := q.model.AfterInsert(q.db); err != nil {
- return nil, err
- }
- }
-
- return res, nil
-}
-
-// SelectOrInsert selects the model inserting one if it does not exist.
-func (q *Query) SelectOrInsert(values ...interface{}) (inserted bool, err error) {
- if q.stickyErr != nil {
- return false, q.stickyErr
- }
-
- insertq := q
- if len(insertq.columns) > 0 {
- insertq = insertq.Copy()
- insertq.columns = nil
- }
-
- var insertErr error
- for i := 0; i < 5; i++ {
- if i >= 2 {
- time.Sleep(internal.RetryBackoff(i-2, 250*time.Millisecond, 5*time.Second))
- }
-
- err := q.Select(values...)
- if err == nil {
- return false, nil
- }
- if err != internal.ErrNoRows {
- return false, err
- }
-
- res, err := insertq.Insert(values...)
- if err != nil {
- insertErr = err
- if pgErr, ok := err.(internal.PGError); ok {
- if pgErr.IntegrityViolation() {
- continue
- }
- if pgErr.Field('C') == "55000" {
- // Retry on "#55000 attempted to delete invisible tuple".
- continue
- }
- }
- return false, err
- }
- if res.RowsAffected() == 1 {
- return true, nil
- }
- }
-
- err = fmt.Errorf(
- "pg: SelectOrInsert: select returns no rows (insert fails with err=%q)",
- insertErr,
- )
- return false, err
-}
-
-// Update updates the model.
-func (q *Query) Update(scan ...interface{}) (Result, error) {
- return q.update(scan, false)
-}
-
-// Update updates the model omitting null columns.
-func (q *Query) UpdateNotNull(scan ...interface{}) (Result, error) {
- return q.update(scan, true)
-}
-
-func (q *Query) update(scan []interface{}, omitZero bool) (Result, error) {
- if q.stickyErr != nil {
- return nil, q.stickyErr
- }
-
- model, err := q.newModel(scan...)
- if err != nil {
- return nil, err
- }
-
- if q.model != nil {
- if err := q.model.BeforeUpdate(q.db); err != nil {
- return nil, err
- }
- }
-
- res, err := q.db.Query(model, updateQuery{q: q, omitZero: omitZero}, q.model)
- if err != nil {
- return nil, err
- }
-
- if q.model != nil {
- if err := q.model.AfterUpdate(q.db); err != nil {
- return nil, err
- }
- }
-
- return res, nil
-}
-
-// Delete deletes the model.
-func (q *Query) Delete(values ...interface{}) (Result, error) {
- if q.stickyErr != nil {
- return nil, q.stickyErr
- }
-
- model, err := q.newModel(values...)
- if err != nil {
- return nil, err
- }
-
- if q.model != nil {
- if err := q.model.BeforeDelete(q.db); err != nil {
- return nil, err
- }
- }
-
- res, err := q.db.Query(model, deleteQuery{q}, q.model)
- if err != nil {
- return nil, err
- }
-
- if q.model != nil {
- if err := q.model.AfterDelete(q.db); err != nil {
- return nil, err
- }
- }
-
- return res, nil
-}
-
-func (q *Query) CreateTable(opt *CreateTableOptions) (Result, error) {
- if q.stickyErr != nil {
- return nil, q.stickyErr
- }
- return q.db.Exec(createTableQuery{
- q: q,
- opt: opt,
- })
-}
-
-func (q *Query) DropTable(opt *DropTableOptions) (Result, error) {
- if q.stickyErr != nil {
- return nil, q.stickyErr
- }
- return q.db.Exec(dropTableQuery{
- q: q,
- opt: opt,
- })
-}
-
-// Exec is an alias for DB.Exec.
-func (q *Query) Exec(query interface{}, params ...interface{}) (Result, error) {
- params = append(params, q.model)
- return q.db.Exec(query, params...)
-}
-
-// ExecOne is an alias for DB.ExecOne.
-func (q *Query) ExecOne(query interface{}, params ...interface{}) (Result, error) {
- params = append(params, q.model)
- return q.db.ExecOne(query, params...)
-}
-
-// Query is an alias for DB.Query.
-func (q *Query) Query(model, query interface{}, params ...interface{}) (Result, error) {
- params = append(params, q.model)
- return q.db.Query(model, query, params...)
-}
-
-// QueryOne is an alias for DB.QueryOne.
-func (q *Query) QueryOne(model, query interface{}, params ...interface{}) (Result, error) {
- params = append(params, q.model)
- return q.db.QueryOne(model, query, params...)
-}
-
-// CopyFrom is an alias from DB.CopyFrom.
-func (q *Query) CopyFrom(r io.Reader, query interface{}, params ...interface{}) (Result, error) {
- params = append(params, q.model)
- return q.db.CopyFrom(r, query, params...)
-}
-
-// CopyTo is an alias from DB.CopyTo.
-func (q *Query) CopyTo(w io.Writer, query interface{}, params ...interface{}) (Result, error) {
- params = append(params, q.model)
- return q.db.CopyTo(w, query, params...)
-}
-
-func (q *Query) FormatQuery(b []byte, query string, params ...interface{}) []byte {
- params = append(params, q.model)
- if q.db != nil {
- return q.db.FormatQuery(b, query, params...)
- }
- return formatter.Append(b, query, params...)
-}
-
-func (q *Query) hasModel() bool {
- return !q.ignoreModel && q.model != nil
-}
-
-func (q *Query) hasTables() bool {
- return q.hasModel() || len(q.tables) > 0
-}
-
-func (q *Query) appendTableName(b []byte) []byte {
- return q.FormatQuery(b, string(q.model.Table().Name))
-}
-
-func (q *Query) appendTableNameWithAlias(b []byte) []byte {
- b = q.appendTableName(b)
- b = append(b, " AS "...)
- b = append(b, q.model.Table().Alias...)
- return b
-}
-
-func (q *Query) appendFirstTable(b []byte) []byte {
- if q.hasModel() {
- return q.appendTableName(b)
- }
- if len(q.tables) > 0 {
- b = q.tables[0].AppendFormat(b, q)
- }
- return b
-}
-
-func (q *Query) appendFirstTableWithAlias(b []byte) []byte {
- if q.hasModel() {
- return q.appendTableNameWithAlias(b)
- }
- if len(q.tables) > 0 {
- b = q.tables[0].AppendFormat(b, q)
- }
- return b
-}
-
-func (q *Query) appendTables(b []byte) []byte {
- if q.hasModel() {
- b = q.appendTableNameWithAlias(b)
- if len(q.tables) > 0 {
- b = append(b, ", "...)
- }
- }
- for i, f := range q.tables {
- if i > 0 {
- b = append(b, ", "...)
- }
- b = f.AppendFormat(b, q)
- }
- return b
-}
-
-func (q *Query) hasOtherTables() bool {
- if q.hasModel() {
- return len(q.tables) > 0
- }
- return len(q.tables) > 1
-}
-
-func (q *Query) modelHasData() bool {
- if !q.hasModel() {
- return false
- }
- v := q.model.Value()
- return v.Kind() == reflect.Slice && v.Len() > 0
-}
-
-func (q *Query) appendOtherTables(b []byte) []byte {
- tables := q.tables
- if !q.hasModel() {
- tables = tables[1:]
- }
- for i, f := range tables {
- if i > 0 {
- b = append(b, ", "...)
- }
- b = f.AppendFormat(b, q)
- }
- return b
-}
-
-func (q *Query) appendColumns(b []byte) []byte {
- for i, f := range q.columns {
- if i > 0 {
- b = append(b, ", "...)
- }
- b = f.AppendFormat(b, q)
- }
- return b
-}
-
-func (q *Query) mustAppendWhere(b []byte) ([]byte, error) {
- if len(q.where) > 0 {
- b = q.appendWhere(b)
- return b, nil
- }
-
- if q.model == nil {
- return nil, errors.New("pg: Model is nil")
- }
-
- if err := q.model.Table().checkPKs(); err != nil {
- return nil, err
- }
-
- b = append(b, " WHERE "...)
- return wherePKQuery{q}.AppendFormat(b, nil), nil
-}
-
-func (q *Query) appendWhere(b []byte) []byte {
- return q._appendWhere(b, q.where)
-}
-
-func (q *Query) appendUpdWhere(b []byte) []byte {
- return q._appendWhere(b, q.updWhere)
-}
-
-func (q *Query) _appendWhere(b []byte, where []sepFormatAppender) []byte {
- b = append(b, " WHERE "...)
- for i, f := range where {
- if i > 0 {
- b = append(b, ' ')
- b = f.AppendSep(b)
- b = append(b, ' ')
- }
- b = f.AppendFormat(b, q)
- }
- return b
-}
-
-func (q *Query) appendSet(b []byte) []byte {
- b = append(b, " SET "...)
- for i, f := range q.set {
- if i > 0 {
- b = append(b, ", "...)
- }
- b = f.AppendFormat(b, q)
- }
- return b
-}
-
-func (q *Query) appendReturning(b []byte) []byte {
- b = append(b, " RETURNING "...)
- for i, f := range q.returning {
- if i > 0 {
- b = append(b, ", "...)
- }
- b = f.AppendFormat(b, q)
- }
- return b
-}
-
-func (q *Query) appendWith(b []byte) ([]byte, error) {
- var err error
- b = append(b, "WITH "...)
- for i, with := range q.with {
- if i > 0 {
- b = append(b, ", "...)
- }
- b = types.AppendField(b, with.name, 1)
- b = append(b, " AS ("...)
-
- b, err = selectQuery{q: with.query}.AppendQuery(b)
- if err != nil {
- return nil, err
- }
-
- b = append(b, ')')
- }
- b = append(b, ' ')
- return b, nil
-}
-
-//------------------------------------------------------------------------------
-
-type wherePKQuery struct {
- *Query
-}
-
-func (wherePKQuery) AppendSep(b []byte) []byte {
- return append(b, "AND"...)
-}
-
-func (q wherePKQuery) AppendFormat(b []byte, f QueryFormatter) []byte {
- table := q.model.Table()
- value := q.model.Value()
- if value.Kind() == reflect.Struct {
- return appendColumnAndValue(b, value, table.Alias, table.PKs)
- } else {
- return appendColumnAndColumn(b, value, table.Alias, table.PKs)
- }
-}
-
-func appendColumnAndValue(b []byte, v reflect.Value, alias types.Q, fields []*Field) []byte {
- for i, f := range fields {
- if i > 0 {
- b = append(b, " AND "...)
- }
- b = append(b, alias...)
- b = append(b, '.')
- b = append(b, f.Column...)
- b = append(b, " = "...)
- b = f.AppendValue(b, v, 1)
- }
- return b
-}
-
-func appendColumnAndColumn(b []byte, v reflect.Value, alias types.Q, fields []*Field) []byte {
- for i, f := range fields {
- if i > 0 {
- b = append(b, " AND "...)
- }
- b = append(b, alias...)
- b = append(b, '.')
- b = append(b, f.Column...)
- b = append(b, " = _data."...)
- b = append(b, f.Column...)
- }
- return b
-}
diff --git a/vendor/github.com/go-pg/pg/orm/query_test.go b/vendor/github.com/go-pg/pg/orm/query_test.go
deleted file mode 100644
index 31c5797..0000000
--- a/vendor/github.com/go-pg/pg/orm/query_test.go
+++ /dev/null
@@ -1,61 +0,0 @@
-package orm_test
-
-import (
- "testing"
- "unsafe"
-
- "github.com/go-pg/pg/orm"
-
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-)
-
-func TestQuerySize(t *testing.T) {
- size := int(unsafe.Sizeof(orm.Query{}))
- wanted := 360
- if size != wanted {
- t.Fatalf("got %d, wanted %d", size, wanted)
- }
-}
-
-func TestQueryFormatQuery(t *testing.T) {
- type FormatModel struct {
- Foo string
- Bar string
- }
-
- q := orm.NewQuery(nil, &FormatModel{"foo", "bar"})
-
- params := &struct {
- Foo string
- }{
- "not_foo",
- }
- b := q.FormatQuery(nil, "?foo ?TableName ?TableAlias ?Columns", params)
-
- wanted := `'not_foo' "format_models" "format_model" "foo", "bar"`
- if string(b) != wanted {
- t.Fatalf("got `%s`, wanted `%s`", string(b), wanted)
- }
-}
-
-var _ = Describe("NewQuery", func() {
- It("works with nil db", func() {
- q := orm.NewQuery(nil)
-
- b, err := q.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal("SELECT *"))
- })
-
- It("works with nil model", func() {
- type Model struct {
- Id int
- }
- q := orm.NewQuery(nil, (*Model)(nil))
-
- b, err := q.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`SELECT "model"."id" FROM "models" AS "model"`))
- })
-})
diff --git a/vendor/github.com/go-pg/pg/orm/relation.go b/vendor/github.com/go-pg/pg/orm/relation.go
deleted file mode 100644
index 6d8f717..0000000
--- a/vendor/github.com/go-pg/pg/orm/relation.go
+++ /dev/null
@@ -1,23 +0,0 @@
-package orm
-
-import "github.com/go-pg/pg/types"
-
-const (
- HasOneRelation = 1 << iota
- BelongsToRelation
- HasManyRelation
- Many2ManyRelation
-)
-
-type Relation struct {
- Type int
- Polymorphic bool
- Field *Field
- JoinTable *Table
- FKs []*Field
-
- M2MTableName types.Q
- M2MTableAlias types.Q
- BasePrefix string
- JoinPrefix string
-}
diff --git a/vendor/github.com/go-pg/pg/orm/result.go b/vendor/github.com/go-pg/pg/orm/result.go
deleted file mode 100644
index 6f81245..0000000
--- a/vendor/github.com/go-pg/pg/orm/result.go
+++ /dev/null
@@ -1,14 +0,0 @@
-package orm
-
-// A Result summarizes an executed SQL command.
-type Result interface {
- Model() Model
-
- // RowsAffected returns the number of rows affected by SELECT, INSERT, UPDATE,
- // or DELETE queries. It returns -1 if query can't possibly affect any rows,
- // e.g. in case of CREATE or SHOW queries.
- RowsAffected() int
-
- // RowsReturned returns the number of rows returned by the query.
- RowsReturned() int
-}
diff --git a/vendor/github.com/go-pg/pg/orm/select.go b/vendor/github.com/go-pg/pg/orm/select.go
deleted file mode 100644
index 2086289..0000000
--- a/vendor/github.com/go-pg/pg/orm/select.go
+++ /dev/null
@@ -1,188 +0,0 @@
-package orm
-
-import (
- "strconv"
- "strings"
-)
-
-func Select(db DB, model interface{}) error {
- q := NewQuery(db, model)
- if err := q.model.Table().checkPKs(); err != nil {
- return err
- }
- q.where = append(q.where, wherePKQuery{q})
- return q.Select()
-}
-
-type selectQuery struct {
- q *Query
-
- count string
-}
-
-var _ QueryAppender = (*selectQuery)(nil)
-
-func (q selectQuery) Copy() QueryAppender {
- return selectQuery{
- q: q.q.Copy(),
- count: q.count,
- }
-}
-
-func (q selectQuery) Query() *Query {
- return q.q
-}
-
-func (q selectQuery) AppendQuery(b []byte) ([]byte, error) {
- if q.q.stickyErr != nil {
- return nil, q.q.stickyErr
- }
-
- var err error
-
- cteCount := q.count != "" && (len(q.q.group) > 0 || q.isDistinct())
- if cteCount {
- b = append(b, `WITH "_count_wrapper" AS (`...)
- }
-
- if len(q.q.with) > 0 {
- b, err = q.q.appendWith(b)
- if err != nil {
- return nil, err
- }
- }
-
- b = append(b, "SELECT "...)
- if q.count != "" && !cteCount {
- b = append(b, q.count...)
- } else {
- b = q.appendColumns(b)
- }
-
- if q.q.hasTables() {
- b = append(b, " FROM "...)
- b = q.q.appendTables(b)
- }
-
- q.q.forEachHasOneJoin(func(j *join) {
- b = append(b, ' ')
- b = j.appendHasOneJoin(q.q.db, b)
- })
- if len(q.q.joins) > 0 {
- for _, f := range q.q.joins {
- b = append(b, ' ')
- b = f.AppendFormat(b, q.q)
- }
- }
-
- if len(q.q.where) > 0 {
- b = q.q.appendWhere(b)
- }
-
- if len(q.q.group) > 0 {
- b = append(b, " GROUP BY "...)
- for i, f := range q.q.group {
- if i > 0 {
- b = append(b, ", "...)
- }
- b = f.AppendFormat(b, q.q)
- }
- }
-
- if len(q.q.having) > 0 {
- b = append(b, " HAVING "...)
- for i, f := range q.q.having {
- if i > 0 {
- b = append(b, " AND "...)
- }
- b = append(b, '(')
- b = f.AppendFormat(b, q.q)
- b = append(b, ')')
- }
- }
-
- if q.count == "" {
- if len(q.q.order) > 0 {
- b = append(b, " ORDER BY "...)
- for i, f := range q.q.order {
- if i > 0 {
- b = append(b, ", "...)
- }
- b = f.AppendFormat(b, q.q)
- }
- }
-
- if q.q.limit != 0 {
- b = append(b, " LIMIT "...)
- b = strconv.AppendInt(b, int64(q.q.limit), 10)
- }
-
- if q.q.offset != 0 {
- b = append(b, " OFFSET "...)
- b = strconv.AppendInt(b, int64(q.q.offset), 10)
- }
-
- if q.q.selFor != nil {
- b = append(b, " FOR "...)
- b = q.q.selFor.AppendFormat(b, q.q)
- }
- } else if cteCount {
- b = append(b, `) SELECT `...)
- b = append(b, q.count...)
- b = append(b, ` FROM "_count_wrapper"`...)
- }
-
- return b, nil
-}
-
-func (q selectQuery) appendColumns(b []byte) []byte {
- start := len(b)
-
- if q.q.columns != nil {
- b = q.q.appendColumns(b)
- } else if q.q.hasModel() {
- b = q.appendTableColumns(b, q.q.model.Table())
- } else {
- b = append(b, '*')
- }
-
- q.q.forEachHasOneJoin(func(j *join) {
- if len(b) != start {
- b = append(b, ", "...)
- start = len(b)
- }
-
- b = j.appendHasOneColumns(b)
-
- if len(b) == start {
- b = b[:len(b)-2]
- }
- })
-
- return b
-}
-
-func (q selectQuery) appendTableColumns(b []byte, table *Table) []byte {
- for i, f := range table.Fields {
- if i > 0 {
- b = append(b, ", "...)
- }
- b = append(b, table.Alias...)
- b = append(b, '.')
- b = append(b, f.Column...)
- }
- return b
-}
-
-func (q selectQuery) isDistinct() bool {
- for _, column := range q.q.columns {
- column, ok := column.(queryParamsAppender)
- if ok {
- if strings.Contains(column.query, "DISTINCT") ||
- strings.Contains(column.query, "distinct") {
- return true
- }
- }
- }
- return false
-}
diff --git a/vendor/github.com/go-pg/pg/orm/select_test.go b/vendor/github.com/go-pg/pg/orm/select_test.go
deleted file mode 100644
index 1401b72..0000000
--- a/vendor/github.com/go-pg/pg/orm/select_test.go
+++ /dev/null
@@ -1,242 +0,0 @@
-package orm
-
-import (
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-)
-
-type User struct {
- tableName struct{} `sql:"user"`
-}
-
-type SelectModel struct {
- Id int
- Name string
- HasOne *HasOneModel
- HasOneId int
- HasMany []HasManyModel
-}
-
-type HasOneModel struct {
- Id int
-}
-
-type HasManyModel struct {
- Id int
- SelectModelId int
-}
-
-var _ = Describe("Select", func() {
- It("works with User model", func() {
- q := NewQuery(nil, &User{})
-
- b, err := selectQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`SELECT FROM "user" AS "user"`))
- })
-
- It("copies query", func() {
- q1 := NewQuery(nil).Where("1 = 1").Where("2 = 2").Where("3 = 3")
- q2 := q1.Copy().Where("q2 = ?", "v2")
- _ = q1.Where("q1 = ?", "v1")
-
- b, err := selectQuery{q: q2}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal("SELECT * WHERE (1 = 1) AND (2 = 2) AND (3 = 3) AND (q2 = 'v2')"))
- })
-
- It("specifies all columns", func() {
- q := NewQuery(nil, &SelectModel{})
-
- b, err := selectQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`SELECT "select_model"."id", "select_model"."name", "select_model"."has_one_id" FROM "select_models" AS "select_model"`))
- })
-
- It("omits columns in main query", func() {
- q := NewQuery(nil, &SelectModel{}).Column("_", "HasOne")
-
- b, err := selectQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`SELECT "has_one"."id" AS "has_one__id" FROM "select_models" AS "select_model" LEFT JOIN "has_one_models" AS "has_one" ON "has_one"."id" = "select_model"."has_one_id"`))
- })
-
- It("omits columns in join query", func() {
- q := NewQuery(nil, &SelectModel{}).Column("HasOne._")
-
- b, err := selectQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`SELECT "select_model"."id", "select_model"."name", "select_model"."has_one_id" FROM "select_models" AS "select_model" LEFT JOIN "has_one_models" AS "has_one" ON "has_one"."id" = "select_model"."has_one_id"`))
- })
-
- It("specifies all columns for has one", func() {
- q := NewQuery(nil, &SelectModel{Id: 1}).Column("HasOne")
-
- b, err := selectQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`SELECT "select_model"."id", "select_model"."name", "select_model"."has_one_id", "has_one"."id" AS "has_one__id" FROM "select_models" AS "select_model" LEFT JOIN "has_one_models" AS "has_one" ON "has_one"."id" = "select_model"."has_one_id"`))
- })
-
- It("specifies all columns for has many", func() {
- q := NewQuery(nil, &SelectModel{Id: 1}).Column("HasMany")
-
- q, err := q.model.GetJoin("HasMany").manyQuery(nil)
- Expect(err).NotTo(HaveOccurred())
-
- b, err := selectQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`SELECT "has_many_model"."id", "has_many_model"."select_model_id" FROM "has_many_models" AS "has_many_model" WHERE (("has_many_model"."select_model_id") IN ((1)))`))
- })
-
- It("supports multiple groups", func() {
- q := NewQuery(nil).Group("one").Group("two")
- b, err := selectQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`SELECT * GROUP BY "one", "two"`))
- })
-
- It("WhereOr", func() {
- q := NewQuery(nil).Where("1 = 1").WhereOr("1 = 2")
-
- b, err := selectQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`SELECT * WHERE (1 = 1) OR (1 = 2)`))
- })
-
- It("supports subqueries", func() {
- subq := NewQuery(nil, &SelectModel{}).Column("id").Where("name IS NOT NULL")
- q := NewQuery(nil).Where("id IN (?)", subq)
-
- b, err := selectQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`SELECT * WHERE (id IN (SELECT "id" FROM "select_models" AS "select_model" WHERE (name IS NOT NULL)))`))
- })
-
- It("supports locking", func() {
- q := NewQuery(nil).For("UPDATE SKIP LOCKED")
- b, err := selectQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`SELECT * FOR UPDATE SKIP LOCKED`))
- })
-
- It("supports WhereGroup", func() {
- q := NewQuery(nil).Where("TRUE").WhereGroup(func(q *Query) (*Query, error) {
- q = q.Where("FALSE").WhereOr("TRUE")
- return q, nil
- })
- b, err := selectQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`SELECT * WHERE (TRUE) AND ((FALSE) OR (TRUE))`))
- })
-
- It("supports WhereOrGroup", func() {
- q := NewQuery(nil).Where("TRUE").WhereOrGroup(func(q *Query) (*Query, error) {
- q = q.Where("FALSE").Where("TRUE")
- return q, nil
- })
- b, err := selectQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`SELECT * WHERE (TRUE) OR ((FALSE) AND (TRUE))`))
- })
-})
-
-var _ = Describe("Count", func() {
- It("removes LIMIT, OFFSET, and ORDER", func() {
- q := NewQuery(nil).Order("order").Limit(1).Offset(2)
-
- b, err := q.countSelectQuery("count(*)").AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`SELECT count(*)`))
- })
-
- It("does not remove LIMIT, OFFSET, and ORDER from CTE", func() {
- q := NewQuery(nil).
- Column("col1", "col2").
- Order("order").
- Limit(1).
- Offset(2).
- WrapWith("wrapper").
- Table("wrapper").
- Order("order").
- Limit(1).
- Offset(2)
-
- b, err := q.countSelectQuery("count(*)").AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`WITH "wrapper" AS (SELECT "col1", "col2" ORDER BY "order" LIMIT 1 OFFSET 2) SELECT count(*) FROM "wrapper"`))
- })
-
- It("includes has one joins", func() {
- q := NewQuery(nil, &SelectModel{Id: 1}).Column("HasOne")
-
- b, err := q.countSelectQuery("count(*)").AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`SELECT count(*) FROM "select_models" AS "select_model" LEFT JOIN "has_one_models" AS "has_one" ON "has_one"."id" = "select_model"."has_one_id"`))
- })
-
- It("uses CTE when query contains GROUP BY", func() {
- q := NewQuery(nil).Group("one")
-
- b, err := q.countSelectQuery("count(*)").AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`WITH "_count_wrapper" AS (SELECT * GROUP BY "one") SELECT count(*) FROM "_count_wrapper"`))
- })
-
- It("uses CTE when column contains DISTINCT", func() {
- q := NewQuery(nil).ColumnExpr("DISTINCT group_id")
-
- b, err := q.countSelectQuery("count(*)").AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`WITH "_count_wrapper" AS (SELECT DISTINCT group_id) SELECT count(*) FROM "_count_wrapper"`))
- })
-})
-
-var _ = Describe("With", func() {
- It("WrapWith wraps query in CTE", func() {
- q := NewQuery(nil, &SelectModel{}).
- Where("cond1").
- WrapWith("wrapper").
- Table("wrapper").
- Where("cond2")
-
- b, err := selectQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`WITH "wrapper" AS (SELECT "select_model"."id", "select_model"."name", "select_model"."has_one_id" FROM "select_models" AS "select_model" WHERE (cond1)) SELECT * FROM "wrapper" WHERE (cond2)`))
- })
-
- It("generates nested CTE", func() {
- q1 := NewQuery(nil).Table("q1")
- q2 := NewQuery(nil).With("q1", q1).Table("q2", "q1")
- q3 := NewQuery(nil).With("q2", q2).Table("q3", "q2")
-
- b, err := selectQuery{q: q3}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`WITH "q2" AS (WITH "q1" AS (SELECT * FROM "q1") SELECT * FROM "q2", "q1") SELECT * FROM "q3", "q2"`))
- })
-})
-
-type orderTest struct {
- order string
- query string
-}
-
-var _ = Describe("Select Order", func() {
- orderTests := []orderTest{
- {"id", `"id"`},
- {"id asc", `"id" asc`},
- {"id desc", `"id" desc`},
- {"id ASC", `"id" ASC`},
- {"id DESC", `"id" DESC`},
- {"id ASC NULLS FIRST", `"id" ASC NULLS FIRST`},
- }
-
- It("sets order", func() {
- for _, test := range orderTests {
- q := NewQuery(nil).Order(test.order)
-
- b, err := selectQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`SELECT * ORDER BY ` + test.query))
- }
- })
-})
diff --git a/vendor/github.com/go-pg/pg/orm/table.go b/vendor/github.com/go-pg/pg/orm/table.go
deleted file mode 100644
index e01582e..0000000
--- a/vendor/github.com/go-pg/pg/orm/table.go
+++ /dev/null
@@ -1,568 +0,0 @@
-package orm
-
-import (
- "bytes"
- "database/sql"
- "encoding/json"
- "fmt"
- "net"
- "reflect"
- "strings"
- "time"
-
- "github.com/go-pg/pg/internal"
- "github.com/go-pg/pg/types"
-)
-
-var timeType = reflect.TypeOf((*time.Time)(nil)).Elem()
-var ipType = reflect.TypeOf((*net.IP)(nil)).Elem()
-var ipNetType = reflect.TypeOf((*net.IPNet)(nil)).Elem()
-var scannerType = reflect.TypeOf((*sql.Scanner)(nil)).Elem()
-var nullBoolType = reflect.TypeOf((*sql.NullBool)(nil)).Elem()
-var nullFloatType = reflect.TypeOf((*sql.NullFloat64)(nil)).Elem()
-var nullIntType = reflect.TypeOf((*sql.NullInt64)(nil)).Elem()
-var nullStringType = reflect.TypeOf((*sql.NullString)(nil)).Elem()
-
-type Table struct {
- Type reflect.Type
- zeroStruct reflect.Value
-
- TypeName string
- Name types.Q
- Alias types.Q
- ModelName string
-
- Fields []*Field // PKs + DataFields
- PKs []*Field
- DataFields []*Field
- FieldsMap map[string]*Field
-
- Methods map[string]*Method
- Relations map[string]*Relation
-
- flags uint8
-}
-
-func (t *Table) SetFlag(flag uint8) {
- t.flags |= flag
-}
-
-func (t *Table) HasFlag(flag uint8) bool {
- if t == nil {
- return false
- }
- return t.flags&flag != 0
-}
-
-func (t *Table) HasField(field string) bool {
- _, err := t.GetField(field)
- return err == nil
-}
-
-func (t *Table) checkPKs() error {
- if len(t.PKs) == 0 {
- return fmt.Errorf("model=%s does not have primary keys", t.Type.Name())
- }
- return nil
-}
-
-func (t *Table) AddField(field *Field) {
- t.Fields = append(t.Fields, field)
- if field.HasFlag(PrimaryKeyFlag) {
- t.PKs = append(t.PKs, field)
- } else {
- t.DataFields = append(t.DataFields, field)
- }
- t.FieldsMap[field.SQLName] = field
-}
-
-func (t *Table) GetField(fieldName string) (*Field, error) {
- field, ok := t.FieldsMap[fieldName]
- if !ok {
- return nil, fmt.Errorf("can't find column=%s in table=%s", fieldName, t.Name)
- }
- return field, nil
-}
-
-func (t *Table) AppendParam(b []byte, strct reflect.Value, name string) ([]byte, bool) {
- if field, ok := t.FieldsMap[name]; ok {
- b = field.AppendValue(b, strct, 1)
- return b, true
- }
-
- if method, ok := t.Methods[name]; ok {
- b = method.AppendValue(b, strct.Addr(), 1)
- return b, true
- }
-
- return b, false
-}
-
-func (t *Table) addRelation(rel *Relation) {
- if t.Relations == nil {
- t.Relations = make(map[string]*Relation)
- }
- t.Relations[rel.Field.GoName] = rel
-}
-
-func newTable(typ reflect.Type) *Table {
- table, ok := Tables.tables[typ]
- if ok {
- return table
- }
-
- modelName := internal.Underscore(typ.Name())
- table = &Table{
- Type: typ,
- zeroStruct: reflect.Zero(typ),
-
- TypeName: internal.ToExported(typ.Name()),
- Name: types.Q(types.AppendField(nil, tableNameInflector(modelName), 1)),
- Alias: types.Q(types.AppendField(nil, modelName, 1)),
- ModelName: modelName,
-
- Fields: make([]*Field, 0, typ.NumField()),
- FieldsMap: make(map[string]*Field, typ.NumField()),
- }
- Tables.tables[typ] = table
-
- table.addFields(typ, nil)
- typ = reflect.PtrTo(typ)
-
- if typ.Implements(afterQueryHookType) {
- table.SetFlag(AfterQueryHookFlag)
- }
- if typ.Implements(afterSelectHookType) {
- table.SetFlag(AfterSelectHookFlag)
- }
- if typ.Implements(beforeInsertHookType) {
- table.SetFlag(BeforeInsertHookFlag)
- }
- if typ.Implements(afterInsertHookType) {
- table.SetFlag(AfterInsertHookFlag)
- }
- if typ.Implements(beforeUpdateHookType) {
- table.SetFlag(BeforeUpdateHookFlag)
- }
- if typ.Implements(afterUpdateHookType) {
- table.SetFlag(AfterUpdateHookFlag)
- }
- if typ.Implements(beforeDeleteHookType) {
- table.SetFlag(BeforeDeleteHookFlag)
- }
- if typ.Implements(afterDeleteHookType) {
- table.SetFlag(AfterDeleteHookFlag)
- }
-
- if table.Methods == nil {
- table.Methods = make(map[string]*Method)
- }
- for i := 0; i < typ.NumMethod(); i++ {
- m := typ.Method(i)
- if m.PkgPath != "" {
- continue
- }
- if m.Type.NumIn() > 1 {
- continue
- }
- if m.Type.NumOut() != 1 {
- continue
- }
-
- retType := m.Type.Out(0)
- method := Method{
- Index: m.Index,
-
- appender: types.Appender(retType),
- }
-
- table.Methods[m.Name] = &method
- }
-
- return table
-}
-
-func (t *Table) addFields(typ reflect.Type, baseIndex []int) {
- for i := 0; i < typ.NumField(); i++ {
- f := typ.Field(i)
-
- // Make a copy so slice is not shared between fields.
- var index []int
- index = append(index, baseIndex...)
-
- if f.Anonymous {
- embeddedTable := newTable(indirectType(f.Type))
-
- pgTag := parseTag(f.Tag.Get("pg"))
- if _, ok := pgTag.Options["override"]; ok {
- t.TypeName = embeddedTable.TypeName
- t.Name = embeddedTable.Name
- t.Alias = embeddedTable.Alias
- t.ModelName = embeddedTable.ModelName
- }
-
- t.addFields(embeddedTable.Type, append(index, f.Index...))
- continue
- }
-
- field := t.newField(f, index)
- if field != nil {
- t.AddField(field)
- }
- }
-}
-
-func (t *Table) getField(name string) *Field {
- for _, f := range t.Fields {
- if f.GoName == name {
- return f
- }
- }
-
- f, ok := t.Type.FieldByName(name)
- if !ok {
- return nil
- }
- return t.newField(f, nil)
-}
-
-func (t *Table) newField(f reflect.StructField, index []int) *Field {
- sqlTag := parseTag(f.Tag.Get("sql"))
-
- switch f.Name {
- case "tableName", "TableName":
- if index != nil {
- return nil
- }
- if sqlTag.Name != "" {
- if isPostgresKeyword(sqlTag.Name) {
- sqlTag.Name = `"` + sqlTag.Name + `"`
- }
- t.Name = types.Q(sqlTag.Name)
- }
- if alias, ok := sqlTag.Options["alias"]; ok {
- t.Alias = types.Q(alias)
- }
- return nil
- }
-
- if f.PkgPath != "" {
- return nil
- }
-
- skip := sqlTag.Name == "-"
- if skip || sqlTag.Name == "" {
- sqlTag.Name = internal.Underscore(f.Name)
- }
-
- if field, ok := t.FieldsMap[sqlTag.Name]; ok {
- if field.GoName == f.Name {
- return field
- }
- }
-
- field := Field{
- Type: indirectType(f.Type),
-
- GoName: f.Name,
- SQLName: sqlTag.Name,
- Column: types.Q(types.AppendField(nil, sqlTag.Name, 1)),
-
- Index: append(index, f.Index...),
- }
-
- if _, ok := sqlTag.Options["notnull"]; ok {
- field.SetFlag(NotNullFlag)
- }
- if _, ok := sqlTag.Options["unique"]; ok {
- field.SetFlag(UniqueFlag)
- }
- if v, ok := sqlTag.Options["default"]; ok {
- v, ok = unquote(v)
- if ok {
- field.Default = types.Q(types.AppendString(nil, v, 1))
- } else {
- field.Default = types.Q(v)
- }
- }
-
- if len(t.PKs) == 0 && (field.SQLName == "id" || field.SQLName == "uuid") {
- field.SetFlag(PrimaryKeyFlag)
- } else if _, ok := sqlTag.Options["pk"]; ok {
- field.SetFlag(PrimaryKeyFlag)
- } else if strings.HasSuffix(field.SQLName, "_id") ||
- strings.HasSuffix(field.SQLName, "_uuid") {
- field.SetFlag(ForeignKeyFlag)
- }
-
- pgTag := parseTag(f.Tag.Get("pg"))
- if _, ok := pgTag.Options["array"]; ok {
- field.SetFlag(ArrayFlag)
- }
-
- field.SQLType = fieldSQLType(&field, sqlTag)
- if strings.HasSuffix(field.SQLType, "[]") {
- field.SetFlag(ArrayFlag)
- }
-
- if _, ok := pgTag.Options["json_use_number"]; ok {
- field.append = types.Appender(f.Type)
- field.scan = scanJSONValue
- } else if field.HasFlag(ArrayFlag) {
- field.append = types.ArrayAppender(f.Type)
- field.scan = types.ArrayScanner(f.Type)
- } else if _, ok := pgTag.Options["hstore"]; ok {
- field.append = types.HstoreAppender(f.Type)
- field.scan = types.HstoreScanner(f.Type)
- } else {
- field.append = types.Appender(f.Type)
- field.scan = types.Scanner(f.Type)
- }
- field.isZero = isZeroFunc(f.Type)
-
- if !skip && isColumn(f.Type) {
- return &field
- }
-
- switch field.Type.Kind() {
- case reflect.Slice:
- elemType := indirectType(field.Type.Elem())
- if elemType.Kind() != reflect.Struct {
- break
- }
-
- joinTable := newTable(elemType)
-
- fk, ok := pgTag.Options["fk"]
- if !ok {
- fk = t.TypeName
- }
-
- if m2mTable, _ := pgTag.Options["many2many"]; m2mTable != "" {
- m2mTableAlias := m2mTable
- if ind := strings.IndexByte(m2mTable, '.'); ind >= 0 {
- m2mTableAlias = m2mTable[ind+1:]
- }
-
- joinFK, ok := pgTag.Options["joinFK"]
- if !ok {
- joinFK = joinTable.TypeName
- }
-
- t.addRelation(&Relation{
- Type: Many2ManyRelation,
- Field: &field,
- JoinTable: joinTable,
- M2MTableName: types.Q(m2mTable),
- M2MTableAlias: types.Q(m2mTableAlias),
- BasePrefix: internal.Underscore(fk + "_"),
- JoinPrefix: internal.Underscore(joinFK + "_"),
- })
- return nil
- }
-
- s, polymorphic := pgTag.Options["polymorphic"]
- if polymorphic {
- fk = s
- }
-
- fks := foreignKeys(t, joinTable, fk, t.TypeName)
- if len(fks) > 0 {
- t.addRelation(&Relation{
- Type: HasManyRelation,
- Polymorphic: polymorphic,
- Field: &field,
- FKs: fks,
- JoinTable: joinTable,
- BasePrefix: internal.Underscore(fk + "_"),
- })
- return nil
- }
- case reflect.Struct:
- joinTable := newTable(field.Type)
- if len(joinTable.Fields) == 0 {
- break
- }
-
- for _, ff := range joinTable.FieldsMap {
- ff = ff.Copy()
- ff.SQLName = field.SQLName + "__" + ff.SQLName
- ff.Column = types.Q(types.AppendField(nil, ff.SQLName, 1))
- ff.Index = append(field.Index, ff.Index...)
- if _, ok := t.FieldsMap[ff.SQLName]; !ok {
- t.FieldsMap[ff.SQLName] = ff
- }
- }
-
- if t.tryHasOne(joinTable, &field, pgTag) ||
- t.tryBelongsToOne(joinTable, &field, pgTag) {
- t.FieldsMap[field.SQLName] = &field
- return nil
- }
- }
-
- if skip {
- t.FieldsMap[field.SQLName] = &field
- return nil
- }
-
- return &field
-}
-
-func isPostgresKeyword(s string) bool {
- switch s {
- case "user":
- return true
- }
- return false
-}
-
-func isColumn(typ reflect.Type) bool {
- return typ.Implements(scannerType) || reflect.PtrTo(typ).Implements(scannerType)
-}
-
-func fieldSQLType(field *Field, sqlTag *tag) string {
- if v, ok := sqlTag.Options["type"]; ok {
- field.SetFlag(customTypeFlag)
- v, _ := unquote(v)
- return v
- }
-
- if field.HasFlag(ArrayFlag) {
- sqlType := sqlType(field.Type.Elem())
- return sqlType + "[]"
- }
-
- sqlType := sqlType(field.Type)
- if field.HasFlag(PrimaryKeyFlag) {
- switch sqlType {
- case "smallint":
- return "smallserial"
- case "integer":
- return "serial"
- case "bigint":
- return "bigserial"
- }
- }
- return sqlType
-}
-
-func sqlType(typ reflect.Type) string {
- switch typ {
- case timeType:
- return "timestamptz"
- case ipType:
- return "inet"
- case ipNetType:
- return "cidr"
- case nullBoolType:
- return "boolean"
- case nullFloatType:
- return "double precision"
- case nullIntType:
- return "bigint"
- case nullStringType:
- return "text"
- }
-
- switch typ.Kind() {
- case reflect.Int8, reflect.Uint8, reflect.Int16:
- return "smallint"
- case reflect.Uint16, reflect.Int32:
- return "integer"
- case reflect.Uint32, reflect.Int64, reflect.Int:
- return "bigint"
- case reflect.Uint, reflect.Uint64:
- return "decimal"
- case reflect.Float32:
- return "real"
- case reflect.Float64:
- return "double precision"
- case reflect.Bool:
- return "boolean"
- case reflect.String:
- return "text"
- case reflect.Map, reflect.Struct:
- return "jsonb"
- case reflect.Array, reflect.Slice:
- if typ.Elem().Kind() == reflect.Uint8 {
- return "bytea"
- }
- return "jsonb"
- default:
- return typ.Kind().String()
- }
-}
-
-func foreignKeys(base, join *Table, fk, fieldName string) []*Field {
- var fks []*Field
-
- for _, pk := range base.PKs {
- fkName := fk + pk.GoName
- if f := join.getField(fkName); f != nil {
- fks = append(fks, f)
- }
- }
-
- if len(fks) > 0 {
- return fks
- }
-
- if fk != "" && fk != fieldName {
- if f := join.getField(fk); f != nil {
- fks = append(fks, f)
- }
- }
- return fks
-}
-
-func (t *Table) tryHasOne(joinTable *Table, field *Field, tag *tag) bool {
- fk, ok := tag.Options["fk"]
- if !ok {
- fk = field.GoName
- }
-
- fks := foreignKeys(joinTable, t, fk, field.GoName)
- if len(fks) > 0 {
- t.addRelation(&Relation{
- Type: HasOneRelation,
- Field: field,
- FKs: fks,
- JoinTable: joinTable,
- })
- return true
- }
- return false
-}
-
-func (t *Table) tryBelongsToOne(joinTable *Table, field *Field, tag *tag) bool {
- fk, ok := tag.Options["fk"]
- if !ok {
- fk = t.TypeName
- }
-
- fks := foreignKeys(t, joinTable, fk, t.TypeName)
- if len(fks) > 0 {
- t.addRelation(&Relation{
- Type: BelongsToRelation,
- Field: field,
- FKs: fks,
- JoinTable: joinTable,
- })
- return true
- }
- return false
-}
-
-func scanJSONValue(v reflect.Value, b []byte) error {
- if !v.CanSet() {
- return fmt.Errorf("pg: Scan(non-pointer %s)", v.Type())
- }
- if b == nil {
- v.Set(reflect.New(v.Type()).Elem())
- return nil
- }
- dec := json.NewDecoder(bytes.NewReader(b))
- dec.UseNumber()
- return dec.Decode(v.Addr().Interface())
-}
diff --git a/vendor/github.com/go-pg/pg/orm/table_params.go b/vendor/github.com/go-pg/pg/orm/table_params.go
deleted file mode 100644
index 3d60382..0000000
--- a/vendor/github.com/go-pg/pg/orm/table_params.go
+++ /dev/null
@@ -1,29 +0,0 @@
-package orm
-
-import "reflect"
-
-type tableParams struct {
- table *Table
- strct reflect.Value
-}
-
-func newTableParams(strct interface{}) (*tableParams, bool) {
- v := reflect.ValueOf(strct)
- if !v.IsValid() {
- return nil, false
- }
-
- v = reflect.Indirect(v)
- if v.Kind() != reflect.Struct {
- return nil, false
- }
-
- return &tableParams{
- table: Tables.Get(v.Type()),
- strct: v,
- }, true
-}
-
-func (m tableParams) AppendParam(b []byte, f QueryFormatter, name string) ([]byte, bool) {
- return m.table.AppendParam(b, m.strct, name)
-}
diff --git a/vendor/github.com/go-pg/pg/orm/table_test.go b/vendor/github.com/go-pg/pg/orm/table_test.go
deleted file mode 100644
index c91d4b9..0000000
--- a/vendor/github.com/go-pg/pg/orm/table_test.go
+++ /dev/null
@@ -1,168 +0,0 @@
-package orm_test
-
-import (
- "reflect"
-
- "github.com/go-pg/pg/orm"
-
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-)
-
-type A struct {
- Id int
-}
-
-func (A) Method() int {
- return 10
-}
-
-type B struct {
- A
-}
-
-var _ = Describe("embedded Model", func() {
- var strct reflect.Value
- var table *orm.Table
-
- BeforeEach(func() {
- strct = reflect.ValueOf(B{A: A{Id: 1}})
- table = orm.Tables.Get(strct.Type())
- })
-
- It("has fields", func() {
- Expect(table.Fields).To(HaveLen(1))
- Expect(table.FieldsMap).To(HaveLen(1))
-
- id, ok := table.FieldsMap["id"]
- Expect(ok).To(BeTrue())
- Expect(id.GoName).To(Equal("Id"))
- Expect(id.SQLName).To(Equal("id"))
- Expect(string(id.Column)).To(Equal(`"id"`))
- Expect(id.HasFlag(orm.PrimaryKeyFlag)).To(BeTrue())
- Expect(string(id.AppendValue(nil, strct, 1))).To(Equal("1"))
-
- Expect(table.PKs).To(HaveLen(1))
- Expect(table.PKs[0]).To(Equal(id))
- })
-
- It("has methods", func() {
- Expect(table.Methods).To(HaveLen(1))
-
- m, ok := table.Methods["Method"]
- Expect(ok).To(BeTrue())
- Expect(m.Index).To(Equal(0))
- Expect(string(m.AppendValue(nil, strct, 1))).To(Equal("10"))
- })
-})
-
-type C struct {
- Name int `sql:",pk"`
- Id int
- UUID int
-}
-
-var _ = Describe("primary key annotation", func() {
- var table *orm.Table
-
- BeforeEach(func() {
- strct := reflect.ValueOf(C{})
- table = orm.Tables.Get(strct.Type())
- })
-
- It("has precedence over auto-detection", func() {
- Expect(table.PKs).To(HaveLen(1))
- Expect(table.PKs[0].GoName).To(Equal("Name"))
- })
-})
-
-type D struct {
- UUID int
-}
-
-var _ = Describe("uuid field", func() {
- var table *orm.Table
-
- BeforeEach(func() {
- strct := reflect.ValueOf(D{})
- table = orm.Tables.Get(strct.Type())
- })
-
- It("is detected as primary key", func() {
- Expect(table.PKs).To(HaveLen(1))
- Expect(table.PKs[0].GoName).To(Equal("UUID"))
- })
-})
-
-type E struct {
- Id int
- StructField struct {
- Foo string
- Bar string
- }
-}
-
-var _ = Describe("struct field", func() {
- var table *orm.Table
-
- BeforeEach(func() {
- strct := reflect.ValueOf(E{})
- table = orm.Tables.Get(strct.Type())
- })
-
- It("is present in the list", func() {
- Expect(table.Fields).To(HaveLen(2))
-
- _, ok := table.FieldsMap["struct_field"]
- Expect(ok).To(BeTrue())
- })
-})
-
-type f struct {
- Id int
- G *g
-}
-
-type g struct {
- Id int
- FId int
- F *f
-}
-
-var _ = Describe("unexported types", func() {
- It("work with belongs to relation", func() {
- strct := reflect.ValueOf(f{})
- table := orm.Tables.Get(strct.Type())
-
- rel, ok := table.Relations["G"]
- Expect(ok).To(BeTrue())
- Expect(rel.Type).To(Equal(orm.BelongsToRelation))
- })
-
- It("work with has one relation", func() {
- strct := reflect.ValueOf(g{})
- table := orm.Tables.Get(strct.Type())
-
- rel, ok := table.Relations["F"]
- Expect(ok).To(BeTrue())
- Expect(rel.Type).To(Equal(orm.HasOneRelation))
- })
-})
-
-type H struct {
- I *I
-}
-
-type I struct {
- H *H
-}
-
-var _ = Describe("model with circular reference", func() {
- It("works", func() {
- table := orm.Tables.Get(reflect.TypeOf(H{}))
- Expect(table).NotTo(BeNil())
-
- table = orm.Tables.Get(reflect.TypeOf(I{}))
- Expect(table).NotTo(BeNil())
- })
-})
diff --git a/vendor/github.com/go-pg/pg/orm/tables.go b/vendor/github.com/go-pg/pg/orm/tables.go
deleted file mode 100644
index d53082b..0000000
--- a/vendor/github.com/go-pg/pg/orm/tables.go
+++ /dev/null
@@ -1,39 +0,0 @@
-package orm
-
-import (
- "fmt"
- "reflect"
- "sync"
-)
-
-var Tables = newTables()
-
-type tables struct {
- mu sync.RWMutex
- tables map[reflect.Type]*Table
-}
-
-func newTables() *tables {
- return &tables{
- tables: make(map[reflect.Type]*Table),
- }
-}
-
-func (t *tables) Get(typ reflect.Type) *Table {
- if typ.Kind() != reflect.Struct {
- panic(fmt.Errorf("got %s, wanted %s", typ.Kind(), reflect.Struct))
- }
-
- t.mu.RLock()
- table, ok := t.tables[typ]
- t.mu.RUnlock()
- if ok {
- return table
- }
-
- t.mu.Lock()
- table = newTable(typ)
- t.mu.Unlock()
-
- return table
-}
diff --git a/vendor/github.com/go-pg/pg/orm/tag.go b/vendor/github.com/go-pg/pg/orm/tag.go
deleted file mode 100644
index 260af53..0000000
--- a/vendor/github.com/go-pg/pg/orm/tag.go
+++ /dev/null
@@ -1,139 +0,0 @@
-package orm
-
-import (
- "github.com/go-pg/pg/internal/parser"
-)
-
-type tag struct {
- Name string
- Options map[string]string
-}
-
-func parseTag(s string) *tag {
- p := &tagParser{
- Parser: parser.NewString(s),
- }
- p.parseKey()
- return &p.tag
-}
-
-type tagParser struct {
- *parser.Parser
-
- tag tag
- key string
-}
-
-func (p *tagParser) setTagOption(key, value string) {
- if p.tag.Options == nil {
- p.tag.Options = make(map[string]string)
- if value == "" && p.tag.Name == "" {
- p.tag.Name = key
- return
- }
- }
- if key != "" {
- p.tag.Options[key] = value
- }
-}
-
-func (p *tagParser) parseKey() {
- var b []byte
- for p.Valid() {
- c := p.Read()
- switch c {
- case ',':
- p.Skip(' ')
- p.setTagOption(string(b), "")
- p.parseKey()
- return
- case ':':
- p.key = string(b)
- p.parseValue()
- return
- default:
- b = append(b, c)
- }
- }
- if len(b) > 0 {
- p.setTagOption(string(b), "")
- }
-}
-
-func (p *tagParser) parseValue() {
- const quote = '\''
-
- c := p.Peek()
- if c == quote {
- p.parseQuotedValue()
- return
- }
-
- var b []byte
- for p.Valid() {
- c = p.Read()
- switch c {
- case '\\':
- c = p.Read()
- b = append(b, c)
- case ',':
- p.Skip(' ')
- p.setTagOption(p.key, string(b))
- p.parseKey()
- return
- default:
- b = append(b, c)
- }
- }
- if len(b) > 0 {
- p.setTagOption(p.key, string(b))
- }
-}
-
-func (p *tagParser) parseQuotedValue() {
- const quote = '\''
-
- if !p.Skip(quote) {
- panic("not reached")
- }
-
- var b []byte
- b = append(b, quote)
-
- for p.Valid() {
- bb, ok := p.ReadSep(quote)
- if !ok {
- b = append(b, bb...)
- break
- }
-
- if len(bb) > 0 && bb[len(bb)-1] == '\\' {
- b = append(b, bb[:len(bb)-1]...)
- b = append(b, quote)
- continue
- }
-
- b = append(b, bb...)
- b = append(b, quote)
-
- p.setTagOption(p.key, string(b))
- p.parseKey()
- return
- }
-
- if len(b) > 0 {
- p.setTagOption(p.key, string(b))
- }
-}
-
-func unquote(s string) (string, bool) {
- const quote = '\''
-
- if len(s) < 2 {
- return s, false
- }
- if s[0] == quote && s[len(s)-1] == quote {
- return s[1 : len(s)-1], true
- }
- return s, false
-}
diff --git a/vendor/github.com/go-pg/pg/orm/tag_test.go b/vendor/github.com/go-pg/pg/orm/tag_test.go
deleted file mode 100644
index 0d953d7..0000000
--- a/vendor/github.com/go-pg/pg/orm/tag_test.go
+++ /dev/null
@@ -1,42 +0,0 @@
-package orm
-
-import (
- "testing"
-)
-
-var tagTests = []struct {
- tag string
- name string
- opts map[string]string
-}{
- {"", "", nil},
-
- {"hello", "hello", nil},
- {",hello", "", map[string]string{"hello": ""}},
- {"hello:world", "", map[string]string{"hello": "world"}},
- {"hello:world,foo:bar", "", map[string]string{"hello": "world", "foo": "bar"}},
- {"hello:'world1,world2'", "", map[string]string{"hello": "'world1,world2'"}},
- {`hello:'D\'Angelo', foo:bar`, "", map[string]string{"hello": "'D'Angelo'", "foo": "bar"}},
-}
-
-func TestTagParser(t *testing.T) {
- for _, test := range tagTests {
- tag := parseTag(test.tag)
- if tag.Name != test.name {
- t.Fatalf("got %q, wanted %q (tag=%q)", tag.Name, test.name, test.tag)
- }
-
- if len(tag.Options) != len(test.opts) {
- t.Fatalf(
- "got %#v options, wanted %#v (tag=%q)",
- tag.Options, test.opts, test.tag,
- )
- }
-
- for k, v := range test.opts {
- if tag.Options[k] != v {
- t.Fatalf("got %s=%q, wanted %q (tag=%q)", k, tag.Options[k], v, test.tag)
- }
- }
- }
-}
diff --git a/vendor/github.com/go-pg/pg/orm/update.go b/vendor/github.com/go-pg/pg/orm/update.go
deleted file mode 100644
index d13cd81..0000000
--- a/vendor/github.com/go-pg/pg/orm/update.go
+++ /dev/null
@@ -1,214 +0,0 @@
-package orm
-
-import (
- "errors"
- "reflect"
-
- "github.com/go-pg/pg/internal"
-)
-
-func Update(db DB, model ...interface{}) error {
- res, err := NewQuery(db, model...).Update()
- if err != nil {
- return err
- }
- return internal.AssertOneRow(res.RowsAffected())
-}
-
-type updateQuery struct {
- q *Query
-
- omitZero bool
-}
-
-var _ QueryAppender = (*updateQuery)(nil)
-
-func (q updateQuery) Copy() QueryAppender {
- return updateQuery{
- q: q.q.Copy(),
- }
-}
-
-func (q updateQuery) Query() *Query {
- return q.q
-}
-
-func (q updateQuery) AppendQuery(b []byte) ([]byte, error) {
- if q.q.stickyErr != nil {
- return nil, q.q.stickyErr
- }
-
- var err error
-
- if len(q.q.with) > 0 {
- b, err = q.q.appendWith(b)
- if err != nil {
- return nil, err
- }
- }
-
- b = append(b, "UPDATE "...)
- b = q.q.appendFirstTableWithAlias(b)
-
- b, err = q.mustAppendSet(b)
- if err != nil {
- return nil, err
- }
-
- if q.q.hasOtherTables() || q.q.modelHasData() {
- b = append(b, " FROM "...)
- b = q.q.appendOtherTables(b)
- b, err = q.appendModelData(b)
- if err != nil {
- return nil, err
- }
- }
-
- b, err = q.q.mustAppendWhere(b)
- if err != nil {
- return nil, err
- }
-
- if len(q.q.returning) > 0 {
- b = q.q.appendReturning(b)
- }
-
- return b, nil
-}
-
-func (q updateQuery) mustAppendSet(b []byte) ([]byte, error) {
- if len(q.q.set) > 0 {
- b = q.q.appendSet(b)
- return b, nil
- }
-
- if q.q.model == nil {
- return nil, errors.New("pg: Model is nil")
- }
-
- b = append(b, " SET "...)
-
- value := q.q.model.Value()
- var err error
- if value.Kind() == reflect.Struct {
- b, err = q.appendSetStruct(b, value)
- } else {
- b, err = q.appendSetSlice(b, value)
- }
- if err != nil {
- return nil, err
- }
-
- return b, nil
-}
-
-func (q updateQuery) appendSetStruct(b []byte, strct reflect.Value) ([]byte, error) {
- fields, err := q.q.getFields()
- if err != nil {
- return nil, err
- }
-
- if len(fields) == 0 {
- fields = q.q.model.Table().DataFields
- }
-
- pos := len(b)
- for _, f := range fields {
- if q.omitZero && f.OmitZero(strct) {
- continue
- }
-
- if len(b) != pos {
- b = append(b, ", "...)
- pos = len(b)
- }
-
- b = append(b, f.Column...)
- b = append(b, " = "...)
- b = f.AppendValue(b, strct, 1)
- }
- return b, nil
-}
-
-func (q updateQuery) appendSetSlice(b []byte, slice reflect.Value) ([]byte, error) {
- fields, err := q.q.getFields()
- if err != nil {
- return nil, err
- }
-
- if len(fields) == 0 {
- fields = q.q.model.Table().DataFields
- }
-
- for i, f := range fields {
- if i > 0 {
- b = append(b, ", "...)
- }
-
- b = append(b, f.Column...)
- b = append(b, " = "...)
- b = append(b, "_data."...)
- b = append(b, f.Column...)
- }
- return b, nil
-}
-
-func (q updateQuery) appendModelData(b []byte) ([]byte, error) {
- if !q.q.hasModel() {
- return b, nil
- }
-
- v := q.q.model.Value()
- if v.Kind() != reflect.Slice || v.Len() == 0 {
- return b, nil
- }
-
- columns, err := q.q.getDataFields()
- if err != nil {
- return nil, err
- }
-
- if len(columns) > 0 {
- columns = append(columns, q.q.model.Table().PKs...)
- } else {
- columns = q.q.model.Table().Fields
- }
-
- return appendSliceValues(b, columns, v), nil
-}
-
-func appendSliceValues(b []byte, fields []*Field, slice reflect.Value) []byte {
- b = append(b, "(VALUES ("...)
- for i := 0; i < slice.Len(); i++ {
- el := slice.Index(i)
- if el.Kind() == reflect.Interface {
- el = el.Elem()
- }
- b = appendValues(b, fields, reflect.Indirect(el))
- if i != slice.Len()-1 {
- b = append(b, "), ("...)
- }
- }
- b = append(b, ")) AS _data("...)
- b = appendColumns(b, fields)
- b = append(b, ")"...)
- return b
-}
-
-func appendValues(b []byte, fields []*Field, v reflect.Value) []byte {
- for i, f := range fields {
- if i > 0 {
- b = append(b, ", "...)
- }
- if f.OmitZero(v) {
- b = append(b, "NULL"...)
- } else {
- b = f.AppendValue(b, v, 1)
- }
- if f.HasFlag(customTypeFlag) {
- b = append(b, "::"...)
- b = append(b, f.SQLType...)
- }
- }
- return b
-}
diff --git a/vendor/github.com/go-pg/pg/orm/update_test.go b/vendor/github.com/go-pg/pg/orm/update_test.go
deleted file mode 100644
index bd062ef..0000000
--- a/vendor/github.com/go-pg/pg/orm/update_test.go
+++ /dev/null
@@ -1,55 +0,0 @@
-package orm
-
-import (
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-)
-
-type UpdateTest struct {
- Id int
- Value string `sql:"type:mytype"`
-}
-
-var _ = Describe("Update", func() {
- It("updates model", func() {
- q := NewQuery(nil, &UpdateTest{})
-
- b, err := updateQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`UPDATE "update_tests" AS "update_test" SET "value" = NULL WHERE "update_test"."id" = NULL`))
- })
-
- It("omits zero", func() {
- q := NewQuery(nil, &UpdateTest{})
-
- b, err := updateQuery{q: q, omitZero: true}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`UPDATE "update_tests" AS "update_test" SET WHERE "update_test"."id" = NULL`))
- })
-
- It("bulk updates", func() {
- q := NewQuery(nil, &UpdateTest{}).
- Model(&UpdateTest{
- Id: 1,
- Value: "hello",
- }, &UpdateTest{
- Id: 2,
- })
-
- b, err := updateQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`UPDATE "update_tests" AS "update_test" SET "value" = _data."value" FROM (VALUES (1, 'hello'::mytype), (2, NULL::mytype)) AS _data("id", "value") WHERE "update_test"."id" = _data."id"`))
- })
-
- It("supports WITH", func() {
- q := NewQuery(nil, &UpdateTest{}).
- WrapWith("wrapper").
- Model(&UpdateTest{}).
- Table("wrapper").
- Where("update_test.id = wrapper.id")
-
- b, err := updateQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(`WITH "wrapper" AS (SELECT "update_test"."id", "update_test"."value" FROM "update_tests" AS "update_test") UPDATE "update_tests" AS "update_test" SET "value" = NULL FROM "wrapper" WHERE (update_test.id = wrapper.id)`))
- })
-})
diff --git a/vendor/github.com/go-pg/pg/orm/url_values.go b/vendor/github.com/go-pg/pg/orm/url_values.go
deleted file mode 100644
index c090912..0000000
--- a/vendor/github.com/go-pg/pg/orm/url_values.go
+++ /dev/null
@@ -1,185 +0,0 @@
-package orm
-
-import (
- "fmt"
- "net/url"
- "strconv"
- "strings"
-
- "github.com/go-pg/pg/types"
-)
-
-// URLFilters is used with Query.Apply to add WHERE clauses from the URL values:
-// - ?foo=bar - Where(`"foo" = 'bar'`)
-// - ?foo=hello&foo=world - Where(`"foo" IN ('hello','world')`)
-// - ?foo__exclude=bar - Where(`"foo" != 'bar'`)
-// - ?foo__ieq=bar - Where(`"foo" ILIKE 'bar'`)
-// - ?foo__match=bar - Where(`"foo" SIMILAR TO 'bar'`)
-// - ?foo__gt=42 - Where(`"foo" > 42`)
-// - ?foo__gte=42 - Where(`"foo" >= 42`)
-// - ?foo__lt=42 - Where(`"foo" < 42`)
-// - ?foo__lte=42 - Where(`"foo" <= 42`)
-func URLFilters(urlValues url.Values) func(*Query) (*Query, error) {
- return func(q *Query) (*Query, error) {
- for fieldName, values := range urlValues {
- var operation string
- if i := strings.Index(fieldName, "__"); i != -1 {
- fieldName, operation = fieldName[:i], fieldName[i+2:]
- }
-
- if q.model.Table().HasField(fieldName) {
- q = addOperator(q, fieldName, operation, values)
- }
- }
- return q, nil
- }
-}
-
-func addOperator(q *Query, fieldName, operator string, values []string) *Query {
- switch operator {
- case "gt":
- q = forEachValue(q, fieldName, values, "? > ?")
- case "gte":
- q = forEachValue(q, fieldName, values, "? >= ?")
- case "lt":
- q = forEachValue(q, fieldName, values, "? < ?")
- case "lte":
- q = forEachValue(q, fieldName, values, "? <= ?")
- case "ieq":
- q = forEachValue(q, fieldName, values, "? ILIKE ?")
- case "match":
- q = forEachValue(q, fieldName, values, "? SIMILAR TO ?")
- case "exclude":
- q = forAllValues(q, fieldName, values, "? != ?", "? NOT IN (?)")
- case "", "include":
- q = forAllValues(q, fieldName, values, "? = ?", "? IN (?)")
- }
- return q
-}
-
-func forEachValue(q *Query, fieldName string, values []string, queryTemplate string) *Query {
- for _, value := range values {
- q = q.Where(queryTemplate, types.F(fieldName), value)
- }
- return q
-}
-
-func forAllValues(q *Query, fieldName string, values []string, queryTemplate, queryArrayTemplate string) *Query {
- if len(values) > 1 {
- q = q.Where(queryArrayTemplate, types.F(fieldName), types.In(values))
- } else {
- q = q.Where(queryTemplate, types.F(fieldName), values[0])
- }
- return q
-}
-
-type Pager struct {
- Limit int
- Offset int
-
- // Default max limit is 1000.
- MaxLimit int
- // Default max offset is 1000000.
- MaxOffset int
-
- stickyErr error
-}
-
-func NewPager(values url.Values) *Pager {
- p := &Pager{}
- p.SetURLValues(values)
- return p
-}
-
-func (p *Pager) SetURLValues(values url.Values) {
- limit, err := intParam(values, "limit")
- if err != nil {
- p.stickyErr = err
- return
- }
- p.Limit = limit
-
- page, err := intParam(values, "page")
- if err != nil {
- p.stickyErr = err
- return
- }
- if page > 0 {
- p.SetPage(page)
- }
-}
-
-func (p *Pager) maxLimit() int {
- if p.MaxLimit > 0 {
- return p.MaxLimit
- }
- return 1000
-}
-
-func (p *Pager) maxOffset() int {
- if p.MaxOffset > 0 {
- return p.MaxOffset
- }
- return 1000000
-}
-
-func (p *Pager) GetLimit() int {
- const defaultLimit = 100
-
- if p.Limit <= 0 {
- return defaultLimit
- }
- if p.Limit > p.maxLimit() {
- return p.maxLimit()
- }
- return p.Limit
-}
-
-func (p *Pager) GetOffset() int {
- if p.Offset > p.maxOffset() {
- return p.maxOffset()
- }
- if p.Offset > 0 {
- return p.Offset
- }
- return 0
-}
-
-func (p *Pager) SetPage(page int) {
- p.Offset = (page - 1) * p.GetLimit()
-}
-
-func (p *Pager) GetPage() int {
- return (p.GetOffset() / p.GetLimit()) + 1
-}
-
-func (p *Pager) Paginate(q *Query) (*Query, error) {
- if p.stickyErr != nil {
- return nil, p.stickyErr
- }
-
- q = q.Limit(p.GetLimit()).
- Offset(p.GetOffset())
- return q, nil
-}
-
-// Pagination is used with Query.Apply to set LIMIT and OFFSET from the URL values:
-// - ?limit=10 - sets q.Limit(10), max limit is 1000.
-// - ?page=5 - sets q.Offset((page - 1) * limit), max offset is 1000000.
-func Pagination(values url.Values) func(*Query) (*Query, error) {
- return NewPager(values).Paginate
-}
-
-func intParam(urlValues url.Values, paramName string) (int, error) {
- values, ok := urlValues[paramName]
- if !ok {
- return 0, nil
- }
-
- value, err := strconv.Atoi(values[0])
- if err != nil {
- return 0, fmt.Errorf("param=%s value=%s is invalid: %s", paramName, values[0], err)
- }
-
- return value, nil
-}
diff --git a/vendor/github.com/go-pg/pg/orm/url_values_test.go b/vendor/github.com/go-pg/pg/orm/url_values_test.go
deleted file mode 100644
index 2b5eab3..0000000
--- a/vendor/github.com/go-pg/pg/orm/url_values_test.go
+++ /dev/null
@@ -1,117 +0,0 @@
-package orm
-
-import (
- "net/http"
-
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-)
-
-type URLValuesModel struct {
- Id int
- Name string
-}
-
-type urlValuesTest struct {
- url string
- query string
-}
-
-var _ = Describe("URLValues", func() {
- query := `SELECT "url_values_model"."id", "url_values_model"."name" FROM "url_values_models" AS "url_values_model"`
- urlValuesTests := []urlValuesTest{
- {
- url: "http://localhost:8000/test?id__gt=1",
- query: query + ` WHERE ("id" > '1')`,
- },
- {
- url: "http://localhost:8000/test?name__gte=Michael",
- query: query + ` WHERE ("name" >= 'Michael')`,
- },
- {
- url: "http://localhost:8000/test?id__lt=10",
- query: query + ` WHERE ("id" < '10')`,
- },
- {
- url: "http://localhost:8000/test?name__lte=Peter",
- query: query + ` WHERE ("name" <= 'Peter')`,
- },
- {
- url: "http://localhost:8000/test?name__exclude=Peter",
- query: query + ` WHERE ("name" != 'Peter')`,
- },
- {
- url: "http://localhost:8000/test?name__exclude=Mike&name__exclude=Peter",
- query: query + ` WHERE ("name" NOT IN ('Mike','Peter'))`,
- },
- {
- url: "http://localhost:8000/test?name=Mike",
- query: query + ` WHERE ("name" = 'Mike')`,
- },
- {
- url: "http://localhost:8000/test?name__ieq=mik_",
- query: query + ` WHERE ("name" ILIKE 'mik_')`,
- },
- {
- url: "http://localhost:8000/test?name__match=(m|p).*",
- query: query + ` WHERE ("name" SIMILAR TO '(m|p).*')`,
- },
- {
- url: "http://localhost:8000/test?name__include=Peter&name__include=Mike",
- query: query + ` WHERE ("name" IN ('Peter','Mike'))`,
- },
- {
- url: "http://localhost:8000/test?name=Mike&name=Peter",
- query: query + ` WHERE ("name" IN ('Mike','Peter'))`,
- },
- {
- url: "http://localhost:8000/test?invalid_field=1",
- query: query,
- },
- }
-
- It("adds conditions to the query", func() {
- for _, urlValuesTest := range urlValuesTests {
- req, _ := http.NewRequest("GET", urlValuesTest.url, nil)
-
- q := NewQuery(nil, &URLValuesModel{})
- q = q.Apply(URLFilters(req.URL.Query()))
-
- b, err := selectQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(urlValuesTest.query))
- }
- })
-})
-
-var _ = Describe("Pager", func() {
- query := `SELECT "url_values_model"."id", "url_values_model"."name" FROM "url_values_models" AS "url_values_model"`
- urlValuesTests := []urlValuesTest{
- {
- url: "http://localhost:8000/test?limit=10",
- query: query + " LIMIT 10",
- },
- {
- url: "http://localhost:8000/test?page=5",
- query: query + ` LIMIT 100 OFFSET 400`,
- },
-
- {
- url: "http://localhost:8000/test?page=5&limit=20",
- query: query + ` LIMIT 20 OFFSET 80`,
- },
- }
-
- It("adds limit and offset to the query", func() {
- for _, urlValuesTest := range urlValuesTests {
- req, _ := http.NewRequest("GET", urlValuesTest.url, nil)
-
- q := NewQuery(nil, &URLValuesModel{})
- q = q.Apply(Pagination(req.URL.Query()))
-
- b, err := selectQuery{q: q}.AppendQuery(nil)
- Expect(err).NotTo(HaveOccurred())
- Expect(string(b)).To(Equal(urlValuesTest.query))
- }
- })
-})
diff --git a/vendor/github.com/go-pg/pg/orm/util.go b/vendor/github.com/go-pg/pg/orm/util.go
deleted file mode 100644
index 6e09fd6..0000000
--- a/vendor/github.com/go-pg/pg/orm/util.go
+++ /dev/null
@@ -1,155 +0,0 @@
-package orm
-
-import (
- "reflect"
-
- "github.com/go-pg/pg/types"
-)
-
-func indirectType(t reflect.Type) reflect.Type {
- if t.Kind() == reflect.Ptr {
- t = t.Elem()
- }
- return t
-}
-
-func sliceElemType(v reflect.Value) reflect.Type {
- elemType := v.Type().Elem()
- if elemType.Kind() == reflect.Interface && v.Len() > 0 {
- return reflect.Indirect(v.Index(0).Elem()).Type()
- } else {
- return indirectType(elemType)
- }
-}
-
-func typeByIndex(t reflect.Type, index []int) reflect.Type {
- for _, x := range index {
- switch t.Kind() {
- case reflect.Ptr:
- t = t.Elem()
- case reflect.Slice:
- t = indirectType(t.Elem())
- }
- t = t.Field(x).Type
- }
- return indirectType(t)
-}
-
-func fieldByIndex(v reflect.Value, index []int) reflect.Value {
- for i, x := range index {
- if i > 0 {
- v = indirectNew(v)
- }
- v = v.Field(x)
- }
- return v
-}
-
-func indirectNew(v reflect.Value) reflect.Value {
- if v.Kind() == reflect.Ptr {
- if v.IsNil() {
- v.Set(reflect.New(v.Type().Elem()))
- }
- v = v.Elem()
- }
- return v
-}
-
-func columns(b []byte, table types.Q, prefix string, fields []*Field) []byte {
- for i, f := range fields {
- if i > 0 {
- b = append(b, ", "...)
- }
-
- if len(table) > 0 {
- b = append(b, table...)
- b = append(b, '.')
- }
- b = types.AppendField(b, prefix+f.SQLName, 1)
- }
- return b
-}
-
-func walk(v reflect.Value, index []int, fn func(reflect.Value)) {
- v = reflect.Indirect(v)
- switch v.Kind() {
- case reflect.Slice:
- for i := 0; i < v.Len(); i++ {
- visitField(v.Index(i), index, fn)
- }
- default:
- visitField(v, index, fn)
- }
-}
-
-func visitField(v reflect.Value, index []int, fn func(reflect.Value)) {
- v = reflect.Indirect(v)
- if len(index) > 0 {
- v = v.Field(index[0])
- walk(v, index[1:], fn)
- } else {
- fn(v)
- }
-}
-
-func appendChildValues(b []byte, v reflect.Value, index []int, fields []*Field) []byte {
- seen := make(map[string]struct{})
- walk(v, index, func(v reflect.Value) {
- start := len(b)
-
- b = append(b, '(')
- for i, f := range fields {
- if i > 0 {
- b = append(b, ", "...)
- }
- b = f.AppendValue(b, v, 1)
- }
- b = append(b, "), "...)
-
- if _, ok := seen[string(b[start:])]; ok {
- b = b[:start]
- } else {
- seen[string(b[start:])] = struct{}{}
- }
- })
- if len(seen) > 0 {
- b = b[:len(b)-2] // trim ", "
- }
- return b
-}
-
-func dstValues(model tableModel, fields []*Field) map[string][]reflect.Value {
- mp := make(map[string][]reflect.Value)
- var id []byte
- walk(model.Root(), model.ParentIndex(), func(v reflect.Value) {
- id = modelId(id[:0], v, fields)
- mp[string(id)] = append(mp[string(id)], v.FieldByIndex(model.Relation().Field.Index))
- })
- return mp
-}
-
-func modelId(b []byte, v reflect.Value, fields []*Field) []byte {
- for _, f := range fields {
- b = f.AppendValue(b, v, 0)
- b = append(b, ',')
- }
- return b
-}
-
-func modelIdMap(b []byte, m map[string]string, prefix string, fields []*Field) []byte {
- for _, f := range fields {
- b = append(b, m[prefix+f.SQLName]...)
- b = append(b, ',')
- }
- return b
-}
-
-func appendColumns(b []byte, fields []*Field) []byte {
- for i, f := range fields {
- if i > 0 {
- b = append(b, ", "...)
- }
- b = append(b, f.Column...)
- }
- return b
-}
diff --git a/vendor/github.com/go-pg/pg/orm/zero.go b/vendor/github.com/go-pg/pg/orm/zero.go
deleted file mode 100644
index fa96666..0000000
--- a/vendor/github.com/go-pg/pg/orm/zero.go
+++ /dev/null
@@ -1,122 +0,0 @@
-package orm
-
-import (
- "database/sql/driver"
- "reflect"
-
- "github.com/go-pg/pg/types"
-)
-
-var driverValuerType = reflect.TypeOf((*driver.Valuer)(nil)).Elem()
-var appenderType = reflect.TypeOf((*types.ValueAppender)(nil)).Elem()
-var isZeroerType = reflect.TypeOf((*isZeroer)(nil)).Elem()
-
-type isZeroer interface {
- IsZero() bool
-}
-
-func isZeroFunc(typ reflect.Type) func(reflect.Value) bool {
- if typ.Implements(isZeroerType) {
- return isZero
- }
-
- switch typ.Kind() {
- case reflect.Array:
- if typ.Elem().Kind() == reflect.Uint8 {
- return isZeroBytes
- }
- return isZeroLen
- case reflect.Map, reflect.Slice, reflect.String:
- return isZeroLen
- case reflect.Bool:
- return isZeroBool
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- return isZeroInt
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
- return isZeroUint
- case reflect.Float32, reflect.Float64:
- return isZeroFloat
- case reflect.Interface, reflect.Ptr:
- return isZeroNil
- }
-
- if typ.Implements(appenderType) {
- return isZeroAppenderValue
- }
- if typ.Implements(driverValuerType) {
- return isZeroDriverValue
- }
-
- return isZeroFalse
-}
-
-func isZero(v reflect.Value) bool {
- if v.Kind() == reflect.Ptr {
- return v.IsNil()
- }
- return v.Interface().(isZeroer).IsZero()
-}
-
-func isZeroAppenderValue(v reflect.Value) bool {
- if v.Kind() == reflect.Ptr {
- return v.IsNil()
- }
-
- appender := v.Interface().(types.ValueAppender)
- value, err := appender.AppendValue(nil, 0)
- if err != nil {
- return false
- }
- return value == nil
-}
-
-func isZeroDriverValue(v reflect.Value) bool {
- if v.Kind() == reflect.Ptr {
- return v.IsNil()
- }
-
- valuer := v.Interface().(driver.Valuer)
- value, err := valuer.Value()
- if err != nil {
- return false
- }
- return value == nil
-}
-
-func isZeroLen(v reflect.Value) bool {
- return v.Len() == 0
-}
-
-func isZeroNil(v reflect.Value) bool {
- return v.IsNil()
-}
-
-func isZeroBool(v reflect.Value) bool {
- return !v.Bool()
-}
-
-func isZeroInt(v reflect.Value) bool {
- return v.Int() == 0
-}
-
-func isZeroUint(v reflect.Value) bool {
- return v.Uint() == 0
-}
-
-func isZeroFloat(v reflect.Value) bool {
- return v.Float() == 0
-}
-
-func isZeroBytes(v reflect.Value) bool {
- b := v.Slice(0, v.Len()).Bytes()
- for _, c := range b {
- if c != 0 {
- return false
- }
- }
- return true
-}
-
-func isZeroFalse(v reflect.Value) bool {
- return false
-}
diff --git a/vendor/github.com/go-pg/pg/pg.go b/vendor/github.com/go-pg/pg/pg.go
deleted file mode 100644
index 2bde7d3..0000000
--- a/vendor/github.com/go-pg/pg/pg.go
+++ /dev/null
@@ -1,289 +0,0 @@
-package pg
-
-import (
- "log"
- "os"
- "strconv"
-
- "github.com/go-pg/pg/internal"
- "github.com/go-pg/pg/orm"
- "github.com/go-pg/pg/types"
-)
-
-// Discard is used with Query and QueryOne to discard rows.
-var Discard orm.Discard
-
-func init() {
- SetLogger(log.New(os.Stderr, "pg: ", log.LstdFlags|log.Lshortfile))
-}
-
-// Model returns new query for the optional model.
-func Model(model ...interface{}) *orm.Query {
- return orm.NewQuery(nil, model...)
-}
-
-// Scan returns ColumnScanner that copies the columns in the
-// row into the values.
-func Scan(values ...interface{}) orm.ColumnScanner {
- return orm.Scan(values...)
-}
-
-// Q replaces any placeholders found in the query.
-func Q(query string, params ...interface{}) types.ValueAppender {
- return orm.Q(query, params...)
-}
-
-// F quotes a SQL identifier such as a table or column name replacing any
-// placeholders found in the field.
-func F(field string) types.ValueAppender {
- return types.F(field)
-}
-
-// In accepts a slice and returns a wrapper that can be used with PostgreSQL
-// IN operator:
-//
-// Where("id IN (?)", pg.In([]int{1, 2, 3}))
-func In(slice interface{}) types.ValueAppender {
- return types.In(slice)
-}
-
-// Array accepts a slice and returns a wrapper for working with PostgreSQL
-// array data type.
-//
-// For struct fields you can use array tag:
-//
-// Emails []string `pg:",array"`
-func Array(v interface{}) *types.Array {
- return types.NewArray(v)
-}
-
-// Hstore accepts a map and returns a wrapper for working with hstore data type.
-// Supported map types are:
-// - map[string]string
-//
-// For struct fields you can use hstore tag:
-//
-// Attrs map[string]string `pg:",hstore"`
-func Hstore(v interface{}) *types.Hstore {
- return types.NewHstore(v)
-}
-
-func SetLogger(logger *log.Logger) {
- internal.Logger = logger
-}
-
-//------------------------------------------------------------------------------
-
-type Strings []string
-
-var _ orm.Model = (*Strings)(nil)
-var _ types.ValueAppender = (*Strings)(nil)
-
-func (strings *Strings) Init() error {
- if s := *strings; len(s) > 0 {
- *strings = s[:0]
- }
- return nil
-}
-
-func (strings *Strings) NewModel() orm.ColumnScanner {
- return strings
-}
-
-func (Strings) AddModel(_ orm.ColumnScanner) error {
- return nil
-}
-
-func (Strings) AfterQuery(_ orm.DB) error {
- return nil
-}
-
-func (Strings) AfterSelect(_ orm.DB) error {
- return nil
-}
-
-func (Strings) BeforeInsert(_ orm.DB) error {
- return nil
-}
-
-func (Strings) AfterInsert(_ orm.DB) error {
- return nil
-}
-
-func (Strings) BeforeUpdate(_ orm.DB) error {
- return nil
-}
-
-func (Strings) AfterUpdate(_ orm.DB) error {
- return nil
-}
-
-func (Strings) BeforeDelete(_ orm.DB) error {
- return nil
-}
-
-func (Strings) AfterDelete(_ orm.DB) error {
- return nil
-}
-
-func (strings *Strings) ScanColumn(colIdx int, _ string, b []byte) error {
- *strings = append(*strings, string(b))
- return nil
-}
-
-func (strings Strings) AppendValue(dst []byte, quote int) ([]byte, error) {
- if len(strings) <= 0 {
- return dst, nil
- }
-
- for _, s := range strings {
- dst = types.AppendString(dst, s, 1)
- dst = append(dst, ',')
- }
- dst = dst[:len(dst)-1]
- return dst, nil
-}
-
-//------------------------------------------------------------------------------
-
-type Ints []int64
-
-var _ orm.Model = (*Ints)(nil)
-var _ types.ValueAppender = (*Ints)(nil)
-
-func (ints *Ints) Init() error {
- if s := *ints; len(s) > 0 {
- *ints = s[:0]
- }
- return nil
-}
-
-func (ints *Ints) NewModel() orm.ColumnScanner {
- return ints
-}
-
-func (Ints) AddModel(_ orm.ColumnScanner) error {
- return nil
-}
-
-func (Ints) AfterQuery(_ orm.DB) error {
- return nil
-}
-
-func (Ints) AfterSelect(_ orm.DB) error {
- return nil
-}
-
-func (Ints) BeforeInsert(_ orm.DB) error {
- return nil
-}
-
-func (Ints) AfterInsert(_ orm.DB) error {
- return nil
-}
-
-func (Ints) BeforeUpdate(_ orm.DB) error {
- return nil
-}
-
-func (Ints) AfterUpdate(_ orm.DB) error {
- return nil
-}
-
-func (Ints) BeforeDelete(_ orm.DB) error {
- return nil
-}
-
-func (Ints) AfterDelete(_ orm.DB) error {
- return nil
-}
-
-func (ints *Ints) ScanColumn(colIdx int, colName string, b []byte) error {
- n, err := strconv.ParseInt(internal.BytesToString(b), 10, 64)
- if err != nil {
- return err
- }
- *ints = append(*ints, n)
- return nil
-}
-
-func (ints Ints) AppendValue(dst []byte, quote int) ([]byte, error) {
- if len(ints) <= 0 {
- return dst, nil
- }
-
- for _, v := range ints {
- dst = strconv.AppendInt(dst, v, 10)
- dst = append(dst, ',')
- }
- dst = dst[:len(dst)-1]
- return dst, nil
-}
-
-//------------------------------------------------------------------------------
-
-type IntSet map[int64]struct{}
-
-var _ orm.Model = (*IntSet)(nil)
-
-func (set *IntSet) Init() error {
- if len(*set) > 0 {
- *set = make(map[int64]struct{})
- }
- return nil
-}
-
-func (set *IntSet) NewModel() orm.ColumnScanner {
- return set
-}
-
-func (IntSet) AddModel(_ orm.ColumnScanner) error {
- return nil
-}
-
-func (IntSet) AfterQuery(_ orm.DB) error {
- return nil
-}
-
-func (IntSet) AfterSelect(_ orm.DB) error {
- return nil
-}
-
-func (IntSet) BeforeInsert(_ orm.DB) error {
- return nil
-}
-
-func (IntSet) AfterInsert(_ orm.DB) error {
- return nil
-}
-
-func (IntSet) BeforeUpdate(_ orm.DB) error {
- return nil
-}
-
-func (IntSet) AfterUpdate(_ orm.DB) error {
- return nil
-}
-
-func (IntSet) BeforeDelete(_ orm.DB) error {
- return nil
-}
-
-func (IntSet) AfterDelete(_ orm.DB) error {
- return nil
-}
-
-func (setptr *IntSet) ScanColumn(colIdx int, colName string, b []byte) error {
- set := *setptr
- if set == nil {
- *setptr = make(IntSet)
- set = *setptr
- }
-
- n, err := strconv.ParseInt(internal.BytesToString(b), 10, 64)
- if err != nil {
- return err
- }
- set[n] = struct{}{}
- return nil
-}
diff --git a/vendor/github.com/go-pg/pg/pool_test.go b/vendor/github.com/go-pg/pg/pool_test.go
deleted file mode 100644
index 54a06dd..0000000
--- a/vendor/github.com/go-pg/pg/pool_test.go
+++ /dev/null
@@ -1,154 +0,0 @@
-package pg_test
-
-import (
- "time"
-
- "github.com/go-pg/pg"
-
- . "gopkg.in/check.v1"
-)
-
-var _ = Suite(&PoolTest{})
-
-type PoolTest struct {
- db *pg.DB
-}
-
-func (t *PoolTest) SetUpTest(c *C) {
- opt := pgOptions()
- opt.IdleTimeout = time.Second
- t.db = pg.Connect(opt)
-}
-
-func (t *PoolTest) TearDownTest(c *C) {
- _ = t.db.Close()
-}
-
-func (t *PoolTest) TestPoolReusesConnection(c *C) {
- for i := 0; i < 100; i++ {
- _, err := t.db.Exec("SELECT 'test_pool_reuses_connection'")
- c.Assert(err, IsNil)
- }
-
- c.Assert(t.db.Pool().Len(), Equals, 1)
- c.Assert(t.db.Pool().FreeLen(), Equals, 1)
-}
-
-func (t *PoolTest) TestPoolMaxSize(c *C) {
- N := 1000
-
- perform(N, func(int) {
- _, err := t.db.Exec("SELECT 'test_pool_max_size'")
- c.Assert(err, IsNil)
- })
-
- c.Assert(t.db.Pool().Len(), Equals, 10)
- c.Assert(t.db.Pool().FreeLen(), Equals, 10)
-}
-
-func (t *PoolTest) TestCloseClosesAllConnections(c *C) {
- ln := t.db.Listen("test_channel")
-
- wait := make(chan struct{}, 2)
- go func() {
- wait <- struct{}{}
- _, _, err := ln.Receive()
- c.Assert(err, ErrorMatches, `^(.*use of closed (file or )?network connection|EOF)$`)
- wait <- struct{}{}
- }()
-
- select {
- case <-wait:
- // ok
- case <-time.After(3 * time.Second):
- c.Fatal("timeout")
- }
-
- c.Assert(t.db.Close(), IsNil)
-
- select {
- case <-wait:
- // ok
- case <-time.After(3 * time.Second):
- c.Fatal("timeout")
- }
-
- c.Assert(t.db.Pool().Len(), Equals, 0)
- c.Assert(t.db.Pool().FreeLen(), Equals, 0)
-}
-
-func (t *PoolTest) TestClosedDB(c *C) {
- c.Assert(t.db.Close(), IsNil)
-
- c.Assert(t.db.Pool().Len(), Equals, 0)
- c.Assert(t.db.Pool().FreeLen(), Equals, 0)
-
- err := t.db.Close()
- c.Assert(err, Not(IsNil))
- c.Assert(err.Error(), Equals, "pg: database is closed")
-
- _, err = t.db.Exec("SELECT 'test_closed_db'")
- c.Assert(err, Not(IsNil))
- c.Assert(err.Error(), Equals, "pg: database is closed")
-}
-
-func (t *PoolTest) TestClosedListener(c *C) {
- ln := t.db.Listen("test_channel")
-
- c.Assert(t.db.Pool().Len(), Equals, 1)
- c.Assert(t.db.Pool().FreeLen(), Equals, 0)
-
- c.Assert(ln.Close(), IsNil)
-
- c.Assert(t.db.Pool().Len(), Equals, 0)
- c.Assert(t.db.Pool().FreeLen(), Equals, 0)
-
- err := ln.Close()
- c.Assert(err, Not(IsNil))
- c.Assert(err.Error(), Equals, "pg: listener is closed")
-
- _, _, err = ln.ReceiveTimeout(time.Second)
- c.Assert(err, Not(IsNil))
- c.Assert(err.Error(), Equals, "pg: listener is closed")
-}
-
-func (t *PoolTest) TestClosedTx(c *C) {
- tx, err := t.db.Begin()
- c.Assert(err, IsNil)
-
- c.Assert(t.db.Pool().Len(), Equals, 1)
- c.Assert(t.db.Pool().FreeLen(), Equals, 0)
-
- c.Assert(tx.Rollback(), IsNil)
-
- c.Assert(t.db.Pool().Len(), Equals, 1)
- c.Assert(t.db.Pool().FreeLen(), Equals, 1)
-
- err = tx.Rollback()
- c.Assert(err, Not(IsNil))
- c.Assert(err.Error(), Equals, "pg: transaction has already been committed or rolled back")
-
- _, err = tx.Exec("SELECT 'test_closed_tx'")
- c.Assert(err, Not(IsNil))
- c.Assert(err.Error(), Equals, "pg: transaction has already been committed or rolled back")
-}
-
-func (t *PoolTest) TestClosedStmt(c *C) {
- stmt, err := t.db.Prepare("SELECT $1::int")
- c.Assert(err, IsNil)
-
- c.Assert(t.db.Pool().Len(), Equals, 1)
- c.Assert(t.db.Pool().FreeLen(), Equals, 0)
-
- c.Assert(stmt.Close(), IsNil)
-
- c.Assert(t.db.Pool().Len(), Equals, 1)
- c.Assert(t.db.Pool().FreeLen(), Equals, 1)
-
- err = stmt.Close()
- c.Assert(err, Not(IsNil))
- c.Assert(err.Error(), Equals, "pg: statement is closed")
-
- _, err = stmt.Exec(1)
- c.Assert(err.Error(), Equals, "pg: statement is closed")
-}
diff --git a/vendor/github.com/go-pg/pg/race_test.go b/vendor/github.com/go-pg/pg/race_test.go
deleted file mode 100644
index 9b1ee7b..0000000
--- a/vendor/github.com/go-pg/pg/race_test.go
+++ /dev/null
@@ -1,175 +0,0 @@
-package pg_test
-
-import (
- "testing"
- "time"
-
- "github.com/go-pg/pg"
-
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-)
-
-func concurrency() (int, int) {
- if testing.Short() {
- return 4, 100
- }
- return 10, 1000
-}
-
-var _ = Describe("DB timeout race", func() {
- var db *pg.DB
- var C, N int
-
- BeforeEach(func() {
- C, N = concurrency()
- N = 100
- })
-
- AfterEach(func() {
- pool := db.Pool()
- Expect(pool.Len()).To(Equal(0))
- Expect(pool.FreeLen()).To(Equal(0))
-
- err := db.Close()
- Expect(err).NotTo(HaveOccurred())
-
- // Give Postgres some time to recover.
- time.Sleep(time.Second)
- })
-
- test := func() {
- It("is race free", func() {
- perform(C, func(id int) {
- for i := 0; i < N; i++ {
- _, err := db.Exec("SELECT pg_sleep(1)")
- Expect(err).To(HaveOccurred())
- }
- })
- })
- }
-
- Describe("dial timeout", func() {
- BeforeEach(func() {
- opt := pgOptions()
- opt.DialTimeout = time.Nanosecond
- db = pg.Connect(opt)
- })
-
- test()
- })
-
- Describe("read timeout", func() {
- BeforeEach(func() {
- opt := pgOptions()
- opt.ReadTimeout = time.Nanosecond
- db = pg.Connect(opt)
- })
-
- test()
- })
-
- Describe("write timeout", func() {
- BeforeEach(func() {
- opt := pgOptions()
- opt.WriteTimeout = time.Nanosecond
- db = pg.Connect(opt)
- })
-
- test()
- })
-})
-
-var _ = Describe("DB race", func() {
- var db *pg.DB
- var C, N int
-
- BeforeEach(func() {
- db = pg.Connect(pgOptions())
-
- err := createTestSchema(db)
- Expect(err).NotTo(HaveOccurred())
-
- C, N = concurrency()
- })
-
- AfterEach(func() {
- err := db.Close()
- Expect(err).NotTo(HaveOccurred())
- })
-
- It("invalid Scan is race free", func() {
- perform(C, func(id int) {
- for i := 0; i < N; i++ {
- var n int
- if i%2 == 0 {
- _, err := db.QueryOne(pg.Scan(&n), "SELECT 1, 2")
- Expect(err).To(HaveOccurred())
- } else {
- _, err := db.QueryOne(pg.Scan(&n), "SELECT 123")
- Expect(err).NotTo(HaveOccurred())
- Expect(n).To(Equal(123))
- }
- }
- })
- })
-
- It("SelectOrInsert with OnConflict is race free", func() {
- perform(C, func(id int) {
- a := &Author{
- Name: "R. Scott Bakker",
- }
- for i := 0; i < N; i++ {
- a.ID = 0
- _, err := db.Model(a).
- Column("id").
- Where("name = ?name").
- OnConflict("DO NOTHING").
- Returning("id").
- SelectOrInsert(&a.ID)
- Expect(err).NotTo(HaveOccurred())
- Expect(a.ID).NotTo(BeZero())
-
- if i%(N/C) == 0 {
- err := db.Delete(a)
- if err != pg.ErrNoRows {
- Expect(err).NotTo(HaveOccurred())
- }
- }
- }
- })
-
- count, err := db.Model(&Author{}).Count()
- Expect(err).NotTo(HaveOccurred())
- Expect(count).To(Equal(1))
- })
-
- It("SelectOrInsert without OnConflict is race free", func() {
- perform(C, func(id int) {
- a := &Author{
- Name: "R. Scott Bakker",
- }
- for i := 0; i < N; i++ {
- a.ID = 0
- _, err := db.Model(a).
- Column("id").
- Where("name = ?name").
- Returning("id").
- SelectOrInsert(&a.ID)
- Expect(err).NotTo(HaveOccurred())
- Expect(a.ID).NotTo(BeZero())
-
- if i%(N/C) == 0 {
- err := db.Delete(a)
- if err != pg.ErrNoRows {
- Expect(err).NotTo(HaveOccurred())
- }
- }
- }
- })
-
- count, err := db.Model(&Author{}).Count()
- Expect(err).NotTo(HaveOccurred())
- Expect(count).To(Equal(1))
- })
-})
diff --git a/vendor/github.com/go-pg/pg/result.go b/vendor/github.com/go-pg/pg/result.go
deleted file mode 100644
index 3a61b3b..0000000
--- a/vendor/github.com/go-pg/pg/result.go
+++ /dev/null
@@ -1,49 +0,0 @@
-package pg
-
-import (
- "bytes"
- "strconv"
-
- "github.com/go-pg/pg/internal"
- "github.com/go-pg/pg/orm"
-)
-
-// A result summarizes an executed SQL command.
-type result struct {
- model orm.Model
-
- affected int
- returned int
-}
-
-var _ orm.Result = (*result)(nil)
-
-func (res *result) parse(b []byte) error {
- res.affected = -1
-
- ind := bytes.LastIndexByte(b, ' ')
- if ind == -1 {
- return nil
- }
-
- s := internal.BytesToString(b[ind+1 : len(b)-1])
-
- affected, err := strconv.Atoi(s)
- if err == nil {
- res.affected = affected
- }
-
- return nil
-}
-
-func (res *result) Model() orm.Model {
- return res.model
-}
-
-func (res *result) RowsAffected() int {
- return res.affected
-}
-
-func (res *result) RowsReturned() int {
- return res.returned
-}
diff --git a/vendor/github.com/go-pg/pg/stmt.go b/vendor/github.com/go-pg/pg/stmt.go
deleted file mode 100644
index 12ab195..0000000
--- a/vendor/github.com/go-pg/pg/stmt.go
+++ /dev/null
@@ -1,241 +0,0 @@
-package pg
-
-import (
- "errors"
- "sync"
- "time"
-
- "github.com/go-pg/pg/internal"
- "github.com/go-pg/pg/internal/pool"
- "github.com/go-pg/pg/orm"
-)
-
-var errStmtClosed = errors.New("pg: statement is closed")
-
-// Stmt is a prepared statement. Stmt is safe for concurrent use by
-// multiple goroutines.
-type Stmt struct {
- db *DB
-
- mu sync.Mutex
- _cn *pool.Conn
- inTx bool
-
- q string
- name string
- columns [][]byte
-
- stickyErr error
-}
-
-// Prepare creates a prepared statement for later queries or
-// executions. Multiple queries or executions may be run concurrently
-// from the returned statement.
-func (db *DB) Prepare(q string) (*Stmt, error) {
- cn, err := db.conn()
- if err != nil {
- return nil, err
- }
- return prepare(db, cn, q)
-}
-
-func (stmt *Stmt) conn() (*pool.Conn, error) {
- if stmt._cn == nil {
- if stmt.stickyErr != nil {
- return nil, stmt.stickyErr
- }
- return nil, errStmtClosed
- }
-
- stmt._cn.SetTimeout(stmt.db.opt.ReadTimeout, stmt.db.opt.WriteTimeout)
- return stmt._cn, nil
-}
-
-func (stmt *Stmt) exec(params ...interface{}) (orm.Result, error) {
- stmt.mu.Lock()
- defer stmt.mu.Unlock()
-
- cn, err := stmt.conn()
- if err != nil {
- return nil, err
- }
- return extQuery(cn, stmt.name, params...)
-}
-
-// Exec executes a prepared statement with the given parameters.
-func (stmt *Stmt) Exec(params ...interface{}) (res orm.Result, err error) {
- for attempt := 0; attempt <= stmt.db.opt.MaxRetries; attempt++ {
- if attempt >= 1 {
- time.Sleep(stmt.db.retryBackoff(attempt - 1))
- }
-
- start := time.Now()
- res, err = stmt.exec(params...)
- stmt.db.queryProcessed(stmt.db, start, stmt.q, params, attempt, res, err)
-
- if !stmt.db.shouldRetry(err) {
- break
- }
- }
- if err != nil {
- stmt.setErr(err)
- }
- return
-}
-
-// ExecOne acts like Exec, but query must affect only one row. It
-// returns ErrNoRows error when query returns zero rows or
-// ErrMultiRows when query returns multiple rows.
-func (stmt *Stmt) ExecOne(params ...interface{}) (orm.Result, error) {
- res, err := stmt.Exec(params...)
- if err != nil {
- return nil, err
- }
-
- if err := internal.AssertOneRow(res.RowsAffected()); err != nil {
- return nil, err
- }
- return res, nil
-}
-
-func (stmt *Stmt) query(model interface{}, params ...interface{}) (orm.Result, error) {
- stmt.mu.Lock()
- defer stmt.mu.Unlock()
-
- cn, err := stmt.conn()
- if err != nil {
- return nil, err
- }
-
- res, err := extQueryData(cn, stmt.name, model, stmt.columns, params...)
- if err != nil {
- return nil, err
- }
-
- if mod := res.Model(); mod != nil && res.RowsReturned() > 0 {
- if err = mod.AfterQuery(stmt.db); err != nil {
- return res, err
- }
- }
-
- return res, nil
-}
-
-// Query executes a prepared query statement with the given parameters.
-func (stmt *Stmt) Query(model interface{}, params ...interface{}) (res orm.Result, err error) {
- for attempt := 0; attempt <= stmt.db.opt.MaxRetries; attempt++ {
- if attempt >= 1 {
- time.Sleep(stmt.db.retryBackoff(attempt - 1))
- }
-
- start := time.Now()
- res, err = stmt.query(model, params...)
- stmt.db.queryProcessed(stmt.db, start, stmt.q, params, attempt, res, err)
-
- if !stmt.db.shouldRetry(err) {
- break
- }
- }
- if err != nil {
- stmt.setErr(err)
- }
- return
-}
-
-// QueryOne acts like Query, but query must return only one row. It
-// returns ErrNoRows error when query returns zero rows or
-// ErrMultiRows when query returns multiple rows.
-func (stmt *Stmt) QueryOne(model interface{}, params ...interface{}) (orm.Result, error) {
- mod, err := orm.NewModel(model)
- if err != nil {
- return nil, err
- }
-
- res, err := stmt.Query(mod, params...)
- if err != nil {
- return nil, err
- }
-
- if err := internal.AssertOneRow(res.RowsAffected()); err != nil {
- return nil, err
- }
- return res, nil
-}
-
-func (stmt *Stmt) setErr(e error) {
- if stmt.stickyErr == nil {
- stmt.stickyErr = e
- }
-}
-
-// Close closes the statement.
-func (stmt *Stmt) Close() error {
- stmt.mu.Lock()
- defer stmt.mu.Unlock()
-
- if stmt._cn == nil {
- return errStmtClosed
- }
-
- err := closeStmt(stmt._cn, stmt.name)
- if !stmt.inTx {
- _ = stmt.db.freeConn(stmt._cn, err)
- }
- stmt._cn = nil
- return err
-}
-
-func prepare(db *DB, cn *pool.Conn, q string) (*Stmt, error) {
- name := cn.NextId()
- writeParseDescribeSyncMsg(cn.Writer, name, q)
- if err := cn.FlushWriter(); err != nil {
- db.freeConn(cn, err)
- return nil, err
- }
-
- columns, err := readParseDescribeSync(cn)
- if err != nil {
- db.freeConn(cn, err)
- return nil, err
- }
-
- stmt := &Stmt{
- db: db,
- _cn: cn,
- q: q,
- name: name,
- columns: columns,
- }
- return stmt, nil
-}
-
-func extQuery(cn *pool.Conn, name string, params ...interface{}) (orm.Result, error) {
- if err := writeBindExecuteMsg(cn.Writer, name, params...); err != nil {
- return nil, err
- }
- if err := cn.FlushWriter(); err != nil {
- return nil, err
- }
- return readExtQuery(cn)
-}
-
-func extQueryData(
- cn *pool.Conn, name string, model interface{}, columns [][]byte, params ...interface{},
-) (orm.Result, error) {
- if err := writeBindExecuteMsg(cn.Writer, name, params...); err != nil {
- return nil, err
- }
- if err := cn.FlushWriter(); err != nil {
- return nil, err
- }
- return readExtQueryData(cn, model, columns)
-}
-
-func closeStmt(cn *pool.Conn, name string) error {
- writeCloseMsg(cn.Writer, name)
- writeFlushMsg(cn.Writer)
- if err := cn.FlushWriter(); err != nil {
- return err
- }
- return readCloseCompleteMsg(cn)
-}
diff --git a/vendor/github.com/go-pg/pg/time.go b/vendor/github.com/go-pg/pg/time.go
deleted file mode 100644
index 358acbd..0000000
--- a/vendor/github.com/go-pg/pg/time.go
+++ /dev/null
@@ -1,58 +0,0 @@
-package pg
-
-import (
- "bytes"
- "database/sql"
- "encoding/json"
- "time"
-
- "github.com/go-pg/pg/types"
-)
-
-var jsonNull = []byte("null")
-
-// NullTime is a time.Time wrapper that marshals zero time as JSON null and
-// PostgreSQL NULL.
-type NullTime struct {
- time.Time
-}
-
-var _ json.Marshaler = (*NullTime)(nil)
-var _ json.Unmarshaler = (*NullTime)(nil)
-var _ sql.Scanner = (*NullTime)(nil)
-var _ types.ValueAppender = (*NullTime)(nil)
-
-func (tm NullTime) MarshalJSON() ([]byte, error) {
- if tm.IsZero() {
- return jsonNull, nil
- }
- return tm.Time.MarshalJSON()
-}
-
-func (tm *NullTime) UnmarshalJSON(b []byte) error {
- if bytes.Equal(b, jsonNull) {
- tm.Time = time.Time{}
- return nil
- }
- return tm.Time.UnmarshalJSON(b)
-}
-
-func (tm NullTime) AppendValue(b []byte, quote int) ([]byte, error) {
- if tm.IsZero() {
- return types.AppendNull(b, quote), nil
- }
- return types.AppendTime(b, tm.Time, quote), nil
-}
-
-func (tm *NullTime) Scan(b interface{}) error {
- if b == nil {
- tm.Time = time.Time{}
- return nil
- }
- newtm, err := types.ParseTime(b.([]byte))
- if err != nil {
- return err
- }
- tm.Time = newtm
- return nil
-}
diff --git a/vendor/github.com/go-pg/pg/tx.go b/vendor/github.com/go-pg/pg/tx.go
deleted file mode 100644
index d0c0571..0000000
--- a/vendor/github.com/go-pg/pg/tx.go
+++ /dev/null
@@ -1,301 +0,0 @@
-package pg
-
-import (
- "errors"
- "io"
- "time"
-
- "github.com/go-pg/pg/internal"
- "github.com/go-pg/pg/internal/pool"
- "github.com/go-pg/pg/orm"
-)
-
-var errTxDone = errors.New("pg: transaction has already been committed or rolled back")
-
-// Tx is an in-progress database transaction.
-//
-// A transaction must end with a call to Commit or Rollback.
-//
-// After a call to Commit or Rollback, all operations on the transaction fail
-// with ErrTxDone.
-//
-// The statements prepared for a transaction by calling the transaction's
-// Prepare or Stmt methods are closed by the call to Commit or Rollback.
-type Tx struct {
- db *DB
- cn *pool.Conn
-
- stmts []*Stmt
-}
-
-var _ orm.DB = (*Tx)(nil)
-
-// Begin starts a transaction. Most callers should use RunInTransaction instead.
-func (db *DB) Begin() (*Tx, error) {
- tx := &Tx{
- db: db,
- }
-
- cn, err := db.conn()
- if err != nil {
- return nil, err
- }
- tx.cn = cn
-
- if err := tx.begin(); err != nil {
- return nil, err
- }
-
- return tx, nil
-}
-
-// RunInTransaction runs a function in a transaction. If function
-// returns an error transaction is rollbacked, otherwise transaction
-// is committed.
-func (db *DB) RunInTransaction(fn func(*Tx) error) error {
- tx, err := db.Begin()
- if err != nil {
- return err
- }
- return tx.RunInTransaction(fn)
-}
-
-// Begin returns the transaction.
-func (tx *Tx) Begin() (*Tx, error) {
- return tx, nil
-}
-
-// RunInTransaction runs a function in the transaction. If function
-// returns an error transaction is rollbacked, otherwise transaction
-// is committed.
-func (tx *Tx) RunInTransaction(fn func(*Tx) error) error {
- defer func() {
- if err := recover(); err != nil {
- tx.Rollback()
- panic(err)
- }
- }()
- if err := fn(tx); err != nil {
- tx.Rollback()
- return err
- }
- return tx.Commit()
-}
-
-func (tx *Tx) conn() (*pool.Conn, error) {
- if tx.cn == nil {
- return nil, errTxDone
- }
-
- tx.cn.SetTimeout(tx.db.opt.ReadTimeout, tx.db.opt.WriteTimeout)
- return tx.cn, nil
-}
-
-func (tx *Tx) freeConn(cn *pool.Conn, err error) {}
-
-// Stmt returns a transaction-specific prepared statement from an existing statement.
-func (tx *Tx) Stmt(stmt *Stmt) *Stmt {
- stmt, err := tx.Prepare(stmt.q)
- if err != nil {
- return &Stmt{stickyErr: err}
- }
- return stmt
-}
-
-// Prepare creates a prepared statement for use within a transaction.
-//
-// The returned statement operates within the transaction and can no longer
-// be used once the transaction has been committed or rolled back.
-//
-// To use an existing prepared statement on this transaction, see Tx.Stmt.
-func (tx *Tx) Prepare(q string) (*Stmt, error) {
- cn, err := tx.conn()
- if err != nil {
- return nil, err
- }
-
- stmt, err := prepare(tx.db, cn, q)
- tx.freeConn(cn, err)
- if err != nil {
- return nil, err
- }
-
- stmt.inTx = true
- tx.stmts = append(tx.stmts, stmt)
-
- return stmt, nil
-}
-
-// Exec is an alias for DB.Exec.
-func (tx *Tx) Exec(query interface{}, params ...interface{}) (orm.Result, error) {
- cn, err := tx.conn()
- if err != nil {
- return nil, err
- }
-
- start := time.Now()
- res, err := tx.db.simpleQuery(cn, query, params...)
- tx.freeConn(cn, err)
- tx.db.queryProcessed(tx, start, query, params, 0, res, err)
-
- return res, err
-}
-
-// ExecOne is an alias for DB.ExecOne.
-func (tx *Tx) ExecOne(query interface{}, params ...interface{}) (orm.Result, error) {
- res, err := tx.Exec(query, params...)
- if err != nil {
- return nil, err
- }
-
- if err := internal.AssertOneRow(res.RowsAffected()); err != nil {
- return nil, err
- }
- return res, nil
-}
-
-// Query is an alias for DB.Query.
-func (tx *Tx) Query(model interface{}, query interface{}, params ...interface{}) (orm.Result, error) {
- cn, err := tx.conn()
- if err != nil {
- return nil, err
- }
-
- start := time.Now()
- res, err := tx.db.simpleQueryData(cn, model, query, params...)
- tx.freeConn(cn, err)
- tx.db.queryProcessed(tx, start, query, params, 0, res, err)
-
- if err != nil {
- return nil, err
- }
-
- if mod := res.Model(); mod != nil && res.RowsReturned() > 0 {
- if err = mod.AfterQuery(tx); err != nil {
- return res, err
- }
- }
-
- return res, err
-}
-
-// QueryOne is an alias for DB.QueryOne.
-func (tx *Tx) QueryOne(model interface{}, query interface{}, params ...interface{}) (orm.Result, error) {
- mod, err := orm.NewModel(model)
- if err != nil {
- return nil, err
- }
-
- res, err := tx.Query(mod, query, params...)
- if err != nil {
- return nil, err
- }
-
- if err := internal.AssertOneRow(res.RowsAffected()); err != nil {
- return nil, err
- }
- return res, nil
-}
-
-// Model is an alias for DB.Model.
-func (tx *Tx) Model(model ...interface{}) *orm.Query {
- return orm.NewQuery(tx, model...)
-}
-
-// Select is an alias for DB.Select.
-func (tx *Tx) Select(model interface{}) error {
- return orm.Select(tx, model)
-}
-
-// Insert is an alias for DB.Insert.
-func (tx *Tx) Insert(model ...interface{}) error {
- return orm.Insert(tx, model...)
-}
-
-// Update is an alias for DB.Update.
-func (tx *Tx) Update(model ...interface{}) error {
- return orm.Update(tx, model...)
-}
-
-// Delete is an alias for DB.Delete.
-func (tx *Tx) Delete(model interface{}) error {
- return orm.Delete(tx, model)
-}
-
-// CreateTable is an alias for DB.CreateTable.
-func (tx *Tx) CreateTable(model interface{}, opt *orm.CreateTableOptions) error {
- _, err := orm.CreateTable(tx, model, opt)
- return err
-}
-
-// DropTable is an alias for DB.DropTable.
-func (tx *Tx) DropTable(model interface{}, opt *orm.DropTableOptions) error {
- _, err := orm.DropTable(tx, model, opt)
- return err
-}
-
-// CopyFrom is an alias for DB.CopyFrom.
-func (tx *Tx) CopyFrom(r io.Reader, query interface{}, params ...interface{}) (orm.Result, error) {
- cn, err := tx.conn()
- if err != nil {
- return nil, err
- }
-
- res, err := tx.db.copyFrom(cn, r, query, params...)
- tx.freeConn(cn, err)
- return res, err
-}
-
-// CopyTo is an alias for DB.CopyTo.
-func (tx *Tx) CopyTo(w io.Writer, query interface{}, params ...interface{}) (orm.Result, error) {
- cn, err := tx.conn()
- if err != nil {
- return nil, err
- }
-
- res, err := tx.db.copyTo(cn, w, query, params...)
- tx.freeConn(cn, err)
- return res, err
-}
-
-func (tx *Tx) FormatQuery(dst []byte, query string, params ...interface{}) []byte {
- return tx.db.FormatQuery(dst, query, params...)
-}
-
-func (tx *Tx) begin() error {
- _, err := tx.Exec("BEGIN")
- if err != nil {
- tx.close(err)
- }
- return err
-}
-
-// Commit commits the transaction.
-func (tx *Tx) Commit() error {
- _, err := tx.Exec("COMMIT")
- tx.close(err)
- return err
-}
-
-// Rollback aborts the transaction.
-func (tx *Tx) Rollback() error {
- _, err := tx.Exec("ROLLBACK")
- tx.close(err)
- return err
-}
-
-func (tx *Tx) close(lastErr error) error {
- if tx.cn == nil {
- return errTxDone
- }
-
- for _, stmt := range tx.stmts {
- _ = stmt.Close()
- }
- tx.stmts = nil
-
- err := tx.db.freeConn(tx.cn, lastErr)
- tx.cn = nil
-
- return err
-}
diff --git a/vendor/github.com/go-pg/pg/tx_test.go b/vendor/github.com/go-pg/pg/tx_test.go
deleted file mode 100644
index c70742d..0000000
--- a/vendor/github.com/go-pg/pg/tx_test.go
+++ /dev/null
@@ -1,130 +0,0 @@
-package pg_test
-
-import (
- "strings"
-
- "github.com/go-pg/pg"
-
- . "gopkg.in/check.v1"
-)
-
-var _ = Suite(&TxTest{})
-
-type TxTest struct {
- db *pg.DB
-}
-
-func (t *TxTest) SetUpTest(c *C) {
- t.db = pg.Connect(pgOptions())
-}
-
-func (t *TxTest) TearDownTest(c *C) {
- c.Assert(t.db.Close(), IsNil)
-}
-
-func (t *TxTest) TestMultiPrepare(c *C) {
- tx, err := t.db.Begin()
- c.Assert(err, IsNil)
-
- stmt1, err := tx.Prepare(`SELECT 'test_multi_prepare_tx1'`)
- c.Assert(err, IsNil)
-
- stmt2, err := tx.Prepare(`SELECT 'test_multi_prepare_tx2'`)
- c.Assert(err, IsNil)
-
- var s1 string
- _, err = stmt1.QueryOne(pg.Scan(&s1))
- c.Assert(err, IsNil)
- c.Assert(s1, Equals, "test_multi_prepare_tx1")
-
- var s2 string
- _, err = stmt2.QueryOne(pg.Scan(&s2))
- c.Assert(err, IsNil)
- c.Assert(s2, Equals, "test_multi_prepare_tx2")
-
- c.Assert(tx.Rollback(), IsNil)
-}
-
-func (t *TxTest) TestCopyFromInTransaction(c *C) {
- data := "hello\t5\nworld\t5\nfoo\t3\nbar\t3\n"
-
- _, err := t.db.Exec("DROP TABLE IF EXISTS test_copy_from")
- c.Assert(err, IsNil)
-
- _, err = t.db.Exec("CREATE TABLE test_copy_from(word text, len int)")
- c.Assert(err, IsNil)
-
- tx1, err := t.db.Begin()
- c.Assert(err, IsNil)
- tx2, err := t.db.Begin()
- c.Assert(err, IsNil)
-
- r := strings.NewReader(data)
- res, err := tx1.CopyFrom(r, "COPY test_copy_from FROM STDIN")
- c.Assert(err, IsNil)
- c.Assert(res.RowsAffected(), Equals, 4)
-
- var count int
- _, err = tx1.QueryOne(pg.Scan(&count), "SELECT COUNT(*) FROM test_copy_from")
- c.Assert(err, IsNil)
- c.Assert(count, Equals, 4)
-
- _, err = tx2.QueryOne(pg.Scan(&count), "SELECT COUNT(*) FROM test_copy_from")
- c.Assert(err, IsNil)
- c.Assert(count, Equals, 0)
-
- c.Assert(tx1.Commit(), IsNil)
-
- _, err = tx2.QueryOne(pg.Scan(&count), "SELECT COUNT(*) FROM test_copy_from")
- c.Assert(err, IsNil)
- c.Assert(count, Equals, 4) // assuming READ COMMITTED
-
- c.Assert(tx2.Rollback(), IsNil)
-
- _, err = t.db.Exec("DROP TABLE IF EXISTS test_copy_from")
- c.Assert(err, IsNil)
-}
-
-func (t *TxTest) TestCopyFromInTransactionWithErrors(c *C) {
- // too many fields on second line
- data := "hello\t5\nworld\t5\t6\t8\t9\nfoo\t3\nbar\t3\n"
-
- _, err := t.db.Exec("DROP TABLE IF EXISTS test_copy_from")
- c.Assert(err, IsNil)
-
- _, err = t.db.Exec("CREATE TABLE test_copy_from(word text, len int)")
- c.Assert(err, IsNil)
- _, err = t.db.Exec("INSERT INTO test_copy_from VALUES ('xxx', 3)")
- c.Assert(err, IsNil)
-
- tx1, err := t.db.Begin()
- c.Assert(err, IsNil)
- tx2, err := t.db.Begin()
- c.Assert(err, IsNil)
-
- _, err = tx1.Exec("INSERT INTO test_copy_from VALUES ('yyy', 3)")
- c.Assert(err, IsNil)
-
- r := strings.NewReader(data)
- _, err = tx1.CopyFrom(r, "COPY test_copy_from FROM STDIN")
- c.Assert(err, Not(IsNil))
-
- var count int
- _, err = tx1.QueryOne(pg.Scan(&count), "SELECT COUNT(*) FROM test_copy_from")
- c.Assert(err, Not(IsNil)) // transaction has errors, cannot proceed
-
- _, err = tx2.QueryOne(pg.Scan(&count), "SELECT COUNT(*) FROM test_copy_from")
- c.Assert(err, IsNil)
- c.Assert(count, Equals, 1)
-
- c.Assert(tx1.Commit(), IsNil) // actually ROLLBACK happens here
-
- _, err = tx2.QueryOne(pg.Scan(&count), "SELECT COUNT(*) FROM test_copy_from")
- c.Assert(err, IsNil)
- c.Assert(count, Equals, 1) // other transaction was rolled back so it's not 2 and not 6
-
- c.Assert(tx2.Rollback(), IsNil)
-
- _, err = t.db.Exec("DROP TABLE IF EXISTS test_copy_from")
- c.Assert(err, IsNil)
-}
diff --git a/vendor/github.com/go-pg/pg/types/append.go b/vendor/github.com/go-pg/pg/types/append.go
deleted file mode 100644
index 95402aa..0000000
--- a/vendor/github.com/go-pg/pg/types/append.go
+++ /dev/null
@@ -1,187 +0,0 @@
-package types
-
-import (
- "database/sql/driver"
- "encoding/hex"
- "reflect"
- "strconv"
- "time"
-)
-
-func Append(b []byte, v interface{}, quote int) []byte {
- switch v := v.(type) {
- case nil:
- return AppendNull(b, quote)
- case bool:
- return appendBool(b, v)
- case int8:
- return strconv.AppendInt(b, int64(v), 10)
- case int16:
- return strconv.AppendInt(b, int64(v), 10)
- case int32:
- return strconv.AppendInt(b, int64(v), 10)
- case int64:
- return strconv.AppendInt(b, int64(v), 10)
- case int:
- return strconv.AppendInt(b, int64(v), 10)
- case uint8:
- return strconv.AppendUint(b, uint64(v), 10)
- case uint16:
- return strconv.AppendUint(b, uint64(v), 10)
- case uint32:
- return strconv.AppendUint(b, uint64(v), 10)
- case uint64:
- return strconv.AppendUint(b, v, 10)
- case uint:
- return strconv.AppendUint(b, uint64(v), 10)
- case float32:
- return appendFloat(b, float64(v))
- case float64:
- return appendFloat(b, v)
- case string:
- return AppendString(b, v, quote)
- case time.Time:
- return AppendTime(b, v, quote)
- case []byte:
- return appendBytes(b, v, quote)
- case ValueAppender:
- return appendAppender(b, v, quote)
- case driver.Valuer:
- return appendDriverValuer(b, v, quote)
- default:
- return appendValue(b, reflect.ValueOf(v), quote)
- }
-}
-
-func AppendError(b []byte, err error) []byte {
- b = append(b, "?!("...)
- b = append(b, err.Error()...)
- b = append(b, ')')
- return b
-}
-
-func AppendNull(b []byte, quote int) []byte {
- if quote == 1 {
- return append(b, "NULL"...)
- } else {
- return nil
- }
-}
-
-func appendBool(dst []byte, v bool) []byte {
- if v {
- return append(dst, "TRUE"...)
- }
- return append(dst, "FALSE"...)
-}
-
-func appendFloat(dst []byte, v float64) []byte {
- return strconv.AppendFloat(dst, v, 'f', -1, 64)
-}
-
-func AppendString(b []byte, s string, quote int) []byte {
- if quote == 2 {
- b = append(b, '"')
- } else if quote == 1 {
- b = append(b, '\'')
- }
-
- for i := 0; i < len(s); i++ {
- c := s[i]
-
- if c == '\000' {
- continue
- }
-
- if quote >= 1 {
- if c == '\'' {
- b = append(b, '\'', '\'')
- continue
- }
- }
-
- if quote == 2 {
- if c == '"' {
- b = append(b, '\\', '"')
- continue
- }
- if c == '\\' {
- b = append(b, '\\', '\\')
- continue
- }
- }
-
- b = append(b, c)
- }
-
- if quote >= 2 {
- b = append(b, '"')
- } else if quote == 1 {
- b = append(b, '\'')
- }
-
- return b
-}
-
-func appendBytes(b []byte, bytes []byte, quote int) []byte {
- if bytes == nil {
- return AppendNull(b, quote)
- }
-
- if quote == 1 {
- b = append(b, '\'')
- }
-
- tmp := make([]byte, hex.EncodedLen(len(bytes)))
- hex.Encode(tmp, bytes)
- b = append(b, "\\x"...)
- b = append(b, tmp...)
-
- if quote == 1 {
- b = append(b, '\'')
- }
-
- return b
-}
-
-func AppendStringStringMap(b []byte, m map[string]string, quote int) []byte {
- if m == nil {
- return AppendNull(b, quote)
- }
-
- if quote == 1 {
- b = append(b, '\'')
- }
-
- for key, value := range m {
- b = AppendString(b, key, 2)
- b = append(b, '=', '>')
- b = AppendString(b, value, 2)
- b = append(b, ',')
- }
- if len(m) > 0 {
- b = b[:len(b)-1] // Strip trailing comma.
- }
-
- if quote == 1 {
- b = append(b, '\'')
- }
-
- return b
-}
-
-func appendDriverValuer(b []byte, v driver.Valuer, quote int) []byte {
- value, err := v.Value()
- if err != nil {
- return AppendError(b, err)
- }
- return Append(b, value, quote)
-}
-
-func appendAppender(b []byte, v ValueAppender, quote int) []byte {
- bb, err := v.AppendValue(b, quote)
- if err != nil {
- return AppendError(b, err)
- }
- return bb
-}
diff --git a/vendor/github.com/go-pg/pg/types/append_array.go b/vendor/github.com/go-pg/pg/types/append_array.go
deleted file mode 100644
index f04b687..0000000
--- a/vendor/github.com/go-pg/pg/types/append_array.go
+++ /dev/null
@@ -1,190 +0,0 @@
-package types
-
-import (
- "reflect"
- "strconv"
-)
-
-var stringType = reflect.TypeOf((*string)(nil)).Elem()
-var sliceStringType = reflect.TypeOf([]string(nil))
-
-var intType = reflect.TypeOf((*int)(nil)).Elem()
-var sliceIntType = reflect.TypeOf([]int(nil))
-
-var int64Type = reflect.TypeOf((*int64)(nil)).Elem()
-var sliceInt64Type = reflect.TypeOf([]int64(nil))
-
-var float64Type = reflect.TypeOf((*float64)(nil)).Elem()
-var sliceFloat64Type = reflect.TypeOf([]float64(nil))
-
-func ArrayAppender(typ reflect.Type) AppenderFunc {
- elemType := typ.Elem()
-
- switch elemType {
- case stringType:
- return appendSliceStringValue
- case intType:
- return appendSliceIntValue
- case int64Type:
- return appendSliceInt64Value
- case float64Type:
- return appendSliceFloat64Value
- }
-
- appendElem := appender(elemType, true)
- return func(b []byte, v reflect.Value, quote int) []byte {
- if v.IsNil() {
- return AppendNull(b, quote)
- }
-
- if quote == 1 {
- b = append(b, '\'')
- }
-
- b = append(b, '{')
- for i := 0; i < v.Len(); i++ {
- elem := v.Index(i)
- b = appendElem(b, elem, 2)
- b = append(b, ',')
- }
- if v.Len() > 0 {
- b[len(b)-1] = '}' // Replace trailing comma.
- } else {
- b = append(b, '}')
- }
-
- if quote == 1 {
- b = append(b, '\'')
- }
-
- return b
- }
-}
-
-func appendSliceStringValue(b []byte, v reflect.Value, quote int) []byte {
- ss := v.Convert(sliceStringType).Interface().([]string)
- return appendSliceString(b, ss, quote)
-}
-
-func appendSliceString(b []byte, ss []string, quote int) []byte {
- if ss == nil {
- return AppendNull(b, quote)
- }
-
- if quote == 1 {
- b = append(b, '\'')
- }
-
- b = append(b, '{')
- for _, s := range ss {
- b = AppendString(b, s, 2)
- b = append(b, ',')
- }
- if len(ss) > 0 {
- b[len(b)-1] = '}' // Replace trailing comma.
- } else {
- b = append(b, '}')
- }
-
- if quote == 1 {
- b = append(b, '\'')
- }
-
- return b
-}
-
-func appendSliceIntValue(b []byte, v reflect.Value, quote int) []byte {
- ints := v.Convert(sliceIntType).Interface().([]int)
- return appendSliceInt(b, ints, quote)
-}
-
-func appendSliceInt(b []byte, ints []int, quote int) []byte {
- if ints == nil {
- return AppendNull(b, quote)
- }
-
- if quote == 1 {
- b = append(b, '\'')
- }
-
- b = append(b, '{')
- for _, n := range ints {
- b = strconv.AppendInt(b, int64(n), 10)
- b = append(b, ',')
- }
- if len(ints) > 0 {
- b[len(b)-1] = '}' // Replace trailing comma.
- } else {
- b = append(b, '}')
- }
-
- if quote == 1 {
- b = append(b, '\'')
- }
-
- return b
-}
-
-func appendSliceInt64Value(b []byte, v reflect.Value, quote int) []byte {
- ints := v.Convert(sliceInt64Type).Interface().([]int64)
- return appendSliceInt64(b, ints, quote)
-}
-
-func appendSliceInt64(b []byte, ints []int64, quote int) []byte {
- if ints == nil {
- return AppendNull(b, quote)
- }
-
- if quote == 1 {
- b = append(b, '\'')
- }
-
- b = append(b, '{')
- for _, n := range ints {
- b = strconv.AppendInt(b, n, 10)
- b = append(b, ',')
- }
- if len(ints) > 0 {
- b[len(b)-1] = '}' // Replace trailing comma.
- } else {
- b = append(b, '}')
- }
-
- if quote == 1 {
- b = append(b, '\'')
- }
-
- return b
-}
-
-func appendSliceFloat64Value(b []byte, v reflect.Value, quote int) []byte {
- floats := v.Convert(sliceFloat64Type).Interface().([]float64)
- return appendSliceFloat64(b, floats, quote)
-}
-
-func appendSliceFloat64(b []byte, floats []float64, quote int) []byte {
- if floats == nil {
- return AppendNull(b, quote)
- }
-
- if quote == 1 {
- b = append(b, '\'')
- }
-
- b = append(b, '{')
- for _, n := range floats {
- b = appendFloat(b, n)
- b = append(b, ',')
- }
- if len(floats) > 0 {
- b[len(b)-1] = '}' // Replace trailing comma.
- } else {
- b = append(b, '}')
- }
-
- if quote == 1 {
- b = append(b, '\'')
- }
-
- return b
-}
diff --git a/vendor/github.com/go-pg/pg/types/append_field.go b/vendor/github.com/go-pg/pg/types/append_field.go
deleted file mode 100644
index 2fa86dc..0000000
--- a/vendor/github.com/go-pg/pg/types/append_field.go
+++ /dev/null
@@ -1,52 +0,0 @@
-package types
-
-import "github.com/go-pg/pg/internal/parser"
-
-func AppendField(b []byte, field string, quote int) []byte {
- return appendField(b, parser.NewString(field), quote)
-}
-
-func AppendFieldBytes(b []byte, field []byte, quote int) []byte {
- return appendField(b, parser.New(field), quote)
-}
-
-func appendField(b []byte, p *parser.Parser, quote int) []byte {
- var quoted bool
- for p.Valid() {
- c := p.Read()
- switch c {
- case '*':
- if !quoted {
- b = append(b, '*')
- continue
- }
- case '.':
- if quoted && quote == 1 {
- b = append(b, '"')
- quoted = false
- }
- b = append(b, '.')
- if p.Skip('*') {
- b = append(b, '*')
- } else if quote == 1 {
- b = append(b, '"')
- quoted = true
- }
- continue
- }
-
- if !quoted && quote == 1 {
- b = append(b, '"')
- quoted = true
- }
- if c == '"' {
- b = append(b, '"', '"')
- } else {
- b = append(b, c)
- }
- }
- if quoted && quote == 1 {
- b = append(b, '"')
- }
- return b
-}
diff --git a/vendor/github.com/go-pg/pg/types/append_field_test.go b/vendor/github.com/go-pg/pg/types/append_field_test.go
deleted file mode 100644
index 0193ad9..0000000
--- a/vendor/github.com/go-pg/pg/types/append_field_test.go
+++ /dev/null
@@ -1,37 +0,0 @@
-package types_test
-
-import (
- "testing"
-
- "github.com/go-pg/pg/types"
-)
-
-var appendFieldTests = []struct {
- field string
- wanted string
-}{
- {"", ""},
- {"id", `"id"`},
- {"table.id", `"table"."id"`},
-
- {"*", "*"},
- {"table.*", `"table".*`},
-
- {"id AS pk", `"id AS pk"`},
- {"table.id AS table__id", `"table"."id AS table__id"`},
-
- {"?shard", `"?shard"`},
- {"?shard.id", `"?shard"."id"`},
-
- {`"`, `""""`},
- {`'`, `"'"`},
-}
-
-func TestAppendField(t *testing.T) {
- for _, test := range appendFieldTests {
- got := types.AppendField(nil, test.field, 1)
- if string(got) != test.wanted {
- t.Errorf("got %q, wanted %q (field=%q)", got, test.wanted, test.field)
- }
- }
-}
diff --git a/vendor/github.com/go-pg/pg/types/append_hstore.go b/vendor/github.com/go-pg/pg/types/append_hstore.go
deleted file mode 100644
index 9549074..0000000
--- a/vendor/github.com/go-pg/pg/types/append_hstore.go
+++ /dev/null
@@ -1,49 +0,0 @@
-package types
-
-import (
- "fmt"
- "reflect"
-)
-
-var mapStringStringType = reflect.TypeOf(map[string]string(nil))
-
-func HstoreAppender(typ reflect.Type) AppenderFunc {
- if typ.Key() == stringType && typ.Elem() == stringType {
- return appendMapStringStringValue
- }
- return func(b []byte, v reflect.Value, quote int) []byte {
- err := fmt.Errorf("pg.Hstore(unsupported %s)", v.Type())
- return AppendError(b, err)
- }
-}
-
-func appendMapStringString(b []byte, m map[string]string, quote int) []byte {
- if m == nil {
- return AppendNull(b, quote)
- }
-
- if quote == 1 {
- b = append(b, '\'')
- }
-
- for key, value := range m {
- b = AppendString(b, key, 2)
- b = append(b, '=', '>')
- b = AppendString(b, value, 2)
- b = append(b, ',')
- }
- if len(m) > 0 {
- b = b[:len(b)-1] // Strip trailing comma.
- }
-
- if quote == 1 {
- b = append(b, '\'')
- }
-
- return b
-}
-
-func appendMapStringStringValue(b []byte, v reflect.Value, quote int) []byte {
- m := v.Convert(mapStringStringType).Interface().(map[string]string)
- return appendMapStringString(b, m, quote)
-}
diff --git a/vendor/github.com/go-pg/pg/types/append_jsonb.go b/vendor/github.com/go-pg/pg/types/append_jsonb.go
deleted file mode 100644
index 3bede71..0000000
--- a/vendor/github.com/go-pg/pg/types/append_jsonb.go
+++ /dev/null
@@ -1,41 +0,0 @@
-package types
-
-import "github.com/go-pg/pg/internal/parser"
-
-func AppendJSONB(b, jsonb []byte, quote int) []byte {
- if quote == 1 {
- b = append(b, '\'')
- }
-
- p := parser.New(jsonb)
- for p.Valid() {
- c := p.Read()
- switch c {
- case '\'':
- if quote == 1 {
- b = append(b, '\'', '\'')
- } else {
- b = append(b, '\'')
- }
- case '\000':
- continue
- case '\\':
- if p.SkipBytes([]byte("u0000")) {
- b = append(b, "\\\\u0000"...)
- } else {
- b = append(b, '\\')
- if p.Valid() {
- b = append(b, p.Read())
- }
- }
- default:
- b = append(b, c)
- }
- }
-
- if quote == 1 {
- b = append(b, '\'')
- }
-
- return b
-}
diff --git a/vendor/github.com/go-pg/pg/types/append_jsonb_test.go b/vendor/github.com/go-pg/pg/types/append_jsonb_test.go
deleted file mode 100644
index 645b8a5..0000000
--- a/vendor/github.com/go-pg/pg/types/append_jsonb_test.go
+++ /dev/null
@@ -1,43 +0,0 @@
-package types_test
-
-import (
- "bytes"
- "encoding/json"
- "testing"
-
- "github.com/go-pg/pg/types"
-)
-
-var jsonbTests = []struct {
- s, wanted string
-}{
- {`\u0000`, `\\u0000`},
- {`\\u0000`, `\\u0000`},
- {`\\\u0000`, `\\\\u0000`},
- {`foo \u0000 bar`, `foo \\u0000 bar`},
- {`\u0001`, `\u0001`},
- {`\\u0001`, `\\u0001`},
-}
-
-func TestAppendJSONB(t *testing.T) {
- for _, test := range jsonbTests {
- got := types.AppendJSONB(nil, []byte(test.s), 0)
- if !bytes.Equal(got, []byte(test.wanted)) {
- t.Errorf("got %q, wanted %q", got, test.wanted)
- }
- }
-}
-
-func BenchmarkAppendJSONB(b *testing.B) {
- bytes, err := json.Marshal(jsonbTests)
- if err != nil {
- b.Fatal(err)
- }
- buf := make([]byte, 1024)
-
- b.ResetTimer()
-
- for i := 0; i < b.N; i++ {
- _ = types.AppendJSONB(buf[:0], bytes, 1)
- }
-}
diff --git a/vendor/github.com/go-pg/pg/types/append_value.go b/vendor/github.com/go-pg/pg/types/append_value.go
deleted file mode 100644
index a107b17..0000000
--- a/vendor/github.com/go-pg/pg/types/append_value.go
+++ /dev/null
@@ -1,173 +0,0 @@
-package types
-
-import (
- "database/sql/driver"
- "encoding/json"
- "net"
- "reflect"
- "strconv"
- "time"
-)
-
-var driverValuerType = reflect.TypeOf((*driver.Valuer)(nil)).Elem()
-var appenderType = reflect.TypeOf((*ValueAppender)(nil)).Elem()
-
-type AppenderFunc func([]byte, reflect.Value, int) []byte
-
-var valueAppenders []AppenderFunc
-
-func init() {
- valueAppenders = []AppenderFunc{
- reflect.Bool: appendBoolValue,
- reflect.Int: appendIntValue,
- reflect.Int8: appendIntValue,
- reflect.Int16: appendIntValue,
- reflect.Int32: appendIntValue,
- reflect.Int64: appendIntValue,
- reflect.Uint: appendUintValue,
- reflect.Uint8: appendUintValue,
- reflect.Uint16: appendUintValue,
- reflect.Uint32: appendUintValue,
- reflect.Uint64: appendUintValue,
- reflect.Uintptr: nil,
- reflect.Float32: appendFloatValue,
- reflect.Float64: appendFloatValue,
- reflect.Complex64: nil,
- reflect.Complex128: nil,
- reflect.Array: nil,
- reflect.Chan: nil,
- reflect.Func: nil,
- reflect.Interface: appendIfaceValue,
- reflect.Map: appendJSONValue,
- reflect.Ptr: nil,
- reflect.Slice: appendJSONValue,
- reflect.String: appendStringValue,
- reflect.Struct: appendStructValue,
- reflect.UnsafePointer: nil,
- }
-}
-
-func Appender(typ reflect.Type) AppenderFunc {
- return appender(typ, false)
-}
-
-func appender(typ reflect.Type, pgArray bool) AppenderFunc {
- switch typ {
- case timeType:
- return appendTimeValue
- case ipType:
- return appendIPValue
- case ipNetType:
- return appendIPNetValue
- }
-
- if typ.Implements(appenderType) {
- return appendAppenderValue
- }
-
- if typ.Implements(driverValuerType) {
- return appendDriverValuerValue
- }
-
- kind := typ.Kind()
- switch kind {
- case reflect.Ptr:
- return ptrAppenderFunc(typ)
- case reflect.Slice:
- if typ.Elem().Kind() == reflect.Uint8 {
- return appendBytesValue
- }
- if pgArray {
- return ArrayAppender(typ)
- }
- }
- return valueAppenders[kind]
-}
-
-func ptrAppenderFunc(typ reflect.Type) AppenderFunc {
- appender := Appender(typ.Elem())
- return func(b []byte, v reflect.Value, quote int) []byte {
- if v.IsNil() {
- return AppendNull(b, quote)
- }
- return appender(b, v.Elem(), quote)
- }
-}
-
-func appendValue(b []byte, v reflect.Value, quote int) []byte {
- if v.Kind() == reflect.Ptr {
- if v.IsNil() {
- return AppendNull(b, quote)
- }
- return appendValue(b, v.Elem(), quote)
- }
-
- appender := Appender(v.Type())
- return appender(b, v, quote)
-}
-
-func appendIfaceValue(b []byte, v reflect.Value, quote int) []byte {
- return Append(b, v.Interface(), quote)
-}
-
-func appendBoolValue(b []byte, v reflect.Value, _ int) []byte {
- return appendBool(b, v.Bool())
-}
-
-func appendIntValue(b []byte, v reflect.Value, _ int) []byte {
- return strconv.AppendInt(b, v.Int(), 10)
-}
-
-func appendUintValue(b []byte, v reflect.Value, _ int) []byte {
- return strconv.AppendUint(b, v.Uint(), 10)
-}
-
-func appendFloatValue(b []byte, v reflect.Value, _ int) []byte {
- return appendFloat(b, v.Float())
-}
-
-func appendBytesValue(b []byte, v reflect.Value, quote int) []byte {
- return appendBytes(b, v.Bytes(), quote)
-}
-
-func appendStringValue(b []byte, v reflect.Value, quote int) []byte {
- return AppendString(b, v.String(), quote)
-}
-
-func appendStructValue(b []byte, v reflect.Value, quote int) []byte {
- if v.Type() == timeType {
- return appendTimeValue(b, v, quote)
- }
- return appendJSONValue(b, v, quote)
-}
-
-func appendJSONValue(b []byte, v reflect.Value, quote int) []byte {
- bytes, err := json.Marshal(v.Interface())
- if err != nil {
- return AppendError(b, err)
- }
- return AppendJSONB(b, bytes, quote)
-}
-
-func appendTimeValue(b []byte, v reflect.Value, quote int) []byte {
- tm := v.Interface().(time.Time)
- return AppendTime(b, tm, quote)
-}
-
-func appendIPValue(b []byte, v reflect.Value, quote int) []byte {
- ip := v.Interface().(net.IP)
- return AppendString(b, ip.String(), quote)
-}
-
-func appendIPNetValue(b []byte, v reflect.Value, quote int) []byte {
- ipnet := v.Interface().(net.IPNet)
- return AppendString(b, ipnet.String(), quote)
-}
-
-func appendAppenderValue(b []byte, v reflect.Value, quote int) []byte {
- return appendAppender(b, v.Interface().(ValueAppender), quote)
-}
-
-func appendDriverValuerValue(b []byte, v reflect.Value, quote int) []byte {
- return appendDriverValuer(b, v.Interface().(driver.Valuer), quote)
-}
diff --git a/vendor/github.com/go-pg/pg/types/array.go b/vendor/github.com/go-pg/pg/types/array.go
deleted file mode 100644
index a4ae31d..0000000
--- a/vendor/github.com/go-pg/pg/types/array.go
+++ /dev/null
@@ -1,53 +0,0 @@
-package types
-
-import (
- "database/sql"
- "fmt"
- "reflect"
-)
-
-type Array struct {
- v reflect.Value
-
- append AppenderFunc
- scan ScannerFunc
-}
-
-var _ ValueAppender = (*Array)(nil)
-var _ sql.Scanner = (*Array)(nil)
-
-func NewArray(vi interface{}) *Array {
- v := reflect.ValueOf(vi)
- if !v.IsValid() {
- panic(fmt.Errorf("pg.Array(nil)"))
- }
- v = reflect.Indirect(v)
- if v.Kind() != reflect.Slice {
- panic(fmt.Errorf("pg.Array(unsupported %s)", v.Type()))
- }
- return &Array{
- v: v,
-
- append: ArrayAppender(v.Type()),
- scan: ArrayScanner(v.Type()),
- }
-}
-
-func (a *Array) Value() interface{} {
- if a.v.IsValid() {
- return a.v.Interface()
- }
- return nil
-}
-
-func (a *Array) AppendValue(b []byte, quote int) ([]byte, error) {
- b = a.append(b, a.v, quote)
- return b, nil
-}
-
-func (a *Array) Scan(b interface{}) error {
- if b == nil {
- return a.scan(a.v, nil)
- }
- return a.scan(a.v, b.([]byte))
-}
diff --git a/vendor/github.com/go-pg/pg/types/hstore.go b/vendor/github.com/go-pg/pg/types/hstore.go
deleted file mode 100644
index b7e435c..0000000
--- a/vendor/github.com/go-pg/pg/types/hstore.go
+++ /dev/null
@@ -1,53 +0,0 @@
-package types
-
-import (
- "database/sql"
- "fmt"
- "reflect"
-)
-
-type Hstore struct {
- v reflect.Value
-
- append AppenderFunc
- scan ScannerFunc
-}
-
-var _ ValueAppender = (*Hstore)(nil)
-var _ sql.Scanner = (*Hstore)(nil)
-
-func NewHstore(vi interface{}) *Hstore {
- v := reflect.ValueOf(vi)
- if !v.IsValid() {
- panic(fmt.Errorf("pg.Hstore(nil)"))
- }
- v = reflect.Indirect(v)
- if v.Kind() != reflect.Map {
- panic(fmt.Errorf("pg.Hstore(unsupported %s)", v.Type()))
- }
- return &Hstore{
- v: v,
-
- append: HstoreAppender(v.Type()),
- scan: HstoreScanner(v.Type()),
- }
-}
-
-func (h *Hstore) Value() interface{} {
- if h.v.IsValid() {
- return h.v.Interface()
- }
- return nil
-}
-
-func (h *Hstore) AppendValue(b []byte, quote int) ([]byte, error) {
- b = h.append(b, h.v, quote)
- return b, nil
-}
-
-func (h *Hstore) Scan(b interface{}) error {
- if b == nil {
- return h.scan(h.v, nil)
- }
- return h.scan(h.v, b.([]byte))
-}
diff --git a/vendor/github.com/go-pg/pg/types/in_op.go b/vendor/github.com/go-pg/pg/types/in_op.go
deleted file mode 100644
index 3b3f687..0000000
--- a/vendor/github.com/go-pg/pg/types/in_op.go
+++ /dev/null
@@ -1,38 +0,0 @@
-package types
-
-import (
- "fmt"
- "reflect"
-)
-
-type InOp struct {
- slice reflect.Value
- append AppenderFunc
-}
-
-var _ ValueAppender = (*InOp)(nil)
-
-func In(slice interface{}) *InOp {
- v := reflect.ValueOf(slice)
- if !v.IsValid() {
- panic(fmt.Errorf("pg.In(nil)"))
- }
- if v.Kind() != reflect.Slice {
- panic(fmt.Errorf("pg.In(unsupported %s)", v.Type()))
- }
- return &InOp{
- slice: v,
- append: Appender(v.Type().Elem()),
- }
-}
-
-func (in *InOp) AppendValue(b []byte, quote int) ([]byte, error) {
- for i := 0; i < in.slice.Len(); i++ {
- b = in.append(b, in.slice.Index(i), quote)
- b = append(b, ',')
- }
- if in.slice.Len() > 0 {
- b = b[:len(b)-1]
- }
- return b, nil
-}
diff --git a/vendor/github.com/go-pg/pg/types/interface.go b/vendor/github.com/go-pg/pg/types/interface.go
deleted file mode 100644
index 8d2765a..0000000
--- a/vendor/github.com/go-pg/pg/types/interface.go
+++ /dev/null
@@ -1,27 +0,0 @@
-package types
-
-type ValueAppender interface {
- AppendValue(b []byte, quote int) ([]byte, error)
-}
-
-//------------------------------------------------------------------------------
-
-// Q represents safe SQL query.
-type Q string
-
-var _ ValueAppender = Q("")
-
-func (q Q) AppendValue(b []byte, quote int) ([]byte, error) {
- return append(b, q...), nil
-}
-
-//------------------------------------------------------------------------------
-
-// F represents a SQL field, e.g. table or column name.
-type F string
-
-var _ ValueAppender = F("")
-
-func (f F) AppendValue(b []byte, quote int) ([]byte, error) {
- return AppendField(b, string(f), quote), nil
-}
diff --git a/vendor/github.com/go-pg/pg/types/scan.go b/vendor/github.com/go-pg/pg/types/scan.go
deleted file mode 100644
index 658d361..0000000
--- a/vendor/github.com/go-pg/pg/types/scan.go
+++ /dev/null
@@ -1,84 +0,0 @@
-package types
-
-import (
- "database/sql"
- "encoding/hex"
- "errors"
- "fmt"
- "reflect"
- "strconv"
- "time"
-
- "github.com/go-pg/pg/internal"
-)
-
-func Scan(v interface{}, b []byte) error {
- switch v := v.(type) {
- case *string:
- *v = string(b)
- return nil
- case *[]byte:
- if b == nil {
- *v = nil
- return nil
- }
- var err error
- *v, err = scanBytes(b)
- return err
- case *int:
- if b == nil {
- *v = 0
- return nil
- }
- var err error
- *v, err = strconv.Atoi(internal.BytesToString(b))
- return err
- case *int64:
- if b == nil {
- *v = 0
- return nil
- }
- var err error
- *v, err = strconv.ParseInt(internal.BytesToString(b), 10, 64)
- return err
- case *time.Time:
- if b == nil {
- *v = time.Time{}
- return nil
- }
- var err error
- *v, err = ParseTime(b)
- return err
- }
-
- vv := reflect.ValueOf(v)
- if !vv.IsValid() {
- return errors.New("pg: Scan(nil)")
- }
- if vv.Kind() != reflect.Ptr {
- return fmt.Errorf("pg: Scan(non-pointer %T)", v)
- }
- vv = vv.Elem()
- if !vv.IsValid() {
- return fmt.Errorf("pg: Scan(non-pointer %T)", v)
- }
- return ScanValue(vv, b)
-}
-
-func scanSQLScanner(scanner sql.Scanner, b []byte) error {
- if b == nil {
- return scanner.Scan(nil)
- }
- return scanner.Scan(b)
-}
-
-func scanBytes(b []byte) ([]byte, error) {
- if len(b) < 2 {
- return nil, fmt.Errorf("pg: can't parse bytes: %q", b)
- }
-
- b = b[2:] // Trim off "\\x".
- tmp := make([]byte, hex.DecodedLen(len(b)))
- _, err := hex.Decode(tmp, b)
- return tmp, err
-}
diff --git a/vendor/github.com/go-pg/pg/types/scan_array.go b/vendor/github.com/go-pg/pg/types/scan_array.go
deleted file mode 100644
index ccc2924..0000000
--- a/vendor/github.com/go-pg/pg/types/scan_array.go
+++ /dev/null
@@ -1,189 +0,0 @@
-package types
-
-import (
- "fmt"
- "reflect"
- "strconv"
-
- "github.com/go-pg/pg/internal"
- "github.com/go-pg/pg/internal/parser"
-)
-
-func ArrayScanner(typ reflect.Type) ScannerFunc {
- elemType := typ.Elem()
-
- switch elemType {
- case stringType:
- return scanSliceStringValue
- case intType:
- return scanSliceIntValue
- case int64Type:
- return scanSliceInt64Value
- case float64Type:
- return scanSliceFloat64Value
- }
-
- scanElem := scanner(elemType, true)
- return func(v reflect.Value, b []byte) error {
- if !v.CanSet() {
- return fmt.Errorf("pg: Scan(non-pointer %s)", v.Type())
- }
- if b == nil {
- if !v.IsNil() {
- v.Set(reflect.New(v.Type()))
- }
- return nil
- }
- if v.IsNil() {
- v.Set(reflect.MakeSlice(v.Type(), 0, 0))
- }
- p := parser.NewArrayParser(b)
- for p.Valid() {
- elem, err := p.NextElem()
- if err != nil {
- return err
- }
- elemValue := internal.SliceNextElem(v)
- if err := scanElem(elemValue, elem); err != nil {
- return err
- }
- }
- return nil
- }
-}
-
-func scanSliceStringValue(v reflect.Value, b []byte) error {
- if !v.CanSet() {
- return fmt.Errorf("pg: Scan(non-pointer %s)", v.Type())
- }
- strings, err := decodeSliceString(b)
- if err != nil {
- return err
- }
- v.Set(reflect.ValueOf(strings))
- return nil
-}
-
-func decodeSliceString(b []byte) ([]string, error) {
- if b == nil {
- return nil, nil
- }
- p := parser.NewArrayParser(b)
- s := make([]string, 0)
- for p.Valid() {
- elem, err := p.NextElem()
- if err != nil {
- return nil, err
- }
- s = append(s, string(elem))
- }
- return s, nil
-}
-
-func scanSliceIntValue(v reflect.Value, b []byte) error {
- if !v.CanSet() {
- return fmt.Errorf("pg: Scan(non-pointer %s)", v.Type())
- }
- ints, err := decodeSliceInt(b)
- if err != nil {
- return err
- }
- v.Set(reflect.ValueOf(ints))
- return nil
-}
-
-func decodeSliceInt(b []byte) ([]int, error) {
- if b == nil {
- return nil, nil
- }
- p := parser.NewArrayParser(b)
- slice := make([]int, 0)
- for p.Valid() {
- elem, err := p.NextElem()
- if err != nil {
- return nil, err
- }
- if elem == nil {
- slice = append(slice, 0)
- continue
- }
- n, err := strconv.Atoi(string(elem))
- if err != nil {
- return nil, err
- }
- slice = append(slice, n)
- }
- return slice, nil
-}
-
-func scanSliceInt64Value(v reflect.Value, b []byte) error {
- if !v.CanSet() {
- return fmt.Errorf("pg: Scan(non-pointer %s)", v.Type())
- }
- ints, err := decodeSliceInt64(b)
- if err != nil {
- return err
- }
- v.Set(reflect.ValueOf(ints))
- return nil
-}
-
-func decodeSliceInt64(b []byte) ([]int64, error) {
- if b == nil {
- return nil, nil
- }
- p := parser.NewArrayParser(b)
- slice := make([]int64, 0)
- for p.Valid() {
- elem, err := p.NextElem()
- if err != nil {
- return nil, err
- }
- if elem == nil {
- slice = append(slice, 0)
- continue
- }
- n, err := strconv.ParseInt(internal.BytesToString(elem), 10, 64)
- if err != nil {
- return nil, err
- }
- slice = append(slice, n)
- }
- return slice, nil
-}
-
-func scanSliceFloat64Value(v reflect.Value, b []byte) error {
- if !v.CanSet() {
- return fmt.Errorf("pg: Scan(non-pointer %s)", v.Type())
- }
- floats, err := decodeSliceFloat64(b)
- if err != nil {
- return err
- }
- v.Set(reflect.ValueOf(floats))
- return nil
-}
-
-func decodeSliceFloat64(b []byte) ([]float64, error) {
- if b == nil {
- return nil, nil
- }
- p := parser.NewArrayParser(b)
- slice := make([]float64, 0)
- for p.Valid() {
- elem, err := p.NextElem()
- if err != nil {
- return nil, err
- }
- if elem == nil {
- slice = append(slice, 0)
- continue
- }
- n, err := strconv.ParseFloat(internal.BytesToString(elem), 64)
- if err != nil {
- return nil, err
- }
- slice = append(slice, n)
- }
- return slice, nil
-}
diff --git a/vendor/github.com/go-pg/pg/types/scan_hstore.go b/vendor/github.com/go-pg/pg/types/scan_hstore.go
deleted file mode 100644
index 86df53f..0000000
--- a/vendor/github.com/go-pg/pg/types/scan_hstore.go
+++ /dev/null
@@ -1,58 +0,0 @@
-package types
-
-import (
- "fmt"
- "reflect"
-
- "github.com/go-pg/pg/internal/parser"
-)
-
-func HstoreScanner(typ reflect.Type) ScannerFunc {
- if typ.Key() == stringType && typ.Elem() == stringType {
- return scanMapStringStringValue
- }
- return func(v reflect.Value, b []byte) error {
- return fmt.Errorf("pg.Hstore(unsupported %s)", v.Type())
- }
-}
-
-func scanMapStringString(b []byte) (map[string]string, error) {
- if b == nil {
- return nil, nil
- }
-
- p := parser.NewHstoreParser(b)
- m := make(map[string]string)
- for p.Valid() {
- key, err := p.NextKey()
- if err != nil {
- return nil, err
- }
- if key == nil {
- return nil, fmt.Errorf("pg: unexpected NULL: %q", b)
- }
-
- value, err := p.NextValue()
- if err != nil {
- return nil, err
- }
- if value == nil {
- return nil, fmt.Errorf("pg: unexpected NULL: %q", b)
- }
-
- m[string(key)] = string(value)
- }
- return m, nil
-}
-
-func scanMapStringStringValue(v reflect.Value, b []byte) error {
- if !v.CanSet() {
- return fmt.Errorf("pg: Scan(non-pointer %s)", v.Type())
- }
- m, err := scanMapStringString(b)
- if err != nil {
- return err
- }
- v.Set(reflect.ValueOf(m))
- return nil
-}
diff --git a/vendor/github.com/go-pg/pg/types/scan_value.go b/vendor/github.com/go-pg/pg/types/scan_value.go
deleted file mode 100644
index 9ac86be..0000000
--- a/vendor/github.com/go-pg/pg/types/scan_value.go
+++ /dev/null
@@ -1,305 +0,0 @@
-package types
-
-import (
- "database/sql"
- "encoding/json"
- "errors"
- "fmt"
- "net"
- "reflect"
- "strconv"
- "time"
-
- "github.com/go-pg/pg/internal"
-)
-
-var scannerType = reflect.TypeOf((*sql.Scanner)(nil)).Elem()
-var timeType = reflect.TypeOf((*time.Time)(nil)).Elem()
-var ipType = reflect.TypeOf((*net.IP)(nil)).Elem()
-var ipNetType = reflect.TypeOf((*net.IPNet)(nil)).Elem()
-
-type ScannerFunc func(reflect.Value, []byte) error
-
-var valueScanners []ScannerFunc
-
-func init() {
- valueScanners = []ScannerFunc{
- reflect.Bool: scanBoolValue,
- reflect.Int: scanIntValue,
- reflect.Int8: scanIntValue,
- reflect.Int16: scanIntValue,
- reflect.Int32: scanIntValue,
- reflect.Int64: scanIntValue,
- reflect.Uint: scanUintValue,
- reflect.Uint8: scanUintValue,
- reflect.Uint16: scanUintValue,
- reflect.Uint32: scanUintValue,
- reflect.Uint64: scanUintValue,
- reflect.Uintptr: nil,
- reflect.Float32: scanFloatValue,
- reflect.Float64: scanFloatValue,
- reflect.Complex64: nil,
- reflect.Complex128: nil,
- reflect.Array: nil,
- reflect.Chan: nil,
- reflect.Func: nil,
- reflect.Interface: scanIfaceValue,
- reflect.Map: scanJSONValue,
- reflect.Ptr: nil,
- reflect.Slice: scanJSONValue,
- reflect.String: scanStringValue,
- reflect.Struct: scanJSONValue,
- reflect.UnsafePointer: nil,
- }
-}
-
-func Scanner(typ reflect.Type) ScannerFunc {
- return scanner(typ, false)
-}
-
-func scanner(typ reflect.Type, pgArray bool) ScannerFunc {
- switch typ {
- case timeType:
- return scanTimeValue
- case ipType:
- return scanIPValue
- case ipNetType:
- return scanIPNetValue
- }
-
- if typ.Implements(scannerType) {
- return scanSQLScannerValue
- }
- if reflect.PtrTo(typ).Implements(scannerType) {
- return scanSQLScannerAddrValue
- }
-
- kind := typ.Kind()
- switch kind {
- case reflect.Ptr:
- return ptrScannerFunc(typ)
- case reflect.Slice:
- if typ.Elem().Kind() == reflect.Uint8 {
- return scanBytesValue
- }
- if pgArray {
- return ArrayScanner(typ)
- }
- }
- return valueScanners[kind]
-}
-
-func ptrScannerFunc(typ reflect.Type) ScannerFunc {
- scanner := Scanner(typ.Elem())
- return func(v reflect.Value, b []byte) error {
- if scanner == nil {
- return fmt.Errorf("pg: Scan(unsupported %s)", v.Type())
- }
- if b == nil {
- if v.IsNil() {
- return nil
- }
- if !v.CanSet() {
- return fmt.Errorf("pg: Scan(non-pointer %s)", v.Type())
- }
- v.Set(reflect.Zero(v.Type()))
- return nil
- }
- if v.IsNil() {
- if !v.CanSet() {
- return fmt.Errorf("pg: Scan(non-pointer %s)", v.Type())
- }
- v.Set(reflect.New(v.Type().Elem()))
- }
- return scanner(v.Elem(), b)
- }
-}
-
-func scanIfaceValue(v reflect.Value, b []byte) error {
- if v.IsNil() {
- return scanJSONValue(v, b)
- }
- return ScanValue(v.Elem(), b)
-}
-
-func ScanValue(v reflect.Value, b []byte) error {
- if !v.IsValid() {
- return errors.New("pg: Scan(nil)")
- }
-
- scanner := Scanner(v.Type())
- if scanner != nil {
- return scanner(v, b)
- }
-
- if v.Kind() == reflect.Interface {
- return errors.New("pg: Scan(nil)")
- }
- return fmt.Errorf("pg: Scan(unsupported %s)", v.Type())
-}
-
-func scanBoolValue(v reflect.Value, b []byte) error {
- if !v.CanSet() {
- return fmt.Errorf("pg: Scan(non-pointer %s)", v.Type())
- }
- if b == nil {
- v.SetBool(false)
- return nil
- }
- v.SetBool(len(b) == 1 && (b[0] == 't' || b[0] == '1'))
- return nil
-}
-
-func scanIntValue(v reflect.Value, b []byte) error {
- if !v.CanSet() {
- return fmt.Errorf("pg: Scan(non-pointer %s)", v.Type())
- }
- if b == nil {
- v.SetInt(0)
- return nil
- }
- n, err := strconv.ParseInt(internal.BytesToString(b), 10, 64)
- if err != nil {
- return err
- }
- v.SetInt(n)
- return nil
-}
-
-func scanUintValue(v reflect.Value, b []byte) error {
- if !v.CanSet() {
- return fmt.Errorf("pg: Scan(non-pointer %s)", v.Type())
- }
- if b == nil {
- v.SetUint(0)
- return nil
- }
- n, err := strconv.ParseUint(internal.BytesToString(b), 10, 64)
- if err != nil {
- return err
- }
- v.SetUint(n)
- return nil
-}
-
-func scanFloatValue(v reflect.Value, b []byte) error {
- if !v.CanSet() {
- return fmt.Errorf("pg: Scan(non-pointer %s)", v.Type())
- }
- if b == nil {
- v.SetFloat(0)
- return nil
- }
- n, err := strconv.ParseFloat(internal.BytesToString(b), 64)
- if err != nil {
- return err
- }
- v.SetFloat(n)
- return nil
-}
-
-func scanStringValue(v reflect.Value, b []byte) error {
- if !v.CanSet() {
- return fmt.Errorf("pg: Scan(non-pointer %s)", v.Type())
- }
- v.SetString(string(b))
- return nil
-}
-
-func scanJSONValue(v reflect.Value, b []byte) error {
- if !v.CanSet() {
- return fmt.Errorf("pg: Scan(non-pointer %s)", v.Type())
- }
- if b == nil {
- v.Set(reflect.New(v.Type()).Elem())
- return nil
- }
- return json.Unmarshal(b, v.Addr().Interface())
-}
-
-var zeroTimeValue = reflect.ValueOf(time.Time{})
-
-func scanTimeValue(v reflect.Value, b []byte) error {
- if !v.CanSet() {
- return fmt.Errorf("pg: Scan(non-pointer %s)", v.Type())
- }
- if b == nil {
- v.Set(zeroTimeValue)
- return nil
- }
- tm, err := ParseTime(b)
- if err != nil {
- return err
- }
- v.Set(reflect.ValueOf(tm))
- return nil
-}
-
-func scanIPValue(v reflect.Value, b []byte) error {
- if !v.CanSet() {
- return fmt.Errorf("pg: Scan(non-pointer %s)", v.Type())
- }
- if b == nil {
- return nil
- }
- ip := net.ParseIP(internal.BytesToString(b))
- if ip == nil {
- return fmt.Errorf("pg: invalid ip=%q", b)
- }
- v.Set(reflect.ValueOf(ip))
- return nil
-}
-
-var zeroIPNetValue = reflect.ValueOf(net.IPNet{})
-
-func scanIPNetValue(v reflect.Value, b []byte) error {
- if !v.CanSet() {
- return fmt.Errorf("pg: Scan(non-pointer %s)", v.Type())
- }
- if b == nil {
- v.Set(zeroIPNetValue)
- return nil
- }
- _, ipnet, err := net.ParseCIDR(internal.BytesToString(b))
- if err != nil {
- return err
- }
- v.Set(reflect.ValueOf(*ipnet))
- return nil
-}
-
-func scanBytesValue(v reflect.Value, b []byte) error {
- if !v.CanSet() {
- return fmt.Errorf("pg: Scan(non-pointer %s)", v.Type())
- }
- if b == nil {
- v.SetBytes(nil)
- return nil
- }
- bs, err := scanBytes(b)
- if err != nil {
- return err
- }
- v.SetBytes(bs)
- return nil
-}
-
-func scanSQLScannerValue(v reflect.Value, b []byte) error {
- if b == nil {
- if v.IsNil() {
- return nil
- }
- return scanSQLScanner(v.Interface().(sql.Scanner), nil)
- }
- if v.IsNil() {
- v.Set(reflect.New(v.Type().Elem()))
- }
- return scanSQLScanner(v.Interface().(sql.Scanner), b)
-}
-
-func scanSQLScannerAddrValue(v reflect.Value, b []byte) error {
- if !v.CanAddr() {
- return fmt.Errorf("pg: Scan(non-pointer %s)", v.Type())
- }
- return scanSQLScanner(v.Addr().Interface().(sql.Scanner), b)
-}
diff --git a/vendor/github.com/go-pg/pg/types/time.go b/vendor/github.com/go-pg/pg/types/time.go
deleted file mode 100644
index 4ab3071..0000000
--- a/vendor/github.com/go-pg/pg/types/time.go
+++ /dev/null
@@ -1,43 +0,0 @@
-package types
-
-import "time"
-
-const (
- dateFormat = "2006-01-02"
- timeFormat = "15:04:05.999999999"
- timestampFormat = "2006-01-02 15:04:05.999999999"
- timestamptzFormat = "2006-01-02 15:04:05.999999999-07:00:00"
- timestamptzFormat2 = "2006-01-02 15:04:05.999999999-07:00"
- timestamptzFormat3 = "2006-01-02 15:04:05.999999999-07"
-)
-
-func ParseTime(b []byte) (time.Time, error) {
- switch l := len(b); {
- case l <= len(dateFormat):
- return time.Parse(dateFormat, string(b))
- case l <= len(timeFormat):
- return time.Parse(timeFormat, string(b))
- default:
- if c := b[len(b)-9]; c == '+' || c == '-' {
- return time.Parse(timestamptzFormat, string(b))
- }
- if c := b[len(b)-6]; c == '+' || c == '-' {
- return time.Parse(timestamptzFormat2, string(b))
- }
- if c := b[len(b)-3]; c == '+' || c == '-' {
- return time.Parse(timestamptzFormat3, string(b))
- }
- return time.ParseInLocation(timestampFormat, string(b), time.Local)
- }
-}
-
-func AppendTime(b []byte, tm time.Time, quote int) []byte {
- if quote == 1 {
- b = append(b, '\'')
- }
- b = tm.AppendFormat(b, timestamptzFormat)
- if quote == 1 {
- b = append(b, '\'')
- }
- return b
-}
diff --git a/vendor/github.com/go-pg/pg/types/time_test.go b/vendor/github.com/go-pg/pg/types/time_test.go
deleted file mode 100644
index 20734eb..0000000
--- a/vendor/github.com/go-pg/pg/types/time_test.go
+++ /dev/null
@@ -1,13 +0,0 @@
-package types_test
-
-import (
- "testing"
-
- "github.com/go-pg/pg/types"
-)
-
-func BenchmarkParseTime(b *testing.B) {
- for i := 0; i < b.N; i++ {
- types.ParseTime([]byte("2001-02-03 04:05:06+07"))
- }
-}
diff --git a/vendor/github.com/gorilla/css/.gitignore b/vendor/github.com/gorilla/css/.gitignore
deleted file mode 100644
index 0026861..0000000
--- a/vendor/github.com/gorilla/css/.gitignore
+++ /dev/null
@@ -1,22 +0,0 @@
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-*.exe
diff --git a/vendor/github.com/gorilla/css/.travis.yml b/vendor/github.com/gorilla/css/.travis.yml
deleted file mode 100644
index fe78007..0000000
--- a/vendor/github.com/gorilla/css/.travis.yml
+++ /dev/null
@@ -1,20 +0,0 @@
-language: go
-sudo: false
-
-matrix:
- include:
- - go: 1.3
- - go: 1.4
- - go: 1.5
- - go: 1.6
- - go: 1.7
- - go: 1.8
- - go: tip
- allow_failures:
- - go: tip
-
-script:
- - go get -t -v ./...
- - diff -u <(echo -n) <(gofmt -d .)
- - go vet $(go list ./... | grep -v /vendor/)
- - go test -v -race ./...
diff --git a/vendor/github.com/gorilla/css/LICENSE b/vendor/github.com/gorilla/css/LICENSE
deleted file mode 100644
index bee2a05..0000000
--- a/vendor/github.com/gorilla/css/LICENSE
+++ /dev/null
@@ -1,27 +0,0 @@
-Copyright (c) 2013, Gorilla web toolkit
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without modification,
-are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice, this
- list of conditions and the following disclaimer in the documentation and/or
- other materials provided with the distribution.
-
- Neither the name of the {organization} nor the names of its
- contributors may be used to endorse or promote products derived from
- this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
-ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
-ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/vendor/github.com/gorilla/css/README.md b/vendor/github.com/gorilla/css/README.md
deleted file mode 100644
index e266555..0000000
--- a/vendor/github.com/gorilla/css/README.md
+++ /dev/null
@@ -1,5 +0,0 @@
-css
-===
-[](https://godoc.org/github.com/gorilla/css) [](https://travis-ci.org/gorilla/css)
-
-A CSS3 tokenizer.
diff --git a/vendor/github.com/gorilla/css/scanner/doc.go b/vendor/github.com/gorilla/css/scanner/doc.go
deleted file mode 100644
index f19850e..0000000
--- a/vendor/github.com/gorilla/css/scanner/doc.go
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright 2012 The Gorilla 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 gorilla/css/scanner generates tokens for a CSS3 input.
-
-It follows the CSS3 specification located at:
-
- http://www.w3.org/TR/css3-syntax/
-
-To use it, create a new scanner for a given CSS string and call Next() until
-the token returned has type TokenEOF or TokenError:
-
- s := scanner.New(myCSS)
- for {
- token := s.Next()
- if token.Type == scanner.TokenEOF || token.Type == scanner.TokenError {
- break
- }
- // Do something with the token...
- }
-
-Following the CSS3 specification, an error can only occur when the scanner
-finds an unclosed quote or unclosed comment. In these cases the text becomes
-"untokenizable". Everything else is tokenizable and it is up to a parser
-to make sense of the token stream (or ignore nonsensical token sequences).
-
-Note: the scanner doesn't perform lexical analysis or, in other words, it
-doesn't care about the token context. It is intended to be used by a
-lexer or parser.
-*/
-package scanner
diff --git a/vendor/github.com/gorilla/css/scanner/scanner.go b/vendor/github.com/gorilla/css/scanner/scanner.go
deleted file mode 100644
index 23fa740..0000000
--- a/vendor/github.com/gorilla/css/scanner/scanner.go
+++ /dev/null
@@ -1,356 +0,0 @@
-// Copyright 2012 The Gorilla 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 scanner
-
-import (
- "fmt"
- "regexp"
- "strings"
- "unicode"
- "unicode/utf8"
-)
-
-// tokenType identifies the type of lexical tokens.
-type tokenType int
-
-// String returns a string representation of the token type.
-func (t tokenType) String() string {
- return tokenNames[t]
-}
-
-// Token represents a token and the corresponding string.
-type Token struct {
- Type tokenType
- Value string
- Line int
- Column int
-}
-
-// String returns a string representation of the token.
-func (t *Token) String() string {
- if len(t.Value) > 10 {
- return fmt.Sprintf("%s (line: %d, column: %d): %.10q...",
- t.Type, t.Line, t.Column, t.Value)
- }
- return fmt.Sprintf("%s (line: %d, column: %d): %q",
- t.Type, t.Line, t.Column, t.Value)
-}
-
-// All tokens -----------------------------------------------------------------
-
-// The complete list of tokens in CSS3.
-const (
- // Scanner flags.
- TokenError tokenType = iota
- TokenEOF
- // From now on, only tokens from the CSS specification.
- TokenIdent
- TokenAtKeyword
- TokenString
- TokenHash
- TokenNumber
- TokenPercentage
- TokenDimension
- TokenURI
- TokenUnicodeRange
- TokenCDO
- TokenCDC
- TokenS
- TokenComment
- TokenFunction
- TokenIncludes
- TokenDashMatch
- TokenPrefixMatch
- TokenSuffixMatch
- TokenSubstringMatch
- TokenChar
- TokenBOM
-)
-
-// tokenNames maps tokenType's to their names. Used for conversion to string.
-var tokenNames = map[tokenType]string{
- TokenError: "error",
- TokenEOF: "EOF",
- TokenIdent: "IDENT",
- TokenAtKeyword: "ATKEYWORD",
- TokenString: "STRING",
- TokenHash: "HASH",
- TokenNumber: "NUMBER",
- TokenPercentage: "PERCENTAGE",
- TokenDimension: "DIMENSION",
- TokenURI: "URI",
- TokenUnicodeRange: "UNICODE-RANGE",
- TokenCDO: "CDO",
- TokenCDC: "CDC",
- TokenS: "S",
- TokenComment: "COMMENT",
- TokenFunction: "FUNCTION",
- TokenIncludes: "INCLUDES",
- TokenDashMatch: "DASHMATCH",
- TokenPrefixMatch: "PREFIXMATCH",
- TokenSuffixMatch: "SUFFIXMATCH",
- TokenSubstringMatch: "SUBSTRINGMATCH",
- TokenChar: "CHAR",
- TokenBOM: "BOM",
-}
-
-// Macros and productions -----------------------------------------------------
-// http://www.w3.org/TR/css3-syntax/#tokenization
-
-var macroRegexp = regexp.MustCompile(`\{[a-z]+\}`)
-
-// macros maps macro names to patterns to be expanded.
-var macros = map[string]string{
- // must be escaped: `\.+*?()|[]{}^$`
- "ident": `-?{nmstart}{nmchar}*`,
- "name": `{nmchar}+`,
- "nmstart": `[a-zA-Z_]|{nonascii}|{escape}`,
- "nonascii": "[\u0080-\uD7FF\uE000-\uFFFD\U00010000-\U0010FFFF]",
- "unicode": `\\[0-9a-fA-F]{1,6}{wc}?`,
- "escape": "{unicode}|\\\\[\u0020-\u007E\u0080-\uD7FF\uE000-\uFFFD\U00010000-\U0010FFFF]",
- "nmchar": `[a-zA-Z0-9_-]|{nonascii}|{escape}`,
- "num": `[0-9]*\.[0-9]+|[0-9]+`,
- "string": `"(?:{stringchar}|')*"|'(?:{stringchar}|")*'`,
- "stringchar": `{urlchar}|[ ]|\\{nl}`,
- "nl": `[\n\r\f]|\r\n`,
- "w": `{wc}*`,
- "wc": `[\t\n\f\r ]`,
-
- // urlchar should accept [(ascii characters minus those that need escaping)|{nonascii}|{escape}]
- // ASCII characters range = `[\u0020-\u007e]`
- // Skip space \u0020 = `[\u0021-\u007e]`
- // Skip quotation mark \0022 = `[\u0021\u0023-\u007e]`
- // Skip apostrophe \u0027 = `[\u0021\u0023-\u0026\u0028-\u007e]`
- // Skip reverse solidus \u005c = `[\u0021\u0023-\u0026\u0028-\u005b\u005d\u007e]`
- // Finally, the left square bracket (\u005b) and right (\u005d) needs escaping themselves
- "urlchar": "[\u0021\u0023-\u0026\u0028-\\\u005b\\\u005d-\u007E]|{nonascii}|{escape}",
-}
-
-// productions maps the list of tokens to patterns to be expanded.
-var productions = map[tokenType]string{
- // Unused regexps (matched using other methods) are commented out.
- TokenIdent: `{ident}`,
- TokenAtKeyword: `@{ident}`,
- TokenString: `{string}`,
- TokenHash: `#{name}`,
- TokenNumber: `{num}`,
- TokenPercentage: `{num}%`,
- TokenDimension: `{num}{ident}`,
- TokenURI: `url\({w}(?:{string}|{urlchar}*?){w}\)`,
- TokenUnicodeRange: `U\+[0-9A-F\?]{1,6}(?:-[0-9A-F]{1,6})?`,
- //TokenCDO: ``,
- TokenS: `{wc}+`,
- TokenComment: `/\*[^\*]*[\*]+(?:[^/][^\*]*[\*]+)*/`,
- TokenFunction: `{ident}\(`,
- //TokenIncludes: `~=`,
- //TokenDashMatch: `\|=`,
- //TokenPrefixMatch: `\^=`,
- //TokenSuffixMatch: `\$=`,
- //TokenSubstringMatch: `\*=`,
- //TokenChar: `[^"']`,
- //TokenBOM: "\uFEFF",
-}
-
-// matchers maps the list of tokens to compiled regular expressions.
-//
-// The map is filled on init() using the macros and productions defined in
-// the CSS specification.
-var matchers = map[tokenType]*regexp.Regexp{}
-
-// matchOrder is the order to test regexps when first-char shortcuts
-// can't be used.
-var matchOrder = []tokenType{
- TokenURI,
- TokenFunction,
- TokenUnicodeRange,
- TokenIdent,
- TokenDimension,
- TokenPercentage,
- TokenNumber,
- TokenCDC,
-}
-
-func init() {
- // replace macros and compile regexps for productions.
- replaceMacro := func(s string) string {
- return "(?:" + macros[s[1:len(s)-1]] + ")"
- }
- for t, s := range productions {
- for macroRegexp.MatchString(s) {
- s = macroRegexp.ReplaceAllStringFunc(s, replaceMacro)
- }
- matchers[t] = regexp.MustCompile("^(?:" + s + ")")
- }
-}
-
-// Scanner --------------------------------------------------------------------
-
-// New returns a new CSS scanner for the given input.
-func New(input string) *Scanner {
- // Normalize newlines.
- input = strings.Replace(input, "\r\n", "\n", -1)
- return &Scanner{
- input: input,
- row: 1,
- col: 1,
- }
-}
-
-// Scanner scans an input and emits tokens following the CSS3 specification.
-type Scanner struct {
- input string
- pos int
- row int
- col int
- err *Token
-}
-
-// Next returns the next token from the input.
-//
-// At the end of the input the token type is TokenEOF.
-//
-// If the input can't be tokenized the token type is TokenError. This occurs
-// in case of unclosed quotation marks or comments.
-func (s *Scanner) Next() *Token {
- if s.err != nil {
- return s.err
- }
- if s.pos >= len(s.input) {
- s.err = &Token{TokenEOF, "", s.row, s.col}
- return s.err
- }
- if s.pos == 0 {
- // Test BOM only once, at the beginning of the file.
- if strings.HasPrefix(s.input, "\uFEFF") {
- return s.emitSimple(TokenBOM, "\uFEFF")
- }
- }
- // There's a lot we can guess based on the first byte so we'll take a
- // shortcut before testing multiple regexps.
- input := s.input[s.pos:]
- switch input[0] {
- case '\t', '\n', '\f', '\r', ' ':
- // Whitespace.
- return s.emitToken(TokenS, matchers[TokenS].FindString(input))
- case '.':
- // Dot is too common to not have a quick check.
- // We'll test if this is a Char; if it is followed by a number it is a
- // dimension/percentage/number, and this will be matched later.
- if len(input) > 1 && !unicode.IsDigit(rune(input[1])) {
- return s.emitSimple(TokenChar, ".")
- }
- case '#':
- // Another common one: Hash or Char.
- if match := matchers[TokenHash].FindString(input); match != "" {
- return s.emitToken(TokenHash, match)
- }
- return s.emitSimple(TokenChar, "#")
- case '@':
- // Another common one: AtKeyword or Char.
- if match := matchers[TokenAtKeyword].FindString(input); match != "" {
- return s.emitSimple(TokenAtKeyword, match)
- }
- return s.emitSimple(TokenChar, "@")
- case ':', ',', ';', '%', '&', '+', '=', '>', '(', ')', '[', ']', '{', '}':
- // More common chars.
- return s.emitSimple(TokenChar, string(input[0]))
- case '"', '\'':
- // String or error.
- match := matchers[TokenString].FindString(input)
- if match != "" {
- return s.emitToken(TokenString, match)
- }
-
- s.err = &Token{TokenError, "unclosed quotation mark", s.row, s.col}
- return s.err
- case '/':
- // Comment, error or Char.
- if len(input) > 1 && input[1] == '*' {
- match := matchers[TokenComment].FindString(input)
- if match != "" {
- return s.emitToken(TokenComment, match)
- } else {
- s.err = &Token{TokenError, "unclosed comment", s.row, s.col}
- return s.err
- }
- }
- return s.emitSimple(TokenChar, "/")
- case '~':
- // Includes or Char.
- return s.emitPrefixOrChar(TokenIncludes, "~=")
- case '|':
- // DashMatch or Char.
- return s.emitPrefixOrChar(TokenDashMatch, "|=")
- case '^':
- // PrefixMatch or Char.
- return s.emitPrefixOrChar(TokenPrefixMatch, "^=")
- case '$':
- // SuffixMatch or Char.
- return s.emitPrefixOrChar(TokenSuffixMatch, "$=")
- case '*':
- // SubstringMatch or Char.
- return s.emitPrefixOrChar(TokenSubstringMatch, "*=")
- case '<':
- // CDO or Char.
- return s.emitPrefixOrChar(TokenCDO, "", TokenCDC, "-->")
- checkMatch(" \n \t \n", TokenS, " \n \t \n")
- checkMatch("/* foo */", TokenComment, "/* foo */")
- checkMatch("bar(", TokenFunction, "bar(")
- checkMatch("~=", TokenIncludes, "~=")
- checkMatch("|=", TokenDashMatch, "|=")
- checkMatch("^=", TokenPrefixMatch, "^=")
- checkMatch("$=", TokenSuffixMatch, "$=")
- checkMatch("*=", TokenSubstringMatch, "*=")
- checkMatch("{", TokenChar, "{")
- checkMatch("\uFEFF", TokenBOM, "\uFEFF")
- checkMatch(`╯︵┻━┻"stuff"`, TokenIdent, "╯︵┻━┻", TokenString, `"stuff"`)
-}
diff --git a/vendor/github.com/hashicorp/hcl/.gitignore b/vendor/github.com/hashicorp/hcl/.gitignore
deleted file mode 100644
index 822fa09..0000000
--- a/vendor/github.com/hashicorp/hcl/.gitignore
+++ /dev/null
@@ -1,9 +0,0 @@
-y.output
-
-# ignore intellij files
-.idea
-*.iml
-*.ipr
-*.iws
-
-*.test
diff --git a/vendor/github.com/hashicorp/hcl/.travis.yml b/vendor/github.com/hashicorp/hcl/.travis.yml
deleted file mode 100644
index cb63a32..0000000
--- a/vendor/github.com/hashicorp/hcl/.travis.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-sudo: false
-
-language: go
-
-go:
- - 1.x
- - tip
-
-branches:
- only:
- - master
-
-script: make test
diff --git a/vendor/github.com/hashicorp/hcl/LICENSE b/vendor/github.com/hashicorp/hcl/LICENSE
deleted file mode 100644
index c33dcc7..0000000
--- a/vendor/github.com/hashicorp/hcl/LICENSE
+++ /dev/null
@@ -1,354 +0,0 @@
-Mozilla Public License, version 2.0
-
-1. Definitions
-
-1.1. “Contributor”
-
- means each individual or legal entity that creates, contributes to the
- creation of, or owns Covered Software.
-
-1.2. “Contributor Version”
-
- means the combination of the Contributions of others (if any) used by a
- Contributor and that particular Contributor’s Contribution.
-
-1.3. “Contribution”
-
- means Covered Software of a particular Contributor.
-
-1.4. “Covered Software”
-
- means Source Code Form to which the initial Contributor has attached the
- notice in Exhibit A, the Executable Form of such Source Code Form, and
- Modifications of such Source Code Form, in each case including portions
- thereof.
-
-1.5. “Incompatible With Secondary Licenses”
- means
-
- a. that the initial Contributor has attached the notice described in
- Exhibit B to the Covered Software; or
-
- b. that the Covered Software was made available under the terms of version
- 1.1 or earlier of the License, but not also under the terms of a
- Secondary License.
-
-1.6. “Executable Form”
-
- means any form of the work other than Source Code Form.
-
-1.7. “Larger Work”
-
- means a work that combines Covered Software with other material, in a separate
- file or files, that is not Covered Software.
-
-1.8. “License”
-
- means this document.
-
-1.9. “Licensable”
-
- means having the right to grant, to the maximum extent possible, whether at the
- time of the initial grant or subsequently, any and all of the rights conveyed by
- this License.
-
-1.10. “Modifications”
-
- means any of the following:
-
- a. any file in Source Code Form that results from an addition to, deletion
- from, or modification of the contents of Covered Software; or
-
- b. any new file in Source Code Form that contains any Covered Software.
-
-1.11. “Patent Claims” of a Contributor
-
- means any patent claim(s), including without limitation, method, process,
- and apparatus claims, in any patent Licensable by such Contributor that
- would be infringed, but for the grant of the License, by the making,
- using, selling, offering for sale, having made, import, or transfer of
- either its Contributions or its Contributor Version.
-
-1.12. “Secondary License”
-
- means either the GNU General Public License, Version 2.0, the GNU Lesser
- General Public License, Version 2.1, the GNU Affero General Public
- License, Version 3.0, or any later versions of those licenses.
-
-1.13. “Source Code Form”
-
- means the form of the work preferred for making modifications.
-
-1.14. “You” (or “Your”)
-
- means an individual or a legal entity exercising rights under this
- License. For legal entities, “You” includes any entity that controls, is
- controlled by, or is under common control with You. For purposes of this
- definition, “control” means (a) the power, direct or indirect, to cause
- the direction or management of such entity, whether by contract or
- otherwise, or (b) ownership of more than fifty percent (50%) of the
- outstanding shares or beneficial ownership of such entity.
-
-
-2. License Grants and Conditions
-
-2.1. Grants
-
- Each Contributor hereby grants You a world-wide, royalty-free,
- non-exclusive license:
-
- a. under intellectual property rights (other than patent or trademark)
- Licensable by such Contributor to use, reproduce, make available,
- modify, display, perform, distribute, and otherwise exploit its
- Contributions, either on an unmodified basis, with Modifications, or as
- part of a Larger Work; and
-
- b. under Patent Claims of such Contributor to make, use, sell, offer for
- sale, have made, import, and otherwise transfer either its Contributions
- or its Contributor Version.
-
-2.2. Effective Date
-
- The licenses granted in Section 2.1 with respect to any Contribution become
- effective for each Contribution on the date the Contributor first distributes
- such Contribution.
-
-2.3. Limitations on Grant Scope
-
- The licenses granted in this Section 2 are the only rights granted under this
- License. No additional rights or licenses will be implied from the distribution
- or licensing of Covered Software under this License. Notwithstanding Section
- 2.1(b) above, no patent license is granted by a Contributor:
-
- a. for any code that a Contributor has removed from Covered Software; or
-
- b. for infringements caused by: (i) Your and any other third party’s
- modifications of Covered Software, or (ii) the combination of its
- Contributions with other software (except as part of its Contributor
- Version); or
-
- c. under Patent Claims infringed by Covered Software in the absence of its
- Contributions.
-
- This License does not grant any rights in the trademarks, service marks, or
- logos of any Contributor (except as may be necessary to comply with the
- notice requirements in Section 3.4).
-
-2.4. Subsequent Licenses
-
- No Contributor makes additional grants as a result of Your choice to
- distribute the Covered Software under a subsequent version of this License
- (see Section 10.2) or under the terms of a Secondary License (if permitted
- under the terms of Section 3.3).
-
-2.5. Representation
-
- Each Contributor represents that the Contributor believes its Contributions
- are its original creation(s) or it has sufficient rights to grant the
- rights to its Contributions conveyed by this License.
-
-2.6. Fair Use
-
- This License is not intended to limit any rights You have under applicable
- copyright doctrines of fair use, fair dealing, or other equivalents.
-
-2.7. Conditions
-
- Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
- Section 2.1.
-
-
-3. Responsibilities
-
-3.1. Distribution of Source Form
-
- All distribution of Covered Software in Source Code Form, including any
- Modifications that You create or to which You contribute, must be under the
- terms of this License. You must inform recipients that the Source Code Form
- of the Covered Software is governed by the terms of this License, and how
- they can obtain a copy of this License. You may not attempt to alter or
- restrict the recipients’ rights in the Source Code Form.
-
-3.2. Distribution of Executable Form
-
- If You distribute Covered Software in Executable Form then:
-
- a. such Covered Software must also be made available in Source Code Form,
- as described in Section 3.1, and You must inform recipients of the
- Executable Form how they can obtain a copy of such Source Code Form by
- reasonable means in a timely manner, at a charge no more than the cost
- of distribution to the recipient; and
-
- b. You may distribute such Executable Form under the terms of this License,
- or sublicense it under different terms, provided that the license for
- the Executable Form does not attempt to limit or alter the recipients’
- rights in the Source Code Form under this License.
-
-3.3. Distribution of a Larger Work
-
- You may create and distribute a Larger Work under terms of Your choice,
- provided that You also comply with the requirements of this License for the
- Covered Software. If the Larger Work is a combination of Covered Software
- with a work governed by one or more Secondary Licenses, and the Covered
- Software is not Incompatible With Secondary Licenses, this License permits
- You to additionally distribute such Covered Software under the terms of
- such Secondary License(s), so that the recipient of the Larger Work may, at
- their option, further distribute the Covered Software under the terms of
- either this License or such Secondary License(s).
-
-3.4. Notices
-
- You may not remove or alter the substance of any license notices (including
- copyright notices, patent notices, disclaimers of warranty, or limitations
- of liability) contained within the Source Code Form of the Covered
- Software, except that You may alter any license notices to the extent
- required to remedy known factual inaccuracies.
-
-3.5. Application of Additional Terms
-
- You may choose to offer, and to charge a fee for, warranty, support,
- indemnity or liability obligations to one or more recipients of Covered
- Software. However, You may do so only on Your own behalf, and not on behalf
- of any Contributor. You must make it absolutely clear that any such
- warranty, support, indemnity, or liability obligation is offered by You
- alone, and You hereby agree to indemnify every Contributor for any
- liability incurred by such Contributor as a result of warranty, support,
- indemnity or liability terms You offer. You may include additional
- disclaimers of warranty and limitations of liability specific to any
- jurisdiction.
-
-4. Inability to Comply Due to Statute or Regulation
-
- If it is impossible for You to comply with any of the terms of this License
- with respect to some or all of the Covered Software due to statute, judicial
- order, or regulation then You must: (a) comply with the terms of this License
- to the maximum extent possible; and (b) describe the limitations and the code
- they affect. Such description must be placed in a text file included with all
- distributions of the Covered Software under this License. Except to the
- extent prohibited by statute or regulation, such description must be
- sufficiently detailed for a recipient of ordinary skill to be able to
- understand it.
-
-5. Termination
-
-5.1. The rights granted under this License will terminate automatically if You
- fail to comply with any of its terms. However, if You become compliant,
- then the rights granted under this License from a particular Contributor
- are reinstated (a) provisionally, unless and until such Contributor
- explicitly and finally terminates Your grants, and (b) on an ongoing basis,
- if such Contributor fails to notify You of the non-compliance by some
- reasonable means prior to 60 days after You have come back into compliance.
- Moreover, Your grants from a particular Contributor are reinstated on an
- ongoing basis if such Contributor notifies You of the non-compliance by
- some reasonable means, this is the first time You have received notice of
- non-compliance with this License from such Contributor, and You become
- compliant prior to 30 days after Your receipt of the notice.
-
-5.2. If You initiate litigation against any entity by asserting a patent
- infringement claim (excluding declaratory judgment actions, counter-claims,
- and cross-claims) alleging that a Contributor Version directly or
- indirectly infringes any patent, then the rights granted to You by any and
- all Contributors for the Covered Software under Section 2.1 of this License
- shall terminate.
-
-5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
- license agreements (excluding distributors and resellers) which have been
- validly granted by You or Your distributors under this License prior to
- termination shall survive termination.
-
-6. Disclaimer of Warranty
-
- Covered Software is provided under this License on an “as is” basis, without
- warranty of any kind, either expressed, implied, or statutory, including,
- without limitation, warranties that the Covered Software is free of defects,
- merchantable, fit for a particular purpose or non-infringing. The entire
- risk as to the quality and performance of the Covered Software is with You.
- Should any Covered Software prove defective in any respect, You (not any
- Contributor) assume the cost of any necessary servicing, repair, or
- correction. This disclaimer of warranty constitutes an essential part of this
- License. No use of any Covered Software is authorized under this License
- except under this disclaimer.
-
-7. Limitation of Liability
-
- Under no circumstances and under no legal theory, whether tort (including
- negligence), contract, or otherwise, shall any Contributor, or anyone who
- distributes Covered Software as permitted above, be liable to You for any
- direct, indirect, special, incidental, or consequential damages of any
- character including, without limitation, damages for lost profits, loss of
- goodwill, work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses, even if such party shall have been
- informed of the possibility of such damages. This limitation of liability
- shall not apply to liability for death or personal injury resulting from such
- party’s negligence to the extent applicable law prohibits such limitation.
- Some jurisdictions do not allow the exclusion or limitation of incidental or
- consequential damages, so this exclusion and limitation may not apply to You.
-
-8. Litigation
-
- Any litigation relating to this License may be brought only in the courts of
- a jurisdiction where the defendant maintains its principal place of business
- and such litigation shall be governed by laws of that jurisdiction, without
- reference to its conflict-of-law provisions. Nothing in this Section shall
- prevent a party’s ability to bring cross-claims or counter-claims.
-
-9. Miscellaneous
-
- This License represents the complete agreement concerning the subject matter
- hereof. If any provision of this License is held to be unenforceable, such
- provision shall be reformed only to the extent necessary to make it
- enforceable. Any law or regulation which provides that the language of a
- contract shall be construed against the drafter shall not be used to construe
- this License against a Contributor.
-
-
-10. Versions of the License
-
-10.1. New Versions
-
- Mozilla Foundation is the license steward. Except as provided in Section
- 10.3, no one other than the license steward has the right to modify or
- publish new versions of this License. Each version will be given a
- distinguishing version number.
-
-10.2. Effect of New Versions
-
- You may distribute the Covered Software under the terms of the version of
- the License under which You originally received the Covered Software, or
- under the terms of any subsequent version published by the license
- steward.
-
-10.3. Modified Versions
-
- If you create software not governed by this License, and you want to
- create a new license for such software, you may create and use a modified
- version of this License if you rename the license and remove any
- references to the name of the license steward (except to note that such
- modified license differs from this License).
-
-10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
- If You choose to distribute Source Code Form that is Incompatible With
- Secondary Licenses under the terms of this version of the License, the
- notice described in Exhibit B of this License must be attached.
-
-Exhibit A - Source Code Form License Notice
-
- This Source Code Form is subject to the
- terms of the Mozilla Public License, v.
- 2.0. If a copy of the MPL was not
- distributed with this file, You can
- obtain one at
- http://mozilla.org/MPL/2.0/.
-
-If it is not possible or desirable to put the notice in a particular file, then
-You may include the notice in a location (such as a LICENSE file in a relevant
-directory) where a recipient would be likely to look for such a notice.
-
-You may add additional accurate notices of copyright ownership.
-
-Exhibit B - “Incompatible With Secondary Licenses” Notice
-
- This Source Code Form is “Incompatible
- With Secondary Licenses”, as defined by
- the Mozilla Public License, v. 2.0.
-
diff --git a/vendor/github.com/hashicorp/hcl/Makefile b/vendor/github.com/hashicorp/hcl/Makefile
deleted file mode 100644
index 9fafd50..0000000
--- a/vendor/github.com/hashicorp/hcl/Makefile
+++ /dev/null
@@ -1,18 +0,0 @@
-TEST?=./...
-
-default: test
-
-fmt: generate
- go fmt ./...
-
-test: generate
- go get -t ./...
- go test $(TEST) $(TESTARGS)
-
-generate:
- go generate ./...
-
-updatedeps:
- go get -u golang.org/x/tools/cmd/stringer
-
-.PHONY: default generate test updatedeps
diff --git a/vendor/github.com/hashicorp/hcl/README.md b/vendor/github.com/hashicorp/hcl/README.md
deleted file mode 100644
index c822332..0000000
--- a/vendor/github.com/hashicorp/hcl/README.md
+++ /dev/null
@@ -1,125 +0,0 @@
-# HCL
-
-[](https://godoc.org/github.com/hashicorp/hcl) [](https://travis-ci.org/hashicorp/hcl)
-
-HCL (HashiCorp Configuration Language) is a configuration language built
-by HashiCorp. The goal of HCL is to build a structured configuration language
-that is both human and machine friendly for use with command-line tools, but
-specifically targeted towards DevOps tools, servers, etc.
-
-HCL is also fully JSON compatible. That is, JSON can be used as completely
-valid input to a system expecting HCL. This helps makes systems
-interoperable with other systems.
-
-HCL is heavily inspired by
-[libucl](https://github.com/vstakhov/libucl),
-nginx configuration, and others similar.
-
-## Why?
-
-A common question when viewing HCL is to ask the question: why not
-JSON, YAML, etc.?
-
-Prior to HCL, the tools we built at [HashiCorp](http://www.hashicorp.com)
-used a variety of configuration languages from full programming languages
-such as Ruby to complete data structure languages such as JSON. What we
-learned is that some people wanted human-friendly configuration languages
-and some people wanted machine-friendly languages.
-
-JSON fits a nice balance in this, but is fairly verbose and most
-importantly doesn't support comments. With YAML, we found that beginners
-had a really hard time determining what the actual structure was, and
-ended up guessing more often than not whether to use a hyphen, colon, etc.
-in order to represent some configuration key.
-
-Full programming languages such as Ruby enable complex behavior
-a configuration language shouldn't usually allow, and also forces
-people to learn some set of Ruby.
-
-Because of this, we decided to create our own configuration language
-that is JSON-compatible. Our configuration language (HCL) is designed
-to be written and modified by humans. The API for HCL allows JSON
-as an input so that it is also machine-friendly (machines can generate
-JSON instead of trying to generate HCL).
-
-Our goal with HCL is not to alienate other configuration languages.
-It is instead to provide HCL as a specialized language for our tools,
-and JSON as the interoperability layer.
-
-## Syntax
-
-For a complete grammar, please see the parser itself. A high-level overview
-of the syntax and grammar is listed here.
-
- * Single line comments start with `#` or `//`
-
- * Multi-line comments are wrapped in `/*` and `*/`. Nested block comments
- are not allowed. A multi-line comment (also known as a block comment)
- terminates at the first `*/` found.
-
- * Values are assigned with the syntax `key = value` (whitespace doesn't
- matter). The value can be any primitive: a string, number, boolean,
- object, or list.
-
- * Strings are double-quoted and can contain any UTF-8 characters.
- Example: `"Hello, World"`
-
- * Multi-line strings start with `<-
- echo %Path%
-
- go version
-
- go env
-
- go get -t ./...
-
-build_script:
-- cmd: go test -v ./...
diff --git a/vendor/github.com/hashicorp/hcl/decoder.go b/vendor/github.com/hashicorp/hcl/decoder.go
deleted file mode 100644
index bed9ebb..0000000
--- a/vendor/github.com/hashicorp/hcl/decoder.go
+++ /dev/null
@@ -1,729 +0,0 @@
-package hcl
-
-import (
- "errors"
- "fmt"
- "reflect"
- "sort"
- "strconv"
- "strings"
-
- "github.com/hashicorp/hcl/hcl/ast"
- "github.com/hashicorp/hcl/hcl/parser"
- "github.com/hashicorp/hcl/hcl/token"
-)
-
-// This is the tag to use with structures to have settings for HCL
-const tagName = "hcl"
-
-var (
- // nodeType holds a reference to the type of ast.Node
- nodeType reflect.Type = findNodeType()
-)
-
-// Unmarshal accepts a byte slice as input and writes the
-// data to the value pointed to by v.
-func Unmarshal(bs []byte, v interface{}) error {
- root, err := parse(bs)
- if err != nil {
- return err
- }
-
- return DecodeObject(v, root)
-}
-
-// Decode reads the given input and decodes it into the structure
-// given by `out`.
-func Decode(out interface{}, in string) error {
- obj, err := Parse(in)
- if err != nil {
- return err
- }
-
- return DecodeObject(out, obj)
-}
-
-// DecodeObject is a lower-level version of Decode. It decodes a
-// raw Object into the given output.
-func DecodeObject(out interface{}, n ast.Node) error {
- val := reflect.ValueOf(out)
- if val.Kind() != reflect.Ptr {
- return errors.New("result must be a pointer")
- }
-
- // If we have the file, we really decode the root node
- if f, ok := n.(*ast.File); ok {
- n = f.Node
- }
-
- var d decoder
- return d.decode("root", n, val.Elem())
-}
-
-type decoder struct {
- stack []reflect.Kind
-}
-
-func (d *decoder) decode(name string, node ast.Node, result reflect.Value) error {
- k := result
-
- // If we have an interface with a valid value, we use that
- // for the check.
- if result.Kind() == reflect.Interface {
- elem := result.Elem()
- if elem.IsValid() {
- k = elem
- }
- }
-
- // Push current onto stack unless it is an interface.
- if k.Kind() != reflect.Interface {
- d.stack = append(d.stack, k.Kind())
-
- // Schedule a pop
- defer func() {
- d.stack = d.stack[:len(d.stack)-1]
- }()
- }
-
- switch k.Kind() {
- case reflect.Bool:
- return d.decodeBool(name, node, result)
- case reflect.Float32, reflect.Float64:
- return d.decodeFloat(name, node, result)
- case reflect.Int, reflect.Int32, reflect.Int64:
- return d.decodeInt(name, node, result)
- case reflect.Interface:
- // When we see an interface, we make our own thing
- return d.decodeInterface(name, node, result)
- case reflect.Map:
- return d.decodeMap(name, node, result)
- case reflect.Ptr:
- return d.decodePtr(name, node, result)
- case reflect.Slice:
- return d.decodeSlice(name, node, result)
- case reflect.String:
- return d.decodeString(name, node, result)
- case reflect.Struct:
- return d.decodeStruct(name, node, result)
- default:
- return &parser.PosError{
- Pos: node.Pos(),
- Err: fmt.Errorf("%s: unknown kind to decode into: %s", name, k.Kind()),
- }
- }
-}
-
-func (d *decoder) decodeBool(name string, node ast.Node, result reflect.Value) error {
- switch n := node.(type) {
- case *ast.LiteralType:
- if n.Token.Type == token.BOOL {
- v, err := strconv.ParseBool(n.Token.Text)
- if err != nil {
- return err
- }
-
- result.Set(reflect.ValueOf(v))
- return nil
- }
- }
-
- return &parser.PosError{
- Pos: node.Pos(),
- Err: fmt.Errorf("%s: unknown type %T", name, node),
- }
-}
-
-func (d *decoder) decodeFloat(name string, node ast.Node, result reflect.Value) error {
- switch n := node.(type) {
- case *ast.LiteralType:
- if n.Token.Type == token.FLOAT || n.Token.Type == token.NUMBER {
- v, err := strconv.ParseFloat(n.Token.Text, 64)
- if err != nil {
- return err
- }
-
- result.Set(reflect.ValueOf(v).Convert(result.Type()))
- return nil
- }
- }
-
- return &parser.PosError{
- Pos: node.Pos(),
- Err: fmt.Errorf("%s: unknown type %T", name, node),
- }
-}
-
-func (d *decoder) decodeInt(name string, node ast.Node, result reflect.Value) error {
- switch n := node.(type) {
- case *ast.LiteralType:
- switch n.Token.Type {
- case token.NUMBER:
- v, err := strconv.ParseInt(n.Token.Text, 0, 0)
- if err != nil {
- return err
- }
-
- if result.Kind() == reflect.Interface {
- result.Set(reflect.ValueOf(int(v)))
- } else {
- result.SetInt(v)
- }
- return nil
- case token.STRING:
- v, err := strconv.ParseInt(n.Token.Value().(string), 0, 0)
- if err != nil {
- return err
- }
-
- if result.Kind() == reflect.Interface {
- result.Set(reflect.ValueOf(int(v)))
- } else {
- result.SetInt(v)
- }
- return nil
- }
- }
-
- return &parser.PosError{
- Pos: node.Pos(),
- Err: fmt.Errorf("%s: unknown type %T", name, node),
- }
-}
-
-func (d *decoder) decodeInterface(name string, node ast.Node, result reflect.Value) error {
- // When we see an ast.Node, we retain the value to enable deferred decoding.
- // Very useful in situations where we want to preserve ast.Node information
- // like Pos
- if result.Type() == nodeType && result.CanSet() {
- result.Set(reflect.ValueOf(node))
- return nil
- }
-
- var set reflect.Value
- redecode := true
-
- // For testing types, ObjectType should just be treated as a list. We
- // set this to a temporary var because we want to pass in the real node.
- testNode := node
- if ot, ok := node.(*ast.ObjectType); ok {
- testNode = ot.List
- }
-
- switch n := testNode.(type) {
- case *ast.ObjectList:
- // If we're at the root or we're directly within a slice, then we
- // decode objects into map[string]interface{}, otherwise we decode
- // them into lists.
- if len(d.stack) == 0 || d.stack[len(d.stack)-1] == reflect.Slice {
- var temp map[string]interface{}
- tempVal := reflect.ValueOf(temp)
- result := reflect.MakeMap(
- reflect.MapOf(
- reflect.TypeOf(""),
- tempVal.Type().Elem()))
-
- set = result
- } else {
- var temp []map[string]interface{}
- tempVal := reflect.ValueOf(temp)
- result := reflect.MakeSlice(
- reflect.SliceOf(tempVal.Type().Elem()), 0, len(n.Items))
- set = result
- }
- case *ast.ObjectType:
- // If we're at the root or we're directly within a slice, then we
- // decode objects into map[string]interface{}, otherwise we decode
- // them into lists.
- if len(d.stack) == 0 || d.stack[len(d.stack)-1] == reflect.Slice {
- var temp map[string]interface{}
- tempVal := reflect.ValueOf(temp)
- result := reflect.MakeMap(
- reflect.MapOf(
- reflect.TypeOf(""),
- tempVal.Type().Elem()))
-
- set = result
- } else {
- var temp []map[string]interface{}
- tempVal := reflect.ValueOf(temp)
- result := reflect.MakeSlice(
- reflect.SliceOf(tempVal.Type().Elem()), 0, 1)
- set = result
- }
- case *ast.ListType:
- var temp []interface{}
- tempVal := reflect.ValueOf(temp)
- result := reflect.MakeSlice(
- reflect.SliceOf(tempVal.Type().Elem()), 0, 0)
- set = result
- case *ast.LiteralType:
- switch n.Token.Type {
- case token.BOOL:
- var result bool
- set = reflect.Indirect(reflect.New(reflect.TypeOf(result)))
- case token.FLOAT:
- var result float64
- set = reflect.Indirect(reflect.New(reflect.TypeOf(result)))
- case token.NUMBER:
- var result int
- set = reflect.Indirect(reflect.New(reflect.TypeOf(result)))
- case token.STRING, token.HEREDOC:
- set = reflect.Indirect(reflect.New(reflect.TypeOf("")))
- default:
- return &parser.PosError{
- Pos: node.Pos(),
- Err: fmt.Errorf("%s: cannot decode into interface: %T", name, node),
- }
- }
- default:
- return fmt.Errorf(
- "%s: cannot decode into interface: %T",
- name, node)
- }
-
- // Set the result to what its supposed to be, then reset
- // result so we don't reflect into this method anymore.
- result.Set(set)
-
- if redecode {
- // Revisit the node so that we can use the newly instantiated
- // thing and populate it.
- if err := d.decode(name, node, result); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func (d *decoder) decodeMap(name string, node ast.Node, result reflect.Value) error {
- if item, ok := node.(*ast.ObjectItem); ok {
- node = &ast.ObjectList{Items: []*ast.ObjectItem{item}}
- }
-
- if ot, ok := node.(*ast.ObjectType); ok {
- node = ot.List
- }
-
- n, ok := node.(*ast.ObjectList)
- if !ok {
- return &parser.PosError{
- Pos: node.Pos(),
- Err: fmt.Errorf("%s: not an object type for map (%T)", name, node),
- }
- }
-
- // If we have an interface, then we can address the interface,
- // but not the slice itself, so get the element but set the interface
- set := result
- if result.Kind() == reflect.Interface {
- result = result.Elem()
- }
-
- resultType := result.Type()
- resultElemType := resultType.Elem()
- resultKeyType := resultType.Key()
- if resultKeyType.Kind() != reflect.String {
- return &parser.PosError{
- Pos: node.Pos(),
- Err: fmt.Errorf("%s: map must have string keys", name),
- }
- }
-
- // Make a map if it is nil
- resultMap := result
- if result.IsNil() {
- resultMap = reflect.MakeMap(
- reflect.MapOf(resultKeyType, resultElemType))
- }
-
- // Go through each element and decode it.
- done := make(map[string]struct{})
- for _, item := range n.Items {
- if item.Val == nil {
- continue
- }
-
- // github.com/hashicorp/terraform/issue/5740
- if len(item.Keys) == 0 {
- return &parser.PosError{
- Pos: node.Pos(),
- Err: fmt.Errorf("%s: map must have string keys", name),
- }
- }
-
- // Get the key we're dealing with, which is the first item
- keyStr := item.Keys[0].Token.Value().(string)
-
- // If we've already processed this key, then ignore it
- if _, ok := done[keyStr]; ok {
- continue
- }
-
- // Determine the value. If we have more than one key, then we
- // get the objectlist of only these keys.
- itemVal := item.Val
- if len(item.Keys) > 1 {
- itemVal = n.Filter(keyStr)
- done[keyStr] = struct{}{}
- }
-
- // Make the field name
- fieldName := fmt.Sprintf("%s.%s", name, keyStr)
-
- // Get the key/value as reflection values
- key := reflect.ValueOf(keyStr)
- val := reflect.Indirect(reflect.New(resultElemType))
-
- // If we have a pre-existing value in the map, use that
- oldVal := resultMap.MapIndex(key)
- if oldVal.IsValid() {
- val.Set(oldVal)
- }
-
- // Decode!
- if err := d.decode(fieldName, itemVal, val); err != nil {
- return err
- }
-
- // Set the value on the map
- resultMap.SetMapIndex(key, val)
- }
-
- // Set the final map if we can
- set.Set(resultMap)
- return nil
-}
-
-func (d *decoder) decodePtr(name string, node ast.Node, result reflect.Value) error {
- // Create an element of the concrete (non pointer) type and decode
- // into that. Then set the value of the pointer to this type.
- resultType := result.Type()
- resultElemType := resultType.Elem()
- val := reflect.New(resultElemType)
- if err := d.decode(name, node, reflect.Indirect(val)); err != nil {
- return err
- }
-
- result.Set(val)
- return nil
-}
-
-func (d *decoder) decodeSlice(name string, node ast.Node, result reflect.Value) error {
- // If we have an interface, then we can address the interface,
- // but not the slice itself, so get the element but set the interface
- set := result
- if result.Kind() == reflect.Interface {
- result = result.Elem()
- }
- // Create the slice if it isn't nil
- resultType := result.Type()
- resultElemType := resultType.Elem()
- if result.IsNil() {
- resultSliceType := reflect.SliceOf(resultElemType)
- result = reflect.MakeSlice(
- resultSliceType, 0, 0)
- }
-
- // Figure out the items we'll be copying into the slice
- var items []ast.Node
- switch n := node.(type) {
- case *ast.ObjectList:
- items = make([]ast.Node, len(n.Items))
- for i, item := range n.Items {
- items[i] = item
- }
- case *ast.ObjectType:
- items = []ast.Node{n}
- case *ast.ListType:
- items = n.List
- default:
- return &parser.PosError{
- Pos: node.Pos(),
- Err: fmt.Errorf("unknown slice type: %T", node),
- }
- }
-
- for i, item := range items {
- fieldName := fmt.Sprintf("%s[%d]", name, i)
-
- // Decode
- val := reflect.Indirect(reflect.New(resultElemType))
-
- // if item is an object that was decoded from ambiguous JSON and
- // flattened, make sure it's expanded if it needs to decode into a
- // defined structure.
- item := expandObject(item, val)
-
- if err := d.decode(fieldName, item, val); err != nil {
- return err
- }
-
- // Append it onto the slice
- result = reflect.Append(result, val)
- }
-
- set.Set(result)
- return nil
-}
-
-// expandObject detects if an ambiguous JSON object was flattened to a List which
-// should be decoded into a struct, and expands the ast to properly deocode.
-func expandObject(node ast.Node, result reflect.Value) ast.Node {
- item, ok := node.(*ast.ObjectItem)
- if !ok {
- return node
- }
-
- elemType := result.Type()
-
- // our target type must be a struct
- switch elemType.Kind() {
- case reflect.Ptr:
- switch elemType.Elem().Kind() {
- case reflect.Struct:
- //OK
- default:
- return node
- }
- case reflect.Struct:
- //OK
- default:
- return node
- }
-
- // A list value will have a key and field name. If it had more fields,
- // it wouldn't have been flattened.
- if len(item.Keys) != 2 {
- return node
- }
-
- keyToken := item.Keys[0].Token
- item.Keys = item.Keys[1:]
-
- // we need to un-flatten the ast enough to decode
- newNode := &ast.ObjectItem{
- Keys: []*ast.ObjectKey{
- &ast.ObjectKey{
- Token: keyToken,
- },
- },
- Val: &ast.ObjectType{
- List: &ast.ObjectList{
- Items: []*ast.ObjectItem{item},
- },
- },
- }
-
- return newNode
-}
-
-func (d *decoder) decodeString(name string, node ast.Node, result reflect.Value) error {
- switch n := node.(type) {
- case *ast.LiteralType:
- switch n.Token.Type {
- case token.NUMBER:
- result.Set(reflect.ValueOf(n.Token.Text).Convert(result.Type()))
- return nil
- case token.STRING, token.HEREDOC:
- result.Set(reflect.ValueOf(n.Token.Value()).Convert(result.Type()))
- return nil
- }
- }
-
- return &parser.PosError{
- Pos: node.Pos(),
- Err: fmt.Errorf("%s: unknown type for string %T", name, node),
- }
-}
-
-func (d *decoder) decodeStruct(name string, node ast.Node, result reflect.Value) error {
- var item *ast.ObjectItem
- if it, ok := node.(*ast.ObjectItem); ok {
- item = it
- node = it.Val
- }
-
- if ot, ok := node.(*ast.ObjectType); ok {
- node = ot.List
- }
-
- // Handle the special case where the object itself is a literal. Previously
- // the yacc parser would always ensure top-level elements were arrays. The new
- // parser does not make the same guarantees, thus we need to convert any
- // top-level literal elements into a list.
- if _, ok := node.(*ast.LiteralType); ok && item != nil {
- node = &ast.ObjectList{Items: []*ast.ObjectItem{item}}
- }
-
- list, ok := node.(*ast.ObjectList)
- if !ok {
- return &parser.PosError{
- Pos: node.Pos(),
- Err: fmt.Errorf("%s: not an object type for struct (%T)", name, node),
- }
- }
-
- // This slice will keep track of all the structs we'll be decoding.
- // There can be more than one struct if there are embedded structs
- // that are squashed.
- structs := make([]reflect.Value, 1, 5)
- structs[0] = result
-
- // Compile the list of all the fields that we're going to be decoding
- // from all the structs.
- type field struct {
- field reflect.StructField
- val reflect.Value
- }
- fields := []field{}
- for len(structs) > 0 {
- structVal := structs[0]
- structs = structs[1:]
-
- structType := structVal.Type()
- for i := 0; i < structType.NumField(); i++ {
- fieldType := structType.Field(i)
- tagParts := strings.Split(fieldType.Tag.Get(tagName), ",")
-
- // Ignore fields with tag name "-"
- if tagParts[0] == "-" {
- continue
- }
-
- if fieldType.Anonymous {
- fieldKind := fieldType.Type.Kind()
- if fieldKind != reflect.Struct {
- return &parser.PosError{
- Pos: node.Pos(),
- Err: fmt.Errorf("%s: unsupported type to struct: %s",
- fieldType.Name, fieldKind),
- }
- }
-
- // We have an embedded field. We "squash" the fields down
- // if specified in the tag.
- squash := false
- for _, tag := range tagParts[1:] {
- if tag == "squash" {
- squash = true
- break
- }
- }
-
- if squash {
- structs = append(
- structs, result.FieldByName(fieldType.Name))
- continue
- }
- }
-
- // Normal struct field, store it away
- fields = append(fields, field{fieldType, structVal.Field(i)})
- }
- }
-
- usedKeys := make(map[string]struct{})
- decodedFields := make([]string, 0, len(fields))
- decodedFieldsVal := make([]reflect.Value, 0)
- unusedKeysVal := make([]reflect.Value, 0)
- for _, f := range fields {
- field, fieldValue := f.field, f.val
- if !fieldValue.IsValid() {
- // This should never happen
- panic("field is not valid")
- }
-
- // If we can't set the field, then it is unexported or something,
- // and we just continue onwards.
- if !fieldValue.CanSet() {
- continue
- }
-
- fieldName := field.Name
-
- tagValue := field.Tag.Get(tagName)
- tagParts := strings.SplitN(tagValue, ",", 2)
- if len(tagParts) >= 2 {
- switch tagParts[1] {
- case "decodedFields":
- decodedFieldsVal = append(decodedFieldsVal, fieldValue)
- continue
- case "key":
- if item == nil {
- return &parser.PosError{
- Pos: node.Pos(),
- Err: fmt.Errorf("%s: %s asked for 'key', impossible",
- name, fieldName),
- }
- }
-
- fieldValue.SetString(item.Keys[0].Token.Value().(string))
- continue
- case "unusedKeys":
- unusedKeysVal = append(unusedKeysVal, fieldValue)
- continue
- }
- }
-
- if tagParts[0] != "" {
- fieldName = tagParts[0]
- }
-
- // Determine the element we'll use to decode. If it is a single
- // match (only object with the field), then we decode it exactly.
- // If it is a prefix match, then we decode the matches.
- filter := list.Filter(fieldName)
-
- prefixMatches := filter.Children()
- matches := filter.Elem()
- if len(matches.Items) == 0 && len(prefixMatches.Items) == 0 {
- continue
- }
-
- // Track the used key
- usedKeys[fieldName] = struct{}{}
-
- // Create the field name and decode. We range over the elements
- // because we actually want the value.
- fieldName = fmt.Sprintf("%s.%s", name, fieldName)
- if len(prefixMatches.Items) > 0 {
- if err := d.decode(fieldName, prefixMatches, fieldValue); err != nil {
- return err
- }
- }
- for _, match := range matches.Items {
- var decodeNode ast.Node = match.Val
- if ot, ok := decodeNode.(*ast.ObjectType); ok {
- decodeNode = &ast.ObjectList{Items: ot.List.Items}
- }
-
- if err := d.decode(fieldName, decodeNode, fieldValue); err != nil {
- return err
- }
- }
-
- decodedFields = append(decodedFields, field.Name)
- }
-
- if len(decodedFieldsVal) > 0 {
- // Sort it so that it is deterministic
- sort.Strings(decodedFields)
-
- for _, v := range decodedFieldsVal {
- v.Set(reflect.ValueOf(decodedFields))
- }
- }
-
- return nil
-}
-
-// findNodeType returns the type of ast.Node
-func findNodeType() reflect.Type {
- var nodeContainer struct {
- Node ast.Node
- }
- value := reflect.ValueOf(nodeContainer).FieldByName("Node")
- return value.Type()
-}
diff --git a/vendor/github.com/hashicorp/hcl/decoder_test.go b/vendor/github.com/hashicorp/hcl/decoder_test.go
deleted file mode 100644
index 8682f47..0000000
--- a/vendor/github.com/hashicorp/hcl/decoder_test.go
+++ /dev/null
@@ -1,1203 +0,0 @@
-package hcl
-
-import (
- "io/ioutil"
- "path/filepath"
- "reflect"
- "testing"
- "time"
-
- "github.com/davecgh/go-spew/spew"
- "github.com/hashicorp/hcl/hcl/ast"
-)
-
-func TestDecode_interface(t *testing.T) {
- cases := []struct {
- File string
- Err bool
- Out interface{}
- }{
- {
- "basic.hcl",
- false,
- map[string]interface{}{
- "foo": "bar",
- "bar": "${file(\"bing/bong.txt\")}",
- },
- },
- {
- "basic_squish.hcl",
- false,
- map[string]interface{}{
- "foo": "bar",
- "bar": "${file(\"bing/bong.txt\")}",
- "foo-bar": "baz",
- },
- },
- {
- "empty.hcl",
- false,
- map[string]interface{}{
- "resource": []map[string]interface{}{
- map[string]interface{}{
- "foo": []map[string]interface{}{
- map[string]interface{}{},
- },
- },
- },
- },
- },
- {
- "tfvars.hcl",
- false,
- map[string]interface{}{
- "regularvar": "Should work",
- "map.key1": "Value",
- "map.key2": "Other value",
- },
- },
- {
- "escape.hcl",
- false,
- map[string]interface{}{
- "foo": "bar\"baz\\n",
- "qux": "back\\slash",
- "bar": "new\nline",
- "qax": `slash\:colon`,
- "nested": `${HH\\:mm\\:ss}`,
- "nestedquotes": `${"\"stringwrappedinquotes\""}`,
- },
- },
- {
- "float.hcl",
- false,
- map[string]interface{}{
- "a": 1.02,
- "b": 2,
- },
- },
- {
- "multiline_bad.hcl",
- true,
- nil,
- },
- {
- "multiline_literal.hcl",
- true,
- nil,
- },
- {
- "multiline_literal_with_hil.hcl",
- false,
- map[string]interface{}{"multiline_literal_with_hil": "${hello\n world}"},
- },
- {
- "multiline_no_marker.hcl",
- true,
- nil,
- },
- {
- "multiline.hcl",
- false,
- map[string]interface{}{"foo": "bar\nbaz\n"},
- },
- {
- "multiline_indented.hcl",
- false,
- map[string]interface{}{"foo": " bar\n baz\n"},
- },
- {
- "multiline_no_hanging_indent.hcl",
- false,
- map[string]interface{}{"foo": " baz\n bar\n foo\n"},
- },
- {
- "multiline_no_eof.hcl",
- false,
- map[string]interface{}{"foo": "bar\nbaz\n", "key": "value"},
- },
- {
- "multiline.json",
- false,
- map[string]interface{}{"foo": "bar\nbaz"},
- },
- {
- "null_strings.json",
- false,
- map[string]interface{}{
- "module": []map[string]interface{}{
- map[string]interface{}{
- "app": []map[string]interface{}{
- map[string]interface{}{"foo": ""},
- },
- },
- },
- },
- },
- {
- "scientific.json",
- false,
- map[string]interface{}{
- "a": 1e-10,
- "b": 1e+10,
- "c": 1e10,
- "d": 1.2e-10,
- "e": 1.2e+10,
- "f": 1.2e10,
- },
- },
- {
- "scientific.hcl",
- false,
- map[string]interface{}{
- "a": 1e-10,
- "b": 1e+10,
- "c": 1e10,
- "d": 1.2e-10,
- "e": 1.2e+10,
- "f": 1.2e10,
- },
- },
- {
- "terraform_heroku.hcl",
- false,
- map[string]interface{}{
- "name": "terraform-test-app",
- "config_vars": []map[string]interface{}{
- map[string]interface{}{
- "FOO": "bar",
- },
- },
- },
- },
- {
- "structure_multi.hcl",
- false,
- map[string]interface{}{
- "foo": []map[string]interface{}{
- map[string]interface{}{
- "baz": []map[string]interface{}{
- map[string]interface{}{"key": 7},
- },
- },
- map[string]interface{}{
- "bar": []map[string]interface{}{
- map[string]interface{}{"key": 12},
- },
- },
- },
- },
- },
- {
- "structure_multi.json",
- false,
- map[string]interface{}{
- "foo": []map[string]interface{}{
- map[string]interface{}{
- "baz": []map[string]interface{}{
- map[string]interface{}{"key": 7},
- },
- },
- map[string]interface{}{
- "bar": []map[string]interface{}{
- map[string]interface{}{"key": 12},
- },
- },
- },
- },
- },
- {
- "list_of_lists.hcl",
- false,
- map[string]interface{}{
- "foo": []interface{}{
- []interface{}{"foo"},
- []interface{}{"bar"},
- },
- },
- },
- {
- "list_of_maps.hcl",
- false,
- map[string]interface{}{
- "foo": []interface{}{
- map[string]interface{}{"somekey1": "someval1"},
- map[string]interface{}{"somekey2": "someval2", "someextrakey": "someextraval"},
- },
- },
- },
- {
- "assign_deep.hcl",
- false,
- map[string]interface{}{
- "resource": []interface{}{
- map[string]interface{}{
- "foo": []interface{}{
- map[string]interface{}{
- "bar": []map[string]interface{}{
- map[string]interface{}{}}}}}}},
- },
- {
- "structure_list.hcl",
- false,
- map[string]interface{}{
- "foo": []map[string]interface{}{
- map[string]interface{}{
- "key": 7,
- },
- map[string]interface{}{
- "key": 12,
- },
- },
- },
- },
- {
- "structure_list.json",
- false,
- map[string]interface{}{
- "foo": []map[string]interface{}{
- map[string]interface{}{
- "key": 7,
- },
- map[string]interface{}{
- "key": 12,
- },
- },
- },
- },
- {
- "structure_list_deep.json",
- false,
- map[string]interface{}{
- "bar": []map[string]interface{}{
- map[string]interface{}{
- "foo": []map[string]interface{}{
- map[string]interface{}{
- "name": "terraform_example",
- "ingress": []map[string]interface{}{
- map[string]interface{}{
- "from_port": 22,
- },
- map[string]interface{}{
- "from_port": 80,
- },
- },
- },
- },
- },
- },
- },
- },
-
- {
- "structure_list_empty.json",
- false,
- map[string]interface{}{
- "foo": []interface{}{},
- },
- },
-
- {
- "nested_block_comment.hcl",
- false,
- map[string]interface{}{
- "bar": "value",
- },
- },
-
- {
- "unterminated_block_comment.hcl",
- true,
- nil,
- },
-
- {
- "unterminated_brace.hcl",
- true,
- nil,
- },
-
- {
- "nested_provider_bad.hcl",
- true,
- nil,
- },
-
- {
- "object_list.json",
- false,
- map[string]interface{}{
- "resource": []map[string]interface{}{
- map[string]interface{}{
- "aws_instance": []map[string]interface{}{
- map[string]interface{}{
- "db": []map[string]interface{}{
- map[string]interface{}{
- "vpc": "foo",
- "provisioner": []map[string]interface{}{
- map[string]interface{}{
- "file": []map[string]interface{}{
- map[string]interface{}{
- "source": "foo",
- "destination": "bar",
- },
- },
- },
- },
- },
- },
- },
- },
- },
- },
- },
- },
-
- // Terraform GH-8295 sanity test that basic decoding into
- // interface{} works.
- {
- "terraform_variable_invalid.json",
- false,
- map[string]interface{}{
- "variable": []map[string]interface{}{
- map[string]interface{}{
- "whatever": "abc123",
- },
- },
- },
- },
-
- {
- "interpolate.json",
- false,
- map[string]interface{}{
- "default": `${replace("europe-west", "-", " ")}`,
- },
- },
-
- {
- "block_assign.hcl",
- true,
- nil,
- },
-
- {
- "escape_backslash.hcl",
- false,
- map[string]interface{}{
- "output": []map[string]interface{}{
- map[string]interface{}{
- "one": `${replace(var.sub_domain, ".", "\\.")}`,
- "two": `${replace(var.sub_domain, ".", "\\\\.")}`,
- "many": `${replace(var.sub_domain, ".", "\\\\\\\\.")}`,
- },
- },
- },
- },
-
- {
- "git_crypt.hcl",
- true,
- nil,
- },
-
- {
- "object_with_bool.hcl",
- false,
- map[string]interface{}{
- "path": []map[string]interface{}{
- map[string]interface{}{
- "policy": "write",
- "permissions": []map[string]interface{}{
- map[string]interface{}{
- "bool": []interface{}{false},
- },
- },
- },
- },
- },
- },
- }
-
- for _, tc := range cases {
- t.Run(tc.File, func(t *testing.T) {
- d, err := ioutil.ReadFile(filepath.Join(fixtureDir, tc.File))
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- var out interface{}
- err = Decode(&out, string(d))
- if (err != nil) != tc.Err {
- t.Fatalf("Input: %s\n\nError: %s", tc.File, err)
- }
-
- if !reflect.DeepEqual(out, tc.Out) {
- t.Fatalf("Input: %s. Actual, Expected.\n\n%#v\n\n%#v", tc.File, out, tc.Out)
- }
-
- var v interface{}
- err = Unmarshal(d, &v)
- if (err != nil) != tc.Err {
- t.Fatalf("Input: %s\n\nError: %s", tc.File, err)
- }
-
- if !reflect.DeepEqual(v, tc.Out) {
- t.Fatalf("Input: %s. Actual, Expected.\n\n%#v\n\n%#v", tc.File, out, tc.Out)
- }
- })
- }
-}
-
-func TestDecode_interfaceInline(t *testing.T) {
- cases := []struct {
- Value string
- Err bool
- Out interface{}
- }{
- {"t t e{{}}", true, nil},
- {"t=0t d {}", true, map[string]interface{}{"t": 0}},
- {"v=0E0v d{}", true, map[string]interface{}{"v": float64(0)}},
- }
-
- for _, tc := range cases {
- t.Logf("Testing: %q", tc.Value)
-
- var out interface{}
- err := Decode(&out, tc.Value)
- if (err != nil) != tc.Err {
- t.Fatalf("Input: %q\n\nError: %s", tc.Value, err)
- }
-
- if !reflect.DeepEqual(out, tc.Out) {
- t.Fatalf("Input: %q. Actual, Expected.\n\n%#v\n\n%#v", tc.Value, out, tc.Out)
- }
-
- var v interface{}
- err = Unmarshal([]byte(tc.Value), &v)
- if (err != nil) != tc.Err {
- t.Fatalf("Input: %q\n\nError: %s", tc.Value, err)
- }
-
- if !reflect.DeepEqual(v, tc.Out) {
- t.Fatalf("Input: %q. Actual, Expected.\n\n%#v\n\n%#v", tc.Value, out, tc.Out)
- }
- }
-}
-
-func TestDecode_equal(t *testing.T) {
- cases := []struct {
- One, Two string
- }{
- {
- "basic.hcl",
- "basic.json",
- },
- {
- "float.hcl",
- "float.json",
- },
- /*
- {
- "structure.hcl",
- "structure.json",
- },
- */
- {
- "structure.hcl",
- "structure_flat.json",
- },
- {
- "terraform_heroku.hcl",
- "terraform_heroku.json",
- },
- }
-
- for _, tc := range cases {
- p1 := filepath.Join(fixtureDir, tc.One)
- p2 := filepath.Join(fixtureDir, tc.Two)
-
- d1, err := ioutil.ReadFile(p1)
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- d2, err := ioutil.ReadFile(p2)
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- var i1, i2 interface{}
- err = Decode(&i1, string(d1))
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- err = Decode(&i2, string(d2))
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- if !reflect.DeepEqual(i1, i2) {
- t.Fatalf(
- "%s != %s\n\n%#v\n\n%#v",
- tc.One, tc.Two,
- i1, i2)
- }
- }
-}
-
-func TestDecode_flatMap(t *testing.T) {
- var val map[string]map[string]string
-
- err := Decode(&val, testReadFile(t, "structure_flatmap.hcl"))
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- expected := map[string]map[string]string{
- "foo": map[string]string{
- "foo": "bar",
- "key": "7",
- },
- }
-
- if !reflect.DeepEqual(val, expected) {
- t.Fatalf("Actual: %#v\n\nExpected: %#v", val, expected)
- }
-}
-
-func TestDecode_structure(t *testing.T) {
- type Embedded interface{}
-
- type V struct {
- Embedded `hcl:"-"`
- Key int
- Foo string
- }
-
- var actual V
-
- err := Decode(&actual, testReadFile(t, "flat.hcl"))
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- expected := V{
- Key: 7,
- Foo: "bar",
- }
-
- if !reflect.DeepEqual(actual, expected) {
- t.Fatalf("Actual: %#v\n\nExpected: %#v", actual, expected)
- }
-}
-
-func TestDecode_structurePtr(t *testing.T) {
- type V struct {
- Key int
- Foo string
- }
-
- var actual *V
-
- err := Decode(&actual, testReadFile(t, "flat.hcl"))
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- expected := &V{
- Key: 7,
- Foo: "bar",
- }
-
- if !reflect.DeepEqual(actual, expected) {
- t.Fatalf("Actual: %#v\n\nExpected: %#v", actual, expected)
- }
-}
-
-func TestDecode_structureArray(t *testing.T) {
- // This test is extracted from a failure in Consul (consul.io),
- // hence the interesting structure naming.
-
- type KeyPolicyType string
-
- type KeyPolicy struct {
- Prefix string `hcl:",key"`
- Policy KeyPolicyType
- }
-
- type Policy struct {
- Keys []KeyPolicy `hcl:"key,expand"`
- }
-
- expected := Policy{
- Keys: []KeyPolicy{
- KeyPolicy{
- Prefix: "",
- Policy: "read",
- },
- KeyPolicy{
- Prefix: "foo/",
- Policy: "write",
- },
- KeyPolicy{
- Prefix: "foo/bar/",
- Policy: "read",
- },
- KeyPolicy{
- Prefix: "foo/bar/baz",
- Policy: "deny",
- },
- },
- }
-
- files := []string{
- "decode_policy.hcl",
- "decode_policy.json",
- }
-
- for _, f := range files {
- var actual Policy
-
- err := Decode(&actual, testReadFile(t, f))
- if err != nil {
- t.Fatalf("Input: %s\n\nerr: %s", f, err)
- }
-
- if !reflect.DeepEqual(actual, expected) {
- t.Fatalf("Input: %s\n\nActual: %#v\n\nExpected: %#v", f, actual, expected)
- }
- }
-}
-
-func TestDecode_sliceExpand(t *testing.T) {
- type testInner struct {
- Name string `hcl:",key"`
- Key string
- }
-
- type testStruct struct {
- Services []testInner `hcl:"service,expand"`
- }
-
- expected := testStruct{
- Services: []testInner{
- testInner{
- Name: "my-service-0",
- Key: "value",
- },
- testInner{
- Name: "my-service-1",
- Key: "value",
- },
- },
- }
-
- files := []string{
- "slice_expand.hcl",
- }
-
- for _, f := range files {
- t.Logf("Testing: %s", f)
-
- var actual testStruct
- err := Decode(&actual, testReadFile(t, f))
- if err != nil {
- t.Fatalf("Input: %s\n\nerr: %s", f, err)
- }
-
- if !reflect.DeepEqual(actual, expected) {
- t.Fatalf("Input: %s\n\nActual: %#v\n\nExpected: %#v", f, actual, expected)
- }
- }
-}
-
-func TestDecode_structureMap(t *testing.T) {
- // This test is extracted from a failure in Terraform (terraform.io),
- // hence the interesting structure naming.
-
- type hclVariable struct {
- Default interface{}
- Description string
- Fields []string `hcl:",decodedFields"`
- }
-
- type rawConfig struct {
- Variable map[string]hclVariable
- }
-
- expected := rawConfig{
- Variable: map[string]hclVariable{
- "foo": hclVariable{
- Default: "bar",
- Description: "bar",
- Fields: []string{"Default", "Description"},
- },
-
- "amis": hclVariable{
- Default: []map[string]interface{}{
- map[string]interface{}{
- "east": "foo",
- },
- },
- Fields: []string{"Default"},
- },
- },
- }
-
- files := []string{
- "decode_tf_variable.hcl",
- "decode_tf_variable.json",
- }
-
- for _, f := range files {
- t.Logf("Testing: %s", f)
-
- var actual rawConfig
- err := Decode(&actual, testReadFile(t, f))
- if err != nil {
- t.Fatalf("Input: %s\n\nerr: %s", f, err)
- }
-
- if !reflect.DeepEqual(actual, expected) {
- t.Fatalf("Input: %s\n\nActual: %#v\n\nExpected: %#v", f, actual, expected)
- }
- }
-}
-
-func TestDecode_structureMapInvalid(t *testing.T) {
- // Terraform GH-8295
-
- type hclVariable struct {
- Default interface{}
- Description string
- Fields []string `hcl:",decodedFields"`
- }
-
- type rawConfig struct {
- Variable map[string]*hclVariable
- }
-
- var actual rawConfig
- err := Decode(&actual, testReadFile(t, "terraform_variable_invalid.json"))
- if err == nil {
- t.Fatal("expected error")
- }
-}
-
-func TestDecode_interfaceNonPointer(t *testing.T) {
- var value interface{}
- err := Decode(value, testReadFile(t, "basic_int_string.hcl"))
- if err == nil {
- t.Fatal("should error")
- }
-}
-
-func TestDecode_intString(t *testing.T) {
- var value struct {
- Count int
- }
-
- err := Decode(&value, testReadFile(t, "basic_int_string.hcl"))
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- if value.Count != 3 {
- t.Fatalf("bad: %#v", value.Count)
- }
-}
-
-func TestDecode_float32(t *testing.T) {
- var value struct {
- A float32 `hcl:"a"`
- B float32 `hcl:"b"`
- }
-
- err := Decode(&value, testReadFile(t, "float.hcl"))
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- if got, want := value.A, float32(1.02); got != want {
- t.Fatalf("wrong result %#v; want %#v", got, want)
- }
- if got, want := value.B, float32(2); got != want {
- t.Fatalf("wrong result %#v; want %#v", got, want)
- }
-}
-
-func TestDecode_float64(t *testing.T) {
- var value struct {
- A float64 `hcl:"a"`
- B float64 `hcl:"b"`
- }
-
- err := Decode(&value, testReadFile(t, "float.hcl"))
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- if got, want := value.A, float64(1.02); got != want {
- t.Fatalf("wrong result %#v; want %#v", got, want)
- }
- if got, want := value.B, float64(2); got != want {
- t.Fatalf("wrong result %#v; want %#v", got, want)
- }
-}
-
-func TestDecode_intStringAliased(t *testing.T) {
- var value struct {
- Count time.Duration
- }
-
- err := Decode(&value, testReadFile(t, "basic_int_string.hcl"))
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- if value.Count != time.Duration(3) {
- t.Fatalf("bad: %#v", value.Count)
- }
-}
-
-func TestDecode_Node(t *testing.T) {
- // given
- var value struct {
- Content ast.Node
- Nested struct {
- Content ast.Node
- }
- }
-
- content := `
-content {
- hello = "world"
-}
-`
-
- // when
- err := Decode(&value, content)
-
- // then
- if err != nil {
- t.Errorf("unable to decode content, %v", err)
- return
- }
-
- // verify ast.Node can be decoded later
- var v map[string]interface{}
- err = DecodeObject(&v, value.Content)
- if err != nil {
- t.Errorf("unable to decode content, %v", err)
- return
- }
-
- if v["hello"] != "world" {
- t.Errorf("expected mapping to be returned")
- }
-}
-
-func TestDecode_NestedNode(t *testing.T) {
- // given
- var value struct {
- Nested struct {
- Content ast.Node
- }
- }
-
- content := `
-nested "content" {
- hello = "world"
-}
-`
-
- // when
- err := Decode(&value, content)
-
- // then
- if err != nil {
- t.Errorf("unable to decode content, %v", err)
- return
- }
-
- // verify ast.Node can be decoded later
- var v map[string]interface{}
- err = DecodeObject(&v, value.Nested.Content)
- if err != nil {
- t.Errorf("unable to decode content, %v", err)
- return
- }
-
- if v["hello"] != "world" {
- t.Errorf("expected mapping to be returned")
- }
-}
-
-// https://github.com/hashicorp/hcl/issues/60
-func TestDecode_topLevelKeys(t *testing.T) {
- type Template struct {
- Source string
- }
-
- templates := struct {
- Templates []*Template `hcl:"template"`
- }{}
-
- err := Decode(&templates, `
- template {
- source = "blah"
- }
-
- template {
- source = "blahblah"
- }`)
-
- if err != nil {
- t.Fatal(err)
- }
-
- if templates.Templates[0].Source != "blah" {
- t.Errorf("bad source: %s", templates.Templates[0].Source)
- }
-
- if templates.Templates[1].Source != "blahblah" {
- t.Errorf("bad source: %s", templates.Templates[1].Source)
- }
-}
-
-func TestDecode_flattenedJSON(t *testing.T) {
- // make sure we can also correctly extract a Name key too
- type V struct {
- Name string `hcl:",key"`
- Description string
- Default map[string]string
- }
- type Vars struct {
- Variable []*V
- }
-
- cases := []struct {
- JSON string
- Out interface{}
- Expected interface{}
- }{
- { // Nested object, no sibling keys
- JSON: `
-{
- "var_name": {
- "default": {
- "key1": "a",
- "key2": "b"
- }
- }
-}
- `,
- Out: &[]*V{},
- Expected: &[]*V{
- &V{
- Name: "var_name",
- Default: map[string]string{"key1": "a", "key2": "b"},
- },
- },
- },
-
- { // Nested object with a sibling key (this worked previously)
- JSON: `
-{
- "var_name": {
- "description": "Described",
- "default": {
- "key1": "a",
- "key2": "b"
- }
- }
-}
- `,
- Out: &[]*V{},
- Expected: &[]*V{
- &V{
- Name: "var_name",
- Description: "Described",
- Default: map[string]string{"key1": "a", "key2": "b"},
- },
- },
- },
-
- { // Multiple nested objects, one with a sibling key
- JSON: `
-{
- "variable": {
- "var_1": {
- "default": {
- "key1": "a",
- "key2": "b"
- }
- },
- "var_2": {
- "description": "Described",
- "default": {
- "key1": "a",
- "key2": "b"
- }
- }
- }
-}
- `,
- Out: &Vars{},
- Expected: &Vars{
- Variable: []*V{
- &V{
- Name: "var_1",
- Default: map[string]string{"key1": "a", "key2": "b"},
- },
- &V{
- Name: "var_2",
- Description: "Described",
- Default: map[string]string{"key1": "a", "key2": "b"},
- },
- },
- },
- },
-
- { // Nested object to maps
- JSON: `
-{
- "variable": {
- "var_name": {
- "description": "Described",
- "default": {
- "key1": "a",
- "key2": "b"
- }
- }
- }
-}
- `,
- Out: &[]map[string]interface{}{},
- Expected: &[]map[string]interface{}{
- {
- "variable": []map[string]interface{}{
- {
- "var_name": []map[string]interface{}{
- {
- "description": "Described",
- "default": []map[string]interface{}{
- {
- "key1": "a",
- "key2": "b",
- },
- },
- },
- },
- },
- },
- },
- },
- },
-
- { // Nested object to maps without a sibling key should decode the same as above
- JSON: `
-{
- "variable": {
- "var_name": {
- "default": {
- "key1": "a",
- "key2": "b"
- }
- }
- }
-}
- `,
- Out: &[]map[string]interface{}{},
- Expected: &[]map[string]interface{}{
- {
- "variable": []map[string]interface{}{
- {
- "var_name": []map[string]interface{}{
- {
- "default": []map[string]interface{}{
- {
- "key1": "a",
- "key2": "b",
- },
- },
- },
- },
- },
- },
- },
- },
- },
-
- { // Nested objects, one with a sibling key, and one without
- JSON: `
-{
- "variable": {
- "var_1": {
- "default": {
- "key1": "a",
- "key2": "b"
- }
- },
- "var_2": {
- "description": "Described",
- "default": {
- "key1": "a",
- "key2": "b"
- }
- }
- }
-}
- `,
- Out: &[]map[string]interface{}{},
- Expected: &[]map[string]interface{}{
- {
- "variable": []map[string]interface{}{
- {
- "var_1": []map[string]interface{}{
- {
- "default": []map[string]interface{}{
- {
- "key1": "a",
- "key2": "b",
- },
- },
- },
- },
- },
- },
- },
- {
- "variable": []map[string]interface{}{
- {
- "var_2": []map[string]interface{}{
- {
- "description": "Described",
- "default": []map[string]interface{}{
- {
- "key1": "a",
- "key2": "b",
- },
- },
- },
- },
- },
- },
- },
- },
- },
- }
-
- for i, tc := range cases {
- err := Decode(tc.Out, tc.JSON)
- if err != nil {
- t.Fatalf("[%d] err: %s", i, err)
- }
-
- if !reflect.DeepEqual(tc.Out, tc.Expected) {
- t.Fatalf("[%d]\ngot: %s\nexpected: %s\n", i, spew.Sdump(tc.Out), spew.Sdump(tc.Expected))
- }
- }
-}
diff --git a/vendor/github.com/hashicorp/hcl/hcl.go b/vendor/github.com/hashicorp/hcl/hcl.go
deleted file mode 100644
index 575a20b..0000000
--- a/vendor/github.com/hashicorp/hcl/hcl.go
+++ /dev/null
@@ -1,11 +0,0 @@
-// Package hcl decodes HCL into usable Go structures.
-//
-// hcl input can come in either pure HCL format or JSON format.
-// It can be parsed into an AST, and then decoded into a structure,
-// or it can be decoded directly from a string into a structure.
-//
-// If you choose to parse HCL into a raw AST, the benefit is that you
-// can write custom visitor implementations to implement custom
-// semantic checks. By default, HCL does not perform any semantic
-// checks.
-package hcl
diff --git a/vendor/github.com/hashicorp/hcl/hcl/ast/ast.go b/vendor/github.com/hashicorp/hcl/hcl/ast/ast.go
deleted file mode 100644
index 6e5ef65..0000000
--- a/vendor/github.com/hashicorp/hcl/hcl/ast/ast.go
+++ /dev/null
@@ -1,219 +0,0 @@
-// Package ast declares the types used to represent syntax trees for HCL
-// (HashiCorp Configuration Language)
-package ast
-
-import (
- "fmt"
- "strings"
-
- "github.com/hashicorp/hcl/hcl/token"
-)
-
-// Node is an element in the abstract syntax tree.
-type Node interface {
- node()
- Pos() token.Pos
-}
-
-func (File) node() {}
-func (ObjectList) node() {}
-func (ObjectKey) node() {}
-func (ObjectItem) node() {}
-func (Comment) node() {}
-func (CommentGroup) node() {}
-func (ObjectType) node() {}
-func (LiteralType) node() {}
-func (ListType) node() {}
-
-// File represents a single HCL file
-type File struct {
- Node Node // usually a *ObjectList
- Comments []*CommentGroup // list of all comments in the source
-}
-
-func (f *File) Pos() token.Pos {
- return f.Node.Pos()
-}
-
-// ObjectList represents a list of ObjectItems. An HCL file itself is an
-// ObjectList.
-type ObjectList struct {
- Items []*ObjectItem
-}
-
-func (o *ObjectList) Add(item *ObjectItem) {
- o.Items = append(o.Items, item)
-}
-
-// Filter filters out the objects with the given key list as a prefix.
-//
-// The returned list of objects contain ObjectItems where the keys have
-// this prefix already stripped off. This might result in objects with
-// zero-length key lists if they have no children.
-//
-// If no matches are found, an empty ObjectList (non-nil) is returned.
-func (o *ObjectList) Filter(keys ...string) *ObjectList {
- var result ObjectList
- for _, item := range o.Items {
- // If there aren't enough keys, then ignore this
- if len(item.Keys) < len(keys) {
- continue
- }
-
- match := true
- for i, key := range item.Keys[:len(keys)] {
- key := key.Token.Value().(string)
- if key != keys[i] && !strings.EqualFold(key, keys[i]) {
- match = false
- break
- }
- }
- if !match {
- continue
- }
-
- // Strip off the prefix from the children
- newItem := *item
- newItem.Keys = newItem.Keys[len(keys):]
- result.Add(&newItem)
- }
-
- return &result
-}
-
-// Children returns further nested objects (key length > 0) within this
-// ObjectList. This should be used with Filter to get at child items.
-func (o *ObjectList) Children() *ObjectList {
- var result ObjectList
- for _, item := range o.Items {
- if len(item.Keys) > 0 {
- result.Add(item)
- }
- }
-
- return &result
-}
-
-// Elem returns items in the list that are direct element assignments
-// (key length == 0). This should be used with Filter to get at elements.
-func (o *ObjectList) Elem() *ObjectList {
- var result ObjectList
- for _, item := range o.Items {
- if len(item.Keys) == 0 {
- result.Add(item)
- }
- }
-
- return &result
-}
-
-func (o *ObjectList) Pos() token.Pos {
- // always returns the uninitiliazed position
- return o.Items[0].Pos()
-}
-
-// ObjectItem represents a HCL Object Item. An item is represented with a key
-// (or keys). It can be an assignment or an object (both normal and nested)
-type ObjectItem struct {
- // keys is only one length long if it's of type assignment. If it's a
- // nested object it can be larger than one. In that case "assign" is
- // invalid as there is no assignments for a nested object.
- Keys []*ObjectKey
-
- // assign contains the position of "=", if any
- Assign token.Pos
-
- // val is the item itself. It can be an object,list, number, bool or a
- // string. If key length is larger than one, val can be only of type
- // Object.
- Val Node
-
- LeadComment *CommentGroup // associated lead comment
- LineComment *CommentGroup // associated line comment
-}
-
-func (o *ObjectItem) Pos() token.Pos {
- // I'm not entirely sure what causes this, but removing this causes
- // a test failure. We should investigate at some point.
- if len(o.Keys) == 0 {
- return token.Pos{}
- }
-
- return o.Keys[0].Pos()
-}
-
-// ObjectKeys are either an identifier or of type string.
-type ObjectKey struct {
- Token token.Token
-}
-
-func (o *ObjectKey) Pos() token.Pos {
- return o.Token.Pos
-}
-
-// LiteralType represents a literal of basic type. Valid types are:
-// token.NUMBER, token.FLOAT, token.BOOL and token.STRING
-type LiteralType struct {
- Token token.Token
-
- // comment types, only used when in a list
- LeadComment *CommentGroup
- LineComment *CommentGroup
-}
-
-func (l *LiteralType) Pos() token.Pos {
- return l.Token.Pos
-}
-
-// ListStatement represents a HCL List type
-type ListType struct {
- Lbrack token.Pos // position of "["
- Rbrack token.Pos // position of "]"
- List []Node // the elements in lexical order
-}
-
-func (l *ListType) Pos() token.Pos {
- return l.Lbrack
-}
-
-func (l *ListType) Add(node Node) {
- l.List = append(l.List, node)
-}
-
-// ObjectType represents a HCL Object Type
-type ObjectType struct {
- Lbrace token.Pos // position of "{"
- Rbrace token.Pos // position of "}"
- List *ObjectList // the nodes in lexical order
-}
-
-func (o *ObjectType) Pos() token.Pos {
- return o.Lbrace
-}
-
-// Comment node represents a single //, # style or /*- style commment
-type Comment struct {
- Start token.Pos // position of / or #
- Text string
-}
-
-func (c *Comment) Pos() token.Pos {
- return c.Start
-}
-
-// CommentGroup node represents a sequence of comments with no other tokens and
-// no empty lines between.
-type CommentGroup struct {
- List []*Comment // len(List) > 0
-}
-
-func (c *CommentGroup) Pos() token.Pos {
- return c.List[0].Pos()
-}
-
-//-------------------------------------------------------------------
-// GoStringer
-//-------------------------------------------------------------------
-
-func (o *ObjectKey) GoString() string { return fmt.Sprintf("*%#v", *o) }
-func (o *ObjectList) GoString() string { return fmt.Sprintf("*%#v", *o) }
diff --git a/vendor/github.com/hashicorp/hcl/hcl/ast/ast_test.go b/vendor/github.com/hashicorp/hcl/hcl/ast/ast_test.go
deleted file mode 100644
index 942256c..0000000
--- a/vendor/github.com/hashicorp/hcl/hcl/ast/ast_test.go
+++ /dev/null
@@ -1,200 +0,0 @@
-package ast
-
-import (
- "reflect"
- "strings"
- "testing"
-
- "github.com/hashicorp/hcl/hcl/token"
-)
-
-func TestObjectListFilter(t *testing.T) {
- var cases = []struct {
- Filter []string
- Input []*ObjectItem
- Output []*ObjectItem
- }{
- {
- []string{"foo"},
- []*ObjectItem{
- &ObjectItem{
- Keys: []*ObjectKey{
- &ObjectKey{
- Token: token.Token{Type: token.STRING, Text: `"foo"`},
- },
- },
- },
- },
- []*ObjectItem{
- &ObjectItem{
- Keys: []*ObjectKey{},
- },
- },
- },
-
- {
- []string{"foo"},
- []*ObjectItem{
- &ObjectItem{
- Keys: []*ObjectKey{
- &ObjectKey{Token: token.Token{Type: token.STRING, Text: `"foo"`}},
- &ObjectKey{Token: token.Token{Type: token.STRING, Text: `"bar"`}},
- },
- },
- &ObjectItem{
- Keys: []*ObjectKey{
- &ObjectKey{Token: token.Token{Type: token.STRING, Text: `"baz"`}},
- },
- },
- },
- []*ObjectItem{
- &ObjectItem{
- Keys: []*ObjectKey{
- &ObjectKey{Token: token.Token{Type: token.STRING, Text: `"bar"`}},
- },
- },
- },
- },
- }
-
- for _, tc := range cases {
- input := &ObjectList{Items: tc.Input}
- expected := &ObjectList{Items: tc.Output}
- if actual := input.Filter(tc.Filter...); !reflect.DeepEqual(actual, expected) {
- t.Fatalf("in order: input, expected, actual\n\n%#v\n\n%#v\n\n%#v", input, expected, actual)
- }
- }
-}
-
-func TestWalk(t *testing.T) {
- items := []*ObjectItem{
- &ObjectItem{
- Keys: []*ObjectKey{
- &ObjectKey{Token: token.Token{Type: token.STRING, Text: `"foo"`}},
- &ObjectKey{Token: token.Token{Type: token.STRING, Text: `"bar"`}},
- },
- Val: &LiteralType{Token: token.Token{Type: token.STRING, Text: `"example"`}},
- },
- &ObjectItem{
- Keys: []*ObjectKey{
- &ObjectKey{Token: token.Token{Type: token.STRING, Text: `"baz"`}},
- },
- },
- }
-
- node := &ObjectList{Items: items}
-
- order := []string{
- "*ast.ObjectList",
- "*ast.ObjectItem",
- "*ast.ObjectKey",
- "*ast.ObjectKey",
- "*ast.LiteralType",
- "*ast.ObjectItem",
- "*ast.ObjectKey",
- }
- count := 0
-
- Walk(node, func(n Node) (Node, bool) {
- if n == nil {
- return n, false
- }
-
- typeName := reflect.TypeOf(n).String()
- if order[count] != typeName {
- t.Errorf("expected '%s' got: '%s'", order[count], typeName)
- }
- count++
- return n, true
- })
-}
-
-func TestWalkEquality(t *testing.T) {
- items := []*ObjectItem{
- &ObjectItem{
- Keys: []*ObjectKey{
- &ObjectKey{Token: token.Token{Type: token.STRING, Text: `"foo"`}},
- },
- },
- &ObjectItem{
- Keys: []*ObjectKey{
- &ObjectKey{Token: token.Token{Type: token.STRING, Text: `"bar"`}},
- },
- },
- }
-
- node := &ObjectList{Items: items}
-
- rewritten := Walk(node, func(n Node) (Node, bool) { return n, true })
-
- newNode, ok := rewritten.(*ObjectList)
- if !ok {
- t.Fatalf("expected Objectlist, got %T", rewritten)
- }
-
- if !reflect.DeepEqual(node, newNode) {
- t.Fatal("rewritten node is not equal to the given node")
- }
-
- if len(newNode.Items) != 2 {
- t.Error("expected newNode length 2, got: %d", len(newNode.Items))
- }
-
- expected := []string{
- `"foo"`,
- `"bar"`,
- }
-
- for i, item := range newNode.Items {
- if len(item.Keys) != 1 {
- t.Error("expected keys newNode length 1, got: %d", len(item.Keys))
- }
-
- if item.Keys[0].Token.Text != expected[i] {
- t.Errorf("expected key %s, got %s", expected[i], item.Keys[0].Token.Text)
- }
-
- if item.Val != nil {
- t.Errorf("expected item value should be nil")
- }
- }
-}
-
-func TestWalkRewrite(t *testing.T) {
- items := []*ObjectItem{
- &ObjectItem{
- Keys: []*ObjectKey{
- &ObjectKey{Token: token.Token{Type: token.STRING, Text: `"foo"`}},
- &ObjectKey{Token: token.Token{Type: token.STRING, Text: `"bar"`}},
- },
- },
- &ObjectItem{
- Keys: []*ObjectKey{
- &ObjectKey{Token: token.Token{Type: token.STRING, Text: `"baz"`}},
- },
- },
- }
-
- node := &ObjectList{Items: items}
-
- suffix := "_example"
- node = Walk(node, func(n Node) (Node, bool) {
- switch i := n.(type) {
- case *ObjectKey:
- i.Token.Text = i.Token.Text + suffix
- n = i
- }
- return n, true
- }).(*ObjectList)
-
- Walk(node, func(n Node) (Node, bool) {
- switch i := n.(type) {
- case *ObjectKey:
- if !strings.HasSuffix(i.Token.Text, suffix) {
- t.Errorf("Token '%s' should have suffix: %s", i.Token.Text, suffix)
- }
- }
- return n, true
- })
-
-}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/ast/walk.go b/vendor/github.com/hashicorp/hcl/hcl/ast/walk.go
deleted file mode 100644
index ba07ad4..0000000
--- a/vendor/github.com/hashicorp/hcl/hcl/ast/walk.go
+++ /dev/null
@@ -1,52 +0,0 @@
-package ast
-
-import "fmt"
-
-// WalkFunc describes a function to be called for each node during a Walk. The
-// returned node can be used to rewrite the AST. Walking stops the returned
-// bool is false.
-type WalkFunc func(Node) (Node, bool)
-
-// Walk traverses an AST in depth-first order: It starts by calling fn(node);
-// node must not be nil. If fn returns true, Walk invokes fn recursively for
-// each of the non-nil children of node, followed by a call of fn(nil). The
-// returned node of fn can be used to rewrite the passed node to fn.
-func Walk(node Node, fn WalkFunc) Node {
- rewritten, ok := fn(node)
- if !ok {
- return rewritten
- }
-
- switch n := node.(type) {
- case *File:
- n.Node = Walk(n.Node, fn)
- case *ObjectList:
- for i, item := range n.Items {
- n.Items[i] = Walk(item, fn).(*ObjectItem)
- }
- case *ObjectKey:
- // nothing to do
- case *ObjectItem:
- for i, k := range n.Keys {
- n.Keys[i] = Walk(k, fn).(*ObjectKey)
- }
-
- if n.Val != nil {
- n.Val = Walk(n.Val, fn)
- }
- case *LiteralType:
- // nothing to do
- case *ListType:
- for i, l := range n.List {
- n.List[i] = Walk(l, fn)
- }
- case *ObjectType:
- n.List = Walk(n.List, fn).(*ObjectList)
- default:
- // should we panic here?
- fmt.Printf("unknown type: %T\n", n)
- }
-
- fn(nil)
- return rewritten
-}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/error.go b/vendor/github.com/hashicorp/hcl/hcl/parser/error.go
deleted file mode 100644
index 5c99381..0000000
--- a/vendor/github.com/hashicorp/hcl/hcl/parser/error.go
+++ /dev/null
@@ -1,17 +0,0 @@
-package parser
-
-import (
- "fmt"
-
- "github.com/hashicorp/hcl/hcl/token"
-)
-
-// PosError is a parse error that contains a position.
-type PosError struct {
- Pos token.Pos
- Err error
-}
-
-func (e *PosError) Error() string {
- return fmt.Sprintf("At %s: %s", e.Pos, e.Err)
-}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/error_test.go b/vendor/github.com/hashicorp/hcl/hcl/parser/error_test.go
deleted file mode 100644
index 32399fe..0000000
--- a/vendor/github.com/hashicorp/hcl/hcl/parser/error_test.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package parser
-
-import (
- "testing"
-)
-
-func TestPosError_impl(t *testing.T) {
- var _ error = new(PosError)
-}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go b/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go
deleted file mode 100644
index 098e1bc..0000000
--- a/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go
+++ /dev/null
@@ -1,526 +0,0 @@
-// Package parser implements a parser for HCL (HashiCorp Configuration
-// Language)
-package parser
-
-import (
- "bytes"
- "errors"
- "fmt"
- "strings"
-
- "github.com/hashicorp/hcl/hcl/ast"
- "github.com/hashicorp/hcl/hcl/scanner"
- "github.com/hashicorp/hcl/hcl/token"
-)
-
-type Parser struct {
- sc *scanner.Scanner
-
- // Last read token
- tok token.Token
- commaPrev token.Token
-
- comments []*ast.CommentGroup
- leadComment *ast.CommentGroup // last lead comment
- lineComment *ast.CommentGroup // last line comment
-
- enableTrace bool
- indent int
- n int // buffer size (max = 1)
-}
-
-func newParser(src []byte) *Parser {
- return &Parser{
- sc: scanner.New(src),
- }
-}
-
-// Parse returns the fully parsed source and returns the abstract syntax tree.
-func Parse(src []byte) (*ast.File, error) {
- // normalize all line endings
- // since the scanner and output only work with "\n" line endings, we may
- // end up with dangling "\r" characters in the parsed data.
- src = bytes.Replace(src, []byte("\r\n"), []byte("\n"), -1)
-
- p := newParser(src)
- return p.Parse()
-}
-
-var errEofToken = errors.New("EOF token found")
-
-// Parse returns the fully parsed source and returns the abstract syntax tree.
-func (p *Parser) Parse() (*ast.File, error) {
- f := &ast.File{}
- var err, scerr error
- p.sc.Error = func(pos token.Pos, msg string) {
- scerr = &PosError{Pos: pos, Err: errors.New(msg)}
- }
-
- f.Node, err = p.objectList(false)
- if scerr != nil {
- return nil, scerr
- }
- if err != nil {
- return nil, err
- }
-
- f.Comments = p.comments
- return f, nil
-}
-
-// objectList parses a list of items within an object (generally k/v pairs).
-// The parameter" obj" tells this whether to we are within an object (braces:
-// '{', '}') or just at the top level. If we're within an object, we end
-// at an RBRACE.
-func (p *Parser) objectList(obj bool) (*ast.ObjectList, error) {
- defer un(trace(p, "ParseObjectList"))
- node := &ast.ObjectList{}
-
- for {
- if obj {
- tok := p.scan()
- p.unscan()
- if tok.Type == token.RBRACE {
- break
- }
- }
-
- n, err := p.objectItem()
- if err == errEofToken {
- break // we are finished
- }
-
- // we don't return a nil node, because might want to use already
- // collected items.
- if err != nil {
- return node, err
- }
-
- node.Add(n)
-
- // object lists can be optionally comma-delimited e.g. when a list of maps
- // is being expressed, so a comma is allowed here - it's simply consumed
- tok := p.scan()
- if tok.Type != token.COMMA {
- p.unscan()
- }
- }
- return node, nil
-}
-
-func (p *Parser) consumeComment() (comment *ast.Comment, endline int) {
- endline = p.tok.Pos.Line
-
- // count the endline if it's multiline comment, ie starting with /*
- if len(p.tok.Text) > 1 && p.tok.Text[1] == '*' {
- // don't use range here - no need to decode Unicode code points
- for i := 0; i < len(p.tok.Text); i++ {
- if p.tok.Text[i] == '\n' {
- endline++
- }
- }
- }
-
- comment = &ast.Comment{Start: p.tok.Pos, Text: p.tok.Text}
- p.tok = p.sc.Scan()
- return
-}
-
-func (p *Parser) consumeCommentGroup(n int) (comments *ast.CommentGroup, endline int) {
- var list []*ast.Comment
- endline = p.tok.Pos.Line
-
- for p.tok.Type == token.COMMENT && p.tok.Pos.Line <= endline+n {
- var comment *ast.Comment
- comment, endline = p.consumeComment()
- list = append(list, comment)
- }
-
- // add comment group to the comments list
- comments = &ast.CommentGroup{List: list}
- p.comments = append(p.comments, comments)
-
- return
-}
-
-// objectItem parses a single object item
-func (p *Parser) objectItem() (*ast.ObjectItem, error) {
- defer un(trace(p, "ParseObjectItem"))
-
- keys, err := p.objectKey()
- if len(keys) > 0 && err == errEofToken {
- // We ignore eof token here since it is an error if we didn't
- // receive a value (but we did receive a key) for the item.
- err = nil
- }
- if len(keys) > 0 && err != nil && p.tok.Type == token.RBRACE {
- // This is a strange boolean statement, but what it means is:
- // We have keys with no value, and we're likely in an object
- // (since RBrace ends an object). For this, we set err to nil so
- // we continue and get the error below of having the wrong value
- // type.
- err = nil
-
- // Reset the token type so we don't think it completed fine. See
- // objectType which uses p.tok.Type to check if we're done with
- // the object.
- p.tok.Type = token.EOF
- }
- if err != nil {
- return nil, err
- }
-
- o := &ast.ObjectItem{
- Keys: keys,
- }
-
- if p.leadComment != nil {
- o.LeadComment = p.leadComment
- p.leadComment = nil
- }
-
- switch p.tok.Type {
- case token.ASSIGN:
- o.Assign = p.tok.Pos
- o.Val, err = p.object()
- if err != nil {
- return nil, err
- }
- case token.LBRACE:
- o.Val, err = p.objectType()
- if err != nil {
- return nil, err
- }
- default:
- keyStr := make([]string, 0, len(keys))
- for _, k := range keys {
- keyStr = append(keyStr, k.Token.Text)
- }
-
- return nil, &PosError{
- Pos: p.tok.Pos,
- Err: fmt.Errorf(
- "key '%s' expected start of object ('{') or assignment ('=')",
- strings.Join(keyStr, " ")),
- }
- }
-
- // do a look-ahead for line comment
- p.scan()
- if len(keys) > 0 && o.Val.Pos().Line == keys[0].Pos().Line && p.lineComment != nil {
- o.LineComment = p.lineComment
- p.lineComment = nil
- }
- p.unscan()
- return o, nil
-}
-
-// objectKey parses an object key and returns a ObjectKey AST
-func (p *Parser) objectKey() ([]*ast.ObjectKey, error) {
- keyCount := 0
- keys := make([]*ast.ObjectKey, 0)
-
- for {
- tok := p.scan()
- switch tok.Type {
- case token.EOF:
- // It is very important to also return the keys here as well as
- // the error. This is because we need to be able to tell if we
- // did parse keys prior to finding the EOF, or if we just found
- // a bare EOF.
- return keys, errEofToken
- case token.ASSIGN:
- // assignment or object only, but not nested objects. this is not
- // allowed: `foo bar = {}`
- if keyCount > 1 {
- return nil, &PosError{
- Pos: p.tok.Pos,
- Err: fmt.Errorf("nested object expected: LBRACE got: %s", p.tok.Type),
- }
- }
-
- if keyCount == 0 {
- return nil, &PosError{
- Pos: p.tok.Pos,
- Err: errors.New("no object keys found!"),
- }
- }
-
- return keys, nil
- case token.LBRACE:
- var err error
-
- // If we have no keys, then it is a syntax error. i.e. {{}} is not
- // allowed.
- if len(keys) == 0 {
- err = &PosError{
- Pos: p.tok.Pos,
- Err: fmt.Errorf("expected: IDENT | STRING got: %s", p.tok.Type),
- }
- }
-
- // object
- return keys, err
- case token.IDENT, token.STRING:
- keyCount++
- keys = append(keys, &ast.ObjectKey{Token: p.tok})
- case token.ILLEGAL:
- return keys, &PosError{
- Pos: p.tok.Pos,
- Err: fmt.Errorf("illegal character"),
- }
- default:
- return keys, &PosError{
- Pos: p.tok.Pos,
- Err: fmt.Errorf("expected: IDENT | STRING | ASSIGN | LBRACE got: %s", p.tok.Type),
- }
- }
- }
-}
-
-// object parses any type of object, such as number, bool, string, object or
-// list.
-func (p *Parser) object() (ast.Node, error) {
- defer un(trace(p, "ParseType"))
- tok := p.scan()
-
- switch tok.Type {
- case token.NUMBER, token.FLOAT, token.BOOL, token.STRING, token.HEREDOC:
- return p.literalType()
- case token.LBRACE:
- return p.objectType()
- case token.LBRACK:
- return p.listType()
- case token.COMMENT:
- // implement comment
- case token.EOF:
- return nil, errEofToken
- }
-
- return nil, &PosError{
- Pos: tok.Pos,
- Err: fmt.Errorf("Unknown token: %+v", tok),
- }
-}
-
-// objectType parses an object type and returns a ObjectType AST
-func (p *Parser) objectType() (*ast.ObjectType, error) {
- defer un(trace(p, "ParseObjectType"))
-
- // we assume that the currently scanned token is a LBRACE
- o := &ast.ObjectType{
- Lbrace: p.tok.Pos,
- }
-
- l, err := p.objectList(true)
-
- // if we hit RBRACE, we are good to go (means we parsed all Items), if it's
- // not a RBRACE, it's an syntax error and we just return it.
- if err != nil && p.tok.Type != token.RBRACE {
- return nil, err
- }
-
- // No error, scan and expect the ending to be a brace
- if tok := p.scan(); tok.Type != token.RBRACE {
- return nil, &PosError{
- Pos: tok.Pos,
- Err: fmt.Errorf("object expected closing RBRACE got: %s", tok.Type),
- }
- }
-
- o.List = l
- o.Rbrace = p.tok.Pos // advanced via parseObjectList
- return o, nil
-}
-
-// listType parses a list type and returns a ListType AST
-func (p *Parser) listType() (*ast.ListType, error) {
- defer un(trace(p, "ParseListType"))
-
- // we assume that the currently scanned token is a LBRACK
- l := &ast.ListType{
- Lbrack: p.tok.Pos,
- }
-
- needComma := false
- for {
- tok := p.scan()
- if needComma {
- switch tok.Type {
- case token.COMMA, token.RBRACK:
- default:
- return nil, &PosError{
- Pos: tok.Pos,
- Err: fmt.Errorf(
- "error parsing list, expected comma or list end, got: %s",
- tok.Type),
- }
- }
- }
- switch tok.Type {
- case token.BOOL, token.NUMBER, token.FLOAT, token.STRING, token.HEREDOC:
- node, err := p.literalType()
- if err != nil {
- return nil, err
- }
-
- // If there is a lead comment, apply it
- if p.leadComment != nil {
- node.LeadComment = p.leadComment
- p.leadComment = nil
- }
-
- l.Add(node)
- needComma = true
- case token.COMMA:
- // get next list item or we are at the end
- // do a look-ahead for line comment
- p.scan()
- if p.lineComment != nil && len(l.List) > 0 {
- lit, ok := l.List[len(l.List)-1].(*ast.LiteralType)
- if ok {
- lit.LineComment = p.lineComment
- l.List[len(l.List)-1] = lit
- p.lineComment = nil
- }
- }
- p.unscan()
-
- needComma = false
- continue
- case token.LBRACE:
- // Looks like a nested object, so parse it out
- node, err := p.objectType()
- if err != nil {
- return nil, &PosError{
- Pos: tok.Pos,
- Err: fmt.Errorf(
- "error while trying to parse object within list: %s", err),
- }
- }
- l.Add(node)
- needComma = true
- case token.LBRACK:
- node, err := p.listType()
- if err != nil {
- return nil, &PosError{
- Pos: tok.Pos,
- Err: fmt.Errorf(
- "error while trying to parse list within list: %s", err),
- }
- }
- l.Add(node)
- case token.RBRACK:
- // finished
- l.Rbrack = p.tok.Pos
- return l, nil
- default:
- return nil, &PosError{
- Pos: tok.Pos,
- Err: fmt.Errorf("unexpected token while parsing list: %s", tok.Type),
- }
- }
- }
-}
-
-// literalType parses a literal type and returns a LiteralType AST
-func (p *Parser) literalType() (*ast.LiteralType, error) {
- defer un(trace(p, "ParseLiteral"))
-
- return &ast.LiteralType{
- Token: p.tok,
- }, nil
-}
-
-// scan returns the next token from the underlying scanner. If a token has
-// been unscanned then read that instead. In the process, it collects any
-// comment groups encountered, and remembers the last lead and line comments.
-func (p *Parser) scan() token.Token {
- // If we have a token on the buffer, then return it.
- if p.n != 0 {
- p.n = 0
- return p.tok
- }
-
- // Otherwise read the next token from the scanner and Save it to the buffer
- // in case we unscan later.
- prev := p.tok
- p.tok = p.sc.Scan()
-
- if p.tok.Type == token.COMMENT {
- var comment *ast.CommentGroup
- var endline int
-
- // fmt.Printf("p.tok.Pos.Line = %+v prev: %d endline %d \n",
- // p.tok.Pos.Line, prev.Pos.Line, endline)
- if p.tok.Pos.Line == prev.Pos.Line {
- // The comment is on same line as the previous token; it
- // cannot be a lead comment but may be a line comment.
- comment, endline = p.consumeCommentGroup(0)
- if p.tok.Pos.Line != endline {
- // The next token is on a different line, thus
- // the last comment group is a line comment.
- p.lineComment = comment
- }
- }
-
- // consume successor comments, if any
- endline = -1
- for p.tok.Type == token.COMMENT {
- comment, endline = p.consumeCommentGroup(1)
- }
-
- if endline+1 == p.tok.Pos.Line && p.tok.Type != token.RBRACE {
- switch p.tok.Type {
- case token.RBRACE, token.RBRACK:
- // Do not count for these cases
- default:
- // The next token is following on the line immediately after the
- // comment group, thus the last comment group is a lead comment.
- p.leadComment = comment
- }
- }
-
- }
-
- return p.tok
-}
-
-// unscan pushes the previously read token back onto the buffer.
-func (p *Parser) unscan() {
- p.n = 1
-}
-
-// ----------------------------------------------------------------------------
-// Parsing support
-
-func (p *Parser) printTrace(a ...interface{}) {
- if !p.enableTrace {
- return
- }
-
- const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
- const n = len(dots)
- fmt.Printf("%5d:%3d: ", p.tok.Pos.Line, p.tok.Pos.Column)
-
- i := 2 * p.indent
- for i > n {
- fmt.Print(dots)
- i -= n
- }
- // i <= n
- fmt.Print(dots[0:i])
- fmt.Println(a...)
-}
-
-func trace(p *Parser, msg string) *Parser {
- p.printTrace(msg, "(")
- p.indent++
- return p
-}
-
-// Usage pattern: defer un(trace(p, "..."))
-func un(p *Parser) {
- p.indent--
- p.printTrace(")")
-}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/parser_test.go b/vendor/github.com/hashicorp/hcl/hcl/parser/parser_test.go
deleted file mode 100644
index 2702122..0000000
--- a/vendor/github.com/hashicorp/hcl/hcl/parser/parser_test.go
+++ /dev/null
@@ -1,575 +0,0 @@
-package parser
-
-import (
- "fmt"
- "io/ioutil"
- "path/filepath"
- "reflect"
- "runtime"
- "strings"
- "testing"
-
- "github.com/hashicorp/hcl/hcl/ast"
- "github.com/hashicorp/hcl/hcl/token"
-)
-
-func TestType(t *testing.T) {
- var literals = []struct {
- typ token.Type
- src string
- }{
- {token.STRING, `foo = "foo"`},
- {token.NUMBER, `foo = 123`},
- {token.NUMBER, `foo = -29`},
- {token.FLOAT, `foo = 123.12`},
- {token.FLOAT, `foo = -123.12`},
- {token.BOOL, `foo = true`},
- {token.HEREDOC, "foo = < 0 {
- s.err("unexpected null character (0x00)")
- return eof
- }
-
- // debug
- // fmt.Printf("ch: %q, offset:column: %d:%d\n", ch, s.srcPos.Offset, s.srcPos.Column)
- return ch
-}
-
-// unread unreads the previous read Rune and updates the source position
-func (s *Scanner) unread() {
- if err := s.buf.UnreadRune(); err != nil {
- panic(err) // this is user fault, we should catch it
- }
- s.srcPos = s.prevPos // put back last position
-}
-
-// peek returns the next rune without advancing the reader.
-func (s *Scanner) peek() rune {
- peek, _, err := s.buf.ReadRune()
- if err != nil {
- return eof
- }
-
- s.buf.UnreadRune()
- return peek
-}
-
-// Scan scans the next token and returns the token.
-func (s *Scanner) Scan() token.Token {
- ch := s.next()
-
- // skip white space
- for isWhitespace(ch) {
- ch = s.next()
- }
-
- var tok token.Type
-
- // token text markings
- s.tokStart = s.srcPos.Offset - s.lastCharLen
-
- // token position, initial next() is moving the offset by one(size of rune
- // actually), though we are interested with the starting point
- s.tokPos.Offset = s.srcPos.Offset - s.lastCharLen
- if s.srcPos.Column > 0 {
- // common case: last character was not a '\n'
- s.tokPos.Line = s.srcPos.Line
- s.tokPos.Column = s.srcPos.Column
- } else {
- // last character was a '\n'
- // (we cannot be at the beginning of the source
- // since we have called next() at least once)
- s.tokPos.Line = s.srcPos.Line - 1
- s.tokPos.Column = s.lastLineLen
- }
-
- switch {
- case isLetter(ch):
- tok = token.IDENT
- lit := s.scanIdentifier()
- if lit == "true" || lit == "false" {
- tok = token.BOOL
- }
- case isDecimal(ch):
- tok = s.scanNumber(ch)
- default:
- switch ch {
- case eof:
- tok = token.EOF
- case '"':
- tok = token.STRING
- s.scanString()
- case '#', '/':
- tok = token.COMMENT
- s.scanComment(ch)
- case '.':
- tok = token.PERIOD
- ch = s.peek()
- if isDecimal(ch) {
- tok = token.FLOAT
- ch = s.scanMantissa(ch)
- ch = s.scanExponent(ch)
- }
- case '<':
- tok = token.HEREDOC
- s.scanHeredoc()
- case '[':
- tok = token.LBRACK
- case ']':
- tok = token.RBRACK
- case '{':
- tok = token.LBRACE
- case '}':
- tok = token.RBRACE
- case ',':
- tok = token.COMMA
- case '=':
- tok = token.ASSIGN
- case '+':
- tok = token.ADD
- case '-':
- if isDecimal(s.peek()) {
- ch := s.next()
- tok = s.scanNumber(ch)
- } else {
- tok = token.SUB
- }
- default:
- s.err("illegal char")
- }
- }
-
- // finish token ending
- s.tokEnd = s.srcPos.Offset
-
- // create token literal
- var tokenText string
- if s.tokStart >= 0 {
- tokenText = string(s.src[s.tokStart:s.tokEnd])
- }
- s.tokStart = s.tokEnd // ensure idempotency of tokenText() call
-
- return token.Token{
- Type: tok,
- Pos: s.tokPos,
- Text: tokenText,
- }
-}
-
-func (s *Scanner) scanComment(ch rune) {
- // single line comments
- if ch == '#' || (ch == '/' && s.peek() != '*') {
- if ch == '/' && s.peek() != '/' {
- s.err("expected '/' for comment")
- return
- }
-
- ch = s.next()
- for ch != '\n' && ch >= 0 && ch != eof {
- ch = s.next()
- }
- if ch != eof && ch >= 0 {
- s.unread()
- }
- return
- }
-
- // be sure we get the character after /* This allows us to find comment's
- // that are not erminated
- if ch == '/' {
- s.next()
- ch = s.next() // read character after "/*"
- }
-
- // look for /* - style comments
- for {
- if ch < 0 || ch == eof {
- s.err("comment not terminated")
- break
- }
-
- ch0 := ch
- ch = s.next()
- if ch0 == '*' && ch == '/' {
- break
- }
- }
-}
-
-// scanNumber scans a HCL number definition starting with the given rune
-func (s *Scanner) scanNumber(ch rune) token.Type {
- if ch == '0' {
- // check for hexadecimal, octal or float
- ch = s.next()
- if ch == 'x' || ch == 'X' {
- // hexadecimal
- ch = s.next()
- found := false
- for isHexadecimal(ch) {
- ch = s.next()
- found = true
- }
-
- if !found {
- s.err("illegal hexadecimal number")
- }
-
- if ch != eof {
- s.unread()
- }
-
- return token.NUMBER
- }
-
- // now it's either something like: 0421(octal) or 0.1231(float)
- illegalOctal := false
- for isDecimal(ch) {
- ch = s.next()
- if ch == '8' || ch == '9' {
- // this is just a possibility. For example 0159 is illegal, but
- // 0159.23 is valid. So we mark a possible illegal octal. If
- // the next character is not a period, we'll print the error.
- illegalOctal = true
- }
- }
-
- if ch == 'e' || ch == 'E' {
- ch = s.scanExponent(ch)
- return token.FLOAT
- }
-
- if ch == '.' {
- ch = s.scanFraction(ch)
-
- if ch == 'e' || ch == 'E' {
- ch = s.next()
- ch = s.scanExponent(ch)
- }
- return token.FLOAT
- }
-
- if illegalOctal {
- s.err("illegal octal number")
- }
-
- if ch != eof {
- s.unread()
- }
- return token.NUMBER
- }
-
- s.scanMantissa(ch)
- ch = s.next() // seek forward
- if ch == 'e' || ch == 'E' {
- ch = s.scanExponent(ch)
- return token.FLOAT
- }
-
- if ch == '.' {
- ch = s.scanFraction(ch)
- if ch == 'e' || ch == 'E' {
- ch = s.next()
- ch = s.scanExponent(ch)
- }
- return token.FLOAT
- }
-
- if ch != eof {
- s.unread()
- }
- return token.NUMBER
-}
-
-// scanMantissa scans the mantissa beginning from the rune. It returns the next
-// non decimal rune. It's used to determine wheter it's a fraction or exponent.
-func (s *Scanner) scanMantissa(ch rune) rune {
- scanned := false
- for isDecimal(ch) {
- ch = s.next()
- scanned = true
- }
-
- if scanned && ch != eof {
- s.unread()
- }
- return ch
-}
-
-// scanFraction scans the fraction after the '.' rune
-func (s *Scanner) scanFraction(ch rune) rune {
- if ch == '.' {
- ch = s.peek() // we peek just to see if we can move forward
- ch = s.scanMantissa(ch)
- }
- return ch
-}
-
-// scanExponent scans the remaining parts of an exponent after the 'e' or 'E'
-// rune.
-func (s *Scanner) scanExponent(ch rune) rune {
- if ch == 'e' || ch == 'E' {
- ch = s.next()
- if ch == '-' || ch == '+' {
- ch = s.next()
- }
- ch = s.scanMantissa(ch)
- }
- return ch
-}
-
-// scanHeredoc scans a heredoc string
-func (s *Scanner) scanHeredoc() {
- // Scan the second '<' in example: '<= len(identBytes) && identRegexp.Match(s.src[lineStart:s.srcPos.Offset-s.lastCharLen]) {
- break
- }
-
- // Not an anchor match, record the start of a new line
- lineStart = s.srcPos.Offset
- }
-
- if ch == eof {
- s.err("heredoc not terminated")
- return
- }
- }
-
- return
-}
-
-// scanString scans a quoted string
-func (s *Scanner) scanString() {
- braces := 0
- for {
- // '"' opening already consumed
- // read character after quote
- ch := s.next()
-
- if (ch == '\n' && braces == 0) || ch < 0 || ch == eof {
- s.err("literal not terminated")
- return
- }
-
- if ch == '"' && braces == 0 {
- break
- }
-
- // If we're going into a ${} then we can ignore quotes for awhile
- if braces == 0 && ch == '$' && s.peek() == '{' {
- braces++
- s.next()
- } else if braces > 0 && ch == '{' {
- braces++
- }
- if braces > 0 && ch == '}' {
- braces--
- }
-
- if ch == '\\' {
- s.scanEscape()
- }
- }
-
- return
-}
-
-// scanEscape scans an escape sequence
-func (s *Scanner) scanEscape() rune {
- // http://en.cppreference.com/w/cpp/language/escape
- ch := s.next() // read character after '/'
- switch ch {
- case 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', '"':
- // nothing to do
- case '0', '1', '2', '3', '4', '5', '6', '7':
- // octal notation
- ch = s.scanDigits(ch, 8, 3)
- case 'x':
- // hexademical notation
- ch = s.scanDigits(s.next(), 16, 2)
- case 'u':
- // universal character name
- ch = s.scanDigits(s.next(), 16, 4)
- case 'U':
- // universal character name
- ch = s.scanDigits(s.next(), 16, 8)
- default:
- s.err("illegal char escape")
- }
- return ch
-}
-
-// scanDigits scans a rune with the given base for n times. For example an
-// octal notation \184 would yield in scanDigits(ch, 8, 3)
-func (s *Scanner) scanDigits(ch rune, base, n int) rune {
- start := n
- for n > 0 && digitVal(ch) < base {
- ch = s.next()
- if ch == eof {
- // If we see an EOF, we halt any more scanning of digits
- // immediately.
- break
- }
-
- n--
- }
- if n > 0 {
- s.err("illegal char escape")
- }
-
- if n != start {
- // we scanned all digits, put the last non digit char back,
- // only if we read anything at all
- s.unread()
- }
-
- return ch
-}
-
-// scanIdentifier scans an identifier and returns the literal string
-func (s *Scanner) scanIdentifier() string {
- offs := s.srcPos.Offset - s.lastCharLen
- ch := s.next()
- for isLetter(ch) || isDigit(ch) || ch == '-' || ch == '.' {
- ch = s.next()
- }
-
- if ch != eof {
- s.unread() // we got identifier, put back latest char
- }
-
- return string(s.src[offs:s.srcPos.Offset])
-}
-
-// recentPosition returns the position of the character immediately after the
-// character or token returned by the last call to Scan.
-func (s *Scanner) recentPosition() (pos token.Pos) {
- pos.Offset = s.srcPos.Offset - s.lastCharLen
- switch {
- case s.srcPos.Column > 0:
- // common case: last character was not a '\n'
- pos.Line = s.srcPos.Line
- pos.Column = s.srcPos.Column
- case s.lastLineLen > 0:
- // last character was a '\n'
- // (we cannot be at the beginning of the source
- // since we have called next() at least once)
- pos.Line = s.srcPos.Line - 1
- pos.Column = s.lastLineLen
- default:
- // at the beginning of the source
- pos.Line = 1
- pos.Column = 1
- }
- return
-}
-
-// err prints the error of any scanning to s.Error function. If the function is
-// not defined, by default it prints them to os.Stderr
-func (s *Scanner) err(msg string) {
- s.ErrorCount++
- pos := s.recentPosition()
-
- if s.Error != nil {
- s.Error(pos, msg)
- return
- }
-
- fmt.Fprintf(os.Stderr, "%s: %s\n", pos, msg)
-}
-
-// isHexadecimal returns true if the given rune is a letter
-func isLetter(ch rune) bool {
- return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch)
-}
-
-// isDigit returns true if the given rune is a decimal digit
-func isDigit(ch rune) bool {
- return '0' <= ch && ch <= '9' || ch >= 0x80 && unicode.IsDigit(ch)
-}
-
-// isDecimal returns true if the given rune is a decimal number
-func isDecimal(ch rune) bool {
- return '0' <= ch && ch <= '9'
-}
-
-// isHexadecimal returns true if the given rune is an hexadecimal number
-func isHexadecimal(ch rune) bool {
- return '0' <= ch && ch <= '9' || 'a' <= ch && ch <= 'f' || 'A' <= ch && ch <= 'F'
-}
-
-// isWhitespace returns true if the rune is a space, tab, newline or carriage return
-func isWhitespace(ch rune) bool {
- return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'
-}
-
-// digitVal returns the integer value of a given octal,decimal or hexadecimal rune
-func digitVal(ch rune) int {
- switch {
- case '0' <= ch && ch <= '9':
- return int(ch - '0')
- case 'a' <= ch && ch <= 'f':
- return int(ch - 'a' + 10)
- case 'A' <= ch && ch <= 'F':
- return int(ch - 'A' + 10)
- }
- return 16 // larger than any legal digit val
-}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner_test.go b/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner_test.go
deleted file mode 100644
index 4f2c9cb..0000000
--- a/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner_test.go
+++ /dev/null
@@ -1,591 +0,0 @@
-package scanner
-
-import (
- "bytes"
- "fmt"
- "testing"
-
- "strings"
-
- "github.com/hashicorp/hcl/hcl/token"
-)
-
-var f100 = strings.Repeat("f", 100)
-
-type tokenPair struct {
- tok token.Type
- text string
-}
-
-var tokenLists = map[string][]tokenPair{
- "comment": []tokenPair{
- {token.COMMENT, "//"},
- {token.COMMENT, "////"},
- {token.COMMENT, "// comment"},
- {token.COMMENT, "// /* comment */"},
- {token.COMMENT, "// // comment //"},
- {token.COMMENT, "//" + f100},
- {token.COMMENT, "#"},
- {token.COMMENT, "##"},
- {token.COMMENT, "# comment"},
- {token.COMMENT, "# /* comment */"},
- {token.COMMENT, "# # comment #"},
- {token.COMMENT, "#" + f100},
- {token.COMMENT, "/**/"},
- {token.COMMENT, "/***/"},
- {token.COMMENT, "/* comment */"},
- {token.COMMENT, "/* // comment */"},
- {token.COMMENT, "/* /* comment */"},
- {token.COMMENT, "/*\n comment\n*/"},
- {token.COMMENT, "/*" + f100 + "*/"},
- },
- "operator": []tokenPair{
- {token.LBRACK, "["},
- {token.LBRACE, "{"},
- {token.COMMA, ","},
- {token.PERIOD, "."},
- {token.RBRACK, "]"},
- {token.RBRACE, "}"},
- {token.ASSIGN, "="},
- {token.ADD, "+"},
- {token.SUB, "-"},
- },
- "bool": []tokenPair{
- {token.BOOL, "true"},
- {token.BOOL, "false"},
- },
- "ident": []tokenPair{
- {token.IDENT, "a"},
- {token.IDENT, "a0"},
- {token.IDENT, "foobar"},
- {token.IDENT, "foo-bar"},
- {token.IDENT, "abc123"},
- {token.IDENT, "LGTM"},
- {token.IDENT, "_"},
- {token.IDENT, "_abc123"},
- {token.IDENT, "abc123_"},
- {token.IDENT, "_abc_123_"},
- {token.IDENT, "_äöü"},
- {token.IDENT, "_本"},
- {token.IDENT, "äöü"},
- {token.IDENT, "本"},
- {token.IDENT, "a۰۱۸"},
- {token.IDENT, "foo६४"},
- {token.IDENT, "bar9876"},
- },
- "heredoc": []tokenPair{
- {token.HEREDOC, "< 0 for %q", s.ErrorCount, src)
- }
-}
-
-func testTokenList(t *testing.T, tokenList []tokenPair) {
- // create artifical source code
- buf := new(bytes.Buffer)
- for _, ident := range tokenList {
- fmt.Fprintf(buf, "%s\n", ident.text)
- }
-
- s := New(buf.Bytes())
- for _, ident := range tokenList {
- tok := s.Scan()
- if tok.Type != ident.tok {
- t.Errorf("tok = %q want %q for %q\n", tok, ident.tok, ident.text)
- }
-
- if tok.Text != ident.text {
- t.Errorf("text = %q want %q", tok.String(), ident.text)
- }
-
- }
-}
-
-func countNewlines(s string) int {
- n := 0
- for _, ch := range s {
- if ch == '\n' {
- n++
- }
- }
- return n
-}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/strconv/quote.go b/vendor/github.com/hashicorp/hcl/hcl/strconv/quote.go
deleted file mode 100644
index 5f981ea..0000000
--- a/vendor/github.com/hashicorp/hcl/hcl/strconv/quote.go
+++ /dev/null
@@ -1,241 +0,0 @@
-package strconv
-
-import (
- "errors"
- "unicode/utf8"
-)
-
-// ErrSyntax indicates that a value does not have the right syntax for the target type.
-var ErrSyntax = errors.New("invalid syntax")
-
-// Unquote interprets s as a single-quoted, double-quoted,
-// or backquoted Go string literal, returning the string value
-// that s quotes. (If s is single-quoted, it would be a Go
-// character literal; Unquote returns the corresponding
-// one-character string.)
-func Unquote(s string) (t string, err error) {
- n := len(s)
- if n < 2 {
- return "", ErrSyntax
- }
- quote := s[0]
- if quote != s[n-1] {
- return "", ErrSyntax
- }
- s = s[1 : n-1]
-
- if quote != '"' {
- return "", ErrSyntax
- }
- if !contains(s, '$') && !contains(s, '{') && contains(s, '\n') {
- return "", ErrSyntax
- }
-
- // Is it trivial? Avoid allocation.
- if !contains(s, '\\') && !contains(s, quote) && !contains(s, '$') {
- switch quote {
- case '"':
- return s, nil
- case '\'':
- r, size := utf8.DecodeRuneInString(s)
- if size == len(s) && (r != utf8.RuneError || size != 1) {
- return s, nil
- }
- }
- }
-
- var runeTmp [utf8.UTFMax]byte
- buf := make([]byte, 0, 3*len(s)/2) // Try to avoid more allocations.
- for len(s) > 0 {
- // If we're starting a '${}' then let it through un-unquoted.
- // Specifically: we don't unquote any characters within the `${}`
- // section.
- if s[0] == '$' && len(s) > 1 && s[1] == '{' {
- buf = append(buf, '$', '{')
- s = s[2:]
-
- // Continue reading until we find the closing brace, copying as-is
- braces := 1
- for len(s) > 0 && braces > 0 {
- r, size := utf8.DecodeRuneInString(s)
- if r == utf8.RuneError {
- return "", ErrSyntax
- }
-
- s = s[size:]
-
- n := utf8.EncodeRune(runeTmp[:], r)
- buf = append(buf, runeTmp[:n]...)
-
- switch r {
- case '{':
- braces++
- case '}':
- braces--
- }
- }
- if braces != 0 {
- return "", ErrSyntax
- }
- if len(s) == 0 {
- // If there's no string left, we're done!
- break
- } else {
- // If there's more left, we need to pop back up to the top of the loop
- // in case there's another interpolation in this string.
- continue
- }
- }
-
- if s[0] == '\n' {
- return "", ErrSyntax
- }
-
- c, multibyte, ss, err := unquoteChar(s, quote)
- if err != nil {
- return "", err
- }
- s = ss
- if c < utf8.RuneSelf || !multibyte {
- buf = append(buf, byte(c))
- } else {
- n := utf8.EncodeRune(runeTmp[:], c)
- buf = append(buf, runeTmp[:n]...)
- }
- if quote == '\'' && len(s) != 0 {
- // single-quoted must be single character
- return "", ErrSyntax
- }
- }
- return string(buf), nil
-}
-
-// contains reports whether the string contains the byte c.
-func contains(s string, c byte) bool {
- for i := 0; i < len(s); i++ {
- if s[i] == c {
- return true
- }
- }
- return false
-}
-
-func unhex(b byte) (v rune, ok bool) {
- c := rune(b)
- switch {
- case '0' <= c && c <= '9':
- return c - '0', true
- case 'a' <= c && c <= 'f':
- return c - 'a' + 10, true
- case 'A' <= c && c <= 'F':
- return c - 'A' + 10, true
- }
- return
-}
-
-func unquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, err error) {
- // easy cases
- switch c := s[0]; {
- case c == quote && (quote == '\'' || quote == '"'):
- err = ErrSyntax
- return
- case c >= utf8.RuneSelf:
- r, size := utf8.DecodeRuneInString(s)
- return r, true, s[size:], nil
- case c != '\\':
- return rune(s[0]), false, s[1:], nil
- }
-
- // hard case: c is backslash
- if len(s) <= 1 {
- err = ErrSyntax
- return
- }
- c := s[1]
- s = s[2:]
-
- switch c {
- case 'a':
- value = '\a'
- case 'b':
- value = '\b'
- case 'f':
- value = '\f'
- case 'n':
- value = '\n'
- case 'r':
- value = '\r'
- case 't':
- value = '\t'
- case 'v':
- value = '\v'
- case 'x', 'u', 'U':
- n := 0
- switch c {
- case 'x':
- n = 2
- case 'u':
- n = 4
- case 'U':
- n = 8
- }
- var v rune
- if len(s) < n {
- err = ErrSyntax
- return
- }
- for j := 0; j < n; j++ {
- x, ok := unhex(s[j])
- if !ok {
- err = ErrSyntax
- return
- }
- v = v<<4 | x
- }
- s = s[n:]
- if c == 'x' {
- // single-byte string, possibly not UTF-8
- value = v
- break
- }
- if v > utf8.MaxRune {
- err = ErrSyntax
- return
- }
- value = v
- multibyte = true
- case '0', '1', '2', '3', '4', '5', '6', '7':
- v := rune(c) - '0'
- if len(s) < 2 {
- err = ErrSyntax
- return
- }
- for j := 0; j < 2; j++ { // one digit already; two more
- x := rune(s[j]) - '0'
- if x < 0 || x > 7 {
- err = ErrSyntax
- return
- }
- v = (v << 3) | x
- }
- s = s[2:]
- if v > 255 {
- err = ErrSyntax
- return
- }
- value = v
- case '\\':
- value = '\\'
- case '\'', '"':
- if c != quote {
- err = ErrSyntax
- return
- }
- value = rune(c)
- default:
- err = ErrSyntax
- return
- }
- tail = s
- return
-}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/strconv/quote_test.go b/vendor/github.com/hashicorp/hcl/hcl/strconv/quote_test.go
deleted file mode 100644
index 65be375..0000000
--- a/vendor/github.com/hashicorp/hcl/hcl/strconv/quote_test.go
+++ /dev/null
@@ -1,96 +0,0 @@
-package strconv
-
-import "testing"
-
-type quoteTest struct {
- in string
- out string
- ascii string
-}
-
-var quotetests = []quoteTest{
- {"\a\b\f\r\n\t\v", `"\a\b\f\r\n\t\v"`, `"\a\b\f\r\n\t\v"`},
- {"\\", `"\\"`, `"\\"`},
- {"abc\xffdef", `"abc\xffdef"`, `"abc\xffdef"`},
- {"\u263a", `"☺"`, `"\u263a"`},
- {"\U0010ffff", `"\U0010ffff"`, `"\U0010ffff"`},
- {"\x04", `"\x04"`, `"\x04"`},
-}
-
-type unQuoteTest struct {
- in string
- out string
-}
-
-var unquotetests = []unQuoteTest{
- {`""`, ""},
- {`"a"`, "a"},
- {`"abc"`, "abc"},
- {`"☺"`, "☺"},
- {`"hello world"`, "hello world"},
- {`"\xFF"`, "\xFF"},
- {`"\377"`, "\377"},
- {`"\u1234"`, "\u1234"},
- {`"\U00010111"`, "\U00010111"},
- {`"\U0001011111"`, "\U0001011111"},
- {`"\a\b\f\n\r\t\v\\\""`, "\a\b\f\n\r\t\v\\\""},
- {`"'"`, "'"},
- {`"${file("foo")}"`, `${file("foo")}`},
- {`"${file("\"foo\"")}"`, `${file("\"foo\"")}`},
- {`"echo ${var.region}${element(split(",",var.zones),0)}"`,
- `echo ${var.region}${element(split(",",var.zones),0)}`},
- {`"${HH\\:mm\\:ss}"`, `${HH\\:mm\\:ss}`},
- {`"${\n}"`, `${\n}`},
-}
-
-var misquoted = []string{
- ``,
- `"`,
- `"a`,
- `"'`,
- `b"`,
- `"\"`,
- `"\9"`,
- `"\19"`,
- `"\129"`,
- `'\'`,
- `'\9'`,
- `'\19'`,
- `'\129'`,
- `'ab'`,
- `"\x1!"`,
- `"\U12345678"`,
- `"\z"`,
- "`",
- "`xxx",
- "`\"",
- `"\'"`,
- `'\"'`,
- "\"\n\"",
- "\"\\n\n\"",
- "'\n'",
- `"${"`,
- `"${foo{}"`,
- "\"${foo}\n\"",
-}
-
-func TestUnquote(t *testing.T) {
- for _, tt := range unquotetests {
- if out, err := Unquote(tt.in); err != nil || out != tt.out {
- t.Errorf("Unquote(%#q) = %q, %v want %q, nil", tt.in, out, err, tt.out)
- }
- }
-
- // run the quote tests too, backward
- for _, tt := range quotetests {
- if in, err := Unquote(tt.out); in != tt.in {
- t.Errorf("Unquote(%#q) = %q, %v, want %q, nil", tt.out, in, err, tt.in)
- }
- }
-
- for _, s := range misquoted {
- if out, err := Unquote(s); out != "" || err != ErrSyntax {
- t.Errorf("Unquote(%#q) = %q, %v want %q, %v", s, out, err, "", ErrSyntax)
- }
- }
-}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/token/position.go b/vendor/github.com/hashicorp/hcl/hcl/token/position.go
deleted file mode 100644
index 59c1bb7..0000000
--- a/vendor/github.com/hashicorp/hcl/hcl/token/position.go
+++ /dev/null
@@ -1,46 +0,0 @@
-package token
-
-import "fmt"
-
-// Pos describes an arbitrary source position
-// including the file, line, and column location.
-// A Position is valid if the line number is > 0.
-type Pos struct {
- Filename string // filename, if any
- Offset int // offset, starting at 0
- Line int // line number, starting at 1
- Column int // column number, starting at 1 (character count)
-}
-
-// IsValid returns true if the position is valid.
-func (p *Pos) IsValid() bool { return p.Line > 0 }
-
-// String returns a string in one of several forms:
-//
-// file:line:column valid position with file name
-// line:column valid position without file name
-// file invalid position with file name
-// - invalid position without file name
-func (p Pos) String() string {
- s := p.Filename
- if p.IsValid() {
- if s != "" {
- s += ":"
- }
- s += fmt.Sprintf("%d:%d", p.Line, p.Column)
- }
- if s == "" {
- s = "-"
- }
- return s
-}
-
-// Before reports whether the position p is before u.
-func (p Pos) Before(u Pos) bool {
- return u.Offset > p.Offset || u.Line > p.Line
-}
-
-// After reports whether the position p is after u.
-func (p Pos) After(u Pos) bool {
- return u.Offset < p.Offset || u.Line < p.Line
-}
diff --git a/vendor/github.com/hashicorp/hcl/hcl/token/token.go b/vendor/github.com/hashicorp/hcl/hcl/token/token.go
deleted file mode 100644
index e37c066..0000000
--- a/vendor/github.com/hashicorp/hcl/hcl/token/token.go
+++ /dev/null
@@ -1,219 +0,0 @@
-// Package token defines constants representing the lexical tokens for HCL
-// (HashiCorp Configuration Language)
-package token
-
-import (
- "fmt"
- "strconv"
- "strings"
-
- hclstrconv "github.com/hashicorp/hcl/hcl/strconv"
-)
-
-// Token defines a single HCL token which can be obtained via the Scanner
-type Token struct {
- Type Type
- Pos Pos
- Text string
- JSON bool
-}
-
-// Type is the set of lexical tokens of the HCL (HashiCorp Configuration Language)
-type Type int
-
-const (
- // Special tokens
- ILLEGAL Type = iota
- EOF
- COMMENT
-
- identifier_beg
- IDENT // literals
- literal_beg
- NUMBER // 12345
- FLOAT // 123.45
- BOOL // true,false
- STRING // "abc"
- HEREDOC // < 0 {
- // Pop the current item
- n := len(frontier)
- item := frontier[n-1]
- frontier = frontier[:n-1]
-
- switch v := item.Val.(type) {
- case *ast.ObjectType:
- items, frontier = flattenObjectType(v, item, items, frontier)
- case *ast.ListType:
- items, frontier = flattenListType(v, item, items, frontier)
- default:
- items = append(items, item)
- }
- }
-
- // Reverse the list since the frontier model runs things backwards
- for i := len(items)/2 - 1; i >= 0; i-- {
- opp := len(items) - 1 - i
- items[i], items[opp] = items[opp], items[i]
- }
-
- // Done! Set the original items
- list.Items = items
- return n, true
- })
-}
-
-func flattenListType(
- ot *ast.ListType,
- item *ast.ObjectItem,
- items []*ast.ObjectItem,
- frontier []*ast.ObjectItem) ([]*ast.ObjectItem, []*ast.ObjectItem) {
- // If the list is empty, keep the original list
- if len(ot.List) == 0 {
- items = append(items, item)
- return items, frontier
- }
-
- // All the elements of this object must also be objects!
- for _, subitem := range ot.List {
- if _, ok := subitem.(*ast.ObjectType); !ok {
- items = append(items, item)
- return items, frontier
- }
- }
-
- // Great! We have a match go through all the items and flatten
- for _, elem := range ot.List {
- // Add it to the frontier so that we can recurse
- frontier = append(frontier, &ast.ObjectItem{
- Keys: item.Keys,
- Assign: item.Assign,
- Val: elem,
- LeadComment: item.LeadComment,
- LineComment: item.LineComment,
- })
- }
-
- return items, frontier
-}
-
-func flattenObjectType(
- ot *ast.ObjectType,
- item *ast.ObjectItem,
- items []*ast.ObjectItem,
- frontier []*ast.ObjectItem) ([]*ast.ObjectItem, []*ast.ObjectItem) {
- // If the list has no items we do not have to flatten anything
- if ot.List.Items == nil {
- items = append(items, item)
- return items, frontier
- }
-
- // All the elements of this object must also be objects!
- for _, subitem := range ot.List.Items {
- if _, ok := subitem.Val.(*ast.ObjectType); !ok {
- items = append(items, item)
- return items, frontier
- }
- }
-
- // Great! We have a match go through all the items and flatten
- for _, subitem := range ot.List.Items {
- // Copy the new key
- keys := make([]*ast.ObjectKey, len(item.Keys)+len(subitem.Keys))
- copy(keys, item.Keys)
- copy(keys[len(item.Keys):], subitem.Keys)
-
- // Add it to the frontier so that we can recurse
- frontier = append(frontier, &ast.ObjectItem{
- Keys: keys,
- Assign: item.Assign,
- Val: subitem.Val,
- LeadComment: item.LeadComment,
- LineComment: item.LineComment,
- })
- }
-
- return items, frontier
-}
diff --git a/vendor/github.com/hashicorp/hcl/json/parser/parser.go b/vendor/github.com/hashicorp/hcl/json/parser/parser.go
deleted file mode 100644
index 125a5f0..0000000
--- a/vendor/github.com/hashicorp/hcl/json/parser/parser.go
+++ /dev/null
@@ -1,313 +0,0 @@
-package parser
-
-import (
- "errors"
- "fmt"
-
- "github.com/hashicorp/hcl/hcl/ast"
- hcltoken "github.com/hashicorp/hcl/hcl/token"
- "github.com/hashicorp/hcl/json/scanner"
- "github.com/hashicorp/hcl/json/token"
-)
-
-type Parser struct {
- sc *scanner.Scanner
-
- // Last read token
- tok token.Token
- commaPrev token.Token
-
- enableTrace bool
- indent int
- n int // buffer size (max = 1)
-}
-
-func newParser(src []byte) *Parser {
- return &Parser{
- sc: scanner.New(src),
- }
-}
-
-// Parse returns the fully parsed source and returns the abstract syntax tree.
-func Parse(src []byte) (*ast.File, error) {
- p := newParser(src)
- return p.Parse()
-}
-
-var errEofToken = errors.New("EOF token found")
-
-// Parse returns the fully parsed source and returns the abstract syntax tree.
-func (p *Parser) Parse() (*ast.File, error) {
- f := &ast.File{}
- var err, scerr error
- p.sc.Error = func(pos token.Pos, msg string) {
- scerr = fmt.Errorf("%s: %s", pos, msg)
- }
-
- // The root must be an object in JSON
- object, err := p.object()
- if scerr != nil {
- return nil, scerr
- }
- if err != nil {
- return nil, err
- }
-
- // We make our final node an object list so it is more HCL compatible
- f.Node = object.List
-
- // Flatten it, which finds patterns and turns them into more HCL-like
- // AST trees.
- flattenObjects(f.Node)
-
- return f, nil
-}
-
-func (p *Parser) objectList() (*ast.ObjectList, error) {
- defer un(trace(p, "ParseObjectList"))
- node := &ast.ObjectList{}
-
- for {
- n, err := p.objectItem()
- if err == errEofToken {
- break // we are finished
- }
-
- // we don't return a nil node, because might want to use already
- // collected items.
- if err != nil {
- return node, err
- }
-
- node.Add(n)
-
- // Check for a followup comma. If it isn't a comma, then we're done
- if tok := p.scan(); tok.Type != token.COMMA {
- break
- }
- }
-
- return node, nil
-}
-
-// objectItem parses a single object item
-func (p *Parser) objectItem() (*ast.ObjectItem, error) {
- defer un(trace(p, "ParseObjectItem"))
-
- keys, err := p.objectKey()
- if err != nil {
- return nil, err
- }
-
- o := &ast.ObjectItem{
- Keys: keys,
- }
-
- switch p.tok.Type {
- case token.COLON:
- pos := p.tok.Pos
- o.Assign = hcltoken.Pos{
- Filename: pos.Filename,
- Offset: pos.Offset,
- Line: pos.Line,
- Column: pos.Column,
- }
-
- o.Val, err = p.objectValue()
- if err != nil {
- return nil, err
- }
- }
-
- return o, nil
-}
-
-// objectKey parses an object key and returns a ObjectKey AST
-func (p *Parser) objectKey() ([]*ast.ObjectKey, error) {
- keyCount := 0
- keys := make([]*ast.ObjectKey, 0)
-
- for {
- tok := p.scan()
- switch tok.Type {
- case token.EOF:
- return nil, errEofToken
- case token.STRING:
- keyCount++
- keys = append(keys, &ast.ObjectKey{
- Token: p.tok.HCLToken(),
- })
- case token.COLON:
- // If we have a zero keycount it means that we never got
- // an object key, i.e. `{ :`. This is a syntax error.
- if keyCount == 0 {
- return nil, fmt.Errorf("expected: STRING got: %s", p.tok.Type)
- }
-
- // Done
- return keys, nil
- case token.ILLEGAL:
- return nil, errors.New("illegal")
- default:
- return nil, fmt.Errorf("expected: STRING got: %s", p.tok.Type)
- }
- }
-}
-
-// object parses any type of object, such as number, bool, string, object or
-// list.
-func (p *Parser) objectValue() (ast.Node, error) {
- defer un(trace(p, "ParseObjectValue"))
- tok := p.scan()
-
- switch tok.Type {
- case token.NUMBER, token.FLOAT, token.BOOL, token.NULL, token.STRING:
- return p.literalType()
- case token.LBRACE:
- return p.objectType()
- case token.LBRACK:
- return p.listType()
- case token.EOF:
- return nil, errEofToken
- }
-
- return nil, fmt.Errorf("Expected object value, got unknown token: %+v", tok)
-}
-
-// object parses any type of object, such as number, bool, string, object or
-// list.
-func (p *Parser) object() (*ast.ObjectType, error) {
- defer un(trace(p, "ParseType"))
- tok := p.scan()
-
- switch tok.Type {
- case token.LBRACE:
- return p.objectType()
- case token.EOF:
- return nil, errEofToken
- }
-
- return nil, fmt.Errorf("Expected object, got unknown token: %+v", tok)
-}
-
-// objectType parses an object type and returns a ObjectType AST
-func (p *Parser) objectType() (*ast.ObjectType, error) {
- defer un(trace(p, "ParseObjectType"))
-
- // we assume that the currently scanned token is a LBRACE
- o := &ast.ObjectType{}
-
- l, err := p.objectList()
-
- // if we hit RBRACE, we are good to go (means we parsed all Items), if it's
- // not a RBRACE, it's an syntax error and we just return it.
- if err != nil && p.tok.Type != token.RBRACE {
- return nil, err
- }
-
- o.List = l
- return o, nil
-}
-
-// listType parses a list type and returns a ListType AST
-func (p *Parser) listType() (*ast.ListType, error) {
- defer un(trace(p, "ParseListType"))
-
- // we assume that the currently scanned token is a LBRACK
- l := &ast.ListType{}
-
- for {
- tok := p.scan()
- switch tok.Type {
- case token.NUMBER, token.FLOAT, token.STRING:
- node, err := p.literalType()
- if err != nil {
- return nil, err
- }
-
- l.Add(node)
- case token.COMMA:
- continue
- case token.LBRACE:
- node, err := p.objectType()
- if err != nil {
- return nil, err
- }
-
- l.Add(node)
- case token.BOOL:
- // TODO(arslan) should we support? not supported by HCL yet
- case token.LBRACK:
- // TODO(arslan) should we support nested lists? Even though it's
- // written in README of HCL, it's not a part of the grammar
- // (not defined in parse.y)
- case token.RBRACK:
- // finished
- return l, nil
- default:
- return nil, fmt.Errorf("unexpected token while parsing list: %s", tok.Type)
- }
-
- }
-}
-
-// literalType parses a literal type and returns a LiteralType AST
-func (p *Parser) literalType() (*ast.LiteralType, error) {
- defer un(trace(p, "ParseLiteral"))
-
- return &ast.LiteralType{
- Token: p.tok.HCLToken(),
- }, nil
-}
-
-// scan returns the next token from the underlying scanner. If a token has
-// been unscanned then read that instead.
-func (p *Parser) scan() token.Token {
- // If we have a token on the buffer, then return it.
- if p.n != 0 {
- p.n = 0
- return p.tok
- }
-
- p.tok = p.sc.Scan()
- return p.tok
-}
-
-// unscan pushes the previously read token back onto the buffer.
-func (p *Parser) unscan() {
- p.n = 1
-}
-
-// ----------------------------------------------------------------------------
-// Parsing support
-
-func (p *Parser) printTrace(a ...interface{}) {
- if !p.enableTrace {
- return
- }
-
- const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
- const n = len(dots)
- fmt.Printf("%5d:%3d: ", p.tok.Pos.Line, p.tok.Pos.Column)
-
- i := 2 * p.indent
- for i > n {
- fmt.Print(dots)
- i -= n
- }
- // i <= n
- fmt.Print(dots[0:i])
- fmt.Println(a...)
-}
-
-func trace(p *Parser, msg string) *Parser {
- p.printTrace(msg, "(")
- p.indent++
- return p
-}
-
-// Usage pattern: defer un(trace(p, "..."))
-func un(p *Parser) {
- p.indent--
- p.printTrace(")")
-}
diff --git a/vendor/github.com/hashicorp/hcl/json/parser/parser_test.go b/vendor/github.com/hashicorp/hcl/json/parser/parser_test.go
deleted file mode 100644
index e0cebf5..0000000
--- a/vendor/github.com/hashicorp/hcl/json/parser/parser_test.go
+++ /dev/null
@@ -1,384 +0,0 @@
-package parser
-
-import (
- "fmt"
- "io/ioutil"
- "path/filepath"
- "reflect"
- "runtime"
- "testing"
-
- "github.com/hashicorp/hcl/hcl/ast"
- "github.com/hashicorp/hcl/hcl/token"
-)
-
-func TestType(t *testing.T) {
- var literals = []struct {
- typ token.Type
- src string
- }{
- {token.STRING, `"foo": "bar"`},
- {token.NUMBER, `"foo": 123`},
- {token.FLOAT, `"foo": 123.12`},
- {token.FLOAT, `"foo": -123.12`},
- {token.BOOL, `"foo": true`},
- {token.STRING, `"foo": null`},
- }
-
- for _, l := range literals {
- t.Logf("Testing: %s", l.src)
-
- p := newParser([]byte(l.src))
- item, err := p.objectItem()
- if err != nil {
- t.Error(err)
- }
-
- lit, ok := item.Val.(*ast.LiteralType)
- if !ok {
- t.Errorf("node should be of type LiteralType, got: %T", item.Val)
- }
-
- if lit.Token.Type != l.typ {
- t.Errorf("want: %s, got: %s", l.typ, lit.Token.Type)
- }
- }
-}
-
-func TestListType(t *testing.T) {
- var literals = []struct {
- src string
- tokens []token.Type
- }{
- {
- `"foo": ["123", 123]`,
- []token.Type{token.STRING, token.NUMBER},
- },
- {
- `"foo": [123, "123",]`,
- []token.Type{token.NUMBER, token.STRING},
- },
- {
- `"foo": []`,
- []token.Type{},
- },
- {
- `"foo": ["123", 123]`,
- []token.Type{token.STRING, token.NUMBER},
- },
- {
- `"foo": ["123", {}]`,
- []token.Type{token.STRING, token.LBRACE},
- },
- }
-
- for _, l := range literals {
- t.Logf("Testing: %s", l.src)
-
- p := newParser([]byte(l.src))
- item, err := p.objectItem()
- if err != nil {
- t.Error(err)
- }
-
- list, ok := item.Val.(*ast.ListType)
- if !ok {
- t.Errorf("node should be of type LiteralType, got: %T", item.Val)
- }
-
- tokens := []token.Type{}
- for _, li := range list.List {
- switch v := li.(type) {
- case *ast.LiteralType:
- tokens = append(tokens, v.Token.Type)
- case *ast.ObjectType:
- tokens = append(tokens, token.LBRACE)
- }
- }
-
- equals(t, l.tokens, tokens)
- }
-}
-
-func TestObjectType(t *testing.T) {
- var literals = []struct {
- src string
- nodeType []ast.Node
- itemLen int
- }{
- {
- `"foo": {}`,
- nil,
- 0,
- },
- {
- `"foo": {
- "bar": "fatih"
- }`,
- []ast.Node{&ast.LiteralType{}},
- 1,
- },
- {
- `"foo": {
- "bar": "fatih",
- "baz": ["arslan"]
- }`,
- []ast.Node{
- &ast.LiteralType{},
- &ast.ListType{},
- },
- 2,
- },
- {
- `"foo": {
- "bar": {}
- }`,
- []ast.Node{
- &ast.ObjectType{},
- },
- 1,
- },
- {
- `"foo": {
- "bar": {},
- "foo": true
- }`,
- []ast.Node{
- &ast.ObjectType{},
- &ast.LiteralType{},
- },
- 2,
- },
- }
-
- for _, l := range literals {
- t.Logf("Testing:\n%s\n", l.src)
-
- p := newParser([]byte(l.src))
- // p.enableTrace = true
- item, err := p.objectItem()
- if err != nil {
- t.Error(err)
- }
-
- // we know that the ObjectKey name is foo for all cases, what matters
- // is the object
- obj, ok := item.Val.(*ast.ObjectType)
- if !ok {
- t.Errorf("node should be of type LiteralType, got: %T", item.Val)
- }
-
- // check if the total length of items are correct
- equals(t, l.itemLen, len(obj.List.Items))
-
- // check if the types are correct
- for i, item := range obj.List.Items {
- equals(t, reflect.TypeOf(l.nodeType[i]), reflect.TypeOf(item.Val))
- }
- }
-}
-
-func TestFlattenObjects(t *testing.T) {
- var literals = []struct {
- src string
- nodeType []ast.Node
- itemLen int
- }{
- {
- `{
- "foo": [
- {
- "foo": "svh",
- "bar": "fatih"
- }
- ]
- }`,
- []ast.Node{
- &ast.ObjectType{},
- &ast.LiteralType{},
- &ast.LiteralType{},
- },
- 3,
- },
- {
- `{
- "variable": {
- "foo": {}
- }
- }`,
- []ast.Node{
- &ast.ObjectType{},
- },
- 1,
- },
- {
- `{
- "empty": []
- }`,
- []ast.Node{
- &ast.ListType{},
- },
- 1,
- },
- {
- `{
- "basic": [1, 2, 3]
- }`,
- []ast.Node{
- &ast.ListType{},
- },
- 1,
- },
- }
-
- for _, l := range literals {
- t.Logf("Testing:\n%s\n", l.src)
-
- f, err := Parse([]byte(l.src))
- if err != nil {
- t.Error(err)
- }
-
- // the first object is always an ObjectList so just assert that one
- // so we can use it as such
- obj, ok := f.Node.(*ast.ObjectList)
- if !ok {
- t.Errorf("node should be *ast.ObjectList, got: %T", f.Node)
- }
-
- // check if the types are correct
- var i int
- for _, item := range obj.Items {
- equals(t, reflect.TypeOf(l.nodeType[i]), reflect.TypeOf(item.Val))
- i++
-
- if obj, ok := item.Val.(*ast.ObjectType); ok {
- for _, item := range obj.List.Items {
- equals(t, reflect.TypeOf(l.nodeType[i]), reflect.TypeOf(item.Val))
- i++
- }
- }
- }
-
- // check if the number of items is correct
- equals(t, l.itemLen, i)
-
- }
-}
-
-func TestObjectKey(t *testing.T) {
- keys := []struct {
- exp []token.Type
- src string
- }{
- {[]token.Type{token.STRING}, `"foo": {}`},
- }
-
- for _, k := range keys {
- p := newParser([]byte(k.src))
- keys, err := p.objectKey()
- if err != nil {
- t.Fatal(err)
- }
-
- tokens := []token.Type{}
- for _, o := range keys {
- tokens = append(tokens, o.Token.Type)
- }
-
- equals(t, k.exp, tokens)
- }
-
- errKeys := []struct {
- src string
- }{
- {`foo 12 {}`},
- {`foo bar = {}`},
- {`foo []`},
- {`12 {}`},
- }
-
- for _, k := range errKeys {
- p := newParser([]byte(k.src))
- _, err := p.objectKey()
- if err == nil {
- t.Errorf("case '%s' should give an error", k.src)
- }
- }
-}
-
-// Official HCL tests
-func TestParse(t *testing.T) {
- cases := []struct {
- Name string
- Err bool
- }{
- {
- "array.json",
- false,
- },
- {
- "basic.json",
- false,
- },
- {
- "object.json",
- false,
- },
- {
- "types.json",
- false,
- },
- {
- "bad_input_128.json",
- true,
- },
- {
- "bad_input_tf_8110.json",
- true,
- },
- {
- "good_input_tf_8110.json",
- false,
- },
- }
-
- const fixtureDir = "./test-fixtures"
-
- for _, tc := range cases {
- d, err := ioutil.ReadFile(filepath.Join(fixtureDir, tc.Name))
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- _, err = Parse(d)
- if (err != nil) != tc.Err {
- t.Fatalf("Input: %s\n\nError: %s", tc.Name, err)
- }
- }
-}
-
-func TestParse_inline(t *testing.T) {
- cases := []struct {
- Value string
- Err bool
- }{
- {"{:{", true},
- }
-
- for _, tc := range cases {
- _, err := Parse([]byte(tc.Value))
- if (err != nil) != tc.Err {
- t.Fatalf("Input: %q\n\nError: %s", tc.Value, err)
- }
- }
-}
-
-// equals fails the test if exp is not equal to act.
-func equals(tb testing.TB, exp, act interface{}) {
- if !reflect.DeepEqual(exp, act) {
- _, file, line, _ := runtime.Caller(1)
- fmt.Printf("\033[31m%s:%d:\n\n\texp: %s\n\n\tgot: %s\033[39m\n\n", filepath.Base(file), line, exp, act)
- tb.FailNow()
- }
-}
diff --git a/vendor/github.com/hashicorp/hcl/json/scanner/scanner.go b/vendor/github.com/hashicorp/hcl/json/scanner/scanner.go
deleted file mode 100644
index fe3f0f0..0000000
--- a/vendor/github.com/hashicorp/hcl/json/scanner/scanner.go
+++ /dev/null
@@ -1,451 +0,0 @@
-package scanner
-
-import (
- "bytes"
- "fmt"
- "os"
- "unicode"
- "unicode/utf8"
-
- "github.com/hashicorp/hcl/json/token"
-)
-
-// eof represents a marker rune for the end of the reader.
-const eof = rune(0)
-
-// Scanner defines a lexical scanner
-type Scanner struct {
- buf *bytes.Buffer // Source buffer for advancing and scanning
- src []byte // Source buffer for immutable access
-
- // Source Position
- srcPos token.Pos // current position
- prevPos token.Pos // previous position, used for peek() method
-
- lastCharLen int // length of last character in bytes
- lastLineLen int // length of last line in characters (for correct column reporting)
-
- tokStart int // token text start position
- tokEnd int // token text end position
-
- // Error is called for each error encountered. If no Error
- // function is set, the error is reported to os.Stderr.
- Error func(pos token.Pos, msg string)
-
- // ErrorCount is incremented by one for each error encountered.
- ErrorCount int
-
- // tokPos is the start position of most recently scanned token; set by
- // Scan. The Filename field is always left untouched by the Scanner. If
- // an error is reported (via Error) and Position is invalid, the scanner is
- // not inside a token.
- tokPos token.Pos
-}
-
-// New creates and initializes a new instance of Scanner using src as
-// its source content.
-func New(src []byte) *Scanner {
- // even though we accept a src, we read from a io.Reader compatible type
- // (*bytes.Buffer). So in the future we might easily change it to streaming
- // read.
- b := bytes.NewBuffer(src)
- s := &Scanner{
- buf: b,
- src: src,
- }
-
- // srcPosition always starts with 1
- s.srcPos.Line = 1
- return s
-}
-
-// next reads the next rune from the bufferred reader. Returns the rune(0) if
-// an error occurs (or io.EOF is returned).
-func (s *Scanner) next() rune {
- ch, size, err := s.buf.ReadRune()
- if err != nil {
- // advance for error reporting
- s.srcPos.Column++
- s.srcPos.Offset += size
- s.lastCharLen = size
- return eof
- }
-
- if ch == utf8.RuneError && size == 1 {
- s.srcPos.Column++
- s.srcPos.Offset += size
- s.lastCharLen = size
- s.err("illegal UTF-8 encoding")
- return ch
- }
-
- // remember last position
- s.prevPos = s.srcPos
-
- s.srcPos.Column++
- s.lastCharLen = size
- s.srcPos.Offset += size
-
- if ch == '\n' {
- s.srcPos.Line++
- s.lastLineLen = s.srcPos.Column
- s.srcPos.Column = 0
- }
-
- // debug
- // fmt.Printf("ch: %q, offset:column: %d:%d\n", ch, s.srcPos.Offset, s.srcPos.Column)
- return ch
-}
-
-// unread unreads the previous read Rune and updates the source position
-func (s *Scanner) unread() {
- if err := s.buf.UnreadRune(); err != nil {
- panic(err) // this is user fault, we should catch it
- }
- s.srcPos = s.prevPos // put back last position
-}
-
-// peek returns the next rune without advancing the reader.
-func (s *Scanner) peek() rune {
- peek, _, err := s.buf.ReadRune()
- if err != nil {
- return eof
- }
-
- s.buf.UnreadRune()
- return peek
-}
-
-// Scan scans the next token and returns the token.
-func (s *Scanner) Scan() token.Token {
- ch := s.next()
-
- // skip white space
- for isWhitespace(ch) {
- ch = s.next()
- }
-
- var tok token.Type
-
- // token text markings
- s.tokStart = s.srcPos.Offset - s.lastCharLen
-
- // token position, initial next() is moving the offset by one(size of rune
- // actually), though we are interested with the starting point
- s.tokPos.Offset = s.srcPos.Offset - s.lastCharLen
- if s.srcPos.Column > 0 {
- // common case: last character was not a '\n'
- s.tokPos.Line = s.srcPos.Line
- s.tokPos.Column = s.srcPos.Column
- } else {
- // last character was a '\n'
- // (we cannot be at the beginning of the source
- // since we have called next() at least once)
- s.tokPos.Line = s.srcPos.Line - 1
- s.tokPos.Column = s.lastLineLen
- }
-
- switch {
- case isLetter(ch):
- lit := s.scanIdentifier()
- if lit == "true" || lit == "false" {
- tok = token.BOOL
- } else if lit == "null" {
- tok = token.NULL
- } else {
- s.err("illegal char")
- }
- case isDecimal(ch):
- tok = s.scanNumber(ch)
- default:
- switch ch {
- case eof:
- tok = token.EOF
- case '"':
- tok = token.STRING
- s.scanString()
- case '.':
- tok = token.PERIOD
- ch = s.peek()
- if isDecimal(ch) {
- tok = token.FLOAT
- ch = s.scanMantissa(ch)
- ch = s.scanExponent(ch)
- }
- case '[':
- tok = token.LBRACK
- case ']':
- tok = token.RBRACK
- case '{':
- tok = token.LBRACE
- case '}':
- tok = token.RBRACE
- case ',':
- tok = token.COMMA
- case ':':
- tok = token.COLON
- case '-':
- if isDecimal(s.peek()) {
- ch := s.next()
- tok = s.scanNumber(ch)
- } else {
- s.err("illegal char")
- }
- default:
- s.err("illegal char: " + string(ch))
- }
- }
-
- // finish token ending
- s.tokEnd = s.srcPos.Offset
-
- // create token literal
- var tokenText string
- if s.tokStart >= 0 {
- tokenText = string(s.src[s.tokStart:s.tokEnd])
- }
- s.tokStart = s.tokEnd // ensure idempotency of tokenText() call
-
- return token.Token{
- Type: tok,
- Pos: s.tokPos,
- Text: tokenText,
- }
-}
-
-// scanNumber scans a HCL number definition starting with the given rune
-func (s *Scanner) scanNumber(ch rune) token.Type {
- zero := ch == '0'
- pos := s.srcPos
-
- s.scanMantissa(ch)
- ch = s.next() // seek forward
- if ch == 'e' || ch == 'E' {
- ch = s.scanExponent(ch)
- return token.FLOAT
- }
-
- if ch == '.' {
- ch = s.scanFraction(ch)
- if ch == 'e' || ch == 'E' {
- ch = s.next()
- ch = s.scanExponent(ch)
- }
- return token.FLOAT
- }
-
- if ch != eof {
- s.unread()
- }
-
- // If we have a larger number and this is zero, error
- if zero && pos != s.srcPos {
- s.err("numbers cannot start with 0")
- }
-
- return token.NUMBER
-}
-
-// scanMantissa scans the mantissa beginning from the rune. It returns the next
-// non decimal rune. It's used to determine wheter it's a fraction or exponent.
-func (s *Scanner) scanMantissa(ch rune) rune {
- scanned := false
- for isDecimal(ch) {
- ch = s.next()
- scanned = true
- }
-
- if scanned && ch != eof {
- s.unread()
- }
- return ch
-}
-
-// scanFraction scans the fraction after the '.' rune
-func (s *Scanner) scanFraction(ch rune) rune {
- if ch == '.' {
- ch = s.peek() // we peek just to see if we can move forward
- ch = s.scanMantissa(ch)
- }
- return ch
-}
-
-// scanExponent scans the remaining parts of an exponent after the 'e' or 'E'
-// rune.
-func (s *Scanner) scanExponent(ch rune) rune {
- if ch == 'e' || ch == 'E' {
- ch = s.next()
- if ch == '-' || ch == '+' {
- ch = s.next()
- }
- ch = s.scanMantissa(ch)
- }
- return ch
-}
-
-// scanString scans a quoted string
-func (s *Scanner) scanString() {
- braces := 0
- for {
- // '"' opening already consumed
- // read character after quote
- ch := s.next()
-
- if ch == '\n' || ch < 0 || ch == eof {
- s.err("literal not terminated")
- return
- }
-
- if ch == '"' {
- break
- }
-
- // If we're going into a ${} then we can ignore quotes for awhile
- if braces == 0 && ch == '$' && s.peek() == '{' {
- braces++
- s.next()
- } else if braces > 0 && ch == '{' {
- braces++
- }
- if braces > 0 && ch == '}' {
- braces--
- }
-
- if ch == '\\' {
- s.scanEscape()
- }
- }
-
- return
-}
-
-// scanEscape scans an escape sequence
-func (s *Scanner) scanEscape() rune {
- // http://en.cppreference.com/w/cpp/language/escape
- ch := s.next() // read character after '/'
- switch ch {
- case 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', '"':
- // nothing to do
- case '0', '1', '2', '3', '4', '5', '6', '7':
- // octal notation
- ch = s.scanDigits(ch, 8, 3)
- case 'x':
- // hexademical notation
- ch = s.scanDigits(s.next(), 16, 2)
- case 'u':
- // universal character name
- ch = s.scanDigits(s.next(), 16, 4)
- case 'U':
- // universal character name
- ch = s.scanDigits(s.next(), 16, 8)
- default:
- s.err("illegal char escape")
- }
- return ch
-}
-
-// scanDigits scans a rune with the given base for n times. For example an
-// octal notation \184 would yield in scanDigits(ch, 8, 3)
-func (s *Scanner) scanDigits(ch rune, base, n int) rune {
- for n > 0 && digitVal(ch) < base {
- ch = s.next()
- n--
- }
- if n > 0 {
- s.err("illegal char escape")
- }
-
- // we scanned all digits, put the last non digit char back
- s.unread()
- return ch
-}
-
-// scanIdentifier scans an identifier and returns the literal string
-func (s *Scanner) scanIdentifier() string {
- offs := s.srcPos.Offset - s.lastCharLen
- ch := s.next()
- for isLetter(ch) || isDigit(ch) || ch == '-' {
- ch = s.next()
- }
-
- if ch != eof {
- s.unread() // we got identifier, put back latest char
- }
-
- return string(s.src[offs:s.srcPos.Offset])
-}
-
-// recentPosition returns the position of the character immediately after the
-// character or token returned by the last call to Scan.
-func (s *Scanner) recentPosition() (pos token.Pos) {
- pos.Offset = s.srcPos.Offset - s.lastCharLen
- switch {
- case s.srcPos.Column > 0:
- // common case: last character was not a '\n'
- pos.Line = s.srcPos.Line
- pos.Column = s.srcPos.Column
- case s.lastLineLen > 0:
- // last character was a '\n'
- // (we cannot be at the beginning of the source
- // since we have called next() at least once)
- pos.Line = s.srcPos.Line - 1
- pos.Column = s.lastLineLen
- default:
- // at the beginning of the source
- pos.Line = 1
- pos.Column = 1
- }
- return
-}
-
-// err prints the error of any scanning to s.Error function. If the function is
-// not defined, by default it prints them to os.Stderr
-func (s *Scanner) err(msg string) {
- s.ErrorCount++
- pos := s.recentPosition()
-
- if s.Error != nil {
- s.Error(pos, msg)
- return
- }
-
- fmt.Fprintf(os.Stderr, "%s: %s\n", pos, msg)
-}
-
-// isHexadecimal returns true if the given rune is a letter
-func isLetter(ch rune) bool {
- return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch)
-}
-
-// isHexadecimal returns true if the given rune is a decimal digit
-func isDigit(ch rune) bool {
- return '0' <= ch && ch <= '9' || ch >= 0x80 && unicode.IsDigit(ch)
-}
-
-// isHexadecimal returns true if the given rune is a decimal number
-func isDecimal(ch rune) bool {
- return '0' <= ch && ch <= '9'
-}
-
-// isHexadecimal returns true if the given rune is an hexadecimal number
-func isHexadecimal(ch rune) bool {
- return '0' <= ch && ch <= '9' || 'a' <= ch && ch <= 'f' || 'A' <= ch && ch <= 'F'
-}
-
-// isWhitespace returns true if the rune is a space, tab, newline or carriage return
-func isWhitespace(ch rune) bool {
- return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'
-}
-
-// digitVal returns the integer value of a given octal,decimal or hexadecimal rune
-func digitVal(ch rune) int {
- switch {
- case '0' <= ch && ch <= '9':
- return int(ch - '0')
- case 'a' <= ch && ch <= 'f':
- return int(ch - 'a' + 10)
- case 'A' <= ch && ch <= 'F':
- return int(ch - 'A' + 10)
- }
- return 16 // larger than any legal digit val
-}
diff --git a/vendor/github.com/hashicorp/hcl/json/scanner/scanner_test.go b/vendor/github.com/hashicorp/hcl/json/scanner/scanner_test.go
deleted file mode 100644
index 3033a57..0000000
--- a/vendor/github.com/hashicorp/hcl/json/scanner/scanner_test.go
+++ /dev/null
@@ -1,362 +0,0 @@
-package scanner
-
-import (
- "bytes"
- "fmt"
- "testing"
-
- "github.com/hashicorp/hcl/json/token"
-)
-
-var f100 = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
-
-type tokenPair struct {
- tok token.Type
- text string
-}
-
-var tokenLists = map[string][]tokenPair{
- "operator": []tokenPair{
- {token.LBRACK, "["},
- {token.LBRACE, "{"},
- {token.COMMA, ","},
- {token.PERIOD, "."},
- {token.RBRACK, "]"},
- {token.RBRACE, "}"},
- },
- "bool": []tokenPair{
- {token.BOOL, "true"},
- {token.BOOL, "false"},
- },
- "string": []tokenPair{
- {token.STRING, `" "`},
- {token.STRING, `"a"`},
- {token.STRING, `"本"`},
- {token.STRING, `"${file(\"foo\")}"`},
- {token.STRING, `"\a"`},
- {token.STRING, `"\b"`},
- {token.STRING, `"\f"`},
- {token.STRING, `"\n"`},
- {token.STRING, `"\r"`},
- {token.STRING, `"\t"`},
- {token.STRING, `"\v"`},
- {token.STRING, `"\""`},
- {token.STRING, `"\000"`},
- {token.STRING, `"\777"`},
- {token.STRING, `"\x00"`},
- {token.STRING, `"\xff"`},
- {token.STRING, `"\u0000"`},
- {token.STRING, `"\ufA16"`},
- {token.STRING, `"\U00000000"`},
- {token.STRING, `"\U0000ffAB"`},
- {token.STRING, `"` + f100 + `"`},
- },
- "number": []tokenPair{
- {token.NUMBER, "0"},
- {token.NUMBER, "1"},
- {token.NUMBER, "9"},
- {token.NUMBER, "42"},
- {token.NUMBER, "1234567890"},
- {token.NUMBER, "-0"},
- {token.NUMBER, "-1"},
- {token.NUMBER, "-9"},
- {token.NUMBER, "-42"},
- {token.NUMBER, "-1234567890"},
- },
- "float": []tokenPair{
- {token.FLOAT, "0."},
- {token.FLOAT, "1."},
- {token.FLOAT, "42."},
- {token.FLOAT, "01234567890."},
- {token.FLOAT, ".0"},
- {token.FLOAT, ".1"},
- {token.FLOAT, ".42"},
- {token.FLOAT, ".0123456789"},
- {token.FLOAT, "0.0"},
- {token.FLOAT, "1.0"},
- {token.FLOAT, "42.0"},
- {token.FLOAT, "01234567890.0"},
- {token.FLOAT, "0e0"},
- {token.FLOAT, "1e0"},
- {token.FLOAT, "42e0"},
- {token.FLOAT, "01234567890e0"},
- {token.FLOAT, "0E0"},
- {token.FLOAT, "1E0"},
- {token.FLOAT, "42E0"},
- {token.FLOAT, "01234567890E0"},
- {token.FLOAT, "0e+10"},
- {token.FLOAT, "1e-10"},
- {token.FLOAT, "42e+10"},
- {token.FLOAT, "01234567890e-10"},
- {token.FLOAT, "0E+10"},
- {token.FLOAT, "1E-10"},
- {token.FLOAT, "42E+10"},
- {token.FLOAT, "01234567890E-10"},
- {token.FLOAT, "01.8e0"},
- {token.FLOAT, "1.4e0"},
- {token.FLOAT, "42.2e0"},
- {token.FLOAT, "01234567890.12e0"},
- {token.FLOAT, "0.E0"},
- {token.FLOAT, "1.12E0"},
- {token.FLOAT, "42.123E0"},
- {token.FLOAT, "01234567890.213E0"},
- {token.FLOAT, "0.2e+10"},
- {token.FLOAT, "1.2e-10"},
- {token.FLOAT, "42.54e+10"},
- {token.FLOAT, "01234567890.98e-10"},
- {token.FLOAT, "0.1E+10"},
- {token.FLOAT, "1.1E-10"},
- {token.FLOAT, "42.1E+10"},
- {token.FLOAT, "01234567890.1E-10"},
- {token.FLOAT, "-0.0"},
- {token.FLOAT, "-1.0"},
- {token.FLOAT, "-42.0"},
- {token.FLOAT, "-01234567890.0"},
- {token.FLOAT, "-0e0"},
- {token.FLOAT, "-1e0"},
- {token.FLOAT, "-42e0"},
- {token.FLOAT, "-01234567890e0"},
- {token.FLOAT, "-0E0"},
- {token.FLOAT, "-1E0"},
- {token.FLOAT, "-42E0"},
- {token.FLOAT, "-01234567890E0"},
- {token.FLOAT, "-0e+10"},
- {token.FLOAT, "-1e-10"},
- {token.FLOAT, "-42e+10"},
- {token.FLOAT, "-01234567890e-10"},
- {token.FLOAT, "-0E+10"},
- {token.FLOAT, "-1E-10"},
- {token.FLOAT, "-42E+10"},
- {token.FLOAT, "-01234567890E-10"},
- {token.FLOAT, "-01.8e0"},
- {token.FLOAT, "-1.4e0"},
- {token.FLOAT, "-42.2e0"},
- {token.FLOAT, "-01234567890.12e0"},
- {token.FLOAT, "-0.E0"},
- {token.FLOAT, "-1.12E0"},
- {token.FLOAT, "-42.123E0"},
- {token.FLOAT, "-01234567890.213E0"},
- {token.FLOAT, "-0.2e+10"},
- {token.FLOAT, "-1.2e-10"},
- {token.FLOAT, "-42.54e+10"},
- {token.FLOAT, "-01234567890.98e-10"},
- {token.FLOAT, "-0.1E+10"},
- {token.FLOAT, "-1.1E-10"},
- {token.FLOAT, "-42.1E+10"},
- {token.FLOAT, "-01234567890.1E-10"},
- },
-}
-
-var orderedTokenLists = []string{
- "comment",
- "operator",
- "bool",
- "string",
- "number",
- "float",
-}
-
-func TestPosition(t *testing.T) {
- // create artifical source code
- buf := new(bytes.Buffer)
-
- for _, listName := range orderedTokenLists {
- for _, ident := range tokenLists[listName] {
- fmt.Fprintf(buf, "\t\t\t\t%s\n", ident.text)
- }
- }
-
- s := New(buf.Bytes())
-
- pos := token.Pos{"", 4, 1, 5}
- s.Scan()
- for _, listName := range orderedTokenLists {
-
- for _, k := range tokenLists[listName] {
- curPos := s.tokPos
- // fmt.Printf("[%q] s = %+v:%+v\n", k.text, curPos.Offset, curPos.Column)
-
- if curPos.Offset != pos.Offset {
- t.Fatalf("offset = %d, want %d for %q", curPos.Offset, pos.Offset, k.text)
- }
- if curPos.Line != pos.Line {
- t.Fatalf("line = %d, want %d for %q", curPos.Line, pos.Line, k.text)
- }
- if curPos.Column != pos.Column {
- t.Fatalf("column = %d, want %d for %q", curPos.Column, pos.Column, k.text)
- }
- pos.Offset += 4 + len(k.text) + 1 // 4 tabs + token bytes + newline
- pos.Line += countNewlines(k.text) + 1 // each token is on a new line
-
- s.Error = func(pos token.Pos, msg string) {
- t.Errorf("error %q for %q", msg, k.text)
- }
-
- s.Scan()
- }
- }
- // make sure there were no token-internal errors reported by scanner
- if s.ErrorCount != 0 {
- t.Errorf("%d errors", s.ErrorCount)
- }
-}
-
-func TestComment(t *testing.T) {
- testTokenList(t, tokenLists["comment"])
-}
-
-func TestOperator(t *testing.T) {
- testTokenList(t, tokenLists["operator"])
-}
-
-func TestBool(t *testing.T) {
- testTokenList(t, tokenLists["bool"])
-}
-
-func TestIdent(t *testing.T) {
- testTokenList(t, tokenLists["ident"])
-}
-
-func TestString(t *testing.T) {
- testTokenList(t, tokenLists["string"])
-}
-
-func TestNumber(t *testing.T) {
- testTokenList(t, tokenLists["number"])
-}
-
-func TestFloat(t *testing.T) {
- testTokenList(t, tokenLists["float"])
-}
-
-func TestRealExample(t *testing.T) {
- complexReal := `
-{
- "variable": {
- "foo": {
- "default": "bar",
- "description": "bar",
- "depends_on": ["something"]
- }
- }
-}`
-
- literals := []struct {
- tokenType token.Type
- literal string
- }{
- {token.LBRACE, `{`},
- {token.STRING, `"variable"`},
- {token.COLON, `:`},
- {token.LBRACE, `{`},
- {token.STRING, `"foo"`},
- {token.COLON, `:`},
- {token.LBRACE, `{`},
- {token.STRING, `"default"`},
- {token.COLON, `:`},
- {token.STRING, `"bar"`},
- {token.COMMA, `,`},
- {token.STRING, `"description"`},
- {token.COLON, `:`},
- {token.STRING, `"bar"`},
- {token.COMMA, `,`},
- {token.STRING, `"depends_on"`},
- {token.COLON, `:`},
- {token.LBRACK, `[`},
- {token.STRING, `"something"`},
- {token.RBRACK, `]`},
- {token.RBRACE, `}`},
- {token.RBRACE, `}`},
- {token.RBRACE, `}`},
- {token.EOF, ``},
- }
-
- s := New([]byte(complexReal))
- for _, l := range literals {
- tok := s.Scan()
- if l.tokenType != tok.Type {
- t.Errorf("got: %s want %s for %s\n", tok, l.tokenType, tok.String())
- }
-
- if l.literal != tok.Text {
- t.Errorf("got: %s want %s\n", tok, l.literal)
- }
- }
-
-}
-
-func TestError(t *testing.T) {
- testError(t, "\x80", "1:1", "illegal UTF-8 encoding", token.ILLEGAL)
- testError(t, "\xff", "1:1", "illegal UTF-8 encoding", token.ILLEGAL)
-
- testError(t, `"ab`+"\x80", "1:4", "illegal UTF-8 encoding", token.STRING)
- testError(t, `"abc`+"\xff", "1:5", "illegal UTF-8 encoding", token.STRING)
-
- testError(t, `01238`, "1:7", "numbers cannot start with 0", token.NUMBER)
- testError(t, `01238123`, "1:10", "numbers cannot start with 0", token.NUMBER)
- testError(t, `'aa'`, "1:1", "illegal char: '", token.ILLEGAL)
-
- testError(t, `"`, "1:2", "literal not terminated", token.STRING)
- testError(t, `"abc`, "1:5", "literal not terminated", token.STRING)
- testError(t, `"abc`+"\n", "1:5", "literal not terminated", token.STRING)
-}
-
-func testError(t *testing.T, src, pos, msg string, tok token.Type) {
- s := New([]byte(src))
-
- errorCalled := false
- s.Error = func(p token.Pos, m string) {
- if !errorCalled {
- if pos != p.String() {
- t.Errorf("pos = %q, want %q for %q", p, pos, src)
- }
-
- if m != msg {
- t.Errorf("msg = %q, want %q for %q", m, msg, src)
- }
- errorCalled = true
- }
- }
-
- tk := s.Scan()
- if tk.Type != tok {
- t.Errorf("tok = %s, want %s for %q", tk, tok, src)
- }
- if !errorCalled {
- t.Errorf("error handler not called for %q", src)
- }
- if s.ErrorCount == 0 {
- t.Errorf("count = %d, want > 0 for %q", s.ErrorCount, src)
- }
-}
-
-func testTokenList(t *testing.T, tokenList []tokenPair) {
- // create artifical source code
- buf := new(bytes.Buffer)
- for _, ident := range tokenList {
- fmt.Fprintf(buf, "%s\n", ident.text)
- }
-
- s := New(buf.Bytes())
- for _, ident := range tokenList {
- tok := s.Scan()
- if tok.Type != ident.tok {
- t.Errorf("tok = %q want %q for %q\n", tok, ident.tok, ident.text)
- }
-
- if tok.Text != ident.text {
- t.Errorf("text = %q want %q", tok.String(), ident.text)
- }
-
- }
-}
-
-func countNewlines(s string) int {
- n := 0
- for _, ch := range s {
- if ch == '\n' {
- n++
- }
- }
- return n
-}
diff --git a/vendor/github.com/hashicorp/hcl/json/token/position.go b/vendor/github.com/hashicorp/hcl/json/token/position.go
deleted file mode 100644
index 59c1bb7..0000000
--- a/vendor/github.com/hashicorp/hcl/json/token/position.go
+++ /dev/null
@@ -1,46 +0,0 @@
-package token
-
-import "fmt"
-
-// Pos describes an arbitrary source position
-// including the file, line, and column location.
-// A Position is valid if the line number is > 0.
-type Pos struct {
- Filename string // filename, if any
- Offset int // offset, starting at 0
- Line int // line number, starting at 1
- Column int // column number, starting at 1 (character count)
-}
-
-// IsValid returns true if the position is valid.
-func (p *Pos) IsValid() bool { return p.Line > 0 }
-
-// String returns a string in one of several forms:
-//
-// file:line:column valid position with file name
-// line:column valid position without file name
-// file invalid position with file name
-// - invalid position without file name
-func (p Pos) String() string {
- s := p.Filename
- if p.IsValid() {
- if s != "" {
- s += ":"
- }
- s += fmt.Sprintf("%d:%d", p.Line, p.Column)
- }
- if s == "" {
- s = "-"
- }
- return s
-}
-
-// Before reports whether the position p is before u.
-func (p Pos) Before(u Pos) bool {
- return u.Offset > p.Offset || u.Line > p.Line
-}
-
-// After reports whether the position p is after u.
-func (p Pos) After(u Pos) bool {
- return u.Offset < p.Offset || u.Line < p.Line
-}
diff --git a/vendor/github.com/hashicorp/hcl/json/token/token.go b/vendor/github.com/hashicorp/hcl/json/token/token.go
deleted file mode 100644
index 95a0c3e..0000000
--- a/vendor/github.com/hashicorp/hcl/json/token/token.go
+++ /dev/null
@@ -1,118 +0,0 @@
-package token
-
-import (
- "fmt"
- "strconv"
-
- hcltoken "github.com/hashicorp/hcl/hcl/token"
-)
-
-// Token defines a single HCL token which can be obtained via the Scanner
-type Token struct {
- Type Type
- Pos Pos
- Text string
-}
-
-// Type is the set of lexical tokens of the HCL (HashiCorp Configuration Language)
-type Type int
-
-const (
- // Special tokens
- ILLEGAL Type = iota
- EOF
-
- identifier_beg
- literal_beg
- NUMBER // 12345
- FLOAT // 123.45
- BOOL // true,false
- STRING // "abc"
- NULL // null
- literal_end
- identifier_end
-
- operator_beg
- LBRACK // [
- LBRACE // {
- COMMA // ,
- PERIOD // .
- COLON // :
-
- RBRACK // ]
- RBRACE // }
-
- operator_end
-)
-
-var tokens = [...]string{
- ILLEGAL: "ILLEGAL",
-
- EOF: "EOF",
-
- NUMBER: "NUMBER",
- FLOAT: "FLOAT",
- BOOL: "BOOL",
- STRING: "STRING",
- NULL: "NULL",
-
- LBRACK: "LBRACK",
- LBRACE: "LBRACE",
- COMMA: "COMMA",
- PERIOD: "PERIOD",
- COLON: "COLON",
-
- RBRACK: "RBRACK",
- RBRACE: "RBRACE",
-}
-
-// String returns the string corresponding to the token tok.
-func (t Type) String() string {
- s := ""
- if 0 <= t && t < Type(len(tokens)) {
- s = tokens[t]
- }
- if s == "" {
- s = "token(" + strconv.Itoa(int(t)) + ")"
- }
- return s
-}
-
-// IsIdentifier returns true for tokens corresponding to identifiers and basic
-// type literals; it returns false otherwise.
-func (t Type) IsIdentifier() bool { return identifier_beg < t && t < identifier_end }
-
-// IsLiteral returns true for tokens corresponding to basic type literals; it
-// returns false otherwise.
-func (t Type) IsLiteral() bool { return literal_beg < t && t < literal_end }
-
-// IsOperator returns true for tokens corresponding to operators and
-// delimiters; it returns false otherwise.
-func (t Type) IsOperator() bool { return operator_beg < t && t < operator_end }
-
-// String returns the token's literal text. Note that this is only
-// applicable for certain token types, such as token.IDENT,
-// token.STRING, etc..
-func (t Token) String() string {
- return fmt.Sprintf("%s %s %s", t.Pos.String(), t.Type.String(), t.Text)
-}
-
-// HCLToken converts this token to an HCL token.
-//
-// The token type must be a literal type or this will panic.
-func (t Token) HCLToken() hcltoken.Token {
- switch t.Type {
- case BOOL:
- return hcltoken.Token{Type: hcltoken.BOOL, Text: t.Text}
- case FLOAT:
- return hcltoken.Token{Type: hcltoken.FLOAT, Text: t.Text}
- case NULL:
- return hcltoken.Token{Type: hcltoken.STRING, Text: ""}
- case NUMBER:
- return hcltoken.Token{Type: hcltoken.NUMBER, Text: t.Text}
- case STRING:
- return hcltoken.Token{Type: hcltoken.STRING, Text: t.Text, JSON: true}
- default:
- panic(fmt.Sprintf("unimplemented HCLToken for type: %s", t.Type))
- }
-}
diff --git a/vendor/github.com/hashicorp/hcl/json/token/token_test.go b/vendor/github.com/hashicorp/hcl/json/token/token_test.go
deleted file mode 100644
index a83fdd5..0000000
--- a/vendor/github.com/hashicorp/hcl/json/token/token_test.go
+++ /dev/null
@@ -1,34 +0,0 @@
-package token
-
-import (
- "testing"
-)
-
-func TestTypeString(t *testing.T) {
- var tokens = []struct {
- tt Type
- str string
- }{
- {ILLEGAL, "ILLEGAL"},
- {EOF, "EOF"},
- {NUMBER, "NUMBER"},
- {FLOAT, "FLOAT"},
- {BOOL, "BOOL"},
- {STRING, "STRING"},
- {NULL, "NULL"},
- {LBRACK, "LBRACK"},
- {LBRACE, "LBRACE"},
- {COMMA, "COMMA"},
- {PERIOD, "PERIOD"},
- {RBRACK, "RBRACK"},
- {RBRACE, "RBRACE"},
- }
-
- for _, token := range tokens {
- if token.tt.String() != token.str {
- t.Errorf("want: %q got:%q\n", token.str, token.tt)
-
- }
- }
-
-}
diff --git a/vendor/github.com/hashicorp/hcl/lex.go b/vendor/github.com/hashicorp/hcl/lex.go
deleted file mode 100644
index d9993c2..0000000
--- a/vendor/github.com/hashicorp/hcl/lex.go
+++ /dev/null
@@ -1,38 +0,0 @@
-package hcl
-
-import (
- "unicode"
- "unicode/utf8"
-)
-
-type lexModeValue byte
-
-const (
- lexModeUnknown lexModeValue = iota
- lexModeHcl
- lexModeJson
-)
-
-// lexMode returns whether we're going to be parsing in JSON
-// mode or HCL mode.
-func lexMode(v []byte) lexModeValue {
- var (
- r rune
- w int
- offset int
- )
-
- for {
- r, w = utf8.DecodeRune(v[offset:])
- offset += w
- if unicode.IsSpace(r) {
- continue
- }
- if r == '{' {
- return lexModeJson
- }
- break
- }
-
- return lexModeHcl
-}
diff --git a/vendor/github.com/hashicorp/hcl/lex_test.go b/vendor/github.com/hashicorp/hcl/lex_test.go
deleted file mode 100644
index 8062764..0000000
--- a/vendor/github.com/hashicorp/hcl/lex_test.go
+++ /dev/null
@@ -1,37 +0,0 @@
-package hcl
-
-import (
- "testing"
-)
-
-func TestLexMode(t *testing.T) {
- cases := []struct {
- Input string
- Mode lexModeValue
- }{
- {
- "",
- lexModeHcl,
- },
- {
- "foo",
- lexModeHcl,
- },
- {
- "{}",
- lexModeJson,
- },
- {
- " {}",
- lexModeJson,
- },
- }
-
- for i, tc := range cases {
- actual := lexMode([]byte(tc.Input))
-
- if actual != tc.Mode {
- t.Fatalf("%d: %#v", i, actual)
- }
- }
-}
diff --git a/vendor/github.com/hashicorp/hcl/parse.go b/vendor/github.com/hashicorp/hcl/parse.go
deleted file mode 100644
index 1fca53c..0000000
--- a/vendor/github.com/hashicorp/hcl/parse.go
+++ /dev/null
@@ -1,39 +0,0 @@
-package hcl
-
-import (
- "fmt"
-
- "github.com/hashicorp/hcl/hcl/ast"
- hclParser "github.com/hashicorp/hcl/hcl/parser"
- jsonParser "github.com/hashicorp/hcl/json/parser"
-)
-
-// ParseBytes accepts as input byte slice and returns ast tree.
-//
-// Input can be either JSON or HCL
-func ParseBytes(in []byte) (*ast.File, error) {
- return parse(in)
-}
-
-// ParseString accepts input as a string and returns ast tree.
-func ParseString(input string) (*ast.File, error) {
- return parse([]byte(input))
-}
-
-func parse(in []byte) (*ast.File, error) {
- switch lexMode(in) {
- case lexModeHcl:
- return hclParser.Parse(in)
- case lexModeJson:
- return jsonParser.Parse(in)
- }
-
- return nil, fmt.Errorf("unknown config format")
-}
-
-// Parse parses the given input and returns the root object.
-//
-// The input format can be either HCL or JSON.
-func Parse(input string) (*ast.File, error) {
- return parse([]byte(input))
-}
diff --git a/vendor/github.com/inconshreveable/mousetrap/LICENSE b/vendor/github.com/inconshreveable/mousetrap/LICENSE
deleted file mode 100644
index 5f0d1fb..0000000
--- a/vendor/github.com/inconshreveable/mousetrap/LICENSE
+++ /dev/null
@@ -1,13 +0,0 @@
-Copyright 2014 Alan Shreve
-
-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.
diff --git a/vendor/github.com/inconshreveable/mousetrap/README.md b/vendor/github.com/inconshreveable/mousetrap/README.md
deleted file mode 100644
index 7a950d1..0000000
--- a/vendor/github.com/inconshreveable/mousetrap/README.md
+++ /dev/null
@@ -1,23 +0,0 @@
-# mousetrap
-
-mousetrap is a tiny library that answers a single question.
-
-On a Windows machine, was the process invoked by someone double clicking on
-the executable file while browsing in explorer?
-
-### Motivation
-
-Windows developers unfamiliar with command line tools will often "double-click"
-the executable for a tool. Because most CLI tools print the help and then exit
-when invoked without arguments, this is often very frustrating for those users.
-
-mousetrap provides a way to detect these invocations so that you can provide
-more helpful behavior and instructions on how to run the CLI tool. To see what
-this looks like, both from an organizational and a technical perspective, see
-https://inconshreveable.com/09-09-2014/sweat-the-small-stuff/
-
-### The interface
-
-The library exposes a single interface:
-
- func StartedByExplorer() (bool)
diff --git a/vendor/github.com/inconshreveable/mousetrap/trap_others.go b/vendor/github.com/inconshreveable/mousetrap/trap_others.go
deleted file mode 100644
index 9d2d8a4..0000000
--- a/vendor/github.com/inconshreveable/mousetrap/trap_others.go
+++ /dev/null
@@ -1,15 +0,0 @@
-// +build !windows
-
-package mousetrap
-
-// StartedByExplorer returns true if the program was invoked by the user
-// double-clicking on the executable from explorer.exe
-//
-// It is conservative and returns false if any of the internal calls fail.
-// It does not guarantee that the program was run from a terminal. It only can tell you
-// whether it was launched from explorer.exe
-//
-// On non-Windows platforms, it always returns false.
-func StartedByExplorer() bool {
- return false
-}
diff --git a/vendor/github.com/inconshreveable/mousetrap/trap_windows.go b/vendor/github.com/inconshreveable/mousetrap/trap_windows.go
deleted file mode 100644
index 336142a..0000000
--- a/vendor/github.com/inconshreveable/mousetrap/trap_windows.go
+++ /dev/null
@@ -1,98 +0,0 @@
-// +build windows
-// +build !go1.4
-
-package mousetrap
-
-import (
- "fmt"
- "os"
- "syscall"
- "unsafe"
-)
-
-const (
- // defined by the Win32 API
- th32cs_snapprocess uintptr = 0x2
-)
-
-var (
- kernel = syscall.MustLoadDLL("kernel32.dll")
- CreateToolhelp32Snapshot = kernel.MustFindProc("CreateToolhelp32Snapshot")
- Process32First = kernel.MustFindProc("Process32FirstW")
- Process32Next = kernel.MustFindProc("Process32NextW")
-)
-
-// ProcessEntry32 structure defined by the Win32 API
-type processEntry32 struct {
- dwSize uint32
- cntUsage uint32
- th32ProcessID uint32
- th32DefaultHeapID int
- th32ModuleID uint32
- cntThreads uint32
- th32ParentProcessID uint32
- pcPriClassBase int32
- dwFlags uint32
- szExeFile [syscall.MAX_PATH]uint16
-}
-
-func getProcessEntry(pid int) (pe *processEntry32, err error) {
- snapshot, _, e1 := CreateToolhelp32Snapshot.Call(th32cs_snapprocess, uintptr(0))
- if snapshot == uintptr(syscall.InvalidHandle) {
- err = fmt.Errorf("CreateToolhelp32Snapshot: %v", e1)
- return
- }
- defer syscall.CloseHandle(syscall.Handle(snapshot))
-
- var processEntry processEntry32
- processEntry.dwSize = uint32(unsafe.Sizeof(processEntry))
- ok, _, e1 := Process32First.Call(snapshot, uintptr(unsafe.Pointer(&processEntry)))
- if ok == 0 {
- err = fmt.Errorf("Process32First: %v", e1)
- return
- }
-
- for {
- if processEntry.th32ProcessID == uint32(pid) {
- pe = &processEntry
- return
- }
-
- ok, _, e1 = Process32Next.Call(snapshot, uintptr(unsafe.Pointer(&processEntry)))
- if ok == 0 {
- err = fmt.Errorf("Process32Next: %v", e1)
- return
- }
- }
-}
-
-func getppid() (pid int, err error) {
- pe, err := getProcessEntry(os.Getpid())
- if err != nil {
- return
- }
-
- pid = int(pe.th32ParentProcessID)
- return
-}
-
-// StartedByExplorer returns true if the program was invoked by the user double-clicking
-// on the executable from explorer.exe
-//
-// It is conservative and returns false if any of the internal calls fail.
-// It does not guarantee that the program was run from a terminal. It only can tell you
-// whether it was launched from explorer.exe
-func StartedByExplorer() bool {
- ppid, err := getppid()
- if err != nil {
- return false
- }
-
- pe, err := getProcessEntry(ppid)
- if err != nil {
- return false
- }
-
- name := syscall.UTF16ToString(pe.szExeFile[:])
- return name == "explorer.exe"
-}
diff --git a/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go b/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go
deleted file mode 100644
index 9a28e57..0000000
--- a/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go
+++ /dev/null
@@ -1,46 +0,0 @@
-// +build windows
-// +build go1.4
-
-package mousetrap
-
-import (
- "os"
- "syscall"
- "unsafe"
-)
-
-func getProcessEntry(pid int) (*syscall.ProcessEntry32, error) {
- snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0)
- if err != nil {
- return nil, err
- }
- defer syscall.CloseHandle(snapshot)
- var procEntry syscall.ProcessEntry32
- procEntry.Size = uint32(unsafe.Sizeof(procEntry))
- if err = syscall.Process32First(snapshot, &procEntry); err != nil {
- return nil, err
- }
- for {
- if procEntry.ProcessID == uint32(pid) {
- return &procEntry, nil
- }
- err = syscall.Process32Next(snapshot, &procEntry)
- if err != nil {
- return nil, err
- }
- }
-}
-
-// StartedByExplorer returns true if the program was invoked by the user double-clicking
-// on the executable from explorer.exe
-//
-// It is conservative and returns false if any of the internal calls fail.
-// It does not guarantee that the program was run from a terminal. It only can tell you
-// whether it was launched from explorer.exe
-func StartedByExplorer() bool {
- pe, err := getProcessEntry(os.Getppid())
- if err != nil {
- return false
- }
- return "explorer.exe" == syscall.UTF16ToString(pe.ExeFile[:])
-}
diff --git a/vendor/github.com/jaytaylor/html2text/.gitignore b/vendor/github.com/jaytaylor/html2text/.gitignore
deleted file mode 100644
index daf913b..0000000
--- a/vendor/github.com/jaytaylor/html2text/.gitignore
+++ /dev/null
@@ -1,24 +0,0 @@
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-*.exe
-*.test
-*.prof
diff --git a/vendor/github.com/jaytaylor/html2text/.travis.yml b/vendor/github.com/jaytaylor/html2text/.travis.yml
deleted file mode 100644
index 6c7f48e..0000000
--- a/vendor/github.com/jaytaylor/html2text/.travis.yml
+++ /dev/null
@@ -1,14 +0,0 @@
-language: go
-go:
- - tip
- - 1.8
- - 1.7
- - 1.6
- - 1.5
- - 1.4
- - 1.3
- - 1.2
-notifications:
- email:
- on_success: change
- on_failure: always
diff --git a/vendor/github.com/jaytaylor/html2text/LICENSE b/vendor/github.com/jaytaylor/html2text/LICENSE
deleted file mode 100644
index 24dc4ab..0000000
--- a/vendor/github.com/jaytaylor/html2text/LICENSE
+++ /dev/null
@@ -1,22 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2015 Jay Taylor
-
-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.
-
diff --git a/vendor/github.com/jaytaylor/html2text/README.md b/vendor/github.com/jaytaylor/html2text/README.md
deleted file mode 100644
index a7a5e56..0000000
--- a/vendor/github.com/jaytaylor/html2text/README.md
+++ /dev/null
@@ -1,137 +0,0 @@
-# html2text
-
-[](https://godoc.org/github.com/jaytaylor/html2text)
-[](https://travis-ci.org/jaytaylor/html2text)
-[](https://goreportcard.com/report/github.com/jaytaylor/html2text)
-
-### Converts HTML into text
-
-
-## Introduction
-
-Ensure your emails are readable by all!
-
-Turns HTML into raw text, useful for sending fancy HTML emails with a equivalently nicely formatted TXT document as a fallback (e.g. for people who don't allow HTML emails or have other display issues).
-
-html2text is a simple golang package for rendering HTML into plaintext.
-
-There are still lots of improvements to be had, but FWIW this has worked fine for my [basic] HTML-2-text needs.
-
-It requires go 1.x or newer ;)
-
-
-## Download the package
-
-```bash
-go get github.com/jaytaylor/html2text
-```
-
-## Example usage
-
-```go
-package main
-
-import (
- "fmt"
-
- "github.com/jaytaylor/html2text"
-)
-
-func main() {
- inputHTML := `
-
-
- My Mega Service
-
-
-
-
-
-
-
-
-
- Welcome to your new account on my service!
-
-
- Here is some more information:
-
-
-
-
-
-
- Header 1 Header 2
-
-
- Footer 1 Footer 2
-
-
- Row 1 Col 1 Row 1 Col 2
- Row 2 Col 1 Row 2 Col 2
-
-
-
-`
-
- text, err := FromString(inputHTML, Options{PrettyTables: true})
- if err != nil {
- panic(err)
- }
- fmt.Println(text)
-}
-```
-
-Output:
-```
-Mega Service ( http://jaytaylor.com/ )
-
-******************************************
-Welcome to your new account on my service!
-******************************************
-
-Here is some more information:
-
-* Link 1: Example.com ( https://example.com )
-* Link 2: Example2.com ( https://example2.com )
-* Something else
-
-+-------------+-------------+
-| HEADER 1 | HEADER 2 |
-+-------------+-------------+
-| Row 1 Col 1 | Row 1 Col 2 |
-| Row 2 Col 1 | Row 2 Col 2 |
-+-------------+-------------+
-| FOOTER 1 | FOOTER 2 |
-+-------------+-------------+
-```
-
-
-## Unit-tests
-
-Running the unit-tests is straightforward and standard:
-
-```bash
-go test
-```
-
-
-# License
-
-Permissive MIT license.
-
-
-## Contact
-
-You are more than welcome to open issues and send pull requests if you find a bug or want a new feature.
-
-If you appreciate this library please feel free to drop me a line and tell me! It's always nice to hear from people who have benefitted from my work.
-
-Email: jay at (my github username).com
-
-Twitter: [@jtaylor](https://twitter.com/jtaylor)
-
diff --git a/vendor/github.com/jaytaylor/html2text/html2text.go b/vendor/github.com/jaytaylor/html2text/html2text.go
deleted file mode 100644
index baaa460..0000000
--- a/vendor/github.com/jaytaylor/html2text/html2text.go
+++ /dev/null
@@ -1,460 +0,0 @@
-package html2text
-
-import (
- "bytes"
- "io"
- "regexp"
- "strings"
- "unicode"
-
- "github.com/olekukonko/tablewriter"
- "github.com/ssor/bom"
- "golang.org/x/net/html"
- "golang.org/x/net/html/atom"
-)
-
-// Options provide toggles and overrides to control specific rendering behaviors.
-type Options struct {
- PrettyTables bool // Turns on pretty ASCII rendering for table elements.
-}
-
-// FromHTMLNode renders text output from a pre-parsed HTML document.
-func FromHTMLNode(doc *html.Node, o ...Options) (string, error) {
- var options Options
- if len(o) > 0 {
- options = o[0]
- }
-
- ctx := textifyTraverseContext{
- buf: bytes.Buffer{},
- options: options,
- }
- if err := ctx.traverse(doc); err != nil {
- return "", err
- }
-
- text := strings.TrimSpace(newlineRe.ReplaceAllString(
- strings.Replace(ctx.buf.String(), "\n ", "\n", -1), "\n\n"),
- )
- return text, nil
-}
-
-// FromReader renders text output after parsing HTML for the specified
-// io.Reader.
-func FromReader(reader io.Reader, options ...Options) (string, error) {
- newReader, err := bom.NewReaderWithoutBom(reader)
- if err != nil {
- return "", err
- }
- doc, err := html.Parse(newReader)
- if err != nil {
- return "", err
- }
- return FromHTMLNode(doc, options...)
-}
-
-// FromString parses HTML from the input string, then renders the text form.
-func FromString(input string, options ...Options) (string, error) {
- bs := bom.CleanBom([]byte(input))
- text, err := FromReader(bytes.NewReader(bs), options...)
- if err != nil {
- return "", err
- }
- return text, nil
-}
-
-var (
- spacingRe = regexp.MustCompile(`[ \r\n\t]+`)
- newlineRe = regexp.MustCompile(`\n\n+`)
-)
-
-// traverseTableCtx holds text-related context.
-type textifyTraverseContext struct {
- buf bytes.Buffer
-
- prefix string
- tableCtx tableTraverseContext
- options Options
- endsWithSpace bool
- justClosedDiv bool
- blockquoteLevel int
- lineLength int
-}
-
-// tableTraverseContext holds table ASCII-form related context.
-type tableTraverseContext struct {
- header []string
- body [][]string
- footer []string
- tmpRow int
- isInFooter bool
-}
-
-func (tableCtx *tableTraverseContext) init() {
- tableCtx.body = [][]string{}
- tableCtx.header = []string{}
- tableCtx.footer = []string{}
- tableCtx.isInFooter = false
- tableCtx.tmpRow = 0
-}
-
-func (ctx *textifyTraverseContext) handleElement(node *html.Node) error {
- ctx.justClosedDiv = false
-
- switch node.DataAtom {
- case atom.Br:
- return ctx.emit("\n")
-
- case atom.H1, atom.H2, atom.H3:
- subCtx := textifyTraverseContext{}
- if err := subCtx.traverseChildren(node); err != nil {
- return err
- }
-
- str := subCtx.buf.String()
- dividerLen := 0
- for _, line := range strings.Split(str, "\n") {
- if lineLen := len([]rune(line)); lineLen-1 > dividerLen {
- dividerLen = lineLen - 1
- }
- }
- var divider string
- if node.DataAtom == atom.H1 {
- divider = strings.Repeat("*", dividerLen)
- } else {
- divider = strings.Repeat("-", dividerLen)
- }
-
- if node.DataAtom == atom.H3 {
- return ctx.emit("\n\n" + str + "\n" + divider + "\n\n")
- }
- return ctx.emit("\n\n" + divider + "\n" + str + "\n" + divider + "\n\n")
-
- case atom.Blockquote:
- ctx.blockquoteLevel++
- ctx.prefix = strings.Repeat(">", ctx.blockquoteLevel) + " "
- if err := ctx.emit("\n"); err != nil {
- return err
- }
- if ctx.blockquoteLevel == 1 {
- if err := ctx.emit("\n"); err != nil {
- return err
- }
- }
- if err := ctx.traverseChildren(node); err != nil {
- return err
- }
- ctx.blockquoteLevel--
- ctx.prefix = strings.Repeat(">", ctx.blockquoteLevel)
- if ctx.blockquoteLevel > 0 {
- ctx.prefix += " "
- }
- return ctx.emit("\n\n")
-
- case atom.Div:
- if ctx.lineLength > 0 {
- if err := ctx.emit("\n"); err != nil {
- return err
- }
- }
- if err := ctx.traverseChildren(node); err != nil {
- return err
- }
- var err error
- if !ctx.justClosedDiv {
- err = ctx.emit("\n")
- }
- ctx.justClosedDiv = true
- return err
-
- case atom.Li:
- if err := ctx.emit("* "); err != nil {
- return err
- }
-
- if err := ctx.traverseChildren(node); err != nil {
- return err
- }
-
- return ctx.emit("\n")
-
- case atom.B, atom.Strong:
- subCtx := textifyTraverseContext{}
- subCtx.endsWithSpace = true
- if err := subCtx.traverseChildren(node); err != nil {
- return err
- }
- str := subCtx.buf.String()
- return ctx.emit("*" + str + "*")
-
- case atom.A:
- linkText := ""
- // For simple link element content with single text node only, peek at the link text.
- if node.FirstChild != nil && node.FirstChild.NextSibling == nil && node.FirstChild.Type == html.TextNode {
- linkText = node.FirstChild.Data
- }
-
- // If image is the only child, take its alt text as the link text.
- if img := node.FirstChild; img != nil && node.LastChild == img && img.DataAtom == atom.Img {
- if altText := getAttrVal(img, "alt"); altText != "" {
- if err := ctx.emit(altText); err != nil {
- return err
- }
- }
- } else if err := ctx.traverseChildren(node); err != nil {
- return err
- }
-
- hrefLink := ""
- if attrVal := getAttrVal(node, "href"); attrVal != "" {
- attrVal = ctx.normalizeHrefLink(attrVal)
- // Don't print link href if it matches link element content or if the link is empty.
- if attrVal != "" && linkText != attrVal {
- hrefLink = "( " + attrVal + " )"
- }
- }
-
- return ctx.emit(hrefLink)
-
- case atom.P, atom.Ul:
- return ctx.paragraphHandler(node)
-
- case atom.Table, atom.Tfoot, atom.Th, atom.Tr, atom.Td:
- if ctx.options.PrettyTables {
- return ctx.handleTableElement(node)
- } else if node.DataAtom == atom.Table {
- return ctx.paragraphHandler(node)
- }
- return ctx.traverseChildren(node)
-
- case atom.Style, atom.Script, atom.Head:
- // Ignore the subtree.
- return nil
-
- default:
- return ctx.traverseChildren(node)
- }
-}
-
-// paragraphHandler renders node children surrounded by double newlines.
-func (ctx *textifyTraverseContext) paragraphHandler(node *html.Node) error {
- if err := ctx.emit("\n\n"); err != nil {
- return err
- }
- if err := ctx.traverseChildren(node); err != nil {
- return err
- }
- return ctx.emit("\n\n")
-}
-
-// handleTableElement is only to be invoked when options.PrettyTables is active.
-func (ctx *textifyTraverseContext) handleTableElement(node *html.Node) error {
- if !ctx.options.PrettyTables {
- panic("handleTableElement invoked when PrettyTables not active")
- }
-
- switch node.DataAtom {
- case atom.Table:
- if err := ctx.emit("\n\n"); err != nil {
- return err
- }
-
- // Re-intialize all table context.
- ctx.tableCtx.init()
-
- // Browse children, enriching context with table data.
- if err := ctx.traverseChildren(node); err != nil {
- return err
- }
-
- buf := &bytes.Buffer{}
- table := tablewriter.NewWriter(buf)
- table.SetHeader(ctx.tableCtx.header)
- table.SetFooter(ctx.tableCtx.footer)
- table.AppendBulk(ctx.tableCtx.body)
-
- // Render the table using ASCII.
- table.Render()
- if err := ctx.emit(buf.String()); err != nil {
- return err
- }
-
- return ctx.emit("\n\n")
-
- case atom.Tfoot:
- ctx.tableCtx.isInFooter = true
- if err := ctx.traverseChildren(node); err != nil {
- return err
- }
- ctx.tableCtx.isInFooter = false
-
- case atom.Tr:
- ctx.tableCtx.body = append(ctx.tableCtx.body, []string{})
- if err := ctx.traverseChildren(node); err != nil {
- return err
- }
- ctx.tableCtx.tmpRow++
-
- case atom.Th:
- res, err := ctx.renderEachChild(node)
- if err != nil {
- return err
- }
-
- ctx.tableCtx.header = append(ctx.tableCtx.header, res)
-
- case atom.Td:
- res, err := ctx.renderEachChild(node)
- if err != nil {
- return err
- }
-
- if ctx.tableCtx.isInFooter {
- ctx.tableCtx.footer = append(ctx.tableCtx.footer, res)
- } else {
- ctx.tableCtx.body[ctx.tableCtx.tmpRow] = append(ctx.tableCtx.body[ctx.tableCtx.tmpRow], res)
- }
-
- }
- return nil
-}
-
-func (ctx *textifyTraverseContext) traverse(node *html.Node) error {
- switch node.Type {
- default:
- return ctx.traverseChildren(node)
-
- case html.TextNode:
- data := strings.Trim(spacingRe.ReplaceAllString(node.Data, " "), " ")
- return ctx.emit(data)
-
- case html.ElementNode:
- return ctx.handleElement(node)
- }
-}
-
-func (ctx *textifyTraverseContext) traverseChildren(node *html.Node) error {
- for c := node.FirstChild; c != nil; c = c.NextSibling {
- if err := ctx.traverse(c); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func (ctx *textifyTraverseContext) emit(data string) error {
- if data == "" {
- return nil
- }
- var (
- lines = ctx.breakLongLines(data)
- err error
- )
- for _, line := range lines {
- runes := []rune(line)
- startsWithSpace := unicode.IsSpace(runes[0])
- if !startsWithSpace && !ctx.endsWithSpace && !strings.HasPrefix(data, ".") {
- if err = ctx.buf.WriteByte(' '); err != nil {
- return err
- }
- ctx.lineLength++
- }
- ctx.endsWithSpace = unicode.IsSpace(runes[len(runes)-1])
- for _, c := range line {
- if _, err = ctx.buf.WriteString(string(c)); err != nil {
- return err
- }
- ctx.lineLength++
- if c == '\n' {
- ctx.lineLength = 0
- if ctx.prefix != "" {
- if _, err = ctx.buf.WriteString(ctx.prefix); err != nil {
- return err
- }
- }
- }
- }
- }
- return nil
-}
-
-const maxLineLen = 74
-
-func (ctx *textifyTraverseContext) breakLongLines(data string) []string {
- // Only break lines when in blockquotes.
- if ctx.blockquoteLevel == 0 {
- return []string{data}
- }
- var (
- ret = []string{}
- runes = []rune(data)
- l = len(runes)
- existing = ctx.lineLength
- )
- if existing >= maxLineLen {
- ret = append(ret, "\n")
- existing = 0
- }
- for l+existing > maxLineLen {
- i := maxLineLen - existing
- for i >= 0 && !unicode.IsSpace(runes[i]) {
- i--
- }
- if i == -1 {
- // No spaces, so go the other way.
- i = maxLineLen - existing
- for i < l && !unicode.IsSpace(runes[i]) {
- i++
- }
- }
- ret = append(ret, string(runes[:i])+"\n")
- for i < l && unicode.IsSpace(runes[i]) {
- i++
- }
- runes = runes[i:]
- l = len(runes)
- existing = 0
- }
- if len(runes) > 0 {
- ret = append(ret, string(runes))
- }
- return ret
-}
-
-func (ctx *textifyTraverseContext) normalizeHrefLink(link string) string {
- link = strings.TrimSpace(link)
- link = strings.TrimPrefix(link, "mailto:")
- return link
-}
-
-// renderEachChild visits each direct child of a node and collects the sequence of
-// textuual representaitons separated by a single newline.
-func (ctx *textifyTraverseContext) renderEachChild(node *html.Node) (string, error) {
- buf := &bytes.Buffer{}
- for c := node.FirstChild; c != nil; c = c.NextSibling {
- s, err := FromHTMLNode(c, ctx.options)
- if err != nil {
- return "", err
- }
- if _, err = buf.WriteString(s); err != nil {
- return "", err
- }
- if c.NextSibling != nil {
- if err = buf.WriteByte('\n'); err != nil {
- return "", err
- }
- }
- }
- return buf.String(), nil
-}
-
-func getAttrVal(node *html.Node, attrName string) string {
- for _, attr := range node.Attr {
- if attr.Key == attrName {
- return attr.Val
- }
- }
-
- return ""
-}
diff --git a/vendor/github.com/jaytaylor/html2text/html2text_test.go b/vendor/github.com/jaytaylor/html2text/html2text_test.go
deleted file mode 100644
index 410cb22..0000000
--- a/vendor/github.com/jaytaylor/html2text/html2text_test.go
+++ /dev/null
@@ -1,973 +0,0 @@
-package html2text
-
-import (
- "bytes"
- "fmt"
- "io/ioutil"
- "os"
- "path"
- "regexp"
- "strings"
- "testing"
-)
-
-const destPath = "testdata"
-
-// EnableExtraLogging turns on additional testing log output.
-// Extra test logging can be enabled by setting the environment variable
-// HTML2TEXT_EXTRA_LOGGING to "1" or "true".
-var EnableExtraLogging bool
-
-func init() {
- if v := os.Getenv("HTML2TEXT_EXTRA_LOGGING"); v == "1" || v == "true" {
- EnableExtraLogging = true
- }
-}
-
-// TODO Add tests for FromHTMLNode and FromReader.
-
-func TestParseUTF8(t *testing.T) {
- htmlFiles := []struct {
- file string
- keywordShouldNotExist string
- keywordShouldExist string
- }{
- {
- "utf8.html",
- "学习之道:美国公认学习第一书title",
- "次世界冠军赛上,我几近疯狂",
- },
- {
- "utf8_with_bom.xhtml",
- "1892年波兰文版序言title",
- "种新的波兰文本已成为必要",
- },
- }
-
- for _, htmlFile := range htmlFiles {
- bs, err := ioutil.ReadFile(path.Join(destPath, htmlFile.file))
- if err != nil {
- t.Fatal(err)
- }
- text, err := FromReader(bytes.NewReader(bs))
- if err != nil {
- t.Fatal(err)
- }
- if !strings.Contains(text, htmlFile.keywordShouldExist) {
- t.Fatalf("keyword %s should exists in file %s", htmlFile.keywordShouldExist, htmlFile.file)
- }
- if strings.Contains(text, htmlFile.keywordShouldNotExist) {
- t.Fatalf("keyword %s should not exists in file %s", htmlFile.keywordShouldNotExist, htmlFile.file)
- }
- }
-}
-
-func TestStrippingWhitespace(t *testing.T) {
- testCases := []struct {
- input string
- output string
- }{
- {
- "test text",
- "test text",
- },
- {
- " \ttext\ntext\n",
- "text text",
- },
- {
- " \na \n\t \n \n a \t",
- "a a",
- },
- {
- "test text",
- "test text",
- },
- {
- "test text ",
- "test text",
- },
- }
-
- for _, testCase := range testCases {
- if msg, err := wantString(testCase.input, testCase.output); err != nil {
- t.Error(err)
- } else if len(msg) > 0 {
- t.Log(msg)
- }
- }
-}
-
-func TestParagraphsAndBreaks(t *testing.T) {
- testCases := []struct {
- input string
- output string
- }{
- {
- "Test text",
- "Test text",
- },
- {
- "Test text ",
- "Test text",
- },
- {
- "Test text Test",
- "Test text\nTest",
- },
- {
- "Test text
",
- "Test text",
- },
- {
- "Test text
Test text
",
- "Test text\n\nTest text",
- },
- {
- "\nTest text
\n\n\n\tTest text
\n",
- "Test text\n\nTest text",
- },
- {
- "\nTest text Test text
\n",
- "Test text\nTest text",
- },
- {
- "\nTest text \tTest text
\n",
- "Test text\nTest text",
- },
- {
- "Test text Test text",
- "Test text\n\nTest text",
- },
- }
-
- for _, testCase := range testCases {
- if msg, err := wantString(testCase.input, testCase.output); err != nil {
- t.Error(err)
- } else if len(msg) > 0 {
- t.Log(msg)
- }
- }
-}
-
-func TestTables(t *testing.T) {
- testCases := []struct {
- input string
- tabularOutput string
- plaintextOutput string
- }{
- {
- "",
- // Empty table
- // +--+--+
- // | | |
- // +--+--+
- "+--+--+\n| | |\n+--+--+",
- "",
- },
- {
- "",
- // +-------+-------+
- // | cell1 | cell2 |
- // +-------+-------+
- "+-------+-------+\n| cell1 | cell2 |\n+-------+-------+",
- "cell1 cell2",
- },
- {
- "",
- // +------+
- // | row1 |
- // | row2 |
- // +------+
- "+------+\n| row1 |\n| row2 |\n+------+",
- "row1 row2",
- },
- {
- `
-
- Row-1-Col-1-Msg1
Row-1-Col-1-Msg2
Row-1-Col-2
- Row-2-Col-1 Row-2-Col-2
-
-
`,
- // +--------------------------------+-------------+
- // | Row-1-Col-1-Msg1 | Row-1-Col-2 |
- // | Row-1-Col-1-Msg2 | |
- // | Row-2-Col-1 | Row-2-Col-2 |
- // +--------------------------------+-------------+
- `+--------------------------------+-------------+
-| Row-1-Col-1-Msg1 | Row-1-Col-2 |
-| Row-1-Col-1-Msg2 | |
-| Row-2-Col-1 | Row-2-Col-2 |
-+--------------------------------+-------------+`,
- `Row-1-Col-1-Msg1
-
-Row-1-Col-1-Msg2
-
-Row-1-Col-2 Row-2-Col-1 Row-2-Col-2`,
- },
- {
- `
- cell1-1 cell1-2
- cell2-1 cell2-2
-
`,
- // +---------+---------+
- // | cell1-1 | cell1-2 |
- // | cell2-1 | cell2-2 |
- // +---------+---------+
- "+---------+---------+\n| cell1-1 | cell1-2 |\n| cell2-1 | cell2-2 |\n+---------+---------+",
- "cell1-1 cell1-2 cell2-1 cell2-2",
- },
- {
- `
-
- Header 1 Header 2
-
-
- Footer 1 Footer 2
-
-
- Row 1 Col 1 Row 1 Col 2
- Row 2 Col 1 Row 2 Col 2
-
-
`,
- `+-------------+-------------+
-| HEADER 1 | HEADER 2 |
-+-------------+-------------+
-| Row 1 Col 1 | Row 1 Col 2 |
-| Row 2 Col 1 | Row 2 Col 2 |
-+-------------+-------------+
-| FOOTER 1 | FOOTER 2 |
-+-------------+-------------+`,
- "Header 1 Header 2 Footer 1 Footer 2 Row 1 Col 1 Row 1 Col 2 Row 2 Col 1 Row 2 Col 2",
- },
- // Two tables in same HTML (goal is to test that context is
- // reinitalized correctly).
- {
- `
-
-
- Table 1 Header 1 Table 1 Header 2
-
-
- Table 1 Footer 1 Table 1 Footer 2
-
-
- Table 1 Row 1 Col 1 Table 1 Row 1 Col 2
- Table 1 Row 2 Col 1 Table 1 Row 2 Col 2
-
-
-
-
- Table 2 Header 1 Table 2 Header 2
-
-
- Table 2 Footer 1 Table 2 Footer 2
-
-
- Table 2 Row 1 Col 1 Table 2 Row 1 Col 2
- Table 2 Row 2 Col 1 Table 2 Row 2 Col 2
-
-
- `,
- `+---------------------+---------------------+
-| TABLE 1 HEADER 1 | TABLE 1 HEADER 2 |
-+---------------------+---------------------+
-| Table 1 Row 1 Col 1 | Table 1 Row 1 Col 2 |
-| Table 1 Row 2 Col 1 | Table 1 Row 2 Col 2 |
-+---------------------+---------------------+
-| TABLE 1 FOOTER 1 | TABLE 1 FOOTER 2 |
-+---------------------+---------------------+
-
-+---------------------+---------------------+
-| TABLE 2 HEADER 1 | TABLE 2 HEADER 2 |
-+---------------------+---------------------+
-| Table 2 Row 1 Col 1 | Table 2 Row 1 Col 2 |
-| Table 2 Row 2 Col 1 | Table 2 Row 2 Col 2 |
-+---------------------+---------------------+
-| TABLE 2 FOOTER 1 | TABLE 2 FOOTER 2 |
-+---------------------+---------------------+`,
- `Table 1 Header 1 Table 1 Header 2 Table 1 Footer 1 Table 1 Footer 2 Table 1 Row 1 Col 1 Table 1 Row 1 Col 2 Table 1 Row 2 Col 1 Table 1 Row 2 Col 2
-
-Table 2 Header 1 Table 2 Header 2 Table 2 Footer 1 Table 2 Footer 2 Table 2 Row 1 Col 1 Table 2 Row 1 Col 2 Table 2 Row 2 Col 1 Table 2 Row 2 Col 2`,
- },
- {
- "__",
- "_\n\n+------+\n| cell |\n+------+\n\n_",
- "_\n\ncell\n\n_",
- },
- {
- `
-
- Item
- Description
- Price
-
-
- Golang
- Open source programming language that makes it easy to build simple, reliable, and efficient software
- $10.99
-
-
- Hermes
- Programmatically create beautiful e-mails using Golang.
- $1.99
-
-
`,
- `+--------+--------------------------------+--------+
-| ITEM | DESCRIPTION | PRICE |
-+--------+--------------------------------+--------+
-| Golang | Open source programming | $10.99 |
-| | language that makes it easy | |
-| | to build simple, reliable, and | |
-| | efficient software | |
-| Hermes | Programmatically create | $1.99 |
-| | beautiful e-mails using | |
-| | Golang. | |
-+--------+--------------------------------+--------+`,
- "Item Description Price Golang Open source programming language that makes it easy to build simple, reliable, and efficient software $10.99 Hermes Programmatically create beautiful e-mails using Golang. $1.99",
- },
- }
-
- for _, testCase := range testCases {
- options := Options{
- PrettyTables: true,
- }
- // Check pretty tabular ASCII version.
- if msg, err := wantString(testCase.input, testCase.tabularOutput, options); err != nil {
- t.Error(err)
- } else if len(msg) > 0 {
- t.Log(msg)
- }
-
- // Check plain version.
- if msg, err := wantString(testCase.input, testCase.plaintextOutput); err != nil {
- t.Error(err)
- } else if len(msg) > 0 {
- t.Log(msg)
- }
- }
-}
-
-func TestStrippingLists(t *testing.T) {
- testCases := []struct {
- input string
- output string
- }{
- {
- "",
- "",
- },
- {
- "_",
- "* item\n\n_",
- },
- {
- "item 1 item 2 \n_",
- "* item 1\n* item 2\n_",
- },
- {
- "item 1 \t\n item 2 item 3 \n_",
- "* item 1\n* item 2\n* item 3\n_",
- },
- }
-
- for _, testCase := range testCases {
- if msg, err := wantString(testCase.input, testCase.output); err != nil {
- t.Error(err)
- } else if len(msg) > 0 {
- t.Log(msg)
- }
- }
-}
-
-func TestLinks(t *testing.T) {
- testCases := []struct {
- input string
- output string
- }{
- {
- ` `,
- ``,
- },
- {
- ` `,
- ``,
- },
- {
- ` `,
- `( http://example.com/ )`,
- },
- {
- `Link `,
- `Link`,
- },
- {
- `Link `,
- `Link ( http://example.com/ )`,
- },
- {
- `Link `,
- `Link ( http://example.com/ )`,
- },
- {
- "\n\tLink \n\t ",
- `Link ( http://example.com/ )`,
- },
- {
- "Contact Us ",
- `Contact Us ( contact@example.org )`,
- },
- {
- "Link ",
- `Link ( http://example.com:80/~user?aaa=bb&c=d,e,f#foo )`,
- },
- {
- "Link ",
- `Link ( http://example.com/ )`,
- },
- {
- " Link ",
- `Link ( http://example.com/ )`,
- },
- {
- "Link A Link B ",
- `Link A ( http://example.com/a/ ) Link B ( http://example.com/b/ )`,
- },
- {
- "Link ",
- `Link ( %%LINK%% )`,
- },
- {
- "Link ",
- `Link ( [LINK] )`,
- },
- {
- "Link ",
- `Link ( {LINK} )`,
- },
- {
- "Link ",
- `Link ( [[!unsubscribe]] )`,
- },
- {
- "This is link1 and link2 is next.
",
- `This is link1 ( http://www.google.com ) and link2 ( http://www.google.com ) is next.`,
- },
- {
- "http://www.google.com ",
- `http://www.google.com`,
- },
- }
-
- for _, testCase := range testCases {
- if msg, err := wantString(testCase.input, testCase.output); err != nil {
- t.Error(err)
- } else if len(msg) > 0 {
- t.Log(msg)
- }
- }
-}
-
-func TestImageAltTags(t *testing.T) {
- testCases := []struct {
- input string
- output string
- }{
- {
- ` `,
- ``,
- },
- {
- ` `,
- ``,
- },
- {
- ` `,
- ``,
- },
- {
- ` `,
- ``,
- },
- // Images do matter if they are in a link.
- {
- ` `,
- `Example ( http://example.com/ )`,
- },
- {
- ` `,
- `Example ( http://example.com/ )`,
- },
- {
- ` `,
- `Example ( http://example.com/ )`,
- },
- {
- ` `,
- `Example ( http://example.com/ )`,
- },
- }
-
- for _, testCase := range testCases {
- if msg, err := wantString(testCase.input, testCase.output); err != nil {
- t.Error(err)
- } else if len(msg) > 0 {
- t.Log(msg)
- }
- }
-}
-
-func TestHeadings(t *testing.T) {
- testCases := []struct {
- input string
- output string
- }{
- {
- "Test ",
- "****\nTest\n****",
- },
- {
- "\t\nTest ",
- "****\nTest\n****",
- },
- {
- "\t\nTest line 1 Test 2 ",
- "***********\nTest line 1\nTest 2\n***********",
- },
- {
- "Test Test ",
- "****\nTest\n****\n\n****\nTest\n****",
- },
- {
- "Test ",
- "----\nTest\n----",
- },
- {
- "",
- "****************************\nTest ( http://example.com/ )\n****************************",
- },
- {
- " Test ",
- "Test\n----",
- },
- }
-
- for _, testCase := range testCases {
- if msg, err := wantString(testCase.input, testCase.output); err != nil {
- t.Error(err)
- } else if len(msg) > 0 {
- t.Log(msg)
- }
- }
-
-}
-
-func TestBold(t *testing.T) {
- testCases := []struct {
- input string
- output string
- }{
- {
- "Test ",
- "*Test*",
- },
- {
- "\tTest ",
- "*Test*",
- },
- {
- "\tTest line 1 Test 2 ",
- "*Test line 1\nTest 2*",
- },
- {
- "Test Test ",
- "*Test* *Test*",
- },
- }
-
- for _, testCase := range testCases {
- if msg, err := wantString(testCase.input, testCase.output); err != nil {
- t.Error(err)
- } else if len(msg) > 0 {
- t.Log(msg)
- }
- }
-
-}
-
-func TestDiv(t *testing.T) {
- testCases := []struct {
- input string
- output string
- }{
- {
- "Test
",
- "Test",
- },
- {
- "\tTest
",
- "Test",
- },
- {
- "",
- "Test line 1\nTest 2",
- },
- {
- "Test 1Test 2
Test 3
Test 4",
- "Test 1\nTest 2\nTest 3\nTest 4",
- },
- }
-
- for _, testCase := range testCases {
- if msg, err := wantString(testCase.input, testCase.output); err != nil {
- t.Error(err)
- } else if len(msg) > 0 {
- t.Log(msg)
- }
- }
-
-}
-
-func TestBlockquotes(t *testing.T) {
- testCases := []struct {
- input string
- output string
- }{
- {
- "level 0
level 1level 2 level 1 level 0
",
- "level 0\n> \n> level 1\n> \n>> level 2\n> \n> level 1\n\nlevel 0",
- },
- {
- "Test Test",
- "> \n> Test\n\nTest",
- },
- {
- "\t \nTest ",
- "> \n> Test\n>",
- },
- {
- "\t \nTest line 1 Test 2 ",
- "> \n> Test line 1\n> Test 2",
- },
- {
- "Test Test Other Test",
- "> \n> Test\n\n> \n> Test\n\nOther Test",
- },
- {
- "Lorem ipsum Commodo id consectetur pariatur ea occaecat minim aliqua ad sit consequat quis ex commodo Duis incididunt eu mollit consectetur fugiat voluptate dolore in pariatur in commodo occaecat Ut occaecat velit esse labore aute quis commodo non sit dolore officia Excepteur cillum amet cupidatat culpa velit labore ullamco dolore mollit elit in aliqua dolor irure do ",
- "> \n> Lorem ipsum Commodo id consectetur pariatur ea occaecat minim aliqua ad\n> sit consequat quis ex commodo Duis incididunt eu mollit consectetur fugiat\n> voluptate dolore in pariatur in commodo occaecat Ut occaecat velit esse\n> labore aute quis commodo non sit dolore officia Excepteur cillum amet\n> cupidatat culpa velit labore ullamco dolore mollit elit in aliqua dolor\n> irure do",
- },
- {
- "Loremipsum Commodo id consectetur pariatur ea occaecat minim aliqua ad sit consequat quis ex commodo Duis incididunt eu mollit consectetur fugiat voluptate dolore in pariatur in commodo occaecat Ut occaecat velit esse labore aute quis commodo non sit dolore officia Excepteur cillum amet cupidatat culpa velit labore ullamco dolore mollit elit in aliqua dolor irure do ",
- "> \n> Lorem *ipsum* *Commodo* *id* *consectetur* *pariatur* *ea* *occaecat* *minim*\n> *aliqua* *ad* *sit* *consequat* *quis* *ex* *commodo* *Duis* *incididunt* *eu*\n> *mollit* *consectetur* *fugiat* *voluptate* *dolore* *in* *pariatur* *in* *commodo*\n> *occaecat* *Ut* *occaecat* *velit* *esse* *labore* *aute* *quis* *commodo*\n> *non* *sit* *dolore* *officia* *Excepteur* *cillum* *amet* *cupidatat* *culpa*\n> *velit* *labore* *ullamco* *dolore* *mollit* *elit* *in* *aliqua* *dolor* *irure*\n> *do*",
- },
- }
-
- for _, testCase := range testCases {
- if msg, err := wantString(testCase.input, testCase.output); err != nil {
- t.Error(err)
- } else if len(msg) > 0 {
- t.Log(msg)
- }
- }
-
-}
-
-func TestIgnoreStylesScriptsHead(t *testing.T) {
- testCases := []struct {
- input string
- output string
- }{
- {
- "",
- "",
- },
- {
- "",
- "",
- },
- {
- " ",
- "",
- },
- {
- "",
- "",
- },
- {
- "",
- "",
- },
- {
- "",
- "",
- },
- {
- "",
- "",
- },
- {
- "",
- "",
- },
- {
- "",
- "",
- },
- {
- `Title `,
- "",
- },
- }
-
- for _, testCase := range testCases {
- if msg, err := wantString(testCase.input, testCase.output); err != nil {
- t.Error(err)
- } else if len(msg) > 0 {
- t.Log(msg)
- }
- }
-}
-
-func TestText(t *testing.T) {
- testCases := []struct {
- input string
- expr string
- }{
- {
- `
- New repository
- `,
- `\* New repository \( /new \)`,
- },
- {
- `hi
-
-
-
- hello google
-
- testList:
-
-
-`,
- `hi
-hello google \( https://google.com \)
-
-test
-
-List:
-
-\* Foo \( foo \)
-\* Barsoap \( http://www.microshwhat.com/bar/soapy \)
-\* Baz`,
- },
- // Malformed input html.
- {
- `hi
-
- hello google
-
- testList:
-
-
- `,
- `hi hello google \( https://google.com \) test
-
-List:
-
-\* Foo \( foo \)
-\* Bar \( /\n[ \t]+bar/baz \)
-\* Baz`,
- },
- }
-
- for _, testCase := range testCases {
- if msg, err := wantRegExp(testCase.input, testCase.expr); err != nil {
- t.Error(err)
- } else if len(msg) > 0 {
- t.Log(msg)
- }
- }
-}
-
-func TestPeriod(t *testing.T) {
- testCases := []struct {
- input string
- expr string
- }{
- {
- `Lorem ipsum test .
`,
- `Lorem ipsum test\.`,
- },
- {
- `Lorem ipsum test.
`,
- `Lorem ipsum test\.`,
- },
- }
-
- for _, testCase := range testCases {
- if msg, err := wantRegExp(testCase.input, testCase.expr); err != nil {
- t.Error(err)
- } else if len(msg) > 0 {
- t.Log(msg)
- }
- }
-}
-
-type StringMatcher interface {
- MatchString(string) bool
- String() string
-}
-
-type RegexpStringMatcher string
-
-func (m RegexpStringMatcher) MatchString(str string) bool {
- return regexp.MustCompile(string(m)).MatchString(str)
-}
-func (m RegexpStringMatcher) String() string {
- return string(m)
-}
-
-type ExactStringMatcher string
-
-func (m ExactStringMatcher) MatchString(str string) bool {
- return string(m) == str
-}
-func (m ExactStringMatcher) String() string {
- return string(m)
-}
-
-func wantRegExp(input string, outputRE string, options ...Options) (string, error) {
- return match(input, RegexpStringMatcher(outputRE), options...)
-}
-
-func wantString(input string, output string, options ...Options) (string, error) {
- return match(input, ExactStringMatcher(output), options...)
-}
-
-func match(input string, matcher StringMatcher, options ...Options) (string, error) {
- text, err := FromString(input, options...)
- if err != nil {
- return "", err
- }
- if !matcher.MatchString(text) {
- return "", fmt.Errorf(`error: input did not match specified expression
-Input:
->>>>
-%v
-<<<<
-
-Output:
->>>>
-%v
-<<<<
-
-Expected:
->>>>
-%v
-<<<<`,
- input,
- text,
- matcher.String(),
- )
- }
-
- var msg string
-
- if EnableExtraLogging {
- msg = fmt.Sprintf(
- `
-input:
-
-%v
-
-output:
-
-%v
-`,
- input,
- text,
- )
- }
- return msg, nil
-}
-
-func Example() {
- inputHTML := `
-
-
- My Mega Service
-
-
-
-
-
-
-
-
-
- Welcome to your new account on my service!
-
-
- Here is some more information:
-
-
-
-
-
-
- Header 1 Header 2
-
-
- Footer 1 Footer 2
-
-
- Row 1 Col 1 Row 1 Col 2
- Row 2 Col 1 Row 2 Col 2
-
-
-
-`
-
- text, err := FromString(inputHTML, Options{PrettyTables: true})
- if err != nil {
- panic(err)
- }
- fmt.Println(text)
-
- // Output:
- // Mega Service ( http://jaytaylor.com/ )
- //
- // ******************************************
- // Welcome to your new account on my service!
- // ******************************************
- //
- // Here is some more information:
- //
- // * Link 1: Example.com ( https://example.com )
- // * Link 2: Example2.com ( https://example2.com )
- // * Something else
- //
- // +-------------+-------------+
- // | HEADER 1 | HEADER 2 |
- // +-------------+-------------+
- // | Row 1 Col 1 | Row 1 Col 2 |
- // | Row 2 Col 1 | Row 2 Col 2 |
- // +-------------+-------------+
- // | FOOTER 1 | FOOTER 2 |
- // +-------------+-------------+
-}
diff --git a/vendor/github.com/jinzhu/inflection/LICENSE b/vendor/github.com/jinzhu/inflection/LICENSE
deleted file mode 100644
index a1ca9a0..0000000
--- a/vendor/github.com/jinzhu/inflection/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2015 - Jinzhu
-
-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.
diff --git a/vendor/github.com/jinzhu/inflection/README.md b/vendor/github.com/jinzhu/inflection/README.md
deleted file mode 100644
index 4dd0f2d..0000000
--- a/vendor/github.com/jinzhu/inflection/README.md
+++ /dev/null
@@ -1,55 +0,0 @@
-Inflection
-=========
-
-Inflection pluralizes and singularizes English nouns
-
-## Basic Usage
-
-```go
-inflection.Plural("person") => "people"
-inflection.Plural("Person") => "People"
-inflection.Plural("PERSON") => "PEOPLE"
-inflection.Plural("bus") => "buses"
-inflection.Plural("BUS") => "BUSES"
-inflection.Plural("Bus") => "Buses"
-
-inflection.Singular("people") => "person"
-inflection.Singular("People") => "Person"
-inflection.Singular("PEOPLE") => "PERSON"
-inflection.Singular("buses") => "bus"
-inflection.Singular("BUSES") => "BUS"
-inflection.Singular("Buses") => "Bus"
-
-inflection.Plural("FancyPerson") => "FancyPeople"
-inflection.Singular("FancyPeople") => "FancyPerson"
-```
-
-## Register Rules
-
-Standard rules are from Rails's ActiveSupport (https://github.com/rails/rails/blob/master/activesupport/lib/active_support/inflections.rb)
-
-If you want to register more rules, follow:
-
-```
-inflection.AddUncountable("fish")
-inflection.AddIrregular("person", "people")
-inflection.AddPlural("(bu)s$", "${1}ses") # "bus" => "buses" / "BUS" => "BUSES" / "Bus" => "Buses"
-inflection.AddSingular("(bus)(es)?$", "${1}") # "buses" => "bus" / "Buses" => "Bus" / "BUSES" => "BUS"
-```
-
-## Supporting the project
-
-[](http://patreon.com/jinzhu)
-
-
-## Author
-
-**jinzhu**
-
-*
-*
-*
-
-## License
-
-Released under the [MIT License](http://www.opensource.org/licenses/MIT).
diff --git a/vendor/github.com/jinzhu/inflection/inflections.go b/vendor/github.com/jinzhu/inflection/inflections.go
deleted file mode 100644
index 606263b..0000000
--- a/vendor/github.com/jinzhu/inflection/inflections.go
+++ /dev/null
@@ -1,273 +0,0 @@
-/*
-Package inflection pluralizes and singularizes English nouns.
-
- inflection.Plural("person") => "people"
- inflection.Plural("Person") => "People"
- inflection.Plural("PERSON") => "PEOPLE"
-
- inflection.Singular("people") => "person"
- inflection.Singular("People") => "Person"
- inflection.Singular("PEOPLE") => "PERSON"
-
- inflection.Plural("FancyPerson") => "FancydPeople"
- inflection.Singular("FancyPeople") => "FancydPerson"
-
-Standard rules are from Rails's ActiveSupport (https://github.com/rails/rails/blob/master/activesupport/lib/active_support/inflections.rb)
-
-If you want to register more rules, follow:
-
- inflection.AddUncountable("fish")
- inflection.AddIrregular("person", "people")
- inflection.AddPlural("(bu)s$", "${1}ses") # "bus" => "buses" / "BUS" => "BUSES" / "Bus" => "Buses"
- inflection.AddSingular("(bus)(es)?$", "${1}") # "buses" => "bus" / "Buses" => "Bus" / "BUSES" => "BUS"
-*/
-package inflection
-
-import (
- "regexp"
- "strings"
-)
-
-type inflection struct {
- regexp *regexp.Regexp
- replace string
-}
-
-// Regular is a regexp find replace inflection
-type Regular struct {
- find string
- replace string
-}
-
-// Irregular is a hard replace inflection,
-// containing both singular and plural forms
-type Irregular struct {
- singular string
- plural string
-}
-
-// RegularSlice is a slice of Regular inflections
-type RegularSlice []Regular
-
-// IrregularSlice is a slice of Irregular inflections
-type IrregularSlice []Irregular
-
-var pluralInflections = RegularSlice{
- {"([a-z])$", "${1}s"},
- {"s$", "s"},
- {"^(ax|test)is$", "${1}es"},
- {"(octop|vir)us$", "${1}i"},
- {"(octop|vir)i$", "${1}i"},
- {"(alias|status)$", "${1}es"},
- {"(bu)s$", "${1}ses"},
- {"(buffal|tomat)o$", "${1}oes"},
- {"([ti])um$", "${1}a"},
- {"([ti])a$", "${1}a"},
- {"sis$", "ses"},
- {"(?:([^f])fe|([lr])f)$", "${1}${2}ves"},
- {"(hive)$", "${1}s"},
- {"([^aeiouy]|qu)y$", "${1}ies"},
- {"(x|ch|ss|sh)$", "${1}es"},
- {"(matr|vert|ind)(?:ix|ex)$", "${1}ices"},
- {"^(m|l)ouse$", "${1}ice"},
- {"^(m|l)ice$", "${1}ice"},
- {"^(ox)$", "${1}en"},
- {"^(oxen)$", "${1}"},
- {"(quiz)$", "${1}zes"},
-}
-
-var singularInflections = RegularSlice{
- {"s$", ""},
- {"(ss)$", "${1}"},
- {"(n)ews$", "${1}ews"},
- {"([ti])a$", "${1}um"},
- {"((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$", "${1}sis"},
- {"(^analy)(sis|ses)$", "${1}sis"},
- {"([^f])ves$", "${1}fe"},
- {"(hive)s$", "${1}"},
- {"(tive)s$", "${1}"},
- {"([lr])ves$", "${1}f"},
- {"([^aeiouy]|qu)ies$", "${1}y"},
- {"(s)eries$", "${1}eries"},
- {"(m)ovies$", "${1}ovie"},
- {"(c)ookies$", "${1}ookie"},
- {"(x|ch|ss|sh)es$", "${1}"},
- {"^(m|l)ice$", "${1}ouse"},
- {"(bus)(es)?$", "${1}"},
- {"(o)es$", "${1}"},
- {"(shoe)s$", "${1}"},
- {"(cris|test)(is|es)$", "${1}is"},
- {"^(a)x[ie]s$", "${1}xis"},
- {"(octop|vir)(us|i)$", "${1}us"},
- {"(alias|status)(es)?$", "${1}"},
- {"^(ox)en", "${1}"},
- {"(vert|ind)ices$", "${1}ex"},
- {"(matr)ices$", "${1}ix"},
- {"(quiz)zes$", "${1}"},
- {"(database)s$", "${1}"},
-}
-
-var irregularInflections = IrregularSlice{
- {"person", "people"},
- {"man", "men"},
- {"child", "children"},
- {"sex", "sexes"},
- {"move", "moves"},
- {"mombie", "mombies"},
-}
-
-var uncountableInflections = []string{"equipment", "information", "rice", "money", "species", "series", "fish", "sheep", "jeans", "police"}
-
-var compiledPluralMaps []inflection
-var compiledSingularMaps []inflection
-
-func compile() {
- compiledPluralMaps = []inflection{}
- compiledSingularMaps = []inflection{}
- for _, uncountable := range uncountableInflections {
- inf := inflection{
- regexp: regexp.MustCompile("^(?i)(" + uncountable + ")$"),
- replace: "${1}",
- }
- compiledPluralMaps = append(compiledPluralMaps, inf)
- compiledSingularMaps = append(compiledSingularMaps, inf)
- }
-
- for _, value := range irregularInflections {
- infs := []inflection{
- inflection{regexp: regexp.MustCompile(strings.ToUpper(value.singular) + "$"), replace: strings.ToUpper(value.plural)},
- inflection{regexp: regexp.MustCompile(strings.Title(value.singular) + "$"), replace: strings.Title(value.plural)},
- inflection{regexp: regexp.MustCompile(value.singular + "$"), replace: value.plural},
- }
- compiledPluralMaps = append(compiledPluralMaps, infs...)
- }
-
- for _, value := range irregularInflections {
- infs := []inflection{
- inflection{regexp: regexp.MustCompile(strings.ToUpper(value.plural) + "$"), replace: strings.ToUpper(value.singular)},
- inflection{regexp: regexp.MustCompile(strings.Title(value.plural) + "$"), replace: strings.Title(value.singular)},
- inflection{regexp: regexp.MustCompile(value.plural + "$"), replace: value.singular},
- }
- compiledSingularMaps = append(compiledSingularMaps, infs...)
- }
-
- for i := len(pluralInflections) - 1; i >= 0; i-- {
- value := pluralInflections[i]
- infs := []inflection{
- inflection{regexp: regexp.MustCompile(strings.ToUpper(value.find)), replace: strings.ToUpper(value.replace)},
- inflection{regexp: regexp.MustCompile(value.find), replace: value.replace},
- inflection{regexp: regexp.MustCompile("(?i)" + value.find), replace: value.replace},
- }
- compiledPluralMaps = append(compiledPluralMaps, infs...)
- }
-
- for i := len(singularInflections) - 1; i >= 0; i-- {
- value := singularInflections[i]
- infs := []inflection{
- inflection{regexp: regexp.MustCompile(strings.ToUpper(value.find)), replace: strings.ToUpper(value.replace)},
- inflection{regexp: regexp.MustCompile(value.find), replace: value.replace},
- inflection{regexp: regexp.MustCompile("(?i)" + value.find), replace: value.replace},
- }
- compiledSingularMaps = append(compiledSingularMaps, infs...)
- }
-}
-
-func init() {
- compile()
-}
-
-// AddPlural adds a plural inflection
-func AddPlural(find, replace string) {
- pluralInflections = append(pluralInflections, Regular{find, replace})
- compile()
-}
-
-// AddSingular adds a singular inflection
-func AddSingular(find, replace string) {
- singularInflections = append(singularInflections, Regular{find, replace})
- compile()
-}
-
-// AddIrregular adds an irregular inflection
-func AddIrregular(singular, plural string) {
- irregularInflections = append(irregularInflections, Irregular{singular, plural})
- compile()
-}
-
-// AddUncountable adds an uncountable inflection
-func AddUncountable(values ...string) {
- uncountableInflections = append(uncountableInflections, values...)
- compile()
-}
-
-// GetPlural retrieves the plural inflection values
-func GetPlural() RegularSlice {
- plurals := make(RegularSlice, len(pluralInflections))
- copy(plurals, pluralInflections)
- return plurals
-}
-
-// GetSingular retrieves the singular inflection values
-func GetSingular() RegularSlice {
- singulars := make(RegularSlice, len(singularInflections))
- copy(singulars, singularInflections)
- return singulars
-}
-
-// GetIrregular retrieves the irregular inflection values
-func GetIrregular() IrregularSlice {
- irregular := make(IrregularSlice, len(irregularInflections))
- copy(irregular, irregularInflections)
- return irregular
-}
-
-// GetUncountable retrieves the uncountable inflection values
-func GetUncountable() []string {
- uncountables := make([]string, len(uncountableInflections))
- copy(uncountables, uncountableInflections)
- return uncountables
-}
-
-// SetPlural sets the plural inflections slice
-func SetPlural(inflections RegularSlice) {
- pluralInflections = inflections
- compile()
-}
-
-// SetSingular sets the singular inflections slice
-func SetSingular(inflections RegularSlice) {
- singularInflections = inflections
- compile()
-}
-
-// SetIrregular sets the irregular inflections slice
-func SetIrregular(inflections IrregularSlice) {
- irregularInflections = inflections
- compile()
-}
-
-// SetUncountable sets the uncountable inflections slice
-func SetUncountable(inflections []string) {
- uncountableInflections = inflections
- compile()
-}
-
-// Plural converts a word to its plural form
-func Plural(str string) string {
- for _, inflection := range compiledPluralMaps {
- if inflection.regexp.MatchString(str) {
- return inflection.regexp.ReplaceAllString(str, inflection.replace)
- }
- }
- return str
-}
-
-// Singular converts a word to its singular form
-func Singular(str string) string {
- for _, inflection := range compiledSingularMaps {
- if inflection.regexp.MatchString(str) {
- return inflection.regexp.ReplaceAllString(str, inflection.replace)
- }
- }
- return str
-}
diff --git a/vendor/github.com/jinzhu/inflection/inflections_test.go b/vendor/github.com/jinzhu/inflection/inflections_test.go
deleted file mode 100644
index 689e1df..0000000
--- a/vendor/github.com/jinzhu/inflection/inflections_test.go
+++ /dev/null
@@ -1,213 +0,0 @@
-package inflection
-
-import (
- "strings"
- "testing"
-)
-
-var inflections = map[string]string{
- "star": "stars",
- "STAR": "STARS",
- "Star": "Stars",
- "bus": "buses",
- "fish": "fish",
- "mouse": "mice",
- "query": "queries",
- "ability": "abilities",
- "agency": "agencies",
- "movie": "movies",
- "archive": "archives",
- "index": "indices",
- "wife": "wives",
- "safe": "saves",
- "half": "halves",
- "move": "moves",
- "salesperson": "salespeople",
- "person": "people",
- "spokesman": "spokesmen",
- "man": "men",
- "woman": "women",
- "basis": "bases",
- "diagnosis": "diagnoses",
- "diagnosis_a": "diagnosis_as",
- "datum": "data",
- "medium": "media",
- "stadium": "stadia",
- "analysis": "analyses",
- "node_child": "node_children",
- "child": "children",
- "experience": "experiences",
- "day": "days",
- "comment": "comments",
- "foobar": "foobars",
- "newsletter": "newsletters",
- "old_news": "old_news",
- "news": "news",
- "series": "series",
- "species": "species",
- "quiz": "quizzes",
- "perspective": "perspectives",
- "ox": "oxen",
- "photo": "photos",
- "buffalo": "buffaloes",
- "tomato": "tomatoes",
- "dwarf": "dwarves",
- "elf": "elves",
- "information": "information",
- "equipment": "equipment",
- "criterion": "criteria",
-}
-
-// storage is used to restore the state of the global variables
-// on each test execution, to ensure no global state pollution
-type storage struct {
- singulars RegularSlice
- plurals RegularSlice
- irregulars IrregularSlice
- uncountables []string
-}
-
-var backup = storage{}
-
-func init() {
- AddIrregular("criterion", "criteria")
- copy(backup.singulars, singularInflections)
- copy(backup.plurals, pluralInflections)
- copy(backup.irregulars, irregularInflections)
- copy(backup.uncountables, uncountableInflections)
-}
-
-func restore() {
- copy(singularInflections, backup.singulars)
- copy(pluralInflections, backup.plurals)
- copy(irregularInflections, backup.irregulars)
- copy(uncountableInflections, backup.uncountables)
-}
-
-func TestPlural(t *testing.T) {
- for key, value := range inflections {
- if v := Plural(strings.ToUpper(key)); v != strings.ToUpper(value) {
- t.Errorf("%v's plural should be %v, but got %v", strings.ToUpper(key), strings.ToUpper(value), v)
- }
-
- if v := Plural(strings.Title(key)); v != strings.Title(value) {
- t.Errorf("%v's plural should be %v, but got %v", strings.Title(key), strings.Title(value), v)
- }
-
- if v := Plural(key); v != value {
- t.Errorf("%v's plural should be %v, but got %v", key, value, v)
- }
- }
-}
-
-func TestSingular(t *testing.T) {
- for key, value := range inflections {
- if v := Singular(strings.ToUpper(value)); v != strings.ToUpper(key) {
- t.Errorf("%v's singular should be %v, but got %v", strings.ToUpper(value), strings.ToUpper(key), v)
- }
-
- if v := Singular(strings.Title(value)); v != strings.Title(key) {
- t.Errorf("%v's singular should be %v, but got %v", strings.Title(value), strings.Title(key), v)
- }
-
- if v := Singular(value); v != key {
- t.Errorf("%v's singular should be %v, but got %v", value, key, v)
- }
- }
-}
-
-func TestAddPlural(t *testing.T) {
- defer restore()
- ln := len(pluralInflections)
- AddPlural("", "")
- if ln+1 != len(pluralInflections) {
- t.Errorf("Expected len %d, got %d", ln+1, len(pluralInflections))
- }
-}
-
-func TestAddSingular(t *testing.T) {
- defer restore()
- ln := len(singularInflections)
- AddSingular("", "")
- if ln+1 != len(singularInflections) {
- t.Errorf("Expected len %d, got %d", ln+1, len(singularInflections))
- }
-}
-
-func TestAddIrregular(t *testing.T) {
- defer restore()
- ln := len(irregularInflections)
- AddIrregular("", "")
- if ln+1 != len(irregularInflections) {
- t.Errorf("Expected len %d, got %d", ln+1, len(irregularInflections))
- }
-}
-
-func TestAddUncountable(t *testing.T) {
- defer restore()
- ln := len(uncountableInflections)
- AddUncountable("", "")
- if ln+2 != len(uncountableInflections) {
- t.Errorf("Expected len %d, got %d", ln+2, len(uncountableInflections))
- }
-}
-
-func TestGetPlural(t *testing.T) {
- plurals := GetPlural()
- if len(plurals) != len(pluralInflections) {
- t.Errorf("Expected len %d, got %d", len(plurals), len(pluralInflections))
- }
-}
-
-func TestGetSingular(t *testing.T) {
- singular := GetSingular()
- if len(singular) != len(singularInflections) {
- t.Errorf("Expected len %d, got %d", len(singular), len(singularInflections))
- }
-}
-
-func TestGetIrregular(t *testing.T) {
- irregular := GetIrregular()
- if len(irregular) != len(irregularInflections) {
- t.Errorf("Expected len %d, got %d", len(irregular), len(irregularInflections))
- }
-}
-
-func TestGetUncountable(t *testing.T) {
- uncountables := GetUncountable()
- if len(uncountables) != len(uncountableInflections) {
- t.Errorf("Expected len %d, got %d", len(uncountables), len(uncountableInflections))
- }
-}
-
-func TestSetPlural(t *testing.T) {
- defer restore()
- SetPlural(RegularSlice{{}, {}})
- if len(pluralInflections) != 2 {
- t.Errorf("Expected len 2, got %d", len(pluralInflections))
- }
-}
-
-func TestSetSingular(t *testing.T) {
- defer restore()
- SetSingular(RegularSlice{{}, {}})
- if len(singularInflections) != 2 {
- t.Errorf("Expected len 2, got %d", len(singularInflections))
- }
-}
-
-func TestSetIrregular(t *testing.T) {
- defer restore()
- SetIrregular(IrregularSlice{{}, {}})
- if len(irregularInflections) != 2 {
- t.Errorf("Expected len 2, got %d", len(irregularInflections))
- }
-}
-
-func TestSetUncountable(t *testing.T) {
- defer restore()
- SetUncountable([]string{"", ""})
- if len(uncountableInflections) != 2 {
- t.Errorf("Expected len 2, got %d", len(uncountableInflections))
- }
-}
diff --git a/vendor/github.com/magiconair/properties/.gitignore b/vendor/github.com/magiconair/properties/.gitignore
deleted file mode 100644
index e7081ff..0000000
--- a/vendor/github.com/magiconair/properties/.gitignore
+++ /dev/null
@@ -1,6 +0,0 @@
-*.sublime-project
-*.sublime-workspace
-*.un~
-*.swp
-.idea/
-*.iml
diff --git a/vendor/github.com/magiconair/properties/.travis.yml b/vendor/github.com/magiconair/properties/.travis.yml
deleted file mode 100644
index 60436b2..0000000
--- a/vendor/github.com/magiconair/properties/.travis.yml
+++ /dev/null
@@ -1,8 +0,0 @@
-language: go
-go:
- - 1.4.x
- - 1.5.x
- - 1.6.x
- - 1.7.x
- - 1.8.x
- - tip
diff --git a/vendor/github.com/magiconair/properties/CHANGELOG.md b/vendor/github.com/magiconair/properties/CHANGELOG.md
deleted file mode 100644
index 4905fec..0000000
--- a/vendor/github.com/magiconair/properties/CHANGELOG.md
+++ /dev/null
@@ -1,96 +0,0 @@
-## Changelog
-
-### [1.7.3](https://github.com/magiconair/properties/tags/v1.7.3) - 10 Jul 2017
-
- * [Issue #17](https://github.com/magiconair/properties/issues/17): Add [SetValue()](http://godoc.org/github.com/magiconair/properties#Properties.SetValue) method to set values generically
- * [Issue #22](https://github.com/magiconair/properties/issues/22): Add [LoadMap()](http://godoc.org/github.com/magiconair/properties#LoadMap) function to load properties from a string map
-
-### [1.7.2](https://github.com/magiconair/properties/tags/v1.7.2) - 20 Mar 2017
-
- * [Issue #15](https://github.com/magiconair/properties/issues/15): Drop gocheck dependency
- * [PR #21](https://github.com/magiconair/properties/pull/21): Add [Map()](http://godoc.org/github.com/magiconair/properties#Properties.Map) and [FilterFunc()](http://godoc.org/github.com/magiconair/properties#Properties.FilterFunc)
-
-### [1.7.1](https://github.com/magiconair/properties/tags/v1.7.1) - 13 Jan 2017
-
- * [PR #16](https://github.com/magiconair/properties/pull/16): Keep gofmt happy
- * [PR #18](https://github.com/magiconair/properties/pull/18): Fix Delete() function
-
-### [1.7.0](https://github.com/magiconair/properties/tags/v1.7.0) - 20 Mar 2016
-
- * [Issue #10](https://github.com/magiconair/properties/issues/10): Add [LoadURL,LoadURLs,MustLoadURL,MustLoadURLs](http://godoc.org/github.com/magiconair/properties#LoadURL) method to load properties from a URL.
- * [Issue #11](https://github.com/magiconair/properties/issues/11): Add [LoadString,MustLoadString](http://godoc.org/github.com/magiconair/properties#LoadString) method to load properties from an UTF8 string.
- * [PR #8](https://github.com/magiconair/properties/pull/8): Add [MustFlag](http://godoc.org/github.com/magiconair/properties#Properties.MustFlag) method to provide overrides via command line flags. (@pascaldekloe)
-
-### [1.6.0](https://github.com/magiconair/properties/tags/v1.6.0) - 11 Dec 2015
-
- * Add [Decode](http://godoc.org/github.com/magiconair/properties#Properties.Decode) method to populate struct from properties via tags.
-
-### [1.5.6](https://github.com/magiconair/properties/tags/v1.5.6) - 18 Oct 2015
-
- * Vendored in gopkg.in/check.v1
-
-### [1.5.5](https://github.com/magiconair/properties/tags/v1.5.5) - 31 Jul 2015
-
- * [PR #6](https://github.com/magiconair/properties/pull/6): Add [Delete](http://godoc.org/github.com/magiconair/properties#Properties.Delete) method to remove keys including comments. (@gerbenjacobs)
-
-### [1.5.4](https://github.com/magiconair/properties/tags/v1.5.4) - 23 Jun 2015
-
- * [Issue #5](https://github.com/magiconair/properties/issues/5): Allow disabling of property expansion [DisableExpansion](http://godoc.org/github.com/magiconair/properties#Properties.DisableExpansion). When property expansion is disabled Properties become a simple key/value store and don't check for circular references.
-
-### [1.5.3](https://github.com/magiconair/properties/tags/v1.5.3) - 02 Jun 2015
-
- * [Issue #4](https://github.com/magiconair/properties/issues/4): Maintain key order in [Filter()](http://godoc.org/github.com/magiconair/properties#Properties.Filter), [FilterPrefix()](http://godoc.org/github.com/magiconair/properties#Properties.FilterPrefix) and [FilterRegexp()](http://godoc.org/github.com/magiconair/properties#Properties.FilterRegexp)
-
-### [1.5.2](https://github.com/magiconair/properties/tags/v1.5.2) - 10 Apr 2015
-
- * [Issue #3](https://github.com/magiconair/properties/issues/3): Don't print comments in [WriteComment()](http://godoc.org/github.com/magiconair/properties#Properties.WriteComment) if they are all empty
- * Add clickable links to README
-
-### [1.5.1](https://github.com/magiconair/properties/tags/v1.5.1) - 08 Dec 2014
-
- * Added [GetParsedDuration()](http://godoc.org/github.com/magiconair/properties#Properties.GetParsedDuration) and [MustGetParsedDuration()](http://godoc.org/github.com/magiconair/properties#Properties.MustGetParsedDuration) for values specified compatible with
- [time.ParseDuration()](http://golang.org/pkg/time/#ParseDuration).
-
-### [1.5.0](https://github.com/magiconair/properties/tags/v1.5.0) - 18 Nov 2014
-
- * Added support for single and multi-line comments (reading, writing and updating)
- * The order of keys is now preserved
- * Calling [Set()](http://godoc.org/github.com/magiconair/properties#Properties.Set) with an empty key now silently ignores the call and does not create a new entry
- * Added a [MustSet()](http://godoc.org/github.com/magiconair/properties#Properties.MustSet) method
- * Migrated test library from launchpad.net/gocheck to [gopkg.in/check.v1](http://gopkg.in/check.v1)
-
-### [1.4.2](https://github.com/magiconair/properties/tags/v1.4.2) - 15 Nov 2014
-
- * [Issue #2](https://github.com/magiconair/properties/issues/2): Fixed goroutine leak in parser which created two lexers but cleaned up only one
-
-### [1.4.1](https://github.com/magiconair/properties/tags/v1.4.1) - 13 Nov 2014
-
- * [Issue #1](https://github.com/magiconair/properties/issues/1): Fixed bug in Keys() method which returned an empty string
-
-### [1.4.0](https://github.com/magiconair/properties/tags/v1.4.0) - 23 Sep 2014
-
- * Added [Keys()](http://godoc.org/github.com/magiconair/properties#Properties.Keys) to get the keys
- * Added [Filter()](http://godoc.org/github.com/magiconair/properties#Properties.Filter), [FilterRegexp()](http://godoc.org/github.com/magiconair/properties#Properties.FilterRegexp) and [FilterPrefix()](http://godoc.org/github.com/magiconair/properties#Properties.FilterPrefix) to get a subset of the properties
-
-### [1.3.0](https://github.com/magiconair/properties/tags/v1.3.0) - 18 Mar 2014
-
-* Added support for time.Duration
-* Made MustXXX() failure beha[ior configurable (log.Fatal, panic](https://github.com/magiconair/properties/tags/vior configurable (log.Fatal, panic) - custom)
-* Changed default of MustXXX() failure from panic to log.Fatal
-
-### [1.2.0](https://github.com/magiconair/properties/tags/v1.2.0) - 05 Mar 2014
-
-* Added MustGet... functions
-* Added support for int and uint with range checks on 32 bit platforms
-
-### [1.1.0](https://github.com/magiconair/properties/tags/v1.1.0) - 20 Jan 2014
-
-* Renamed from goproperties to properties
-* Added support for expansion of environment vars in
- filenames and value expressions
-* Fixed bug where value expressions were not at the
- start of the string
-
-### [1.0.0](https://github.com/magiconair/properties/tags/v1.0.0) - 7 Jan 2014
-
-* Initial release
diff --git a/vendor/github.com/magiconair/properties/LICENSE b/vendor/github.com/magiconair/properties/LICENSE
deleted file mode 100644
index 7eab43b..0000000
--- a/vendor/github.com/magiconair/properties/LICENSE
+++ /dev/null
@@ -1,25 +0,0 @@
-goproperties - properties file decoder for Go
-
-Copyright (c) 2013-2014 - Frank Schroeder
-
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
-1. Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
-ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/vendor/github.com/magiconair/properties/README.md b/vendor/github.com/magiconair/properties/README.md
deleted file mode 100644
index eb3b8c4..0000000
--- a/vendor/github.com/magiconair/properties/README.md
+++ /dev/null
@@ -1,100 +0,0 @@
-Overview [](https://travis-ci.org/magiconair/properties)
-========
-
-#### Current version: 1.7.3
-
-properties is a Go library for reading and writing properties files.
-
-It supports reading from multiple files or URLs and Spring style recursive
-property expansion of expressions like `${key}` to their corresponding value.
-Value expressions can refer to other keys like in `${key}` or to environment
-variables like in `${USER}`. Filenames can also contain environment variables
-like in `/home/${USER}/myapp.properties`.
-
-Properties can be decoded into structs, maps, arrays and values through
-struct tags.
-
-Comments and the order of keys are preserved. Comments can be modified
-and can be written to the output.
-
-The properties library supports both ISO-8859-1 and UTF-8 encoded data.
-
-Starting from version 1.3.0 the behavior of the MustXXX() functions is
-configurable by providing a custom `ErrorHandler` function. The default has
-changed from `panic` to `log.Fatal` but this is configurable and custom
-error handling functions can be provided. See the package documentation for
-details.
-
-Read the full documentation on [GoDoc](https://godoc.org/github.com/magiconair/properties) [](https://godoc.org/github.com/magiconair/properties)
-
-Getting Started
----------------
-
-```go
-import (
- "flag"
- "github.com/magiconair/properties"
-)
-
-func main() {
- // init from a file
- p := properties.MustLoadFile("${HOME}/config.properties", properties.UTF8)
-
- // or multiple files
- p = properties.MustLoadFiles([]string{
- "${HOME}/config.properties",
- "${HOME}/config-${USER}.properties",
- }, properties.UTF8, true)
-
- // or from a map
- p = properties.LoadMap(map[string]string{"key": "value", "abc": "def"})
-
- // or from a string
- p = properties.MustLoadString("key=value\nabc=def")
-
- // or from a URL
- p = properties.MustLoadURL("http://host/path")
-
- // or from multiple URLs
- p = properties.MustLoadURL([]string{
- "http://host/config",
- "http://host/config-${USER}",
- }, true)
-
- // or from flags
- p.MustFlag(flag.CommandLine)
-
- // get values through getters
- host := p.MustGetString("host")
- port := p.GetInt("port", 8080)
-
- // or through Decode
- type Config struct {
- Host string `properties:"host"`
- Port int `properties:"port,default=9000"`
- Accept []string `properties:"accept,default=image/png;image;gif"`
- Timeout time.Duration `properties:"timeout,default=5s"`
- }
- var cfg Config
- if err := p.Decode(&cfg); err != nil {
- log.Fatal(err)
- }
-}
-
-```
-
-Installation and Upgrade
-------------------------
-
-```
-$ go get -u github.com/magiconair/properties
-```
-
-License
--------
-
-2 clause BSD license. See [LICENSE](https://github.com/magiconair/properties/blob/master/LICENSE) file for details.
-
-ToDo
-----
-* Dump contents with passwords and secrets obscured
diff --git a/vendor/github.com/magiconair/properties/benchmark_test.go b/vendor/github.com/magiconair/properties/benchmark_test.go
deleted file mode 100644
index 62c7cc5..0000000
--- a/vendor/github.com/magiconair/properties/benchmark_test.go
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright 2013-2014 Frank Schroeder. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package properties
-
-import (
- "fmt"
- "testing"
-)
-
-// Benchmarks the decoder by creating a property file with 1000 key/value pairs.
-func BenchmarkLoad(b *testing.B) {
- input := ""
- for i := 0; i < 1000; i++ {
- input += fmt.Sprintf("key%d=value%d\n", i, i)
- }
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- if _, err := Load([]byte(input), ISO_8859_1); err != nil {
- b.Fatal(err)
- }
- }
-}
diff --git a/vendor/github.com/magiconair/properties/decode.go b/vendor/github.com/magiconair/properties/decode.go
deleted file mode 100644
index 0a961bb..0000000
--- a/vendor/github.com/magiconair/properties/decode.go
+++ /dev/null
@@ -1,289 +0,0 @@
-// Copyright 2017 Frank Schroeder. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package properties
-
-import (
- "fmt"
- "reflect"
- "strconv"
- "strings"
- "time"
-)
-
-// Decode assigns property values to exported fields of a struct.
-//
-// Decode traverses v recursively and returns an error if a value cannot be
-// converted to the field type or a required value is missing for a field.
-//
-// The following type dependent decodings are used:
-//
-// String, boolean, numeric fields have the value of the property key assigned.
-// The property key name is the name of the field. A different key and a default
-// value can be set in the field's tag. Fields without default value are
-// required. If the value cannot be converted to the field type an error is
-// returned.
-//
-// time.Duration fields have the result of time.ParseDuration() assigned.
-//
-// time.Time fields have the vaule of time.Parse() assigned. The default layout
-// is time.RFC3339 but can be set in the field's tag.
-//
-// Arrays and slices of string, boolean, numeric, time.Duration and time.Time
-// fields have the value interpreted as a comma separated list of values. The
-// individual values are trimmed of whitespace and empty values are ignored. A
-// default value can be provided as a semicolon separated list in the field's
-// tag.
-//
-// Struct fields are decoded recursively using the field name plus "." as
-// prefix. The prefix (without dot) can be overridden in the field's tag.
-// Default values are not supported in the field's tag. Specify them on the
-// fields of the inner struct instead.
-//
-// Map fields must have a key of type string and are decoded recursively by
-// using the field's name plus ".' as prefix and the next element of the key
-// name as map key. The prefix (without dot) can be overridden in the field's
-// tag. Default values are not supported.
-//
-// Examples:
-//
-// // Field is ignored.
-// Field int `properties:"-"`
-//
-// // Field is assigned value of 'Field'.
-// Field int
-//
-// // Field is assigned value of 'myName'.
-// Field int `properties:"myName"`
-//
-// // Field is assigned value of key 'myName' and has a default
-// // value 15 if the key does not exist.
-// Field int `properties:"myName,default=15"`
-//
-// // Field is assigned value of key 'Field' and has a default
-// // value 15 if the key does not exist.
-// Field int `properties:",default=15"`
-//
-// // Field is assigned value of key 'date' and the date
-// // is in format 2006-01-02
-// Field time.Time `properties:"date,layout=2006-01-02"`
-//
-// // Field is assigned the non-empty and whitespace trimmed
-// // values of key 'Field' split by commas.
-// Field []string
-//
-// // Field is assigned the non-empty and whitespace trimmed
-// // values of key 'Field' split by commas and has a default
-// // value ["a", "b", "c"] if the key does not exist.
-// Field []string `properties:",default=a;b;c"`
-//
-// // Field is decoded recursively with "Field." as key prefix.
-// Field SomeStruct
-//
-// // Field is decoded recursively with "myName." as key prefix.
-// Field SomeStruct `properties:"myName"`
-//
-// // Field is decoded recursively with "Field." as key prefix
-// // and the next dotted element of the key as map key.
-// Field map[string]string
-//
-// // Field is decoded recursively with "myName." as key prefix
-// // and the next dotted element of the key as map key.
-// Field map[string]string `properties:"myName"`
-func (p *Properties) Decode(x interface{}) error {
- t, v := reflect.TypeOf(x), reflect.ValueOf(x)
- if t.Kind() != reflect.Ptr || v.Elem().Type().Kind() != reflect.Struct {
- return fmt.Errorf("not a pointer to struct: %s", t)
- }
- if err := dec(p, "", nil, nil, v); err != nil {
- return err
- }
- return nil
-}
-
-func dec(p *Properties, key string, def *string, opts map[string]string, v reflect.Value) error {
- t := v.Type()
-
- // value returns the property value for key or the default if provided.
- value := func() (string, error) {
- if val, ok := p.Get(key); ok {
- return val, nil
- }
- if def != nil {
- return *def, nil
- }
- return "", fmt.Errorf("missing required key %s", key)
- }
-
- // conv converts a string to a value of the given type.
- conv := func(s string, t reflect.Type) (val reflect.Value, err error) {
- var v interface{}
-
- switch {
- case isDuration(t):
- v, err = time.ParseDuration(s)
-
- case isTime(t):
- layout := opts["layout"]
- if layout == "" {
- layout = time.RFC3339
- }
- v, err = time.Parse(layout, s)
-
- case isBool(t):
- v, err = boolVal(s), nil
-
- case isString(t):
- v, err = s, nil
-
- case isFloat(t):
- v, err = strconv.ParseFloat(s, 64)
-
- case isInt(t):
- v, err = strconv.ParseInt(s, 10, 64)
-
- case isUint(t):
- v, err = strconv.ParseUint(s, 10, 64)
-
- default:
- return reflect.Zero(t), fmt.Errorf("unsupported type %s", t)
- }
- if err != nil {
- return reflect.Zero(t), err
- }
- return reflect.ValueOf(v).Convert(t), nil
- }
-
- // keydef returns the property key and the default value based on the
- // name of the struct field and the options in the tag.
- keydef := func(f reflect.StructField) (string, *string, map[string]string) {
- _key, _opts := parseTag(f.Tag.Get("properties"))
-
- var _def *string
- if d, ok := _opts["default"]; ok {
- _def = &d
- }
- if _key != "" {
- return _key, _def, _opts
- }
- return f.Name, _def, _opts
- }
-
- switch {
- case isDuration(t) || isTime(t) || isBool(t) || isString(t) || isFloat(t) || isInt(t) || isUint(t):
- s, err := value()
- if err != nil {
- return err
- }
- val, err := conv(s, t)
- if err != nil {
- return err
- }
- v.Set(val)
-
- case isPtr(t):
- return dec(p, key, def, opts, v.Elem())
-
- case isStruct(t):
- for i := 0; i < v.NumField(); i++ {
- fv := v.Field(i)
- fk, def, opts := keydef(t.Field(i))
- if !fv.CanSet() {
- return fmt.Errorf("cannot set %s", t.Field(i).Name)
- }
- if fk == "-" {
- continue
- }
- if key != "" {
- fk = key + "." + fk
- }
- if err := dec(p, fk, def, opts, fv); err != nil {
- return err
- }
- }
- return nil
-
- case isArray(t):
- val, err := value()
- if err != nil {
- return err
- }
- vals := split(val, ";")
- a := reflect.MakeSlice(t, 0, len(vals))
- for _, s := range vals {
- val, err := conv(s, t.Elem())
- if err != nil {
- return err
- }
- a = reflect.Append(a, val)
- }
- v.Set(a)
-
- case isMap(t):
- valT := t.Elem()
- m := reflect.MakeMap(t)
- for postfix := range p.FilterStripPrefix(key + ".").m {
- pp := strings.SplitN(postfix, ".", 2)
- mk, mv := pp[0], reflect.New(valT)
- if err := dec(p, key+"."+mk, nil, nil, mv); err != nil {
- return err
- }
- m.SetMapIndex(reflect.ValueOf(mk), mv.Elem())
- }
- v.Set(m)
-
- default:
- return fmt.Errorf("unsupported type %s", t)
- }
- return nil
-}
-
-// split splits a string on sep, trims whitespace of elements
-// and omits empty elements
-func split(s string, sep string) []string {
- var a []string
- for _, v := range strings.Split(s, sep) {
- if v = strings.TrimSpace(v); v != "" {
- a = append(a, v)
- }
- }
- return a
-}
-
-// parseTag parses a "key,k=v,k=v,..."
-func parseTag(tag string) (key string, opts map[string]string) {
- opts = map[string]string{}
- for i, s := range strings.Split(tag, ",") {
- if i == 0 {
- key = s
- continue
- }
-
- pp := strings.SplitN(s, "=", 2)
- if len(pp) == 1 {
- opts[pp[0]] = ""
- } else {
- opts[pp[0]] = pp[1]
- }
- }
- return key, opts
-}
-
-func isArray(t reflect.Type) bool { return t.Kind() == reflect.Array || t.Kind() == reflect.Slice }
-func isBool(t reflect.Type) bool { return t.Kind() == reflect.Bool }
-func isDuration(t reflect.Type) bool { return t == reflect.TypeOf(time.Second) }
-func isMap(t reflect.Type) bool { return t.Kind() == reflect.Map }
-func isPtr(t reflect.Type) bool { return t.Kind() == reflect.Ptr }
-func isString(t reflect.Type) bool { return t.Kind() == reflect.String }
-func isStruct(t reflect.Type) bool { return t.Kind() == reflect.Struct }
-func isTime(t reflect.Type) bool { return t == reflect.TypeOf(time.Time{}) }
-func isFloat(t reflect.Type) bool {
- return t.Kind() == reflect.Float32 || t.Kind() == reflect.Float64
-}
-func isInt(t reflect.Type) bool {
- return t.Kind() == reflect.Int || t.Kind() == reflect.Int8 || t.Kind() == reflect.Int16 || t.Kind() == reflect.Int32 || t.Kind() == reflect.Int64
-}
-func isUint(t reflect.Type) bool {
- return t.Kind() == reflect.Uint || t.Kind() == reflect.Uint8 || t.Kind() == reflect.Uint16 || t.Kind() == reflect.Uint32 || t.Kind() == reflect.Uint64
-}
diff --git a/vendor/github.com/magiconair/properties/decode_test.go b/vendor/github.com/magiconair/properties/decode_test.go
deleted file mode 100644
index c829314..0000000
--- a/vendor/github.com/magiconair/properties/decode_test.go
+++ /dev/null
@@ -1,299 +0,0 @@
-// Copyright 2017 Frank Schroeder. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package properties
-
-import (
- "reflect"
- "testing"
- "time"
-)
-
-func TestDecodeValues(t *testing.T) {
- type S struct {
- S string
- BT bool
- BF bool
- I int
- I8 int8
- I16 int16
- I32 int32
- I64 int64
- U uint
- U8 uint8
- U16 uint16
- U32 uint32
- U64 uint64
- F32 float32
- F64 float64
- D time.Duration
- TM time.Time
- }
- in := `
- S=abc
- BT=true
- BF=false
- I=-1
- I8=-8
- I16=-16
- I32=-32
- I64=-64
- U=1
- U8=8
- U16=16
- U32=32
- U64=64
- F32=3.2
- F64=6.4
- D=5s
- TM=2015-01-02T12:34:56Z
- `
- out := &S{
- S: "abc",
- BT: true,
- BF: false,
- I: -1,
- I8: -8,
- I16: -16,
- I32: -32,
- I64: -64,
- U: 1,
- U8: 8,
- U16: 16,
- U32: 32,
- U64: 64,
- F32: 3.2,
- F64: 6.4,
- D: 5 * time.Second,
- TM: tm(t, time.RFC3339, "2015-01-02T12:34:56Z"),
- }
- testDecode(t, in, &S{}, out)
-}
-
-func TestDecodeValueDefaults(t *testing.T) {
- type S struct {
- S string `properties:",default=abc"`
- BT bool `properties:",default=true"`
- BF bool `properties:",default=false"`
- I int `properties:",default=-1"`
- I8 int8 `properties:",default=-8"`
- I16 int16 `properties:",default=-16"`
- I32 int32 `properties:",default=-32"`
- I64 int64 `properties:",default=-64"`
- U uint `properties:",default=1"`
- U8 uint8 `properties:",default=8"`
- U16 uint16 `properties:",default=16"`
- U32 uint32 `properties:",default=32"`
- U64 uint64 `properties:",default=64"`
- F32 float32 `properties:",default=3.2"`
- F64 float64 `properties:",default=6.4"`
- D time.Duration `properties:",default=5s"`
- TM time.Time `properties:",default=2015-01-02T12:34:56Z"`
- }
- out := &S{
- S: "abc",
- BT: true,
- BF: false,
- I: -1,
- I8: -8,
- I16: -16,
- I32: -32,
- I64: -64,
- U: 1,
- U8: 8,
- U16: 16,
- U32: 32,
- U64: 64,
- F32: 3.2,
- F64: 6.4,
- D: 5 * time.Second,
- TM: tm(t, time.RFC3339, "2015-01-02T12:34:56Z"),
- }
- testDecode(t, "", &S{}, out)
-}
-
-func TestDecodeArrays(t *testing.T) {
- type S struct {
- S []string
- B []bool
- I []int
- I8 []int8
- I16 []int16
- I32 []int32
- I64 []int64
- U []uint
- U8 []uint8
- U16 []uint16
- U32 []uint32
- U64 []uint64
- F32 []float32
- F64 []float64
- D []time.Duration
- TM []time.Time
- }
- in := `
- S=a;b
- B=true;false
- I=-1;-2
- I8=-8;-9
- I16=-16;-17
- I32=-32;-33
- I64=-64;-65
- U=1;2
- U8=8;9
- U16=16;17
- U32=32;33
- U64=64;65
- F32=3.2;3.3
- F64=6.4;6.5
- D=4s;5s
- TM=2015-01-01T00:00:00Z;2016-01-01T00:00:00Z
- `
- out := &S{
- S: []string{"a", "b"},
- B: []bool{true, false},
- I: []int{-1, -2},
- I8: []int8{-8, -9},
- I16: []int16{-16, -17},
- I32: []int32{-32, -33},
- I64: []int64{-64, -65},
- U: []uint{1, 2},
- U8: []uint8{8, 9},
- U16: []uint16{16, 17},
- U32: []uint32{32, 33},
- U64: []uint64{64, 65},
- F32: []float32{3.2, 3.3},
- F64: []float64{6.4, 6.5},
- D: []time.Duration{4 * time.Second, 5 * time.Second},
- TM: []time.Time{tm(t, time.RFC3339, "2015-01-01T00:00:00Z"), tm(t, time.RFC3339, "2016-01-01T00:00:00Z")},
- }
- testDecode(t, in, &S{}, out)
-}
-
-func TestDecodeArrayDefaults(t *testing.T) {
- type S struct {
- S []string `properties:",default=a;b"`
- B []bool `properties:",default=true;false"`
- I []int `properties:",default=-1;-2"`
- I8 []int8 `properties:",default=-8;-9"`
- I16 []int16 `properties:",default=-16;-17"`
- I32 []int32 `properties:",default=-32;-33"`
- I64 []int64 `properties:",default=-64;-65"`
- U []uint `properties:",default=1;2"`
- U8 []uint8 `properties:",default=8;9"`
- U16 []uint16 `properties:",default=16;17"`
- U32 []uint32 `properties:",default=32;33"`
- U64 []uint64 `properties:",default=64;65"`
- F32 []float32 `properties:",default=3.2;3.3"`
- F64 []float64 `properties:",default=6.4;6.5"`
- D []time.Duration `properties:",default=4s;5s"`
- TM []time.Time `properties:",default=2015-01-01T00:00:00Z;2016-01-01T00:00:00Z"`
- }
- out := &S{
- S: []string{"a", "b"},
- B: []bool{true, false},
- I: []int{-1, -2},
- I8: []int8{-8, -9},
- I16: []int16{-16, -17},
- I32: []int32{-32, -33},
- I64: []int64{-64, -65},
- U: []uint{1, 2},
- U8: []uint8{8, 9},
- U16: []uint16{16, 17},
- U32: []uint32{32, 33},
- U64: []uint64{64, 65},
- F32: []float32{3.2, 3.3},
- F64: []float64{6.4, 6.5},
- D: []time.Duration{4 * time.Second, 5 * time.Second},
- TM: []time.Time{tm(t, time.RFC3339, "2015-01-01T00:00:00Z"), tm(t, time.RFC3339, "2016-01-01T00:00:00Z")},
- }
- testDecode(t, "", &S{}, out)
-}
-
-func TestDecodeSkipUndef(t *testing.T) {
- type S struct {
- X string `properties:"-"`
- Undef string `properties:",default=some value"`
- }
- in := `X=ignore`
- out := &S{"", "some value"}
- testDecode(t, in, &S{}, out)
-}
-
-func TestDecodeStruct(t *testing.T) {
- type A struct {
- S string
- T string `properties:"t"`
- U string `properties:"u,default=uuu"`
- }
- type S struct {
- A A
- B A `properties:"b"`
- }
- in := `
- A.S=sss
- A.t=ttt
- b.S=SSS
- b.t=TTT
- `
- out := &S{
- A{S: "sss", T: "ttt", U: "uuu"},
- A{S: "SSS", T: "TTT", U: "uuu"},
- }
- testDecode(t, in, &S{}, out)
-}
-
-func TestDecodeMap(t *testing.T) {
- type S struct {
- A string `properties:"a"`
- }
- type X struct {
- A map[string]string
- B map[string][]string
- C map[string]map[string]string
- D map[string]S
- E map[string]int
- F map[string]int `properties:"-"`
- }
- in := `
- A.foo=bar
- A.bar=bang
- B.foo=a;b;c
- B.bar=1;2;3
- C.foo.one=1
- C.foo.two=2
- C.bar.three=3
- C.bar.four=4
- D.foo.a=bar
- `
- out := &X{
- A: map[string]string{"foo": "bar", "bar": "bang"},
- B: map[string][]string{"foo": []string{"a", "b", "c"}, "bar": []string{"1", "2", "3"}},
- C: map[string]map[string]string{"foo": map[string]string{"one": "1", "two": "2"}, "bar": map[string]string{"three": "3", "four": "4"}},
- D: map[string]S{"foo": S{"bar"}},
- E: map[string]int{},
- }
- testDecode(t, in, &X{}, out)
-}
-
-func testDecode(t *testing.T, in string, v, out interface{}) {
- p, err := parse(in)
- if err != nil {
- t.Fatalf("got %v want nil", err)
- }
- if err := p.Decode(v); err != nil {
- t.Fatalf("got %v want nil", err)
- }
- if got, want := v, out; !reflect.DeepEqual(got, want) {
- t.Fatalf("\ngot %+v\nwant %+v", got, want)
- }
-}
-
-func tm(t *testing.T, layout, s string) time.Time {
- tm, err := time.Parse(layout, s)
- if err != nil {
- t.Fatalf("got %v want nil", err)
- }
- return tm
-}
diff --git a/vendor/github.com/magiconair/properties/doc.go b/vendor/github.com/magiconair/properties/doc.go
deleted file mode 100644
index 36c8368..0000000
--- a/vendor/github.com/magiconair/properties/doc.go
+++ /dev/null
@@ -1,156 +0,0 @@
-// Copyright 2017 Frank Schroeder. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Package properties provides functions for reading and writing
-// ISO-8859-1 and UTF-8 encoded .properties files and has
-// support for recursive property expansion.
-//
-// Java properties files are ISO-8859-1 encoded and use Unicode
-// literals for characters outside the ISO character set. Unicode
-// literals can be used in UTF-8 encoded properties files but
-// aren't necessary.
-//
-// To load a single properties file use MustLoadFile():
-//
-// p := properties.MustLoadFile(filename, properties.UTF8)
-//
-// To load multiple properties files use MustLoadFiles()
-// which loads the files in the given order and merges the
-// result. Missing properties files can be ignored if the
-// 'ignoreMissing' flag is set to true.
-//
-// Filenames can contain environment variables which are expanded
-// before loading.
-//
-// f1 := "/etc/myapp/myapp.conf"
-// f2 := "/home/${USER}/myapp.conf"
-// p := MustLoadFiles([]string{f1, f2}, properties.UTF8, true)
-//
-// All of the different key/value delimiters ' ', ':' and '=' are
-// supported as well as the comment characters '!' and '#' and
-// multi-line values.
-//
-// ! this is a comment
-// # and so is this
-//
-// # the following expressions are equal
-// key value
-// key=value
-// key:value
-// key = value
-// key : value
-// key = val\
-// ue
-//
-// Properties stores all comments preceding a key and provides
-// GetComments() and SetComments() methods to retrieve and
-// update them. The convenience functions GetComment() and
-// SetComment() allow access to the last comment. The
-// WriteComment() method writes properties files including
-// the comments and with the keys in the original order.
-// This can be used for sanitizing properties files.
-//
-// Property expansion is recursive and circular references
-// and malformed expressions are not allowed and cause an
-// error. Expansion of environment variables is supported.
-//
-// # standard property
-// key = value
-//
-// # property expansion: key2 = value
-// key2 = ${key}
-//
-// # recursive expansion: key3 = value
-// key3 = ${key2}
-//
-// # circular reference (error)
-// key = ${key}
-//
-// # malformed expression (error)
-// key = ${ke
-//
-// # refers to the users' home dir
-// home = ${HOME}
-//
-// # local key takes precendence over env var: u = foo
-// USER = foo
-// u = ${USER}
-//
-// The default property expansion format is ${key} but can be
-// changed by setting different pre- and postfix values on the
-// Properties object.
-//
-// p := properties.NewProperties()
-// p.Prefix = "#["
-// p.Postfix = "]#"
-//
-// Properties provides convenience functions for getting typed
-// values with default values if the key does not exist or the
-// type conversion failed.
-//
-// # Returns true if the value is either "1", "on", "yes" or "true"
-// # Returns false for every other value and the default value if
-// # the key does not exist.
-// v = p.GetBool("key", false)
-//
-// # Returns the value if the key exists and the format conversion
-// # was successful. Otherwise, the default value is returned.
-// v = p.GetInt64("key", 999)
-// v = p.GetUint64("key", 999)
-// v = p.GetFloat64("key", 123.0)
-// v = p.GetString("key", "def")
-// v = p.GetDuration("key", 999)
-//
-// As an alterantive properties may be applied with the standard
-// library's flag implementation at any time.
-//
-// # Standard configuration
-// v = flag.Int("key", 999, "help message")
-// flag.Parse()
-//
-// # Merge p into the flag set
-// p.MustFlag(flag.CommandLine)
-//
-// Properties provides several MustXXX() convenience functions
-// which will terminate the app if an error occurs. The behavior
-// of the failure is configurable and the default is to call
-// log.Fatal(err). To have the MustXXX() functions panic instead
-// of logging the error set a different ErrorHandler before
-// you use the Properties package.
-//
-// properties.ErrorHandler = properties.PanicHandler
-//
-// # Will panic instead of logging an error
-// p := properties.MustLoadFile("config.properties")
-//
-// You can also provide your own ErrorHandler function. The only requirement
-// is that the error handler function must exit after handling the error.
-//
-// properties.ErrorHandler = func(err error) {
-// fmt.Println(err)
-// os.Exit(1)
-// }
-//
-// # Will write to stdout and then exit
-// p := properties.MustLoadFile("config.properties")
-//
-// Properties can also be loaded into a struct via the `Decode`
-// method, e.g.
-//
-// type S struct {
-// A string `properties:"a,default=foo"`
-// D time.Duration `properties:"timeout,default=5s"`
-// E time.Time `properties:"expires,layout=2006-01-02,default=2015-01-01"`
-// }
-//
-// See `Decode()` method for the full documentation.
-//
-// The following documents provide a description of the properties
-// file format.
-//
-// http://en.wikipedia.org/wiki/.properties
-//
-// http://docs.oracle.com/javase/7/docs/api/java/util/Properties.html#load%28java.io.Reader%29
-//
-package properties
diff --git a/vendor/github.com/magiconair/properties/example_test.go b/vendor/github.com/magiconair/properties/example_test.go
deleted file mode 100644
index 6f21dfb..0000000
--- a/vendor/github.com/magiconair/properties/example_test.go
+++ /dev/null
@@ -1,93 +0,0 @@
-// Copyright 2017 Frank Schroeder. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package properties
-
-import (
- "fmt"
- "log"
-)
-
-func ExampleLoad_iso88591() {
- buf := []byte("key = ISO-8859-1 value with unicode literal \\u2318 and umlaut \xE4") // 0xE4 == ä
- p, _ := Load(buf, ISO_8859_1)
- v, ok := p.Get("key")
- fmt.Println(ok)
- fmt.Println(v)
- // Output:
- // true
- // ISO-8859-1 value with unicode literal ⌘ and umlaut ä
-}
-
-func ExampleLoad_utf8() {
- p, _ := Load([]byte("key = UTF-8 value with unicode character ⌘ and umlaut ä"), UTF8)
- v, ok := p.Get("key")
- fmt.Println(ok)
- fmt.Println(v)
- // Output:
- // true
- // UTF-8 value with unicode character ⌘ and umlaut ä
-}
-
-func ExampleProperties_GetBool() {
- var input = `
- key=1
- key2=On
- key3=YES
- key4=true`
- p, _ := Load([]byte(input), ISO_8859_1)
- fmt.Println(p.GetBool("key", false))
- fmt.Println(p.GetBool("key2", false))
- fmt.Println(p.GetBool("key3", false))
- fmt.Println(p.GetBool("key4", false))
- fmt.Println(p.GetBool("keyX", false))
- // Output:
- // true
- // true
- // true
- // true
- // false
-}
-
-func ExampleProperties_GetString() {
- p, _ := Load([]byte("key=value"), ISO_8859_1)
- v := p.GetString("another key", "default value")
- fmt.Println(v)
- // Output:
- // default value
-}
-
-func Example() {
- // Decode some key/value pairs with expressions
- p, err := Load([]byte("key=value\nkey2=${key}"), ISO_8859_1)
- if err != nil {
- log.Fatal(err)
- }
-
- // Get a valid key
- if v, ok := p.Get("key"); ok {
- fmt.Println(v)
- }
-
- // Get an invalid key
- if _, ok := p.Get("does not exist"); !ok {
- fmt.Println("invalid key")
- }
-
- // Get a key with a default value
- v := p.GetString("does not exist", "some value")
- fmt.Println(v)
-
- // Dump the expanded key/value pairs of the Properties
- fmt.Println("Expanded key/value pairs")
- fmt.Println(p)
-
- // Output:
- // value
- // invalid key
- // some value
- // Expanded key/value pairs
- // key = value
- // key2 = value
-}
diff --git a/vendor/github.com/magiconair/properties/integrate.go b/vendor/github.com/magiconair/properties/integrate.go
deleted file mode 100644
index 0d775e0..0000000
--- a/vendor/github.com/magiconair/properties/integrate.go
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright 2017 Frank Schroeder. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package properties
-
-import "flag"
-
-// MustFlag sets flags that are skipped by dst.Parse when p contains
-// the respective key for flag.Flag.Name.
-//
-// It's use is recommended with command line arguments as in:
-// flag.Parse()
-// p.MustFlag(flag.CommandLine)
-func (p *Properties) MustFlag(dst *flag.FlagSet) {
- m := make(map[string]*flag.Flag)
- dst.VisitAll(func(f *flag.Flag) {
- m[f.Name] = f
- })
- dst.Visit(func(f *flag.Flag) {
- delete(m, f.Name) // overridden
- })
-
- for name, f := range m {
- v, ok := p.Get(name)
- if !ok {
- continue
- }
-
- if err := f.Value.Set(v); err != nil {
- ErrorHandler(err)
- }
- }
-}
diff --git a/vendor/github.com/magiconair/properties/integrate_test.go b/vendor/github.com/magiconair/properties/integrate_test.go
deleted file mode 100644
index cbee181..0000000
--- a/vendor/github.com/magiconair/properties/integrate_test.go
+++ /dev/null
@@ -1,76 +0,0 @@
-// Copyright 2017 Frank Schroeder. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package properties
-
-import (
- "flag"
- "fmt"
- "testing"
-)
-
-// TestFlag verifies Properties.MustFlag without flag.FlagSet.Parse
-func TestFlag(t *testing.T) {
- f := flag.NewFlagSet("src", flag.PanicOnError)
- gotS := f.String("s", "?", "string flag")
- gotI := f.Int("i", -1, "int flag")
-
- p := NewProperties()
- p.MustSet("s", "t")
- p.MustSet("i", "9")
- p.MustFlag(f)
-
- if want := "t"; *gotS != want {
- t.Errorf("Got string s=%q, want %q", *gotS, want)
- }
- if want := 9; *gotI != want {
- t.Errorf("Got int i=%d, want %d", *gotI, want)
- }
-}
-
-// TestFlagOverride verifies Properties.MustFlag with flag.FlagSet.Parse.
-func TestFlagOverride(t *testing.T) {
- f := flag.NewFlagSet("src", flag.PanicOnError)
- gotA := f.Int("a", 1, "remain default")
- gotB := f.Int("b", 2, "customized")
- gotC := f.Int("c", 3, "overridden")
-
- if err := f.Parse([]string{"-c", "4"}); err != nil {
- t.Fatal(err)
- }
-
- p := NewProperties()
- p.MustSet("b", "5")
- p.MustSet("c", "6")
- p.MustFlag(f)
-
- if want := 1; *gotA != want {
- t.Errorf("Got remain default a=%d, want %d", *gotA, want)
- }
- if want := 5; *gotB != want {
- t.Errorf("Got customized b=%d, want %d", *gotB, want)
- }
- if want := 4; *gotC != want {
- t.Errorf("Got overriden c=%d, want %d", *gotC, want)
- }
-}
-
-func ExampleProperties_MustFlag() {
- x := flag.Int("x", 0, "demo customize")
- y := flag.Int("y", 0, "demo override")
-
- // Demo alternative for flag.Parse():
- flag.CommandLine.Parse([]string{"-y", "10"})
- fmt.Printf("flagged as x=%d, y=%d\n", *x, *y)
-
- p := NewProperties()
- p.MustSet("x", "7")
- p.MustSet("y", "42") // note discard
- p.MustFlag(flag.CommandLine)
- fmt.Printf("configured to x=%d, y=%d\n", *x, *y)
-
- // Output:
- // flagged as x=0, y=10
- // configured to x=7, y=10
-}
diff --git a/vendor/github.com/magiconair/properties/lex.go b/vendor/github.com/magiconair/properties/lex.go
deleted file mode 100644
index a3cba03..0000000
--- a/vendor/github.com/magiconair/properties/lex.go
+++ /dev/null
@@ -1,408 +0,0 @@
-// Copyright 2017 Frank Schroeder. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-//
-// Parts of the lexer are from the template/text/parser package
-// For these parts the following applies:
-//
-// Copyright 2011 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 of the go 1.2
-// distribution.
-
-package properties
-
-import (
- "fmt"
- "strconv"
- "strings"
- "unicode/utf8"
-)
-
-// item represents a token or text string returned from the scanner.
-type item struct {
- typ itemType // The type of this item.
- pos int // The starting position, in bytes, of this item in the input string.
- val string // The value of this item.
-}
-
-func (i item) String() string {
- switch {
- case i.typ == itemEOF:
- return "EOF"
- case i.typ == itemError:
- return i.val
- case len(i.val) > 10:
- return fmt.Sprintf("%.10q...", i.val)
- }
- return fmt.Sprintf("%q", i.val)
-}
-
-// itemType identifies the type of lex items.
-type itemType int
-
-const (
- itemError itemType = iota // error occurred; value is text of error
- itemEOF
- itemKey // a key
- itemValue // a value
- itemComment // a comment
-)
-
-// defines a constant for EOF
-const eof = -1
-
-// permitted whitespace characters space, FF and TAB
-const whitespace = " \f\t"
-
-// stateFn represents the state of the scanner as a function that returns the next state.
-type stateFn func(*lexer) stateFn
-
-// lexer holds the state of the scanner.
-type lexer struct {
- input string // the string being scanned
- state stateFn // the next lexing function to enter
- pos int // current position in the input
- start int // start position of this item
- width int // width of last rune read from input
- lastPos int // position of most recent item returned by nextItem
- runes []rune // scanned runes for this item
- items chan item // channel of scanned items
-}
-
-// next returns the next rune in the input.
-func (l *lexer) next() rune {
- if l.pos >= len(l.input) {
- l.width = 0
- return eof
- }
- r, w := utf8.DecodeRuneInString(l.input[l.pos:])
- l.width = w
- l.pos += l.width
- return r
-}
-
-// peek returns but does not consume the next rune in the input.
-func (l *lexer) peek() rune {
- r := l.next()
- l.backup()
- return r
-}
-
-// backup steps back one rune. Can only be called once per call of next.
-func (l *lexer) backup() {
- l.pos -= l.width
-}
-
-// emit passes an item back to the client.
-func (l *lexer) emit(t itemType) {
- i := item{t, l.start, string(l.runes)}
- l.items <- i
- l.start = l.pos
- l.runes = l.runes[:0]
-}
-
-// ignore skips over the pending input before this point.
-func (l *lexer) ignore() {
- l.start = l.pos
-}
-
-// appends the rune to the current value
-func (l *lexer) appendRune(r rune) {
- l.runes = append(l.runes, r)
-}
-
-// accept consumes the next rune if it's from the valid set.
-func (l *lexer) accept(valid string) bool {
- if strings.ContainsRune(valid, l.next()) {
- return true
- }
- l.backup()
- return false
-}
-
-// acceptRun consumes a run of runes from the valid set.
-func (l *lexer) acceptRun(valid string) {
- for strings.ContainsRune(valid, l.next()) {
- }
- l.backup()
-}
-
-// acceptRunUntil consumes a run of runes up to a terminator.
-func (l *lexer) acceptRunUntil(term rune) {
- for term != l.next() {
- }
- l.backup()
-}
-
-// hasText returns true if the current parsed text is not empty.
-func (l *lexer) isNotEmpty() bool {
- return l.pos > l.start
-}
-
-// lineNumber reports which line we're on, based on the position of
-// the previous item returned by nextItem. Doing it this way
-// means we don't have to worry about peek double counting.
-func (l *lexer) lineNumber() int {
- return 1 + strings.Count(l.input[:l.lastPos], "\n")
-}
-
-// errorf returns an error token and terminates the scan by passing
-// back a nil pointer that will be the next state, terminating l.nextItem.
-func (l *lexer) errorf(format string, args ...interface{}) stateFn {
- l.items <- item{itemError, l.start, fmt.Sprintf(format, args...)}
- return nil
-}
-
-// nextItem returns the next item from the input.
-func (l *lexer) nextItem() item {
- i := <-l.items
- l.lastPos = i.pos
- return i
-}
-
-// lex creates a new scanner for the input string.
-func lex(input string) *lexer {
- l := &lexer{
- input: input,
- items: make(chan item),
- runes: make([]rune, 0, 32),
- }
- go l.run()
- return l
-}
-
-// run runs the state machine for the lexer.
-func (l *lexer) run() {
- for l.state = lexBeforeKey(l); l.state != nil; {
- l.state = l.state(l)
- }
-}
-
-// state functions
-
-// lexBeforeKey scans until a key begins.
-func lexBeforeKey(l *lexer) stateFn {
- switch r := l.next(); {
- case isEOF(r):
- l.emit(itemEOF)
- return nil
-
- case isEOL(r):
- l.ignore()
- return lexBeforeKey
-
- case isComment(r):
- return lexComment
-
- case isWhitespace(r):
- l.acceptRun(whitespace)
- l.ignore()
- return lexKey
-
- default:
- l.backup()
- return lexKey
- }
-}
-
-// lexComment scans a comment line. The comment character has already been scanned.
-func lexComment(l *lexer) stateFn {
- l.acceptRun(whitespace)
- l.ignore()
- for {
- switch r := l.next(); {
- case isEOF(r):
- l.ignore()
- l.emit(itemEOF)
- return nil
- case isEOL(r):
- l.emit(itemComment)
- return lexBeforeKey
- default:
- l.appendRune(r)
- }
- }
-}
-
-// lexKey scans the key up to a delimiter
-func lexKey(l *lexer) stateFn {
- var r rune
-
-Loop:
- for {
- switch r = l.next(); {
-
- case isEscape(r):
- err := l.scanEscapeSequence()
- if err != nil {
- return l.errorf(err.Error())
- }
-
- case isEndOfKey(r):
- l.backup()
- break Loop
-
- case isEOF(r):
- break Loop
-
- default:
- l.appendRune(r)
- }
- }
-
- if len(l.runes) > 0 {
- l.emit(itemKey)
- }
-
- if isEOF(r) {
- l.emit(itemEOF)
- return nil
- }
-
- return lexBeforeValue
-}
-
-// lexBeforeValue scans the delimiter between key and value.
-// Leading and trailing whitespace is ignored.
-// We expect to be just after the key.
-func lexBeforeValue(l *lexer) stateFn {
- l.acceptRun(whitespace)
- l.accept(":=")
- l.acceptRun(whitespace)
- l.ignore()
- return lexValue
-}
-
-// lexValue scans text until the end of the line. We expect to be just after the delimiter.
-func lexValue(l *lexer) stateFn {
- for {
- switch r := l.next(); {
- case isEscape(r):
- if isEOL(l.peek()) {
- l.next()
- l.acceptRun(whitespace)
- } else {
- err := l.scanEscapeSequence()
- if err != nil {
- return l.errorf(err.Error())
- }
- }
-
- case isEOL(r):
- l.emit(itemValue)
- l.ignore()
- return lexBeforeKey
-
- case isEOF(r):
- l.emit(itemValue)
- l.emit(itemEOF)
- return nil
-
- default:
- l.appendRune(r)
- }
- }
-}
-
-// scanEscapeSequence scans either one of the escaped characters
-// or a unicode literal. We expect to be after the escape character.
-func (l *lexer) scanEscapeSequence() error {
- switch r := l.next(); {
-
- case isEscapedCharacter(r):
- l.appendRune(decodeEscapedCharacter(r))
- return nil
-
- case atUnicodeLiteral(r):
- return l.scanUnicodeLiteral()
-
- case isEOF(r):
- return fmt.Errorf("premature EOF")
-
- // silently drop the escape character and append the rune as is
- default:
- l.appendRune(r)
- return nil
- }
-}
-
-// scans a unicode literal in the form \uXXXX. We expect to be after the \u.
-func (l *lexer) scanUnicodeLiteral() error {
- // scan the digits
- d := make([]rune, 4)
- for i := 0; i < 4; i++ {
- d[i] = l.next()
- if d[i] == eof || !strings.ContainsRune("0123456789abcdefABCDEF", d[i]) {
- return fmt.Errorf("invalid unicode literal")
- }
- }
-
- // decode the digits into a rune
- r, err := strconv.ParseInt(string(d), 16, 0)
- if err != nil {
- return err
- }
-
- l.appendRune(rune(r))
- return nil
-}
-
-// decodeEscapedCharacter returns the unescaped rune. We expect to be after the escape character.
-func decodeEscapedCharacter(r rune) rune {
- switch r {
- case 'f':
- return '\f'
- case 'n':
- return '\n'
- case 'r':
- return '\r'
- case 't':
- return '\t'
- default:
- return r
- }
-}
-
-// atUnicodeLiteral reports whether we are at a unicode literal.
-// The escape character has already been consumed.
-func atUnicodeLiteral(r rune) bool {
- return r == 'u'
-}
-
-// isComment reports whether we are at the start of a comment.
-func isComment(r rune) bool {
- return r == '#' || r == '!'
-}
-
-// isEndOfKey reports whether the rune terminates the current key.
-func isEndOfKey(r rune) bool {
- return strings.ContainsRune(" \f\t\r\n:=", r)
-}
-
-// isEOF reports whether we are at EOF.
-func isEOF(r rune) bool {
- return r == eof
-}
-
-// isEOL reports whether we are at a new line character.
-func isEOL(r rune) bool {
- return r == '\n' || r == '\r'
-}
-
-// isEscape reports whether the rune is the escape character which
-// prefixes unicode literals and other escaped characters.
-func isEscape(r rune) bool {
- return r == '\\'
-}
-
-// isEscapedCharacter reports whether we are at one of the characters that need escaping.
-// The escape character has already been consumed.
-func isEscapedCharacter(r rune) bool {
- return strings.ContainsRune(" :=fnrt", r)
-}
-
-// isWhitespace reports whether the rune is a whitespace character.
-func isWhitespace(r rune) bool {
- return strings.ContainsRune(whitespace, r)
-}
diff --git a/vendor/github.com/magiconair/properties/load.go b/vendor/github.com/magiconair/properties/load.go
deleted file mode 100644
index 278cc2e..0000000
--- a/vendor/github.com/magiconair/properties/load.go
+++ /dev/null
@@ -1,241 +0,0 @@
-// Copyright 2017 Frank Schroeder. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package properties
-
-import (
- "fmt"
- "io/ioutil"
- "net/http"
- "os"
- "strings"
-)
-
-// Encoding specifies encoding of the input data.
-type Encoding uint
-
-const (
- // UTF8 interprets the input data as UTF-8.
- UTF8 Encoding = 1 << iota
-
- // ISO_8859_1 interprets the input data as ISO-8859-1.
- ISO_8859_1
-)
-
-// Load reads a buffer into a Properties struct.
-func Load(buf []byte, enc Encoding) (*Properties, error) {
- return loadBuf(buf, enc)
-}
-
-// LoadString reads an UTF8 string into a properties struct.
-func LoadString(s string) (*Properties, error) {
- return loadBuf([]byte(s), UTF8)
-}
-
-// LoadMap creates a new Properties struct from a string map.
-func LoadMap(m map[string]string) *Properties {
- p := NewProperties()
- for k, v := range m {
- p.Set(k, v)
- }
- return p
-}
-
-// LoadFile reads a file into a Properties struct.
-func LoadFile(filename string, enc Encoding) (*Properties, error) {
- return loadAll([]string{filename}, enc, false)
-}
-
-// LoadFiles reads multiple files in the given order into
-// a Properties struct. If 'ignoreMissing' is true then
-// non-existent files will not be reported as error.
-func LoadFiles(filenames []string, enc Encoding, ignoreMissing bool) (*Properties, error) {
- return loadAll(filenames, enc, ignoreMissing)
-}
-
-// LoadURL reads the content of the URL into a Properties struct.
-//
-// The encoding is determined via the Content-Type header which
-// should be set to 'text/plain'. If the 'charset' parameter is
-// missing, 'iso-8859-1' or 'latin1' the encoding is set to
-// ISO-8859-1. If the 'charset' parameter is set to 'utf-8' the
-// encoding is set to UTF-8. A missing content type header is
-// interpreted as 'text/plain; charset=utf-8'.
-func LoadURL(url string) (*Properties, error) {
- return loadAll([]string{url}, UTF8, false)
-}
-
-// LoadURLs reads the content of multiple URLs in the given order into a
-// Properties struct. If 'ignoreMissing' is true then a 404 status code will
-// not be reported as error. See LoadURL for the Content-Type header
-// and the encoding.
-func LoadURLs(urls []string, ignoreMissing bool) (*Properties, error) {
- return loadAll(urls, UTF8, ignoreMissing)
-}
-
-// LoadAll reads the content of multiple URLs or files in the given order into a
-// Properties struct. If 'ignoreMissing' is true then a 404 status code or missing file will
-// not be reported as error. Encoding sets the encoding for files. For the URLs please see
-// LoadURL for the Content-Type header and the encoding.
-func LoadAll(names []string, enc Encoding, ignoreMissing bool) (*Properties, error) {
- return loadAll(names, enc, ignoreMissing)
-}
-
-// MustLoadString reads an UTF8 string into a Properties struct and
-// panics on error.
-func MustLoadString(s string) *Properties {
- return must(LoadString(s))
-}
-
-// MustLoadFile reads a file into a Properties struct and
-// panics on error.
-func MustLoadFile(filename string, enc Encoding) *Properties {
- return must(LoadFile(filename, enc))
-}
-
-// MustLoadFiles reads multiple files in the given order into
-// a Properties struct and panics on error. If 'ignoreMissing'
-// is true then non-existent files will not be reported as error.
-func MustLoadFiles(filenames []string, enc Encoding, ignoreMissing bool) *Properties {
- return must(LoadFiles(filenames, enc, ignoreMissing))
-}
-
-// MustLoadURL reads the content of a URL into a Properties struct and
-// panics on error.
-func MustLoadURL(url string) *Properties {
- return must(LoadURL(url))
-}
-
-// MustLoadURLs reads the content of multiple URLs in the given order into a
-// Properties struct and panics on error. If 'ignoreMissing' is true then a 404
-// status code will not be reported as error.
-func MustLoadURLs(urls []string, ignoreMissing bool) *Properties {
- return must(LoadURLs(urls, ignoreMissing))
-}
-
-// MustLoadAll reads the content of multiple URLs or files in the given order into a
-// Properties struct. If 'ignoreMissing' is true then a 404 status code or missing file will
-// not be reported as error. Encoding sets the encoding for files. For the URLs please see
-// LoadURL for the Content-Type header and the encoding. It panics on error.
-func MustLoadAll(names []string, enc Encoding, ignoreMissing bool) *Properties {
- return must(LoadAll(names, enc, ignoreMissing))
-}
-
-func loadBuf(buf []byte, enc Encoding) (*Properties, error) {
- p, err := parse(convert(buf, enc))
- if err != nil {
- return nil, err
- }
- return p, p.check()
-}
-
-func loadAll(names []string, enc Encoding, ignoreMissing bool) (*Properties, error) {
- result := NewProperties()
- for _, name := range names {
- n, err := expandName(name)
- if err != nil {
- return nil, err
- }
- var p *Properties
- if strings.HasPrefix(n, "http://") || strings.HasPrefix(n, "https://") {
- p, err = loadURL(n, ignoreMissing)
- } else {
- p, err = loadFile(n, enc, ignoreMissing)
- }
- if err != nil {
- return nil, err
- }
- result.Merge(p)
-
- }
- return result, result.check()
-}
-
-func loadFile(filename string, enc Encoding, ignoreMissing bool) (*Properties, error) {
- data, err := ioutil.ReadFile(filename)
- if err != nil {
- if ignoreMissing && os.IsNotExist(err) {
- LogPrintf("properties: %s not found. skipping", filename)
- return NewProperties(), nil
- }
- return nil, err
- }
- p, err := parse(convert(data, enc))
- if err != nil {
- return nil, err
- }
- return p, nil
-}
-
-func loadURL(url string, ignoreMissing bool) (*Properties, error) {
- resp, err := http.Get(url)
- if err != nil {
- return nil, fmt.Errorf("properties: error fetching %q. %s", url, err)
- }
- if resp.StatusCode == 404 && ignoreMissing {
- LogPrintf("properties: %s returned %d. skipping", url, resp.StatusCode)
- return NewProperties(), nil
- }
- if resp.StatusCode != 200 {
- return nil, fmt.Errorf("properties: %s returned %d", url, resp.StatusCode)
- }
- body, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- return nil, fmt.Errorf("properties: %s error reading response. %s", url, err)
- }
- if err = resp.Body.Close(); err != nil {
- return nil, fmt.Errorf("properties: %s error reading response. %s", url, err)
- }
-
- ct := resp.Header.Get("Content-Type")
- var enc Encoding
- switch strings.ToLower(ct) {
- case "text/plain", "text/plain; charset=iso-8859-1", "text/plain; charset=latin1":
- enc = ISO_8859_1
- case "", "text/plain; charset=utf-8":
- enc = UTF8
- default:
- return nil, fmt.Errorf("properties: invalid content type %s", ct)
- }
-
- p, err := parse(convert(body, enc))
- if err != nil {
- return nil, err
- }
- return p, nil
-}
-
-func must(p *Properties, err error) *Properties {
- if err != nil {
- ErrorHandler(err)
- }
- return p
-}
-
-// expandName expands ${ENV_VAR} expressions in a name.
-// If the environment variable does not exist then it will be replaced
-// with an empty string. Malformed expressions like "${ENV_VAR" will
-// be reported as error.
-func expandName(name string) (string, error) {
- return expand(name, make(map[string]bool), "${", "}", make(map[string]string))
-}
-
-// Interprets a byte buffer either as an ISO-8859-1 or UTF-8 encoded string.
-// For ISO-8859-1 we can convert each byte straight into a rune since the
-// first 256 unicode code points cover ISO-8859-1.
-func convert(buf []byte, enc Encoding) string {
- switch enc {
- case UTF8:
- return string(buf)
- case ISO_8859_1:
- runes := make([]rune, len(buf))
- for i, b := range buf {
- runes[i] = rune(b)
- }
- return string(runes)
- default:
- ErrorHandler(fmt.Errorf("unsupported encoding %v", enc))
- }
- panic("ErrorHandler should exit")
-}
diff --git a/vendor/github.com/magiconair/properties/load_test.go b/vendor/github.com/magiconair/properties/load_test.go
deleted file mode 100644
index d8770c8..0000000
--- a/vendor/github.com/magiconair/properties/load_test.go
+++ /dev/null
@@ -1,231 +0,0 @@
-// Copyright 2017 Frank Schroeder. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package properties
-
-import (
- "fmt"
- "io/ioutil"
- "net/http"
- "net/http/httptest"
- "os"
- "strings"
- "testing"
-
- "github.com/magiconair/properties/assert"
-)
-
-func TestLoadFailsWithNotExistingFile(t *testing.T) {
- _, err := LoadFile("doesnotexist.properties", ISO_8859_1)
- assert.Equal(t, err != nil, true, "")
- assert.Matches(t, err.Error(), "open.*no such file or directory")
-}
-
-func TestLoadFilesFailsOnNotExistingFile(t *testing.T) {
- _, err := LoadFile("doesnotexist.properties", ISO_8859_1)
- assert.Equal(t, err != nil, true, "")
- assert.Matches(t, err.Error(), "open.*no such file or directory")
-}
-
-func TestLoadFilesDoesNotFailOnNotExistingFileAndIgnoreMissing(t *testing.T) {
- p, err := LoadFiles([]string{"doesnotexist.properties"}, ISO_8859_1, true)
- assert.Equal(t, err, nil)
- assert.Equal(t, p.Len(), 0)
-}
-
-func TestLoadString(t *testing.T) {
- x := "key=äüö"
- p1 := MustLoadString(x)
- p2 := must(Load([]byte(x), UTF8))
- assert.Equal(t, p1, p2)
-}
-
-func TestLoadMap(t *testing.T) {
- // LoadMap does not guarantee the same import order
- // of keys every time since map access is randomized.
- // Therefore, we need to compare the generated maps.
- m := map[string]string{"key": "value", "abc": "def"}
- assert.Equal(t, LoadMap(m).Map(), m)
-}
-
-func TestLoadFile(t *testing.T) {
- tf := make(tempFiles, 0)
- defer tf.removeAll()
-
- filename := tf.makeFile("key=value")
- p := MustLoadFile(filename, ISO_8859_1)
-
- assert.Equal(t, p.Len(), 1)
- assertKeyValues(t, "", p, "key", "value")
-}
-
-func TestLoadFiles(t *testing.T) {
- tf := make(tempFiles, 0)
- defer tf.removeAll()
-
- filename := tf.makeFile("key=value")
- filename2 := tf.makeFile("key2=value2")
- p := MustLoadFiles([]string{filename, filename2}, ISO_8859_1, false)
- assertKeyValues(t, "", p, "key", "value", "key2", "value2")
-}
-
-func TestLoadExpandedFile(t *testing.T) {
- tf := make(tempFiles, 0)
- defer tf.removeAll()
-
- if err := os.Setenv("_VARX", "some-value"); err != nil {
- t.Fatal(err)
- }
- filename := tf.makeFilePrefix(os.Getenv("_VARX"), "key=value")
- filename = strings.Replace(filename, os.Getenv("_VARX"), "${_VARX}", -1)
- p := MustLoadFile(filename, ISO_8859_1)
- assertKeyValues(t, "", p, "key", "value")
-}
-
-func TestLoadFilesAndIgnoreMissing(t *testing.T) {
- tf := make(tempFiles, 0)
- defer tf.removeAll()
-
- filename := tf.makeFile("key=value")
- filename2 := tf.makeFile("key2=value2")
- p := MustLoadFiles([]string{filename, filename + "foo", filename2, filename2 + "foo"}, ISO_8859_1, true)
- assertKeyValues(t, "", p, "key", "value", "key2", "value2")
-}
-
-func TestLoadURL(t *testing.T) {
- srv := testServer()
- defer srv.Close()
- p := MustLoadURL(srv.URL + "/a")
- assertKeyValues(t, "", p, "key", "value")
-}
-
-func TestLoadURLs(t *testing.T) {
- srv := testServer()
- defer srv.Close()
- p := MustLoadURLs([]string{srv.URL + "/a", srv.URL + "/b"}, false)
- assertKeyValues(t, "", p, "key", "value", "key2", "value2")
-}
-
-func TestLoadURLsAndFailMissing(t *testing.T) {
- srv := testServer()
- defer srv.Close()
- p, err := LoadURLs([]string{srv.URL + "/a", srv.URL + "/c"}, false)
- assert.Equal(t, p, (*Properties)(nil))
- assert.Matches(t, err.Error(), ".*returned 404.*")
-}
-
-func TestLoadURLsAndIgnoreMissing(t *testing.T) {
- srv := testServer()
- defer srv.Close()
- p := MustLoadURLs([]string{srv.URL + "/a", srv.URL + "/b", srv.URL + "/c"}, true)
- assertKeyValues(t, "", p, "key", "value", "key2", "value2")
-}
-
-func TestLoadURLEncoding(t *testing.T) {
- srv := testServer()
- defer srv.Close()
-
- uris := []string{"/none", "/utf8", "/plain", "/latin1", "/iso88591"}
- for i, uri := range uris {
- p := MustLoadURL(srv.URL + uri)
- assert.Equal(t, p.GetString("key", ""), "äöü", fmt.Sprintf("%d", i))
- }
-}
-
-func TestLoadURLFailInvalidEncoding(t *testing.T) {
- srv := testServer()
- defer srv.Close()
-
- p, err := LoadURL(srv.URL + "/json")
- assert.Equal(t, p, (*Properties)(nil))
- assert.Matches(t, err.Error(), ".*invalid content type.*")
-}
-
-func TestLoadAll(t *testing.T) {
- tf := make(tempFiles, 0)
- defer tf.removeAll()
-
- filename := tf.makeFile("key=value")
- filename2 := tf.makeFile("key2=value3")
- filename3 := tf.makeFile("key=value4")
- srv := testServer()
- defer srv.Close()
- p := MustLoadAll([]string{filename, filename2, srv.URL + "/a", srv.URL + "/b", filename3}, UTF8, false)
- assertKeyValues(t, "", p, "key", "value4", "key2", "value2")
-}
-
-type tempFiles []string
-
-func (tf *tempFiles) removeAll() {
- for _, path := range *tf {
- err := os.Remove(path)
- if err != nil {
- fmt.Printf("os.Remove: %v", err)
- }
- }
-}
-
-func (tf *tempFiles) makeFile(data string) string {
- return tf.makeFilePrefix("properties", data)
-}
-
-func (tf *tempFiles) makeFilePrefix(prefix, data string) string {
- f, err := ioutil.TempFile("", prefix)
- if err != nil {
- panic("ioutil.TempFile: " + err.Error())
- }
-
- // remember the temp file so that we can remove it later
- *tf = append(*tf, f.Name())
-
- n, err := fmt.Fprint(f, data)
- if err != nil {
- panic("fmt.Fprintln: " + err.Error())
- }
- if n != len(data) {
- panic(fmt.Sprintf("Data size mismatch. expected=%d wrote=%d\n", len(data), n))
- }
-
- err = f.Close()
- if err != nil {
- panic("f.Close: " + err.Error())
- }
-
- return f.Name()
-}
-
-func testServer() *httptest.Server {
- return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- send := func(data []byte, contentType string) {
- w.Header().Set("Content-Type", contentType)
- if _, err := w.Write(data); err != nil {
- panic(err)
- }
- }
-
- utf8 := []byte("key=äöü")
- iso88591 := []byte{0x6b, 0x65, 0x79, 0x3d, 0xe4, 0xf6, 0xfc} // key=äöü
-
- switch r.RequestURI {
- case "/a":
- send([]byte("key=value"), "")
- case "/b":
- send([]byte("key2=value2"), "")
- case "/none":
- send(utf8, "")
- case "/utf8":
- send(utf8, "text/plain; charset=utf-8")
- case "/json":
- send(utf8, "application/json; charset=utf-8")
- case "/plain":
- send(iso88591, "text/plain")
- case "/latin1":
- send(iso88591, "text/plain; charset=latin1")
- case "/iso88591":
- send(iso88591, "text/plain; charset=iso-8859-1")
- default:
- w.WriteHeader(404)
- }
- }))
-}
diff --git a/vendor/github.com/magiconair/properties/parser.go b/vendor/github.com/magiconair/properties/parser.go
deleted file mode 100644
index 90f555c..0000000
--- a/vendor/github.com/magiconair/properties/parser.go
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright 2017 Frank Schroeder. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package properties
-
-import (
- "fmt"
- "runtime"
-)
-
-type parser struct {
- lex *lexer
-}
-
-func parse(input string) (properties *Properties, err error) {
- p := &parser{lex: lex(input)}
- defer p.recover(&err)
-
- properties = NewProperties()
- key := ""
- comments := []string{}
-
- for {
- token := p.expectOneOf(itemComment, itemKey, itemEOF)
- switch token.typ {
- case itemEOF:
- goto done
- case itemComment:
- comments = append(comments, token.val)
- continue
- case itemKey:
- key = token.val
- if _, ok := properties.m[key]; !ok {
- properties.k = append(properties.k, key)
- }
- }
-
- token = p.expectOneOf(itemValue, itemEOF)
- if len(comments) > 0 {
- properties.c[key] = comments
- comments = []string{}
- }
- switch token.typ {
- case itemEOF:
- properties.m[key] = ""
- goto done
- case itemValue:
- properties.m[key] = token.val
- }
- }
-
-done:
- return properties, nil
-}
-
-func (p *parser) errorf(format string, args ...interface{}) {
- format = fmt.Sprintf("properties: Line %d: %s", p.lex.lineNumber(), format)
- panic(fmt.Errorf(format, args...))
-}
-
-func (p *parser) expect(expected itemType) (token item) {
- token = p.lex.nextItem()
- if token.typ != expected {
- p.unexpected(token)
- }
- return token
-}
-
-func (p *parser) expectOneOf(expected ...itemType) (token item) {
- token = p.lex.nextItem()
- for _, v := range expected {
- if token.typ == v {
- return token
- }
- }
- p.unexpected(token)
- panic("unexpected token")
-}
-
-func (p *parser) unexpected(token item) {
- p.errorf(token.String())
-}
-
-// recover is the handler that turns panics into returns from the top level of Parse.
-func (p *parser) recover(errp *error) {
- e := recover()
- if e != nil {
- if _, ok := e.(runtime.Error); ok {
- panic(e)
- }
- *errp = e.(error)
- }
- return
-}
diff --git a/vendor/github.com/magiconair/properties/properties.go b/vendor/github.com/magiconair/properties/properties.go
deleted file mode 100644
index 4f3d5a4..0000000
--- a/vendor/github.com/magiconair/properties/properties.go
+++ /dev/null
@@ -1,808 +0,0 @@
-// Copyright 2017 Frank Schroeder. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package properties
-
-// BUG(frank): Set() does not check for invalid unicode literals since this is currently handled by the lexer.
-// BUG(frank): Write() does not allow to configure the newline character. Therefore, on Windows LF is used.
-
-import (
- "fmt"
- "io"
- "log"
- "os"
- "regexp"
- "strconv"
- "strings"
- "time"
- "unicode/utf8"
-)
-
-// ErrorHandlerFunc defines the type of function which handles failures
-// of the MustXXX() functions. An error handler function must exit
-// the application after handling the error.
-type ErrorHandlerFunc func(error)
-
-// ErrorHandler is the function which handles failures of the MustXXX()
-// functions. The default is LogFatalHandler.
-var ErrorHandler ErrorHandlerFunc = LogFatalHandler
-
-// LogHandlerFunc defines the function prototype for logging errors.
-type LogHandlerFunc func(fmt string, args ...interface{})
-
-// LogPrintf defines a log handler which uses log.Printf.
-var LogPrintf LogHandlerFunc = log.Printf
-
-// LogFatalHandler handles the error by logging a fatal error and exiting.
-func LogFatalHandler(err error) {
- log.Fatal(err)
-}
-
-// PanicHandler handles the error by panicking.
-func PanicHandler(err error) {
- panic(err)
-}
-
-// -----------------------------------------------------------------------------
-
-// A Properties contains the key/value pairs from the properties input.
-// All values are stored in unexpanded form and are expanded at runtime
-type Properties struct {
- // Pre-/Postfix for property expansion.
- Prefix string
- Postfix string
-
- // DisableExpansion controls the expansion of properties on Get()
- // and the check for circular references on Set(). When set to
- // true Properties behaves like a simple key/value store and does
- // not check for circular references on Get() or on Set().
- DisableExpansion bool
-
- // Stores the key/value pairs
- m map[string]string
-
- // Stores the comments per key.
- c map[string][]string
-
- // Stores the keys in order of appearance.
- k []string
-}
-
-// NewProperties creates a new Properties struct with the default
-// configuration for "${key}" expressions.
-func NewProperties() *Properties {
- return &Properties{
- Prefix: "${",
- Postfix: "}",
- m: map[string]string{},
- c: map[string][]string{},
- k: []string{},
- }
-}
-
-// Get returns the expanded value for the given key if exists.
-// Otherwise, ok is false.
-func (p *Properties) Get(key string) (value string, ok bool) {
- v, ok := p.m[key]
- if p.DisableExpansion {
- return v, ok
- }
- if !ok {
- return "", false
- }
-
- expanded, err := p.expand(v)
-
- // we guarantee that the expanded value is free of
- // circular references and malformed expressions
- // so we panic if we still get an error here.
- if err != nil {
- ErrorHandler(fmt.Errorf("%s in %q", err, key+" = "+v))
- }
-
- return expanded, true
-}
-
-// MustGet returns the expanded value for the given key if exists.
-// Otherwise, it panics.
-func (p *Properties) MustGet(key string) string {
- if v, ok := p.Get(key); ok {
- return v
- }
- ErrorHandler(invalidKeyError(key))
- panic("ErrorHandler should exit")
-}
-
-// ----------------------------------------------------------------------------
-
-// ClearComments removes the comments for all keys.
-func (p *Properties) ClearComments() {
- p.c = map[string][]string{}
-}
-
-// ----------------------------------------------------------------------------
-
-// GetComment returns the last comment before the given key or an empty string.
-func (p *Properties) GetComment(key string) string {
- comments, ok := p.c[key]
- if !ok || len(comments) == 0 {
- return ""
- }
- return comments[len(comments)-1]
-}
-
-// ----------------------------------------------------------------------------
-
-// GetComments returns all comments that appeared before the given key or nil.
-func (p *Properties) GetComments(key string) []string {
- if comments, ok := p.c[key]; ok {
- return comments
- }
- return nil
-}
-
-// ----------------------------------------------------------------------------
-
-// SetComment sets the comment for the key.
-func (p *Properties) SetComment(key, comment string) {
- p.c[key] = []string{comment}
-}
-
-// ----------------------------------------------------------------------------
-
-// SetComments sets the comments for the key. If the comments are nil then
-// all comments for this key are deleted.
-func (p *Properties) SetComments(key string, comments []string) {
- if comments == nil {
- delete(p.c, key)
- return
- }
- p.c[key] = comments
-}
-
-// ----------------------------------------------------------------------------
-
-// GetBool checks if the expanded value is one of '1', 'yes',
-// 'true' or 'on' if the key exists. The comparison is case-insensitive.
-// If the key does not exist the default value is returned.
-func (p *Properties) GetBool(key string, def bool) bool {
- v, err := p.getBool(key)
- if err != nil {
- return def
- }
- return v
-}
-
-// MustGetBool checks if the expanded value is one of '1', 'yes',
-// 'true' or 'on' if the key exists. The comparison is case-insensitive.
-// If the key does not exist the function panics.
-func (p *Properties) MustGetBool(key string) bool {
- v, err := p.getBool(key)
- if err != nil {
- ErrorHandler(err)
- }
- return v
-}
-
-func (p *Properties) getBool(key string) (value bool, err error) {
- if v, ok := p.Get(key); ok {
- return boolVal(v), nil
- }
- return false, invalidKeyError(key)
-}
-
-func boolVal(v string) bool {
- v = strings.ToLower(v)
- return v == "1" || v == "true" || v == "yes" || v == "on"
-}
-
-// ----------------------------------------------------------------------------
-
-// GetDuration parses the expanded value as an time.Duration (in ns) if the
-// key exists. If key does not exist or the value cannot be parsed the default
-// value is returned. In almost all cases you want to use GetParsedDuration().
-func (p *Properties) GetDuration(key string, def time.Duration) time.Duration {
- v, err := p.getInt64(key)
- if err != nil {
- return def
- }
- return time.Duration(v)
-}
-
-// MustGetDuration parses the expanded value as an time.Duration (in ns) if
-// the key exists. If key does not exist or the value cannot be parsed the
-// function panics. In almost all cases you want to use MustGetParsedDuration().
-func (p *Properties) MustGetDuration(key string) time.Duration {
- v, err := p.getInt64(key)
- if err != nil {
- ErrorHandler(err)
- }
- return time.Duration(v)
-}
-
-// ----------------------------------------------------------------------------
-
-// GetParsedDuration parses the expanded value with time.ParseDuration() if the key exists.
-// If key does not exist or the value cannot be parsed the default
-// value is returned.
-func (p *Properties) GetParsedDuration(key string, def time.Duration) time.Duration {
- s, ok := p.Get(key)
- if !ok {
- return def
- }
- v, err := time.ParseDuration(s)
- if err != nil {
- return def
- }
- return v
-}
-
-// MustGetParsedDuration parses the expanded value with time.ParseDuration() if the key exists.
-// If key does not exist or the value cannot be parsed the function panics.
-func (p *Properties) MustGetParsedDuration(key string) time.Duration {
- s, ok := p.Get(key)
- if !ok {
- ErrorHandler(invalidKeyError(key))
- }
- v, err := time.ParseDuration(s)
- if err != nil {
- ErrorHandler(err)
- }
- return v
-}
-
-// ----------------------------------------------------------------------------
-
-// GetFloat64 parses the expanded value as a float64 if the key exists.
-// If key does not exist or the value cannot be parsed the default
-// value is returned.
-func (p *Properties) GetFloat64(key string, def float64) float64 {
- v, err := p.getFloat64(key)
- if err != nil {
- return def
- }
- return v
-}
-
-// MustGetFloat64 parses the expanded value as a float64 if the key exists.
-// If key does not exist or the value cannot be parsed the function panics.
-func (p *Properties) MustGetFloat64(key string) float64 {
- v, err := p.getFloat64(key)
- if err != nil {
- ErrorHandler(err)
- }
- return v
-}
-
-func (p *Properties) getFloat64(key string) (value float64, err error) {
- if v, ok := p.Get(key); ok {
- value, err = strconv.ParseFloat(v, 64)
- if err != nil {
- return 0, err
- }
- return value, nil
- }
- return 0, invalidKeyError(key)
-}
-
-// ----------------------------------------------------------------------------
-
-// GetInt parses the expanded value as an int if the key exists.
-// If key does not exist or the value cannot be parsed the default
-// value is returned. If the value does not fit into an int the
-// function panics with an out of range error.
-func (p *Properties) GetInt(key string, def int) int {
- v, err := p.getInt64(key)
- if err != nil {
- return def
- }
- return intRangeCheck(key, v)
-}
-
-// MustGetInt parses the expanded value as an int if the key exists.
-// If key does not exist or the value cannot be parsed the function panics.
-// If the value does not fit into an int the function panics with
-// an out of range error.
-func (p *Properties) MustGetInt(key string) int {
- v, err := p.getInt64(key)
- if err != nil {
- ErrorHandler(err)
- }
- return intRangeCheck(key, v)
-}
-
-// ----------------------------------------------------------------------------
-
-// GetInt64 parses the expanded value as an int64 if the key exists.
-// If key does not exist or the value cannot be parsed the default
-// value is returned.
-func (p *Properties) GetInt64(key string, def int64) int64 {
- v, err := p.getInt64(key)
- if err != nil {
- return def
- }
- return v
-}
-
-// MustGetInt64 parses the expanded value as an int if the key exists.
-// If key does not exist or the value cannot be parsed the function panics.
-func (p *Properties) MustGetInt64(key string) int64 {
- v, err := p.getInt64(key)
- if err != nil {
- ErrorHandler(err)
- }
- return v
-}
-
-func (p *Properties) getInt64(key string) (value int64, err error) {
- if v, ok := p.Get(key); ok {
- value, err = strconv.ParseInt(v, 10, 64)
- if err != nil {
- return 0, err
- }
- return value, nil
- }
- return 0, invalidKeyError(key)
-}
-
-// ----------------------------------------------------------------------------
-
-// GetUint parses the expanded value as an uint if the key exists.
-// If key does not exist or the value cannot be parsed the default
-// value is returned. If the value does not fit into an int the
-// function panics with an out of range error.
-func (p *Properties) GetUint(key string, def uint) uint {
- v, err := p.getUint64(key)
- if err != nil {
- return def
- }
- return uintRangeCheck(key, v)
-}
-
-// MustGetUint parses the expanded value as an int if the key exists.
-// If key does not exist or the value cannot be parsed the function panics.
-// If the value does not fit into an int the function panics with
-// an out of range error.
-func (p *Properties) MustGetUint(key string) uint {
- v, err := p.getUint64(key)
- if err != nil {
- ErrorHandler(err)
- }
- return uintRangeCheck(key, v)
-}
-
-// ----------------------------------------------------------------------------
-
-// GetUint64 parses the expanded value as an uint64 if the key exists.
-// If key does not exist or the value cannot be parsed the default
-// value is returned.
-func (p *Properties) GetUint64(key string, def uint64) uint64 {
- v, err := p.getUint64(key)
- if err != nil {
- return def
- }
- return v
-}
-
-// MustGetUint64 parses the expanded value as an int if the key exists.
-// If key does not exist or the value cannot be parsed the function panics.
-func (p *Properties) MustGetUint64(key string) uint64 {
- v, err := p.getUint64(key)
- if err != nil {
- ErrorHandler(err)
- }
- return v
-}
-
-func (p *Properties) getUint64(key string) (value uint64, err error) {
- if v, ok := p.Get(key); ok {
- value, err = strconv.ParseUint(v, 10, 64)
- if err != nil {
- return 0, err
- }
- return value, nil
- }
- return 0, invalidKeyError(key)
-}
-
-// ----------------------------------------------------------------------------
-
-// GetString returns the expanded value for the given key if exists or
-// the default value otherwise.
-func (p *Properties) GetString(key, def string) string {
- if v, ok := p.Get(key); ok {
- return v
- }
- return def
-}
-
-// MustGetString returns the expanded value for the given key if exists or
-// panics otherwise.
-func (p *Properties) MustGetString(key string) string {
- if v, ok := p.Get(key); ok {
- return v
- }
- ErrorHandler(invalidKeyError(key))
- panic("ErrorHandler should exit")
-}
-
-// ----------------------------------------------------------------------------
-
-// Filter returns a new properties object which contains all properties
-// for which the key matches the pattern.
-func (p *Properties) Filter(pattern string) (*Properties, error) {
- re, err := regexp.Compile(pattern)
- if err != nil {
- return nil, err
- }
-
- return p.FilterRegexp(re), nil
-}
-
-// FilterRegexp returns a new properties object which contains all properties
-// for which the key matches the regular expression.
-func (p *Properties) FilterRegexp(re *regexp.Regexp) *Properties {
- pp := NewProperties()
- for _, k := range p.k {
- if re.MatchString(k) {
- // TODO(fs): we are ignoring the error which flags a circular reference.
- // TODO(fs): since we are just copying a subset of keys this cannot happen (fingers crossed)
- pp.Set(k, p.m[k])
- }
- }
- return pp
-}
-
-// FilterPrefix returns a new properties object with a subset of all keys
-// with the given prefix.
-func (p *Properties) FilterPrefix(prefix string) *Properties {
- pp := NewProperties()
- for _, k := range p.k {
- if strings.HasPrefix(k, prefix) {
- // TODO(fs): we are ignoring the error which flags a circular reference.
- // TODO(fs): since we are just copying a subset of keys this cannot happen (fingers crossed)
- pp.Set(k, p.m[k])
- }
- }
- return pp
-}
-
-// FilterStripPrefix returns a new properties object with a subset of all keys
-// with the given prefix and the prefix removed from the keys.
-func (p *Properties) FilterStripPrefix(prefix string) *Properties {
- pp := NewProperties()
- n := len(prefix)
- for _, k := range p.k {
- if len(k) > len(prefix) && strings.HasPrefix(k, prefix) {
- // TODO(fs): we are ignoring the error which flags a circular reference.
- // TODO(fs): since we are modifying keys I am not entirely sure whether we can create a circular reference
- // TODO(fs): this function should probably return an error but the signature is fixed
- pp.Set(k[n:], p.m[k])
- }
- }
- return pp
-}
-
-// Len returns the number of keys.
-func (p *Properties) Len() int {
- return len(p.m)
-}
-
-// Keys returns all keys in the same order as in the input.
-func (p *Properties) Keys() []string {
- keys := make([]string, len(p.k))
- copy(keys, p.k)
- return keys
-}
-
-// Set sets the property key to the corresponding value.
-// If a value for key existed before then ok is true and prev
-// contains the previous value. If the value contains a
-// circular reference or a malformed expression then
-// an error is returned.
-// An empty key is silently ignored.
-func (p *Properties) Set(key, value string) (prev string, ok bool, err error) {
- if key == "" {
- return "", false, nil
- }
-
- // if expansion is disabled we allow circular references
- if p.DisableExpansion {
- prev, ok = p.Get(key)
- p.m[key] = value
- return prev, ok, nil
- }
-
- // to check for a circular reference we temporarily need
- // to set the new value. If there is an error then revert
- // to the previous state. Only if all tests are successful
- // then we add the key to the p.k list.
- prev, ok = p.Get(key)
- p.m[key] = value
-
- // now check for a circular reference
- _, err = p.expand(value)
- if err != nil {
-
- // revert to the previous state
- if ok {
- p.m[key] = prev
- } else {
- delete(p.m, key)
- }
-
- return "", false, err
- }
-
- if !ok {
- p.k = append(p.k, key)
- }
-
- return prev, ok, nil
-}
-
-// SetValue sets property key to the default string value
-// as defined by fmt.Sprintf("%v").
-func (p *Properties) SetValue(key string, value interface{}) error {
- _, _, err := p.Set(key, fmt.Sprintf("%v", value))
- return err
-}
-
-// MustSet sets the property key to the corresponding value.
-// If a value for key existed before then ok is true and prev
-// contains the previous value. An empty key is silently ignored.
-func (p *Properties) MustSet(key, value string) (prev string, ok bool) {
- prev, ok, err := p.Set(key, value)
- if err != nil {
- ErrorHandler(err)
- }
- return prev, ok
-}
-
-// String returns a string of all expanded 'key = value' pairs.
-func (p *Properties) String() string {
- var s string
- for _, key := range p.k {
- value, _ := p.Get(key)
- s = fmt.Sprintf("%s%s = %s\n", s, key, value)
- }
- return s
-}
-
-// Write writes all unexpanded 'key = value' pairs to the given writer.
-// Write returns the number of bytes written and any write error encountered.
-func (p *Properties) Write(w io.Writer, enc Encoding) (n int, err error) {
- return p.WriteComment(w, "", enc)
-}
-
-// WriteComment writes all unexpanced 'key = value' pairs to the given writer.
-// If prefix is not empty then comments are written with a blank line and the
-// given prefix. The prefix should be either "# " or "! " to be compatible with
-// the properties file format. Otherwise, the properties parser will not be
-// able to read the file back in. It returns the number of bytes written and
-// any write error encountered.
-func (p *Properties) WriteComment(w io.Writer, prefix string, enc Encoding) (n int, err error) {
- var x int
-
- for _, key := range p.k {
- value := p.m[key]
-
- if prefix != "" {
- if comments, ok := p.c[key]; ok {
- // don't print comments if they are all empty
- allEmpty := true
- for _, c := range comments {
- if c != "" {
- allEmpty = false
- break
- }
- }
-
- if !allEmpty {
- // add a blank line between entries but not at the top
- if len(comments) > 0 && n > 0 {
- x, err = fmt.Fprintln(w)
- if err != nil {
- return
- }
- n += x
- }
-
- for _, c := range comments {
- x, err = fmt.Fprintf(w, "%s%s\n", prefix, encode(c, "", enc))
- if err != nil {
- return
- }
- n += x
- }
- }
- }
- }
-
- x, err = fmt.Fprintf(w, "%s = %s\n", encode(key, " :", enc), encode(value, "", enc))
- if err != nil {
- return
- }
- n += x
- }
- return
-}
-
-// Map returns a copy of the properties as a map.
-func (p *Properties) Map() map[string]string {
- m := make(map[string]string)
- for k, v := range p.m {
- m[k] = v
- }
- return m
-}
-
-// FilterFunc returns a copy of the properties which includes the values which passed all filters.
-func (p *Properties) FilterFunc(filters ...func(k, v string) bool) *Properties {
- pp := NewProperties()
-outer:
- for k, v := range p.m {
- for _, f := range filters {
- if !f(k, v) {
- continue outer
- }
- pp.Set(k, v)
- }
- }
- return pp
-}
-
-// ----------------------------------------------------------------------------
-
-// Delete removes the key and its comments.
-func (p *Properties) Delete(key string) {
- delete(p.m, key)
- delete(p.c, key)
- newKeys := []string{}
- for _, k := range p.k {
- if k != key {
- newKeys = append(newKeys, k)
- }
- }
- p.k = newKeys
-}
-
-// Merge merges properties, comments and keys from other *Properties into p
-func (p *Properties) Merge(other *Properties) {
- for k, v := range other.m {
- p.m[k] = v
- }
- for k, v := range other.c {
- p.c[k] = v
- }
-
-outer:
- for _, otherKey := range other.k {
- for _, key := range p.k {
- if otherKey == key {
- continue outer
- }
- }
- p.k = append(p.k, otherKey)
- }
-}
-
-// ----------------------------------------------------------------------------
-
-// check expands all values and returns an error if a circular reference or
-// a malformed expression was found.
-func (p *Properties) check() error {
- for _, value := range p.m {
- if _, err := p.expand(value); err != nil {
- return err
- }
- }
- return nil
-}
-
-func (p *Properties) expand(input string) (string, error) {
- // no pre/postfix -> nothing to expand
- if p.Prefix == "" && p.Postfix == "" {
- return input, nil
- }
-
- return expand(input, make(map[string]bool), p.Prefix, p.Postfix, p.m)
-}
-
-// expand recursively expands expressions of '(prefix)key(postfix)' to their corresponding values.
-// The function keeps track of the keys that were already expanded and stops if it
-// detects a circular reference or a malformed expression of the form '(prefix)key'.
-func expand(s string, keys map[string]bool, prefix, postfix string, values map[string]string) (string, error) {
- start := strings.Index(s, prefix)
- if start == -1 {
- return s, nil
- }
-
- keyStart := start + len(prefix)
- keyLen := strings.Index(s[keyStart:], postfix)
- if keyLen == -1 {
- return "", fmt.Errorf("malformed expression")
- }
-
- end := keyStart + keyLen + len(postfix) - 1
- key := s[keyStart : keyStart+keyLen]
-
- // fmt.Printf("s:%q pp:%q start:%d end:%d keyStart:%d keyLen:%d key:%q\n", s, prefix + "..." + postfix, start, end, keyStart, keyLen, key)
-
- if _, ok := keys[key]; ok {
- return "", fmt.Errorf("circular reference")
- }
-
- val, ok := values[key]
- if !ok {
- val = os.Getenv(key)
- }
-
- // remember that we've seen the key
- keys[key] = true
-
- return expand(s[:start]+val+s[end+1:], keys, prefix, postfix, values)
-}
-
-// encode encodes a UTF-8 string to ISO-8859-1 and escapes some characters.
-func encode(s string, special string, enc Encoding) string {
- switch enc {
- case UTF8:
- return encodeUtf8(s, special)
- case ISO_8859_1:
- return encodeIso(s, special)
- default:
- panic(fmt.Sprintf("unsupported encoding %v", enc))
- }
-}
-
-func encodeUtf8(s string, special string) string {
- v := ""
- for pos := 0; pos < len(s); {
- r, w := utf8.DecodeRuneInString(s[pos:])
- pos += w
- v += escape(r, special)
- }
- return v
-}
-
-func encodeIso(s string, special string) string {
- var r rune
- var w int
- var v string
- for pos := 0; pos < len(s); {
- switch r, w = utf8.DecodeRuneInString(s[pos:]); {
- case r < 1<<8: // single byte rune -> escape special chars only
- v += escape(r, special)
- case r < 1<<16: // two byte rune -> unicode literal
- v += fmt.Sprintf("\\u%04x", r)
- default: // more than two bytes per rune -> can't encode
- v += "?"
- }
- pos += w
- }
- return v
-}
-
-func escape(r rune, special string) string {
- switch r {
- case '\f':
- return "\\f"
- case '\n':
- return "\\n"
- case '\r':
- return "\\r"
- case '\t':
- return "\\t"
- default:
- if strings.ContainsRune(special, r) {
- return "\\" + string(r)
- }
- return string(r)
- }
-}
-
-func invalidKeyError(key string) error {
- return fmt.Errorf("unknown property: %s", key)
-}
diff --git a/vendor/github.com/magiconair/properties/properties_test.go b/vendor/github.com/magiconair/properties/properties_test.go
deleted file mode 100644
index 0eac1f4..0000000
--- a/vendor/github.com/magiconair/properties/properties_test.go
+++ /dev/null
@@ -1,934 +0,0 @@
-// Copyright 2017 Frank Schroeder. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package properties
-
-import (
- "bytes"
- "flag"
- "fmt"
- "math"
- "os"
- "reflect"
- "strings"
- "testing"
- "time"
-
- "github.com/magiconair/properties/assert"
-)
-
-var verbose = flag.Bool("verbose", false, "Verbose output")
-
-func init() {
- ErrorHandler = PanicHandler
-}
-
-// ----------------------------------------------------------------------------
-
-// define test cases in the form of
-// {"input", "key1", "value1", "key2", "value2", ...}
-var complexTests = [][]string{
- // whitespace prefix
- {" key=value", "key", "value"}, // SPACE prefix
- {"\fkey=value", "key", "value"}, // FF prefix
- {"\tkey=value", "key", "value"}, // TAB prefix
- {" \f\tkey=value", "key", "value"}, // mix prefix
-
- // multiple keys
- {"key1=value1\nkey2=value2\n", "key1", "value1", "key2", "value2"},
- {"key1=value1\rkey2=value2\r", "key1", "value1", "key2", "value2"},
- {"key1=value1\r\nkey2=value2\r\n", "key1", "value1", "key2", "value2"},
-
- // blank lines
- {"\nkey=value\n", "key", "value"},
- {"\rkey=value\r", "key", "value"},
- {"\r\nkey=value\r\n", "key", "value"},
-
- // escaped chars in key
- {"k\\ ey = value", "k ey", "value"},
- {"k\\:ey = value", "k:ey", "value"},
- {"k\\=ey = value", "k=ey", "value"},
- {"k\\fey = value", "k\fey", "value"},
- {"k\\ney = value", "k\ney", "value"},
- {"k\\rey = value", "k\rey", "value"},
- {"k\\tey = value", "k\tey", "value"},
-
- // escaped chars in value
- {"key = v\\ alue", "key", "v alue"},
- {"key = v\\:alue", "key", "v:alue"},
- {"key = v\\=alue", "key", "v=alue"},
- {"key = v\\falue", "key", "v\falue"},
- {"key = v\\nalue", "key", "v\nalue"},
- {"key = v\\ralue", "key", "v\ralue"},
- {"key = v\\talue", "key", "v\talue"},
-
- // silently dropped escape character
- {"k\\zey = value", "kzey", "value"},
- {"key = v\\zalue", "key", "vzalue"},
-
- // unicode literals
- {"key\\u2318 = value", "key⌘", "value"},
- {"k\\u2318ey = value", "k⌘ey", "value"},
- {"key = value\\u2318", "key", "value⌘"},
- {"key = valu\\u2318e", "key", "valu⌘e"},
-
- // multiline values
- {"key = valueA,\\\n valueB", "key", "valueA,valueB"}, // SPACE indent
- {"key = valueA,\\\n\f\f\fvalueB", "key", "valueA,valueB"}, // FF indent
- {"key = valueA,\\\n\t\t\tvalueB", "key", "valueA,valueB"}, // TAB indent
- {"key = valueA,\\\n \f\tvalueB", "key", "valueA,valueB"}, // mix indent
-
- // comments
- {"# this is a comment\n! and so is this\nkey1=value1\nkey#2=value#2\n\nkey!3=value!3\n# and another one\n! and the final one", "key1", "value1", "key#2", "value#2", "key!3", "value!3"},
-
- // expansion tests
- {"key=value\nkey2=${key}", "key", "value", "key2", "value"},
- {"key=value\nkey2=aa${key}", "key", "value", "key2", "aavalue"},
- {"key=value\nkey2=${key}bb", "key", "value", "key2", "valuebb"},
- {"key=value\nkey2=aa${key}bb", "key", "value", "key2", "aavaluebb"},
- {"key=value\nkey2=${key}\nkey3=${key2}", "key", "value", "key2", "value", "key3", "value"},
- {"key=${USER}", "key", os.Getenv("USER")},
- {"key=${USER}\nUSER=value", "key", "value", "USER", "value"},
-}
-
-// ----------------------------------------------------------------------------
-
-var commentTests = []struct {
- input, key, value string
- comments []string
-}{
- {"key=value", "key", "value", nil},
- {"#\nkey=value", "key", "value", []string{""}},
- {"#comment\nkey=value", "key", "value", []string{"comment"}},
- {"# comment\nkey=value", "key", "value", []string{"comment"}},
- {"# comment\nkey=value", "key", "value", []string{"comment"}},
- {"# comment\n\nkey=value", "key", "value", []string{"comment"}},
- {"# comment1\n# comment2\nkey=value", "key", "value", []string{"comment1", "comment2"}},
- {"# comment1\n\n# comment2\n\nkey=value", "key", "value", []string{"comment1", "comment2"}},
- {"!comment\nkey=value", "key", "value", []string{"comment"}},
- {"! comment\nkey=value", "key", "value", []string{"comment"}},
- {"! comment\nkey=value", "key", "value", []string{"comment"}},
- {"! comment\n\nkey=value", "key", "value", []string{"comment"}},
- {"! comment1\n! comment2\nkey=value", "key", "value", []string{"comment1", "comment2"}},
- {"! comment1\n\n! comment2\n\nkey=value", "key", "value", []string{"comment1", "comment2"}},
-}
-
-// ----------------------------------------------------------------------------
-
-var errorTests = []struct {
- input, msg string
-}{
- // unicode literals
- {"key\\u1 = value", "invalid unicode literal"},
- {"key\\u12 = value", "invalid unicode literal"},
- {"key\\u123 = value", "invalid unicode literal"},
- {"key\\u123g = value", "invalid unicode literal"},
- {"key\\u123", "invalid unicode literal"},
-
- // circular references
- {"key=${key}", "circular reference"},
- {"key1=${key2}\nkey2=${key1}", "circular reference"},
-
- // malformed expressions
- {"key=${ke", "malformed expression"},
- {"key=valu${ke", "malformed expression"},
-}
-
-// ----------------------------------------------------------------------------
-
-var writeTests = []struct {
- input, output, encoding string
-}{
- // ISO-8859-1 tests
- {"key = value", "key = value\n", "ISO-8859-1"},
- {"key = value \\\n continued", "key = value continued\n", "ISO-8859-1"},
- {"key⌘ = value", "key\\u2318 = value\n", "ISO-8859-1"},
- {"ke\\ \\:y = value", "ke\\ \\:y = value\n", "ISO-8859-1"},
-
- // UTF-8 tests
- {"key = value", "key = value\n", "UTF-8"},
- {"key = value \\\n continued", "key = value continued\n", "UTF-8"},
- {"key⌘ = value⌘", "key⌘ = value⌘\n", "UTF-8"},
- {"ke\\ \\:y = value", "ke\\ \\:y = value\n", "UTF-8"},
-}
-
-// ----------------------------------------------------------------------------
-
-var writeCommentTests = []struct {
- input, output, encoding string
-}{
- // ISO-8859-1 tests
- {"key = value", "key = value\n", "ISO-8859-1"},
- {"#\nkey = value", "key = value\n", "ISO-8859-1"},
- {"#\n#\n#\nkey = value", "key = value\n", "ISO-8859-1"},
- {"# comment\nkey = value", "# comment\nkey = value\n", "ISO-8859-1"},
- {"\n# comment\nkey = value", "# comment\nkey = value\n", "ISO-8859-1"},
- {"# comment\n\nkey = value", "# comment\nkey = value\n", "ISO-8859-1"},
- {"# comment1\n# comment2\nkey = value", "# comment1\n# comment2\nkey = value\n", "ISO-8859-1"},
- {"#comment1\nkey1 = value1\n#comment2\nkey2 = value2", "# comment1\nkey1 = value1\n\n# comment2\nkey2 = value2\n", "ISO-8859-1"},
-
- // UTF-8 tests
- {"key = value", "key = value\n", "UTF-8"},
- {"# comment⌘\nkey = value⌘", "# comment⌘\nkey = value⌘\n", "UTF-8"},
- {"\n# comment⌘\nkey = value⌘", "# comment⌘\nkey = value⌘\n", "UTF-8"},
- {"# comment⌘\n\nkey = value⌘", "# comment⌘\nkey = value⌘\n", "UTF-8"},
- {"# comment1⌘\n# comment2⌘\nkey = value⌘", "# comment1⌘\n# comment2⌘\nkey = value⌘\n", "UTF-8"},
- {"#comment1⌘\nkey1 = value1⌘\n#comment2⌘\nkey2 = value2⌘", "# comment1⌘\nkey1 = value1⌘\n\n# comment2⌘\nkey2 = value2⌘\n", "UTF-8"},
-}
-
-// ----------------------------------------------------------------------------
-
-var boolTests = []struct {
- input, key string
- def, value bool
-}{
- // valid values for TRUE
- {"key = 1", "key", false, true},
- {"key = on", "key", false, true},
- {"key = On", "key", false, true},
- {"key = ON", "key", false, true},
- {"key = true", "key", false, true},
- {"key = True", "key", false, true},
- {"key = TRUE", "key", false, true},
- {"key = yes", "key", false, true},
- {"key = Yes", "key", false, true},
- {"key = YES", "key", false, true},
-
- // valid values for FALSE (all other)
- {"key = 0", "key", true, false},
- {"key = off", "key", true, false},
- {"key = false", "key", true, false},
- {"key = no", "key", true, false},
-
- // non existent key
- {"key = true", "key2", false, false},
-}
-
-// ----------------------------------------------------------------------------
-
-var durationTests = []struct {
- input, key string
- def, value time.Duration
-}{
- // valid values
- {"key = 1", "key", 999, 1},
- {"key = 0", "key", 999, 0},
- {"key = -1", "key", 999, -1},
- {"key = 0123", "key", 999, 123},
-
- // invalid values
- {"key = 0xff", "key", 999, 999},
- {"key = 1.0", "key", 999, 999},
- {"key = a", "key", 999, 999},
-
- // non existent key
- {"key = 1", "key2", 999, 999},
-}
-
-// ----------------------------------------------------------------------------
-
-var parsedDurationTests = []struct {
- input, key string
- def, value time.Duration
-}{
- // valid values
- {"key = -1ns", "key", 999, -1 * time.Nanosecond},
- {"key = 300ms", "key", 999, 300 * time.Millisecond},
- {"key = 5s", "key", 999, 5 * time.Second},
- {"key = 3h", "key", 999, 3 * time.Hour},
- {"key = 2h45m", "key", 999, 2*time.Hour + 45*time.Minute},
-
- // invalid values
- {"key = 0xff", "key", 999, 999},
- {"key = 1.0", "key", 999, 999},
- {"key = a", "key", 999, 999},
- {"key = 1", "key", 999, 999},
- {"key = 0", "key", 999, 0},
-
- // non existent key
- {"key = 1", "key2", 999, 999},
-}
-
-// ----------------------------------------------------------------------------
-
-var floatTests = []struct {
- input, key string
- def, value float64
-}{
- // valid values
- {"key = 1.0", "key", 999, 1.0},
- {"key = 0.0", "key", 999, 0.0},
- {"key = -1.0", "key", 999, -1.0},
- {"key = 1", "key", 999, 1},
- {"key = 0", "key", 999, 0},
- {"key = -1", "key", 999, -1},
- {"key = 0123", "key", 999, 123},
-
- // invalid values
- {"key = 0xff", "key", 999, 999},
- {"key = a", "key", 999, 999},
-
- // non existent key
- {"key = 1", "key2", 999, 999},
-}
-
-// ----------------------------------------------------------------------------
-
-var int64Tests = []struct {
- input, key string
- def, value int64
-}{
- // valid values
- {"key = 1", "key", 999, 1},
- {"key = 0", "key", 999, 0},
- {"key = -1", "key", 999, -1},
- {"key = 0123", "key", 999, 123},
-
- // invalid values
- {"key = 0xff", "key", 999, 999},
- {"key = 1.0", "key", 999, 999},
- {"key = a", "key", 999, 999},
-
- // non existent key
- {"key = 1", "key2", 999, 999},
-}
-
-// ----------------------------------------------------------------------------
-
-var uint64Tests = []struct {
- input, key string
- def, value uint64
-}{
- // valid values
- {"key = 1", "key", 999, 1},
- {"key = 0", "key", 999, 0},
- {"key = 0123", "key", 999, 123},
-
- // invalid values
- {"key = -1", "key", 999, 999},
- {"key = 0xff", "key", 999, 999},
- {"key = 1.0", "key", 999, 999},
- {"key = a", "key", 999, 999},
-
- // non existent key
- {"key = 1", "key2", 999, 999},
-}
-
-// ----------------------------------------------------------------------------
-
-var stringTests = []struct {
- input, key string
- def, value string
-}{
- // valid values
- {"key = abc", "key", "def", "abc"},
-
- // non existent key
- {"key = abc", "key2", "def", "def"},
-}
-
-// ----------------------------------------------------------------------------
-
-var keysTests = []struct {
- input string
- keys []string
-}{
- {"", []string{}},
- {"key = abc", []string{"key"}},
- {"key = abc\nkey2=def", []string{"key", "key2"}},
- {"key2 = abc\nkey=def", []string{"key2", "key"}},
- {"key = abc\nkey=def", []string{"key"}},
-}
-
-// ----------------------------------------------------------------------------
-
-var filterTests = []struct {
- input string
- pattern string
- keys []string
- err string
-}{
- {"", "", []string{}, ""},
- {"", "abc", []string{}, ""},
- {"key=value", "", []string{"key"}, ""},
- {"key=value", "key=", []string{}, ""},
- {"key=value\nfoo=bar", "", []string{"foo", "key"}, ""},
- {"key=value\nfoo=bar", "f", []string{"foo"}, ""},
- {"key=value\nfoo=bar", "fo", []string{"foo"}, ""},
- {"key=value\nfoo=bar", "foo", []string{"foo"}, ""},
- {"key=value\nfoo=bar", "fooo", []string{}, ""},
- {"key=value\nkey2=value2\nfoo=bar", "ey", []string{"key", "key2"}, ""},
- {"key=value\nkey2=value2\nfoo=bar", "key", []string{"key", "key2"}, ""},
- {"key=value\nkey2=value2\nfoo=bar", "^key", []string{"key", "key2"}, ""},
- {"key=value\nkey2=value2\nfoo=bar", "^(key|foo)", []string{"foo", "key", "key2"}, ""},
- {"key=value\nkey2=value2\nfoo=bar", "[ abc", nil, "error parsing regexp.*"},
-}
-
-// ----------------------------------------------------------------------------
-
-var filterPrefixTests = []struct {
- input string
- prefix string
- keys []string
-}{
- {"", "", []string{}},
- {"", "abc", []string{}},
- {"key=value", "", []string{"key"}},
- {"key=value", "key=", []string{}},
- {"key=value\nfoo=bar", "", []string{"foo", "key"}},
- {"key=value\nfoo=bar", "f", []string{"foo"}},
- {"key=value\nfoo=bar", "fo", []string{"foo"}},
- {"key=value\nfoo=bar", "foo", []string{"foo"}},
- {"key=value\nfoo=bar", "fooo", []string{}},
- {"key=value\nkey2=value2\nfoo=bar", "key", []string{"key", "key2"}},
-}
-
-// ----------------------------------------------------------------------------
-
-var filterStripPrefixTests = []struct {
- input string
- prefix string
- keys []string
-}{
- {"", "", []string{}},
- {"", "abc", []string{}},
- {"key=value", "", []string{"key"}},
- {"key=value", "key=", []string{}},
- {"key=value\nfoo=bar", "", []string{"foo", "key"}},
- {"key=value\nfoo=bar", "f", []string{"foo"}},
- {"key=value\nfoo=bar", "fo", []string{"foo"}},
- {"key=value\nfoo=bar", "foo", []string{"foo"}},
- {"key=value\nfoo=bar", "fooo", []string{}},
- {"key=value\nkey2=value2\nfoo=bar", "key", []string{"key", "key2"}},
-}
-
-// ----------------------------------------------------------------------------
-
-var setTests = []struct {
- input string
- key, value string
- prev string
- ok bool
- err string
- keys []string
-}{
- {"", "", "", "", false, "", []string{}},
- {"", "key", "value", "", false, "", []string{"key"}},
- {"key=value", "key2", "value2", "", false, "", []string{"key", "key2"}},
- {"key=value", "abc", "value3", "", false, "", []string{"key", "abc"}},
- {"key=value", "key", "value3", "value", true, "", []string{"key"}},
-}
-
-// ----------------------------------------------------------------------------
-
-// TestBasic tests basic single key/value combinations with all possible
-// whitespace, delimiter and newline permutations.
-func TestBasic(t *testing.T) {
- testWhitespaceAndDelimiterCombinations(t, "key", "")
- testWhitespaceAndDelimiterCombinations(t, "key", "value")
- testWhitespaceAndDelimiterCombinations(t, "key", "value ")
-}
-
-func TestComplex(t *testing.T) {
- for _, test := range complexTests {
- testKeyValue(t, test[0], test[1:]...)
- }
-}
-
-func TestErrors(t *testing.T) {
- for _, test := range errorTests {
- _, err := Load([]byte(test.input), ISO_8859_1)
- assert.Equal(t, err != nil, true, "want error")
- assert.Equal(t, strings.Contains(err.Error(), test.msg), true)
- }
-}
-
-func TestDisableExpansion(t *testing.T) {
- input := "key=value\nkey2=${key}"
- p := mustParse(t, input)
- p.DisableExpansion = true
- assert.Equal(t, p.MustGet("key"), "value")
- assert.Equal(t, p.MustGet("key2"), "${key}")
-
- // with expansion disabled we can introduce circular references
- p.MustSet("keyA", "${keyB}")
- p.MustSet("keyB", "${keyA}")
- assert.Equal(t, p.MustGet("keyA"), "${keyB}")
- assert.Equal(t, p.MustGet("keyB"), "${keyA}")
-}
-
-func TestMustGet(t *testing.T) {
- input := "key = value\nkey2 = ghi"
- p := mustParse(t, input)
- assert.Equal(t, p.MustGet("key"), "value")
- assert.Panic(t, func() { p.MustGet("invalid") }, "unknown property: invalid")
-}
-
-func TestGetBool(t *testing.T) {
- for _, test := range boolTests {
- p := mustParse(t, test.input)
- assert.Equal(t, p.Len(), 1)
- assert.Equal(t, p.GetBool(test.key, test.def), test.value)
- }
-}
-
-func TestMustGetBool(t *testing.T) {
- input := "key = true\nkey2 = ghi"
- p := mustParse(t, input)
- assert.Equal(t, p.MustGetBool("key"), true)
- assert.Panic(t, func() { p.MustGetBool("invalid") }, "unknown property: invalid")
-}
-
-func TestGetDuration(t *testing.T) {
- for _, test := range durationTests {
- p := mustParse(t, test.input)
- assert.Equal(t, p.Len(), 1)
- assert.Equal(t, p.GetDuration(test.key, test.def), test.value)
- }
-}
-
-func TestMustGetDuration(t *testing.T) {
- input := "key = 123\nkey2 = ghi"
- p := mustParse(t, input)
- assert.Equal(t, p.MustGetDuration("key"), time.Duration(123))
- assert.Panic(t, func() { p.MustGetDuration("key2") }, "strconv.ParseInt: parsing.*")
- assert.Panic(t, func() { p.MustGetDuration("invalid") }, "unknown property: invalid")
-}
-
-func TestGetParsedDuration(t *testing.T) {
- for _, test := range parsedDurationTests {
- p := mustParse(t, test.input)
- assert.Equal(t, p.Len(), 1)
- assert.Equal(t, p.GetParsedDuration(test.key, test.def), test.value)
- }
-}
-
-func TestMustGetParsedDuration(t *testing.T) {
- input := "key = 123ms\nkey2 = ghi"
- p := mustParse(t, input)
- assert.Equal(t, p.MustGetParsedDuration("key"), 123*time.Millisecond)
- assert.Panic(t, func() { p.MustGetParsedDuration("key2") }, "time: invalid duration ghi")
- assert.Panic(t, func() { p.MustGetParsedDuration("invalid") }, "unknown property: invalid")
-}
-
-func TestGetFloat64(t *testing.T) {
- for _, test := range floatTests {
- p := mustParse(t, test.input)
- assert.Equal(t, p.Len(), 1)
- assert.Equal(t, p.GetFloat64(test.key, test.def), test.value)
- }
-}
-
-func TestMustGetFloat64(t *testing.T) {
- input := "key = 123\nkey2 = ghi"
- p := mustParse(t, input)
- assert.Equal(t, p.MustGetFloat64("key"), float64(123))
- assert.Panic(t, func() { p.MustGetFloat64("key2") }, "strconv.ParseFloat: parsing.*")
- assert.Panic(t, func() { p.MustGetFloat64("invalid") }, "unknown property: invalid")
-}
-
-func TestGetInt(t *testing.T) {
- for _, test := range int64Tests {
- p := mustParse(t, test.input)
- assert.Equal(t, p.Len(), 1)
- assert.Equal(t, p.GetInt(test.key, int(test.def)), int(test.value))
- }
-}
-
-func TestMustGetInt(t *testing.T) {
- input := "key = 123\nkey2 = ghi"
- p := mustParse(t, input)
- assert.Equal(t, p.MustGetInt("key"), int(123))
- assert.Panic(t, func() { p.MustGetInt("key2") }, "strconv.ParseInt: parsing.*")
- assert.Panic(t, func() { p.MustGetInt("invalid") }, "unknown property: invalid")
-}
-
-func TestGetInt64(t *testing.T) {
- for _, test := range int64Tests {
- p := mustParse(t, test.input)
- assert.Equal(t, p.Len(), 1)
- assert.Equal(t, p.GetInt64(test.key, test.def), test.value)
- }
-}
-
-func TestMustGetInt64(t *testing.T) {
- input := "key = 123\nkey2 = ghi"
- p := mustParse(t, input)
- assert.Equal(t, p.MustGetInt64("key"), int64(123))
- assert.Panic(t, func() { p.MustGetInt64("key2") }, "strconv.ParseInt: parsing.*")
- assert.Panic(t, func() { p.MustGetInt64("invalid") }, "unknown property: invalid")
-}
-
-func TestGetUint(t *testing.T) {
- for _, test := range uint64Tests {
- p := mustParse(t, test.input)
- assert.Equal(t, p.Len(), 1)
- assert.Equal(t, p.GetUint(test.key, uint(test.def)), uint(test.value))
- }
-}
-
-func TestMustGetUint(t *testing.T) {
- input := "key = 123\nkey2 = ghi"
- p := mustParse(t, input)
- assert.Equal(t, p.MustGetUint("key"), uint(123))
- assert.Panic(t, func() { p.MustGetUint64("key2") }, "strconv.ParseUint: parsing.*")
- assert.Panic(t, func() { p.MustGetUint64("invalid") }, "unknown property: invalid")
-}
-
-func TestGetUint64(t *testing.T) {
- for _, test := range uint64Tests {
- p := mustParse(t, test.input)
- assert.Equal(t, p.Len(), 1)
- assert.Equal(t, p.GetUint64(test.key, test.def), test.value)
- }
-}
-
-func TestMustGetUint64(t *testing.T) {
- input := "key = 123\nkey2 = ghi"
- p := mustParse(t, input)
- assert.Equal(t, p.MustGetUint64("key"), uint64(123))
- assert.Panic(t, func() { p.MustGetUint64("key2") }, "strconv.ParseUint: parsing.*")
- assert.Panic(t, func() { p.MustGetUint64("invalid") }, "unknown property: invalid")
-}
-
-func TestGetString(t *testing.T) {
- for _, test := range stringTests {
- p := mustParse(t, test.input)
- assert.Equal(t, p.Len(), 1)
- assert.Equal(t, p.GetString(test.key, test.def), test.value)
- }
-}
-
-func TestMustGetString(t *testing.T) {
- input := `key = value`
- p := mustParse(t, input)
- assert.Equal(t, p.MustGetString("key"), "value")
- assert.Panic(t, func() { p.MustGetString("invalid") }, "unknown property: invalid")
-}
-
-func TestComment(t *testing.T) {
- for _, test := range commentTests {
- p := mustParse(t, test.input)
- assert.Equal(t, p.MustGetString(test.key), test.value)
- assert.Equal(t, p.GetComments(test.key), test.comments)
- if test.comments != nil {
- assert.Equal(t, p.GetComment(test.key), test.comments[len(test.comments)-1])
- } else {
- assert.Equal(t, p.GetComment(test.key), "")
- }
-
- // test setting comments
- if len(test.comments) > 0 {
- // set single comment
- p.ClearComments()
- assert.Equal(t, len(p.c), 0)
- p.SetComment(test.key, test.comments[0])
- assert.Equal(t, p.GetComment(test.key), test.comments[0])
-
- // set multiple comments
- p.ClearComments()
- assert.Equal(t, len(p.c), 0)
- p.SetComments(test.key, test.comments)
- assert.Equal(t, p.GetComments(test.key), test.comments)
-
- // clear comments for a key
- p.SetComments(test.key, nil)
- assert.Equal(t, p.GetComment(test.key), "")
- assert.Equal(t, p.GetComments(test.key), ([]string)(nil))
- }
- }
-}
-
-func TestFilter(t *testing.T) {
- for _, test := range filterTests {
- p := mustParse(t, test.input)
- pp, err := p.Filter(test.pattern)
- if err != nil {
- assert.Matches(t, err.Error(), test.err)
- continue
- }
- assert.Equal(t, pp != nil, true, "want properties")
- assert.Equal(t, pp.Len(), len(test.keys))
- for _, key := range test.keys {
- v1, ok1 := p.Get(key)
- v2, ok2 := pp.Get(key)
- assert.Equal(t, ok1, true)
- assert.Equal(t, ok2, true)
- assert.Equal(t, v1, v2)
- }
- }
-}
-
-func TestFilterPrefix(t *testing.T) {
- for _, test := range filterPrefixTests {
- p := mustParse(t, test.input)
- pp := p.FilterPrefix(test.prefix)
- assert.Equal(t, pp != nil, true, "want properties")
- assert.Equal(t, pp.Len(), len(test.keys))
- for _, key := range test.keys {
- v1, ok1 := p.Get(key)
- v2, ok2 := pp.Get(key)
- assert.Equal(t, ok1, true)
- assert.Equal(t, ok2, true)
- assert.Equal(t, v1, v2)
- }
- }
-}
-
-func TestFilterStripPrefix(t *testing.T) {
- for _, test := range filterStripPrefixTests {
- p := mustParse(t, test.input)
- pp := p.FilterPrefix(test.prefix)
- assert.Equal(t, pp != nil, true, "want properties")
- assert.Equal(t, pp.Len(), len(test.keys))
- for _, key := range test.keys {
- v1, ok1 := p.Get(key)
- v2, ok2 := pp.Get(key)
- assert.Equal(t, ok1, true)
- assert.Equal(t, ok2, true)
- assert.Equal(t, v1, v2)
- }
- }
-}
-
-func TestKeys(t *testing.T) {
- for _, test := range keysTests {
- p := mustParse(t, test.input)
- assert.Equal(t, p.Len(), len(test.keys))
- assert.Equal(t, len(p.Keys()), len(test.keys))
- assert.Equal(t, p.Keys(), test.keys)
- }
-}
-
-func TestSet(t *testing.T) {
- for _, test := range setTests {
- p := mustParse(t, test.input)
- prev, ok, err := p.Set(test.key, test.value)
- if test.err != "" {
- assert.Matches(t, err.Error(), test.err)
- continue
- }
-
- assert.Equal(t, err, nil)
- assert.Equal(t, ok, test.ok)
- if ok {
- assert.Equal(t, prev, test.prev)
- }
- assert.Equal(t, p.Keys(), test.keys)
- }
-}
-
-func TestSetValue(t *testing.T) {
- tests := []interface{}{
- true, false,
- int8(123), int16(123), int32(123), int64(123), int(123),
- uint8(123), uint16(123), uint32(123), uint64(123), uint(123),
- float32(1.23), float64(1.23),
- "abc",
- }
-
- for _, v := range tests {
- p := NewProperties()
- err := p.SetValue("x", v)
- assert.Equal(t, err, nil)
- assert.Equal(t, p.GetString("x", ""), fmt.Sprintf("%v", v))
- }
-}
-
-func TestMustSet(t *testing.T) {
- input := "key=${key}"
- p := mustParse(t, input)
- assert.Panic(t, func() { p.MustSet("key", "${key}") }, "circular reference .*")
-}
-
-func TestWrite(t *testing.T) {
- for _, test := range writeTests {
- p, err := parse(test.input)
-
- buf := new(bytes.Buffer)
- var n int
- switch test.encoding {
- case "UTF-8":
- n, err = p.Write(buf, UTF8)
- case "ISO-8859-1":
- n, err = p.Write(buf, ISO_8859_1)
- }
- assert.Equal(t, err, nil)
- s := string(buf.Bytes())
- assert.Equal(t, n, len(test.output), fmt.Sprintf("input=%q expected=%q obtained=%q", test.input, test.output, s))
- assert.Equal(t, s, test.output, fmt.Sprintf("input=%q expected=%q obtained=%q", test.input, test.output, s))
- }
-}
-
-func TestWriteComment(t *testing.T) {
- for _, test := range writeCommentTests {
- p, err := parse(test.input)
-
- buf := new(bytes.Buffer)
- var n int
- switch test.encoding {
- case "UTF-8":
- n, err = p.WriteComment(buf, "# ", UTF8)
- case "ISO-8859-1":
- n, err = p.WriteComment(buf, "# ", ISO_8859_1)
- }
- assert.Equal(t, err, nil)
- s := string(buf.Bytes())
- assert.Equal(t, n, len(test.output), fmt.Sprintf("input=%q expected=%q obtained=%q", test.input, test.output, s))
- assert.Equal(t, s, test.output, fmt.Sprintf("input=%q expected=%q obtained=%q", test.input, test.output, s))
- }
-}
-
-func TestCustomExpansionExpression(t *testing.T) {
- testKeyValuePrePostfix(t, "*[", "]*", "key=value\nkey2=*[key]*", "key", "value", "key2", "value")
-}
-
-func TestPanicOn32BitIntOverflow(t *testing.T) {
- is32Bit = true
- var min, max int64 = math.MinInt32 - 1, math.MaxInt32 + 1
- input := fmt.Sprintf("min=%d\nmax=%d", min, max)
- p := mustParse(t, input)
- assert.Equal(t, p.MustGetInt64("min"), min)
- assert.Equal(t, p.MustGetInt64("max"), max)
- assert.Panic(t, func() { p.MustGetInt("min") }, ".* out of range")
- assert.Panic(t, func() { p.MustGetInt("max") }, ".* out of range")
-}
-
-func TestPanicOn32BitUintOverflow(t *testing.T) {
- is32Bit = true
- var max uint64 = math.MaxUint32 + 1
- input := fmt.Sprintf("max=%d", max)
- p := mustParse(t, input)
- assert.Equal(t, p.MustGetUint64("max"), max)
- assert.Panic(t, func() { p.MustGetUint("max") }, ".* out of range")
-}
-
-func TestDeleteKey(t *testing.T) {
- input := "#comments should also be gone\nkey=to-be-deleted\nsecond=key"
- p := mustParse(t, input)
- assert.Equal(t, len(p.m), 2)
- assert.Equal(t, len(p.c), 1)
- assert.Equal(t, len(p.k), 2)
- p.Delete("key")
- assert.Equal(t, len(p.m), 1)
- assert.Equal(t, len(p.c), 0)
- assert.Equal(t, len(p.k), 1)
- assert.Equal(t, p.k[0], "second")
- assert.Equal(t, p.m["second"], "key")
-}
-
-func TestDeleteUnknownKey(t *testing.T) {
- input := "#comments should also be gone\nkey=to-be-deleted"
- p := mustParse(t, input)
- assert.Equal(t, len(p.m), 1)
- assert.Equal(t, len(p.c), 1)
- assert.Equal(t, len(p.k), 1)
- p.Delete("wrong-key")
- assert.Equal(t, len(p.m), 1)
- assert.Equal(t, len(p.c), 1)
- assert.Equal(t, len(p.k), 1)
-}
-
-func TestMerge(t *testing.T) {
- input1 := "#comment\nkey=value\nkey2=value2"
- input2 := "#another comment\nkey=another value\nkey3=value3"
- p1 := mustParse(t, input1)
- p2 := mustParse(t, input2)
- p1.Merge(p2)
- assert.Equal(t, len(p1.m), 3)
- assert.Equal(t, len(p1.c), 1)
- assert.Equal(t, len(p1.k), 3)
- assert.Equal(t, p1.MustGet("key"), "another value")
- assert.Equal(t, p1.GetComment("key"), "another comment")
-}
-
-func TestMap(t *testing.T) {
- input := "key=value\nabc=def"
- p := mustParse(t, input)
- m := map[string]string{"key": "value", "abc": "def"}
- assert.Equal(t, p.Map(), m)
-}
-
-func TestFilterFunc(t *testing.T) {
- input := "key=value\nabc=def"
- p := mustParse(t, input)
- pp := p.FilterFunc(func(k, v string) bool {
- return k != "abc"
- })
- m := map[string]string{"key": "value"}
- assert.Equal(t, pp.Map(), m)
-}
-
-// ----------------------------------------------------------------------------
-
-// tests all combinations of delimiters, leading and/or trailing whitespace and newlines.
-func testWhitespaceAndDelimiterCombinations(t *testing.T, key, value string) {
- whitespace := []string{"", " ", "\f", "\t"}
- delimiters := []string{"", " ", "=", ":"}
- newlines := []string{"", "\r", "\n", "\r\n"}
- for _, dl := range delimiters {
- for _, ws1 := range whitespace {
- for _, ws2 := range whitespace {
- for _, nl := range newlines {
- // skip the one case where there is nothing between a key and a value
- if ws1 == "" && dl == "" && ws2 == "" && value != "" {
- continue
- }
-
- input := fmt.Sprintf("%s%s%s%s%s%s", key, ws1, dl, ws2, value, nl)
- testKeyValue(t, input, key, value)
- }
- }
- }
- }
-}
-
-// tests whether key/value pairs exist for a given input.
-// keyvalues is expected to be an even number of strings of "key", "value", ...
-func testKeyValue(t *testing.T, input string, keyvalues ...string) {
- testKeyValuePrePostfix(t, "${", "}", input, keyvalues...)
-}
-
-// tests whether key/value pairs exist for a given input.
-// keyvalues is expected to be an even number of strings of "key", "value", ...
-func testKeyValuePrePostfix(t *testing.T, prefix, postfix, input string, keyvalues ...string) {
- p, err := Load([]byte(input), ISO_8859_1)
- assert.Equal(t, err, nil)
- p.Prefix = prefix
- p.Postfix = postfix
- assertKeyValues(t, input, p, keyvalues...)
-}
-
-// tests whether key/value pairs exist for a given input.
-// keyvalues is expected to be an even number of strings of "key", "value", ...
-func assertKeyValues(t *testing.T, input string, p *Properties, keyvalues ...string) {
- assert.Equal(t, p != nil, true, "want properties")
- assert.Equal(t, 2*p.Len(), len(keyvalues), "Odd number of key/value pairs.")
-
- for i := 0; i < len(keyvalues); i += 2 {
- key, value := keyvalues[i], keyvalues[i+1]
- v, ok := p.Get(key)
- if !ok {
- t.Errorf("No key %q found (input=%q)", key, input)
- }
- if got, want := v, value; !reflect.DeepEqual(got, want) {
- t.Errorf("Value %q does not match %q (input=%q)", v, value, input)
- }
- }
-}
-
-func mustParse(t *testing.T, s string) *Properties {
- p, err := parse(s)
- if err != nil {
- t.Fatalf("parse failed with %s", err)
- }
- return p
-}
-
-// prints to stderr if the -verbose flag was given.
-func printf(format string, args ...interface{}) {
- if *verbose {
- fmt.Fprintf(os.Stderr, format, args...)
- }
-}
diff --git a/vendor/github.com/magiconair/properties/rangecheck.go b/vendor/github.com/magiconair/properties/rangecheck.go
deleted file mode 100644
index 2e907d5..0000000
--- a/vendor/github.com/magiconair/properties/rangecheck.go
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright 2017 Frank Schroeder. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package properties
-
-import (
- "fmt"
- "math"
-)
-
-// make this a var to overwrite it in a test
-var is32Bit = ^uint(0) == math.MaxUint32
-
-// intRangeCheck checks if the value fits into the int type and
-// panics if it does not.
-func intRangeCheck(key string, v int64) int {
- if is32Bit && (v < math.MinInt32 || v > math.MaxInt32) {
- panic(fmt.Sprintf("Value %d for key %s out of range", v, key))
- }
- return int(v)
-}
-
-// uintRangeCheck checks if the value fits into the uint type and
-// panics if it does not.
-func uintRangeCheck(key string, v uint64) uint {
- if is32Bit && v > math.MaxUint32 {
- panic(fmt.Sprintf("Value %d for key %s out of range", v, key))
- }
- return uint(v)
-}
diff --git a/vendor/github.com/mattn/go-runewidth/.travis.yml b/vendor/github.com/mattn/go-runewidth/.travis.yml
deleted file mode 100644
index 5c9c2a3..0000000
--- a/vendor/github.com/mattn/go-runewidth/.travis.yml
+++ /dev/null
@@ -1,8 +0,0 @@
-language: go
-go:
- - tip
-before_install:
- - go get github.com/mattn/goveralls
- - go get golang.org/x/tools/cmd/cover
-script:
- - $HOME/gopath/bin/goveralls -repotoken lAKAWPzcGsD3A8yBX3BGGtRUdJ6CaGERL
diff --git a/vendor/github.com/mattn/go-runewidth/LICENSE b/vendor/github.com/mattn/go-runewidth/LICENSE
deleted file mode 100644
index 91b5cef..0000000
--- a/vendor/github.com/mattn/go-runewidth/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2016 Yasuhiro Matsumoto
-
-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.
diff --git a/vendor/github.com/mattn/go-runewidth/README.mkd b/vendor/github.com/mattn/go-runewidth/README.mkd
deleted file mode 100644
index 66663a9..0000000
--- a/vendor/github.com/mattn/go-runewidth/README.mkd
+++ /dev/null
@@ -1,27 +0,0 @@
-go-runewidth
-============
-
-[](https://travis-ci.org/mattn/go-runewidth)
-[](https://coveralls.io/r/mattn/go-runewidth?branch=HEAD)
-[](http://godoc.org/github.com/mattn/go-runewidth)
-[](https://goreportcard.com/report/github.com/mattn/go-runewidth)
-
-Provides functions to get fixed width of the character or string.
-
-Usage
------
-
-```go
-runewidth.StringWidth("つのだ☆HIRO") == 12
-```
-
-
-Author
-------
-
-Yasuhiro Matsumoto
-
-License
--------
-
-under the MIT License: http://mattn.mit-license.org/2013
diff --git a/vendor/github.com/mattn/go-runewidth/runewidth.go b/vendor/github.com/mattn/go-runewidth/runewidth.go
deleted file mode 100644
index 2164497..0000000
--- a/vendor/github.com/mattn/go-runewidth/runewidth.go
+++ /dev/null
@@ -1,1223 +0,0 @@
-package runewidth
-
-var (
- // EastAsianWidth will be set true if the current locale is CJK
- EastAsianWidth = IsEastAsian()
-
- // DefaultCondition is a condition in current locale
- DefaultCondition = &Condition{EastAsianWidth}
-)
-
-type interval struct {
- first rune
- last rune
-}
-
-type table []interval
-
-func inTables(r rune, ts ...table) bool {
- for _, t := range ts {
- if inTable(r, t) {
- return true
- }
- }
- return false
-}
-
-func inTable(r rune, t table) bool {
- // func (t table) IncludesRune(r rune) bool {
- if r < t[0].first {
- return false
- }
-
- bot := 0
- top := len(t) - 1
- for top >= bot {
- mid := (bot + top) / 2
-
- switch {
- case t[mid].last < r:
- bot = mid + 1
- case t[mid].first > r:
- top = mid - 1
- default:
- return true
- }
- }
-
- return false
-}
-
-var private = table{
- {0x00E000, 0x00F8FF}, {0x0F0000, 0x0FFFFD}, {0x100000, 0x10FFFD},
-}
-
-var nonprint = table{
- {0x0000, 0x001F}, {0x007F, 0x009F}, {0x00AD, 0x00AD},
- {0x070F, 0x070F}, {0x180B, 0x180E}, {0x200B, 0x200F},
- {0x202A, 0x202E}, {0x206A, 0x206F}, {0xD800, 0xDFFF},
- {0xFEFF, 0xFEFF}, {0xFFF9, 0xFFFB}, {0xFFFE, 0xFFFF},
-}
-
-var combining = table{
- {0x0300, 0x036F}, {0x0483, 0x0489}, {0x0591, 0x05BD},
- {0x05BF, 0x05BF}, {0x05C1, 0x05C2}, {0x05C4, 0x05C5},
- {0x05C7, 0x05C7}, {0x0610, 0x061A}, {0x064B, 0x065F},
- {0x0670, 0x0670}, {0x06D6, 0x06DC}, {0x06DF, 0x06E4},
- {0x06E7, 0x06E8}, {0x06EA, 0x06ED}, {0x0711, 0x0711},
- {0x0730, 0x074A}, {0x07A6, 0x07B0}, {0x07EB, 0x07F3},
- {0x0816, 0x0819}, {0x081B, 0x0823}, {0x0825, 0x0827},
- {0x0829, 0x082D}, {0x0859, 0x085B}, {0x08D4, 0x08E1},
- {0x08E3, 0x0903}, {0x093A, 0x093C}, {0x093E, 0x094F},
- {0x0951, 0x0957}, {0x0962, 0x0963}, {0x0981, 0x0983},
- {0x09BC, 0x09BC}, {0x09BE, 0x09C4}, {0x09C7, 0x09C8},
- {0x09CB, 0x09CD}, {0x09D7, 0x09D7}, {0x09E2, 0x09E3},
- {0x0A01, 0x0A03}, {0x0A3C, 0x0A3C}, {0x0A3E, 0x0A42},
- {0x0A47, 0x0A48}, {0x0A4B, 0x0A4D}, {0x0A51, 0x0A51},
- {0x0A70, 0x0A71}, {0x0A75, 0x0A75}, {0x0A81, 0x0A83},
- {0x0ABC, 0x0ABC}, {0x0ABE, 0x0AC5}, {0x0AC7, 0x0AC9},
- {0x0ACB, 0x0ACD}, {0x0AE2, 0x0AE3}, {0x0B01, 0x0B03},
- {0x0B3C, 0x0B3C}, {0x0B3E, 0x0B44}, {0x0B47, 0x0B48},
- {0x0B4B, 0x0B4D}, {0x0B56, 0x0B57}, {0x0B62, 0x0B63},
- {0x0B82, 0x0B82}, {0x0BBE, 0x0BC2}, {0x0BC6, 0x0BC8},
- {0x0BCA, 0x0BCD}, {0x0BD7, 0x0BD7}, {0x0C00, 0x0C03},
- {0x0C3E, 0x0C44}, {0x0C46, 0x0C48}, {0x0C4A, 0x0C4D},
- {0x0C55, 0x0C56}, {0x0C62, 0x0C63}, {0x0C81, 0x0C83},
- {0x0CBC, 0x0CBC}, {0x0CBE, 0x0CC4}, {0x0CC6, 0x0CC8},
- {0x0CCA, 0x0CCD}, {0x0CD5, 0x0CD6}, {0x0CE2, 0x0CE3},
- {0x0D01, 0x0D03}, {0x0D3E, 0x0D44}, {0x0D46, 0x0D48},
- {0x0D4A, 0x0D4D}, {0x0D57, 0x0D57}, {0x0D62, 0x0D63},
- {0x0D82, 0x0D83}, {0x0DCA, 0x0DCA}, {0x0DCF, 0x0DD4},
- {0x0DD6, 0x0DD6}, {0x0DD8, 0x0DDF}, {0x0DF2, 0x0DF3},
- {0x0E31, 0x0E31}, {0x0E34, 0x0E3A}, {0x0E47, 0x0E4E},
- {0x0EB1, 0x0EB1}, {0x0EB4, 0x0EB9}, {0x0EBB, 0x0EBC},
- {0x0EC8, 0x0ECD}, {0x0F18, 0x0F19}, {0x0F35, 0x0F35},
- {0x0F37, 0x0F37}, {0x0F39, 0x0F39}, {0x0F3E, 0x0F3F},
- {0x0F71, 0x0F84}, {0x0F86, 0x0F87}, {0x0F8D, 0x0F97},
- {0x0F99, 0x0FBC}, {0x0FC6, 0x0FC6}, {0x102B, 0x103E},
- {0x1056, 0x1059}, {0x105E, 0x1060}, {0x1062, 0x1064},
- {0x1067, 0x106D}, {0x1071, 0x1074}, {0x1082, 0x108D},
- {0x108F, 0x108F}, {0x109A, 0x109D}, {0x135D, 0x135F},
- {0x1712, 0x1714}, {0x1732, 0x1734}, {0x1752, 0x1753},
- {0x1772, 0x1773}, {0x17B4, 0x17D3}, {0x17DD, 0x17DD},
- {0x180B, 0x180D}, {0x1885, 0x1886}, {0x18A9, 0x18A9},
- {0x1920, 0x192B}, {0x1930, 0x193B}, {0x1A17, 0x1A1B},
- {0x1A55, 0x1A5E}, {0x1A60, 0x1A7C}, {0x1A7F, 0x1A7F},
- {0x1AB0, 0x1ABE}, {0x1B00, 0x1B04}, {0x1B34, 0x1B44},
- {0x1B6B, 0x1B73}, {0x1B80, 0x1B82}, {0x1BA1, 0x1BAD},
- {0x1BE6, 0x1BF3}, {0x1C24, 0x1C37}, {0x1CD0, 0x1CD2},
- {0x1CD4, 0x1CE8}, {0x1CED, 0x1CED}, {0x1CF2, 0x1CF4},
- {0x1CF8, 0x1CF9}, {0x1DC0, 0x1DF5}, {0x1DFB, 0x1DFF},
- {0x20D0, 0x20F0}, {0x2CEF, 0x2CF1}, {0x2D7F, 0x2D7F},
- {0x2DE0, 0x2DFF}, {0x302A, 0x302F}, {0x3099, 0x309A},
- {0xA66F, 0xA672}, {0xA674, 0xA67D}, {0xA69E, 0xA69F},
- {0xA6F0, 0xA6F1}, {0xA802, 0xA802}, {0xA806, 0xA806},
- {0xA80B, 0xA80B}, {0xA823, 0xA827}, {0xA880, 0xA881},
- {0xA8B4, 0xA8C5}, {0xA8E0, 0xA8F1}, {0xA926, 0xA92D},
- {0xA947, 0xA953}, {0xA980, 0xA983}, {0xA9B3, 0xA9C0},
- {0xA9E5, 0xA9E5}, {0xAA29, 0xAA36}, {0xAA43, 0xAA43},
- {0xAA4C, 0xAA4D}, {0xAA7B, 0xAA7D}, {0xAAB0, 0xAAB0},
- {0xAAB2, 0xAAB4}, {0xAAB7, 0xAAB8}, {0xAABE, 0xAABF},
- {0xAAC1, 0xAAC1}, {0xAAEB, 0xAAEF}, {0xAAF5, 0xAAF6},
- {0xABE3, 0xABEA}, {0xABEC, 0xABED}, {0xFB1E, 0xFB1E},
- {0xFE00, 0xFE0F}, {0xFE20, 0xFE2F}, {0x101FD, 0x101FD},
- {0x102E0, 0x102E0}, {0x10376, 0x1037A}, {0x10A01, 0x10A03},
- {0x10A05, 0x10A06}, {0x10A0C, 0x10A0F}, {0x10A38, 0x10A3A},
- {0x10A3F, 0x10A3F}, {0x10AE5, 0x10AE6}, {0x11000, 0x11002},
- {0x11038, 0x11046}, {0x1107F, 0x11082}, {0x110B0, 0x110BA},
- {0x11100, 0x11102}, {0x11127, 0x11134}, {0x11173, 0x11173},
- {0x11180, 0x11182}, {0x111B3, 0x111C0}, {0x111CA, 0x111CC},
- {0x1122C, 0x11237}, {0x1123E, 0x1123E}, {0x112DF, 0x112EA},
- {0x11300, 0x11303}, {0x1133C, 0x1133C}, {0x1133E, 0x11344},
- {0x11347, 0x11348}, {0x1134B, 0x1134D}, {0x11357, 0x11357},
- {0x11362, 0x11363}, {0x11366, 0x1136C}, {0x11370, 0x11374},
- {0x11435, 0x11446}, {0x114B0, 0x114C3}, {0x115AF, 0x115B5},
- {0x115B8, 0x115C0}, {0x115DC, 0x115DD}, {0x11630, 0x11640},
- {0x116AB, 0x116B7}, {0x1171D, 0x1172B}, {0x11C2F, 0x11C36},
- {0x11C38, 0x11C3F}, {0x11C92, 0x11CA7}, {0x11CA9, 0x11CB6},
- {0x16AF0, 0x16AF4}, {0x16B30, 0x16B36}, {0x16F51, 0x16F7E},
- {0x16F8F, 0x16F92}, {0x1BC9D, 0x1BC9E}, {0x1D165, 0x1D169},
- {0x1D16D, 0x1D172}, {0x1D17B, 0x1D182}, {0x1D185, 0x1D18B},
- {0x1D1AA, 0x1D1AD}, {0x1D242, 0x1D244}, {0x1DA00, 0x1DA36},
- {0x1DA3B, 0x1DA6C}, {0x1DA75, 0x1DA75}, {0x1DA84, 0x1DA84},
- {0x1DA9B, 0x1DA9F}, {0x1DAA1, 0x1DAAF}, {0x1E000, 0x1E006},
- {0x1E008, 0x1E018}, {0x1E01B, 0x1E021}, {0x1E023, 0x1E024},
- {0x1E026, 0x1E02A}, {0x1E8D0, 0x1E8D6}, {0x1E944, 0x1E94A},
- {0xE0100, 0xE01EF},
-}
-
-var doublewidth = table{
- {0x1100, 0x115F}, {0x231A, 0x231B}, {0x2329, 0x232A},
- {0x23E9, 0x23EC}, {0x23F0, 0x23F0}, {0x23F3, 0x23F3},
- {0x25FD, 0x25FE}, {0x2614, 0x2615}, {0x2648, 0x2653},
- {0x267F, 0x267F}, {0x2693, 0x2693}, {0x26A1, 0x26A1},
- {0x26AA, 0x26AB}, {0x26BD, 0x26BE}, {0x26C4, 0x26C5},
- {0x26CE, 0x26CE}, {0x26D4, 0x26D4}, {0x26EA, 0x26EA},
- {0x26F2, 0x26F3}, {0x26F5, 0x26F5}, {0x26FA, 0x26FA},
- {0x26FD, 0x26FD}, {0x2705, 0x2705}, {0x270A, 0x270B},
- {0x2728, 0x2728}, {0x274C, 0x274C}, {0x274E, 0x274E},
- {0x2753, 0x2755}, {0x2757, 0x2757}, {0x2795, 0x2797},
- {0x27B0, 0x27B0}, {0x27BF, 0x27BF}, {0x2B1B, 0x2B1C},
- {0x2B50, 0x2B50}, {0x2B55, 0x2B55}, {0x2E80, 0x2E99},
- {0x2E9B, 0x2EF3}, {0x2F00, 0x2FD5}, {0x2FF0, 0x2FFB},
- {0x3000, 0x303E}, {0x3041, 0x3096}, {0x3099, 0x30FF},
- {0x3105, 0x312D}, {0x3131, 0x318E}, {0x3190, 0x31BA},
- {0x31C0, 0x31E3}, {0x31F0, 0x321E}, {0x3220, 0x3247},
- {0x3250, 0x32FE}, {0x3300, 0x4DBF}, {0x4E00, 0xA48C},
- {0xA490, 0xA4C6}, {0xA960, 0xA97C}, {0xAC00, 0xD7A3},
- {0xF900, 0xFAFF}, {0xFE10, 0xFE19}, {0xFE30, 0xFE52},
- {0xFE54, 0xFE66}, {0xFE68, 0xFE6B}, {0xFF01, 0xFF60},
- {0xFFE0, 0xFFE6}, {0x16FE0, 0x16FE0}, {0x17000, 0x187EC},
- {0x18800, 0x18AF2}, {0x1B000, 0x1B001}, {0x1F004, 0x1F004},
- {0x1F0CF, 0x1F0CF}, {0x1F18E, 0x1F18E}, {0x1F191, 0x1F19A},
- {0x1F200, 0x1F202}, {0x1F210, 0x1F23B}, {0x1F240, 0x1F248},
- {0x1F250, 0x1F251}, {0x1F300, 0x1F320}, {0x1F32D, 0x1F335},
- {0x1F337, 0x1F37C}, {0x1F37E, 0x1F393}, {0x1F3A0, 0x1F3CA},
- {0x1F3CF, 0x1F3D3}, {0x1F3E0, 0x1F3F0}, {0x1F3F4, 0x1F3F4},
- {0x1F3F8, 0x1F43E}, {0x1F440, 0x1F440}, {0x1F442, 0x1F4FC},
- {0x1F4FF, 0x1F53D}, {0x1F54B, 0x1F54E}, {0x1F550, 0x1F567},
- {0x1F57A, 0x1F57A}, {0x1F595, 0x1F596}, {0x1F5A4, 0x1F5A4},
- {0x1F5FB, 0x1F64F}, {0x1F680, 0x1F6C5}, {0x1F6CC, 0x1F6CC},
- {0x1F6D0, 0x1F6D2}, {0x1F6EB, 0x1F6EC}, {0x1F6F4, 0x1F6F6},
- {0x1F910, 0x1F91E}, {0x1F920, 0x1F927}, {0x1F930, 0x1F930},
- {0x1F933, 0x1F93E}, {0x1F940, 0x1F94B}, {0x1F950, 0x1F95E},
- {0x1F980, 0x1F991}, {0x1F9C0, 0x1F9C0}, {0x20000, 0x2FFFD},
- {0x30000, 0x3FFFD},
-}
-
-var ambiguous = table{
- {0x00A1, 0x00A1}, {0x00A4, 0x00A4}, {0x00A7, 0x00A8},
- {0x00AA, 0x00AA}, {0x00AD, 0x00AE}, {0x00B0, 0x00B4},
- {0x00B6, 0x00BA}, {0x00BC, 0x00BF}, {0x00C6, 0x00C6},
- {0x00D0, 0x00D0}, {0x00D7, 0x00D8}, {0x00DE, 0x00E1},
- {0x00E6, 0x00E6}, {0x00E8, 0x00EA}, {0x00EC, 0x00ED},
- {0x00F0, 0x00F0}, {0x00F2, 0x00F3}, {0x00F7, 0x00FA},
- {0x00FC, 0x00FC}, {0x00FE, 0x00FE}, {0x0101, 0x0101},
- {0x0111, 0x0111}, {0x0113, 0x0113}, {0x011B, 0x011B},
- {0x0126, 0x0127}, {0x012B, 0x012B}, {0x0131, 0x0133},
- {0x0138, 0x0138}, {0x013F, 0x0142}, {0x0144, 0x0144},
- {0x0148, 0x014B}, {0x014D, 0x014D}, {0x0152, 0x0153},
- {0x0166, 0x0167}, {0x016B, 0x016B}, {0x01CE, 0x01CE},
- {0x01D0, 0x01D0}, {0x01D2, 0x01D2}, {0x01D4, 0x01D4},
- {0x01D6, 0x01D6}, {0x01D8, 0x01D8}, {0x01DA, 0x01DA},
- {0x01DC, 0x01DC}, {0x0251, 0x0251}, {0x0261, 0x0261},
- {0x02C4, 0x02C4}, {0x02C7, 0x02C7}, {0x02C9, 0x02CB},
- {0x02CD, 0x02CD}, {0x02D0, 0x02D0}, {0x02D8, 0x02DB},
- {0x02DD, 0x02DD}, {0x02DF, 0x02DF}, {0x0300, 0x036F},
- {0x0391, 0x03A1}, {0x03A3, 0x03A9}, {0x03B1, 0x03C1},
- {0x03C3, 0x03C9}, {0x0401, 0x0401}, {0x0410, 0x044F},
- {0x0451, 0x0451}, {0x2010, 0x2010}, {0x2013, 0x2016},
- {0x2018, 0x2019}, {0x201C, 0x201D}, {0x2020, 0x2022},
- {0x2024, 0x2027}, {0x2030, 0x2030}, {0x2032, 0x2033},
- {0x2035, 0x2035}, {0x203B, 0x203B}, {0x203E, 0x203E},
- {0x2074, 0x2074}, {0x207F, 0x207F}, {0x2081, 0x2084},
- {0x20AC, 0x20AC}, {0x2103, 0x2103}, {0x2105, 0x2105},
- {0x2109, 0x2109}, {0x2113, 0x2113}, {0x2116, 0x2116},
- {0x2121, 0x2122}, {0x2126, 0x2126}, {0x212B, 0x212B},
- {0x2153, 0x2154}, {0x215B, 0x215E}, {0x2160, 0x216B},
- {0x2170, 0x2179}, {0x2189, 0x2189}, {0x2190, 0x2199},
- {0x21B8, 0x21B9}, {0x21D2, 0x21D2}, {0x21D4, 0x21D4},
- {0x21E7, 0x21E7}, {0x2200, 0x2200}, {0x2202, 0x2203},
- {0x2207, 0x2208}, {0x220B, 0x220B}, {0x220F, 0x220F},
- {0x2211, 0x2211}, {0x2215, 0x2215}, {0x221A, 0x221A},
- {0x221D, 0x2220}, {0x2223, 0x2223}, {0x2225, 0x2225},
- {0x2227, 0x222C}, {0x222E, 0x222E}, {0x2234, 0x2237},
- {0x223C, 0x223D}, {0x2248, 0x2248}, {0x224C, 0x224C},
- {0x2252, 0x2252}, {0x2260, 0x2261}, {0x2264, 0x2267},
- {0x226A, 0x226B}, {0x226E, 0x226F}, {0x2282, 0x2283},
- {0x2286, 0x2287}, {0x2295, 0x2295}, {0x2299, 0x2299},
- {0x22A5, 0x22A5}, {0x22BF, 0x22BF}, {0x2312, 0x2312},
- {0x2460, 0x24E9}, {0x24EB, 0x254B}, {0x2550, 0x2573},
- {0x2580, 0x258F}, {0x2592, 0x2595}, {0x25A0, 0x25A1},
- {0x25A3, 0x25A9}, {0x25B2, 0x25B3}, {0x25B6, 0x25B7},
- {0x25BC, 0x25BD}, {0x25C0, 0x25C1}, {0x25C6, 0x25C8},
- {0x25CB, 0x25CB}, {0x25CE, 0x25D1}, {0x25E2, 0x25E5},
- {0x25EF, 0x25EF}, {0x2605, 0x2606}, {0x2609, 0x2609},
- {0x260E, 0x260F}, {0x261C, 0x261C}, {0x261E, 0x261E},
- {0x2640, 0x2640}, {0x2642, 0x2642}, {0x2660, 0x2661},
- {0x2663, 0x2665}, {0x2667, 0x266A}, {0x266C, 0x266D},
- {0x266F, 0x266F}, {0x269E, 0x269F}, {0x26BF, 0x26BF},
- {0x26C6, 0x26CD}, {0x26CF, 0x26D3}, {0x26D5, 0x26E1},
- {0x26E3, 0x26E3}, {0x26E8, 0x26E9}, {0x26EB, 0x26F1},
- {0x26F4, 0x26F4}, {0x26F6, 0x26F9}, {0x26FB, 0x26FC},
- {0x26FE, 0x26FF}, {0x273D, 0x273D}, {0x2776, 0x277F},
- {0x2B56, 0x2B59}, {0x3248, 0x324F}, {0xE000, 0xF8FF},
- {0xFE00, 0xFE0F}, {0xFFFD, 0xFFFD}, {0x1F100, 0x1F10A},
- {0x1F110, 0x1F12D}, {0x1F130, 0x1F169}, {0x1F170, 0x1F18D},
- {0x1F18F, 0x1F190}, {0x1F19B, 0x1F1AC}, {0xE0100, 0xE01EF},
- {0xF0000, 0xFFFFD}, {0x100000, 0x10FFFD},
-}
-
-var emoji = table{
- {0x1F1E6, 0x1F1FF}, {0x1F321, 0x1F321}, {0x1F324, 0x1F32C},
- {0x1F336, 0x1F336}, {0x1F37D, 0x1F37D}, {0x1F396, 0x1F397},
- {0x1F399, 0x1F39B}, {0x1F39E, 0x1F39F}, {0x1F3CB, 0x1F3CE},
- {0x1F3D4, 0x1F3DF}, {0x1F3F3, 0x1F3F5}, {0x1F3F7, 0x1F3F7},
- {0x1F43F, 0x1F43F}, {0x1F441, 0x1F441}, {0x1F4FD, 0x1F4FD},
- {0x1F549, 0x1F54A}, {0x1F56F, 0x1F570}, {0x1F573, 0x1F579},
- {0x1F587, 0x1F587}, {0x1F58A, 0x1F58D}, {0x1F590, 0x1F590},
- {0x1F5A5, 0x1F5A5}, {0x1F5A8, 0x1F5A8}, {0x1F5B1, 0x1F5B2},
- {0x1F5BC, 0x1F5BC}, {0x1F5C2, 0x1F5C4}, {0x1F5D1, 0x1F5D3},
- {0x1F5DC, 0x1F5DE}, {0x1F5E1, 0x1F5E1}, {0x1F5E3, 0x1F5E3},
- {0x1F5E8, 0x1F5E8}, {0x1F5EF, 0x1F5EF}, {0x1F5F3, 0x1F5F3},
- {0x1F5FA, 0x1F5FA}, {0x1F6CB, 0x1F6CF}, {0x1F6E0, 0x1F6E5},
- {0x1F6E9, 0x1F6E9}, {0x1F6F0, 0x1F6F0}, {0x1F6F3, 0x1F6F3},
-}
-
-var notassigned = table{
- {0x0378, 0x0379}, {0x0380, 0x0383}, {0x038B, 0x038B},
- {0x038D, 0x038D}, {0x03A2, 0x03A2}, {0x0530, 0x0530},
- {0x0557, 0x0558}, {0x0560, 0x0560}, {0x0588, 0x0588},
- {0x058B, 0x058C}, {0x0590, 0x0590}, {0x05C8, 0x05CF},
- {0x05EB, 0x05EF}, {0x05F5, 0x05FF}, {0x061D, 0x061D},
- {0x070E, 0x070E}, {0x074B, 0x074C}, {0x07B2, 0x07BF},
- {0x07FB, 0x07FF}, {0x082E, 0x082F}, {0x083F, 0x083F},
- {0x085C, 0x085D}, {0x085F, 0x089F}, {0x08B5, 0x08B5},
- {0x08BE, 0x08D3}, {0x0984, 0x0984}, {0x098D, 0x098E},
- {0x0991, 0x0992}, {0x09A9, 0x09A9}, {0x09B1, 0x09B1},
- {0x09B3, 0x09B5}, {0x09BA, 0x09BB}, {0x09C5, 0x09C6},
- {0x09C9, 0x09CA}, {0x09CF, 0x09D6}, {0x09D8, 0x09DB},
- {0x09DE, 0x09DE}, {0x09E4, 0x09E5}, {0x09FC, 0x0A00},
- {0x0A04, 0x0A04}, {0x0A0B, 0x0A0E}, {0x0A11, 0x0A12},
- {0x0A29, 0x0A29}, {0x0A31, 0x0A31}, {0x0A34, 0x0A34},
- {0x0A37, 0x0A37}, {0x0A3A, 0x0A3B}, {0x0A3D, 0x0A3D},
- {0x0A43, 0x0A46}, {0x0A49, 0x0A4A}, {0x0A4E, 0x0A50},
- {0x0A52, 0x0A58}, {0x0A5D, 0x0A5D}, {0x0A5F, 0x0A65},
- {0x0A76, 0x0A80}, {0x0A84, 0x0A84}, {0x0A8E, 0x0A8E},
- {0x0A92, 0x0A92}, {0x0AA9, 0x0AA9}, {0x0AB1, 0x0AB1},
- {0x0AB4, 0x0AB4}, {0x0ABA, 0x0ABB}, {0x0AC6, 0x0AC6},
- {0x0ACA, 0x0ACA}, {0x0ACE, 0x0ACF}, {0x0AD1, 0x0ADF},
- {0x0AE4, 0x0AE5}, {0x0AF2, 0x0AF8}, {0x0AFA, 0x0B00},
- {0x0B04, 0x0B04}, {0x0B0D, 0x0B0E}, {0x0B11, 0x0B12},
- {0x0B29, 0x0B29}, {0x0B31, 0x0B31}, {0x0B34, 0x0B34},
- {0x0B3A, 0x0B3B}, {0x0B45, 0x0B46}, {0x0B49, 0x0B4A},
- {0x0B4E, 0x0B55}, {0x0B58, 0x0B5B}, {0x0B5E, 0x0B5E},
- {0x0B64, 0x0B65}, {0x0B78, 0x0B81}, {0x0B84, 0x0B84},
- {0x0B8B, 0x0B8D}, {0x0B91, 0x0B91}, {0x0B96, 0x0B98},
- {0x0B9B, 0x0B9B}, {0x0B9D, 0x0B9D}, {0x0BA0, 0x0BA2},
- {0x0BA5, 0x0BA7}, {0x0BAB, 0x0BAD}, {0x0BBA, 0x0BBD},
- {0x0BC3, 0x0BC5}, {0x0BC9, 0x0BC9}, {0x0BCE, 0x0BCF},
- {0x0BD1, 0x0BD6}, {0x0BD8, 0x0BE5}, {0x0BFB, 0x0BFF},
- {0x0C04, 0x0C04}, {0x0C0D, 0x0C0D}, {0x0C11, 0x0C11},
- {0x0C29, 0x0C29}, {0x0C3A, 0x0C3C}, {0x0C45, 0x0C45},
- {0x0C49, 0x0C49}, {0x0C4E, 0x0C54}, {0x0C57, 0x0C57},
- {0x0C5B, 0x0C5F}, {0x0C64, 0x0C65}, {0x0C70, 0x0C77},
- {0x0C84, 0x0C84}, {0x0C8D, 0x0C8D}, {0x0C91, 0x0C91},
- {0x0CA9, 0x0CA9}, {0x0CB4, 0x0CB4}, {0x0CBA, 0x0CBB},
- {0x0CC5, 0x0CC5}, {0x0CC9, 0x0CC9}, {0x0CCE, 0x0CD4},
- {0x0CD7, 0x0CDD}, {0x0CDF, 0x0CDF}, {0x0CE4, 0x0CE5},
- {0x0CF0, 0x0CF0}, {0x0CF3, 0x0D00}, {0x0D04, 0x0D04},
- {0x0D0D, 0x0D0D}, {0x0D11, 0x0D11}, {0x0D3B, 0x0D3C},
- {0x0D45, 0x0D45}, {0x0D49, 0x0D49}, {0x0D50, 0x0D53},
- {0x0D64, 0x0D65}, {0x0D80, 0x0D81}, {0x0D84, 0x0D84},
- {0x0D97, 0x0D99}, {0x0DB2, 0x0DB2}, {0x0DBC, 0x0DBC},
- {0x0DBE, 0x0DBF}, {0x0DC7, 0x0DC9}, {0x0DCB, 0x0DCE},
- {0x0DD5, 0x0DD5}, {0x0DD7, 0x0DD7}, {0x0DE0, 0x0DE5},
- {0x0DF0, 0x0DF1}, {0x0DF5, 0x0E00}, {0x0E3B, 0x0E3E},
- {0x0E5C, 0x0E80}, {0x0E83, 0x0E83}, {0x0E85, 0x0E86},
- {0x0E89, 0x0E89}, {0x0E8B, 0x0E8C}, {0x0E8E, 0x0E93},
- {0x0E98, 0x0E98}, {0x0EA0, 0x0EA0}, {0x0EA4, 0x0EA4},
- {0x0EA6, 0x0EA6}, {0x0EA8, 0x0EA9}, {0x0EAC, 0x0EAC},
- {0x0EBA, 0x0EBA}, {0x0EBE, 0x0EBF}, {0x0EC5, 0x0EC5},
- {0x0EC7, 0x0EC7}, {0x0ECE, 0x0ECF}, {0x0EDA, 0x0EDB},
- {0x0EE0, 0x0EFF}, {0x0F48, 0x0F48}, {0x0F6D, 0x0F70},
- {0x0F98, 0x0F98}, {0x0FBD, 0x0FBD}, {0x0FCD, 0x0FCD},
- {0x0FDB, 0x0FFF}, {0x10C6, 0x10C6}, {0x10C8, 0x10CC},
- {0x10CE, 0x10CF}, {0x1249, 0x1249}, {0x124E, 0x124F},
- {0x1257, 0x1257}, {0x1259, 0x1259}, {0x125E, 0x125F},
- {0x1289, 0x1289}, {0x128E, 0x128F}, {0x12B1, 0x12B1},
- {0x12B6, 0x12B7}, {0x12BF, 0x12BF}, {0x12C1, 0x12C1},
- {0x12C6, 0x12C7}, {0x12D7, 0x12D7}, {0x1311, 0x1311},
- {0x1316, 0x1317}, {0x135B, 0x135C}, {0x137D, 0x137F},
- {0x139A, 0x139F}, {0x13F6, 0x13F7}, {0x13FE, 0x13FF},
- {0x169D, 0x169F}, {0x16F9, 0x16FF}, {0x170D, 0x170D},
- {0x1715, 0x171F}, {0x1737, 0x173F}, {0x1754, 0x175F},
- {0x176D, 0x176D}, {0x1771, 0x1771}, {0x1774, 0x177F},
- {0x17DE, 0x17DF}, {0x17EA, 0x17EF}, {0x17FA, 0x17FF},
- {0x180F, 0x180F}, {0x181A, 0x181F}, {0x1878, 0x187F},
- {0x18AB, 0x18AF}, {0x18F6, 0x18FF}, {0x191F, 0x191F},
- {0x192C, 0x192F}, {0x193C, 0x193F}, {0x1941, 0x1943},
- {0x196E, 0x196F}, {0x1975, 0x197F}, {0x19AC, 0x19AF},
- {0x19CA, 0x19CF}, {0x19DB, 0x19DD}, {0x1A1C, 0x1A1D},
- {0x1A5F, 0x1A5F}, {0x1A7D, 0x1A7E}, {0x1A8A, 0x1A8F},
- {0x1A9A, 0x1A9F}, {0x1AAE, 0x1AAF}, {0x1ABF, 0x1AFF},
- {0x1B4C, 0x1B4F}, {0x1B7D, 0x1B7F}, {0x1BF4, 0x1BFB},
- {0x1C38, 0x1C3A}, {0x1C4A, 0x1C4C}, {0x1C89, 0x1CBF},
- {0x1CC8, 0x1CCF}, {0x1CF7, 0x1CF7}, {0x1CFA, 0x1CFF},
- {0x1DF6, 0x1DFA}, {0x1F16, 0x1F17}, {0x1F1E, 0x1F1F},
- {0x1F46, 0x1F47}, {0x1F4E, 0x1F4F}, {0x1F58, 0x1F58},
- {0x1F5A, 0x1F5A}, {0x1F5C, 0x1F5C}, {0x1F5E, 0x1F5E},
- {0x1F7E, 0x1F7F}, {0x1FB5, 0x1FB5}, {0x1FC5, 0x1FC5},
- {0x1FD4, 0x1FD5}, {0x1FDC, 0x1FDC}, {0x1FF0, 0x1FF1},
- {0x1FF5, 0x1FF5}, {0x1FFF, 0x1FFF}, {0x2065, 0x2065},
- {0x2072, 0x2073}, {0x208F, 0x208F}, {0x209D, 0x209F},
- {0x20BF, 0x20CF}, {0x20F1, 0x20FF}, {0x218C, 0x218F},
- {0x23FF, 0x23FF}, {0x2427, 0x243F}, {0x244B, 0x245F},
- {0x2B74, 0x2B75}, {0x2B96, 0x2B97}, {0x2BBA, 0x2BBC},
- {0x2BC9, 0x2BC9}, {0x2BD2, 0x2BEB}, {0x2BF0, 0x2BFF},
- {0x2C2F, 0x2C2F}, {0x2C5F, 0x2C5F}, {0x2CF4, 0x2CF8},
- {0x2D26, 0x2D26}, {0x2D28, 0x2D2C}, {0x2D2E, 0x2D2F},
- {0x2D68, 0x2D6E}, {0x2D71, 0x2D7E}, {0x2D97, 0x2D9F},
- {0x2DA7, 0x2DA7}, {0x2DAF, 0x2DAF}, {0x2DB7, 0x2DB7},
- {0x2DBF, 0x2DBF}, {0x2DC7, 0x2DC7}, {0x2DCF, 0x2DCF},
- {0x2DD7, 0x2DD7}, {0x2DDF, 0x2DDF}, {0x2E45, 0x2E7F},
- {0x2E9A, 0x2E9A}, {0x2EF4, 0x2EFF}, {0x2FD6, 0x2FEF},
- {0x2FFC, 0x2FFF}, {0x3040, 0x3040}, {0x3097, 0x3098},
- {0x3100, 0x3104}, {0x312E, 0x3130}, {0x318F, 0x318F},
- {0x31BB, 0x31BF}, {0x31E4, 0x31EF}, {0x321F, 0x321F},
- {0x32FF, 0x32FF}, {0x4DB6, 0x4DBF}, {0x9FD6, 0x9FFF},
- {0xA48D, 0xA48F}, {0xA4C7, 0xA4CF}, {0xA62C, 0xA63F},
- {0xA6F8, 0xA6FF}, {0xA7AF, 0xA7AF}, {0xA7B8, 0xA7F6},
- {0xA82C, 0xA82F}, {0xA83A, 0xA83F}, {0xA878, 0xA87F},
- {0xA8C6, 0xA8CD}, {0xA8DA, 0xA8DF}, {0xA8FE, 0xA8FF},
- {0xA954, 0xA95E}, {0xA97D, 0xA97F}, {0xA9CE, 0xA9CE},
- {0xA9DA, 0xA9DD}, {0xA9FF, 0xA9FF}, {0xAA37, 0xAA3F},
- {0xAA4E, 0xAA4F}, {0xAA5A, 0xAA5B}, {0xAAC3, 0xAADA},
- {0xAAF7, 0xAB00}, {0xAB07, 0xAB08}, {0xAB0F, 0xAB10},
- {0xAB17, 0xAB1F}, {0xAB27, 0xAB27}, {0xAB2F, 0xAB2F},
- {0xAB66, 0xAB6F}, {0xABEE, 0xABEF}, {0xABFA, 0xABFF},
- {0xD7A4, 0xD7AF}, {0xD7C7, 0xD7CA}, {0xD7FC, 0xD7FF},
- {0xFA6E, 0xFA6F}, {0xFADA, 0xFAFF}, {0xFB07, 0xFB12},
- {0xFB18, 0xFB1C}, {0xFB37, 0xFB37}, {0xFB3D, 0xFB3D},
- {0xFB3F, 0xFB3F}, {0xFB42, 0xFB42}, {0xFB45, 0xFB45},
- {0xFBC2, 0xFBD2}, {0xFD40, 0xFD4F}, {0xFD90, 0xFD91},
- {0xFDC8, 0xFDEF}, {0xFDFE, 0xFDFF}, {0xFE1A, 0xFE1F},
- {0xFE53, 0xFE53}, {0xFE67, 0xFE67}, {0xFE6C, 0xFE6F},
- {0xFE75, 0xFE75}, {0xFEFD, 0xFEFE}, {0xFF00, 0xFF00},
- {0xFFBF, 0xFFC1}, {0xFFC8, 0xFFC9}, {0xFFD0, 0xFFD1},
- {0xFFD8, 0xFFD9}, {0xFFDD, 0xFFDF}, {0xFFE7, 0xFFE7},
- {0xFFEF, 0xFFF8}, {0xFFFE, 0xFFFF}, {0x1000C, 0x1000C},
- {0x10027, 0x10027}, {0x1003B, 0x1003B}, {0x1003E, 0x1003E},
- {0x1004E, 0x1004F}, {0x1005E, 0x1007F}, {0x100FB, 0x100FF},
- {0x10103, 0x10106}, {0x10134, 0x10136}, {0x1018F, 0x1018F},
- {0x1019C, 0x1019F}, {0x101A1, 0x101CF}, {0x101FE, 0x1027F},
- {0x1029D, 0x1029F}, {0x102D1, 0x102DF}, {0x102FC, 0x102FF},
- {0x10324, 0x1032F}, {0x1034B, 0x1034F}, {0x1037B, 0x1037F},
- {0x1039E, 0x1039E}, {0x103C4, 0x103C7}, {0x103D6, 0x103FF},
- {0x1049E, 0x1049F}, {0x104AA, 0x104AF}, {0x104D4, 0x104D7},
- {0x104FC, 0x104FF}, {0x10528, 0x1052F}, {0x10564, 0x1056E},
- {0x10570, 0x105FF}, {0x10737, 0x1073F}, {0x10756, 0x1075F},
- {0x10768, 0x107FF}, {0x10806, 0x10807}, {0x10809, 0x10809},
- {0x10836, 0x10836}, {0x10839, 0x1083B}, {0x1083D, 0x1083E},
- {0x10856, 0x10856}, {0x1089F, 0x108A6}, {0x108B0, 0x108DF},
- {0x108F3, 0x108F3}, {0x108F6, 0x108FA}, {0x1091C, 0x1091E},
- {0x1093A, 0x1093E}, {0x10940, 0x1097F}, {0x109B8, 0x109BB},
- {0x109D0, 0x109D1}, {0x10A04, 0x10A04}, {0x10A07, 0x10A0B},
- {0x10A14, 0x10A14}, {0x10A18, 0x10A18}, {0x10A34, 0x10A37},
- {0x10A3B, 0x10A3E}, {0x10A48, 0x10A4F}, {0x10A59, 0x10A5F},
- {0x10AA0, 0x10ABF}, {0x10AE7, 0x10AEA}, {0x10AF7, 0x10AFF},
- {0x10B36, 0x10B38}, {0x10B56, 0x10B57}, {0x10B73, 0x10B77},
- {0x10B92, 0x10B98}, {0x10B9D, 0x10BA8}, {0x10BB0, 0x10BFF},
- {0x10C49, 0x10C7F}, {0x10CB3, 0x10CBF}, {0x10CF3, 0x10CF9},
- {0x10D00, 0x10E5F}, {0x10E7F, 0x10FFF}, {0x1104E, 0x11051},
- {0x11070, 0x1107E}, {0x110C2, 0x110CF}, {0x110E9, 0x110EF},
- {0x110FA, 0x110FF}, {0x11135, 0x11135}, {0x11144, 0x1114F},
- {0x11177, 0x1117F}, {0x111CE, 0x111CF}, {0x111E0, 0x111E0},
- {0x111F5, 0x111FF}, {0x11212, 0x11212}, {0x1123F, 0x1127F},
- {0x11287, 0x11287}, {0x11289, 0x11289}, {0x1128E, 0x1128E},
- {0x1129E, 0x1129E}, {0x112AA, 0x112AF}, {0x112EB, 0x112EF},
- {0x112FA, 0x112FF}, {0x11304, 0x11304}, {0x1130D, 0x1130E},
- {0x11311, 0x11312}, {0x11329, 0x11329}, {0x11331, 0x11331},
- {0x11334, 0x11334}, {0x1133A, 0x1133B}, {0x11345, 0x11346},
- {0x11349, 0x1134A}, {0x1134E, 0x1134F}, {0x11351, 0x11356},
- {0x11358, 0x1135C}, {0x11364, 0x11365}, {0x1136D, 0x1136F},
- {0x11375, 0x113FF}, {0x1145A, 0x1145A}, {0x1145C, 0x1145C},
- {0x1145E, 0x1147F}, {0x114C8, 0x114CF}, {0x114DA, 0x1157F},
- {0x115B6, 0x115B7}, {0x115DE, 0x115FF}, {0x11645, 0x1164F},
- {0x1165A, 0x1165F}, {0x1166D, 0x1167F}, {0x116B8, 0x116BF},
- {0x116CA, 0x116FF}, {0x1171A, 0x1171C}, {0x1172C, 0x1172F},
- {0x11740, 0x1189F}, {0x118F3, 0x118FE}, {0x11900, 0x11ABF},
- {0x11AF9, 0x11BFF}, {0x11C09, 0x11C09}, {0x11C37, 0x11C37},
- {0x11C46, 0x11C4F}, {0x11C6D, 0x11C6F}, {0x11C90, 0x11C91},
- {0x11CA8, 0x11CA8}, {0x11CB7, 0x11FFF}, {0x1239A, 0x123FF},
- {0x1246F, 0x1246F}, {0x12475, 0x1247F}, {0x12544, 0x12FFF},
- {0x1342F, 0x143FF}, {0x14647, 0x167FF}, {0x16A39, 0x16A3F},
- {0x16A5F, 0x16A5F}, {0x16A6A, 0x16A6D}, {0x16A70, 0x16ACF},
- {0x16AEE, 0x16AEF}, {0x16AF6, 0x16AFF}, {0x16B46, 0x16B4F},
- {0x16B5A, 0x16B5A}, {0x16B62, 0x16B62}, {0x16B78, 0x16B7C},
- {0x16B90, 0x16EFF}, {0x16F45, 0x16F4F}, {0x16F7F, 0x16F8E},
- {0x16FA0, 0x16FDF}, {0x16FE1, 0x16FFF}, {0x187ED, 0x187FF},
- {0x18AF3, 0x1AFFF}, {0x1B002, 0x1BBFF}, {0x1BC6B, 0x1BC6F},
- {0x1BC7D, 0x1BC7F}, {0x1BC89, 0x1BC8F}, {0x1BC9A, 0x1BC9B},
- {0x1BCA4, 0x1CFFF}, {0x1D0F6, 0x1D0FF}, {0x1D127, 0x1D128},
- {0x1D1E9, 0x1D1FF}, {0x1D246, 0x1D2FF}, {0x1D357, 0x1D35F},
- {0x1D372, 0x1D3FF}, {0x1D455, 0x1D455}, {0x1D49D, 0x1D49D},
- {0x1D4A0, 0x1D4A1}, {0x1D4A3, 0x1D4A4}, {0x1D4A7, 0x1D4A8},
- {0x1D4AD, 0x1D4AD}, {0x1D4BA, 0x1D4BA}, {0x1D4BC, 0x1D4BC},
- {0x1D4C4, 0x1D4C4}, {0x1D506, 0x1D506}, {0x1D50B, 0x1D50C},
- {0x1D515, 0x1D515}, {0x1D51D, 0x1D51D}, {0x1D53A, 0x1D53A},
- {0x1D53F, 0x1D53F}, {0x1D545, 0x1D545}, {0x1D547, 0x1D549},
- {0x1D551, 0x1D551}, {0x1D6A6, 0x1D6A7}, {0x1D7CC, 0x1D7CD},
- {0x1DA8C, 0x1DA9A}, {0x1DAA0, 0x1DAA0}, {0x1DAB0, 0x1DFFF},
- {0x1E007, 0x1E007}, {0x1E019, 0x1E01A}, {0x1E022, 0x1E022},
- {0x1E025, 0x1E025}, {0x1E02B, 0x1E7FF}, {0x1E8C5, 0x1E8C6},
- {0x1E8D7, 0x1E8FF}, {0x1E94B, 0x1E94F}, {0x1E95A, 0x1E95D},
- {0x1E960, 0x1EDFF}, {0x1EE04, 0x1EE04}, {0x1EE20, 0x1EE20},
- {0x1EE23, 0x1EE23}, {0x1EE25, 0x1EE26}, {0x1EE28, 0x1EE28},
- {0x1EE33, 0x1EE33}, {0x1EE38, 0x1EE38}, {0x1EE3A, 0x1EE3A},
- {0x1EE3C, 0x1EE41}, {0x1EE43, 0x1EE46}, {0x1EE48, 0x1EE48},
- {0x1EE4A, 0x1EE4A}, {0x1EE4C, 0x1EE4C}, {0x1EE50, 0x1EE50},
- {0x1EE53, 0x1EE53}, {0x1EE55, 0x1EE56}, {0x1EE58, 0x1EE58},
- {0x1EE5A, 0x1EE5A}, {0x1EE5C, 0x1EE5C}, {0x1EE5E, 0x1EE5E},
- {0x1EE60, 0x1EE60}, {0x1EE63, 0x1EE63}, {0x1EE65, 0x1EE66},
- {0x1EE6B, 0x1EE6B}, {0x1EE73, 0x1EE73}, {0x1EE78, 0x1EE78},
- {0x1EE7D, 0x1EE7D}, {0x1EE7F, 0x1EE7F}, {0x1EE8A, 0x1EE8A},
- {0x1EE9C, 0x1EEA0}, {0x1EEA4, 0x1EEA4}, {0x1EEAA, 0x1EEAA},
- {0x1EEBC, 0x1EEEF}, {0x1EEF2, 0x1EFFF}, {0x1F02C, 0x1F02F},
- {0x1F094, 0x1F09F}, {0x1F0AF, 0x1F0B0}, {0x1F0C0, 0x1F0C0},
- {0x1F0D0, 0x1F0D0}, {0x1F0F6, 0x1F0FF}, {0x1F10D, 0x1F10F},
- {0x1F12F, 0x1F12F}, {0x1F16C, 0x1F16F}, {0x1F1AD, 0x1F1E5},
- {0x1F203, 0x1F20F}, {0x1F23C, 0x1F23F}, {0x1F249, 0x1F24F},
- {0x1F252, 0x1F2FF}, {0x1F6D3, 0x1F6DF}, {0x1F6ED, 0x1F6EF},
- {0x1F6F7, 0x1F6FF}, {0x1F774, 0x1F77F}, {0x1F7D5, 0x1F7FF},
- {0x1F80C, 0x1F80F}, {0x1F848, 0x1F84F}, {0x1F85A, 0x1F85F},
- {0x1F888, 0x1F88F}, {0x1F8AE, 0x1F90F}, {0x1F91F, 0x1F91F},
- {0x1F928, 0x1F92F}, {0x1F931, 0x1F932}, {0x1F93F, 0x1F93F},
- {0x1F94C, 0x1F94F}, {0x1F95F, 0x1F97F}, {0x1F992, 0x1F9BF},
- {0x1F9C1, 0x1FFFF}, {0x2A6D7, 0x2A6FF}, {0x2B735, 0x2B73F},
- {0x2B81E, 0x2B81F}, {0x2CEA2, 0x2F7FF}, {0x2FA1E, 0xE0000},
- {0xE0002, 0xE001F}, {0xE0080, 0xE00FF}, {0xE01F0, 0xEFFFF},
- {0xFFFFE, 0xFFFFF},
-}
-
-var neutral = table{
- {0x0000, 0x001F}, {0x007F, 0x007F}, {0x0080, 0x009F},
- {0x00A0, 0x00A0}, {0x00A9, 0x00A9}, {0x00AB, 0x00AB},
- {0x00B5, 0x00B5}, {0x00BB, 0x00BB}, {0x00C0, 0x00C5},
- {0x00C7, 0x00CF}, {0x00D1, 0x00D6}, {0x00D9, 0x00DD},
- {0x00E2, 0x00E5}, {0x00E7, 0x00E7}, {0x00EB, 0x00EB},
- {0x00EE, 0x00EF}, {0x00F1, 0x00F1}, {0x00F4, 0x00F6},
- {0x00FB, 0x00FB}, {0x00FD, 0x00FD}, {0x00FF, 0x00FF},
- {0x0100, 0x0100}, {0x0102, 0x0110}, {0x0112, 0x0112},
- {0x0114, 0x011A}, {0x011C, 0x0125}, {0x0128, 0x012A},
- {0x012C, 0x0130}, {0x0134, 0x0137}, {0x0139, 0x013E},
- {0x0143, 0x0143}, {0x0145, 0x0147}, {0x014C, 0x014C},
- {0x014E, 0x0151}, {0x0154, 0x0165}, {0x0168, 0x016A},
- {0x016C, 0x017F}, {0x0180, 0x01BA}, {0x01BB, 0x01BB},
- {0x01BC, 0x01BF}, {0x01C0, 0x01C3}, {0x01C4, 0x01CD},
- {0x01CF, 0x01CF}, {0x01D1, 0x01D1}, {0x01D3, 0x01D3},
- {0x01D5, 0x01D5}, {0x01D7, 0x01D7}, {0x01D9, 0x01D9},
- {0x01DB, 0x01DB}, {0x01DD, 0x024F}, {0x0250, 0x0250},
- {0x0252, 0x0260}, {0x0262, 0x0293}, {0x0294, 0x0294},
- {0x0295, 0x02AF}, {0x02B0, 0x02C1}, {0x02C2, 0x02C3},
- {0x02C5, 0x02C5}, {0x02C6, 0x02C6}, {0x02C8, 0x02C8},
- {0x02CC, 0x02CC}, {0x02CE, 0x02CF}, {0x02D1, 0x02D1},
- {0x02D2, 0x02D7}, {0x02DC, 0x02DC}, {0x02DE, 0x02DE},
- {0x02E0, 0x02E4}, {0x02E5, 0x02EB}, {0x02EC, 0x02EC},
- {0x02ED, 0x02ED}, {0x02EE, 0x02EE}, {0x02EF, 0x02FF},
- {0x0370, 0x0373}, {0x0374, 0x0374}, {0x0375, 0x0375},
- {0x0376, 0x0377}, {0x037A, 0x037A}, {0x037B, 0x037D},
- {0x037E, 0x037E}, {0x037F, 0x037F}, {0x0384, 0x0385},
- {0x0386, 0x0386}, {0x0387, 0x0387}, {0x0388, 0x038A},
- {0x038C, 0x038C}, {0x038E, 0x0390}, {0x03AA, 0x03B0},
- {0x03C2, 0x03C2}, {0x03CA, 0x03F5}, {0x03F6, 0x03F6},
- {0x03F7, 0x03FF}, {0x0400, 0x0400}, {0x0402, 0x040F},
- {0x0450, 0x0450}, {0x0452, 0x0481}, {0x0482, 0x0482},
- {0x0483, 0x0487}, {0x0488, 0x0489}, {0x048A, 0x04FF},
- {0x0500, 0x052F}, {0x0531, 0x0556}, {0x0559, 0x0559},
- {0x055A, 0x055F}, {0x0561, 0x0587}, {0x0589, 0x0589},
- {0x058A, 0x058A}, {0x058D, 0x058E}, {0x058F, 0x058F},
- {0x0591, 0x05BD}, {0x05BE, 0x05BE}, {0x05BF, 0x05BF},
- {0x05C0, 0x05C0}, {0x05C1, 0x05C2}, {0x05C3, 0x05C3},
- {0x05C4, 0x05C5}, {0x05C6, 0x05C6}, {0x05C7, 0x05C7},
- {0x05D0, 0x05EA}, {0x05F0, 0x05F2}, {0x05F3, 0x05F4},
- {0x0600, 0x0605}, {0x0606, 0x0608}, {0x0609, 0x060A},
- {0x060B, 0x060B}, {0x060C, 0x060D}, {0x060E, 0x060F},
- {0x0610, 0x061A}, {0x061B, 0x061B}, {0x061C, 0x061C},
- {0x061E, 0x061F}, {0x0620, 0x063F}, {0x0640, 0x0640},
- {0x0641, 0x064A}, {0x064B, 0x065F}, {0x0660, 0x0669},
- {0x066A, 0x066D}, {0x066E, 0x066F}, {0x0670, 0x0670},
- {0x0671, 0x06D3}, {0x06D4, 0x06D4}, {0x06D5, 0x06D5},
- {0x06D6, 0x06DC}, {0x06DD, 0x06DD}, {0x06DE, 0x06DE},
- {0x06DF, 0x06E4}, {0x06E5, 0x06E6}, {0x06E7, 0x06E8},
- {0x06E9, 0x06E9}, {0x06EA, 0x06ED}, {0x06EE, 0x06EF},
- {0x06F0, 0x06F9}, {0x06FA, 0x06FC}, {0x06FD, 0x06FE},
- {0x06FF, 0x06FF}, {0x0700, 0x070D}, {0x070F, 0x070F},
- {0x0710, 0x0710}, {0x0711, 0x0711}, {0x0712, 0x072F},
- {0x0730, 0x074A}, {0x074D, 0x074F}, {0x0750, 0x077F},
- {0x0780, 0x07A5}, {0x07A6, 0x07B0}, {0x07B1, 0x07B1},
- {0x07C0, 0x07C9}, {0x07CA, 0x07EA}, {0x07EB, 0x07F3},
- {0x07F4, 0x07F5}, {0x07F6, 0x07F6}, {0x07F7, 0x07F9},
- {0x07FA, 0x07FA}, {0x0800, 0x0815}, {0x0816, 0x0819},
- {0x081A, 0x081A}, {0x081B, 0x0823}, {0x0824, 0x0824},
- {0x0825, 0x0827}, {0x0828, 0x0828}, {0x0829, 0x082D},
- {0x0830, 0x083E}, {0x0840, 0x0858}, {0x0859, 0x085B},
- {0x085E, 0x085E}, {0x08A0, 0x08B4}, {0x08B6, 0x08BD},
- {0x08D4, 0x08E1}, {0x08E2, 0x08E2}, {0x08E3, 0x08FF},
- {0x0900, 0x0902}, {0x0903, 0x0903}, {0x0904, 0x0939},
- {0x093A, 0x093A}, {0x093B, 0x093B}, {0x093C, 0x093C},
- {0x093D, 0x093D}, {0x093E, 0x0940}, {0x0941, 0x0948},
- {0x0949, 0x094C}, {0x094D, 0x094D}, {0x094E, 0x094F},
- {0x0950, 0x0950}, {0x0951, 0x0957}, {0x0958, 0x0961},
- {0x0962, 0x0963}, {0x0964, 0x0965}, {0x0966, 0x096F},
- {0x0970, 0x0970}, {0x0971, 0x0971}, {0x0972, 0x097F},
- {0x0980, 0x0980}, {0x0981, 0x0981}, {0x0982, 0x0983},
- {0x0985, 0x098C}, {0x098F, 0x0990}, {0x0993, 0x09A8},
- {0x09AA, 0x09B0}, {0x09B2, 0x09B2}, {0x09B6, 0x09B9},
- {0x09BC, 0x09BC}, {0x09BD, 0x09BD}, {0x09BE, 0x09C0},
- {0x09C1, 0x09C4}, {0x09C7, 0x09C8}, {0x09CB, 0x09CC},
- {0x09CD, 0x09CD}, {0x09CE, 0x09CE}, {0x09D7, 0x09D7},
- {0x09DC, 0x09DD}, {0x09DF, 0x09E1}, {0x09E2, 0x09E3},
- {0x09E6, 0x09EF}, {0x09F0, 0x09F1}, {0x09F2, 0x09F3},
- {0x09F4, 0x09F9}, {0x09FA, 0x09FA}, {0x09FB, 0x09FB},
- {0x0A01, 0x0A02}, {0x0A03, 0x0A03}, {0x0A05, 0x0A0A},
- {0x0A0F, 0x0A10}, {0x0A13, 0x0A28}, {0x0A2A, 0x0A30},
- {0x0A32, 0x0A33}, {0x0A35, 0x0A36}, {0x0A38, 0x0A39},
- {0x0A3C, 0x0A3C}, {0x0A3E, 0x0A40}, {0x0A41, 0x0A42},
- {0x0A47, 0x0A48}, {0x0A4B, 0x0A4D}, {0x0A51, 0x0A51},
- {0x0A59, 0x0A5C}, {0x0A5E, 0x0A5E}, {0x0A66, 0x0A6F},
- {0x0A70, 0x0A71}, {0x0A72, 0x0A74}, {0x0A75, 0x0A75},
- {0x0A81, 0x0A82}, {0x0A83, 0x0A83}, {0x0A85, 0x0A8D},
- {0x0A8F, 0x0A91}, {0x0A93, 0x0AA8}, {0x0AAA, 0x0AB0},
- {0x0AB2, 0x0AB3}, {0x0AB5, 0x0AB9}, {0x0ABC, 0x0ABC},
- {0x0ABD, 0x0ABD}, {0x0ABE, 0x0AC0}, {0x0AC1, 0x0AC5},
- {0x0AC7, 0x0AC8}, {0x0AC9, 0x0AC9}, {0x0ACB, 0x0ACC},
- {0x0ACD, 0x0ACD}, {0x0AD0, 0x0AD0}, {0x0AE0, 0x0AE1},
- {0x0AE2, 0x0AE3}, {0x0AE6, 0x0AEF}, {0x0AF0, 0x0AF0},
- {0x0AF1, 0x0AF1}, {0x0AF9, 0x0AF9}, {0x0B01, 0x0B01},
- {0x0B02, 0x0B03}, {0x0B05, 0x0B0C}, {0x0B0F, 0x0B10},
- {0x0B13, 0x0B28}, {0x0B2A, 0x0B30}, {0x0B32, 0x0B33},
- {0x0B35, 0x0B39}, {0x0B3C, 0x0B3C}, {0x0B3D, 0x0B3D},
- {0x0B3E, 0x0B3E}, {0x0B3F, 0x0B3F}, {0x0B40, 0x0B40},
- {0x0B41, 0x0B44}, {0x0B47, 0x0B48}, {0x0B4B, 0x0B4C},
- {0x0B4D, 0x0B4D}, {0x0B56, 0x0B56}, {0x0B57, 0x0B57},
- {0x0B5C, 0x0B5D}, {0x0B5F, 0x0B61}, {0x0B62, 0x0B63},
- {0x0B66, 0x0B6F}, {0x0B70, 0x0B70}, {0x0B71, 0x0B71},
- {0x0B72, 0x0B77}, {0x0B82, 0x0B82}, {0x0B83, 0x0B83},
- {0x0B85, 0x0B8A}, {0x0B8E, 0x0B90}, {0x0B92, 0x0B95},
- {0x0B99, 0x0B9A}, {0x0B9C, 0x0B9C}, {0x0B9E, 0x0B9F},
- {0x0BA3, 0x0BA4}, {0x0BA8, 0x0BAA}, {0x0BAE, 0x0BB9},
- {0x0BBE, 0x0BBF}, {0x0BC0, 0x0BC0}, {0x0BC1, 0x0BC2},
- {0x0BC6, 0x0BC8}, {0x0BCA, 0x0BCC}, {0x0BCD, 0x0BCD},
- {0x0BD0, 0x0BD0}, {0x0BD7, 0x0BD7}, {0x0BE6, 0x0BEF},
- {0x0BF0, 0x0BF2}, {0x0BF3, 0x0BF8}, {0x0BF9, 0x0BF9},
- {0x0BFA, 0x0BFA}, {0x0C00, 0x0C00}, {0x0C01, 0x0C03},
- {0x0C05, 0x0C0C}, {0x0C0E, 0x0C10}, {0x0C12, 0x0C28},
- {0x0C2A, 0x0C39}, {0x0C3D, 0x0C3D}, {0x0C3E, 0x0C40},
- {0x0C41, 0x0C44}, {0x0C46, 0x0C48}, {0x0C4A, 0x0C4D},
- {0x0C55, 0x0C56}, {0x0C58, 0x0C5A}, {0x0C60, 0x0C61},
- {0x0C62, 0x0C63}, {0x0C66, 0x0C6F}, {0x0C78, 0x0C7E},
- {0x0C7F, 0x0C7F}, {0x0C80, 0x0C80}, {0x0C81, 0x0C81},
- {0x0C82, 0x0C83}, {0x0C85, 0x0C8C}, {0x0C8E, 0x0C90},
- {0x0C92, 0x0CA8}, {0x0CAA, 0x0CB3}, {0x0CB5, 0x0CB9},
- {0x0CBC, 0x0CBC}, {0x0CBD, 0x0CBD}, {0x0CBE, 0x0CBE},
- {0x0CBF, 0x0CBF}, {0x0CC0, 0x0CC4}, {0x0CC6, 0x0CC6},
- {0x0CC7, 0x0CC8}, {0x0CCA, 0x0CCB}, {0x0CCC, 0x0CCD},
- {0x0CD5, 0x0CD6}, {0x0CDE, 0x0CDE}, {0x0CE0, 0x0CE1},
- {0x0CE2, 0x0CE3}, {0x0CE6, 0x0CEF}, {0x0CF1, 0x0CF2},
- {0x0D01, 0x0D01}, {0x0D02, 0x0D03}, {0x0D05, 0x0D0C},
- {0x0D0E, 0x0D10}, {0x0D12, 0x0D3A}, {0x0D3D, 0x0D3D},
- {0x0D3E, 0x0D40}, {0x0D41, 0x0D44}, {0x0D46, 0x0D48},
- {0x0D4A, 0x0D4C}, {0x0D4D, 0x0D4D}, {0x0D4E, 0x0D4E},
- {0x0D4F, 0x0D4F}, {0x0D54, 0x0D56}, {0x0D57, 0x0D57},
- {0x0D58, 0x0D5E}, {0x0D5F, 0x0D61}, {0x0D62, 0x0D63},
- {0x0D66, 0x0D6F}, {0x0D70, 0x0D78}, {0x0D79, 0x0D79},
- {0x0D7A, 0x0D7F}, {0x0D82, 0x0D83}, {0x0D85, 0x0D96},
- {0x0D9A, 0x0DB1}, {0x0DB3, 0x0DBB}, {0x0DBD, 0x0DBD},
- {0x0DC0, 0x0DC6}, {0x0DCA, 0x0DCA}, {0x0DCF, 0x0DD1},
- {0x0DD2, 0x0DD4}, {0x0DD6, 0x0DD6}, {0x0DD8, 0x0DDF},
- {0x0DE6, 0x0DEF}, {0x0DF2, 0x0DF3}, {0x0DF4, 0x0DF4},
- {0x0E01, 0x0E30}, {0x0E31, 0x0E31}, {0x0E32, 0x0E33},
- {0x0E34, 0x0E3A}, {0x0E3F, 0x0E3F}, {0x0E40, 0x0E45},
- {0x0E46, 0x0E46}, {0x0E47, 0x0E4E}, {0x0E4F, 0x0E4F},
- {0x0E50, 0x0E59}, {0x0E5A, 0x0E5B}, {0x0E81, 0x0E82},
- {0x0E84, 0x0E84}, {0x0E87, 0x0E88}, {0x0E8A, 0x0E8A},
- {0x0E8D, 0x0E8D}, {0x0E94, 0x0E97}, {0x0E99, 0x0E9F},
- {0x0EA1, 0x0EA3}, {0x0EA5, 0x0EA5}, {0x0EA7, 0x0EA7},
- {0x0EAA, 0x0EAB}, {0x0EAD, 0x0EB0}, {0x0EB1, 0x0EB1},
- {0x0EB2, 0x0EB3}, {0x0EB4, 0x0EB9}, {0x0EBB, 0x0EBC},
- {0x0EBD, 0x0EBD}, {0x0EC0, 0x0EC4}, {0x0EC6, 0x0EC6},
- {0x0EC8, 0x0ECD}, {0x0ED0, 0x0ED9}, {0x0EDC, 0x0EDF},
- {0x0F00, 0x0F00}, {0x0F01, 0x0F03}, {0x0F04, 0x0F12},
- {0x0F13, 0x0F13}, {0x0F14, 0x0F14}, {0x0F15, 0x0F17},
- {0x0F18, 0x0F19}, {0x0F1A, 0x0F1F}, {0x0F20, 0x0F29},
- {0x0F2A, 0x0F33}, {0x0F34, 0x0F34}, {0x0F35, 0x0F35},
- {0x0F36, 0x0F36}, {0x0F37, 0x0F37}, {0x0F38, 0x0F38},
- {0x0F39, 0x0F39}, {0x0F3A, 0x0F3A}, {0x0F3B, 0x0F3B},
- {0x0F3C, 0x0F3C}, {0x0F3D, 0x0F3D}, {0x0F3E, 0x0F3F},
- {0x0F40, 0x0F47}, {0x0F49, 0x0F6C}, {0x0F71, 0x0F7E},
- {0x0F7F, 0x0F7F}, {0x0F80, 0x0F84}, {0x0F85, 0x0F85},
- {0x0F86, 0x0F87}, {0x0F88, 0x0F8C}, {0x0F8D, 0x0F97},
- {0x0F99, 0x0FBC}, {0x0FBE, 0x0FC5}, {0x0FC6, 0x0FC6},
- {0x0FC7, 0x0FCC}, {0x0FCE, 0x0FCF}, {0x0FD0, 0x0FD4},
- {0x0FD5, 0x0FD8}, {0x0FD9, 0x0FDA}, {0x1000, 0x102A},
- {0x102B, 0x102C}, {0x102D, 0x1030}, {0x1031, 0x1031},
- {0x1032, 0x1037}, {0x1038, 0x1038}, {0x1039, 0x103A},
- {0x103B, 0x103C}, {0x103D, 0x103E}, {0x103F, 0x103F},
- {0x1040, 0x1049}, {0x104A, 0x104F}, {0x1050, 0x1055},
- {0x1056, 0x1057}, {0x1058, 0x1059}, {0x105A, 0x105D},
- {0x105E, 0x1060}, {0x1061, 0x1061}, {0x1062, 0x1064},
- {0x1065, 0x1066}, {0x1067, 0x106D}, {0x106E, 0x1070},
- {0x1071, 0x1074}, {0x1075, 0x1081}, {0x1082, 0x1082},
- {0x1083, 0x1084}, {0x1085, 0x1086}, {0x1087, 0x108C},
- {0x108D, 0x108D}, {0x108E, 0x108E}, {0x108F, 0x108F},
- {0x1090, 0x1099}, {0x109A, 0x109C}, {0x109D, 0x109D},
- {0x109E, 0x109F}, {0x10A0, 0x10C5}, {0x10C7, 0x10C7},
- {0x10CD, 0x10CD}, {0x10D0, 0x10FA}, {0x10FB, 0x10FB},
- {0x10FC, 0x10FC}, {0x10FD, 0x10FF}, {0x1160, 0x11FF},
- {0x1200, 0x1248}, {0x124A, 0x124D}, {0x1250, 0x1256},
- {0x1258, 0x1258}, {0x125A, 0x125D}, {0x1260, 0x1288},
- {0x128A, 0x128D}, {0x1290, 0x12B0}, {0x12B2, 0x12B5},
- {0x12B8, 0x12BE}, {0x12C0, 0x12C0}, {0x12C2, 0x12C5},
- {0x12C8, 0x12D6}, {0x12D8, 0x1310}, {0x1312, 0x1315},
- {0x1318, 0x135A}, {0x135D, 0x135F}, {0x1360, 0x1368},
- {0x1369, 0x137C}, {0x1380, 0x138F}, {0x1390, 0x1399},
- {0x13A0, 0x13F5}, {0x13F8, 0x13FD}, {0x1400, 0x1400},
- {0x1401, 0x166C}, {0x166D, 0x166E}, {0x166F, 0x167F},
- {0x1680, 0x1680}, {0x1681, 0x169A}, {0x169B, 0x169B},
- {0x169C, 0x169C}, {0x16A0, 0x16EA}, {0x16EB, 0x16ED},
- {0x16EE, 0x16F0}, {0x16F1, 0x16F8}, {0x1700, 0x170C},
- {0x170E, 0x1711}, {0x1712, 0x1714}, {0x1720, 0x1731},
- {0x1732, 0x1734}, {0x1735, 0x1736}, {0x1740, 0x1751},
- {0x1752, 0x1753}, {0x1760, 0x176C}, {0x176E, 0x1770},
- {0x1772, 0x1773}, {0x1780, 0x17B3}, {0x17B4, 0x17B5},
- {0x17B6, 0x17B6}, {0x17B7, 0x17BD}, {0x17BE, 0x17C5},
- {0x17C6, 0x17C6}, {0x17C7, 0x17C8}, {0x17C9, 0x17D3},
- {0x17D4, 0x17D6}, {0x17D7, 0x17D7}, {0x17D8, 0x17DA},
- {0x17DB, 0x17DB}, {0x17DC, 0x17DC}, {0x17DD, 0x17DD},
- {0x17E0, 0x17E9}, {0x17F0, 0x17F9}, {0x1800, 0x1805},
- {0x1806, 0x1806}, {0x1807, 0x180A}, {0x180B, 0x180D},
- {0x180E, 0x180E}, {0x1810, 0x1819}, {0x1820, 0x1842},
- {0x1843, 0x1843}, {0x1844, 0x1877}, {0x1880, 0x1884},
- {0x1885, 0x1886}, {0x1887, 0x18A8}, {0x18A9, 0x18A9},
- {0x18AA, 0x18AA}, {0x18B0, 0x18F5}, {0x1900, 0x191E},
- {0x1920, 0x1922}, {0x1923, 0x1926}, {0x1927, 0x1928},
- {0x1929, 0x192B}, {0x1930, 0x1931}, {0x1932, 0x1932},
- {0x1933, 0x1938}, {0x1939, 0x193B}, {0x1940, 0x1940},
- {0x1944, 0x1945}, {0x1946, 0x194F}, {0x1950, 0x196D},
- {0x1970, 0x1974}, {0x1980, 0x19AB}, {0x19B0, 0x19C9},
- {0x19D0, 0x19D9}, {0x19DA, 0x19DA}, {0x19DE, 0x19DF},
- {0x19E0, 0x19FF}, {0x1A00, 0x1A16}, {0x1A17, 0x1A18},
- {0x1A19, 0x1A1A}, {0x1A1B, 0x1A1B}, {0x1A1E, 0x1A1F},
- {0x1A20, 0x1A54}, {0x1A55, 0x1A55}, {0x1A56, 0x1A56},
- {0x1A57, 0x1A57}, {0x1A58, 0x1A5E}, {0x1A60, 0x1A60},
- {0x1A61, 0x1A61}, {0x1A62, 0x1A62}, {0x1A63, 0x1A64},
- {0x1A65, 0x1A6C}, {0x1A6D, 0x1A72}, {0x1A73, 0x1A7C},
- {0x1A7F, 0x1A7F}, {0x1A80, 0x1A89}, {0x1A90, 0x1A99},
- {0x1AA0, 0x1AA6}, {0x1AA7, 0x1AA7}, {0x1AA8, 0x1AAD},
- {0x1AB0, 0x1ABD}, {0x1ABE, 0x1ABE}, {0x1B00, 0x1B03},
- {0x1B04, 0x1B04}, {0x1B05, 0x1B33}, {0x1B34, 0x1B34},
- {0x1B35, 0x1B35}, {0x1B36, 0x1B3A}, {0x1B3B, 0x1B3B},
- {0x1B3C, 0x1B3C}, {0x1B3D, 0x1B41}, {0x1B42, 0x1B42},
- {0x1B43, 0x1B44}, {0x1B45, 0x1B4B}, {0x1B50, 0x1B59},
- {0x1B5A, 0x1B60}, {0x1B61, 0x1B6A}, {0x1B6B, 0x1B73},
- {0x1B74, 0x1B7C}, {0x1B80, 0x1B81}, {0x1B82, 0x1B82},
- {0x1B83, 0x1BA0}, {0x1BA1, 0x1BA1}, {0x1BA2, 0x1BA5},
- {0x1BA6, 0x1BA7}, {0x1BA8, 0x1BA9}, {0x1BAA, 0x1BAA},
- {0x1BAB, 0x1BAD}, {0x1BAE, 0x1BAF}, {0x1BB0, 0x1BB9},
- {0x1BBA, 0x1BBF}, {0x1BC0, 0x1BE5}, {0x1BE6, 0x1BE6},
- {0x1BE7, 0x1BE7}, {0x1BE8, 0x1BE9}, {0x1BEA, 0x1BEC},
- {0x1BED, 0x1BED}, {0x1BEE, 0x1BEE}, {0x1BEF, 0x1BF1},
- {0x1BF2, 0x1BF3}, {0x1BFC, 0x1BFF}, {0x1C00, 0x1C23},
- {0x1C24, 0x1C2B}, {0x1C2C, 0x1C33}, {0x1C34, 0x1C35},
- {0x1C36, 0x1C37}, {0x1C3B, 0x1C3F}, {0x1C40, 0x1C49},
- {0x1C4D, 0x1C4F}, {0x1C50, 0x1C59}, {0x1C5A, 0x1C77},
- {0x1C78, 0x1C7D}, {0x1C7E, 0x1C7F}, {0x1C80, 0x1C88},
- {0x1CC0, 0x1CC7}, {0x1CD0, 0x1CD2}, {0x1CD3, 0x1CD3},
- {0x1CD4, 0x1CE0}, {0x1CE1, 0x1CE1}, {0x1CE2, 0x1CE8},
- {0x1CE9, 0x1CEC}, {0x1CED, 0x1CED}, {0x1CEE, 0x1CF1},
- {0x1CF2, 0x1CF3}, {0x1CF4, 0x1CF4}, {0x1CF5, 0x1CF6},
- {0x1CF8, 0x1CF9}, {0x1D00, 0x1D2B}, {0x1D2C, 0x1D6A},
- {0x1D6B, 0x1D77}, {0x1D78, 0x1D78}, {0x1D79, 0x1D7F},
- {0x1D80, 0x1D9A}, {0x1D9B, 0x1DBF}, {0x1DC0, 0x1DF5},
- {0x1DFB, 0x1DFF}, {0x1E00, 0x1EFF}, {0x1F00, 0x1F15},
- {0x1F18, 0x1F1D}, {0x1F20, 0x1F45}, {0x1F48, 0x1F4D},
- {0x1F50, 0x1F57}, {0x1F59, 0x1F59}, {0x1F5B, 0x1F5B},
- {0x1F5D, 0x1F5D}, {0x1F5F, 0x1F7D}, {0x1F80, 0x1FB4},
- {0x1FB6, 0x1FBC}, {0x1FBD, 0x1FBD}, {0x1FBE, 0x1FBE},
- {0x1FBF, 0x1FC1}, {0x1FC2, 0x1FC4}, {0x1FC6, 0x1FCC},
- {0x1FCD, 0x1FCF}, {0x1FD0, 0x1FD3}, {0x1FD6, 0x1FDB},
- {0x1FDD, 0x1FDF}, {0x1FE0, 0x1FEC}, {0x1FED, 0x1FEF},
- {0x1FF2, 0x1FF4}, {0x1FF6, 0x1FFC}, {0x1FFD, 0x1FFE},
- {0x2000, 0x200A}, {0x200B, 0x200F}, {0x2011, 0x2012},
- {0x2017, 0x2017}, {0x201A, 0x201A}, {0x201B, 0x201B},
- {0x201E, 0x201E}, {0x201F, 0x201F}, {0x2023, 0x2023},
- {0x2028, 0x2028}, {0x2029, 0x2029}, {0x202A, 0x202E},
- {0x202F, 0x202F}, {0x2031, 0x2031}, {0x2034, 0x2034},
- {0x2036, 0x2038}, {0x2039, 0x2039}, {0x203A, 0x203A},
- {0x203C, 0x203D}, {0x203F, 0x2040}, {0x2041, 0x2043},
- {0x2044, 0x2044}, {0x2045, 0x2045}, {0x2046, 0x2046},
- {0x2047, 0x2051}, {0x2052, 0x2052}, {0x2053, 0x2053},
- {0x2054, 0x2054}, {0x2055, 0x205E}, {0x205F, 0x205F},
- {0x2060, 0x2064}, {0x2066, 0x206F}, {0x2070, 0x2070},
- {0x2071, 0x2071}, {0x2075, 0x2079}, {0x207A, 0x207C},
- {0x207D, 0x207D}, {0x207E, 0x207E}, {0x2080, 0x2080},
- {0x2085, 0x2089}, {0x208A, 0x208C}, {0x208D, 0x208D},
- {0x208E, 0x208E}, {0x2090, 0x209C}, {0x20A0, 0x20A8},
- {0x20AA, 0x20AB}, {0x20AD, 0x20BE}, {0x20D0, 0x20DC},
- {0x20DD, 0x20E0}, {0x20E1, 0x20E1}, {0x20E2, 0x20E4},
- {0x20E5, 0x20F0}, {0x2100, 0x2101}, {0x2102, 0x2102},
- {0x2104, 0x2104}, {0x2106, 0x2106}, {0x2107, 0x2107},
- {0x2108, 0x2108}, {0x210A, 0x2112}, {0x2114, 0x2114},
- {0x2115, 0x2115}, {0x2117, 0x2117}, {0x2118, 0x2118},
- {0x2119, 0x211D}, {0x211E, 0x2120}, {0x2123, 0x2123},
- {0x2124, 0x2124}, {0x2125, 0x2125}, {0x2127, 0x2127},
- {0x2128, 0x2128}, {0x2129, 0x2129}, {0x212A, 0x212A},
- {0x212C, 0x212D}, {0x212E, 0x212E}, {0x212F, 0x2134},
- {0x2135, 0x2138}, {0x2139, 0x2139}, {0x213A, 0x213B},
- {0x213C, 0x213F}, {0x2140, 0x2144}, {0x2145, 0x2149},
- {0x214A, 0x214A}, {0x214B, 0x214B}, {0x214C, 0x214D},
- {0x214E, 0x214E}, {0x214F, 0x214F}, {0x2150, 0x2152},
- {0x2155, 0x215A}, {0x215F, 0x215F}, {0x216C, 0x216F},
- {0x217A, 0x2182}, {0x2183, 0x2184}, {0x2185, 0x2188},
- {0x218A, 0x218B}, {0x219A, 0x219B}, {0x219C, 0x219F},
- {0x21A0, 0x21A0}, {0x21A1, 0x21A2}, {0x21A3, 0x21A3},
- {0x21A4, 0x21A5}, {0x21A6, 0x21A6}, {0x21A7, 0x21AD},
- {0x21AE, 0x21AE}, {0x21AF, 0x21B7}, {0x21BA, 0x21CD},
- {0x21CE, 0x21CF}, {0x21D0, 0x21D1}, {0x21D3, 0x21D3},
- {0x21D5, 0x21E6}, {0x21E8, 0x21F3}, {0x21F4, 0x21FF},
- {0x2201, 0x2201}, {0x2204, 0x2206}, {0x2209, 0x220A},
- {0x220C, 0x220E}, {0x2210, 0x2210}, {0x2212, 0x2214},
- {0x2216, 0x2219}, {0x221B, 0x221C}, {0x2221, 0x2222},
- {0x2224, 0x2224}, {0x2226, 0x2226}, {0x222D, 0x222D},
- {0x222F, 0x2233}, {0x2238, 0x223B}, {0x223E, 0x2247},
- {0x2249, 0x224B}, {0x224D, 0x2251}, {0x2253, 0x225F},
- {0x2262, 0x2263}, {0x2268, 0x2269}, {0x226C, 0x226D},
- {0x2270, 0x2281}, {0x2284, 0x2285}, {0x2288, 0x2294},
- {0x2296, 0x2298}, {0x229A, 0x22A4}, {0x22A6, 0x22BE},
- {0x22C0, 0x22FF}, {0x2300, 0x2307}, {0x2308, 0x2308},
- {0x2309, 0x2309}, {0x230A, 0x230A}, {0x230B, 0x230B},
- {0x230C, 0x2311}, {0x2313, 0x2319}, {0x231C, 0x231F},
- {0x2320, 0x2321}, {0x2322, 0x2328}, {0x232B, 0x237B},
- {0x237C, 0x237C}, {0x237D, 0x239A}, {0x239B, 0x23B3},
- {0x23B4, 0x23DB}, {0x23DC, 0x23E1}, {0x23E2, 0x23E8},
- {0x23ED, 0x23EF}, {0x23F1, 0x23F2}, {0x23F4, 0x23FE},
- {0x2400, 0x2426}, {0x2440, 0x244A}, {0x24EA, 0x24EA},
- {0x254C, 0x254F}, {0x2574, 0x257F}, {0x2590, 0x2591},
- {0x2596, 0x259F}, {0x25A2, 0x25A2}, {0x25AA, 0x25B1},
- {0x25B4, 0x25B5}, {0x25B8, 0x25BB}, {0x25BE, 0x25BF},
- {0x25C2, 0x25C5}, {0x25C9, 0x25CA}, {0x25CC, 0x25CD},
- {0x25D2, 0x25E1}, {0x25E6, 0x25EE}, {0x25F0, 0x25F7},
- {0x25F8, 0x25FC}, {0x25FF, 0x25FF}, {0x2600, 0x2604},
- {0x2607, 0x2608}, {0x260A, 0x260D}, {0x2610, 0x2613},
- {0x2616, 0x261B}, {0x261D, 0x261D}, {0x261F, 0x263F},
- {0x2641, 0x2641}, {0x2643, 0x2647}, {0x2654, 0x265F},
- {0x2662, 0x2662}, {0x2666, 0x2666}, {0x266B, 0x266B},
- {0x266E, 0x266E}, {0x2670, 0x267E}, {0x2680, 0x2692},
- {0x2694, 0x269D}, {0x26A0, 0x26A0}, {0x26A2, 0x26A9},
- {0x26AC, 0x26BC}, {0x26C0, 0x26C3}, {0x26E2, 0x26E2},
- {0x26E4, 0x26E7}, {0x2700, 0x2704}, {0x2706, 0x2709},
- {0x270C, 0x2727}, {0x2729, 0x273C}, {0x273E, 0x274B},
- {0x274D, 0x274D}, {0x274F, 0x2752}, {0x2756, 0x2756},
- {0x2758, 0x2767}, {0x2768, 0x2768}, {0x2769, 0x2769},
- {0x276A, 0x276A}, {0x276B, 0x276B}, {0x276C, 0x276C},
- {0x276D, 0x276D}, {0x276E, 0x276E}, {0x276F, 0x276F},
- {0x2770, 0x2770}, {0x2771, 0x2771}, {0x2772, 0x2772},
- {0x2773, 0x2773}, {0x2774, 0x2774}, {0x2775, 0x2775},
- {0x2780, 0x2793}, {0x2794, 0x2794}, {0x2798, 0x27AF},
- {0x27B1, 0x27BE}, {0x27C0, 0x27C4}, {0x27C5, 0x27C5},
- {0x27C6, 0x27C6}, {0x27C7, 0x27E5}, {0x27EE, 0x27EE},
- {0x27EF, 0x27EF}, {0x27F0, 0x27FF}, {0x2800, 0x28FF},
- {0x2900, 0x297F}, {0x2980, 0x2982}, {0x2983, 0x2983},
- {0x2984, 0x2984}, {0x2987, 0x2987}, {0x2988, 0x2988},
- {0x2989, 0x2989}, {0x298A, 0x298A}, {0x298B, 0x298B},
- {0x298C, 0x298C}, {0x298D, 0x298D}, {0x298E, 0x298E},
- {0x298F, 0x298F}, {0x2990, 0x2990}, {0x2991, 0x2991},
- {0x2992, 0x2992}, {0x2993, 0x2993}, {0x2994, 0x2994},
- {0x2995, 0x2995}, {0x2996, 0x2996}, {0x2997, 0x2997},
- {0x2998, 0x2998}, {0x2999, 0x29D7}, {0x29D8, 0x29D8},
- {0x29D9, 0x29D9}, {0x29DA, 0x29DA}, {0x29DB, 0x29DB},
- {0x29DC, 0x29FB}, {0x29FC, 0x29FC}, {0x29FD, 0x29FD},
- {0x29FE, 0x29FF}, {0x2A00, 0x2AFF}, {0x2B00, 0x2B1A},
- {0x2B1D, 0x2B2F}, {0x2B30, 0x2B44}, {0x2B45, 0x2B46},
- {0x2B47, 0x2B4C}, {0x2B4D, 0x2B4F}, {0x2B51, 0x2B54},
- {0x2B5A, 0x2B73}, {0x2B76, 0x2B95}, {0x2B98, 0x2BB9},
- {0x2BBD, 0x2BC8}, {0x2BCA, 0x2BD1}, {0x2BEC, 0x2BEF},
- {0x2C00, 0x2C2E}, {0x2C30, 0x2C5E}, {0x2C60, 0x2C7B},
- {0x2C7C, 0x2C7D}, {0x2C7E, 0x2C7F}, {0x2C80, 0x2CE4},
- {0x2CE5, 0x2CEA}, {0x2CEB, 0x2CEE}, {0x2CEF, 0x2CF1},
- {0x2CF2, 0x2CF3}, {0x2CF9, 0x2CFC}, {0x2CFD, 0x2CFD},
- {0x2CFE, 0x2CFF}, {0x2D00, 0x2D25}, {0x2D27, 0x2D27},
- {0x2D2D, 0x2D2D}, {0x2D30, 0x2D67}, {0x2D6F, 0x2D6F},
- {0x2D70, 0x2D70}, {0x2D7F, 0x2D7F}, {0x2D80, 0x2D96},
- {0x2DA0, 0x2DA6}, {0x2DA8, 0x2DAE}, {0x2DB0, 0x2DB6},
- {0x2DB8, 0x2DBE}, {0x2DC0, 0x2DC6}, {0x2DC8, 0x2DCE},
- {0x2DD0, 0x2DD6}, {0x2DD8, 0x2DDE}, {0x2DE0, 0x2DFF},
- {0x2E00, 0x2E01}, {0x2E02, 0x2E02}, {0x2E03, 0x2E03},
- {0x2E04, 0x2E04}, {0x2E05, 0x2E05}, {0x2E06, 0x2E08},
- {0x2E09, 0x2E09}, {0x2E0A, 0x2E0A}, {0x2E0B, 0x2E0B},
- {0x2E0C, 0x2E0C}, {0x2E0D, 0x2E0D}, {0x2E0E, 0x2E16},
- {0x2E17, 0x2E17}, {0x2E18, 0x2E19}, {0x2E1A, 0x2E1A},
- {0x2E1B, 0x2E1B}, {0x2E1C, 0x2E1C}, {0x2E1D, 0x2E1D},
- {0x2E1E, 0x2E1F}, {0x2E20, 0x2E20}, {0x2E21, 0x2E21},
- {0x2E22, 0x2E22}, {0x2E23, 0x2E23}, {0x2E24, 0x2E24},
- {0x2E25, 0x2E25}, {0x2E26, 0x2E26}, {0x2E27, 0x2E27},
- {0x2E28, 0x2E28}, {0x2E29, 0x2E29}, {0x2E2A, 0x2E2E},
- {0x2E2F, 0x2E2F}, {0x2E30, 0x2E39}, {0x2E3A, 0x2E3B},
- {0x2E3C, 0x2E3F}, {0x2E40, 0x2E40}, {0x2E41, 0x2E41},
- {0x2E42, 0x2E42}, {0x2E43, 0x2E44}, {0x303F, 0x303F},
- {0x4DC0, 0x4DFF}, {0xA4D0, 0xA4F7}, {0xA4F8, 0xA4FD},
- {0xA4FE, 0xA4FF}, {0xA500, 0xA60B}, {0xA60C, 0xA60C},
- {0xA60D, 0xA60F}, {0xA610, 0xA61F}, {0xA620, 0xA629},
- {0xA62A, 0xA62B}, {0xA640, 0xA66D}, {0xA66E, 0xA66E},
- {0xA66F, 0xA66F}, {0xA670, 0xA672}, {0xA673, 0xA673},
- {0xA674, 0xA67D}, {0xA67E, 0xA67E}, {0xA67F, 0xA67F},
- {0xA680, 0xA69B}, {0xA69C, 0xA69D}, {0xA69E, 0xA69F},
- {0xA6A0, 0xA6E5}, {0xA6E6, 0xA6EF}, {0xA6F0, 0xA6F1},
- {0xA6F2, 0xA6F7}, {0xA700, 0xA716}, {0xA717, 0xA71F},
- {0xA720, 0xA721}, {0xA722, 0xA76F}, {0xA770, 0xA770},
- {0xA771, 0xA787}, {0xA788, 0xA788}, {0xA789, 0xA78A},
- {0xA78B, 0xA78E}, {0xA78F, 0xA78F}, {0xA790, 0xA7AE},
- {0xA7B0, 0xA7B7}, {0xA7F7, 0xA7F7}, {0xA7F8, 0xA7F9},
- {0xA7FA, 0xA7FA}, {0xA7FB, 0xA7FF}, {0xA800, 0xA801},
- {0xA802, 0xA802}, {0xA803, 0xA805}, {0xA806, 0xA806},
- {0xA807, 0xA80A}, {0xA80B, 0xA80B}, {0xA80C, 0xA822},
- {0xA823, 0xA824}, {0xA825, 0xA826}, {0xA827, 0xA827},
- {0xA828, 0xA82B}, {0xA830, 0xA835}, {0xA836, 0xA837},
- {0xA838, 0xA838}, {0xA839, 0xA839}, {0xA840, 0xA873},
- {0xA874, 0xA877}, {0xA880, 0xA881}, {0xA882, 0xA8B3},
- {0xA8B4, 0xA8C3}, {0xA8C4, 0xA8C5}, {0xA8CE, 0xA8CF},
- {0xA8D0, 0xA8D9}, {0xA8E0, 0xA8F1}, {0xA8F2, 0xA8F7},
- {0xA8F8, 0xA8FA}, {0xA8FB, 0xA8FB}, {0xA8FC, 0xA8FC},
- {0xA8FD, 0xA8FD}, {0xA900, 0xA909}, {0xA90A, 0xA925},
- {0xA926, 0xA92D}, {0xA92E, 0xA92F}, {0xA930, 0xA946},
- {0xA947, 0xA951}, {0xA952, 0xA953}, {0xA95F, 0xA95F},
- {0xA980, 0xA982}, {0xA983, 0xA983}, {0xA984, 0xA9B2},
- {0xA9B3, 0xA9B3}, {0xA9B4, 0xA9B5}, {0xA9B6, 0xA9B9},
- {0xA9BA, 0xA9BB}, {0xA9BC, 0xA9BC}, {0xA9BD, 0xA9C0},
- {0xA9C1, 0xA9CD}, {0xA9CF, 0xA9CF}, {0xA9D0, 0xA9D9},
- {0xA9DE, 0xA9DF}, {0xA9E0, 0xA9E4}, {0xA9E5, 0xA9E5},
- {0xA9E6, 0xA9E6}, {0xA9E7, 0xA9EF}, {0xA9F0, 0xA9F9},
- {0xA9FA, 0xA9FE}, {0xAA00, 0xAA28}, {0xAA29, 0xAA2E},
- {0xAA2F, 0xAA30}, {0xAA31, 0xAA32}, {0xAA33, 0xAA34},
- {0xAA35, 0xAA36}, {0xAA40, 0xAA42}, {0xAA43, 0xAA43},
- {0xAA44, 0xAA4B}, {0xAA4C, 0xAA4C}, {0xAA4D, 0xAA4D},
- {0xAA50, 0xAA59}, {0xAA5C, 0xAA5F}, {0xAA60, 0xAA6F},
- {0xAA70, 0xAA70}, {0xAA71, 0xAA76}, {0xAA77, 0xAA79},
- {0xAA7A, 0xAA7A}, {0xAA7B, 0xAA7B}, {0xAA7C, 0xAA7C},
- {0xAA7D, 0xAA7D}, {0xAA7E, 0xAA7F}, {0xAA80, 0xAAAF},
- {0xAAB0, 0xAAB0}, {0xAAB1, 0xAAB1}, {0xAAB2, 0xAAB4},
- {0xAAB5, 0xAAB6}, {0xAAB7, 0xAAB8}, {0xAAB9, 0xAABD},
- {0xAABE, 0xAABF}, {0xAAC0, 0xAAC0}, {0xAAC1, 0xAAC1},
- {0xAAC2, 0xAAC2}, {0xAADB, 0xAADC}, {0xAADD, 0xAADD},
- {0xAADE, 0xAADF}, {0xAAE0, 0xAAEA}, {0xAAEB, 0xAAEB},
- {0xAAEC, 0xAAED}, {0xAAEE, 0xAAEF}, {0xAAF0, 0xAAF1},
- {0xAAF2, 0xAAF2}, {0xAAF3, 0xAAF4}, {0xAAF5, 0xAAF5},
- {0xAAF6, 0xAAF6}, {0xAB01, 0xAB06}, {0xAB09, 0xAB0E},
- {0xAB11, 0xAB16}, {0xAB20, 0xAB26}, {0xAB28, 0xAB2E},
- {0xAB30, 0xAB5A}, {0xAB5B, 0xAB5B}, {0xAB5C, 0xAB5F},
- {0xAB60, 0xAB65}, {0xAB70, 0xABBF}, {0xABC0, 0xABE2},
- {0xABE3, 0xABE4}, {0xABE5, 0xABE5}, {0xABE6, 0xABE7},
- {0xABE8, 0xABE8}, {0xABE9, 0xABEA}, {0xABEB, 0xABEB},
- {0xABEC, 0xABEC}, {0xABED, 0xABED}, {0xABF0, 0xABF9},
- {0xD7B0, 0xD7C6}, {0xD7CB, 0xD7FB}, {0xD800, 0xDB7F},
- {0xDB80, 0xDBFF}, {0xDC00, 0xDFFF}, {0xFB00, 0xFB06},
- {0xFB13, 0xFB17}, {0xFB1D, 0xFB1D}, {0xFB1E, 0xFB1E},
- {0xFB1F, 0xFB28}, {0xFB29, 0xFB29}, {0xFB2A, 0xFB36},
- {0xFB38, 0xFB3C}, {0xFB3E, 0xFB3E}, {0xFB40, 0xFB41},
- {0xFB43, 0xFB44}, {0xFB46, 0xFB4F}, {0xFB50, 0xFBB1},
- {0xFBB2, 0xFBC1}, {0xFBD3, 0xFD3D}, {0xFD3E, 0xFD3E},
- {0xFD3F, 0xFD3F}, {0xFD50, 0xFD8F}, {0xFD92, 0xFDC7},
- {0xFDF0, 0xFDFB}, {0xFDFC, 0xFDFC}, {0xFDFD, 0xFDFD},
- {0xFE20, 0xFE2F}, {0xFE70, 0xFE74}, {0xFE76, 0xFEFC},
- {0xFEFF, 0xFEFF}, {0xFFF9, 0xFFFB}, {0xFFFC, 0xFFFC},
- {0x10000, 0x1000B}, {0x1000D, 0x10026}, {0x10028, 0x1003A},
- {0x1003C, 0x1003D}, {0x1003F, 0x1004D}, {0x10050, 0x1005D},
- {0x10080, 0x100FA}, {0x10100, 0x10102}, {0x10107, 0x10133},
- {0x10137, 0x1013F}, {0x10140, 0x10174}, {0x10175, 0x10178},
- {0x10179, 0x10189}, {0x1018A, 0x1018B}, {0x1018C, 0x1018E},
- {0x10190, 0x1019B}, {0x101A0, 0x101A0}, {0x101D0, 0x101FC},
- {0x101FD, 0x101FD}, {0x10280, 0x1029C}, {0x102A0, 0x102D0},
- {0x102E0, 0x102E0}, {0x102E1, 0x102FB}, {0x10300, 0x1031F},
- {0x10320, 0x10323}, {0x10330, 0x10340}, {0x10341, 0x10341},
- {0x10342, 0x10349}, {0x1034A, 0x1034A}, {0x10350, 0x10375},
- {0x10376, 0x1037A}, {0x10380, 0x1039D}, {0x1039F, 0x1039F},
- {0x103A0, 0x103C3}, {0x103C8, 0x103CF}, {0x103D0, 0x103D0},
- {0x103D1, 0x103D5}, {0x10400, 0x1044F}, {0x10450, 0x1047F},
- {0x10480, 0x1049D}, {0x104A0, 0x104A9}, {0x104B0, 0x104D3},
- {0x104D8, 0x104FB}, {0x10500, 0x10527}, {0x10530, 0x10563},
- {0x1056F, 0x1056F}, {0x10600, 0x10736}, {0x10740, 0x10755},
- {0x10760, 0x10767}, {0x10800, 0x10805}, {0x10808, 0x10808},
- {0x1080A, 0x10835}, {0x10837, 0x10838}, {0x1083C, 0x1083C},
- {0x1083F, 0x1083F}, {0x10840, 0x10855}, {0x10857, 0x10857},
- {0x10858, 0x1085F}, {0x10860, 0x10876}, {0x10877, 0x10878},
- {0x10879, 0x1087F}, {0x10880, 0x1089E}, {0x108A7, 0x108AF},
- {0x108E0, 0x108F2}, {0x108F4, 0x108F5}, {0x108FB, 0x108FF},
- {0x10900, 0x10915}, {0x10916, 0x1091B}, {0x1091F, 0x1091F},
- {0x10920, 0x10939}, {0x1093F, 0x1093F}, {0x10980, 0x1099F},
- {0x109A0, 0x109B7}, {0x109BC, 0x109BD}, {0x109BE, 0x109BF},
- {0x109C0, 0x109CF}, {0x109D2, 0x109FF}, {0x10A00, 0x10A00},
- {0x10A01, 0x10A03}, {0x10A05, 0x10A06}, {0x10A0C, 0x10A0F},
- {0x10A10, 0x10A13}, {0x10A15, 0x10A17}, {0x10A19, 0x10A33},
- {0x10A38, 0x10A3A}, {0x10A3F, 0x10A3F}, {0x10A40, 0x10A47},
- {0x10A50, 0x10A58}, {0x10A60, 0x10A7C}, {0x10A7D, 0x10A7E},
- {0x10A7F, 0x10A7F}, {0x10A80, 0x10A9C}, {0x10A9D, 0x10A9F},
- {0x10AC0, 0x10AC7}, {0x10AC8, 0x10AC8}, {0x10AC9, 0x10AE4},
- {0x10AE5, 0x10AE6}, {0x10AEB, 0x10AEF}, {0x10AF0, 0x10AF6},
- {0x10B00, 0x10B35}, {0x10B39, 0x10B3F}, {0x10B40, 0x10B55},
- {0x10B58, 0x10B5F}, {0x10B60, 0x10B72}, {0x10B78, 0x10B7F},
- {0x10B80, 0x10B91}, {0x10B99, 0x10B9C}, {0x10BA9, 0x10BAF},
- {0x10C00, 0x10C48}, {0x10C80, 0x10CB2}, {0x10CC0, 0x10CF2},
- {0x10CFA, 0x10CFF}, {0x10E60, 0x10E7E}, {0x11000, 0x11000},
- {0x11001, 0x11001}, {0x11002, 0x11002}, {0x11003, 0x11037},
- {0x11038, 0x11046}, {0x11047, 0x1104D}, {0x11052, 0x11065},
- {0x11066, 0x1106F}, {0x1107F, 0x1107F}, {0x11080, 0x11081},
- {0x11082, 0x11082}, {0x11083, 0x110AF}, {0x110B0, 0x110B2},
- {0x110B3, 0x110B6}, {0x110B7, 0x110B8}, {0x110B9, 0x110BA},
- {0x110BB, 0x110BC}, {0x110BD, 0x110BD}, {0x110BE, 0x110C1},
- {0x110D0, 0x110E8}, {0x110F0, 0x110F9}, {0x11100, 0x11102},
- {0x11103, 0x11126}, {0x11127, 0x1112B}, {0x1112C, 0x1112C},
- {0x1112D, 0x11134}, {0x11136, 0x1113F}, {0x11140, 0x11143},
- {0x11150, 0x11172}, {0x11173, 0x11173}, {0x11174, 0x11175},
- {0x11176, 0x11176}, {0x11180, 0x11181}, {0x11182, 0x11182},
- {0x11183, 0x111B2}, {0x111B3, 0x111B5}, {0x111B6, 0x111BE},
- {0x111BF, 0x111C0}, {0x111C1, 0x111C4}, {0x111C5, 0x111C9},
- {0x111CA, 0x111CC}, {0x111CD, 0x111CD}, {0x111D0, 0x111D9},
- {0x111DA, 0x111DA}, {0x111DB, 0x111DB}, {0x111DC, 0x111DC},
- {0x111DD, 0x111DF}, {0x111E1, 0x111F4}, {0x11200, 0x11211},
- {0x11213, 0x1122B}, {0x1122C, 0x1122E}, {0x1122F, 0x11231},
- {0x11232, 0x11233}, {0x11234, 0x11234}, {0x11235, 0x11235},
- {0x11236, 0x11237}, {0x11238, 0x1123D}, {0x1123E, 0x1123E},
- {0x11280, 0x11286}, {0x11288, 0x11288}, {0x1128A, 0x1128D},
- {0x1128F, 0x1129D}, {0x1129F, 0x112A8}, {0x112A9, 0x112A9},
- {0x112B0, 0x112DE}, {0x112DF, 0x112DF}, {0x112E0, 0x112E2},
- {0x112E3, 0x112EA}, {0x112F0, 0x112F9}, {0x11300, 0x11301},
- {0x11302, 0x11303}, {0x11305, 0x1130C}, {0x1130F, 0x11310},
- {0x11313, 0x11328}, {0x1132A, 0x11330}, {0x11332, 0x11333},
- {0x11335, 0x11339}, {0x1133C, 0x1133C}, {0x1133D, 0x1133D},
- {0x1133E, 0x1133F}, {0x11340, 0x11340}, {0x11341, 0x11344},
- {0x11347, 0x11348}, {0x1134B, 0x1134D}, {0x11350, 0x11350},
- {0x11357, 0x11357}, {0x1135D, 0x11361}, {0x11362, 0x11363},
- {0x11366, 0x1136C}, {0x11370, 0x11374}, {0x11400, 0x11434},
- {0x11435, 0x11437}, {0x11438, 0x1143F}, {0x11440, 0x11441},
- {0x11442, 0x11444}, {0x11445, 0x11445}, {0x11446, 0x11446},
- {0x11447, 0x1144A}, {0x1144B, 0x1144F}, {0x11450, 0x11459},
- {0x1145B, 0x1145B}, {0x1145D, 0x1145D}, {0x11480, 0x114AF},
- {0x114B0, 0x114B2}, {0x114B3, 0x114B8}, {0x114B9, 0x114B9},
- {0x114BA, 0x114BA}, {0x114BB, 0x114BE}, {0x114BF, 0x114C0},
- {0x114C1, 0x114C1}, {0x114C2, 0x114C3}, {0x114C4, 0x114C5},
- {0x114C6, 0x114C6}, {0x114C7, 0x114C7}, {0x114D0, 0x114D9},
- {0x11580, 0x115AE}, {0x115AF, 0x115B1}, {0x115B2, 0x115B5},
- {0x115B8, 0x115BB}, {0x115BC, 0x115BD}, {0x115BE, 0x115BE},
- {0x115BF, 0x115C0}, {0x115C1, 0x115D7}, {0x115D8, 0x115DB},
- {0x115DC, 0x115DD}, {0x11600, 0x1162F}, {0x11630, 0x11632},
- {0x11633, 0x1163A}, {0x1163B, 0x1163C}, {0x1163D, 0x1163D},
- {0x1163E, 0x1163E}, {0x1163F, 0x11640}, {0x11641, 0x11643},
- {0x11644, 0x11644}, {0x11650, 0x11659}, {0x11660, 0x1166C},
- {0x11680, 0x116AA}, {0x116AB, 0x116AB}, {0x116AC, 0x116AC},
- {0x116AD, 0x116AD}, {0x116AE, 0x116AF}, {0x116B0, 0x116B5},
- {0x116B6, 0x116B6}, {0x116B7, 0x116B7}, {0x116C0, 0x116C9},
- {0x11700, 0x11719}, {0x1171D, 0x1171F}, {0x11720, 0x11721},
- {0x11722, 0x11725}, {0x11726, 0x11726}, {0x11727, 0x1172B},
- {0x11730, 0x11739}, {0x1173A, 0x1173B}, {0x1173C, 0x1173E},
- {0x1173F, 0x1173F}, {0x118A0, 0x118DF}, {0x118E0, 0x118E9},
- {0x118EA, 0x118F2}, {0x118FF, 0x118FF}, {0x11AC0, 0x11AF8},
- {0x11C00, 0x11C08}, {0x11C0A, 0x11C2E}, {0x11C2F, 0x11C2F},
- {0x11C30, 0x11C36}, {0x11C38, 0x11C3D}, {0x11C3E, 0x11C3E},
- {0x11C3F, 0x11C3F}, {0x11C40, 0x11C40}, {0x11C41, 0x11C45},
- {0x11C50, 0x11C59}, {0x11C5A, 0x11C6C}, {0x11C70, 0x11C71},
- {0x11C72, 0x11C8F}, {0x11C92, 0x11CA7}, {0x11CA9, 0x11CA9},
- {0x11CAA, 0x11CB0}, {0x11CB1, 0x11CB1}, {0x11CB2, 0x11CB3},
- {0x11CB4, 0x11CB4}, {0x11CB5, 0x11CB6}, {0x12000, 0x12399},
- {0x12400, 0x1246E}, {0x12470, 0x12474}, {0x12480, 0x12543},
- {0x13000, 0x1342E}, {0x14400, 0x14646}, {0x16800, 0x16A38},
- {0x16A40, 0x16A5E}, {0x16A60, 0x16A69}, {0x16A6E, 0x16A6F},
- {0x16AD0, 0x16AED}, {0x16AF0, 0x16AF4}, {0x16AF5, 0x16AF5},
- {0x16B00, 0x16B2F}, {0x16B30, 0x16B36}, {0x16B37, 0x16B3B},
- {0x16B3C, 0x16B3F}, {0x16B40, 0x16B43}, {0x16B44, 0x16B44},
- {0x16B45, 0x16B45}, {0x16B50, 0x16B59}, {0x16B5B, 0x16B61},
- {0x16B63, 0x16B77}, {0x16B7D, 0x16B8F}, {0x16F00, 0x16F44},
- {0x16F50, 0x16F50}, {0x16F51, 0x16F7E}, {0x16F8F, 0x16F92},
- {0x16F93, 0x16F9F}, {0x1BC00, 0x1BC6A}, {0x1BC70, 0x1BC7C},
- {0x1BC80, 0x1BC88}, {0x1BC90, 0x1BC99}, {0x1BC9C, 0x1BC9C},
- {0x1BC9D, 0x1BC9E}, {0x1BC9F, 0x1BC9F}, {0x1BCA0, 0x1BCA3},
- {0x1D000, 0x1D0F5}, {0x1D100, 0x1D126}, {0x1D129, 0x1D164},
- {0x1D165, 0x1D166}, {0x1D167, 0x1D169}, {0x1D16A, 0x1D16C},
- {0x1D16D, 0x1D172}, {0x1D173, 0x1D17A}, {0x1D17B, 0x1D182},
- {0x1D183, 0x1D184}, {0x1D185, 0x1D18B}, {0x1D18C, 0x1D1A9},
- {0x1D1AA, 0x1D1AD}, {0x1D1AE, 0x1D1E8}, {0x1D200, 0x1D241},
- {0x1D242, 0x1D244}, {0x1D245, 0x1D245}, {0x1D300, 0x1D356},
- {0x1D360, 0x1D371}, {0x1D400, 0x1D454}, {0x1D456, 0x1D49C},
- {0x1D49E, 0x1D49F}, {0x1D4A2, 0x1D4A2}, {0x1D4A5, 0x1D4A6},
- {0x1D4A9, 0x1D4AC}, {0x1D4AE, 0x1D4B9}, {0x1D4BB, 0x1D4BB},
- {0x1D4BD, 0x1D4C3}, {0x1D4C5, 0x1D505}, {0x1D507, 0x1D50A},
- {0x1D50D, 0x1D514}, {0x1D516, 0x1D51C}, {0x1D51E, 0x1D539},
- {0x1D53B, 0x1D53E}, {0x1D540, 0x1D544}, {0x1D546, 0x1D546},
- {0x1D54A, 0x1D550}, {0x1D552, 0x1D6A5}, {0x1D6A8, 0x1D6C0},
- {0x1D6C1, 0x1D6C1}, {0x1D6C2, 0x1D6DA}, {0x1D6DB, 0x1D6DB},
- {0x1D6DC, 0x1D6FA}, {0x1D6FB, 0x1D6FB}, {0x1D6FC, 0x1D714},
- {0x1D715, 0x1D715}, {0x1D716, 0x1D734}, {0x1D735, 0x1D735},
- {0x1D736, 0x1D74E}, {0x1D74F, 0x1D74F}, {0x1D750, 0x1D76E},
- {0x1D76F, 0x1D76F}, {0x1D770, 0x1D788}, {0x1D789, 0x1D789},
- {0x1D78A, 0x1D7A8}, {0x1D7A9, 0x1D7A9}, {0x1D7AA, 0x1D7C2},
- {0x1D7C3, 0x1D7C3}, {0x1D7C4, 0x1D7CB}, {0x1D7CE, 0x1D7FF},
- {0x1D800, 0x1D9FF}, {0x1DA00, 0x1DA36}, {0x1DA37, 0x1DA3A},
- {0x1DA3B, 0x1DA6C}, {0x1DA6D, 0x1DA74}, {0x1DA75, 0x1DA75},
- {0x1DA76, 0x1DA83}, {0x1DA84, 0x1DA84}, {0x1DA85, 0x1DA86},
- {0x1DA87, 0x1DA8B}, {0x1DA9B, 0x1DA9F}, {0x1DAA1, 0x1DAAF},
- {0x1E000, 0x1E006}, {0x1E008, 0x1E018}, {0x1E01B, 0x1E021},
- {0x1E023, 0x1E024}, {0x1E026, 0x1E02A}, {0x1E800, 0x1E8C4},
- {0x1E8C7, 0x1E8CF}, {0x1E8D0, 0x1E8D6}, {0x1E900, 0x1E943},
- {0x1E944, 0x1E94A}, {0x1E950, 0x1E959}, {0x1E95E, 0x1E95F},
- {0x1EE00, 0x1EE03}, {0x1EE05, 0x1EE1F}, {0x1EE21, 0x1EE22},
- {0x1EE24, 0x1EE24}, {0x1EE27, 0x1EE27}, {0x1EE29, 0x1EE32},
- {0x1EE34, 0x1EE37}, {0x1EE39, 0x1EE39}, {0x1EE3B, 0x1EE3B},
- {0x1EE42, 0x1EE42}, {0x1EE47, 0x1EE47}, {0x1EE49, 0x1EE49},
- {0x1EE4B, 0x1EE4B}, {0x1EE4D, 0x1EE4F}, {0x1EE51, 0x1EE52},
- {0x1EE54, 0x1EE54}, {0x1EE57, 0x1EE57}, {0x1EE59, 0x1EE59},
- {0x1EE5B, 0x1EE5B}, {0x1EE5D, 0x1EE5D}, {0x1EE5F, 0x1EE5F},
- {0x1EE61, 0x1EE62}, {0x1EE64, 0x1EE64}, {0x1EE67, 0x1EE6A},
- {0x1EE6C, 0x1EE72}, {0x1EE74, 0x1EE77}, {0x1EE79, 0x1EE7C},
- {0x1EE7E, 0x1EE7E}, {0x1EE80, 0x1EE89}, {0x1EE8B, 0x1EE9B},
- {0x1EEA1, 0x1EEA3}, {0x1EEA5, 0x1EEA9}, {0x1EEAB, 0x1EEBB},
- {0x1EEF0, 0x1EEF1}, {0x1F000, 0x1F003}, {0x1F005, 0x1F02B},
- {0x1F030, 0x1F093}, {0x1F0A0, 0x1F0AE}, {0x1F0B1, 0x1F0BF},
- {0x1F0C1, 0x1F0CE}, {0x1F0D1, 0x1F0F5}, {0x1F10B, 0x1F10C},
- {0x1F12E, 0x1F12E}, {0x1F16A, 0x1F16B}, {0x1F1E6, 0x1F1FF},
- {0x1F321, 0x1F32C}, {0x1F336, 0x1F336}, {0x1F37D, 0x1F37D},
- {0x1F394, 0x1F39F}, {0x1F3CB, 0x1F3CE}, {0x1F3D4, 0x1F3DF},
- {0x1F3F1, 0x1F3F3}, {0x1F3F5, 0x1F3F7}, {0x1F43F, 0x1F43F},
- {0x1F441, 0x1F441}, {0x1F4FD, 0x1F4FE}, {0x1F53E, 0x1F54A},
- {0x1F54F, 0x1F54F}, {0x1F568, 0x1F579}, {0x1F57B, 0x1F594},
- {0x1F597, 0x1F5A3}, {0x1F5A5, 0x1F5FA}, {0x1F650, 0x1F67F},
- {0x1F6C6, 0x1F6CB}, {0x1F6CD, 0x1F6CF}, {0x1F6E0, 0x1F6EA},
- {0x1F6F0, 0x1F6F3}, {0x1F700, 0x1F773}, {0x1F780, 0x1F7D4},
- {0x1F800, 0x1F80B}, {0x1F810, 0x1F847}, {0x1F850, 0x1F859},
- {0x1F860, 0x1F887}, {0x1F890, 0x1F8AD}, {0xE0001, 0xE0001},
- {0xE0020, 0xE007F},
-}
-
-// Condition have flag EastAsianWidth whether the current locale is CJK or not.
-type Condition struct {
- EastAsianWidth bool
-}
-
-// NewCondition return new instance of Condition which is current locale.
-func NewCondition() *Condition {
- return &Condition{EastAsianWidth}
-}
-
-// RuneWidth returns the number of cells in r.
-// See http://www.unicode.org/reports/tr11/
-func (c *Condition) RuneWidth(r rune) int {
- switch {
- case r < 0 || r > 0x10FFFF ||
- inTables(r, nonprint, combining, notassigned):
- return 0
- case (c.EastAsianWidth && IsAmbiguousWidth(r)) ||
- inTables(r, doublewidth, emoji):
- return 2
- default:
- return 1
- }
-}
-
-// StringWidth return width as you can see
-func (c *Condition) StringWidth(s string) (width int) {
- for _, r := range []rune(s) {
- width += c.RuneWidth(r)
- }
- return width
-}
-
-// Truncate return string truncated with w cells
-func (c *Condition) Truncate(s string, w int, tail string) string {
- if c.StringWidth(s) <= w {
- return s
- }
- r := []rune(s)
- tw := c.StringWidth(tail)
- w -= tw
- width := 0
- i := 0
- for ; i < len(r); i++ {
- cw := c.RuneWidth(r[i])
- if width+cw > w {
- break
- }
- width += cw
- }
- return string(r[0:i]) + tail
-}
-
-// Wrap return string wrapped with w cells
-func (c *Condition) Wrap(s string, w int) string {
- width := 0
- out := ""
- for _, r := range []rune(s) {
- cw := RuneWidth(r)
- if r == '\n' {
- out += string(r)
- width = 0
- continue
- } else if width+cw > w {
- out += "\n"
- width = 0
- out += string(r)
- width += cw
- continue
- }
- out += string(r)
- width += cw
- }
- return out
-}
-
-// FillLeft return string filled in left by spaces in w cells
-func (c *Condition) FillLeft(s string, w int) string {
- width := c.StringWidth(s)
- count := w - width
- if count > 0 {
- b := make([]byte, count)
- for i := range b {
- b[i] = ' '
- }
- return string(b) + s
- }
- return s
-}
-
-// FillRight return string filled in left by spaces in w cells
-func (c *Condition) FillRight(s string, w int) string {
- width := c.StringWidth(s)
- count := w - width
- if count > 0 {
- b := make([]byte, count)
- for i := range b {
- b[i] = ' '
- }
- return s + string(b)
- }
- return s
-}
-
-// RuneWidth returns the number of cells in r.
-// See http://www.unicode.org/reports/tr11/
-func RuneWidth(r rune) int {
- return DefaultCondition.RuneWidth(r)
-}
-
-// IsAmbiguousWidth returns whether is ambiguous width or not.
-func IsAmbiguousWidth(r rune) bool {
- return inTables(r, private, ambiguous)
-}
-
-// IsNeutralWidth returns whether is neutral width or not.
-func IsNeutralWidth(r rune) bool {
- return inTable(r, neutral)
-}
-
-// StringWidth return width as you can see
-func StringWidth(s string) (width int) {
- return DefaultCondition.StringWidth(s)
-}
-
-// Truncate return string truncated with w cells
-func Truncate(s string, w int, tail string) string {
- return DefaultCondition.Truncate(s, w, tail)
-}
-
-// Wrap return string wrapped with w cells
-func Wrap(s string, w int) string {
- return DefaultCondition.Wrap(s, w)
-}
-
-// FillLeft return string filled in left by spaces in w cells
-func FillLeft(s string, w int) string {
- return DefaultCondition.FillLeft(s, w)
-}
-
-// FillRight return string filled in left by spaces in w cells
-func FillRight(s string, w int) string {
- return DefaultCondition.FillRight(s, w)
-}
diff --git a/vendor/github.com/mattn/go-runewidth/runewidth_js.go b/vendor/github.com/mattn/go-runewidth/runewidth_js.go
deleted file mode 100644
index 0ce32c5..0000000
--- a/vendor/github.com/mattn/go-runewidth/runewidth_js.go
+++ /dev/null
@@ -1,8 +0,0 @@
-// +build js
-
-package runewidth
-
-func IsEastAsian() bool {
- // TODO: Implement this for the web. Detect east asian in a compatible way, and return true.
- return false
-}
diff --git a/vendor/github.com/mattn/go-runewidth/runewidth_posix.go b/vendor/github.com/mattn/go-runewidth/runewidth_posix.go
deleted file mode 100644
index c579e9a..0000000
--- a/vendor/github.com/mattn/go-runewidth/runewidth_posix.go
+++ /dev/null
@@ -1,77 +0,0 @@
-// +build !windows,!js
-
-package runewidth
-
-import (
- "os"
- "regexp"
- "strings"
-)
-
-var reLoc = regexp.MustCompile(`^[a-z][a-z][a-z]?(?:_[A-Z][A-Z])?\.(.+)`)
-
-var mblenTable = map[string]int{
- "utf-8": 6,
- "utf8": 6,
- "jis": 8,
- "eucjp": 3,
- "euckr": 2,
- "euccn": 2,
- "sjis": 2,
- "cp932": 2,
- "cp51932": 2,
- "cp936": 2,
- "cp949": 2,
- "cp950": 2,
- "big5": 2,
- "gbk": 2,
- "gb2312": 2,
-}
-
-func isEastAsian(locale string) bool {
- charset := strings.ToLower(locale)
- r := reLoc.FindStringSubmatch(locale)
- if len(r) == 2 {
- charset = strings.ToLower(r[1])
- }
-
- if strings.HasSuffix(charset, "@cjk_narrow") {
- return false
- }
-
- for pos, b := range []byte(charset) {
- if b == '@' {
- charset = charset[:pos]
- break
- }
- }
- max := 1
- if m, ok := mblenTable[charset]; ok {
- max = m
- }
- if max > 1 && (charset[0] != 'u' ||
- strings.HasPrefix(locale, "ja") ||
- strings.HasPrefix(locale, "ko") ||
- strings.HasPrefix(locale, "zh")) {
- return true
- }
- return false
-}
-
-// IsEastAsian return true if the current locale is CJK
-func IsEastAsian() bool {
- locale := os.Getenv("LC_CTYPE")
- if locale == "" {
- locale = os.Getenv("LANG")
- }
-
- // ignore C locale
- if locale == "POSIX" || locale == "C" {
- return false
- }
- if len(locale) > 1 && locale[0] == 'C' && (locale[1] == '.' || locale[1] == '-') {
- return false
- }
-
- return isEastAsian(locale)
-}
diff --git a/vendor/github.com/mattn/go-runewidth/runewidth_test.go b/vendor/github.com/mattn/go-runewidth/runewidth_test.go
deleted file mode 100644
index b0378a1..0000000
--- a/vendor/github.com/mattn/go-runewidth/runewidth_test.go
+++ /dev/null
@@ -1,275 +0,0 @@
-package runewidth
-
-import (
- "sort"
- "testing"
-)
-
-var _ sort.Interface = (*table)(nil)
-
-func (t table) Len() int {
- return len(t)
-}
-
-func (t table) Less(i, j int) bool {
- return t[i].first < t[j].first
-}
-
-func (t *table) Swap(i, j int) {
- (*t)[i], (*t)[j] = (*t)[j], (*t)[i]
-}
-
-var tables = []table{
- private,
- nonprint,
- combining,
- doublewidth,
- ambiguous,
- emoji,
- notassigned,
- neutral,
-}
-
-func TestSorted(t *testing.T) {
- for _, tbl := range tables {
- if !sort.IsSorted(&tbl) {
- t.Errorf("not sorted")
- }
- }
-}
-
-var runewidthtests = []struct {
- in rune
- out int
- eaout int
-}{
- {'世', 2, 2},
- {'界', 2, 2},
- {'セ', 1, 1},
- {'カ', 1, 1},
- {'イ', 1, 1},
- {'☆', 1, 2}, // double width in ambiguous
- {'\x00', 0, 0},
- {'\x01', 0, 0},
- {'\u0300', 0, 0},
-}
-
-func TestRuneWidth(t *testing.T) {
- c := NewCondition()
- for _, tt := range runewidthtests {
- if out := c.RuneWidth(tt.in); out != tt.out {
- t.Errorf("RuneWidth(%q) = %d, want %d", tt.in, out, tt.out)
- }
- }
- c.EastAsianWidth = true
- for _, tt := range runewidthtests {
- if out := c.RuneWidth(tt.in); out != tt.eaout {
- t.Errorf("RuneWidth(%q) = %d, want %d", tt.in, out, tt.eaout)
- }
- }
-}
-
-var isambiguouswidthtests = []struct {
- in rune
- out bool
-}{
- {'世', false},
- {'■', true},
- {'界', false},
- {'○', true},
- {'㈱', false},
- {'①', true},
- {'②', true},
- {'③', true},
- {'④', true},
- {'⑤', true},
- {'⑥', true},
- {'⑦', true},
- {'⑧', true},
- {'⑨', true},
- {'⑩', true},
- {'⑪', true},
- {'⑫', true},
- {'⑬', true},
- {'⑭', true},
- {'⑮', true},
- {'⑯', true},
- {'⑰', true},
- {'⑱', true},
- {'⑲', true},
- {'⑳', true},
- {'☆', true},
-}
-
-func TestIsAmbiguousWidth(t *testing.T) {
- for _, tt := range isambiguouswidthtests {
- if out := IsAmbiguousWidth(tt.in); out != tt.out {
- t.Errorf("IsAmbiguousWidth(%q) = %v, want %v", tt.in, out, tt.out)
- }
- }
-}
-
-var stringwidthtests = []struct {
- in string
- out int
- eaout int
-}{
- {"■㈱の世界①", 10, 12},
- {"スター☆", 7, 8},
- {"つのだ☆HIRO", 11, 12},
-}
-
-func TestStringWidth(t *testing.T) {
- c := NewCondition()
- for _, tt := range stringwidthtests {
- if out := c.StringWidth(tt.in); out != tt.out {
- t.Errorf("StringWidth(%q) = %q, want %q", tt.in, out, tt.out)
- }
- }
- c.EastAsianWidth = true
- for _, tt := range stringwidthtests {
- if out := c.StringWidth(tt.in); out != tt.eaout {
- t.Errorf("StringWidth(%q) = %q, want %q", tt.in, out, tt.eaout)
- }
- }
-}
-
-func TestStringWidthInvalid(t *testing.T) {
- s := "こんにちわ\x00世界"
- if out := StringWidth(s); out != 14 {
- t.Errorf("StringWidth(%q) = %q, want %q", s, out, 14)
- }
-}
-
-func TestTruncateSmaller(t *testing.T) {
- s := "あいうえお"
- expected := "あいうえお"
-
- if out := Truncate(s, 10, "..."); out != expected {
- t.Errorf("Truncate(%q) = %q, want %q", s, out, expected)
- }
-}
-
-func TestTruncate(t *testing.T) {
- s := "あいうえおあいうえおえおおおおおおおおおおおおおおおおおおおおおおおおおおおおおお"
- expected := "あいうえおあいうえおえおおおおおおおおおおおおおおおおおおおおおおおおおおお..."
- out := Truncate(s, 80, "...")
- if out != expected {
- t.Errorf("Truncate(%q) = %q, want %q", s, out, expected)
- }
- width := StringWidth(out)
- if width != 79 {
- t.Errorf("width of Truncate(%q) should be %d, but %d", s, 79, width)
- }
-}
-
-func TestTruncateFit(t *testing.T) {
- s := "aあいうえおあいうえおえおおおおおおおおおおおおおおおおおおおおおおおおおおおおおお"
- expected := "aあいうえおあいうえおえおおおおおおおおおおおおおおおおおおおおおおおおおおお..."
-
- out := Truncate(s, 80, "...")
- if out != expected {
- t.Errorf("Truncate(%q) = %q, want %q", s, out, expected)
- }
- width := StringWidth(out)
- if width != 80 {
- t.Errorf("width of Truncate(%q) should be %d, but %d", s, 80, width)
- }
-}
-
-func TestTruncateJustFit(t *testing.T) {
- s := "あいうえおあいうえおえおおおおおおおおおおおおおおおおおおおおおおおおおおおおお"
- expected := "あいうえおあいうえおえおおおおおおおおおおおおおおおおおおおおおおおおおおおおお"
-
- out := Truncate(s, 80, "...")
- if out != expected {
- t.Errorf("Truncate(%q) = %q, want %q", s, out, expected)
- }
- width := StringWidth(out)
- if width != 80 {
- t.Errorf("width of Truncate(%q) should be %d, but %d", s, 80, width)
- }
-}
-
-func TestWrap(t *testing.T) {
- s := `東京特許許可局局長はよく柿喰う客だ/東京特許許可局局長はよく柿喰う客だ
-123456789012345678901234567890
-
-END`
- expected := `東京特許許可局局長はよく柿喰う
-客だ/東京特許許可局局長はよく
-柿喰う客だ
-123456789012345678901234567890
-
-END`
-
- if out := Wrap(s, 30); out != expected {
- t.Errorf("Wrap(%q) = %q, want %q", s, out, expected)
- }
-}
-
-func TestTruncateNoNeeded(t *testing.T) {
- s := "あいうえおあい"
- expected := "あいうえおあい"
-
- if out := Truncate(s, 80, "..."); out != expected {
- t.Errorf("Truncate(%q) = %q, want %q", s, out, expected)
- }
-}
-
-var isneutralwidthtests = []struct {
- in rune
- out bool
-}{
- {'→', false},
- {'┊', false},
- {'┈', false},
- {'~', false},
- {'└', false},
- {'⣀', true},
- {'⣀', true},
-}
-
-func TestIsNeutralWidth(t *testing.T) {
- for _, tt := range isneutralwidthtests {
- if out := IsNeutralWidth(tt.in); out != tt.out {
- t.Errorf("IsNeutralWidth(%q) = %v, want %v", tt.in, out, tt.out)
- }
- }
-}
-
-func TestFillLeft(t *testing.T) {
- s := "あxいうえお"
- expected := " あxいうえお"
-
- if out := FillLeft(s, 15); out != expected {
- t.Errorf("FillLeft(%q) = %q, want %q", s, out, expected)
- }
-}
-
-func TestFillLeftFit(t *testing.T) {
- s := "あいうえお"
- expected := "あいうえお"
-
- if out := FillLeft(s, 10); out != expected {
- t.Errorf("FillLeft(%q) = %q, want %q", s, out, expected)
- }
-}
-
-func TestFillRight(t *testing.T) {
- s := "あxいうえお"
- expected := "あxいうえお "
-
- if out := FillRight(s, 15); out != expected {
- t.Errorf("FillRight(%q) = %q, want %q", s, out, expected)
- }
-}
-
-func TestFillRightFit(t *testing.T) {
- s := "あいうえお"
- expected := "あいうえお"
-
- if out := FillRight(s, 10); out != expected {
- t.Errorf("FillRight(%q) = %q, want %q", s, out, expected)
- }
-}
diff --git a/vendor/github.com/mattn/go-runewidth/runewidth_windows.go b/vendor/github.com/mattn/go-runewidth/runewidth_windows.go
deleted file mode 100644
index 0258876..0000000
--- a/vendor/github.com/mattn/go-runewidth/runewidth_windows.go
+++ /dev/null
@@ -1,25 +0,0 @@
-package runewidth
-
-import (
- "syscall"
-)
-
-var (
- kernel32 = syscall.NewLazyDLL("kernel32")
- procGetConsoleOutputCP = kernel32.NewProc("GetConsoleOutputCP")
-)
-
-// IsEastAsian return true if the current locale is CJK
-func IsEastAsian() bool {
- r1, _, _ := procGetConsoleOutputCP.Call()
- if r1 == 0 {
- return false
- }
-
- switch int(r1) {
- case 932, 51932, 936, 949, 950:
- return true
- }
-
- return false
-}
diff --git a/vendor/github.com/mitchellh/go-homedir/LICENSE b/vendor/github.com/mitchellh/go-homedir/LICENSE
deleted file mode 100644
index f9c841a..0000000
--- a/vendor/github.com/mitchellh/go-homedir/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2013 Mitchell Hashimoto
-
-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.
diff --git a/vendor/github.com/mitchellh/go-homedir/README.md b/vendor/github.com/mitchellh/go-homedir/README.md
deleted file mode 100644
index d70706d..0000000
--- a/vendor/github.com/mitchellh/go-homedir/README.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# go-homedir
-
-This is a Go library for detecting the user's home directory without
-the use of cgo, so the library can be used in cross-compilation environments.
-
-Usage is incredibly simple, just call `homedir.Dir()` to get the home directory
-for a user, and `homedir.Expand()` to expand the `~` in a path to the home
-directory.
-
-**Why not just use `os/user`?** The built-in `os/user` package requires
-cgo on Darwin systems. This means that any Go code that uses that package
-cannot cross compile. But 99% of the time the use for `os/user` is just to
-retrieve the home directory, which we can do for the current user without
-cgo. This library does that, enabling cross-compilation.
diff --git a/vendor/github.com/mitchellh/go-homedir/homedir.go b/vendor/github.com/mitchellh/go-homedir/homedir.go
deleted file mode 100644
index 47e1f9e..0000000
--- a/vendor/github.com/mitchellh/go-homedir/homedir.go
+++ /dev/null
@@ -1,137 +0,0 @@
-package homedir
-
-import (
- "bytes"
- "errors"
- "os"
- "os/exec"
- "path/filepath"
- "runtime"
- "strconv"
- "strings"
- "sync"
-)
-
-// DisableCache will disable caching of the home directory. Caching is enabled
-// by default.
-var DisableCache bool
-
-var homedirCache string
-var cacheLock sync.RWMutex
-
-// Dir returns the home directory for the executing user.
-//
-// This uses an OS-specific method for discovering the home directory.
-// An error is returned if a home directory cannot be detected.
-func Dir() (string, error) {
- if !DisableCache {
- cacheLock.RLock()
- cached := homedirCache
- cacheLock.RUnlock()
- if cached != "" {
- return cached, nil
- }
- }
-
- cacheLock.Lock()
- defer cacheLock.Unlock()
-
- var result string
- var err error
- if runtime.GOOS == "windows" {
- result, err = dirWindows()
- } else {
- // Unix-like system, so just assume Unix
- result, err = dirUnix()
- }
-
- if err != nil {
- return "", err
- }
- homedirCache = result
- return result, nil
-}
-
-// Expand expands the path to include the home directory if the path
-// is prefixed with `~`. If it isn't prefixed with `~`, the path is
-// returned as-is.
-func Expand(path string) (string, error) {
- if len(path) == 0 {
- return path, nil
- }
-
- if path[0] != '~' {
- return path, nil
- }
-
- if len(path) > 1 && path[1] != '/' && path[1] != '\\' {
- return "", errors.New("cannot expand user-specific home dir")
- }
-
- dir, err := Dir()
- if err != nil {
- return "", err
- }
-
- return filepath.Join(dir, path[1:]), nil
-}
-
-func dirUnix() (string, error) {
- // First prefer the HOME environmental variable
- if home := os.Getenv("HOME"); home != "" {
- return home, nil
- }
-
- // If that fails, try getent
- var stdout bytes.Buffer
- cmd := exec.Command("getent", "passwd", strconv.Itoa(os.Getuid()))
- cmd.Stdout = &stdout
- if err := cmd.Run(); err != nil {
- // If the error is ErrNotFound, we ignore it. Otherwise, return it.
- if err != exec.ErrNotFound {
- return "", err
- }
- } else {
- if passwd := strings.TrimSpace(stdout.String()); passwd != "" {
- // username:password:uid:gid:gecos:home:shell
- passwdParts := strings.SplitN(passwd, ":", 7)
- if len(passwdParts) > 5 {
- return passwdParts[5], nil
- }
- }
- }
-
- // If all else fails, try the shell
- stdout.Reset()
- cmd = exec.Command("sh", "-c", "cd && pwd")
- cmd.Stdout = &stdout
- if err := cmd.Run(); err != nil {
- return "", err
- }
-
- result := strings.TrimSpace(stdout.String())
- if result == "" {
- return "", errors.New("blank output when reading home directory")
- }
-
- return result, nil
-}
-
-func dirWindows() (string, error) {
- // First prefer the HOME environmental variable
- if home := os.Getenv("HOME"); home != "" {
- return home, nil
- }
-
- drive := os.Getenv("HOMEDRIVE")
- path := os.Getenv("HOMEPATH")
- home := drive + path
- if drive == "" || path == "" {
- home = os.Getenv("USERPROFILE")
- }
- if home == "" {
- return "", errors.New("HOMEDRIVE, HOMEPATH, and USERPROFILE are blank")
- }
-
- return home, nil
-}
diff --git a/vendor/github.com/mitchellh/go-homedir/homedir_test.go b/vendor/github.com/mitchellh/go-homedir/homedir_test.go
deleted file mode 100644
index e4054e7..0000000
--- a/vendor/github.com/mitchellh/go-homedir/homedir_test.go
+++ /dev/null
@@ -1,112 +0,0 @@
-package homedir
-
-import (
- "os"
- "os/user"
- "path/filepath"
- "testing"
-)
-
-func patchEnv(key, value string) func() {
- bck := os.Getenv(key)
- deferFunc := func() {
- os.Setenv(key, bck)
- }
-
- os.Setenv(key, value)
- return deferFunc
-}
-
-func BenchmarkDir(b *testing.B) {
- // We do this for any "warmups"
- for i := 0; i < 10; i++ {
- Dir()
- }
-
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- Dir()
- }
-}
-
-func TestDir(t *testing.T) {
- u, err := user.Current()
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- dir, err := Dir()
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- if u.HomeDir != dir {
- t.Fatalf("%#v != %#v", u.HomeDir, dir)
- }
-}
-
-func TestExpand(t *testing.T) {
- u, err := user.Current()
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- cases := []struct {
- Input string
- Output string
- Err bool
- }{
- {
- "/foo",
- "/foo",
- false,
- },
-
- {
- "~/foo",
- filepath.Join(u.HomeDir, "foo"),
- false,
- },
-
- {
- "",
- "",
- false,
- },
-
- {
- "~",
- u.HomeDir,
- false,
- },
-
- {
- "~foo/foo",
- "",
- true,
- },
- }
-
- for _, tc := range cases {
- actual, err := Expand(tc.Input)
- if (err != nil) != tc.Err {
- t.Fatalf("Input: %#v\n\nErr: %s", tc.Input, err)
- }
-
- if actual != tc.Output {
- t.Fatalf("Input: %#v\n\nOutput: %#v", tc.Input, actual)
- }
- }
-
- DisableCache = true
- defer func() { DisableCache = false }()
- defer patchEnv("HOME", "/custom/path/")()
- expected := filepath.Join("/", "custom", "path", "foo/bar")
- actual, err := Expand("~/foo/bar")
-
- if err != nil {
- t.Errorf("No error is expected, got: %v", err)
- } else if actual != expected {
- t.Errorf("Expected: %v; actual: %v", expected, actual)
- }
-}
diff --git a/vendor/github.com/mitchellh/mapstructure/.travis.yml b/vendor/github.com/mitchellh/mapstructure/.travis.yml
deleted file mode 100644
index 5c14c13..0000000
--- a/vendor/github.com/mitchellh/mapstructure/.travis.yml
+++ /dev/null
@@ -1,7 +0,0 @@
-language: go
-
-go:
- - 1.8.1
-
-script:
- - go test
diff --git a/vendor/github.com/mitchellh/mapstructure/LICENSE b/vendor/github.com/mitchellh/mapstructure/LICENSE
deleted file mode 100644
index f9c841a..0000000
--- a/vendor/github.com/mitchellh/mapstructure/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2013 Mitchell Hashimoto
-
-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.
diff --git a/vendor/github.com/mitchellh/mapstructure/README.md b/vendor/github.com/mitchellh/mapstructure/README.md
deleted file mode 100644
index 659d688..0000000
--- a/vendor/github.com/mitchellh/mapstructure/README.md
+++ /dev/null
@@ -1,46 +0,0 @@
-# mapstructure
-
-mapstructure is a Go library for decoding generic map values to structures
-and vice versa, while providing helpful error handling.
-
-This library is most useful when decoding values from some data stream (JSON,
-Gob, etc.) where you don't _quite_ know the structure of the underlying data
-until you read a part of it. You can therefore read a `map[string]interface{}`
-and use this library to decode it into the proper underlying native Go
-structure.
-
-## Installation
-
-Standard `go get`:
-
-```
-$ go get github.com/mitchellh/mapstructure
-```
-
-## Usage & Example
-
-For usage and examples see the [Godoc](http://godoc.org/github.com/mitchellh/mapstructure).
-
-The `Decode` function has examples associated with it there.
-
-## But Why?!
-
-Go offers fantastic standard libraries for decoding formats such as JSON.
-The standard method is to have a struct pre-created, and populate that struct
-from the bytes of the encoded format. This is great, but the problem is if
-you have configuration or an encoding that changes slightly depending on
-specific fields. For example, consider this JSON:
-
-```json
-{
- "type": "person",
- "name": "Mitchell"
-}
-```
-
-Perhaps we can't populate a specific structure without first reading
-the "type" field from the JSON. We could always do two passes over the
-decoding of the JSON (reading the "type" first, and the rest later).
-However, it is much simpler to just decode this into a `map[string]interface{}`
-structure, read the "type" key, then use something like this library
-to decode it into the proper structure.
diff --git a/vendor/github.com/mitchellh/mapstructure/decode_hooks.go b/vendor/github.com/mitchellh/mapstructure/decode_hooks.go
deleted file mode 100644
index afcfd5e..0000000
--- a/vendor/github.com/mitchellh/mapstructure/decode_hooks.go
+++ /dev/null
@@ -1,152 +0,0 @@
-package mapstructure
-
-import (
- "errors"
- "reflect"
- "strconv"
- "strings"
- "time"
-)
-
-// typedDecodeHook takes a raw DecodeHookFunc (an interface{}) and turns
-// it into the proper DecodeHookFunc type, such as DecodeHookFuncType.
-func typedDecodeHook(h DecodeHookFunc) DecodeHookFunc {
- // Create variables here so we can reference them with the reflect pkg
- var f1 DecodeHookFuncType
- var f2 DecodeHookFuncKind
-
- // Fill in the variables into this interface and the rest is done
- // automatically using the reflect package.
- potential := []interface{}{f1, f2}
-
- v := reflect.ValueOf(h)
- vt := v.Type()
- for _, raw := range potential {
- pt := reflect.ValueOf(raw).Type()
- if vt.ConvertibleTo(pt) {
- return v.Convert(pt).Interface()
- }
- }
-
- return nil
-}
-
-// DecodeHookExec executes the given decode hook. This should be used
-// since it'll naturally degrade to the older backwards compatible DecodeHookFunc
-// that took reflect.Kind instead of reflect.Type.
-func DecodeHookExec(
- raw DecodeHookFunc,
- from reflect.Type, to reflect.Type,
- data interface{}) (interface{}, error) {
- switch f := typedDecodeHook(raw).(type) {
- case DecodeHookFuncType:
- return f(from, to, data)
- case DecodeHookFuncKind:
- return f(from.Kind(), to.Kind(), data)
- default:
- return nil, errors.New("invalid decode hook signature")
- }
-}
-
-// ComposeDecodeHookFunc creates a single DecodeHookFunc that
-// automatically composes multiple DecodeHookFuncs.
-//
-// The composed funcs are called in order, with the result of the
-// previous transformation.
-func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc {
- return func(
- f reflect.Type,
- t reflect.Type,
- data interface{}) (interface{}, error) {
- var err error
- for _, f1 := range fs {
- data, err = DecodeHookExec(f1, f, t, data)
- if err != nil {
- return nil, err
- }
-
- // Modify the from kind to be correct with the new data
- f = nil
- if val := reflect.ValueOf(data); val.IsValid() {
- f = val.Type()
- }
- }
-
- return data, nil
- }
-}
-
-// StringToSliceHookFunc returns a DecodeHookFunc that converts
-// string to []string by splitting on the given sep.
-func StringToSliceHookFunc(sep string) DecodeHookFunc {
- return func(
- f reflect.Kind,
- t reflect.Kind,
- data interface{}) (interface{}, error) {
- if f != reflect.String || t != reflect.Slice {
- return data, nil
- }
-
- raw := data.(string)
- if raw == "" {
- return []string{}, nil
- }
-
- return strings.Split(raw, sep), nil
- }
-}
-
-// StringToTimeDurationHookFunc returns a DecodeHookFunc that converts
-// strings to time.Duration.
-func StringToTimeDurationHookFunc() DecodeHookFunc {
- return func(
- f reflect.Type,
- t reflect.Type,
- data interface{}) (interface{}, error) {
- if f.Kind() != reflect.String {
- return data, nil
- }
- if t != reflect.TypeOf(time.Duration(5)) {
- return data, nil
- }
-
- // Convert it by parsing
- return time.ParseDuration(data.(string))
- }
-}
-
-// WeaklyTypedHook is a DecodeHookFunc which adds support for weak typing to
-// the decoder.
-//
-// Note that this is significantly different from the WeaklyTypedInput option
-// of the DecoderConfig.
-func WeaklyTypedHook(
- f reflect.Kind,
- t reflect.Kind,
- data interface{}) (interface{}, error) {
- dataVal := reflect.ValueOf(data)
- switch t {
- case reflect.String:
- switch f {
- case reflect.Bool:
- if dataVal.Bool() {
- return "1", nil
- }
- return "0", nil
- case reflect.Float32:
- return strconv.FormatFloat(dataVal.Float(), 'f', -1, 64), nil
- case reflect.Int:
- return strconv.FormatInt(dataVal.Int(), 10), nil
- case reflect.Slice:
- dataType := dataVal.Type()
- elemKind := dataType.Elem().Kind()
- if elemKind == reflect.Uint8 {
- return string(dataVal.Interface().([]uint8)), nil
- }
- case reflect.Uint:
- return strconv.FormatUint(dataVal.Uint(), 10), nil
- }
- }
-
- return data, nil
-}
diff --git a/vendor/github.com/mitchellh/mapstructure/decode_hooks_test.go b/vendor/github.com/mitchellh/mapstructure/decode_hooks_test.go
deleted file mode 100644
index 53289af..0000000
--- a/vendor/github.com/mitchellh/mapstructure/decode_hooks_test.go
+++ /dev/null
@@ -1,229 +0,0 @@
-package mapstructure
-
-import (
- "errors"
- "reflect"
- "testing"
- "time"
-)
-
-func TestComposeDecodeHookFunc(t *testing.T) {
- f1 := func(
- f reflect.Kind,
- t reflect.Kind,
- data interface{}) (interface{}, error) {
- return data.(string) + "foo", nil
- }
-
- f2 := func(
- f reflect.Kind,
- t reflect.Kind,
- data interface{}) (interface{}, error) {
- return data.(string) + "bar", nil
- }
-
- f := ComposeDecodeHookFunc(f1, f2)
-
- result, err := DecodeHookExec(
- f, reflect.TypeOf(""), reflect.TypeOf([]byte("")), "")
- if err != nil {
- t.Fatalf("bad: %s", err)
- }
- if result.(string) != "foobar" {
- t.Fatalf("bad: %#v", result)
- }
-}
-
-func TestComposeDecodeHookFunc_err(t *testing.T) {
- f1 := func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error) {
- return nil, errors.New("foo")
- }
-
- f2 := func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error) {
- panic("NOPE")
- }
-
- f := ComposeDecodeHookFunc(f1, f2)
-
- _, err := DecodeHookExec(
- f, reflect.TypeOf(""), reflect.TypeOf([]byte("")), 42)
- if err.Error() != "foo" {
- t.Fatalf("bad: %s", err)
- }
-}
-
-func TestComposeDecodeHookFunc_kinds(t *testing.T) {
- var f2From reflect.Kind
-
- f1 := func(
- f reflect.Kind,
- t reflect.Kind,
- data interface{}) (interface{}, error) {
- return int(42), nil
- }
-
- f2 := func(
- f reflect.Kind,
- t reflect.Kind,
- data interface{}) (interface{}, error) {
- f2From = f
- return data, nil
- }
-
- f := ComposeDecodeHookFunc(f1, f2)
-
- _, err := DecodeHookExec(
- f, reflect.TypeOf(""), reflect.TypeOf([]byte("")), "")
- if err != nil {
- t.Fatalf("bad: %s", err)
- }
- if f2From != reflect.Int {
- t.Fatalf("bad: %#v", f2From)
- }
-}
-
-func TestStringToSliceHookFunc(t *testing.T) {
- f := StringToSliceHookFunc(",")
-
- strType := reflect.TypeOf("")
- sliceType := reflect.TypeOf([]byte(""))
- cases := []struct {
- f, t reflect.Type
- data interface{}
- result interface{}
- err bool
- }{
- {sliceType, sliceType, 42, 42, false},
- {strType, strType, 42, 42, false},
- {
- strType,
- sliceType,
- "foo,bar,baz",
- []string{"foo", "bar", "baz"},
- false,
- },
- {
- strType,
- sliceType,
- "",
- []string{},
- false,
- },
- }
-
- for i, tc := range cases {
- actual, err := DecodeHookExec(f, tc.f, tc.t, tc.data)
- if tc.err != (err != nil) {
- t.Fatalf("case %d: expected err %#v", i, tc.err)
- }
- if !reflect.DeepEqual(actual, tc.result) {
- t.Fatalf(
- "case %d: expected %#v, got %#v",
- i, tc.result, actual)
- }
- }
-}
-
-func TestStringToTimeDurationHookFunc(t *testing.T) {
- f := StringToTimeDurationHookFunc()
-
- strType := reflect.TypeOf("")
- timeType := reflect.TypeOf(time.Duration(5))
- cases := []struct {
- f, t reflect.Type
- data interface{}
- result interface{}
- err bool
- }{
- {strType, timeType, "5s", 5 * time.Second, false},
- {strType, timeType, "5", time.Duration(0), true},
- {strType, strType, "5", "5", false},
- }
-
- for i, tc := range cases {
- actual, err := DecodeHookExec(f, tc.f, tc.t, tc.data)
- if tc.err != (err != nil) {
- t.Fatalf("case %d: expected err %#v", i, tc.err)
- }
- if !reflect.DeepEqual(actual, tc.result) {
- t.Fatalf(
- "case %d: expected %#v, got %#v",
- i, tc.result, actual)
- }
- }
-}
-
-func TestWeaklyTypedHook(t *testing.T) {
- var f DecodeHookFunc = WeaklyTypedHook
-
- boolType := reflect.TypeOf(true)
- strType := reflect.TypeOf("")
- sliceType := reflect.TypeOf([]byte(""))
- cases := []struct {
- f, t reflect.Type
- data interface{}
- result interface{}
- err bool
- }{
- // TO STRING
- {
- boolType,
- strType,
- false,
- "0",
- false,
- },
-
- {
- boolType,
- strType,
- true,
- "1",
- false,
- },
-
- {
- reflect.TypeOf(float32(1)),
- strType,
- float32(7),
- "7",
- false,
- },
-
- {
- reflect.TypeOf(int(1)),
- strType,
- int(7),
- "7",
- false,
- },
-
- {
- sliceType,
- strType,
- []uint8("foo"),
- "foo",
- false,
- },
-
- {
- reflect.TypeOf(uint(1)),
- strType,
- uint(7),
- "7",
- false,
- },
- }
-
- for i, tc := range cases {
- actual, err := DecodeHookExec(f, tc.f, tc.t, tc.data)
- if tc.err != (err != nil) {
- t.Fatalf("case %d: expected err %#v", i, tc.err)
- }
- if !reflect.DeepEqual(actual, tc.result) {
- t.Fatalf(
- "case %d: expected %#v, got %#v",
- i, tc.result, actual)
- }
- }
-}
diff --git a/vendor/github.com/mitchellh/mapstructure/error.go b/vendor/github.com/mitchellh/mapstructure/error.go
deleted file mode 100644
index 47a99e5..0000000
--- a/vendor/github.com/mitchellh/mapstructure/error.go
+++ /dev/null
@@ -1,50 +0,0 @@
-package mapstructure
-
-import (
- "errors"
- "fmt"
- "sort"
- "strings"
-)
-
-// Error implements the error interface and can represents multiple
-// errors that occur in the course of a single decode.
-type Error struct {
- Errors []string
-}
-
-func (e *Error) Error() string {
- points := make([]string, len(e.Errors))
- for i, err := range e.Errors {
- points[i] = fmt.Sprintf("* %s", err)
- }
-
- sort.Strings(points)
- return fmt.Sprintf(
- "%d error(s) decoding:\n\n%s",
- len(e.Errors), strings.Join(points, "\n"))
-}
-
-// WrappedErrors implements the errwrap.Wrapper interface to make this
-// return value more useful with the errwrap and go-multierror libraries.
-func (e *Error) WrappedErrors() []error {
- if e == nil {
- return nil
- }
-
- result := make([]error, len(e.Errors))
- for i, e := range e.Errors {
- result[i] = errors.New(e)
- }
-
- return result
-}
-
-func appendErrors(errors []string, err error) []string {
- switch e := err.(type) {
- case *Error:
- return append(errors, e.Errors...)
- default:
- return append(errors, e.Error())
- }
-}
diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure.go b/vendor/github.com/mitchellh/mapstructure/mapstructure.go
deleted file mode 100644
index 30a9957..0000000
--- a/vendor/github.com/mitchellh/mapstructure/mapstructure.go
+++ /dev/null
@@ -1,834 +0,0 @@
-// Package mapstructure exposes functionality to convert an arbitrary
-// map[string]interface{} into a native Go structure.
-//
-// The Go structure can be arbitrarily complex, containing slices,
-// other structs, etc. and the decoder will properly decode nested
-// maps and so on into the proper structures in the native Go struct.
-// See the examples to see what the decoder is capable of.
-package mapstructure
-
-import (
- "encoding/json"
- "errors"
- "fmt"
- "reflect"
- "sort"
- "strconv"
- "strings"
-)
-
-// DecodeHookFunc is the callback function that can be used for
-// data transformations. See "DecodeHook" in the DecoderConfig
-// struct.
-//
-// The type should be DecodeHookFuncType or DecodeHookFuncKind.
-// Either is accepted. Types are a superset of Kinds (Types can return
-// Kinds) and are generally a richer thing to use, but Kinds are simpler
-// if you only need those.
-//
-// The reason DecodeHookFunc is multi-typed is for backwards compatibility:
-// we started with Kinds and then realized Types were the better solution,
-// but have a promise to not break backwards compat so we now support
-// both.
-type DecodeHookFunc interface{}
-
-// DecodeHookFuncType is a DecodeHookFunc which has complete information about
-// the source and target types.
-type DecodeHookFuncType func(reflect.Type, reflect.Type, interface{}) (interface{}, error)
-
-// DecodeHookFuncKind is a DecodeHookFunc which knows only the Kinds of the
-// source and target types.
-type DecodeHookFuncKind func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error)
-
-// DecoderConfig is the configuration that is used to create a new decoder
-// and allows customization of various aspects of decoding.
-type DecoderConfig struct {
- // DecodeHook, if set, will be called before any decoding and any
- // type conversion (if WeaklyTypedInput is on). This lets you modify
- // the values before they're set down onto the resulting struct.
- //
- // If an error is returned, the entire decode will fail with that
- // error.
- DecodeHook DecodeHookFunc
-
- // If ErrorUnused is true, then it is an error for there to exist
- // keys in the original map that were unused in the decoding process
- // (extra keys).
- ErrorUnused bool
-
- // ZeroFields, if set to true, will zero fields before writing them.
- // For example, a map will be emptied before decoded values are put in
- // it. If this is false, a map will be merged.
- ZeroFields bool
-
- // If WeaklyTypedInput is true, the decoder will make the following
- // "weak" conversions:
- //
- // - bools to string (true = "1", false = "0")
- // - numbers to string (base 10)
- // - bools to int/uint (true = 1, false = 0)
- // - strings to int/uint (base implied by prefix)
- // - int to bool (true if value != 0)
- // - string to bool (accepts: 1, t, T, TRUE, true, True, 0, f, F,
- // FALSE, false, False. Anything else is an error)
- // - empty array = empty map and vice versa
- // - negative numbers to overflowed uint values (base 10)
- // - slice of maps to a merged map
- // - single values are converted to slices if required. Each
- // element is weakly decoded. For example: "4" can become []int{4}
- // if the target type is an int slice.
- //
- WeaklyTypedInput bool
-
- // Metadata is the struct that will contain extra metadata about
- // the decoding. If this is nil, then no metadata will be tracked.
- Metadata *Metadata
-
- // Result is a pointer to the struct that will contain the decoded
- // value.
- Result interface{}
-
- // The tag name that mapstructure reads for field names. This
- // defaults to "mapstructure"
- TagName string
-}
-
-// A Decoder takes a raw interface value and turns it into structured
-// data, keeping track of rich error information along the way in case
-// anything goes wrong. Unlike the basic top-level Decode method, you can
-// more finely control how the Decoder behaves using the DecoderConfig
-// structure. The top-level Decode method is just a convenience that sets
-// up the most basic Decoder.
-type Decoder struct {
- config *DecoderConfig
-}
-
-// Metadata contains information about decoding a structure that
-// is tedious or difficult to get otherwise.
-type Metadata struct {
- // Keys are the keys of the structure which were successfully decoded
- Keys []string
-
- // Unused is a slice of keys that were found in the raw value but
- // weren't decoded since there was no matching field in the result interface
- Unused []string
-}
-
-// Decode takes a map and uses reflection to convert it into the
-// given Go native structure. val must be a pointer to a struct.
-func Decode(m interface{}, rawVal interface{}) error {
- config := &DecoderConfig{
- Metadata: nil,
- Result: rawVal,
- }
-
- decoder, err := NewDecoder(config)
- if err != nil {
- return err
- }
-
- return decoder.Decode(m)
-}
-
-// WeakDecode is the same as Decode but is shorthand to enable
-// WeaklyTypedInput. See DecoderConfig for more info.
-func WeakDecode(input, output interface{}) error {
- config := &DecoderConfig{
- Metadata: nil,
- Result: output,
- WeaklyTypedInput: true,
- }
-
- decoder, err := NewDecoder(config)
- if err != nil {
- return err
- }
-
- return decoder.Decode(input)
-}
-
-// NewDecoder returns a new decoder for the given configuration. Once
-// a decoder has been returned, the same configuration must not be used
-// again.
-func NewDecoder(config *DecoderConfig) (*Decoder, error) {
- val := reflect.ValueOf(config.Result)
- if val.Kind() != reflect.Ptr {
- return nil, errors.New("result must be a pointer")
- }
-
- val = val.Elem()
- if !val.CanAddr() {
- return nil, errors.New("result must be addressable (a pointer)")
- }
-
- if config.Metadata != nil {
- if config.Metadata.Keys == nil {
- config.Metadata.Keys = make([]string, 0)
- }
-
- if config.Metadata.Unused == nil {
- config.Metadata.Unused = make([]string, 0)
- }
- }
-
- if config.TagName == "" {
- config.TagName = "mapstructure"
- }
-
- result := &Decoder{
- config: config,
- }
-
- return result, nil
-}
-
-// Decode decodes the given raw interface to the target pointer specified
-// by the configuration.
-func (d *Decoder) Decode(raw interface{}) error {
- return d.decode("", raw, reflect.ValueOf(d.config.Result).Elem())
-}
-
-// Decodes an unknown data type into a specific reflection value.
-func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error {
- if data == nil {
- // If the data is nil, then we don't set anything.
- return nil
- }
-
- dataVal := reflect.ValueOf(data)
- if !dataVal.IsValid() {
- // If the data value is invalid, then we just set the value
- // to be the zero value.
- val.Set(reflect.Zero(val.Type()))
- return nil
- }
-
- if d.config.DecodeHook != nil {
- // We have a DecodeHook, so let's pre-process the data.
- var err error
- data, err = DecodeHookExec(
- d.config.DecodeHook,
- dataVal.Type(), val.Type(), data)
- if err != nil {
- return fmt.Errorf("error decoding '%s': %s", name, err)
- }
- }
-
- var err error
- dataKind := getKind(val)
- switch dataKind {
- case reflect.Bool:
- err = d.decodeBool(name, data, val)
- case reflect.Interface:
- err = d.decodeBasic(name, data, val)
- case reflect.String:
- err = d.decodeString(name, data, val)
- case reflect.Int:
- err = d.decodeInt(name, data, val)
- case reflect.Uint:
- err = d.decodeUint(name, data, val)
- case reflect.Float32:
- err = d.decodeFloat(name, data, val)
- case reflect.Struct:
- err = d.decodeStruct(name, data, val)
- case reflect.Map:
- err = d.decodeMap(name, data, val)
- case reflect.Ptr:
- err = d.decodePtr(name, data, val)
- case reflect.Slice:
- err = d.decodeSlice(name, data, val)
- case reflect.Func:
- err = d.decodeFunc(name, data, val)
- default:
- // If we reached this point then we weren't able to decode it
- return fmt.Errorf("%s: unsupported type: %s", name, dataKind)
- }
-
- // If we reached here, then we successfully decoded SOMETHING, so
- // mark the key as used if we're tracking metadata.
- if d.config.Metadata != nil && name != "" {
- d.config.Metadata.Keys = append(d.config.Metadata.Keys, name)
- }
-
- return err
-}
-
-// This decodes a basic type (bool, int, string, etc.) and sets the
-// value to "data" of that type.
-func (d *Decoder) decodeBasic(name string, data interface{}, val reflect.Value) error {
- dataVal := reflect.ValueOf(data)
- if !dataVal.IsValid() {
- dataVal = reflect.Zero(val.Type())
- }
-
- dataValType := dataVal.Type()
- if !dataValType.AssignableTo(val.Type()) {
- return fmt.Errorf(
- "'%s' expected type '%s', got '%s'",
- name, val.Type(), dataValType)
- }
-
- val.Set(dataVal)
- return nil
-}
-
-func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) error {
- dataVal := reflect.ValueOf(data)
- dataKind := getKind(dataVal)
-
- converted := true
- switch {
- case dataKind == reflect.String:
- val.SetString(dataVal.String())
- case dataKind == reflect.Bool && d.config.WeaklyTypedInput:
- if dataVal.Bool() {
- val.SetString("1")
- } else {
- val.SetString("0")
- }
- case dataKind == reflect.Int && d.config.WeaklyTypedInput:
- val.SetString(strconv.FormatInt(dataVal.Int(), 10))
- case dataKind == reflect.Uint && d.config.WeaklyTypedInput:
- val.SetString(strconv.FormatUint(dataVal.Uint(), 10))
- case dataKind == reflect.Float32 && d.config.WeaklyTypedInput:
- val.SetString(strconv.FormatFloat(dataVal.Float(), 'f', -1, 64))
- case dataKind == reflect.Slice && d.config.WeaklyTypedInput:
- dataType := dataVal.Type()
- elemKind := dataType.Elem().Kind()
- switch {
- case elemKind == reflect.Uint8:
- val.SetString(string(dataVal.Interface().([]uint8)))
- default:
- converted = false
- }
- default:
- converted = false
- }
-
- if !converted {
- return fmt.Errorf(
- "'%s' expected type '%s', got unconvertible type '%s'",
- name, val.Type(), dataVal.Type())
- }
-
- return nil
-}
-
-func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) error {
- dataVal := reflect.ValueOf(data)
- dataKind := getKind(dataVal)
- dataType := dataVal.Type()
-
- switch {
- case dataKind == reflect.Int:
- val.SetInt(dataVal.Int())
- case dataKind == reflect.Uint:
- val.SetInt(int64(dataVal.Uint()))
- case dataKind == reflect.Float32:
- val.SetInt(int64(dataVal.Float()))
- case dataKind == reflect.Bool && d.config.WeaklyTypedInput:
- if dataVal.Bool() {
- val.SetInt(1)
- } else {
- val.SetInt(0)
- }
- case dataKind == reflect.String && d.config.WeaklyTypedInput:
- i, err := strconv.ParseInt(dataVal.String(), 0, val.Type().Bits())
- if err == nil {
- val.SetInt(i)
- } else {
- return fmt.Errorf("cannot parse '%s' as int: %s", name, err)
- }
- case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number":
- jn := data.(json.Number)
- i, err := jn.Int64()
- if err != nil {
- return fmt.Errorf(
- "error decoding json.Number into %s: %s", name, err)
- }
- val.SetInt(i)
- default:
- return fmt.Errorf(
- "'%s' expected type '%s', got unconvertible type '%s'",
- name, val.Type(), dataVal.Type())
- }
-
- return nil
-}
-
-func (d *Decoder) decodeUint(name string, data interface{}, val reflect.Value) error {
- dataVal := reflect.ValueOf(data)
- dataKind := getKind(dataVal)
-
- switch {
- case dataKind == reflect.Int:
- i := dataVal.Int()
- if i < 0 && !d.config.WeaklyTypedInput {
- return fmt.Errorf("cannot parse '%s', %d overflows uint",
- name, i)
- }
- val.SetUint(uint64(i))
- case dataKind == reflect.Uint:
- val.SetUint(dataVal.Uint())
- case dataKind == reflect.Float32:
- f := dataVal.Float()
- if f < 0 && !d.config.WeaklyTypedInput {
- return fmt.Errorf("cannot parse '%s', %f overflows uint",
- name, f)
- }
- val.SetUint(uint64(f))
- case dataKind == reflect.Bool && d.config.WeaklyTypedInput:
- if dataVal.Bool() {
- val.SetUint(1)
- } else {
- val.SetUint(0)
- }
- case dataKind == reflect.String && d.config.WeaklyTypedInput:
- i, err := strconv.ParseUint(dataVal.String(), 0, val.Type().Bits())
- if err == nil {
- val.SetUint(i)
- } else {
- return fmt.Errorf("cannot parse '%s' as uint: %s", name, err)
- }
- default:
- return fmt.Errorf(
- "'%s' expected type '%s', got unconvertible type '%s'",
- name, val.Type(), dataVal.Type())
- }
-
- return nil
-}
-
-func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) error {
- dataVal := reflect.ValueOf(data)
- dataKind := getKind(dataVal)
-
- switch {
- case dataKind == reflect.Bool:
- val.SetBool(dataVal.Bool())
- case dataKind == reflect.Int && d.config.WeaklyTypedInput:
- val.SetBool(dataVal.Int() != 0)
- case dataKind == reflect.Uint && d.config.WeaklyTypedInput:
- val.SetBool(dataVal.Uint() != 0)
- case dataKind == reflect.Float32 && d.config.WeaklyTypedInput:
- val.SetBool(dataVal.Float() != 0)
- case dataKind == reflect.String && d.config.WeaklyTypedInput:
- b, err := strconv.ParseBool(dataVal.String())
- if err == nil {
- val.SetBool(b)
- } else if dataVal.String() == "" {
- val.SetBool(false)
- } else {
- return fmt.Errorf("cannot parse '%s' as bool: %s", name, err)
- }
- default:
- return fmt.Errorf(
- "'%s' expected type '%s', got unconvertible type '%s'",
- name, val.Type(), dataVal.Type())
- }
-
- return nil
-}
-
-func (d *Decoder) decodeFloat(name string, data interface{}, val reflect.Value) error {
- dataVal := reflect.ValueOf(data)
- dataKind := getKind(dataVal)
- dataType := dataVal.Type()
-
- switch {
- case dataKind == reflect.Int:
- val.SetFloat(float64(dataVal.Int()))
- case dataKind == reflect.Uint:
- val.SetFloat(float64(dataVal.Uint()))
- case dataKind == reflect.Float32:
- val.SetFloat(dataVal.Float())
- case dataKind == reflect.Bool && d.config.WeaklyTypedInput:
- if dataVal.Bool() {
- val.SetFloat(1)
- } else {
- val.SetFloat(0)
- }
- case dataKind == reflect.String && d.config.WeaklyTypedInput:
- f, err := strconv.ParseFloat(dataVal.String(), val.Type().Bits())
- if err == nil {
- val.SetFloat(f)
- } else {
- return fmt.Errorf("cannot parse '%s' as float: %s", name, err)
- }
- case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number":
- jn := data.(json.Number)
- i, err := jn.Float64()
- if err != nil {
- return fmt.Errorf(
- "error decoding json.Number into %s: %s", name, err)
- }
- val.SetFloat(i)
- default:
- return fmt.Errorf(
- "'%s' expected type '%s', got unconvertible type '%s'",
- name, val.Type(), dataVal.Type())
- }
-
- return nil
-}
-
-func (d *Decoder) decodeMap(name string, data interface{}, val reflect.Value) error {
- valType := val.Type()
- valKeyType := valType.Key()
- valElemType := valType.Elem()
-
- // By default we overwrite keys in the current map
- valMap := val
-
- // If the map is nil or we're purposely zeroing fields, make a new map
- if valMap.IsNil() || d.config.ZeroFields {
- // Make a new map to hold our result
- mapType := reflect.MapOf(valKeyType, valElemType)
- valMap = reflect.MakeMap(mapType)
- }
-
- // Check input type
- dataVal := reflect.Indirect(reflect.ValueOf(data))
- if dataVal.Kind() != reflect.Map {
- // In weak mode, we accept a slice of maps as an input...
- if d.config.WeaklyTypedInput {
- switch dataVal.Kind() {
- case reflect.Array, reflect.Slice:
- // Special case for BC reasons (covered by tests)
- if dataVal.Len() == 0 {
- val.Set(valMap)
- return nil
- }
-
- for i := 0; i < dataVal.Len(); i++ {
- err := d.decode(
- fmt.Sprintf("%s[%d]", name, i),
- dataVal.Index(i).Interface(), val)
- if err != nil {
- return err
- }
- }
-
- return nil
- }
- }
-
- return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind())
- }
-
- // Accumulate errors
- errors := make([]string, 0)
-
- for _, k := range dataVal.MapKeys() {
- fieldName := fmt.Sprintf("%s[%s]", name, k)
-
- // First decode the key into the proper type
- currentKey := reflect.Indirect(reflect.New(valKeyType))
- if err := d.decode(fieldName, k.Interface(), currentKey); err != nil {
- errors = appendErrors(errors, err)
- continue
- }
-
- // Next decode the data into the proper type
- v := dataVal.MapIndex(k).Interface()
- currentVal := reflect.Indirect(reflect.New(valElemType))
- if err := d.decode(fieldName, v, currentVal); err != nil {
- errors = appendErrors(errors, err)
- continue
- }
-
- valMap.SetMapIndex(currentKey, currentVal)
- }
-
- // Set the built up map to the value
- val.Set(valMap)
-
- // If we had errors, return those
- if len(errors) > 0 {
- return &Error{errors}
- }
-
- return nil
-}
-
-func (d *Decoder) decodePtr(name string, data interface{}, val reflect.Value) error {
- // Create an element of the concrete (non pointer) type and decode
- // into that. Then set the value of the pointer to this type.
- valType := val.Type()
- valElemType := valType.Elem()
-
- realVal := val
- if realVal.IsNil() || d.config.ZeroFields {
- realVal = reflect.New(valElemType)
- }
-
- if err := d.decode(name, data, reflect.Indirect(realVal)); err != nil {
- return err
- }
-
- val.Set(realVal)
- return nil
-}
-
-func (d *Decoder) decodeFunc(name string, data interface{}, val reflect.Value) error {
- // Create an element of the concrete (non pointer) type and decode
- // into that. Then set the value of the pointer to this type.
- dataVal := reflect.Indirect(reflect.ValueOf(data))
- if val.Type() != dataVal.Type() {
- return fmt.Errorf(
- "'%s' expected type '%s', got unconvertible type '%s'",
- name, val.Type(), dataVal.Type())
- }
- val.Set(dataVal)
- return nil
-}
-
-func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) error {
- dataVal := reflect.Indirect(reflect.ValueOf(data))
- dataValKind := dataVal.Kind()
- valType := val.Type()
- valElemType := valType.Elem()
- sliceType := reflect.SliceOf(valElemType)
-
- valSlice := val
- if valSlice.IsNil() || d.config.ZeroFields {
- // Check input type
- if dataValKind != reflect.Array && dataValKind != reflect.Slice {
- if d.config.WeaklyTypedInput {
- switch {
- // Empty maps turn into empty slices
- case dataValKind == reflect.Map:
- if dataVal.Len() == 0 {
- val.Set(reflect.MakeSlice(sliceType, 0, 0))
- return nil
- }
-
- // All other types we try to convert to the slice type
- // and "lift" it into it. i.e. a string becomes a string slice.
- default:
- // Just re-try this function with data as a slice.
- return d.decodeSlice(name, []interface{}{data}, val)
- }
- }
-
- return fmt.Errorf(
- "'%s': source data must be an array or slice, got %s", name, dataValKind)
-
- }
-
- // Make a new slice to hold our result, same size as the original data.
- valSlice = reflect.MakeSlice(sliceType, dataVal.Len(), dataVal.Len())
- }
-
- // Accumulate any errors
- errors := make([]string, 0)
-
- for i := 0; i < dataVal.Len(); i++ {
- currentData := dataVal.Index(i).Interface()
- for valSlice.Len() <= i {
- valSlice = reflect.Append(valSlice, reflect.Zero(valElemType))
- }
- currentField := valSlice.Index(i)
-
- fieldName := fmt.Sprintf("%s[%d]", name, i)
- if err := d.decode(fieldName, currentData, currentField); err != nil {
- errors = appendErrors(errors, err)
- }
- }
-
- // Finally, set the value to the slice we built up
- val.Set(valSlice)
-
- // If there were errors, we return those
- if len(errors) > 0 {
- return &Error{errors}
- }
-
- return nil
-}
-
-func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) error {
- dataVal := reflect.Indirect(reflect.ValueOf(data))
-
- // If the type of the value to write to and the data match directly,
- // then we just set it directly instead of recursing into the structure.
- if dataVal.Type() == val.Type() {
- val.Set(dataVal)
- return nil
- }
-
- dataValKind := dataVal.Kind()
- if dataValKind != reflect.Map {
- return fmt.Errorf("'%s' expected a map, got '%s'", name, dataValKind)
- }
-
- dataValType := dataVal.Type()
- if kind := dataValType.Key().Kind(); kind != reflect.String && kind != reflect.Interface {
- return fmt.Errorf(
- "'%s' needs a map with string keys, has '%s' keys",
- name, dataValType.Key().Kind())
- }
-
- dataValKeys := make(map[reflect.Value]struct{})
- dataValKeysUnused := make(map[interface{}]struct{})
- for _, dataValKey := range dataVal.MapKeys() {
- dataValKeys[dataValKey] = struct{}{}
- dataValKeysUnused[dataValKey.Interface()] = struct{}{}
- }
-
- errors := make([]string, 0)
-
- // This slice will keep track of all the structs we'll be decoding.
- // There can be more than one struct if there are embedded structs
- // that are squashed.
- structs := make([]reflect.Value, 1, 5)
- structs[0] = val
-
- // Compile the list of all the fields that we're going to be decoding
- // from all the structs.
- type field struct {
- field reflect.StructField
- val reflect.Value
- }
- fields := []field{}
- for len(structs) > 0 {
- structVal := structs[0]
- structs = structs[1:]
-
- structType := structVal.Type()
-
- for i := 0; i < structType.NumField(); i++ {
- fieldType := structType.Field(i)
- fieldKind := fieldType.Type.Kind()
-
- // If "squash" is specified in the tag, we squash the field down.
- squash := false
- tagParts := strings.Split(fieldType.Tag.Get(d.config.TagName), ",")
- for _, tag := range tagParts[1:] {
- if tag == "squash" {
- squash = true
- break
- }
- }
-
- if squash {
- if fieldKind != reflect.Struct {
- errors = appendErrors(errors,
- fmt.Errorf("%s: unsupported type for squash: %s", fieldType.Name, fieldKind))
- } else {
- structs = append(structs, val.FieldByName(fieldType.Name))
- }
- continue
- }
-
- // Normal struct field, store it away
- fields = append(fields, field{fieldType, structVal.Field(i)})
- }
- }
-
- // for fieldType, field := range fields {
- for _, f := range fields {
- field, fieldValue := f.field, f.val
- fieldName := field.Name
-
- tagValue := field.Tag.Get(d.config.TagName)
- tagValue = strings.SplitN(tagValue, ",", 2)[0]
- if tagValue != "" {
- fieldName = tagValue
- }
-
- rawMapKey := reflect.ValueOf(fieldName)
- rawMapVal := dataVal.MapIndex(rawMapKey)
- if !rawMapVal.IsValid() {
- // Do a slower search by iterating over each key and
- // doing case-insensitive search.
- for dataValKey := range dataValKeys {
- mK, ok := dataValKey.Interface().(string)
- if !ok {
- // Not a string key
- continue
- }
-
- if strings.EqualFold(mK, fieldName) {
- rawMapKey = dataValKey
- rawMapVal = dataVal.MapIndex(dataValKey)
- break
- }
- }
-
- if !rawMapVal.IsValid() {
- // There was no matching key in the map for the value in
- // the struct. Just ignore.
- continue
- }
- }
-
- // Delete the key we're using from the unused map so we stop tracking
- delete(dataValKeysUnused, rawMapKey.Interface())
-
- if !fieldValue.IsValid() {
- // This should never happen
- panic("field is not valid")
- }
-
- // If we can't set the field, then it is unexported or something,
- // and we just continue onwards.
- if !fieldValue.CanSet() {
- continue
- }
-
- // If the name is empty string, then we're at the root, and we
- // don't dot-join the fields.
- if name != "" {
- fieldName = fmt.Sprintf("%s.%s", name, fieldName)
- }
-
- if err := d.decode(fieldName, rawMapVal.Interface(), fieldValue); err != nil {
- errors = appendErrors(errors, err)
- }
- }
-
- if d.config.ErrorUnused && len(dataValKeysUnused) > 0 {
- keys := make([]string, 0, len(dataValKeysUnused))
- for rawKey := range dataValKeysUnused {
- keys = append(keys, rawKey.(string))
- }
- sort.Strings(keys)
-
- err := fmt.Errorf("'%s' has invalid keys: %s", name, strings.Join(keys, ", "))
- errors = appendErrors(errors, err)
- }
-
- if len(errors) > 0 {
- return &Error{errors}
- }
-
- // Add the unused keys to the list of unused keys if we're tracking metadata
- if d.config.Metadata != nil {
- for rawKey := range dataValKeysUnused {
- key := rawKey.(string)
- if name != "" {
- key = fmt.Sprintf("%s.%s", name, key)
- }
-
- d.config.Metadata.Unused = append(d.config.Metadata.Unused, key)
- }
- }
-
- return nil
-}
-
-func getKind(val reflect.Value) reflect.Kind {
- kind := val.Kind()
-
- switch {
- case kind >= reflect.Int && kind <= reflect.Int64:
- return reflect.Int
- case kind >= reflect.Uint && kind <= reflect.Uint64:
- return reflect.Uint
- case kind >= reflect.Float32 && kind <= reflect.Float64:
- return reflect.Float32
- default:
- return kind
- }
-}
diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure_benchmark_test.go b/vendor/github.com/mitchellh/mapstructure/mapstructure_benchmark_test.go
deleted file mode 100644
index 41d2a41..0000000
--- a/vendor/github.com/mitchellh/mapstructure/mapstructure_benchmark_test.go
+++ /dev/null
@@ -1,279 +0,0 @@
-package mapstructure
-
-import (
- "encoding/json"
- "testing"
-)
-
-func Benchmark_Decode(b *testing.B) {
- type Person struct {
- Name string
- Age int
- Emails []string
- Extra map[string]string
- }
-
- input := map[string]interface{}{
- "name": "Mitchell",
- "age": 91,
- "emails": []string{"one", "two", "three"},
- "extra": map[string]string{
- "twitter": "mitchellh",
- },
- }
-
- var result Person
- for i := 0; i < b.N; i++ {
- Decode(input, &result)
- }
-}
-
-// decodeViaJSON takes the map data and passes it through encoding/json to convert it into the
-// given Go native structure pointed to by v. v must be a pointer to a struct.
-func decodeViaJSON(data interface{}, v interface{}) error {
- // Perform the task by simply marshalling the input into JSON,
- // then unmarshalling it into target native Go struct.
- b, err := json.Marshal(data)
- if err != nil {
- return err
- }
- return json.Unmarshal(b, v)
-}
-
-func Benchmark_DecodeViaJSON(b *testing.B) {
- type Person struct {
- Name string
- Age int
- Emails []string
- Extra map[string]string
- }
-
- input := map[string]interface{}{
- "name": "Mitchell",
- "age": 91,
- "emails": []string{"one", "two", "three"},
- "extra": map[string]string{
- "twitter": "mitchellh",
- },
- }
-
- var result Person
- for i := 0; i < b.N; i++ {
- decodeViaJSON(input, &result)
- }
-}
-
-func Benchmark_DecodeBasic(b *testing.B) {
- input := map[string]interface{}{
- "vstring": "foo",
- "vint": 42,
- "Vuint": 42,
- "vbool": true,
- "Vfloat": 42.42,
- "vsilent": true,
- "vdata": 42,
- }
-
- var result Basic
- for i := 0; i < b.N; i++ {
- Decode(input, &result)
- }
-}
-
-func Benchmark_DecodeEmbedded(b *testing.B) {
- input := map[string]interface{}{
- "vstring": "foo",
- "Basic": map[string]interface{}{
- "vstring": "innerfoo",
- },
- "vunique": "bar",
- }
-
- var result Embedded
- for i := 0; i < b.N; i++ {
- Decode(input, &result)
- }
-}
-
-func Benchmark_DecodeTypeConversion(b *testing.B) {
- input := map[string]interface{}{
- "IntToFloat": 42,
- "IntToUint": 42,
- "IntToBool": 1,
- "IntToString": 42,
- "UintToInt": 42,
- "UintToFloat": 42,
- "UintToBool": 42,
- "UintToString": 42,
- "BoolToInt": true,
- "BoolToUint": true,
- "BoolToFloat": true,
- "BoolToString": true,
- "FloatToInt": 42.42,
- "FloatToUint": 42.42,
- "FloatToBool": 42.42,
- "FloatToString": 42.42,
- "StringToInt": "42",
- "StringToUint": "42",
- "StringToBool": "1",
- "StringToFloat": "42.42",
- "SliceToMap": []interface{}{},
- "MapToSlice": map[string]interface{}{},
- }
-
- var resultStrict TypeConversionResult
- for i := 0; i < b.N; i++ {
- Decode(input, &resultStrict)
- }
-}
-
-func Benchmark_DecodeMap(b *testing.B) {
- input := map[string]interface{}{
- "vfoo": "foo",
- "vother": map[interface{}]interface{}{
- "foo": "foo",
- "bar": "bar",
- },
- }
-
- var result Map
- for i := 0; i < b.N; i++ {
- Decode(input, &result)
- }
-}
-
-func Benchmark_DecodeMapOfStruct(b *testing.B) {
- input := map[string]interface{}{
- "value": map[string]interface{}{
- "foo": map[string]string{"vstring": "one"},
- "bar": map[string]string{"vstring": "two"},
- },
- }
-
- var result MapOfStruct
- for i := 0; i < b.N; i++ {
- Decode(input, &result)
- }
-}
-
-func Benchmark_DecodeSlice(b *testing.B) {
- input := map[string]interface{}{
- "vfoo": "foo",
- "vbar": []string{"foo", "bar", "baz"},
- }
-
- var result Slice
- for i := 0; i < b.N; i++ {
- Decode(input, &result)
- }
-}
-
-func Benchmark_DecodeSliceOfStruct(b *testing.B) {
- input := map[string]interface{}{
- "value": []map[string]interface{}{
- {"vstring": "one"},
- {"vstring": "two"},
- },
- }
-
- var result SliceOfStruct
- for i := 0; i < b.N; i++ {
- Decode(input, &result)
- }
-}
-
-func Benchmark_DecodeWeaklyTypedInput(b *testing.B) {
- type Person struct {
- Name string
- Age int
- Emails []string
- }
-
- // This input can come from anywhere, but typically comes from
- // something like decoding JSON, generated by a weakly typed language
- // such as PHP.
- input := map[string]interface{}{
- "name": 123, // number => string
- "age": "42", // string => number
- "emails": map[string]interface{}{}, // empty map => empty array
- }
-
- var result Person
- config := &DecoderConfig{
- WeaklyTypedInput: true,
- Result: &result,
- }
-
- decoder, err := NewDecoder(config)
- if err != nil {
- panic(err)
- }
-
- for i := 0; i < b.N; i++ {
- decoder.Decode(input)
- }
-}
-
-func Benchmark_DecodeMetadata(b *testing.B) {
- type Person struct {
- Name string
- Age int
- }
-
- input := map[string]interface{}{
- "name": "Mitchell",
- "age": 91,
- "email": "foo@bar.com",
- }
-
- var md Metadata
- var result Person
- config := &DecoderConfig{
- Metadata: &md,
- Result: &result,
- }
-
- decoder, err := NewDecoder(config)
- if err != nil {
- panic(err)
- }
-
- for i := 0; i < b.N; i++ {
- decoder.Decode(input)
- }
-}
-
-func Benchmark_DecodeMetadataEmbedded(b *testing.B) {
- input := map[string]interface{}{
- "vstring": "foo",
- "vunique": "bar",
- }
-
- var md Metadata
- var result EmbeddedSquash
- config := &DecoderConfig{
- Metadata: &md,
- Result: &result,
- }
-
- decoder, err := NewDecoder(config)
- if err != nil {
- b.Fatalf("err: %s", err)
- }
-
- for i := 0; i < b.N; i++ {
- decoder.Decode(input)
- }
-}
-
-func Benchmark_DecodeTagged(b *testing.B) {
- input := map[string]interface{}{
- "foo": "bar",
- "bar": "value",
- }
-
- var result Tagged
- for i := 0; i < b.N; i++ {
- Decode(input, &result)
- }
-}
diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure_bugs_test.go b/vendor/github.com/mitchellh/mapstructure/mapstructure_bugs_test.go
deleted file mode 100644
index 08e4956..0000000
--- a/vendor/github.com/mitchellh/mapstructure/mapstructure_bugs_test.go
+++ /dev/null
@@ -1,260 +0,0 @@
-package mapstructure
-
-import "testing"
-
-// GH-1
-func TestDecode_NilValue(t *testing.T) {
- input := map[string]interface{}{
- "vfoo": nil,
- "vother": nil,
- }
-
- var result Map
- err := Decode(input, &result)
- if err != nil {
- t.Fatalf("should not error: %s", err)
- }
-
- if result.Vfoo != "" {
- t.Fatalf("value should be default: %s", result.Vfoo)
- }
-
- if result.Vother != nil {
- t.Fatalf("Vother should be nil: %s", result.Vother)
- }
-}
-
-// GH-10
-func TestDecode_mapInterfaceInterface(t *testing.T) {
- input := map[interface{}]interface{}{
- "vfoo": nil,
- "vother": nil,
- }
-
- var result Map
- err := Decode(input, &result)
- if err != nil {
- t.Fatalf("should not error: %s", err)
- }
-
- if result.Vfoo != "" {
- t.Fatalf("value should be default: %s", result.Vfoo)
- }
-
- if result.Vother != nil {
- t.Fatalf("Vother should be nil: %s", result.Vother)
- }
-}
-
-// #48
-func TestNestedTypePointerWithDefaults(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "vfoo": "foo",
- "vbar": map[string]interface{}{
- "vstring": "foo",
- "vint": 42,
- "vbool": true,
- },
- }
-
- result := NestedPointer{
- Vbar: &Basic{
- Vuint: 42,
- },
- }
- err := Decode(input, &result)
- if err != nil {
- t.Fatalf("got an err: %s", err.Error())
- }
-
- if result.Vfoo != "foo" {
- t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo)
- }
-
- if result.Vbar.Vstring != "foo" {
- t.Errorf("vstring value should be 'foo': %#v", result.Vbar.Vstring)
- }
-
- if result.Vbar.Vint != 42 {
- t.Errorf("vint value should be 42: %#v", result.Vbar.Vint)
- }
-
- if result.Vbar.Vbool != true {
- t.Errorf("vbool value should be true: %#v", result.Vbar.Vbool)
- }
-
- if result.Vbar.Vextra != "" {
- t.Errorf("vextra value should be empty: %#v", result.Vbar.Vextra)
- }
-
- // this is the error
- if result.Vbar.Vuint != 42 {
- t.Errorf("vuint value should be 42: %#v", result.Vbar.Vuint)
- }
-
-}
-
-type NestedSlice struct {
- Vfoo string
- Vbars []Basic
- Vempty []Basic
-}
-
-// #48
-func TestNestedTypeSliceWithDefaults(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "vfoo": "foo",
- "vbars": []map[string]interface{}{
- {"vstring": "foo", "vint": 42, "vbool": true},
- {"vint": 42, "vbool": true},
- },
- "vempty": []map[string]interface{}{
- {"vstring": "foo", "vint": 42, "vbool": true},
- {"vint": 42, "vbool": true},
- },
- }
-
- result := NestedSlice{
- Vbars: []Basic{
- {Vuint: 42},
- {Vstring: "foo"},
- },
- }
- err := Decode(input, &result)
- if err != nil {
- t.Fatalf("got an err: %s", err.Error())
- }
-
- if result.Vfoo != "foo" {
- t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo)
- }
-
- if result.Vbars[0].Vstring != "foo" {
- t.Errorf("vstring value should be 'foo': %#v", result.Vbars[0].Vstring)
- }
- // this is the error
- if result.Vbars[0].Vuint != 42 {
- t.Errorf("vuint value should be 42: %#v", result.Vbars[0].Vuint)
- }
-}
-
-// #48 workaround
-func TestNestedTypeWithDefaults(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "vfoo": "foo",
- "vbar": map[string]interface{}{
- "vstring": "foo",
- "vint": 42,
- "vbool": true,
- },
- }
-
- result := Nested{
- Vbar: Basic{
- Vuint: 42,
- },
- }
- err := Decode(input, &result)
- if err != nil {
- t.Fatalf("got an err: %s", err.Error())
- }
-
- if result.Vfoo != "foo" {
- t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo)
- }
-
- if result.Vbar.Vstring != "foo" {
- t.Errorf("vstring value should be 'foo': %#v", result.Vbar.Vstring)
- }
-
- if result.Vbar.Vint != 42 {
- t.Errorf("vint value should be 42: %#v", result.Vbar.Vint)
- }
-
- if result.Vbar.Vbool != true {
- t.Errorf("vbool value should be true: %#v", result.Vbar.Vbool)
- }
-
- if result.Vbar.Vextra != "" {
- t.Errorf("vextra value should be empty: %#v", result.Vbar.Vextra)
- }
-
- // this is the error
- if result.Vbar.Vuint != 42 {
- t.Errorf("vuint value should be 42: %#v", result.Vbar.Vuint)
- }
-
-}
-
-// #67 panic() on extending slices (decodeSlice with disabled ZeroValues)
-func TestDecodeSliceToEmptySliceWOZeroing(t *testing.T) {
- t.Parallel()
-
- type TestStruct struct {
- Vfoo []string
- }
-
- decode := func(m interface{}, rawVal interface{}) error {
- config := &DecoderConfig{
- Metadata: nil,
- Result: rawVal,
- ZeroFields: false,
- }
-
- decoder, err := NewDecoder(config)
- if err != nil {
- return err
- }
-
- return decoder.Decode(m)
- }
-
- {
- input := map[string]interface{}{
- "vfoo": []string{"1"},
- }
-
- result := &TestStruct{}
-
- err := decode(input, &result)
- if err != nil {
- t.Fatalf("got an err: %s", err.Error())
- }
- }
-
- {
- input := map[string]interface{}{
- "vfoo": []string{"1"},
- }
-
- result := &TestStruct{
- Vfoo: []string{},
- }
-
- err := decode(input, &result)
- if err != nil {
- t.Fatalf("got an err: %s", err.Error())
- }
- }
-
- {
- input := map[string]interface{}{
- "vfoo": []string{"2", "3"},
- }
-
- result := &TestStruct{
- Vfoo: []string{"1"},
- }
-
- err := decode(input, &result)
- if err != nil {
- t.Fatalf("got an err: %s", err.Error())
- }
- }
-}
diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure_examples_test.go b/vendor/github.com/mitchellh/mapstructure/mapstructure_examples_test.go
deleted file mode 100644
index f17c214..0000000
--- a/vendor/github.com/mitchellh/mapstructure/mapstructure_examples_test.go
+++ /dev/null
@@ -1,203 +0,0 @@
-package mapstructure
-
-import (
- "fmt"
-)
-
-func ExampleDecode() {
- type Person struct {
- Name string
- Age int
- Emails []string
- Extra map[string]string
- }
-
- // This input can come from anywhere, but typically comes from
- // something like decoding JSON where we're not quite sure of the
- // struct initially.
- input := map[string]interface{}{
- "name": "Mitchell",
- "age": 91,
- "emails": []string{"one", "two", "three"},
- "extra": map[string]string{
- "twitter": "mitchellh",
- },
- }
-
- var result Person
- err := Decode(input, &result)
- if err != nil {
- panic(err)
- }
-
- fmt.Printf("%#v", result)
- // Output:
- // mapstructure.Person{Name:"Mitchell", Age:91, Emails:[]string{"one", "two", "three"}, Extra:map[string]string{"twitter":"mitchellh"}}
-}
-
-func ExampleDecode_errors() {
- type Person struct {
- Name string
- Age int
- Emails []string
- Extra map[string]string
- }
-
- // This input can come from anywhere, but typically comes from
- // something like decoding JSON where we're not quite sure of the
- // struct initially.
- input := map[string]interface{}{
- "name": 123,
- "age": "bad value",
- "emails": []int{1, 2, 3},
- }
-
- var result Person
- err := Decode(input, &result)
- if err == nil {
- panic("should have an error")
- }
-
- fmt.Println(err.Error())
- // Output:
- // 5 error(s) decoding:
- //
- // * 'Age' expected type 'int', got unconvertible type 'string'
- // * 'Emails[0]' expected type 'string', got unconvertible type 'int'
- // * 'Emails[1]' expected type 'string', got unconvertible type 'int'
- // * 'Emails[2]' expected type 'string', got unconvertible type 'int'
- // * 'Name' expected type 'string', got unconvertible type 'int'
-}
-
-func ExampleDecode_metadata() {
- type Person struct {
- Name string
- Age int
- }
-
- // This input can come from anywhere, but typically comes from
- // something like decoding JSON where we're not quite sure of the
- // struct initially.
- input := map[string]interface{}{
- "name": "Mitchell",
- "age": 91,
- "email": "foo@bar.com",
- }
-
- // For metadata, we make a more advanced DecoderConfig so we can
- // more finely configure the decoder that is used. In this case, we
- // just tell the decoder we want to track metadata.
- var md Metadata
- var result Person
- config := &DecoderConfig{
- Metadata: &md,
- Result: &result,
- }
-
- decoder, err := NewDecoder(config)
- if err != nil {
- panic(err)
- }
-
- if err := decoder.Decode(input); err != nil {
- panic(err)
- }
-
- fmt.Printf("Unused keys: %#v", md.Unused)
- // Output:
- // Unused keys: []string{"email"}
-}
-
-func ExampleDecode_weaklyTypedInput() {
- type Person struct {
- Name string
- Age int
- Emails []string
- }
-
- // This input can come from anywhere, but typically comes from
- // something like decoding JSON, generated by a weakly typed language
- // such as PHP.
- input := map[string]interface{}{
- "name": 123, // number => string
- "age": "42", // string => number
- "emails": map[string]interface{}{}, // empty map => empty array
- }
-
- var result Person
- config := &DecoderConfig{
- WeaklyTypedInput: true,
- Result: &result,
- }
-
- decoder, err := NewDecoder(config)
- if err != nil {
- panic(err)
- }
-
- err = decoder.Decode(input)
- if err != nil {
- panic(err)
- }
-
- fmt.Printf("%#v", result)
- // Output: mapstructure.Person{Name:"123", Age:42, Emails:[]string{}}
-}
-
-func ExampleDecode_tags() {
- // Note that the mapstructure tags defined in the struct type
- // can indicate which fields the values are mapped to.
- type Person struct {
- Name string `mapstructure:"person_name"`
- Age int `mapstructure:"person_age"`
- }
-
- input := map[string]interface{}{
- "person_name": "Mitchell",
- "person_age": 91,
- }
-
- var result Person
- err := Decode(input, &result)
- if err != nil {
- panic(err)
- }
-
- fmt.Printf("%#v", result)
- // Output:
- // mapstructure.Person{Name:"Mitchell", Age:91}
-}
-
-func ExampleDecode_embeddedStruct() {
- // Squashing multiple embedded structs is allowed using the squash tag.
- // This is demonstrated by creating a composite struct of multiple types
- // and decoding into it. In this case, a person can carry with it both
- // a Family and a Location, as well as their own FirstName.
- type Family struct {
- LastName string
- }
- type Location struct {
- City string
- }
- type Person struct {
- Family `mapstructure:",squash"`
- Location `mapstructure:",squash"`
- FirstName string
- }
-
- input := map[string]interface{}{
- "FirstName": "Mitchell",
- "LastName": "Hashimoto",
- "City": "San Francisco",
- }
-
- var result Person
- err := Decode(input, &result)
- if err != nil {
- panic(err)
- }
-
- fmt.Printf("%s %s, %s", result.FirstName, result.LastName, result.City)
- // Output:
- // Mitchell Hashimoto, San Francisco
-}
diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure_test.go b/vendor/github.com/mitchellh/mapstructure/mapstructure_test.go
deleted file mode 100644
index 547af73..0000000
--- a/vendor/github.com/mitchellh/mapstructure/mapstructure_test.go
+++ /dev/null
@@ -1,1193 +0,0 @@
-package mapstructure
-
-import (
- "encoding/json"
- "io"
- "reflect"
- "sort"
- "strings"
- "testing"
-)
-
-type Basic struct {
- Vstring string
- Vint int
- Vuint uint
- Vbool bool
- Vfloat float64
- Vextra string
- vsilent bool
- Vdata interface{}
- VjsonInt int
- VjsonFloat float64
- VjsonNumber json.Number
-}
-
-type BasicSquash struct {
- Test Basic `mapstructure:",squash"`
-}
-
-type Embedded struct {
- Basic
- Vunique string
-}
-
-type EmbeddedPointer struct {
- *Basic
- Vunique string
-}
-
-type EmbeddedSquash struct {
- Basic `mapstructure:",squash"`
- Vunique string
-}
-
-type SliceAlias []string
-
-type EmbeddedSlice struct {
- SliceAlias `mapstructure:"slice_alias"`
- Vunique string
-}
-
-type SquashOnNonStructType struct {
- InvalidSquashType int `mapstructure:",squash"`
-}
-
-type Map struct {
- Vfoo string
- Vother map[string]string
-}
-
-type MapOfStruct struct {
- Value map[string]Basic
-}
-
-type Nested struct {
- Vfoo string
- Vbar Basic
-}
-
-type NestedPointer struct {
- Vfoo string
- Vbar *Basic
-}
-
-type NilInterface struct {
- W io.Writer
-}
-
-type Slice struct {
- Vfoo string
- Vbar []string
-}
-
-type SliceOfStruct struct {
- Value []Basic
-}
-
-type Func struct {
- Foo func() string
-}
-
-type Tagged struct {
- Extra string `mapstructure:"bar,what,what"`
- Value string `mapstructure:"foo"`
-}
-
-type TypeConversionResult struct {
- IntToFloat float32
- IntToUint uint
- IntToBool bool
- IntToString string
- UintToInt int
- UintToFloat float32
- UintToBool bool
- UintToString string
- BoolToInt int
- BoolToUint uint
- BoolToFloat float32
- BoolToString string
- FloatToInt int
- FloatToUint uint
- FloatToBool bool
- FloatToString string
- SliceUint8ToString string
- StringToInt int
- StringToUint uint
- StringToBool bool
- StringToFloat float32
- StringToStrSlice []string
- StringToIntSlice []int
- SliceToMap map[string]interface{}
- MapToSlice []interface{}
-}
-
-func TestBasicTypes(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "vstring": "foo",
- "vint": 42,
- "Vuint": 42,
- "vbool": true,
- "Vfloat": 42.42,
- "vsilent": true,
- "vdata": 42,
- "vjsonInt": json.Number("1234"),
- "vjsonFloat": json.Number("1234.5"),
- "vjsonNumber": json.Number("1234.5"),
- }
-
- var result Basic
- err := Decode(input, &result)
- if err != nil {
- t.Errorf("got an err: %s", err.Error())
- t.FailNow()
- }
-
- if result.Vstring != "foo" {
- t.Errorf("vstring value should be 'foo': %#v", result.Vstring)
- }
-
- if result.Vint != 42 {
- t.Errorf("vint value should be 42: %#v", result.Vint)
- }
-
- if result.Vuint != 42 {
- t.Errorf("vuint value should be 42: %#v", result.Vuint)
- }
-
- if result.Vbool != true {
- t.Errorf("vbool value should be true: %#v", result.Vbool)
- }
-
- if result.Vfloat != 42.42 {
- t.Errorf("vfloat value should be 42.42: %#v", result.Vfloat)
- }
-
- if result.Vextra != "" {
- t.Errorf("vextra value should be empty: %#v", result.Vextra)
- }
-
- if result.vsilent != false {
- t.Error("vsilent should not be set, it is unexported")
- }
-
- if result.Vdata != 42 {
- t.Error("vdata should be valid")
- }
-
- if result.VjsonInt != 1234 {
- t.Errorf("vjsonint value should be 1234: %#v", result.VjsonInt)
- }
-
- if result.VjsonFloat != 1234.5 {
- t.Errorf("vjsonfloat value should be 1234.5: %#v", result.VjsonFloat)
- }
-
- if !reflect.DeepEqual(result.VjsonNumber, json.Number("1234.5")) {
- t.Errorf("vjsonnumber value should be '1234.5': %T, %#v", result.VjsonNumber, result.VjsonNumber)
- }
-}
-
-func TestBasic_IntWithFloat(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "vint": float64(42),
- }
-
- var result Basic
- err := Decode(input, &result)
- if err != nil {
- t.Fatalf("got an err: %s", err)
- }
-}
-
-func TestBasic_Merge(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "vint": 42,
- }
-
- var result Basic
- result.Vuint = 100
- err := Decode(input, &result)
- if err != nil {
- t.Fatalf("got an err: %s", err)
- }
-
- expected := Basic{
- Vint: 42,
- Vuint: 100,
- }
- if !reflect.DeepEqual(result, expected) {
- t.Fatalf("bad: %#v", result)
- }
-}
-
-func TestDecode_BasicSquash(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "vstring": "foo",
- }
-
- var result BasicSquash
- err := Decode(input, &result)
- if err != nil {
- t.Fatalf("got an err: %s", err.Error())
- }
-
- if result.Test.Vstring != "foo" {
- t.Errorf("vstring value should be 'foo': %#v", result.Test.Vstring)
- }
-}
-
-func TestDecode_Embedded(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "vstring": "foo",
- "Basic": map[string]interface{}{
- "vstring": "innerfoo",
- },
- "vunique": "bar",
- }
-
- var result Embedded
- err := Decode(input, &result)
- if err != nil {
- t.Fatalf("got an err: %s", err.Error())
- }
-
- if result.Vstring != "innerfoo" {
- t.Errorf("vstring value should be 'innerfoo': %#v", result.Vstring)
- }
-
- if result.Vunique != "bar" {
- t.Errorf("vunique value should be 'bar': %#v", result.Vunique)
- }
-}
-
-func TestDecode_EmbeddedPointer(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "vstring": "foo",
- "Basic": map[string]interface{}{
- "vstring": "innerfoo",
- },
- "vunique": "bar",
- }
-
- var result EmbeddedPointer
- err := Decode(input, &result)
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- expected := EmbeddedPointer{
- Basic: &Basic{
- Vstring: "innerfoo",
- },
- Vunique: "bar",
- }
- if !reflect.DeepEqual(result, expected) {
- t.Fatalf("bad: %#v", result)
- }
-}
-
-func TestDecode_EmbeddedSlice(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "slice_alias": []string{"foo", "bar"},
- "vunique": "bar",
- }
-
- var result EmbeddedSlice
- err := Decode(input, &result)
- if err != nil {
- t.Fatalf("got an err: %s", err.Error())
- }
-
- if !reflect.DeepEqual(result.SliceAlias, SliceAlias([]string{"foo", "bar"})) {
- t.Errorf("slice value: %#v", result.SliceAlias)
- }
-
- if result.Vunique != "bar" {
- t.Errorf("vunique value should be 'bar': %#v", result.Vunique)
- }
-}
-
-func TestDecode_EmbeddedSquash(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "vstring": "foo",
- "vunique": "bar",
- }
-
- var result EmbeddedSquash
- err := Decode(input, &result)
- if err != nil {
- t.Fatalf("got an err: %s", err.Error())
- }
-
- if result.Vstring != "foo" {
- t.Errorf("vstring value should be 'foo': %#v", result.Vstring)
- }
-
- if result.Vunique != "bar" {
- t.Errorf("vunique value should be 'bar': %#v", result.Vunique)
- }
-}
-
-func TestDecode_SquashOnNonStructType(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "InvalidSquashType": 42,
- }
-
- var result SquashOnNonStructType
- err := Decode(input, &result)
- if err == nil {
- t.Fatal("unexpected success decoding invalid squash field type")
- } else if !strings.Contains(err.Error(), "unsupported type for squash") {
- t.Fatalf("unexpected error message for invalid squash field type: %s", err)
- }
-}
-
-func TestDecode_DecodeHook(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "vint": "WHAT",
- }
-
- decodeHook := func(from reflect.Kind, to reflect.Kind, v interface{}) (interface{}, error) {
- if from == reflect.String && to != reflect.String {
- return 5, nil
- }
-
- return v, nil
- }
-
- var result Basic
- config := &DecoderConfig{
- DecodeHook: decodeHook,
- Result: &result,
- }
-
- decoder, err := NewDecoder(config)
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- err = decoder.Decode(input)
- if err != nil {
- t.Fatalf("got an err: %s", err)
- }
-
- if result.Vint != 5 {
- t.Errorf("vint should be 5: %#v", result.Vint)
- }
-}
-
-func TestDecode_DecodeHookType(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "vint": "WHAT",
- }
-
- decodeHook := func(from reflect.Type, to reflect.Type, v interface{}) (interface{}, error) {
- if from.Kind() == reflect.String &&
- to.Kind() != reflect.String {
- return 5, nil
- }
-
- return v, nil
- }
-
- var result Basic
- config := &DecoderConfig{
- DecodeHook: decodeHook,
- Result: &result,
- }
-
- decoder, err := NewDecoder(config)
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- err = decoder.Decode(input)
- if err != nil {
- t.Fatalf("got an err: %s", err)
- }
-
- if result.Vint != 5 {
- t.Errorf("vint should be 5: %#v", result.Vint)
- }
-}
-
-func TestDecode_Nil(t *testing.T) {
- t.Parallel()
-
- var input interface{}
- result := Basic{
- Vstring: "foo",
- }
-
- err := Decode(input, &result)
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- if result.Vstring != "foo" {
- t.Fatalf("bad: %#v", result.Vstring)
- }
-}
-
-func TestDecode_NilInterfaceHook(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "w": "",
- }
-
- decodeHook := func(f, t reflect.Type, v interface{}) (interface{}, error) {
- if t.String() == "io.Writer" {
- return nil, nil
- }
-
- return v, nil
- }
-
- var result NilInterface
- config := &DecoderConfig{
- DecodeHook: decodeHook,
- Result: &result,
- }
-
- decoder, err := NewDecoder(config)
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- err = decoder.Decode(input)
- if err != nil {
- t.Fatalf("got an err: %s", err)
- }
-
- if result.W != nil {
- t.Errorf("W should be nil: %#v", result.W)
- }
-}
-
-func TestDecode_FuncHook(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "foo": "baz",
- }
-
- decodeHook := func(f, t reflect.Type, v interface{}) (interface{}, error) {
- if t.Kind() != reflect.Func {
- return v, nil
- }
- val := v.(string)
- return func() string { return val }, nil
- }
-
- var result Func
- config := &DecoderConfig{
- DecodeHook: decodeHook,
- Result: &result,
- }
-
- decoder, err := NewDecoder(config)
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- err = decoder.Decode(input)
- if err != nil {
- t.Fatalf("got an err: %s", err)
- }
-
- if result.Foo() != "baz" {
- t.Errorf("Foo call result should be 'baz': %s", result.Foo())
- }
-}
-
-func TestDecode_NonStruct(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "foo": "bar",
- "bar": "baz",
- }
-
- var result map[string]string
- err := Decode(input, &result)
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- if result["foo"] != "bar" {
- t.Fatal("foo is not bar")
- }
-}
-
-func TestDecode_StructMatch(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "vbar": Basic{
- Vstring: "foo",
- },
- }
-
- var result Nested
- err := Decode(input, &result)
- if err != nil {
- t.Fatalf("got an err: %s", err.Error())
- }
-
- if result.Vbar.Vstring != "foo" {
- t.Errorf("bad: %#v", result)
- }
-}
-
-func TestDecode_TypeConversion(t *testing.T) {
- input := map[string]interface{}{
- "IntToFloat": 42,
- "IntToUint": 42,
- "IntToBool": 1,
- "IntToString": 42,
- "UintToInt": 42,
- "UintToFloat": 42,
- "UintToBool": 42,
- "UintToString": 42,
- "BoolToInt": true,
- "BoolToUint": true,
- "BoolToFloat": true,
- "BoolToString": true,
- "FloatToInt": 42.42,
- "FloatToUint": 42.42,
- "FloatToBool": 42.42,
- "FloatToString": 42.42,
- "SliceUint8ToString": []uint8("foo"),
- "StringToInt": "42",
- "StringToUint": "42",
- "StringToBool": "1",
- "StringToFloat": "42.42",
- "StringToStrSlice": "A",
- "StringToIntSlice": "42",
- "SliceToMap": []interface{}{},
- "MapToSlice": map[string]interface{}{},
- }
-
- expectedResultStrict := TypeConversionResult{
- IntToFloat: 42.0,
- IntToUint: 42,
- UintToInt: 42,
- UintToFloat: 42,
- BoolToInt: 0,
- BoolToUint: 0,
- BoolToFloat: 0,
- FloatToInt: 42,
- FloatToUint: 42,
- }
-
- expectedResultWeak := TypeConversionResult{
- IntToFloat: 42.0,
- IntToUint: 42,
- IntToBool: true,
- IntToString: "42",
- UintToInt: 42,
- UintToFloat: 42,
- UintToBool: true,
- UintToString: "42",
- BoolToInt: 1,
- BoolToUint: 1,
- BoolToFloat: 1,
- BoolToString: "1",
- FloatToInt: 42,
- FloatToUint: 42,
- FloatToBool: true,
- FloatToString: "42.42",
- SliceUint8ToString: "foo",
- StringToInt: 42,
- StringToUint: 42,
- StringToBool: true,
- StringToFloat: 42.42,
- StringToStrSlice: []string{"A"},
- StringToIntSlice: []int{42},
- SliceToMap: map[string]interface{}{},
- MapToSlice: []interface{}{},
- }
-
- // Test strict type conversion
- var resultStrict TypeConversionResult
- err := Decode(input, &resultStrict)
- if err == nil {
- t.Errorf("should return an error")
- }
- if !reflect.DeepEqual(resultStrict, expectedResultStrict) {
- t.Errorf("expected %v, got: %v", expectedResultStrict, resultStrict)
- }
-
- // Test weak type conversion
- var decoder *Decoder
- var resultWeak TypeConversionResult
-
- config := &DecoderConfig{
- WeaklyTypedInput: true,
- Result: &resultWeak,
- }
-
- decoder, err = NewDecoder(config)
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- err = decoder.Decode(input)
- if err != nil {
- t.Fatalf("got an err: %s", err)
- }
-
- if !reflect.DeepEqual(resultWeak, expectedResultWeak) {
- t.Errorf("expected \n%#v, got: \n%#v", expectedResultWeak, resultWeak)
- }
-}
-
-func TestDecoder_ErrorUnused(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "vstring": "hello",
- "foo": "bar",
- }
-
- var result Basic
- config := &DecoderConfig{
- ErrorUnused: true,
- Result: &result,
- }
-
- decoder, err := NewDecoder(config)
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- err = decoder.Decode(input)
- if err == nil {
- t.Fatal("expected error")
- }
-}
-
-func TestMap(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "vfoo": "foo",
- "vother": map[interface{}]interface{}{
- "foo": "foo",
- "bar": "bar",
- },
- }
-
- var result Map
- err := Decode(input, &result)
- if err != nil {
- t.Fatalf("got an error: %s", err)
- }
-
- if result.Vfoo != "foo" {
- t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo)
- }
-
- if result.Vother == nil {
- t.Fatal("vother should not be nil")
- }
-
- if len(result.Vother) != 2 {
- t.Error("vother should have two items")
- }
-
- if result.Vother["foo"] != "foo" {
- t.Errorf("'foo' key should be foo, got: %#v", result.Vother["foo"])
- }
-
- if result.Vother["bar"] != "bar" {
- t.Errorf("'bar' key should be bar, got: %#v", result.Vother["bar"])
- }
-}
-
-func TestMapMerge(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "vfoo": "foo",
- "vother": map[interface{}]interface{}{
- "foo": "foo",
- "bar": "bar",
- },
- }
-
- var result Map
- result.Vother = map[string]string{"hello": "world"}
- err := Decode(input, &result)
- if err != nil {
- t.Fatalf("got an error: %s", err)
- }
-
- if result.Vfoo != "foo" {
- t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo)
- }
-
- expected := map[string]string{
- "foo": "foo",
- "bar": "bar",
- "hello": "world",
- }
- if !reflect.DeepEqual(result.Vother, expected) {
- t.Errorf("bad: %#v", result.Vother)
- }
-}
-
-func TestMapOfStruct(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "value": map[string]interface{}{
- "foo": map[string]string{"vstring": "one"},
- "bar": map[string]string{"vstring": "two"},
- },
- }
-
- var result MapOfStruct
- err := Decode(input, &result)
- if err != nil {
- t.Fatalf("got an err: %s", err)
- }
-
- if result.Value == nil {
- t.Fatal("value should not be nil")
- }
-
- if len(result.Value) != 2 {
- t.Error("value should have two items")
- }
-
- if result.Value["foo"].Vstring != "one" {
- t.Errorf("foo value should be 'one', got: %s", result.Value["foo"].Vstring)
- }
-
- if result.Value["bar"].Vstring != "two" {
- t.Errorf("bar value should be 'two', got: %s", result.Value["bar"].Vstring)
- }
-}
-
-func TestNestedType(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "vfoo": "foo",
- "vbar": map[string]interface{}{
- "vstring": "foo",
- "vint": 42,
- "vbool": true,
- },
- }
-
- var result Nested
- err := Decode(input, &result)
- if err != nil {
- t.Fatalf("got an err: %s", err.Error())
- }
-
- if result.Vfoo != "foo" {
- t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo)
- }
-
- if result.Vbar.Vstring != "foo" {
- t.Errorf("vstring value should be 'foo': %#v", result.Vbar.Vstring)
- }
-
- if result.Vbar.Vint != 42 {
- t.Errorf("vint value should be 42: %#v", result.Vbar.Vint)
- }
-
- if result.Vbar.Vbool != true {
- t.Errorf("vbool value should be true: %#v", result.Vbar.Vbool)
- }
-
- if result.Vbar.Vextra != "" {
- t.Errorf("vextra value should be empty: %#v", result.Vbar.Vextra)
- }
-}
-
-func TestNestedTypePointer(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "vfoo": "foo",
- "vbar": &map[string]interface{}{
- "vstring": "foo",
- "vint": 42,
- "vbool": true,
- },
- }
-
- var result NestedPointer
- err := Decode(input, &result)
- if err != nil {
- t.Fatalf("got an err: %s", err.Error())
- }
-
- if result.Vfoo != "foo" {
- t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo)
- }
-
- if result.Vbar.Vstring != "foo" {
- t.Errorf("vstring value should be 'foo': %#v", result.Vbar.Vstring)
- }
-
- if result.Vbar.Vint != 42 {
- t.Errorf("vint value should be 42: %#v", result.Vbar.Vint)
- }
-
- if result.Vbar.Vbool != true {
- t.Errorf("vbool value should be true: %#v", result.Vbar.Vbool)
- }
-
- if result.Vbar.Vextra != "" {
- t.Errorf("vextra value should be empty: %#v", result.Vbar.Vextra)
- }
-}
-
-func TestSlice(t *testing.T) {
- t.Parallel()
-
- inputStringSlice := map[string]interface{}{
- "vfoo": "foo",
- "vbar": []string{"foo", "bar", "baz"},
- }
-
- inputStringSlicePointer := map[string]interface{}{
- "vfoo": "foo",
- "vbar": &[]string{"foo", "bar", "baz"},
- }
-
- outputStringSlice := &Slice{
- "foo",
- []string{"foo", "bar", "baz"},
- }
-
- testSliceInput(t, inputStringSlice, outputStringSlice)
- testSliceInput(t, inputStringSlicePointer, outputStringSlice)
-}
-
-func TestInvalidSlice(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "vfoo": "foo",
- "vbar": 42,
- }
-
- result := Slice{}
- err := Decode(input, &result)
- if err == nil {
- t.Errorf("expected failure")
- }
-}
-
-func TestSliceOfStruct(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "value": []map[string]interface{}{
- {"vstring": "one"},
- {"vstring": "two"},
- },
- }
-
- var result SliceOfStruct
- err := Decode(input, &result)
- if err != nil {
- t.Fatalf("got unexpected error: %s", err)
- }
-
- if len(result.Value) != 2 {
- t.Fatalf("expected two values, got %d", len(result.Value))
- }
-
- if result.Value[0].Vstring != "one" {
- t.Errorf("first value should be 'one', got: %s", result.Value[0].Vstring)
- }
-
- if result.Value[1].Vstring != "two" {
- t.Errorf("second value should be 'two', got: %s", result.Value[1].Vstring)
- }
-}
-
-func TestSliceToMap(t *testing.T) {
- t.Parallel()
-
- input := []map[string]interface{}{
- {
- "foo": "bar",
- },
- {
- "bar": "baz",
- },
- }
-
- var result map[string]interface{}
- err := WeakDecode(input, &result)
- if err != nil {
- t.Fatalf("got an error: %s", err)
- }
-
- expected := map[string]interface{}{
- "foo": "bar",
- "bar": "baz",
- }
- if !reflect.DeepEqual(result, expected) {
- t.Errorf("bad: %#v", result)
- }
-}
-
-func TestInvalidType(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "vstring": 42,
- }
-
- var result Basic
- err := Decode(input, &result)
- if err == nil {
- t.Fatal("error should exist")
- }
-
- derr, ok := err.(*Error)
- if !ok {
- t.Fatalf("error should be kind of Error, instead: %#v", err)
- }
-
- if derr.Errors[0] != "'Vstring' expected type 'string', got unconvertible type 'int'" {
- t.Errorf("got unexpected error: %s", err)
- }
-
- inputNegIntUint := map[string]interface{}{
- "vuint": -42,
- }
-
- err = Decode(inputNegIntUint, &result)
- if err == nil {
- t.Fatal("error should exist")
- }
-
- derr, ok = err.(*Error)
- if !ok {
- t.Fatalf("error should be kind of Error, instead: %#v", err)
- }
-
- if derr.Errors[0] != "cannot parse 'Vuint', -42 overflows uint" {
- t.Errorf("got unexpected error: %s", err)
- }
-
- inputNegFloatUint := map[string]interface{}{
- "vuint": -42.0,
- }
-
- err = Decode(inputNegFloatUint, &result)
- if err == nil {
- t.Fatal("error should exist")
- }
-
- derr, ok = err.(*Error)
- if !ok {
- t.Fatalf("error should be kind of Error, instead: %#v", err)
- }
-
- if derr.Errors[0] != "cannot parse 'Vuint', -42.000000 overflows uint" {
- t.Errorf("got unexpected error: %s", err)
- }
-}
-
-func TestMetadata(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "vfoo": "foo",
- "vbar": map[string]interface{}{
- "vstring": "foo",
- "Vuint": 42,
- "foo": "bar",
- },
- "bar": "nil",
- }
-
- var md Metadata
- var result Nested
- config := &DecoderConfig{
- Metadata: &md,
- Result: &result,
- }
-
- decoder, err := NewDecoder(config)
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- err = decoder.Decode(input)
- if err != nil {
- t.Fatalf("err: %s", err.Error())
- }
-
- expectedKeys := []string{"Vbar", "Vbar.Vstring", "Vbar.Vuint", "Vfoo"}
- sort.Strings(md.Keys)
- if !reflect.DeepEqual(md.Keys, expectedKeys) {
- t.Fatalf("bad keys: %#v", md.Keys)
- }
-
- expectedUnused := []string{"Vbar.foo", "bar"}
- if !reflect.DeepEqual(md.Unused, expectedUnused) {
- t.Fatalf("bad unused: %#v", md.Unused)
- }
-}
-
-func TestMetadata_Embedded(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "vstring": "foo",
- "vunique": "bar",
- }
-
- var md Metadata
- var result EmbeddedSquash
- config := &DecoderConfig{
- Metadata: &md,
- Result: &result,
- }
-
- decoder, err := NewDecoder(config)
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- err = decoder.Decode(input)
- if err != nil {
- t.Fatalf("err: %s", err.Error())
- }
-
- expectedKeys := []string{"Vstring", "Vunique"}
-
- sort.Strings(md.Keys)
- if !reflect.DeepEqual(md.Keys, expectedKeys) {
- t.Fatalf("bad keys: %#v", md.Keys)
- }
-
- expectedUnused := []string{}
- if !reflect.DeepEqual(md.Unused, expectedUnused) {
- t.Fatalf("bad unused: %#v", md.Unused)
- }
-}
-
-func TestNonPtrValue(t *testing.T) {
- t.Parallel()
-
- err := Decode(map[string]interface{}{}, Basic{})
- if err == nil {
- t.Fatal("error should exist")
- }
-
- if err.Error() != "result must be a pointer" {
- t.Errorf("got unexpected error: %s", err)
- }
-}
-
-func TestTagged(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "foo": "bar",
- "bar": "value",
- }
-
- var result Tagged
- err := Decode(input, &result)
- if err != nil {
- t.Fatalf("unexpected error: %s", err)
- }
-
- if result.Value != "bar" {
- t.Errorf("value should be 'bar', got: %#v", result.Value)
- }
-
- if result.Extra != "value" {
- t.Errorf("extra should be 'value', got: %#v", result.Extra)
- }
-}
-
-func TestWeakDecode(t *testing.T) {
- t.Parallel()
-
- input := map[string]interface{}{
- "foo": "4",
- "bar": "value",
- }
-
- var result struct {
- Foo int
- Bar string
- }
-
- if err := WeakDecode(input, &result); err != nil {
- t.Fatalf("err: %s", err)
- }
- if result.Foo != 4 {
- t.Fatalf("bad: %#v", result)
- }
- if result.Bar != "value" {
- t.Fatalf("bad: %#v", result)
- }
-}
-
-func testSliceInput(t *testing.T, input map[string]interface{}, expected *Slice) {
- var result Slice
- err := Decode(input, &result)
- if err != nil {
- t.Fatalf("got error: %s", err)
- }
-
- if result.Vfoo != expected.Vfoo {
- t.Errorf("Vfoo expected '%s', got '%s'", expected.Vfoo, result.Vfoo)
- }
-
- if result.Vbar == nil {
- t.Fatalf("Vbar a slice, got '%#v'", result.Vbar)
- }
-
- if len(result.Vbar) != len(expected.Vbar) {
- t.Errorf("Vbar length should be %d, got %d", len(expected.Vbar), len(result.Vbar))
- }
-
- for i, v := range result.Vbar {
- if v != expected.Vbar[i] {
- t.Errorf(
- "Vbar[%d] should be '%#v', got '%#v'",
- i, expected.Vbar[i], v)
- }
- }
-}
diff --git a/vendor/github.com/mssola/user_agent/.travis.yml b/vendor/github.com/mssola/user_agent/.travis.yml
deleted file mode 100644
index add0c8a..0000000
--- a/vendor/github.com/mssola/user_agent/.travis.yml
+++ /dev/null
@@ -1,10 +0,0 @@
-language: go
-go:
- - 1.0
- - 1.1
- - 1.2
- - 1.3
- - tip
-matrix:
- allow_failures:
- - go: tip
diff --git a/vendor/github.com/mssola/user_agent/LICENSE b/vendor/github.com/mssola/user_agent/LICENSE
deleted file mode 100644
index c02b644..0000000
--- a/vendor/github.com/mssola/user_agent/LICENSE
+++ /dev/null
@@ -1,20 +0,0 @@
-Copyright (c) 2012-2014 Miquel Sabaté Solà
-
-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.
diff --git a/vendor/github.com/mssola/user_agent/README.md b/vendor/github.com/mssola/user_agent/README.md
deleted file mode 100644
index 9719025..0000000
--- a/vendor/github.com/mssola/user_agent/README.md
+++ /dev/null
@@ -1,51 +0,0 @@
-
-# UserAgent [](https://travis-ci.org/mssola/user_agent) [](http://godoc.org/github.com/mssola/user_agent)
-
-
-UserAgent is a Go library that parses HTTP User Agents.
-
-## Usage
-
-~~~ go
-package main
-
-import (
- "fmt"
-
- "github.com/mssola/user_agent"
-)
-
-func main() {
- // The "New" function will create a new UserAgent object and it will parse
- // the given string. If you need to parse more strings, you can re-use
- // this object and call: ua.Parse("another string")
- ua := user_agent.New("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11");
-
- fmt.Printf("%v\n", ua.Mobile()) // => false
- fmt.Printf("%v\n", ua.Bot()) // => false
- fmt.Printf("%v\n", ua.Mozilla()) // => "5.0"
-
- fmt.Printf("%v\n", ua.Platform()) // => "X11"
- fmt.Printf("%v\n", ua.OS()) // => "Linux x86_64"
-
- name, version := ua.Engine()
- fmt.Printf("%v\n", name) // => "AppleWebKit"
- fmt.Printf("%v\n", version) // => "537.11"
-
- name, version = ua.Browser()
- fmt.Printf("%v\n", name) // => "Chrome"
- fmt.Printf("%v\n", version) // => "23.0.1271.97"
-
- // Let's see an example with a bot.
-
- ua.Parse("Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)")
-
- fmt.Printf("%v\n", ua.Bot()) // => true
-
- name, version = ua.Browser()
- fmt.Printf("%v\n", name) // => Googlebot
- fmt.Printf("%v\n", version) // => 2.1
-}
-~~~
-
-Copyright © 2012-2014 Miquel Sabaté Solà, released under the MIT License.
diff --git a/vendor/github.com/mssola/user_agent/all_test.go b/vendor/github.com/mssola/user_agent/all_test.go
deleted file mode 100644
index 4f3c031..0000000
--- a/vendor/github.com/mssola/user_agent/all_test.go
+++ /dev/null
@@ -1,257 +0,0 @@
-// Copyright (C) 2012-2014 Miquel Sabaté Solà
-// This file is licensed under the MIT license.
-// See the LICENSE file.
-
-package user_agent
-
-import (
- "fmt"
- "testing"
-)
-
-// Slice that contains all the tests. Each test is contained in a struct
-// that groups the name of the test and the User-Agent string to be tested.
-var uastrings = []struct {
- name string
- ua string
-}{
- // Bots
- {"GoogleBot", "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"},
- {"GoogleBotSmartphone", "Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"},
- {"BingBot", "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)"},
- {"BaiduBot", "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)"},
- {"Twitterbot", "Twitterbot"},
- {"YahooBot", "Mozilla/5.0 (compatible; Yahoo! Slurp; http://help.yahoo.com/help/us/ysearch/slurp)"},
- {"FacebookExternalHit", "facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)"},
- {"FacebookPlatform", "facebookplatform/1.0 (+http://developers.facebook.com)"},
- {"FaceBot", "Facebot"},
-
- // Internet Explorer
- {"IE10", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)"},
- {"Tablet", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.2; ARM; Trident/6.0; Touch; .NET4.0E; .NET4.0C; Tablet PC 2.0)"},
- {"Touch", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; ARM; Trident/6.0; Touch)"},
- {"Phone", "Mozilla/4.0 (compatible; MSIE 7.0; Windows Phone OS 7.0; Trident/3.1; IEMobile/7.0; SAMSUNG; SGH-i917)"},
- {"IE6", "Mozilla/4.0 (compatible; MSIE6.0; Windows NT 5.0; .NET CLR 1.1.4322)"},
- {"IE8Compatibility", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; MS-RTC LM 8)"},
- {"IE10Compatibility", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; MS-RTC LM 8)"},
- {"IE11Win81", "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko"},
- {"IE11Win7", "Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko"},
- {"IE11b32Win7b64", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"},
- {"IE11b32Win7b64MDDRJS", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; MDDRJS; rv:11.0) like Gecko"},
- {"IE11Compatibility", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.3; Trident/7.0)"},
-
- // Gecko
- {"FirefoxMac", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0b8) Gecko/20100101 Firefox/4.0b8"},
- {"FirefoxMacLoc", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13"},
- {"FirefoxLinux", "Mozilla/5.0 (X11; Linux x86_64; rv:17.0) Gecko/20100101 Firefox/17.0"},
- {"FirefoxWin", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14"},
- {"Firefox29Win7", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"},
- {"CaminoMac", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en; rv:1.8.1.14) Gecko/20080409 Camino/1.6 (like Firefox/2.0.0.14)"},
- {"Iceweasel", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1) Gecko/20061024 Iceweasel/2.0 (Debian-2.0+dfsg-1)"},
- {"SeaMonkey", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.1.4) Gecko/20091017 SeaMonkey/2.0"},
- {"AndroidFirefox", "Mozilla/5.0 (Android; Mobile; rv:17.0) Gecko/17.0 Firefox/17.0"},
- {"AndroidFirefoxTablet", "Mozilla/5.0 (Android; Tablet; rv:26.0) Gecko/26.0 Firefox/26.0"},
- {"FirefoxOS", "Mozilla/5.0 (Mobile; rv:26.0) Gecko/26.0 Firefox/26.0"},
- {"FirefoxOSTablet", "Mozilla/5.0 (Tablet; rv:26.0) Gecko/26.0 Firefox/26.0"},
- {"FirefoxWinXP", "Mozilla/5.0 (Windows NT 5.2; rv:31.0) Gecko/20100101 Firefox/31.0"},
- {"FirefoxMRA", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:24.0) Gecko/20130405 MRA 5.5 (build 02842) Firefox/24.0 (.NET CLR 3.5.30729)"},
-
- // Opera
- {"OperaMac", "Opera/9.27 (Macintosh; Intel Mac OS X; U; en)"},
- {"OperaWin", "Opera/9.27 (Windows NT 5.1; U; en)"},
- {"OperaWinNoLocale", "Opera/9.80 (Windows NT 5.1) Presto/2.12.388 Version/12.10"},
- {"OperaWin2Comment", "Opera/9.80 (Windows NT 6.0; WOW64) Presto/2.12.388 Version/12.15"},
- {"OperaMinimal", "Opera/9.80"},
- {"OperaFull", "Opera/9.80 (Windows NT 6.0; U; en) Presto/2.2.15 Version/10.10"},
- {"OperaLinux", "Opera/9.80 (X11; Linux x86_64) Presto/2.12.388 Version/12.10"},
- {"OperaAndroid", "Opera/9.80 (Android 4.2.1; Linux; Opera Mobi/ADR-1212030829) Presto/2.11.355 Version/12.10"},
- {"OperaNested", "Opera/9.80 (Windows NT 5.1; MRA 6.0 (build 5831)) Presto/2.12.388 Version/12.10"},
- {"OperaMRA", "Opera/9.80 (Windows NT 6.1; U; MRA 5.8 (build 4139); en) Presto/2.9.168 Version/11.50"},
-
- // Other
- {"Empty", ""},
- {"Nil", "nil"},
- {"Compatible", "Mozilla/4.0 (compatible)"},
- {"Mozilla", "Mozilla/5.0"},
- {"Amaya", "amaya/9.51 libwww/5.4.0"},
- {"Rails", "Rails Testing"},
- {"Python", "Python-urllib/2.7"},
- {"Curl", "curl/7.28.1"},
-
- // WebKit
- {"ChromeLinux", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11"},
- {"ChromeWin7", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19"},
- {"ChromeMinimal", "Mozilla/5.0 AppleWebKit/534.10 Chrome/8.0.552.215 Safari/534.10"},
- {"ChromeMac", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.231 Safari/534.10"},
- {"SafariMac", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16"},
- {"SafariWin", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en) AppleWebKit/526.9 (KHTML, like Gecko) Version/4.0dp1 Safari/526.8"},
- {"iPhone7", "Mozilla/5.0 (iPhone; CPU iPhone OS 7_0_3 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11B511 Safari/9537.53"},
- {"iPhone", "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/4A102 Safari/419"},
- {"iPod", "Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/4A102 Safari/419"},
- {"iPad", "Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B367 Safari/531.21.10"},
- {"webOS", "Mozilla/5.0 (webOS/1.4.0; U; en-US) AppleWebKit/532.2 (KHTML, like Gecko) Version/1.0 Safari/532.2 Pre/1.1"},
- {"Android", "Mozilla/5.0 (Linux; U; Android 1.5; de-; HTC Magic Build/PLAT-RC33) AppleWebKit/528.5+ (KHTML, like Gecko) Version/3.1.2 Mobile Safari/525.20.1"},
- {"BlackBerry", "Mozilla/5.0 (BlackBerry; U; BlackBerry 9800; en) AppleWebKit/534.1+ (KHTML, Like Gecko) Version/6.0.0.141 Mobile Safari/534.1+"},
- {"BB10", "Mozilla/5.0 (BB10; Touch) AppleWebKit/537.3+ (KHTML, like Gecko) Version/10.0.9.388 Mobile Safari/537.3+"},
- {"Ericsson", "Mozilla/5.0 (SymbianOS/9.4; U; Series60/5.0 Profile/MIDP-2.1 Configuration/CLDC-1.1) AppleWebKit/525 (KHTML, like Gecko) Version/3.0 Safari/525"},
- {"ChromeAndroid", "Mozilla/5.0 (Linux; Android 4.2.1; Galaxy Nexus Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19"},
- {"WebkitNoPlatform", "Mozilla/5.0 (en-us) AppleWebKit/525.13 (KHTML, like Gecko; Google Web Preview) Version/3.1 Safari/525.13"},
- {"OperaWebkitMobile", "Mozilla/5.0 (Linux; Android 4.2.2; Galaxy Nexus Build/JDQ39) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.58 Mobile Safari/537.31 OPR/14.0.1074.57453"},
- {"OperaWebkitDesktop", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.58 Safari/537.31 OPR/14.0.1074.57453"},
- {"ChromeNothingAfterU", "Mozilla/5.0 (Linux; U) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4"},
- {"SafariOnSymbian", "Mozilla/5.0 (SymbianOS/9.1; U; [en-us]) AppleWebKit/413 (KHTML, like Gecko) Safari/413"},
-}
-
-// Slice of the expected results from the previous slice.
-var expected = []string{
- // Bots
- "Mozilla:5.0 Browser:Googlebot-2.1 Bot:true Mobile:false",
- "Mozilla:5.0 Browser:Googlebot-2.1 Bot:true Mobile:true",
- "Mozilla:5.0 Browser:bingbot-2.0 Bot:true Mobile:false",
- "Mozilla:5.0 Browser:Baiduspider-2.0 Bot:true Mobile:false",
- "Browser:Twitterbot Bot:true Mobile:false",
- "Mozilla:5.0 Browser:Yahoo! Slurp Bot:true Mobile:false",
- "Browser:facebookexternalhit-1.1 Bot:true Mobile:false",
- "Browser:facebookplatform-1.0 Bot:true Mobile:false",
- "Browser:Facebot Bot:true Mobile:false",
-
- // Internet Explorer
- "Mozilla:5.0 Platform:Windows OS:Windows 8 Browser:Internet Explorer-10.0 Engine:Trident Bot:false Mobile:false",
- "Mozilla:4.0 Platform:Windows OS:Windows 8 Browser:Internet Explorer-10.0 Engine:Trident Bot:false Mobile:false",
- "Mozilla:5.0 Platform:Windows OS:Windows 8 Browser:Internet Explorer-10.0 Engine:Trident Bot:false Mobile:false",
- "Mozilla:4.0 Platform:Windows OS:Windows Phone OS 7.0 Browser:Internet Explorer-7.0 Engine:Trident Bot:false Mobile:true",
- "Mozilla:4.0 Platform:Windows OS:Windows 2000 Browser:Internet Explorer-6.0 Engine:Trident Bot:false Mobile:false",
- "Mozilla:4.0 Platform:Windows OS:Windows 7 Browser:Internet Explorer-8.0 Engine:Trident Bot:false Mobile:false",
- "Mozilla:4.0 Platform:Windows OS:Windows 7 Browser:Internet Explorer-10.0 Engine:Trident Bot:false Mobile:false",
- "Mozilla:5.0 Platform:Windows OS:Windows 8.1 Browser:Internet Explorer-11.0 Engine:Trident Bot:false Mobile:false",
- "Mozilla:5.0 Platform:Windows OS:Windows 7 Browser:Internet Explorer-11.0 Engine:Trident Bot:false Mobile:false",
- "Mozilla:5.0 Platform:Windows OS:Windows 7 Browser:Internet Explorer-11.0 Engine:Trident Bot:false Mobile:false",
- "Mozilla:5.0 Platform:Windows OS:Windows 7 Browser:Internet Explorer-11.0 Engine:Trident Bot:false Mobile:false",
- "Mozilla:4.0 Platform:Windows OS:Windows 8.1 Browser:Internet Explorer-7.0 Engine:Trident Bot:false Mobile:false",
-
- // Gecko
- "Mozilla:5.0 Platform:Macintosh OS:Intel Mac OS X 10.6 Browser:Firefox-4.0b8 Engine:Gecko-20100101 Bot:false Mobile:false",
- "Mozilla:5.0 Platform:Macintosh OS:Intel Mac OS X 10.6 Localization:en-US Browser:Firefox-3.6.13 Engine:Gecko-20101203 Bot:false Mobile:false",
- "Mozilla:5.0 Platform:X11 OS:Linux x86_64 Browser:Firefox-17.0 Engine:Gecko-20100101 Bot:false Mobile:false",
- "Mozilla:5.0 Platform:Windows OS:Windows XP Localization:en-US Browser:Firefox-2.0.0.14 Engine:Gecko-20080404 Bot:false Mobile:false",
- "Mozilla:5.0 Platform:Windows OS:Windows 7 Browser:Firefox-29.0 Engine:Gecko-20100101 Bot:false Mobile:false",
- "Mozilla:5.0 Platform:Macintosh OS:Intel Mac OS X Localization:en Browser:Camino-1.6 Engine:Gecko-20080409 Bot:false Mobile:false",
- "Mozilla:5.0 Platform:X11 OS:Linux i686 Localization:en-US Browser:Iceweasel-2.0 Engine:Gecko-20061024 Bot:false Mobile:false",
- "Mozilla:5.0 Platform:Macintosh OS:Intel Mac OS X 10.6 Localization:en-US Browser:SeaMonkey-2.0 Engine:Gecko-20091017 Bot:false Mobile:false",
- "Mozilla:5.0 Platform:Mobile OS:Android Browser:Firefox-17.0 Engine:Gecko-17.0 Bot:false Mobile:true",
- "Mozilla:5.0 Platform:Tablet OS:Android Browser:Firefox-26.0 Engine:Gecko-26.0 Bot:false Mobile:true",
- "Mozilla:5.0 Platform:Mobile OS:FirefoxOS Browser:Firefox-26.0 Engine:Gecko-26.0 Bot:false Mobile:true",
- "Mozilla:5.0 Platform:Tablet OS:FirefoxOS Browser:Firefox-26.0 Engine:Gecko-26.0 Bot:false Mobile:true",
- "Mozilla:5.0 Platform:Windows OS:Windows XP x64 Edition Browser:Firefox-31.0 Engine:Gecko-20100101 Bot:false Mobile:false",
- "Mozilla:5.0 Platform:Windows OS:Windows XP Localization:en-US Browser:Firefox-24.0 Engine:Gecko-20130405 Bot:false Mobile:false",
-
- // Opera
- "Platform:Macintosh OS:Intel Mac OS X Localization:en Browser:Opera-9.27 Engine:Presto Bot:false Mobile:false",
- "Platform:Windows OS:Windows XP Localization:en Browser:Opera-9.27 Engine:Presto Bot:false Mobile:false",
- "Platform:Windows OS:Windows XP Browser:Opera-9.80 Engine:Presto-2.12.388 Bot:false Mobile:false",
- "Platform:Windows OS:Windows Vista Browser:Opera-9.80 Engine:Presto-2.12.388 Bot:false Mobile:false",
- "Browser:Opera-9.80 Engine:Presto Bot:false Mobile:false",
- "Platform:Windows OS:Windows Vista Localization:en Browser:Opera-9.80 Engine:Presto-2.2.15 Bot:false Mobile:false",
- "Platform:X11 OS:Linux x86_64 Browser:Opera-9.80 Engine:Presto-2.12.388 Bot:false Mobile:false",
- "Platform:Android 4.2.1 OS:Linux Browser:Opera-9.80 Engine:Presto-2.11.355 Bot:false Mobile:true",
- "Platform:Windows OS:Windows XP Browser:Opera-9.80 Engine:Presto-2.12.388 Bot:false Mobile:false",
- "Platform:Windows OS:Windows 7 Localization:en Browser:Opera-9.80 Engine:Presto-2.9.168 Bot:false Mobile:false",
-
- // Other
- "Bot:false Mobile:false",
- "Browser:nil Bot:false Mobile:false",
- "Browser:Mozilla-4.0 Bot:false Mobile:false",
- "Browser:Mozilla-5.0 Bot:false Mobile:false",
- "Browser:amaya-9.51 Engine:libwww-5.4.0 Bot:false Mobile:false",
- "Browser:Rails Engine:Testing Bot:false Mobile:false",
- "Browser:Python-urllib-2.7 Bot:false Mobile:false",
- "Browser:curl-7.28.1 Bot:false Mobile:false",
-
- // WebKit
- "Mozilla:5.0 Platform:X11 OS:Linux x86_64 Browser:Chrome-23.0.1271.97 Engine:AppleWebKit-537.11 Bot:false Mobile:false",
- "Mozilla:5.0 Platform:Windows OS:Windows 7 Browser:Chrome-18.0.1025.168 Engine:AppleWebKit-535.19 Bot:false Mobile:false",
- "Mozilla:5.0 Browser:Chrome-8.0.552.215 Engine:AppleWebKit-534.10 Bot:false Mobile:false",
- "Mozilla:5.0 Platform:Macintosh OS:Intel Mac OS X 10_6_5 Localization:en-US Browser:Chrome-8.0.552.231 Engine:AppleWebKit-534.10 Bot:false Mobile:false",
- "Mozilla:5.0 Platform:Macintosh OS:Intel Mac OS X 10_6_3 Localization:en-us Browser:Safari-5.0 Engine:AppleWebKit-533.16 Bot:false Mobile:false",
- "Mozilla:5.0 Platform:Windows OS:Windows XP Localization:en Browser:Safari-4.0dp1 Engine:AppleWebKit-526.9 Bot:false Mobile:false",
- "Mozilla:5.0 Platform:iPhone OS:CPU iPhone OS 7_0_3 like Mac OS X Browser:Safari-7.0 Engine:AppleWebKit-537.51.1 Bot:false Mobile:true",
- "Mozilla:5.0 Platform:iPhone OS:CPU like Mac OS X Localization:en Browser:Safari-3.0 Engine:AppleWebKit-420.1 Bot:false Mobile:true",
- "Mozilla:5.0 Platform:iPod OS:CPU like Mac OS X Localization:en Browser:Safari-3.0 Engine:AppleWebKit-420.1 Bot:false Mobile:true",
- "Mozilla:5.0 Platform:iPad OS:CPU OS 3_2 like Mac OS X Localization:en-us Browser:Safari-4.0.4 Engine:AppleWebKit-531.21.10 Bot:false Mobile:true",
- "Mozilla:5.0 Platform:webOS OS:Palm Localization:en-US Browser:webOS-1.0 Engine:AppleWebKit-532.2 Bot:false Mobile:true",
- "Mozilla:5.0 Platform:Linux OS:Android 1.5 Localization:de- Browser:Android-3.1.2 Engine:AppleWebKit-528.5+ Bot:false Mobile:true",
- "Mozilla:5.0 Platform:BlackBerry OS:BlackBerry 9800 Localization:en Browser:BlackBerry-6.0.0.141 Engine:AppleWebKit-534.1+ Bot:false Mobile:true",
- "Mozilla:5.0 Platform:BlackBerry OS:BlackBerry Browser:BlackBerry-10.0.9.388 Engine:AppleWebKit-537.3+ Bot:false Mobile:true",
- "Mozilla:5.0 Platform:Symbian OS:SymbianOS/9.4 Browser:Symbian-3.0 Engine:AppleWebKit-525 Bot:false Mobile:true",
- "Mozilla:5.0 Platform:Linux OS:Android 4.2.1 Browser:Chrome-18.0.1025.166 Engine:AppleWebKit-535.19 Bot:false Mobile:true",
- "Mozilla:5.0 Platform:en-us Localization:en-us Browser:Safari-3.1 Engine:AppleWebKit-525.13 Bot:false Mobile:false",
- "Mozilla:5.0 Platform:Linux OS:Android 4.2.2 Browser:Opera-14.0.1074.57453 Engine:AppleWebKit-537.31 Bot:false Mobile:true",
- "Mozilla:5.0 Platform:X11 OS:Linux x86_64 Browser:Opera-14.0.1074.57453 Engine:AppleWebKit-537.31 Bot:false Mobile:false",
- "Mozilla:5.0 Platform:Linux OS:Linux Browser:Chrome-22.0.1229.79 Engine:AppleWebKit-537.4 Bot:false Mobile:false",
- "Mozilla:5.0 Platform:Symbian OS:SymbianOS/9.1 Browser:Symbian-413 Engine:AppleWebKit-413 Bot:false Mobile:true",
-}
-
-// Internal: beautify the UserAgent reference into a string so it can be
-// tested later on.
-//
-// ua - a UserAgent reference.
-//
-// Returns a string that contains the beautified representation.
-func beautify(ua *UserAgent) (s string) {
- if len(ua.Mozilla()) > 0 {
- s += "Mozilla:" + ua.Mozilla() + " "
- }
- if len(ua.Platform()) > 0 {
- s += "Platform:" + ua.Platform() + " "
- }
- if len(ua.OS()) > 0 {
- s += "OS:" + ua.OS() + " "
- }
- if len(ua.Localization()) > 0 {
- s += "Localization:" + ua.Localization() + " "
- }
- str1, str2 := ua.Browser()
- if len(str1) > 0 {
- s += "Browser:" + str1
- if len(str2) > 0 {
- s += "-" + str2 + " "
- } else {
- s += " "
- }
- }
- str1, str2 = ua.Engine()
- if len(str1) > 0 {
- s += "Engine:" + str1
- if len(str2) > 0 {
- s += "-" + str2 + " "
- } else {
- s += " "
- }
- }
- s += "Bot:" + fmt.Sprintf("%v", ua.Bot()) + " "
- s += "Mobile:" + fmt.Sprintf("%v", ua.Mobile())
- return s
-}
-
-// The test suite.
-func TestUserAgent(t *testing.T) {
- for i, tt := range uastrings {
- ua := New(tt.ua)
- got := beautify(ua)
- if expected[i] != got {
- t.Errorf("Test %v => %q, expected %q", tt.name, got, expected[i])
- }
- }
-}
-
-// Benchmark: it parses each User-Agent string on the uastrings slice b.N times.
-func BenchmarkUserAgent(b *testing.B) {
- for i := 0; i < b.N; i++ {
- b.StopTimer()
- for _, tt := range uastrings {
- ua := new(UserAgent)
- b.StartTimer()
- ua.Parse(tt.ua)
- }
- }
-}
diff --git a/vendor/github.com/mssola/user_agent/bot.go b/vendor/github.com/mssola/user_agent/bot.go
deleted file mode 100644
index efcab92..0000000
--- a/vendor/github.com/mssola/user_agent/bot.go
+++ /dev/null
@@ -1,121 +0,0 @@
-// Copyright (C) 2014 Miquel Sabaté Solà
-// This file is licensed under the MIT license.
-// See the LICENSE file.
-
-package user_agent
-
-import (
- "regexp"
- "strings"
-)
-
-// Get the name of the bot from the website that may be in the given comment. If
-// there is no website in the comment, then an empty string is returned.
-func getFromSite(comment []string) string {
- if len(comment) == 0 {
- return ""
- }
-
- // Where we should check the website.
- idx := 2
- if len(comment) < 3 {
- idx = 0
- }
-
- // Pick the site.
- re := regexp.MustCompile("http://.+\\.\\w+")
- results := re.FindStringSubmatch(comment[idx])
- if len(results) == 1 {
- // If it's a simple comment, just return the name of the site.
- if idx == 0 {
- return results[0]
- }
-
- // This is a large comment, usually the name will be in the previous
- // field of the comment.
- return strings.TrimSpace(comment[1])
- }
- return ""
-}
-
-// Returns true if the info that we currently have corresponds to the Google
-// mobile bot. This function also modifies some attributes in the receiver
-// accordingly.
-func (p *UserAgent) googleBot() bool {
- // This is a hackish way to detect Google's mobile bot.
- if strings.Index(p.ua, "Googlebot") != -1 {
- p.platform = ""
- p.undecided = true
- }
- return p.undecided
-}
-
-// Set the attributes of the receiver as given by the parameters. All the other
-// parameters are set to empty.
-func (p *UserAgent) setSimple(name, version string, bot bool) {
- p.bot = bot
- if !bot {
- p.mozilla = ""
- }
- p.browser.Name = name
- p.browser.Version = version
- p.browser.Engine = ""
- p.browser.EngineVersion = ""
- p.os = ""
- p.localization = ""
-}
-
-// Fix some values for some weird browsers.
-func (p *UserAgent) fixOther(sections []section) {
- if len(sections) > 0 {
- p.browser.Name = sections[0].name
- p.browser.Version = sections[0].version
- p.mozilla = ""
- }
-}
-
-// Check if we're dealing with a bot or with some weird browser. If that is the
-// case, the receiver will be modified accordingly.
-func (p *UserAgent) checkBot(sections []section) {
- // If there's only one element, and it's doesn't have the Mozilla string,
- // check whether this is a bot or not.
- if len(sections) == 1 && sections[0].name != "Mozilla" {
- p.mozilla = ""
-
- // Check whether the name has some suspicious "bot" in his name.
- reg, _ := regexp.Compile("(?i)bot")
- if reg.Match([]byte(sections[0].name)) {
- p.setSimple(sections[0].name, "", true)
- return
- }
-
- // Tough luck, let's try to see if it has a website in his comment.
- if name := getFromSite(sections[0].comment); name != "" {
- // First of all, this is a bot. Moreover, since it doesn't have the
- // Mozilla string, we can assume that the name and the version are
- // the ones from the first section.
- p.setSimple(sections[0].name, sections[0].version, true)
- return
- }
-
- // At this point we are sure that this is not a bot, but some weirdo.
- p.setSimple(sections[0].name, sections[0].version, false)
- } else {
- // Let's iterate over the available comments and check for a website.
- for _, v := range sections {
- if name := getFromSite(v.comment); name != "" {
- // Ok, we've got a bot name.
- results := strings.SplitN(name, "/", 2)
- version := ""
- if len(results) == 2 {
- version = results[1]
- }
- p.setSimple(results[0], version, true)
- return
- }
- }
-
- // We will assume that this is some other weird browser.
- p.fixOther(sections)
- }
-}
diff --git a/vendor/github.com/mssola/user_agent/browser.go b/vendor/github.com/mssola/user_agent/browser.go
deleted file mode 100644
index 74fb931..0000000
--- a/vendor/github.com/mssola/user_agent/browser.go
+++ /dev/null
@@ -1,120 +0,0 @@
-// Copyright (C) 2012-2014 Miquel Sabaté Solà
-// This file is licensed under the MIT license.
-// See the LICENSE file.
-
-package user_agent
-
-import (
- "regexp"
- "strings"
-)
-
-// A struct containing all the information that we might be
-// interested from the browser.
-type Browser struct {
- // The name of the browser's engine.
- Engine string
-
- // The version of the browser's engine.
- EngineVersion string
-
- // The name of the browser.
- Name string
-
- // The version of the browser.
- Version string
-}
-
-// Extract all the information that we can get from the User-Agent string
-// about the browser and update the receiver with this information.
-//
-// The function receives just one argument "sections", that contains the
-// sections from the User-Agent string after being parsed.
-func (p *UserAgent) detectBrowser(sections []section) {
- slen := len(sections)
-
- if sections[0].name == "Opera" {
- p.mozilla = ""
- p.browser.Name = "Opera"
- p.browser.Version = sections[0].version
- p.browser.Engine = "Presto"
- if slen > 1 {
- p.browser.EngineVersion = sections[1].version
- }
- } else if slen > 1 {
- engine := sections[1]
- p.browser.Engine = engine.name
- p.browser.EngineVersion = engine.version
- if slen > 2 {
- p.browser.Version = sections[2].version
- if engine.name == "AppleWebKit" {
- if sections[slen-1].name == "OPR" {
- p.browser.Name = "Opera"
- p.browser.Version = sections[slen-1].version
- } else if sections[2].name == "Chrome" {
- p.browser.Name = "Chrome"
- } else {
- p.browser.Name = "Safari"
- }
- } else if engine.name == "Gecko" {
- name := sections[2].name
- if name == "MRA" && slen > 4 {
- name = sections[4].name
- p.browser.Version = sections[4].version
- }
- p.browser.Name = name
- } else if engine.name == "like" && sections[2].name == "Gecko" {
- // This is the new user agent from Internet Explorer 11.
- p.browser.Engine = "Trident"
- p.browser.Name = "Internet Explorer"
- reg, _ := regexp.Compile("^rv:(.+)$")
- for _, c := range sections[0].comment {
- version := reg.FindStringSubmatch(c)
- if len(version) > 0 {
- p.browser.Version = version[1]
- return
- }
- }
- p.browser.Version = ""
- }
- }
- } else if slen == 1 && len(sections[0].comment) > 1 {
- comment := sections[0].comment
- if comment[0] == "compatible" && strings.HasPrefix(comment[1], "MSIE") {
- p.browser.Engine = "Trident"
- p.browser.Name = "Internet Explorer"
- // The MSIE version may be reported as the compatibility version.
- // For IE 8 through 10, the Trident token is more accurate.
- // http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx#VerToken
- for _, v := range comment {
- if strings.HasPrefix(v, "Trident/") {
- switch v[8:] {
- case "4.0":
- p.browser.Version = "8.0"
- case "5.0":
- p.browser.Version = "9.0"
- case "6.0":
- p.browser.Version = "10.0"
- }
- break
- }
- }
- // If the Trident token is not provided, fall back to MSIE token.
- if p.browser.Version == "" {
- p.browser.Version = strings.TrimSpace(comment[1][4:])
- }
- }
- }
-}
-
-// Returns two strings. The first string is the name of the engine and the
-// second one is the version of the engine.
-func (p *UserAgent) Engine() (string, string) {
- return p.browser.Engine, p.browser.EngineVersion
-}
-
-// Returns two strings. The first string is the name of the browser and the
-// second one is the version of the browser.
-func (p *UserAgent) Browser() (string, string) {
- return p.browser.Name, p.browser.Version
-}
diff --git a/vendor/github.com/mssola/user_agent/operating_systems.go b/vendor/github.com/mssola/user_agent/operating_systems.go
deleted file mode 100644
index 0b1e93d..0000000
--- a/vendor/github.com/mssola/user_agent/operating_systems.go
+++ /dev/null
@@ -1,260 +0,0 @@
-// Copyright (C) 2012-2014 Miquel Sabaté Solà
-// This file is licensed under the MIT license.
-// See the LICENSE file.
-
-package user_agent
-
-import "strings"
-
-// Normalize the name of the operating system. By now, this just
-// affects to Windows.
-//
-// Returns a string containing the normalized name for the Operating System.
-func normalizeOS(name string) string {
- sp := strings.SplitN(name, " ", 3)
- if len(sp) != 3 {
- return name
- }
-
- switch sp[2] {
- case "5.0":
- return "Windows 2000"
- case "5.01":
- return "Windows 2000, Service Pack 1 (SP1)"
- case "5.1":
- return "Windows XP"
- case "5.2":
- return "Windows XP x64 Edition"
- case "6.0":
- return "Windows Vista"
- case "6.1":
- return "Windows 7"
- case "6.2":
- return "Windows 8"
- case "6.3":
- return "Windows 8.1"
- case "6.4":
- return "Windows 10"
- }
- return name
-}
-
-// Guess the OS, the localization and if this is a mobile device for a
-// Webkit-powered browser.
-//
-// The first argument p is a reference to the current UserAgent and the second
-// argument is a slice of strings containing the comment.
-func webkit(p *UserAgent, comment []string) {
- if p.platform == "webOS" {
- p.browser.Name = p.platform
- p.os = "Palm"
- if len(comment) > 2 {
- p.localization = comment[2]
- }
- p.mobile = true
- } else if p.platform == "Symbian" {
- p.mobile = true
- p.browser.Name = p.platform
- p.os = comment[0]
- } else if p.platform == "Linux" {
- p.mobile = true
- if p.browser.Name == "Safari" {
- p.browser.Name = "Android"
- }
- if len(comment) > 1 {
- if comment[1] == "U" {
- if len(comment) > 2 {
- p.os = comment[2]
- } else {
- p.mobile = false
- p.os = comment[0]
- }
- } else {
- p.os = comment[1]
- }
- }
- if len(comment) > 3 {
- p.localization = comment[3]
- }
- } else if len(comment) > 0 {
- if len(comment) > 3 {
- p.localization = comment[3]
- }
- if strings.HasPrefix(comment[0], "Windows NT") {
- p.os = normalizeOS(comment[0])
- } else if len(comment) < 2 {
- p.localization = comment[0]
- } else if len(comment) < 3 {
- if !p.googleBot() {
- p.os = normalizeOS(comment[1])
- }
- } else {
- p.os = normalizeOS(comment[2])
- }
- if p.platform == "BlackBerry" {
- p.browser.Name = p.platform
- if p.os == "Touch" {
- p.os = p.platform
- }
- }
- }
-}
-
-// Guess the OS, the localization and if this is a mobile device
-// for a Gecko-powered browser.
-//
-// The first argument p is a reference to the current UserAgent and the second
-// argument is a slice of strings containing the comment.
-func gecko(p *UserAgent, comment []string) {
- if len(comment) > 1 {
- if comment[1] == "U" {
- if len(comment) > 2 {
- p.os = normalizeOS(comment[2])
- } else {
- p.os = normalizeOS(comment[1])
- }
- } else {
- if p.platform == "Android" {
- p.mobile = true
- p.platform, p.os = normalizeOS(comment[1]), p.platform
- } else if comment[0] == "Mobile" || comment[0] == "Tablet" {
- p.mobile = true
- p.os = "FirefoxOS"
- } else {
- if p.os == "" {
- p.os = normalizeOS(comment[1])
- }
- }
- }
- if len(comment) > 3 {
- p.localization = comment[3]
- }
- }
-}
-
-// Guess the OS, the localization and if this is a mobile device
-// for Internet Explorer.
-//
-// The first argument p is a reference to the current UserAgent and the second
-// argument is a slice of strings containing the comment.
-func trident(p *UserAgent, comment []string) {
- // Internet Explorer only runs on Windows.
- p.platform = "Windows"
-
- // The OS can be set before to handle a new case in IE11.
- if p.os == "" {
- if len(comment) > 2 {
- p.os = normalizeOS(comment[2])
- } else {
- p.os = "Windows NT 4.0"
- }
- }
-
- // Last but not least, let's detect if it comes from a mobile device.
- for _, v := range comment {
- if strings.HasPrefix(v, "IEMobile") {
- p.mobile = true
- return
- }
- }
-}
-
-// Guess the OS, the localization and if this is a mobile device
-// for Opera.
-//
-// The first argument p is a reference to the current UserAgent and the second
-// argument is a slice of strings containing the comment.
-func opera(p *UserAgent, comment []string) {
- slen := len(comment)
-
- if strings.HasPrefix(comment[0], "Windows") {
- p.platform = "Windows"
- p.os = normalizeOS(comment[0])
- if slen > 2 {
- if slen > 3 && strings.HasPrefix(comment[2], "MRA") {
- p.localization = comment[3]
- } else {
- p.localization = comment[2]
- }
- }
- } else {
- if strings.HasPrefix(comment[0], "Android") {
- p.mobile = true
- }
- p.platform = comment[0]
- if slen > 1 {
- p.os = comment[1]
- if slen > 3 {
- p.localization = comment[3]
- }
- } else {
- p.os = comment[0]
- }
- }
-}
-
-// Given the comment of the first section of the UserAgent string,
-// get the platform.
-func getPlatform(comment []string) string {
- if len(comment) > 0 {
- if comment[0] != "compatible" {
- if strings.HasPrefix(comment[0], "Windows") {
- return "Windows"
- } else if strings.HasPrefix(comment[0], "Symbian") {
- return "Symbian"
- } else if strings.HasPrefix(comment[0], "webOS") {
- return "webOS"
- } else if comment[0] == "BB10" {
- return "BlackBerry"
- }
- return comment[0]
- }
- }
- return ""
-}
-
-// Detect some properties of the OS from the given section.
-func (p *UserAgent) detectOS(s section) {
- if s.name == "Mozilla" {
- // Get the platform here. Be aware that IE11 provides a new format
- // that is not backwards-compatible with previous versions of IE.
- p.platform = getPlatform(s.comment)
- if p.platform == "Windows" && len(s.comment) > 0 {
- p.os = normalizeOS(s.comment[0])
- }
-
- // And finally get the OS depending on the engine.
- switch p.browser.Engine {
- case "":
- p.undecided = true
- case "Gecko":
- gecko(p, s.comment)
- case "AppleWebKit":
- webkit(p, s.comment)
- case "Trident":
- trident(p, s.comment)
- }
- } else if s.name == "Opera" {
- if len(s.comment) > 0 {
- opera(p, s.comment)
- }
- } else {
- // Check whether this is a bot or just a weird browser.
- p.undecided = true
- }
-}
-
-// Returns a string containing the platform..
-func (p *UserAgent) Platform() string {
- return p.platform
-}
-
-// Returns a string containing the name of the Operating System.
-func (p *UserAgent) OS() string {
- return p.os
-}
-
-// Returns a string containing the localization.
-func (p *UserAgent) Localization() string {
- return p.localization
-}
diff --git a/vendor/github.com/mssola/user_agent/user_agent.go b/vendor/github.com/mssola/user_agent/user_agent.go
deleted file mode 100644
index 74ddf27..0000000
--- a/vendor/github.com/mssola/user_agent/user_agent.go
+++ /dev/null
@@ -1,169 +0,0 @@
-// Copyright (C) 2012-2014 Miquel Sabaté Solà
-// This file is licensed under the MIT license.
-// See the LICENSE file.
-
-// Package user_agent implements an HTTP User Agent string parser. It defines
-// the type UserAgent that contains all the information from the parsed string.
-// It also implements the Parse function and getters for all the relevant
-// information that has been extracted from a parsed User Agent string.
-package user_agent
-
-import (
- "strings"
-)
-
-// A section contains the name of the product, its version and
-// an optional comment.
-type section struct {
- name string
- version string
- comment []string
-}
-
-// The UserAgent struct contains all the info that can be extracted
-// from the User-Agent string.
-type UserAgent struct {
- ua string
- mozilla string
- platform string
- os string
- localization string
- browser Browser
- bot bool
- mobile bool
- undecided bool
-}
-
-// Read from the given string until the given delimiter or the
-// end of the string have been reached.
-//
-// The first argument is the user agent string being parsed. The second
-// argument is a reference pointing to the current index of the user agent
-// string. The delimiter argument specifies which character is the delimiter
-// and the cat argument determines whether nested '(' should be ignored or not.
-//
-// Returns an array of bytes containing what has been read.
-func readUntil(ua string, index *int, delimiter byte, cat bool) []byte {
- var buffer []byte
-
- i := *index
- catalan := 0
- for ; i < len(ua); i = i + 1 {
- if ua[i] == delimiter {
- if catalan == 0 {
- *index = i + 1
- return buffer
- }
- catalan--
- } else if cat && ua[i] == '(' {
- catalan++
- }
- buffer = append(buffer, ua[i])
- }
- *index = i + 1
- return buffer
-}
-
-// Parse the given product, that is, just a name or a string
-// formatted as Name/Version.
-//
-// It returns two strings. The first string is the name of the product and the
-// second string contains the version of the product.
-func parseProduct(product []byte) (string, string) {
- prod := strings.SplitN(string(product), "/", 2)
- if len(prod) == 2 {
- return prod[0], prod[1]
- }
- return string(product), ""
-}
-
-// Parse a section. A section is typically formatted as follows
-// "Name/Version (comment)". Both, the comment and the version are optional.
-//
-// The first argument is the user agent string being parsed. The second
-// argument is a reference pointing to the current index of the user agent
-// string.
-//
-// Returns a section containing the information that we could extract
-// from the last parsed section.
-func parseSection(ua string, index *int) (s section) {
- buffer := readUntil(ua, index, ' ', false)
-
- s.name, s.version = parseProduct(buffer)
- if *index < len(ua) && ua[*index] == '(' {
- *index++
- buffer = readUntil(ua, index, ')', true)
- s.comment = strings.Split(string(buffer), "; ")
- *index++
- }
- return s
-}
-
-// Initialize the parser.
-func (p *UserAgent) initialize() {
- p.ua = ""
- p.mozilla = ""
- p.platform = ""
- p.os = ""
- p.localization = ""
- p.browser.Engine = ""
- p.browser.EngineVersion = ""
- p.browser.Name = ""
- p.browser.Version = ""
- p.bot = false
- p.mobile = false
- p.undecided = false
-}
-
-// Parse the given User-Agent string and get the resulting UserAgent object.
-//
-// Returns an UserAgent object that has been initialized after parsing
-// the given User-Agent string.
-func New(ua string) *UserAgent {
- o := &UserAgent{}
- o.Parse(ua)
- return o
-}
-
-// Parse the given User-Agent string. After calling this function, the
-// receiver will be setted up with all the information that we've extracted.
-func (p *UserAgent) Parse(ua string) {
- var sections []section
-
- p.initialize()
- p.ua = ua
- for index, limit := 0, len(ua); index < limit; {
- s := parseSection(ua, &index)
- if !p.mobile && s.name == "Mobile" {
- p.mobile = true
- }
- sections = append(sections, s)
- }
-
- if len(sections) > 0 {
- p.mozilla = sections[0].version
-
- p.detectBrowser(sections)
- p.detectOS(sections[0])
-
- if p.undecided {
- p.checkBot(sections)
- }
- }
-}
-
-// Returns the mozilla version (it's how the User Agent string begins:
-// "Mozilla/5.0 ...", unless we're dealing with Opera, of course).
-func (p *UserAgent) Mozilla() string {
- return p.mozilla
-}
-
-// Returns true if it's a bot, false otherwise.
-func (p *UserAgent) Bot() bool {
- return p.bot
-}
-
-// Returns true if it's a mobile device, false otherwise.
-func (p *UserAgent) Mobile() bool {
- return p.mobile
-}
diff --git a/vendor/github.com/olekukonko/tablewriter/.travis.yml b/vendor/github.com/olekukonko/tablewriter/.travis.yml
deleted file mode 100644
index f156b3b..0000000
--- a/vendor/github.com/olekukonko/tablewriter/.travis.yml
+++ /dev/null
@@ -1,12 +0,0 @@
-language: go
-
-go:
- - 1.1
- - 1.2
- - 1.3
- - 1.4
- - 1.5
- - 1.6
- - 1.7
- - 1.8
- - tip
diff --git a/vendor/github.com/olekukonko/tablewriter/LICENCE.md b/vendor/github.com/olekukonko/tablewriter/LICENCE.md
deleted file mode 100644
index 1fd8484..0000000
--- a/vendor/github.com/olekukonko/tablewriter/LICENCE.md
+++ /dev/null
@@ -1,19 +0,0 @@
-Copyright (C) 2014 by Oleku Konko
-
-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.
\ No newline at end of file
diff --git a/vendor/github.com/olekukonko/tablewriter/README.md b/vendor/github.com/olekukonko/tablewriter/README.md
deleted file mode 100644
index 4e706a5..0000000
--- a/vendor/github.com/olekukonko/tablewriter/README.md
+++ /dev/null
@@ -1,277 +0,0 @@
-ASCII Table Writer
-=========
-
-[](https://travis-ci.org/olekukonko/tablewriter) [](https://sourcegraph.com/github.com/olekukonko/tablewriter)
-
-Generate ASCII table on the fly ... Installation is simple as
-
- go get github.com/olekukonko/tablewriter
-
-
-#### Features
-- Automatic Padding
-- Support Multiple Lines
-- Supports Alignment
-- Support Custom Separators
-- Automatic Alignment of numbers & percentage
-- Write directly to http , file etc via `io.Writer`
-- Read directly from CSV file
-- Optional row line via `SetRowLine`
-- Normalise table header
-- Make CSV Headers optional
-- Enable or disable table border
-- Set custom footer support
-- Optional identical cells merging
-- Set custom caption
-
-
-#### Example 1 - Basic
-```go
-data := [][]string{
- []string{"A", "The Good", "500"},
- []string{"B", "The Very very Bad Man", "288"},
- []string{"C", "The Ugly", "120"},
- []string{"D", "The Gopher", "800"},
-}
-
-table := tablewriter.NewWriter(os.Stdout)
-table.SetHeader([]string{"Name", "Sign", "Rating"})
-
-for _, v := range data {
- table.Append(v)
-}
-table.Render() // Send output
-```
-
-##### Output 1
-```
-+------+-----------------------+--------+
-| NAME | SIGN | RATING |
-+------+-----------------------+--------+
-| A | The Good | 500 |
-| B | The Very very Bad Man | 288 |
-| C | The Ugly | 120 |
-| D | The Gopher | 800 |
-+------+-----------------------+--------+
-```
-
-#### Example 2 - Without Border / Footer / Bulk Append
-```go
-data := [][]string{
- []string{"1/1/2014", "Domain name", "2233", "$10.98"},
- []string{"1/1/2014", "January Hosting", "2233", "$54.95"},
- []string{"1/4/2014", "February Hosting", "2233", "$51.00"},
- []string{"1/4/2014", "February Extra Bandwidth", "2233", "$30.00"},
-}
-
-table := tablewriter.NewWriter(os.Stdout)
-table.SetHeader([]string{"Date", "Description", "CV2", "Amount"})
-table.SetFooter([]string{"", "", "Total", "$146.93"}) // Add Footer
-table.SetBorder(false) // Set Border to false
-table.AppendBulk(data) // Add Bulk Data
-table.Render()
-```
-
-##### Output 2
-```
-
- DATE | DESCRIPTION | CV2 | AMOUNT
-+----------+--------------------------+-------+---------+
- 1/1/2014 | Domain name | 2233 | $10.98
- 1/1/2014 | January Hosting | 2233 | $54.95
- 1/4/2014 | February Hosting | 2233 | $51.00
- 1/4/2014 | February Extra Bandwidth | 2233 | $30.00
-+----------+--------------------------+-------+---------+
- TOTAL | $146 93
- +-------+---------+
-
-```
-
-
-#### Example 3 - CSV
-```go
-table, _ := tablewriter.NewCSV(os.Stdout, "test_info.csv", true)
-table.SetAlignment(tablewriter.ALIGN_LEFT) // Set Alignment
-table.Render()
-```
-
-##### Output 3
-```
-+----------+--------------+------+-----+---------+----------------+
-| FIELD | TYPE | NULL | KEY | DEFAULT | EXTRA |
-+----------+--------------+------+-----+---------+----------------+
-| user_id | smallint(5) | NO | PRI | NULL | auto_increment |
-| username | varchar(10) | NO | | NULL | |
-| password | varchar(100) | NO | | NULL | |
-+----------+--------------+------+-----+---------+----------------+
-```
-
-#### Example 4 - Custom Separator
-```go
-table, _ := tablewriter.NewCSV(os.Stdout, "test.csv", true)
-table.SetRowLine(true) // Enable row line
-
-// Change table lines
-table.SetCenterSeparator("*")
-table.SetColumnSeparator("‡")
-table.SetRowSeparator("-")
-
-table.SetAlignment(tablewriter.ALIGN_LEFT)
-table.Render()
-```
-
-##### Output 4
-```
-*------------*-----------*---------*
-╪ FIRST NAME ╪ LAST NAME ╪ SSN ╪
-*------------*-----------*---------*
-╪ John ╪ Barry ╪ 123456 ╪
-*------------*-----------*---------*
-╪ Kathy ╪ Smith ╪ 687987 ╪
-*------------*-----------*---------*
-╪ Bob ╪ McCornick ╪ 3979870 ╪
-*------------*-----------*---------*
-```
-
-#### Example 5 - Markdown Format
-```go
-data := [][]string{
- []string{"1/1/2014", "Domain name", "2233", "$10.98"},
- []string{"1/1/2014", "January Hosting", "2233", "$54.95"},
- []string{"1/4/2014", "February Hosting", "2233", "$51.00"},
- []string{"1/4/2014", "February Extra Bandwidth", "2233", "$30.00"},
-}
-
-table := tablewriter.NewWriter(os.Stdout)
-table.SetHeader([]string{"Date", "Description", "CV2", "Amount"})
-table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false})
-table.SetCenterSeparator("|")
-table.AppendBulk(data) // Add Bulk Data
-table.Render()
-```
-
-##### Output 5
-```
-| DATE | DESCRIPTION | CV2 | AMOUNT |
-|----------|--------------------------|------|--------|
-| 1/1/2014 | Domain name | 2233 | $10.98 |
-| 1/1/2014 | January Hosting | 2233 | $54.95 |
-| 1/4/2014 | February Hosting | 2233 | $51.00 |
-| 1/4/2014 | February Extra Bandwidth | 2233 | $30.00 |
-```
-
-#### Example 6 - Identical cells merging
-```go
-data := [][]string{
- []string{"1/1/2014", "Domain name", "1234", "$10.98"},
- []string{"1/1/2014", "January Hosting", "2345", "$54.95"},
- []string{"1/4/2014", "February Hosting", "3456", "$51.00"},
- []string{"1/4/2014", "February Extra Bandwidth", "4567", "$30.00"},
-}
-
-table := tablewriter.NewWriter(os.Stdout)
-table.SetHeader([]string{"Date", "Description", "CV2", "Amount"})
-table.SetFooter([]string{"", "", "Total", "$146.93"})
-table.SetAutoMergeCells(true)
-table.SetRowLine(true)
-table.AppendBulk(data)
-table.Render()
-```
-
-##### Output 6
-```
-+----------+--------------------------+-------+---------+
-| DATE | DESCRIPTION | CV2 | AMOUNT |
-+----------+--------------------------+-------+---------+
-| 1/1/2014 | Domain name | 1234 | $10.98 |
-+ +--------------------------+-------+---------+
-| | January Hosting | 2345 | $54.95 |
-+----------+--------------------------+-------+---------+
-| 1/4/2014 | February Hosting | 3456 | $51.00 |
-+ +--------------------------+-------+---------+
-| | February Extra Bandwidth | 4567 | $30.00 |
-+----------+--------------------------+-------+---------+
-| TOTAL | $146 93 |
-+----------+--------------------------+-------+---------+
-```
-
-
-#### Table with color
-```go
-data := [][]string{
- []string{"1/1/2014", "Domain name", "2233", "$10.98"},
- []string{"1/1/2014", "January Hosting", "2233", "$54.95"},
- []string{"1/4/2014", "February Hosting", "2233", "$51.00"},
- []string{"1/4/2014", "February Extra Bandwidth", "2233", "$30.00"},
-}
-
-table := tablewriter.NewWriter(os.Stdout)
-table.SetHeader([]string{"Date", "Description", "CV2", "Amount"})
-table.SetFooter([]string{"", "", "Total", "$146.93"}) // Add Footer
-table.SetBorder(false) // Set Border to false
-
-table.SetHeaderAttributes(tablewriter.Add(tablewriter.Bold, tablewriter.BgGreenColor),
- tablewriter.Add(tablewriter.FgHiRedColor, tablewriter.Bold, tablewriter.BgBlackColor),
- tablewriter.Add(tablewriter.BgRedColor, tablewriter.FgWhiteColor),
- tablewriter.Add(tablewriter.BgCyanColor, tablewriter.FgWhiteColor))
-
-table.SetColumnAttributes(tablewriter.Add(tablewriter.Bold, tablewriter.FgHiBlackColor),
- tablewriter.Add(tablewriter.Bold, tablewriter.FgHiRedColor),
- tablewriter.Add(tablewriter.Bold, tablewriter.FgHiBlackColor),
- tablewriter.Add(tablewriter.Bold, tablewriter.FgBlackColor))
-
-table.SetFooterAttributes(tablewriter.Add(), tablewriter.Add(),
- tablewriter.Add(tablewriter.Bold),
- tablewriter.Add(tablewriter.FgHiRedColor))
-
-table.AppendBulk(data)
-table.Render()
-```
-
-#### Table with color Output
-
-
-#### Example 6 - Set table caption
-```go
-data := [][]string{
- []string{"A", "The Good", "500"},
- []string{"B", "The Very very Bad Man", "288"},
- []string{"C", "The Ugly", "120"},
- []string{"D", "The Gopher", "800"},
-}
-
-table := tablewriter.NewWriter(os.Stdout)
-table.SetHeader([]string{"Name", "Sign", "Rating"})
-table.SetCaption(true, "Movie ratings.")
-
-for _, v := range data {
- table.Append(v)
-}
-table.Render() // Send output
-```
-
-Note: Caption text will wrap with total width of rendered table.
-
-##### Output 6
-```
-+------+-----------------------+--------+
-| NAME | SIGN | RATING |
-+------+-----------------------+--------+
-| A | The Good | 500 |
-| B | The Very very Bad Man | 288 |
-| C | The Ugly | 120 |
-| D | The Gopher | 800 |
-+------+-----------------------+--------+
-Movie ratings.
-```
-
-#### TODO
-- ~~Import Directly from CSV~~ - `done`
-- ~~Support for `SetFooter`~~ - `done`
-- ~~Support for `SetBorder`~~ - `done`
-- ~~Support table with uneven rows~~ - `done`
-- Support custom alignment
-- General Improvement & Optimisation
-- `NewHTML` Parse table from HTML
-
-
diff --git a/vendor/github.com/olekukonko/tablewriter/csv.go b/vendor/github.com/olekukonko/tablewriter/csv.go
deleted file mode 100644
index 9887830..0000000
--- a/vendor/github.com/olekukonko/tablewriter/csv.go
+++ /dev/null
@@ -1,52 +0,0 @@
-// Copyright 2014 Oleku Konko All rights reserved.
-// Use of this source code is governed by a MIT
-// license that can be found in the LICENSE file.
-
-// This module is a Table Writer API for the Go Programming Language.
-// The protocols were written in pure Go and works on windows and unix systems
-
-package tablewriter
-
-import (
- "encoding/csv"
- "io"
- "os"
-)
-
-// Start A new table by importing from a CSV file
-// Takes io.Writer and csv File name
-func NewCSV(writer io.Writer, fileName string, hasHeader bool) (*Table, error) {
- file, err := os.Open(fileName)
- if err != nil {
- return &Table{}, err
- }
- defer file.Close()
- csvReader := csv.NewReader(file)
- t, err := NewCSVReader(writer, csvReader, hasHeader)
- return t, err
-}
-
-// Start a New Table Writer with csv.Reader
-// This enables customisation such as reader.Comma = ';'
-// See http://golang.org/src/pkg/encoding/csv/reader.go?s=3213:3671#L94
-func NewCSVReader(writer io.Writer, csvReader *csv.Reader, hasHeader bool) (*Table, error) {
- t := NewWriter(writer)
- if hasHeader {
- // Read the first row
- headers, err := csvReader.Read()
- if err != nil {
- return &Table{}, err
- }
- t.SetHeader(headers)
- }
- for {
- record, err := csvReader.Read()
- if err == io.EOF {
- break
- } else if err != nil {
- return &Table{}, err
- }
- t.Append(record)
- }
- return t, nil
-}
diff --git a/vendor/github.com/olekukonko/tablewriter/table.go b/vendor/github.com/olekukonko/tablewriter/table.go
deleted file mode 100644
index 4d07251..0000000
--- a/vendor/github.com/olekukonko/tablewriter/table.go
+++ /dev/null
@@ -1,793 +0,0 @@
-// Copyright 2014 Oleku Konko All rights reserved.
-// Use of this source code is governed by a MIT
-// license that can be found in the LICENSE file.
-
-// This module is a Table Writer API for the Go Programming Language.
-// The protocols were written in pure Go and works on windows and unix systems
-
-// Create & Generate text based table
-package tablewriter
-
-import (
- "bytes"
- "fmt"
- "io"
- "regexp"
- "strings"
-)
-
-const (
- MAX_ROW_WIDTH = 30
-)
-
-const (
- CENTER = "+"
- ROW = "-"
- COLUMN = "|"
- SPACE = " "
- NEWLINE = "\n"
-)
-
-const (
- ALIGN_DEFAULT = iota
- ALIGN_CENTER
- ALIGN_RIGHT
- ALIGN_LEFT
-)
-
-var (
- decimal = regexp.MustCompile(`^-*\d*\.?\d*$`)
- percent = regexp.MustCompile(`^-*\d*\.?\d*$%$`)
-)
-
-type Border struct {
- Left bool
- Right bool
- Top bool
- Bottom bool
-}
-
-type Table struct {
- out io.Writer
- rows [][]string
- lines [][][]string
- cs map[int]int
- rs map[int]int
- headers []string
- footers []string
- caption bool
- captionText string
- autoFmt bool
- autoWrap bool
- mW int
- pCenter string
- pRow string
- pColumn string
- tColumn int
- tRow int
- hAlign int
- fAlign int
- align int
- newLine string
- rowLine bool
- autoMergeCells bool
- hdrLine bool
- borders Border
- colSize int
- headerParams []string
- columnsParams []string
- footerParams []string
- columnsAlign []int
-}
-
-// Start New Table
-// Take io.Writer Directly
-func NewWriter(writer io.Writer) *Table {
- t := &Table{
- out: writer,
- rows: [][]string{},
- lines: [][][]string{},
- cs: make(map[int]int),
- rs: make(map[int]int),
- headers: []string{},
- footers: []string{},
- caption: false,
- captionText: "Table caption.",
- autoFmt: true,
- autoWrap: true,
- mW: MAX_ROW_WIDTH,
- pCenter: CENTER,
- pRow: ROW,
- pColumn: COLUMN,
- tColumn: -1,
- tRow: -1,
- hAlign: ALIGN_DEFAULT,
- fAlign: ALIGN_DEFAULT,
- align: ALIGN_DEFAULT,
- newLine: NEWLINE,
- rowLine: false,
- hdrLine: true,
- borders: Border{Left: true, Right: true, Bottom: true, Top: true},
- colSize: -1,
- headerParams: []string{},
- columnsParams: []string{},
- footerParams: []string{},
- columnsAlign: []int{}}
- return t
-}
-
-// Render table output
-func (t *Table) Render() {
- if t.borders.Top {
- t.printLine(true)
- }
- t.printHeading()
- if t.autoMergeCells {
- t.printRowsMergeCells()
- } else {
- t.printRows()
- }
- if !t.rowLine && t.borders.Bottom {
- t.printLine(true)
- }
- t.printFooter()
-
- if t.caption {
- t.printCaption()
- }
-}
-
-// Set table header
-func (t *Table) SetHeader(keys []string) {
- t.colSize = len(keys)
- for i, v := range keys {
- t.parseDimension(v, i, -1)
- t.headers = append(t.headers, v)
- }
-}
-
-// Set table Footer
-func (t *Table) SetFooter(keys []string) {
- //t.colSize = len(keys)
- for i, v := range keys {
- t.parseDimension(v, i, -1)
- t.footers = append(t.footers, v)
- }
-}
-
-// Set table Caption
-func (t *Table) SetCaption(caption bool, captionText ...string) {
- t.caption = caption
- if len(captionText) == 1 {
- t.captionText = captionText[0]
- }
-}
-
-// Turn header autoformatting on/off. Default is on (true).
-func (t *Table) SetAutoFormatHeaders(auto bool) {
- t.autoFmt = auto
-}
-
-// Turn automatic multiline text adjustment on/off. Default is on (true).
-func (t *Table) SetAutoWrapText(auto bool) {
- t.autoWrap = auto
-}
-
-// Set the Default column width
-func (t *Table) SetColWidth(width int) {
- t.mW = width
-}
-
-// Set the minimal width for a column
-func (t *Table) SetColMinWidth(column int, width int) {
- t.cs[column] = width
-}
-
-// Set the Column Separator
-func (t *Table) SetColumnSeparator(sep string) {
- t.pColumn = sep
-}
-
-// Set the Row Separator
-func (t *Table) SetRowSeparator(sep string) {
- t.pRow = sep
-}
-
-// Set the center Separator
-func (t *Table) SetCenterSeparator(sep string) {
- t.pCenter = sep
-}
-
-// Set Header Alignment
-func (t *Table) SetHeaderAlignment(hAlign int) {
- t.hAlign = hAlign
-}
-
-// Set Footer Alignment
-func (t *Table) SetFooterAlignment(fAlign int) {
- t.fAlign = fAlign
-}
-
-// Set Table Alignment
-func (t *Table) SetAlignment(align int) {
- t.align = align
-}
-
-func (t *Table) SetColumnAlignment(keys []int) {
- for _, v := range keys {
- switch v {
- case ALIGN_CENTER:
- break
- case ALIGN_LEFT:
- break
- case ALIGN_RIGHT:
- break
- default:
- v = ALIGN_DEFAULT
- }
- t.columnsAlign = append(t.columnsAlign, v)
- }
-}
-
-// Set New Line
-func (t *Table) SetNewLine(nl string) {
- t.newLine = nl
-}
-
-// Set Header Line
-// This would enable / disable a line after the header
-func (t *Table) SetHeaderLine(line bool) {
- t.hdrLine = line
-}
-
-// Set Row Line
-// This would enable / disable a line on each row of the table
-func (t *Table) SetRowLine(line bool) {
- t.rowLine = line
-}
-
-// Set Auto Merge Cells
-// This would enable / disable the merge of cells with identical values
-func (t *Table) SetAutoMergeCells(auto bool) {
- t.autoMergeCells = auto
-}
-
-// Set Table Border
-// This would enable / disable line around the table
-func (t *Table) SetBorder(border bool) {
- t.SetBorders(Border{border, border, border, border})
-}
-
-func (t *Table) SetBorders(border Border) {
- t.borders = border
-}
-
-// Append row to table
-func (t *Table) Append(row []string) {
- rowSize := len(t.headers)
- if rowSize > t.colSize {
- t.colSize = rowSize
- }
-
- n := len(t.lines)
- line := [][]string{}
- for i, v := range row {
-
- // Detect string width
- // Detect String height
- // Break strings into words
- out := t.parseDimension(v, i, n)
-
- // Append broken words
- line = append(line, out)
- }
- t.lines = append(t.lines, line)
-}
-
-// Allow Support for Bulk Append
-// Eliminates repeated for loops
-func (t *Table) AppendBulk(rows [][]string) {
- for _, row := range rows {
- t.Append(row)
- }
-}
-
-// Clear rows
-func (t *Table) ClearRows() {
- t.lines = [][][]string{}
-}
-
-// Clear footer
-func (t *Table) ClearFooter() {
- t.footers = []string{}
-}
-
-// Print line based on row width
-func (t *Table) printLine(nl bool) {
- fmt.Fprint(t.out, t.pCenter)
- for i := 0; i < len(t.cs); i++ {
- v := t.cs[i]
- fmt.Fprintf(t.out, "%s%s%s%s",
- t.pRow,
- strings.Repeat(string(t.pRow), v),
- t.pRow,
- t.pCenter)
- }
- if nl {
- fmt.Fprint(t.out, t.newLine)
- }
-}
-
-// Print line based on row width with our without cell separator
-func (t *Table) printLineOptionalCellSeparators(nl bool, displayCellSeparator []bool) {
- fmt.Fprint(t.out, t.pCenter)
- for i := 0; i < len(t.cs); i++ {
- v := t.cs[i]
- if i > len(displayCellSeparator) || displayCellSeparator[i] {
- // Display the cell separator
- fmt.Fprintf(t.out, "%s%s%s%s",
- t.pRow,
- strings.Repeat(string(t.pRow), v),
- t.pRow,
- t.pCenter)
- } else {
- // Don't display the cell separator for this cell
- fmt.Fprintf(t.out, "%s%s",
- strings.Repeat(" ", v+2),
- t.pCenter)
- }
- }
- if nl {
- fmt.Fprint(t.out, t.newLine)
- }
-}
-
-// Return the PadRight function if align is left, PadLeft if align is right,
-// and Pad by default
-func pad(align int) func(string, string, int) string {
- padFunc := Pad
- switch align {
- case ALIGN_LEFT:
- padFunc = PadRight
- case ALIGN_RIGHT:
- padFunc = PadLeft
- }
- return padFunc
-}
-
-// Print heading information
-func (t *Table) printHeading() {
- // Check if headers is available
- if len(t.headers) < 1 {
- return
- }
-
- // Check if border is set
- // Replace with space if not set
- fmt.Fprint(t.out, ConditionString(t.borders.Left, t.pColumn, SPACE))
-
- // Identify last column
- end := len(t.cs) - 1
-
- // Get pad function
- padFunc := pad(t.hAlign)
-
- // Checking for ANSI escape sequences for header
- is_esc_seq := false
- if len(t.headerParams) > 0 {
- is_esc_seq = true
- }
-
- // Print Heading column
- for i := 0; i <= end; i++ {
- v := t.cs[i]
- h := ""
- if i < len(t.headers) {
- h = t.headers[i]
- }
- if t.autoFmt {
- h = Title(h)
- }
- pad := ConditionString((i == end && !t.borders.Left), SPACE, t.pColumn)
-
- if is_esc_seq {
- fmt.Fprintf(t.out, " %s %s",
- format(padFunc(h, SPACE, v),
- t.headerParams[i]), pad)
- } else {
- fmt.Fprintf(t.out, " %s %s",
- padFunc(h, SPACE, v),
- pad)
- }
-
- }
- // Next line
- fmt.Fprint(t.out, t.newLine)
- if t.hdrLine {
- t.printLine(true)
- }
-}
-
-// Print heading information
-func (t *Table) printFooter() {
- // Check if headers is available
- if len(t.footers) < 1 {
- return
- }
-
- // Only print line if border is not set
- if !t.borders.Bottom {
- t.printLine(true)
- }
- // Check if border is set
- // Replace with space if not set
- fmt.Fprint(t.out, ConditionString(t.borders.Bottom, t.pColumn, SPACE))
-
- // Identify last column
- end := len(t.cs) - 1
-
- // Get pad function
- padFunc := pad(t.fAlign)
-
- // Checking for ANSI escape sequences for header
- is_esc_seq := false
- if len(t.footerParams) > 0 {
- is_esc_seq = true
- }
-
- // Print Heading column
- for i := 0; i <= end; i++ {
- v := t.cs[i]
- f := t.footers[i]
- if t.autoFmt {
- f = Title(f)
- }
- pad := ConditionString((i == end && !t.borders.Top), SPACE, t.pColumn)
-
- if len(t.footers[i]) == 0 {
- pad = SPACE
- }
-
- if is_esc_seq {
- fmt.Fprintf(t.out, " %s %s",
- format(padFunc(f, SPACE, v),
- t.footerParams[i]), pad)
- } else {
- fmt.Fprintf(t.out, " %s %s",
- padFunc(f, SPACE, v),
- pad)
- }
-
- //fmt.Fprintf(t.out, " %s %s",
- // padFunc(f, SPACE, v),
- // pad)
- }
- // Next line
- fmt.Fprint(t.out, t.newLine)
- //t.printLine(true)
-
- hasPrinted := false
-
- for i := 0; i <= end; i++ {
- v := t.cs[i]
- pad := t.pRow
- center := t.pCenter
- length := len(t.footers[i])
-
- if length > 0 {
- hasPrinted = true
- }
-
- // Set center to be space if length is 0
- if length == 0 && !t.borders.Right {
- center = SPACE
- }
-
- // Print first junction
- if i == 0 {
- fmt.Fprint(t.out, center)
- }
-
- // Pad With space of length is 0
- if length == 0 {
- pad = SPACE
- }
- // Ignore left space of it has printed before
- if hasPrinted || t.borders.Left {
- pad = t.pRow
- center = t.pCenter
- }
-
- // Change Center start position
- if center == SPACE {
- if i < end && len(t.footers[i+1]) != 0 {
- center = t.pCenter
- }
- }
-
- // Print the footer
- fmt.Fprintf(t.out, "%s%s%s%s",
- pad,
- strings.Repeat(string(pad), v),
- pad,
- center)
-
- }
-
- fmt.Fprint(t.out, t.newLine)
-}
-
-// Print caption text
-func (t Table) printCaption() {
- width := t.getTableWidth()
- paragraph, _ := WrapString(t.captionText, width)
- for linecount := 0; linecount < len(paragraph); linecount++ {
- fmt.Fprintln(t.out, paragraph[linecount])
- }
-}
-
-// Calculate the total number of characters in a row
-func (t Table) getTableWidth() int {
- var chars int
- for _, v := range t.cs {
- chars += v
- }
-
- // Add chars, spaces, seperators to calculate the total width of the table.
- // ncols := t.colSize
- // spaces := ncols * 2
- // seps := ncols + 1
-
- return (chars + (3 * t.colSize) + 2)
-}
-
-func (t Table) printRows() {
- for i, lines := range t.lines {
- t.printRow(lines, i)
- }
-}
-
-func (t *Table) fillAlignment(num int) {
- if len(t.columnsAlign) < num {
- t.columnsAlign = make([]int, num)
- for i := range t.columnsAlign {
- t.columnsAlign[i] = t.align
- }
- }
-}
-
-// Print Row Information
-// Adjust column alignment based on type
-
-func (t *Table) printRow(columns [][]string, colKey int) {
- // Get Maximum Height
- max := t.rs[colKey]
- total := len(columns)
-
- // TODO Fix uneven col size
- // if total < t.colSize {
- // for n := t.colSize - total; n < t.colSize ; n++ {
- // columns = append(columns, []string{SPACE})
- // t.cs[n] = t.mW
- // }
- //}
-
- // Pad Each Height
- // pads := []int{}
- pads := []int{}
-
- // Checking for ANSI escape sequences for columns
- is_esc_seq := false
- if len(t.columnsParams) > 0 {
- is_esc_seq = true
- }
- t.fillAlignment(total)
-
- for i, line := range columns {
- length := len(line)
- pad := max - length
- pads = append(pads, pad)
- for n := 0; n < pad; n++ {
- columns[i] = append(columns[i], " ")
- }
- }
- //fmt.Println(max, "\n")
- for x := 0; x < max; x++ {
- for y := 0; y < total; y++ {
-
- // Check if border is set
- fmt.Fprint(t.out, ConditionString((!t.borders.Left && y == 0), SPACE, t.pColumn))
-
- fmt.Fprintf(t.out, SPACE)
- str := columns[y][x]
-
- // Embedding escape sequence with column value
- if is_esc_seq {
- str = format(str, t.columnsParams[y])
- }
-
- // This would print alignment
- // Default alignment would use multiple configuration
- switch t.columnsAlign[y] {
- case ALIGN_CENTER: //
- fmt.Fprintf(t.out, "%s", Pad(str, SPACE, t.cs[y]))
- case ALIGN_RIGHT:
- fmt.Fprintf(t.out, "%s", PadLeft(str, SPACE, t.cs[y]))
- case ALIGN_LEFT:
- fmt.Fprintf(t.out, "%s", PadRight(str, SPACE, t.cs[y]))
- default:
- if decimal.MatchString(strings.TrimSpace(str)) || percent.MatchString(strings.TrimSpace(str)) {
- fmt.Fprintf(t.out, "%s", PadLeft(str, SPACE, t.cs[y]))
- } else {
- fmt.Fprintf(t.out, "%s", PadRight(str, SPACE, t.cs[y]))
-
- // TODO Custom alignment per column
- //if max == 1 || pads[y] > 0 {
- // fmt.Fprintf(t.out, "%s", Pad(str, SPACE, t.cs[y]))
- //} else {
- // fmt.Fprintf(t.out, "%s", PadRight(str, SPACE, t.cs[y]))
- //}
-
- }
- }
- fmt.Fprintf(t.out, SPACE)
- }
- // Check if border is set
- // Replace with space if not set
- fmt.Fprint(t.out, ConditionString(t.borders.Left, t.pColumn, SPACE))
- fmt.Fprint(t.out, t.newLine)
- }
-
- if t.rowLine {
- t.printLine(true)
- }
-}
-
-// Print the rows of the table and merge the cells that are identical
-func (t *Table) printRowsMergeCells() {
- var previousLine []string
- var displayCellBorder []bool
- var tmpWriter bytes.Buffer
- for i, lines := range t.lines {
- // We store the display of the current line in a tmp writer, as we need to know which border needs to be print above
- previousLine, displayCellBorder = t.printRowMergeCells(&tmpWriter, lines, i, previousLine)
- if i > 0 { //We don't need to print borders above first line
- if t.rowLine {
- t.printLineOptionalCellSeparators(true, displayCellBorder)
- }
- }
- tmpWriter.WriteTo(t.out)
- }
- //Print the end of the table
- if t.rowLine {
- t.printLine(true)
- }
-}
-
-// Print Row Information to a writer and merge identical cells.
-// Adjust column alignment based on type
-
-func (t *Table) printRowMergeCells(writer io.Writer, columns [][]string, colKey int, previousLine []string) ([]string, []bool) {
- // Get Maximum Height
- max := t.rs[colKey]
- total := len(columns)
-
- // Pad Each Height
- pads := []int{}
-
- for i, line := range columns {
- length := len(line)
- pad := max - length
- pads = append(pads, pad)
- for n := 0; n < pad; n++ {
- columns[i] = append(columns[i], " ")
- }
- }
-
- var displayCellBorder []bool
- t.fillAlignment(total)
- for x := 0; x < max; x++ {
- for y := 0; y < total; y++ {
-
- // Check if border is set
- fmt.Fprint(writer, ConditionString((!t.borders.Left && y == 0), SPACE, t.pColumn))
-
- fmt.Fprintf(writer, SPACE)
-
- str := columns[y][x]
-
- if t.autoMergeCells {
- //Store the full line to merge mutli-lines cells
- fullLine := strings.Join(columns[y], " ")
- if len(previousLine) > y && fullLine == previousLine[y] && fullLine != "" {
- // If this cell is identical to the one above but not empty, we don't display the border and keep the cell empty.
- displayCellBorder = append(displayCellBorder, false)
- str = ""
- } else {
- // First line or different content, keep the content and print the cell border
- displayCellBorder = append(displayCellBorder, true)
- }
- }
-
- // This would print alignment
- // Default alignment would use multiple configuration
- switch t.columnsAlign[y] {
- case ALIGN_CENTER: //
- fmt.Fprintf(writer, "%s", Pad(str, SPACE, t.cs[y]))
- case ALIGN_RIGHT:
- fmt.Fprintf(writer, "%s", PadLeft(str, SPACE, t.cs[y]))
- case ALIGN_LEFT:
- fmt.Fprintf(writer, "%s", PadRight(str, SPACE, t.cs[y]))
- default:
- if decimal.MatchString(strings.TrimSpace(str)) || percent.MatchString(strings.TrimSpace(str)) {
- fmt.Fprintf(writer, "%s", PadLeft(str, SPACE, t.cs[y]))
- } else {
- fmt.Fprintf(writer, "%s", PadRight(str, SPACE, t.cs[y]))
- }
- }
- fmt.Fprintf(writer, SPACE)
- }
- // Check if border is set
- // Replace with space if not set
- fmt.Fprint(writer, ConditionString(t.borders.Left, t.pColumn, SPACE))
- fmt.Fprint(writer, t.newLine)
- }
-
- //The new previous line is the current one
- previousLine = make([]string, total)
- for y := 0; y < total; y++ {
- previousLine[y] = strings.Join(columns[y], " ") //Store the full line for multi-lines cells
- }
- //Returns the newly added line and wether or not a border should be displayed above.
- return previousLine, displayCellBorder
-}
-
-func (t *Table) parseDimension(str string, colKey, rowKey int) []string {
- var (
- raw []string
- max int
- )
- w := DisplayWidth(str)
- // Calculate Width
- // Check if with is grater than maximum width
- if w > t.mW {
- w = t.mW
- }
-
- // Check if width exists
- v, ok := t.cs[colKey]
- if !ok || v < w || v == 0 {
- t.cs[colKey] = w
- }
-
- if rowKey == -1 {
- return raw
- }
- // Calculate Height
- if t.autoWrap {
- raw, _ = WrapString(str, t.cs[colKey])
- } else {
- raw = getLines(str)
- }
-
- for _, line := range raw {
- if w := DisplayWidth(line); w > max {
- max = w
- }
- }
-
- // Make sure the with is the same length as maximum word
- // Important for cases where the width is smaller than maxu word
- if max > t.cs[colKey] {
- t.cs[colKey] = max
- }
-
- h := len(raw)
- v, ok = t.rs[rowKey]
-
- if !ok || v < h || v == 0 {
- t.rs[rowKey] = h
- }
- //fmt.Printf("Raw %+v %d\n", raw, len(raw))
- return raw
-}
diff --git a/vendor/github.com/olekukonko/tablewriter/table_test.go b/vendor/github.com/olekukonko/tablewriter/table_test.go
deleted file mode 100644
index 1a6022e..0000000
--- a/vendor/github.com/olekukonko/tablewriter/table_test.go
+++ /dev/null
@@ -1,869 +0,0 @@
-// Copyright 2014 Oleku Konko All rights reserved.
-// Use of this source code is governed by a MIT
-// license that can be found in the LICENSE file.
-
-// This module is a Table Writer API for the Go Programming Language.
-// The protocols were written in pure Go and works on windows and unix systems
-
-package tablewriter
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
- "reflect"
- "strings"
- "testing"
-)
-
-func ExampleShort() {
- data := [][]string{
- []string{"A", "The Good", "500"},
- []string{"B", "The Very very Bad Man", "288"},
- []string{"C", "The Ugly", "120"},
- []string{"D", "The Gopher", "800"},
- }
-
- table := NewWriter(os.Stdout)
- table.SetHeader([]string{"Name", "Sign", "Rating"})
-
- for _, v := range data {
- table.Append(v)
- }
- table.Render()
-
- // Output: +------+-----------------------+--------+
- // | NAME | SIGN | RATING |
- // +------+-----------------------+--------+
- // | A | The Good | 500 |
- // | B | The Very very Bad Man | 288 |
- // | C | The Ugly | 120 |
- // | D | The Gopher | 800 |
- // +------+-----------------------+--------+
-}
-
-func ExampleLong() {
- data := [][]string{
- []string{"Learn East has computers with adapted keyboards with enlarged print etc", " Some Data ", " Another Data"},
- []string{"Instead of lining up the letters all ", "the way across, he splits the keyboard in two", "Like most ergonomic keyboards", "See Data"},
- }
-
- table := NewWriter(os.Stdout)
- table.SetHeader([]string{"Name", "Sign", "Rating"})
- table.SetCenterSeparator("*")
- table.SetRowSeparator("=")
-
- for _, v := range data {
- table.Append(v)
- }
- table.Render()
-}
-
-func ExampleCSV() {
- table, _ := NewCSV(os.Stdout, "test.csv", true)
- table.SetCenterSeparator("*")
- table.SetRowSeparator("=")
-
- table.Render()
-
- // Output: *============*===========*=========*
- // | FIRST NAME | LAST NAME | SSN |
- // *============*===========*=========*
- // | John | Barry | 123456 |
- // | Kathy | Smith | 687987 |
- // | Bob | McCornick | 3979870 |
- // *============*===========*=========*
-}
-
-func TestCSVInfo(t *testing.T) {
- buf := &bytes.Buffer{}
- table, err := NewCSV(buf, "test_info.csv", true)
- if err != nil {
- t.Error(err)
- return
- }
- table.SetAlignment(ALIGN_LEFT)
- table.SetBorder(false)
- table.Render()
-
- got := buf.String()
- want := ` FIELD | TYPE | NULL | KEY | DEFAULT | EXTRA
-+----------+--------------+------+-----+---------+----------------+
- user_id | smallint(5) | NO | PRI | NULL | auto_increment
- username | varchar(10) | NO | | NULL |
- password | varchar(100) | NO | | NULL |
-`
-
- if got != want {
- t.Errorf("CSV info failed\ngot:\n[%s]\nwant:\n[%s]\n", got, want)
- }
-}
-
-func TestCSVSeparator(t *testing.T) {
- buf := &bytes.Buffer{}
- table, err := NewCSV(buf, "test.csv", true)
- if err != nil {
- t.Error(err)
- return
- }
- table.SetRowLine(true)
- table.SetCenterSeparator("+")
- table.SetColumnSeparator("|")
- table.SetRowSeparator("-")
- table.SetAlignment(ALIGN_LEFT)
- table.Render()
-
- want := `+------------+-----------+---------+
-| FIRST NAME | LAST NAME | SSN |
-+------------+-----------+---------+
-| John | Barry | 123456 |
-+------------+-----------+---------+
-| Kathy | Smith | 687987 |
-+------------+-----------+---------+
-| Bob | McCornick | 3979870 |
-+------------+-----------+---------+
-`
-
- got := buf.String()
- if got != want {
- t.Errorf("CSV info failed\ngot:\n[%s]\nwant:\n[%s]\n", got, want)
- }
-}
-
-func TestNoBorder(t *testing.T) {
- data := [][]string{
- []string{"1/1/2014", "Domain name", "2233", "$10.98"},
- []string{"1/1/2014", "January Hosting", "2233", "$54.95"},
- []string{"", " (empty)\n (empty)", "", ""},
- []string{"1/4/2014", "February Hosting", "2233", "$51.00"},
- []string{"1/4/2014", "February Extra Bandwidth", "2233", "$30.00"},
- []string{"1/4/2014", " (Discount)", "2233", "-$1.00"},
- }
-
- var buf bytes.Buffer
- table := NewWriter(&buf)
- table.SetAutoWrapText(false)
- table.SetHeader([]string{"Date", "Description", "CV2", "Amount"})
- table.SetFooter([]string{"", "", "Total", "$145.93"}) // Add Footer
- table.SetBorder(false) // Set Border to false
- table.AppendBulk(data) // Add Bulk Data
- table.Render()
-
- want := ` DATE | DESCRIPTION | CV2 | AMOUNT
-+----------+--------------------------+-------+---------+
- 1/1/2014 | Domain name | 2233 | $10.98
- 1/1/2014 | January Hosting | 2233 | $54.95
- | (empty) | |
- | (empty) | |
- 1/4/2014 | February Hosting | 2233 | $51.00
- 1/4/2014 | February Extra Bandwidth | 2233 | $30.00
- 1/4/2014 | (Discount) | 2233 | -$1.00
-+----------+--------------------------+-------+---------+
- TOTAL | $145 93
- +-------+---------+
-`
- got := buf.String()
- if got != want {
- t.Errorf("border table rendering failed\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-}
-
-func TestWithBorder(t *testing.T) {
- data := [][]string{
- []string{"1/1/2014", "Domain name", "2233", "$10.98"},
- []string{"1/1/2014", "January Hosting", "2233", "$54.95"},
- []string{"", " (empty)\n (empty)", "", ""},
- []string{"1/4/2014", "February Hosting", "2233", "$51.00"},
- []string{"1/4/2014", "February Extra Bandwidth", "2233", "$30.00"},
- []string{"1/4/2014", " (Discount)", "2233", "-$1.00"},
- }
-
- var buf bytes.Buffer
- table := NewWriter(&buf)
- table.SetAutoWrapText(false)
- table.SetHeader([]string{"Date", "Description", "CV2", "Amount"})
- table.SetFooter([]string{"", "", "Total", "$145.93"}) // Add Footer
- table.AppendBulk(data) // Add Bulk Data
- table.Render()
-
- want := `+----------+--------------------------+-------+---------+
-| DATE | DESCRIPTION | CV2 | AMOUNT |
-+----------+--------------------------+-------+---------+
-| 1/1/2014 | Domain name | 2233 | $10.98 |
-| 1/1/2014 | January Hosting | 2233 | $54.95 |
-| | (empty) | | |
-| | (empty) | | |
-| 1/4/2014 | February Hosting | 2233 | $51.00 |
-| 1/4/2014 | February Extra Bandwidth | 2233 | $30.00 |
-| 1/4/2014 | (Discount) | 2233 | -$1.00 |
-+----------+--------------------------+-------+---------+
-| TOTAL | $145 93 |
-+----------+--------------------------+-------+---------+
-`
- got := buf.String()
- if got != want {
- t.Errorf("border table rendering failed\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-}
-
-func TestPrintingInMarkdown(t *testing.T) {
- data := [][]string{
- []string{"1/1/2014", "Domain name", "2233", "$10.98"},
- []string{"1/1/2014", "January Hosting", "2233", "$54.95"},
- []string{"1/4/2014", "February Hosting", "2233", "$51.00"},
- []string{"1/4/2014", "February Extra Bandwidth", "2233", "$30.00"},
- }
-
- var buf bytes.Buffer
- table := NewWriter(&buf)
- table.SetHeader([]string{"Date", "Description", "CV2", "Amount"})
- table.AppendBulk(data) // Add Bulk Data
- table.SetBorders(Border{Left: true, Top: false, Right: true, Bottom: false})
- table.SetCenterSeparator("|")
- table.Render()
-
- want := `| DATE | DESCRIPTION | CV2 | AMOUNT |
-|----------|--------------------------|------|--------|
-| 1/1/2014 | Domain name | 2233 | $10.98 |
-| 1/1/2014 | January Hosting | 2233 | $54.95 |
-| 1/4/2014 | February Hosting | 2233 | $51.00 |
-| 1/4/2014 | February Extra Bandwidth | 2233 | $30.00 |
-`
- got := buf.String()
- if got != want {
- t.Errorf("border table rendering failed\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-}
-
-func TestPrintHeading(t *testing.T) {
- var buf bytes.Buffer
- table := NewWriter(&buf)
- table.SetHeader([]string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c"})
- table.printHeading()
- want := `| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C |
-+---+---+---+---+---+---+---+---+---+---+---+---+
-`
- got := buf.String()
- if got != want {
- t.Errorf("header rendering failed\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-}
-
-func TestPrintHeadingWithoutAutoFormat(t *testing.T) {
- var buf bytes.Buffer
- table := NewWriter(&buf)
- table.SetHeader([]string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c"})
- table.SetAutoFormatHeaders(false)
- table.printHeading()
- want := `| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | a | b | c |
-+---+---+---+---+---+---+---+---+---+---+---+---+
-`
- got := buf.String()
- if got != want {
- t.Errorf("header rendering failed\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-}
-
-func TestPrintFooter(t *testing.T) {
- var buf bytes.Buffer
- table := NewWriter(&buf)
- table.SetHeader([]string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c"})
- table.SetFooter([]string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c"})
- table.printFooter()
- want := `| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C |
-+---+---+---+---+---+---+---+---+---+---+---+---+
-`
- got := buf.String()
- if got != want {
- t.Errorf("footer rendering failed\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-}
-
-func TestPrintFooterWithoutAutoFormat(t *testing.T) {
- var buf bytes.Buffer
- table := NewWriter(&buf)
- table.SetAutoFormatHeaders(false)
- table.SetHeader([]string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c"})
- table.SetFooter([]string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c"})
- table.printFooter()
- want := `| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | a | b | c |
-+---+---+---+---+---+---+---+---+---+---+---+---+
-`
- got := buf.String()
- if got != want {
- t.Errorf("footer rendering failed\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-}
-
-func TestPrintShortCaption(t *testing.T) {
- var buf bytes.Buffer
- data := [][]string{
- []string{"A", "The Good", "500"},
- []string{"B", "The Very very Bad Man", "288"},
- []string{"C", "The Ugly", "120"},
- []string{"D", "The Gopher", "800"},
- }
-
- table := NewWriter(&buf)
- table.SetHeader([]string{"Name", "Sign", "Rating"})
- table.SetCaption(true, "Short caption.")
-
- for _, v := range data {
- table.Append(v)
- }
- table.Render()
-
- want := `+------+-----------------------+--------+
-| NAME | SIGN | RATING |
-+------+-----------------------+--------+
-| A | The Good | 500 |
-| B | The Very very Bad Man | 288 |
-| C | The Ugly | 120 |
-| D | The Gopher | 800 |
-+------+-----------------------+--------+
-Short caption.
-`
- got := buf.String()
- if got != want {
- t.Errorf("long caption for short example rendering failed\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-}
-
-func TestPrintLongCaptionWithShortExample(t *testing.T) {
- var buf bytes.Buffer
- data := [][]string{
- []string{"A", "The Good", "500"},
- []string{"B", "The Very very Bad Man", "288"},
- []string{"C", "The Ugly", "120"},
- []string{"D", "The Gopher", "800"},
- }
-
- table := NewWriter(&buf)
- table.SetHeader([]string{"Name", "Sign", "Rating"})
- table.SetCaption(true, "This is a very long caption. The text should wrap. If not, we have a problem that needs to be solved.")
-
- for _, v := range data {
- table.Append(v)
- }
- table.Render()
-
- want := `+------+-----------------------+--------+
-| NAME | SIGN | RATING |
-+------+-----------------------+--------+
-| A | The Good | 500 |
-| B | The Very very Bad Man | 288 |
-| C | The Ugly | 120 |
-| D | The Gopher | 800 |
-+------+-----------------------+--------+
-This is a very long caption. The text
-should wrap. If not, we have a problem
-that needs to be solved.
-`
- got := buf.String()
- if got != want {
- t.Errorf("long caption for short example rendering failed\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-}
-
-func TestPrintCaptionWithFooter(t *testing.T) {
- data := [][]string{
- []string{"1/1/2014", "Domain name", "2233", "$10.98"},
- []string{"1/1/2014", "January Hosting", "2233", "$54.95"},
- []string{"1/4/2014", "February Hosting", "2233", "$51.00"},
- []string{"1/4/2014", "February Extra Bandwidth", "2233", "$30.00"},
- }
-
- var buf bytes.Buffer
- table := NewWriter(&buf)
- table.SetHeader([]string{"Date", "Description", "CV2", "Amount"})
- table.SetFooter([]string{"", "", "Total", "$146.93"}) // Add Footer
- table.SetCaption(true, "This is a very long caption. The text should wrap to the width of the table.") // Add caption
- table.SetBorder(false) // Set Border to false
- table.AppendBulk(data) // Add Bulk Data
- table.Render()
-
- want := ` DATE | DESCRIPTION | CV2 | AMOUNT
-+----------+--------------------------+-------+---------+
- 1/1/2014 | Domain name | 2233 | $10.98
- 1/1/2014 | January Hosting | 2233 | $54.95
- 1/4/2014 | February Hosting | 2233 | $51.00
- 1/4/2014 | February Extra Bandwidth | 2233 | $30.00
-+----------+--------------------------+-------+---------+
- TOTAL | $146 93
- +-------+---------+
-This is a very long caption. The text should wrap to the
-width of the table.
-`
- got := buf.String()
- if got != want {
- t.Errorf("border table rendering failed\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-}
-
-func TestPrintLongCaptionWithLongExample(t *testing.T) {
- var buf bytes.Buffer
- data := [][]string{
- []string{"Learn East has computers with adapted keyboards with enlarged print etc", "Some Data", "Another Data"},
- []string{"Instead of lining up the letters all", "the way across, he splits the keyboard in two", "Like most ergonomic keyboards"},
- }
-
- table := NewWriter(&buf)
- table.SetCaption(true, "This is a very long caption. The text should wrap. If not, we have a problem that needs to be solved.")
- table.SetHeader([]string{"Name", "Sign", "Rating"})
-
- for _, v := range data {
- table.Append(v)
- }
- table.Render()
-
- want := `+--------------------------------+--------------------------------+-------------------------------+
-| NAME | SIGN | RATING |
-+--------------------------------+--------------------------------+-------------------------------+
-| Learn East has computers | Some Data | Another Data |
-| with adapted keyboards with | | |
-| enlarged print etc | | |
-| Instead of lining up the | the way across, he splits the | Like most ergonomic keyboards |
-| letters all | keyboard in two | |
-+--------------------------------+--------------------------------+-------------------------------+
-This is a very long caption. The text should wrap. If not, we have a problem that needs to be
-solved.
-`
- got := buf.String()
- if got != want {
- t.Errorf("long caption for long example rendering failed\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-}
-
-func TestPrintTableWithAndWithoutAutoWrap(t *testing.T) {
- var buf bytes.Buffer
- var multiline = `A multiline
-string with some lines being really long.`
-
- with := NewWriter(&buf)
- with.Append([]string{multiline})
- with.Render()
- want := `+--------------------------------+
-| A multiline string with some |
-| lines being really long. |
-+--------------------------------+
-`
- got := buf.String()
- if got != want {
- t.Errorf("multiline text rendering with wrapping failed\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-
- buf.Truncate(0)
- without := NewWriter(&buf)
- without.SetAutoWrapText(false)
- without.Append([]string{multiline})
- without.Render()
- want = `+-------------------------------------------+
-| A multiline |
-| string with some lines being really long. |
-+-------------------------------------------+
-`
- got = buf.String()
- if got != want {
- t.Errorf("multiline text rendering without wrapping rendering failed\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-}
-
-func TestPrintLine(t *testing.T) {
- header := make([]string, 12)
- val := " "
- want := ""
- for i := range header {
- header[i] = val
- want = fmt.Sprintf("%s+-%s-", want, strings.Replace(val, " ", "-", -1))
- val = val + " "
- }
- want = want + "+"
- var buf bytes.Buffer
- table := NewWriter(&buf)
- table.SetHeader(header)
- table.printLine(false)
- got := buf.String()
- if got != want {
- t.Errorf("line rendering failed\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-}
-
-func TestAnsiStrip(t *testing.T) {
- header := make([]string, 12)
- val := " "
- want := ""
- for i := range header {
- header[i] = "\033[43;30m" + val + "\033[00m"
- want = fmt.Sprintf("%s+-%s-", want, strings.Replace(val, " ", "-", -1))
- val = val + " "
- }
- want = want + "+"
- var buf bytes.Buffer
- table := NewWriter(&buf)
- table.SetHeader(header)
- table.printLine(false)
- got := buf.String()
- if got != want {
- t.Errorf("line rendering failed\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-}
-
-func NewCustomizedTable(out io.Writer) *Table {
- table := NewWriter(out)
- table.SetCenterSeparator("")
- table.SetColumnSeparator("")
- table.SetRowSeparator("")
- table.SetBorder(false)
- table.SetAlignment(ALIGN_LEFT)
- table.SetHeader([]string{})
- return table
-}
-
-func TestSubclass(t *testing.T) {
- buf := new(bytes.Buffer)
- table := NewCustomizedTable(buf)
-
- data := [][]string{
- []string{"A", "The Good", "500"},
- []string{"B", "The Very very Bad Man", "288"},
- []string{"C", "The Ugly", "120"},
- []string{"D", "The Gopher", "800"},
- }
-
- for _, v := range data {
- table.Append(v)
- }
- table.Render()
-
- output := string(buf.Bytes())
- want := ` A The Good 500
- B The Very very Bad Man 288
- C The Ugly 120
- D The Gopher 800
-`
- if output != want {
- t.Error(fmt.Sprintf("Unexpected output '%v' != '%v'", output, want))
- }
-}
-
-func TestAutoMergeRows(t *testing.T) {
- data := [][]string{
- []string{"A", "The Good", "500"},
- []string{"A", "The Very very Bad Man", "288"},
- []string{"B", "The Very very Bad Man", "120"},
- []string{"B", "The Very very Bad Man", "200"},
- }
- var buf bytes.Buffer
- table := NewWriter(&buf)
- table.SetHeader([]string{"Name", "Sign", "Rating"})
-
- for _, v := range data {
- table.Append(v)
- }
- table.SetAutoMergeCells(true)
- table.Render()
- want := `+------+-----------------------+--------+
-| NAME | SIGN | RATING |
-+------+-----------------------+--------+
-| A | The Good | 500 |
-| | The Very very Bad Man | 288 |
-| B | | 120 |
-| | | 200 |
-+------+-----------------------+--------+
-`
- got := buf.String()
- if got != want {
- t.Errorf("\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-
- buf.Reset()
- table = NewWriter(&buf)
- table.SetHeader([]string{"Name", "Sign", "Rating"})
-
- for _, v := range data {
- table.Append(v)
- }
- table.SetAutoMergeCells(true)
- table.SetRowLine(true)
- table.Render()
- want = `+------+-----------------------+--------+
-| NAME | SIGN | RATING |
-+------+-----------------------+--------+
-| A | The Good | 500 |
-+ +-----------------------+--------+
-| | The Very very Bad Man | 288 |
-+------+ +--------+
-| B | | 120 |
-+ + +--------+
-| | | 200 |
-+------+-----------------------+--------+
-`
- got = buf.String()
- if got != want {
- t.Errorf("\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-
- buf.Reset()
- table = NewWriter(&buf)
- table.SetHeader([]string{"Name", "Sign", "Rating"})
-
- dataWithlongText := [][]string{
- []string{"A", "The Good", "500"},
- []string{"A", "The Very very very very very Bad Man", "288"},
- []string{"B", "The Very very very very very Bad Man", "120"},
- []string{"C", "The Very very Bad Man", "200"},
- }
- table.AppendBulk(dataWithlongText)
- table.SetAutoMergeCells(true)
- table.SetRowLine(true)
- table.Render()
- want = `+------+--------------------------------+--------+
-| NAME | SIGN | RATING |
-+------+--------------------------------+--------+
-| A | The Good | 500 |
-+------+--------------------------------+--------+
-| A | The Very very very very very | 288 |
-| | Bad Man | |
-+------+ +--------+
-| B | | 120 |
-| | | |
-+------+--------------------------------+--------+
-| C | The Very very Bad Man | 200 |
-+------+--------------------------------+--------+
-`
- got = buf.String()
- if got != want {
- t.Errorf("\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-}
-
-func TestClearRows(t *testing.T) {
- data := [][]string{
- []string{"1/1/2014", "Domain name", "2233", "$10.98"},
- }
-
- var buf bytes.Buffer
- table := NewWriter(&buf)
- table.SetAutoWrapText(false)
- table.SetHeader([]string{"Date", "Description", "CV2", "Amount"})
- table.SetFooter([]string{"", "", "Total", "$145.93"}) // Add Footer
- table.AppendBulk(data) // Add Bulk Data
- table.Render()
-
- originalWant := `+----------+-------------+-------+---------+
-| DATE | DESCRIPTION | CV2 | AMOUNT |
-+----------+-------------+-------+---------+
-| 1/1/2014 | Domain name | 2233 | $10.98 |
-+----------+-------------+-------+---------+
-| TOTAL | $145 93 |
-+----------+-------------+-------+---------+
-`
- want := originalWant
-
- got := buf.String()
- if got != want {
- t.Errorf("table clear rows failed\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-
- buf.Reset()
- table.ClearRows()
- table.Render()
-
- want = `+----------+-------------+-------+---------+
-| DATE | DESCRIPTION | CV2 | AMOUNT |
-+----------+-------------+-------+---------+
-+----------+-------------+-------+---------+
-| TOTAL | $145 93 |
-+----------+-------------+-------+---------+
-`
-
- got = buf.String()
- if got != want {
- t.Errorf("table clear failed\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-
- buf.Reset()
- table.AppendBulk(data) // Add Bulk Data
- table.Render()
-
- want = `+----------+-------------+-------+---------+
-| DATE | DESCRIPTION | CV2 | AMOUNT |
-+----------+-------------+-------+---------+
-| 1/1/2014 | Domain name | 2233 | $10.98 |
-+----------+-------------+-------+---------+
-| TOTAL | $145 93 |
-+----------+-------------+-------+---------+
-`
-
- got = buf.String()
- if got != want {
- t.Errorf("table clear rows failed\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-}
-
-func TestClearFooters(t *testing.T) {
- data := [][]string{
- []string{"1/1/2014", "Domain name", "2233", "$10.98"},
- }
-
- var buf bytes.Buffer
- table := NewWriter(&buf)
- table.SetAutoWrapText(false)
- table.SetHeader([]string{"Date", "Description", "CV2", "Amount"})
- table.SetFooter([]string{"", "", "Total", "$145.93"}) // Add Footer
- table.AppendBulk(data) // Add Bulk Data
- table.Render()
-
- buf.Reset()
- table.ClearFooter()
- table.Render()
-
- want := `+----------+-------------+-------+---------+
-| DATE | DESCRIPTION | CV2 | AMOUNT |
-+----------+-------------+-------+---------+
-| 1/1/2014 | Domain name | 2233 | $10.98 |
-+----------+-------------+-------+---------+
-`
-
- got := buf.String()
- if got != want {
- t.Errorf("table clear rows failed\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-}
-
-func TestMoreDataColumnsThanHeaders(t *testing.T) {
- var (
- buf = &bytes.Buffer{}
- table = NewWriter(buf)
- header = []string{"A", "B", "C"}
- data = [][]string{
- []string{"a", "b", "c", "d"},
- []string{"1", "2", "3", "4"},
- }
- want = `+---+---+---+---+
-| A | B | C | |
-+---+---+---+---+
-| a | b | c | d |
-| 1 | 2 | 3 | 4 |
-+---+---+---+---+
-`
- )
- table.SetHeader(header)
- // table.SetFooter(ctx.tableCtx.footer)
- table.AppendBulk(data)
- table.Render()
-
- got := buf.String()
-
- if got != want {
- t.Errorf("\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-}
-
-func TestMoreFooterColumnsThanHeaders(t *testing.T) {
- var (
- buf = &bytes.Buffer{}
- table = NewWriter(buf)
- header = []string{"A", "B", "C"}
- data = [][]string{
- []string{"a", "b", "c", "d"},
- []string{"1", "2", "3", "4"},
- }
- footer = []string{"a", "b", "c", "d", "e"}
- want = `+---+---+---+---+---+
-| A | B | C | | |
-+---+---+---+---+---+
-| a | b | c | d |
-| 1 | 2 | 3 | 4 |
-+---+---+---+---+---+
-| A | B | C | D | E |
-+---+---+---+---+---+
-`
- )
- table.SetHeader(header)
- table.SetFooter(footer)
- table.AppendBulk(data)
- table.Render()
-
- got := buf.String()
-
- if got != want {
- t.Errorf("\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-}
-
-func TestSetColMinWidth(t *testing.T) {
- var (
- buf = &bytes.Buffer{}
- table = NewWriter(buf)
- header = []string{"AAA", "BBB", "CCC"}
- data = [][]string{
- []string{"a", "b", "c"},
- []string{"1", "2", "3"},
- }
- footer = []string{"a", "b", "cccc"}
- want = `+-----+-----+-------+
-| AAA | BBB | CCC |
-+-----+-----+-------+
-| a | b | c |
-| 1 | 2 | 3 |
-+-----+-----+-------+
-| A | B | CCCC |
-+-----+-----+-------+
-`
- )
- table.SetHeader(header)
- table.SetFooter(footer)
- table.AppendBulk(data)
- table.SetColMinWidth(2, 5)
- table.Render()
-
- got := buf.String()
-
- if got != want {
- t.Errorf("\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-}
-
-func TestWrapString(t *testing.T) {
- want := []string{"ああああああああああああああああああああああああ", "あああああああ"}
- got, _ := WrapString("ああああああああああああああああああああああああ あああああああ", 55)
- if !reflect.DeepEqual(got, want) {
- t.Errorf("\ngot:\n%v\nwant:\n%v\n", got, want)
- }
-}
-
-func TestCustomAlign(t *testing.T) {
- var (
- buf = &bytes.Buffer{}
- table = NewWriter(buf)
- header = []string{"AAA", "BBB", "CCC"}
- data = [][]string{
- []string{"a", "b", "c"},
- []string{"1", "2", "3"},
- }
- footer = []string{"a", "b", "cccc"}
- want = `+-----+-----+-------+
-| AAA | BBB | CCC |
-+-----+-----+-------+
-| a | b | c |
-| 1 | 2 | 3 |
-+-----+-----+-------+
-| A | B | CCCC |
-+-----+-----+-------+
-`
- )
- table.SetHeader(header)
- table.SetFooter(footer)
- table.AppendBulk(data)
- table.SetColMinWidth(2, 5)
- table.SetColumnAlignment([]int{ALIGN_LEFT, ALIGN_CENTER, ALIGN_RIGHT})
- table.Render()
-
- got := buf.String()
-
- if got != want {
- t.Errorf("\ngot:\n%s\nwant:\n%s\n", got, want)
- }
-}
diff --git a/vendor/github.com/olekukonko/tablewriter/table_with_color.go b/vendor/github.com/olekukonko/tablewriter/table_with_color.go
deleted file mode 100644
index 5a4a53e..0000000
--- a/vendor/github.com/olekukonko/tablewriter/table_with_color.go
+++ /dev/null
@@ -1,134 +0,0 @@
-package tablewriter
-
-import (
- "fmt"
- "strconv"
- "strings"
-)
-
-const ESC = "\033"
-const SEP = ";"
-
-const (
- BgBlackColor int = iota + 40
- BgRedColor
- BgGreenColor
- BgYellowColor
- BgBlueColor
- BgMagentaColor
- BgCyanColor
- BgWhiteColor
-)
-
-const (
- FgBlackColor int = iota + 30
- FgRedColor
- FgGreenColor
- FgYellowColor
- FgBlueColor
- FgMagentaColor
- FgCyanColor
- FgWhiteColor
-)
-
-const (
- BgHiBlackColor int = iota + 100
- BgHiRedColor
- BgHiGreenColor
- BgHiYellowColor
- BgHiBlueColor
- BgHiMagentaColor
- BgHiCyanColor
- BgHiWhiteColor
-)
-
-const (
- FgHiBlackColor int = iota + 90
- FgHiRedColor
- FgHiGreenColor
- FgHiYellowColor
- FgHiBlueColor
- FgHiMagentaColor
- FgHiCyanColor
- FgHiWhiteColor
-)
-
-const (
- Normal = 0
- Bold = 1
- UnderlineSingle = 4
- Italic
-)
-
-type Colors []int
-
-func startFormat(seq string) string {
- return fmt.Sprintf("%s[%sm", ESC, seq)
-}
-
-func stopFormat() string {
- return fmt.Sprintf("%s[%dm", ESC, Normal)
-}
-
-// Making the SGR (Select Graphic Rendition) sequence.
-func makeSequence(codes []int) string {
- codesInString := []string{}
- for _, code := range codes {
- codesInString = append(codesInString, strconv.Itoa(code))
- }
- return strings.Join(codesInString, SEP)
-}
-
-// Adding ANSI escape sequences before and after string
-func format(s string, codes interface{}) string {
- var seq string
-
- switch v := codes.(type) {
-
- case string:
- seq = v
- case []int:
- seq = makeSequence(v)
- default:
- return s
- }
-
- if len(seq) == 0 {
- return s
- }
- return startFormat(seq) + s + stopFormat()
-}
-
-// Adding header colors (ANSI codes)
-func (t *Table) SetHeaderColor(colors ...Colors) {
- if t.colSize != len(colors) {
- panic("Number of header colors must be equal to number of headers.")
- }
- for i := 0; i < len(colors); i++ {
- t.headerParams = append(t.headerParams, makeSequence(colors[i]))
- }
-}
-
-// Adding column colors (ANSI codes)
-func (t *Table) SetColumnColor(colors ...Colors) {
- if t.colSize != len(colors) {
- panic("Number of column colors must be equal to number of headers.")
- }
- for i := 0; i < len(colors); i++ {
- t.columnsParams = append(t.columnsParams, makeSequence(colors[i]))
- }
-}
-
-// Adding column colors (ANSI codes)
-func (t *Table) SetFooterColor(colors ...Colors) {
- if len(t.footers) != len(colors) {
- panic("Number of footer colors must be equal to number of footer.")
- }
- for i := 0; i < len(colors); i++ {
- t.footerParams = append(t.footerParams, makeSequence(colors[i]))
- }
-}
-
-func Color(colors ...int) []int {
- return colors
-}
diff --git a/vendor/github.com/olekukonko/tablewriter/test.csv b/vendor/github.com/olekukonko/tablewriter/test.csv
deleted file mode 100644
index 1609327..0000000
--- a/vendor/github.com/olekukonko/tablewriter/test.csv
+++ /dev/null
@@ -1,4 +0,0 @@
-first_name,last_name,ssn
-John,Barry,123456
-Kathy,Smith,687987
-Bob,McCornick,3979870
\ No newline at end of file
diff --git a/vendor/github.com/olekukonko/tablewriter/test_info.csv b/vendor/github.com/olekukonko/tablewriter/test_info.csv
deleted file mode 100644
index e4c40e9..0000000
--- a/vendor/github.com/olekukonko/tablewriter/test_info.csv
+++ /dev/null
@@ -1,4 +0,0 @@
-Field,Type,Null,Key,Default,Extra
-user_id,smallint(5),NO,PRI,NULL,auto_increment
-username,varchar(10),NO,,NULL,
-password,varchar(100),NO,,NULL,
\ No newline at end of file
diff --git a/vendor/github.com/olekukonko/tablewriter/util.go b/vendor/github.com/olekukonko/tablewriter/util.go
deleted file mode 100644
index 2deefbc..0000000
--- a/vendor/github.com/olekukonko/tablewriter/util.go
+++ /dev/null
@@ -1,72 +0,0 @@
-// Copyright 2014 Oleku Konko All rights reserved.
-// Use of this source code is governed by a MIT
-// license that can be found in the LICENSE file.
-
-// This module is a Table Writer API for the Go Programming Language.
-// The protocols were written in pure Go and works on windows and unix systems
-
-package tablewriter
-
-import (
- "math"
- "regexp"
- "strings"
-
- "github.com/mattn/go-runewidth"
-)
-
-var ansi = regexp.MustCompile("\033\\[(?:[0-9]{1,3}(?:;[0-9]{1,3})*)?[m|K]")
-
-func DisplayWidth(str string) int {
- return runewidth.StringWidth(ansi.ReplaceAllLiteralString(str, ""))
-}
-
-// Simple Condition for string
-// Returns value based on condition
-func ConditionString(cond bool, valid, inValid string) string {
- if cond {
- return valid
- }
- return inValid
-}
-
-// Format Table Header
-// Replace _ , . and spaces
-func Title(name string) string {
- name = strings.Replace(name, "_", " ", -1)
- name = strings.Replace(name, ".", " ", -1)
- name = strings.TrimSpace(name)
- return strings.ToUpper(name)
-}
-
-// Pad String
-// Attempts to play string in the center
-func Pad(s, pad string, width int) string {
- gap := width - DisplayWidth(s)
- if gap > 0 {
- gapLeft := int(math.Ceil(float64(gap / 2)))
- gapRight := gap - gapLeft
- return strings.Repeat(string(pad), gapLeft) + s + strings.Repeat(string(pad), gapRight)
- }
- return s
-}
-
-// Pad String Right position
-// This would pace string at the left side fo the screen
-func PadRight(s, pad string, width int) string {
- gap := width - DisplayWidth(s)
- if gap > 0 {
- return s + strings.Repeat(string(pad), gap)
- }
- return s
-}
-
-// Pad String Left position
-// This would pace string at the right side fo the screen
-func PadLeft(s, pad string, width int) string {
- gap := width - DisplayWidth(s)
- if gap > 0 {
- return strings.Repeat(string(pad), gap) + s
- }
- return s
-}
diff --git a/vendor/github.com/olekukonko/tablewriter/wrap.go b/vendor/github.com/olekukonko/tablewriter/wrap.go
deleted file mode 100644
index 9ef69e9..0000000
--- a/vendor/github.com/olekukonko/tablewriter/wrap.go
+++ /dev/null
@@ -1,104 +0,0 @@
-// Copyright 2014 Oleku Konko All rights reserved.
-// Use of this source code is governed by a MIT
-// license that can be found in the LICENSE file.
-
-// This module is a Table Writer API for the Go Programming Language.
-// The protocols were written in pure Go and works on windows and unix systems
-
-package tablewriter
-
-import (
- "math"
- "strings"
-
- "github.com/mattn/go-runewidth"
-)
-
-var (
- nl = "\n"
- sp = " "
-)
-
-const defaultPenalty = 1e5
-
-// Wrap wraps s into a paragraph of lines of length lim, with minimal
-// raggedness.
-func WrapString(s string, lim int) ([]string, int) {
- words := strings.Split(strings.Replace(s, nl, sp, -1), sp)
- var lines []string
- max := 0
- for _, v := range words {
- max = runewidth.StringWidth(v)
- if max > lim {
- lim = max
- }
- }
- for _, line := range WrapWords(words, 1, lim, defaultPenalty) {
- lines = append(lines, strings.Join(line, sp))
- }
- return lines, lim
-}
-
-// WrapWords is the low-level line-breaking algorithm, useful if you need more
-// control over the details of the text wrapping process. For most uses,
-// WrapString will be sufficient and more convenient.
-//
-// WrapWords splits a list of words into lines with minimal "raggedness",
-// treating each rune as one unit, accounting for spc units between adjacent
-// words on each line, and attempting to limit lines to lim units. Raggedness
-// is the total error over all lines, where error is the square of the
-// difference of the length of the line and lim. Too-long lines (which only
-// happen when a single word is longer than lim units) have pen penalty units
-// added to the error.
-func WrapWords(words []string, spc, lim, pen int) [][]string {
- n := len(words)
-
- length := make([][]int, n)
- for i := 0; i < n; i++ {
- length[i] = make([]int, n)
- length[i][i] = runewidth.StringWidth(words[i])
- for j := i + 1; j < n; j++ {
- length[i][j] = length[i][j-1] + spc + runewidth.StringWidth(words[j])
- }
- }
- nbrk := make([]int, n)
- cost := make([]int, n)
- for i := range cost {
- cost[i] = math.MaxInt32
- }
- for i := n - 1; i >= 0; i-- {
- if length[i][n-1] <= lim {
- cost[i] = 0
- nbrk[i] = n
- } else {
- for j := i + 1; j < n; j++ {
- d := lim - length[i][j-1]
- c := d*d + cost[j]
- if length[i][j-1] > lim {
- c += pen // too-long lines get a worse penalty
- }
- if c < cost[i] {
- cost[i] = c
- nbrk[i] = j
- }
- }
- }
- }
- var lines [][]string
- i := 0
- for i < n {
- lines = append(lines, words[i:nbrk[i]])
- i = nbrk[i]
- }
- return lines
-}
-
-// getLines decomposes a multiline string into a slice of strings.
-func getLines(s string) []string {
- var lines []string
-
- for _, line := range strings.Split(s, nl) {
- lines = append(lines, line)
- }
- return lines
-}
diff --git a/vendor/github.com/olekukonko/tablewriter/wrap_test.go b/vendor/github.com/olekukonko/tablewriter/wrap_test.go
deleted file mode 100644
index bec56b6..0000000
--- a/vendor/github.com/olekukonko/tablewriter/wrap_test.go
+++ /dev/null
@@ -1,66 +0,0 @@
-// Copyright 2014 Oleku Konko All rights reserved.
-// Use of this source code is governed by a MIT
-// license that can be found in the LICENSE file.
-
-// This module is a Table Writer API for the Go Programming Language.
-// The protocols were written in pure Go and works on windows and unix systems
-
-package tablewriter
-
-import (
- "strings"
- "testing"
-
- "github.com/mattn/go-runewidth"
-)
-
-var text = "The quick brown fox jumps over the lazy dog."
-
-func TestWrap(t *testing.T) {
- exp := []string{
- "The", "quick", "brown", "fox",
- "jumps", "over", "the", "lazy", "dog."}
-
- got, _ := WrapString(text, 6)
- if len(exp) != len(got) {
- t.Fail()
- }
-}
-
-func TestWrapOneLine(t *testing.T) {
- exp := "The quick brown fox jumps over the lazy dog."
- words, _ := WrapString(text, 500)
- got := strings.Join(words, string(sp))
- if exp != got {
- t.Errorf("expected: %q, got: %q", exp, got)
- }
-}
-
-func TestUnicode(t *testing.T) {
- input := "Česká řeřicha"
- var wordsUnicode []string
- if runewidth.IsEastAsian() {
- wordsUnicode, _ = WrapString(input, 14)
- } else {
- wordsUnicode, _ = WrapString(input, 13)
- }
- // input contains 13 (or 14 for CJK) runes, so it fits on one line.
- if len(wordsUnicode) != 1 {
- t.Fail()
- }
-}
-
-func TestDisplayWidth(t *testing.T) {
- input := "Česká řeřicha"
- want := 13
- if runewidth.IsEastAsian() {
- want = 14
- }
- if n := DisplayWidth(input); n != want {
- t.Errorf("Wants: %d Got: %d", want, n)
- }
- input = "\033[43;30m" + input + "\033[00m"
- if n := DisplayWidth(input); n != want {
- t.Errorf("Wants: %d Got: %d", want, n)
- }
-}
diff --git a/vendor/github.com/pelletier/go-toml/.gitignore b/vendor/github.com/pelletier/go-toml/.gitignore
deleted file mode 100644
index f1b6190..0000000
--- a/vendor/github.com/pelletier/go-toml/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-test_program/test_program_bin
diff --git a/vendor/github.com/pelletier/go-toml/.travis.yml b/vendor/github.com/pelletier/go-toml/.travis.yml
deleted file mode 100644
index 4966911..0000000
--- a/vendor/github.com/pelletier/go-toml/.travis.yml
+++ /dev/null
@@ -1,23 +0,0 @@
-sudo: false
-language: go
-go:
- - 1.7.6
- - 1.8.3
- - 1.9
- - tip
-matrix:
- allow_failures:
- - go: tip
- fast_finish: true
-script:
- - if [ -n "$(go fmt ./...)" ]; then exit 1; fi
- - ./test.sh
- - ./benchmark.sh $TRAVIS_BRANCH https://github.com/$TRAVIS_REPO_SLUG.git
-before_install:
- - go get github.com/axw/gocov/gocov
- - go get github.com/mattn/goveralls
- - if ! go get code.google.com/p/go.tools/cmd/cover; then go get golang.org/x/tools/cmd/cover; fi
-branches:
- only: [master]
-after_success:
- - $HOME/gopath/bin/goveralls -service=travis-ci -coverprofile=coverage.out -repotoken $COVERALLS_TOKEN
diff --git a/vendor/github.com/pelletier/go-toml/LICENSE b/vendor/github.com/pelletier/go-toml/LICENSE
deleted file mode 100644
index 583bdae..0000000
--- a/vendor/github.com/pelletier/go-toml/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2013 - 2017 Thomas Pelletier, Eric Anderton
-
-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.
diff --git a/vendor/github.com/pelletier/go-toml/README.md b/vendor/github.com/pelletier/go-toml/README.md
deleted file mode 100644
index 2681690..0000000
--- a/vendor/github.com/pelletier/go-toml/README.md
+++ /dev/null
@@ -1,119 +0,0 @@
-# go-toml
-
-Go library for the [TOML](https://github.com/mojombo/toml) format.
-
-This library supports TOML version
-[v0.4.0](https://github.com/toml-lang/toml/blob/master/versions/en/toml-v0.4.0.md)
-
-[](http://godoc.org/github.com/pelletier/go-toml)
-[](https://github.com/pelletier/go-toml/blob/master/LICENSE)
-[](https://travis-ci.org/pelletier/go-toml)
-[](https://coveralls.io/github/pelletier/go-toml?branch=master)
-[](https://goreportcard.com/report/github.com/pelletier/go-toml)
-
-## Features
-
-Go-toml provides the following features for using data parsed from TOML documents:
-
-* Load TOML documents from files and string data
-* Easily navigate TOML structure using Tree
-* Mashaling and unmarshaling to and from data structures
-* Line & column position data for all parsed elements
-* [Query support similar to JSON-Path](query/)
-* Syntax errors contain line and column numbers
-
-## Import
-
-```go
-import "github.com/pelletier/go-toml"
-```
-
-## Usage example
-
-Read a TOML document:
-
-```go
-config, _ := toml.Load(`
-[postgres]
-user = "pelletier"
-password = "mypassword"`)
-// retrieve data directly
-user := config.Get("postgres.user").(string)
-
-// or using an intermediate object
-postgresConfig := config.Get("postgres").(*toml.Tree)
-password := postgresConfig.Get("password").(string)
-```
-
-Or use Unmarshal:
-
-```go
-type Postgres struct {
- User string
- Password string
-}
-type Config struct {
- Postgres Postgres
-}
-
-doc := []byte(`
-[postgres]
-user = "pelletier"
-password = "mypassword"`)
-
-config := Config{}
-toml.Unmarshal(doc, &config)
-fmt.Println("user=", config.Postgres.User)
-```
-
-Or use a query:
-
-```go
-// use a query to gather elements without walking the tree
-q, _ := query.Compile("$..[user,password]")
-results := q.Execute(config)
-for ii, item := range results.Values() {
- fmt.Println("Query result %d: %v", ii, item)
-}
-```
-
-## Documentation
-
-The documentation and additional examples are available at
-[godoc.org](http://godoc.org/github.com/pelletier/go-toml).
-
-## Tools
-
-Go-toml provides two handy command line tools:
-
-* `tomll`: Reads TOML files and lint them.
-
- ```
- go install github.com/pelletier/go-toml/cmd/tomll
- tomll --help
- ```
-* `tomljson`: Reads a TOML file and outputs its JSON representation.
-
- ```
- go install github.com/pelletier/go-toml/cmd/tomljson
- tomljson --help
- ```
-
-## Contribute
-
-Feel free to report bugs and patches using GitHub's pull requests system on
-[pelletier/go-toml](https://github.com/pelletier/go-toml). Any feedback would be
-much appreciated!
-
-### Run tests
-
-You have to make sure two kind of tests run:
-
-1. The Go unit tests
-2. The TOML examples base
-
-You can run both of them using `./test.sh`.
-
-## License
-
-The MIT License (MIT). Read [LICENSE](LICENSE).
diff --git a/vendor/github.com/pelletier/go-toml/benchmark.json b/vendor/github.com/pelletier/go-toml/benchmark.json
deleted file mode 100644
index 86f99c6..0000000
--- a/vendor/github.com/pelletier/go-toml/benchmark.json
+++ /dev/null
@@ -1,164 +0,0 @@
-{
- "array": {
- "key1": [
- 1,
- 2,
- 3
- ],
- "key2": [
- "red",
- "yellow",
- "green"
- ],
- "key3": [
- [
- 1,
- 2
- ],
- [
- 3,
- 4,
- 5
- ]
- ],
- "key4": [
- [
- 1,
- 2
- ],
- [
- "a",
- "b",
- "c"
- ]
- ],
- "key5": [
- 1,
- 2,
- 3
- ],
- "key6": [
- 1,
- 2
- ]
- },
- "boolean": {
- "False": false,
- "True": true
- },
- "datetime": {
- "key1": "1979-05-27T07:32:00Z",
- "key2": "1979-05-27T00:32:00-07:00",
- "key3": "1979-05-27T00:32:00.999999-07:00"
- },
- "float": {
- "both": {
- "key": 6.626e-34
- },
- "exponent": {
- "key1": 5e+22,
- "key2": 1000000,
- "key3": -0.02
- },
- "fractional": {
- "key1": 1,
- "key2": 3.1415,
- "key3": -0.01
- },
- "underscores": {
- "key1": 9224617.445991227,
- "key2": 1e+100
- }
- },
- "fruit": [{
- "name": "apple",
- "physical": {
- "color": "red",
- "shape": "round"
- },
- "variety": [{
- "name": "red delicious"
- },
- {
- "name": "granny smith"
- }
- ]
- },
- {
- "name": "banana",
- "variety": [{
- "name": "plantain"
- }]
- }
- ],
- "integer": {
- "key1": 99,
- "key2": 42,
- "key3": 0,
- "key4": -17,
- "underscores": {
- "key1": 1000,
- "key2": 5349221,
- "key3": 12345
- }
- },
- "products": [{
- "name": "Hammer",
- "sku": 738594937
- },
- {},
- {
- "color": "gray",
- "name": "Nail",
- "sku": 284758393
- }
- ],
- "string": {
- "basic": {
- "basic": "I'm a string. \"You can quote me\". Name\tJosé\nLocation\tSF."
- },
- "literal": {
- "multiline": {
- "lines": "The first newline is\ntrimmed in raw strings.\n All other whitespace\n is preserved.\n",
- "regex2": "I [dw]on't need \\d{2} apples"
- },
- "quoted": "Tom \"Dubs\" Preston-Werner",
- "regex": "\u003c\\i\\c*\\s*\u003e",
- "winpath": "C:\\Users\\nodejs\\templates",
- "winpath2": "\\\\ServerX\\admin$\\system32\\"
- },
- "multiline": {
- "continued": {
- "key1": "The quick brown fox jumps over the lazy dog.",
- "key2": "The quick brown fox jumps over the lazy dog.",
- "key3": "The quick brown fox jumps over the lazy dog."
- },
- "key1": "One\nTwo",
- "key2": "One\nTwo",
- "key3": "One\nTwo"
- }
- },
- "table": {
- "inline": {
- "name": {
- "first": "Tom",
- "last": "Preston-Werner"
- },
- "point": {
- "x": 1,
- "y": 2
- }
- },
- "key": "value",
- "subtable": {
- "key": "another value"
- }
- },
- "x": {
- "y": {
- "z": {
- "w": {}
- }
- }
- }
-}
diff --git a/vendor/github.com/pelletier/go-toml/benchmark.sh b/vendor/github.com/pelletier/go-toml/benchmark.sh
deleted file mode 100755
index 8b8bb52..0000000
--- a/vendor/github.com/pelletier/go-toml/benchmark.sh
+++ /dev/null
@@ -1,32 +0,0 @@
-#!/bin/bash
-
-set -e
-
-reference_ref=${1:-master}
-reference_git=${2:-.}
-
-if ! `hash benchstat 2>/dev/null`; then
- echo "Installing benchstat"
- go get golang.org/x/perf/cmd/benchstat
- go install golang.org/x/perf/cmd/benchstat
-fi
-
-tempdir=`mktemp -d /tmp/go-toml-benchmark-XXXXXX`
-ref_tempdir="${tempdir}/ref"
-ref_benchmark="${ref_tempdir}/benchmark-`echo -n ${reference_ref}|tr -s '/' '-'`.txt"
-local_benchmark="`pwd`/benchmark-local.txt"
-
-echo "=== ${reference_ref} (${ref_tempdir})"
-git clone ${reference_git} ${ref_tempdir} >/dev/null 2>/dev/null
-pushd ${ref_tempdir} >/dev/null
-git checkout ${reference_ref} >/dev/null 2>/dev/null
-go test -bench=. -benchmem | tee ${ref_benchmark}
-popd >/dev/null
-
-echo ""
-echo "=== local"
-go test -bench=. -benchmem | tee ${local_benchmark}
-
-echo ""
-echo "=== diff"
-benchstat -delta-test=none ${ref_benchmark} ${local_benchmark}
\ No newline at end of file
diff --git a/vendor/github.com/pelletier/go-toml/benchmark.toml b/vendor/github.com/pelletier/go-toml/benchmark.toml
deleted file mode 100644
index dfd77e0..0000000
--- a/vendor/github.com/pelletier/go-toml/benchmark.toml
+++ /dev/null
@@ -1,244 +0,0 @@
-################################################################################
-## Comment
-
-# Speak your mind with the hash symbol. They go from the symbol to the end of
-# the line.
-
-
-################################################################################
-## Table
-
-# Tables (also known as hash tables or dictionaries) are collections of
-# key/value pairs. They appear in square brackets on a line by themselves.
-
-[table]
-
-key = "value" # Yeah, you can do this.
-
-# Nested tables are denoted by table names with dots in them. Name your tables
-# whatever crap you please, just don't use #, ., [ or ].
-
-[table.subtable]
-
-key = "another value"
-
-# You don't need to specify all the super-tables if you don't want to. TOML
-# knows how to do it for you.
-
-# [x] you
-# [x.y] don't
-# [x.y.z] need these
-[x.y.z.w] # for this to work
-
-
-################################################################################
-## Inline Table
-
-# Inline tables provide a more compact syntax for expressing tables. They are
-# especially useful for grouped data that can otherwise quickly become verbose.
-# Inline tables are enclosed in curly braces `{` and `}`. No newlines are
-# allowed between the curly braces unless they are valid within a value.
-
-[table.inline]
-
-name = { first = "Tom", last = "Preston-Werner" }
-point = { x = 1, y = 2 }
-
-
-################################################################################
-## String
-
-# There are four ways to express strings: basic, multi-line basic, literal, and
-# multi-line literal. All strings must contain only valid UTF-8 characters.
-
-[string.basic]
-
-basic = "I'm a string. \"You can quote me\". Name\tJos\u00E9\nLocation\tSF."
-
-[string.multiline]
-
-# The following strings are byte-for-byte equivalent:
-key1 = "One\nTwo"
-key2 = """One\nTwo"""
-key3 = """
-One
-Two"""
-
-[string.multiline.continued]
-
-# The following strings are byte-for-byte equivalent:
-key1 = "The quick brown fox jumps over the lazy dog."
-
-key2 = """
-The quick brown \
-
-
- fox jumps over \
- the lazy dog."""
-
-key3 = """\
- The quick brown \
- fox jumps over \
- the lazy dog.\
- """
-
-[string.literal]
-
-# What you see is what you get.
-winpath = 'C:\Users\nodejs\templates'
-winpath2 = '\\ServerX\admin$\system32\'
-quoted = 'Tom "Dubs" Preston-Werner'
-regex = '<\i\c*\s*>'
-
-
-[string.literal.multiline]
-
-regex2 = '''I [dw]on't need \d{2} apples'''
-lines = '''
-The first newline is
-trimmed in raw strings.
- All other whitespace
- is preserved.
-'''
-
-
-################################################################################
-## Integer
-
-# Integers are whole numbers. Positive numbers may be prefixed with a plus sign.
-# Negative numbers are prefixed with a minus sign.
-
-[integer]
-
-key1 = +99
-key2 = 42
-key3 = 0
-key4 = -17
-
-[integer.underscores]
-
-# For large numbers, you may use underscores to enhance readability. Each
-# underscore must be surrounded by at least one digit.
-key1 = 1_000
-key2 = 5_349_221
-key3 = 1_2_3_4_5 # valid but inadvisable
-
-
-################################################################################
-## Float
-
-# A float consists of an integer part (which may be prefixed with a plus or
-# minus sign) followed by a fractional part and/or an exponent part.
-
-[float.fractional]
-
-key1 = +1.0
-key2 = 3.1415
-key3 = -0.01
-
-[float.exponent]
-
-key1 = 5e+22
-key2 = 1e6
-key3 = -2E-2
-
-[float.both]
-
-key = 6.626e-34
-
-[float.underscores]
-
-key1 = 9_224_617.445_991_228_313
-key2 = 1e1_00
-
-
-################################################################################
-## Boolean
-
-# Booleans are just the tokens you're used to. Always lowercase.
-
-[boolean]
-
-True = true
-False = false
-
-
-################################################################################
-## Datetime
-
-# Datetimes are RFC 3339 dates.
-
-[datetime]
-
-key1 = 1979-05-27T07:32:00Z
-key2 = 1979-05-27T00:32:00-07:00
-key3 = 1979-05-27T00:32:00.999999-07:00
-
-
-################################################################################
-## Array
-
-# Arrays are square brackets with other primitives inside. Whitespace is
-# ignored. Elements are separated by commas. Data types may not be mixed.
-
-[array]
-
-key1 = [ 1, 2, 3 ]
-key2 = [ "red", "yellow", "green" ]
-key3 = [ [ 1, 2 ], [3, 4, 5] ]
-#key4 = [ [ 1, 2 ], ["a", "b", "c"] ] # this is ok
-
-# Arrays can also be multiline. So in addition to ignoring whitespace, arrays
-# also ignore newlines between the brackets. Terminating commas are ok before
-# the closing bracket.
-
-key5 = [
- 1, 2, 3
-]
-key6 = [
- 1,
- 2, # this is ok
-]
-
-
-################################################################################
-## Array of Tables
-
-# These can be expressed by using a table name in double brackets. Each table
-# with the same double bracketed name will be an element in the array. The
-# tables are inserted in the order encountered.
-
-[[products]]
-
-name = "Hammer"
-sku = 738594937
-
-[[products]]
-
-[[products]]
-
-name = "Nail"
-sku = 284758393
-color = "gray"
-
-
-# You can create nested arrays of tables as well.
-
-[[fruit]]
- name = "apple"
-
- [fruit.physical]
- color = "red"
- shape = "round"
-
- [[fruit.variety]]
- name = "red delicious"
-
- [[fruit.variety]]
- name = "granny smith"
-
-[[fruit]]
- name = "banana"
-
- [[fruit.variety]]
- name = "plantain"
diff --git a/vendor/github.com/pelletier/go-toml/benchmark.yml b/vendor/github.com/pelletier/go-toml/benchmark.yml
deleted file mode 100644
index 0bd19f0..0000000
--- a/vendor/github.com/pelletier/go-toml/benchmark.yml
+++ /dev/null
@@ -1,121 +0,0 @@
----
-array:
- key1:
- - 1
- - 2
- - 3
- key2:
- - red
- - yellow
- - green
- key3:
- - - 1
- - 2
- - - 3
- - 4
- - 5
- key4:
- - - 1
- - 2
- - - a
- - b
- - c
- key5:
- - 1
- - 2
- - 3
- key6:
- - 1
- - 2
-boolean:
- 'False': false
- 'True': true
-datetime:
- key1: '1979-05-27T07:32:00Z'
- key2: '1979-05-27T00:32:00-07:00'
- key3: '1979-05-27T00:32:00.999999-07:00'
-float:
- both:
- key: 6.626e-34
- exponent:
- key1: 5.0e+22
- key2: 1000000
- key3: -0.02
- fractional:
- key1: 1
- key2: 3.1415
- key3: -0.01
- underscores:
- key1: 9224617.445991227
- key2: 1.0e+100
-fruit:
-- name: apple
- physical:
- color: red
- shape: round
- variety:
- - name: red delicious
- - name: granny smith
-- name: banana
- variety:
- - name: plantain
-integer:
- key1: 99
- key2: 42
- key3: 0
- key4: -17
- underscores:
- key1: 1000
- key2: 5349221
- key3: 12345
-products:
-- name: Hammer
- sku: 738594937
-- {}
-- color: gray
- name: Nail
- sku: 284758393
-string:
- basic:
- basic: "I'm a string. \"You can quote me\". Name\tJosé\nLocation\tSF."
- literal:
- multiline:
- lines: |
- The first newline is
- trimmed in raw strings.
- All other whitespace
- is preserved.
- regex2: I [dw]on't need \d{2} apples
- quoted: Tom "Dubs" Preston-Werner
- regex: "<\\i\\c*\\s*>"
- winpath: C:\Users\nodejs\templates
- winpath2: "\\\\ServerX\\admin$\\system32\\"
- multiline:
- continued:
- key1: The quick brown fox jumps over the lazy dog.
- key2: The quick brown fox jumps over the lazy dog.
- key3: The quick brown fox jumps over the lazy dog.
- key1: |-
- One
- Two
- key2: |-
- One
- Two
- key3: |-
- One
- Two
-table:
- inline:
- name:
- first: Tom
- last: Preston-Werner
- point:
- x: 1
- y: 2
- key: value
- subtable:
- key: another value
-x:
- y:
- z:
- w: {}
diff --git a/vendor/github.com/pelletier/go-toml/benchmark_test.go b/vendor/github.com/pelletier/go-toml/benchmark_test.go
deleted file mode 100644
index e1f209d..0000000
--- a/vendor/github.com/pelletier/go-toml/benchmark_test.go
+++ /dev/null
@@ -1,192 +0,0 @@
-package toml
-
-import (
- "bytes"
- "encoding/json"
- "io/ioutil"
- "testing"
- "time"
-
- burntsushi "github.com/BurntSushi/toml"
- yaml "gopkg.in/yaml.v2"
-)
-
-type benchmarkDoc struct {
- Table struct {
- Key string
- Subtable struct {
- Key string
- }
- Inline struct {
- Name struct {
- First string
- Last string
- }
- Point struct {
- X int64
- U int64
- }
- }
- }
- String struct {
- Basic struct {
- Basic string
- }
- Multiline struct {
- Key1 string
- Key2 string
- Key3 string
- Continued struct {
- Key1 string
- Key2 string
- Key3 string
- }
- }
- Literal struct {
- Winpath string
- Winpath2 string
- Quoted string
- Regex string
- Multiline struct {
- Regex2 string
- Lines string
- }
- }
- }
- Integer struct {
- Key1 int64
- Key2 int64
- Key3 int64
- Key4 int64
- Underscores struct {
- Key1 int64
- Key2 int64
- Key3 int64
- }
- }
- Float struct {
- Fractional struct {
- Key1 float64
- Key2 float64
- Key3 float64
- }
- Exponent struct {
- Key1 float64
- Key2 float64
- Key3 float64
- }
- Both struct {
- Key float64
- }
- Underscores struct {
- Key1 float64
- Key2 float64
- }
- }
- Boolean struct {
- True bool
- False bool
- }
- Datetime struct {
- Key1 time.Time
- Key2 time.Time
- Key3 time.Time
- }
- Array struct {
- Key1 []int64
- Key2 []string
- Key3 [][]int64
- // TODO: Key4 not supported by go-toml's Unmarshal
- Key5 []int64
- Key6 []int64
- }
- Products []struct {
- Name string
- Sku int64
- Color string
- }
- Fruit []struct {
- Name string
- Physical struct {
- Color string
- Shape string
- Variety []struct {
- Name string
- }
- }
- }
-}
-
-func BenchmarkParseToml(b *testing.B) {
- fileBytes, err := ioutil.ReadFile("benchmark.toml")
- if err != nil {
- b.Fatal(err)
- }
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- _, err := LoadReader(bytes.NewReader(fileBytes))
- if err != nil {
- b.Fatal(err)
- }
- }
-}
-
-func BenchmarkUnmarshalToml(b *testing.B) {
- bytes, err := ioutil.ReadFile("benchmark.toml")
- if err != nil {
- b.Fatal(err)
- }
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- target := benchmarkDoc{}
- err := Unmarshal(bytes, &target)
- if err != nil {
- b.Fatal(err)
- }
- }
-}
-
-func BenchmarkUnmarshalBurntSushiToml(b *testing.B) {
- bytes, err := ioutil.ReadFile("benchmark.toml")
- if err != nil {
- b.Fatal(err)
- }
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- target := benchmarkDoc{}
- err := burntsushi.Unmarshal(bytes, &target)
- if err != nil {
- b.Fatal(err)
- }
- }
-}
-
-func BenchmarkUnmarshalJson(b *testing.B) {
- bytes, err := ioutil.ReadFile("benchmark.json")
- if err != nil {
- b.Fatal(err)
- }
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- target := benchmarkDoc{}
- err := json.Unmarshal(bytes, &target)
- if err != nil {
- b.Fatal(err)
- }
- }
-}
-
-func BenchmarkUnmarshalYaml(b *testing.B) {
- bytes, err := ioutil.ReadFile("benchmark.yml")
- if err != nil {
- b.Fatal(err)
- }
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- target := benchmarkDoc{}
- err := yaml.Unmarshal(bytes, &target)
- if err != nil {
- b.Fatal(err)
- }
- }
-}
diff --git a/vendor/github.com/pelletier/go-toml/doc.go b/vendor/github.com/pelletier/go-toml/doc.go
deleted file mode 100644
index 3c89619..0000000
--- a/vendor/github.com/pelletier/go-toml/doc.go
+++ /dev/null
@@ -1,23 +0,0 @@
-// Package toml is a TOML parser and manipulation library.
-//
-// This version supports the specification as described in
-// https://github.com/toml-lang/toml/blob/master/versions/en/toml-v0.4.0.md
-//
-// Marshaling
-//
-// Go-toml can marshal and unmarshal TOML documents from and to data
-// structures.
-//
-// TOML document as a tree
-//
-// Go-toml can operate on a TOML document as a tree. Use one of the Load*
-// functions to parse TOML data and obtain a Tree instance, then one of its
-// methods to manipulate the tree.
-//
-// JSONPath-like queries
-//
-// The package github.com/pelletier/go-toml/query implements a system
-// similar to JSONPath to quickly retrive elements of a TOML document using a
-// single expression. See the package documentation for more information.
-//
-package toml
diff --git a/vendor/github.com/pelletier/go-toml/doc_test.go b/vendor/github.com/pelletier/go-toml/doc_test.go
deleted file mode 100644
index a48c04b..0000000
--- a/vendor/github.com/pelletier/go-toml/doc_test.go
+++ /dev/null
@@ -1,100 +0,0 @@
-// code examples for godoc
-
-package toml_test
-
-import (
- "fmt"
- "log"
-
- toml "github.com/pelletier/go-toml"
-)
-
-func Example_tree() {
- config, err := toml.LoadFile("config.toml")
-
- if err != nil {
- fmt.Println("Error ", err.Error())
- } else {
- // retrieve data directly
- user := config.Get("postgres.user").(string)
- password := config.Get("postgres.password").(string)
-
- // or using an intermediate object
- configTree := config.Get("postgres").(*toml.Tree)
- user = configTree.Get("user").(string)
- password = configTree.Get("password").(string)
- fmt.Println("User is", user, " and password is", password)
-
- // show where elements are in the file
- fmt.Printf("User position: %v\n", configTree.GetPosition("user"))
- fmt.Printf("Password position: %v\n", configTree.GetPosition("password"))
- }
-}
-
-func Example_unmarshal() {
- type Employer struct {
- Name string
- Phone string
- }
- type Person struct {
- Name string
- Age int64
- Employer Employer
- }
-
- document := []byte(`
- name = "John"
- age = 30
- [employer]
- name = "Company Inc."
- phone = "+1 234 567 89012"
- `)
-
- person := Person{}
- toml.Unmarshal(document, &person)
- fmt.Println(person.Name, "is", person.Age, "and works at", person.Employer.Name)
- // Output:
- // John is 30 and works at Company Inc.
-}
-
-func ExampleMarshal() {
- type Postgres struct {
- User string `toml:"user"`
- Password string `toml:"password"`
- }
- type Config struct {
- Postgres Postgres `toml:"postgres"`
- }
-
- config := Config{Postgres{User: "pelletier", Password: "mypassword"}}
- b, err := toml.Marshal(config)
- if err != nil {
- log.Fatal(err)
- }
- fmt.Println(string(b))
- // Output:
- // [postgres]
- // password = "mypassword"
- // user = "pelletier"
-}
-
-func ExampleUnmarshal() {
- type Postgres struct {
- User string
- Password string
- }
- type Config struct {
- Postgres Postgres
- }
-
- doc := []byte(`
- [postgres]
- user = "pelletier"
- password = "mypassword"`)
-
- config := Config{}
- toml.Unmarshal(doc, &config)
- fmt.Println("user=", config.Postgres.User)
- // Output:
- // user= pelletier
-}
diff --git a/vendor/github.com/pelletier/go-toml/example-crlf.toml b/vendor/github.com/pelletier/go-toml/example-crlf.toml
deleted file mode 100644
index 3d902f2..0000000
--- a/vendor/github.com/pelletier/go-toml/example-crlf.toml
+++ /dev/null
@@ -1,29 +0,0 @@
-# This is a TOML document. Boom.
-
-title = "TOML Example"
-
-[owner]
-name = "Tom Preston-Werner"
-organization = "GitHub"
-bio = "GitHub Cofounder & CEO\nLikes tater tots and beer."
-dob = 1979-05-27T07:32:00Z # First class dates? Why not?
-
-[database]
-server = "192.168.1.1"
-ports = [ 8001, 8001, 8002 ]
-connection_max = 5000
-enabled = true
-
-[servers]
-
- # You can indent as you please. Tabs or spaces. TOML don't care.
- [servers.alpha]
- ip = "10.0.0.1"
- dc = "eqdc10"
-
- [servers.beta]
- ip = "10.0.0.2"
- dc = "eqdc10"
-
-[clients]
-data = [ ["gamma", "delta"], [1, 2] ] # just an update to make sure parsers support it
diff --git a/vendor/github.com/pelletier/go-toml/example.toml b/vendor/github.com/pelletier/go-toml/example.toml
deleted file mode 100644
index 3d902f2..0000000
--- a/vendor/github.com/pelletier/go-toml/example.toml
+++ /dev/null
@@ -1,29 +0,0 @@
-# This is a TOML document. Boom.
-
-title = "TOML Example"
-
-[owner]
-name = "Tom Preston-Werner"
-organization = "GitHub"
-bio = "GitHub Cofounder & CEO\nLikes tater tots and beer."
-dob = 1979-05-27T07:32:00Z # First class dates? Why not?
-
-[database]
-server = "192.168.1.1"
-ports = [ 8001, 8001, 8002 ]
-connection_max = 5000
-enabled = true
-
-[servers]
-
- # You can indent as you please. Tabs or spaces. TOML don't care.
- [servers.alpha]
- ip = "10.0.0.1"
- dc = "eqdc10"
-
- [servers.beta]
- ip = "10.0.0.2"
- dc = "eqdc10"
-
-[clients]
-data = [ ["gamma", "delta"], [1, 2] ] # just an update to make sure parsers support it
diff --git a/vendor/github.com/pelletier/go-toml/keysparsing.go b/vendor/github.com/pelletier/go-toml/keysparsing.go
deleted file mode 100644
index d62ca5f..0000000
--- a/vendor/github.com/pelletier/go-toml/keysparsing.go
+++ /dev/null
@@ -1,94 +0,0 @@
-// Parsing keys handling both bare and quoted keys.
-
-package toml
-
-import (
- "bytes"
- "errors"
- "fmt"
- "unicode"
-)
-
-func parseKey(key string) ([]string, error) {
- groups := []string{}
- var buffer bytes.Buffer
- inQuotes := false
- wasInQuotes := false
- escapeNext := false
- ignoreSpace := true
- expectDot := false
-
- for _, char := range key {
- if ignoreSpace {
- if char == ' ' {
- continue
- }
- ignoreSpace = false
- }
- if escapeNext {
- buffer.WriteRune(char)
- escapeNext = false
- continue
- }
- switch char {
- case '\\':
- escapeNext = true
- continue
- case '"':
- if inQuotes {
- groups = append(groups, buffer.String())
- buffer.Reset()
- wasInQuotes = true
- }
- inQuotes = !inQuotes
- expectDot = false
- case '.':
- if inQuotes {
- buffer.WriteRune(char)
- } else {
- if !wasInQuotes {
- if buffer.Len() == 0 {
- return nil, errors.New("empty table key")
- }
- groups = append(groups, buffer.String())
- buffer.Reset()
- }
- ignoreSpace = true
- expectDot = false
- wasInQuotes = false
- }
- case ' ':
- if inQuotes {
- buffer.WriteRune(char)
- } else {
- expectDot = true
- }
- default:
- if !inQuotes && !isValidBareChar(char) {
- return nil, fmt.Errorf("invalid bare character: %c", char)
- }
- if !inQuotes && expectDot {
- return nil, errors.New("what?")
- }
- buffer.WriteRune(char)
- expectDot = false
- }
- }
- if inQuotes {
- return nil, errors.New("mismatched quotes")
- }
- if escapeNext {
- return nil, errors.New("unfinished escape sequence")
- }
- if buffer.Len() > 0 {
- groups = append(groups, buffer.String())
- }
- if len(groups) == 0 {
- return nil, errors.New("empty key")
- }
- return groups, nil
-}
-
-func isValidBareChar(r rune) bool {
- return isAlphanumeric(r) || r == '-' || unicode.IsNumber(r)
-}
diff --git a/vendor/github.com/pelletier/go-toml/keysparsing_test.go b/vendor/github.com/pelletier/go-toml/keysparsing_test.go
deleted file mode 100644
index 1a9eccc..0000000
--- a/vendor/github.com/pelletier/go-toml/keysparsing_test.go
+++ /dev/null
@@ -1,56 +0,0 @@
-package toml
-
-import (
- "fmt"
- "testing"
-)
-
-func testResult(t *testing.T, key string, expected []string) {
- parsed, err := parseKey(key)
- t.Logf("key=%s expected=%s parsed=%s", key, expected, parsed)
- if err != nil {
- t.Fatal("Unexpected error:", err)
- }
- if len(expected) != len(parsed) {
- t.Fatal("Expected length", len(expected), "but", len(parsed), "parsed")
- }
- for index, expectedKey := range expected {
- if expectedKey != parsed[index] {
- t.Fatal("Expected", expectedKey, "at index", index, "but found", parsed[index])
- }
- }
-}
-
-func testError(t *testing.T, key string, expectedError string) {
- _, err := parseKey(key)
- if fmt.Sprintf("%s", err) != expectedError {
- t.Fatalf("Expected error \"%s\", but got \"%s\".", expectedError, err)
- }
-}
-
-func TestBareKeyBasic(t *testing.T) {
- testResult(t, "test", []string{"test"})
-}
-
-func TestBareKeyDotted(t *testing.T) {
- testResult(t, "this.is.a.key", []string{"this", "is", "a", "key"})
-}
-
-func TestDottedKeyBasic(t *testing.T) {
- testResult(t, "\"a.dotted.key\"", []string{"a.dotted.key"})
-}
-
-func TestBaseKeyPound(t *testing.T) {
- testError(t, "hello#world", "invalid bare character: #")
-}
-
-func TestQuotedKeys(t *testing.T) {
- testResult(t, `hello."foo".bar`, []string{"hello", "foo", "bar"})
- testResult(t, `"hello!"`, []string{"hello!"})
-}
-
-func TestEmptyKey(t *testing.T) {
- testError(t, "", "empty key")
- testError(t, " ", "empty key")
- testResult(t, `""`, []string{""})
-}
diff --git a/vendor/github.com/pelletier/go-toml/lexer.go b/vendor/github.com/pelletier/go-toml/lexer.go
deleted file mode 100644
index 1b6647d..0000000
--- a/vendor/github.com/pelletier/go-toml/lexer.go
+++ /dev/null
@@ -1,651 +0,0 @@
-// TOML lexer.
-//
-// Written using the principles developed by Rob Pike in
-// http://www.youtube.com/watch?v=HxaD_trXwRE
-
-package toml
-
-import (
- "bytes"
- "errors"
- "fmt"
- "regexp"
- "strconv"
- "strings"
-)
-
-var dateRegexp *regexp.Regexp
-
-// Define state functions
-type tomlLexStateFn func() tomlLexStateFn
-
-// Define lexer
-type tomlLexer struct {
- inputIdx int
- input []rune // Textual source
- currentTokenStart int
- currentTokenStop int
- tokens []token
- depth int
- line int
- col int
- endbufferLine int
- endbufferCol int
-}
-
-// Basic read operations on input
-
-func (l *tomlLexer) read() rune {
- r := l.peek()
- if r == '\n' {
- l.endbufferLine++
- l.endbufferCol = 1
- } else {
- l.endbufferCol++
- }
- l.inputIdx++
- return r
-}
-
-func (l *tomlLexer) next() rune {
- r := l.read()
-
- if r != eof {
- l.currentTokenStop++
- }
- return r
-}
-
-func (l *tomlLexer) ignore() {
- l.currentTokenStart = l.currentTokenStop
- l.line = l.endbufferLine
- l.col = l.endbufferCol
-}
-
-func (l *tomlLexer) skip() {
- l.next()
- l.ignore()
-}
-
-func (l *tomlLexer) fastForward(n int) {
- for i := 0; i < n; i++ {
- l.next()
- }
-}
-
-func (l *tomlLexer) emitWithValue(t tokenType, value string) {
- l.tokens = append(l.tokens, token{
- Position: Position{l.line, l.col},
- typ: t,
- val: value,
- })
- l.ignore()
-}
-
-func (l *tomlLexer) emit(t tokenType) {
- l.emitWithValue(t, string(l.input[l.currentTokenStart:l.currentTokenStop]))
-}
-
-func (l *tomlLexer) peek() rune {
- if l.inputIdx >= len(l.input) {
- return eof
- }
- return l.input[l.inputIdx]
-}
-
-func (l *tomlLexer) peekString(size int) string {
- maxIdx := len(l.input)
- upperIdx := l.inputIdx + size // FIXME: potential overflow
- if upperIdx > maxIdx {
- upperIdx = maxIdx
- }
- return string(l.input[l.inputIdx:upperIdx])
-}
-
-func (l *tomlLexer) follow(next string) bool {
- return next == l.peekString(len(next))
-}
-
-// Error management
-
-func (l *tomlLexer) errorf(format string, args ...interface{}) tomlLexStateFn {
- l.tokens = append(l.tokens, token{
- Position: Position{l.line, l.col},
- typ: tokenError,
- val: fmt.Sprintf(format, args...),
- })
- return nil
-}
-
-// State functions
-
-func (l *tomlLexer) lexVoid() tomlLexStateFn {
- for {
- next := l.peek()
- switch next {
- case '[':
- return l.lexTableKey
- case '#':
- return l.lexComment(l.lexVoid)
- case '=':
- return l.lexEqual
- case '\r':
- fallthrough
- case '\n':
- l.skip()
- continue
- }
-
- if isSpace(next) {
- l.skip()
- }
-
- if l.depth > 0 {
- return l.lexRvalue
- }
-
- if isKeyStartChar(next) {
- return l.lexKey
- }
-
- if next == eof {
- l.next()
- break
- }
- }
-
- l.emit(tokenEOF)
- return nil
-}
-
-func (l *tomlLexer) lexRvalue() tomlLexStateFn {
- for {
- next := l.peek()
- switch next {
- case '.':
- return l.errorf("cannot start float with a dot")
- case '=':
- return l.lexEqual
- case '[':
- l.depth++
- return l.lexLeftBracket
- case ']':
- l.depth--
- return l.lexRightBracket
- case '{':
- return l.lexLeftCurlyBrace
- case '}':
- return l.lexRightCurlyBrace
- case '#':
- return l.lexComment(l.lexRvalue)
- case '"':
- return l.lexString
- case '\'':
- return l.lexLiteralString
- case ',':
- return l.lexComma
- case '\r':
- fallthrough
- case '\n':
- l.skip()
- if l.depth == 0 {
- return l.lexVoid
- }
- return l.lexRvalue
- case '_':
- return l.errorf("cannot start number with underscore")
- }
-
- if l.follow("true") {
- return l.lexTrue
- }
-
- if l.follow("false") {
- return l.lexFalse
- }
-
- if isSpace(next) {
- l.skip()
- continue
- }
-
- if next == eof {
- l.next()
- break
- }
-
- possibleDate := l.peekString(35)
- dateMatch := dateRegexp.FindString(possibleDate)
- if dateMatch != "" {
- l.fastForward(len(dateMatch))
- return l.lexDate
- }
-
- if next == '+' || next == '-' || isDigit(next) {
- return l.lexNumber
- }
-
- if isAlphanumeric(next) {
- return l.lexKey
- }
-
- return l.errorf("no value can start with %c", next)
- }
-
- l.emit(tokenEOF)
- return nil
-}
-
-func (l *tomlLexer) lexLeftCurlyBrace() tomlLexStateFn {
- l.next()
- l.emit(tokenLeftCurlyBrace)
- return l.lexRvalue
-}
-
-func (l *tomlLexer) lexRightCurlyBrace() tomlLexStateFn {
- l.next()
- l.emit(tokenRightCurlyBrace)
- return l.lexRvalue
-}
-
-func (l *tomlLexer) lexDate() tomlLexStateFn {
- l.emit(tokenDate)
- return l.lexRvalue
-}
-
-func (l *tomlLexer) lexTrue() tomlLexStateFn {
- l.fastForward(4)
- l.emit(tokenTrue)
- return l.lexRvalue
-}
-
-func (l *tomlLexer) lexFalse() tomlLexStateFn {
- l.fastForward(5)
- l.emit(tokenFalse)
- return l.lexRvalue
-}
-
-func (l *tomlLexer) lexEqual() tomlLexStateFn {
- l.next()
- l.emit(tokenEqual)
- return l.lexRvalue
-}
-
-func (l *tomlLexer) lexComma() tomlLexStateFn {
- l.next()
- l.emit(tokenComma)
- return l.lexRvalue
-}
-
-func (l *tomlLexer) lexKey() tomlLexStateFn {
- growingString := ""
-
- for r := l.peek(); isKeyChar(r) || r == '\n' || r == '\r'; r = l.peek() {
- if r == '"' {
- l.next()
- str, err := l.lexStringAsString(`"`, false, true)
- if err != nil {
- return l.errorf(err.Error())
- }
- growingString += `"` + str + `"`
- l.next()
- continue
- } else if r == '\n' {
- return l.errorf("keys cannot contain new lines")
- } else if isSpace(r) {
- break
- } else if !isValidBareChar(r) {
- return l.errorf("keys cannot contain %c character", r)
- }
- growingString += string(r)
- l.next()
- }
- l.emitWithValue(tokenKey, growingString)
- return l.lexVoid
-}
-
-func (l *tomlLexer) lexComment(previousState tomlLexStateFn) tomlLexStateFn {
- return func() tomlLexStateFn {
- for next := l.peek(); next != '\n' && next != eof; next = l.peek() {
- if next == '\r' && l.follow("\r\n") {
- break
- }
- l.next()
- }
- l.ignore()
- return previousState
- }
-}
-
-func (l *tomlLexer) lexLeftBracket() tomlLexStateFn {
- l.next()
- l.emit(tokenLeftBracket)
- return l.lexRvalue
-}
-
-func (l *tomlLexer) lexLiteralStringAsString(terminator string, discardLeadingNewLine bool) (string, error) {
- growingString := ""
-
- if discardLeadingNewLine {
- if l.follow("\r\n") {
- l.skip()
- l.skip()
- } else if l.peek() == '\n' {
- l.skip()
- }
- }
-
- // find end of string
- for {
- if l.follow(terminator) {
- return growingString, nil
- }
-
- next := l.peek()
- if next == eof {
- break
- }
- growingString += string(l.next())
- }
-
- return "", errors.New("unclosed string")
-}
-
-func (l *tomlLexer) lexLiteralString() tomlLexStateFn {
- l.skip()
-
- // handle special case for triple-quote
- terminator := "'"
- discardLeadingNewLine := false
- if l.follow("''") {
- l.skip()
- l.skip()
- terminator = "'''"
- discardLeadingNewLine = true
- }
-
- str, err := l.lexLiteralStringAsString(terminator, discardLeadingNewLine)
- if err != nil {
- return l.errorf(err.Error())
- }
-
- l.emitWithValue(tokenString, str)
- l.fastForward(len(terminator))
- l.ignore()
- return l.lexRvalue
-}
-
-// Lex a string and return the results as a string.
-// Terminator is the substring indicating the end of the token.
-// The resulting string does not include the terminator.
-func (l *tomlLexer) lexStringAsString(terminator string, discardLeadingNewLine, acceptNewLines bool) (string, error) {
- growingString := ""
-
- if discardLeadingNewLine {
- if l.follow("\r\n") {
- l.skip()
- l.skip()
- } else if l.peek() == '\n' {
- l.skip()
- }
- }
-
- for {
- if l.follow(terminator) {
- return growingString, nil
- }
-
- if l.follow("\\") {
- l.next()
- switch l.peek() {
- case '\r':
- fallthrough
- case '\n':
- fallthrough
- case '\t':
- fallthrough
- case ' ':
- // skip all whitespace chars following backslash
- for strings.ContainsRune("\r\n\t ", l.peek()) {
- l.next()
- }
- case '"':
- growingString += "\""
- l.next()
- case 'n':
- growingString += "\n"
- l.next()
- case 'b':
- growingString += "\b"
- l.next()
- case 'f':
- growingString += "\f"
- l.next()
- case '/':
- growingString += "/"
- l.next()
- case 't':
- growingString += "\t"
- l.next()
- case 'r':
- growingString += "\r"
- l.next()
- case '\\':
- growingString += "\\"
- l.next()
- case 'u':
- l.next()
- code := ""
- for i := 0; i < 4; i++ {
- c := l.peek()
- if !isHexDigit(c) {
- return "", errors.New("unfinished unicode escape")
- }
- l.next()
- code = code + string(c)
- }
- intcode, err := strconv.ParseInt(code, 16, 32)
- if err != nil {
- return "", errors.New("invalid unicode escape: \\u" + code)
- }
- growingString += string(rune(intcode))
- case 'U':
- l.next()
- code := ""
- for i := 0; i < 8; i++ {
- c := l.peek()
- if !isHexDigit(c) {
- return "", errors.New("unfinished unicode escape")
- }
- l.next()
- code = code + string(c)
- }
- intcode, err := strconv.ParseInt(code, 16, 64)
- if err != nil {
- return "", errors.New("invalid unicode escape: \\U" + code)
- }
- growingString += string(rune(intcode))
- default:
- return "", errors.New("invalid escape sequence: \\" + string(l.peek()))
- }
- } else {
- r := l.peek()
-
- if 0x00 <= r && r <= 0x1F && !(acceptNewLines && (r == '\n' || r == '\r')) {
- return "", fmt.Errorf("unescaped control character %U", r)
- }
- l.next()
- growingString += string(r)
- }
-
- if l.peek() == eof {
- break
- }
- }
-
- return "", errors.New("unclosed string")
-}
-
-func (l *tomlLexer) lexString() tomlLexStateFn {
- l.skip()
-
- // handle special case for triple-quote
- terminator := `"`
- discardLeadingNewLine := false
- acceptNewLines := false
- if l.follow(`""`) {
- l.skip()
- l.skip()
- terminator = `"""`
- discardLeadingNewLine = true
- acceptNewLines = true
- }
-
- str, err := l.lexStringAsString(terminator, discardLeadingNewLine, acceptNewLines)
-
- if err != nil {
- return l.errorf(err.Error())
- }
-
- l.emitWithValue(tokenString, str)
- l.fastForward(len(terminator))
- l.ignore()
- return l.lexRvalue
-}
-
-func (l *tomlLexer) lexTableKey() tomlLexStateFn {
- l.next()
-
- if l.peek() == '[' {
- // token '[[' signifies an array of tables
- l.next()
- l.emit(tokenDoubleLeftBracket)
- return l.lexInsideTableArrayKey
- }
- // vanilla table key
- l.emit(tokenLeftBracket)
- return l.lexInsideTableKey
-}
-
-func (l *tomlLexer) lexInsideTableArrayKey() tomlLexStateFn {
- for r := l.peek(); r != eof; r = l.peek() {
- switch r {
- case ']':
- if l.currentTokenStop > l.currentTokenStart {
- l.emit(tokenKeyGroupArray)
- }
- l.next()
- if l.peek() != ']' {
- break
- }
- l.next()
- l.emit(tokenDoubleRightBracket)
- return l.lexVoid
- case '[':
- return l.errorf("table array key cannot contain ']'")
- default:
- l.next()
- }
- }
- return l.errorf("unclosed table array key")
-}
-
-func (l *tomlLexer) lexInsideTableKey() tomlLexStateFn {
- for r := l.peek(); r != eof; r = l.peek() {
- switch r {
- case ']':
- if l.currentTokenStop > l.currentTokenStart {
- l.emit(tokenKeyGroup)
- }
- l.next()
- l.emit(tokenRightBracket)
- return l.lexVoid
- case '[':
- return l.errorf("table key cannot contain ']'")
- default:
- l.next()
- }
- }
- return l.errorf("unclosed table key")
-}
-
-func (l *tomlLexer) lexRightBracket() tomlLexStateFn {
- l.next()
- l.emit(tokenRightBracket)
- return l.lexRvalue
-}
-
-func (l *tomlLexer) lexNumber() tomlLexStateFn {
- r := l.peek()
- if r == '+' || r == '-' {
- l.next()
- }
- pointSeen := false
- expSeen := false
- digitSeen := false
- for {
- next := l.peek()
- if next == '.' {
- if pointSeen {
- return l.errorf("cannot have two dots in one float")
- }
- l.next()
- if !isDigit(l.peek()) {
- return l.errorf("float cannot end with a dot")
- }
- pointSeen = true
- } else if next == 'e' || next == 'E' {
- expSeen = true
- l.next()
- r := l.peek()
- if r == '+' || r == '-' {
- l.next()
- }
- } else if isDigit(next) {
- digitSeen = true
- l.next()
- } else if next == '_' {
- l.next()
- } else {
- break
- }
- if pointSeen && !digitSeen {
- return l.errorf("cannot start float with a dot")
- }
- }
-
- if !digitSeen {
- return l.errorf("no digit in that number")
- }
- if pointSeen || expSeen {
- l.emit(tokenFloat)
- } else {
- l.emit(tokenInteger)
- }
- return l.lexRvalue
-}
-
-func (l *tomlLexer) run() {
- for state := l.lexVoid; state != nil; {
- state = state()
- }
-}
-
-func init() {
- dateRegexp = regexp.MustCompile(`^\d{1,4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?(Z|[+-]\d{2}:\d{2})`)
-}
-
-// Entry point
-func lexToml(inputBytes []byte) []token {
- runes := bytes.Runes(inputBytes)
- l := &tomlLexer{
- input: runes,
- tokens: make([]token, 0, 256),
- line: 1,
- col: 1,
- endbufferLine: 1,
- endbufferCol: 1,
- }
- l.run()
- return l.tokens
-}
diff --git a/vendor/github.com/pelletier/go-toml/lexer_test.go b/vendor/github.com/pelletier/go-toml/lexer_test.go
deleted file mode 100644
index 313b83c..0000000
--- a/vendor/github.com/pelletier/go-toml/lexer_test.go
+++ /dev/null
@@ -1,750 +0,0 @@
-package toml
-
-import (
- "reflect"
- "testing"
-)
-
-func testFlow(t *testing.T, input string, expectedFlow []token) {
- tokens := lexToml([]byte(input))
- if !reflect.DeepEqual(tokens, expectedFlow) {
- t.Fatal("Different flows. Expected\n", expectedFlow, "\nGot:\n", tokens)
- }
-}
-
-func TestValidKeyGroup(t *testing.T) {
- testFlow(t, "[hello world]", []token{
- {Position{1, 1}, tokenLeftBracket, "["},
- {Position{1, 2}, tokenKeyGroup, "hello world"},
- {Position{1, 13}, tokenRightBracket, "]"},
- {Position{1, 14}, tokenEOF, ""},
- })
-}
-
-func TestNestedQuotedUnicodeKeyGroup(t *testing.T) {
- testFlow(t, `[ j . "ʞ" . l ]`, []token{
- {Position{1, 1}, tokenLeftBracket, "["},
- {Position{1, 2}, tokenKeyGroup, ` j . "ʞ" . l `},
- {Position{1, 15}, tokenRightBracket, "]"},
- {Position{1, 16}, tokenEOF, ""},
- })
-}
-
-func TestUnclosedKeyGroup(t *testing.T) {
- testFlow(t, "[hello world", []token{
- {Position{1, 1}, tokenLeftBracket, "["},
- {Position{1, 2}, tokenError, "unclosed table key"},
- })
-}
-
-func TestComment(t *testing.T) {
- testFlow(t, "# blahblah", []token{
- {Position{1, 11}, tokenEOF, ""},
- })
-}
-
-func TestKeyGroupComment(t *testing.T) {
- testFlow(t, "[hello world] # blahblah", []token{
- {Position{1, 1}, tokenLeftBracket, "["},
- {Position{1, 2}, tokenKeyGroup, "hello world"},
- {Position{1, 13}, tokenRightBracket, "]"},
- {Position{1, 25}, tokenEOF, ""},
- })
-}
-
-func TestMultipleKeyGroupsComment(t *testing.T) {
- testFlow(t, "[hello world] # blahblah\n[test]", []token{
- {Position{1, 1}, tokenLeftBracket, "["},
- {Position{1, 2}, tokenKeyGroup, "hello world"},
- {Position{1, 13}, tokenRightBracket, "]"},
- {Position{2, 1}, tokenLeftBracket, "["},
- {Position{2, 2}, tokenKeyGroup, "test"},
- {Position{2, 6}, tokenRightBracket, "]"},
- {Position{2, 7}, tokenEOF, ""},
- })
-}
-
-func TestSimpleWindowsCRLF(t *testing.T) {
- testFlow(t, "a=4\r\nb=2", []token{
- {Position{1, 1}, tokenKey, "a"},
- {Position{1, 2}, tokenEqual, "="},
- {Position{1, 3}, tokenInteger, "4"},
- {Position{2, 1}, tokenKey, "b"},
- {Position{2, 2}, tokenEqual, "="},
- {Position{2, 3}, tokenInteger, "2"},
- {Position{2, 4}, tokenEOF, ""},
- })
-}
-
-func TestBasicKey(t *testing.T) {
- testFlow(t, "hello", []token{
- {Position{1, 1}, tokenKey, "hello"},
- {Position{1, 6}, tokenEOF, ""},
- })
-}
-
-func TestBasicKeyWithUnderscore(t *testing.T) {
- testFlow(t, "hello_hello", []token{
- {Position{1, 1}, tokenKey, "hello_hello"},
- {Position{1, 12}, tokenEOF, ""},
- })
-}
-
-func TestBasicKeyWithDash(t *testing.T) {
- testFlow(t, "hello-world", []token{
- {Position{1, 1}, tokenKey, "hello-world"},
- {Position{1, 12}, tokenEOF, ""},
- })
-}
-
-func TestBasicKeyWithUppercaseMix(t *testing.T) {
- testFlow(t, "helloHELLOHello", []token{
- {Position{1, 1}, tokenKey, "helloHELLOHello"},
- {Position{1, 16}, tokenEOF, ""},
- })
-}
-
-func TestBasicKeyWithInternationalCharacters(t *testing.T) {
- testFlow(t, "héllÖ", []token{
- {Position{1, 1}, tokenKey, "héllÖ"},
- {Position{1, 6}, tokenEOF, ""},
- })
-}
-
-func TestBasicKeyAndEqual(t *testing.T) {
- testFlow(t, "hello =", []token{
- {Position{1, 1}, tokenKey, "hello"},
- {Position{1, 7}, tokenEqual, "="},
- {Position{1, 8}, tokenEOF, ""},
- })
-}
-
-func TestKeyWithSharpAndEqual(t *testing.T) {
- testFlow(t, "key#name = 5", []token{
- {Position{1, 1}, tokenError, "keys cannot contain # character"},
- })
-}
-
-func TestKeyWithSymbolsAndEqual(t *testing.T) {
- testFlow(t, "~!@$^&*()_+-`1234567890[]\\|/?><.,;:' = 5", []token{
- {Position{1, 1}, tokenError, "keys cannot contain ~ character"},
- })
-}
-
-func TestKeyEqualStringEscape(t *testing.T) {
- testFlow(t, `foo = "hello\""`, []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 8}, tokenString, "hello\""},
- {Position{1, 16}, tokenEOF, ""},
- })
-}
-
-func TestKeyEqualStringUnfinished(t *testing.T) {
- testFlow(t, `foo = "bar`, []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 8}, tokenError, "unclosed string"},
- })
-}
-
-func TestKeyEqualString(t *testing.T) {
- testFlow(t, `foo = "bar"`, []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 8}, tokenString, "bar"},
- {Position{1, 12}, tokenEOF, ""},
- })
-}
-
-func TestKeyEqualTrue(t *testing.T) {
- testFlow(t, "foo = true", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 7}, tokenTrue, "true"},
- {Position{1, 11}, tokenEOF, ""},
- })
-}
-
-func TestKeyEqualFalse(t *testing.T) {
- testFlow(t, "foo = false", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 7}, tokenFalse, "false"},
- {Position{1, 12}, tokenEOF, ""},
- })
-}
-
-func TestArrayNestedString(t *testing.T) {
- testFlow(t, `a = [ ["hello", "world"] ]`, []token{
- {Position{1, 1}, tokenKey, "a"},
- {Position{1, 3}, tokenEqual, "="},
- {Position{1, 5}, tokenLeftBracket, "["},
- {Position{1, 7}, tokenLeftBracket, "["},
- {Position{1, 9}, tokenString, "hello"},
- {Position{1, 15}, tokenComma, ","},
- {Position{1, 18}, tokenString, "world"},
- {Position{1, 24}, tokenRightBracket, "]"},
- {Position{1, 26}, tokenRightBracket, "]"},
- {Position{1, 27}, tokenEOF, ""},
- })
-}
-
-func TestArrayNestedInts(t *testing.T) {
- testFlow(t, "a = [ [42, 21], [10] ]", []token{
- {Position{1, 1}, tokenKey, "a"},
- {Position{1, 3}, tokenEqual, "="},
- {Position{1, 5}, tokenLeftBracket, "["},
- {Position{1, 7}, tokenLeftBracket, "["},
- {Position{1, 8}, tokenInteger, "42"},
- {Position{1, 10}, tokenComma, ","},
- {Position{1, 12}, tokenInteger, "21"},
- {Position{1, 14}, tokenRightBracket, "]"},
- {Position{1, 15}, tokenComma, ","},
- {Position{1, 17}, tokenLeftBracket, "["},
- {Position{1, 18}, tokenInteger, "10"},
- {Position{1, 20}, tokenRightBracket, "]"},
- {Position{1, 22}, tokenRightBracket, "]"},
- {Position{1, 23}, tokenEOF, ""},
- })
-}
-
-func TestArrayInts(t *testing.T) {
- testFlow(t, "a = [ 42, 21, 10, ]", []token{
- {Position{1, 1}, tokenKey, "a"},
- {Position{1, 3}, tokenEqual, "="},
- {Position{1, 5}, tokenLeftBracket, "["},
- {Position{1, 7}, tokenInteger, "42"},
- {Position{1, 9}, tokenComma, ","},
- {Position{1, 11}, tokenInteger, "21"},
- {Position{1, 13}, tokenComma, ","},
- {Position{1, 15}, tokenInteger, "10"},
- {Position{1, 17}, tokenComma, ","},
- {Position{1, 19}, tokenRightBracket, "]"},
- {Position{1, 20}, tokenEOF, ""},
- })
-}
-
-func TestMultilineArrayComments(t *testing.T) {
- testFlow(t, "a = [1, # wow\n2, # such items\n3, # so array\n]", []token{
- {Position{1, 1}, tokenKey, "a"},
- {Position{1, 3}, tokenEqual, "="},
- {Position{1, 5}, tokenLeftBracket, "["},
- {Position{1, 6}, tokenInteger, "1"},
- {Position{1, 7}, tokenComma, ","},
- {Position{2, 1}, tokenInteger, "2"},
- {Position{2, 2}, tokenComma, ","},
- {Position{3, 1}, tokenInteger, "3"},
- {Position{3, 2}, tokenComma, ","},
- {Position{4, 1}, tokenRightBracket, "]"},
- {Position{4, 2}, tokenEOF, ""},
- })
-}
-
-func TestNestedArraysComment(t *testing.T) {
- toml := `
-someArray = [
-# does not work
-["entry1"]
-]`
- testFlow(t, toml, []token{
- {Position{2, 1}, tokenKey, "someArray"},
- {Position{2, 11}, tokenEqual, "="},
- {Position{2, 13}, tokenLeftBracket, "["},
- {Position{4, 1}, tokenLeftBracket, "["},
- {Position{4, 3}, tokenString, "entry1"},
- {Position{4, 10}, tokenRightBracket, "]"},
- {Position{5, 1}, tokenRightBracket, "]"},
- {Position{5, 2}, tokenEOF, ""},
- })
-}
-
-func TestKeyEqualArrayBools(t *testing.T) {
- testFlow(t, "foo = [true, false, true]", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 7}, tokenLeftBracket, "["},
- {Position{1, 8}, tokenTrue, "true"},
- {Position{1, 12}, tokenComma, ","},
- {Position{1, 14}, tokenFalse, "false"},
- {Position{1, 19}, tokenComma, ","},
- {Position{1, 21}, tokenTrue, "true"},
- {Position{1, 25}, tokenRightBracket, "]"},
- {Position{1, 26}, tokenEOF, ""},
- })
-}
-
-func TestKeyEqualArrayBoolsWithComments(t *testing.T) {
- testFlow(t, "foo = [true, false, true] # YEAH", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 7}, tokenLeftBracket, "["},
- {Position{1, 8}, tokenTrue, "true"},
- {Position{1, 12}, tokenComma, ","},
- {Position{1, 14}, tokenFalse, "false"},
- {Position{1, 19}, tokenComma, ","},
- {Position{1, 21}, tokenTrue, "true"},
- {Position{1, 25}, tokenRightBracket, "]"},
- {Position{1, 33}, tokenEOF, ""},
- })
-}
-
-func TestDateRegexp(t *testing.T) {
- if dateRegexp.FindString("1979-05-27T07:32:00Z") == "" {
- t.Error("basic lexing")
- }
- if dateRegexp.FindString("1979-05-27T00:32:00-07:00") == "" {
- t.Error("offset lexing")
- }
- if dateRegexp.FindString("1979-05-27T00:32:00.999999-07:00") == "" {
- t.Error("nano precision lexing")
- }
-}
-
-func TestKeyEqualDate(t *testing.T) {
- testFlow(t, "foo = 1979-05-27T07:32:00Z", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 7}, tokenDate, "1979-05-27T07:32:00Z"},
- {Position{1, 27}, tokenEOF, ""},
- })
- testFlow(t, "foo = 1979-05-27T00:32:00-07:00", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 7}, tokenDate, "1979-05-27T00:32:00-07:00"},
- {Position{1, 32}, tokenEOF, ""},
- })
- testFlow(t, "foo = 1979-05-27T00:32:00.999999-07:00", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 7}, tokenDate, "1979-05-27T00:32:00.999999-07:00"},
- {Position{1, 39}, tokenEOF, ""},
- })
-}
-
-func TestFloatEndingWithDot(t *testing.T) {
- testFlow(t, "foo = 42.", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 7}, tokenError, "float cannot end with a dot"},
- })
-}
-
-func TestFloatWithTwoDots(t *testing.T) {
- testFlow(t, "foo = 4.2.", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 7}, tokenError, "cannot have two dots in one float"},
- })
-}
-
-func TestFloatWithExponent1(t *testing.T) {
- testFlow(t, "a = 5e+22", []token{
- {Position{1, 1}, tokenKey, "a"},
- {Position{1, 3}, tokenEqual, "="},
- {Position{1, 5}, tokenFloat, "5e+22"},
- {Position{1, 10}, tokenEOF, ""},
- })
-}
-
-func TestFloatWithExponent2(t *testing.T) {
- testFlow(t, "a = 5E+22", []token{
- {Position{1, 1}, tokenKey, "a"},
- {Position{1, 3}, tokenEqual, "="},
- {Position{1, 5}, tokenFloat, "5E+22"},
- {Position{1, 10}, tokenEOF, ""},
- })
-}
-
-func TestFloatWithExponent3(t *testing.T) {
- testFlow(t, "a = -5e+22", []token{
- {Position{1, 1}, tokenKey, "a"},
- {Position{1, 3}, tokenEqual, "="},
- {Position{1, 5}, tokenFloat, "-5e+22"},
- {Position{1, 11}, tokenEOF, ""},
- })
-}
-
-func TestFloatWithExponent4(t *testing.T) {
- testFlow(t, "a = -5e-22", []token{
- {Position{1, 1}, tokenKey, "a"},
- {Position{1, 3}, tokenEqual, "="},
- {Position{1, 5}, tokenFloat, "-5e-22"},
- {Position{1, 11}, tokenEOF, ""},
- })
-}
-
-func TestFloatWithExponent5(t *testing.T) {
- testFlow(t, "a = 6.626e-34", []token{
- {Position{1, 1}, tokenKey, "a"},
- {Position{1, 3}, tokenEqual, "="},
- {Position{1, 5}, tokenFloat, "6.626e-34"},
- {Position{1, 14}, tokenEOF, ""},
- })
-}
-
-func TestInvalidEsquapeSequence(t *testing.T) {
- testFlow(t, `foo = "\x"`, []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 8}, tokenError, "invalid escape sequence: \\x"},
- })
-}
-
-func TestNestedArrays(t *testing.T) {
- testFlow(t, "foo = [[[]]]", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 7}, tokenLeftBracket, "["},
- {Position{1, 8}, tokenLeftBracket, "["},
- {Position{1, 9}, tokenLeftBracket, "["},
- {Position{1, 10}, tokenRightBracket, "]"},
- {Position{1, 11}, tokenRightBracket, "]"},
- {Position{1, 12}, tokenRightBracket, "]"},
- {Position{1, 13}, tokenEOF, ""},
- })
-}
-
-func TestKeyEqualNumber(t *testing.T) {
- testFlow(t, "foo = 42", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 7}, tokenInteger, "42"},
- {Position{1, 9}, tokenEOF, ""},
- })
-
- testFlow(t, "foo = +42", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 7}, tokenInteger, "+42"},
- {Position{1, 10}, tokenEOF, ""},
- })
-
- testFlow(t, "foo = -42", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 7}, tokenInteger, "-42"},
- {Position{1, 10}, tokenEOF, ""},
- })
-
- testFlow(t, "foo = 4.2", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 7}, tokenFloat, "4.2"},
- {Position{1, 10}, tokenEOF, ""},
- })
-
- testFlow(t, "foo = +4.2", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 7}, tokenFloat, "+4.2"},
- {Position{1, 11}, tokenEOF, ""},
- })
-
- testFlow(t, "foo = -4.2", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 7}, tokenFloat, "-4.2"},
- {Position{1, 11}, tokenEOF, ""},
- })
-
- testFlow(t, "foo = 1_000", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 7}, tokenInteger, "1_000"},
- {Position{1, 12}, tokenEOF, ""},
- })
-
- testFlow(t, "foo = 5_349_221", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 7}, tokenInteger, "5_349_221"},
- {Position{1, 16}, tokenEOF, ""},
- })
-
- testFlow(t, "foo = 1_2_3_4_5", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 7}, tokenInteger, "1_2_3_4_5"},
- {Position{1, 16}, tokenEOF, ""},
- })
-
- testFlow(t, "flt8 = 9_224_617.445_991_228_313", []token{
- {Position{1, 1}, tokenKey, "flt8"},
- {Position{1, 6}, tokenEqual, "="},
- {Position{1, 8}, tokenFloat, "9_224_617.445_991_228_313"},
- {Position{1, 33}, tokenEOF, ""},
- })
-
- testFlow(t, "foo = +", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 7}, tokenError, "no digit in that number"},
- })
-}
-
-func TestMultiline(t *testing.T) {
- testFlow(t, "foo = 42\nbar=21", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 7}, tokenInteger, "42"},
- {Position{2, 1}, tokenKey, "bar"},
- {Position{2, 4}, tokenEqual, "="},
- {Position{2, 5}, tokenInteger, "21"},
- {Position{2, 7}, tokenEOF, ""},
- })
-}
-
-func TestKeyEqualStringUnicodeEscape(t *testing.T) {
- testFlow(t, `foo = "hello \u2665"`, []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 8}, tokenString, "hello ♥"},
- {Position{1, 21}, tokenEOF, ""},
- })
- testFlow(t, `foo = "hello \U000003B4"`, []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 8}, tokenString, "hello δ"},
- {Position{1, 25}, tokenEOF, ""},
- })
- testFlow(t, `foo = "\uabcd"`, []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 8}, tokenString, "\uabcd"},
- {Position{1, 15}, tokenEOF, ""},
- })
- testFlow(t, `foo = "\uABCD"`, []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 8}, tokenString, "\uABCD"},
- {Position{1, 15}, tokenEOF, ""},
- })
- testFlow(t, `foo = "\U000bcdef"`, []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 8}, tokenString, "\U000bcdef"},
- {Position{1, 19}, tokenEOF, ""},
- })
- testFlow(t, `foo = "\U000BCDEF"`, []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 8}, tokenString, "\U000BCDEF"},
- {Position{1, 19}, tokenEOF, ""},
- })
- testFlow(t, `foo = "\u2"`, []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 8}, tokenError, "unfinished unicode escape"},
- })
- testFlow(t, `foo = "\U2"`, []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 8}, tokenError, "unfinished unicode escape"},
- })
-}
-
-func TestKeyEqualStringNoEscape(t *testing.T) {
- testFlow(t, "foo = \"hello \u0002\"", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 8}, tokenError, "unescaped control character U+0002"},
- })
- testFlow(t, "foo = \"hello \u001F\"", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 8}, tokenError, "unescaped control character U+001F"},
- })
-}
-
-func TestLiteralString(t *testing.T) {
- testFlow(t, `foo = 'C:\Users\nodejs\templates'`, []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 8}, tokenString, `C:\Users\nodejs\templates`},
- {Position{1, 34}, tokenEOF, ""},
- })
- testFlow(t, `foo = '\\ServerX\admin$\system32\'`, []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 8}, tokenString, `\\ServerX\admin$\system32\`},
- {Position{1, 35}, tokenEOF, ""},
- })
- testFlow(t, `foo = 'Tom "Dubs" Preston-Werner'`, []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 8}, tokenString, `Tom "Dubs" Preston-Werner`},
- {Position{1, 34}, tokenEOF, ""},
- })
- testFlow(t, `foo = '<\i\c*\s*>'`, []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 8}, tokenString, `<\i\c*\s*>`},
- {Position{1, 19}, tokenEOF, ""},
- })
- testFlow(t, `foo = 'C:\Users\nodejs\unfinis`, []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 8}, tokenError, "unclosed string"},
- })
-}
-
-func TestMultilineLiteralString(t *testing.T) {
- testFlow(t, `foo = '''hello 'literal' world'''`, []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 10}, tokenString, `hello 'literal' world`},
- {Position{1, 34}, tokenEOF, ""},
- })
-
- testFlow(t, "foo = '''\nhello\n'literal'\nworld'''", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{2, 1}, tokenString, "hello\n'literal'\nworld"},
- {Position{4, 9}, tokenEOF, ""},
- })
- testFlow(t, "foo = '''\r\nhello\r\n'literal'\r\nworld'''", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{2, 1}, tokenString, "hello\r\n'literal'\r\nworld"},
- {Position{4, 9}, tokenEOF, ""},
- })
-}
-
-func TestMultilineString(t *testing.T) {
- testFlow(t, `foo = """hello "literal" world"""`, []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 10}, tokenString, `hello "literal" world`},
- {Position{1, 34}, tokenEOF, ""},
- })
-
- testFlow(t, "foo = \"\"\"\r\nhello\\\r\n\"literal\"\\\nworld\"\"\"", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{2, 1}, tokenString, "hello\"literal\"world"},
- {Position{4, 9}, tokenEOF, ""},
- })
-
- testFlow(t, "foo = \"\"\"\\\n \\\n \\\n hello\\\nmultiline\\\nworld\"\"\"", []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 10}, tokenString, "hellomultilineworld"},
- {Position{6, 9}, tokenEOF, ""},
- })
-
- testFlow(t, "key2 = \"\"\"\nThe quick brown \\\n\n\n fox jumps over \\\n the lazy dog.\"\"\"", []token{
- {Position{1, 1}, tokenKey, "key2"},
- {Position{1, 6}, tokenEqual, "="},
- {Position{2, 1}, tokenString, "The quick brown fox jumps over the lazy dog."},
- {Position{6, 21}, tokenEOF, ""},
- })
-
- testFlow(t, "key2 = \"\"\"\\\n The quick brown \\\n fox jumps over \\\n the lazy dog.\\\n \"\"\"", []token{
- {Position{1, 1}, tokenKey, "key2"},
- {Position{1, 6}, tokenEqual, "="},
- {Position{1, 11}, tokenString, "The quick brown fox jumps over the lazy dog."},
- {Position{5, 11}, tokenEOF, ""},
- })
-
- testFlow(t, `key2 = "Roses are red\nViolets are blue"`, []token{
- {Position{1, 1}, tokenKey, "key2"},
- {Position{1, 6}, tokenEqual, "="},
- {Position{1, 9}, tokenString, "Roses are red\nViolets are blue"},
- {Position{1, 41}, tokenEOF, ""},
- })
-
- testFlow(t, "key2 = \"\"\"\nRoses are red\nViolets are blue\"\"\"", []token{
- {Position{1, 1}, tokenKey, "key2"},
- {Position{1, 6}, tokenEqual, "="},
- {Position{2, 1}, tokenString, "Roses are red\nViolets are blue"},
- {Position{3, 20}, tokenEOF, ""},
- })
-}
-
-func TestUnicodeString(t *testing.T) {
- testFlow(t, `foo = "hello ♥ world"`, []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 8}, tokenString, "hello ♥ world"},
- {Position{1, 22}, tokenEOF, ""},
- })
-}
-func TestEscapeInString(t *testing.T) {
- testFlow(t, `foo = "\b\f\/"`, []token{
- {Position{1, 1}, tokenKey, "foo"},
- {Position{1, 5}, tokenEqual, "="},
- {Position{1, 8}, tokenString, "\b\f/"},
- {Position{1, 15}, tokenEOF, ""},
- })
-}
-
-func TestKeyGroupArray(t *testing.T) {
- testFlow(t, "[[foo]]", []token{
- {Position{1, 1}, tokenDoubleLeftBracket, "[["},
- {Position{1, 3}, tokenKeyGroupArray, "foo"},
- {Position{1, 6}, tokenDoubleRightBracket, "]]"},
- {Position{1, 8}, tokenEOF, ""},
- })
-}
-
-func TestQuotedKey(t *testing.T) {
- testFlow(t, "\"a b\" = 42", []token{
- {Position{1, 1}, tokenKey, "\"a b\""},
- {Position{1, 7}, tokenEqual, "="},
- {Position{1, 9}, tokenInteger, "42"},
- {Position{1, 11}, tokenEOF, ""},
- })
-}
-
-func TestKeyNewline(t *testing.T) {
- testFlow(t, "a\n= 4", []token{
- {Position{1, 1}, tokenError, "keys cannot contain new lines"},
- })
-}
-
-func TestInvalidFloat(t *testing.T) {
- testFlow(t, "a=7e1_", []token{
- {Position{1, 1}, tokenKey, "a"},
- {Position{1, 2}, tokenEqual, "="},
- {Position{1, 3}, tokenFloat, "7e1_"},
- {Position{1, 7}, tokenEOF, ""},
- })
-}
-
-func TestLexUnknownRvalue(t *testing.T) {
- testFlow(t, `a = !b`, []token{
- {Position{1, 1}, tokenKey, "a"},
- {Position{1, 3}, tokenEqual, "="},
- {Position{1, 5}, tokenError, "no value can start with !"},
- })
-
- testFlow(t, `a = \b`, []token{
- {Position{1, 1}, tokenKey, "a"},
- {Position{1, 3}, tokenEqual, "="},
- {Position{1, 5}, tokenError, `no value can start with \`},
- })
-}
-
-func BenchmarkLexer(b *testing.B) {
- sample := `title = "Hugo: A Fast and Flexible Website Generator"
-baseurl = "http://gohugo.io/"
-MetaDataFormat = "yaml"
-pluralizeListTitles = false
-
-[params]
- description = "Documentation of Hugo, a fast and flexible static site generator built with love by spf13, bep and friends in Go"
- author = "Steve Francia (spf13) and friends"
- release = "0.22-DEV"
-
-[[menu.main]]
- name = "Download Hugo"
- pre = " "
- url = "https://github.com/spf13/hugo/releases"
- weight = -200
-`
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- lexToml([]byte(sample))
- }
-}
diff --git a/vendor/github.com/pelletier/go-toml/marshal.go b/vendor/github.com/pelletier/go-toml/marshal.go
deleted file mode 100644
index 1a3176f..0000000
--- a/vendor/github.com/pelletier/go-toml/marshal.go
+++ /dev/null
@@ -1,489 +0,0 @@
-package toml
-
-import (
- "bytes"
- "errors"
- "fmt"
- "reflect"
- "strings"
- "time"
-)
-
-type tomlOpts struct {
- name string
- include bool
- omitempty bool
-}
-
-var timeType = reflect.TypeOf(time.Time{})
-var marshalerType = reflect.TypeOf(new(Marshaler)).Elem()
-
-// Check if the given marshall type maps to a Tree primitive
-func isPrimitive(mtype reflect.Type) bool {
- switch mtype.Kind() {
- case reflect.Ptr:
- return isPrimitive(mtype.Elem())
- case reflect.Bool:
- return true
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- return true
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- return true
- case reflect.Float32, reflect.Float64:
- return true
- case reflect.String:
- return true
- case reflect.Struct:
- return mtype == timeType || isCustomMarshaler(mtype)
- default:
- return false
- }
-}
-
-// Check if the given marshall type maps to a Tree slice
-func isTreeSlice(mtype reflect.Type) bool {
- switch mtype.Kind() {
- case reflect.Slice:
- return !isOtherSlice(mtype)
- default:
- return false
- }
-}
-
-// Check if the given marshall type maps to a non-Tree slice
-func isOtherSlice(mtype reflect.Type) bool {
- switch mtype.Kind() {
- case reflect.Ptr:
- return isOtherSlice(mtype.Elem())
- case reflect.Slice:
- return isPrimitive(mtype.Elem()) || isOtherSlice(mtype.Elem())
- default:
- return false
- }
-}
-
-// Check if the given marshall type maps to a Tree
-func isTree(mtype reflect.Type) bool {
- switch mtype.Kind() {
- case reflect.Map:
- return true
- case reflect.Struct:
- return !isPrimitive(mtype)
- default:
- return false
- }
-}
-
-func isCustomMarshaler(mtype reflect.Type) bool {
- return mtype.Implements(marshalerType)
-}
-
-func callCustomMarshaler(mval reflect.Value) ([]byte, error) {
- return mval.Interface().(Marshaler).MarshalTOML()
-}
-
-// Marshaler is the interface implemented by types that
-// can marshal themselves into valid TOML.
-type Marshaler interface {
- MarshalTOML() ([]byte, error)
-}
-
-/*
-Marshal returns the TOML encoding of v. Behavior is similar to the Go json
-encoder, except that there is no concept of a Marshaler interface or MarshalTOML
-function for sub-structs, and currently only definite types can be marshaled
-(i.e. no `interface{}`).
-
-Note that pointers are automatically assigned the "omitempty" option, as TOML
-explicity does not handle null values (saying instead the label should be
-dropped).
-
-Tree structural types and corresponding marshal types:
-
- *Tree (*)struct, (*)map[string]interface{}
- []*Tree (*)[](*)struct, (*)[](*)map[string]interface{}
- []interface{} (as interface{}) (*)[]primitive, (*)[]([]interface{})
- interface{} (*)primitive
-
-Tree primitive types and corresponding marshal types:
-
- uint64 uint, uint8-uint64, pointers to same
- int64 int, int8-uint64, pointers to same
- float64 float32, float64, pointers to same
- string string, pointers to same
- bool bool, pointers to same
- time.Time time.Time{}, pointers to same
-*/
-func Marshal(v interface{}) ([]byte, error) {
- mtype := reflect.TypeOf(v)
- if mtype.Kind() != reflect.Struct {
- return []byte{}, errors.New("Only a struct can be marshaled to TOML")
- }
- sval := reflect.ValueOf(v)
- if isCustomMarshaler(mtype) {
- return callCustomMarshaler(sval)
- }
- t, err := valueToTree(mtype, sval)
- if err != nil {
- return []byte{}, err
- }
- s, err := t.ToTomlString()
- return []byte(s), err
-}
-
-// Convert given marshal struct or map value to toml tree
-func valueToTree(mtype reflect.Type, mval reflect.Value) (*Tree, error) {
- if mtype.Kind() == reflect.Ptr {
- return valueToTree(mtype.Elem(), mval.Elem())
- }
- tval := newTree()
- switch mtype.Kind() {
- case reflect.Struct:
- for i := 0; i < mtype.NumField(); i++ {
- mtypef, mvalf := mtype.Field(i), mval.Field(i)
- opts := tomlOptions(mtypef)
- if opts.include && (!opts.omitempty || !isZero(mvalf)) {
- val, err := valueToToml(mtypef.Type, mvalf)
- if err != nil {
- return nil, err
- }
- tval.Set(opts.name, val)
- }
- }
- case reflect.Map:
- for _, key := range mval.MapKeys() {
- mvalf := mval.MapIndex(key)
- val, err := valueToToml(mtype.Elem(), mvalf)
- if err != nil {
- return nil, err
- }
- tval.Set(key.String(), val)
- }
- }
- return tval, nil
-}
-
-// Convert given marshal slice to slice of Toml trees
-func valueToTreeSlice(mtype reflect.Type, mval reflect.Value) ([]*Tree, error) {
- tval := make([]*Tree, mval.Len(), mval.Len())
- for i := 0; i < mval.Len(); i++ {
- val, err := valueToTree(mtype.Elem(), mval.Index(i))
- if err != nil {
- return nil, err
- }
- tval[i] = val
- }
- return tval, nil
-}
-
-// Convert given marshal slice to slice of toml values
-func valueToOtherSlice(mtype reflect.Type, mval reflect.Value) (interface{}, error) {
- tval := make([]interface{}, mval.Len(), mval.Len())
- for i := 0; i < mval.Len(); i++ {
- val, err := valueToToml(mtype.Elem(), mval.Index(i))
- if err != nil {
- return nil, err
- }
- tval[i] = val
- }
- return tval, nil
-}
-
-// Convert given marshal value to toml value
-func valueToToml(mtype reflect.Type, mval reflect.Value) (interface{}, error) {
- if mtype.Kind() == reflect.Ptr {
- return valueToToml(mtype.Elem(), mval.Elem())
- }
- switch {
- case isCustomMarshaler(mtype):
- return callCustomMarshaler(mval)
- case isTree(mtype):
- return valueToTree(mtype, mval)
- case isTreeSlice(mtype):
- return valueToTreeSlice(mtype, mval)
- case isOtherSlice(mtype):
- return valueToOtherSlice(mtype, mval)
- default:
- switch mtype.Kind() {
- case reflect.Bool:
- return mval.Bool(), nil
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- return mval.Int(), nil
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- return mval.Uint(), nil
- case reflect.Float32, reflect.Float64:
- return mval.Float(), nil
- case reflect.String:
- return mval.String(), nil
- case reflect.Struct:
- return mval.Interface().(time.Time), nil
- default:
- return nil, fmt.Errorf("Marshal can't handle %v(%v)", mtype, mtype.Kind())
- }
- }
-}
-
-// Unmarshal attempts to unmarshal the Tree into a Go struct pointed by v.
-// Neither Unmarshaler interfaces nor UnmarshalTOML functions are supported for
-// sub-structs, and only definite types can be unmarshaled.
-func (t *Tree) Unmarshal(v interface{}) error {
- mtype := reflect.TypeOf(v)
- if mtype.Kind() != reflect.Ptr || mtype.Elem().Kind() != reflect.Struct {
- return errors.New("Only a pointer to struct can be unmarshaled from TOML")
- }
-
- sval, err := valueFromTree(mtype.Elem(), t)
- if err != nil {
- return err
- }
- reflect.ValueOf(v).Elem().Set(sval)
- return nil
-}
-
-// Unmarshal parses the TOML-encoded data and stores the result in the value
-// pointed to by v. Behavior is similar to the Go json encoder, except that there
-// is no concept of an Unmarshaler interface or UnmarshalTOML function for
-// sub-structs, and currently only definite types can be unmarshaled to (i.e. no
-// `interface{}`).
-//
-// See Marshal() documentation for types mapping table.
-func Unmarshal(data []byte, v interface{}) error {
- t, err := LoadReader(bytes.NewReader(data))
- if err != nil {
- return err
- }
- return t.Unmarshal(v)
-}
-
-// Convert toml tree to marshal struct or map, using marshal type
-func valueFromTree(mtype reflect.Type, tval *Tree) (reflect.Value, error) {
- if mtype.Kind() == reflect.Ptr {
- return unwrapPointer(mtype, tval)
- }
- var mval reflect.Value
- switch mtype.Kind() {
- case reflect.Struct:
- mval = reflect.New(mtype).Elem()
- for i := 0; i < mtype.NumField(); i++ {
- mtypef := mtype.Field(i)
- opts := tomlOptions(mtypef)
- if opts.include {
- baseKey := opts.name
- keysToTry := []string{baseKey, strings.ToLower(baseKey), strings.ToTitle(baseKey)}
- for _, key := range keysToTry {
- exists := tval.Has(key)
- if !exists {
- continue
- }
- val := tval.Get(key)
- mvalf, err := valueFromToml(mtypef.Type, val)
- if err != nil {
- return mval, formatError(err, tval.GetPosition(key))
- }
- mval.Field(i).Set(mvalf)
- break
- }
- }
- }
- case reflect.Map:
- mval = reflect.MakeMap(mtype)
- for _, key := range tval.Keys() {
- val := tval.Get(key)
- mvalf, err := valueFromToml(mtype.Elem(), val)
- if err != nil {
- return mval, formatError(err, tval.GetPosition(key))
- }
- mval.SetMapIndex(reflect.ValueOf(key), mvalf)
- }
- }
- return mval, nil
-}
-
-// Convert toml value to marshal struct/map slice, using marshal type
-func valueFromTreeSlice(mtype reflect.Type, tval []*Tree) (reflect.Value, error) {
- mval := reflect.MakeSlice(mtype, len(tval), len(tval))
- for i := 0; i < len(tval); i++ {
- val, err := valueFromTree(mtype.Elem(), tval[i])
- if err != nil {
- return mval, err
- }
- mval.Index(i).Set(val)
- }
- return mval, nil
-}
-
-// Convert toml value to marshal primitive slice, using marshal type
-func valueFromOtherSlice(mtype reflect.Type, tval []interface{}) (reflect.Value, error) {
- mval := reflect.MakeSlice(mtype, len(tval), len(tval))
- for i := 0; i < len(tval); i++ {
- val, err := valueFromToml(mtype.Elem(), tval[i])
- if err != nil {
- return mval, err
- }
- mval.Index(i).Set(val)
- }
- return mval, nil
-}
-
-// Convert toml value to marshal value, using marshal type
-func valueFromToml(mtype reflect.Type, tval interface{}) (reflect.Value, error) {
- if mtype.Kind() == reflect.Ptr {
- return unwrapPointer(mtype, tval)
- }
- switch {
- case isTree(mtype):
- return valueFromTree(mtype, tval.(*Tree))
- case isTreeSlice(mtype):
- return valueFromTreeSlice(mtype, tval.([]*Tree))
- case isOtherSlice(mtype):
- return valueFromOtherSlice(mtype, tval.([]interface{}))
- default:
- switch mtype.Kind() {
- case reflect.Bool:
- val, ok := tval.(bool)
- if !ok {
- return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to bool", tval, tval)
- }
- return reflect.ValueOf(val), nil
- case reflect.Int:
- val, ok := tval.(int64)
- if !ok {
- return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to int", tval, tval)
- }
- return reflect.ValueOf(int(val)), nil
- case reflect.Int8:
- val, ok := tval.(int64)
- if !ok {
- return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to int", tval, tval)
- }
- return reflect.ValueOf(int8(val)), nil
- case reflect.Int16:
- val, ok := tval.(int64)
- if !ok {
- return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to int", tval, tval)
- }
- return reflect.ValueOf(int16(val)), nil
- case reflect.Int32:
- val, ok := tval.(int64)
- if !ok {
- return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to int", tval, tval)
- }
- return reflect.ValueOf(int32(val)), nil
- case reflect.Int64:
- val, ok := tval.(int64)
- if !ok {
- return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to int", tval, tval)
- }
- return reflect.ValueOf(val), nil
- case reflect.Uint:
- val, ok := tval.(int64)
- if !ok {
- return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to uint", tval, tval)
- }
- return reflect.ValueOf(uint(val)), nil
- case reflect.Uint8:
- val, ok := tval.(int64)
- if !ok {
- return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to uint", tval, tval)
- }
- return reflect.ValueOf(uint8(val)), nil
- case reflect.Uint16:
- val, ok := tval.(int64)
- if !ok {
- return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to uint", tval, tval)
- }
- return reflect.ValueOf(uint16(val)), nil
- case reflect.Uint32:
- val, ok := tval.(int64)
- if !ok {
- return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to uint", tval, tval)
- }
- return reflect.ValueOf(uint32(val)), nil
- case reflect.Uint64:
- val, ok := tval.(int64)
- if !ok {
- return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to uint", tval, tval)
- }
- return reflect.ValueOf(uint64(val)), nil
- case reflect.Float32:
- val, ok := tval.(float64)
- if !ok {
- return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to float", tval, tval)
- }
- return reflect.ValueOf(float32(val)), nil
- case reflect.Float64:
- val, ok := tval.(float64)
- if !ok {
- return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to float", tval, tval)
- }
- return reflect.ValueOf(val), nil
- case reflect.String:
- val, ok := tval.(string)
- if !ok {
- return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to string", tval, tval)
- }
- return reflect.ValueOf(val), nil
- case reflect.Struct:
- val, ok := tval.(time.Time)
- if !ok {
- return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to time", tval, tval)
- }
- return reflect.ValueOf(val), nil
- default:
- return reflect.ValueOf(nil), fmt.Errorf("Unmarshal can't handle %v(%v)", mtype, mtype.Kind())
- }
- }
-}
-
-func unwrapPointer(mtype reflect.Type, tval interface{}) (reflect.Value, error) {
- val, err := valueFromToml(mtype.Elem(), tval)
- if err != nil {
- return reflect.ValueOf(nil), err
- }
- mval := reflect.New(mtype.Elem())
- mval.Elem().Set(val)
- return mval, nil
-}
-
-func tomlOptions(vf reflect.StructField) tomlOpts {
- tag := vf.Tag.Get("toml")
- parse := strings.Split(tag, ",")
- result := tomlOpts{vf.Name, true, false}
- if parse[0] != "" {
- if parse[0] == "-" && len(parse) == 1 {
- result.include = false
- } else {
- result.name = strings.Trim(parse[0], " ")
- }
- }
- if vf.PkgPath != "" {
- result.include = false
- }
- if len(parse) > 1 && strings.Trim(parse[1], " ") == "omitempty" {
- result.omitempty = true
- }
- if vf.Type.Kind() == reflect.Ptr {
- result.omitempty = true
- }
- return result
-}
-
-func isZero(val reflect.Value) bool {
- switch val.Type().Kind() {
- case reflect.Map:
- fallthrough
- case reflect.Array:
- fallthrough
- case reflect.Slice:
- return val.Len() == 0
- default:
- return reflect.DeepEqual(val.Interface(), reflect.Zero(val.Type()).Interface())
- }
-}
-
-func formatError(err error, pos Position) error {
- if err.Error()[0] == '(' { // Error already contains position information
- return err
- }
- return fmt.Errorf("%s: %s", pos, err)
-}
diff --git a/vendor/github.com/pelletier/go-toml/marshal_test.go b/vendor/github.com/pelletier/go-toml/marshal_test.go
deleted file mode 100644
index dbfc7c1..0000000
--- a/vendor/github.com/pelletier/go-toml/marshal_test.go
+++ /dev/null
@@ -1,600 +0,0 @@
-package toml
-
-import (
- "bytes"
- "encoding/json"
- "fmt"
- "io/ioutil"
- "reflect"
- "testing"
- "time"
-)
-
-type basicMarshalTestStruct struct {
- String string `toml:"string"`
- StringList []string `toml:"strlist"`
- Sub basicMarshalTestSubStruct `toml:"subdoc"`
- SubList []basicMarshalTestSubStruct `toml:"sublist"`
-}
-
-type basicMarshalTestSubStruct struct {
- String2 string
-}
-
-var basicTestData = basicMarshalTestStruct{
- String: "Hello",
- StringList: []string{"Howdy", "Hey There"},
- Sub: basicMarshalTestSubStruct{"One"},
- SubList: []basicMarshalTestSubStruct{{"Two"}, {"Three"}},
-}
-
-var basicTestToml = []byte(`string = "Hello"
-strlist = ["Howdy","Hey There"]
-
-[subdoc]
- String2 = "One"
-
-[[sublist]]
- String2 = "Two"
-
-[[sublist]]
- String2 = "Three"
-`)
-
-func TestBasicMarshal(t *testing.T) {
- result, err := Marshal(basicTestData)
- if err != nil {
- t.Fatal(err)
- }
- expected := basicTestToml
- if !bytes.Equal(result, expected) {
- t.Errorf("Bad marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result)
- }
-}
-
-func TestBasicUnmarshal(t *testing.T) {
- result := basicMarshalTestStruct{}
- err := Unmarshal(basicTestToml, &result)
- expected := basicTestData
- if err != nil {
- t.Fatal(err)
- }
- if !reflect.DeepEqual(result, expected) {
- t.Errorf("Bad unmarshal: expected %v, got %v", expected, result)
- }
-}
-
-type testDoc struct {
- Title string `toml:"title"`
- Basics testDocBasics `toml:"basic"`
- BasicLists testDocBasicLists `toml:"basic_lists"`
- BasicMap map[string]string `toml:"basic_map"`
- Subdocs testDocSubs `toml:"subdoc"`
- SubDocList []testSubDoc `toml:"subdoclist"`
- SubDocPtrs []*testSubDoc `toml:"subdocptrs"`
- err int `toml:"shouldntBeHere"`
- unexported int `toml:"shouldntBeHere"`
- Unexported2 int `toml:"-"`
-}
-
-type testDocBasics struct {
- Bool bool `toml:"bool"`
- Date time.Time `toml:"date"`
- Float float32 `toml:"float"`
- Int int `toml:"int"`
- Uint uint `toml:"uint"`
- String *string `toml:"string"`
- unexported int `toml:"shouldntBeHere"`
-}
-
-type testDocBasicLists struct {
- Bools []bool `toml:"bools"`
- Dates []time.Time `toml:"dates"`
- Floats []*float32 `toml:"floats"`
- Ints []int `toml:"ints"`
- Strings []string `toml:"strings"`
- UInts []uint `toml:"uints"`
-}
-
-type testDocSubs struct {
- First testSubDoc `toml:"first"`
- Second *testSubDoc `toml:"second"`
-}
-
-type testSubDoc struct {
- Name string `toml:"name"`
- unexported int `toml:"shouldntBeHere"`
-}
-
-var biteMe = "Bite me"
-var float1 float32 = 12.3
-var float2 float32 = 45.6
-var float3 float32 = 78.9
-var subdoc = testSubDoc{"Second", 0}
-
-var docData = testDoc{
- Title: "TOML Marshal Testing",
- unexported: 0,
- Unexported2: 0,
- Basics: testDocBasics{
- Bool: true,
- Date: time.Date(1979, 5, 27, 7, 32, 0, 0, time.UTC),
- Float: 123.4,
- Int: 5000,
- Uint: 5001,
- String: &biteMe,
- unexported: 0,
- },
- BasicLists: testDocBasicLists{
- Bools: []bool{true, false, true},
- Dates: []time.Time{
- time.Date(1979, 5, 27, 7, 32, 0, 0, time.UTC),
- time.Date(1980, 5, 27, 7, 32, 0, 0, time.UTC),
- },
- Floats: []*float32{&float1, &float2, &float3},
- Ints: []int{8001, 8001, 8002},
- Strings: []string{"One", "Two", "Three"},
- UInts: []uint{5002, 5003},
- },
- BasicMap: map[string]string{
- "one": "one",
- "two": "two",
- },
- Subdocs: testDocSubs{
- First: testSubDoc{"First", 0},
- Second: &subdoc,
- },
- SubDocList: []testSubDoc{
- testSubDoc{"List.First", 0},
- testSubDoc{"List.Second", 0},
- },
- SubDocPtrs: []*testSubDoc{&subdoc},
-}
-
-func TestDocMarshal(t *testing.T) {
- result, err := Marshal(docData)
- if err != nil {
- t.Fatal(err)
- }
- expected, _ := ioutil.ReadFile("marshal_test.toml")
- if !bytes.Equal(result, expected) {
- t.Errorf("Bad marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result)
- }
-}
-
-func TestDocUnmarshal(t *testing.T) {
- result := testDoc{}
- tomlData, _ := ioutil.ReadFile("marshal_test.toml")
- err := Unmarshal(tomlData, &result)
- expected := docData
- if err != nil {
- t.Fatal(err)
- }
- if !reflect.DeepEqual(result, expected) {
- resStr, _ := json.MarshalIndent(result, "", " ")
- expStr, _ := json.MarshalIndent(expected, "", " ")
- t.Errorf("Bad unmarshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expStr, resStr)
- }
-}
-
-func TestDocPartialUnmarshal(t *testing.T) {
- result := testDocSubs{}
-
- tree, _ := LoadFile("marshal_test.toml")
- subTree := tree.Get("subdoc").(*Tree)
- err := subTree.Unmarshal(&result)
- expected := docData.Subdocs
- if err != nil {
- t.Fatal(err)
- }
- if !reflect.DeepEqual(result, expected) {
- resStr, _ := json.MarshalIndent(result, "", " ")
- expStr, _ := json.MarshalIndent(expected, "", " ")
- t.Errorf("Bad partial unmartial: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expStr, resStr)
- }
-}
-
-type tomlTypeCheckTest struct {
- name string
- item interface{}
- typ int //0=primitive, 1=otherslice, 2=treeslice, 3=tree
-}
-
-func TestTypeChecks(t *testing.T) {
- tests := []tomlTypeCheckTest{
- {"integer", 2, 0},
- {"time", time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC), 0},
- {"stringlist", []string{"hello", "hi"}, 1},
- {"timelist", []time.Time{time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC)}, 1},
- {"objectlist", []tomlTypeCheckTest{}, 2},
- {"object", tomlTypeCheckTest{}, 3},
- }
-
- for _, test := range tests {
- expected := []bool{false, false, false, false}
- expected[test.typ] = true
- result := []bool{
- isPrimitive(reflect.TypeOf(test.item)),
- isOtherSlice(reflect.TypeOf(test.item)),
- isTreeSlice(reflect.TypeOf(test.item)),
- isTree(reflect.TypeOf(test.item)),
- }
- if !reflect.DeepEqual(expected, result) {
- t.Errorf("Bad type check on %q: expected %v, got %v", test.name, expected, result)
- }
- }
-}
-
-type unexportedMarshalTestStruct struct {
- String string `toml:"string"`
- StringList []string `toml:"strlist"`
- Sub basicMarshalTestSubStruct `toml:"subdoc"`
- SubList []basicMarshalTestSubStruct `toml:"sublist"`
- unexported int `toml:"shouldntBeHere"`
- Unexported2 int `toml:"-"`
-}
-
-var unexportedTestData = unexportedMarshalTestStruct{
- String: "Hello",
- StringList: []string{"Howdy", "Hey There"},
- Sub: basicMarshalTestSubStruct{"One"},
- SubList: []basicMarshalTestSubStruct{{"Two"}, {"Three"}},
- unexported: 0,
- Unexported2: 0,
-}
-
-var unexportedTestToml = []byte(`string = "Hello"
-strlist = ["Howdy","Hey There"]
-unexported = 1
-shouldntBeHere = 2
-
-[subdoc]
- String2 = "One"
-
-[[sublist]]
- String2 = "Two"
-
-[[sublist]]
- String2 = "Three"
-`)
-
-func TestUnexportedUnmarshal(t *testing.T) {
- result := unexportedMarshalTestStruct{}
- err := Unmarshal(unexportedTestToml, &result)
- expected := unexportedTestData
- if err != nil {
- t.Fatal(err)
- }
- if !reflect.DeepEqual(result, expected) {
- t.Errorf("Bad unexported unmarshal: expected %v, got %v", expected, result)
- }
-}
-
-type errStruct struct {
- Bool bool `toml:"bool"`
- Date time.Time `toml:"date"`
- Float float64 `toml:"float"`
- Int int16 `toml:"int"`
- String *string `toml:"string"`
-}
-
-var errTomls = []string{
- "bool = truly\ndate = 1979-05-27T07:32:00Z\nfloat = 123.4\nint = 5000\nstring = \"Bite me\"",
- "bool = true\ndate = 1979-05-27T07:3200Z\nfloat = 123.4\nint = 5000\nstring = \"Bite me\"",
- "bool = true\ndate = 1979-05-27T07:32:00Z\nfloat = 123a4\nint = 5000\nstring = \"Bite me\"",
- "bool = true\ndate = 1979-05-27T07:32:00Z\nfloat = 123.4\nint = j000\nstring = \"Bite me\"",
- "bool = true\ndate = 1979-05-27T07:32:00Z\nfloat = 123.4\nint = 5000\nstring = Bite me",
- "bool = true\ndate = 1979-05-27T07:32:00Z\nfloat = 123.4\nint = 5000\nstring = Bite me",
- "bool = 1\ndate = 1979-05-27T07:32:00Z\nfloat = 123.4\nint = 5000\nstring = \"Bite me\"",
- "bool = true\ndate = 1\nfloat = 123.4\nint = 5000\nstring = \"Bite me\"",
- "bool = true\ndate = 1979-05-27T07:32:00Z\n\"sorry\"\nint = 5000\nstring = \"Bite me\"",
- "bool = true\ndate = 1979-05-27T07:32:00Z\nfloat = 123.4\nint = \"sorry\"\nstring = \"Bite me\"",
- "bool = true\ndate = 1979-05-27T07:32:00Z\nfloat = 123.4\nint = 5000\nstring = 1",
-}
-
-type mapErr struct {
- Vals map[string]float64
-}
-
-type intErr struct {
- Int1 int
- Int2 int8
- Int3 int16
- Int4 int32
- Int5 int64
- UInt1 uint
- UInt2 uint8
- UInt3 uint16
- UInt4 uint32
- UInt5 uint64
- Flt1 float32
- Flt2 float64
-}
-
-var intErrTomls = []string{
- "Int1 = []\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0",
- "Int1 = 1\nInt2 = []\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0",
- "Int1 = 1\nInt2 = 2\nInt3 = []\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0",
- "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = []\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0",
- "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = []\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0",
- "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = []\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0",
- "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = []\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0",
- "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = []\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0",
- "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = []\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0",
- "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = []\nFlt1 = 1.0\nFlt2 = 2.0",
- "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = []\nFlt2 = 2.0",
- "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = []",
-}
-
-func TestErrUnmarshal(t *testing.T) {
- for ind, toml := range errTomls {
- result := errStruct{}
- err := Unmarshal([]byte(toml), &result)
- if err == nil {
- t.Errorf("Expected err from case %d\n", ind)
- }
- }
- result2 := mapErr{}
- err := Unmarshal([]byte("[Vals]\nfred=\"1.2\""), &result2)
- if err == nil {
- t.Errorf("Expected err from map")
- }
- for ind, toml := range intErrTomls {
- result3 := intErr{}
- err := Unmarshal([]byte(toml), &result3)
- if err == nil {
- t.Errorf("Expected int err from case %d\n", ind)
- }
- }
-}
-
-type emptyMarshalTestStruct struct {
- Title string `toml:"title"`
- Bool bool `toml:"bool"`
- Int int `toml:"int"`
- String string `toml:"string"`
- StringList []string `toml:"stringlist"`
- Ptr *basicMarshalTestStruct `toml:"ptr"`
- Map map[string]string `toml:"map"`
-}
-
-var emptyTestData = emptyMarshalTestStruct{
- Title: "Placeholder",
- Bool: false,
- Int: 0,
- String: "",
- StringList: []string{},
- Ptr: nil,
- Map: map[string]string{},
-}
-
-var emptyTestToml = []byte(`bool = false
-int = 0
-string = ""
-stringlist = []
-title = "Placeholder"
-
-[map]
-`)
-
-type emptyMarshalTestStruct2 struct {
- Title string `toml:"title"`
- Bool bool `toml:"bool,omitempty"`
- Int int `toml:"int, omitempty"`
- String string `toml:"string,omitempty "`
- StringList []string `toml:"stringlist,omitempty"`
- Ptr *basicMarshalTestStruct `toml:"ptr,omitempty"`
- Map map[string]string `toml:"map,omitempty"`
-}
-
-var emptyTestData2 = emptyMarshalTestStruct2{
- Title: "Placeholder",
- Bool: false,
- Int: 0,
- String: "",
- StringList: []string{},
- Ptr: nil,
- Map: map[string]string{},
-}
-
-var emptyTestToml2 = []byte(`title = "Placeholder"
-`)
-
-func TestEmptyMarshal(t *testing.T) {
- result, err := Marshal(emptyTestData)
- if err != nil {
- t.Fatal(err)
- }
- expected := emptyTestToml
- if !bytes.Equal(result, expected) {
- t.Errorf("Bad empty marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result)
- }
-}
-
-func TestEmptyMarshalOmit(t *testing.T) {
- result, err := Marshal(emptyTestData2)
- if err != nil {
- t.Fatal(err)
- }
- expected := emptyTestToml2
- if !bytes.Equal(result, expected) {
- t.Errorf("Bad empty omit marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result)
- }
-}
-
-func TestEmptyUnmarshal(t *testing.T) {
- result := emptyMarshalTestStruct{}
- err := Unmarshal(emptyTestToml, &result)
- expected := emptyTestData
- if err != nil {
- t.Fatal(err)
- }
- if !reflect.DeepEqual(result, expected) {
- t.Errorf("Bad empty unmarshal: expected %v, got %v", expected, result)
- }
-}
-
-func TestEmptyUnmarshalOmit(t *testing.T) {
- result := emptyMarshalTestStruct2{}
- err := Unmarshal(emptyTestToml, &result)
- expected := emptyTestData2
- if err != nil {
- t.Fatal(err)
- }
- if !reflect.DeepEqual(result, expected) {
- t.Errorf("Bad empty omit unmarshal: expected %v, got %v", expected, result)
- }
-}
-
-type pointerMarshalTestStruct struct {
- Str *string
- List *[]string
- ListPtr *[]*string
- Map *map[string]string
- MapPtr *map[string]*string
- EmptyStr *string
- EmptyList *[]string
- EmptyMap *map[string]string
- DblPtr *[]*[]*string
-}
-
-var pointerStr = "Hello"
-var pointerList = []string{"Hello back"}
-var pointerListPtr = []*string{&pointerStr}
-var pointerMap = map[string]string{"response": "Goodbye"}
-var pointerMapPtr = map[string]*string{"alternate": &pointerStr}
-var pointerTestData = pointerMarshalTestStruct{
- Str: &pointerStr,
- List: &pointerList,
- ListPtr: &pointerListPtr,
- Map: &pointerMap,
- MapPtr: &pointerMapPtr,
- EmptyStr: nil,
- EmptyList: nil,
- EmptyMap: nil,
-}
-
-var pointerTestToml = []byte(`List = ["Hello back"]
-ListPtr = ["Hello"]
-Str = "Hello"
-
-[Map]
- response = "Goodbye"
-
-[MapPtr]
- alternate = "Hello"
-`)
-
-func TestPointerMarshal(t *testing.T) {
- result, err := Marshal(pointerTestData)
- if err != nil {
- t.Fatal(err)
- }
- expected := pointerTestToml
- if !bytes.Equal(result, expected) {
- t.Errorf("Bad pointer marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result)
- }
-}
-
-func TestPointerUnmarshal(t *testing.T) {
- result := pointerMarshalTestStruct{}
- err := Unmarshal(pointerTestToml, &result)
- expected := pointerTestData
- if err != nil {
- t.Fatal(err)
- }
- if !reflect.DeepEqual(result, expected) {
- t.Errorf("Bad pointer unmarshal: expected %v, got %v", expected, result)
- }
-}
-
-type nestedMarshalTestStruct struct {
- String [][]string
- //Struct [][]basicMarshalTestSubStruct
- StringPtr *[]*[]*string
- // StructPtr *[]*[]*basicMarshalTestSubStruct
-}
-
-var str1 = "Three"
-var str2 = "Four"
-var strPtr = []*string{&str1, &str2}
-var strPtr2 = []*[]*string{&strPtr}
-
-var nestedTestData = nestedMarshalTestStruct{
- String: [][]string{[]string{"Five", "Six"}, []string{"One", "Two"}},
- StringPtr: &strPtr2,
-}
-
-var nestedTestToml = []byte(`String = [["Five","Six"],["One","Two"]]
-StringPtr = [["Three","Four"]]
-`)
-
-func TestNestedMarshal(t *testing.T) {
- result, err := Marshal(nestedTestData)
- if err != nil {
- t.Fatal(err)
- }
- expected := nestedTestToml
- if !bytes.Equal(result, expected) {
- t.Errorf("Bad nested marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result)
- }
-}
-
-func TestNestedUnmarshal(t *testing.T) {
- result := nestedMarshalTestStruct{}
- err := Unmarshal(nestedTestToml, &result)
- expected := nestedTestData
- if err != nil {
- t.Fatal(err)
- }
- if !reflect.DeepEqual(result, expected) {
- t.Errorf("Bad nested unmarshal: expected %v, got %v", expected, result)
- }
-}
-
-type customMarshalerParent struct {
- Self customMarshaler `toml:"me"`
- Friends []customMarshaler `toml:"friends"`
-}
-
-type customMarshaler struct {
- FirsName string
- LastName string
-}
-
-func (c customMarshaler) MarshalTOML() ([]byte, error) {
- fullName := fmt.Sprintf("%s %s", c.FirsName, c.LastName)
- return []byte(fullName), nil
-}
-
-var customMarshalerData = customMarshaler{FirsName: "Sally", LastName: "Fields"}
-var customMarshalerToml = []byte(`Sally Fields`)
-var nestedCustomMarshalerData = customMarshalerParent{
- Self: customMarshaler{FirsName: "Maiku", LastName: "Suteda"},
- Friends: []customMarshaler{customMarshalerData},
-}
-var nestedCustomMarshalerToml = []byte(`friends = ["Sally Fields"]
-me = "Maiku Suteda"
-`)
-
-func TestCustomMarshaler(t *testing.T) {
- result, err := Marshal(customMarshalerData)
- if err != nil {
- t.Fatal(err)
- }
- expected := customMarshalerToml
- if !bytes.Equal(result, expected) {
- t.Errorf("Bad custom marshaler: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result)
- }
-}
-
-func TestNestedCustomMarshaler(t *testing.T) {
- result, err := Marshal(nestedCustomMarshalerData)
- if err != nil {
- t.Fatal(err)
- }
- expected := nestedCustomMarshalerToml
- if !bytes.Equal(result, expected) {
- t.Errorf("Bad nested custom marshaler: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result)
- }
-}
diff --git a/vendor/github.com/pelletier/go-toml/marshal_test.toml b/vendor/github.com/pelletier/go-toml/marshal_test.toml
deleted file mode 100644
index 1c5f98e..0000000
--- a/vendor/github.com/pelletier/go-toml/marshal_test.toml
+++ /dev/null
@@ -1,38 +0,0 @@
-title = "TOML Marshal Testing"
-
-[basic]
- bool = true
- date = 1979-05-27T07:32:00Z
- float = 123.4
- int = 5000
- string = "Bite me"
- uint = 5001
-
-[basic_lists]
- bools = [true,false,true]
- dates = [1979-05-27T07:32:00Z,1980-05-27T07:32:00Z]
- floats = [12.3,45.6,78.9]
- ints = [8001,8001,8002]
- strings = ["One","Two","Three"]
- uints = [5002,5003]
-
-[basic_map]
- one = "one"
- two = "two"
-
-[subdoc]
-
- [subdoc.first]
- name = "First"
-
- [subdoc.second]
- name = "Second"
-
-[[subdoclist]]
- name = "List.First"
-
-[[subdoclist]]
- name = "List.Second"
-
-[[subdocptrs]]
- name = "Second"
diff --git a/vendor/github.com/pelletier/go-toml/parser.go b/vendor/github.com/pelletier/go-toml/parser.go
deleted file mode 100644
index 8ee49cb..0000000
--- a/vendor/github.com/pelletier/go-toml/parser.go
+++ /dev/null
@@ -1,383 +0,0 @@
-// TOML Parser.
-
-package toml
-
-import (
- "errors"
- "fmt"
- "reflect"
- "regexp"
- "strconv"
- "strings"
- "time"
-)
-
-type tomlParser struct {
- flowIdx int
- flow []token
- tree *Tree
- currentTable []string
- seenTableKeys []string
-}
-
-type tomlParserStateFn func() tomlParserStateFn
-
-// Formats and panics an error message based on a token
-func (p *tomlParser) raiseError(tok *token, msg string, args ...interface{}) {
- panic(tok.Position.String() + ": " + fmt.Sprintf(msg, args...))
-}
-
-func (p *tomlParser) run() {
- for state := p.parseStart; state != nil; {
- state = state()
- }
-}
-
-func (p *tomlParser) peek() *token {
- if p.flowIdx >= len(p.flow) {
- return nil
- }
- return &p.flow[p.flowIdx]
-}
-
-func (p *tomlParser) assume(typ tokenType) {
- tok := p.getToken()
- if tok == nil {
- p.raiseError(tok, "was expecting token %s, but token stream is empty", tok)
- }
- if tok.typ != typ {
- p.raiseError(tok, "was expecting token %s, but got %s instead", typ, tok)
- }
-}
-
-func (p *tomlParser) getToken() *token {
- tok := p.peek()
- if tok == nil {
- return nil
- }
- p.flowIdx++
- return tok
-}
-
-func (p *tomlParser) parseStart() tomlParserStateFn {
- tok := p.peek()
-
- // end of stream, parsing is finished
- if tok == nil {
- return nil
- }
-
- switch tok.typ {
- case tokenDoubleLeftBracket:
- return p.parseGroupArray
- case tokenLeftBracket:
- return p.parseGroup
- case tokenKey:
- return p.parseAssign
- case tokenEOF:
- return nil
- default:
- p.raiseError(tok, "unexpected token")
- }
- return nil
-}
-
-func (p *tomlParser) parseGroupArray() tomlParserStateFn {
- startToken := p.getToken() // discard the [[
- key := p.getToken()
- if key.typ != tokenKeyGroupArray {
- p.raiseError(key, "unexpected token %s, was expecting a table array key", key)
- }
-
- // get or create table array element at the indicated part in the path
- keys, err := parseKey(key.val)
- if err != nil {
- p.raiseError(key, "invalid table array key: %s", err)
- }
- p.tree.createSubTree(keys[:len(keys)-1], startToken.Position) // create parent entries
- destTree := p.tree.GetPath(keys)
- var array []*Tree
- if destTree == nil {
- array = make([]*Tree, 0)
- } else if target, ok := destTree.([]*Tree); ok && target != nil {
- array = destTree.([]*Tree)
- } else {
- p.raiseError(key, "key %s is already assigned and not of type table array", key)
- }
- p.currentTable = keys
-
- // add a new tree to the end of the table array
- newTree := newTree()
- newTree.position = startToken.Position
- array = append(array, newTree)
- p.tree.SetPath(p.currentTable, array)
-
- // remove all keys that were children of this table array
- prefix := key.val + "."
- found := false
- for ii := 0; ii < len(p.seenTableKeys); {
- tableKey := p.seenTableKeys[ii]
- if strings.HasPrefix(tableKey, prefix) {
- p.seenTableKeys = append(p.seenTableKeys[:ii], p.seenTableKeys[ii+1:]...)
- } else {
- found = (tableKey == key.val)
- ii++
- }
- }
-
- // keep this key name from use by other kinds of assignments
- if !found {
- p.seenTableKeys = append(p.seenTableKeys, key.val)
- }
-
- // move to next parser state
- p.assume(tokenDoubleRightBracket)
- return p.parseStart
-}
-
-func (p *tomlParser) parseGroup() tomlParserStateFn {
- startToken := p.getToken() // discard the [
- key := p.getToken()
- if key.typ != tokenKeyGroup {
- p.raiseError(key, "unexpected token %s, was expecting a table key", key)
- }
- for _, item := range p.seenTableKeys {
- if item == key.val {
- p.raiseError(key, "duplicated tables")
- }
- }
-
- p.seenTableKeys = append(p.seenTableKeys, key.val)
- keys, err := parseKey(key.val)
- if err != nil {
- p.raiseError(key, "invalid table array key: %s", err)
- }
- if err := p.tree.createSubTree(keys, startToken.Position); err != nil {
- p.raiseError(key, "%s", err)
- }
- p.assume(tokenRightBracket)
- p.currentTable = keys
- return p.parseStart
-}
-
-func (p *tomlParser) parseAssign() tomlParserStateFn {
- key := p.getToken()
- p.assume(tokenEqual)
-
- value := p.parseRvalue()
- var tableKey []string
- if len(p.currentTable) > 0 {
- tableKey = p.currentTable
- } else {
- tableKey = []string{}
- }
-
- // find the table to assign, looking out for arrays of tables
- var targetNode *Tree
- switch node := p.tree.GetPath(tableKey).(type) {
- case []*Tree:
- targetNode = node[len(node)-1]
- case *Tree:
- targetNode = node
- default:
- p.raiseError(key, "Unknown table type for path: %s",
- strings.Join(tableKey, "."))
- }
-
- // assign value to the found table
- keyVals, err := parseKey(key.val)
- if err != nil {
- p.raiseError(key, "%s", err)
- }
- if len(keyVals) != 1 {
- p.raiseError(key, "Invalid key")
- }
- keyVal := keyVals[0]
- localKey := []string{keyVal}
- finalKey := append(tableKey, keyVal)
- if targetNode.GetPath(localKey) != nil {
- p.raiseError(key, "The following key was defined twice: %s",
- strings.Join(finalKey, "."))
- }
- var toInsert interface{}
-
- switch value.(type) {
- case *Tree, []*Tree:
- toInsert = value
- default:
- toInsert = &tomlValue{value, key.Position}
- }
- targetNode.values[keyVal] = toInsert
- return p.parseStart
-}
-
-var numberUnderscoreInvalidRegexp *regexp.Regexp
-
-func cleanupNumberToken(value string) (string, error) {
- if numberUnderscoreInvalidRegexp.MatchString(value) {
- return "", errors.New("invalid use of _ in number")
- }
- cleanedVal := strings.Replace(value, "_", "", -1)
- return cleanedVal, nil
-}
-
-func (p *tomlParser) parseRvalue() interface{} {
- tok := p.getToken()
- if tok == nil || tok.typ == tokenEOF {
- p.raiseError(tok, "expecting a value")
- }
-
- switch tok.typ {
- case tokenString:
- return tok.val
- case tokenTrue:
- return true
- case tokenFalse:
- return false
- case tokenInteger:
- cleanedVal, err := cleanupNumberToken(tok.val)
- if err != nil {
- p.raiseError(tok, "%s", err)
- }
- val, err := strconv.ParseInt(cleanedVal, 10, 64)
- if err != nil {
- p.raiseError(tok, "%s", err)
- }
- return val
- case tokenFloat:
- cleanedVal, err := cleanupNumberToken(tok.val)
- if err != nil {
- p.raiseError(tok, "%s", err)
- }
- val, err := strconv.ParseFloat(cleanedVal, 64)
- if err != nil {
- p.raiseError(tok, "%s", err)
- }
- return val
- case tokenDate:
- val, err := time.ParseInLocation(time.RFC3339Nano, tok.val, time.UTC)
- if err != nil {
- p.raiseError(tok, "%s", err)
- }
- return val
- case tokenLeftBracket:
- return p.parseArray()
- case tokenLeftCurlyBrace:
- return p.parseInlineTable()
- case tokenEqual:
- p.raiseError(tok, "cannot have multiple equals for the same key")
- case tokenError:
- p.raiseError(tok, "%s", tok)
- }
-
- p.raiseError(tok, "never reached")
-
- return nil
-}
-
-func tokenIsComma(t *token) bool {
- return t != nil && t.typ == tokenComma
-}
-
-func (p *tomlParser) parseInlineTable() *Tree {
- tree := newTree()
- var previous *token
-Loop:
- for {
- follow := p.peek()
- if follow == nil || follow.typ == tokenEOF {
- p.raiseError(follow, "unterminated inline table")
- }
- switch follow.typ {
- case tokenRightCurlyBrace:
- p.getToken()
- break Loop
- case tokenKey:
- if !tokenIsComma(previous) && previous != nil {
- p.raiseError(follow, "comma expected between fields in inline table")
- }
- key := p.getToken()
- p.assume(tokenEqual)
- value := p.parseRvalue()
- tree.Set(key.val, value)
- case tokenComma:
- if previous == nil {
- p.raiseError(follow, "inline table cannot start with a comma")
- }
- if tokenIsComma(previous) {
- p.raiseError(follow, "need field between two commas in inline table")
- }
- p.getToken()
- default:
- p.raiseError(follow, "unexpected token type in inline table: %s", follow.typ.String())
- }
- previous = follow
- }
- if tokenIsComma(previous) {
- p.raiseError(previous, "trailing comma at the end of inline table")
- }
- return tree
-}
-
-func (p *tomlParser) parseArray() interface{} {
- var array []interface{}
- arrayType := reflect.TypeOf(nil)
- for {
- follow := p.peek()
- if follow == nil || follow.typ == tokenEOF {
- p.raiseError(follow, "unterminated array")
- }
- if follow.typ == tokenRightBracket {
- p.getToken()
- break
- }
- val := p.parseRvalue()
- if arrayType == nil {
- arrayType = reflect.TypeOf(val)
- }
- if reflect.TypeOf(val) != arrayType {
- p.raiseError(follow, "mixed types in array")
- }
- array = append(array, val)
- follow = p.peek()
- if follow == nil || follow.typ == tokenEOF {
- p.raiseError(follow, "unterminated array")
- }
- if follow.typ != tokenRightBracket && follow.typ != tokenComma {
- p.raiseError(follow, "missing comma")
- }
- if follow.typ == tokenComma {
- p.getToken()
- }
- }
- // An array of Trees is actually an array of inline
- // tables, which is a shorthand for a table array. If the
- // array was not converted from []interface{} to []*Tree,
- // the two notations would not be equivalent.
- if arrayType == reflect.TypeOf(newTree()) {
- tomlArray := make([]*Tree, len(array))
- for i, v := range array {
- tomlArray[i] = v.(*Tree)
- }
- return tomlArray
- }
- return array
-}
-
-func parseToml(flow []token) *Tree {
- result := newTree()
- result.position = Position{1, 1}
- parser := &tomlParser{
- flowIdx: 0,
- flow: flow,
- tree: result,
- currentTable: make([]string, 0),
- seenTableKeys: make([]string, 0),
- }
- parser.run()
- return result
-}
-
-func init() {
- numberUnderscoreInvalidRegexp = regexp.MustCompile(`([^\d]_|_[^\d]|_$|^_)`)
-}
diff --git a/vendor/github.com/pelletier/go-toml/parser_test.go b/vendor/github.com/pelletier/go-toml/parser_test.go
deleted file mode 100644
index 508cb65..0000000
--- a/vendor/github.com/pelletier/go-toml/parser_test.go
+++ /dev/null
@@ -1,785 +0,0 @@
-package toml
-
-import (
- "fmt"
- "reflect"
- "testing"
- "time"
-
- "github.com/davecgh/go-spew/spew"
-)
-
-func assertSubTree(t *testing.T, path []string, tree *Tree, err error, ref map[string]interface{}) {
- if err != nil {
- t.Error("Non-nil error:", err.Error())
- return
- }
- for k, v := range ref {
- nextPath := append(path, k)
- t.Log("asserting path", nextPath)
- // NOTE: directly access key instead of resolve by path
- // NOTE: see TestSpecialKV
- switch node := tree.GetPath([]string{k}).(type) {
- case []*Tree:
- t.Log("\tcomparing key", nextPath, "by array iteration")
- for idx, item := range node {
- assertSubTree(t, nextPath, item, err, v.([]map[string]interface{})[idx])
- }
- case *Tree:
- t.Log("\tcomparing key", nextPath, "by subtree assestion")
- assertSubTree(t, nextPath, node, err, v.(map[string]interface{}))
- default:
- t.Log("\tcomparing key", nextPath, "by string representation because it's of type", reflect.TypeOf(node))
- if fmt.Sprintf("%v", node) != fmt.Sprintf("%v", v) {
- t.Errorf("was expecting %v at %v but got %v", v, k, node)
- }
- }
- }
-}
-
-func assertTree(t *testing.T, tree *Tree, err error, ref map[string]interface{}) {
- t.Log("Asserting tree:\n", spew.Sdump(tree))
- assertSubTree(t, []string{}, tree, err, ref)
- t.Log("Finished tree assertion.")
-}
-
-func TestCreateSubTree(t *testing.T) {
- tree := newTree()
- tree.createSubTree([]string{"a", "b", "c"}, Position{})
- tree.Set("a.b.c", 42)
- if tree.Get("a.b.c") != 42 {
- t.Fail()
- }
-}
-
-func TestSimpleKV(t *testing.T) {
- tree, err := Load("a = 42")
- assertTree(t, tree, err, map[string]interface{}{
- "a": int64(42),
- })
-
- tree, _ = Load("a = 42\nb = 21")
- assertTree(t, tree, err, map[string]interface{}{
- "a": int64(42),
- "b": int64(21),
- })
-}
-
-func TestNumberInKey(t *testing.T) {
- tree, err := Load("hello2 = 42")
- assertTree(t, tree, err, map[string]interface{}{
- "hello2": int64(42),
- })
-}
-
-func TestSimpleNumbers(t *testing.T) {
- tree, err := Load("a = +42\nb = -21\nc = +4.2\nd = -2.1")
- assertTree(t, tree, err, map[string]interface{}{
- "a": int64(42),
- "b": int64(-21),
- "c": float64(4.2),
- "d": float64(-2.1),
- })
-}
-
-func TestNumbersWithUnderscores(t *testing.T) {
- tree, err := Load("a = 1_000")
- assertTree(t, tree, err, map[string]interface{}{
- "a": int64(1000),
- })
-
- tree, err = Load("a = 5_349_221")
- assertTree(t, tree, err, map[string]interface{}{
- "a": int64(5349221),
- })
-
- tree, err = Load("a = 1_2_3_4_5")
- assertTree(t, tree, err, map[string]interface{}{
- "a": int64(12345),
- })
-
- tree, err = Load("flt8 = 9_224_617.445_991_228_313")
- assertTree(t, tree, err, map[string]interface{}{
- "flt8": float64(9224617.445991228313),
- })
-
- tree, err = Load("flt9 = 1e1_00")
- assertTree(t, tree, err, map[string]interface{}{
- "flt9": float64(1e100),
- })
-}
-
-func TestFloatsWithExponents(t *testing.T) {
- tree, err := Load("a = 5e+22\nb = 5E+22\nc = -5e+22\nd = -5e-22\ne = 6.626e-34")
- assertTree(t, tree, err, map[string]interface{}{
- "a": float64(5e+22),
- "b": float64(5E+22),
- "c": float64(-5e+22),
- "d": float64(-5e-22),
- "e": float64(6.626e-34),
- })
-}
-
-func TestSimpleDate(t *testing.T) {
- tree, err := Load("a = 1979-05-27T07:32:00Z")
- assertTree(t, tree, err, map[string]interface{}{
- "a": time.Date(1979, time.May, 27, 7, 32, 0, 0, time.UTC),
- })
-}
-
-func TestDateOffset(t *testing.T) {
- tree, err := Load("a = 1979-05-27T00:32:00-07:00")
- assertTree(t, tree, err, map[string]interface{}{
- "a": time.Date(1979, time.May, 27, 0, 32, 0, 0, time.FixedZone("", -7*60*60)),
- })
-}
-
-func TestDateNano(t *testing.T) {
- tree, err := Load("a = 1979-05-27T00:32:00.999999999-07:00")
- assertTree(t, tree, err, map[string]interface{}{
- "a": time.Date(1979, time.May, 27, 0, 32, 0, 999999999, time.FixedZone("", -7*60*60)),
- })
-}
-
-func TestSimpleString(t *testing.T) {
- tree, err := Load("a = \"hello world\"")
- assertTree(t, tree, err, map[string]interface{}{
- "a": "hello world",
- })
-}
-
-func TestSpaceKey(t *testing.T) {
- tree, err := Load("\"a b\" = \"hello world\"")
- assertTree(t, tree, err, map[string]interface{}{
- "a b": "hello world",
- })
-}
-
-func TestStringEscapables(t *testing.T) {
- tree, err := Load("a = \"a \\n b\"")
- assertTree(t, tree, err, map[string]interface{}{
- "a": "a \n b",
- })
-
- tree, err = Load("a = \"a \\t b\"")
- assertTree(t, tree, err, map[string]interface{}{
- "a": "a \t b",
- })
-
- tree, err = Load("a = \"a \\r b\"")
- assertTree(t, tree, err, map[string]interface{}{
- "a": "a \r b",
- })
-
- tree, err = Load("a = \"a \\\\ b\"")
- assertTree(t, tree, err, map[string]interface{}{
- "a": "a \\ b",
- })
-}
-
-func TestEmptyQuotedString(t *testing.T) {
- tree, err := Load(`[""]
-"" = 1`)
- assertTree(t, tree, err, map[string]interface{}{
- "": map[string]interface{}{
- "": int64(1),
- },
- })
-}
-
-func TestBools(t *testing.T) {
- tree, err := Load("a = true\nb = false")
- assertTree(t, tree, err, map[string]interface{}{
- "a": true,
- "b": false,
- })
-}
-
-func TestNestedKeys(t *testing.T) {
- tree, err := Load("[a.b.c]\nd = 42")
- assertTree(t, tree, err, map[string]interface{}{
- "a": map[string]interface{}{
- "b": map[string]interface{}{
- "c": map[string]interface{}{
- "d": int64(42),
- },
- },
- },
- })
-}
-
-func TestNestedQuotedUnicodeKeys(t *testing.T) {
- tree, err := Load("[ j . \"ʞ\" . l ]\nd = 42")
- assertTree(t, tree, err, map[string]interface{}{
- "j": map[string]interface{}{
- "ʞ": map[string]interface{}{
- "l": map[string]interface{}{
- "d": int64(42),
- },
- },
- },
- })
-
- tree, err = Load("[ g . h . i ]\nd = 42")
- assertTree(t, tree, err, map[string]interface{}{
- "g": map[string]interface{}{
- "h": map[string]interface{}{
- "i": map[string]interface{}{
- "d": int64(42),
- },
- },
- },
- })
-
- tree, err = Load("[ d.e.f ]\nk = 42")
- assertTree(t, tree, err, map[string]interface{}{
- "d": map[string]interface{}{
- "e": map[string]interface{}{
- "f": map[string]interface{}{
- "k": int64(42),
- },
- },
- },
- })
-}
-
-func TestArrayOne(t *testing.T) {
- tree, err := Load("a = [1]")
- assertTree(t, tree, err, map[string]interface{}{
- "a": []int64{int64(1)},
- })
-}
-
-func TestArrayZero(t *testing.T) {
- tree, err := Load("a = []")
- assertTree(t, tree, err, map[string]interface{}{
- "a": []interface{}{},
- })
-}
-
-func TestArraySimple(t *testing.T) {
- tree, err := Load("a = [42, 21, 10]")
- assertTree(t, tree, err, map[string]interface{}{
- "a": []int64{int64(42), int64(21), int64(10)},
- })
-
- tree, _ = Load("a = [42, 21, 10,]")
- assertTree(t, tree, err, map[string]interface{}{
- "a": []int64{int64(42), int64(21), int64(10)},
- })
-}
-
-func TestArrayMultiline(t *testing.T) {
- tree, err := Load("a = [42,\n21, 10,]")
- assertTree(t, tree, err, map[string]interface{}{
- "a": []int64{int64(42), int64(21), int64(10)},
- })
-}
-
-func TestArrayNested(t *testing.T) {
- tree, err := Load("a = [[42, 21], [10]]")
- assertTree(t, tree, err, map[string]interface{}{
- "a": [][]int64{{int64(42), int64(21)}, {int64(10)}},
- })
-}
-
-func TestNestedArrayComment(t *testing.T) {
- tree, err := Load(`
-someArray = [
-# does not work
-["entry1"]
-]`)
- assertTree(t, tree, err, map[string]interface{}{
- "someArray": [][]string{{"entry1"}},
- })
-}
-
-func TestNestedEmptyArrays(t *testing.T) {
- tree, err := Load("a = [[[]]]")
- assertTree(t, tree, err, map[string]interface{}{
- "a": [][][]interface{}{{{}}},
- })
-}
-
-func TestArrayMixedTypes(t *testing.T) {
- _, err := Load("a = [42, 16.0]")
- if err.Error() != "(1, 10): mixed types in array" {
- t.Error("Bad error message:", err.Error())
- }
-
- _, err = Load("a = [42, \"hello\"]")
- if err.Error() != "(1, 11): mixed types in array" {
- t.Error("Bad error message:", err.Error())
- }
-}
-
-func TestArrayNestedStrings(t *testing.T) {
- tree, err := Load("data = [ [\"gamma\", \"delta\"], [\"Foo\"] ]")
- assertTree(t, tree, err, map[string]interface{}{
- "data": [][]string{{"gamma", "delta"}, {"Foo"}},
- })
-}
-
-func TestParseUnknownRvalue(t *testing.T) {
- _, err := Load("a = !bssss")
- if err == nil {
- t.Error("Expecting a parse error")
- }
-
- _, err = Load("a = /b")
- if err == nil {
- t.Error("Expecting a parse error")
- }
-}
-
-func TestMissingValue(t *testing.T) {
- _, err := Load("a = ")
- if err.Error() != "(1, 5): expecting a value" {
- t.Error("Bad error message:", err.Error())
- }
-}
-
-func TestUnterminatedArray(t *testing.T) {
- _, err := Load("a = [1,")
- if err.Error() != "(1, 8): unterminated array" {
- t.Error("Bad error message:", err.Error())
- }
-
- _, err = Load("a = [1")
- if err.Error() != "(1, 7): unterminated array" {
- t.Error("Bad error message:", err.Error())
- }
-
- _, err = Load("a = [1 2")
- if err.Error() != "(1, 8): missing comma" {
- t.Error("Bad error message:", err.Error())
- }
-}
-
-func TestNewlinesInArrays(t *testing.T) {
- tree, err := Load("a = [1,\n2,\n3]")
- assertTree(t, tree, err, map[string]interface{}{
- "a": []int64{int64(1), int64(2), int64(3)},
- })
-}
-
-func TestArrayWithExtraComma(t *testing.T) {
- tree, err := Load("a = [1,\n2,\n3,\n]")
- assertTree(t, tree, err, map[string]interface{}{
- "a": []int64{int64(1), int64(2), int64(3)},
- })
-}
-
-func TestArrayWithExtraCommaComment(t *testing.T) {
- tree, err := Load("a = [1, # wow\n2, # such items\n3, # so array\n]")
- assertTree(t, tree, err, map[string]interface{}{
- "a": []int64{int64(1), int64(2), int64(3)},
- })
-}
-
-func TestSimpleInlineGroup(t *testing.T) {
- tree, err := Load("key = {a = 42}")
- assertTree(t, tree, err, map[string]interface{}{
- "key": map[string]interface{}{
- "a": int64(42),
- },
- })
-}
-
-func TestDoubleInlineGroup(t *testing.T) {
- tree, err := Load("key = {a = 42, b = \"foo\"}")
- assertTree(t, tree, err, map[string]interface{}{
- "key": map[string]interface{}{
- "a": int64(42),
- "b": "foo",
- },
- })
-}
-
-func TestExampleInlineGroup(t *testing.T) {
- tree, err := Load(`name = { first = "Tom", last = "Preston-Werner" }
-point = { x = 1, y = 2 }`)
- assertTree(t, tree, err, map[string]interface{}{
- "name": map[string]interface{}{
- "first": "Tom",
- "last": "Preston-Werner",
- },
- "point": map[string]interface{}{
- "x": int64(1),
- "y": int64(2),
- },
- })
-}
-
-func TestExampleInlineGroupInArray(t *testing.T) {
- tree, err := Load(`points = [{ x = 1, y = 2 }]`)
- assertTree(t, tree, err, map[string]interface{}{
- "points": []map[string]interface{}{
- {
- "x": int64(1),
- "y": int64(2),
- },
- },
- })
-}
-
-func TestInlineTableUnterminated(t *testing.T) {
- _, err := Load("foo = {")
- if err.Error() != "(1, 8): unterminated inline table" {
- t.Error("Bad error message:", err.Error())
- }
-}
-
-func TestInlineTableCommaExpected(t *testing.T) {
- _, err := Load("foo = {hello = 53 test = foo}")
- if err.Error() != "(1, 19): comma expected between fields in inline table" {
- t.Error("Bad error message:", err.Error())
- }
-}
-
-func TestInlineTableCommaStart(t *testing.T) {
- _, err := Load("foo = {, hello = 53}")
- if err.Error() != "(1, 8): inline table cannot start with a comma" {
- t.Error("Bad error message:", err.Error())
- }
-}
-
-func TestInlineTableDoubleComma(t *testing.T) {
- _, err := Load("foo = {hello = 53,, foo = 17}")
- if err.Error() != "(1, 19): need field between two commas in inline table" {
- t.Error("Bad error message:", err.Error())
- }
-}
-
-func TestDuplicateGroups(t *testing.T) {
- _, err := Load("[foo]\na=2\n[foo]b=3")
- if err.Error() != "(3, 2): duplicated tables" {
- t.Error("Bad error message:", err.Error())
- }
-}
-
-func TestDuplicateKeys(t *testing.T) {
- _, err := Load("foo = 2\nfoo = 3")
- if err.Error() != "(2, 1): The following key was defined twice: foo" {
- t.Error("Bad error message:", err.Error())
- }
-}
-
-func TestEmptyIntermediateTable(t *testing.T) {
- _, err := Load("[foo..bar]")
- if err.Error() != "(1, 2): invalid table array key: empty table key" {
- t.Error("Bad error message:", err.Error())
- }
-}
-
-func TestImplicitDeclarationBefore(t *testing.T) {
- tree, err := Load("[a.b.c]\nanswer = 42\n[a]\nbetter = 43")
- assertTree(t, tree, err, map[string]interface{}{
- "a": map[string]interface{}{
- "b": map[string]interface{}{
- "c": map[string]interface{}{
- "answer": int64(42),
- },
- },
- "better": int64(43),
- },
- })
-}
-
-func TestFloatsWithoutLeadingZeros(t *testing.T) {
- _, err := Load("a = .42")
- if err.Error() != "(1, 5): cannot start float with a dot" {
- t.Error("Bad error message:", err.Error())
- }
-
- _, err = Load("a = -.42")
- if err.Error() != "(1, 5): cannot start float with a dot" {
- t.Error("Bad error message:", err.Error())
- }
-}
-
-func TestMissingFile(t *testing.T) {
- _, err := LoadFile("foo.toml")
- if err.Error() != "open foo.toml: no such file or directory" &&
- err.Error() != "open foo.toml: The system cannot find the file specified." {
- t.Error("Bad error message:", err.Error())
- }
-}
-
-func TestParseFile(t *testing.T) {
- tree, err := LoadFile("example.toml")
-
- assertTree(t, tree, err, map[string]interface{}{
- "title": "TOML Example",
- "owner": map[string]interface{}{
- "name": "Tom Preston-Werner",
- "organization": "GitHub",
- "bio": "GitHub Cofounder & CEO\nLikes tater tots and beer.",
- "dob": time.Date(1979, time.May, 27, 7, 32, 0, 0, time.UTC),
- },
- "database": map[string]interface{}{
- "server": "192.168.1.1",
- "ports": []int64{8001, 8001, 8002},
- "connection_max": 5000,
- "enabled": true,
- },
- "servers": map[string]interface{}{
- "alpha": map[string]interface{}{
- "ip": "10.0.0.1",
- "dc": "eqdc10",
- },
- "beta": map[string]interface{}{
- "ip": "10.0.0.2",
- "dc": "eqdc10",
- },
- },
- "clients": map[string]interface{}{
- "data": []interface{}{
- []string{"gamma", "delta"},
- []int64{1, 2},
- },
- },
- })
-}
-
-func TestParseFileCRLF(t *testing.T) {
- tree, err := LoadFile("example-crlf.toml")
-
- assertTree(t, tree, err, map[string]interface{}{
- "title": "TOML Example",
- "owner": map[string]interface{}{
- "name": "Tom Preston-Werner",
- "organization": "GitHub",
- "bio": "GitHub Cofounder & CEO\nLikes tater tots and beer.",
- "dob": time.Date(1979, time.May, 27, 7, 32, 0, 0, time.UTC),
- },
- "database": map[string]interface{}{
- "server": "192.168.1.1",
- "ports": []int64{8001, 8001, 8002},
- "connection_max": 5000,
- "enabled": true,
- },
- "servers": map[string]interface{}{
- "alpha": map[string]interface{}{
- "ip": "10.0.0.1",
- "dc": "eqdc10",
- },
- "beta": map[string]interface{}{
- "ip": "10.0.0.2",
- "dc": "eqdc10",
- },
- },
- "clients": map[string]interface{}{
- "data": []interface{}{
- []string{"gamma", "delta"},
- []int64{1, 2},
- },
- },
- })
-}
-
-func TestParseKeyGroupArray(t *testing.T) {
- tree, err := Load("[[foo.bar]] a = 42\n[[foo.bar]] a = 69")
- assertTree(t, tree, err, map[string]interface{}{
- "foo": map[string]interface{}{
- "bar": []map[string]interface{}{
- {"a": int64(42)},
- {"a": int64(69)},
- },
- },
- })
-}
-
-func TestParseKeyGroupArrayUnfinished(t *testing.T) {
- _, err := Load("[[foo.bar]\na = 42")
- if err.Error() != "(1, 10): was expecting token [[, but got unclosed table array key instead" {
- t.Error("Bad error message:", err.Error())
- }
-
- _, err = Load("[[foo.[bar]\na = 42")
- if err.Error() != "(1, 3): unexpected token table array key cannot contain ']', was expecting a table array key" {
- t.Error("Bad error message:", err.Error())
- }
-}
-
-func TestParseKeyGroupArrayQueryExample(t *testing.T) {
- tree, err := Load(`
- [[book]]
- title = "The Stand"
- author = "Stephen King"
- [[book]]
- title = "For Whom the Bell Tolls"
- author = "Ernest Hemmingway"
- [[book]]
- title = "Neuromancer"
- author = "William Gibson"
- `)
-
- assertTree(t, tree, err, map[string]interface{}{
- "book": []map[string]interface{}{
- {"title": "The Stand", "author": "Stephen King"},
- {"title": "For Whom the Bell Tolls", "author": "Ernest Hemmingway"},
- {"title": "Neuromancer", "author": "William Gibson"},
- },
- })
-}
-
-func TestParseKeyGroupArraySpec(t *testing.T) {
- tree, err := Load("[[fruit]]\n name=\"apple\"\n [fruit.physical]\n color=\"red\"\n shape=\"round\"\n [[fruit]]\n name=\"banana\"")
- assertTree(t, tree, err, map[string]interface{}{
- "fruit": []map[string]interface{}{
- {"name": "apple", "physical": map[string]interface{}{"color": "red", "shape": "round"}},
- {"name": "banana"},
- },
- })
-}
-
-func TestTomlValueStringRepresentation(t *testing.T) {
- for idx, item := range []struct {
- Value interface{}
- Expect string
- }{
- {int64(12345), "12345"},
- {uint64(50), "50"},
- {float64(123.45), "123.45"},
- {bool(true), "true"},
- {"hello world", "\"hello world\""},
- {"\b\t\n\f\r\"\\", "\"\\b\\t\\n\\f\\r\\\"\\\\\""},
- {"\x05", "\"\\u0005\""},
- {time.Date(1979, time.May, 27, 7, 32, 0, 0, time.UTC),
- "1979-05-27T07:32:00Z"},
- {[]interface{}{"gamma", "delta"},
- "[\"gamma\",\"delta\"]"},
- {nil, ""},
- } {
- result, err := tomlValueStringRepresentation(item.Value)
- if err != nil {
- t.Errorf("Test %d - unexpected error: %s", idx, err)
- }
- if result != item.Expect {
- t.Errorf("Test %d - got '%s', expected '%s'", idx, result, item.Expect)
- }
- }
-}
-
-func TestToStringMapStringString(t *testing.T) {
- tree, err := TreeFromMap(map[string]interface{}{"m": map[string]interface{}{"v": "abc"}})
- if err != nil {
- t.Fatalf("unexpected error: %s", err)
- }
- want := "\n[m]\n v = \"abc\"\n"
- got := tree.String()
-
- if got != want {
- t.Errorf("want:\n%q\ngot:\n%q", want, got)
- }
-}
-
-func assertPosition(t *testing.T, text string, ref map[string]Position) {
- tree, err := Load(text)
- if err != nil {
- t.Errorf("Error loading document text: `%v`", text)
- t.Errorf("Error: %v", err)
- }
- for path, pos := range ref {
- testPos := tree.GetPosition(path)
- if testPos.Invalid() {
- t.Errorf("Failed to query tree path or path has invalid position: %s", path)
- } else if pos != testPos {
- t.Errorf("Expected position %v, got %v instead", pos, testPos)
- }
- }
-}
-
-func TestDocumentPositions(t *testing.T) {
- assertPosition(t,
- "[foo]\nbar=42\nbaz=69",
- map[string]Position{
- "": {1, 1},
- "foo": {1, 1},
- "foo.bar": {2, 1},
- "foo.baz": {3, 1},
- })
-}
-
-func TestDocumentPositionsWithSpaces(t *testing.T) {
- assertPosition(t,
- " [foo]\n bar=42\n baz=69",
- map[string]Position{
- "": {1, 1},
- "foo": {1, 3},
- "foo.bar": {2, 3},
- "foo.baz": {3, 3},
- })
-}
-
-func TestDocumentPositionsWithGroupArray(t *testing.T) {
- assertPosition(t,
- "[[foo]]\nbar=42\nbaz=69",
- map[string]Position{
- "": {1, 1},
- "foo": {1, 1},
- "foo.bar": {2, 1},
- "foo.baz": {3, 1},
- })
-}
-
-func TestNestedTreePosition(t *testing.T) {
- assertPosition(t,
- "[foo.bar]\na=42\nb=69",
- map[string]Position{
- "": {1, 1},
- "foo": {1, 1},
- "foo.bar": {1, 1},
- "foo.bar.a": {2, 1},
- "foo.bar.b": {3, 1},
- })
-}
-
-func TestInvalidGroupArray(t *testing.T) {
- _, err := Load("[table#key]\nanswer = 42")
- if err == nil {
- t.Error("Should error")
- }
-
- _, err = Load("[foo.[bar]\na = 42")
- if err.Error() != "(1, 2): unexpected token table key cannot contain ']', was expecting a table key" {
- t.Error("Bad error message:", err.Error())
- }
-}
-
-func TestDoubleEqual(t *testing.T) {
- _, err := Load("foo= = 2")
- if err.Error() != "(1, 6): cannot have multiple equals for the same key" {
- t.Error("Bad error message:", err.Error())
- }
-}
-
-func TestGroupArrayReassign(t *testing.T) {
- _, err := Load("[hello]\n[[hello]]")
- if err.Error() != "(2, 3): key \"hello\" is already assigned and not of type table array" {
- t.Error("Bad error message:", err.Error())
- }
-}
-
-func TestInvalidFloatParsing(t *testing.T) {
- _, err := Load("a=1e_2")
- if err.Error() != "(1, 3): invalid use of _ in number" {
- t.Error("Bad error message:", err.Error())
- }
-
- _, err = Load("a=1e2_")
- if err.Error() != "(1, 3): invalid use of _ in number" {
- t.Error("Bad error message:", err.Error())
- }
-
- _, err = Load("a=1__2")
- if err.Error() != "(1, 3): invalid use of _ in number" {
- t.Error("Bad error message:", err.Error())
- }
-
- _, err = Load("a=_1_2")
- if err.Error() != "(1, 3): cannot start number with underscore" {
- t.Error("Bad error message:", err.Error())
- }
-}
diff --git a/vendor/github.com/pelletier/go-toml/position.go b/vendor/github.com/pelletier/go-toml/position.go
deleted file mode 100644
index c17bff8..0000000
--- a/vendor/github.com/pelletier/go-toml/position.go
+++ /dev/null
@@ -1,29 +0,0 @@
-// Position support for go-toml
-
-package toml
-
-import (
- "fmt"
-)
-
-// Position of a document element within a TOML document.
-//
-// Line and Col are both 1-indexed positions for the element's line number and
-// column number, respectively. Values of zero or less will cause Invalid(),
-// to return true.
-type Position struct {
- Line int // line within the document
- Col int // column within the line
-}
-
-// String representation of the position.
-// Displays 1-indexed line and column numbers.
-func (p Position) String() string {
- return fmt.Sprintf("(%d, %d)", p.Line, p.Col)
-}
-
-// Invalid returns whether or not the position is valid (i.e. with negative or
-// null values)
-func (p Position) Invalid() bool {
- return p.Line <= 0 || p.Col <= 0
-}
diff --git a/vendor/github.com/pelletier/go-toml/position_test.go b/vendor/github.com/pelletier/go-toml/position_test.go
deleted file mode 100644
index 63ad1af..0000000
--- a/vendor/github.com/pelletier/go-toml/position_test.go
+++ /dev/null
@@ -1,29 +0,0 @@
-// Testing support for go-toml
-
-package toml
-
-import (
- "testing"
-)
-
-func TestPositionString(t *testing.T) {
- p := Position{123, 456}
- expected := "(123, 456)"
- value := p.String()
-
- if value != expected {
- t.Errorf("Expected %v, got %v instead", expected, value)
- }
-}
-
-func TestInvalid(t *testing.T) {
- for i, v := range []Position{
- {0, 1234},
- {1234, 0},
- {0, 0},
- } {
- if !v.Invalid() {
- t.Errorf("Position at %v is valid: %v", i, v)
- }
- }
-}
diff --git a/vendor/github.com/pelletier/go-toml/test.sh b/vendor/github.com/pelletier/go-toml/test.sh
deleted file mode 100755
index 91a8896..0000000
--- a/vendor/github.com/pelletier/go-toml/test.sh
+++ /dev/null
@@ -1,90 +0,0 @@
-#!/bin/bash
-# fail out of the script if anything here fails
-set -e
-
-# set the path to the present working directory
-export GOPATH=`pwd`
-
-function git_clone() {
- path=$1
- branch=$2
- version=$3
- if [ ! -d "src/$path" ]; then
- mkdir -p src/$path
- git clone https://$path.git src/$path
- fi
- pushd src/$path
- git checkout "$branch"
- git reset --hard "$version"
- popd
-}
-
-# Remove potential previous runs
-rm -rf src test_program_bin toml-test
-
-# Run go vet
-go vet ./...
-
-go get github.com/pelletier/go-buffruneio
-go get github.com/davecgh/go-spew/spew
-go get gopkg.in/yaml.v2
-go get github.com/BurntSushi/toml
-
-# get code for BurntSushi TOML validation
-# pinning all to 'HEAD' for version 0.3.x work (TODO: pin to commit hash when tests stabilize)
-git_clone github.com/BurntSushi/toml master HEAD
-git_clone github.com/BurntSushi/toml-test master HEAD #was: 0.2.0 HEAD
-
-# build the BurntSushi test application
-go build -o toml-test github.com/BurntSushi/toml-test
-
-# vendorize the current lib for testing
-# NOTE: this basically mocks an install without having to go back out to github for code
-mkdir -p src/github.com/pelletier/go-toml/cmd
-mkdir -p src/github.com/pelletier/go-toml/query
-cp *.go *.toml src/github.com/pelletier/go-toml
-cp -R cmd/* src/github.com/pelletier/go-toml/cmd
-cp -R query/* src/github.com/pelletier/go-toml/query
-go build -o test_program_bin src/github.com/pelletier/go-toml/cmd/test_program.go
-
-# Run basic unit tests
-go test github.com/pelletier/go-toml -covermode=count -coverprofile=coverage.out
-go test github.com/pelletier/go-toml/cmd/tomljson
-go test github.com/pelletier/go-toml/query
-
-# run the entire BurntSushi test suite
-if [[ $# -eq 0 ]] ; then
- echo "Running all BurntSushi tests"
- ./toml-test ./test_program_bin | tee test_out
-else
- # run a specific test
- test=$1
- test_path='src/github.com/BurntSushi/toml-test/tests'
- valid_test="$test_path/valid/$test"
- invalid_test="$test_path/invalid/$test"
-
- if [ -e "$valid_test.toml" ]; then
- echo "Valid Test TOML for $test:"
- echo "===="
- cat "$valid_test.toml"
-
- echo "Valid Test JSON for $test:"
- echo "===="
- cat "$valid_test.json"
-
- echo "Go-TOML Output for $test:"
- echo "===="
- cat "$valid_test.toml" | ./test_program_bin
- fi
-
- if [ -e "$invalid_test.toml" ]; then
- echo "Invalid Test TOML for $test:"
- echo "===="
- cat "$invalid_test.toml"
-
- echo "Go-TOML Output for $test:"
- echo "===="
- echo "go-toml Output:"
- cat "$invalid_test.toml" | ./test_program_bin
- fi
-fi
diff --git a/vendor/github.com/pelletier/go-toml/token.go b/vendor/github.com/pelletier/go-toml/token.go
deleted file mode 100644
index 5581fe0..0000000
--- a/vendor/github.com/pelletier/go-toml/token.go
+++ /dev/null
@@ -1,140 +0,0 @@
-package toml
-
-import (
- "fmt"
- "strconv"
- "unicode"
-)
-
-// Define tokens
-type tokenType int
-
-const (
- eof = -(iota + 1)
-)
-
-const (
- tokenError tokenType = iota
- tokenEOF
- tokenComment
- tokenKey
- tokenString
- tokenInteger
- tokenTrue
- tokenFalse
- tokenFloat
- tokenEqual
- tokenLeftBracket
- tokenRightBracket
- tokenLeftCurlyBrace
- tokenRightCurlyBrace
- tokenLeftParen
- tokenRightParen
- tokenDoubleLeftBracket
- tokenDoubleRightBracket
- tokenDate
- tokenKeyGroup
- tokenKeyGroupArray
- tokenComma
- tokenColon
- tokenDollar
- tokenStar
- tokenQuestion
- tokenDot
- tokenDotDot
- tokenEOL
-)
-
-var tokenTypeNames = []string{
- "Error",
- "EOF",
- "Comment",
- "Key",
- "String",
- "Integer",
- "True",
- "False",
- "Float",
- "=",
- "[",
- "]",
- "{",
- "}",
- "(",
- ")",
- "]]",
- "[[",
- "Date",
- "KeyGroup",
- "KeyGroupArray",
- ",",
- ":",
- "$",
- "*",
- "?",
- ".",
- "..",
- "EOL",
-}
-
-type token struct {
- Position
- typ tokenType
- val string
-}
-
-func (tt tokenType) String() string {
- idx := int(tt)
- if idx < len(tokenTypeNames) {
- return tokenTypeNames[idx]
- }
- return "Unknown"
-}
-
-func (t token) Int() int {
- if result, err := strconv.Atoi(t.val); err != nil {
- panic(err)
- } else {
- return result
- }
-}
-
-func (t token) String() string {
- switch t.typ {
- case tokenEOF:
- return "EOF"
- case tokenError:
- return t.val
- }
-
- return fmt.Sprintf("%q", t.val)
-}
-
-func isSpace(r rune) bool {
- return r == ' ' || r == '\t'
-}
-
-func isAlphanumeric(r rune) bool {
- return unicode.IsLetter(r) || r == '_'
-}
-
-func isKeyChar(r rune) bool {
- // Keys start with the first character that isn't whitespace or [ and end
- // with the last non-whitespace character before the equals sign. Keys
- // cannot contain a # character."
- return !(r == '\r' || r == '\n' || r == eof || r == '=')
-}
-
-func isKeyStartChar(r rune) bool {
- return !(isSpace(r) || r == '\r' || r == '\n' || r == eof || r == '[')
-}
-
-func isDigit(r rune) bool {
- return unicode.IsNumber(r)
-}
-
-func isHexDigit(r rune) bool {
- return isDigit(r) ||
- (r >= 'a' && r <= 'f') ||
- (r >= 'A' && r <= 'F')
-}
diff --git a/vendor/github.com/pelletier/go-toml/token_test.go b/vendor/github.com/pelletier/go-toml/token_test.go
deleted file mode 100644
index 20b560d..0000000
--- a/vendor/github.com/pelletier/go-toml/token_test.go
+++ /dev/null
@@ -1,67 +0,0 @@
-package toml
-
-import "testing"
-
-func TestTokenStringer(t *testing.T) {
- var tests = []struct {
- tt tokenType
- expect string
- }{
- {tokenError, "Error"},
- {tokenEOF, "EOF"},
- {tokenComment, "Comment"},
- {tokenKey, "Key"},
- {tokenString, "String"},
- {tokenInteger, "Integer"},
- {tokenTrue, "True"},
- {tokenFalse, "False"},
- {tokenFloat, "Float"},
- {tokenEqual, "="},
- {tokenLeftBracket, "["},
- {tokenRightBracket, "]"},
- {tokenLeftCurlyBrace, "{"},
- {tokenRightCurlyBrace, "}"},
- {tokenLeftParen, "("},
- {tokenRightParen, ")"},
- {tokenDoubleLeftBracket, "]]"},
- {tokenDoubleRightBracket, "[["},
- {tokenDate, "Date"},
- {tokenKeyGroup, "KeyGroup"},
- {tokenKeyGroupArray, "KeyGroupArray"},
- {tokenComma, ","},
- {tokenColon, ":"},
- {tokenDollar, "$"},
- {tokenStar, "*"},
- {tokenQuestion, "?"},
- {tokenDot, "."},
- {tokenDotDot, ".."},
- {tokenEOL, "EOL"},
- {tokenEOL + 1, "Unknown"},
- }
-
- for i, test := range tests {
- got := test.tt.String()
- if got != test.expect {
- t.Errorf("[%d] invalid string of token type; got %q, expected %q", i, got, test.expect)
- }
- }
-}
-
-func TestTokenString(t *testing.T) {
- var tests = []struct {
- tok token
- expect string
- }{
- {token{Position{1, 1}, tokenEOF, ""}, "EOF"},
- {token{Position{1, 1}, tokenError, "Δt"}, "Δt"},
- {token{Position{1, 1}, tokenString, "bar"}, `"bar"`},
- {token{Position{1, 1}, tokenString, "123456789012345"}, `"123456789012345"`},
- }
-
- for i, test := range tests {
- got := test.tok.String()
- if got != test.expect {
- t.Errorf("[%d] invalid of string token; got %q, expected %q", i, got, test.expect)
- }
- }
-}
diff --git a/vendor/github.com/pelletier/go-toml/toml.go b/vendor/github.com/pelletier/go-toml/toml.go
deleted file mode 100644
index 64f19ed..0000000
--- a/vendor/github.com/pelletier/go-toml/toml.go
+++ /dev/null
@@ -1,292 +0,0 @@
-package toml
-
-import (
- "errors"
- "fmt"
- "io"
- "io/ioutil"
- "os"
- "runtime"
- "strings"
-)
-
-type tomlValue struct {
- value interface{} // string, int64, uint64, float64, bool, time.Time, [] of any of this list
- position Position
-}
-
-// Tree is the result of the parsing of a TOML file.
-type Tree struct {
- values map[string]interface{} // string -> *tomlValue, *Tree, []*Tree
- position Position
-}
-
-func newTree() *Tree {
- return &Tree{
- values: make(map[string]interface{}),
- position: Position{},
- }
-}
-
-// TreeFromMap initializes a new Tree object using the given map.
-func TreeFromMap(m map[string]interface{}) (*Tree, error) {
- result, err := toTree(m)
- if err != nil {
- return nil, err
- }
- return result.(*Tree), nil
-}
-
-// Position returns the position of the tree.
-func (t *Tree) Position() Position {
- return t.position
-}
-
-// Has returns a boolean indicating if the given key exists.
-func (t *Tree) Has(key string) bool {
- if key == "" {
- return false
- }
- return t.HasPath(strings.Split(key, "."))
-}
-
-// HasPath returns true if the given path of keys exists, false otherwise.
-func (t *Tree) HasPath(keys []string) bool {
- return t.GetPath(keys) != nil
-}
-
-// Keys returns the keys of the toplevel tree (does not recurse).
-func (t *Tree) Keys() []string {
- keys := make([]string, len(t.values))
- i := 0
- for k := range t.values {
- keys[i] = k
- i++
- }
- return keys
-}
-
-// Get the value at key in the Tree.
-// Key is a dot-separated path (e.g. a.b.c).
-// Returns nil if the path does not exist in the tree.
-// If keys is of length zero, the current tree is returned.
-func (t *Tree) Get(key string) interface{} {
- if key == "" {
- return t
- }
- comps, err := parseKey(key)
- if err != nil {
- return nil
- }
- return t.GetPath(comps)
-}
-
-// GetPath returns the element in the tree indicated by 'keys'.
-// If keys is of length zero, the current tree is returned.
-func (t *Tree) GetPath(keys []string) interface{} {
- if len(keys) == 0 {
- return t
- }
- subtree := t
- for _, intermediateKey := range keys[:len(keys)-1] {
- value, exists := subtree.values[intermediateKey]
- if !exists {
- return nil
- }
- switch node := value.(type) {
- case *Tree:
- subtree = node
- case []*Tree:
- // go to most recent element
- if len(node) == 0 {
- return nil
- }
- subtree = node[len(node)-1]
- default:
- return nil // cannot navigate through other node types
- }
- }
- // branch based on final node type
- switch node := subtree.values[keys[len(keys)-1]].(type) {
- case *tomlValue:
- return node.value
- default:
- return node
- }
-}
-
-// GetPosition returns the position of the given key.
-func (t *Tree) GetPosition(key string) Position {
- if key == "" {
- return t.position
- }
- return t.GetPositionPath(strings.Split(key, "."))
-}
-
-// GetPositionPath returns the element in the tree indicated by 'keys'.
-// If keys is of length zero, the current tree is returned.
-func (t *Tree) GetPositionPath(keys []string) Position {
- if len(keys) == 0 {
- return t.position
- }
- subtree := t
- for _, intermediateKey := range keys[:len(keys)-1] {
- value, exists := subtree.values[intermediateKey]
- if !exists {
- return Position{0, 0}
- }
- switch node := value.(type) {
- case *Tree:
- subtree = node
- case []*Tree:
- // go to most recent element
- if len(node) == 0 {
- return Position{0, 0}
- }
- subtree = node[len(node)-1]
- default:
- return Position{0, 0}
- }
- }
- // branch based on final node type
- switch node := subtree.values[keys[len(keys)-1]].(type) {
- case *tomlValue:
- return node.position
- case *Tree:
- return node.position
- case []*Tree:
- // go to most recent element
- if len(node) == 0 {
- return Position{0, 0}
- }
- return node[len(node)-1].position
- default:
- return Position{0, 0}
- }
-}
-
-// GetDefault works like Get but with a default value
-func (t *Tree) GetDefault(key string, def interface{}) interface{} {
- val := t.Get(key)
- if val == nil {
- return def
- }
- return val
-}
-
-// Set an element in the tree.
-// Key is a dot-separated path (e.g. a.b.c).
-// Creates all necessary intermediate trees, if needed.
-func (t *Tree) Set(key string, value interface{}) {
- t.SetPath(strings.Split(key, "."), value)
-}
-
-// SetPath sets an element in the tree.
-// Keys is an array of path elements (e.g. {"a","b","c"}).
-// Creates all necessary intermediate trees, if needed.
-func (t *Tree) SetPath(keys []string, value interface{}) {
- subtree := t
- for _, intermediateKey := range keys[:len(keys)-1] {
- nextTree, exists := subtree.values[intermediateKey]
- if !exists {
- nextTree = newTree()
- subtree.values[intermediateKey] = nextTree // add new element here
- }
- switch node := nextTree.(type) {
- case *Tree:
- subtree = node
- case []*Tree:
- // go to most recent element
- if len(node) == 0 {
- // create element if it does not exist
- subtree.values[intermediateKey] = append(node, newTree())
- }
- subtree = node[len(node)-1]
- }
- }
-
- var toInsert interface{}
-
- switch value.(type) {
- case *Tree:
- toInsert = value
- case []*Tree:
- toInsert = value
- case *tomlValue:
- toInsert = value
- default:
- toInsert = &tomlValue{value: value}
- }
-
- subtree.values[keys[len(keys)-1]] = toInsert
-}
-
-// createSubTree takes a tree and a key and create the necessary intermediate
-// subtrees to create a subtree at that point. In-place.
-//
-// e.g. passing a.b.c will create (assuming tree is empty) tree[a], tree[a][b]
-// and tree[a][b][c]
-//
-// Returns nil on success, error object on failure
-func (t *Tree) createSubTree(keys []string, pos Position) error {
- subtree := t
- for _, intermediateKey := range keys {
- nextTree, exists := subtree.values[intermediateKey]
- if !exists {
- tree := newTree()
- tree.position = pos
- subtree.values[intermediateKey] = tree
- nextTree = tree
- }
-
- switch node := nextTree.(type) {
- case []*Tree:
- subtree = node[len(node)-1]
- case *Tree:
- subtree = node
- default:
- return fmt.Errorf("unknown type for path %s (%s): %T (%#v)",
- strings.Join(keys, "."), intermediateKey, nextTree, nextTree)
- }
- }
- return nil
-}
-
-// LoadBytes creates a Tree from a []byte.
-func LoadBytes(b []byte) (tree *Tree, err error) {
- defer func() {
- if r := recover(); r != nil {
- if _, ok := r.(runtime.Error); ok {
- panic(r)
- }
- err = errors.New(r.(string))
- }
- }()
- tree = parseToml(lexToml(b))
- return
-}
-
-// LoadReader creates a Tree from any io.Reader.
-func LoadReader(reader io.Reader) (tree *Tree, err error) {
- inputBytes, err := ioutil.ReadAll(reader)
- if err != nil {
- return
- }
- tree, err = LoadBytes(inputBytes)
- return
-}
-
-// Load creates a Tree from a string.
-func Load(content string) (tree *Tree, err error) {
- return LoadBytes([]byte(content))
-}
-
-// LoadFile creates a Tree from a file.
-func LoadFile(path string) (tree *Tree, err error) {
- file, err := os.Open(path)
- if err != nil {
- return nil, err
- }
- defer file.Close()
- return LoadReader(file)
-}
diff --git a/vendor/github.com/pelletier/go-toml/toml_test.go b/vendor/github.com/pelletier/go-toml/toml_test.go
deleted file mode 100644
index ab9c242..0000000
--- a/vendor/github.com/pelletier/go-toml/toml_test.go
+++ /dev/null
@@ -1,106 +0,0 @@
-// Testing support for go-toml
-
-package toml
-
-import (
- "testing"
-)
-
-func TestTomlHas(t *testing.T) {
- tree, _ := Load(`
- [test]
- key = "value"
- `)
-
- if !tree.Has("test.key") {
- t.Errorf("Has - expected test.key to exists")
- }
-
- if tree.Has("") {
- t.Errorf("Should return false if the key is not provided")
- }
-}
-
-func TestTomlGet(t *testing.T) {
- tree, _ := Load(`
- [test]
- key = "value"
- `)
-
- if tree.Get("") != tree {
- t.Errorf("Get should return the tree itself when given an empty path")
- }
-
- if tree.Get("test.key") != "value" {
- t.Errorf("Get should return the value")
- }
- if tree.Get(`\`) != nil {
- t.Errorf("should return nil when the key is malformed")
- }
-}
-
-func TestTomlGetDefault(t *testing.T) {
- tree, _ := Load(`
- [test]
- key = "value"
- `)
-
- if tree.GetDefault("", "hello") != tree {
- t.Error("GetDefault should return the tree itself when given an empty path")
- }
-
- if tree.GetDefault("test.key", "hello") != "value" {
- t.Error("Get should return the value")
- }
-
- if tree.GetDefault("whatever", "hello") != "hello" {
- t.Error("GetDefault should return the default value if the key does not exist")
- }
-}
-
-func TestTomlHasPath(t *testing.T) {
- tree, _ := Load(`
- [test]
- key = "value"
- `)
-
- if !tree.HasPath([]string{"test", "key"}) {
- t.Errorf("HasPath - expected test.key to exists")
- }
-}
-
-func TestTomlGetPath(t *testing.T) {
- node := newTree()
- //TODO: set other node data
-
- for idx, item := range []struct {
- Path []string
- Expected *Tree
- }{
- { // empty path test
- []string{},
- node,
- },
- } {
- result := node.GetPath(item.Path)
- if result != item.Expected {
- t.Errorf("GetPath[%d] %v - expected %v, got %v instead.", idx, item.Path, item.Expected, result)
- }
- }
-
- tree, _ := Load("[foo.bar]\na=1\nb=2\n[baz.foo]\na=3\nb=4\n[gorf.foo]\na=5\nb=6")
- if tree.GetPath([]string{"whatever"}) != nil {
- t.Error("GetPath should return nil when the key does not exist")
- }
-}
-
-func TestTomlFromMap(t *testing.T) {
- simpleMap := map[string]interface{}{"hello": 42}
- tree, err := TreeFromMap(simpleMap)
- if err != nil {
- t.Fatal("unexpected error:", err)
- }
- if tree.Get("hello") != int64(42) {
- t.Fatal("hello should be 42, not", tree.Get("hello"))
- }
-}
diff --git a/vendor/github.com/pelletier/go-toml/tomltree_create.go b/vendor/github.com/pelletier/go-toml/tomltree_create.go
deleted file mode 100644
index 19d1c0d..0000000
--- a/vendor/github.com/pelletier/go-toml/tomltree_create.go
+++ /dev/null
@@ -1,142 +0,0 @@
-package toml
-
-import (
- "fmt"
- "reflect"
- "time"
-)
-
-var kindToType = [reflect.String + 1]reflect.Type{
- reflect.Bool: reflect.TypeOf(true),
- reflect.String: reflect.TypeOf(""),
- reflect.Float32: reflect.TypeOf(float64(1)),
- reflect.Float64: reflect.TypeOf(float64(1)),
- reflect.Int: reflect.TypeOf(int64(1)),
- reflect.Int8: reflect.TypeOf(int64(1)),
- reflect.Int16: reflect.TypeOf(int64(1)),
- reflect.Int32: reflect.TypeOf(int64(1)),
- reflect.Int64: reflect.TypeOf(int64(1)),
- reflect.Uint: reflect.TypeOf(uint64(1)),
- reflect.Uint8: reflect.TypeOf(uint64(1)),
- reflect.Uint16: reflect.TypeOf(uint64(1)),
- reflect.Uint32: reflect.TypeOf(uint64(1)),
- reflect.Uint64: reflect.TypeOf(uint64(1)),
-}
-
-// typeFor returns a reflect.Type for a reflect.Kind, or nil if none is found.
-// supported values:
-// string, bool, int64, uint64, float64, time.Time, int, int8, int16, int32, uint, uint8, uint16, uint32, float32
-func typeFor(k reflect.Kind) reflect.Type {
- if k > 0 && int(k) < len(kindToType) {
- return kindToType[k]
- }
- return nil
-}
-
-func simpleValueCoercion(object interface{}) (interface{}, error) {
- switch original := object.(type) {
- case string, bool, int64, uint64, float64, time.Time:
- return original, nil
- case int:
- return int64(original), nil
- case int8:
- return int64(original), nil
- case int16:
- return int64(original), nil
- case int32:
- return int64(original), nil
- case uint:
- return uint64(original), nil
- case uint8:
- return uint64(original), nil
- case uint16:
- return uint64(original), nil
- case uint32:
- return uint64(original), nil
- case float32:
- return float64(original), nil
- case fmt.Stringer:
- return original.String(), nil
- default:
- return nil, fmt.Errorf("cannot convert type %T to Tree", object)
- }
-}
-
-func sliceToTree(object interface{}) (interface{}, error) {
- // arrays are a bit tricky, since they can represent either a
- // collection of simple values, which is represented by one
- // *tomlValue, or an array of tables, which is represented by an
- // array of *Tree.
-
- // holding the assumption that this function is called from toTree only when value.Kind() is Array or Slice
- value := reflect.ValueOf(object)
- insideType := value.Type().Elem()
- length := value.Len()
- if length > 0 {
- insideType = reflect.ValueOf(value.Index(0).Interface()).Type()
- }
- if insideType.Kind() == reflect.Map {
- // this is considered as an array of tables
- tablesArray := make([]*Tree, 0, length)
- for i := 0; i < length; i++ {
- table := value.Index(i)
- tree, err := toTree(table.Interface())
- if err != nil {
- return nil, err
- }
- tablesArray = append(tablesArray, tree.(*Tree))
- }
- return tablesArray, nil
- }
-
- sliceType := typeFor(insideType.Kind())
- if sliceType == nil {
- sliceType = insideType
- }
-
- arrayValue := reflect.MakeSlice(reflect.SliceOf(sliceType), 0, length)
-
- for i := 0; i < length; i++ {
- val := value.Index(i).Interface()
- simpleValue, err := simpleValueCoercion(val)
- if err != nil {
- return nil, err
- }
- arrayValue = reflect.Append(arrayValue, reflect.ValueOf(simpleValue))
- }
- return &tomlValue{arrayValue.Interface(), Position{}}, nil
-}
-
-func toTree(object interface{}) (interface{}, error) {
- value := reflect.ValueOf(object)
-
- if value.Kind() == reflect.Map {
- values := map[string]interface{}{}
- keys := value.MapKeys()
- for _, key := range keys {
- if key.Kind() != reflect.String {
- if _, ok := key.Interface().(string); !ok {
- return nil, fmt.Errorf("map key needs to be a string, not %T (%v)", key.Interface(), key.Kind())
- }
- }
-
- v := value.MapIndex(key)
- newValue, err := toTree(v.Interface())
- if err != nil {
- return nil, err
- }
- values[key.String()] = newValue
- }
- return &Tree{values, Position{}}, nil
- }
-
- if value.Kind() == reflect.Array || value.Kind() == reflect.Slice {
- return sliceToTree(object)
- }
-
- simpleValue, err := simpleValueCoercion(object)
- if err != nil {
- return nil, err
- }
- return &tomlValue{simpleValue, Position{}}, nil
-}
diff --git a/vendor/github.com/pelletier/go-toml/tomltree_create_test.go b/vendor/github.com/pelletier/go-toml/tomltree_create_test.go
deleted file mode 100644
index 1ca108a..0000000
--- a/vendor/github.com/pelletier/go-toml/tomltree_create_test.go
+++ /dev/null
@@ -1,126 +0,0 @@
-package toml
-
-import (
- "strconv"
- "testing"
- "time"
-)
-
-type customString string
-
-type stringer struct{}
-
-func (s stringer) String() string {
- return "stringer"
-}
-
-func validate(t *testing.T, path string, object interface{}) {
- switch o := object.(type) {
- case *Tree:
- for key, tree := range o.values {
- validate(t, path+"."+key, tree)
- }
- case []*Tree:
- for index, tree := range o {
- validate(t, path+"."+strconv.Itoa(index), tree)
- }
- case *tomlValue:
- switch o.value.(type) {
- case int64, uint64, bool, string, float64, time.Time,
- []int64, []uint64, []bool, []string, []float64, []time.Time:
- default:
- t.Fatalf("tomlValue at key %s containing incorrect type %T", path, o.value)
- }
- default:
- t.Fatalf("value at key %s is of incorrect type %T", path, object)
- }
- t.Logf("validation ok %s as %T", path, object)
-}
-
-func validateTree(t *testing.T, tree *Tree) {
- validate(t, "", tree)
-}
-
-func TestTreeCreateToTree(t *testing.T) {
- data := map[string]interface{}{
- "a_string": "bar",
- "an_int": 42,
- "time": time.Now(),
- "int8": int8(2),
- "int16": int16(2),
- "int32": int32(2),
- "uint8": uint8(2),
- "uint16": uint16(2),
- "uint32": uint32(2),
- "float32": float32(2),
- "a_bool": false,
- "stringer": stringer{},
- "nested": map[string]interface{}{
- "foo": "bar",
- },
- "array": []string{"a", "b", "c"},
- "array_uint": []uint{uint(1), uint(2)},
- "array_table": []map[string]interface{}{map[string]interface{}{"sub_map": 52}},
- "array_times": []time.Time{time.Now(), time.Now()},
- "map_times": map[string]time.Time{"now": time.Now()},
- "custom_string_map_key": map[customString]interface{}{customString("custom"): "custom"},
- }
- tree, err := TreeFromMap(data)
- if err != nil {
- t.Fatal("unexpected error:", err)
- }
- validateTree(t, tree)
-}
-
-func TestTreeCreateToTreeInvalidLeafType(t *testing.T) {
- _, err := TreeFromMap(map[string]interface{}{"foo": t})
- expected := "cannot convert type *testing.T to Tree"
- if err.Error() != expected {
- t.Fatalf("expected error %s, got %s", expected, err.Error())
- }
-}
-
-func TestTreeCreateToTreeInvalidMapKeyType(t *testing.T) {
- _, err := TreeFromMap(map[string]interface{}{"foo": map[int]interface{}{2: 1}})
- expected := "map key needs to be a string, not int (int)"
- if err.Error() != expected {
- t.Fatalf("expected error %s, got %s", expected, err.Error())
- }
-}
-
-func TestTreeCreateToTreeInvalidArrayMemberType(t *testing.T) {
- _, err := TreeFromMap(map[string]interface{}{"foo": []*testing.T{t}})
- expected := "cannot convert type *testing.T to Tree"
- if err.Error() != expected {
- t.Fatalf("expected error %s, got %s", expected, err.Error())
- }
-}
-
-func TestTreeCreateToTreeInvalidTableGroupType(t *testing.T) {
- _, err := TreeFromMap(map[string]interface{}{"foo": []map[string]interface{}{map[string]interface{}{"hello": t}}})
- expected := "cannot convert type *testing.T to Tree"
- if err.Error() != expected {
- t.Fatalf("expected error %s, got %s", expected, err.Error())
- }
-}
-
-func TestRoundTripArrayOfTables(t *testing.T) {
- orig := "\n[[stuff]]\n name = \"foo\"\n things = [\"a\",\"b\"]\n"
- tree, err := Load(orig)
- if err != nil {
- t.Fatalf("unexpected error: %s", err)
- }
-
- m := tree.ToMap()
-
- tree, err = TreeFromMap(m)
- if err != nil {
- t.Fatalf("unexpected error: %s", err)
- }
- want := orig
- got := tree.String()
-
- if got != want {
- t.Errorf("want:\n%s\ngot:\n%s", want, got)
- }
-}
diff --git a/vendor/github.com/pelletier/go-toml/tomltree_write.go b/vendor/github.com/pelletier/go-toml/tomltree_write.go
deleted file mode 100644
index ca763ed..0000000
--- a/vendor/github.com/pelletier/go-toml/tomltree_write.go
+++ /dev/null
@@ -1,233 +0,0 @@
-package toml
-
-import (
- "bytes"
- "fmt"
- "io"
- "math"
- "reflect"
- "sort"
- "strconv"
- "strings"
- "time"
-)
-
-// encodes a string to a TOML-compliant string value
-func encodeTomlString(value string) string {
- var b bytes.Buffer
-
- for _, rr := range value {
- switch rr {
- case '\b':
- b.WriteString(`\b`)
- case '\t':
- b.WriteString(`\t`)
- case '\n':
- b.WriteString(`\n`)
- case '\f':
- b.WriteString(`\f`)
- case '\r':
- b.WriteString(`\r`)
- case '"':
- b.WriteString(`\"`)
- case '\\':
- b.WriteString(`\\`)
- default:
- intRr := uint16(rr)
- if intRr < 0x001F {
- b.WriteString(fmt.Sprintf("\\u%0.4X", intRr))
- } else {
- b.WriteRune(rr)
- }
- }
- }
- return b.String()
-}
-
-func tomlValueStringRepresentation(v interface{}) (string, error) {
- switch value := v.(type) {
- case uint64:
- return strconv.FormatUint(value, 10), nil
- case int64:
- return strconv.FormatInt(value, 10), nil
- case float64:
- // Ensure a round float does contain a decimal point. Otherwise feeding
- // the output back to the parser would convert to an integer.
- if math.Trunc(value) == value {
- return strconv.FormatFloat(value, 'f', 1, 32), nil
- }
- return strconv.FormatFloat(value, 'f', -1, 32), nil
- case string:
- return "\"" + encodeTomlString(value) + "\"", nil
- case []byte:
- b, _ := v.([]byte)
- return tomlValueStringRepresentation(string(b))
- case bool:
- if value {
- return "true", nil
- }
- return "false", nil
- case time.Time:
- return value.Format(time.RFC3339), nil
- case nil:
- return "", nil
- }
-
- rv := reflect.ValueOf(v)
-
- if rv.Kind() == reflect.Slice {
- values := []string{}
- for i := 0; i < rv.Len(); i++ {
- item := rv.Index(i).Interface()
- itemRepr, err := tomlValueStringRepresentation(item)
- if err != nil {
- return "", err
- }
- values = append(values, itemRepr)
- }
- return "[" + strings.Join(values, ",") + "]", nil
- }
- return "", fmt.Errorf("unsupported value type %T: %v", v, v)
-}
-
-func (t *Tree) writeTo(w io.Writer, indent, keyspace string, bytesCount int64) (int64, error) {
- simpleValuesKeys := make([]string, 0)
- complexValuesKeys := make([]string, 0)
-
- for k := range t.values {
- v := t.values[k]
- switch v.(type) {
- case *Tree, []*Tree:
- complexValuesKeys = append(complexValuesKeys, k)
- default:
- simpleValuesKeys = append(simpleValuesKeys, k)
- }
- }
-
- sort.Strings(simpleValuesKeys)
- sort.Strings(complexValuesKeys)
-
- for _, k := range simpleValuesKeys {
- v, ok := t.values[k].(*tomlValue)
- if !ok {
- return bytesCount, fmt.Errorf("invalid value type at %s: %T", k, t.values[k])
- }
-
- repr, err := tomlValueStringRepresentation(v.value)
- if err != nil {
- return bytesCount, err
- }
-
- writtenBytesCount, err := writeStrings(w, indent, k, " = ", repr, "\n")
- bytesCount += int64(writtenBytesCount)
- if err != nil {
- return bytesCount, err
- }
- }
-
- for _, k := range complexValuesKeys {
- v := t.values[k]
-
- combinedKey := k
- if keyspace != "" {
- combinedKey = keyspace + "." + combinedKey
- }
-
- switch node := v.(type) {
- // node has to be of those two types given how keys are sorted above
- case *Tree:
- writtenBytesCount, err := writeStrings(w, "\n", indent, "[", combinedKey, "]\n")
- bytesCount += int64(writtenBytesCount)
- if err != nil {
- return bytesCount, err
- }
- bytesCount, err = node.writeTo(w, indent+" ", combinedKey, bytesCount)
- if err != nil {
- return bytesCount, err
- }
- case []*Tree:
- for _, subTree := range node {
- writtenBytesCount, err := writeStrings(w, "\n", indent, "[[", combinedKey, "]]\n")
- bytesCount += int64(writtenBytesCount)
- if err != nil {
- return bytesCount, err
- }
-
- bytesCount, err = subTree.writeTo(w, indent+" ", combinedKey, bytesCount)
- if err != nil {
- return bytesCount, err
- }
- }
- }
- }
-
- return bytesCount, nil
-}
-
-func writeStrings(w io.Writer, s ...string) (int, error) {
- var n int
- for i := range s {
- b, err := io.WriteString(w, s[i])
- n += b
- if err != nil {
- return n, err
- }
- }
- return n, nil
-}
-
-// WriteTo encode the Tree as Toml and writes it to the writer w.
-// Returns the number of bytes written in case of success, or an error if anything happened.
-func (t *Tree) WriteTo(w io.Writer) (int64, error) {
- return t.writeTo(w, "", "", 0)
-}
-
-// ToTomlString generates a human-readable representation of the current tree.
-// Output spans multiple lines, and is suitable for ingest by a TOML parser.
-// If the conversion cannot be performed, ToString returns a non-nil error.
-func (t *Tree) ToTomlString() (string, error) {
- var buf bytes.Buffer
- _, err := t.WriteTo(&buf)
- if err != nil {
- return "", err
- }
- return buf.String(), nil
-}
-
-// String generates a human-readable representation of the current tree.
-// Alias of ToString. Present to implement the fmt.Stringer interface.
-func (t *Tree) String() string {
- result, _ := t.ToTomlString()
- return result
-}
-
-// ToMap recursively generates a representation of the tree using Go built-in structures.
-// The following types are used:
-//
-// * bool
-// * float64
-// * int64
-// * string
-// * uint64
-// * time.Time
-// * map[string]interface{} (where interface{} is any of this list)
-// * []interface{} (where interface{} is any of this list)
-func (t *Tree) ToMap() map[string]interface{} {
- result := map[string]interface{}{}
-
- for k, v := range t.values {
- switch node := v.(type) {
- case []*Tree:
- var array []interface{}
- for _, item := range node {
- array = append(array, item.ToMap())
- }
- result[k] = array
- case *Tree:
- result[k] = node.ToMap()
- case *tomlValue:
- result[k] = node.value
- }
- }
- return result
-}
diff --git a/vendor/github.com/pelletier/go-toml/tomltree_write_test.go b/vendor/github.com/pelletier/go-toml/tomltree_write_test.go
deleted file mode 100644
index c2a1ce3..0000000
--- a/vendor/github.com/pelletier/go-toml/tomltree_write_test.go
+++ /dev/null
@@ -1,358 +0,0 @@
-package toml
-
-import (
- "bytes"
- "errors"
- "fmt"
- "reflect"
- "strings"
- "testing"
- "time"
-)
-
-type failingWriter struct {
- failAt int
- written int
- buffer bytes.Buffer
-}
-
-func (f *failingWriter) Write(p []byte) (n int, err error) {
- count := len(p)
- toWrite := f.failAt - (count + f.written)
- if toWrite < 0 {
- toWrite = 0
- }
- if toWrite > count {
- f.written += count
- f.buffer.Write(p)
- return count, nil
- }
-
- f.buffer.Write(p[:toWrite])
- f.written = f.failAt
- return toWrite, fmt.Errorf("failingWriter failed after writting %d bytes", f.written)
-}
-
-func assertErrorString(t *testing.T, expected string, err error) {
- expectedErr := errors.New(expected)
- if err == nil || err.Error() != expectedErr.Error() {
- t.Errorf("expecting error %s, but got %s instead", expected, err)
- }
-}
-
-func TestTreeWriteToEmptyTable(t *testing.T) {
- doc := `[[empty-tables]]
-[[empty-tables]]`
-
- toml, err := Load(doc)
- if err != nil {
- t.Fatal("Unexpected Load error:", err)
- }
- tomlString, err := toml.ToTomlString()
- if err != nil {
- t.Fatal("Unexpected ToTomlString error:", err)
- }
-
- expected := `
-[[empty-tables]]
-
-[[empty-tables]]
-`
-
- if tomlString != expected {
- t.Fatalf("Expected:\n%s\nGot:\n%s", expected, tomlString)
- }
-}
-
-func TestTreeWriteToTomlString(t *testing.T) {
- toml, err := Load(`name = { first = "Tom", last = "Preston-Werner" }
-points = { x = 1, y = 2 }`)
-
- if err != nil {
- t.Fatal("Unexpected error:", err)
- }
-
- tomlString, _ := toml.ToTomlString()
- reparsedTree, err := Load(tomlString)
-
- assertTree(t, reparsedTree, err, map[string]interface{}{
- "name": map[string]interface{}{
- "first": "Tom",
- "last": "Preston-Werner",
- },
- "points": map[string]interface{}{
- "x": int64(1),
- "y": int64(2),
- },
- })
-}
-
-func TestTreeWriteToTomlStringSimple(t *testing.T) {
- tree, err := Load("[foo]\n\n[[foo.bar]]\na = 42\n\n[[foo.bar]]\na = 69\n")
- if err != nil {
- t.Errorf("Test failed to parse: %v", err)
- return
- }
- result, err := tree.ToTomlString()
- if err != nil {
- t.Errorf("Unexpected error: %s", err)
- }
- expected := "\n[foo]\n\n [[foo.bar]]\n a = 42\n\n [[foo.bar]]\n a = 69\n"
- if result != expected {
- t.Errorf("Expected got '%s', expected '%s'", result, expected)
- }
-}
-
-func TestTreeWriteToTomlStringKeysOrders(t *testing.T) {
- for i := 0; i < 100; i++ {
- tree, _ := Load(`
- foobar = true
- bar = "baz"
- foo = 1
- [qux]
- foo = 1
- bar = "baz2"`)
-
- stringRepr, _ := tree.ToTomlString()
-
- t.Log("Intermediate string representation:")
- t.Log(stringRepr)
-
- r := strings.NewReader(stringRepr)
- toml, err := LoadReader(r)
-
- if err != nil {
- t.Fatal("Unexpected error:", err)
- }
-
- assertTree(t, toml, err, map[string]interface{}{
- "foobar": true,
- "bar": "baz",
- "foo": 1,
- "qux": map[string]interface{}{
- "foo": 1,
- "bar": "baz2",
- },
- })
- }
-}
-
-func testMaps(t *testing.T, actual, expected map[string]interface{}) {
- if !reflect.DeepEqual(actual, expected) {
- t.Fatal("trees aren't equal.\n", "Expected:\n", expected, "\nActual:\n", actual)
- }
-}
-
-func TestTreeWriteToMapSimple(t *testing.T) {
- tree, _ := Load("a = 42\nb = 17")
-
- expected := map[string]interface{}{
- "a": int64(42),
- "b": int64(17),
- }
-
- testMaps(t, tree.ToMap(), expected)
-}
-
-func TestTreeWriteToInvalidTreeSimpleValue(t *testing.T) {
- tree := Tree{values: map[string]interface{}{"foo": int8(1)}}
- _, err := tree.ToTomlString()
- assertErrorString(t, "invalid value type at foo: int8", err)
-}
-
-func TestTreeWriteToInvalidTreeTomlValue(t *testing.T) {
- tree := Tree{values: map[string]interface{}{"foo": &tomlValue{int8(1), Position{}}}}
- _, err := tree.ToTomlString()
- assertErrorString(t, "unsupported value type int8: 1", err)
-}
-
-func TestTreeWriteToInvalidTreeTomlValueArray(t *testing.T) {
- tree := Tree{values: map[string]interface{}{"foo": &tomlValue{[]interface{}{int8(1)}, Position{}}}}
- _, err := tree.ToTomlString()
- assertErrorString(t, "unsupported value type int8: 1", err)
-}
-
-func TestTreeWriteToFailingWriterInSimpleValue(t *testing.T) {
- toml, _ := Load(`a = 2`)
- writer := failingWriter{failAt: 0, written: 0}
- _, err := toml.WriteTo(&writer)
- assertErrorString(t, "failingWriter failed after writting 0 bytes", err)
-}
-
-func TestTreeWriteToFailingWriterInTable(t *testing.T) {
- toml, _ := Load(`
-[b]
-a = 2`)
- writer := failingWriter{failAt: 2, written: 0}
- _, err := toml.WriteTo(&writer)
- assertErrorString(t, "failingWriter failed after writting 2 bytes", err)
-
- writer = failingWriter{failAt: 13, written: 0}
- _, err = toml.WriteTo(&writer)
- assertErrorString(t, "failingWriter failed after writting 13 bytes", err)
-}
-
-func TestTreeWriteToFailingWriterInArray(t *testing.T) {
- toml, _ := Load(`
-[[b]]
-a = 2`)
- writer := failingWriter{failAt: 2, written: 0}
- _, err := toml.WriteTo(&writer)
- assertErrorString(t, "failingWriter failed after writting 2 bytes", err)
-
- writer = failingWriter{failAt: 15, written: 0}
- _, err = toml.WriteTo(&writer)
- assertErrorString(t, "failingWriter failed after writting 15 bytes", err)
-}
-
-func TestTreeWriteToMapExampleFile(t *testing.T) {
- tree, _ := LoadFile("example.toml")
- expected := map[string]interface{}{
- "title": "TOML Example",
- "owner": map[string]interface{}{
- "name": "Tom Preston-Werner",
- "organization": "GitHub",
- "bio": "GitHub Cofounder & CEO\nLikes tater tots and beer.",
- "dob": time.Date(1979, time.May, 27, 7, 32, 0, 0, time.UTC),
- },
- "database": map[string]interface{}{
- "server": "192.168.1.1",
- "ports": []interface{}{int64(8001), int64(8001), int64(8002)},
- "connection_max": int64(5000),
- "enabled": true,
- },
- "servers": map[string]interface{}{
- "alpha": map[string]interface{}{
- "ip": "10.0.0.1",
- "dc": "eqdc10",
- },
- "beta": map[string]interface{}{
- "ip": "10.0.0.2",
- "dc": "eqdc10",
- },
- },
- "clients": map[string]interface{}{
- "data": []interface{}{
- []interface{}{"gamma", "delta"},
- []interface{}{int64(1), int64(2)},
- },
- },
- }
- testMaps(t, tree.ToMap(), expected)
-}
-
-func TestTreeWriteToMapWithTablesInMultipleChunks(t *testing.T) {
- tree, _ := Load(`
- [[menu.main]]
- a = "menu 1"
- b = "menu 2"
- [[menu.main]]
- c = "menu 3"
- d = "menu 4"`)
- expected := map[string]interface{}{
- "menu": map[string]interface{}{
- "main": []interface{}{
- map[string]interface{}{"a": "menu 1", "b": "menu 2"},
- map[string]interface{}{"c": "menu 3", "d": "menu 4"},
- },
- },
- }
- treeMap := tree.ToMap()
-
- testMaps(t, treeMap, expected)
-}
-
-func TestTreeWriteToMapWithArrayOfInlineTables(t *testing.T) {
- tree, _ := Load(`
- [params]
- language_tabs = [
- { key = "shell", name = "Shell" },
- { key = "ruby", name = "Ruby" },
- { key = "python", name = "Python" }
- ]`)
-
- expected := map[string]interface{}{
- "params": map[string]interface{}{
- "language_tabs": []interface{}{
- map[string]interface{}{
- "key": "shell",
- "name": "Shell",
- },
- map[string]interface{}{
- "key": "ruby",
- "name": "Ruby",
- },
- map[string]interface{}{
- "key": "python",
- "name": "Python",
- },
- },
- },
- }
-
- treeMap := tree.ToMap()
- testMaps(t, treeMap, expected)
-}
-
-func TestTreeWriteToFloat(t *testing.T) {
- tree, err := Load(`a = 3.0`)
- if err != nil {
- t.Fatal(err)
- }
- str, err := tree.ToTomlString()
- if err != nil {
- t.Fatal(err)
- }
- expected := `a = 3.0`
- if strings.TrimSpace(str) != strings.TrimSpace(expected) {
- t.Fatalf("Expected:\n%s\nGot:\n%s", expected, str)
- }
-}
-
-func BenchmarkTreeToTomlString(b *testing.B) {
- toml, err := Load(sampleHard)
- if err != nil {
- b.Fatal("Unexpected error:", err)
- }
-
- for i := 0; i < b.N; i++ {
- _, err := toml.ToTomlString()
- if err != nil {
- b.Fatal(err)
- }
- }
-}
-
-var sampleHard = `# Test file for TOML
-# Only this one tries to emulate a TOML file written by a user of the kind of parser writers probably hate
-# This part you'll really hate
-
-[the]
-test_string = "You'll hate me after this - #" # " Annoying, isn't it?
-
- [the.hard]
- test_array = [ "] ", " # "] # ] There you go, parse this!
- test_array2 = [ "Test #11 ]proved that", "Experiment #9 was a success" ]
- # You didn't think it'd as easy as chucking out the last #, did you?
- another_test_string = " Same thing, but with a string #"
- harder_test_string = " And when \"'s are in the string, along with # \"" # "and comments are there too"
- # Things will get harder
-
- [the.hard."bit#"]
- "what?" = "You don't think some user won't do that?"
- multi_line_array = [
- "]",
- # ] Oh yes I did
- ]
-
-# Each of the following keygroups/key value pairs should produce an error. Uncomment to them to test
-
-#[error] if you didn't catch this, your parser is broken
-#string = "Anything other than tabs, spaces and newline after a keygroup or key value pair has ended should produce an error unless it is a comment" like this
-#array = [
-# "This might most likely happen in multiline arrays",
-# Like here,
-# "or here,
-# and here"
-# ] End of array comment, forgot the #
-#number = 3.14 pi <--again forgot the # `
diff --git a/vendor/github.com/satori/go.uuid/.travis.yml b/vendor/github.com/satori/go.uuid/.travis.yml
deleted file mode 100644
index 38517e2..0000000
--- a/vendor/github.com/satori/go.uuid/.travis.yml
+++ /dev/null
@@ -1,15 +0,0 @@
-language: go
-sudo: false
-go:
- - 1.2
- - 1.3
- - 1.4
- - 1.5
- - 1.6
-before_install:
- - go get github.com/mattn/goveralls
- - go get golang.org/x/tools/cmd/cover
-script:
- - $HOME/gopath/bin/goveralls -service=travis-ci
-notifications:
- email: false
diff --git a/vendor/github.com/satori/go.uuid/LICENSE b/vendor/github.com/satori/go.uuid/LICENSE
deleted file mode 100644
index 488357b..0000000
--- a/vendor/github.com/satori/go.uuid/LICENSE
+++ /dev/null
@@ -1,20 +0,0 @@
-Copyright (C) 2013-2016 by Maxim Bublis
-
-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.
diff --git a/vendor/github.com/satori/go.uuid/README.md b/vendor/github.com/satori/go.uuid/README.md
deleted file mode 100644
index b6aad1c..0000000
--- a/vendor/github.com/satori/go.uuid/README.md
+++ /dev/null
@@ -1,65 +0,0 @@
-# UUID package for Go language
-
-[](https://travis-ci.org/satori/go.uuid)
-[](https://coveralls.io/github/satori/go.uuid)
-[](http://godoc.org/github.com/satori/go.uuid)
-
-This package provides pure Go implementation of Universally Unique Identifier (UUID). Supported both creation and parsing of UUIDs.
-
-With 100% test coverage and benchmarks out of box.
-
-Supported versions:
-* Version 1, based on timestamp and MAC address (RFC 4122)
-* Version 2, based on timestamp, MAC address and POSIX UID/GID (DCE 1.1)
-* Version 3, based on MD5 hashing (RFC 4122)
-* Version 4, based on random numbers (RFC 4122)
-* Version 5, based on SHA-1 hashing (RFC 4122)
-
-## Installation
-
-Use the `go` command:
-
- $ go get github.com/satori/go.uuid
-
-## Requirements
-
-UUID package requires Go >= 1.2.
-
-## Example
-
-```go
-package main
-
-import (
- "fmt"
- "github.com/satori/go.uuid"
-)
-
-func main() {
- // Creating UUID Version 4
- u1 := uuid.NewV4()
- fmt.Printf("UUIDv4: %s\n", u1)
-
- // Parsing UUID from string input
- u2, err := uuid.FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
- if err != nil {
- fmt.Printf("Something gone wrong: %s", err)
- }
- fmt.Printf("Successfully parsed: %s", u2)
-}
-```
-
-## Documentation
-
-[Documentation](http://godoc.org/github.com/satori/go.uuid) is hosted at GoDoc project.
-
-## Links
-* [RFC 4122](http://tools.ietf.org/html/rfc4122)
-* [DCE 1.1: Authentication and Security Services](http://pubs.opengroup.org/onlinepubs/9696989899/chap5.htm#tagcjh_08_02_01_01)
-
-## Copyright
-
-Copyright (C) 2013-2016 by Maxim Bublis .
-
-UUID package released under MIT License.
-See [LICENSE](https://github.com/satori/go.uuid/blob/master/LICENSE) for details.
diff --git a/vendor/github.com/satori/go.uuid/benchmarks_test.go b/vendor/github.com/satori/go.uuid/benchmarks_test.go
deleted file mode 100644
index b4e567f..0000000
--- a/vendor/github.com/satori/go.uuid/benchmarks_test.go
+++ /dev/null
@@ -1,121 +0,0 @@
-// Copyright (C) 2013-2015 by Maxim Bublis
-//
-// 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.
-
-package uuid
-
-import (
- "testing"
-)
-
-func BenchmarkFromBytes(b *testing.B) {
- bytes := []byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
- for i := 0; i < b.N; i++ {
- FromBytes(bytes)
- }
-}
-
-func BenchmarkFromString(b *testing.B) {
- s := "6ba7b810-9dad-11d1-80b4-00c04fd430c8"
- for i := 0; i < b.N; i++ {
- FromString(s)
- }
-}
-
-func BenchmarkFromStringUrn(b *testing.B) {
- s := "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8"
- for i := 0; i < b.N; i++ {
- FromString(s)
- }
-}
-
-func BenchmarkFromStringWithBrackets(b *testing.B) {
- s := "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}"
- for i := 0; i < b.N; i++ {
- FromString(s)
- }
-}
-
-func BenchmarkNewV1(b *testing.B) {
- for i := 0; i < b.N; i++ {
- NewV1()
- }
-}
-
-func BenchmarkNewV2(b *testing.B) {
- for i := 0; i < b.N; i++ {
- NewV2(DomainPerson)
- }
-}
-
-func BenchmarkNewV3(b *testing.B) {
- for i := 0; i < b.N; i++ {
- NewV3(NamespaceDNS, "www.example.com")
- }
-}
-
-func BenchmarkNewV4(b *testing.B) {
- for i := 0; i < b.N; i++ {
- NewV4()
- }
-}
-
-func BenchmarkNewV5(b *testing.B) {
- for i := 0; i < b.N; i++ {
- NewV5(NamespaceDNS, "www.example.com")
- }
-}
-
-func BenchmarkMarshalBinary(b *testing.B) {
- u := NewV4()
- for i := 0; i < b.N; i++ {
- u.MarshalBinary()
- }
-}
-
-func BenchmarkMarshalText(b *testing.B) {
- u := NewV4()
- for i := 0; i < b.N; i++ {
- u.MarshalText()
- }
-}
-
-func BenchmarkUnmarshalBinary(b *testing.B) {
- bytes := []byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
- u := UUID{}
- for i := 0; i < b.N; i++ {
- u.UnmarshalBinary(bytes)
- }
-}
-
-func BenchmarkUnmarshalText(b *testing.B) {
- bytes := []byte("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
- u := UUID{}
- for i := 0; i < b.N; i++ {
- u.UnmarshalText(bytes)
- }
-}
-
-func BenchmarkMarshalToString(b *testing.B) {
- u := NewV4()
- for i := 0; i < b.N; i++ {
- u.String()
- }
-}
diff --git a/vendor/github.com/satori/go.uuid/uuid.go b/vendor/github.com/satori/go.uuid/uuid.go
deleted file mode 100644
index 9c7fbaa..0000000
--- a/vendor/github.com/satori/go.uuid/uuid.go
+++ /dev/null
@@ -1,488 +0,0 @@
-// Copyright (C) 2013-2015 by Maxim Bublis
-//
-// 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.
-
-// Package uuid provides implementation of Universally Unique Identifier (UUID).
-// Supported versions are 1, 3, 4 and 5 (as specified in RFC 4122) and
-// version 2 (as specified in DCE 1.1).
-package uuid
-
-import (
- "bytes"
- "crypto/md5"
- "crypto/rand"
- "crypto/sha1"
- "database/sql/driver"
- "encoding/binary"
- "encoding/hex"
- "fmt"
- "hash"
- "net"
- "os"
- "sync"
- "time"
-)
-
-// UUID layout variants.
-const (
- VariantNCS = iota
- VariantRFC4122
- VariantMicrosoft
- VariantFuture
-)
-
-// UUID DCE domains.
-const (
- DomainPerson = iota
- DomainGroup
- DomainOrg
-)
-
-// Difference in 100-nanosecond intervals between
-// UUID epoch (October 15, 1582) and Unix epoch (January 1, 1970).
-const epochStart = 122192928000000000
-
-// Used in string method conversion
-const dash byte = '-'
-
-// UUID v1/v2 storage.
-var (
- storageMutex sync.Mutex
- storageOnce sync.Once
- epochFunc = unixTimeFunc
- clockSequence uint16
- lastTime uint64
- hardwareAddr [6]byte
- posixUID = uint32(os.Getuid())
- posixGID = uint32(os.Getgid())
-)
-
-// String parse helpers.
-var (
- urnPrefix = []byte("urn:uuid:")
- byteGroups = []int{8, 4, 4, 4, 12}
-)
-
-func initClockSequence() {
- buf := make([]byte, 2)
- safeRandom(buf)
- clockSequence = binary.BigEndian.Uint16(buf)
-}
-
-func initHardwareAddr() {
- interfaces, err := net.Interfaces()
- if err == nil {
- for _, iface := range interfaces {
- if len(iface.HardwareAddr) >= 6 {
- copy(hardwareAddr[:], iface.HardwareAddr)
- return
- }
- }
- }
-
- // Initialize hardwareAddr randomly in case
- // of real network interfaces absence
- safeRandom(hardwareAddr[:])
-
- // Set multicast bit as recommended in RFC 4122
- hardwareAddr[0] |= 0x01
-}
-
-func initStorage() {
- initClockSequence()
- initHardwareAddr()
-}
-
-func safeRandom(dest []byte) {
- if _, err := rand.Read(dest); err != nil {
- panic(err)
- }
-}
-
-// Returns difference in 100-nanosecond intervals between
-// UUID epoch (October 15, 1582) and current time.
-// This is default epoch calculation function.
-func unixTimeFunc() uint64 {
- return epochStart + uint64(time.Now().UnixNano()/100)
-}
-
-// UUID representation compliant with specification
-// described in RFC 4122.
-type UUID [16]byte
-
-// NullUUID can be used with the standard sql package to represent a
-// UUID value that can be NULL in the database
-type NullUUID struct {
- UUID UUID
- Valid bool
-}
-
-// The nil UUID is special form of UUID that is specified to have all
-// 128 bits set to zero.
-var Nil = UUID{}
-
-// Predefined namespace UUIDs.
-var (
- NamespaceDNS, _ = FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
- NamespaceURL, _ = FromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8")
- NamespaceOID, _ = FromString("6ba7b812-9dad-11d1-80b4-00c04fd430c8")
- NamespaceX500, _ = FromString("6ba7b814-9dad-11d1-80b4-00c04fd430c8")
-)
-
-// And returns result of binary AND of two UUIDs.
-func And(u1 UUID, u2 UUID) UUID {
- u := UUID{}
- for i := 0; i < 16; i++ {
- u[i] = u1[i] & u2[i]
- }
- return u
-}
-
-// Or returns result of binary OR of two UUIDs.
-func Or(u1 UUID, u2 UUID) UUID {
- u := UUID{}
- for i := 0; i < 16; i++ {
- u[i] = u1[i] | u2[i]
- }
- return u
-}
-
-// Equal returns true if u1 and u2 equals, otherwise returns false.
-func Equal(u1 UUID, u2 UUID) bool {
- return bytes.Equal(u1[:], u2[:])
-}
-
-// Version returns algorithm version used to generate UUID.
-func (u UUID) Version() uint {
- return uint(u[6] >> 4)
-}
-
-// Variant returns UUID layout variant.
-func (u UUID) Variant() uint {
- switch {
- case (u[8] & 0x80) == 0x00:
- return VariantNCS
- case (u[8]&0xc0)|0x80 == 0x80:
- return VariantRFC4122
- case (u[8]&0xe0)|0xc0 == 0xc0:
- return VariantMicrosoft
- }
- return VariantFuture
-}
-
-// Bytes returns bytes slice representation of UUID.
-func (u UUID) Bytes() []byte {
- return u[:]
-}
-
-// Returns canonical string representation of UUID:
-// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
-func (u UUID) String() string {
- buf := make([]byte, 36)
-
- hex.Encode(buf[0:8], u[0:4])
- buf[8] = dash
- hex.Encode(buf[9:13], u[4:6])
- buf[13] = dash
- hex.Encode(buf[14:18], u[6:8])
- buf[18] = dash
- hex.Encode(buf[19:23], u[8:10])
- buf[23] = dash
- hex.Encode(buf[24:], u[10:])
-
- return string(buf)
-}
-
-// SetVersion sets version bits.
-func (u *UUID) SetVersion(v byte) {
- u[6] = (u[6] & 0x0f) | (v << 4)
-}
-
-// SetVariant sets variant bits as described in RFC 4122.
-func (u *UUID) SetVariant() {
- u[8] = (u[8] & 0xbf) | 0x80
-}
-
-// MarshalText implements the encoding.TextMarshaler interface.
-// The encoding is the same as returned by String.
-func (u UUID) MarshalText() (text []byte, err error) {
- text = []byte(u.String())
- return
-}
-
-// UnmarshalText implements the encoding.TextUnmarshaler interface.
-// Following formats are supported:
-// "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
-// "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
-// "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8"
-func (u *UUID) UnmarshalText(text []byte) (err error) {
- if len(text) < 32 {
- err = fmt.Errorf("uuid: UUID string too short: %s", text)
- return
- }
-
- t := text[:]
- braced := false
-
- if bytes.Equal(t[:9], urnPrefix) {
- t = t[9:]
- } else if t[0] == '{' {
- braced = true
- t = t[1:]
- }
-
- b := u[:]
-
- for i, byteGroup := range byteGroups {
- if i > 0 && t[0] == '-' {
- t = t[1:]
- } else if i > 0 && t[0] != '-' {
- err = fmt.Errorf("uuid: invalid string format")
- return
- }
-
- if i == 2 {
- if !bytes.Contains([]byte("012345"), []byte{t[0]}) {
- err = fmt.Errorf("uuid: invalid version number: %s", t[0])
- return
- }
- }
-
- if len(t) < byteGroup {
- err = fmt.Errorf("uuid: UUID string too short: %s", text)
- return
- }
-
- if i == 4 && len(t) > byteGroup &&
- ((braced && t[byteGroup] != '}') || len(t[byteGroup:]) > 1 || !braced) {
- err = fmt.Errorf("uuid: UUID string too long: %s", t)
- return
- }
-
- _, err = hex.Decode(b[:byteGroup/2], t[:byteGroup])
-
- if err != nil {
- return
- }
-
- t = t[byteGroup:]
- b = b[byteGroup/2:]
- }
-
- return
-}
-
-// MarshalBinary implements the encoding.BinaryMarshaler interface.
-func (u UUID) MarshalBinary() (data []byte, err error) {
- data = u.Bytes()
- return
-}
-
-// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
-// It will return error if the slice isn't 16 bytes long.
-func (u *UUID) UnmarshalBinary(data []byte) (err error) {
- if len(data) != 16 {
- err = fmt.Errorf("uuid: UUID must be exactly 16 bytes long, got %d bytes", len(data))
- return
- }
- copy(u[:], data)
-
- return
-}
-
-// Value implements the driver.Valuer interface.
-func (u UUID) Value() (driver.Value, error) {
- return u.String(), nil
-}
-
-// Scan implements the sql.Scanner interface.
-// A 16-byte slice is handled by UnmarshalBinary, while
-// a longer byte slice or a string is handled by UnmarshalText.
-func (u *UUID) Scan(src interface{}) error {
- switch src := src.(type) {
- case []byte:
- if len(src) == 16 {
- return u.UnmarshalBinary(src)
- }
- return u.UnmarshalText(src)
-
- case string:
- return u.UnmarshalText([]byte(src))
- }
-
- return fmt.Errorf("uuid: cannot convert %T to UUID", src)
-}
-
-// Value implements the driver.Valuer interface.
-func (u NullUUID) Value() (driver.Value, error) {
- if !u.Valid {
- return nil, nil
- }
- // Delegate to UUID Value function
- return u.UUID.Value()
-}
-
-// Scan implements the sql.Scanner interface.
-func (u *NullUUID) Scan(src interface{}) error {
- if src == nil {
- u.UUID, u.Valid = Nil, false
- return nil
- }
-
- // Delegate to UUID Scan function
- u.Valid = true
- return u.UUID.Scan(src)
-}
-
-// FromBytes returns UUID converted from raw byte slice input.
-// It will return error if the slice isn't 16 bytes long.
-func FromBytes(input []byte) (u UUID, err error) {
- err = u.UnmarshalBinary(input)
- return
-}
-
-// FromBytesOrNil returns UUID converted from raw byte slice input.
-// Same behavior as FromBytes, but returns a Nil UUID on error.
-func FromBytesOrNil(input []byte) UUID {
- uuid, err := FromBytes(input)
- if err != nil {
- return Nil
- }
- return uuid
-}
-
-// FromString returns UUID parsed from string input.
-// Input is expected in a form accepted by UnmarshalText.
-func FromString(input string) (u UUID, err error) {
- err = u.UnmarshalText([]byte(input))
- return
-}
-
-// FromStringOrNil returns UUID parsed from string input.
-// Same behavior as FromString, but returns a Nil UUID on error.
-func FromStringOrNil(input string) UUID {
- uuid, err := FromString(input)
- if err != nil {
- return Nil
- }
- return uuid
-}
-
-// Returns UUID v1/v2 storage state.
-// Returns epoch timestamp, clock sequence, and hardware address.
-func getStorage() (uint64, uint16, []byte) {
- storageOnce.Do(initStorage)
-
- storageMutex.Lock()
- defer storageMutex.Unlock()
-
- timeNow := epochFunc()
- // Clock changed backwards since last UUID generation.
- // Should increase clock sequence.
- if timeNow <= lastTime {
- clockSequence++
- }
- lastTime = timeNow
-
- return timeNow, clockSequence, hardwareAddr[:]
-}
-
-// NewV1 returns UUID based on current timestamp and MAC address.
-func NewV1() UUID {
- u := UUID{}
-
- timeNow, clockSeq, hardwareAddr := getStorage()
-
- binary.BigEndian.PutUint32(u[0:], uint32(timeNow))
- binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32))
- binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48))
- binary.BigEndian.PutUint16(u[8:], clockSeq)
-
- copy(u[10:], hardwareAddr)
-
- u.SetVersion(1)
- u.SetVariant()
-
- return u
-}
-
-// NewV2 returns DCE Security UUID based on POSIX UID/GID.
-func NewV2(domain byte) UUID {
- u := UUID{}
-
- timeNow, clockSeq, hardwareAddr := getStorage()
-
- switch domain {
- case DomainPerson:
- binary.BigEndian.PutUint32(u[0:], posixUID)
- case DomainGroup:
- binary.BigEndian.PutUint32(u[0:], posixGID)
- }
-
- binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32))
- binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48))
- binary.BigEndian.PutUint16(u[8:], clockSeq)
- u[9] = domain
-
- copy(u[10:], hardwareAddr)
-
- u.SetVersion(2)
- u.SetVariant()
-
- return u
-}
-
-// NewV3 returns UUID based on MD5 hash of namespace UUID and name.
-func NewV3(ns UUID, name string) UUID {
- u := newFromHash(md5.New(), ns, name)
- u.SetVersion(3)
- u.SetVariant()
-
- return u
-}
-
-// NewV4 returns random generated UUID.
-func NewV4() UUID {
- u := UUID{}
- safeRandom(u[:])
- u.SetVersion(4)
- u.SetVariant()
-
- return u
-}
-
-// NewV5 returns UUID based on SHA-1 hash of namespace UUID and name.
-func NewV5(ns UUID, name string) UUID {
- u := newFromHash(sha1.New(), ns, name)
- u.SetVersion(5)
- u.SetVariant()
-
- return u
-}
-
-// Returns UUID based on hashing of namespace UUID and name.
-func newFromHash(h hash.Hash, ns UUID, name string) UUID {
- u := UUID{}
- h.Write(ns[:])
- h.Write([]byte(name))
- copy(u[:], h.Sum(nil))
-
- return u
-}
diff --git a/vendor/github.com/satori/go.uuid/uuid_test.go b/vendor/github.com/satori/go.uuid/uuid_test.go
deleted file mode 100644
index aa68ac9..0000000
--- a/vendor/github.com/satori/go.uuid/uuid_test.go
+++ /dev/null
@@ -1,633 +0,0 @@
-// Copyright (C) 2013, 2015 by Maxim Bublis
-//
-// 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.
-
-package uuid
-
-import (
- "bytes"
- "testing"
-)
-
-func TestBytes(t *testing.T) {
- u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
-
- bytes1 := []byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
-
- if !bytes.Equal(u.Bytes(), bytes1) {
- t.Errorf("Incorrect bytes representation for UUID: %s", u)
- }
-}
-
-func TestString(t *testing.T) {
- if NamespaceDNS.String() != "6ba7b810-9dad-11d1-80b4-00c04fd430c8" {
- t.Errorf("Incorrect string representation for UUID: %s", NamespaceDNS.String())
- }
-}
-
-func TestEqual(t *testing.T) {
- if !Equal(NamespaceDNS, NamespaceDNS) {
- t.Errorf("Incorrect comparison of %s and %s", NamespaceDNS, NamespaceDNS)
- }
-
- if Equal(NamespaceDNS, NamespaceURL) {
- t.Errorf("Incorrect comparison of %s and %s", NamespaceDNS, NamespaceURL)
- }
-}
-
-func TestOr(t *testing.T) {
- u1 := UUID{0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff}
- u2 := UUID{0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00}
-
- u := UUID{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
-
- if !Equal(u, Or(u1, u2)) {
- t.Errorf("Incorrect bitwise OR result %s", Or(u1, u2))
- }
-}
-
-func TestAnd(t *testing.T) {
- u1 := UUID{0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff}
- u2 := UUID{0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00}
-
- u := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
-
- if !Equal(u, And(u1, u2)) {
- t.Errorf("Incorrect bitwise AND result %s", And(u1, u2))
- }
-}
-
-func TestVersion(t *testing.T) {
- u := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
-
- if u.Version() != 1 {
- t.Errorf("Incorrect version for UUID: %d", u.Version())
- }
-}
-
-func TestSetVersion(t *testing.T) {
- u := UUID{}
- u.SetVersion(4)
-
- if u.Version() != 4 {
- t.Errorf("Incorrect version for UUID after u.setVersion(4): %d", u.Version())
- }
-}
-
-func TestVariant(t *testing.T) {
- u1 := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
-
- if u1.Variant() != VariantNCS {
- t.Errorf("Incorrect variant for UUID variant %d: %d", VariantNCS, u1.Variant())
- }
-
- u2 := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
-
- if u2.Variant() != VariantRFC4122 {
- t.Errorf("Incorrect variant for UUID variant %d: %d", VariantRFC4122, u2.Variant())
- }
-
- u3 := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
-
- if u3.Variant() != VariantMicrosoft {
- t.Errorf("Incorrect variant for UUID variant %d: %d", VariantMicrosoft, u3.Variant())
- }
-
- u4 := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
-
- if u4.Variant() != VariantFuture {
- t.Errorf("Incorrect variant for UUID variant %d: %d", VariantFuture, u4.Variant())
- }
-}
-
-func TestSetVariant(t *testing.T) {
- u := new(UUID)
- u.SetVariant()
-
- if u.Variant() != VariantRFC4122 {
- t.Errorf("Incorrect variant for UUID after u.setVariant(): %d", u.Variant())
- }
-}
-
-func TestFromBytes(t *testing.T) {
- u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
- b1 := []byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
-
- u1, err := FromBytes(b1)
- if err != nil {
- t.Errorf("Error parsing UUID from bytes: %s", err)
- }
-
- if !Equal(u, u1) {
- t.Errorf("UUIDs should be equal: %s and %s", u, u1)
- }
-
- b2 := []byte{}
-
- _, err = FromBytes(b2)
- if err == nil {
- t.Errorf("Should return error parsing from empty byte slice, got %s", err)
- }
-}
-
-func TestMarshalBinary(t *testing.T) {
- u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
- b1 := []byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
-
- b2, err := u.MarshalBinary()
- if err != nil {
- t.Errorf("Error marshaling UUID: %s", err)
- }
-
- if !bytes.Equal(b1, b2) {
- t.Errorf("Marshaled UUID should be %s, got %s", b1, b2)
- }
-}
-
-func TestUnmarshalBinary(t *testing.T) {
- u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
- b1 := []byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
-
- u1 := UUID{}
- err := u1.UnmarshalBinary(b1)
- if err != nil {
- t.Errorf("Error unmarshaling UUID: %s", err)
- }
-
- if !Equal(u, u1) {
- t.Errorf("UUIDs should be equal: %s and %s", u, u1)
- }
-
- b2 := []byte{}
- u2 := UUID{}
-
- err = u2.UnmarshalBinary(b2)
- if err == nil {
- t.Errorf("Should return error unmarshalling from empty byte slice, got %s", err)
- }
-}
-
-func TestFromString(t *testing.T) {
- u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
-
- s1 := "6ba7b810-9dad-11d1-80b4-00c04fd430c8"
- s2 := "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}"
- s3 := "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8"
-
- _, err := FromString("")
- if err == nil {
- t.Errorf("Should return error trying to parse empty string, got %s", err)
- }
-
- u1, err := FromString(s1)
- if err != nil {
- t.Errorf("Error parsing UUID from string: %s", err)
- }
-
- if !Equal(u, u1) {
- t.Errorf("UUIDs should be equal: %s and %s", u, u1)
- }
-
- u2, err := FromString(s2)
- if err != nil {
- t.Errorf("Error parsing UUID from string: %s", err)
- }
-
- if !Equal(u, u2) {
- t.Errorf("UUIDs should be equal: %s and %s", u, u2)
- }
-
- u3, err := FromString(s3)
- if err != nil {
- t.Errorf("Error parsing UUID from string: %s", err)
- }
-
- if !Equal(u, u3) {
- t.Errorf("UUIDs should be equal: %s and %s", u, u3)
- }
-}
-
-func TestFromStringShort(t *testing.T) {
- // Invalid 35-character UUID string
- s1 := "6ba7b810-9dad-11d1-80b4-00c04fd430c"
-
- for i := len(s1); i >= 0; i-- {
- _, err := FromString(s1[:i])
- if err == nil {
- t.Errorf("Should return error trying to parse too short string, got %s", err)
- }
- }
-}
-
-func TestFromStringLong(t *testing.T) {
- // Invalid 37+ character UUID string
- s := []string{
- "6ba7b810-9dad-11d1-80b4-00c04fd430c8=",
- "6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
- "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}f",
- "6ba7b810-9dad-11d1-80b4-00c04fd430c800c04fd430c8",
- }
-
- for _, str := range s {
- _, err := FromString(str)
- if err == nil {
- t.Errorf("Should return error trying to parse too long string, passed %s", str)
- }
- }
-}
-
-func TestFromStringInvalid(t *testing.T) {
- // Invalid UUID string formats
- s := []string{
- "6ba7b8109dad11d180b400c04fd430c8",
- "6ba7b8109dad11d180b400c04fd430c86ba7b8109dad11d180b400c04fd430c8",
- "urn:uuid:{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
- "6ba7b8109-dad-11d1-80b4-00c04fd430c8",
- "6ba7b810-9dad1-1d1-80b4-00c04fd430c8",
- "6ba7b810-9dad-11d18-0b4-00c04fd430c8",
- "6ba7b810-9dad-11d1-80b40-0c04fd430c8",
- "6ba7b810+9dad+11d1+80b4+00c04fd430c8",
- "6ba7b810-9dad11d180b400c04fd430c8",
- "6ba7b8109dad-11d180b400c04fd430c8",
- "6ba7b8109dad11d1-80b400c04fd430c8",
- "6ba7b8109dad11d180b4-00c04fd430c8",
- }
-
- for _, str := range s {
- _, err := FromString(str)
- if err == nil {
- t.Errorf("Should return error trying to parse invalid string, passed %s", str)
- }
- }
-}
-
-func TestFromStringOrNil(t *testing.T) {
- u := FromStringOrNil("")
- if u != Nil {
- t.Errorf("Should return Nil UUID on parse failure, got %s", u)
- }
-}
-
-func TestFromBytesOrNil(t *testing.T) {
- b := []byte{}
- u := FromBytesOrNil(b)
- if u != Nil {
- t.Errorf("Should return Nil UUID on parse failure, got %s", u)
- }
-}
-
-func TestMarshalText(t *testing.T) {
- u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
- b1 := []byte("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
-
- b2, err := u.MarshalText()
- if err != nil {
- t.Errorf("Error marshaling UUID: %s", err)
- }
-
- if !bytes.Equal(b1, b2) {
- t.Errorf("Marshaled UUID should be %s, got %s", b1, b2)
- }
-}
-
-func TestUnmarshalText(t *testing.T) {
- u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
- b1 := []byte("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
-
- u1 := UUID{}
- err := u1.UnmarshalText(b1)
- if err != nil {
- t.Errorf("Error unmarshaling UUID: %s", err)
- }
-
- if !Equal(u, u1) {
- t.Errorf("UUIDs should be equal: %s and %s", u, u1)
- }
-
- b2 := []byte("")
- u2 := UUID{}
-
- err = u2.UnmarshalText(b2)
- if err == nil {
- t.Errorf("Should return error trying to unmarshal from empty string")
- }
-}
-
-func TestValue(t *testing.T) {
- u, err := FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
- if err != nil {
- t.Errorf("Error parsing UUID from string: %s", err)
- }
-
- val, err := u.Value()
- if err != nil {
- t.Errorf("Error getting UUID value: %s", err)
- }
-
- if val != u.String() {
- t.Errorf("Wrong value returned, should be equal: %s and %s", val, u)
- }
-}
-
-func TestValueNil(t *testing.T) {
- u := UUID{}
-
- val, err := u.Value()
- if err != nil {
- t.Errorf("Error getting UUID value: %s", err)
- }
-
- if val != Nil.String() {
- t.Errorf("Wrong value returned, should be equal to UUID.Nil: %s", val)
- }
-}
-
-func TestNullUUIDValueNil(t *testing.T) {
- u := NullUUID{}
-
- val, err := u.Value()
- if err != nil {
- t.Errorf("Error getting UUID value: %s", err)
- }
-
- if val != nil {
- t.Errorf("Wrong value returned, should be nil: %s", val)
- }
-}
-
-func TestScanBinary(t *testing.T) {
- u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
- b1 := []byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
-
- u1 := UUID{}
- err := u1.Scan(b1)
- if err != nil {
- t.Errorf("Error unmarshaling UUID: %s", err)
- }
-
- if !Equal(u, u1) {
- t.Errorf("UUIDs should be equal: %s and %s", u, u1)
- }
-
- b2 := []byte{}
- u2 := UUID{}
-
- err = u2.Scan(b2)
- if err == nil {
- t.Errorf("Should return error unmarshalling from empty byte slice, got %s", err)
- }
-}
-
-func TestScanString(t *testing.T) {
- u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
- s1 := "6ba7b810-9dad-11d1-80b4-00c04fd430c8"
-
- u1 := UUID{}
- err := u1.Scan(s1)
- if err != nil {
- t.Errorf("Error unmarshaling UUID: %s", err)
- }
-
- if !Equal(u, u1) {
- t.Errorf("UUIDs should be equal: %s and %s", u, u1)
- }
-
- s2 := ""
- u2 := UUID{}
-
- err = u2.Scan(s2)
- if err == nil {
- t.Errorf("Should return error trying to unmarshal from empty string")
- }
-}
-
-func TestScanText(t *testing.T) {
- u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
- b1 := []byte("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
-
- u1 := UUID{}
- err := u1.Scan(b1)
- if err != nil {
- t.Errorf("Error unmarshaling UUID: %s", err)
- }
-
- if !Equal(u, u1) {
- t.Errorf("UUIDs should be equal: %s and %s", u, u1)
- }
-
- b2 := []byte("")
- u2 := UUID{}
-
- err = u2.Scan(b2)
- if err == nil {
- t.Errorf("Should return error trying to unmarshal from empty string")
- }
-}
-
-func TestScanUnsupported(t *testing.T) {
- u := UUID{}
-
- err := u.Scan(true)
- if err == nil {
- t.Errorf("Should return error trying to unmarshal from bool")
- }
-}
-
-func TestScanNil(t *testing.T) {
- u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
-
- err := u.Scan(nil)
- if err == nil {
- t.Errorf("Error UUID shouldn't allow unmarshalling from nil")
- }
-}
-
-func TestNullUUIDScanValid(t *testing.T) {
- u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
- s1 := "6ba7b810-9dad-11d1-80b4-00c04fd430c8"
-
- u1 := NullUUID{}
- err := u1.Scan(s1)
- if err != nil {
- t.Errorf("Error unmarshaling NullUUID: %s", err)
- }
-
- if !u1.Valid {
- t.Errorf("NullUUID should be valid")
- }
-
- if !Equal(u, u1.UUID) {
- t.Errorf("UUIDs should be equal: %s and %s", u, u1.UUID)
- }
-}
-
-func TestNullUUIDScanNil(t *testing.T) {
- u := NullUUID{UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}, true}
-
- err := u.Scan(nil)
- if err != nil {
- t.Errorf("Error unmarshaling NullUUID: %s", err)
- }
-
- if u.Valid {
- t.Errorf("NullUUID should not be valid")
- }
-
- if !Equal(u.UUID, Nil) {
- t.Errorf("NullUUID value should be equal to Nil: %s", u)
- }
-}
-
-func TestNewV1(t *testing.T) {
- u := NewV1()
-
- if u.Version() != 1 {
- t.Errorf("UUIDv1 generated with incorrect version: %d", u.Version())
- }
-
- if u.Variant() != VariantRFC4122 {
- t.Errorf("UUIDv1 generated with incorrect variant: %d", u.Variant())
- }
-
- u1 := NewV1()
- u2 := NewV1()
-
- if Equal(u1, u2) {
- t.Errorf("UUIDv1 generated two equal UUIDs: %s and %s", u1, u2)
- }
-
- oldFunc := epochFunc
- epochFunc = func() uint64 { return 0 }
-
- u3 := NewV1()
- u4 := NewV1()
-
- if Equal(u3, u4) {
- t.Errorf("UUIDv1 generated two equal UUIDs: %s and %s", u3, u4)
- }
-
- epochFunc = oldFunc
-}
-
-func TestNewV2(t *testing.T) {
- u1 := NewV2(DomainPerson)
-
- if u1.Version() != 2 {
- t.Errorf("UUIDv2 generated with incorrect version: %d", u1.Version())
- }
-
- if u1.Variant() != VariantRFC4122 {
- t.Errorf("UUIDv2 generated with incorrect variant: %d", u1.Variant())
- }
-
- u2 := NewV2(DomainGroup)
-
- if u2.Version() != 2 {
- t.Errorf("UUIDv2 generated with incorrect version: %d", u2.Version())
- }
-
- if u2.Variant() != VariantRFC4122 {
- t.Errorf("UUIDv2 generated with incorrect variant: %d", u2.Variant())
- }
-}
-
-func TestNewV3(t *testing.T) {
- u := NewV3(NamespaceDNS, "www.example.com")
-
- if u.Version() != 3 {
- t.Errorf("UUIDv3 generated with incorrect version: %d", u.Version())
- }
-
- if u.Variant() != VariantRFC4122 {
- t.Errorf("UUIDv3 generated with incorrect variant: %d", u.Variant())
- }
-
- if u.String() != "5df41881-3aed-3515-88a7-2f4a814cf09e" {
- t.Errorf("UUIDv3 generated incorrectly: %s", u.String())
- }
-
- u = NewV3(NamespaceDNS, "python.org")
-
- if u.String() != "6fa459ea-ee8a-3ca4-894e-db77e160355e" {
- t.Errorf("UUIDv3 generated incorrectly: %s", u.String())
- }
-
- u1 := NewV3(NamespaceDNS, "golang.org")
- u2 := NewV3(NamespaceDNS, "golang.org")
- if !Equal(u1, u2) {
- t.Errorf("UUIDv3 generated different UUIDs for same namespace and name: %s and %s", u1, u2)
- }
-
- u3 := NewV3(NamespaceDNS, "example.com")
- if Equal(u1, u3) {
- t.Errorf("UUIDv3 generated same UUIDs for different names in same namespace: %s and %s", u1, u2)
- }
-
- u4 := NewV3(NamespaceURL, "golang.org")
- if Equal(u1, u4) {
- t.Errorf("UUIDv3 generated same UUIDs for sane names in different namespaces: %s and %s", u1, u4)
- }
-}
-
-func TestNewV4(t *testing.T) {
- u := NewV4()
-
- if u.Version() != 4 {
- t.Errorf("UUIDv4 generated with incorrect version: %d", u.Version())
- }
-
- if u.Variant() != VariantRFC4122 {
- t.Errorf("UUIDv4 generated with incorrect variant: %d", u.Variant())
- }
-}
-
-func TestNewV5(t *testing.T) {
- u := NewV5(NamespaceDNS, "www.example.com")
-
- if u.Version() != 5 {
- t.Errorf("UUIDv5 generated with incorrect version: %d", u.Version())
- }
-
- if u.Variant() != VariantRFC4122 {
- t.Errorf("UUIDv5 generated with incorrect variant: %d", u.Variant())
- }
-
- u = NewV5(NamespaceDNS, "python.org")
-
- if u.String() != "886313e1-3b8a-5372-9b90-0c9aee199e5d" {
- t.Errorf("UUIDv5 generated incorrectly: %s", u.String())
- }
-
- u1 := NewV5(NamespaceDNS, "golang.org")
- u2 := NewV5(NamespaceDNS, "golang.org")
- if !Equal(u1, u2) {
- t.Errorf("UUIDv5 generated different UUIDs for same namespace and name: %s and %s", u1, u2)
- }
-
- u3 := NewV5(NamespaceDNS, "example.com")
- if Equal(u1, u3) {
- t.Errorf("UUIDv5 generated same UUIDs for different names in same namespace: %s and %s", u1, u2)
- }
-
- u4 := NewV5(NamespaceURL, "golang.org")
- if Equal(u1, u4) {
- t.Errorf("UUIDv3 generated same UUIDs for sane names in different namespaces: %s and %s", u1, u4)
- }
-}
diff --git a/vendor/github.com/sirupsen/logrus/.gitignore b/vendor/github.com/sirupsen/logrus/.gitignore
deleted file mode 100644
index 66be63a..0000000
--- a/vendor/github.com/sirupsen/logrus/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-logrus
diff --git a/vendor/github.com/sirupsen/logrus/.travis.yml b/vendor/github.com/sirupsen/logrus/.travis.yml
deleted file mode 100644
index a23296a..0000000
--- a/vendor/github.com/sirupsen/logrus/.travis.yml
+++ /dev/null
@@ -1,15 +0,0 @@
-language: go
-go:
- - 1.6.x
- - 1.7.x
- - 1.8.x
- - tip
-env:
- - GOMAXPROCS=4 GORACE=halt_on_error=1
-install:
- - go get github.com/stretchr/testify/assert
- - go get gopkg.in/gemnasium/logrus-airbrake-hook.v2
- - go get golang.org/x/sys/unix
- - go get golang.org/x/sys/windows
-script:
- - go test -race -v ./...
diff --git a/vendor/github.com/sirupsen/logrus/CHANGELOG.md b/vendor/github.com/sirupsen/logrus/CHANGELOG.md
deleted file mode 100644
index 8236d8b..0000000
--- a/vendor/github.com/sirupsen/logrus/CHANGELOG.md
+++ /dev/null
@@ -1,113 +0,0 @@
-# 1.0.3
-
-* Replace example files with testable examples
-
-# 1.0.2
-
-* bug: quote non-string values in text formatter (#583)
-* Make (*Logger) SetLevel a public method
-
-# 1.0.1
-
-* bug: fix escaping in text formatter (#575)
-
-# 1.0.0
-
-* Officially changed name to lower-case
-* bug: colors on Windows 10 (#541)
-* bug: fix race in accessing level (#512)
-
-# 0.11.5
-
-* feature: add writer and writerlevel to entry (#372)
-
-# 0.11.4
-
-* bug: fix undefined variable on solaris (#493)
-
-# 0.11.3
-
-* formatter: configure quoting of empty values (#484)
-* formatter: configure quoting character (default is `"`) (#484)
-* bug: fix not importing io correctly in non-linux environments (#481)
-
-# 0.11.2
-
-* bug: fix windows terminal detection (#476)
-
-# 0.11.1
-
-* bug: fix tty detection with custom out (#471)
-
-# 0.11.0
-
-* performance: Use bufferpool to allocate (#370)
-* terminal: terminal detection for app-engine (#343)
-* feature: exit handler (#375)
-
-# 0.10.0
-
-* feature: Add a test hook (#180)
-* feature: `ParseLevel` is now case-insensitive (#326)
-* feature: `FieldLogger` interface that generalizes `Logger` and `Entry` (#308)
-* performance: avoid re-allocations on `WithFields` (#335)
-
-# 0.9.0
-
-* logrus/text_formatter: don't emit empty msg
-* logrus/hooks/airbrake: move out of main repository
-* logrus/hooks/sentry: move out of main repository
-* logrus/hooks/papertrail: move out of main repository
-* logrus/hooks/bugsnag: move out of main repository
-* logrus/core: run tests with `-race`
-* logrus/core: detect TTY based on `stderr`
-* logrus/core: support `WithError` on logger
-* logrus/core: Solaris support
-
-# 0.8.7
-
-* logrus/core: fix possible race (#216)
-* logrus/doc: small typo fixes and doc improvements
-
-
-# 0.8.6
-
-* hooks/raven: allow passing an initialized client
-
-# 0.8.5
-
-* logrus/core: revert #208
-
-# 0.8.4
-
-* formatter/text: fix data race (#218)
-
-# 0.8.3
-
-* logrus/core: fix entry log level (#208)
-* logrus/core: improve performance of text formatter by 40%
-* logrus/core: expose `LevelHooks` type
-* logrus/core: add support for DragonflyBSD and NetBSD
-* formatter/text: print structs more verbosely
-
-# 0.8.2
-
-* logrus: fix more Fatal family functions
-
-# 0.8.1
-
-* logrus: fix not exiting on `Fatalf` and `Fatalln`
-
-# 0.8.0
-
-* logrus: defaults to stderr instead of stdout
-* hooks/sentry: add special field for `*http.Request`
-* formatter/text: ignore Windows for colors
-
-# 0.7.3
-
-* formatter/\*: allow configuration of timestamp layout
-
-# 0.7.2
-
-* formatter/text: Add configuration option for time format (#158)
diff --git a/vendor/github.com/sirupsen/logrus/LICENSE b/vendor/github.com/sirupsen/logrus/LICENSE
deleted file mode 100644
index f090cb4..0000000
--- a/vendor/github.com/sirupsen/logrus/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2014 Simon Eskildsen
-
-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.
diff --git a/vendor/github.com/sirupsen/logrus/README.md b/vendor/github.com/sirupsen/logrus/README.md
deleted file mode 100644
index 4f5ce57..0000000
--- a/vendor/github.com/sirupsen/logrus/README.md
+++ /dev/null
@@ -1,505 +0,0 @@
-# Logrus [](https://travis-ci.org/sirupsen/logrus) [](https://godoc.org/github.com/sirupsen/logrus)
-
-Logrus is a structured logger for Go (golang), completely API compatible with
-the standard library logger.
-
-**Seeing weird case-sensitive problems?** It's in the past been possible to
-import Logrus as both upper- and lower-case. Due to the Go package environment,
-this caused issues in the community and we needed a standard. Some environments
-experienced problems with the upper-case variant, so the lower-case was decided.
-Everything using `logrus` will need to use the lower-case:
-`github.com/sirupsen/logrus`. Any package that isn't, should be changed.
-
-To fix Glide, see [these
-comments](https://github.com/sirupsen/logrus/issues/553#issuecomment-306591437).
-For an in-depth explanation of the casing issue, see [this
-comment](https://github.com/sirupsen/logrus/issues/570#issuecomment-313933276).
-
-**Are you interested in assisting in maintaining Logrus?** Currently I have a
-lot of obligations, and I am unable to provide Logrus with the maintainership it
-needs. If you'd like to help, please reach out to me at `simon at author's
-username dot com`.
-
-Nicely color-coded in development (when a TTY is attached, otherwise just
-plain text):
-
-
-
-With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash
-or Splunk:
-
-```json
-{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the
-ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"}
-
-{"level":"warning","msg":"The group's number increased tremendously!",
-"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"}
-
-{"animal":"walrus","level":"info","msg":"A giant walrus appears!",
-"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"}
-
-{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.",
-"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"}
-
-{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true,
-"time":"2014-03-10 19:57:38.562543128 -0400 EDT"}
-```
-
-With the default `log.SetFormatter(&log.TextFormatter{})` when a TTY is not
-attached, the output is compatible with the
-[logfmt](http://godoc.org/github.com/kr/logfmt) format:
-
-```text
-time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8
-time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
-time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true
-time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4
-time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009
-time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true
-exit status 1
-```
-
-#### Case-sensitivity
-
-The organization's name was changed to lower-case--and this will not be changed
-back. If you are getting import conflicts due to case sensitivity, please use
-the lower-case import: `github.com/sirupsen/logrus`.
-
-#### Example
-
-The simplest way to use Logrus is simply the package-level exported logger:
-
-```go
-package main
-
-import (
- log "github.com/sirupsen/logrus"
-)
-
-func main() {
- log.WithFields(log.Fields{
- "animal": "walrus",
- }).Info("A walrus appears")
-}
-```
-
-Note that it's completely api-compatible with the stdlib logger, so you can
-replace your `log` imports everywhere with `log "github.com/sirupsen/logrus"`
-and you'll now have the flexibility of Logrus. You can customize it all you
-want:
-
-```go
-package main
-
-import (
- "os"
- log "github.com/sirupsen/logrus"
-)
-
-func init() {
- // Log as JSON instead of the default ASCII formatter.
- log.SetFormatter(&log.JSONFormatter{})
-
- // Output to stdout instead of the default stderr
- // Can be any io.Writer, see below for File example
- log.SetOutput(os.Stdout)
-
- // Only log the warning severity or above.
- log.SetLevel(log.WarnLevel)
-}
-
-func main() {
- log.WithFields(log.Fields{
- "animal": "walrus",
- "size": 10,
- }).Info("A group of walrus emerges from the ocean")
-
- log.WithFields(log.Fields{
- "omg": true,
- "number": 122,
- }).Warn("The group's number increased tremendously!")
-
- log.WithFields(log.Fields{
- "omg": true,
- "number": 100,
- }).Fatal("The ice breaks!")
-
- // A common pattern is to re-use fields between logging statements by re-using
- // the logrus.Entry returned from WithFields()
- contextLogger := log.WithFields(log.Fields{
- "common": "this is a common field",
- "other": "I also should be logged always",
- })
-
- contextLogger.Info("I'll be logged with common and other field")
- contextLogger.Info("Me too")
-}
-```
-
-For more advanced usage such as logging to multiple locations from the same
-application, you can also create an instance of the `logrus` Logger:
-
-```go
-package main
-
-import (
- "os"
- "github.com/sirupsen/logrus"
-)
-
-// Create a new instance of the logger. You can have any number of instances.
-var log = logrus.New()
-
-func main() {
- // The API for setting attributes is a little different than the package level
- // exported logger. See Godoc.
- log.Out = os.Stdout
-
- // You could set this to any `io.Writer` such as a file
- // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666)
- // if err == nil {
- // log.Out = file
- // } else {
- // log.Info("Failed to log to file, using default stderr")
- // }
-
- log.WithFields(logrus.Fields{
- "animal": "walrus",
- "size": 10,
- }).Info("A group of walrus emerges from the ocean")
-}
-```
-
-#### Fields
-
-Logrus encourages careful, structured logging through logging fields instead of
-long, unparseable error messages. For example, instead of: `log.Fatalf("Failed
-to send event %s to topic %s with key %d")`, you should log the much more
-discoverable:
-
-```go
-log.WithFields(log.Fields{
- "event": event,
- "topic": topic,
- "key": key,
-}).Fatal("Failed to send event")
-```
-
-We've found this API forces you to think about logging in a way that produces
-much more useful logging messages. We've been in countless situations where just
-a single added field to a log statement that was already there would've saved us
-hours. The `WithFields` call is optional.
-
-In general, with Logrus using any of the `printf`-family functions should be
-seen as a hint you should add a field, however, you can still use the
-`printf`-family functions with Logrus.
-
-#### Default Fields
-
-Often it's helpful to have fields _always_ attached to log statements in an
-application or parts of one. For example, you may want to always log the
-`request_id` and `user_ip` in the context of a request. Instead of writing
-`log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})` on
-every line, you can create a `logrus.Entry` to pass around instead:
-
-```go
-requestLogger := log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})
-requestLogger.Info("something happened on that request") # will log request_id and user_ip
-requestLogger.Warn("something not great happened")
-```
-
-#### Hooks
-
-You can add hooks for logging levels. For example to send errors to an exception
-tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to
-multiple places simultaneously, e.g. syslog.
-
-Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in
-`init`:
-
-```go
-import (
- log "github.com/sirupsen/logrus"
- "gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "aibrake"
- logrus_syslog "github.com/sirupsen/logrus/hooks/syslog"
- "log/syslog"
-)
-
-func init() {
-
- // Use the Airbrake hook to report errors that have Error severity or above to
- // an exception tracker. You can create custom hooks, see the Hooks section.
- log.AddHook(airbrake.NewHook(123, "xyz", "production"))
-
- hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
- if err != nil {
- log.Error("Unable to connect to local syslog daemon")
- } else {
- log.AddHook(hook)
- }
-}
-```
-Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md).
-
-| Hook | Description |
-| ----- | ----------- |
-| [Airbrake "legacy"](https://github.com/gemnasium/logrus-airbrake-legacy-hook) | Send errors to an exception tracking service compatible with the Airbrake API V2. Uses [`airbrake-go`](https://github.com/tobi/airbrake-go) behind the scenes. |
-| [Airbrake](https://github.com/gemnasium/logrus-airbrake-hook) | Send errors to the Airbrake API V3. Uses the official [`gobrake`](https://github.com/airbrake/gobrake) behind the scenes. |
-| [Amazon Kinesis](https://github.com/evalphobia/logrus_kinesis) | Hook for logging to [Amazon Kinesis](https://aws.amazon.com/kinesis/) |
-| [Amqp-Hook](https://github.com/vladoatanasov/logrus_amqp) | Hook for logging to Amqp broker (Like RabbitMQ) |
-| [Bugsnag](https://github.com/Shopify/logrus-bugsnag/blob/master/bugsnag.go) | Send errors to the Bugsnag exception tracking service. |
-| [DeferPanic](https://github.com/deferpanic/dp-logrus) | Hook for logging to DeferPanic |
-| [Discordrus](https://github.com/kz/discordrus) | Hook for logging to [Discord](https://discordapp.com/) |
-| [ElasticSearch](https://github.com/sohlich/elogrus) | Hook for logging to ElasticSearch|
-| [Firehose](https://github.com/beaubrewer/logrus_firehose) | Hook for logging to [Amazon Firehose](https://aws.amazon.com/kinesis/firehose/)
-| [Fluentd](https://github.com/evalphobia/logrus_fluent) | Hook for logging to fluentd |
-| [Go-Slack](https://github.com/multiplay/go-slack) | Hook for logging to [Slack](https://slack.com) |
-| [Graylog](https://github.com/gemnasium/logrus-graylog-hook) | Hook for logging to [Graylog](http://graylog2.org/) |
-| [Hiprus](https://github.com/nubo/hiprus) | Send errors to a channel in hipchat. |
-| [Honeybadger](https://github.com/agonzalezro/logrus_honeybadger) | Hook for sending exceptions to Honeybadger |
-| [InfluxDB](https://github.com/Abramovic/logrus_influxdb) | Hook for logging to influxdb |
-| [Influxus](http://github.com/vlad-doru/influxus) | Hook for concurrently logging to [InfluxDB](http://influxdata.com/) |
-| [Journalhook](https://github.com/wercker/journalhook) | Hook for logging to `systemd-journald` |
-| [KafkaLogrus](https://github.com/goibibo/KafkaLogrus) | Hook for logging to kafka |
-| [LFShook](https://github.com/rifflock/lfshook) | Hook for logging to the local filesystem |
-| [Logentries](https://github.com/jcftang/logentriesrus) | Hook for logging to [Logentries](https://logentries.com/) |
-| [Logentrus](https://github.com/puddingfactory/logentrus) | Hook for logging to [Logentries](https://logentries.com/) |
-| [Logmatic.io](https://github.com/logmatic/logmatic-go) | Hook for logging to [Logmatic.io](http://logmatic.io/) |
-| [Logrusly](https://github.com/sebest/logrusly) | Send logs to [Loggly](https://www.loggly.com/) |
-| [Logstash](https://github.com/bshuster-repo/logrus-logstash-hook) | Hook for logging to [Logstash](https://www.elastic.co/products/logstash) |
-| [Mail](https://github.com/zbindenren/logrus_mail) | Hook for sending exceptions via mail |
-| [Mattermost](https://github.com/shuLhan/mattermost-integration/tree/master/hooks/logrus) | Hook for logging to [Mattermost](https://mattermost.com/) |
-| [Mongodb](https://github.com/weekface/mgorus) | Hook for logging to mongodb |
-| [NATS-Hook](https://github.com/rybit/nats_logrus_hook) | Hook for logging to [NATS](https://nats.io) |
-| [Octokit](https://github.com/dorajistyle/logrus-octokit-hook) | Hook for logging to github via octokit |
-| [Papertrail](https://github.com/polds/logrus-papertrail-hook) | Send errors to the [Papertrail](https://papertrailapp.com) hosted logging service via UDP. |
-| [PostgreSQL](https://github.com/gemnasium/logrus-postgresql-hook) | Send logs to [PostgreSQL](http://postgresql.org) |
-| [Pushover](https://github.com/toorop/logrus_pushover) | Send error via [Pushover](https://pushover.net) |
-| [Raygun](https://github.com/squirkle/logrus-raygun-hook) | Hook for logging to [Raygun.io](http://raygun.io/) |
-| [Redis-Hook](https://github.com/rogierlommers/logrus-redis-hook) | Hook for logging to a ELK stack (through Redis) |
-| [Rollrus](https://github.com/heroku/rollrus) | Hook for sending errors to rollbar |
-| [Scribe](https://github.com/sagar8192/logrus-scribe-hook) | Hook for logging to [Scribe](https://github.com/facebookarchive/scribe)|
-| [Sentry](https://github.com/evalphobia/logrus_sentry) | Send errors to the Sentry error logging and aggregation service. |
-| [Slackrus](https://github.com/johntdyer/slackrus) | Hook for Slack chat. |
-| [Stackdriver](https://github.com/knq/sdhook) | Hook for logging to [Google Stackdriver](https://cloud.google.com/logging/) |
-| [Sumorus](https://github.com/doublefree/sumorus) | Hook for logging to [SumoLogic](https://www.sumologic.com/)|
-| [Syslog](https://github.com/sirupsen/logrus/blob/master/hooks/syslog/syslog.go) | Send errors to remote syslog server. Uses standard library `log/syslog` behind the scenes. |
-| [Syslog TLS](https://github.com/shinji62/logrus-syslog-ng) | Send errors to remote syslog server with TLS support. |
-| [TraceView](https://github.com/evalphobia/logrus_appneta) | Hook for logging to [AppNeta TraceView](https://www.appneta.com/products/traceview/) |
-| [Typetalk](https://github.com/dragon3/logrus-typetalk-hook) | Hook for logging to [Typetalk](https://www.typetalk.in/) |
-| [logz.io](https://github.com/ripcurld00d/logrus-logzio-hook) | Hook for logging to [logz.io](https://logz.io), a Log as a Service using Logstash |
-| [SQS-Hook](https://github.com/tsarpaul/logrus_sqs) | Hook for logging to [Amazon Simple Queue Service (SQS)](https://aws.amazon.com/sqs/) |
-
-#### Level logging
-
-Logrus has six logging levels: Debug, Info, Warning, Error, Fatal and Panic.
-
-```go
-log.Debug("Useful debugging information.")
-log.Info("Something noteworthy happened!")
-log.Warn("You should probably take a look at this.")
-log.Error("Something failed but I'm not quitting.")
-// Calls os.Exit(1) after logging
-log.Fatal("Bye.")
-// Calls panic() after logging
-log.Panic("I'm bailing.")
-```
-
-You can set the logging level on a `Logger`, then it will only log entries with
-that severity or anything above it:
-
-```go
-// Will log anything that is info or above (warn, error, fatal, panic). Default.
-log.SetLevel(log.InfoLevel)
-```
-
-It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose
-environment if your application has that.
-
-#### Entries
-
-Besides the fields added with `WithField` or `WithFields` some fields are
-automatically added to all logging events:
-
-1. `time`. The timestamp when the entry was created.
-2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after
- the `AddFields` call. E.g. `Failed to send event.`
-3. `level`. The logging level. E.g. `info`.
-
-#### Environments
-
-Logrus has no notion of environment.
-
-If you wish for hooks and formatters to only be used in specific environments,
-you should handle that yourself. For example, if your application has a global
-variable `Environment`, which is a string representation of the environment you
-could do:
-
-```go
-import (
- log "github.com/sirupsen/logrus"
-)
-
-init() {
- // do something here to set environment depending on an environment variable
- // or command-line flag
- if Environment == "production" {
- log.SetFormatter(&log.JSONFormatter{})
- } else {
- // The TextFormatter is default, you don't actually have to do this.
- log.SetFormatter(&log.TextFormatter{})
- }
-}
-```
-
-This configuration is how `logrus` was intended to be used, but JSON in
-production is mostly only useful if you do log aggregation with tools like
-Splunk or Logstash.
-
-#### Formatters
-
-The built-in logging formatters are:
-
-* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise
- without colors.
- * *Note:* to force colored output when there is no TTY, set the `ForceColors`
- field to `true`. To force no colored output even if there is a TTY set the
- `DisableColors` field to `true`. For Windows, see
- [github.com/mattn/go-colorable](https://github.com/mattn/go-colorable).
- * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#TextFormatter).
-* `logrus.JSONFormatter`. Logs fields as JSON.
- * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#JSONFormatter).
-
-Third party logging formatters:
-
-* [`FluentdFormatter`](https://github.com/joonix/log). Formats entries that can by parsed by Kubernetes and Google Container Engine.
-* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events.
-* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout.
-* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦.
-
-You can define your formatter by implementing the `Formatter` interface,
-requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a
-`Fields` type (`map[string]interface{}`) with all your fields as well as the
-default ones (see Entries section above):
-
-```go
-type MyJSONFormatter struct {
-}
-
-log.SetFormatter(new(MyJSONFormatter))
-
-func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) {
- // Note this doesn't include Time, Level and Message which are available on
- // the Entry. Consult `godoc` on information about those fields or read the
- // source of the official loggers.
- serialized, err := json.Marshal(entry.Data)
- if err != nil {
- return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
- }
- return append(serialized, '\n'), nil
-}
-```
-
-#### Logger as an `io.Writer`
-
-Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it.
-
-```go
-w := logger.Writer()
-defer w.Close()
-
-srv := http.Server{
- // create a stdlib log.Logger that writes to
- // logrus.Logger.
- ErrorLog: log.New(w, "", 0),
-}
-```
-
-Each line written to that writer will be printed the usual way, using formatters
-and hooks. The level for those entries is `info`.
-
-This means that we can override the standard library logger easily:
-
-```go
-logger := logrus.New()
-logger.Formatter = &logrus.JSONFormatter{}
-
-// Use logrus for standard log output
-// Note that `log` here references stdlib's log
-// Not logrus imported under the name `log`.
-log.SetOutput(logger.Writer())
-```
-
-#### Rotation
-
-Log rotation is not provided with Logrus. Log rotation should be done by an
-external program (like `logrotate(8)`) that can compress and delete old log
-entries. It should not be a feature of the application-level logger.
-
-#### Tools
-
-| Tool | Description |
-| ---- | ----------- |
-|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will generated with different config at different environment.|
-|[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper around Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) |
-
-#### Testing
-
-Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides:
-
-* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just add the `test` hook
-* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any):
-
-```go
-import(
- "github.com/sirupsen/logrus"
- "github.com/sirupsen/logrus/hooks/test"
- "github.com/stretchr/testify/assert"
- "testing"
-)
-
-func TestSomething(t*testing.T){
- logger, hook := test.NewNullLogger()
- logger.Error("Helloerror")
-
- assert.Equal(t, 1, len(hook.Entries))
- assert.Equal(t, logrus.ErrorLevel, hook.LastEntry().Level)
- assert.Equal(t, "Helloerror", hook.LastEntry().Message)
-
- hook.Reset()
- assert.Nil(t, hook.LastEntry())
-}
-```
-
-#### Fatal handlers
-
-Logrus can register one or more functions that will be called when any `fatal`
-level message is logged. The registered handlers will be executed before
-logrus performs a `os.Exit(1)`. This behavior may be helpful if callers need
-to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted.
-
-```
-...
-handler := func() {
- // gracefully shutdown something...
-}
-logrus.RegisterExitHandler(handler)
-...
-```
-
-#### Thread safety
-
-By default Logger is protected by mutex for concurrent writes, this mutex is invoked when calling hooks and writing logs.
-If you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking.
-
-Situation when locking is not needed includes:
-
-* You have no hooks registered, or hooks calling is already thread-safe.
-
-* Writing to logger.Out is already thread-safe, for example:
-
- 1) logger.Out is protected by locks.
-
- 2) logger.Out is a os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allow multi-thread/multi-process writing)
-
- (Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/)
diff --git a/vendor/github.com/sirupsen/logrus/alt_exit.go b/vendor/github.com/sirupsen/logrus/alt_exit.go
deleted file mode 100644
index 8af9063..0000000
--- a/vendor/github.com/sirupsen/logrus/alt_exit.go
+++ /dev/null
@@ -1,64 +0,0 @@
-package logrus
-
-// The following code was sourced and modified from the
-// https://github.com/tebeka/atexit package governed by the following license:
-//
-// Copyright (c) 2012 Miki Tebeka .
-//
-// 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.
-
-import (
- "fmt"
- "os"
-)
-
-var handlers = []func(){}
-
-func runHandler(handler func()) {
- defer func() {
- if err := recover(); err != nil {
- fmt.Fprintln(os.Stderr, "Error: Logrus exit handler error:", err)
- }
- }()
-
- handler()
-}
-
-func runHandlers() {
- for _, handler := range handlers {
- runHandler(handler)
- }
-}
-
-// Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code)
-func Exit(code int) {
- runHandlers()
- os.Exit(code)
-}
-
-// RegisterExitHandler adds a Logrus Exit handler, call logrus.Exit to invoke
-// all handlers. The handlers will also be invoked when any Fatal log entry is
-// made.
-//
-// This method is useful when a caller wishes to use logrus to log a fatal
-// message but also needs to gracefully shutdown. An example usecase could be
-// closing database connections, or sending a alert that the application is
-// closing.
-func RegisterExitHandler(handler func()) {
- handlers = append(handlers, handler)
-}
diff --git a/vendor/github.com/sirupsen/logrus/alt_exit_test.go b/vendor/github.com/sirupsen/logrus/alt_exit_test.go
deleted file mode 100644
index a08b1a8..0000000
--- a/vendor/github.com/sirupsen/logrus/alt_exit_test.go
+++ /dev/null
@@ -1,83 +0,0 @@
-package logrus
-
-import (
- "io/ioutil"
- "log"
- "os"
- "os/exec"
- "path/filepath"
- "testing"
- "time"
-)
-
-func TestRegister(t *testing.T) {
- current := len(handlers)
- RegisterExitHandler(func() {})
- if len(handlers) != current+1 {
- t.Fatalf("expected %d handlers, got %d", current+1, len(handlers))
- }
-}
-
-func TestHandler(t *testing.T) {
- tempDir, err := ioutil.TempDir("", "test_handler")
- if err != nil {
- log.Fatalf("can't create temp dir. %q", err)
- }
- defer os.RemoveAll(tempDir)
-
- gofile := filepath.Join(tempDir, "gofile.go")
- if err := ioutil.WriteFile(gofile, testprog, 0666); err != nil {
- t.Fatalf("can't create go file. %q", err)
- }
-
- outfile := filepath.Join(tempDir, "outfile.out")
- arg := time.Now().UTC().String()
- err = exec.Command("go", "run", gofile, outfile, arg).Run()
- if err == nil {
- t.Fatalf("completed normally, should have failed")
- }
-
- data, err := ioutil.ReadFile(outfile)
- if err != nil {
- t.Fatalf("can't read output file %s. %q", outfile, err)
- }
-
- if string(data) != arg {
- t.Fatalf("bad data. Expected %q, got %q", data, arg)
- }
-}
-
-var testprog = []byte(`
-// Test program for atexit, gets output file and data as arguments and writes
-// data to output file in atexit handler.
-package main
-
-import (
- "github.com/sirupsen/logrus"
- "flag"
- "fmt"
- "io/ioutil"
-)
-
-var outfile = ""
-var data = ""
-
-func handler() {
- ioutil.WriteFile(outfile, []byte(data), 0666)
-}
-
-func badHandler() {
- n := 0
- fmt.Println(1/n)
-}
-
-func main() {
- flag.Parse()
- outfile = flag.Arg(0)
- data = flag.Arg(1)
-
- logrus.RegisterExitHandler(handler)
- logrus.RegisterExitHandler(badHandler)
- logrus.Fatal("Bye bye")
-}
-`)
diff --git a/vendor/github.com/sirupsen/logrus/appveyor.yml b/vendor/github.com/sirupsen/logrus/appveyor.yml
deleted file mode 100644
index b4ffca2..0000000
--- a/vendor/github.com/sirupsen/logrus/appveyor.yml
+++ /dev/null
@@ -1,14 +0,0 @@
-version: "{build}"
-platform: x64
-clone_folder: c:\gopath\src\github.com\sirupsen\logrus
-environment:
- GOPATH: c:\gopath
-branches:
- only:
- - master
-install:
- - set PATH=%GOPATH%\bin;c:\go\bin;%PATH%
- - go version
-build_script:
- - go get -t
- - go test
diff --git a/vendor/github.com/sirupsen/logrus/doc.go b/vendor/github.com/sirupsen/logrus/doc.go
deleted file mode 100644
index da67aba..0000000
--- a/vendor/github.com/sirupsen/logrus/doc.go
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
-Package logrus is a structured logger for Go, completely API compatible with the standard library logger.
-
-
-The simplest way to use Logrus is simply the package-level exported logger:
-
- package main
-
- import (
- log "github.com/sirupsen/logrus"
- )
-
- func main() {
- log.WithFields(log.Fields{
- "animal": "walrus",
- "number": 1,
- "size": 10,
- }).Info("A walrus appears")
- }
-
-Output:
- time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10
-
-For a full guide visit https://github.com/sirupsen/logrus
-*/
-package logrus
diff --git a/vendor/github.com/sirupsen/logrus/entry.go b/vendor/github.com/sirupsen/logrus/entry.go
deleted file mode 100644
index 5bf582e..0000000
--- a/vendor/github.com/sirupsen/logrus/entry.go
+++ /dev/null
@@ -1,276 +0,0 @@
-package logrus
-
-import (
- "bytes"
- "fmt"
- "os"
- "sync"
- "time"
-)
-
-var bufferPool *sync.Pool
-
-func init() {
- bufferPool = &sync.Pool{
- New: func() interface{} {
- return new(bytes.Buffer)
- },
- }
-}
-
-// Defines the key when adding errors using WithError.
-var ErrorKey = "error"
-
-// An entry is the final or intermediate Logrus logging entry. It contains all
-// the fields passed with WithField{,s}. It's finally logged when Debug, Info,
-// Warn, Error, Fatal or Panic is called on it. These objects can be reused and
-// passed around as much as you wish to avoid field duplication.
-type Entry struct {
- Logger *Logger
-
- // Contains all the fields set by the user.
- Data Fields
-
- // Time at which the log entry was created
- Time time.Time
-
- // Level the log entry was logged at: Debug, Info, Warn, Error, Fatal or Panic
- // This field will be set on entry firing and the value will be equal to the one in Logger struct field.
- Level Level
-
- // Message passed to Debug, Info, Warn, Error, Fatal or Panic
- Message string
-
- // When formatter is called in entry.log(), an Buffer may be set to entry
- Buffer *bytes.Buffer
-}
-
-func NewEntry(logger *Logger) *Entry {
- return &Entry{
- Logger: logger,
- // Default is three fields, give a little extra room
- Data: make(Fields, 5),
- }
-}
-
-// Returns the string representation from the reader and ultimately the
-// formatter.
-func (entry *Entry) String() (string, error) {
- serialized, err := entry.Logger.Formatter.Format(entry)
- if err != nil {
- return "", err
- }
- str := string(serialized)
- return str, nil
-}
-
-// Add an error as single field (using the key defined in ErrorKey) to the Entry.
-func (entry *Entry) WithError(err error) *Entry {
- return entry.WithField(ErrorKey, err)
-}
-
-// Add a single field to the Entry.
-func (entry *Entry) WithField(key string, value interface{}) *Entry {
- return entry.WithFields(Fields{key: value})
-}
-
-// Add a map of fields to the Entry.
-func (entry *Entry) WithFields(fields Fields) *Entry {
- data := make(Fields, len(entry.Data)+len(fields))
- for k, v := range entry.Data {
- data[k] = v
- }
- for k, v := range fields {
- data[k] = v
- }
- return &Entry{Logger: entry.Logger, Data: data}
-}
-
-// This function is not declared with a pointer value because otherwise
-// race conditions will occur when using multiple goroutines
-func (entry Entry) log(level Level, msg string) {
- var buffer *bytes.Buffer
- entry.Time = time.Now()
- entry.Level = level
- entry.Message = msg
-
- if err := entry.Logger.Hooks.Fire(level, &entry); err != nil {
- entry.Logger.mu.Lock()
- fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err)
- entry.Logger.mu.Unlock()
- }
- buffer = bufferPool.Get().(*bytes.Buffer)
- buffer.Reset()
- defer bufferPool.Put(buffer)
- entry.Buffer = buffer
- serialized, err := entry.Logger.Formatter.Format(&entry)
- entry.Buffer = nil
- if err != nil {
- entry.Logger.mu.Lock()
- fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
- entry.Logger.mu.Unlock()
- } else {
- entry.Logger.mu.Lock()
- _, err = entry.Logger.Out.Write(serialized)
- if err != nil {
- fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
- }
- entry.Logger.mu.Unlock()
- }
-
- // To avoid Entry#log() returning a value that only would make sense for
- // panic() to use in Entry#Panic(), we avoid the allocation by checking
- // directly here.
- if level <= PanicLevel {
- panic(&entry)
- }
-}
-
-func (entry *Entry) Debug(args ...interface{}) {
- if entry.Logger.level() >= DebugLevel {
- entry.log(DebugLevel, fmt.Sprint(args...))
- }
-}
-
-func (entry *Entry) Print(args ...interface{}) {
- entry.Info(args...)
-}
-
-func (entry *Entry) Info(args ...interface{}) {
- if entry.Logger.level() >= InfoLevel {
- entry.log(InfoLevel, fmt.Sprint(args...))
- }
-}
-
-func (entry *Entry) Warn(args ...interface{}) {
- if entry.Logger.level() >= WarnLevel {
- entry.log(WarnLevel, fmt.Sprint(args...))
- }
-}
-
-func (entry *Entry) Warning(args ...interface{}) {
- entry.Warn(args...)
-}
-
-func (entry *Entry) Error(args ...interface{}) {
- if entry.Logger.level() >= ErrorLevel {
- entry.log(ErrorLevel, fmt.Sprint(args...))
- }
-}
-
-func (entry *Entry) Fatal(args ...interface{}) {
- if entry.Logger.level() >= FatalLevel {
- entry.log(FatalLevel, fmt.Sprint(args...))
- }
- Exit(1)
-}
-
-func (entry *Entry) Panic(args ...interface{}) {
- if entry.Logger.level() >= PanicLevel {
- entry.log(PanicLevel, fmt.Sprint(args...))
- }
- panic(fmt.Sprint(args...))
-}
-
-// Entry Printf family functions
-
-func (entry *Entry) Debugf(format string, args ...interface{}) {
- if entry.Logger.level() >= DebugLevel {
- entry.Debug(fmt.Sprintf(format, args...))
- }
-}
-
-func (entry *Entry) Infof(format string, args ...interface{}) {
- if entry.Logger.level() >= InfoLevel {
- entry.Info(fmt.Sprintf(format, args...))
- }
-}
-
-func (entry *Entry) Printf(format string, args ...interface{}) {
- entry.Infof(format, args...)
-}
-
-func (entry *Entry) Warnf(format string, args ...interface{}) {
- if entry.Logger.level() >= WarnLevel {
- entry.Warn(fmt.Sprintf(format, args...))
- }
-}
-
-func (entry *Entry) Warningf(format string, args ...interface{}) {
- entry.Warnf(format, args...)
-}
-
-func (entry *Entry) Errorf(format string, args ...interface{}) {
- if entry.Logger.level() >= ErrorLevel {
- entry.Error(fmt.Sprintf(format, args...))
- }
-}
-
-func (entry *Entry) Fatalf(format string, args ...interface{}) {
- if entry.Logger.level() >= FatalLevel {
- entry.Fatal(fmt.Sprintf(format, args...))
- }
- Exit(1)
-}
-
-func (entry *Entry) Panicf(format string, args ...interface{}) {
- if entry.Logger.level() >= PanicLevel {
- entry.Panic(fmt.Sprintf(format, args...))
- }
-}
-
-// Entry Println family functions
-
-func (entry *Entry) Debugln(args ...interface{}) {
- if entry.Logger.level() >= DebugLevel {
- entry.Debug(entry.sprintlnn(args...))
- }
-}
-
-func (entry *Entry) Infoln(args ...interface{}) {
- if entry.Logger.level() >= InfoLevel {
- entry.Info(entry.sprintlnn(args...))
- }
-}
-
-func (entry *Entry) Println(args ...interface{}) {
- entry.Infoln(args...)
-}
-
-func (entry *Entry) Warnln(args ...interface{}) {
- if entry.Logger.level() >= WarnLevel {
- entry.Warn(entry.sprintlnn(args...))
- }
-}
-
-func (entry *Entry) Warningln(args ...interface{}) {
- entry.Warnln(args...)
-}
-
-func (entry *Entry) Errorln(args ...interface{}) {
- if entry.Logger.level() >= ErrorLevel {
- entry.Error(entry.sprintlnn(args...))
- }
-}
-
-func (entry *Entry) Fatalln(args ...interface{}) {
- if entry.Logger.level() >= FatalLevel {
- entry.Fatal(entry.sprintlnn(args...))
- }
- Exit(1)
-}
-
-func (entry *Entry) Panicln(args ...interface{}) {
- if entry.Logger.level() >= PanicLevel {
- entry.Panic(entry.sprintlnn(args...))
- }
-}
-
-// Sprintlnn => Sprint no newline. This is to get the behavior of how
-// fmt.Sprintln where spaces are always added between operands, regardless of
-// their type. Instead of vendoring the Sprintln implementation to spare a
-// string allocation, we do the simplest thing.
-func (entry *Entry) sprintlnn(args ...interface{}) string {
- msg := fmt.Sprintln(args...)
- return msg[:len(msg)-1]
-}
diff --git a/vendor/github.com/sirupsen/logrus/entry_test.go b/vendor/github.com/sirupsen/logrus/entry_test.go
deleted file mode 100644
index 99c3b41..0000000
--- a/vendor/github.com/sirupsen/logrus/entry_test.go
+++ /dev/null
@@ -1,77 +0,0 @@
-package logrus
-
-import (
- "bytes"
- "fmt"
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-func TestEntryWithError(t *testing.T) {
-
- assert := assert.New(t)
-
- defer func() {
- ErrorKey = "error"
- }()
-
- err := fmt.Errorf("kaboom at layer %d", 4711)
-
- assert.Equal(err, WithError(err).Data["error"])
-
- logger := New()
- logger.Out = &bytes.Buffer{}
- entry := NewEntry(logger)
-
- assert.Equal(err, entry.WithError(err).Data["error"])
-
- ErrorKey = "err"
-
- assert.Equal(err, entry.WithError(err).Data["err"])
-
-}
-
-func TestEntryPanicln(t *testing.T) {
- errBoom := fmt.Errorf("boom time")
-
- defer func() {
- p := recover()
- assert.NotNil(t, p)
-
- switch pVal := p.(type) {
- case *Entry:
- assert.Equal(t, "kaboom", pVal.Message)
- assert.Equal(t, errBoom, pVal.Data["err"])
- default:
- t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal)
- }
- }()
-
- logger := New()
- logger.Out = &bytes.Buffer{}
- entry := NewEntry(logger)
- entry.WithField("err", errBoom).Panicln("kaboom")
-}
-
-func TestEntryPanicf(t *testing.T) {
- errBoom := fmt.Errorf("boom again")
-
- defer func() {
- p := recover()
- assert.NotNil(t, p)
-
- switch pVal := p.(type) {
- case *Entry:
- assert.Equal(t, "kaboom true", pVal.Message)
- assert.Equal(t, errBoom, pVal.Data["err"])
- default:
- t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal)
- }
- }()
-
- logger := New()
- logger.Out = &bytes.Buffer{}
- entry := NewEntry(logger)
- entry.WithField("err", errBoom).Panicf("kaboom %v", true)
-}
diff --git a/vendor/github.com/sirupsen/logrus/example_basic_test.go b/vendor/github.com/sirupsen/logrus/example_basic_test.go
deleted file mode 100644
index a2acf55..0000000
--- a/vendor/github.com/sirupsen/logrus/example_basic_test.go
+++ /dev/null
@@ -1,69 +0,0 @@
-package logrus_test
-
-import (
- "github.com/sirupsen/logrus"
- "os"
-)
-
-func Example_basic() {
- var log = logrus.New()
- log.Formatter = new(logrus.JSONFormatter)
- log.Formatter = new(logrus.TextFormatter) //default
- log.Formatter.(*logrus.TextFormatter).DisableTimestamp = true // remove timestamp from test output
- log.Level = logrus.DebugLevel
- log.Out = os.Stdout
-
- // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666)
- // if err == nil {
- // log.Out = file
- // } else {
- // log.Info("Failed to log to file, using default stderr")
- // }
-
- defer func() {
- err := recover()
- if err != nil {
- entry := err.(*logrus.Entry)
- log.WithFields(logrus.Fields{
- "omg": true,
- "err_animal": entry.Data["animal"],
- "err_size": entry.Data["size"],
- "err_level": entry.Level,
- "err_message": entry.Message,
- "number": 100,
- }).Error("The ice breaks!") // or use Fatal() to force the process to exit with a nonzero code
- }
- }()
-
- log.WithFields(logrus.Fields{
- "animal": "walrus",
- "number": 8,
- }).Debug("Started observing beach")
-
- log.WithFields(logrus.Fields{
- "animal": "walrus",
- "size": 10,
- }).Info("A group of walrus emerges from the ocean")
-
- log.WithFields(logrus.Fields{
- "omg": true,
- "number": 122,
- }).Warn("The group's number increased tremendously!")
-
- log.WithFields(logrus.Fields{
- "temperature": -4,
- }).Debug("Temperature changes")
-
- log.WithFields(logrus.Fields{
- "animal": "orca",
- "size": 9009,
- }).Panic("It's over 9000!")
-
- // Output:
- // level=debug msg="Started observing beach" animal=walrus number=8
- // level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
- // level=warning msg="The group's number increased tremendously!" number=122 omg=true
- // level=debug msg="Temperature changes" temperature=-4
- // level=panic msg="It's over 9000!" animal=orca size=9009
- // level=error msg="The ice breaks!" err_animal=orca err_level=panic err_message="It's over 9000!" err_size=9009 number=100 omg=true
-}
diff --git a/vendor/github.com/sirupsen/logrus/example_hook_test.go b/vendor/github.com/sirupsen/logrus/example_hook_test.go
deleted file mode 100644
index d4ddffc..0000000
--- a/vendor/github.com/sirupsen/logrus/example_hook_test.go
+++ /dev/null
@@ -1,35 +0,0 @@
-package logrus_test
-
-import (
- "github.com/sirupsen/logrus"
- "gopkg.in/gemnasium/logrus-airbrake-hook.v2"
- "os"
-)
-
-func Example_hook() {
- var log = logrus.New()
- log.Formatter = new(logrus.TextFormatter) // default
- log.Formatter.(*logrus.TextFormatter).DisableTimestamp = true // remove timestamp from test output
- log.Hooks.Add(airbrake.NewHook(123, "xyz", "development"))
- log.Out = os.Stdout
-
- log.WithFields(logrus.Fields{
- "animal": "walrus",
- "size": 10,
- }).Info("A group of walrus emerges from the ocean")
-
- log.WithFields(logrus.Fields{
- "omg": true,
- "number": 122,
- }).Warn("The group's number increased tremendously!")
-
- log.WithFields(logrus.Fields{
- "omg": true,
- "number": 100,
- }).Error("The ice breaks!")
-
- // Output:
- // level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
- // level=warning msg="The group's number increased tremendously!" number=122 omg=true
- // level=error msg="The ice breaks!" number=100 omg=true
-}
diff --git a/vendor/github.com/sirupsen/logrus/exported.go b/vendor/github.com/sirupsen/logrus/exported.go
deleted file mode 100644
index 013183e..0000000
--- a/vendor/github.com/sirupsen/logrus/exported.go
+++ /dev/null
@@ -1,193 +0,0 @@
-package logrus
-
-import (
- "io"
-)
-
-var (
- // std is the name of the standard logger in stdlib `log`
- std = New()
-)
-
-func StandardLogger() *Logger {
- return std
-}
-
-// SetOutput sets the standard logger output.
-func SetOutput(out io.Writer) {
- std.mu.Lock()
- defer std.mu.Unlock()
- std.Out = out
-}
-
-// SetFormatter sets the standard logger formatter.
-func SetFormatter(formatter Formatter) {
- std.mu.Lock()
- defer std.mu.Unlock()
- std.Formatter = formatter
-}
-
-// SetLevel sets the standard logger level.
-func SetLevel(level Level) {
- std.mu.Lock()
- defer std.mu.Unlock()
- std.SetLevel(level)
-}
-
-// GetLevel returns the standard logger level.
-func GetLevel() Level {
- std.mu.Lock()
- defer std.mu.Unlock()
- return std.level()
-}
-
-// AddHook adds a hook to the standard logger hooks.
-func AddHook(hook Hook) {
- std.mu.Lock()
- defer std.mu.Unlock()
- std.Hooks.Add(hook)
-}
-
-// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key.
-func WithError(err error) *Entry {
- return std.WithField(ErrorKey, err)
-}
-
-// WithField creates an entry from the standard logger and adds a field to
-// it. If you want multiple fields, use `WithFields`.
-//
-// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
-// or Panic on the Entry it returns.
-func WithField(key string, value interface{}) *Entry {
- return std.WithField(key, value)
-}
-
-// WithFields creates an entry from the standard logger and adds multiple
-// fields to it. This is simply a helper for `WithField`, invoking it
-// once for each field.
-//
-// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
-// or Panic on the Entry it returns.
-func WithFields(fields Fields) *Entry {
- return std.WithFields(fields)
-}
-
-// Debug logs a message at level Debug on the standard logger.
-func Debug(args ...interface{}) {
- std.Debug(args...)
-}
-
-// Print logs a message at level Info on the standard logger.
-func Print(args ...interface{}) {
- std.Print(args...)
-}
-
-// Info logs a message at level Info on the standard logger.
-func Info(args ...interface{}) {
- std.Info(args...)
-}
-
-// Warn logs a message at level Warn on the standard logger.
-func Warn(args ...interface{}) {
- std.Warn(args...)
-}
-
-// Warning logs a message at level Warn on the standard logger.
-func Warning(args ...interface{}) {
- std.Warning(args...)
-}
-
-// Error logs a message at level Error on the standard logger.
-func Error(args ...interface{}) {
- std.Error(args...)
-}
-
-// Panic logs a message at level Panic on the standard logger.
-func Panic(args ...interface{}) {
- std.Panic(args...)
-}
-
-// Fatal logs a message at level Fatal on the standard logger.
-func Fatal(args ...interface{}) {
- std.Fatal(args...)
-}
-
-// Debugf logs a message at level Debug on the standard logger.
-func Debugf(format string, args ...interface{}) {
- std.Debugf(format, args...)
-}
-
-// Printf logs a message at level Info on the standard logger.
-func Printf(format string, args ...interface{}) {
- std.Printf(format, args...)
-}
-
-// Infof logs a message at level Info on the standard logger.
-func Infof(format string, args ...interface{}) {
- std.Infof(format, args...)
-}
-
-// Warnf logs a message at level Warn on the standard logger.
-func Warnf(format string, args ...interface{}) {
- std.Warnf(format, args...)
-}
-
-// Warningf logs a message at level Warn on the standard logger.
-func Warningf(format string, args ...interface{}) {
- std.Warningf(format, args...)
-}
-
-// Errorf logs a message at level Error on the standard logger.
-func Errorf(format string, args ...interface{}) {
- std.Errorf(format, args...)
-}
-
-// Panicf logs a message at level Panic on the standard logger.
-func Panicf(format string, args ...interface{}) {
- std.Panicf(format, args...)
-}
-
-// Fatalf logs a message at level Fatal on the standard logger.
-func Fatalf(format string, args ...interface{}) {
- std.Fatalf(format, args...)
-}
-
-// Debugln logs a message at level Debug on the standard logger.
-func Debugln(args ...interface{}) {
- std.Debugln(args...)
-}
-
-// Println logs a message at level Info on the standard logger.
-func Println(args ...interface{}) {
- std.Println(args...)
-}
-
-// Infoln logs a message at level Info on the standard logger.
-func Infoln(args ...interface{}) {
- std.Infoln(args...)
-}
-
-// Warnln logs a message at level Warn on the standard logger.
-func Warnln(args ...interface{}) {
- std.Warnln(args...)
-}
-
-// Warningln logs a message at level Warn on the standard logger.
-func Warningln(args ...interface{}) {
- std.Warningln(args...)
-}
-
-// Errorln logs a message at level Error on the standard logger.
-func Errorln(args ...interface{}) {
- std.Errorln(args...)
-}
-
-// Panicln logs a message at level Panic on the standard logger.
-func Panicln(args ...interface{}) {
- std.Panicln(args...)
-}
-
-// Fatalln logs a message at level Fatal on the standard logger.
-func Fatalln(args ...interface{}) {
- std.Fatalln(args...)
-}
diff --git a/vendor/github.com/sirupsen/logrus/formatter.go b/vendor/github.com/sirupsen/logrus/formatter.go
deleted file mode 100644
index b183ff5..0000000
--- a/vendor/github.com/sirupsen/logrus/formatter.go
+++ /dev/null
@@ -1,45 +0,0 @@
-package logrus
-
-import "time"
-
-const defaultTimestampFormat = time.RFC3339
-
-// The Formatter interface is used to implement a custom Formatter. It takes an
-// `Entry`. It exposes all the fields, including the default ones:
-//
-// * `entry.Data["msg"]`. The message passed from Info, Warn, Error ..
-// * `entry.Data["time"]`. The timestamp.
-// * `entry.Data["level"]. The level the entry was logged at.
-//
-// Any additional fields added with `WithField` or `WithFields` are also in
-// `entry.Data`. Format is expected to return an array of bytes which are then
-// logged to `logger.Out`.
-type Formatter interface {
- Format(*Entry) ([]byte, error)
-}
-
-// This is to not silently overwrite `time`, `msg` and `level` fields when
-// dumping it. If this code wasn't there doing:
-//
-// logrus.WithField("level", 1).Info("hello")
-//
-// Would just silently drop the user provided level. Instead with this code
-// it'll logged as:
-//
-// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."}
-//
-// It's not exported because it's still using Data in an opinionated way. It's to
-// avoid code duplication between the two default formatters.
-func prefixFieldClashes(data Fields) {
- if t, ok := data["time"]; ok {
- data["fields.time"] = t
- }
-
- if m, ok := data["msg"]; ok {
- data["fields.msg"] = m
- }
-
- if l, ok := data["level"]; ok {
- data["fields.level"] = l
- }
-}
diff --git a/vendor/github.com/sirupsen/logrus/formatter_bench_test.go b/vendor/github.com/sirupsen/logrus/formatter_bench_test.go
deleted file mode 100644
index d948158..0000000
--- a/vendor/github.com/sirupsen/logrus/formatter_bench_test.go
+++ /dev/null
@@ -1,101 +0,0 @@
-package logrus
-
-import (
- "fmt"
- "testing"
- "time"
-)
-
-// smallFields is a small size data set for benchmarking
-var smallFields = Fields{
- "foo": "bar",
- "baz": "qux",
- "one": "two",
- "three": "four",
-}
-
-// largeFields is a large size data set for benchmarking
-var largeFields = Fields{
- "foo": "bar",
- "baz": "qux",
- "one": "two",
- "three": "four",
- "five": "six",
- "seven": "eight",
- "nine": "ten",
- "eleven": "twelve",
- "thirteen": "fourteen",
- "fifteen": "sixteen",
- "seventeen": "eighteen",
- "nineteen": "twenty",
- "a": "b",
- "c": "d",
- "e": "f",
- "g": "h",
- "i": "j",
- "k": "l",
- "m": "n",
- "o": "p",
- "q": "r",
- "s": "t",
- "u": "v",
- "w": "x",
- "y": "z",
- "this": "will",
- "make": "thirty",
- "entries": "yeah",
-}
-
-var errorFields = Fields{
- "foo": fmt.Errorf("bar"),
- "baz": fmt.Errorf("qux"),
-}
-
-func BenchmarkErrorTextFormatter(b *testing.B) {
- doBenchmark(b, &TextFormatter{DisableColors: true}, errorFields)
-}
-
-func BenchmarkSmallTextFormatter(b *testing.B) {
- doBenchmark(b, &TextFormatter{DisableColors: true}, smallFields)
-}
-
-func BenchmarkLargeTextFormatter(b *testing.B) {
- doBenchmark(b, &TextFormatter{DisableColors: true}, largeFields)
-}
-
-func BenchmarkSmallColoredTextFormatter(b *testing.B) {
- doBenchmark(b, &TextFormatter{ForceColors: true}, smallFields)
-}
-
-func BenchmarkLargeColoredTextFormatter(b *testing.B) {
- doBenchmark(b, &TextFormatter{ForceColors: true}, largeFields)
-}
-
-func BenchmarkSmallJSONFormatter(b *testing.B) {
- doBenchmark(b, &JSONFormatter{}, smallFields)
-}
-
-func BenchmarkLargeJSONFormatter(b *testing.B) {
- doBenchmark(b, &JSONFormatter{}, largeFields)
-}
-
-func doBenchmark(b *testing.B, formatter Formatter, fields Fields) {
- logger := New()
-
- entry := &Entry{
- Time: time.Time{},
- Level: InfoLevel,
- Message: "message",
- Data: fields,
- Logger: logger,
- }
- var d []byte
- var err error
- for i := 0; i < b.N; i++ {
- d, err = formatter.Format(entry)
- if err != nil {
- b.Fatal(err)
- }
- b.SetBytes(int64(len(d)))
- }
-}
diff --git a/vendor/github.com/sirupsen/logrus/hook_test.go b/vendor/github.com/sirupsen/logrus/hook_test.go
deleted file mode 100644
index 13f34cb..0000000
--- a/vendor/github.com/sirupsen/logrus/hook_test.go
+++ /dev/null
@@ -1,122 +0,0 @@
-package logrus
-
-import (
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-type TestHook struct {
- Fired bool
-}
-
-func (hook *TestHook) Fire(entry *Entry) error {
- hook.Fired = true
- return nil
-}
-
-func (hook *TestHook) Levels() []Level {
- return []Level{
- DebugLevel,
- InfoLevel,
- WarnLevel,
- ErrorLevel,
- FatalLevel,
- PanicLevel,
- }
-}
-
-func TestHookFires(t *testing.T) {
- hook := new(TestHook)
-
- LogAndAssertJSON(t, func(log *Logger) {
- log.Hooks.Add(hook)
- assert.Equal(t, hook.Fired, false)
-
- log.Print("test")
- }, func(fields Fields) {
- assert.Equal(t, hook.Fired, true)
- })
-}
-
-type ModifyHook struct {
-}
-
-func (hook *ModifyHook) Fire(entry *Entry) error {
- entry.Data["wow"] = "whale"
- return nil
-}
-
-func (hook *ModifyHook) Levels() []Level {
- return []Level{
- DebugLevel,
- InfoLevel,
- WarnLevel,
- ErrorLevel,
- FatalLevel,
- PanicLevel,
- }
-}
-
-func TestHookCanModifyEntry(t *testing.T) {
- hook := new(ModifyHook)
-
- LogAndAssertJSON(t, func(log *Logger) {
- log.Hooks.Add(hook)
- log.WithField("wow", "elephant").Print("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["wow"], "whale")
- })
-}
-
-func TestCanFireMultipleHooks(t *testing.T) {
- hook1 := new(ModifyHook)
- hook2 := new(TestHook)
-
- LogAndAssertJSON(t, func(log *Logger) {
- log.Hooks.Add(hook1)
- log.Hooks.Add(hook2)
-
- log.WithField("wow", "elephant").Print("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["wow"], "whale")
- assert.Equal(t, hook2.Fired, true)
- })
-}
-
-type ErrorHook struct {
- Fired bool
-}
-
-func (hook *ErrorHook) Fire(entry *Entry) error {
- hook.Fired = true
- return nil
-}
-
-func (hook *ErrorHook) Levels() []Level {
- return []Level{
- ErrorLevel,
- }
-}
-
-func TestErrorHookShouldntFireOnInfo(t *testing.T) {
- hook := new(ErrorHook)
-
- LogAndAssertJSON(t, func(log *Logger) {
- log.Hooks.Add(hook)
- log.Info("test")
- }, func(fields Fields) {
- assert.Equal(t, hook.Fired, false)
- })
-}
-
-func TestErrorHookShouldFireOnError(t *testing.T) {
- hook := new(ErrorHook)
-
- LogAndAssertJSON(t, func(log *Logger) {
- log.Hooks.Add(hook)
- log.Error("test")
- }, func(fields Fields) {
- assert.Equal(t, hook.Fired, true)
- })
-}
diff --git a/vendor/github.com/sirupsen/logrus/hooks.go b/vendor/github.com/sirupsen/logrus/hooks.go
deleted file mode 100644
index 3f151cd..0000000
--- a/vendor/github.com/sirupsen/logrus/hooks.go
+++ /dev/null
@@ -1,34 +0,0 @@
-package logrus
-
-// A hook to be fired when logging on the logging levels returned from
-// `Levels()` on your implementation of the interface. Note that this is not
-// fired in a goroutine or a channel with workers, you should handle such
-// functionality yourself if your call is non-blocking and you don't wish for
-// the logging calls for levels returned from `Levels()` to block.
-type Hook interface {
- Levels() []Level
- Fire(*Entry) error
-}
-
-// Internal type for storing the hooks on a logger instance.
-type LevelHooks map[Level][]Hook
-
-// Add a hook to an instance of logger. This is called with
-// `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface.
-func (hooks LevelHooks) Add(hook Hook) {
- for _, level := range hook.Levels() {
- hooks[level] = append(hooks[level], hook)
- }
-}
-
-// Fire all the hooks for the passed level. Used by `entry.log` to fire
-// appropriate hooks for a log entry.
-func (hooks LevelHooks) Fire(level Level, entry *Entry) error {
- for _, hook := range hooks[level] {
- if err := hook.Fire(entry); err != nil {
- return err
- }
- }
-
- return nil
-}
diff --git a/vendor/github.com/sirupsen/logrus/json_formatter.go b/vendor/github.com/sirupsen/logrus/json_formatter.go
deleted file mode 100644
index fb01c1b..0000000
--- a/vendor/github.com/sirupsen/logrus/json_formatter.go
+++ /dev/null
@@ -1,79 +0,0 @@
-package logrus
-
-import (
- "encoding/json"
- "fmt"
-)
-
-type fieldKey string
-
-// FieldMap allows customization of the key names for default fields.
-type FieldMap map[fieldKey]string
-
-// Default key names for the default fields
-const (
- FieldKeyMsg = "msg"
- FieldKeyLevel = "level"
- FieldKeyTime = "time"
-)
-
-func (f FieldMap) resolve(key fieldKey) string {
- if k, ok := f[key]; ok {
- return k
- }
-
- return string(key)
-}
-
-// JSONFormatter formats logs into parsable json
-type JSONFormatter struct {
- // TimestampFormat sets the format used for marshaling timestamps.
- TimestampFormat string
-
- // DisableTimestamp allows disabling automatic timestamps in output
- DisableTimestamp bool
-
- // FieldMap allows users to customize the names of keys for default fields.
- // As an example:
- // formatter := &JSONFormatter{
- // FieldMap: FieldMap{
- // FieldKeyTime: "@timestamp",
- // FieldKeyLevel: "@level",
- // FieldKeyMsg: "@message",
- // },
- // }
- FieldMap FieldMap
-}
-
-// Format renders a single log entry
-func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
- data := make(Fields, len(entry.Data)+3)
- for k, v := range entry.Data {
- switch v := v.(type) {
- case error:
- // Otherwise errors are ignored by `encoding/json`
- // https://github.com/sirupsen/logrus/issues/137
- data[k] = v.Error()
- default:
- data[k] = v
- }
- }
- prefixFieldClashes(data)
-
- timestampFormat := f.TimestampFormat
- if timestampFormat == "" {
- timestampFormat = defaultTimestampFormat
- }
-
- if !f.DisableTimestamp {
- data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat)
- }
- data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message
- data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String()
-
- serialized, err := json.Marshal(data)
- if err != nil {
- return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
- }
- return append(serialized, '\n'), nil
-}
diff --git a/vendor/github.com/sirupsen/logrus/json_formatter_test.go b/vendor/github.com/sirupsen/logrus/json_formatter_test.go
deleted file mode 100644
index 51093a7..0000000
--- a/vendor/github.com/sirupsen/logrus/json_formatter_test.go
+++ /dev/null
@@ -1,199 +0,0 @@
-package logrus
-
-import (
- "encoding/json"
- "errors"
- "strings"
- "testing"
-)
-
-func TestErrorNotLost(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("error", errors.New("wild walrus")))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
-
- entry := make(map[string]interface{})
- err = json.Unmarshal(b, &entry)
- if err != nil {
- t.Fatal("Unable to unmarshal formatted entry: ", err)
- }
-
- if entry["error"] != "wild walrus" {
- t.Fatal("Error field not set")
- }
-}
-
-func TestErrorNotLostOnFieldNotNamedError(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("omg", errors.New("wild walrus")))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
-
- entry := make(map[string]interface{})
- err = json.Unmarshal(b, &entry)
- if err != nil {
- t.Fatal("Unable to unmarshal formatted entry: ", err)
- }
-
- if entry["omg"] != "wild walrus" {
- t.Fatal("Error field not set")
- }
-}
-
-func TestFieldClashWithTime(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("time", "right now!"))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
-
- entry := make(map[string]interface{})
- err = json.Unmarshal(b, &entry)
- if err != nil {
- t.Fatal("Unable to unmarshal formatted entry: ", err)
- }
-
- if entry["fields.time"] != "right now!" {
- t.Fatal("fields.time not set to original time field")
- }
-
- if entry["time"] != "0001-01-01T00:00:00Z" {
- t.Fatal("time field not set to current time, was: ", entry["time"])
- }
-}
-
-func TestFieldClashWithMsg(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("msg", "something"))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
-
- entry := make(map[string]interface{})
- err = json.Unmarshal(b, &entry)
- if err != nil {
- t.Fatal("Unable to unmarshal formatted entry: ", err)
- }
-
- if entry["fields.msg"] != "something" {
- t.Fatal("fields.msg not set to original msg field")
- }
-}
-
-func TestFieldClashWithLevel(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("level", "something"))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
-
- entry := make(map[string]interface{})
- err = json.Unmarshal(b, &entry)
- if err != nil {
- t.Fatal("Unable to unmarshal formatted entry: ", err)
- }
-
- if entry["fields.level"] != "something" {
- t.Fatal("fields.level not set to original level field")
- }
-}
-
-func TestJSONEntryEndsWithNewline(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("level", "something"))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
-
- if b[len(b)-1] != '\n' {
- t.Fatal("Expected JSON log entry to end with a newline")
- }
-}
-
-func TestJSONMessageKey(t *testing.T) {
- formatter := &JSONFormatter{
- FieldMap: FieldMap{
- FieldKeyMsg: "message",
- },
- }
-
- b, err := formatter.Format(&Entry{Message: "oh hai"})
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
- s := string(b)
- if !(strings.Contains(s, "message") && strings.Contains(s, "oh hai")) {
- t.Fatal("Expected JSON to format message key")
- }
-}
-
-func TestJSONLevelKey(t *testing.T) {
- formatter := &JSONFormatter{
- FieldMap: FieldMap{
- FieldKeyLevel: "somelevel",
- },
- }
-
- b, err := formatter.Format(WithField("level", "something"))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
- s := string(b)
- if !strings.Contains(s, "somelevel") {
- t.Fatal("Expected JSON to format level key")
- }
-}
-
-func TestJSONTimeKey(t *testing.T) {
- formatter := &JSONFormatter{
- FieldMap: FieldMap{
- FieldKeyTime: "timeywimey",
- },
- }
-
- b, err := formatter.Format(WithField("level", "something"))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
- s := string(b)
- if !strings.Contains(s, "timeywimey") {
- t.Fatal("Expected JSON to format time key")
- }
-}
-
-func TestJSONDisableTimestamp(t *testing.T) {
- formatter := &JSONFormatter{
- DisableTimestamp: true,
- }
-
- b, err := formatter.Format(WithField("level", "something"))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
- s := string(b)
- if strings.Contains(s, FieldKeyTime) {
- t.Error("Did not prevent timestamp", s)
- }
-}
-
-func TestJSONEnableTimestamp(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("level", "something"))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
- s := string(b)
- if !strings.Contains(s, FieldKeyTime) {
- t.Error("Timestamp not present", s)
- }
-}
diff --git a/vendor/github.com/sirupsen/logrus/logger.go b/vendor/github.com/sirupsen/logrus/logger.go
deleted file mode 100644
index 2acab05..0000000
--- a/vendor/github.com/sirupsen/logrus/logger.go
+++ /dev/null
@@ -1,317 +0,0 @@
-package logrus
-
-import (
- "io"
- "os"
- "sync"
- "sync/atomic"
-)
-
-type Logger struct {
- // The logs are `io.Copy`'d to this in a mutex. It's common to set this to a
- // file, or leave it default which is `os.Stderr`. You can also set this to
- // something more adventorous, such as logging to Kafka.
- Out io.Writer
- // Hooks for the logger instance. These allow firing events based on logging
- // levels and log entries. For example, to send errors to an error tracking
- // service, log to StatsD or dump the core on fatal errors.
- Hooks LevelHooks
- // All log entries pass through the formatter before logged to Out. The
- // included formatters are `TextFormatter` and `JSONFormatter` for which
- // TextFormatter is the default. In development (when a TTY is attached) it
- // logs with colors, but to a file it wouldn't. You can easily implement your
- // own that implements the `Formatter` interface, see the `README` or included
- // formatters for examples.
- Formatter Formatter
- // The logging level the logger should log at. This is typically (and defaults
- // to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be
- // logged.
- Level Level
- // Used to sync writing to the log. Locking is enabled by Default
- mu MutexWrap
- // Reusable empty entry
- entryPool sync.Pool
-}
-
-type MutexWrap struct {
- lock sync.Mutex
- disabled bool
-}
-
-func (mw *MutexWrap) Lock() {
- if !mw.disabled {
- mw.lock.Lock()
- }
-}
-
-func (mw *MutexWrap) Unlock() {
- if !mw.disabled {
- mw.lock.Unlock()
- }
-}
-
-func (mw *MutexWrap) Disable() {
- mw.disabled = true
-}
-
-// Creates a new logger. Configuration should be set by changing `Formatter`,
-// `Out` and `Hooks` directly on the default logger instance. You can also just
-// instantiate your own:
-//
-// var log = &Logger{
-// Out: os.Stderr,
-// Formatter: new(JSONFormatter),
-// Hooks: make(LevelHooks),
-// Level: logrus.DebugLevel,
-// }
-//
-// It's recommended to make this a global instance called `log`.
-func New() *Logger {
- return &Logger{
- Out: os.Stderr,
- Formatter: new(TextFormatter),
- Hooks: make(LevelHooks),
- Level: InfoLevel,
- }
-}
-
-func (logger *Logger) newEntry() *Entry {
- entry, ok := logger.entryPool.Get().(*Entry)
- if ok {
- return entry
- }
- return NewEntry(logger)
-}
-
-func (logger *Logger) releaseEntry(entry *Entry) {
- logger.entryPool.Put(entry)
-}
-
-// Adds a field to the log entry, note that it doesn't log until you call
-// Debug, Print, Info, Warn, Fatal or Panic. It only creates a log entry.
-// If you want multiple fields, use `WithFields`.
-func (logger *Logger) WithField(key string, value interface{}) *Entry {
- entry := logger.newEntry()
- defer logger.releaseEntry(entry)
- return entry.WithField(key, value)
-}
-
-// Adds a struct of fields to the log entry. All it does is call `WithField` for
-// each `Field`.
-func (logger *Logger) WithFields(fields Fields) *Entry {
- entry := logger.newEntry()
- defer logger.releaseEntry(entry)
- return entry.WithFields(fields)
-}
-
-// Add an error as single field to the log entry. All it does is call
-// `WithError` for the given `error`.
-func (logger *Logger) WithError(err error) *Entry {
- entry := logger.newEntry()
- defer logger.releaseEntry(entry)
- return entry.WithError(err)
-}
-
-func (logger *Logger) Debugf(format string, args ...interface{}) {
- if logger.level() >= DebugLevel {
- entry := logger.newEntry()
- entry.Debugf(format, args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Infof(format string, args ...interface{}) {
- if logger.level() >= InfoLevel {
- entry := logger.newEntry()
- entry.Infof(format, args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Printf(format string, args ...interface{}) {
- entry := logger.newEntry()
- entry.Printf(format, args...)
- logger.releaseEntry(entry)
-}
-
-func (logger *Logger) Warnf(format string, args ...interface{}) {
- if logger.level() >= WarnLevel {
- entry := logger.newEntry()
- entry.Warnf(format, args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Warningf(format string, args ...interface{}) {
- if logger.level() >= WarnLevel {
- entry := logger.newEntry()
- entry.Warnf(format, args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Errorf(format string, args ...interface{}) {
- if logger.level() >= ErrorLevel {
- entry := logger.newEntry()
- entry.Errorf(format, args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Fatalf(format string, args ...interface{}) {
- if logger.level() >= FatalLevel {
- entry := logger.newEntry()
- entry.Fatalf(format, args...)
- logger.releaseEntry(entry)
- }
- Exit(1)
-}
-
-func (logger *Logger) Panicf(format string, args ...interface{}) {
- if logger.level() >= PanicLevel {
- entry := logger.newEntry()
- entry.Panicf(format, args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Debug(args ...interface{}) {
- if logger.level() >= DebugLevel {
- entry := logger.newEntry()
- entry.Debug(args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Info(args ...interface{}) {
- if logger.level() >= InfoLevel {
- entry := logger.newEntry()
- entry.Info(args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Print(args ...interface{}) {
- entry := logger.newEntry()
- entry.Info(args...)
- logger.releaseEntry(entry)
-}
-
-func (logger *Logger) Warn(args ...interface{}) {
- if logger.level() >= WarnLevel {
- entry := logger.newEntry()
- entry.Warn(args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Warning(args ...interface{}) {
- if logger.level() >= WarnLevel {
- entry := logger.newEntry()
- entry.Warn(args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Error(args ...interface{}) {
- if logger.level() >= ErrorLevel {
- entry := logger.newEntry()
- entry.Error(args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Fatal(args ...interface{}) {
- if logger.level() >= FatalLevel {
- entry := logger.newEntry()
- entry.Fatal(args...)
- logger.releaseEntry(entry)
- }
- Exit(1)
-}
-
-func (logger *Logger) Panic(args ...interface{}) {
- if logger.level() >= PanicLevel {
- entry := logger.newEntry()
- entry.Panic(args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Debugln(args ...interface{}) {
- if logger.level() >= DebugLevel {
- entry := logger.newEntry()
- entry.Debugln(args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Infoln(args ...interface{}) {
- if logger.level() >= InfoLevel {
- entry := logger.newEntry()
- entry.Infoln(args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Println(args ...interface{}) {
- entry := logger.newEntry()
- entry.Println(args...)
- logger.releaseEntry(entry)
-}
-
-func (logger *Logger) Warnln(args ...interface{}) {
- if logger.level() >= WarnLevel {
- entry := logger.newEntry()
- entry.Warnln(args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Warningln(args ...interface{}) {
- if logger.level() >= WarnLevel {
- entry := logger.newEntry()
- entry.Warnln(args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Errorln(args ...interface{}) {
- if logger.level() >= ErrorLevel {
- entry := logger.newEntry()
- entry.Errorln(args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Fatalln(args ...interface{}) {
- if logger.level() >= FatalLevel {
- entry := logger.newEntry()
- entry.Fatalln(args...)
- logger.releaseEntry(entry)
- }
- Exit(1)
-}
-
-func (logger *Logger) Panicln(args ...interface{}) {
- if logger.level() >= PanicLevel {
- entry := logger.newEntry()
- entry.Panicln(args...)
- logger.releaseEntry(entry)
- }
-}
-
-//When file is opened with appending mode, it's safe to
-//write concurrently to a file (within 4k message on Linux).
-//In these cases user can choose to disable the lock.
-func (logger *Logger) SetNoLock() {
- logger.mu.Disable()
-}
-
-func (logger *Logger) level() Level {
- return Level(atomic.LoadUint32((*uint32)(&logger.Level)))
-}
-
-func (logger *Logger) SetLevel(level Level) {
- atomic.StoreUint32((*uint32)(&logger.Level), uint32(level))
-}
diff --git a/vendor/github.com/sirupsen/logrus/logger_bench_test.go b/vendor/github.com/sirupsen/logrus/logger_bench_test.go
deleted file mode 100644
index dd23a35..0000000
--- a/vendor/github.com/sirupsen/logrus/logger_bench_test.go
+++ /dev/null
@@ -1,61 +0,0 @@
-package logrus
-
-import (
- "os"
- "testing"
-)
-
-// smallFields is a small size data set for benchmarking
-var loggerFields = Fields{
- "foo": "bar",
- "baz": "qux",
- "one": "two",
- "three": "four",
-}
-
-func BenchmarkDummyLogger(b *testing.B) {
- nullf, err := os.OpenFile("/dev/null", os.O_WRONLY, 0666)
- if err != nil {
- b.Fatalf("%v", err)
- }
- defer nullf.Close()
- doLoggerBenchmark(b, nullf, &TextFormatter{DisableColors: true}, smallFields)
-}
-
-func BenchmarkDummyLoggerNoLock(b *testing.B) {
- nullf, err := os.OpenFile("/dev/null", os.O_WRONLY|os.O_APPEND, 0666)
- if err != nil {
- b.Fatalf("%v", err)
- }
- defer nullf.Close()
- doLoggerBenchmarkNoLock(b, nullf, &TextFormatter{DisableColors: true}, smallFields)
-}
-
-func doLoggerBenchmark(b *testing.B, out *os.File, formatter Formatter, fields Fields) {
- logger := Logger{
- Out: out,
- Level: InfoLevel,
- Formatter: formatter,
- }
- entry := logger.WithFields(fields)
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- entry.Info("aaa")
- }
- })
-}
-
-func doLoggerBenchmarkNoLock(b *testing.B, out *os.File, formatter Formatter, fields Fields) {
- logger := Logger{
- Out: out,
- Level: InfoLevel,
- Formatter: formatter,
- }
- logger.SetNoLock()
- entry := logger.WithFields(fields)
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- entry.Info("aaa")
- }
- })
-}
diff --git a/vendor/github.com/sirupsen/logrus/logrus.go b/vendor/github.com/sirupsen/logrus/logrus.go
deleted file mode 100644
index dd38999..0000000
--- a/vendor/github.com/sirupsen/logrus/logrus.go
+++ /dev/null
@@ -1,143 +0,0 @@
-package logrus
-
-import (
- "fmt"
- "log"
- "strings"
-)
-
-// Fields type, used to pass to `WithFields`.
-type Fields map[string]interface{}
-
-// Level type
-type Level uint32
-
-// Convert the Level to a string. E.g. PanicLevel becomes "panic".
-func (level Level) String() string {
- switch level {
- case DebugLevel:
- return "debug"
- case InfoLevel:
- return "info"
- case WarnLevel:
- return "warning"
- case ErrorLevel:
- return "error"
- case FatalLevel:
- return "fatal"
- case PanicLevel:
- return "panic"
- }
-
- return "unknown"
-}
-
-// ParseLevel takes a string level and returns the Logrus log level constant.
-func ParseLevel(lvl string) (Level, error) {
- switch strings.ToLower(lvl) {
- case "panic":
- return PanicLevel, nil
- case "fatal":
- return FatalLevel, nil
- case "error":
- return ErrorLevel, nil
- case "warn", "warning":
- return WarnLevel, nil
- case "info":
- return InfoLevel, nil
- case "debug":
- return DebugLevel, nil
- }
-
- var l Level
- return l, fmt.Errorf("not a valid logrus Level: %q", lvl)
-}
-
-// A constant exposing all logging levels
-var AllLevels = []Level{
- PanicLevel,
- FatalLevel,
- ErrorLevel,
- WarnLevel,
- InfoLevel,
- DebugLevel,
-}
-
-// These are the different logging levels. You can set the logging level to log
-// on your instance of logger, obtained with `logrus.New()`.
-const (
- // PanicLevel level, highest level of severity. Logs and then calls panic with the
- // message passed to Debug, Info, ...
- PanicLevel Level = iota
- // FatalLevel level. Logs and then calls `os.Exit(1)`. It will exit even if the
- // logging level is set to Panic.
- FatalLevel
- // ErrorLevel level. Logs. Used for errors that should definitely be noted.
- // Commonly used for hooks to send errors to an error tracking service.
- ErrorLevel
- // WarnLevel level. Non-critical entries that deserve eyes.
- WarnLevel
- // InfoLevel level. General operational entries about what's going on inside the
- // application.
- InfoLevel
- // DebugLevel level. Usually only enabled when debugging. Very verbose logging.
- DebugLevel
-)
-
-// Won't compile if StdLogger can't be realized by a log.Logger
-var (
- _ StdLogger = &log.Logger{}
- _ StdLogger = &Entry{}
- _ StdLogger = &Logger{}
-)
-
-// StdLogger is what your logrus-enabled library should take, that way
-// it'll accept a stdlib logger and a logrus logger. There's no standard
-// interface, this is the closest we get, unfortunately.
-type StdLogger interface {
- Print(...interface{})
- Printf(string, ...interface{})
- Println(...interface{})
-
- Fatal(...interface{})
- Fatalf(string, ...interface{})
- Fatalln(...interface{})
-
- Panic(...interface{})
- Panicf(string, ...interface{})
- Panicln(...interface{})
-}
-
-// The FieldLogger interface generalizes the Entry and Logger types
-type FieldLogger interface {
- WithField(key string, value interface{}) *Entry
- WithFields(fields Fields) *Entry
- WithError(err error) *Entry
-
- Debugf(format string, args ...interface{})
- Infof(format string, args ...interface{})
- Printf(format string, args ...interface{})
- Warnf(format string, args ...interface{})
- Warningf(format string, args ...interface{})
- Errorf(format string, args ...interface{})
- Fatalf(format string, args ...interface{})
- Panicf(format string, args ...interface{})
-
- Debug(args ...interface{})
- Info(args ...interface{})
- Print(args ...interface{})
- Warn(args ...interface{})
- Warning(args ...interface{})
- Error(args ...interface{})
- Fatal(args ...interface{})
- Panic(args ...interface{})
-
- Debugln(args ...interface{})
- Infoln(args ...interface{})
- Println(args ...interface{})
- Warnln(args ...interface{})
- Warningln(args ...interface{})
- Errorln(args ...interface{})
- Fatalln(args ...interface{})
- Panicln(args ...interface{})
-}
diff --git a/vendor/github.com/sirupsen/logrus/logrus_test.go b/vendor/github.com/sirupsen/logrus/logrus_test.go
deleted file mode 100644
index 78cbc28..0000000
--- a/vendor/github.com/sirupsen/logrus/logrus_test.go
+++ /dev/null
@@ -1,386 +0,0 @@
-package logrus
-
-import (
- "bytes"
- "encoding/json"
- "strconv"
- "strings"
- "sync"
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-func LogAndAssertJSON(t *testing.T, log func(*Logger), assertions func(fields Fields)) {
- var buffer bytes.Buffer
- var fields Fields
-
- logger := New()
- logger.Out = &buffer
- logger.Formatter = new(JSONFormatter)
-
- log(logger)
-
- err := json.Unmarshal(buffer.Bytes(), &fields)
- assert.Nil(t, err)
-
- assertions(fields)
-}
-
-func LogAndAssertText(t *testing.T, log func(*Logger), assertions func(fields map[string]string)) {
- var buffer bytes.Buffer
-
- logger := New()
- logger.Out = &buffer
- logger.Formatter = &TextFormatter{
- DisableColors: true,
- }
-
- log(logger)
-
- fields := make(map[string]string)
- for _, kv := range strings.Split(buffer.String(), " ") {
- if !strings.Contains(kv, "=") {
- continue
- }
- kvArr := strings.Split(kv, "=")
- key := strings.TrimSpace(kvArr[0])
- val := kvArr[1]
- if kvArr[1][0] == '"' {
- var err error
- val, err = strconv.Unquote(val)
- assert.NoError(t, err)
- }
- fields[key] = val
- }
- assertions(fields)
-}
-
-func TestPrint(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Print("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test")
- assert.Equal(t, fields["level"], "info")
- })
-}
-
-func TestInfo(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Info("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test")
- assert.Equal(t, fields["level"], "info")
- })
-}
-
-func TestWarn(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Warn("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test")
- assert.Equal(t, fields["level"], "warning")
- })
-}
-
-func TestInfolnShouldAddSpacesBetweenStrings(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Infoln("test", "test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test test")
- })
-}
-
-func TestInfolnShouldAddSpacesBetweenStringAndNonstring(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Infoln("test", 10)
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test 10")
- })
-}
-
-func TestInfolnShouldAddSpacesBetweenTwoNonStrings(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Infoln(10, 10)
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "10 10")
- })
-}
-
-func TestInfoShouldAddSpacesBetweenTwoNonStrings(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Infoln(10, 10)
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "10 10")
- })
-}
-
-func TestInfoShouldNotAddSpacesBetweenStringAndNonstring(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Info("test", 10)
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test10")
- })
-}
-
-func TestInfoShouldNotAddSpacesBetweenStrings(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Info("test", "test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "testtest")
- })
-}
-
-func TestWithFieldsShouldAllowAssignments(t *testing.T) {
- var buffer bytes.Buffer
- var fields Fields
-
- logger := New()
- logger.Out = &buffer
- logger.Formatter = new(JSONFormatter)
-
- localLog := logger.WithFields(Fields{
- "key1": "value1",
- })
-
- localLog.WithField("key2", "value2").Info("test")
- err := json.Unmarshal(buffer.Bytes(), &fields)
- assert.Nil(t, err)
-
- assert.Equal(t, "value2", fields["key2"])
- assert.Equal(t, "value1", fields["key1"])
-
- buffer = bytes.Buffer{}
- fields = Fields{}
- localLog.Info("test")
- err = json.Unmarshal(buffer.Bytes(), &fields)
- assert.Nil(t, err)
-
- _, ok := fields["key2"]
- assert.Equal(t, false, ok)
- assert.Equal(t, "value1", fields["key1"])
-}
-
-func TestUserSuppliedFieldDoesNotOverwriteDefaults(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.WithField("msg", "hello").Info("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test")
- })
-}
-
-func TestUserSuppliedMsgFieldHasPrefix(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.WithField("msg", "hello").Info("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test")
- assert.Equal(t, fields["fields.msg"], "hello")
- })
-}
-
-func TestUserSuppliedTimeFieldHasPrefix(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.WithField("time", "hello").Info("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["fields.time"], "hello")
- })
-}
-
-func TestUserSuppliedLevelFieldHasPrefix(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.WithField("level", 1).Info("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["level"], "info")
- assert.Equal(t, fields["fields.level"], 1.0) // JSON has floats only
- })
-}
-
-func TestDefaultFieldsAreNotPrefixed(t *testing.T) {
- LogAndAssertText(t, func(log *Logger) {
- ll := log.WithField("herp", "derp")
- ll.Info("hello")
- ll.Info("bye")
- }, func(fields map[string]string) {
- for _, fieldName := range []string{"fields.level", "fields.time", "fields.msg"} {
- if _, ok := fields[fieldName]; ok {
- t.Fatalf("should not have prefixed %q: %v", fieldName, fields)
- }
- }
- })
-}
-
-func TestDoubleLoggingDoesntPrefixPreviousFields(t *testing.T) {
-
- var buffer bytes.Buffer
- var fields Fields
-
- logger := New()
- logger.Out = &buffer
- logger.Formatter = new(JSONFormatter)
-
- llog := logger.WithField("context", "eating raw fish")
-
- llog.Info("looks delicious")
-
- err := json.Unmarshal(buffer.Bytes(), &fields)
- assert.NoError(t, err, "should have decoded first message")
- assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields")
- assert.Equal(t, fields["msg"], "looks delicious")
- assert.Equal(t, fields["context"], "eating raw fish")
-
- buffer.Reset()
-
- llog.Warn("omg it is!")
-
- err = json.Unmarshal(buffer.Bytes(), &fields)
- assert.NoError(t, err, "should have decoded second message")
- assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields")
- assert.Equal(t, fields["msg"], "omg it is!")
- assert.Equal(t, fields["context"], "eating raw fish")
- assert.Nil(t, fields["fields.msg"], "should not have prefixed previous `msg` entry")
-
-}
-
-func TestConvertLevelToString(t *testing.T) {
- assert.Equal(t, "debug", DebugLevel.String())
- assert.Equal(t, "info", InfoLevel.String())
- assert.Equal(t, "warning", WarnLevel.String())
- assert.Equal(t, "error", ErrorLevel.String())
- assert.Equal(t, "fatal", FatalLevel.String())
- assert.Equal(t, "panic", PanicLevel.String())
-}
-
-func TestParseLevel(t *testing.T) {
- l, err := ParseLevel("panic")
- assert.Nil(t, err)
- assert.Equal(t, PanicLevel, l)
-
- l, err = ParseLevel("PANIC")
- assert.Nil(t, err)
- assert.Equal(t, PanicLevel, l)
-
- l, err = ParseLevel("fatal")
- assert.Nil(t, err)
- assert.Equal(t, FatalLevel, l)
-
- l, err = ParseLevel("FATAL")
- assert.Nil(t, err)
- assert.Equal(t, FatalLevel, l)
-
- l, err = ParseLevel("error")
- assert.Nil(t, err)
- assert.Equal(t, ErrorLevel, l)
-
- l, err = ParseLevel("ERROR")
- assert.Nil(t, err)
- assert.Equal(t, ErrorLevel, l)
-
- l, err = ParseLevel("warn")
- assert.Nil(t, err)
- assert.Equal(t, WarnLevel, l)
-
- l, err = ParseLevel("WARN")
- assert.Nil(t, err)
- assert.Equal(t, WarnLevel, l)
-
- l, err = ParseLevel("warning")
- assert.Nil(t, err)
- assert.Equal(t, WarnLevel, l)
-
- l, err = ParseLevel("WARNING")
- assert.Nil(t, err)
- assert.Equal(t, WarnLevel, l)
-
- l, err = ParseLevel("info")
- assert.Nil(t, err)
- assert.Equal(t, InfoLevel, l)
-
- l, err = ParseLevel("INFO")
- assert.Nil(t, err)
- assert.Equal(t, InfoLevel, l)
-
- l, err = ParseLevel("debug")
- assert.Nil(t, err)
- assert.Equal(t, DebugLevel, l)
-
- l, err = ParseLevel("DEBUG")
- assert.Nil(t, err)
- assert.Equal(t, DebugLevel, l)
-
- l, err = ParseLevel("invalid")
- assert.Equal(t, "not a valid logrus Level: \"invalid\"", err.Error())
-}
-
-func TestGetSetLevelRace(t *testing.T) {
- wg := sync.WaitGroup{}
- for i := 0; i < 100; i++ {
- wg.Add(1)
- go func(i int) {
- defer wg.Done()
- if i%2 == 0 {
- SetLevel(InfoLevel)
- } else {
- GetLevel()
- }
- }(i)
-
- }
- wg.Wait()
-}
-
-func TestLoggingRace(t *testing.T) {
- logger := New()
-
- var wg sync.WaitGroup
- wg.Add(100)
-
- for i := 0; i < 100; i++ {
- go func() {
- logger.Info("info")
- wg.Done()
- }()
- }
- wg.Wait()
-}
-
-// Compile test
-func TestLogrusInterface(t *testing.T) {
- var buffer bytes.Buffer
- fn := func(l FieldLogger) {
- b := l.WithField("key", "value")
- b.Debug("Test")
- }
- // test logger
- logger := New()
- logger.Out = &buffer
- fn(logger)
-
- // test Entry
- e := logger.WithField("another", "value")
- fn(e)
-}
-
-// Implements io.Writer using channels for synchronization, so we can wait on
-// the Entry.Writer goroutine to write in a non-racey way. This does assume that
-// there is a single call to Logger.Out for each message.
-type channelWriter chan []byte
-
-func (cw channelWriter) Write(p []byte) (int, error) {
- cw <- p
- return len(p), nil
-}
-
-func TestEntryWriter(t *testing.T) {
- cw := channelWriter(make(chan []byte, 1))
- log := New()
- log.Out = cw
- log.Formatter = new(JSONFormatter)
- log.WithField("foo", "bar").WriterLevel(WarnLevel).Write([]byte("hello\n"))
-
- bs := <-cw
- var fields Fields
- err := json.Unmarshal(bs, &fields)
- assert.Nil(t, err)
- assert.Equal(t, fields["foo"], "bar")
- assert.Equal(t, fields["level"], "warning")
-}
diff --git a/vendor/github.com/sirupsen/logrus/terminal_bsd.go b/vendor/github.com/sirupsen/logrus/terminal_bsd.go
deleted file mode 100644
index d7b3893..0000000
--- a/vendor/github.com/sirupsen/logrus/terminal_bsd.go
+++ /dev/null
@@ -1,10 +0,0 @@
-// +build darwin freebsd openbsd netbsd dragonfly
-// +build !appengine
-
-package logrus
-
-import "golang.org/x/sys/unix"
-
-const ioctlReadTermios = unix.TIOCGETA
-
-type Termios unix.Termios
diff --git a/vendor/github.com/sirupsen/logrus/terminal_linux.go b/vendor/github.com/sirupsen/logrus/terminal_linux.go
deleted file mode 100644
index 88d7298..0000000
--- a/vendor/github.com/sirupsen/logrus/terminal_linux.go
+++ /dev/null
@@ -1,14 +0,0 @@
-// Based on ssh/terminal:
-// Copyright 2013 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.
-
-// +build !appengine
-
-package logrus
-
-import "golang.org/x/sys/unix"
-
-const ioctlReadTermios = unix.TCGETS
-
-type Termios unix.Termios
diff --git a/vendor/github.com/sirupsen/logrus/text_formatter.go b/vendor/github.com/sirupsen/logrus/text_formatter.go
deleted file mode 100644
index be412aa..0000000
--- a/vendor/github.com/sirupsen/logrus/text_formatter.go
+++ /dev/null
@@ -1,191 +0,0 @@
-package logrus
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
- "sort"
- "strings"
- "sync"
- "time"
-
- "golang.org/x/crypto/ssh/terminal"
-)
-
-const (
- nocolor = 0
- red = 31
- green = 32
- yellow = 33
- blue = 36
- gray = 37
-)
-
-var (
- baseTimestamp time.Time
-)
-
-func init() {
- baseTimestamp = time.Now()
-}
-
-// TextFormatter formats logs into text
-type TextFormatter struct {
- // Set to true to bypass checking for a TTY before outputting colors.
- ForceColors bool
-
- // Force disabling colors.
- DisableColors bool
-
- // Disable timestamp logging. useful when output is redirected to logging
- // system that already adds timestamps.
- DisableTimestamp bool
-
- // Enable logging the full timestamp when a TTY is attached instead of just
- // the time passed since beginning of execution.
- FullTimestamp bool
-
- // TimestampFormat to use for display when a full timestamp is printed
- TimestampFormat string
-
- // The fields are sorted by default for a consistent output. For applications
- // that log extremely frequently and don't use the JSON formatter this may not
- // be desired.
- DisableSorting bool
-
- // QuoteEmptyFields will wrap empty fields in quotes if true
- QuoteEmptyFields bool
-
- // Whether the logger's out is to a terminal
- isTerminal bool
-
- sync.Once
-}
-
-func (f *TextFormatter) init(entry *Entry) {
- if entry.Logger != nil {
- f.isTerminal = f.checkIfTerminal(entry.Logger.Out)
- }
-}
-
-func (f *TextFormatter) checkIfTerminal(w io.Writer) bool {
- switch v := w.(type) {
- case *os.File:
- return terminal.IsTerminal(int(v.Fd()))
- default:
- return false
- }
-}
-
-// Format renders a single log entry
-func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
- var b *bytes.Buffer
- keys := make([]string, 0, len(entry.Data))
- for k := range entry.Data {
- keys = append(keys, k)
- }
-
- if !f.DisableSorting {
- sort.Strings(keys)
- }
- if entry.Buffer != nil {
- b = entry.Buffer
- } else {
- b = &bytes.Buffer{}
- }
-
- prefixFieldClashes(entry.Data)
-
- f.Do(func() { f.init(entry) })
-
- isColored := (f.ForceColors || f.isTerminal) && !f.DisableColors
-
- timestampFormat := f.TimestampFormat
- if timestampFormat == "" {
- timestampFormat = defaultTimestampFormat
- }
- if isColored {
- f.printColored(b, entry, keys, timestampFormat)
- } else {
- if !f.DisableTimestamp {
- f.appendKeyValue(b, "time", entry.Time.Format(timestampFormat))
- }
- f.appendKeyValue(b, "level", entry.Level.String())
- if entry.Message != "" {
- f.appendKeyValue(b, "msg", entry.Message)
- }
- for _, key := range keys {
- f.appendKeyValue(b, key, entry.Data[key])
- }
- }
-
- b.WriteByte('\n')
- return b.Bytes(), nil
-}
-
-func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, timestampFormat string) {
- var levelColor int
- switch entry.Level {
- case DebugLevel:
- levelColor = gray
- case WarnLevel:
- levelColor = yellow
- case ErrorLevel, FatalLevel, PanicLevel:
- levelColor = red
- default:
- levelColor = blue
- }
-
- levelText := strings.ToUpper(entry.Level.String())[0:4]
-
- if f.DisableTimestamp {
- fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m %-44s ", levelColor, levelText, entry.Message)
- } else if !f.FullTimestamp {
- fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), entry.Message)
- } else {
- fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), entry.Message)
- }
- for _, k := range keys {
- v := entry.Data[k]
- fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k)
- f.appendValue(b, v)
- }
-}
-
-func (f *TextFormatter) needsQuoting(text string) bool {
- if f.QuoteEmptyFields && len(text) == 0 {
- return true
- }
- for _, ch := range text {
- if !((ch >= 'a' && ch <= 'z') ||
- (ch >= 'A' && ch <= 'Z') ||
- (ch >= '0' && ch <= '9') ||
- ch == '-' || ch == '.' || ch == '_' || ch == '/' || ch == '@' || ch == '^' || ch == '+') {
- return true
- }
- }
- return false
-}
-
-func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) {
- if b.Len() > 0 {
- b.WriteByte(' ')
- }
- b.WriteString(key)
- b.WriteByte('=')
- f.appendValue(b, value)
-}
-
-func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) {
- stringVal, ok := value.(string)
- if !ok {
- stringVal = fmt.Sprint(value)
- }
-
- if !f.needsQuoting(stringVal) {
- b.WriteString(stringVal)
- } else {
- b.WriteString(fmt.Sprintf("%q", stringVal))
- }
-}
diff --git a/vendor/github.com/sirupsen/logrus/text_formatter_test.go b/vendor/github.com/sirupsen/logrus/text_formatter_test.go
deleted file mode 100644
index d93b931..0000000
--- a/vendor/github.com/sirupsen/logrus/text_formatter_test.go
+++ /dev/null
@@ -1,141 +0,0 @@
-package logrus
-
-import (
- "bytes"
- "errors"
- "fmt"
- "strings"
- "testing"
- "time"
-)
-
-func TestFormatting(t *testing.T) {
- tf := &TextFormatter{DisableColors: true}
-
- testCases := []struct {
- value string
- expected string
- }{
- {`foo`, "time=\"0001-01-01T00:00:00Z\" level=panic test=foo\n"},
- }
-
- for _, tc := range testCases {
- b, _ := tf.Format(WithField("test", tc.value))
-
- if string(b) != tc.expected {
- t.Errorf("formatting expected for %q (result was %q instead of %q)", tc.value, string(b), tc.expected)
- }
- }
-}
-
-func TestQuoting(t *testing.T) {
- tf := &TextFormatter{DisableColors: true}
-
- checkQuoting := func(q bool, value interface{}) {
- b, _ := tf.Format(WithField("test", value))
- idx := bytes.Index(b, ([]byte)("test="))
- cont := bytes.Contains(b[idx+5:], []byte("\""))
- if cont != q {
- if q {
- t.Errorf("quoting expected for: %#v", value)
- } else {
- t.Errorf("quoting not expected for: %#v", value)
- }
- }
- }
-
- checkQuoting(false, "")
- checkQuoting(false, "abcd")
- checkQuoting(false, "v1.0")
- checkQuoting(false, "1234567890")
- checkQuoting(false, "/foobar")
- checkQuoting(false, "foo_bar")
- checkQuoting(false, "foo@bar")
- checkQuoting(false, "foobar^")
- checkQuoting(false, "+/-_^@f.oobar")
- checkQuoting(true, "foobar$")
- checkQuoting(true, "&foobar")
- checkQuoting(true, "x y")
- checkQuoting(true, "x,y")
- checkQuoting(false, errors.New("invalid"))
- checkQuoting(true, errors.New("invalid argument"))
-
- // Test for quoting empty fields.
- tf.QuoteEmptyFields = true
- checkQuoting(true, "")
- checkQuoting(false, "abcd")
- checkQuoting(true, errors.New("invalid argument"))
-}
-
-func TestEscaping(t *testing.T) {
- tf := &TextFormatter{DisableColors: true}
-
- testCases := []struct {
- value string
- expected string
- }{
- {`ba"r`, `ba\"r`},
- {`ba'r`, `ba'r`},
- }
-
- for _, tc := range testCases {
- b, _ := tf.Format(WithField("test", tc.value))
- if !bytes.Contains(b, []byte(tc.expected)) {
- t.Errorf("escaping expected for %q (result was %q instead of %q)", tc.value, string(b), tc.expected)
- }
- }
-}
-
-func TestEscaping_Interface(t *testing.T) {
- tf := &TextFormatter{DisableColors: true}
-
- ts := time.Now()
-
- testCases := []struct {
- value interface{}
- expected string
- }{
- {ts, fmt.Sprintf("\"%s\"", ts.String())},
- {errors.New("error: something went wrong"), "\"error: something went wrong\""},
- }
-
- for _, tc := range testCases {
- b, _ := tf.Format(WithField("test", tc.value))
- if !bytes.Contains(b, []byte(tc.expected)) {
- t.Errorf("escaping expected for %q (result was %q instead of %q)", tc.value, string(b), tc.expected)
- }
- }
-}
-
-func TestTimestampFormat(t *testing.T) {
- checkTimeStr := func(format string) {
- customFormatter := &TextFormatter{DisableColors: true, TimestampFormat: format}
- customStr, _ := customFormatter.Format(WithField("test", "test"))
- timeStart := bytes.Index(customStr, ([]byte)("time="))
- timeEnd := bytes.Index(customStr, ([]byte)("level="))
- timeStr := customStr[timeStart+5+len("\"") : timeEnd-1-len("\"")]
- if format == "" {
- format = time.RFC3339
- }
- _, e := time.Parse(format, (string)(timeStr))
- if e != nil {
- t.Errorf("time string \"%s\" did not match provided time format \"%s\": %s", timeStr, format, e)
- }
- }
-
- checkTimeStr("2006-01-02T15:04:05.000000000Z07:00")
- checkTimeStr("Mon Jan _2 15:04:05 2006")
- checkTimeStr("")
-}
-
-func TestDisableTimestampWithColoredOutput(t *testing.T) {
- tf := &TextFormatter{DisableTimestamp: true, ForceColors: true}
-
- b, _ := tf.Format(WithField("test", "test"))
- if strings.Contains(string(b), "[0000]") {
- t.Error("timestamp not expected when DisableTimestamp is true")
- }
-}
-
-// TODO add tests for sorting etc., this requires a parser for the text
-// formatter output.
diff --git a/vendor/github.com/sirupsen/logrus/writer.go b/vendor/github.com/sirupsen/logrus/writer.go
deleted file mode 100644
index 7bdebed..0000000
--- a/vendor/github.com/sirupsen/logrus/writer.go
+++ /dev/null
@@ -1,62 +0,0 @@
-package logrus
-
-import (
- "bufio"
- "io"
- "runtime"
-)
-
-func (logger *Logger) Writer() *io.PipeWriter {
- return logger.WriterLevel(InfoLevel)
-}
-
-func (logger *Logger) WriterLevel(level Level) *io.PipeWriter {
- return NewEntry(logger).WriterLevel(level)
-}
-
-func (entry *Entry) Writer() *io.PipeWriter {
- return entry.WriterLevel(InfoLevel)
-}
-
-func (entry *Entry) WriterLevel(level Level) *io.PipeWriter {
- reader, writer := io.Pipe()
-
- var printFunc func(args ...interface{})
-
- switch level {
- case DebugLevel:
- printFunc = entry.Debug
- case InfoLevel:
- printFunc = entry.Info
- case WarnLevel:
- printFunc = entry.Warn
- case ErrorLevel:
- printFunc = entry.Error
- case FatalLevel:
- printFunc = entry.Fatal
- case PanicLevel:
- printFunc = entry.Panic
- default:
- printFunc = entry.Print
- }
-
- go entry.writerScanner(reader, printFunc)
- runtime.SetFinalizer(writer, writerFinalizer)
-
- return writer
-}
-
-func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) {
- scanner := bufio.NewScanner(reader)
- for scanner.Scan() {
- printFunc(scanner.Text())
- }
- if err := scanner.Err(); err != nil {
- entry.Errorf("Error while reading from Writer: %s", err)
- }
- reader.Close()
-}
-
-func writerFinalizer(writer *io.PipeWriter) {
- writer.Close()
-}
diff --git a/vendor/github.com/spf13/afero/.travis.yml b/vendor/github.com/spf13/afero/.travis.yml
deleted file mode 100644
index b288d26..0000000
--- a/vendor/github.com/spf13/afero/.travis.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-sudo: false
-language: go
-
-go:
- - 1.7.5
- - 1.8
- - tip
-
-os:
- - linux
- - osx
-
-matrix:
- allow_failures:
- - go: tip
- fast_finish: true
-
-script:
- - go build
- - go test -race -v ./...
-
diff --git a/vendor/github.com/spf13/afero/LICENSE.txt b/vendor/github.com/spf13/afero/LICENSE.txt
deleted file mode 100644
index 298f0e2..0000000
--- a/vendor/github.com/spf13/afero/LICENSE.txt
+++ /dev/null
@@ -1,174 +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.
diff --git a/vendor/github.com/spf13/afero/README.md b/vendor/github.com/spf13/afero/README.md
deleted file mode 100644
index 0c9b04b..0000000
--- a/vendor/github.com/spf13/afero/README.md
+++ /dev/null
@@ -1,452 +0,0 @@
-
-
-A FileSystem Abstraction System for Go
-
-[](https://travis-ci.org/spf13/afero) [](https://ci.appveyor.com/project/spf13/afero) [](https://godoc.org/github.com/spf13/afero) [](https://gitter.im/spf13/afero?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
-
-# Overview
-
-Afero is an filesystem framework providing a simple, uniform and universal API
-interacting with any filesystem, as an abstraction layer providing interfaces,
-types and methods. Afero has an exceptionally clean interface and simple design
-without needless constructors or initialization methods.
-
-Afero is also a library providing a base set of interoperable backend
-filesystems that make it easy to work with afero while retaining all the power
-and benefit of the os and ioutil packages.
-
-Afero provides significant improvements over using the os package alone, most
-notably the ability to create mock and testing filesystems without relying on the disk.
-
-It is suitable for use in a any situation where you would consider using the OS
-package as it provides an additional abstraction that makes it easy to use a
-memory backed file system during testing. It also adds support for the http
-filesystem for full interoperability.
-
-
-## Afero Features
-
-* A single consistent API for accessing a variety of filesystems
-* Interoperation between a variety of file system types
-* A set of interfaces to encourage and enforce interoperability between backends
-* An atomic cross platform memory backed file system
-* Support for compositional (union) file systems by combining multiple file systems acting as one
-* Specialized backends which modify existing filesystems (Read Only, Regexp filtered)
-* A set of utility functions ported from io, ioutil & hugo to be afero aware
-
-
-# Using Afero
-
-Afero is easy to use and easier to adopt.
-
-A few different ways you could use Afero:
-
-* Use the interfaces alone to define you own file system.
-* Wrap for the OS packages.
-* Define different filesystems for different parts of your application.
-* Use Afero for mock filesystems while testing
-
-## Step 1: Install Afero
-
-First use go get to install the latest version of the library.
-
- $ go get github.com/spf13/afero
-
-Next include Afero in your application.
-```go
-import "github.com/spf13/afero"
-```
-
-## Step 2: Declare a backend
-
-First define a package variable and set it to a pointer to a filesystem.
-```go
-var AppFs = afero.NewMemMapFs()
-
-or
-
-var AppFs = afero.NewOsFs()
-```
-It is important to note that if you repeat the composite literal you
-will be using a completely new and isolated filesystem. In the case of
-OsFs it will still use the same underlying filesystem but will reduce
-the ability to drop in other filesystems as desired.
-
-## Step 3: Use it like you would the OS package
-
-Throughout your application use any function and method like you normally
-would.
-
-So if my application before had:
-```go
-os.Open('/tmp/foo')
-```
-We would replace it with:
-```go
-AppFs.Open('/tmp/foo')
-```
-
-`AppFs` being the variable we defined above.
-
-
-## List of all available functions
-
-File System Methods Available:
-```go
-Chmod(name string, mode os.FileMode) : error
-Chtimes(name string, atime time.Time, mtime time.Time) : error
-Create(name string) : File, error
-Mkdir(name string, perm os.FileMode) : error
-MkdirAll(path string, perm os.FileMode) : error
-Name() : string
-Open(name string) : File, error
-OpenFile(name string, flag int, perm os.FileMode) : File, error
-Remove(name string) : error
-RemoveAll(path string) : error
-Rename(oldname, newname string) : error
-Stat(name string) : os.FileInfo, error
-```
-File Interfaces and Methods Available:
-```go
-io.Closer
-io.Reader
-io.ReaderAt
-io.Seeker
-io.Writer
-io.WriterAt
-
-Name() : string
-Readdir(count int) : []os.FileInfo, error
-Readdirnames(n int) : []string, error
-Stat() : os.FileInfo, error
-Sync() : error
-Truncate(size int64) : error
-WriteString(s string) : ret int, err error
-```
-In some applications it may make sense to define a new package that
-simply exports the file system variable for easy access from anywhere.
-
-## Using Afero's utility functions
-
-Afero provides a set of functions to make it easier to use the underlying file systems.
-These functions have been primarily ported from io & ioutil with some developed for Hugo.
-
-The afero utilities support all afero compatible backends.
-
-The list of utilities includes:
-
-```go
-DirExists(path string) (bool, error)
-Exists(path string) (bool, error)
-FileContainsBytes(filename string, subslice []byte) (bool, error)
-GetTempDir(subPath string) string
-IsDir(path string) (bool, error)
-IsEmpty(path string) (bool, error)
-ReadDir(dirname string) ([]os.FileInfo, error)
-ReadFile(filename string) ([]byte, error)
-SafeWriteReader(path string, r io.Reader) (err error)
-TempDir(dir, prefix string) (name string, err error)
-TempFile(dir, prefix string) (f File, err error)
-Walk(root string, walkFn filepath.WalkFunc) error
-WriteFile(filename string, data []byte, perm os.FileMode) error
-WriteReader(path string, r io.Reader) (err error)
-```
-For a complete list see [Afero's GoDoc](https://godoc.org/github.com/spf13/afero)
-
-They are available under two different approaches to use. You can either call
-them directly where the first parameter of each function will be the file
-system, or you can declare a new `Afero`, a custom type used to bind these
-functions as methods to a given filesystem.
-
-### Calling utilities directly
-
-```go
-fs := new(afero.MemMapFs)
-f, err := afero.TempFile(fs,"", "ioutil-test")
-
-```
-
-### Calling via Afero
-
-```go
-fs := afero.NewMemMapFs()
-afs := &afero.Afero{Fs: fs}
-f, err := afs.TempFile("", "ioutil-test")
-```
-
-## Using Afero for Testing
-
-There is a large benefit to using a mock filesystem for testing. It has a
-completely blank state every time it is initialized and can be easily
-reproducible regardless of OS. You could create files to your heart’s content
-and the file access would be fast while also saving you from all the annoying
-issues with deleting temporary files, Windows file locking, etc. The MemMapFs
-backend is perfect for testing.
-
-* Much faster than performing I/O operations on disk
-* Avoid security issues and permissions
-* Far more control. 'rm -rf /' with confidence
-* Test setup is far more easier to do
-* No test cleanup needed
-
-One way to accomplish this is to define a variable as mentioned above.
-In your application this will be set to afero.NewOsFs() during testing you
-can set it to afero.NewMemMapFs().
-
-It wouldn't be uncommon to have each test initialize a blank slate memory
-backend. To do this I would define my `appFS = afero.NewOsFs()` somewhere
-appropriate in my application code. This approach ensures that Tests are order
-independent, with no test relying on the state left by an earlier test.
-
-Then in my tests I would initialize a new MemMapFs for each test:
-```go
-func TestExist(t *testing.T) {
- appFS := afero.NewMemMapFs()
- // create test files and directories
- appFS.MkdirAll("src/a", 0755)
- afero.WriteFile(appFS, "src/a/b", []byte("file b"), 0644)
- afero.WriteFile(appFS, "src/c", []byte("file c"), 0644)
- name := "src/c"
- _, err := appFS.Stat(name)
- if os.IsNotExist(err) {
- t.Errorf("file \"%s\" does not exist.\n", name)
- }
-}
-```
-
-# Available Backends
-
-## Operating System Native
-
-### OsFs
-
-The first is simply a wrapper around the native OS calls. This makes it
-very easy to use as all of the calls are the same as the existing OS
-calls. It also makes it trivial to have your code use the OS during
-operation and a mock filesystem during testing or as needed.
-
-```go
-appfs := afero.NewOsFs()
-appfs.MkdirAll("src/a", 0755))
-```
-
-## Memory Backed Storage
-
-### MemMapFs
-
-Afero also provides a fully atomic memory backed filesystem perfect for use in
-mocking and to speed up unnecessary disk io when persistence isn’t
-necessary. It is fully concurrent and will work within go routines
-safely.
-
-```go
-mm := afero.NewMemMapFs()
-mm.MkdirAll("src/a", 0755))
-```
-
-#### InMemoryFile
-
-As part of MemMapFs, Afero also provides an atomic, fully concurrent memory
-backed file implementation. This can be used in other memory backed file
-systems with ease. Plans are to add a radix tree memory stored file
-system using InMemoryFile.
-
-## Network Interfaces
-
-### SftpFs
-
-Afero has experimental support for secure file transfer protocol (sftp). Which can
-be used to perform file operations over a encrypted channel.
-
-## Filtering Backends
-
-### BasePathFs
-
-The BasePathFs restricts all operations to a given path within an Fs.
-The given file name to the operations on this Fs will be prepended with
-the base path before calling the source Fs.
-
-```go
-bp := afero.NewBasePathFs(afero.NewOsFs(), "/base/path")
-```
-
-### ReadOnlyFs
-
-A thin wrapper around the source Fs providing a read only view.
-
-```go
-fs := afero.NewReadOnlyFs(afero.NewOsFs())
-_, err := fs.Create("/file.txt")
-// err = syscall.EPERM
-```
-
-# RegexpFs
-
-A filtered view on file names, any file NOT matching
-the passed regexp will be treated as non-existing.
-Files not matching the regexp provided will not be created.
-Directories are not filtered.
-
-```go
-fs := afero.NewRegexpFs(afero.NewMemMapFs(), regexp.MustCompile(`\.txt$`))
-_, err := fs.Create("/file.html")
-// err = syscall.ENOENT
-```
-
-### HttpFs
-
-Afero provides an http compatible backend which can wrap any of the existing
-backends.
-
-The Http package requires a slightly specific version of Open which
-returns an http.File type.
-
-Afero provides an httpFs file system which satisfies this requirement.
-Any Afero FileSystem can be used as an httpFs.
-
-```go
-httpFs := afero.NewHttpFs()
-fileserver := http.FileServer(httpFs.Dir()))
-http.Handle("/", fileserver)
-```
-
-## Composite Backends
-
-Afero provides the ability have two filesystems (or more) act as a single
-file system.
-
-### CacheOnReadFs
-
-The CacheOnReadFs will lazily make copies of any accessed files from the base
-layer into the overlay. Subsequent reads will be pulled from the overlay
-directly permitting the request is within the cache duration of when it was
-created in the overlay.
-
-If the base filesystem is writeable, any changes to files will be
-done first to the base, then to the overlay layer. Write calls to open file
-handles like `Write()` or `Truncate()` to the overlay first.
-
-To writing files to the overlay only, you can use the overlay Fs directly (not
-via the union Fs).
-
-Cache files in the layer for the given time.Duration, a cache duration of 0
-means "forever" meaning the file will not be re-requested from the base ever.
-
-A read-only base will make the overlay also read-only but still copy files
-from the base to the overlay when they're not present (or outdated) in the
-caching layer.
-
-```go
-base := afero.NewOsFs()
-layer := afero.NewMemMapFs()
-ufs := afero.NewCacheOnReadFs(base, layer, 100 * time.Second)
-```
-
-### CopyOnWriteFs()
-
-The CopyOnWriteFs is a read only base file system with a potentially
-writeable layer on top.
-
-Read operations will first look in the overlay and if not found there, will
-serve the file from the base.
-
-Changes to the file system will only be made in the overlay.
-
-Any attempt to modify a file found only in the base will copy the file to the
-overlay layer before modification (including opening a file with a writable
-handle).
-
-Removing and Renaming files present only in the base layer is not currently
-permitted. If a file is present in the base layer and the overlay, only the
-overlay will be removed/renamed.
-
-```go
- base := afero.NewOsFs()
- roBase := afero.NewReadOnlyFs(base)
- ufs := afero.NewCopyOnWriteFs(roBase, afero.NewMemMapFs())
-
- fh, _ = ufs.Create("/home/test/file2.txt")
- fh.WriteString("This is a test")
- fh.Close()
-```
-
-In this example all write operations will only occur in memory (MemMapFs)
-leaving the base filesystem (OsFs) untouched.
-
-
-## Desired/possible backends
-
-The following is a short list of possible backends we hope someone will
-implement:
-
-* SSH
-* ZIP
-* TAR
-* S3
-
-# About the project
-
-## What's in the name
-
-Afero comes from the latin roots Ad-Facere.
-
-**"Ad"** is a prefix meaning "to".
-
-**"Facere"** is a form of the root "faciō" making "make or do".
-
-The literal meaning of afero is "to make" or "to do" which seems very fitting
-for a library that allows one to make files and directories and do things with them.
-
-The English word that shares the same roots as Afero is "affair". Affair shares
-the same concept but as a noun it means "something that is made or done" or "an
-object of a particular type".
-
-It's also nice that unlike some of my other libraries (hugo, cobra, viper) it
-Googles very well.
-
-## Release Notes
-
-* **0.10.0** 2015.12.10
- * Full compatibility with Windows
- * Introduction of afero utilities
- * Test suite rewritten to work cross platform
- * Normalize paths for MemMapFs
- * Adding Sync to the file interface
- * **Breaking Change** Walk and ReadDir have changed parameter order
- * Moving types used by MemMapFs to a subpackage
- * General bugfixes and improvements
-* **0.9.0** 2015.11.05
- * New Walk function similar to filepath.Walk
- * MemMapFs.OpenFile handles O_CREATE, O_APPEND, O_TRUNC
- * MemMapFs.Remove now really deletes the file
- * InMemoryFile.Readdir and Readdirnames work correctly
- * InMemoryFile functions lock it for concurrent access
- * Test suite improvements
-* **0.8.0** 2014.10.28
- * First public version
- * Interfaces feel ready for people to build using
- * Interfaces satisfy all known uses
- * MemMapFs passes the majority of the OS test suite
- * OsFs passes the majority of the OS test suite
-
-## Contributing
-
-1. Fork it
-2. Create your feature branch (`git checkout -b my-new-feature`)
-3. Commit your changes (`git commit -am 'Add some feature'`)
-4. Push to the branch (`git push origin my-new-feature`)
-5. Create new Pull Request
-
-## Contributors
-
-Names in no particular order:
-
-* [spf13](https://github.com/spf13)
-* [jaqx0r](https://github.com/jaqx0r)
-* [mbertschler](https://github.com/mbertschler)
-* [xor-gate](https://github.com/xor-gate)
-
-## License
-
-Afero is released under the Apache 2.0 license. See
-[LICENSE.txt](https://github.com/spf13/afero/blob/master/LICENSE.txt)
diff --git a/vendor/github.com/spf13/afero/afero.go b/vendor/github.com/spf13/afero/afero.go
deleted file mode 100644
index f5b5e12..0000000
--- a/vendor/github.com/spf13/afero/afero.go
+++ /dev/null
@@ -1,108 +0,0 @@
-// Copyright © 2014 Steve Francia .
-// Copyright 2013 tsuru authors. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// Package afero provides types and methods for interacting with the filesystem,
-// as an abstraction layer.
-
-// Afero also provides a few implementations that are mostly interoperable. One that
-// uses the operating system filesystem, one that uses memory to store files
-// (cross platform) and an interface that should be implemented if you want to
-// provide your own filesystem.
-
-package afero
-
-import (
- "errors"
- "io"
- "os"
- "time"
-)
-
-type Afero struct {
- Fs
-}
-
-// File represents a file in the filesystem.
-type File interface {
- io.Closer
- io.Reader
- io.ReaderAt
- io.Seeker
- io.Writer
- io.WriterAt
-
- Name() string
- Readdir(count int) ([]os.FileInfo, error)
- Readdirnames(n int) ([]string, error)
- Stat() (os.FileInfo, error)
- Sync() error
- Truncate(size int64) error
- WriteString(s string) (ret int, err error)
-}
-
-// Fs is the filesystem interface.
-//
-// Any simulated or real filesystem should implement this interface.
-type Fs interface {
- // Create creates a file in the filesystem, returning the file and an
- // error, if any happens.
- Create(name string) (File, error)
-
- // Mkdir creates a directory in the filesystem, return an error if any
- // happens.
- Mkdir(name string, perm os.FileMode) error
-
- // MkdirAll creates a directory path and all parents that does not exist
- // yet.
- MkdirAll(path string, perm os.FileMode) error
-
- // Open opens a file, returning it or an error, if any happens.
- Open(name string) (File, error)
-
- // OpenFile opens a file using the given flags and the given mode.
- OpenFile(name string, flag int, perm os.FileMode) (File, error)
-
- // Remove removes a file identified by name, returning an error, if any
- // happens.
- Remove(name string) error
-
- // RemoveAll removes a directory path and any children it contains. It
- // does not fail if the path does not exist (return nil).
- RemoveAll(path string) error
-
- // Rename renames a file.
- Rename(oldname, newname string) error
-
- // Stat returns a FileInfo describing the named file, or an error, if any
- // happens.
- Stat(name string) (os.FileInfo, error)
-
- // The name of this FileSystem
- Name() string
-
- //Chmod changes the mode of the named file to mode.
- Chmod(name string, mode os.FileMode) error
-
- //Chtimes changes the access and modification times of the named file
- Chtimes(name string, atime time.Time, mtime time.Time) error
-}
-
-var (
- ErrFileClosed = errors.New("File is closed")
- ErrOutOfRange = errors.New("Out of range")
- ErrTooLarge = errors.New("Too large")
- ErrFileNotFound = os.ErrNotExist
- ErrFileExists = os.ErrExist
- ErrDestinationExists = os.ErrExist
-)
diff --git a/vendor/github.com/spf13/afero/afero_test.go b/vendor/github.com/spf13/afero/afero_test.go
deleted file mode 100644
index 526afa9..0000000
--- a/vendor/github.com/spf13/afero/afero_test.go
+++ /dev/null
@@ -1,699 +0,0 @@
-// Copyright © 2014 Steve Francia .
-// Copyright 2009 The Go Authors. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package afero
-
-import (
- "bytes"
- "fmt"
- "io"
- "io/ioutil"
- "os"
- "path/filepath"
- "runtime"
- "strings"
- "syscall"
- "testing"
-)
-
-var testName = "test.txt"
-var Fss = []Fs{&MemMapFs{}, &OsFs{}}
-
-var testRegistry map[Fs][]string = make(map[Fs][]string)
-
-func testDir(fs Fs) string {
- name, err := TempDir(fs, "", "afero")
- if err != nil {
- panic(fmt.Sprint("unable to work with test dir", err))
- }
- testRegistry[fs] = append(testRegistry[fs], name)
-
- return name
-}
-
-func tmpFile(fs Fs) File {
- x, err := TempFile(fs, "", "afero")
-
- if err != nil {
- panic(fmt.Sprint("unable to work with temp file", err))
- }
-
- testRegistry[fs] = append(testRegistry[fs], x.Name())
-
- return x
-}
-
-//Read with length 0 should not return EOF.
-func TestRead0(t *testing.T) {
- for _, fs := range Fss {
- f := tmpFile(fs)
- defer f.Close()
- f.WriteString("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")
-
- var b []byte
- // b := make([]byte, 0)
- n, err := f.Read(b)
- if n != 0 || err != nil {
- t.Errorf("%v: Read(0) = %d, %v, want 0, nil", fs.Name(), n, err)
- }
- f.Seek(0, 0)
- b = make([]byte, 100)
- n, err = f.Read(b)
- if n <= 0 || err != nil {
- t.Errorf("%v: Read(100) = %d, %v, want >0, nil", fs.Name(), n, err)
- }
- }
-}
-
-func TestOpenFile(t *testing.T) {
- defer removeAllTestFiles(t)
- for _, fs := range Fss {
- tmp := testDir(fs)
- path := filepath.Join(tmp, testName)
-
- f, err := fs.OpenFile(path, os.O_RDWR|os.O_CREATE, 0600)
- if err != nil {
- t.Error(fs.Name(), "OpenFile (O_CREATE) failed:", err)
- continue
- }
- io.WriteString(f, "initial")
- f.Close()
-
- f, err = fs.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0600)
- if err != nil {
- t.Error(fs.Name(), "OpenFile (O_APPEND) failed:", err)
- continue
- }
- io.WriteString(f, "|append")
- f.Close()
-
- f, err = fs.OpenFile(path, os.O_RDONLY, 0600)
- contents, _ := ioutil.ReadAll(f)
- expectedContents := "initial|append"
- if string(contents) != expectedContents {
- t.Errorf("%v: appending, expected '%v', got: '%v'", fs.Name(), expectedContents, string(contents))
- }
- f.Close()
-
- f, err = fs.OpenFile(path, os.O_RDWR|os.O_TRUNC, 0600)
- if err != nil {
- t.Error(fs.Name(), "OpenFile (O_TRUNC) failed:", err)
- continue
- }
- contents, _ = ioutil.ReadAll(f)
- if string(contents) != "" {
- t.Errorf("%v: expected truncated file, got: '%v'", fs.Name(), string(contents))
- }
- f.Close()
- }
-}
-
-func TestCreate(t *testing.T) {
- defer removeAllTestFiles(t)
- for _, fs := range Fss {
- tmp := testDir(fs)
- path := filepath.Join(tmp, testName)
-
- f, err := fs.Create(path)
- if err != nil {
- t.Error(fs.Name(), "Create failed:", err)
- f.Close()
- continue
- }
- io.WriteString(f, "initial")
- f.Close()
-
- f, err = fs.Create(path)
- if err != nil {
- t.Error(fs.Name(), "Create failed:", err)
- f.Close()
- continue
- }
- secondContent := "second create"
- io.WriteString(f, secondContent)
- f.Close()
-
- f, err = fs.Open(path)
- if err != nil {
- t.Error(fs.Name(), "Open failed:", err)
- f.Close()
- continue
- }
- buf, err := ReadAll(f)
- if err != nil {
- t.Error(fs.Name(), "ReadAll failed:", err)
- f.Close()
- continue
- }
- if string(buf) != secondContent {
- t.Error(fs.Name(), "Content should be", "\""+secondContent+"\" but is \""+string(buf)+"\"")
- f.Close()
- continue
- }
- f.Close()
- }
-}
-
-func TestMemFileRead(t *testing.T) {
- f := tmpFile(new(MemMapFs))
- // f := MemFileCreate("testfile")
- f.WriteString("abcd")
- f.Seek(0, 0)
- b := make([]byte, 8)
- n, err := f.Read(b)
- if n != 4 {
- t.Errorf("didn't read all bytes: %v %v %v", n, err, b)
- }
- if err != nil {
- t.Errorf("err is not nil: %v %v %v", n, err, b)
- }
- n, err = f.Read(b)
- if n != 0 {
- t.Errorf("read more bytes: %v %v %v", n, err, b)
- }
- if err != io.EOF {
- t.Errorf("error is not EOF: %v %v %v", n, err, b)
- }
-}
-
-func TestRename(t *testing.T) {
- defer removeAllTestFiles(t)
- for _, fs := range Fss {
- tDir := testDir(fs)
- from := filepath.Join(tDir, "/renamefrom")
- to := filepath.Join(tDir, "/renameto")
- exists := filepath.Join(tDir, "/renameexists")
- file, err := fs.Create(from)
- if err != nil {
- t.Fatalf("%s: open %q failed: %v", fs.Name(), to, err)
- }
- if err = file.Close(); err != nil {
- t.Errorf("%s: close %q failed: %v", fs.Name(), to, err)
- }
- file, err = fs.Create(exists)
- if err != nil {
- t.Fatalf("%s: open %q failed: %v", fs.Name(), to, err)
- }
- if err = file.Close(); err != nil {
- t.Errorf("%s: close %q failed: %v", fs.Name(), to, err)
- }
- err = fs.Rename(from, to)
- if err != nil {
- t.Fatalf("%s: rename %q, %q failed: %v", fs.Name(), to, from, err)
- }
- file, err = fs.Create(from)
- if err != nil {
- t.Fatalf("%s: open %q failed: %v", fs.Name(), to, err)
- }
- if err = file.Close(); err != nil {
- t.Errorf("%s: close %q failed: %v", fs.Name(), to, err)
- }
- err = fs.Rename(from, exists)
- if err != nil {
- t.Errorf("%s: rename %q, %q failed: %v", fs.Name(), exists, from, err)
- }
- names, err := readDirNames(fs, tDir)
- if err != nil {
- t.Errorf("%s: readDirNames error: %v", fs.Name(), err)
- }
- found := false
- for _, e := range names {
- if e == "renamefrom" {
- t.Error("File is still called renamefrom")
- }
- if e == "renameto" {
- found = true
- }
- }
- if !found {
- t.Error("File was not renamed to renameto")
- }
-
- _, err = fs.Stat(to)
- if err != nil {
- t.Errorf("%s: stat %q failed: %v", fs.Name(), to, err)
- }
- }
-}
-
-func TestRemove(t *testing.T) {
- for _, fs := range Fss {
-
- x, err := TempFile(fs, "", "afero")
- if err != nil {
- t.Error(fmt.Sprint("unable to work with temp file", err))
- }
-
- path := x.Name()
- x.Close()
-
- tDir := filepath.Dir(path)
-
- err = fs.Remove(path)
- if err != nil {
- t.Errorf("%v: Remove() failed: %v", fs.Name(), err)
- continue
- }
-
- _, err = fs.Stat(path)
- if !os.IsNotExist(err) {
- t.Errorf("%v: Remove() didn't remove file", fs.Name())
- continue
- }
-
- // Deleting non-existent file should raise error
- err = fs.Remove(path)
- if !os.IsNotExist(err) {
- t.Errorf("%v: Remove() didn't raise error for non-existent file", fs.Name())
- }
-
- f, err := fs.Open(tDir)
- if err != nil {
- t.Error("TestDir should still exist:", err)
- }
-
- names, err := f.Readdirnames(-1)
- if err != nil {
- t.Error("Readdirnames failed:", err)
- }
-
- for _, e := range names {
- if e == testName {
- t.Error("File was not removed from parent directory")
- }
- }
- }
-}
-
-func TestTruncate(t *testing.T) {
- defer removeAllTestFiles(t)
- for _, fs := range Fss {
- f := tmpFile(fs)
- defer f.Close()
-
- checkSize(t, f, 0)
- f.Write([]byte("hello, world\n"))
- checkSize(t, f, 13)
- f.Truncate(10)
- checkSize(t, f, 10)
- f.Truncate(1024)
- checkSize(t, f, 1024)
- f.Truncate(0)
- checkSize(t, f, 0)
- _, err := f.Write([]byte("surprise!"))
- if err == nil {
- checkSize(t, f, 13+9) // wrote at offset past where hello, world was.
- }
- }
-}
-
-func TestSeek(t *testing.T) {
- defer removeAllTestFiles(t)
- for _, fs := range Fss {
- f := tmpFile(fs)
- defer f.Close()
-
- const data = "hello, world\n"
- io.WriteString(f, data)
-
- type test struct {
- in int64
- whence int
- out int64
- }
- var tests = []test{
- {0, 1, int64(len(data))},
- {0, 0, 0},
- {5, 0, 5},
- {0, 2, int64(len(data))},
- {0, 0, 0},
- {-1, 2, int64(len(data)) - 1},
- {1 << 33, 0, 1 << 33},
- {1 << 33, 2, 1<<33 + int64(len(data))},
- }
- for i, tt := range tests {
- off, err := f.Seek(tt.in, tt.whence)
- if off != tt.out || err != nil {
- if e, ok := err.(*os.PathError); ok && e.Err == syscall.EINVAL && tt.out > 1<<32 {
- // Reiserfs rejects the big seeks.
- // http://code.google.com/p/go/issues/detail?id=91
- break
- }
- t.Errorf("#%d: Seek(%v, %v) = %v, %v want %v, nil", i, tt.in, tt.whence, off, err, tt.out)
- }
- }
- }
-}
-
-func TestReadAt(t *testing.T) {
- defer removeAllTestFiles(t)
- for _, fs := range Fss {
- f := tmpFile(fs)
- defer f.Close()
-
- const data = "hello, world\n"
- io.WriteString(f, data)
-
- b := make([]byte, 5)
- n, err := f.ReadAt(b, 7)
- if err != nil || n != len(b) {
- t.Fatalf("ReadAt 7: %d, %v", n, err)
- }
- if string(b) != "world" {
- t.Fatalf("ReadAt 7: have %q want %q", string(b), "world")
- }
- }
-}
-
-func TestWriteAt(t *testing.T) {
- defer removeAllTestFiles(t)
- for _, fs := range Fss {
- f := tmpFile(fs)
- defer f.Close()
-
- const data = "hello, world\n"
- io.WriteString(f, data)
-
- n, err := f.WriteAt([]byte("WORLD"), 7)
- if err != nil || n != 5 {
- t.Fatalf("WriteAt 7: %d, %v", n, err)
- }
-
- f2, err := fs.Open(f.Name())
- if err != nil {
- t.Fatalf("%v: ReadFile %s: %v", fs.Name(), f.Name(), err)
- }
- defer f2.Close()
- buf := new(bytes.Buffer)
- buf.ReadFrom(f2)
- b := buf.Bytes()
- if string(b) != "hello, WORLD\n" {
- t.Fatalf("after write: have %q want %q", string(b), "hello, WORLD\n")
- }
-
- }
-}
-
-func setupTestDir(t *testing.T, fs Fs) string {
- path := testDir(fs)
- return setupTestFiles(t, fs, path)
-}
-
-func setupTestDirRoot(t *testing.T, fs Fs) string {
- path := testDir(fs)
- setupTestFiles(t, fs, path)
- return path
-}
-
-func setupTestDirReusePath(t *testing.T, fs Fs, path string) string {
- testRegistry[fs] = append(testRegistry[fs], path)
- return setupTestFiles(t, fs, path)
-}
-
-func setupTestFiles(t *testing.T, fs Fs, path string) string {
- testSubDir := filepath.Join(path, "more", "subdirectories", "for", "testing", "we")
- err := fs.MkdirAll(testSubDir, 0700)
- if err != nil && !os.IsExist(err) {
- t.Fatal(err)
- }
-
- f, err := fs.Create(filepath.Join(testSubDir, "testfile1"))
- if err != nil {
- t.Fatal(err)
- }
- f.WriteString("Testfile 1 content")
- f.Close()
-
- f, err = fs.Create(filepath.Join(testSubDir, "testfile2"))
- if err != nil {
- t.Fatal(err)
- }
- f.WriteString("Testfile 2 content")
- f.Close()
-
- f, err = fs.Create(filepath.Join(testSubDir, "testfile3"))
- if err != nil {
- t.Fatal(err)
- }
- f.WriteString("Testfile 3 content")
- f.Close()
-
- f, err = fs.Create(filepath.Join(testSubDir, "testfile4"))
- if err != nil {
- t.Fatal(err)
- }
- f.WriteString("Testfile 4 content")
- f.Close()
- return testSubDir
-}
-
-func TestReaddirnames(t *testing.T) {
- defer removeAllTestFiles(t)
- for _, fs := range Fss {
- testSubDir := setupTestDir(t, fs)
- tDir := filepath.Dir(testSubDir)
-
- root, err := fs.Open(tDir)
- if err != nil {
- t.Fatal(fs.Name(), tDir, err)
- }
- defer root.Close()
-
- namesRoot, err := root.Readdirnames(-1)
- if err != nil {
- t.Fatal(fs.Name(), namesRoot, err)
- }
-
- sub, err := fs.Open(testSubDir)
- if err != nil {
- t.Fatal(err)
- }
- defer sub.Close()
-
- namesSub, err := sub.Readdirnames(-1)
- if err != nil {
- t.Fatal(fs.Name(), namesSub, err)
- }
-
- findNames(fs, t, tDir, testSubDir, namesRoot, namesSub)
- }
-}
-
-func TestReaddirSimple(t *testing.T) {
- defer removeAllTestFiles(t)
- for _, fs := range Fss {
- testSubDir := setupTestDir(t, fs)
- tDir := filepath.Dir(testSubDir)
-
- root, err := fs.Open(tDir)
- if err != nil {
- t.Fatal(err)
- }
- defer root.Close()
-
- rootInfo, err := root.Readdir(1)
- if err != nil {
- t.Log(myFileInfo(rootInfo))
- t.Error(err)
- }
-
- rootInfo, err = root.Readdir(5)
- if err != io.EOF {
- t.Log(myFileInfo(rootInfo))
- t.Error(err)
- }
-
- sub, err := fs.Open(testSubDir)
- if err != nil {
- t.Fatal(err)
- }
- defer sub.Close()
-
- subInfo, err := sub.Readdir(5)
- if err != nil {
- t.Log(myFileInfo(subInfo))
- t.Error(err)
- }
- }
-}
-
-func TestReaddir(t *testing.T) {
- defer removeAllTestFiles(t)
- for num := 0; num < 6; num++ {
- outputs := make([]string, len(Fss))
- infos := make([]string, len(Fss))
- for i, fs := range Fss {
- testSubDir := setupTestDir(t, fs)
- //tDir := filepath.Dir(testSubDir)
- root, err := fs.Open(testSubDir)
- if err != nil {
- t.Fatal(err)
- }
- defer root.Close()
-
- for j := 0; j < 6; j++ {
- info, err := root.Readdir(num)
- outputs[i] += fmt.Sprintf("%v Error: %v\n", myFileInfo(info), err)
- infos[i] += fmt.Sprintln(len(info), err)
- }
- }
-
- fail := false
- for i, o := range infos {
- if i == 0 {
- continue
- }
- if o != infos[i-1] {
- fail = true
- break
- }
- }
- if fail {
- t.Log("Readdir outputs not equal for Readdir(", num, ")")
- for i, o := range outputs {
- t.Log(Fss[i].Name())
- t.Log(o)
- }
- t.Fail()
- }
- }
-}
-
-type myFileInfo []os.FileInfo
-
-func (m myFileInfo) String() string {
- out := "Fileinfos:\n"
- for _, e := range m {
- out += " " + e.Name() + "\n"
- }
- return out
-}
-
-func TestReaddirAll(t *testing.T) {
- defer removeAllTestFiles(t)
- for _, fs := range Fss {
- testSubDir := setupTestDir(t, fs)
- tDir := filepath.Dir(testSubDir)
-
- root, err := fs.Open(tDir)
- if err != nil {
- t.Fatal(err)
- }
- defer root.Close()
-
- rootInfo, err := root.Readdir(-1)
- if err != nil {
- t.Fatal(err)
- }
- var namesRoot = []string{}
- for _, e := range rootInfo {
- namesRoot = append(namesRoot, e.Name())
- }
-
- sub, err := fs.Open(testSubDir)
- if err != nil {
- t.Fatal(err)
- }
- defer sub.Close()
-
- subInfo, err := sub.Readdir(-1)
- if err != nil {
- t.Fatal(err)
- }
- var namesSub = []string{}
- for _, e := range subInfo {
- namesSub = append(namesSub, e.Name())
- }
-
- findNames(fs, t, tDir, testSubDir, namesRoot, namesSub)
- }
-}
-
-func findNames(fs Fs, t *testing.T, tDir, testSubDir string, root, sub []string) {
- var foundRoot bool
- for _, e := range root {
- f, err := fs.Open(filepath.Join(tDir, e))
- if err != nil {
- t.Error("Open", filepath.Join(tDir, e), ":", err)
- }
- defer f.Close()
-
- if equal(e, "we") {
- foundRoot = true
- }
- }
- if !foundRoot {
- t.Logf("Names root: %v", root)
- t.Logf("Names sub: %v", sub)
- t.Error("Didn't find subdirectory we")
- }
-
- var found1, found2 bool
- for _, e := range sub {
- f, err := fs.Open(filepath.Join(testSubDir, e))
- if err != nil {
- t.Error("Open", filepath.Join(testSubDir, e), ":", err)
- }
- defer f.Close()
-
- if equal(e, "testfile1") {
- found1 = true
- }
- if equal(e, "testfile2") {
- found2 = true
- }
- }
-
- if !found1 {
- t.Logf("Names root: %v", root)
- t.Logf("Names sub: %v", sub)
- t.Error("Didn't find testfile1")
- }
- if !found2 {
- t.Logf("Names root: %v", root)
- t.Logf("Names sub: %v", sub)
- t.Error("Didn't find testfile2")
- }
-}
-
-func removeAllTestFiles(t *testing.T) {
- for fs, list := range testRegistry {
- for _, path := range list {
- if err := fs.RemoveAll(path); err != nil {
- t.Error(fs.Name(), err)
- }
- }
- }
- testRegistry = make(map[Fs][]string)
-}
-
-func equal(name1, name2 string) (r bool) {
- switch runtime.GOOS {
- case "windows":
- r = strings.ToLower(name1) == strings.ToLower(name2)
- default:
- r = name1 == name2
- }
- return
-}
-
-func checkSize(t *testing.T, f File, size int64) {
- dir, err := f.Stat()
- if err != nil {
- t.Fatalf("Stat %q (looking for size %d): %s", f.Name(), size, err)
- }
- if dir.Size() != size {
- t.Errorf("Stat %q: size %d want %d", f.Name(), dir.Size(), size)
- }
-}
diff --git a/vendor/github.com/spf13/afero/appveyor.yml b/vendor/github.com/spf13/afero/appveyor.yml
deleted file mode 100644
index a633ad5..0000000
--- a/vendor/github.com/spf13/afero/appveyor.yml
+++ /dev/null
@@ -1,15 +0,0 @@
-version: '{build}'
-clone_folder: C:\gopath\src\github.com\spf13\afero
-environment:
- GOPATH: C:\gopath
-build_script:
-- cmd: >-
- go version
-
- go env
-
- go get -v github.com/spf13/afero/...
-
- go build github.com/spf13/afero
-test_script:
-- cmd: go test -race -v github.com/spf13/afero/...
diff --git a/vendor/github.com/spf13/afero/basepath.go b/vendor/github.com/spf13/afero/basepath.go
deleted file mode 100644
index 5e4fc2e..0000000
--- a/vendor/github.com/spf13/afero/basepath.go
+++ /dev/null
@@ -1,145 +0,0 @@
-package afero
-
-import (
- "errors"
- "os"
- "path/filepath"
- "runtime"
- "strings"
- "time"
-)
-
-// The BasePathFs restricts all operations to a given path within an Fs.
-// The given file name to the operations on this Fs will be prepended with
-// the base path before calling the base Fs.
-// Any file name (after filepath.Clean()) outside this base path will be
-// treated as non existing file.
-//
-// Note that it does not clean the error messages on return, so you may
-// reveal the real path on errors.
-type BasePathFs struct {
- source Fs
- path string
-}
-
-func NewBasePathFs(source Fs, path string) Fs {
- return &BasePathFs{source: source, path: path}
-}
-
-// on a file outside the base path it returns the given file name and an error,
-// else the given file with the base path prepended
-func (b *BasePathFs) RealPath(name string) (path string, err error) {
- if err := validateBasePathName(name); err != nil {
- return "", err
- }
-
- bpath := filepath.Clean(b.path)
- path = filepath.Clean(filepath.Join(bpath, name))
- if !strings.HasPrefix(path, bpath) {
- return name, os.ErrNotExist
- }
-
- return path, nil
-}
-
-func validateBasePathName(name string) error {
- if runtime.GOOS != "windows" {
- // Not much to do here;
- // the virtual file paths all look absolute on *nix.
- return nil
- }
-
- // On Windows a common mistake would be to provide an absolute OS path
- // We could strip out the base part, but that would not be very portable.
- if filepath.IsAbs(name) {
- return &os.PathError{Op: "realPath", Path: name, Err: errors.New("got a real OS path instead of a virtual")}
- }
-
- return nil
-}
-
-func (b *BasePathFs) Chtimes(name string, atime, mtime time.Time) (err error) {
- if name, err = b.RealPath(name); err != nil {
- return &os.PathError{Op: "chtimes", Path: name, Err: err}
- }
- return b.source.Chtimes(name, atime, mtime)
-}
-
-func (b *BasePathFs) Chmod(name string, mode os.FileMode) (err error) {
- if name, err = b.RealPath(name); err != nil {
- return &os.PathError{Op: "chmod", Path: name, Err: err}
- }
- return b.source.Chmod(name, mode)
-}
-
-func (b *BasePathFs) Name() string {
- return "BasePathFs"
-}
-
-func (b *BasePathFs) Stat(name string) (fi os.FileInfo, err error) {
- if name, err = b.RealPath(name); err != nil {
- return nil, &os.PathError{Op: "stat", Path: name, Err: err}
- }
- return b.source.Stat(name)
-}
-
-func (b *BasePathFs) Rename(oldname, newname string) (err error) {
- if oldname, err = b.RealPath(oldname); err != nil {
- return &os.PathError{Op: "rename", Path: oldname, Err: err}
- }
- if newname, err = b.RealPath(newname); err != nil {
- return &os.PathError{Op: "rename", Path: newname, Err: err}
- }
- return b.source.Rename(oldname, newname)
-}
-
-func (b *BasePathFs) RemoveAll(name string) (err error) {
- if name, err = b.RealPath(name); err != nil {
- return &os.PathError{Op: "remove_all", Path: name, Err: err}
- }
- return b.source.RemoveAll(name)
-}
-
-func (b *BasePathFs) Remove(name string) (err error) {
- if name, err = b.RealPath(name); err != nil {
- return &os.PathError{Op: "remove", Path: name, Err: err}
- }
- return b.source.Remove(name)
-}
-
-func (b *BasePathFs) OpenFile(name string, flag int, mode os.FileMode) (f File, err error) {
- if name, err = b.RealPath(name); err != nil {
- return nil, &os.PathError{Op: "openfile", Path: name, Err: err}
- }
- return b.source.OpenFile(name, flag, mode)
-}
-
-func (b *BasePathFs) Open(name string) (f File, err error) {
- if name, err = b.RealPath(name); err != nil {
- return nil, &os.PathError{Op: "open", Path: name, Err: err}
- }
- return b.source.Open(name)
-}
-
-func (b *BasePathFs) Mkdir(name string, mode os.FileMode) (err error) {
- if name, err = b.RealPath(name); err != nil {
- return &os.PathError{Op: "mkdir", Path: name, Err: err}
- }
- return b.source.Mkdir(name, mode)
-}
-
-func (b *BasePathFs) MkdirAll(name string, mode os.FileMode) (err error) {
- if name, err = b.RealPath(name); err != nil {
- return &os.PathError{Op: "mkdir", Path: name, Err: err}
- }
- return b.source.MkdirAll(name, mode)
-}
-
-func (b *BasePathFs) Create(name string) (f File, err error) {
- if name, err = b.RealPath(name); err != nil {
- return nil, &os.PathError{Op: "create", Path: name, Err: err}
- }
- return b.source.Create(name)
-}
-
-// vim: ts=4 sw=4 noexpandtab nolist syn=go
diff --git a/vendor/github.com/spf13/afero/basepath_test.go b/vendor/github.com/spf13/afero/basepath_test.go
deleted file mode 100644
index abc22b9..0000000
--- a/vendor/github.com/spf13/afero/basepath_test.go
+++ /dev/null
@@ -1,142 +0,0 @@
-package afero
-
-import (
- "os"
- "path/filepath"
- "runtime"
- "testing"
-)
-
-func TestBasePath(t *testing.T) {
- baseFs := &MemMapFs{}
- baseFs.MkdirAll("/base/path/tmp", 0777)
- bp := NewBasePathFs(baseFs, "/base/path")
-
- if _, err := bp.Create("/tmp/foo"); err != nil {
- t.Errorf("Failed to set real path")
- }
-
- if fh, err := bp.Create("../tmp/bar"); err == nil {
- t.Errorf("succeeded in creating %s ...", fh.Name())
- }
-}
-
-func TestBasePathRoot(t *testing.T) {
- baseFs := &MemMapFs{}
- baseFs.MkdirAll("/base/path/foo/baz", 0777)
- baseFs.MkdirAll("/base/path/boo/", 0777)
- bp := NewBasePathFs(baseFs, "/base/path")
-
- rd, err := ReadDir(bp, string(os.PathSeparator))
-
- if len(rd) != 2 {
- t.Errorf("base path doesn't respect root")
- }
-
- if err != nil {
- t.Error(err)
- }
-}
-
-func TestRealPath(t *testing.T) {
- fs := NewOsFs()
- baseDir, err := TempDir(fs, "", "base")
- if err != nil {
- t.Fatal("error creating tempDir", err)
- }
- defer fs.RemoveAll(baseDir)
- anotherDir, err := TempDir(fs, "", "another")
- if err != nil {
- t.Fatal("error creating tempDir", err)
- }
- defer fs.RemoveAll(anotherDir)
-
- bp := NewBasePathFs(fs, baseDir).(*BasePathFs)
-
- subDir := filepath.Join(baseDir, "s1")
-
- realPath, err := bp.RealPath("/s1")
-
- if err != nil {
- t.Errorf("Got error %s", err)
- }
-
- if realPath != subDir {
- t.Errorf("Expected \n%s got \n%s", subDir, realPath)
- }
-
- if runtime.GOOS == "windows" {
- _, err = bp.RealPath(anotherDir)
-
- if err == nil {
- t.Errorf("Expected error")
- }
-
- } else {
- // on *nix we have no way of just looking at the path and tell that anotherDir
- // is not inside the base file system.
- // The user will receive an os.ErrNotExist later.
- surrealPath, err := bp.RealPath(anotherDir)
-
- if err != nil {
- t.Errorf("Got error %s", err)
- }
-
- excpected := filepath.Join(baseDir, anotherDir)
-
- if surrealPath != excpected {
- t.Errorf("Expected \n%s got \n%s", excpected, surrealPath)
- }
- }
-
-}
-
-func TestNestedBasePaths(t *testing.T) {
- type dirSpec struct {
- Dir1, Dir2, Dir3 string
- }
- dirSpecs := []dirSpec{
- dirSpec{Dir1: "/", Dir2: "/", Dir3: "/"},
- dirSpec{Dir1: "/", Dir2: "/path2", Dir3: "/"},
- dirSpec{Dir1: "/path1/dir", Dir2: "/path2/dir/", Dir3: "/path3/dir"},
- dirSpec{Dir1: "C:/path1", Dir2: "path2/dir", Dir3: "/path3/dir/"},
- }
-
- for _, ds := range dirSpecs {
- memFs := NewMemMapFs()
- level1Fs := NewBasePathFs(memFs, ds.Dir1)
- level2Fs := NewBasePathFs(level1Fs, ds.Dir2)
- level3Fs := NewBasePathFs(level2Fs, ds.Dir3)
-
- type spec struct {
- BaseFs Fs
- FileName string
- }
- specs := []spec{
- spec{BaseFs: level3Fs, FileName: "f.txt"},
- spec{BaseFs: level2Fs, FileName: "f.txt"},
- spec{BaseFs: level1Fs, FileName: "f.txt"},
- }
-
- for _, s := range specs {
- if err := s.BaseFs.MkdirAll(s.FileName, 0755); err != nil {
- t.Errorf("Got error %s", err.Error())
- }
- if _, err := s.BaseFs.Stat(s.FileName); err != nil {
- t.Errorf("Got error %s", err.Error())
- }
-
- if s.BaseFs == level3Fs {
- pathToExist := filepath.Join(ds.Dir3, s.FileName)
- if _, err := level2Fs.Stat(pathToExist); err != nil {
- t.Errorf("Got error %s (path %s)", err.Error(), pathToExist)
- }
- } else if s.BaseFs == level2Fs {
- pathToExist := filepath.Join(ds.Dir2, ds.Dir3, s.FileName)
- if _, err := level1Fs.Stat(pathToExist); err != nil {
- t.Errorf("Got error %s (path %s)", err.Error(), pathToExist)
- }
- }
- }
- }
-}
diff --git a/vendor/github.com/spf13/afero/cacheOnReadFs.go b/vendor/github.com/spf13/afero/cacheOnReadFs.go
deleted file mode 100644
index b026e0d..0000000
--- a/vendor/github.com/spf13/afero/cacheOnReadFs.go
+++ /dev/null
@@ -1,290 +0,0 @@
-package afero
-
-import (
- "os"
- "syscall"
- "time"
-)
-
-// If the cache duration is 0, cache time will be unlimited, i.e. once
-// a file is in the layer, the base will never be read again for this file.
-//
-// For cache times greater than 0, the modification time of a file is
-// checked. Note that a lot of file system implementations only allow a
-// resolution of a second for timestamps... or as the godoc for os.Chtimes()
-// states: "The underlying filesystem may truncate or round the values to a
-// less precise time unit."
-//
-// This caching union will forward all write calls also to the base file
-// system first. To prevent writing to the base Fs, wrap it in a read-only
-// filter - Note: this will also make the overlay read-only, for writing files
-// in the overlay, use the overlay Fs directly, not via the union Fs.
-type CacheOnReadFs struct {
- base Fs
- layer Fs
- cacheTime time.Duration
-}
-
-func NewCacheOnReadFs(base Fs, layer Fs, cacheTime time.Duration) Fs {
- return &CacheOnReadFs{base: base, layer: layer, cacheTime: cacheTime}
-}
-
-type cacheState int
-
-const (
- // not present in the overlay, unknown if it exists in the base:
- cacheMiss cacheState = iota
- // present in the overlay and in base, base file is newer:
- cacheStale
- // present in the overlay - with cache time == 0 it may exist in the base,
- // with cacheTime > 0 it exists in the base and is same age or newer in the
- // overlay
- cacheHit
- // happens if someone writes directly to the overlay without
- // going through this union
- cacheLocal
-)
-
-func (u *CacheOnReadFs) cacheStatus(name string) (state cacheState, fi os.FileInfo, err error) {
- var lfi, bfi os.FileInfo
- lfi, err = u.layer.Stat(name)
- if err == nil {
- if u.cacheTime == 0 {
- return cacheHit, lfi, nil
- }
- if lfi.ModTime().Add(u.cacheTime).Before(time.Now()) {
- bfi, err = u.base.Stat(name)
- if err != nil {
- return cacheLocal, lfi, nil
- }
- if bfi.ModTime().After(lfi.ModTime()) {
- return cacheStale, bfi, nil
- }
- }
- return cacheHit, lfi, nil
- }
-
- if err == syscall.ENOENT || os.IsNotExist(err) {
- return cacheMiss, nil, nil
- }
-
- return cacheMiss, nil, err
-}
-
-func (u *CacheOnReadFs) copyToLayer(name string) error {
- return copyToLayer(u.base, u.layer, name)
-}
-
-func (u *CacheOnReadFs) Chtimes(name string, atime, mtime time.Time) error {
- st, _, err := u.cacheStatus(name)
- if err != nil {
- return err
- }
- switch st {
- case cacheLocal:
- case cacheHit:
- err = u.base.Chtimes(name, atime, mtime)
- case cacheStale, cacheMiss:
- if err := u.copyToLayer(name); err != nil {
- return err
- }
- err = u.base.Chtimes(name, atime, mtime)
- }
- if err != nil {
- return err
- }
- return u.layer.Chtimes(name, atime, mtime)
-}
-
-func (u *CacheOnReadFs) Chmod(name string, mode os.FileMode) error {
- st, _, err := u.cacheStatus(name)
- if err != nil {
- return err
- }
- switch st {
- case cacheLocal:
- case cacheHit:
- err = u.base.Chmod(name, mode)
- case cacheStale, cacheMiss:
- if err := u.copyToLayer(name); err != nil {
- return err
- }
- err = u.base.Chmod(name, mode)
- }
- if err != nil {
- return err
- }
- return u.layer.Chmod(name, mode)
-}
-
-func (u *CacheOnReadFs) Stat(name string) (os.FileInfo, error) {
- st, fi, err := u.cacheStatus(name)
- if err != nil {
- return nil, err
- }
- switch st {
- case cacheMiss:
- return u.base.Stat(name)
- default: // cacheStale has base, cacheHit and cacheLocal the layer os.FileInfo
- return fi, nil
- }
-}
-
-func (u *CacheOnReadFs) Rename(oldname, newname string) error {
- st, _, err := u.cacheStatus(oldname)
- if err != nil {
- return err
- }
- switch st {
- case cacheLocal:
- case cacheHit:
- err = u.base.Rename(oldname, newname)
- case cacheStale, cacheMiss:
- if err := u.copyToLayer(oldname); err != nil {
- return err
- }
- err = u.base.Rename(oldname, newname)
- }
- if err != nil {
- return err
- }
- return u.layer.Rename(oldname, newname)
-}
-
-func (u *CacheOnReadFs) Remove(name string) error {
- st, _, err := u.cacheStatus(name)
- if err != nil {
- return err
- }
- switch st {
- case cacheLocal:
- case cacheHit, cacheStale, cacheMiss:
- err = u.base.Remove(name)
- }
- if err != nil {
- return err
- }
- return u.layer.Remove(name)
-}
-
-func (u *CacheOnReadFs) RemoveAll(name string) error {
- st, _, err := u.cacheStatus(name)
- if err != nil {
- return err
- }
- switch st {
- case cacheLocal:
- case cacheHit, cacheStale, cacheMiss:
- err = u.base.RemoveAll(name)
- }
- if err != nil {
- return err
- }
- return u.layer.RemoveAll(name)
-}
-
-func (u *CacheOnReadFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
- st, _, err := u.cacheStatus(name)
- if err != nil {
- return nil, err
- }
- switch st {
- case cacheLocal, cacheHit:
- default:
- if err := u.copyToLayer(name); err != nil {
- return nil, err
- }
- }
- if flag&(os.O_WRONLY|syscall.O_RDWR|os.O_APPEND|os.O_CREATE|os.O_TRUNC) != 0 {
- bfi, err := u.base.OpenFile(name, flag, perm)
- if err != nil {
- return nil, err
- }
- lfi, err := u.layer.OpenFile(name, flag, perm)
- if err != nil {
- bfi.Close() // oops, what if O_TRUNC was set and file opening in the layer failed...?
- return nil, err
- }
- return &UnionFile{base: bfi, layer: lfi}, nil
- }
- return u.layer.OpenFile(name, flag, perm)
-}
-
-func (u *CacheOnReadFs) Open(name string) (File, error) {
- st, fi, err := u.cacheStatus(name)
- if err != nil {
- return nil, err
- }
-
- switch st {
- case cacheLocal:
- return u.layer.Open(name)
-
- case cacheMiss:
- bfi, err := u.base.Stat(name)
- if err != nil {
- return nil, err
- }
- if bfi.IsDir() {
- return u.base.Open(name)
- }
- if err := u.copyToLayer(name); err != nil {
- return nil, err
- }
- return u.layer.Open(name)
-
- case cacheStale:
- if !fi.IsDir() {
- if err := u.copyToLayer(name); err != nil {
- return nil, err
- }
- return u.layer.Open(name)
- }
- case cacheHit:
- if !fi.IsDir() {
- return u.layer.Open(name)
- }
- }
- // the dirs from cacheHit, cacheStale fall down here:
- bfile, _ := u.base.Open(name)
- lfile, err := u.layer.Open(name)
- if err != nil && bfile == nil {
- return nil, err
- }
- return &UnionFile{base: bfile, layer: lfile}, nil
-}
-
-func (u *CacheOnReadFs) Mkdir(name string, perm os.FileMode) error {
- err := u.base.Mkdir(name, perm)
- if err != nil {
- return err
- }
- return u.layer.MkdirAll(name, perm) // yes, MkdirAll... we cannot assume it exists in the cache
-}
-
-func (u *CacheOnReadFs) Name() string {
- return "CacheOnReadFs"
-}
-
-func (u *CacheOnReadFs) MkdirAll(name string, perm os.FileMode) error {
- err := u.base.MkdirAll(name, perm)
- if err != nil {
- return err
- }
- return u.layer.MkdirAll(name, perm)
-}
-
-func (u *CacheOnReadFs) Create(name string) (File, error) {
- bfh, err := u.base.Create(name)
- if err != nil {
- return nil, err
- }
- lfh, err := u.layer.Create(name)
- if err != nil {
- // oops, see comment about OS_TRUNC above, should we remove? then we have to
- // remember if the file did not exist before
- bfh.Close()
- return nil, err
- }
- return &UnionFile{base: bfh, layer: lfh}, nil
-}
diff --git a/vendor/github.com/spf13/afero/composite_test.go b/vendor/github.com/spf13/afero/composite_test.go
deleted file mode 100644
index 8e44611..0000000
--- a/vendor/github.com/spf13/afero/composite_test.go
+++ /dev/null
@@ -1,404 +0,0 @@
-package afero
-
-import (
- "bytes"
- "fmt"
- "io/ioutil"
- "os"
- "testing"
- "time"
-)
-
-var tempDirs []string
-
-func NewTempOsBaseFs(t *testing.T) Fs {
- name, err := TempDir(NewOsFs(), "", "")
- if err != nil {
- t.Error("error creating tempDir", err)
- }
-
- tempDirs = append(tempDirs, name)
-
- return NewBasePathFs(NewOsFs(), name)
-}
-
-func CleanupTempDirs(t *testing.T) {
- osfs := NewOsFs()
- type ev struct {
- path string
- e error
- }
-
- errs := []ev{}
-
- for _, x := range tempDirs {
- err := osfs.RemoveAll(x)
- if err != nil {
- errs = append(errs, ev{path: x, e: err})
- }
- }
-
- for _, e := range errs {
- fmt.Println("error removing tempDir", e.path, e.e)
- }
-
- if len(errs) > 0 {
- t.Error("error cleaning up tempDirs")
- }
- tempDirs = []string{}
-}
-
-func TestUnionCreateExisting(t *testing.T) {
- base := &MemMapFs{}
- roBase := &ReadOnlyFs{source: base}
-
- ufs := NewCopyOnWriteFs(roBase, &MemMapFs{})
-
- base.MkdirAll("/home/test", 0777)
- fh, _ := base.Create("/home/test/file.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- fh, err := ufs.OpenFile("/home/test/file.txt", os.O_RDWR, 0666)
- if err != nil {
- t.Errorf("Failed to open file r/w: %s", err)
- }
-
- _, err = fh.Write([]byte("####"))
- if err != nil {
- t.Errorf("Failed to write file: %s", err)
- }
- fh.Seek(0, 0)
- data, err := ioutil.ReadAll(fh)
- if err != nil {
- t.Errorf("Failed to read file: %s", err)
- }
- if string(data) != "#### is a test" {
- t.Errorf("Got wrong data")
- }
- fh.Close()
-
- fh, _ = base.Open("/home/test/file.txt")
- data, err = ioutil.ReadAll(fh)
- if string(data) != "This is a test" {
- t.Errorf("Got wrong data in base file")
- }
- fh.Close()
-
- fh, err = ufs.Create("/home/test/file.txt")
- switch err {
- case nil:
- if fi, _ := fh.Stat(); fi.Size() != 0 {
- t.Errorf("Create did not truncate file")
- }
- fh.Close()
- default:
- t.Errorf("Create failed on existing file")
- }
-
-}
-
-func TestUnionMergeReaddir(t *testing.T) {
- base := &MemMapFs{}
- roBase := &ReadOnlyFs{source: base}
-
- ufs := &CopyOnWriteFs{base: roBase, layer: &MemMapFs{}}
-
- base.MkdirAll("/home/test", 0777)
- fh, _ := base.Create("/home/test/file.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- fh, _ = ufs.Create("/home/test/file2.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- fh, _ = ufs.Open("/home/test")
- files, err := fh.Readdirnames(-1)
- if err != nil {
- t.Errorf("Readdirnames failed")
- }
- if len(files) != 2 {
- t.Errorf("Got wrong number of files: %v", files)
- }
-}
-
-func TestExistingDirectoryCollisionReaddir(t *testing.T) {
- base := &MemMapFs{}
- roBase := &ReadOnlyFs{source: base}
- overlay := &MemMapFs{}
-
- ufs := &CopyOnWriteFs{base: roBase, layer: overlay}
-
- base.MkdirAll("/home/test", 0777)
- fh, _ := base.Create("/home/test/file.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- overlay.MkdirAll("home/test", 0777)
- fh, _ = overlay.Create("/home/test/file2.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- fh, _ = ufs.Create("/home/test/file3.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- fh, _ = ufs.Open("/home/test")
- files, err := fh.Readdirnames(-1)
- if err != nil {
- t.Errorf("Readdirnames failed")
- }
- if len(files) != 3 {
- t.Errorf("Got wrong number of files in union: %v", files)
- }
-
- fh, _ = overlay.Open("/home/test")
- files, err = fh.Readdirnames(-1)
- if err != nil {
- t.Errorf("Readdirnames failed")
- }
- if len(files) != 2 {
- t.Errorf("Got wrong number of files in overlay: %v", files)
- }
-}
-
-func TestNestedDirBaseReaddir(t *testing.T) {
- base := &MemMapFs{}
- roBase := &ReadOnlyFs{source: base}
- overlay := &MemMapFs{}
-
- ufs := &CopyOnWriteFs{base: roBase, layer: overlay}
-
- base.MkdirAll("/home/test/foo/bar", 0777)
- fh, _ := base.Create("/home/test/file.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- fh, _ = base.Create("/home/test/foo/file2.txt")
- fh.WriteString("This is a test")
- fh.Close()
- fh, _ = base.Create("/home/test/foo/bar/file3.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- overlay.MkdirAll("/", 0777)
-
- // Opening something only in the base
- fh, _ = ufs.Open("/home/test/foo")
- list, err := fh.Readdir(-1)
- if err != nil {
- t.Errorf("Readdir failed %s", err)
- }
- if len(list) != 2 {
- for _, x := range list {
- fmt.Println(x.Name())
- }
- t.Errorf("Got wrong number of files in union: %v", len(list))
- }
-}
-
-func TestNestedDirOverlayReaddir(t *testing.T) {
- base := &MemMapFs{}
- roBase := &ReadOnlyFs{source: base}
- overlay := &MemMapFs{}
-
- ufs := &CopyOnWriteFs{base: roBase, layer: overlay}
-
- base.MkdirAll("/", 0777)
- overlay.MkdirAll("/home/test/foo/bar", 0777)
- fh, _ := overlay.Create("/home/test/file.txt")
- fh.WriteString("This is a test")
- fh.Close()
- fh, _ = overlay.Create("/home/test/foo/file2.txt")
- fh.WriteString("This is a test")
- fh.Close()
- fh, _ = overlay.Create("/home/test/foo/bar/file3.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- // Opening nested dir only in the overlay
- fh, _ = ufs.Open("/home/test/foo")
- list, err := fh.Readdir(-1)
- if err != nil {
- t.Errorf("Readdir failed %s", err)
- }
- if len(list) != 2 {
- for _, x := range list {
- fmt.Println(x.Name())
- }
- t.Errorf("Got wrong number of files in union: %v", len(list))
- }
-}
-
-func TestNestedDirOverlayOsFsReaddir(t *testing.T) {
- defer CleanupTempDirs(t)
- base := NewTempOsBaseFs(t)
- roBase := &ReadOnlyFs{source: base}
- overlay := NewTempOsBaseFs(t)
-
- ufs := &CopyOnWriteFs{base: roBase, layer: overlay}
-
- base.MkdirAll("/", 0777)
- overlay.MkdirAll("/home/test/foo/bar", 0777)
- fh, _ := overlay.Create("/home/test/file.txt")
- fh.WriteString("This is a test")
- fh.Close()
- fh, _ = overlay.Create("/home/test/foo/file2.txt")
- fh.WriteString("This is a test")
- fh.Close()
- fh, _ = overlay.Create("/home/test/foo/bar/file3.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- // Opening nested dir only in the overlay
- fh, _ = ufs.Open("/home/test/foo")
- list, err := fh.Readdir(-1)
- fh.Close()
- if err != nil {
- t.Errorf("Readdir failed %s", err)
- }
- if len(list) != 2 {
- for _, x := range list {
- fmt.Println(x.Name())
- }
- t.Errorf("Got wrong number of files in union: %v", len(list))
- }
-}
-
-func TestCopyOnWriteFsWithOsFs(t *testing.T) {
- defer CleanupTempDirs(t)
- base := NewTempOsBaseFs(t)
- roBase := &ReadOnlyFs{source: base}
- overlay := NewTempOsBaseFs(t)
-
- ufs := &CopyOnWriteFs{base: roBase, layer: overlay}
-
- base.MkdirAll("/home/test", 0777)
- fh, _ := base.Create("/home/test/file.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- overlay.MkdirAll("home/test", 0777)
- fh, _ = overlay.Create("/home/test/file2.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- fh, _ = ufs.Create("/home/test/file3.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- fh, _ = ufs.Open("/home/test")
- files, err := fh.Readdirnames(-1)
- fh.Close()
- if err != nil {
- t.Errorf("Readdirnames failed")
- }
- if len(files) != 3 {
- t.Errorf("Got wrong number of files in union: %v", files)
- }
-
- fh, _ = overlay.Open("/home/test")
- files, err = fh.Readdirnames(-1)
- fh.Close()
- if err != nil {
- t.Errorf("Readdirnames failed")
- }
- if len(files) != 2 {
- t.Errorf("Got wrong number of files in overlay: %v", files)
- }
-}
-
-func TestUnionCacheWrite(t *testing.T) {
- base := &MemMapFs{}
- layer := &MemMapFs{}
-
- ufs := NewCacheOnReadFs(base, layer, 0)
-
- base.Mkdir("/data", 0777)
-
- fh, err := ufs.Create("/data/file.txt")
- if err != nil {
- t.Errorf("Failed to create file")
- }
- _, err = fh.Write([]byte("This is a test"))
- if err != nil {
- t.Errorf("Failed to write file")
- }
-
- fh.Seek(0, os.SEEK_SET)
- buf := make([]byte, 4)
- _, err = fh.Read(buf)
- fh.Write([]byte(" IS A"))
- fh.Close()
-
- baseData, _ := ReadFile(base, "/data/file.txt")
- layerData, _ := ReadFile(layer, "/data/file.txt")
- if string(baseData) != string(layerData) {
- t.Errorf("Different data: %s <=> %s", baseData, layerData)
- }
-}
-
-func TestUnionCacheExpire(t *testing.T) {
- base := &MemMapFs{}
- layer := &MemMapFs{}
- ufs := &CacheOnReadFs{base: base, layer: layer, cacheTime: 1 * time.Second}
-
- base.Mkdir("/data", 0777)
-
- fh, err := ufs.Create("/data/file.txt")
- if err != nil {
- t.Errorf("Failed to create file")
- }
- _, err = fh.Write([]byte("This is a test"))
- if err != nil {
- t.Errorf("Failed to write file")
- }
- fh.Close()
-
- fh, _ = base.Create("/data/file.txt")
- // sleep some time, so we really get a different time.Now() on write...
- time.Sleep(2 * time.Second)
- fh.WriteString("Another test")
- fh.Close()
-
- data, _ := ReadFile(ufs, "/data/file.txt")
- if string(data) != "Another test" {
- t.Errorf("cache time failed: <%s>", data)
- }
-}
-
-func TestCacheOnReadFsNotInLayer(t *testing.T) {
- base := NewMemMapFs()
- layer := NewMemMapFs()
- fs := NewCacheOnReadFs(base, layer, 0)
-
- fh, err := base.Create("/file.txt")
- if err != nil {
- t.Fatal("unable to create file: ", err)
- }
-
- txt := []byte("This is a test")
- fh.Write(txt)
- fh.Close()
-
- fh, err = fs.Open("/file.txt")
- if err != nil {
- t.Fatal("could not open file: ", err)
- }
-
- b, err := ReadAll(fh)
- fh.Close()
-
- if err != nil {
- t.Fatal("could not read file: ", err)
- } else if !bytes.Equal(txt, b) {
- t.Fatalf("wanted file text %q, got %q", txt, b)
- }
-
- fh, err = layer.Open("/file.txt")
- if err != nil {
- t.Fatal("could not open file from layer: ", err)
- }
- fh.Close()
-}
diff --git a/vendor/github.com/spf13/afero/const_bsds.go b/vendor/github.com/spf13/afero/const_bsds.go
deleted file mode 100644
index 5728243..0000000
--- a/vendor/github.com/spf13/afero/const_bsds.go
+++ /dev/null
@@ -1,22 +0,0 @@
-// Copyright © 2016 Steve Francia .
-//
-// 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.
-
-// +build darwin openbsd freebsd netbsd dragonfly
-
-package afero
-
-import (
- "syscall"
-)
-
-const BADFD = syscall.EBADF
diff --git a/vendor/github.com/spf13/afero/const_win_unix.go b/vendor/github.com/spf13/afero/const_win_unix.go
deleted file mode 100644
index 968fc27..0000000
--- a/vendor/github.com/spf13/afero/const_win_unix.go
+++ /dev/null
@@ -1,25 +0,0 @@
-// Copyright © 2016 Steve Francia .
-//
-// 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.
-// +build !darwin
-// +build !openbsd
-// +build !freebsd
-// +build !dragonfly
-// +build !netbsd
-
-package afero
-
-import (
- "syscall"
-)
-
-const BADFD = syscall.EBADFD
diff --git a/vendor/github.com/spf13/afero/copyOnWriteFs.go b/vendor/github.com/spf13/afero/copyOnWriteFs.go
deleted file mode 100644
index ed692ae..0000000
--- a/vendor/github.com/spf13/afero/copyOnWriteFs.go
+++ /dev/null
@@ -1,253 +0,0 @@
-package afero
-
-import (
- "fmt"
- "os"
- "path/filepath"
- "syscall"
- "time"
-)
-
-// The CopyOnWriteFs is a union filesystem: a read only base file system with
-// a possibly writeable layer on top. Changes to the file system will only
-// be made in the overlay: Changing an existing file in the base layer which
-// is not present in the overlay will copy the file to the overlay ("changing"
-// includes also calls to e.g. Chtimes() and Chmod()).
-//
-// Reading directories is currently only supported via Open(), not OpenFile().
-type CopyOnWriteFs struct {
- base Fs
- layer Fs
-}
-
-func NewCopyOnWriteFs(base Fs, layer Fs) Fs {
- return &CopyOnWriteFs{base: base, layer: layer}
-}
-
-// Returns true if the file is not in the overlay
-func (u *CopyOnWriteFs) isBaseFile(name string) (bool, error) {
- if _, err := u.layer.Stat(name); err == nil {
- return false, nil
- }
- _, err := u.base.Stat(name)
- if err != nil {
- if oerr, ok := err.(*os.PathError); ok {
- if oerr.Err == os.ErrNotExist || oerr.Err == syscall.ENOENT || oerr.Err == syscall.ENOTDIR {
- return false, nil
- }
- }
- if err == syscall.ENOENT {
- return false, nil
- }
- }
- return true, err
-}
-
-func (u *CopyOnWriteFs) copyToLayer(name string) error {
- return copyToLayer(u.base, u.layer, name)
-}
-
-func (u *CopyOnWriteFs) Chtimes(name string, atime, mtime time.Time) error {
- b, err := u.isBaseFile(name)
- if err != nil {
- return err
- }
- if b {
- if err := u.copyToLayer(name); err != nil {
- return err
- }
- }
- return u.layer.Chtimes(name, atime, mtime)
-}
-
-func (u *CopyOnWriteFs) Chmod(name string, mode os.FileMode) error {
- b, err := u.isBaseFile(name)
- if err != nil {
- return err
- }
- if b {
- if err := u.copyToLayer(name); err != nil {
- return err
- }
- }
- return u.layer.Chmod(name, mode)
-}
-
-func (u *CopyOnWriteFs) Stat(name string) (os.FileInfo, error) {
- fi, err := u.layer.Stat(name)
- if err != nil {
- origErr := err
- if e, ok := err.(*os.PathError); ok {
- err = e.Err
- }
- if err == syscall.ENOENT || err == syscall.ENOTDIR {
- return u.base.Stat(name)
- }
- return nil, origErr
- }
- return fi, nil
-}
-
-// Renaming files present only in the base layer is not permitted
-func (u *CopyOnWriteFs) Rename(oldname, newname string) error {
- b, err := u.isBaseFile(oldname)
- if err != nil {
- return err
- }
- if b {
- return syscall.EPERM
- }
- return u.layer.Rename(oldname, newname)
-}
-
-// Removing files present only in the base layer is not permitted. If
-// a file is present in the base layer and the overlay, only the overlay
-// will be removed.
-func (u *CopyOnWriteFs) Remove(name string) error {
- err := u.layer.Remove(name)
- switch err {
- case syscall.ENOENT:
- _, err = u.base.Stat(name)
- if err == nil {
- return syscall.EPERM
- }
- return syscall.ENOENT
- default:
- return err
- }
-}
-
-func (u *CopyOnWriteFs) RemoveAll(name string) error {
- err := u.layer.RemoveAll(name)
- switch err {
- case syscall.ENOENT:
- _, err = u.base.Stat(name)
- if err == nil {
- return syscall.EPERM
- }
- return syscall.ENOENT
- default:
- return err
- }
-}
-
-func (u *CopyOnWriteFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
- b, err := u.isBaseFile(name)
- if err != nil {
- return nil, err
- }
-
- if flag&(os.O_WRONLY|os.O_RDWR|os.O_APPEND|os.O_CREATE|os.O_TRUNC) != 0 {
- if b {
- if err = u.copyToLayer(name); err != nil {
- return nil, err
- }
- return u.layer.OpenFile(name, flag, perm)
- }
-
- dir := filepath.Dir(name)
- isaDir, err := IsDir(u.base, dir)
- if err != nil && !os.IsNotExist(err) {
- return nil, err
- }
- if isaDir {
- if err = u.layer.MkdirAll(dir, 0777); err != nil {
- return nil, err
- }
- return u.layer.OpenFile(name, flag, perm)
- }
-
- isaDir, err = IsDir(u.layer, dir)
- if err != nil {
- return nil, err
- }
- if isaDir {
- return u.layer.OpenFile(name, flag, perm)
- }
-
- return nil, &os.PathError{Op: "open", Path: name, Err: syscall.ENOTDIR} // ...or os.ErrNotExist?
- }
- if b {
- return u.base.OpenFile(name, flag, perm)
- }
- return u.layer.OpenFile(name, flag, perm)
-}
-
-// This function handles the 9 different possibilities caused
-// by the union which are the intersection of the following...
-// layer: doesn't exist, exists as a file, and exists as a directory
-// base: doesn't exist, exists as a file, and exists as a directory
-func (u *CopyOnWriteFs) Open(name string) (File, error) {
- // Since the overlay overrides the base we check that first
- b, err := u.isBaseFile(name)
- if err != nil {
- return nil, err
- }
-
- // If overlay doesn't exist, return the base (base state irrelevant)
- if b {
- return u.base.Open(name)
- }
-
- // If overlay is a file, return it (base state irrelevant)
- dir, err := IsDir(u.layer, name)
- if err != nil {
- return nil, err
- }
- if !dir {
- return u.layer.Open(name)
- }
-
- // Overlay is a directory, base state now matters.
- // Base state has 3 states to check but 2 outcomes:
- // A. It's a file or non-readable in the base (return just the overlay)
- // B. It's an accessible directory in the base (return a UnionFile)
-
- // If base is file or nonreadable, return overlay
- dir, err = IsDir(u.base, name)
- if !dir || err != nil {
- return u.layer.Open(name)
- }
-
- // Both base & layer are directories
- // Return union file (if opens are without error)
- bfile, bErr := u.base.Open(name)
- lfile, lErr := u.layer.Open(name)
-
- // If either have errors at this point something is very wrong. Return nil and the errors
- if bErr != nil || lErr != nil {
- return nil, fmt.Errorf("BaseErr: %v\nOverlayErr: %v", bErr, lErr)
- }
-
- return &UnionFile{base: bfile, layer: lfile}, nil
-}
-
-func (u *CopyOnWriteFs) Mkdir(name string, perm os.FileMode) error {
- dir, err := IsDir(u.base, name)
- if err != nil {
- return u.layer.MkdirAll(name, perm)
- }
- if dir {
- return syscall.EEXIST
- }
- return u.layer.MkdirAll(name, perm)
-}
-
-func (u *CopyOnWriteFs) Name() string {
- return "CopyOnWriteFs"
-}
-
-func (u *CopyOnWriteFs) MkdirAll(name string, perm os.FileMode) error {
- dir, err := IsDir(u.base, name)
- if err != nil {
- return u.layer.MkdirAll(name, perm)
- }
- if dir {
- return syscall.EEXIST
- }
- return u.layer.MkdirAll(name, perm)
-}
-
-func (u *CopyOnWriteFs) Create(name string) (File, error) {
- return u.OpenFile(name, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0666)
-}
diff --git a/vendor/github.com/spf13/afero/copyOnWriteFs_test.go b/vendor/github.com/spf13/afero/copyOnWriteFs_test.go
deleted file mode 100644
index 2a00fab..0000000
--- a/vendor/github.com/spf13/afero/copyOnWriteFs_test.go
+++ /dev/null
@@ -1,23 +0,0 @@
-package afero
-
-import "testing"
-
-func TestCopyOnWrite(t *testing.T) {
- var fs Fs
- var err error
- base := NewOsFs()
- roBase := NewReadOnlyFs(base)
- ufs := NewCopyOnWriteFs(roBase, NewMemMapFs())
- fs = ufs
- err = fs.MkdirAll("nonexistent/directory/", 0744)
- if err != nil {
- t.Error(err)
- return
- }
- _, err = fs.Create("nonexistent/directory/newfile")
- if err != nil {
- t.Error(err)
- return
- }
-
-}
diff --git a/vendor/github.com/spf13/afero/httpFs.go b/vendor/github.com/spf13/afero/httpFs.go
deleted file mode 100644
index c421936..0000000
--- a/vendor/github.com/spf13/afero/httpFs.go
+++ /dev/null
@@ -1,110 +0,0 @@
-// Copyright © 2014 Steve Francia .
-//
-// 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 afero
-
-import (
- "errors"
- "net/http"
- "os"
- "path"
- "path/filepath"
- "strings"
- "time"
-)
-
-type httpDir struct {
- basePath string
- fs HttpFs
-}
-
-func (d httpDir) Open(name string) (http.File, error) {
- if filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0 ||
- strings.Contains(name, "\x00") {
- return nil, errors.New("http: invalid character in file path")
- }
- dir := string(d.basePath)
- if dir == "" {
- dir = "."
- }
-
- f, err := d.fs.Open(filepath.Join(dir, filepath.FromSlash(path.Clean("/"+name))))
- if err != nil {
- return nil, err
- }
- return f, nil
-}
-
-type HttpFs struct {
- source Fs
-}
-
-func NewHttpFs(source Fs) *HttpFs {
- return &HttpFs{source: source}
-}
-
-func (h HttpFs) Dir(s string) *httpDir {
- return &httpDir{basePath: s, fs: h}
-}
-
-func (h HttpFs) Name() string { return "h HttpFs" }
-
-func (h HttpFs) Create(name string) (File, error) {
- return h.source.Create(name)
-}
-
-func (h HttpFs) Chmod(name string, mode os.FileMode) error {
- return h.source.Chmod(name, mode)
-}
-
-func (h HttpFs) Chtimes(name string, atime time.Time, mtime time.Time) error {
- return h.source.Chtimes(name, atime, mtime)
-}
-
-func (h HttpFs) Mkdir(name string, perm os.FileMode) error {
- return h.source.Mkdir(name, perm)
-}
-
-func (h HttpFs) MkdirAll(path string, perm os.FileMode) error {
- return h.source.MkdirAll(path, perm)
-}
-
-func (h HttpFs) Open(name string) (http.File, error) {
- f, err := h.source.Open(name)
- if err == nil {
- if httpfile, ok := f.(http.File); ok {
- return httpfile, nil
- }
- }
- return nil, err
-}
-
-func (h HttpFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
- return h.source.OpenFile(name, flag, perm)
-}
-
-func (h HttpFs) Remove(name string) error {
- return h.source.Remove(name)
-}
-
-func (h HttpFs) RemoveAll(path string) error {
- return h.source.RemoveAll(path)
-}
-
-func (h HttpFs) Rename(oldname, newname string) error {
- return h.source.Rename(oldname, newname)
-}
-
-func (h HttpFs) Stat(name string) (os.FileInfo, error) {
- return h.source.Stat(name)
-}
diff --git a/vendor/github.com/spf13/afero/ioutil.go b/vendor/github.com/spf13/afero/ioutil.go
deleted file mode 100644
index 5c3a3d8..0000000
--- a/vendor/github.com/spf13/afero/ioutil.go
+++ /dev/null
@@ -1,230 +0,0 @@
-// Copyright ©2015 The Go Authors
-// Copyright ©2015 Steve Francia
-//
-// 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 afero
-
-import (
- "bytes"
- "io"
- "os"
- "path/filepath"
- "sort"
- "strconv"
- "sync"
- "time"
-)
-
-// byName implements sort.Interface.
-type byName []os.FileInfo
-
-func (f byName) Len() int { return len(f) }
-func (f byName) Less(i, j int) bool { return f[i].Name() < f[j].Name() }
-func (f byName) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
-
-// ReadDir reads the directory named by dirname and returns
-// a list of sorted directory entries.
-func (a Afero) ReadDir(dirname string) ([]os.FileInfo, error) {
- return ReadDir(a.Fs, dirname)
-}
-
-func ReadDir(fs Fs, dirname string) ([]os.FileInfo, error) {
- f, err := fs.Open(dirname)
- if err != nil {
- return nil, err
- }
- list, err := f.Readdir(-1)
- f.Close()
- if err != nil {
- return nil, err
- }
- sort.Sort(byName(list))
- return list, nil
-}
-
-// ReadFile reads the file named by filename and returns the contents.
-// A successful call returns err == nil, not err == EOF. Because ReadFile
-// reads the whole file, it does not treat an EOF from Read as an error
-// to be reported.
-func (a Afero) ReadFile(filename string) ([]byte, error) {
- return ReadFile(a.Fs, filename)
-}
-
-func ReadFile(fs Fs, filename string) ([]byte, error) {
- f, err := fs.Open(filename)
- if err != nil {
- return nil, err
- }
- defer f.Close()
- // It's a good but not certain bet that FileInfo will tell us exactly how much to
- // read, so let's try it but be prepared for the answer to be wrong.
- var n int64
-
- if fi, err := f.Stat(); err == nil {
- // Don't preallocate a huge buffer, just in case.
- if size := fi.Size(); size < 1e9 {
- n = size
- }
- }
- // As initial capacity for readAll, use n + a little extra in case Size is zero,
- // and to avoid another allocation after Read has filled the buffer. The readAll
- // call will read into its allocated internal buffer cheaply. If the size was
- // wrong, we'll either waste some space off the end or reallocate as needed, but
- // in the overwhelmingly common case we'll get it just right.
- return readAll(f, n+bytes.MinRead)
-}
-
-// readAll reads from r until an error or EOF and returns the data it read
-// from the internal buffer allocated with a specified capacity.
-func readAll(r io.Reader, capacity int64) (b []byte, err error) {
- buf := bytes.NewBuffer(make([]byte, 0, capacity))
- // If the buffer overflows, we will get bytes.ErrTooLarge.
- // Return that as an error. Any other panic remains.
- defer func() {
- e := recover()
- if e == nil {
- return
- }
- if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge {
- err = panicErr
- } else {
- panic(e)
- }
- }()
- _, err = buf.ReadFrom(r)
- return buf.Bytes(), err
-}
-
-// ReadAll reads from r until an error or EOF and returns the data it read.
-// A successful call returns err == nil, not err == EOF. Because ReadAll is
-// defined to read from src until EOF, it does not treat an EOF from Read
-// as an error to be reported.
-func ReadAll(r io.Reader) ([]byte, error) {
- return readAll(r, bytes.MinRead)
-}
-
-// WriteFile writes data to a file named by filename.
-// If the file does not exist, WriteFile creates it with permissions perm;
-// otherwise WriteFile truncates it before writing.
-func (a Afero) WriteFile(filename string, data []byte, perm os.FileMode) error {
- return WriteFile(a.Fs, filename, data, perm)
-}
-
-func WriteFile(fs Fs, filename string, data []byte, perm os.FileMode) error {
- f, err := fs.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
- if err != nil {
- return err
- }
- n, err := f.Write(data)
- if err == nil && n < len(data) {
- err = io.ErrShortWrite
- }
- if err1 := f.Close(); err == nil {
- err = err1
- }
- return err
-}
-
-// Random number state.
-// We generate random temporary file names so that there's a good
-// chance the file doesn't exist yet - keeps the number of tries in
-// TempFile to a minimum.
-var rand uint32
-var randmu sync.Mutex
-
-func reseed() uint32 {
- return uint32(time.Now().UnixNano() + int64(os.Getpid()))
-}
-
-func nextSuffix() string {
- randmu.Lock()
- r := rand
- if r == 0 {
- r = reseed()
- }
- r = r*1664525 + 1013904223 // constants from Numerical Recipes
- rand = r
- randmu.Unlock()
- return strconv.Itoa(int(1e9 + r%1e9))[1:]
-}
-
-// TempFile creates a new temporary file in the directory dir
-// with a name beginning with prefix, opens the file for reading
-// and writing, and returns the resulting *File.
-// If dir is the empty string, TempFile uses the default directory
-// for temporary files (see os.TempDir).
-// Multiple programs calling TempFile simultaneously
-// will not choose the same file. The caller can use f.Name()
-// to find the pathname of the file. It is the caller's responsibility
-// to remove the file when no longer needed.
-func (a Afero) TempFile(dir, prefix string) (f File, err error) {
- return TempFile(a.Fs, dir, prefix)
-}
-
-func TempFile(fs Fs, dir, prefix string) (f File, err error) {
- if dir == "" {
- dir = os.TempDir()
- }
-
- nconflict := 0
- for i := 0; i < 10000; i++ {
- name := filepath.Join(dir, prefix+nextSuffix())
- f, err = fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
- if os.IsExist(err) {
- if nconflict++; nconflict > 10 {
- randmu.Lock()
- rand = reseed()
- randmu.Unlock()
- }
- continue
- }
- break
- }
- return
-}
-
-// TempDir creates a new temporary directory in the directory dir
-// with a name beginning with prefix and returns the path of the
-// new directory. If dir is the empty string, TempDir uses the
-// default directory for temporary files (see os.TempDir).
-// Multiple programs calling TempDir simultaneously
-// will not choose the same directory. It is the caller's responsibility
-// to remove the directory when no longer needed.
-func (a Afero) TempDir(dir, prefix string) (name string, err error) {
- return TempDir(a.Fs, dir, prefix)
-}
-func TempDir(fs Fs, dir, prefix string) (name string, err error) {
- if dir == "" {
- dir = os.TempDir()
- }
-
- nconflict := 0
- for i := 0; i < 10000; i++ {
- try := filepath.Join(dir, prefix+nextSuffix())
- err = fs.Mkdir(try, 0700)
- if os.IsExist(err) {
- if nconflict++; nconflict > 10 {
- randmu.Lock()
- rand = reseed()
- randmu.Unlock()
- }
- continue
- }
- if err == nil {
- name = try
- }
- break
- }
- return
-}
diff --git a/vendor/github.com/spf13/afero/ioutil_test.go b/vendor/github.com/spf13/afero/ioutil_test.go
deleted file mode 100644
index e7c9f06..0000000
--- a/vendor/github.com/spf13/afero/ioutil_test.go
+++ /dev/null
@@ -1,112 +0,0 @@
-// ©2015 The Go Authors
-// Copyright ©2015 Steve Francia
-//
-// 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 afero
-
-import "testing"
-
-func checkSizePath(t *testing.T, path string, size int64) {
- dir, err := testFS.Stat(path)
- if err != nil {
- t.Fatalf("Stat %q (looking for size %d): %s", path, size, err)
- }
- if dir.Size() != size {
- t.Errorf("Stat %q: size %d want %d", path, dir.Size(), size)
- }
-}
-
-func TestReadFile(t *testing.T) {
- testFS = &MemMapFs{}
- fsutil := &Afero{Fs: testFS}
-
- testFS.Create("this_exists.go")
- filename := "rumpelstilzchen"
- contents, err := fsutil.ReadFile(filename)
- if err == nil {
- t.Fatalf("ReadFile %s: error expected, none found", filename)
- }
-
- filename = "this_exists.go"
- contents, err = fsutil.ReadFile(filename)
- if err != nil {
- t.Fatalf("ReadFile %s: %v", filename, err)
- }
-
- checkSizePath(t, filename, int64(len(contents)))
-}
-
-func TestWriteFile(t *testing.T) {
- testFS = &MemMapFs{}
- fsutil := &Afero{Fs: testFS}
- f, err := fsutil.TempFile("", "ioutil-test")
- if err != nil {
- t.Fatal(err)
- }
- filename := f.Name()
- data := "Programming today is a race between software engineers striving to " +
- "build bigger and better idiot-proof programs, and the Universe trying " +
- "to produce bigger and better idiots. So far, the Universe is winning."
-
- if err := fsutil.WriteFile(filename, []byte(data), 0644); err != nil {
- t.Fatalf("WriteFile %s: %v", filename, err)
- }
-
- contents, err := fsutil.ReadFile(filename)
- if err != nil {
- t.Fatalf("ReadFile %s: %v", filename, err)
- }
-
- if string(contents) != data {
- t.Fatalf("contents = %q\nexpected = %q", string(contents), data)
- }
-
- // cleanup
- f.Close()
- testFS.Remove(filename) // ignore error
-}
-
-func TestReadDir(t *testing.T) {
- testFS = &MemMapFs{}
- testFS.Mkdir("/i-am-a-dir", 0777)
- testFS.Create("/this_exists.go")
- dirname := "rumpelstilzchen"
- _, err := ReadDir(testFS, dirname)
- if err == nil {
- t.Fatalf("ReadDir %s: error expected, none found", dirname)
- }
-
- dirname = ".."
- list, err := ReadDir(testFS, dirname)
- if err != nil {
- t.Fatalf("ReadDir %s: %v", dirname, err)
- }
-
- foundFile := false
- foundSubDir := false
- for _, dir := range list {
- switch {
- case !dir.IsDir() && dir.Name() == "this_exists.go":
- foundFile = true
- case dir.IsDir() && dir.Name() == "i-am-a-dir":
- foundSubDir = true
- }
- }
- if !foundFile {
- t.Fatalf("ReadDir %s: this_exists.go file not found", dirname)
- }
- if !foundSubDir {
- t.Fatalf("ReadDir %s: i-am-a-dir directory not found", dirname)
- }
-}
diff --git a/vendor/github.com/spf13/afero/match.go b/vendor/github.com/spf13/afero/match.go
deleted file mode 100644
index 08b3b7e..0000000
--- a/vendor/github.com/spf13/afero/match.go
+++ /dev/null
@@ -1,110 +0,0 @@
-// Copyright © 2014 Steve Francia .
-// Copyright 2009 The Go Authors. All rights reserved.
-
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package afero
-
-import (
- "path/filepath"
- "sort"
- "strings"
-)
-
-// Glob returns the names of all files matching pattern or nil
-// if there is no matching file. The syntax of patterns is the same
-// as in Match. The pattern may describe hierarchical names such as
-// /usr/*/bin/ed (assuming the Separator is '/').
-//
-// Glob ignores file system errors such as I/O errors reading directories.
-// The only possible returned error is ErrBadPattern, when pattern
-// is malformed.
-//
-// This was adapted from (http://golang.org/pkg/path/filepath) and uses several
-// built-ins from that package.
-func Glob(fs Fs, pattern string) (matches []string, err error) {
- if !hasMeta(pattern) {
- // afero does not support Lstat directly.
- if _, err = lstatIfOs(fs, pattern); err != nil {
- return nil, nil
- }
- return []string{pattern}, nil
- }
-
- dir, file := filepath.Split(pattern)
- switch dir {
- case "":
- dir = "."
- case string(filepath.Separator):
- // nothing
- default:
- dir = dir[0 : len(dir)-1] // chop off trailing separator
- }
-
- if !hasMeta(dir) {
- return glob(fs, dir, file, nil)
- }
-
- var m []string
- m, err = Glob(fs, dir)
- if err != nil {
- return
- }
- for _, d := range m {
- matches, err = glob(fs, d, file, matches)
- if err != nil {
- return
- }
- }
- return
-}
-
-// glob searches for files matching pattern in the directory dir
-// and appends them to matches. If the directory cannot be
-// opened, it returns the existing matches. New matches are
-// added in lexicographical order.
-func glob(fs Fs, dir, pattern string, matches []string) (m []string, e error) {
- m = matches
- fi, err := fs.Stat(dir)
- if err != nil {
- return
- }
- if !fi.IsDir() {
- return
- }
- d, err := fs.Open(dir)
- if err != nil {
- return
- }
- defer d.Close()
-
- names, _ := d.Readdirnames(-1)
- sort.Strings(names)
-
- for _, n := range names {
- matched, err := filepath.Match(pattern, n)
- if err != nil {
- return m, err
- }
- if matched {
- m = append(m, filepath.Join(dir, n))
- }
- }
- return
-}
-
-// hasMeta reports whether path contains any of the magic characters
-// recognized by Match.
-func hasMeta(path string) bool {
- // TODO(niemeyer): Should other magic characters be added here?
- return strings.IndexAny(path, "*?[") >= 0
-}
diff --git a/vendor/github.com/spf13/afero/match_test.go b/vendor/github.com/spf13/afero/match_test.go
deleted file mode 100644
index 21e1fae..0000000
--- a/vendor/github.com/spf13/afero/match_test.go
+++ /dev/null
@@ -1,183 +0,0 @@
-// Copyright © 2014 Steve Francia .
-// Copyright 2009 The Go Authors. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package afero
-
-import (
- "os"
- "path/filepath"
- "runtime"
- "testing"
-)
-
-// contains returns true if vector contains the string s.
-func contains(vector []string, s string) bool {
- for _, elem := range vector {
- if elem == s {
- return true
- }
- }
- return false
-}
-
-func setupGlobDirRoot(t *testing.T, fs Fs) string {
- path := testDir(fs)
- setupGlobFiles(t, fs, path)
- return path
-}
-
-func setupGlobDirReusePath(t *testing.T, fs Fs, path string) string {
- testRegistry[fs] = append(testRegistry[fs], path)
- return setupGlobFiles(t, fs, path)
-}
-
-func setupGlobFiles(t *testing.T, fs Fs, path string) string {
- testSubDir := filepath.Join(path, "globs", "bobs")
- err := fs.MkdirAll(testSubDir, 0700)
- if err != nil && !os.IsExist(err) {
- t.Fatal(err)
- }
-
- f, err := fs.Create(filepath.Join(testSubDir, "/matcher"))
- if err != nil {
- t.Fatal(err)
- }
- f.WriteString("Testfile 1 content")
- f.Close()
-
- f, err = fs.Create(filepath.Join(testSubDir, "/../submatcher"))
- if err != nil {
- t.Fatal(err)
- }
- f.WriteString("Testfile 2 content")
- f.Close()
-
- f, err = fs.Create(filepath.Join(testSubDir, "/../../match"))
- if err != nil {
- t.Fatal(err)
- }
- f.WriteString("Testfile 3 content")
- f.Close()
-
- return testSubDir
-}
-
-func TestGlob(t *testing.T) {
- defer removeAllTestFiles(t)
- var testDir string
- for i, fs := range Fss {
- if i == 0 {
- testDir = setupGlobDirRoot(t, fs)
- } else {
- setupGlobDirReusePath(t, fs, testDir)
- }
- }
-
- var globTests = []struct {
- pattern, result string
- }{
- {testDir + "/globs/bobs/matcher", testDir + "/globs/bobs/matcher"},
- {testDir + "/globs/*/mat?her", testDir + "/globs/bobs/matcher"},
- {testDir + "/globs/bobs/../*", testDir + "/globs/submatcher"},
- {testDir + "/match", testDir + "/match"},
- }
-
- for _, fs := range Fss {
-
- for _, tt := range globTests {
- pattern := tt.pattern
- result := tt.result
- if runtime.GOOS == "windows" {
- pattern = filepath.Clean(pattern)
- result = filepath.Clean(result)
- }
- matches, err := Glob(fs, pattern)
- if err != nil {
- t.Errorf("Glob error for %q: %s", pattern, err)
- continue
- }
- if !contains(matches, result) {
- t.Errorf("Glob(%#q) = %#v want %v", pattern, matches, result)
- }
- }
- for _, pattern := range []string{"no_match", "../*/no_match"} {
- matches, err := Glob(fs, pattern)
- if err != nil {
- t.Errorf("Glob error for %q: %s", pattern, err)
- continue
- }
- if len(matches) != 0 {
- t.Errorf("Glob(%#q) = %#v want []", pattern, matches)
- }
- }
-
- }
-}
-
-func TestGlobSymlink(t *testing.T) {
- defer removeAllTestFiles(t)
-
- fs := &OsFs{}
- testDir := setupGlobDirRoot(t, fs)
-
- err := os.Symlink("target", filepath.Join(testDir, "symlink"))
- if err != nil {
- t.Skipf("skipping on %s", runtime.GOOS)
- }
-
- var globSymlinkTests = []struct {
- path, dest string
- brokenLink bool
- }{
- {"test1", "link1", false},
- {"test2", "link2", true},
- }
-
- for _, tt := range globSymlinkTests {
- path := filepath.Join(testDir, tt.path)
- dest := filepath.Join(testDir, tt.dest)
- f, err := fs.Create(path)
- if err != nil {
- t.Fatal(err)
- }
- if err := f.Close(); err != nil {
- t.Fatal(err)
- }
- err = os.Symlink(path, dest)
- if err != nil {
- t.Fatal(err)
- }
- if tt.brokenLink {
- // Break the symlink.
- fs.Remove(path)
- }
- matches, err := Glob(fs, dest)
- if err != nil {
- t.Errorf("GlobSymlink error for %q: %s", dest, err)
- }
- if !contains(matches, dest) {
- t.Errorf("Glob(%#q) = %#v want %v", dest, matches, dest)
- }
- }
-}
-
-
-func TestGlobError(t *testing.T) {
- for _, fs := range Fss {
- _, err := Glob(fs, "[7]")
- if err != nil {
- t.Error("expected error for bad pattern; got none")
- }
- }
-}
diff --git a/vendor/github.com/spf13/afero/mem/dir.go b/vendor/github.com/spf13/afero/mem/dir.go
deleted file mode 100644
index e104013..0000000
--- a/vendor/github.com/spf13/afero/mem/dir.go
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright © 2014 Steve Francia .
-//
-// 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 mem
-
-type Dir interface {
- Len() int
- Names() []string
- Files() []*FileData
- Add(*FileData)
- Remove(*FileData)
-}
-
-func RemoveFromMemDir(dir *FileData, f *FileData) {
- dir.memDir.Remove(f)
-}
-
-func AddToMemDir(dir *FileData, f *FileData) {
- dir.memDir.Add(f)
-}
-
-func InitializeDir(d *FileData) {
- if d.memDir == nil {
- d.dir = true
- d.memDir = &DirMap{}
- }
-}
diff --git a/vendor/github.com/spf13/afero/mem/dirmap.go b/vendor/github.com/spf13/afero/mem/dirmap.go
deleted file mode 100644
index 03a57ee..0000000
--- a/vendor/github.com/spf13/afero/mem/dirmap.go
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright © 2015 Steve Francia .
-//
-// 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 mem
-
-import "sort"
-
-type DirMap map[string]*FileData
-
-func (m DirMap) Len() int { return len(m) }
-func (m DirMap) Add(f *FileData) { m[f.name] = f }
-func (m DirMap) Remove(f *FileData) { delete(m, f.name) }
-func (m DirMap) Files() (files []*FileData) {
- for _, f := range m {
- files = append(files, f)
- }
- sort.Sort(filesSorter(files))
- return files
-}
-
-// implement sort.Interface for []*FileData
-type filesSorter []*FileData
-
-func (s filesSorter) Len() int { return len(s) }
-func (s filesSorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
-func (s filesSorter) Less(i, j int) bool { return s[i].name < s[j].name }
-
-func (m DirMap) Names() (names []string) {
- for x := range m {
- names = append(names, x)
- }
- return names
-}
diff --git a/vendor/github.com/spf13/afero/mem/file.go b/vendor/github.com/spf13/afero/mem/file.go
deleted file mode 100644
index 5401a3b..0000000
--- a/vendor/github.com/spf13/afero/mem/file.go
+++ /dev/null
@@ -1,311 +0,0 @@
-// Copyright © 2015 Steve Francia .
-// Copyright 2013 tsuru authors. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package mem
-
-import (
- "bytes"
- "errors"
- "io"
- "os"
- "path/filepath"
- "sync"
- "sync/atomic"
-)
-
-import "time"
-
-const FilePathSeparator = string(filepath.Separator)
-
-type File struct {
- // atomic requires 64-bit alignment for struct field access
- at int64
- readDirCount int64
- closed bool
- readOnly bool
- fileData *FileData
-}
-
-func NewFileHandle(data *FileData) *File {
- return &File{fileData: data}
-}
-
-func NewReadOnlyFileHandle(data *FileData) *File {
- return &File{fileData: data, readOnly: true}
-}
-
-func (f File) Data() *FileData {
- return f.fileData
-}
-
-type FileData struct {
- sync.Mutex
- name string
- data []byte
- memDir Dir
- dir bool
- mode os.FileMode
- modtime time.Time
-}
-
-func (d *FileData) Name() string {
- d.Lock()
- defer d.Unlock()
- return d.name
-}
-
-func CreateFile(name string) *FileData {
- return &FileData{name: name, mode: os.ModeTemporary, modtime: time.Now()}
-}
-
-func CreateDir(name string) *FileData {
- return &FileData{name: name, memDir: &DirMap{}, dir: true}
-}
-
-func ChangeFileName(f *FileData, newname string) {
- f.Lock()
- f.name = newname
- f.Unlock()
-}
-
-func SetMode(f *FileData, mode os.FileMode) {
- f.Lock()
- f.mode = mode
- f.Unlock()
-}
-
-func SetModTime(f *FileData, mtime time.Time) {
- f.Lock()
- setModTime(f, mtime)
- f.Unlock()
-}
-
-func setModTime(f *FileData, mtime time.Time) {
- f.modtime = mtime
-}
-
-func GetFileInfo(f *FileData) *FileInfo {
- return &FileInfo{f}
-}
-
-func (f *File) Open() error {
- atomic.StoreInt64(&f.at, 0)
- atomic.StoreInt64(&f.readDirCount, 0)
- f.fileData.Lock()
- f.closed = false
- f.fileData.Unlock()
- return nil
-}
-
-func (f *File) Close() error {
- f.fileData.Lock()
- f.closed = true
- if !f.readOnly {
- setModTime(f.fileData, time.Now())
- }
- f.fileData.Unlock()
- return nil
-}
-
-func (f *File) Name() string {
- return f.fileData.Name()
-}
-
-func (f *File) Stat() (os.FileInfo, error) {
- return &FileInfo{f.fileData}, nil
-}
-
-func (f *File) Sync() error {
- return nil
-}
-
-func (f *File) Readdir(count int) (res []os.FileInfo, err error) {
- var outLength int64
-
- f.fileData.Lock()
- files := f.fileData.memDir.Files()[f.readDirCount:]
- if count > 0 {
- if len(files) < count {
- outLength = int64(len(files))
- } else {
- outLength = int64(count)
- }
- if len(files) == 0 {
- err = io.EOF
- }
- } else {
- outLength = int64(len(files))
- }
- f.readDirCount += outLength
- f.fileData.Unlock()
-
- res = make([]os.FileInfo, outLength)
- for i := range res {
- res[i] = &FileInfo{files[i]}
- }
-
- return res, err
-}
-
-func (f *File) Readdirnames(n int) (names []string, err error) {
- fi, err := f.Readdir(n)
- names = make([]string, len(fi))
- for i, f := range fi {
- _, names[i] = filepath.Split(f.Name())
- }
- return names, err
-}
-
-func (f *File) Read(b []byte) (n int, err error) {
- f.fileData.Lock()
- defer f.fileData.Unlock()
- if f.closed == true {
- return 0, ErrFileClosed
- }
- if len(b) > 0 && int(f.at) == len(f.fileData.data) {
- return 0, io.EOF
- }
- if len(f.fileData.data)-int(f.at) >= len(b) {
- n = len(b)
- } else {
- n = len(f.fileData.data) - int(f.at)
- }
- copy(b, f.fileData.data[f.at:f.at+int64(n)])
- atomic.AddInt64(&f.at, int64(n))
- return
-}
-
-func (f *File) ReadAt(b []byte, off int64) (n int, err error) {
- atomic.StoreInt64(&f.at, off)
- return f.Read(b)
-}
-
-func (f *File) Truncate(size int64) error {
- if f.closed == true {
- return ErrFileClosed
- }
- if f.readOnly {
- return &os.PathError{Op: "truncate", Path: f.fileData.name, Err: errors.New("file handle is read only")}
- }
- if size < 0 {
- return ErrOutOfRange
- }
- if size > int64(len(f.fileData.data)) {
- diff := size - int64(len(f.fileData.data))
- f.fileData.data = append(f.fileData.data, bytes.Repeat([]byte{00}, int(diff))...)
- } else {
- f.fileData.data = f.fileData.data[0:size]
- }
- setModTime(f.fileData, time.Now())
- return nil
-}
-
-func (f *File) Seek(offset int64, whence int) (int64, error) {
- if f.closed == true {
- return 0, ErrFileClosed
- }
- switch whence {
- case 0:
- atomic.StoreInt64(&f.at, offset)
- case 1:
- atomic.AddInt64(&f.at, int64(offset))
- case 2:
- atomic.StoreInt64(&f.at, int64(len(f.fileData.data))+offset)
- }
- return f.at, nil
-}
-
-func (f *File) Write(b []byte) (n int, err error) {
- if f.readOnly {
- return 0, &os.PathError{Op: "write", Path: f.fileData.name, Err: errors.New("file handle is read only")}
- }
- n = len(b)
- cur := atomic.LoadInt64(&f.at)
- f.fileData.Lock()
- defer f.fileData.Unlock()
- diff := cur - int64(len(f.fileData.data))
- var tail []byte
- if n+int(cur) < len(f.fileData.data) {
- tail = f.fileData.data[n+int(cur):]
- }
- if diff > 0 {
- f.fileData.data = append(bytes.Repeat([]byte{00}, int(diff)), b...)
- f.fileData.data = append(f.fileData.data, tail...)
- } else {
- f.fileData.data = append(f.fileData.data[:cur], b...)
- f.fileData.data = append(f.fileData.data, tail...)
- }
- setModTime(f.fileData, time.Now())
-
- atomic.StoreInt64(&f.at, int64(len(f.fileData.data)))
- return
-}
-
-func (f *File) WriteAt(b []byte, off int64) (n int, err error) {
- atomic.StoreInt64(&f.at, off)
- return f.Write(b)
-}
-
-func (f *File) WriteString(s string) (ret int, err error) {
- return f.Write([]byte(s))
-}
-
-func (f *File) Info() *FileInfo {
- return &FileInfo{f.fileData}
-}
-
-type FileInfo struct {
- *FileData
-}
-
-// Implements os.FileInfo
-func (s *FileInfo) Name() string {
- s.Lock()
- _, name := filepath.Split(s.name)
- s.Unlock()
- return name
-}
-func (s *FileInfo) Mode() os.FileMode {
- s.Lock()
- defer s.Unlock()
- return s.mode
-}
-func (s *FileInfo) ModTime() time.Time {
- s.Lock()
- defer s.Unlock()
- return s.modtime
-}
-func (s *FileInfo) IsDir() bool {
- s.Lock()
- defer s.Unlock()
- return s.dir
-}
-func (s *FileInfo) Sys() interface{} { return nil }
-func (s *FileInfo) Size() int64 {
- if s.IsDir() {
- return int64(42)
- }
- s.Lock()
- defer s.Unlock()
- return int64(len(s.data))
-}
-
-var (
- ErrFileClosed = errors.New("File is closed")
- ErrOutOfRange = errors.New("Out of range")
- ErrTooLarge = errors.New("Too large")
- ErrFileNotFound = os.ErrNotExist
- ErrFileExists = os.ErrExist
- ErrDestinationExists = os.ErrExist
-)
diff --git a/vendor/github.com/spf13/afero/mem/file_test.go b/vendor/github.com/spf13/afero/mem/file_test.go
deleted file mode 100644
index 5769067..0000000
--- a/vendor/github.com/spf13/afero/mem/file_test.go
+++ /dev/null
@@ -1,154 +0,0 @@
-package mem
-
-import (
- "testing"
- "time"
-)
-
-func TestFileDataNameRace(t *testing.T) {
- t.Parallel()
- const someName = "someName"
- const someOtherName = "someOtherName"
- d := FileData{
- name: someName,
- }
-
- if d.Name() != someName {
- t.Errorf("Failed to read correct Name, was %v", d.Name())
- }
-
- ChangeFileName(&d, someOtherName)
- if d.Name() != someOtherName {
- t.Errorf("Failed to set Name, was %v", d.Name())
- }
-
- go func() {
- ChangeFileName(&d, someName)
- }()
-
- if d.Name() != someName && d.Name() != someOtherName {
- t.Errorf("Failed to read either Name, was %v", d.Name())
- }
-}
-
-func TestFileDataModTimeRace(t *testing.T) {
- t.Parallel()
- someTime := time.Now()
- someOtherTime := someTime.Add(1 * time.Minute)
-
- d := FileData{
- modtime: someTime,
- }
-
- s := FileInfo{
- FileData: &d,
- }
-
- if s.ModTime() != someTime {
- t.Errorf("Failed to read correct value, was %v", s.ModTime())
- }
-
- SetModTime(&d, someOtherTime)
- if s.ModTime() != someOtherTime {
- t.Errorf("Failed to set ModTime, was %v", s.ModTime())
- }
-
- go func() {
- SetModTime(&d, someTime)
- }()
-
- if s.ModTime() != someTime && s.ModTime() != someOtherTime {
- t.Errorf("Failed to read either modtime, was %v", s.ModTime())
- }
-}
-
-func TestFileDataModeRace(t *testing.T) {
- t.Parallel()
- const someMode = 0777
- const someOtherMode = 0660
-
- d := FileData{
- mode: someMode,
- }
-
- s := FileInfo{
- FileData: &d,
- }
-
- if s.Mode() != someMode {
- t.Errorf("Failed to read correct value, was %v", s.Mode())
- }
-
- SetMode(&d, someOtherMode)
- if s.Mode() != someOtherMode {
- t.Errorf("Failed to set Mode, was %v", s.Mode())
- }
-
- go func() {
- SetMode(&d, someMode)
- }()
-
- if s.Mode() != someMode && s.Mode() != someOtherMode {
- t.Errorf("Failed to read either mode, was %v", s.Mode())
- }
-}
-
-func TestFileDataIsDirRace(t *testing.T) {
- t.Parallel()
-
- d := FileData{
- dir: true,
- }
-
- s := FileInfo{
- FileData: &d,
- }
-
- if s.IsDir() != true {
- t.Errorf("Failed to read correct value, was %v", s.IsDir())
- }
-
- go func() {
- s.Lock()
- d.dir = false
- s.Unlock()
- }()
-
- //just logging the value to trigger a read:
- t.Logf("Value is %v", s.IsDir())
-}
-
-func TestFileDataSizeRace(t *testing.T) {
- t.Parallel()
-
- const someData = "Hello"
- const someOtherDataSize = "Hello World"
-
- d := FileData{
- data: []byte(someData),
- dir: false,
- }
-
- s := FileInfo{
- FileData: &d,
- }
-
- if s.Size() != int64(len(someData)) {
- t.Errorf("Failed to read correct value, was %v", s.Size())
- }
-
- go func() {
- s.Lock()
- d.data = []byte(someOtherDataSize)
- s.Unlock()
- }()
-
- //just logging the value to trigger a read:
- t.Logf("Value is %v", s.Size())
-
- //Testing the Dir size case
- d.dir = true
- if s.Size() != int64(42) {
- t.Errorf("Failed to read correct value for dir, was %v", s.Size())
- }
-}
diff --git a/vendor/github.com/spf13/afero/memmap.go b/vendor/github.com/spf13/afero/memmap.go
deleted file mode 100644
index 09498e7..0000000
--- a/vendor/github.com/spf13/afero/memmap.go
+++ /dev/null
@@ -1,365 +0,0 @@
-// Copyright © 2014 Steve Francia .
-//
-// 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 afero
-
-import (
- "fmt"
- "log"
- "os"
- "path/filepath"
- "strings"
- "sync"
- "time"
-
- "github.com/spf13/afero/mem"
-)
-
-type MemMapFs struct {
- mu sync.RWMutex
- data map[string]*mem.FileData
- init sync.Once
-}
-
-func NewMemMapFs() Fs {
- return &MemMapFs{}
-}
-
-func (m *MemMapFs) getData() map[string]*mem.FileData {
- m.init.Do(func() {
- m.data = make(map[string]*mem.FileData)
- // Root should always exist, right?
- // TODO: what about windows?
- m.data[FilePathSeparator] = mem.CreateDir(FilePathSeparator)
- })
- return m.data
-}
-
-func (*MemMapFs) Name() string { return "MemMapFS" }
-
-func (m *MemMapFs) Create(name string) (File, error) {
- name = normalizePath(name)
- m.mu.Lock()
- file := mem.CreateFile(name)
- m.getData()[name] = file
- m.registerWithParent(file)
- m.mu.Unlock()
- return mem.NewFileHandle(file), nil
-}
-
-func (m *MemMapFs) unRegisterWithParent(fileName string) error {
- f, err := m.lockfreeOpen(fileName)
- if err != nil {
- return err
- }
- parent := m.findParent(f)
- if parent == nil {
- log.Panic("parent of ", f.Name(), " is nil")
- }
-
- parent.Lock()
- mem.RemoveFromMemDir(parent, f)
- parent.Unlock()
- return nil
-}
-
-func (m *MemMapFs) findParent(f *mem.FileData) *mem.FileData {
- pdir, _ := filepath.Split(f.Name())
- pdir = filepath.Clean(pdir)
- pfile, err := m.lockfreeOpen(pdir)
- if err != nil {
- return nil
- }
- return pfile
-}
-
-func (m *MemMapFs) registerWithParent(f *mem.FileData) {
- if f == nil {
- return
- }
- parent := m.findParent(f)
- if parent == nil {
- pdir := filepath.Dir(filepath.Clean(f.Name()))
- err := m.lockfreeMkdir(pdir, 0777)
- if err != nil {
- //log.Println("Mkdir error:", err)
- return
- }
- parent, err = m.lockfreeOpen(pdir)
- if err != nil {
- //log.Println("Open after Mkdir error:", err)
- return
- }
- }
-
- parent.Lock()
- mem.InitializeDir(parent)
- mem.AddToMemDir(parent, f)
- parent.Unlock()
-}
-
-func (m *MemMapFs) lockfreeMkdir(name string, perm os.FileMode) error {
- name = normalizePath(name)
- x, ok := m.getData()[name]
- if ok {
- // Only return ErrFileExists if it's a file, not a directory.
- i := mem.FileInfo{FileData: x}
- if !i.IsDir() {
- return ErrFileExists
- }
- } else {
- item := mem.CreateDir(name)
- m.getData()[name] = item
- m.registerWithParent(item)
- }
- return nil
-}
-
-func (m *MemMapFs) Mkdir(name string, perm os.FileMode) error {
- name = normalizePath(name)
-
- m.mu.RLock()
- _, ok := m.getData()[name]
- m.mu.RUnlock()
- if ok {
- return &os.PathError{Op: "mkdir", Path: name, Err: ErrFileExists}
- }
-
- m.mu.Lock()
- item := mem.CreateDir(name)
- m.getData()[name] = item
- m.registerWithParent(item)
- m.mu.Unlock()
-
- m.Chmod(name, perm|os.ModeDir)
-
- return nil
-}
-
-func (m *MemMapFs) MkdirAll(path string, perm os.FileMode) error {
- err := m.Mkdir(path, perm)
- if err != nil {
- if err.(*os.PathError).Err == ErrFileExists {
- return nil
- }
- return err
- }
- return nil
-}
-
-// Handle some relative paths
-func normalizePath(path string) string {
- path = filepath.Clean(path)
-
- switch path {
- case ".":
- return FilePathSeparator
- case "..":
- return FilePathSeparator
- default:
- return path
- }
-}
-
-func (m *MemMapFs) Open(name string) (File, error) {
- f, err := m.open(name)
- if f != nil {
- return mem.NewReadOnlyFileHandle(f), err
- }
- return nil, err
-}
-
-func (m *MemMapFs) openWrite(name string) (File, error) {
- f, err := m.open(name)
- if f != nil {
- return mem.NewFileHandle(f), err
- }
- return nil, err
-}
-
-func (m *MemMapFs) open(name string) (*mem.FileData, error) {
- name = normalizePath(name)
-
- m.mu.RLock()
- f, ok := m.getData()[name]
- m.mu.RUnlock()
- if !ok {
- return nil, &os.PathError{Op: "open", Path: name, Err: ErrFileNotFound}
- }
- return f, nil
-}
-
-func (m *MemMapFs) lockfreeOpen(name string) (*mem.FileData, error) {
- name = normalizePath(name)
- f, ok := m.getData()[name]
- if ok {
- return f, nil
- } else {
- return nil, ErrFileNotFound
- }
-}
-
-func (m *MemMapFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
- chmod := false
- file, err := m.openWrite(name)
- if os.IsNotExist(err) && (flag&os.O_CREATE > 0) {
- file, err = m.Create(name)
- chmod = true
- }
- if err != nil {
- return nil, err
- }
- if flag == os.O_RDONLY {
- file = mem.NewReadOnlyFileHandle(file.(*mem.File).Data())
- }
- if flag&os.O_APPEND > 0 {
- _, err = file.Seek(0, os.SEEK_END)
- if err != nil {
- file.Close()
- return nil, err
- }
- }
- if flag&os.O_TRUNC > 0 && flag&(os.O_RDWR|os.O_WRONLY) > 0 {
- err = file.Truncate(0)
- if err != nil {
- file.Close()
- return nil, err
- }
- }
- if chmod {
- m.Chmod(name, perm)
- }
- return file, nil
-}
-
-func (m *MemMapFs) Remove(name string) error {
- name = normalizePath(name)
-
- m.mu.Lock()
- defer m.mu.Unlock()
-
- if _, ok := m.getData()[name]; ok {
- err := m.unRegisterWithParent(name)
- if err != nil {
- return &os.PathError{Op: "remove", Path: name, Err: err}
- }
- delete(m.getData(), name)
- } else {
- return &os.PathError{Op: "remove", Path: name, Err: os.ErrNotExist}
- }
- return nil
-}
-
-func (m *MemMapFs) RemoveAll(path string) error {
- path = normalizePath(path)
- m.mu.Lock()
- m.unRegisterWithParent(path)
- m.mu.Unlock()
-
- m.mu.RLock()
- defer m.mu.RUnlock()
-
- for p, _ := range m.getData() {
- if strings.HasPrefix(p, path) {
- m.mu.RUnlock()
- m.mu.Lock()
- delete(m.getData(), p)
- m.mu.Unlock()
- m.mu.RLock()
- }
- }
- return nil
-}
-
-func (m *MemMapFs) Rename(oldname, newname string) error {
- oldname = normalizePath(oldname)
- newname = normalizePath(newname)
-
- if oldname == newname {
- return nil
- }
-
- m.mu.RLock()
- defer m.mu.RUnlock()
- if _, ok := m.getData()[oldname]; ok {
- m.mu.RUnlock()
- m.mu.Lock()
- m.unRegisterWithParent(oldname)
- fileData := m.getData()[oldname]
- delete(m.getData(), oldname)
- mem.ChangeFileName(fileData, newname)
- m.getData()[newname] = fileData
- m.registerWithParent(fileData)
- m.mu.Unlock()
- m.mu.RLock()
- } else {
- return &os.PathError{Op: "rename", Path: oldname, Err: ErrFileNotFound}
- }
- return nil
-}
-
-func (m *MemMapFs) Stat(name string) (os.FileInfo, error) {
- f, err := m.Open(name)
- if err != nil {
- return nil, err
- }
- fi := mem.GetFileInfo(f.(*mem.File).Data())
- return fi, nil
-}
-
-func (m *MemMapFs) Chmod(name string, mode os.FileMode) error {
- name = normalizePath(name)
-
- m.mu.RLock()
- f, ok := m.getData()[name]
- m.mu.RUnlock()
- if !ok {
- return &os.PathError{Op: "chmod", Path: name, Err: ErrFileNotFound}
- }
-
- m.mu.Lock()
- mem.SetMode(f, mode)
- m.mu.Unlock()
-
- return nil
-}
-
-func (m *MemMapFs) Chtimes(name string, atime time.Time, mtime time.Time) error {
- name = normalizePath(name)
-
- m.mu.RLock()
- f, ok := m.getData()[name]
- m.mu.RUnlock()
- if !ok {
- return &os.PathError{Op: "chtimes", Path: name, Err: ErrFileNotFound}
- }
-
- m.mu.Lock()
- mem.SetModTime(f, mtime)
- m.mu.Unlock()
-
- return nil
-}
-
-func (m *MemMapFs) List() {
- for _, x := range m.data {
- y := mem.FileInfo{FileData: x}
- fmt.Println(x.Name(), y.Size())
- }
-}
-
-// func debugMemMapList(fs Fs) {
-// if x, ok := fs.(*MemMapFs); ok {
-// x.List()
-// }
-// }
diff --git a/vendor/github.com/spf13/afero/memmap_test.go b/vendor/github.com/spf13/afero/memmap_test.go
deleted file mode 100644
index 09d8680..0000000
--- a/vendor/github.com/spf13/afero/memmap_test.go
+++ /dev/null
@@ -1,421 +0,0 @@
-package afero
-
-import (
- "fmt"
- "os"
- "path/filepath"
- "runtime"
- "testing"
- "time"
-)
-
-func TestNormalizePath(t *testing.T) {
- type test struct {
- input string
- expected string
- }
-
- data := []test{
- {".", FilePathSeparator},
- {"./", FilePathSeparator},
- {"..", FilePathSeparator},
- {"../", FilePathSeparator},
- {"./..", FilePathSeparator},
- {"./../", FilePathSeparator},
- }
-
- for i, d := range data {
- cpath := normalizePath(d.input)
- if d.expected != cpath {
- t.Errorf("Test %d failed. Expected %q got %q", i, d.expected, cpath)
- }
- }
-}
-
-func TestPathErrors(t *testing.T) {
- path := filepath.Join(".", "some", "path")
- path2 := filepath.Join(".", "different", "path")
- fs := NewMemMapFs()
- perm := os.FileMode(0755)
-
- // relevant functions:
- // func (m *MemMapFs) Chmod(name string, mode os.FileMode) error
- // func (m *MemMapFs) Chtimes(name string, atime time.Time, mtime time.Time) error
- // func (m *MemMapFs) Create(name string) (File, error)
- // func (m *MemMapFs) Mkdir(name string, perm os.FileMode) error
- // func (m *MemMapFs) MkdirAll(path string, perm os.FileMode) error
- // func (m *MemMapFs) Open(name string) (File, error)
- // func (m *MemMapFs) OpenFile(name string, flag int, perm os.FileMode) (File, error)
- // func (m *MemMapFs) Remove(name string) error
- // func (m *MemMapFs) Rename(oldname, newname string) error
- // func (m *MemMapFs) Stat(name string) (os.FileInfo, error)
-
- err := fs.Chmod(path, perm)
- checkPathError(t, err, "Chmod")
-
- err = fs.Chtimes(path, time.Now(), time.Now())
- checkPathError(t, err, "Chtimes")
-
- // fs.Create doesn't return an error
-
- err = fs.Mkdir(path2, perm)
- if err != nil {
- t.Error(err)
- }
- err = fs.Mkdir(path2, perm)
- checkPathError(t, err, "Mkdir")
-
- err = fs.MkdirAll(path2, perm)
- if err != nil {
- t.Error("MkdirAll:", err)
- }
-
- _, err = fs.Open(path)
- checkPathError(t, err, "Open")
-
- _, err = fs.OpenFile(path, os.O_RDWR, perm)
- checkPathError(t, err, "OpenFile")
-
- err = fs.Remove(path)
- checkPathError(t, err, "Remove")
-
- err = fs.RemoveAll(path)
- if err != nil {
- t.Error("RemoveAll:", err)
- }
-
- err = fs.Rename(path, path2)
- checkPathError(t, err, "Rename")
-
- _, err = fs.Stat(path)
- checkPathError(t, err, "Stat")
-}
-
-func checkPathError(t *testing.T, err error, op string) {
- pathErr, ok := err.(*os.PathError)
- if !ok {
- t.Error(op+":", err, "is not a os.PathError")
- return
- }
- _, ok = pathErr.Err.(*os.PathError)
- if ok {
- t.Error(op+":", err, "contains another os.PathError")
- }
-}
-
-// Ensure Permissions are set on OpenFile/Mkdir/MkdirAll
-func TestPermSet(t *testing.T) {
- const fileName = "/myFileTest"
- const dirPath = "/myDirTest"
- const dirPathAll = "/my/path/to/dir"
-
- const fileMode = os.FileMode(0765)
- // directories will also have the directory bit set
- const dirMode = fileMode | os.ModeDir
-
- fs := NewMemMapFs()
-
- // Test Openfile
- f, err := fs.OpenFile(fileName, os.O_CREATE, fileMode)
- if err != nil {
- t.Errorf("OpenFile Create failed: %s", err)
- return
- }
- f.Close()
-
- s, err := fs.Stat(fileName)
- if err != nil {
- t.Errorf("Stat failed: %s", err)
- return
- }
- if s.Mode().String() != fileMode.String() {
- t.Errorf("Permissions Incorrect: %s != %s", s.Mode().String(), fileMode.String())
- return
- }
-
- // Test Mkdir
- err = fs.Mkdir(dirPath, dirMode)
- if err != nil {
- t.Errorf("MkDir Create failed: %s", err)
- return
- }
- s, err = fs.Stat(dirPath)
- if err != nil {
- t.Errorf("Stat failed: %s", err)
- return
- }
- // sets File
- if s.Mode().String() != dirMode.String() {
- t.Errorf("Permissions Incorrect: %s != %s", s.Mode().String(), dirMode.String())
- return
- }
-
- // Test MkdirAll
- err = fs.MkdirAll(dirPathAll, dirMode)
- if err != nil {
- t.Errorf("MkDir Create failed: %s", err)
- return
- }
- s, err = fs.Stat(dirPathAll)
- if err != nil {
- t.Errorf("Stat failed: %s", err)
- return
- }
- if s.Mode().String() != dirMode.String() {
- t.Errorf("Permissions Incorrect: %s != %s", s.Mode().String(), dirMode.String())
- return
- }
-}
-
-// Fails if multiple file objects use the same file.at counter in MemMapFs
-func TestMultipleOpenFiles(t *testing.T) {
- defer removeAllTestFiles(t)
- const fileName = "afero-demo2.txt"
-
- var data = make([][]byte, len(Fss))
-
- for i, fs := range Fss {
- dir := testDir(fs)
- path := filepath.Join(dir, fileName)
- fh1, err := fs.Create(path)
- if err != nil {
- t.Error("fs.Create failed: " + err.Error())
- }
- _, err = fh1.Write([]byte("test"))
- if err != nil {
- t.Error("fh.Write failed: " + err.Error())
- }
- _, err = fh1.Seek(0, os.SEEK_SET)
- if err != nil {
- t.Error(err)
- }
-
- fh2, err := fs.OpenFile(path, os.O_RDWR, 0777)
- if err != nil {
- t.Error("fs.OpenFile failed: " + err.Error())
- }
- _, err = fh2.Seek(0, os.SEEK_END)
- if err != nil {
- t.Error(err)
- }
- _, err = fh2.Write([]byte("data"))
- if err != nil {
- t.Error(err)
- }
- err = fh2.Close()
- if err != nil {
- t.Error(err)
- }
-
- _, err = fh1.Write([]byte("data"))
- if err != nil {
- t.Error(err)
- }
- err = fh1.Close()
- if err != nil {
- t.Error(err)
- }
- // the file now should contain "datadata"
- data[i], err = ReadFile(fs, path)
- if err != nil {
- t.Error(err)
- }
- }
-
- for i, fs := range Fss {
- if i == 0 {
- continue
- }
- if string(data[0]) != string(data[i]) {
- t.Errorf("%s and %s don't behave the same\n"+
- "%s: \"%s\"\n%s: \"%s\"\n",
- Fss[0].Name(), fs.Name(), Fss[0].Name(), data[0], fs.Name(), data[i])
- }
- }
-}
-
-// Test if file.Write() fails when opened as read only
-func TestReadOnly(t *testing.T) {
- defer removeAllTestFiles(t)
- const fileName = "afero-demo.txt"
-
- for _, fs := range Fss {
- dir := testDir(fs)
- path := filepath.Join(dir, fileName)
-
- f, err := fs.Create(path)
- if err != nil {
- t.Error(fs.Name()+":", "fs.Create failed: "+err.Error())
- }
- _, err = f.Write([]byte("test"))
- if err != nil {
- t.Error(fs.Name()+":", "Write failed: "+err.Error())
- }
- f.Close()
-
- f, err = fs.Open(path)
- if err != nil {
- t.Error("fs.Open failed: " + err.Error())
- }
- _, err = f.Write([]byte("data"))
- if err == nil {
- t.Error(fs.Name()+":", "No write error")
- }
- f.Close()
-
- f, err = fs.OpenFile(path, os.O_RDONLY, 0644)
- if err != nil {
- t.Error("fs.Open failed: " + err.Error())
- }
- _, err = f.Write([]byte("data"))
- if err == nil {
- t.Error(fs.Name()+":", "No write error")
- }
- f.Close()
- }
-}
-
-func TestWriteCloseTime(t *testing.T) {
- defer removeAllTestFiles(t)
- const fileName = "afero-demo.txt"
-
- for _, fs := range Fss {
- dir := testDir(fs)
- path := filepath.Join(dir, fileName)
-
- f, err := fs.Create(path)
- if err != nil {
- t.Error(fs.Name()+":", "fs.Create failed: "+err.Error())
- }
- f.Close()
-
- f, err = fs.Create(path)
- if err != nil {
- t.Error(fs.Name()+":", "fs.Create failed: "+err.Error())
- }
- fi, err := f.Stat()
- if err != nil {
- t.Error(fs.Name()+":", "Stat failed: "+err.Error())
- }
- timeBefore := fi.ModTime()
-
- // sorry for the delay, but we have to make sure time advances,
- // also on non Un*x systems...
- switch runtime.GOOS {
- case "windows":
- time.Sleep(2 * time.Second)
- case "darwin":
- time.Sleep(1 * time.Second)
- default: // depending on the FS, this may work with < 1 second, on my old ext3 it does not
- time.Sleep(1 * time.Second)
- }
-
- _, err = f.Write([]byte("test"))
- if err != nil {
- t.Error(fs.Name()+":", "Write failed: "+err.Error())
- }
- f.Close()
- fi, err = fs.Stat(path)
- if err != nil {
- t.Error(fs.Name()+":", "fs.Stat failed: "+err.Error())
- }
- if fi.ModTime().Equal(timeBefore) {
- t.Error(fs.Name()+":", "ModTime was not set on Close()")
- }
- }
-}
-
-// This test should be run with the race detector on:
-// go test -race -v -timeout 10s -run TestRacingDeleteAndClose
-func TestRacingDeleteAndClose(t *testing.T) {
- fs := NewMemMapFs()
- pathname := "testfile"
- f, err := fs.Create(pathname)
- if err != nil {
- t.Fatal(err)
- }
-
- in := make(chan bool)
-
- go func() {
- <-in
- f.Close()
- }()
- go func() {
- <-in
- fs.Remove(pathname)
- }()
- close(in)
-}
-
-// This test should be run with the race detector on:
-// go test -run TestMemFsDataRace -race
-func TestMemFsDataRace(t *testing.T) {
- const dir = "test_dir"
- fs := NewMemMapFs()
-
- if err := fs.MkdirAll(dir, 0777); err != nil {
- t.Fatal(err)
- }
-
- const n = 1000
- done := make(chan struct{})
-
- go func() {
- defer close(done)
- for i := 0; i < n; i++ {
- fname := filepath.Join(dir, fmt.Sprintf("%d.txt", i))
- if err := WriteFile(fs, fname, []byte(""), 0777); err != nil {
- panic(err)
- }
- if err := fs.Remove(fname); err != nil {
- panic(err)
- }
- }
- }()
-
-loop:
- for {
- select {
- case <-done:
- break loop
- default:
- _, err := ReadDir(fs, dir)
- if err != nil {
- t.Fatal(err)
- }
- }
- }
-}
-
-func TestMemFsDirMode(t *testing.T) {
- fs := NewMemMapFs()
- err := fs.Mkdir("/testDir1", 0644)
- if err != nil {
- t.Error(err)
- }
- err = fs.MkdirAll("/sub/testDir2", 0644)
- if err != nil {
- t.Error(err)
- }
- info, err := fs.Stat("/testDir1")
- if err != nil {
- t.Error(err)
- }
- if !info.IsDir() {
- t.Error("should be a directory")
- }
- if !info.Mode().IsDir() {
- t.Error("FileMode is not directory")
- }
- info, err = fs.Stat("/sub/testDir2")
- if err != nil {
- t.Error(err)
- }
- if !info.IsDir() {
- t.Error("should be a directory")
- }
- if !info.Mode().IsDir() {
- t.Error("FileMode is not directory")
- }
-}
diff --git a/vendor/github.com/spf13/afero/os.go b/vendor/github.com/spf13/afero/os.go
deleted file mode 100644
index 6b8bce1..0000000
--- a/vendor/github.com/spf13/afero/os.go
+++ /dev/null
@@ -1,94 +0,0 @@
-// Copyright © 2014 Steve Francia .
-// Copyright 2013 tsuru authors. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package afero
-
-import (
- "os"
- "time"
-)
-
-// OsFs is a Fs implementation that uses functions provided by the os package.
-//
-// For details in any method, check the documentation of the os package
-// (http://golang.org/pkg/os/).
-type OsFs struct{}
-
-func NewOsFs() Fs {
- return &OsFs{}
-}
-
-func (OsFs) Name() string { return "OsFs" }
-
-func (OsFs) Create(name string) (File, error) {
- f, e := os.Create(name)
- if f == nil {
- // while this looks strange, we need to return a bare nil (of type nil) not
- // a nil value of type *os.File or nil won't be nil
- return nil, e
- }
- return f, e
-}
-
-func (OsFs) Mkdir(name string, perm os.FileMode) error {
- return os.Mkdir(name, perm)
-}
-
-func (OsFs) MkdirAll(path string, perm os.FileMode) error {
- return os.MkdirAll(path, perm)
-}
-
-func (OsFs) Open(name string) (File, error) {
- f, e := os.Open(name)
- if f == nil {
- // while this looks strange, we need to return a bare nil (of type nil) not
- // a nil value of type *os.File or nil won't be nil
- return nil, e
- }
- return f, e
-}
-
-func (OsFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
- f, e := os.OpenFile(name, flag, perm)
- if f == nil {
- // while this looks strange, we need to return a bare nil (of type nil) not
- // a nil value of type *os.File or nil won't be nil
- return nil, e
- }
- return f, e
-}
-
-func (OsFs) Remove(name string) error {
- return os.Remove(name)
-}
-
-func (OsFs) RemoveAll(path string) error {
- return os.RemoveAll(path)
-}
-
-func (OsFs) Rename(oldname, newname string) error {
- return os.Rename(oldname, newname)
-}
-
-func (OsFs) Stat(name string) (os.FileInfo, error) {
- return os.Stat(name)
-}
-
-func (OsFs) Chmod(name string, mode os.FileMode) error {
- return os.Chmod(name, mode)
-}
-
-func (OsFs) Chtimes(name string, atime time.Time, mtime time.Time) error {
- return os.Chtimes(name, atime, mtime)
-}
diff --git a/vendor/github.com/spf13/afero/path.go b/vendor/github.com/spf13/afero/path.go
deleted file mode 100644
index 1d90e46..0000000
--- a/vendor/github.com/spf13/afero/path.go
+++ /dev/null
@@ -1,108 +0,0 @@
-// Copyright ©2015 The Go Authors
-// Copyright ©2015 Steve Francia
-//
-// 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 afero
-
-import (
- "os"
- "path/filepath"
- "sort"
-)
-
-// readDirNames reads the directory named by dirname and returns
-// a sorted list of directory entries.
-// adapted from https://golang.org/src/path/filepath/path.go
-func readDirNames(fs Fs, dirname string) ([]string, error) {
- f, err := fs.Open(dirname)
- if err != nil {
- return nil, err
- }
- names, err := f.Readdirnames(-1)
- f.Close()
- if err != nil {
- return nil, err
- }
- sort.Strings(names)
- return names, nil
-}
-
-// walk recursively descends path, calling walkFn
-// adapted from https://golang.org/src/path/filepath/path.go
-func walk(fs Fs, path string, info os.FileInfo, walkFn filepath.WalkFunc) error {
- err := walkFn(path, info, nil)
- if err != nil {
- if info.IsDir() && err == filepath.SkipDir {
- return nil
- }
- return err
- }
-
- if !info.IsDir() {
- return nil
- }
-
- names, err := readDirNames(fs, path)
- if err != nil {
- return walkFn(path, info, err)
- }
-
- for _, name := range names {
- filename := filepath.Join(path, name)
- fileInfo, err := lstatIfOs(fs, filename)
- if err != nil {
- if err := walkFn(filename, fileInfo, err); err != nil && err != filepath.SkipDir {
- return err
- }
- } else {
- err = walk(fs, filename, fileInfo, walkFn)
- if err != nil {
- if !fileInfo.IsDir() || err != filepath.SkipDir {
- return err
- }
- }
- }
- }
- return nil
-}
-
-// if the filesystem is OsFs use Lstat, else use fs.Stat
-func lstatIfOs(fs Fs, path string) (info os.FileInfo, err error) {
- _, ok := fs.(*OsFs)
- if ok {
- info, err = os.Lstat(path)
- } else {
- info, err = fs.Stat(path)
- }
- return
-}
-
-// Walk walks the file tree rooted at root, calling walkFn for each file or
-// directory in the tree, including root. All errors that arise visiting files
-// and directories are filtered by walkFn. The files are walked in lexical
-// order, which makes the output deterministic but means that for very
-// large directories Walk can be inefficient.
-// Walk does not follow symbolic links.
-
-func (a Afero) Walk(root string, walkFn filepath.WalkFunc) error {
- return Walk(a.Fs, root, walkFn)
-}
-
-func Walk(fs Fs, root string, walkFn filepath.WalkFunc) error {
- info, err := lstatIfOs(fs, root)
- if err != nil {
- return walkFn(root, nil, err)
- }
- return walk(fs, root, info, walkFn)
-}
diff --git a/vendor/github.com/spf13/afero/path_test.go b/vendor/github.com/spf13/afero/path_test.go
deleted file mode 100644
index 104a6bc..0000000
--- a/vendor/github.com/spf13/afero/path_test.go
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright © 2014 Steve Francia .
-// Copyright 2009 The Go Authors. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package afero
-
-import (
- "fmt"
- "os"
- "testing"
-)
-
-func TestWalk(t *testing.T) {
- defer removeAllTestFiles(t)
- var testDir string
- for i, fs := range Fss {
- if i == 0 {
- testDir = setupTestDirRoot(t, fs)
- } else {
- setupTestDirReusePath(t, fs, testDir)
- }
- }
-
- outputs := make([]string, len(Fss))
- for i, fs := range Fss {
- walkFn := func(path string, info os.FileInfo, err error) error {
- if err != nil {
- t.Error("walkFn err:", err)
- }
- var size int64
- if !info.IsDir() {
- size = info.Size()
- }
- outputs[i] += fmt.Sprintln(path, info.Name(), size, info.IsDir(), err)
- return nil
- }
- err := Walk(fs, testDir, walkFn)
- if err != nil {
- t.Error(err)
- }
- }
- fail := false
- for i, o := range outputs {
- if i == 0 {
- continue
- }
- if o != outputs[i-1] {
- fail = true
- break
- }
- }
- if fail {
- t.Log("Walk outputs not equal!")
- for i, o := range outputs {
- t.Log(Fss[i].Name() + "\n" + o)
- }
- t.Fail()
- }
-}
diff --git a/vendor/github.com/spf13/afero/readonlyfs.go b/vendor/github.com/spf13/afero/readonlyfs.go
deleted file mode 100644
index f1fa55b..0000000
--- a/vendor/github.com/spf13/afero/readonlyfs.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package afero
-
-import (
- "os"
- "syscall"
- "time"
-)
-
-type ReadOnlyFs struct {
- source Fs
-}
-
-func NewReadOnlyFs(source Fs) Fs {
- return &ReadOnlyFs{source: source}
-}
-
-func (r *ReadOnlyFs) ReadDir(name string) ([]os.FileInfo, error) {
- return ReadDir(r.source, name)
-}
-
-func (r *ReadOnlyFs) Chtimes(n string, a, m time.Time) error {
- return syscall.EPERM
-}
-
-func (r *ReadOnlyFs) Chmod(n string, m os.FileMode) error {
- return syscall.EPERM
-}
-
-func (r *ReadOnlyFs) Name() string {
- return "ReadOnlyFilter"
-}
-
-func (r *ReadOnlyFs) Stat(name string) (os.FileInfo, error) {
- return r.source.Stat(name)
-}
-
-func (r *ReadOnlyFs) Rename(o, n string) error {
- return syscall.EPERM
-}
-
-func (r *ReadOnlyFs) RemoveAll(p string) error {
- return syscall.EPERM
-}
-
-func (r *ReadOnlyFs) Remove(n string) error {
- return syscall.EPERM
-}
-
-func (r *ReadOnlyFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
- if flag&(os.O_WRONLY|syscall.O_RDWR|os.O_APPEND|os.O_CREATE|os.O_TRUNC) != 0 {
- return nil, syscall.EPERM
- }
- return r.source.OpenFile(name, flag, perm)
-}
-
-func (r *ReadOnlyFs) Open(n string) (File, error) {
- return r.source.Open(n)
-}
-
-func (r *ReadOnlyFs) Mkdir(n string, p os.FileMode) error {
- return syscall.EPERM
-}
-
-func (r *ReadOnlyFs) MkdirAll(n string, p os.FileMode) error {
- return syscall.EPERM
-}
-
-func (r *ReadOnlyFs) Create(n string) (File, error) {
- return nil, syscall.EPERM
-}
diff --git a/vendor/github.com/spf13/afero/regexpfs.go b/vendor/github.com/spf13/afero/regexpfs.go
deleted file mode 100644
index 9d92dbc..0000000
--- a/vendor/github.com/spf13/afero/regexpfs.go
+++ /dev/null
@@ -1,214 +0,0 @@
-package afero
-
-import (
- "os"
- "regexp"
- "syscall"
- "time"
-)
-
-// The RegexpFs filters files (not directories) by regular expression. Only
-// files matching the given regexp will be allowed, all others get a ENOENT error (
-// "No such file or directory").
-//
-type RegexpFs struct {
- re *regexp.Regexp
- source Fs
-}
-
-func NewRegexpFs(source Fs, re *regexp.Regexp) Fs {
- return &RegexpFs{source: source, re: re}
-}
-
-type RegexpFile struct {
- f File
- re *regexp.Regexp
-}
-
-func (r *RegexpFs) matchesName(name string) error {
- if r.re == nil {
- return nil
- }
- if r.re.MatchString(name) {
- return nil
- }
- return syscall.ENOENT
-}
-
-func (r *RegexpFs) dirOrMatches(name string) error {
- dir, err := IsDir(r.source, name)
- if err != nil {
- return err
- }
- if dir {
- return nil
- }
- return r.matchesName(name)
-}
-
-func (r *RegexpFs) Chtimes(name string, a, m time.Time) error {
- if err := r.dirOrMatches(name); err != nil {
- return err
- }
- return r.source.Chtimes(name, a, m)
-}
-
-func (r *RegexpFs) Chmod(name string, mode os.FileMode) error {
- if err := r.dirOrMatches(name); err != nil {
- return err
- }
- return r.source.Chmod(name, mode)
-}
-
-func (r *RegexpFs) Name() string {
- return "RegexpFs"
-}
-
-func (r *RegexpFs) Stat(name string) (os.FileInfo, error) {
- if err := r.dirOrMatches(name); err != nil {
- return nil, err
- }
- return r.source.Stat(name)
-}
-
-func (r *RegexpFs) Rename(oldname, newname string) error {
- dir, err := IsDir(r.source, oldname)
- if err != nil {
- return err
- }
- if dir {
- return nil
- }
- if err := r.matchesName(oldname); err != nil {
- return err
- }
- if err := r.matchesName(newname); err != nil {
- return err
- }
- return r.source.Rename(oldname, newname)
-}
-
-func (r *RegexpFs) RemoveAll(p string) error {
- dir, err := IsDir(r.source, p)
- if err != nil {
- return err
- }
- if !dir {
- if err := r.matchesName(p); err != nil {
- return err
- }
- }
- return r.source.RemoveAll(p)
-}
-
-func (r *RegexpFs) Remove(name string) error {
- if err := r.dirOrMatches(name); err != nil {
- return err
- }
- return r.source.Remove(name)
-}
-
-func (r *RegexpFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
- if err := r.dirOrMatches(name); err != nil {
- return nil, err
- }
- return r.source.OpenFile(name, flag, perm)
-}
-
-func (r *RegexpFs) Open(name string) (File, error) {
- dir, err := IsDir(r.source, name)
- if err != nil {
- return nil, err
- }
- if !dir {
- if err := r.matchesName(name); err != nil {
- return nil, err
- }
- }
- f, err := r.source.Open(name)
- return &RegexpFile{f: f, re: r.re}, nil
-}
-
-func (r *RegexpFs) Mkdir(n string, p os.FileMode) error {
- return r.source.Mkdir(n, p)
-}
-
-func (r *RegexpFs) MkdirAll(n string, p os.FileMode) error {
- return r.source.MkdirAll(n, p)
-}
-
-func (r *RegexpFs) Create(name string) (File, error) {
- if err := r.matchesName(name); err != nil {
- return nil, err
- }
- return r.source.Create(name)
-}
-
-func (f *RegexpFile) Close() error {
- return f.f.Close()
-}
-
-func (f *RegexpFile) Read(s []byte) (int, error) {
- return f.f.Read(s)
-}
-
-func (f *RegexpFile) ReadAt(s []byte, o int64) (int, error) {
- return f.f.ReadAt(s, o)
-}
-
-func (f *RegexpFile) Seek(o int64, w int) (int64, error) {
- return f.f.Seek(o, w)
-}
-
-func (f *RegexpFile) Write(s []byte) (int, error) {
- return f.f.Write(s)
-}
-
-func (f *RegexpFile) WriteAt(s []byte, o int64) (int, error) {
- return f.f.WriteAt(s, o)
-}
-
-func (f *RegexpFile) Name() string {
- return f.f.Name()
-}
-
-func (f *RegexpFile) Readdir(c int) (fi []os.FileInfo, err error) {
- var rfi []os.FileInfo
- rfi, err = f.f.Readdir(c)
- if err != nil {
- return nil, err
- }
- for _, i := range rfi {
- if i.IsDir() || f.re.MatchString(i.Name()) {
- fi = append(fi, i)
- }
- }
- return fi, nil
-}
-
-func (f *RegexpFile) Readdirnames(c int) (n []string, err error) {
- fi, err := f.Readdir(c)
- if err != nil {
- return nil, err
- }
- for _, s := range fi {
- n = append(n, s.Name())
- }
- return n, nil
-}
-
-func (f *RegexpFile) Stat() (os.FileInfo, error) {
- return f.f.Stat()
-}
-
-func (f *RegexpFile) Sync() error {
- return f.f.Sync()
-}
-
-func (f *RegexpFile) Truncate(s int64) error {
- return f.f.Truncate(s)
-}
-
-func (f *RegexpFile) WriteString(s string) (int, error) {
- return f.f.WriteString(s)
-}
diff --git a/vendor/github.com/spf13/afero/ro_regexp_test.go b/vendor/github.com/spf13/afero/ro_regexp_test.go
deleted file mode 100644
index ef8a35d..0000000
--- a/vendor/github.com/spf13/afero/ro_regexp_test.go
+++ /dev/null
@@ -1,96 +0,0 @@
-package afero
-
-import (
- "regexp"
- "testing"
-)
-
-func TestFilterReadOnly(t *testing.T) {
- fs := &ReadOnlyFs{source: &MemMapFs{}}
- _, err := fs.Create("/file.txt")
- if err == nil {
- t.Errorf("Did not fail to create file")
- }
- // t.Logf("ERR=%s", err)
-}
-
-func TestFilterReadonlyRemoveAndRead(t *testing.T) {
- mfs := &MemMapFs{}
- fh, err := mfs.Create("/file.txt")
- fh.Write([]byte("content here"))
- fh.Close()
-
- fs := NewReadOnlyFs(mfs)
- err = fs.Remove("/file.txt")
- if err == nil {
- t.Errorf("Did not fail to remove file")
- }
-
- fh, err = fs.Open("/file.txt")
- if err != nil {
- t.Errorf("Failed to open file: %s", err)
- }
-
- buf := make([]byte, len("content here"))
- _, err = fh.Read(buf)
- fh.Close()
- if string(buf) != "content here" {
- t.Errorf("Failed to read file: %s", err)
- }
-
- err = mfs.Remove("/file.txt")
- if err != nil {
- t.Errorf("Failed to remove file")
- }
-
- fh, err = fs.Open("/file.txt")
- if err == nil {
- fh.Close()
- t.Errorf("File still present")
- }
-}
-
-func TestFilterRegexp(t *testing.T) {
- fs := NewRegexpFs(&MemMapFs{}, regexp.MustCompile(`\.txt$`))
- _, err := fs.Create("/file.html")
- if err == nil {
-
- t.Errorf("Did not fail to create file")
- }
- // t.Logf("ERR=%s", err)
-}
-
-func TestFilterRORegexpChain(t *testing.T) {
- rofs := &ReadOnlyFs{source: &MemMapFs{}}
- fs := &RegexpFs{re: regexp.MustCompile(`\.txt$`), source: rofs}
- _, err := fs.Create("/file.txt")
- if err == nil {
- t.Errorf("Did not fail to create file")
- }
- // t.Logf("ERR=%s", err)
-}
-
-func TestFilterRegexReadDir(t *testing.T) {
- mfs := &MemMapFs{}
- fs1 := &RegexpFs{re: regexp.MustCompile(`\.txt$`), source: mfs}
- fs := &RegexpFs{re: regexp.MustCompile(`^a`), source: fs1}
-
- mfs.MkdirAll("/dir/sub", 0777)
- for _, name := range []string{"afile.txt", "afile.html", "bfile.txt"} {
- for _, dir := range []string{"/dir/", "/dir/sub/"} {
- fh, _ := mfs.Create(dir + name)
- fh.Close()
- }
- }
-
- files, _ := ReadDir(fs, "/dir")
- if len(files) != 2 { // afile.txt, sub
- t.Errorf("Got wrong number of files: %#v", files)
- }
-
- f, _ := fs.Open("/dir/sub")
- names, _ := f.Readdirnames(-1)
- if len(names) != 1 {
- t.Errorf("Got wrong number of names: %v", names)
- }
-}
diff --git a/vendor/github.com/spf13/afero/unionFile.go b/vendor/github.com/spf13/afero/unionFile.go
deleted file mode 100644
index 99f9e5d..0000000
--- a/vendor/github.com/spf13/afero/unionFile.go
+++ /dev/null
@@ -1,274 +0,0 @@
-package afero
-
-import (
- "io"
- "os"
- "path/filepath"
- "syscall"
-)
-
-// The UnionFile implements the afero.File interface and will be returned
-// when reading a directory present at least in the overlay or opening a file
-// for writing.
-//
-// The calls to
-// Readdir() and Readdirnames() merge the file os.FileInfo / names from the
-// base and the overlay - for files present in both layers, only those
-// from the overlay will be used.
-//
-// When opening files for writing (Create() / OpenFile() with the right flags)
-// the operations will be done in both layers, starting with the overlay. A
-// successful read in the overlay will move the cursor position in the base layer
-// by the number of bytes read.
-type UnionFile struct {
- base File
- layer File
- off int
- files []os.FileInfo
-}
-
-func (f *UnionFile) Close() error {
- // first close base, so we have a newer timestamp in the overlay. If we'd close
- // the overlay first, we'd get a cacheStale the next time we access this file
- // -> cache would be useless ;-)
- if f.base != nil {
- f.base.Close()
- }
- if f.layer != nil {
- return f.layer.Close()
- }
- return BADFD
-}
-
-func (f *UnionFile) Read(s []byte) (int, error) {
- if f.layer != nil {
- n, err := f.layer.Read(s)
- if (err == nil || err == io.EOF) && f.base != nil {
- // advance the file position also in the base file, the next
- // call may be a write at this position (or a seek with SEEK_CUR)
- if _, seekErr := f.base.Seek(int64(n), os.SEEK_CUR); seekErr != nil {
- // only overwrite err in case the seek fails: we need to
- // report an eventual io.EOF to the caller
- err = seekErr
- }
- }
- return n, err
- }
- if f.base != nil {
- return f.base.Read(s)
- }
- return 0, BADFD
-}
-
-func (f *UnionFile) ReadAt(s []byte, o int64) (int, error) {
- if f.layer != nil {
- n, err := f.layer.ReadAt(s, o)
- if (err == nil || err == io.EOF) && f.base != nil {
- _, err = f.base.Seek(o+int64(n), os.SEEK_SET)
- }
- return n, err
- }
- if f.base != nil {
- return f.base.ReadAt(s, o)
- }
- return 0, BADFD
-}
-
-func (f *UnionFile) Seek(o int64, w int) (pos int64, err error) {
- if f.layer != nil {
- pos, err = f.layer.Seek(o, w)
- if (err == nil || err == io.EOF) && f.base != nil {
- _, err = f.base.Seek(o, w)
- }
- return pos, err
- }
- if f.base != nil {
- return f.base.Seek(o, w)
- }
- return 0, BADFD
-}
-
-func (f *UnionFile) Write(s []byte) (n int, err error) {
- if f.layer != nil {
- n, err = f.layer.Write(s)
- if err == nil && f.base != nil { // hmm, do we have fixed size files where a write may hit the EOF mark?
- _, err = f.base.Write(s)
- }
- return n, err
- }
- if f.base != nil {
- return f.base.Write(s)
- }
- return 0, BADFD
-}
-
-func (f *UnionFile) WriteAt(s []byte, o int64) (n int, err error) {
- if f.layer != nil {
- n, err = f.layer.WriteAt(s, o)
- if err == nil && f.base != nil {
- _, err = f.base.WriteAt(s, o)
- }
- return n, err
- }
- if f.base != nil {
- return f.base.WriteAt(s, o)
- }
- return 0, BADFD
-}
-
-func (f *UnionFile) Name() string {
- if f.layer != nil {
- return f.layer.Name()
- }
- return f.base.Name()
-}
-
-// Readdir will weave the two directories together and
-// return a single view of the overlayed directories
-func (f *UnionFile) Readdir(c int) (ofi []os.FileInfo, err error) {
- if f.off == 0 {
- var files = make(map[string]os.FileInfo)
- var rfi []os.FileInfo
- if f.layer != nil {
- rfi, err = f.layer.Readdir(-1)
- if err != nil {
- return nil, err
- }
- for _, fi := range rfi {
- files[fi.Name()] = fi
- }
- }
-
- if f.base != nil {
- rfi, err = f.base.Readdir(-1)
- if err != nil {
- return nil, err
- }
- for _, fi := range rfi {
- if _, exists := files[fi.Name()]; !exists {
- files[fi.Name()] = fi
- }
- }
- }
- for _, fi := range files {
- f.files = append(f.files, fi)
- }
- }
- if c == -1 {
- return f.files[f.off:], nil
- }
- defer func() { f.off += c }()
- return f.files[f.off:c], nil
-}
-
-func (f *UnionFile) Readdirnames(c int) ([]string, error) {
- rfi, err := f.Readdir(c)
- if err != nil {
- return nil, err
- }
- var names []string
- for _, fi := range rfi {
- names = append(names, fi.Name())
- }
- return names, nil
-}
-
-func (f *UnionFile) Stat() (os.FileInfo, error) {
- if f.layer != nil {
- return f.layer.Stat()
- }
- if f.base != nil {
- return f.base.Stat()
- }
- return nil, BADFD
-}
-
-func (f *UnionFile) Sync() (err error) {
- if f.layer != nil {
- err = f.layer.Sync()
- if err == nil && f.base != nil {
- err = f.base.Sync()
- }
- return err
- }
- if f.base != nil {
- return f.base.Sync()
- }
- return BADFD
-}
-
-func (f *UnionFile) Truncate(s int64) (err error) {
- if f.layer != nil {
- err = f.layer.Truncate(s)
- if err == nil && f.base != nil {
- err = f.base.Truncate(s)
- }
- return err
- }
- if f.base != nil {
- return f.base.Truncate(s)
- }
- return BADFD
-}
-
-func (f *UnionFile) WriteString(s string) (n int, err error) {
- if f.layer != nil {
- n, err = f.layer.WriteString(s)
- if err == nil && f.base != nil {
- _, err = f.base.WriteString(s)
- }
- return n, err
- }
- if f.base != nil {
- return f.base.WriteString(s)
- }
- return 0, BADFD
-}
-
-func copyToLayer(base Fs, layer Fs, name string) error {
- bfh, err := base.Open(name)
- if err != nil {
- return err
- }
- defer bfh.Close()
-
- // First make sure the directory exists
- exists, err := Exists(layer, filepath.Dir(name))
- if err != nil {
- return err
- }
- if !exists {
- err = layer.MkdirAll(filepath.Dir(name), 0777) // FIXME?
- if err != nil {
- return err
- }
- }
-
- // Create the file on the overlay
- lfh, err := layer.Create(name)
- if err != nil {
- return err
- }
- n, err := io.Copy(lfh, bfh)
- if err != nil {
- // If anything fails, clean up the file
- layer.Remove(name)
- lfh.Close()
- return err
- }
-
- bfi, err := bfh.Stat()
- if err != nil || bfi.Size() != n {
- layer.Remove(name)
- lfh.Close()
- return syscall.EIO
- }
-
- err = lfh.Close()
- if err != nil {
- layer.Remove(name)
- lfh.Close()
- return err
- }
- return layer.Chtimes(name, bfi.ModTime(), bfi.ModTime())
-}
diff --git a/vendor/github.com/spf13/afero/util.go b/vendor/github.com/spf13/afero/util.go
deleted file mode 100644
index 7463887..0000000
--- a/vendor/github.com/spf13/afero/util.go
+++ /dev/null
@@ -1,331 +0,0 @@
-// Copyright ©2015 Steve Francia
-// Portions Copyright ©2015 The Hugo Authors
-// Portions Copyright 2016-present Bjørn Erik Pedersen
-//
-// 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 afero
-
-import (
- "bytes"
- "fmt"
- "io"
- "log"
- "os"
- "path/filepath"
- "strings"
- "unicode"
-
- "golang.org/x/text/transform"
- "golang.org/x/text/unicode/norm"
-)
-
-// Filepath separator defined by os.Separator.
-const FilePathSeparator = string(filepath.Separator)
-
-// Takes a reader and a path and writes the content
-func (a Afero) WriteReader(path string, r io.Reader) (err error) {
- return WriteReader(a.Fs, path, r)
-}
-
-func WriteReader(fs Fs, path string, r io.Reader) (err error) {
- dir, _ := filepath.Split(path)
- ospath := filepath.FromSlash(dir)
-
- if ospath != "" {
- err = fs.MkdirAll(ospath, 0777) // rwx, rw, r
- if err != nil {
- if err != os.ErrExist {
- log.Panicln(err)
- }
- }
- }
-
- file, err := fs.Create(path)
- if err != nil {
- return
- }
- defer file.Close()
-
- _, err = io.Copy(file, r)
- return
-}
-
-// Same as WriteReader but checks to see if file/directory already exists.
-func (a Afero) SafeWriteReader(path string, r io.Reader) (err error) {
- return SafeWriteReader(a.Fs, path, r)
-}
-
-func SafeWriteReader(fs Fs, path string, r io.Reader) (err error) {
- dir, _ := filepath.Split(path)
- ospath := filepath.FromSlash(dir)
-
- if ospath != "" {
- err = fs.MkdirAll(ospath, 0777) // rwx, rw, r
- if err != nil {
- return
- }
- }
-
- exists, err := Exists(fs, path)
- if err != nil {
- return
- }
- if exists {
- return fmt.Errorf("%v already exists", path)
- }
-
- file, err := fs.Create(path)
- if err != nil {
- return
- }
- defer file.Close()
-
- _, err = io.Copy(file, r)
- return
-}
-
-func (a Afero) GetTempDir(subPath string) string {
- return GetTempDir(a.Fs, subPath)
-}
-
-// GetTempDir returns the default temp directory with trailing slash
-// if subPath is not empty then it will be created recursively with mode 777 rwx rwx rwx
-func GetTempDir(fs Fs, subPath string) string {
- addSlash := func(p string) string {
- if FilePathSeparator != p[len(p)-1:] {
- p = p + FilePathSeparator
- }
- return p
- }
- dir := addSlash(os.TempDir())
-
- if subPath != "" {
- // preserve windows backslash :-(
- if FilePathSeparator == "\\" {
- subPath = strings.Replace(subPath, "\\", "____", -1)
- }
- dir = dir + UnicodeSanitize((subPath))
- if FilePathSeparator == "\\" {
- dir = strings.Replace(dir, "____", "\\", -1)
- }
-
- if exists, _ := Exists(fs, dir); exists {
- return addSlash(dir)
- }
-
- err := fs.MkdirAll(dir, 0777)
- if err != nil {
- panic(err)
- }
- dir = addSlash(dir)
- }
- return dir
-}
-
-// Rewrite string to remove non-standard path characters
-func UnicodeSanitize(s string) string {
- source := []rune(s)
- target := make([]rune, 0, len(source))
-
- for _, r := range source {
- if unicode.IsLetter(r) ||
- unicode.IsDigit(r) ||
- unicode.IsMark(r) ||
- r == '.' ||
- r == '/' ||
- r == '\\' ||
- r == '_' ||
- r == '-' ||
- r == '%' ||
- r == ' ' ||
- r == '#' {
- target = append(target, r)
- }
- }
-
- return string(target)
-}
-
-// Transform characters with accents into plain forms.
-func NeuterAccents(s string) string {
- t := transform.Chain(norm.NFD, transform.RemoveFunc(isMn), norm.NFC)
- result, _, _ := transform.String(t, string(s))
-
- return result
-}
-
-func isMn(r rune) bool {
- return unicode.Is(unicode.Mn, r) // Mn: nonspacing marks
-}
-
-func (a Afero) FileContainsBytes(filename string, subslice []byte) (bool, error) {
- return FileContainsBytes(a.Fs, filename, subslice)
-}
-
-// Check if a file contains a specified byte slice.
-func FileContainsBytes(fs Fs, filename string, subslice []byte) (bool, error) {
- f, err := fs.Open(filename)
- if err != nil {
- return false, err
- }
- defer f.Close()
-
- return readerContainsAny(f, subslice), nil
-}
-
-func (a Afero) FileContainsAnyBytes(filename string, subslices [][]byte) (bool, error) {
- return FileContainsAnyBytes(a.Fs, filename, subslices)
-}
-
-// Check if a file contains any of the specified byte slices.
-func FileContainsAnyBytes(fs Fs, filename string, subslices [][]byte) (bool, error) {
- f, err := fs.Open(filename)
- if err != nil {
- return false, err
- }
- defer f.Close()
-
- return readerContainsAny(f, subslices...), nil
-}
-
-// readerContains reports whether any of the subslices is within r.
-func readerContainsAny(r io.Reader, subslices ...[]byte) bool {
-
- if r == nil || len(subslices) == 0 {
- return false
- }
-
- largestSlice := 0
-
- for _, sl := range subslices {
- if len(sl) > largestSlice {
- largestSlice = len(sl)
- }
- }
-
- if largestSlice == 0 {
- return false
- }
-
- bufflen := largestSlice * 4
- halflen := bufflen / 2
- buff := make([]byte, bufflen)
- var err error
- var n, i int
-
- for {
- i++
- if i == 1 {
- n, err = io.ReadAtLeast(r, buff[:halflen], halflen)
- } else {
- if i != 2 {
- // shift left to catch overlapping matches
- copy(buff[:], buff[halflen:])
- }
- n, err = io.ReadAtLeast(r, buff[halflen:], halflen)
- }
-
- if n > 0 {
- for _, sl := range subslices {
- if bytes.Contains(buff, sl) {
- return true
- }
- }
- }
-
- if err != nil {
- break
- }
- }
- return false
-}
-
-func (a Afero) DirExists(path string) (bool, error) {
- return DirExists(a.Fs, path)
-}
-
-// DirExists checks if a path exists and is a directory.
-func DirExists(fs Fs, path string) (bool, error) {
- fi, err := fs.Stat(path)
- if err == nil && fi.IsDir() {
- return true, nil
- }
- if os.IsNotExist(err) {
- return false, nil
- }
- return false, err
-}
-
-func (a Afero) IsDir(path string) (bool, error) {
- return IsDir(a.Fs, path)
-}
-
-// IsDir checks if a given path is a directory.
-func IsDir(fs Fs, path string) (bool, error) {
- fi, err := fs.Stat(path)
- if err != nil {
- return false, err
- }
- return fi.IsDir(), nil
-}
-
-func (a Afero) IsEmpty(path string) (bool, error) {
- return IsEmpty(a.Fs, path)
-}
-
-// IsEmpty checks if a given file or directory is empty.
-func IsEmpty(fs Fs, path string) (bool, error) {
- if b, _ := Exists(fs, path); !b {
- return false, fmt.Errorf("%q path does not exist", path)
- }
- fi, err := fs.Stat(path)
- if err != nil {
- return false, err
- }
- if fi.IsDir() {
- f, err := fs.Open(path)
- if err != nil {
- return false, err
- }
- defer f.Close()
- list, err := f.Readdir(-1)
- return len(list) == 0, nil
- }
- return fi.Size() == 0, nil
-}
-
-func (a Afero) Exists(path string) (bool, error) {
- return Exists(a.Fs, path)
-}
-
-// Check if a file or directory exists.
-func Exists(fs Fs, path string) (bool, error) {
- _, err := fs.Stat(path)
- if err == nil {
- return true, nil
- }
- if os.IsNotExist(err) {
- return false, nil
- }
- return false, err
-}
-
-func FullBaseFsPath(basePathFs *BasePathFs, relativePath string) string {
- combinedPath := filepath.Join(basePathFs.path, relativePath)
- if parent, ok := basePathFs.source.(*BasePathFs); ok {
- return FullBaseFsPath(parent, combinedPath)
- }
-
- return combinedPath
-}
diff --git a/vendor/github.com/spf13/afero/util_test.go b/vendor/github.com/spf13/afero/util_test.go
deleted file mode 100644
index b5852f1..0000000
--- a/vendor/github.com/spf13/afero/util_test.go
+++ /dev/null
@@ -1,450 +0,0 @@
-// Copyright ©2015 Steve Francia
-// Portions Copyright ©2015 The Hugo Authors
-//
-//
-// 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 afero
-
-import (
- "fmt"
- "os"
- "path/filepath"
- "strconv"
- "strings"
- "testing"
- "time"
-)
-
-var testFS = new(MemMapFs)
-
-func TestDirExists(t *testing.T) {
- type test struct {
- input string
- expected bool
- }
-
- // First create a couple directories so there is something in the filesystem
- //testFS := new(MemMapFs)
- testFS.MkdirAll("/foo/bar", 0777)
-
- data := []test{
- {".", true},
- {"./", true},
- {"..", true},
- {"../", true},
- {"./..", true},
- {"./../", true},
- {"/foo/", true},
- {"/foo", true},
- {"/foo/bar", true},
- {"/foo/bar/", true},
- {"/", true},
- {"/some-really-random-directory-name", false},
- {"/some/really/random/directory/name", false},
- {"./some-really-random-local-directory-name", false},
- {"./some/really/random/local/directory/name", false},
- }
-
- for i, d := range data {
- exists, _ := DirExists(testFS, filepath.FromSlash(d.input))
- if d.expected != exists {
- t.Errorf("Test %d %q failed. Expected %t got %t", i, d.input, d.expected, exists)
- }
- }
-}
-
-func TestIsDir(t *testing.T) {
- testFS = new(MemMapFs)
-
- type test struct {
- input string
- expected bool
- }
- data := []test{
- {"./", true},
- {"/", true},
- {"./this-directory-does-not-existi", false},
- {"/this-absolute-directory/does-not-exist", false},
- }
-
- for i, d := range data {
-
- exists, _ := IsDir(testFS, d.input)
- if d.expected != exists {
- t.Errorf("Test %d failed. Expected %t got %t", i, d.expected, exists)
- }
- }
-}
-
-func TestIsEmpty(t *testing.T) {
- testFS = new(MemMapFs)
-
- zeroSizedFile, _ := createZeroSizedFileInTempDir()
- defer deleteFileInTempDir(zeroSizedFile)
- nonZeroSizedFile, _ := createNonZeroSizedFileInTempDir()
- defer deleteFileInTempDir(nonZeroSizedFile)
- emptyDirectory, _ := createEmptyTempDir()
- defer deleteTempDir(emptyDirectory)
- nonEmptyZeroLengthFilesDirectory, _ := createTempDirWithZeroLengthFiles()
- defer deleteTempDir(nonEmptyZeroLengthFilesDirectory)
- nonEmptyNonZeroLengthFilesDirectory, _ := createTempDirWithNonZeroLengthFiles()
- defer deleteTempDir(nonEmptyNonZeroLengthFilesDirectory)
- nonExistentFile := os.TempDir() + "/this-file-does-not-exist.txt"
- nonExistentDir := os.TempDir() + "/this/direcotry/does/not/exist/"
-
- fileDoesNotExist := fmt.Errorf("%q path does not exist", nonExistentFile)
- dirDoesNotExist := fmt.Errorf("%q path does not exist", nonExistentDir)
-
- type test struct {
- input string
- expectedResult bool
- expectedErr error
- }
-
- data := []test{
- {zeroSizedFile.Name(), true, nil},
- {nonZeroSizedFile.Name(), false, nil},
- {emptyDirectory, true, nil},
- {nonEmptyZeroLengthFilesDirectory, false, nil},
- {nonEmptyNonZeroLengthFilesDirectory, false, nil},
- {nonExistentFile, false, fileDoesNotExist},
- {nonExistentDir, false, dirDoesNotExist},
- }
- for i, d := range data {
- exists, err := IsEmpty(testFS, d.input)
- if d.expectedResult != exists {
- t.Errorf("Test %d %q failed exists. Expected result %t got %t", i, d.input, d.expectedResult, exists)
- }
- if d.expectedErr != nil {
- if d.expectedErr.Error() != err.Error() {
- t.Errorf("Test %d failed with err. Expected %q(%#v) got %q(%#v)", i, d.expectedErr, d.expectedErr, err, err)
- }
- } else {
- if d.expectedErr != err {
- t.Errorf("Test %d failed. Expected error %q(%#v) got %q(%#v)", i, d.expectedErr, d.expectedErr, err, err)
- }
- }
- }
-}
-
-func TestReaderContains(t *testing.T) {
- for i, this := range []struct {
- v1 string
- v2 [][]byte
- expect bool
- }{
- {"abc", [][]byte{[]byte("a")}, true},
- {"abc", [][]byte{[]byte("b")}, true},
- {"abcdefg", [][]byte{[]byte("efg")}, true},
- {"abc", [][]byte{[]byte("d")}, false},
- {"abc", [][]byte{[]byte("d"), []byte("e")}, false},
- {"abc", [][]byte{[]byte("d"), []byte("a")}, true},
- {"abc", [][]byte{[]byte("b"), []byte("e")}, true},
- {"", nil, false},
- {"", [][]byte{[]byte("a")}, false},
- {"a", [][]byte{[]byte("")}, false},
- {"", [][]byte{[]byte("")}, false}} {
- result := readerContainsAny(strings.NewReader(this.v1), this.v2...)
- if result != this.expect {
- t.Errorf("[%d] readerContains: got %t but expected %t", i, result, this.expect)
- }
- }
-
- if readerContainsAny(nil, []byte("a")) {
- t.Error("readerContains with nil reader")
- }
-
- if readerContainsAny(nil, nil) {
- t.Error("readerContains with nil arguments")
- }
-}
-
-func createZeroSizedFileInTempDir() (File, error) {
- filePrefix := "_path_test_"
- f, e := TempFile(testFS, "", filePrefix) // dir is os.TempDir()
- if e != nil {
- // if there was an error no file was created.
- // => no requirement to delete the file
- return nil, e
- }
- return f, nil
-}
-
-func createNonZeroSizedFileInTempDir() (File, error) {
- f, err := createZeroSizedFileInTempDir()
- if err != nil {
- // no file ??
- }
- byteString := []byte("byteString")
- err = WriteFile(testFS, f.Name(), byteString, 0644)
- if err != nil {
- // delete the file
- deleteFileInTempDir(f)
- return nil, err
- }
- return f, nil
-}
-
-func deleteFileInTempDir(f File) {
- err := testFS.Remove(f.Name())
- if err != nil {
- // now what?
- }
-}
-
-func createEmptyTempDir() (string, error) {
- dirPrefix := "_dir_prefix_"
- d, e := TempDir(testFS, "", dirPrefix) // will be in os.TempDir()
- if e != nil {
- // no directory to delete - it was never created
- return "", e
- }
- return d, nil
-}
-
-func createTempDirWithZeroLengthFiles() (string, error) {
- d, dirErr := createEmptyTempDir()
- if dirErr != nil {
- //now what?
- }
- filePrefix := "_path_test_"
- _, fileErr := TempFile(testFS, d, filePrefix) // dir is os.TempDir()
- if fileErr != nil {
- // if there was an error no file was created.
- // but we need to remove the directory to clean-up
- deleteTempDir(d)
- return "", fileErr
- }
- // the dir now has one, zero length file in it
- return d, nil
-
-}
-
-func createTempDirWithNonZeroLengthFiles() (string, error) {
- d, dirErr := createEmptyTempDir()
- if dirErr != nil {
- //now what?
- }
- filePrefix := "_path_test_"
- f, fileErr := TempFile(testFS, d, filePrefix) // dir is os.TempDir()
- if fileErr != nil {
- // if there was an error no file was created.
- // but we need to remove the directory to clean-up
- deleteTempDir(d)
- return "", fileErr
- }
- byteString := []byte("byteString")
- fileErr = WriteFile(testFS, f.Name(), byteString, 0644)
- if fileErr != nil {
- // delete the file
- deleteFileInTempDir(f)
- // also delete the directory
- deleteTempDir(d)
- return "", fileErr
- }
-
- // the dir now has one, zero length file in it
- return d, nil
-
-}
-
-func TestExists(t *testing.T) {
- zeroSizedFile, _ := createZeroSizedFileInTempDir()
- defer deleteFileInTempDir(zeroSizedFile)
- nonZeroSizedFile, _ := createNonZeroSizedFileInTempDir()
- defer deleteFileInTempDir(nonZeroSizedFile)
- emptyDirectory, _ := createEmptyTempDir()
- defer deleteTempDir(emptyDirectory)
- nonExistentFile := os.TempDir() + "/this-file-does-not-exist.txt"
- nonExistentDir := os.TempDir() + "/this/direcotry/does/not/exist/"
-
- type test struct {
- input string
- expectedResult bool
- expectedErr error
- }
-
- data := []test{
- {zeroSizedFile.Name(), true, nil},
- {nonZeroSizedFile.Name(), true, nil},
- {emptyDirectory, true, nil},
- {nonExistentFile, false, nil},
- {nonExistentDir, false, nil},
- }
- for i, d := range data {
- exists, err := Exists(testFS, d.input)
- if d.expectedResult != exists {
- t.Errorf("Test %d failed. Expected result %t got %t", i, d.expectedResult, exists)
- }
- if d.expectedErr != err {
- t.Errorf("Test %d failed. Expected %q got %q", i, d.expectedErr, err)
- }
- }
-
-}
-
-func TestSafeWriteToDisk(t *testing.T) {
- emptyFile, _ := createZeroSizedFileInTempDir()
- defer deleteFileInTempDir(emptyFile)
- tmpDir, _ := createEmptyTempDir()
- defer deleteTempDir(tmpDir)
-
- randomString := "This is a random string!"
- reader := strings.NewReader(randomString)
-
- fileExists := fmt.Errorf("%v already exists", emptyFile.Name())
-
- type test struct {
- filename string
- expectedErr error
- }
-
- now := time.Now().Unix()
- nowStr := strconv.FormatInt(now, 10)
- data := []test{
- {emptyFile.Name(), fileExists},
- {tmpDir + "/" + nowStr, nil},
- }
-
- for i, d := range data {
- e := SafeWriteReader(testFS, d.filename, reader)
- if d.expectedErr != nil {
- if d.expectedErr.Error() != e.Error() {
- t.Errorf("Test %d failed. Expected error %q but got %q", i, d.expectedErr.Error(), e.Error())
- }
- } else {
- if d.expectedErr != e {
- t.Errorf("Test %d failed. Expected %q but got %q", i, d.expectedErr, e)
- }
- contents, _ := ReadFile(testFS, d.filename)
- if randomString != string(contents) {
- t.Errorf("Test %d failed. Expected contents %q but got %q", i, randomString, string(contents))
- }
- }
- reader.Seek(0, 0)
- }
-}
-
-func TestWriteToDisk(t *testing.T) {
- emptyFile, _ := createZeroSizedFileInTempDir()
- defer deleteFileInTempDir(emptyFile)
- tmpDir, _ := createEmptyTempDir()
- defer deleteTempDir(tmpDir)
-
- randomString := "This is a random string!"
- reader := strings.NewReader(randomString)
-
- type test struct {
- filename string
- expectedErr error
- }
-
- now := time.Now().Unix()
- nowStr := strconv.FormatInt(now, 10)
- data := []test{
- {emptyFile.Name(), nil},
- {tmpDir + "/" + nowStr, nil},
- }
-
- for i, d := range data {
- e := WriteReader(testFS, d.filename, reader)
- if d.expectedErr != e {
- t.Errorf("Test %d failed. WriteToDisk Error Expected %q but got %q", i, d.expectedErr, e)
- }
- contents, e := ReadFile(testFS, d.filename)
- if e != nil {
- t.Errorf("Test %d failed. Could not read file %s. Reason: %s\n", i, d.filename, e)
- }
- if randomString != string(contents) {
- t.Errorf("Test %d failed. Expected contents %q but got %q", i, randomString, string(contents))
- }
- reader.Seek(0, 0)
- }
-}
-
-func TestGetTempDir(t *testing.T) {
- dir := os.TempDir()
- if FilePathSeparator != dir[len(dir)-1:] {
- dir = dir + FilePathSeparator
- }
- testDir := "hugoTestFolder" + FilePathSeparator
- tests := []struct {
- input string
- expected string
- }{
- {"", dir},
- {testDir + " Foo bar ", dir + testDir + " Foo bar " + FilePathSeparator},
- {testDir + "Foo.Bar/foo_Bar-Foo", dir + testDir + "Foo.Bar/foo_Bar-Foo" + FilePathSeparator},
- {testDir + "fOO,bar:foo%bAR", dir + testDir + "fOObarfoo%bAR" + FilePathSeparator},
- {testDir + "FOo/BaR.html", dir + testDir + "FOo/BaR.html" + FilePathSeparator},
- {testDir + "трям/трям", dir + testDir + "трям/трям" + FilePathSeparator},
- {testDir + "은행", dir + testDir + "은행" + FilePathSeparator},
- {testDir + "Банковский кассир", dir + testDir + "Банковский кассир" + FilePathSeparator},
- }
-
- for _, test := range tests {
- output := GetTempDir(new(MemMapFs), test.input)
- if output != test.expected {
- t.Errorf("Expected %#v, got %#v\n", test.expected, output)
- }
- }
-}
-
-// This function is very dangerous. Don't use it.
-func deleteTempDir(d string) {
- err := os.RemoveAll(d)
- if err != nil {
- // now what?
- }
-}
-
-func TestFullBaseFsPath(t *testing.T) {
- type dirSpec struct {
- Dir1, Dir2, Dir3 string
- }
- dirSpecs := []dirSpec{
- dirSpec{Dir1: "/", Dir2: "/", Dir3: "/"},
- dirSpec{Dir1: "/", Dir2: "/path2", Dir3: "/"},
- dirSpec{Dir1: "/path1/dir", Dir2: "/path2/dir/", Dir3: "/path3/dir"},
- dirSpec{Dir1: "C:/path1", Dir2: "path2/dir", Dir3: "/path3/dir/"},
- }
-
- for _, ds := range dirSpecs {
- memFs := NewMemMapFs()
- level1Fs := NewBasePathFs(memFs, ds.Dir1)
- level2Fs := NewBasePathFs(level1Fs, ds.Dir2)
- level3Fs := NewBasePathFs(level2Fs, ds.Dir3)
-
- type spec struct {
- BaseFs Fs
- FileName string
- ExpectedPath string
- }
- specs := []spec{
- spec{BaseFs: level3Fs, FileName: "f.txt", ExpectedPath: filepath.Join(ds.Dir1, ds.Dir2, ds.Dir3, "f.txt")},
- spec{BaseFs: level3Fs, FileName: "", ExpectedPath: filepath.Join(ds.Dir1, ds.Dir2, ds.Dir3, "")},
- spec{BaseFs: level2Fs, FileName: "f.txt", ExpectedPath: filepath.Join(ds.Dir1, ds.Dir2, "f.txt")},
- spec{BaseFs: level2Fs, FileName: "", ExpectedPath: filepath.Join(ds.Dir1, ds.Dir2, "")},
- spec{BaseFs: level1Fs, FileName: "f.txt", ExpectedPath: filepath.Join(ds.Dir1, "f.txt")},
- spec{BaseFs: level1Fs, FileName: "", ExpectedPath: filepath.Join(ds.Dir1, "")},
- }
-
- for _, s := range specs {
- if actualPath := FullBaseFsPath(s.BaseFs.(*BasePathFs), s.FileName); actualPath != s.ExpectedPath {
- t.Errorf("Expected \n%s got \n%s", s.ExpectedPath, actualPath)
- }
- }
- }
-}
diff --git a/vendor/github.com/spf13/cast/.gitignore b/vendor/github.com/spf13/cast/.gitignore
deleted file mode 100644
index 53053a8..0000000
--- a/vendor/github.com/spf13/cast/.gitignore
+++ /dev/null
@@ -1,25 +0,0 @@
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-*.exe
-*.test
-
-*.bench
diff --git a/vendor/github.com/spf13/cast/.travis.yml b/vendor/github.com/spf13/cast/.travis.yml
deleted file mode 100644
index 4da9766..0000000
--- a/vendor/github.com/spf13/cast/.travis.yml
+++ /dev/null
@@ -1,14 +0,0 @@
-language: go
-sudo: required
-go:
- - 1.7.5
- - 1.8
- - tip
-os:
- - linux
-matrix:
- allow_failures:
- - go: tip
- fast_finish: true
-script:
- - make check
diff --git a/vendor/github.com/spf13/cast/LICENSE b/vendor/github.com/spf13/cast/LICENSE
deleted file mode 100644
index 4527efb..0000000
--- a/vendor/github.com/spf13/cast/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2014 Steve Francia
-
-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.
\ No newline at end of file
diff --git a/vendor/github.com/spf13/cast/Makefile b/vendor/github.com/spf13/cast/Makefile
deleted file mode 100644
index 7ccf893..0000000
--- a/vendor/github.com/spf13/cast/Makefile
+++ /dev/null
@@ -1,38 +0,0 @@
-# A Self-Documenting Makefile: http://marmelab.com/blog/2016/02/29/auto-documented-makefile.html
-
-.PHONY: check fmt lint test test-race vet test-cover-html help
-.DEFAULT_GOAL := help
-
-check: test-race fmt vet lint ## Run tests and linters
-
-test: ## Run tests
- go test ./...
-
-test-race: ## Run tests with race detector
- go test -race ./...
-
-fmt: ## Run gofmt linter
- @for d in `go list` ; do \
- if [ "`gofmt -l -s $$GOPATH/src/$$d | tee /dev/stderr`" ]; then \
- echo "^ improperly formatted go files" && echo && exit 1; \
- fi \
- done
-
-lint: ## Run golint linter
- @for d in `go list` ; do \
- if [ "`golint $$d | tee /dev/stderr`" ]; then \
- echo "^ golint errors!" && echo && exit 1; \
- fi \
- done
-
-vet: ## Run go vet linter
- @if [ "`go vet | tee /dev/stderr`" ]; then \
- echo "^ go vet errors!" && echo && exit 1; \
- fi
-
-test-cover-html: ## Generate test coverage report
- go test -coverprofile=coverage.out -covermode=count
- go tool cover -func=coverage.out
-
-help:
- @grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
diff --git a/vendor/github.com/spf13/cast/README.md b/vendor/github.com/spf13/cast/README.md
deleted file mode 100644
index e693939..0000000
--- a/vendor/github.com/spf13/cast/README.md
+++ /dev/null
@@ -1,75 +0,0 @@
-cast
-====
-[](https://godoc.org/github.com/spf13/cast)
-[](https://travis-ci.org/spf13/cast)
-[](https://goreportcard.com/report/github.com/spf13/cast)
-
-Easy and safe casting from one type to another in Go
-
-Don’t Panic! ... Cast
-
-## What is Cast?
-
-Cast is a library to convert between different go types in a consistent and easy way.
-
-Cast provides simple functions to easily convert a number to a string, an
-interface into a bool, etc. Cast does this intelligently when an obvious
-conversion is possible. It doesn’t make any attempts to guess what you meant,
-for example you can only convert a string to an int when it is a string
-representation of an int such as “8”. Cast was developed for use in
-[Hugo](http://hugo.spf13.com), a website engine which uses YAML, TOML or JSON
-for meta data.
-
-## Why use Cast?
-
-When working with dynamic data in Go you often need to cast or convert the data
-from one type into another. Cast goes beyond just using type assertion (though
-it uses that when possible) to provide a very straightforward and convenient
-library.
-
-If you are working with interfaces to handle things like dynamic content
-you’ll need an easy way to convert an interface into a given type. This
-is the library for you.
-
-If you are taking in data from YAML, TOML or JSON or other formats which lack
-full types, then Cast is the library for you.
-
-## Usage
-
-Cast provides a handful of To_____ methods. These methods will always return
-the desired type. **If input is provided that will not convert to that type, the
-0 or nil value for that type will be returned**.
-
-Cast also provides identical methods To_____E. These return the same result as
-the To_____ methods, plus an additional error which tells you if it successfully
-converted. Using these methods you can tell the difference between when the
-input matched the zero value or when the conversion failed and the zero value
-was returned.
-
-The following examples are merely a sample of what is available. Please review
-the code for a complete set.
-
-### Example ‘ToString’:
-
- cast.ToString("mayonegg") // "mayonegg"
- cast.ToString(8) // "8"
- cast.ToString(8.31) // "8.31"
- cast.ToString([]byte("one time")) // "one time"
- cast.ToString(nil) // ""
-
- var foo interface{} = "one more time"
- cast.ToString(foo) // "one more time"
-
-
-### Example ‘ToInt’:
-
- cast.ToInt(8) // 8
- cast.ToInt(8.31) // 8
- cast.ToInt("8") // 8
- cast.ToInt(true) // 1
- cast.ToInt(false) // 0
-
- var eight interface{} = 8
- cast.ToInt(eight) // 8
- cast.ToInt(nil) // 0
-
diff --git a/vendor/github.com/spf13/cast/cast.go b/vendor/github.com/spf13/cast/cast.go
deleted file mode 100644
index 8b8c208..0000000
--- a/vendor/github.com/spf13/cast/cast.go
+++ /dev/null
@@ -1,159 +0,0 @@
-// Copyright © 2014 Steve Francia .
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-// Package cast provides easy and safe casting in Go.
-package cast
-
-import "time"
-
-// ToBool casts an interface to a bool type.
-func ToBool(i interface{}) bool {
- v, _ := ToBoolE(i)
- return v
-}
-
-// ToTime casts an interface to a time.Time type.
-func ToTime(i interface{}) time.Time {
- v, _ := ToTimeE(i)
- return v
-}
-
-// ToDuration casts an interface to a time.Duration type.
-func ToDuration(i interface{}) time.Duration {
- v, _ := ToDurationE(i)
- return v
-}
-
-// ToFloat64 casts an interface to a float64 type.
-func ToFloat64(i interface{}) float64 {
- v, _ := ToFloat64E(i)
- return v
-}
-
-// ToFloat32 casts an interface to a float32 type.
-func ToFloat32(i interface{}) float32 {
- v, _ := ToFloat32E(i)
- return v
-}
-
-// ToInt64 casts an interface to an int64 type.
-func ToInt64(i interface{}) int64 {
- v, _ := ToInt64E(i)
- return v
-}
-
-// ToInt32 casts an interface to an int32 type.
-func ToInt32(i interface{}) int32 {
- v, _ := ToInt32E(i)
- return v
-}
-
-// ToInt16 casts an interface to an int16 type.
-func ToInt16(i interface{}) int16 {
- v, _ := ToInt16E(i)
- return v
-}
-
-// ToInt8 casts an interface to an int8 type.
-func ToInt8(i interface{}) int8 {
- v, _ := ToInt8E(i)
- return v
-}
-
-// ToInt casts an interface to an int type.
-func ToInt(i interface{}) int {
- v, _ := ToIntE(i)
- return v
-}
-
-// ToUint casts an interface to a uint type.
-func ToUint(i interface{}) uint {
- v, _ := ToUintE(i)
- return v
-}
-
-// ToUint64 casts an interface to a uint64 type.
-func ToUint64(i interface{}) uint64 {
- v, _ := ToUint64E(i)
- return v
-}
-
-// ToUint32 casts an interface to a uint32 type.
-func ToUint32(i interface{}) uint32 {
- v, _ := ToUint32E(i)
- return v
-}
-
-// ToUint16 casts an interface to a uint16 type.
-func ToUint16(i interface{}) uint16 {
- v, _ := ToUint16E(i)
- return v
-}
-
-// ToUint8 casts an interface to a uint8 type.
-func ToUint8(i interface{}) uint8 {
- v, _ := ToUint8E(i)
- return v
-}
-
-// ToString casts an interface to a string type.
-func ToString(i interface{}) string {
- v, _ := ToStringE(i)
- return v
-}
-
-// ToStringMapString casts an interface to a map[string]string type.
-func ToStringMapString(i interface{}) map[string]string {
- v, _ := ToStringMapStringE(i)
- return v
-}
-
-// ToStringMapStringSlice casts an interface to a map[string][]string type.
-func ToStringMapStringSlice(i interface{}) map[string][]string {
- v, _ := ToStringMapStringSliceE(i)
- return v
-}
-
-// ToStringMapBool casts an interface to a map[string]bool type.
-func ToStringMapBool(i interface{}) map[string]bool {
- v, _ := ToStringMapBoolE(i)
- return v
-}
-
-// ToStringMap casts an interface to a map[string]interface{} type.
-func ToStringMap(i interface{}) map[string]interface{} {
- v, _ := ToStringMapE(i)
- return v
-}
-
-// ToSlice casts an interface to a []interface{} type.
-func ToSlice(i interface{}) []interface{} {
- v, _ := ToSliceE(i)
- return v
-}
-
-// ToBoolSlice casts an interface to a []bool type.
-func ToBoolSlice(i interface{}) []bool {
- v, _ := ToBoolSliceE(i)
- return v
-}
-
-// ToStringSlice casts an interface to a []string type.
-func ToStringSlice(i interface{}) []string {
- v, _ := ToStringSliceE(i)
- return v
-}
-
-// ToIntSlice casts an interface to a []int type.
-func ToIntSlice(i interface{}) []int {
- v, _ := ToIntSliceE(i)
- return v
-}
-
-// ToDurationSlice casts an interface to a []time.Duration type.
-func ToDurationSlice(i interface{}) []time.Duration {
- v, _ := ToDurationSliceE(i)
- return v
-}
diff --git a/vendor/github.com/spf13/cast/cast_test.go b/vendor/github.com/spf13/cast/cast_test.go
deleted file mode 100644
index 404fe76..0000000
--- a/vendor/github.com/spf13/cast/cast_test.go
+++ /dev/null
@@ -1,1183 +0,0 @@
-// Copyright © 2014 Steve Francia .
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-package cast
-
-import (
- "fmt"
- "html/template"
- "testing"
- "time"
-
- "github.com/stretchr/testify/assert"
-)
-
-func TestToUintE(t *testing.T) {
- tests := []struct {
- input interface{}
- expect uint
- iserr bool
- }{
- {int(8), 8, false},
- {int8(8), 8, false},
- {int16(8), 8, false},
- {int32(8), 8, false},
- {int64(8), 8, false},
- {uint(8), 8, false},
- {uint8(8), 8, false},
- {uint16(8), 8, false},
- {uint32(8), 8, false},
- {uint64(8), 8, false},
- {float32(8.31), 8, false},
- {float64(8.31), 8, false},
- {true, 1, false},
- {false, 0, false},
- {"8", 8, false},
- {nil, 0, false},
- // errors
- {int(-8), 0, true},
- {int8(-8), 0, true},
- {int16(-8), 0, true},
- {int32(-8), 0, true},
- {int64(-8), 0, true},
- {float32(-8.31), 0, true},
- {float64(-8.31), 0, true},
- {"-8", 0, true},
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToUintE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test:
- v = ToUint(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToUint64E(t *testing.T) {
- tests := []struct {
- input interface{}
- expect uint64
- iserr bool
- }{
- {int(8), 8, false},
- {int8(8), 8, false},
- {int16(8), 8, false},
- {int32(8), 8, false},
- {int64(8), 8, false},
- {uint(8), 8, false},
- {uint8(8), 8, false},
- {uint16(8), 8, false},
- {uint32(8), 8, false},
- {uint64(8), 8, false},
- {float32(8.31), 8, false},
- {float64(8.31), 8, false},
- {true, 1, false},
- {false, 0, false},
- {"8", 8, false},
- {nil, 0, false},
- // errors
- {int(-8), 0, true},
- {int8(-8), 0, true},
- {int16(-8), 0, true},
- {int32(-8), 0, true},
- {int64(-8), 0, true},
- {float32(-8.31), 0, true},
- {float64(-8.31), 0, true},
- {"-8", 0, true},
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToUint64E(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test:
- v = ToUint64(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToUint32E(t *testing.T) {
- tests := []struct {
- input interface{}
- expect uint32
- iserr bool
- }{
- {int(8), 8, false},
- {int8(8), 8, false},
- {int16(8), 8, false},
- {int32(8), 8, false},
- {int64(8), 8, false},
- {uint(8), 8, false},
- {uint8(8), 8, false},
- {uint16(8), 8, false},
- {uint32(8), 8, false},
- {uint64(8), 8, false},
- {float32(8.31), 8, false},
- {float64(8.31), 8, false},
- {true, 1, false},
- {false, 0, false},
- {"8", 8, false},
- {nil, 0, false},
- {int(-8), 0, true},
- {int8(-8), 0, true},
- {int16(-8), 0, true},
- {int32(-8), 0, true},
- {int64(-8), 0, true},
- {float32(-8.31), 0, true},
- {float64(-8.31), 0, true},
- {"-8", 0, true},
- // errors
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToUint32E(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test:
- v = ToUint32(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToUint16E(t *testing.T) {
- tests := []struct {
- input interface{}
- expect uint16
- iserr bool
- }{
- {int(8), 8, false},
- {int8(8), 8, false},
- {int16(8), 8, false},
- {int32(8), 8, false},
- {int64(8), 8, false},
- {uint(8), 8, false},
- {uint8(8), 8, false},
- {uint16(8), 8, false},
- {uint32(8), 8, false},
- {uint64(8), 8, false},
- {float32(8.31), 8, false},
- {float64(8.31), 8, false},
- {true, 1, false},
- {false, 0, false},
- {"8", 8, false},
- {nil, 0, false},
- // errors
- {int(-8), 0, true},
- {int8(-8), 0, true},
- {int16(-8), 0, true},
- {int32(-8), 0, true},
- {int64(-8), 0, true},
- {float32(-8.31), 0, true},
- {float64(-8.31), 0, true},
- {"-8", 0, true},
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToUint16E(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToUint16(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToUint8E(t *testing.T) {
- tests := []struct {
- input interface{}
- expect uint8
- iserr bool
- }{
- {int(8), 8, false},
- {int8(8), 8, false},
- {int16(8), 8, false},
- {int32(8), 8, false},
- {int64(8), 8, false},
- {uint(8), 8, false},
- {uint8(8), 8, false},
- {uint16(8), 8, false},
- {uint32(8), 8, false},
- {uint64(8), 8, false},
- {float32(8.31), 8, false},
- {float64(8.31), 8, false},
- {true, 1, false},
- {false, 0, false},
- {"8", 8, false},
- {nil, 0, false},
- // errors
- {int(-8), 0, true},
- {int8(-8), 0, true},
- {int16(-8), 0, true},
- {int32(-8), 0, true},
- {int64(-8), 0, true},
- {float32(-8.31), 0, true},
- {float64(-8.31), 0, true},
- {"-8", 0, true},
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToUint8E(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToUint8(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToIntE(t *testing.T) {
- tests := []struct {
- input interface{}
- expect int
- iserr bool
- }{
- {int(8), 8, false},
- {int8(8), 8, false},
- {int16(8), 8, false},
- {int32(8), 8, false},
- {int64(8), 8, false},
- {uint(8), 8, false},
- {uint8(8), 8, false},
- {uint16(8), 8, false},
- {uint32(8), 8, false},
- {uint64(8), 8, false},
- {float32(8.31), 8, false},
- {float64(8.31), 8, false},
- {true, 1, false},
- {false, 0, false},
- {"8", 8, false},
- {nil, 0, false},
- // errors
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToIntE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToInt(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToInt64E(t *testing.T) {
- tests := []struct {
- input interface{}
- expect int64
- iserr bool
- }{
- {int(8), 8, false},
- {int8(8), 8, false},
- {int16(8), 8, false},
- {int32(8), 8, false},
- {int64(8), 8, false},
- {uint(8), 8, false},
- {uint8(8), 8, false},
- {uint16(8), 8, false},
- {uint32(8), 8, false},
- {uint64(8), 8, false},
- {float32(8.31), 8, false},
- {float64(8.31), 8, false},
- {true, 1, false},
- {false, 0, false},
- {"8", 8, false},
- {nil, 0, false},
- // errors
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToInt64E(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToInt64(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToInt32E(t *testing.T) {
- tests := []struct {
- input interface{}
- expect int32
- iserr bool
- }{
- {int(8), 8, false},
- {int8(8), 8, false},
- {int16(8), 8, false},
- {int32(8), 8, false},
- {int64(8), 8, false},
- {uint(8), 8, false},
- {uint8(8), 8, false},
- {uint16(8), 8, false},
- {uint32(8), 8, false},
- {uint64(8), 8, false},
- {float32(8.31), 8, false},
- {float64(8.31), 8, false},
- {true, 1, false},
- {false, 0, false},
- {"8", 8, false},
- {nil, 0, false},
- // errors
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToInt32E(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToInt32(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToInt16E(t *testing.T) {
- tests := []struct {
- input interface{}
- expect int16
- iserr bool
- }{
- {int(8), 8, false},
- {int8(8), 8, false},
- {int16(8), 8, false},
- {int32(8), 8, false},
- {int64(8), 8, false},
- {uint(8), 8, false},
- {uint8(8), 8, false},
- {uint16(8), 8, false},
- {uint32(8), 8, false},
- {uint64(8), 8, false},
- {float32(8.31), 8, false},
- {float64(8.31), 8, false},
- {true, 1, false},
- {false, 0, false},
- {"8", 8, false},
- {nil, 0, false},
- // errors
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToInt16E(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToInt16(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToInt8E(t *testing.T) {
- tests := []struct {
- input interface{}
- expect int8
- iserr bool
- }{
- {int(8), 8, false},
- {int8(8), 8, false},
- {int16(8), 8, false},
- {int32(8), 8, false},
- {int64(8), 8, false},
- {uint(8), 8, false},
- {uint8(8), 8, false},
- {uint16(8), 8, false},
- {uint32(8), 8, false},
- {uint64(8), 8, false},
- {float32(8.31), 8, false},
- {float64(8.31), 8, false},
- {true, 1, false},
- {false, 0, false},
- {"8", 8, false},
- {nil, 0, false},
- // errors
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToInt8E(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToInt8(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToFloat64E(t *testing.T) {
- tests := []struct {
- input interface{}
- expect float64
- iserr bool
- }{
- {int(8), 8, false},
- {int8(8), 8, false},
- {int16(8), 8, false},
- {int32(8), 8, false},
- {int64(8), 8, false},
- {uint(8), 8, false},
- {uint8(8), 8, false},
- {uint16(8), 8, false},
- {uint32(8), 8, false},
- {uint64(8), 8, false},
- {float32(8), 8, false},
- {float64(8.31), 8.31, false},
- {"8", 8, false},
- {true, 1, false},
- {false, 0, false},
- // errors
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToFloat64E(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToFloat64(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToFloat32E(t *testing.T) {
- tests := []struct {
- input interface{}
- expect float32
- iserr bool
- }{
- {int(8), 8, false},
- {int8(8), 8, false},
- {int16(8), 8, false},
- {int32(8), 8, false},
- {int64(8), 8, false},
- {uint(8), 8, false},
- {uint8(8), 8, false},
- {uint16(8), 8, false},
- {uint32(8), 8, false},
- {uint64(8), 8, false},
- {float32(8.31), 8.31, false},
- {float64(8.31), 8.31, false},
- {"8", 8, false},
- {true, 1, false},
- {false, 0, false},
- // errors
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToFloat32E(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToFloat32(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToStringE(t *testing.T) {
- type Key struct {
- k string
- }
- key := &Key{"foo"}
-
- tests := []struct {
- input interface{}
- expect string
- iserr bool
- }{
- {int(8), "8", false},
- {int8(8), "8", false},
- {int16(8), "8", false},
- {int32(8), "8", false},
- {int64(8), "8", false},
- {uint(8), "8", false},
- {uint8(8), "8", false},
- {uint16(8), "8", false},
- {uint32(8), "8", false},
- {uint64(8), "8", false},
- {float32(8.31), "8.31", false},
- {float64(8.31), "8.31", false},
- {true, "true", false},
- {false, "false", false},
- {nil, "", false},
- {[]byte("one time"), "one time", false},
- {"one more time", "one more time", false},
- {template.HTML("one time"), "one time", false},
- {template.URL("http://somehost.foo"), "http://somehost.foo", false},
- {template.JS("(1+2)"), "(1+2)", false},
- {template.CSS("a"), "a", false},
- {template.HTMLAttr("a"), "a", false},
- // errors
- {testing.T{}, "", true},
- {key, "", true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToStringE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToString(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-type foo struct {
- val string
-}
-
-func (x foo) String() string {
- return x.val
-}
-
-func TestStringerToString(t *testing.T) {
- var x foo
- x.val = "bar"
- assert.Equal(t, "bar", ToString(x))
-}
-
-type fu struct {
- val string
-}
-
-func (x fu) Error() string {
- return x.val
-}
-
-func TestErrorToString(t *testing.T) {
- var x fu
- x.val = "bar"
- assert.Equal(t, "bar", ToString(x))
-}
-
-func TestStringMapStringSliceE(t *testing.T) {
- // ToStringMapString inputs/outputs
- var stringMapString = map[string]string{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
- var stringMapInterface = map[string]interface{}{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
- var interfaceMapString = map[interface{}]string{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
- var interfaceMapInterface = map[interface{}]interface{}{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
-
- // ToStringMapStringSlice inputs/outputs
- var stringMapStringSlice = map[string][]string{"key 1": {"value 1", "value 2", "value 3"}, "key 2": {"value 1", "value 2", "value 3"}, "key 3": {"value 1", "value 2", "value 3"}}
- var stringMapInterfaceSlice = map[string][]interface{}{"key 1": {"value 1", "value 2", "value 3"}, "key 2": {"value 1", "value 2", "value 3"}, "key 3": {"value 1", "value 2", "value 3"}}
- var stringMapInterfaceInterfaceSlice = map[string]interface{}{"key 1": []interface{}{"value 1", "value 2", "value 3"}, "key 2": []interface{}{"value 1", "value 2", "value 3"}, "key 3": []interface{}{"value 1", "value 2", "value 3"}}
- var stringMapStringSingleSliceFieldsResult = map[string][]string{"key 1": {"value", "1"}, "key 2": {"value", "2"}, "key 3": {"value", "3"}}
- var interfaceMapStringSlice = map[interface{}][]string{"key 1": {"value 1", "value 2", "value 3"}, "key 2": {"value 1", "value 2", "value 3"}, "key 3": {"value 1", "value 2", "value 3"}}
- var interfaceMapInterfaceSlice = map[interface{}][]interface{}{"key 1": {"value 1", "value 2", "value 3"}, "key 2": {"value 1", "value 2", "value 3"}, "key 3": {"value 1", "value 2", "value 3"}}
-
- var stringMapStringSliceMultiple = map[string][]string{"key 1": {"value 1", "value 2", "value 3"}, "key 2": {"value 1", "value 2", "value 3"}, "key 3": {"value 1", "value 2", "value 3"}}
- var stringMapStringSliceSingle = map[string][]string{"key 1": {"value 1"}, "key 2": {"value 2"}, "key 3": {"value 3"}}
-
- var stringMapInterface1 = map[string]interface{}{"key 1": []string{"value 1"}, "key 2": []string{"value 2"}}
- var stringMapInterfaceResult1 = map[string][]string{"key 1": {"value 1"}, "key 2": {"value 2"}}
-
- type Key struct {
- k string
- }
-
- tests := []struct {
- input interface{}
- expect map[string][]string
- iserr bool
- }{
- {stringMapStringSlice, stringMapStringSlice, false},
- {stringMapInterfaceSlice, stringMapStringSlice, false},
- {stringMapInterfaceInterfaceSlice, stringMapStringSlice, false},
- {stringMapStringSliceMultiple, stringMapStringSlice, false},
- {stringMapStringSliceMultiple, stringMapStringSlice, false},
- {stringMapString, stringMapStringSliceSingle, false},
- {stringMapInterface, stringMapStringSliceSingle, false},
- {stringMapInterface1, stringMapInterfaceResult1, false},
- {interfaceMapStringSlice, stringMapStringSlice, false},
- {interfaceMapInterfaceSlice, stringMapStringSlice, false},
- {interfaceMapString, stringMapStringSingleSliceFieldsResult, false},
- {interfaceMapInterface, stringMapStringSingleSliceFieldsResult, false},
- // errors
- {nil, nil, true},
- {testing.T{}, nil, true},
- {map[interface{}]interface{}{"foo": testing.T{}}, nil, true},
- {map[interface{}]interface{}{Key{"foo"}: "bar"}, nil, true}, // ToStringE(Key{"foo"}) should fail
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToStringMapStringSliceE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToStringMapStringSlice(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToStringMapE(t *testing.T) {
- tests := []struct {
- input interface{}
- expect map[string]interface{}
- iserr bool
- }{
- {map[interface{}]interface{}{"tag": "tags", "group": "groups"}, map[string]interface{}{"tag": "tags", "group": "groups"}, false},
- {map[string]interface{}{"tag": "tags", "group": "groups"}, map[string]interface{}{"tag": "tags", "group": "groups"}, false},
- // errors
- {nil, nil, true},
- {testing.T{}, nil, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToStringMapE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToStringMap(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToStringMapBoolE(t *testing.T) {
- tests := []struct {
- input interface{}
- expect map[string]bool
- iserr bool
- }{
- {map[interface{}]interface{}{"v1": true, "v2": false}, map[string]bool{"v1": true, "v2": false}, false},
- {map[string]interface{}{"v1": true, "v2": false}, map[string]bool{"v1": true, "v2": false}, false},
- {map[string]bool{"v1": true, "v2": false}, map[string]bool{"v1": true, "v2": false}, false},
- // errors
- {nil, nil, true},
- {testing.T{}, nil, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToStringMapBoolE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToStringMapBool(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToStringMapStringE(t *testing.T) {
- var stringMapString = map[string]string{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
- var stringMapInterface = map[string]interface{}{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
- var interfaceMapString = map[interface{}]string{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
- var interfaceMapInterface = map[interface{}]interface{}{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
-
- tests := []struct {
- input interface{}
- expect map[string]string
- iserr bool
- }{
- {stringMapString, stringMapString, false},
- {stringMapInterface, stringMapString, false},
- {interfaceMapString, stringMapString, false},
- {interfaceMapInterface, stringMapString, false},
- // errors
- {nil, nil, true},
- {testing.T{}, nil, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToStringMapStringE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToStringMapString(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToBoolSliceE(t *testing.T) {
- tests := []struct {
- input interface{}
- expect []bool
- iserr bool
- }{
- {[]bool{true, false, true}, []bool{true, false, true}, false},
- {[]interface{}{true, false, true}, []bool{true, false, true}, false},
- {[]int{1, 0, 1}, []bool{true, false, true}, false},
- {[]string{"true", "false", "true"}, []bool{true, false, true}, false},
- // errors
- {nil, nil, true},
- {testing.T{}, nil, true},
- {[]string{"foo", "bar"}, nil, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToBoolSliceE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToBoolSlice(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToIntSliceE(t *testing.T) {
- tests := []struct {
- input interface{}
- expect []int
- iserr bool
- }{
- {[]int{1, 3}, []int{1, 3}, false},
- {[]interface{}{1.2, 3.2}, []int{1, 3}, false},
- {[]string{"2", "3"}, []int{2, 3}, false},
- {[2]string{"2", "3"}, []int{2, 3}, false},
- // errors
- {nil, nil, true},
- {testing.T{}, nil, true},
- {[]string{"foo", "bar"}, nil, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToIntSliceE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToIntSlice(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToSliceE(t *testing.T) {
- tests := []struct {
- input interface{}
- expect []interface{}
- iserr bool
- }{
- {[]interface{}{1, 3}, []interface{}{1, 3}, false},
- {[]map[string]interface{}{{"k1": 1}, {"k2": 2}}, []interface{}{map[string]interface{}{"k1": 1}, map[string]interface{}{"k2": 2}}, false},
- // errors
- {nil, nil, true},
- {testing.T{}, nil, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToSliceE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToSlice(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToStringSliceE(t *testing.T) {
- tests := []struct {
- input interface{}
- expect []string
- iserr bool
- }{
- {[]string{"a", "b"}, []string{"a", "b"}, false},
- {[]interface{}{1, 3}, []string{"1", "3"}, false},
- {interface{}(1), []string{"1"}, false},
- // errors
- {nil, nil, true},
- {testing.T{}, nil, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToStringSliceE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToStringSlice(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToDurationSliceE(t *testing.T) {
- tests := []struct {
- input interface{}
- expect []time.Duration
- iserr bool
- }{
- {[]string{"1s", "1m"}, []time.Duration{time.Second, time.Minute}, false},
- {[]int{1, 2}, []time.Duration{1, 2}, false},
- {[]interface{}{1, 3}, []time.Duration{1, 3}, false},
- // errors
- {nil, nil, true},
- {testing.T{}, nil, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToDurationSliceE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToDurationSlice(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToBoolE(t *testing.T) {
- tests := []struct {
- input interface{}
- expect bool
- iserr bool
- }{
- {0, false, false},
- {nil, false, false},
- {"false", false, false},
- {"FALSE", false, false},
- {"False", false, false},
- {"f", false, false},
- {"F", false, false},
- {false, false, false},
-
- {"true", true, false},
- {"TRUE", true, false},
- {"True", true, false},
- {"t", true, false},
- {"T", true, false},
- {1, true, false},
- {true, true, false},
- {-1, true, false},
-
- // errors
- {"test", false, true},
- {testing.T{}, false, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToBoolE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToBool(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func BenchmarkTooBool(b *testing.B) {
- for i := 0; i < b.N; i++ {
- if !ToBool(true) {
- b.Fatal("ToBool returned false")
- }
- }
-}
-
-func TestIndirectPointers(t *testing.T) {
- x := 13
- y := &x
- z := &y
-
- assert.Equal(t, ToInt(y), 13)
- assert.Equal(t, ToInt(z), 13)
-}
-
-func TestToTimeEE(t *testing.T) {
- tests := []struct {
- input interface{}
- expect time.Time
- iserr bool
- }{
- {"2009-11-10 23:00:00 +0000 UTC", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // Time.String()
- {"Tue Nov 10 23:00:00 2009", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // ANSIC
- {"Tue Nov 10 23:00:00 UTC 2009", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // UnixDate
- {"Tue Nov 10 23:00:00 +0000 2009", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // RubyDate
- {"10 Nov 09 23:00 UTC", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // RFC822
- {"10 Nov 09 23:00 +0000", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // RFC822Z
- {"Tuesday, 10-Nov-09 23:00:00 UTC", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // RFC850
- {"Tue, 10 Nov 2009 23:00:00 UTC", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // RFC1123
- {"Tue, 10 Nov 2009 23:00:00 +0000", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // RFC1123Z
- {"2009-11-10T23:00:00Z", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // RFC3339
- {"2009-11-10T23:00:00Z", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // RFC3339Nano
- {"11:00PM", time.Date(0, 1, 1, 23, 0, 0, 0, time.UTC), false}, // Kitchen
- {"Nov 10 23:00:00", time.Date(0, 11, 10, 23, 0, 0, 0, time.UTC), false}, // Stamp
- {"Nov 10 23:00:00.000", time.Date(0, 11, 10, 23, 0, 0, 0, time.UTC), false}, // StampMilli
- {"Nov 10 23:00:00.000000", time.Date(0, 11, 10, 23, 0, 0, 0, time.UTC), false}, // StampMicro
- {"Nov 10 23:00:00.000000000", time.Date(0, 11, 10, 23, 0, 0, 0, time.UTC), false}, // StampNano
- {"2016-03-06 15:28:01-00:00", time.Date(2016, 3, 6, 15, 28, 1, 0, time.UTC), false}, // RFC3339 without T
- {"2016-03-06 15:28:01", time.Date(2016, 3, 6, 15, 28, 1, 0, time.UTC), false},
- {"2016-03-06 15:28:01 -0000", time.Date(2016, 3, 6, 15, 28, 1, 0, time.UTC), false},
- {"2016-03-06 15:28:01 -00:00", time.Date(2016, 3, 6, 15, 28, 1, 0, time.UTC), false},
- {"2006-01-02", time.Date(2006, 1, 2, 0, 0, 0, 0, time.UTC), false},
- {"02 Jan 2006", time.Date(2006, 1, 2, 0, 0, 0, 0, time.UTC), false},
- {1472574600, time.Date(2016, 8, 30, 16, 30, 0, 0, time.UTC), false},
- {int(1482597504), time.Date(2016, 12, 24, 16, 38, 24, 0, time.UTC), false},
- {int64(1234567890), time.Date(2009, 2, 13, 23, 31, 30, 0, time.UTC), false},
- {int32(1234567890), time.Date(2009, 2, 13, 23, 31, 30, 0, time.UTC), false},
- {uint(1482597504), time.Date(2016, 12, 24, 16, 38, 24, 0, time.UTC), false},
- {uint64(1234567890), time.Date(2009, 2, 13, 23, 31, 30, 0, time.UTC), false},
- {uint32(1234567890), time.Date(2009, 2, 13, 23, 31, 30, 0, time.UTC), false},
- {time.Date(2009, 2, 13, 23, 31, 30, 0, time.UTC), time.Date(2009, 2, 13, 23, 31, 30, 0, time.UTC), false},
- // errors
- {"2006", time.Time{}, true},
- {testing.T{}, time.Time{}, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToTimeE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v.UTC(), errmsg)
-
- // Non-E test
- v = ToTime(test.input)
- assert.Equal(t, test.expect, v.UTC(), errmsg)
- }
-}
-
-func TestToDurationE(t *testing.T) {
- var td time.Duration = 5
-
- tests := []struct {
- input interface{}
- expect time.Duration
- iserr bool
- }{
- {time.Duration(5), td, false},
- {int(5), td, false},
- {int64(5), td, false},
- {int32(5), td, false},
- {int16(5), td, false},
- {int8(5), td, false},
- {uint(5), td, false},
- {uint64(5), td, false},
- {uint32(5), td, false},
- {uint16(5), td, false},
- {uint8(5), td, false},
- {float64(5), td, false},
- {float32(5), td, false},
- {string("5"), td, false},
- {string("5ns"), td, false},
- {string("5us"), time.Microsecond * td, false},
- {string("5µs"), time.Microsecond * td, false},
- {string("5ms"), time.Millisecond * td, false},
- {string("5s"), time.Second * td, false},
- {string("5m"), time.Minute * td, false},
- {string("5h"), time.Hour * td, false},
- // errors
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToDurationE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToDuration(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
diff --git a/vendor/github.com/spf13/cast/caste.go b/vendor/github.com/spf13/cast/caste.go
deleted file mode 100644
index 81511fe..0000000
--- a/vendor/github.com/spf13/cast/caste.go
+++ /dev/null
@@ -1,1146 +0,0 @@
-// Copyright © 2014 Steve Francia .
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-package cast
-
-import (
- "errors"
- "fmt"
- "html/template"
- "reflect"
- "strconv"
- "strings"
- "time"
-)
-
-var errNegativeNotAllowed = errors.New("unable to cast negative value")
-
-// ToTimeE casts an interface to a time.Time type.
-func ToTimeE(i interface{}) (tim time.Time, err error) {
- i = indirect(i)
-
- switch v := i.(type) {
- case time.Time:
- return v, nil
- case string:
- return StringToDate(v)
- case int:
- return time.Unix(int64(v), 0), nil
- case int64:
- return time.Unix(v, 0), nil
- case int32:
- return time.Unix(int64(v), 0), nil
- case uint:
- return time.Unix(int64(v), 0), nil
- case uint64:
- return time.Unix(int64(v), 0), nil
- case uint32:
- return time.Unix(int64(v), 0), nil
- default:
- return time.Time{}, fmt.Errorf("unable to cast %#v of type %T to Time", i, i)
- }
-}
-
-// ToDurationE casts an interface to a time.Duration type.
-func ToDurationE(i interface{}) (d time.Duration, err error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case time.Duration:
- return s, nil
- case int, int64, int32, int16, int8, uint, uint64, uint32, uint16, uint8:
- d = time.Duration(ToInt64(s))
- return
- case float32, float64:
- d = time.Duration(ToFloat64(s))
- return
- case string:
- if strings.ContainsAny(s, "nsuµmh") {
- d, err = time.ParseDuration(s)
- } else {
- d, err = time.ParseDuration(s + "ns")
- }
- return
- default:
- err = fmt.Errorf("unable to cast %#v of type %T to Duration", i, i)
- return
- }
-}
-
-// ToBoolE casts an interface to a bool type.
-func ToBoolE(i interface{}) (bool, error) {
- i = indirect(i)
-
- switch b := i.(type) {
- case bool:
- return b, nil
- case nil:
- return false, nil
- case int:
- if i.(int) != 0 {
- return true, nil
- }
- return false, nil
- case string:
- return strconv.ParseBool(i.(string))
- default:
- return false, fmt.Errorf("unable to cast %#v of type %T to bool", i, i)
- }
-}
-
-// ToFloat64E casts an interface to a float64 type.
-func ToFloat64E(i interface{}) (float64, error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case float64:
- return s, nil
- case float32:
- return float64(s), nil
- case int:
- return float64(s), nil
- case int64:
- return float64(s), nil
- case int32:
- return float64(s), nil
- case int16:
- return float64(s), nil
- case int8:
- return float64(s), nil
- case uint:
- return float64(s), nil
- case uint64:
- return float64(s), nil
- case uint32:
- return float64(s), nil
- case uint16:
- return float64(s), nil
- case uint8:
- return float64(s), nil
- case string:
- v, err := strconv.ParseFloat(s, 64)
- if err == nil {
- return v, nil
- }
- return 0, fmt.Errorf("unable to cast %#v of type %T to float64", i, i)
- case bool:
- if s {
- return 1, nil
- }
- return 0, nil
- default:
- return 0, fmt.Errorf("unable to cast %#v of type %T to float64", i, i)
- }
-}
-
-// ToFloat32E casts an interface to a float32 type.
-func ToFloat32E(i interface{}) (float32, error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case float64:
- return float32(s), nil
- case float32:
- return s, nil
- case int:
- return float32(s), nil
- case int64:
- return float32(s), nil
- case int32:
- return float32(s), nil
- case int16:
- return float32(s), nil
- case int8:
- return float32(s), nil
- case uint:
- return float32(s), nil
- case uint64:
- return float32(s), nil
- case uint32:
- return float32(s), nil
- case uint16:
- return float32(s), nil
- case uint8:
- return float32(s), nil
- case string:
- v, err := strconv.ParseFloat(s, 32)
- if err == nil {
- return float32(v), nil
- }
- return 0, fmt.Errorf("unable to cast %#v of type %T to float32", i, i)
- case bool:
- if s {
- return 1, nil
- }
- return 0, nil
- default:
- return 0, fmt.Errorf("unable to cast %#v of type %T to float32", i, i)
- }
-}
-
-// ToInt64E casts an interface to an int64 type.
-func ToInt64E(i interface{}) (int64, error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case int:
- return int64(s), nil
- case int64:
- return s, nil
- case int32:
- return int64(s), nil
- case int16:
- return int64(s), nil
- case int8:
- return int64(s), nil
- case uint:
- return int64(s), nil
- case uint64:
- return int64(s), nil
- case uint32:
- return int64(s), nil
- case uint16:
- return int64(s), nil
- case uint8:
- return int64(s), nil
- case float64:
- return int64(s), nil
- case float32:
- return int64(s), nil
- case string:
- v, err := strconv.ParseInt(s, 0, 0)
- if err == nil {
- return v, nil
- }
- return 0, fmt.Errorf("unable to cast %#v of type %T to int64", i, i)
- case bool:
- if s {
- return 1, nil
- }
- return 0, nil
- case nil:
- return 0, nil
- default:
- return 0, fmt.Errorf("unable to cast %#v of type %T to int64", i, i)
- }
-}
-
-// ToInt32E casts an interface to an int32 type.
-func ToInt32E(i interface{}) (int32, error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case int:
- return int32(s), nil
- case int64:
- return int32(s), nil
- case int32:
- return s, nil
- case int16:
- return int32(s), nil
- case int8:
- return int32(s), nil
- case uint:
- return int32(s), nil
- case uint64:
- return int32(s), nil
- case uint32:
- return int32(s), nil
- case uint16:
- return int32(s), nil
- case uint8:
- return int32(s), nil
- case float64:
- return int32(s), nil
- case float32:
- return int32(s), nil
- case string:
- v, err := strconv.ParseInt(s, 0, 0)
- if err == nil {
- return int32(v), nil
- }
- return 0, fmt.Errorf("unable to cast %#v of type %T to int32", i, i)
- case bool:
- if s {
- return 1, nil
- }
- return 0, nil
- case nil:
- return 0, nil
- default:
- return 0, fmt.Errorf("unable to cast %#v of type %T to int32", i, i)
- }
-}
-
-// ToInt16E casts an interface to an int16 type.
-func ToInt16E(i interface{}) (int16, error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case int:
- return int16(s), nil
- case int64:
- return int16(s), nil
- case int32:
- return int16(s), nil
- case int16:
- return s, nil
- case int8:
- return int16(s), nil
- case uint:
- return int16(s), nil
- case uint64:
- return int16(s), nil
- case uint32:
- return int16(s), nil
- case uint16:
- return int16(s), nil
- case uint8:
- return int16(s), nil
- case float64:
- return int16(s), nil
- case float32:
- return int16(s), nil
- case string:
- v, err := strconv.ParseInt(s, 0, 0)
- if err == nil {
- return int16(v), nil
- }
- return 0, fmt.Errorf("unable to cast %#v of type %T to int16", i, i)
- case bool:
- if s {
- return 1, nil
- }
- return 0, nil
- case nil:
- return 0, nil
- default:
- return 0, fmt.Errorf("unable to cast %#v of type %T to int16", i, i)
- }
-}
-
-// ToInt8E casts an interface to an int8 type.
-func ToInt8E(i interface{}) (int8, error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case int:
- return int8(s), nil
- case int64:
- return int8(s), nil
- case int32:
- return int8(s), nil
- case int16:
- return int8(s), nil
- case int8:
- return s, nil
- case uint:
- return int8(s), nil
- case uint64:
- return int8(s), nil
- case uint32:
- return int8(s), nil
- case uint16:
- return int8(s), nil
- case uint8:
- return int8(s), nil
- case float64:
- return int8(s), nil
- case float32:
- return int8(s), nil
- case string:
- v, err := strconv.ParseInt(s, 0, 0)
- if err == nil {
- return int8(v), nil
- }
- return 0, fmt.Errorf("unable to cast %#v of type %T to int8", i, i)
- case bool:
- if s {
- return 1, nil
- }
- return 0, nil
- case nil:
- return 0, nil
- default:
- return 0, fmt.Errorf("unable to cast %#v of type %T to int8", i, i)
- }
-}
-
-// ToIntE casts an interface to an int type.
-func ToIntE(i interface{}) (int, error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case int:
- return s, nil
- case int64:
- return int(s), nil
- case int32:
- return int(s), nil
- case int16:
- return int(s), nil
- case int8:
- return int(s), nil
- case uint:
- return int(s), nil
- case uint64:
- return int(s), nil
- case uint32:
- return int(s), nil
- case uint16:
- return int(s), nil
- case uint8:
- return int(s), nil
- case float64:
- return int(s), nil
- case float32:
- return int(s), nil
- case string:
- v, err := strconv.ParseInt(s, 0, 0)
- if err == nil {
- return int(v), nil
- }
- return 0, fmt.Errorf("unable to cast %#v of type %T to int", i, i)
- case bool:
- if s {
- return 1, nil
- }
- return 0, nil
- case nil:
- return 0, nil
- default:
- return 0, fmt.Errorf("unable to cast %#v of type %T to int", i, i)
- }
-}
-
-// ToUintE casts an interface to a uint type.
-func ToUintE(i interface{}) (uint, error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case string:
- v, err := strconv.ParseUint(s, 0, 0)
- if err == nil {
- return uint(v), nil
- }
- return 0, fmt.Errorf("unable to cast %#v to uint: %s", i, err)
- case int:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint(s), nil
- case int64:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint(s), nil
- case int32:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint(s), nil
- case int16:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint(s), nil
- case int8:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint(s), nil
- case uint:
- return s, nil
- case uint64:
- return uint(s), nil
- case uint32:
- return uint(s), nil
- case uint16:
- return uint(s), nil
- case uint8:
- return uint(s), nil
- case float64:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint(s), nil
- case float32:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint(s), nil
- case bool:
- if s {
- return 1, nil
- }
- return 0, nil
- case nil:
- return 0, nil
- default:
- return 0, fmt.Errorf("unable to cast %#v of type %T to uint", i, i)
- }
-}
-
-// ToUint64E casts an interface to a uint64 type.
-func ToUint64E(i interface{}) (uint64, error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case string:
- v, err := strconv.ParseUint(s, 0, 64)
- if err == nil {
- return v, nil
- }
- return 0, fmt.Errorf("unable to cast %#v to uint64: %s", i, err)
- case int:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint64(s), nil
- case int64:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint64(s), nil
- case int32:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint64(s), nil
- case int16:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint64(s), nil
- case int8:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint64(s), nil
- case uint:
- return uint64(s), nil
- case uint64:
- return s, nil
- case uint32:
- return uint64(s), nil
- case uint16:
- return uint64(s), nil
- case uint8:
- return uint64(s), nil
- case float32:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint64(s), nil
- case float64:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint64(s), nil
- case bool:
- if s {
- return 1, nil
- }
- return 0, nil
- case nil:
- return 0, nil
- default:
- return 0, fmt.Errorf("unable to cast %#v of type %T to uint64", i, i)
- }
-}
-
-// ToUint32E casts an interface to a uint32 type.
-func ToUint32E(i interface{}) (uint32, error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case string:
- v, err := strconv.ParseUint(s, 0, 32)
- if err == nil {
- return uint32(v), nil
- }
- return 0, fmt.Errorf("unable to cast %#v to uint32: %s", i, err)
- case int:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint32(s), nil
- case int64:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint32(s), nil
- case int32:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint32(s), nil
- case int16:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint32(s), nil
- case int8:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint32(s), nil
- case uint:
- return uint32(s), nil
- case uint64:
- return uint32(s), nil
- case uint32:
- return s, nil
- case uint16:
- return uint32(s), nil
- case uint8:
- return uint32(s), nil
- case float64:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint32(s), nil
- case float32:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint32(s), nil
- case bool:
- if s {
- return 1, nil
- }
- return 0, nil
- case nil:
- return 0, nil
- default:
- return 0, fmt.Errorf("unable to cast %#v of type %T to uint32", i, i)
- }
-}
-
-// ToUint16E casts an interface to a uint16 type.
-func ToUint16E(i interface{}) (uint16, error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case string:
- v, err := strconv.ParseUint(s, 0, 16)
- if err == nil {
- return uint16(v), nil
- }
- return 0, fmt.Errorf("unable to cast %#v to uint16: %s", i, err)
- case int:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint16(s), nil
- case int64:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint16(s), nil
- case int32:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint16(s), nil
- case int16:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint16(s), nil
- case int8:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint16(s), nil
- case uint:
- return uint16(s), nil
- case uint64:
- return uint16(s), nil
- case uint32:
- return uint16(s), nil
- case uint16:
- return s, nil
- case uint8:
- return uint16(s), nil
- case float64:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint16(s), nil
- case float32:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint16(s), nil
- case bool:
- if s {
- return 1, nil
- }
- return 0, nil
- case nil:
- return 0, nil
- default:
- return 0, fmt.Errorf("unable to cast %#v of type %T to uint16", i, i)
- }
-}
-
-// ToUint8E casts an interface to a uint type.
-func ToUint8E(i interface{}) (uint8, error) {
- i = indirect(i)
-
- switch s := i.(type) {
- case string:
- v, err := strconv.ParseUint(s, 0, 8)
- if err == nil {
- return uint8(v), nil
- }
- return 0, fmt.Errorf("unable to cast %#v to uint8: %s", i, err)
- case int:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint8(s), nil
- case int64:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint8(s), nil
- case int32:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint8(s), nil
- case int16:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint8(s), nil
- case int8:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint8(s), nil
- case uint:
- return uint8(s), nil
- case uint64:
- return uint8(s), nil
- case uint32:
- return uint8(s), nil
- case uint16:
- return uint8(s), nil
- case uint8:
- return s, nil
- case float64:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint8(s), nil
- case float32:
- if s < 0 {
- return 0, errNegativeNotAllowed
- }
- return uint8(s), nil
- case bool:
- if s {
- return 1, nil
- }
- return 0, nil
- case nil:
- return 0, nil
- default:
- return 0, fmt.Errorf("unable to cast %#v of type %T to uint8", i, i)
- }
-}
-
-// From html/template/content.go
-// Copyright 2011 The Go Authors. All rights reserved.
-// indirect returns the value, after dereferencing as many times
-// as necessary to reach the base type (or nil).
-func indirect(a interface{}) interface{} {
- if a == nil {
- return nil
- }
- if t := reflect.TypeOf(a); t.Kind() != reflect.Ptr {
- // Avoid creating a reflect.Value if it's not a pointer.
- return a
- }
- v := reflect.ValueOf(a)
- for v.Kind() == reflect.Ptr && !v.IsNil() {
- v = v.Elem()
- }
- return v.Interface()
-}
-
-// From html/template/content.go
-// Copyright 2011 The Go Authors. All rights reserved.
-// indirectToStringerOrError returns the value, after dereferencing as many times
-// as necessary to reach the base type (or nil) or an implementation of fmt.Stringer
-// or error,
-func indirectToStringerOrError(a interface{}) interface{} {
- if a == nil {
- return nil
- }
-
- var errorType = reflect.TypeOf((*error)(nil)).Elem()
- var fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
-
- v := reflect.ValueOf(a)
- for !v.Type().Implements(fmtStringerType) && !v.Type().Implements(errorType) && v.Kind() == reflect.Ptr && !v.IsNil() {
- v = v.Elem()
- }
- return v.Interface()
-}
-
-// ToStringE casts an interface to a string type.
-func ToStringE(i interface{}) (string, error) {
- i = indirectToStringerOrError(i)
-
- switch s := i.(type) {
- case string:
- return s, nil
- case bool:
- return strconv.FormatBool(s), nil
- case float64:
- return strconv.FormatFloat(s, 'f', -1, 64), nil
- case float32:
- return strconv.FormatFloat(float64(s), 'f', -1, 32), nil
- case int:
- return strconv.Itoa(s), nil
- case int64:
- return strconv.FormatInt(s, 10), nil
- case int32:
- return strconv.Itoa(int(s)), nil
- case int16:
- return strconv.FormatInt(int64(s), 10), nil
- case int8:
- return strconv.FormatInt(int64(s), 10), nil
- case uint:
- return strconv.FormatInt(int64(s), 10), nil
- case uint64:
- return strconv.FormatInt(int64(s), 10), nil
- case uint32:
- return strconv.FormatInt(int64(s), 10), nil
- case uint16:
- return strconv.FormatInt(int64(s), 10), nil
- case uint8:
- return strconv.FormatInt(int64(s), 10), nil
- case []byte:
- return string(s), nil
- case template.HTML:
- return string(s), nil
- case template.URL:
- return string(s), nil
- case template.JS:
- return string(s), nil
- case template.CSS:
- return string(s), nil
- case template.HTMLAttr:
- return string(s), nil
- case nil:
- return "", nil
- case fmt.Stringer:
- return s.String(), nil
- case error:
- return s.Error(), nil
- default:
- return "", fmt.Errorf("unable to cast %#v of type %T to string", i, i)
- }
-}
-
-// ToStringMapStringE casts an interface to a map[string]string type.
-func ToStringMapStringE(i interface{}) (map[string]string, error) {
- var m = map[string]string{}
-
- switch v := i.(type) {
- case map[string]string:
- return v, nil
- case map[string]interface{}:
- for k, val := range v {
- m[ToString(k)] = ToString(val)
- }
- return m, nil
- case map[interface{}]string:
- for k, val := range v {
- m[ToString(k)] = ToString(val)
- }
- return m, nil
- case map[interface{}]interface{}:
- for k, val := range v {
- m[ToString(k)] = ToString(val)
- }
- return m, nil
- default:
- return m, fmt.Errorf("unable to cast %#v of type %T to map[string]string", i, i)
- }
-}
-
-// ToStringMapStringSliceE casts an interface to a map[string][]string type.
-func ToStringMapStringSliceE(i interface{}) (map[string][]string, error) {
- var m = map[string][]string{}
-
- switch v := i.(type) {
- case map[string][]string:
- return v, nil
- case map[string][]interface{}:
- for k, val := range v {
- m[ToString(k)] = ToStringSlice(val)
- }
- return m, nil
- case map[string]string:
- for k, val := range v {
- m[ToString(k)] = []string{val}
- }
- case map[string]interface{}:
- for k, val := range v {
- switch vt := val.(type) {
- case []interface{}:
- m[ToString(k)] = ToStringSlice(vt)
- case []string:
- m[ToString(k)] = vt
- default:
- m[ToString(k)] = []string{ToString(val)}
- }
- }
- return m, nil
- case map[interface{}][]string:
- for k, val := range v {
- m[ToString(k)] = ToStringSlice(val)
- }
- return m, nil
- case map[interface{}]string:
- for k, val := range v {
- m[ToString(k)] = ToStringSlice(val)
- }
- return m, nil
- case map[interface{}][]interface{}:
- for k, val := range v {
- m[ToString(k)] = ToStringSlice(val)
- }
- return m, nil
- case map[interface{}]interface{}:
- for k, val := range v {
- key, err := ToStringE(k)
- if err != nil {
- return m, fmt.Errorf("unable to cast %#v of type %T to map[string][]string", i, i)
- }
- value, err := ToStringSliceE(val)
- if err != nil {
- return m, fmt.Errorf("unable to cast %#v of type %T to map[string][]string", i, i)
- }
- m[key] = value
- }
- default:
- return m, fmt.Errorf("unable to cast %#v of type %T to map[string][]string", i, i)
- }
- return m, nil
-}
-
-// ToStringMapBoolE casts an interface to a map[string]bool type.
-func ToStringMapBoolE(i interface{}) (map[string]bool, error) {
- var m = map[string]bool{}
-
- switch v := i.(type) {
- case map[interface{}]interface{}:
- for k, val := range v {
- m[ToString(k)] = ToBool(val)
- }
- return m, nil
- case map[string]interface{}:
- for k, val := range v {
- m[ToString(k)] = ToBool(val)
- }
- return m, nil
- case map[string]bool:
- return v, nil
- default:
- return m, fmt.Errorf("unable to cast %#v of type %T to map[string]bool", i, i)
- }
-}
-
-// ToStringMapE casts an interface to a map[string]interface{} type.
-func ToStringMapE(i interface{}) (map[string]interface{}, error) {
- var m = map[string]interface{}{}
-
- switch v := i.(type) {
- case map[interface{}]interface{}:
- for k, val := range v {
- m[ToString(k)] = val
- }
- return m, nil
- case map[string]interface{}:
- return v, nil
- default:
- return m, fmt.Errorf("unable to cast %#v of type %T to map[string]interface{}", i, i)
- }
-}
-
-// ToSliceE casts an interface to a []interface{} type.
-func ToSliceE(i interface{}) ([]interface{}, error) {
- var s []interface{}
-
- switch v := i.(type) {
- case []interface{}:
- return append(s, v...), nil
- case []map[string]interface{}:
- for _, u := range v {
- s = append(s, u)
- }
- return s, nil
- default:
- return s, fmt.Errorf("unable to cast %#v of type %T to []interface{}", i, i)
- }
-}
-
-// ToBoolSliceE casts an interface to a []bool type.
-func ToBoolSliceE(i interface{}) ([]bool, error) {
- if i == nil {
- return []bool{}, fmt.Errorf("unable to cast %#v of type %T to []bool", i, i)
- }
-
- switch v := i.(type) {
- case []bool:
- return v, nil
- }
-
- kind := reflect.TypeOf(i).Kind()
- switch kind {
- case reflect.Slice, reflect.Array:
- s := reflect.ValueOf(i)
- a := make([]bool, s.Len())
- for j := 0; j < s.Len(); j++ {
- val, err := ToBoolE(s.Index(j).Interface())
- if err != nil {
- return []bool{}, fmt.Errorf("unable to cast %#v of type %T to []bool", i, i)
- }
- a[j] = val
- }
- return a, nil
- default:
- return []bool{}, fmt.Errorf("unable to cast %#v of type %T to []bool", i, i)
- }
-}
-
-// ToStringSliceE casts an interface to a []string type.
-func ToStringSliceE(i interface{}) ([]string, error) {
- var a []string
-
- switch v := i.(type) {
- case []interface{}:
- for _, u := range v {
- a = append(a, ToString(u))
- }
- return a, nil
- case []string:
- return v, nil
- case string:
- return strings.Fields(v), nil
- case interface{}:
- str, err := ToStringE(v)
- if err != nil {
- return a, fmt.Errorf("unable to cast %#v of type %T to []string", i, i)
- }
- return []string{str}, nil
- default:
- return a, fmt.Errorf("unable to cast %#v of type %T to []string", i, i)
- }
-}
-
-// ToIntSliceE casts an interface to a []int type.
-func ToIntSliceE(i interface{}) ([]int, error) {
- if i == nil {
- return []int{}, fmt.Errorf("unable to cast %#v of type %T to []int", i, i)
- }
-
- switch v := i.(type) {
- case []int:
- return v, nil
- }
-
- kind := reflect.TypeOf(i).Kind()
- switch kind {
- case reflect.Slice, reflect.Array:
- s := reflect.ValueOf(i)
- a := make([]int, s.Len())
- for j := 0; j < s.Len(); j++ {
- val, err := ToIntE(s.Index(j).Interface())
- if err != nil {
- return []int{}, fmt.Errorf("unable to cast %#v of type %T to []int", i, i)
- }
- a[j] = val
- }
- return a, nil
- default:
- return []int{}, fmt.Errorf("unable to cast %#v of type %T to []int", i, i)
- }
-}
-
-// ToDurationSliceE casts an interface to a []time.Duration type.
-func ToDurationSliceE(i interface{}) ([]time.Duration, error) {
- if i == nil {
- return []time.Duration{}, fmt.Errorf("unable to cast %#v of type %T to []time.Duration", i, i)
- }
-
- switch v := i.(type) {
- case []time.Duration:
- return v, nil
- }
-
- kind := reflect.TypeOf(i).Kind()
- switch kind {
- case reflect.Slice, reflect.Array:
- s := reflect.ValueOf(i)
- a := make([]time.Duration, s.Len())
- for j := 0; j < s.Len(); j++ {
- val, err := ToDurationE(s.Index(j).Interface())
- if err != nil {
- return []time.Duration{}, fmt.Errorf("unable to cast %#v of type %T to []time.Duration", i, i)
- }
- a[j] = val
- }
- return a, nil
- default:
- return []time.Duration{}, fmt.Errorf("unable to cast %#v of type %T to []time.Duration", i, i)
- }
-}
-
-// StringToDate attempts to parse a string into a time.Time type using a
-// predefined list of formats. If no suitable format is found, an error is
-// returned.
-func StringToDate(s string) (time.Time, error) {
- return parseDateWith(s, []string{
- time.RFC3339,
- "2006-01-02T15:04:05", // iso8601 without timezone
- time.RFC1123Z,
- time.RFC1123,
- time.RFC822Z,
- time.RFC822,
- time.RFC850,
- time.ANSIC,
- time.UnixDate,
- time.RubyDate,
- "2006-01-02 15:04:05.999999999 -0700 MST", // Time.String()
- "2006-01-02",
- "02 Jan 2006",
- "2006-01-02 15:04:05 -07:00",
- "2006-01-02 15:04:05 -0700",
- "2006-01-02 15:04:05Z07:00", // RFC3339 without T
- "2006-01-02 15:04:05",
- time.Kitchen,
- time.Stamp,
- time.StampMilli,
- time.StampMicro,
- time.StampNano,
- })
-}
-
-func parseDateWith(s string, dates []string) (d time.Time, e error) {
- for _, dateType := range dates {
- if d, e = time.Parse(dateType, s); e == nil {
- return
- }
- }
- return d, fmt.Errorf("unable to parse date: %s", s)
-}
diff --git a/vendor/github.com/spf13/cobra/.gitignore b/vendor/github.com/spf13/cobra/.gitignore
deleted file mode 100644
index 1b8c7c2..0000000
--- a/vendor/github.com/spf13/cobra/.gitignore
+++ /dev/null
@@ -1,36 +0,0 @@
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-# Vim files https://github.com/github/gitignore/blob/master/Global/Vim.gitignore
-# swap
-[._]*.s[a-w][a-z]
-[._]s[a-w][a-z]
-# session
-Session.vim
-# temporary
-.netrwhist
-*~
-# auto-generated tag files
-tags
-
-*.exe
-
-cobra.test
diff --git a/vendor/github.com/spf13/cobra/.mailmap b/vendor/github.com/spf13/cobra/.mailmap
deleted file mode 100644
index 94ec530..0000000
--- a/vendor/github.com/spf13/cobra/.mailmap
+++ /dev/null
@@ -1,3 +0,0 @@
-Steve Francia
-Bjørn Erik Pedersen
-Fabiano Franz
diff --git a/vendor/github.com/spf13/cobra/.travis.yml b/vendor/github.com/spf13/cobra/.travis.yml
deleted file mode 100644
index 68efa13..0000000
--- a/vendor/github.com/spf13/cobra/.travis.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-language: go
-
-matrix:
- include:
- - go: 1.7.6
- - go: 1.8.3
- - go: tip
- allow_failures:
- - go: tip
-
-before_install:
- - mkdir -p bin
- - curl -Lso bin/shellcheck https://github.com/caarlos0/shellcheck-docker/releases/download/v0.4.3/shellcheck
- - chmod +x bin/shellcheck
-script:
- - PATH=$PATH:$PWD/bin go test -v ./...
- - go build
- - diff -u <(echo -n) <(gofmt -d -s .)
- - if [ -z $NOVET ]; then
- diff -u <(echo -n) <(go tool vet . 2>&1 | grep -vE 'ExampleCommand|bash_completions.*Fprint');
- fi
diff --git a/vendor/github.com/spf13/cobra/LICENSE.txt b/vendor/github.com/spf13/cobra/LICENSE.txt
deleted file mode 100644
index 298f0e2..0000000
--- a/vendor/github.com/spf13/cobra/LICENSE.txt
+++ /dev/null
@@ -1,174 +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.
diff --git a/vendor/github.com/spf13/cobra/README.md b/vendor/github.com/spf13/cobra/README.md
deleted file mode 100644
index 373a056..0000000
--- a/vendor/github.com/spf13/cobra/README.md
+++ /dev/null
@@ -1,721 +0,0 @@
-
-
-Cobra is both a library for creating powerful modern CLI applications as well as a program to generate applications and command files.
-
-Many of the most widely used Go projects are built using Cobra including:
-
-* [Kubernetes](http://kubernetes.io/)
-* [Hugo](http://gohugo.io)
-* [rkt](https://github.com/coreos/rkt)
-* [etcd](https://github.com/coreos/etcd)
-* [Moby (former Docker)](https://github.com/moby/moby)
-* [Docker (distribution)](https://github.com/docker/distribution)
-* [OpenShift](https://www.openshift.com/)
-* [Delve](https://github.com/derekparker/delve)
-* [GopherJS](http://www.gopherjs.org/)
-* [CockroachDB](http://www.cockroachlabs.com/)
-* [Bleve](http://www.blevesearch.com/)
-* [ProjectAtomic (enterprise)](http://www.projectatomic.io/)
-* [GiantSwarm's swarm](https://github.com/giantswarm/cli)
-* [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack)
-* [rclone](http://rclone.org/)
-* [nehm](https://github.com/bogem/nehm)
-
-[](https://travis-ci.org/spf13/cobra)
-[](https://circleci.com/gh/spf13/cobra)
-[](https://godoc.org/github.com/spf13/cobra)
-
-# Table of Contents
-
-- [Overview](#overview)
-- [Concepts](#concepts)
- * [Commands](#commands)
- * [Flags](#flags)
-- [Installing](#installing)
-- [Getting Started](#getting-started)
- * [Using the Cobra Generator](#using-the-cobra-generator)
- * [Using the Cobra Library](#using-the-cobra-library)
- * [Working with Flags](#working-with-flags)
- * [Positional and Custom Arguments](#positional-and-custom-arguments)
- * [Example](#example)
- * [Help Command](#help-command)
- * [Usage Message](#usage-message)
- * [PreRun and PostRun Hooks](#prerun-and-postrun-hooks)
- * [Suggestions when "unknown command" happens](#suggestions-when-unknown-command-happens)
- * [Generating documentation for your command](#generating-documentation-for-your-command)
- * [Generating bash completions](#generating-bash-completions)
-- [Contributing](#contributing)
-- [License](#license)
-
-# Overview
-
-Cobra is a library providing a simple interface to create powerful modern CLI
-interfaces similar to git & go tools.
-
-Cobra is also an application that will generate your application scaffolding to rapidly
-develop a Cobra-based application.
-
-Cobra provides:
-* Easy subcommand-based CLIs: `app server`, `app fetch`, etc.
-* Fully POSIX-compliant flags (including short & long versions)
-* Nested subcommands
-* Global, local and cascading flags
-* Easy generation of applications & commands with `cobra init appname` & `cobra add cmdname`
-* Intelligent suggestions (`app srver`... did you mean `app server`?)
-* Automatic help generation for commands and flags
-* Automatic help flag recognition of `-h`, `--help`, etc.
-* Automatically generated bash autocomplete for your application
-* Automatically generated man pages for your application
-* Command aliases so you can change things without breaking them
-* The flexibility to define your own help, usage, etc.
-* Optional tight integration with [viper](http://github.com/spf13/viper) for 12-factor apps
-
-# Concepts
-
-Cobra is built on a structure of commands, arguments & flags.
-
-**Commands** represent actions, **Args** are things and **Flags** are modifiers for those actions.
-
-The best applications will read like sentences when used. Users will know how
-to use the application because they will natively understand how to use it.
-
-The pattern to follow is
-`APPNAME VERB NOUN --ADJECTIVE.`
- or
-`APPNAME COMMAND ARG --FLAG`
-
-A few good real world examples may better illustrate this point.
-
-In the following example, 'server' is a command, and 'port' is a flag:
-
- hugo server --port=1313
-
-In this command we are telling Git to clone the url bare.
-
- git clone URL --bare
-
-## Commands
-
-Command is the central point of the application. Each interaction that
-the application supports will be contained in a Command. A command can
-have children commands and optionally run an action.
-
-In the example above, 'server' is the command.
-
-[More about cobra.Command](https://godoc.org/github.com/spf13/cobra#Command)
-
-## Flags
-
-A flag is a way to modify the behavior of a command. Cobra supports
-fully POSIX-compliant flags as well as the Go [flag package](https://golang.org/pkg/flag/).
-A Cobra command can define flags that persist through to children commands
-and flags that are only available to that command.
-
-In the example above, 'port' is the flag.
-
-Flag functionality is provided by the [pflag
-library](https://github.com/spf13/pflag), a fork of the flag standard library
-which maintains the same interface while adding POSIX compliance.
-
-# Installing
-Using Cobra is easy. First, use `go get` to install the latest version
-of the library. This command will install the `cobra` generator executable
-along with the library and its dependencies:
-
- go get -u github.com/spf13/cobra/cobra
-
-Next, include Cobra in your application:
-
-```go
-import "github.com/spf13/cobra"
-```
-
-# Getting Started
-
-While you are welcome to provide your own organization, typically a Cobra-based
-application will follow the following organizational structure:
-
-```
- ▾ appName/
- ▾ cmd/
- add.go
- your.go
- commands.go
- here.go
- main.go
-```
-
-In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra.
-
-```go
-package main
-
-import (
- "fmt"
- "os"
-
- "{pathToYourApp}/cmd"
-)
-
-func main() {
- if err := cmd.RootCmd.Execute(); err != nil {
- fmt.Println(err)
- os.Exit(1)
- }
-}
-```
-
-## Using the Cobra Generator
-
-Cobra provides its own program that will create your application and add any
-commands you want. It's the easiest way to incorporate Cobra into your application.
-
-[Here](https://github.com/spf13/cobra/blob/master/cobra/README.md) you can find more information about it.
-
-## Using the Cobra Library
-
-To manually implement Cobra you need to create a bare main.go file and a RootCmd file.
-You will optionally provide additional commands as you see fit.
-
-### Create rootCmd
-
-Cobra doesn't require any special constructors. Simply create your commands.
-
-Ideally you place this in app/cmd/root.go:
-
-```go
-var RootCmd = &cobra.Command{
- Use: "hugo",
- Short: "Hugo is a very fast static site generator",
- Long: `A Fast and Flexible Static Site Generator built with
- love by spf13 and friends in Go.
- Complete documentation is available at http://hugo.spf13.com`,
- Run: func(cmd *cobra.Command, args []string) {
- // Do Stuff Here
- },
-}
-```
-
-You will additionally define flags and handle configuration in your init() function.
-
-For example cmd/root.go:
-
-```go
-import (
- "fmt"
- "os"
-
- homedir "github.com/mitchellh/go-homedir"
- "github.com/spf13/cobra"
- "github.com/spf13/viper"
-)
-
-func init() {
- cobra.OnInitialize(initConfig)
- RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
- RootCmd.PersistentFlags().StringVarP(&projectBase, "projectbase", "b", "", "base project directory eg. github.com/spf13/")
- RootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "Author name for copyright attribution")
- RootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "Name of license for the project (can provide `licensetext` in config)")
- RootCmd.PersistentFlags().Bool("viper", true, "Use Viper for configuration")
- viper.BindPFlag("author", RootCmd.PersistentFlags().Lookup("author"))
- viper.BindPFlag("projectbase", RootCmd.PersistentFlags().Lookup("projectbase"))
- viper.BindPFlag("useViper", RootCmd.PersistentFlags().Lookup("viper"))
- viper.SetDefault("author", "NAME HERE ")
- viper.SetDefault("license", "apache")
-}
-
-func Execute() {
- RootCmd.Execute()
-}
-
-func initConfig() {
- // Don't forget to read config either from cfgFile or from home directory!
- if cfgFile != "" {
- // Use config file from the flag.
- viper.SetConfigFile(cfgFile)
- } else {
- // Find home directory.
- home, err := homedir.Dir()
- if err != nil {
- fmt.Println(err)
- os.Exit(1)
- }
-
- // Search config in home directory with name ".cobra" (without extension).
- viper.AddConfigPath(home)
- viper.SetConfigName(".cobra")
- }
-
- if err := viper.ReadInConfig(); err != nil {
- fmt.Println("Can't read config:", err)
- os.Exit(1)
- }
-}
-```
-
-### Create your main.go
-
-With the root command you need to have your main function execute it.
-Execute should be run on the root for clarity, though it can be called on any command.
-
-In a Cobra app, typically the main.go file is very bare. It serves, one purpose, to initialize Cobra.
-
-```go
-package main
-
-import (
- "fmt"
- "os"
-
- "{pathToYourApp}/cmd"
-)
-
-func main() {
- if err := cmd.RootCmd.Execute(); err != nil {
- fmt.Println(err)
- os.Exit(1)
- }
-}
-```
-
-### Create additional commands
-
-Additional commands can be defined and typically are each given their own file
-inside of the cmd/ directory.
-
-If you wanted to create a version command you would create cmd/version.go and
-populate it with the following:
-
-```go
-package cmd
-
-import (
- "github.com/spf13/cobra"
- "fmt"
-)
-
-func init() {
- RootCmd.AddCommand(versionCmd)
-}
-
-var versionCmd = &cobra.Command{
- Use: "version",
- Short: "Print the version number of Hugo",
- Long: `All software has versions. This is Hugo's`,
- Run: func(cmd *cobra.Command, args []string) {
- fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")
- },
-}
-```
-
-## Working with Flags
-
-Flags provide modifiers to control how the action command operates.
-
-### Assign flags to a command
-
-Since the flags are defined and used in different locations, we need to
-define a variable outside with the correct scope to assign the flag to
-work with.
-
-```go
-var Verbose bool
-var Source string
-```
-
-There are two different approaches to assign a flag.
-
-### Persistent Flags
-
-A flag can be 'persistent' meaning that this flag will be available to the
-command it's assigned to as well as every command under that command. For
-global flags, assign a flag as a persistent flag on the root.
-
-```go
-RootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
-```
-
-### Local Flags
-
-A flag can also be assigned locally which will only apply to that specific command.
-
-```go
-RootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
-```
-
-### Local Flag on Parent Commands
-
-By default Cobra only parses local flags on the target command, any local flags on
-parent commands are ignored. By enabling `Command.TraverseChildren` Cobra will
-parse local flags on each command before executing the target command.
-
-```go
-command := cobra.Command{
- Use: "print [OPTIONS] [COMMANDS]",
- TraverseChildren: true,
-}
-```
-
-### Bind Flags with Config
-
-You can also bind your flags with [viper](https://github.com/spf13/viper):
-```go
-var author string
-
-func init() {
- RootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution")
- viper.BindPFlag("author", RootCmd.PersistentFlags().Lookup("author"))
-}
-```
-
-In this example the persistent flag `author` is bound with `viper`.
-**Note**, that the variable `author` will not be set to the value from config,
-when the `--author` flag is not provided by user.
-
-More in [viper documentation](https://github.com/spf13/viper#working-with-flags).
-
-## Positional and Custom Arguments
-
-Validation of positional arguments can be specified using the `Args` field
-of `Command`.
-
-The following validators are built in:
-
-- `NoArgs` - the command will report an error if there are any positional args.
-- `ArbitraryArgs` - the command will accept any args.
-- `OnlyValidArgs` - the command will report an error if there are any positional args that are not in the `ValidArgs` field of `Command`.
-- `MinimumNArgs(int)` - the command will report an error if there are not at least N positional args.
-- `MaximumNArgs(int)` - the command will report an error if there are more than N positional args.
-- `ExactArgs(int)` - the command will report an error if there are not exactly N positional args.
-- `RangeArgs(min, max)` - the command will report an error if the number of args is not between the minimum and maximum number of expected args.
-
-An example of setting the custom validator:
-
-```go
-var cmd = &cobra.Command{
- Short: "hello",
- Args: func(cmd *cobra.Command, args []string) error {
- if len(args) < 1 {
- return errors.New("requires at least one arg")
- }
- if myapp.IsValidColor(args[0]) {
- return nil
- }
- return fmt.Errorf("invalid color specified: %s", args[0])
- },
- Run: func(cmd *cobra.Command, args []string) {
- fmt.Println("Hello, World!")
- },
-}
-```
-
-## Example
-
-In the example below, we have defined three commands. Two are at the top level
-and one (cmdTimes) is a child of one of the top commands. In this case the root
-is not executable meaning that a subcommand is required. This is accomplished
-by not providing a 'Run' for the 'rootCmd'.
-
-We have only defined one flag for a single command.
-
-More documentation about flags is available at https://github.com/spf13/pflag
-
-```go
-package main
-
-import (
- "fmt"
- "strings"
-
- "github.com/spf13/cobra"
-)
-
-func main() {
- var echoTimes int
-
- var cmdPrint = &cobra.Command{
- Use: "print [string to print]",
- Short: "Print anything to the screen",
- Long: `print is for printing anything back to the screen.
-For many years people have printed back to the screen.`,
- Args: cobra.MinimumNArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- fmt.Println("Print: " + strings.Join(args, " "))
- },
- }
-
- var cmdEcho = &cobra.Command{
- Use: "echo [string to echo]",
- Short: "Echo anything to the screen",
- Long: `echo is for echoing anything back.
-Echo works a lot like print, except it has a child command.`,
- Args: cobra.MinimumNArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- fmt.Println("Print: " + strings.Join(args, " "))
- },
- }
-
- var cmdTimes = &cobra.Command{
- Use: "times [# times] [string to echo]",
- Short: "Echo anything to the screen more times",
- Long: `echo things multiple times back to the user by providing
-a count and a string.`,
- Args: cobra.MinimumNArgs(1),
- Run: func(cmd *cobra.Command, args []string) {
- for i := 0; i < echoTimes; i++ {
- fmt.Println("Echo: " + strings.Join(args, " "))
- }
- },
- }
-
- cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")
-
- var rootCmd = &cobra.Command{Use: "app"}
- rootCmd.AddCommand(cmdPrint, cmdEcho)
- cmdEcho.AddCommand(cmdTimes)
- rootCmd.Execute()
-}
-```
-
-For a more complete example of a larger application, please checkout [Hugo](http://gohugo.io/).
-
-## Help Command
-
-Cobra automatically adds a help command to your application when you have subcommands.
-This will be called when a user runs 'app help'. Additionally, help will also
-support all other commands as input. Say, for instance, you have a command called
-'create' without any additional configuration; Cobra will work when 'app help
-create' is called. Every command will automatically have the '--help' flag added.
-
-### Example
-
-The following output is automatically generated by Cobra. Nothing beyond the
-command and flag definitions are needed.
-
- $ cobra help
-
- Cobra is a CLI library for Go that empowers applications.
- This application is a tool to generate the needed files
- to quickly create a Cobra application.
-
- Usage:
- cobra [command]
-
- Available Commands:
- add Add a command to a Cobra Application
- help Help about any command
- init Initialize a Cobra Application
-
- Flags:
- -a, --author string author name for copyright attribution (default "YOUR NAME")
- --config string config file (default is $HOME/.cobra.yaml)
- -h, --help help for cobra
- -l, --license string name of license for the project
- --viper use Viper for configuration (default true)
-
- Use "cobra [command] --help" for more information about a command.
-
-
-Help is just a command like any other. There is no special logic or behavior
-around it. In fact, you can provide your own if you want.
-
-### Defining your own help
-
-You can provide your own Help command or your own template for the default command to use
-with followind functions:
-
-```go
-cmd.SetHelpCommand(cmd *Command)
-cmd.SetHelpFunc(f func(*Command, []string))
-cmd.SetHelpTemplate(s string)
-```
-
-The latter two will also apply to any children commands.
-
-## Usage Message
-
-When the user provides an invalid flag or invalid command, Cobra responds by
-showing the user the 'usage'.
-
-### Example
-You may recognize this from the help above. That's because the default help
-embeds the usage as part of its output.
-
- $ cobra --invalid
- Error: unknown flag: --invalid
- Usage:
- cobra [command]
-
- Available Commands:
- add Add a command to a Cobra Application
- help Help about any command
- init Initialize a Cobra Application
-
- Flags:
- -a, --author string author name for copyright attribution (default "YOUR NAME")
- --config string config file (default is $HOME/.cobra.yaml)
- -h, --help help for cobra
- -l, --license string name of license for the project
- --viper use Viper for configuration (default true)
-
- Use "cobra [command] --help" for more information about a command.
-
-### Defining your own usage
-You can provide your own usage function or template for Cobra to use.
-Like help, the function and template are overridable through public methods:
-
-```go
-cmd.SetUsageFunc(f func(*Command) error)
-cmd.SetUsageTemplate(s string)
-```
-
-## PreRun and PostRun Hooks
-
-It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherited by children if they do not declare their own. These functions are run in the following order:
-
-- `PersistentPreRun`
-- `PreRun`
-- `Run`
-- `PostRun`
-- `PersistentPostRun`
-
-An example of two commands which use all of these features is below. When the subcommand is executed, it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun`:
-
-```go
-package main
-
-import (
- "fmt"
-
- "github.com/spf13/cobra"
-)
-
-func main() {
-
- var rootCmd = &cobra.Command{
- Use: "root [sub]",
- Short: "My root command",
- PersistentPreRun: func(cmd *cobra.Command, args []string) {
- fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args)
- },
- PreRun: func(cmd *cobra.Command, args []string) {
- fmt.Printf("Inside rootCmd PreRun with args: %v\n", args)
- },
- Run: func(cmd *cobra.Command, args []string) {
- fmt.Printf("Inside rootCmd Run with args: %v\n", args)
- },
- PostRun: func(cmd *cobra.Command, args []string) {
- fmt.Printf("Inside rootCmd PostRun with args: %v\n", args)
- },
- PersistentPostRun: func(cmd *cobra.Command, args []string) {
- fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args)
- },
- }
-
- var subCmd = &cobra.Command{
- Use: "sub [no options!]",
- Short: "My subcommand",
- PreRun: func(cmd *cobra.Command, args []string) {
- fmt.Printf("Inside subCmd PreRun with args: %v\n", args)
- },
- Run: func(cmd *cobra.Command, args []string) {
- fmt.Printf("Inside subCmd Run with args: %v\n", args)
- },
- PostRun: func(cmd *cobra.Command, args []string) {
- fmt.Printf("Inside subCmd PostRun with args: %v\n", args)
- },
- PersistentPostRun: func(cmd *cobra.Command, args []string) {
- fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args)
- },
- }
-
- rootCmd.AddCommand(subCmd)
-
- rootCmd.SetArgs([]string{""})
- rootCmd.Execute()
- fmt.Println()
- rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})
- rootCmd.Execute()
-}
-```
-
-Output:
-```
-Inside rootCmd PersistentPreRun with args: []
-Inside rootCmd PreRun with args: []
-Inside rootCmd Run with args: []
-Inside rootCmd PostRun with args: []
-Inside rootCmd PersistentPostRun with args: []
-
-Inside rootCmd PersistentPreRun with args: [arg1 arg2]
-Inside subCmd PreRun with args: [arg1 arg2]
-Inside subCmd Run with args: [arg1 arg2]
-Inside subCmd PostRun with args: [arg1 arg2]
-Inside subCmd PersistentPostRun with args: [arg1 arg2]
-```
-
-## Suggestions when "unknown command" happens
-
-Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behave similarly to the `git` command when a typo happens. For example:
-
-```
-$ hugo srever
-Error: unknown command "srever" for "hugo"
-
-Did you mean this?
- server
-
-Run 'hugo --help' for usage.
-```
-
-Suggestions are automatic based on every subcommand registered and use an implementation of [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.
-
-If you need to disable suggestions or tweak the string distance in your command, use:
-
-```go
-command.DisableSuggestions = true
-```
-
-or
-
-```go
-command.SuggestionsMinimumDistance = 1
-```
-
-You can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but makes sense in your set of commands and for some which you don't want aliases. Example:
-
-```
-$ kubectl remove
-Error: unknown command "remove" for "kubectl"
-
-Did you mean this?
- delete
-
-Run 'kubectl help' for usage.
-```
-
-## Generating documentation for your command
-
-Cobra can generate documentation based on subcommands, flags, etc. in the following formats:
-
-- [Markdown](doc/md_docs.md)
-- [ReStructured Text](doc/rest_docs.md)
-- [Man Page](doc/man_docs.md)
-
-## Generating bash completions
-
-Cobra can generate a bash-completion file. If you add more information to your command, these completions can be amazingly powerful and flexible. Read more about it in [Bash Completions](bash_completions.md).
-
-# Contributing
-
-1. Fork it
-2. Download your fork to your PC (`git clone https://github.com/your_username/cobra && cd cobra`)
-3. Create your feature branch (`git checkout -b my-new-feature`)
-4. Make changes and add them (`git add .`)
-5. Commit your changes (`git commit -m 'Add some feature'`)
-6. Push to the branch (`git push origin my-new-feature`)
-7. Create new pull request
-
-# License
-
-Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt)
diff --git a/vendor/github.com/spf13/cobra/args.go b/vendor/github.com/spf13/cobra/args.go
deleted file mode 100644
index 94a6ca2..0000000
--- a/vendor/github.com/spf13/cobra/args.go
+++ /dev/null
@@ -1,98 +0,0 @@
-package cobra
-
-import (
- "fmt"
-)
-
-type PositionalArgs func(cmd *Command, args []string) error
-
-// Legacy arg validation has the following behaviour:
-// - root commands with no subcommands can take arbitrary arguments
-// - root commands with subcommands will do subcommand validity checking
-// - subcommands will always accept arbitrary arguments
-func legacyArgs(cmd *Command, args []string) error {
- // no subcommand, always take args
- if !cmd.HasSubCommands() {
- return nil
- }
-
- // root command with subcommands, do subcommand checking
- if !cmd.HasParent() && len(args) > 0 {
- return fmt.Errorf("unknown command %q for %q%s", args[0], cmd.CommandPath(), cmd.findSuggestions(args[0]))
- }
- return nil
-}
-
-// NoArgs returns an error if any args are included
-func NoArgs(cmd *Command, args []string) error {
- if len(args) > 0 {
- return fmt.Errorf("unknown command %q for %q", args[0], cmd.CommandPath())
- }
- return nil
-}
-
-// OnlyValidArgs returns an error if any args are not in the list of ValidArgs
-func OnlyValidArgs(cmd *Command, args []string) error {
- if len(cmd.ValidArgs) > 0 {
- for _, v := range args {
- if !stringInSlice(v, cmd.ValidArgs) {
- return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0]))
- }
- }
- }
- return nil
-}
-
-func stringInSlice(a string, list []string) bool {
- for _, b := range list {
- if b == a {
- return true
- }
- }
- return false
-}
-
-// ArbitraryArgs never returns an error
-func ArbitraryArgs(cmd *Command, args []string) error {
- return nil
-}
-
-// MinimumNArgs returns an error if there is not at least N args
-func MinimumNArgs(n int) PositionalArgs {
- return func(cmd *Command, args []string) error {
- if len(args) < n {
- return fmt.Errorf("requires at least %d arg(s), only received %d", n, len(args))
- }
- return nil
- }
-}
-
-// MaximumNArgs returns an error if there are more than N args
-func MaximumNArgs(n int) PositionalArgs {
- return func(cmd *Command, args []string) error {
- if len(args) > n {
- return fmt.Errorf("accepts at most %d arg(s), received %d", n, len(args))
- }
- return nil
- }
-}
-
-// ExactArgs returns an error if there are not exactly n args
-func ExactArgs(n int) PositionalArgs {
- return func(cmd *Command, args []string) error {
- if len(args) != n {
- return fmt.Errorf("accepts %d arg(s), received %d", n, len(args))
- }
- return nil
- }
-}
-
-// RangeArgs returns an error if the number of args is not within the expected range
-func RangeArgs(min int, max int) PositionalArgs {
- return func(cmd *Command, args []string) error {
- if len(args) < min || len(args) > max {
- return fmt.Errorf("accepts between %d and %d arg(s), received %d", min, max, len(args))
- }
- return nil
- }
-}
diff --git a/vendor/github.com/spf13/cobra/bash_completions.go b/vendor/github.com/spf13/cobra/bash_completions.go
deleted file mode 100644
index c19fe7a..0000000
--- a/vendor/github.com/spf13/cobra/bash_completions.go
+++ /dev/null
@@ -1,537 +0,0 @@
-package cobra
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
- "sort"
- "strings"
-
- "github.com/spf13/pflag"
-)
-
-// Annotations for Bash completion.
-const (
- BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extensions"
- BashCompCustom = "cobra_annotation_bash_completion_custom"
- BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag"
- BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir"
-)
-
-func writePreamble(buf *bytes.Buffer, name string) {
- buf.WriteString(fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name))
- buf.WriteString(`
-__debug()
-{
- if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then
- echo "$*" >> "${BASH_COMP_DEBUG_FILE}"
- fi
-}
-
-# Homebrew on Macs have version 1.3 of bash-completion which doesn't include
-# _init_completion. This is a very minimal version of that function.
-__my_init_completion()
-{
- COMPREPLY=()
- _get_comp_words_by_ref "$@" cur prev words cword
-}
-
-__index_of_word()
-{
- local w word=$1
- shift
- index=0
- for w in "$@"; do
- [[ $w = "$word" ]] && return
- index=$((index+1))
- done
- index=-1
-}
-
-__contains_word()
-{
- local w word=$1; shift
- for w in "$@"; do
- [[ $w = "$word" ]] && return
- done
- return 1
-}
-
-__handle_reply()
-{
- __debug "${FUNCNAME[0]}"
- case $cur in
- -*)
- if [[ $(type -t compopt) = "builtin" ]]; then
- compopt -o nospace
- fi
- local allflags
- if [ ${#must_have_one_flag[@]} -ne 0 ]; then
- allflags=("${must_have_one_flag[@]}")
- else
- allflags=("${flags[*]} ${two_word_flags[*]}")
- fi
- COMPREPLY=( $(compgen -W "${allflags[*]}" -- "$cur") )
- if [[ $(type -t compopt) = "builtin" ]]; then
- [[ "${COMPREPLY[0]}" == *= ]] || compopt +o nospace
- fi
-
- # complete after --flag=abc
- if [[ $cur == *=* ]]; then
- if [[ $(type -t compopt) = "builtin" ]]; then
- compopt +o nospace
- fi
-
- local index flag
- flag="${cur%%=*}"
- __index_of_word "${flag}" "${flags_with_completion[@]}"
- COMPREPLY=()
- if [[ ${index} -ge 0 ]]; then
- PREFIX=""
- cur="${cur#*=}"
- ${flags_completion[${index}]}
- if [ -n "${ZSH_VERSION}" ]; then
- # zsh completion needs --flag= prefix
- eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )"
- fi
- fi
- fi
- return 0;
- ;;
- esac
-
- # check if we are handling a flag with special work handling
- local index
- __index_of_word "${prev}" "${flags_with_completion[@]}"
- if [[ ${index} -ge 0 ]]; then
- ${flags_completion[${index}]}
- return
- fi
-
- # we are parsing a flag and don't have a special handler, no completion
- if [[ ${cur} != "${words[cword]}" ]]; then
- return
- fi
-
- local completions
- completions=("${commands[@]}")
- if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then
- completions=("${must_have_one_noun[@]}")
- fi
- if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then
- completions+=("${must_have_one_flag[@]}")
- fi
- COMPREPLY=( $(compgen -W "${completions[*]}" -- "$cur") )
-
- if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then
- COMPREPLY=( $(compgen -W "${noun_aliases[*]}" -- "$cur") )
- fi
-
- if [[ ${#COMPREPLY[@]} -eq 0 ]]; then
- declare -F __custom_func >/dev/null && __custom_func
- fi
-
- # available in bash-completion >= 2, not always present on macOS
- if declare -F __ltrim_colon_completions >/dev/null; then
- __ltrim_colon_completions "$cur"
- fi
-}
-
-# The arguments should be in the form "ext1|ext2|extn"
-__handle_filename_extension_flag()
-{
- local ext="$1"
- _filedir "@(${ext})"
-}
-
-__handle_subdirs_in_dir_flag()
-{
- local dir="$1"
- pushd "${dir}" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1
-}
-
-__handle_flag()
-{
- __debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
-
- # if a command required a flag, and we found it, unset must_have_one_flag()
- local flagname=${words[c]}
- local flagvalue
- # if the word contained an =
- if [[ ${words[c]} == *"="* ]]; then
- flagvalue=${flagname#*=} # take in as flagvalue after the =
- flagname=${flagname%%=*} # strip everything after the =
- flagname="${flagname}=" # but put the = back
- fi
- __debug "${FUNCNAME[0]}: looking for ${flagname}"
- if __contains_word "${flagname}" "${must_have_one_flag[@]}"; then
- must_have_one_flag=()
- fi
-
- # if you set a flag which only applies to this command, don't show subcommands
- if __contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then
- commands=()
- fi
-
- # keep flag value with flagname as flaghash
- if [ -n "${flagvalue}" ] ; then
- flaghash[${flagname}]=${flagvalue}
- elif [ -n "${words[ $((c+1)) ]}" ] ; then
- flaghash[${flagname}]=${words[ $((c+1)) ]}
- else
- flaghash[${flagname}]="true" # pad "true" for bool flag
- fi
-
- # skip the argument to a two word flag
- if __contains_word "${words[c]}" "${two_word_flags[@]}"; then
- c=$((c+1))
- # if we are looking for a flags value, don't show commands
- if [[ $c -eq $cword ]]; then
- commands=()
- fi
- fi
-
- c=$((c+1))
-
-}
-
-__handle_noun()
-{
- __debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
-
- if __contains_word "${words[c]}" "${must_have_one_noun[@]}"; then
- must_have_one_noun=()
- elif __contains_word "${words[c]}" "${noun_aliases[@]}"; then
- must_have_one_noun=()
- fi
-
- nouns+=("${words[c]}")
- c=$((c+1))
-}
-
-__handle_command()
-{
- __debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
-
- local next_command
- if [[ -n ${last_command} ]]; then
- next_command="_${last_command}_${words[c]//:/__}"
- else
- if [[ $c -eq 0 ]]; then
- next_command="_$(basename "${words[c]//:/__}")"
- else
- next_command="_${words[c]//:/__}"
- fi
- fi
- c=$((c+1))
- __debug "${FUNCNAME[0]}: looking for ${next_command}"
- declare -F "$next_command" >/dev/null && $next_command
-}
-
-__handle_word()
-{
- if [[ $c -ge $cword ]]; then
- __handle_reply
- return
- fi
- __debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
- if [[ "${words[c]}" == -* ]]; then
- __handle_flag
- elif __contains_word "${words[c]}" "${commands[@]}"; then
- __handle_command
- elif [[ $c -eq 0 ]] && __contains_word "$(basename "${words[c]}")" "${commands[@]}"; then
- __handle_command
- else
- __handle_noun
- fi
- __handle_word
-}
-
-`)
-}
-
-func writePostscript(buf *bytes.Buffer, name string) {
- name = strings.Replace(name, ":", "__", -1)
- buf.WriteString(fmt.Sprintf("__start_%s()\n", name))
- buf.WriteString(fmt.Sprintf(`{
- local cur prev words cword
- declare -A flaghash 2>/dev/null || :
- if declare -F _init_completion >/dev/null 2>&1; then
- _init_completion -s || return
- else
- __my_init_completion -n "=" || return
- fi
-
- local c=0
- local flags=()
- local two_word_flags=()
- local local_nonpersistent_flags=()
- local flags_with_completion=()
- local flags_completion=()
- local commands=("%s")
- local must_have_one_flag=()
- local must_have_one_noun=()
- local last_command
- local nouns=()
-
- __handle_word
-}
-
-`, name))
- buf.WriteString(fmt.Sprintf(`if [[ $(type -t compopt) = "builtin" ]]; then
- complete -o default -F __start_%s %s
-else
- complete -o default -o nospace -F __start_%s %s
-fi
-
-`, name, name, name, name))
- buf.WriteString("# ex: ts=4 sw=4 et filetype=sh\n")
-}
-
-func writeCommands(buf *bytes.Buffer, cmd *Command) {
- buf.WriteString(" commands=()\n")
- for _, c := range cmd.Commands() {
- if !c.IsAvailableCommand() || c == cmd.helpCommand {
- continue
- }
- buf.WriteString(fmt.Sprintf(" commands+=(%q)\n", c.Name()))
- }
- buf.WriteString("\n")
-}
-
-func writeFlagHandler(buf *bytes.Buffer, name string, annotations map[string][]string) {
- for key, value := range annotations {
- switch key {
- case BashCompFilenameExt:
- buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
-
- var ext string
- if len(value) > 0 {
- ext = "__handle_filename_extension_flag " + strings.Join(value, "|")
- } else {
- ext = "_filedir"
- }
- buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", ext))
- case BashCompCustom:
- buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
- if len(value) > 0 {
- handlers := strings.Join(value, "; ")
- buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", handlers))
- } else {
- buf.WriteString(" flags_completion+=(:)\n")
- }
- case BashCompSubdirsInDir:
- buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
-
- var ext string
- if len(value) == 1 {
- ext = "__handle_subdirs_in_dir_flag " + value[0]
- } else {
- ext = "_filedir -d"
- }
- buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", ext))
- }
- }
-}
-
-func writeShortFlag(buf *bytes.Buffer, flag *pflag.Flag) {
- name := flag.Shorthand
- format := " "
- if len(flag.NoOptDefVal) == 0 {
- format += "two_word_"
- }
- format += "flags+=(\"-%s\")\n"
- buf.WriteString(fmt.Sprintf(format, name))
- writeFlagHandler(buf, "-"+name, flag.Annotations)
-}
-
-func writeFlag(buf *bytes.Buffer, flag *pflag.Flag) {
- name := flag.Name
- format := " flags+=(\"--%s"
- if len(flag.NoOptDefVal) == 0 {
- format += "="
- }
- format += "\")\n"
- buf.WriteString(fmt.Sprintf(format, name))
- writeFlagHandler(buf, "--"+name, flag.Annotations)
-}
-
-func writeLocalNonPersistentFlag(buf *bytes.Buffer, flag *pflag.Flag) {
- name := flag.Name
- format := " local_nonpersistent_flags+=(\"--%s"
- if len(flag.NoOptDefVal) == 0 {
- format += "="
- }
- format += "\")\n"
- buf.WriteString(fmt.Sprintf(format, name))
-}
-
-func writeFlags(buf *bytes.Buffer, cmd *Command) {
- buf.WriteString(` flags=()
- two_word_flags=()
- local_nonpersistent_flags=()
- flags_with_completion=()
- flags_completion=()
-
-`)
- localNonPersistentFlags := cmd.LocalNonPersistentFlags()
- cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
- if nonCompletableFlag(flag) {
- return
- }
- writeFlag(buf, flag)
- if len(flag.Shorthand) > 0 {
- writeShortFlag(buf, flag)
- }
- if localNonPersistentFlags.Lookup(flag.Name) != nil {
- writeLocalNonPersistentFlag(buf, flag)
- }
- })
- cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {
- if nonCompletableFlag(flag) {
- return
- }
- writeFlag(buf, flag)
- if len(flag.Shorthand) > 0 {
- writeShortFlag(buf, flag)
- }
- })
-
- buf.WriteString("\n")
-}
-
-func writeRequiredFlag(buf *bytes.Buffer, cmd *Command) {
- buf.WriteString(" must_have_one_flag=()\n")
- flags := cmd.NonInheritedFlags()
- flags.VisitAll(func(flag *pflag.Flag) {
- if nonCompletableFlag(flag) {
- return
- }
- for key := range flag.Annotations {
- switch key {
- case BashCompOneRequiredFlag:
- format := " must_have_one_flag+=(\"--%s"
- if flag.Value.Type() != "bool" {
- format += "="
- }
- format += "\")\n"
- buf.WriteString(fmt.Sprintf(format, flag.Name))
-
- if len(flag.Shorthand) > 0 {
- buf.WriteString(fmt.Sprintf(" must_have_one_flag+=(\"-%s\")\n", flag.Shorthand))
- }
- }
- }
- })
-}
-
-func writeRequiredNouns(buf *bytes.Buffer, cmd *Command) {
- buf.WriteString(" must_have_one_noun=()\n")
- sort.Sort(sort.StringSlice(cmd.ValidArgs))
- for _, value := range cmd.ValidArgs {
- buf.WriteString(fmt.Sprintf(" must_have_one_noun+=(%q)\n", value))
- }
-}
-
-func writeArgAliases(buf *bytes.Buffer, cmd *Command) {
- buf.WriteString(" noun_aliases=()\n")
- sort.Sort(sort.StringSlice(cmd.ArgAliases))
- for _, value := range cmd.ArgAliases {
- buf.WriteString(fmt.Sprintf(" noun_aliases+=(%q)\n", value))
- }
-}
-
-func gen(buf *bytes.Buffer, cmd *Command) {
- for _, c := range cmd.Commands() {
- if !c.IsAvailableCommand() || c == cmd.helpCommand {
- continue
- }
- gen(buf, c)
- }
- commandName := cmd.CommandPath()
- commandName = strings.Replace(commandName, " ", "_", -1)
- commandName = strings.Replace(commandName, ":", "__", -1)
- buf.WriteString(fmt.Sprintf("_%s()\n{\n", commandName))
- buf.WriteString(fmt.Sprintf(" last_command=%q\n", commandName))
- writeCommands(buf, cmd)
- writeFlags(buf, cmd)
- writeRequiredFlag(buf, cmd)
- writeRequiredNouns(buf, cmd)
- writeArgAliases(buf, cmd)
- buf.WriteString("}\n\n")
-}
-
-// GenBashCompletion generates bash completion file and writes to the passed writer.
-func (c *Command) GenBashCompletion(w io.Writer) error {
- buf := new(bytes.Buffer)
- writePreamble(buf, c.Name())
- if len(c.BashCompletionFunction) > 0 {
- buf.WriteString(c.BashCompletionFunction + "\n")
- }
- gen(buf, c)
- writePostscript(buf, c.Name())
-
- _, err := buf.WriteTo(w)
- return err
-}
-
-func nonCompletableFlag(flag *pflag.Flag) bool {
- return flag.Hidden || len(flag.Deprecated) > 0
-}
-
-// GenBashCompletionFile generates bash completion file.
-func (c *Command) GenBashCompletionFile(filename string) error {
- outFile, err := os.Create(filename)
- if err != nil {
- return err
- }
- defer outFile.Close()
-
- return c.GenBashCompletion(outFile)
-}
-
-// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag, if it exists.
-func (c *Command) MarkFlagRequired(name string) error {
- return MarkFlagRequired(c.Flags(), name)
-}
-
-// MarkPersistentFlagRequired adds the BashCompOneRequiredFlag annotation to the named persistent flag, if it exists.
-func (c *Command) MarkPersistentFlagRequired(name string) error {
- return MarkFlagRequired(c.PersistentFlags(), name)
-}
-
-// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag in the flag set, if it exists.
-func MarkFlagRequired(flags *pflag.FlagSet, name string) error {
- return flags.SetAnnotation(name, BashCompOneRequiredFlag, []string{"true"})
-}
-
-// MarkFlagFilename adds the BashCompFilenameExt annotation to the named flag, if it exists.
-// Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided.
-func (c *Command) MarkFlagFilename(name string, extensions ...string) error {
- return MarkFlagFilename(c.Flags(), name, extensions...)
-}
-
-// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists.
-// Generated bash autocompletion will call the bash function f for the flag.
-func (c *Command) MarkFlagCustom(name string, f string) error {
- return MarkFlagCustom(c.Flags(), name, f)
-}
-
-// MarkPersistentFlagFilename adds the BashCompFilenameExt annotation to the named persistent flag, if it exists.
-// Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided.
-func (c *Command) MarkPersistentFlagFilename(name string, extensions ...string) error {
- return MarkFlagFilename(c.PersistentFlags(), name, extensions...)
-}
-
-// MarkFlagFilename adds the BashCompFilenameExt annotation to the named flag in the flag set, if it exists.
-// Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided.
-func MarkFlagFilename(flags *pflag.FlagSet, name string, extensions ...string) error {
- return flags.SetAnnotation(name, BashCompFilenameExt, extensions)
-}
-
-// MarkFlagCustom adds the BashCompCustom annotation to the named flag in the flag set, if it exists.
-// Generated bash autocompletion will call the bash function f for the flag.
-func MarkFlagCustom(flags *pflag.FlagSet, name string, f string) error {
- return flags.SetAnnotation(name, BashCompCustom, []string{f})
-}
diff --git a/vendor/github.com/spf13/cobra/bash_completions.md b/vendor/github.com/spf13/cobra/bash_completions.md
deleted file mode 100644
index 52bd39d..0000000
--- a/vendor/github.com/spf13/cobra/bash_completions.md
+++ /dev/null
@@ -1,206 +0,0 @@
-# Generating Bash Completions For Your Own cobra.Command
-
-Generating bash completions from a cobra command is incredibly easy. An actual program which does so for the kubernetes kubectl binary is as follows:
-
-```go
-package main
-
-import (
- "io/ioutil"
- "os"
-
- "github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd"
-)
-
-func main() {
- kubectl := cmd.NewFactory(nil).NewKubectlCommand(os.Stdin, ioutil.Discard, ioutil.Discard)
- kubectl.GenBashCompletionFile("out.sh")
-}
-```
-
-`out.sh` will get you completions of subcommands and flags. Copy it to `/etc/bash_completion.d/` as described [here](https://debian-administration.org/article/316/An_introduction_to_bash_completion_part_1) and reset your terminal to use autocompletion. If you make additional annotations to your code, you can get even more intelligent and flexible behavior.
-
-## Creating your own custom functions
-
-Some more actual code that works in kubernetes:
-
-```bash
-const (
- bash_completion_func = `__kubectl_parse_get()
-{
- local kubectl_output out
- if kubectl_output=$(kubectl get --no-headers "$1" 2>/dev/null); then
- out=($(echo "${kubectl_output}" | awk '{print $1}'))
- COMPREPLY=( $( compgen -W "${out[*]}" -- "$cur" ) )
- fi
-}
-
-__kubectl_get_resource()
-{
- if [[ ${#nouns[@]} -eq 0 ]]; then
- return 1
- fi
- __kubectl_parse_get ${nouns[${#nouns[@]} -1]}
- if [[ $? -eq 0 ]]; then
- return 0
- fi
-}
-
-__custom_func() {
- case ${last_command} in
- kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop)
- __kubectl_get_resource
- return
- ;;
- *)
- ;;
- esac
-}
-`)
-```
-
-And then I set that in my command definition:
-
-```go
-cmds := &cobra.Command{
- Use: "kubectl",
- Short: "kubectl controls the Kubernetes cluster manager",
- Long: `kubectl controls the Kubernetes cluster manager.
-
-Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`,
- Run: runHelp,
- BashCompletionFunction: bash_completion_func,
-}
-```
-
-The `BashCompletionFunction` option is really only valid/useful on the root command. Doing the above will cause `__custom_func()` to be called when the built in processor was unable to find a solution. In the case of kubernetes a valid command might look something like `kubectl get pod [mypod]`. If you type `kubectl get pod [tab][tab]` the `__customc_func()` will run because the cobra.Command only understood "kubectl" and "get." `__custom_func()` will see that the cobra.Command is "kubectl_get" and will thus call another helper `__kubectl_get_resource()`. `__kubectl_get_resource` will look at the 'nouns' collected. In our example the only noun will be `pod`. So it will call `__kubectl_parse_get pod`. `__kubectl_parse_get` will actually call out to kubernetes and get any pods. It will then set `COMPREPLY` to valid pods!
-
-## Have the completions code complete your 'nouns'
-
-In the above example "pod" was assumed to already be typed. But if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them. Simplified code from `kubectl get` looks like:
-
-```go
-validArgs []string = { "pod", "node", "service", "replicationcontroller" }
-
-cmd := &cobra.Command{
- Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)",
- Short: "Display one or many resources",
- Long: get_long,
- Example: get_example,
- Run: func(cmd *cobra.Command, args []string) {
- err := RunGet(f, out, cmd, args)
- util.CheckErr(err)
- },
- ValidArgs: validArgs,
-}
-```
-
-Notice we put the "ValidArgs" on the "get" subcommand. Doing so will give results like
-
-```bash
-# kubectl get [tab][tab]
-node pod replicationcontroller service
-```
-
-## Plural form and shortcuts for nouns
-
-If your nouns have a number of aliases, you can define them alongside `ValidArgs` using `ArgAliases`:
-
-```go
-argAliases []string = { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" }
-
-cmd := &cobra.Command{
- ...
- ValidArgs: validArgs,
- ArgAliases: argAliases
-}
-```
-
-The aliases are not shown to the user on tab completion, but they are accepted as valid nouns by
-the completion algorithm if entered manually, e.g. in:
-
-```bash
-# kubectl get rc [tab][tab]
-backend frontend database
-```
-
-Note that without declaring `rc` as an alias, the completion algorithm would show the list of nouns
-in this example again instead of the replication controllers.
-
-## Mark flags as required
-
-Most of the time completions will only show subcommands. But if a flag is required to make a subcommand work, you probably want it to show up when the user types [tab][tab]. Marking a flag as 'Required' is incredibly easy.
-
-```go
-cmd.MarkFlagRequired("pod")
-cmd.MarkFlagRequired("container")
-```
-
-and you'll get something like
-
-```bash
-# kubectl exec [tab][tab][tab]
--c --container= -p --pod=
-```
-
-# Specify valid filename extensions for flags that take a filename
-
-In this example we use --filename= and expect to get a json or yaml file as the argument. To make this easier we annotate the --filename flag with valid filename extensions.
-
-```go
- annotations := []string{"json", "yaml", "yml"}
- annotation := make(map[string][]string)
- annotation[cobra.BashCompFilenameExt] = annotations
-
- flag := &pflag.Flag{
- Name: "filename",
- Shorthand: "f",
- Usage: usage,
- Value: value,
- DefValue: value.String(),
- Annotations: annotation,
- }
- cmd.Flags().AddFlag(flag)
-```
-
-Now when you run a command with this filename flag you'll get something like
-
-```bash
-# kubectl create -f
-test/ example/ rpmbuild/
-hello.yml test.json
-```
-
-So while there are many other files in the CWD it only shows me subdirs and those with valid extensions.
-
-# Specifiy custom flag completion
-
-Similar to the filename completion and filtering using cobra.BashCompFilenameExt, you can specifiy
-a custom flag completion function with cobra.BashCompCustom:
-
-```go
- annotation := make(map[string][]string)
- annotation[cobra.BashCompFilenameExt] = []string{"__kubectl_get_namespaces"}
-
- flag := &pflag.Flag{
- Name: "namespace",
- Usage: usage,
- Annotations: annotation,
- }
- cmd.Flags().AddFlag(flag)
-```
-
-In addition add the `__handle_namespace_flag` implementation in the `BashCompletionFunction`
-value, e.g.:
-
-```bash
-__kubectl_get_namespaces()
-{
- local template
- template="{{ range .items }}{{ .metadata.name }} {{ end }}"
- local kubectl_out
- if kubectl_out=$(kubectl get -o template --template="${template}" namespace 2>/dev/null); then
- COMPREPLY=( $( compgen -W "${kubectl_out}[*]" -- "$cur" ) )
- fi
-}
-```
diff --git a/vendor/github.com/spf13/cobra/bash_completions_test.go b/vendor/github.com/spf13/cobra/bash_completions_test.go
deleted file mode 100644
index a3b13a3..0000000
--- a/vendor/github.com/spf13/cobra/bash_completions_test.go
+++ /dev/null
@@ -1,194 +0,0 @@
-package cobra
-
-import (
- "bytes"
- "os"
- "os/exec"
- "strings"
- "testing"
-)
-
-func checkOmit(t *testing.T, found, unexpected string) {
- if strings.Contains(found, unexpected) {
- t.Errorf("Unexpected response.\nGot: %q\nBut should not have!\n", unexpected)
- }
-}
-
-func check(t *testing.T, found, expected string) {
- if !strings.Contains(found, expected) {
- t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
- }
-}
-
-func runShellCheck(s string) error {
- excluded := []string{
- "SC2034", // PREFIX appears unused. Verify it or export it.
- }
- cmd := exec.Command("shellcheck", "-s", "bash", "-", "-e", strings.Join(excluded, ","))
- cmd.Stderr = os.Stderr
- cmd.Stdout = os.Stdout
-
- stdin, err := cmd.StdinPipe()
- if err != nil {
- return err
- }
- go func() {
- defer stdin.Close()
- stdin.Write([]byte(s))
- }()
-
- return cmd.Run()
-}
-
-// World worst custom function, just keep telling you to enter hello!
-const (
- bashCompletionFunc = `__custom_func() {
-COMPREPLY=( "hello" )
-}
-`
-)
-
-func TestBashCompletions(t *testing.T) {
- c := initializeWithRootCmd()
- cmdEcho.AddCommand(cmdTimes)
- c.AddCommand(cmdEcho, cmdPrint, cmdDeprecated, cmdColon)
-
- // custom completion function
- c.BashCompletionFunction = bashCompletionFunc
-
- // required flag
- c.MarkFlagRequired("introot")
-
- // valid nouns
- validArgs := []string{"pod", "node", "service", "replicationcontroller"}
- c.ValidArgs = validArgs
-
- // noun aliases
- argAliases := []string{"pods", "nodes", "services", "replicationcontrollers", "po", "no", "svc", "rc"}
- c.ArgAliases = argAliases
-
- // filename
- var flagval string
- c.Flags().StringVar(&flagval, "filename", "", "Enter a filename")
- c.MarkFlagFilename("filename", "json", "yaml", "yml")
-
- // persistent filename
- var flagvalPersistent string
- c.PersistentFlags().StringVar(&flagvalPersistent, "persistent-filename", "", "Enter a filename")
- c.MarkPersistentFlagFilename("persistent-filename")
- c.MarkPersistentFlagRequired("persistent-filename")
-
- // filename extensions
- var flagvalExt string
- c.Flags().StringVar(&flagvalExt, "filename-ext", "", "Enter a filename (extension limited)")
- c.MarkFlagFilename("filename-ext")
-
- // filename extensions
- var flagvalCustom string
- c.Flags().StringVar(&flagvalCustom, "custom", "", "Enter a filename (extension limited)")
- c.MarkFlagCustom("custom", "__complete_custom")
-
- // subdirectories in a given directory
- var flagvalTheme string
- c.Flags().StringVar(&flagvalTheme, "theme", "", "theme to use (located in /themes/THEMENAME/)")
- c.Flags().SetAnnotation("theme", BashCompSubdirsInDir, []string{"themes"})
-
- out := new(bytes.Buffer)
- c.GenBashCompletion(out)
- str := out.String()
-
- check(t, str, "_cobra-test")
- check(t, str, "_cobra-test_echo")
- check(t, str, "_cobra-test_echo_times")
- check(t, str, "_cobra-test_print")
- check(t, str, "_cobra-test_cmd__colon")
-
- // check for required flags
- check(t, str, `must_have_one_flag+=("--introot=")`)
- check(t, str, `must_have_one_flag+=("--persistent-filename=")`)
- // check for custom completion function
- check(t, str, `COMPREPLY=( "hello" )`)
- // check for required nouns
- check(t, str, `must_have_one_noun+=("pod")`)
- // check for noun aliases
- check(t, str, `noun_aliases+=("pods")`)
- check(t, str, `noun_aliases+=("rc")`)
- checkOmit(t, str, `must_have_one_noun+=("pods")`)
- // check for filename extension flags
- check(t, str, `flags_completion+=("_filedir")`)
- // check for filename extension flags
- check(t, str, `must_have_one_noun+=("three")`)
- // check for filename extension flags
- check(t, str, `flags_completion+=("__handle_filename_extension_flag json|yaml|yml")`)
- // check for custom flags
- check(t, str, `flags_completion+=("__complete_custom")`)
- // check for subdirs_in_dir flags
- check(t, str, `flags_completion+=("__handle_subdirs_in_dir_flag themes")`)
-
- checkOmit(t, str, cmdDeprecated.Name())
-
- // if available, run shellcheck against the script
- if err := exec.Command("which", "shellcheck").Run(); err != nil {
- return
- }
- err := runShellCheck(str)
- if err != nil {
- t.Fatalf("shellcheck failed: %v", err)
- }
-}
-
-func TestBashCompletionHiddenFlag(t *testing.T) {
- var cmdTrue = &Command{
- Use: "does nothing",
- Run: func(cmd *Command, args []string) {},
- }
-
- const flagName = "hidden-foo-bar-baz"
-
- var flagValue bool
- cmdTrue.Flags().BoolVar(&flagValue, flagName, false, "hidden flag")
- cmdTrue.Flags().MarkHidden(flagName)
-
- out := new(bytes.Buffer)
- cmdTrue.GenBashCompletion(out)
- bashCompletion := out.String()
- if strings.Contains(bashCompletion, flagName) {
- t.Errorf("expected completion to not include %q flag: Got %v", flagName, bashCompletion)
- }
-}
-
-func TestBashCompletionDeprecatedFlag(t *testing.T) {
- var cmdTrue = &Command{
- Use: "does nothing",
- Run: func(cmd *Command, args []string) {},
- }
-
- const flagName = "deprecated-foo-bar-baz"
-
- var flagValue bool
- cmdTrue.Flags().BoolVar(&flagValue, flagName, false, "hidden flag")
- cmdTrue.Flags().MarkDeprecated(flagName, "use --does-not-exist instead")
-
- out := new(bytes.Buffer)
- cmdTrue.GenBashCompletion(out)
- bashCompletion := out.String()
- if strings.Contains(bashCompletion, flagName) {
- t.Errorf("expected completion to not include %q flag: Got %v", flagName, bashCompletion)
- }
-}
-
-func BenchmarkBashCompletion(b *testing.B) {
- c := initializeWithRootCmd()
- cmdEcho.AddCommand(cmdTimes)
- c.AddCommand(cmdEcho, cmdPrint, cmdDeprecated, cmdColon)
-
- buf := new(bytes.Buffer)
-
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- buf.Reset()
- if err := c.GenBashCompletion(buf); err != nil {
- b.Fatal(err)
- }
- }
-}
diff --git a/vendor/github.com/spf13/cobra/cobra.go b/vendor/github.com/spf13/cobra/cobra.go
deleted file mode 100644
index 8928cef..0000000
--- a/vendor/github.com/spf13/cobra/cobra.go
+++ /dev/null
@@ -1,190 +0,0 @@
-// Copyright © 2013 Steve Francia .
-//
-// 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.
-
-// Commands similar to git, go tools and other modern CLI tools
-// inspired by go, go-Commander, gh and subcommand
-
-package cobra
-
-import (
- "fmt"
- "io"
- "reflect"
- "strconv"
- "strings"
- "text/template"
- "unicode"
-)
-
-var templateFuncs = template.FuncMap{
- "trim": strings.TrimSpace,
- "trimRightSpace": trimRightSpace,
- "trimTrailingWhitespaces": trimRightSpace,
- "appendIfNotPresent": appendIfNotPresent,
- "rpad": rpad,
- "gt": Gt,
- "eq": Eq,
-}
-
-var initializers []func()
-
-// EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing
-// to automatically enable in CLI tools.
-// Set this to true to enable it.
-var EnablePrefixMatching = false
-
-// EnableCommandSorting controls sorting of the slice of commands, which is turned on by default.
-// To disable sorting, set it to false.
-var EnableCommandSorting = true
-
-// MousetrapHelpText enables an information splash screen on Windows
-// if the CLI is started from explorer.exe.
-// To disable the mousetrap, just set this variable to blank string ("").
-// Works only on Microsoft Windows.
-var MousetrapHelpText string = `This is a command line tool.
-
-You need to open cmd.exe and run it from there.
-`
-
-// AddTemplateFunc adds a template function that's available to Usage and Help
-// template generation.
-func AddTemplateFunc(name string, tmplFunc interface{}) {
- templateFuncs[name] = tmplFunc
-}
-
-// AddTemplateFuncs adds multiple template functions that are available to Usage and
-// Help template generation.
-func AddTemplateFuncs(tmplFuncs template.FuncMap) {
- for k, v := range tmplFuncs {
- templateFuncs[k] = v
- }
-}
-
-// OnInitialize takes a series of func() arguments and appends them to a slice of func().
-func OnInitialize(y ...func()) {
- initializers = append(initializers, y...)
-}
-
-// FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
-
-// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,
-// Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as
-// ints and then compared.
-func Gt(a interface{}, b interface{}) bool {
- var left, right int64
- av := reflect.ValueOf(a)
-
- switch av.Kind() {
- case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
- left = int64(av.Len())
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- left = av.Int()
- case reflect.String:
- left, _ = strconv.ParseInt(av.String(), 10, 64)
- }
-
- bv := reflect.ValueOf(b)
-
- switch bv.Kind() {
- case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
- right = int64(bv.Len())
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- right = bv.Int()
- case reflect.String:
- right, _ = strconv.ParseInt(bv.String(), 10, 64)
- }
-
- return left > right
-}
-
-// FIXME Eq is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
-
-// Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.
-func Eq(a interface{}, b interface{}) bool {
- av := reflect.ValueOf(a)
- bv := reflect.ValueOf(b)
-
- switch av.Kind() {
- case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
- panic("Eq called on unsupported type")
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- return av.Int() == bv.Int()
- case reflect.String:
- return av.String() == bv.String()
- }
- return false
-}
-
-func trimRightSpace(s string) string {
- return strings.TrimRightFunc(s, unicode.IsSpace)
-}
-
-// FIXME appendIfNotPresent is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
-
-// appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s.
-func appendIfNotPresent(s, stringToAppend string) string {
- if strings.Contains(s, stringToAppend) {
- return s
- }
- return s + " " + stringToAppend
-}
-
-// rpad adds padding to the right of a string.
-func rpad(s string, padding int) string {
- template := fmt.Sprintf("%%-%ds", padding)
- return fmt.Sprintf(template, s)
-}
-
-// tmpl executes the given template text on data, writing the result to w.
-func tmpl(w io.Writer, text string, data interface{}) error {
- t := template.New("top")
- t.Funcs(templateFuncs)
- template.Must(t.Parse(text))
- return t.Execute(w, data)
-}
-
-// ld compares two strings and returns the levenshtein distance between them.
-func ld(s, t string, ignoreCase bool) int {
- if ignoreCase {
- s = strings.ToLower(s)
- t = strings.ToLower(t)
- }
- d := make([][]int, len(s)+1)
- for i := range d {
- d[i] = make([]int, len(t)+1)
- }
- for i := range d {
- d[i][0] = i
- }
- for j := range d[0] {
- d[0][j] = j
- }
- for j := 1; j <= len(t); j++ {
- for i := 1; i <= len(s); i++ {
- if s[i-1] == t[j-1] {
- d[i][j] = d[i-1][j-1]
- } else {
- min := d[i-1][j]
- if d[i][j-1] < min {
- min = d[i][j-1]
- }
- if d[i-1][j-1] < min {
- min = d[i-1][j-1]
- }
- d[i][j] = min + 1
- }
- }
-
- }
- return d[len(s)][len(t)]
-}
diff --git a/vendor/github.com/spf13/cobra/cobra_test.go b/vendor/github.com/spf13/cobra/cobra_test.go
deleted file mode 100644
index 8192b52..0000000
--- a/vendor/github.com/spf13/cobra/cobra_test.go
+++ /dev/null
@@ -1,1314 +0,0 @@
-package cobra
-
-import (
- "bytes"
- "fmt"
- "os"
- "reflect"
- "runtime"
- "strings"
- "testing"
- "text/template"
-
- "github.com/spf13/pflag"
-)
-
-var tp, te, tt, tr []string
-var rootPersPre, echoPre, echoPersPre, timesPersPre []string
-var flagb1, flagb2, flagb3, flagbr, flagbp bool
-var flags1, flags2a, flags2b, flags3, outs string
-var flagi1, flagi2, flagi3, flagi4, flagir int
-var rootcalled bool
-var versionUsed int
-
-const strtwoParentHelp = "help message for parent flag strtwo"
-const strtwoChildHelp = "help message for child flag strtwo"
-
-var cmdHidden = &Command{
- Use: "hide [secret string to print]",
- Short: "Print anything to screen (if command is known)",
- Long: `an absolutely utterly useless command for testing.`,
- Run: func(cmd *Command, args []string) {
- outs = "hidden"
- },
- Hidden: true,
-}
-
-var cmdPrint = &Command{
- Use: "print [string to print]",
- Args: MinimumNArgs(1),
- Short: "Print anything to the screen",
- Long: `an absolutely utterly useless command for testing.`,
- Run: func(cmd *Command, args []string) {
- tp = args
- },
-}
-
-var cmdEcho = &Command{
- Use: "echo [string to echo]",
- Aliases: []string{"say"},
- Short: "Echo anything to the screen",
- Long: `an utterly useless command for testing.`,
- Example: "Just run cobra-test echo",
- PersistentPreRun: func(cmd *Command, args []string) {
- echoPersPre = args
- },
- PreRun: func(cmd *Command, args []string) {
- echoPre = args
- },
- Run: func(cmd *Command, args []string) {
- te = args
- },
-}
-
-var cmdEchoSub = &Command{
- Use: "echosub [string to print]",
- Short: "second sub command for echo",
- Long: `an absolutely utterly useless command for testing gendocs!.`,
- Run: func(cmd *Command, args []string) {
- },
-}
-
-var cmdDeprecated = &Command{
- Use: "deprecated [can't do anything here]",
- Short: "A command which is deprecated",
- Long: `an absolutely utterly useless command for testing deprecation!.`,
- Deprecated: "Please use echo instead",
- Run: func(cmd *Command, args []string) {
- },
- Args: NoArgs,
-}
-
-var cmdTimes = &Command{
- Use: "times [# times] [string to echo]",
- SuggestFor: []string{"counts"},
- Short: "Echo anything to the screen more times",
- Long: `a slightly useless command for testing.`,
- PersistentPreRun: func(cmd *Command, args []string) {
- timesPersPre = args
- },
- Run: func(cmd *Command, args []string) {
- tt = args
- },
- Args: OnlyValidArgs,
- ValidArgs: []string{"one", "two", "three", "four"},
-}
-
-var cmdRootNoRun = &Command{
- Use: "cobra-test",
- Short: "The root can run its own function",
- Long: "The root description for help",
- PersistentPreRun: func(cmd *Command, args []string) {
- rootPersPre = args
- },
-}
-
-var cmdRootSameName = &Command{
- Use: "print",
- Short: "Root with the same name as a subcommand",
- Long: "The root description for help",
-}
-
-var cmdRootTakesArgs = &Command{
- Use: "root-with-args [random args]",
- Short: "The root can run it's own function and takes args!",
- Long: "The root description for help, and some args",
- Run: func(cmd *Command, args []string) {
- tr = args
- },
- Args: ArbitraryArgs,
-}
-
-var cmdRootWithRun = &Command{
- Use: "cobra-test",
- Short: "The root can run its own function",
- Long: "The root description for help",
- Run: func(cmd *Command, args []string) {
- tr = args
- rootcalled = true
- },
-}
-
-var cmdSubNoRun = &Command{
- Use: "subnorun",
- Short: "A subcommand without a Run function",
- Long: "A long output about a subcommand without a Run function",
-}
-
-var cmdCustomFlags = &Command{
- Use: "customflags [flags] -- REMOTE_COMMAND",
- Short: "A command that expects flags in a custom location",
- Long: "A long output about a command that expects flags in a custom location",
- Run: func(cmd *Command, args []string) {
- },
-}
-
-var cmdVersion1 = &Command{
- Use: "version",
- Short: "Print the version number",
- Long: `First version of the version command`,
- Run: func(cmd *Command, args []string) {
- versionUsed = 1
- },
-}
-
-var cmdVersion2 = &Command{
- Use: "version",
- Short: "Print the version number",
- Long: `Second version of the version command`,
- Run: func(cmd *Command, args []string) {
- versionUsed = 2
- },
-}
-
-var cmdColon = &Command{
- Use: "cmd:colon",
- Run: func(cmd *Command, args []string) {
- },
-}
-
-func flagInit() {
- cmdEcho.ResetFlags()
- cmdPrint.ResetFlags()
- cmdTimes.ResetFlags()
- cmdRootNoRun.ResetFlags()
- cmdRootSameName.ResetFlags()
- cmdRootWithRun.ResetFlags()
- cmdSubNoRun.ResetFlags()
- cmdCustomFlags.ResetFlags()
- cmdVersion1.ResetFlags()
- cmdVersion2.ResetFlags()
-
- cmdRootNoRun.PersistentFlags().StringVarP(&flags2a, "strtwo", "t", "two", strtwoParentHelp)
- cmdCustomFlags.Flags().IntVar(&flagi4, "intfour", 456, "help message for flag intfour")
- cmdEcho.Flags().BoolVarP(&flagb1, "boolone", "b", true, "help message for flag boolone")
- cmdEcho.Flags().IntVarP(&flagi1, "intone", "i", 123, "help message for flag intone")
- cmdEcho.PersistentFlags().BoolVarP(&flagbp, "persistentbool", "p", false, "help message for flag persistentbool")
- cmdEcho.PersistentFlags().StringVarP(&flags1, "strone", "s", "one", "help message for flag strone")
- cmdPrint.Flags().IntVarP(&flagi3, "intthree", "i", 345, "help message for flag intthree")
- cmdTimes.Flags().BoolVarP(&flagb2, "booltwo", "c", false, "help message for flag booltwo")
- cmdTimes.Flags().IntVarP(&flagi2, "inttwo", "j", 234, "help message for flag inttwo")
- cmdTimes.Flags().StringVarP(&flags2b, "strtwo", "t", "2", strtwoChildHelp)
- cmdTimes.PersistentFlags().StringVarP(&flags2b, "strtwo", "t", "2", strtwoChildHelp)
- cmdTimes.LocalFlags() // populate lflags before parent is set
- cmdPrint.Flags().BoolVarP(&flagb3, "boolthree", "b", true, "help message for flag boolthree")
- cmdPrint.PersistentFlags().StringVarP(&flags3, "strthree", "s", "three", "help message for flag strthree")
-}
-
-func commandInit() {
- cmdEcho.ResetCommands()
- cmdPrint.ResetCommands()
- cmdTimes.ResetCommands()
- cmdRootNoRun.ResetCommands()
- cmdRootSameName.ResetCommands()
- cmdRootWithRun.ResetCommands()
- cmdSubNoRun.ResetCommands()
- cmdCustomFlags.ResetCommands()
-}
-
-func initialize() *Command {
- tt, tp, te = nil, nil, nil
- rootPersPre, echoPre, echoPersPre, timesPersPre = nil, nil, nil, nil
-
- var c = cmdRootNoRun
- commandInit()
- flagInit()
- return c
-}
-
-func initializeWithSameName() *Command {
- tt, tp, te = nil, nil, nil
- rootPersPre, echoPre, echoPersPre, timesPersPre = nil, nil, nil, nil
- var c = cmdRootSameName
- commandInit()
- flagInit()
- return c
-}
-
-func initializeWithRootCmd() *Command {
- cmdRootWithRun.ResetCommands()
- tt, tp, te, tr, rootcalled = nil, nil, nil, nil, false
- flagInit()
- cmdRootWithRun.Flags().BoolVarP(&flagbr, "boolroot", "b", false, "help message for flag boolroot")
- cmdRootWithRun.Flags().IntVarP(&flagir, "introot", "i", 321, "help message for flag introot")
- commandInit()
- return cmdRootWithRun
-}
-
-type resulter struct {
- Error error
- Output string
- Command *Command
-}
-
-func fullSetupTest(args ...string) resulter {
- c := initializeWithRootCmd()
-
- return fullTester(c, args...)
-}
-
-func noRRSetupTestSilenced(args ...string) resulter {
- c := initialize()
- c.SilenceErrors = true
- c.SilenceUsage = true
- return fullTester(c, args...)
-}
-
-func noRRSetupTest(args ...string) resulter {
- c := initialize()
-
- return fullTester(c, args...)
-}
-
-func rootOnlySetupTest(args ...string) resulter {
- c := initializeWithRootCmd()
-
- return simpleTester(c, args...)
-}
-
-func simpleTester(c *Command, args ...string) resulter {
- buf := new(bytes.Buffer)
- // Testing flag with invalid input
- c.SetOutput(buf)
- c.SetArgs(args)
-
- err := c.Execute()
- output := buf.String()
-
- return resulter{err, output, c}
-}
-
-func simpleTesterC(c *Command, args ...string) resulter {
- buf := new(bytes.Buffer)
- // Testing flag with invalid input
- c.SetOutput(buf)
- c.SetArgs(args)
-
- cmd, err := c.ExecuteC()
- output := buf.String()
-
- return resulter{err, output, cmd}
-}
-
-func fullTester(c *Command, args ...string) resulter {
- buf := new(bytes.Buffer)
- // Testing flag with invalid input
- c.SetOutput(buf)
- cmdEcho.AddCommand(cmdTimes)
- c.AddCommand(cmdPrint, cmdEcho, cmdSubNoRun, cmdCustomFlags, cmdDeprecated)
- c.SetArgs(args)
-
- err := c.Execute()
- output := buf.String()
-
- return resulter{err, output, c}
-}
-
-func logErr(t *testing.T, found, expected string) {
- out := new(bytes.Buffer)
-
- _, _, line, ok := runtime.Caller(2)
- if ok {
- fmt.Fprintf(out, "Line: %d ", line)
- }
- fmt.Fprintf(out, "Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
- t.Errorf(out.String())
-}
-
-func checkStringContains(t *testing.T, found, expected string) {
- if !strings.Contains(found, expected) {
- logErr(t, found, expected)
- }
-}
-
-func checkResultContains(t *testing.T, x resulter, check string) {
- checkStringContains(t, x.Output, check)
-}
-
-func checkStringOmits(t *testing.T, found, expected string) {
- if strings.Contains(found, expected) {
- logErr(t, found, expected)
- }
-}
-
-func checkResultOmits(t *testing.T, x resulter, check string) {
- checkStringOmits(t, x.Output, check)
-}
-
-func checkOutputContains(t *testing.T, c *Command, check string) {
- buf := new(bytes.Buffer)
- c.SetOutput(buf)
- c.Execute()
-
- if !strings.Contains(buf.String(), check) {
- logErr(t, buf.String(), check)
- }
-}
-
-func TestSingleCommand(t *testing.T) {
- noRRSetupTest("print", "one", "two")
-
- if te != nil || tt != nil {
- t.Error("Wrong command called")
- }
- if tp == nil {
- t.Error("Wrong command called")
- }
- if strings.Join(tp, " ") != "one two" {
- t.Error("Command didn't parse correctly")
- }
-}
-
-func TestChildCommand(t *testing.T) {
- noRRSetupTest("echo", "times", "one", "two")
-
- if te != nil || tp != nil {
- t.Error("Wrong command called")
- }
- if tt == nil {
- t.Error("Wrong command called")
- }
- if strings.Join(tt, " ") != "one two" {
- t.Error("Command didn't parse correctly")
- }
-}
-
-func TestCommandAlias(t *testing.T) {
- noRRSetupTest("say", "times", "one", "two")
-
- if te != nil || tp != nil {
- t.Error("Wrong command called")
- }
- if tt == nil {
- t.Error("Wrong command called")
- }
- if strings.Join(tt, " ") != "one two" {
- t.Error("Command didn't parse correctly")
- }
-}
-
-func TestPrefixMatching(t *testing.T) {
- EnablePrefixMatching = true
- noRRSetupTest("ech", "times", "one", "two")
-
- if te != nil || tp != nil {
- t.Error("Wrong command called")
- }
- if tt == nil {
- t.Error("Wrong command called")
- }
- if strings.Join(tt, " ") != "one two" {
- t.Error("Command didn't parse correctly")
- }
-
- EnablePrefixMatching = false
-}
-
-func TestNoPrefixMatching(t *testing.T) {
- EnablePrefixMatching = false
-
- noRRSetupTest("ech", "times", "one", "two")
-
- if !(tt == nil && te == nil && tp == nil) {
- t.Error("Wrong command called")
- }
-}
-
-func TestAliasPrefixMatching(t *testing.T) {
- EnablePrefixMatching = true
- noRRSetupTest("sa", "times", "one", "two")
-
- if te != nil || tp != nil {
- t.Error("Wrong command called")
- }
- if tt == nil {
- t.Error("Wrong command called")
- }
- if strings.Join(tt, " ") != "one two" {
- t.Error("Command didn't parse correctly")
- }
- EnablePrefixMatching = false
-}
-
-func TestChildSameName(t *testing.T) {
- c := initializeWithSameName()
- c.AddCommand(cmdPrint, cmdEcho)
- c.SetArgs([]string{"print", "one", "two"})
- c.Execute()
-
- if te != nil || tt != nil {
- t.Error("Wrong command called")
- }
- if tp == nil {
- t.Error("Wrong command called")
- }
- if strings.Join(tp, " ") != "one two" {
- t.Error("Command didn't parse correctly")
- }
-}
-
-func TestGrandChildSameName(t *testing.T) {
- c := initializeWithSameName()
- cmdTimes.AddCommand(cmdPrint)
- c.AddCommand(cmdTimes)
- c.SetArgs([]string{"times", "print", "one", "two"})
- c.Execute()
-
- if te != nil || tt != nil {
- t.Error("Wrong command called")
- }
- if tp == nil {
- t.Error("Wrong command called")
- }
- if strings.Join(tp, " ") != "one two" {
- t.Error("Command didn't parse correctly")
- }
-}
-
-func TestUsage(t *testing.T) {
- x := fullSetupTest("help")
- checkResultContains(t, x, cmdRootWithRun.Use+" [flags]")
- x = fullSetupTest("help", "customflags")
- checkResultContains(t, x, cmdCustomFlags.Use)
- checkResultOmits(t, x, cmdCustomFlags.Use+" [flags]")
-}
-
-func TestRootTakesNoArgs(t *testing.T) {
- c := initializeWithSameName()
- c.AddCommand(cmdPrint, cmdEcho)
- result := simpleTester(c, "illegal")
-
- if result.Error == nil {
- t.Fatal("Expected an error")
- }
-
- expectedError := `unknown command "illegal" for "print"`
- if !strings.Contains(result.Error.Error(), expectedError) {
- t.Errorf("exptected %v, got %v", expectedError, result.Error.Error())
- }
-}
-
-func TestRootTakesArgs(t *testing.T) {
- c := cmdRootTakesArgs
- result := simpleTester(c, "legal")
-
- if result.Error != nil {
- t.Errorf("expected no error, but got %v", result.Error)
- }
-}
-
-func TestSubCmdTakesNoArgs(t *testing.T) {
- result := fullSetupTest("deprecated", "illegal")
-
- if result.Error == nil {
- t.Fatal("Expected an error")
- }
-
- expectedError := `unknown command "illegal" for "cobra-test deprecated"`
- if !strings.Contains(result.Error.Error(), expectedError) {
- t.Errorf("expected %v, got %v", expectedError, result.Error.Error())
- }
-}
-
-func TestSubCmdTakesArgs(t *testing.T) {
- noRRSetupTest("echo", "times", "one", "two")
- if strings.Join(tt, " ") != "one two" {
- t.Error("Command didn't parse correctly")
- }
-}
-
-func TestCmdOnlyValidArgs(t *testing.T) {
- result := noRRSetupTest("echo", "times", "one", "two", "five")
-
- if result.Error == nil {
- t.Fatal("Expected an error")
- }
-
- expectedError := `invalid argument "five"`
- if !strings.Contains(result.Error.Error(), expectedError) {
- t.Errorf("expected %v, got %v", expectedError, result.Error.Error())
- }
-}
-
-func TestFlagLong(t *testing.T) {
- noRRSetupTest("echo", "--intone=13", "something", "--", "here")
-
- if cmdEcho.ArgsLenAtDash() != 1 {
- t.Errorf("expected argsLenAtDash: %d but got %d", 1, cmdRootNoRun.ArgsLenAtDash())
- }
- if strings.Join(te, " ") != "something here" {
- t.Errorf("flags didn't leave proper args remaining..%s given", te)
- }
- if flagi1 != 13 {
- t.Errorf("int flag didn't get correct value, had %d", flagi1)
- }
- if flagi2 != 234 {
- t.Errorf("default flag value changed, 234 expected, %d given", flagi2)
- }
-}
-
-func TestFlagShort(t *testing.T) {
- noRRSetupTest("echo", "-i13", "--", "something", "here")
-
- if cmdEcho.ArgsLenAtDash() != 0 {
- t.Errorf("expected argsLenAtDash: %d but got %d", 0, cmdRootNoRun.ArgsLenAtDash())
- }
- if strings.Join(te, " ") != "something here" {
- t.Errorf("flags didn't leave proper args remaining..%s given", te)
- }
- if flagi1 != 13 {
- t.Errorf("int flag didn't get correct value, had %d", flagi1)
- }
- if flagi2 != 234 {
- t.Errorf("default flag value changed, 234 expected, %d given", flagi2)
- }
-
- noRRSetupTest("echo", "-i", "13", "something", "here")
-
- if strings.Join(te, " ") != "something here" {
- t.Errorf("flags didn't leave proper args remaining..%s given", te)
- }
- if flagi1 != 13 {
- t.Errorf("int flag didn't get correct value, had %d", flagi1)
- }
- if flagi2 != 234 {
- t.Errorf("default flag value changed, 234 expected, %d given", flagi2)
- }
-
- noRRSetupTest("print", "-i99", "one", "two")
-
- if strings.Join(tp, " ") != "one two" {
- t.Errorf("flags didn't leave proper args remaining..%s given", tp)
- }
- if flagi3 != 99 {
- t.Errorf("int flag didn't get correct value, had %d", flagi3)
- }
- if flagi1 != 123 {
- t.Errorf("default flag value changed on different command with same shortname, 234 expected, %d given", flagi2)
- }
-}
-
-func TestChildCommandFlags(t *testing.T) {
- noRRSetupTest("echo", "times", "-j", "99", "one", "two")
-
- if strings.Join(tt, " ") != "one two" {
- t.Errorf("flags didn't leave proper args remaining..%s given", tt)
- }
-
- // Testing with flag that shouldn't be persistent
- r := noRRSetupTest("echo", "times", "-j", "99", "-i77", "one", "two")
-
- if r.Error == nil {
- t.Errorf("invalid flag should generate error")
- }
-
- if !strings.Contains(r.Error.Error(), "unknown shorthand") {
- t.Errorf("Wrong error message displayed, \n %s", r.Error)
- }
-
- if flagi2 != 99 {
- t.Errorf("flag value should be 99, %d given", flagi2)
- }
-
- if flagi1 != 123 {
- t.Errorf("unset flag should have default value, expecting 123, given %d", flagi1)
- }
-
- // Testing with flag only existing on child
- r = noRRSetupTest("echo", "-j", "99", "-i77", "one", "two")
-
- if r.Error == nil {
- t.Errorf("invalid flag should generate error")
- }
- if !strings.Contains(r.Error.Error(), "unknown shorthand flag") {
- t.Errorf("Wrong error message displayed, \n %s", r.Error)
- }
-
- // Testing with persistent flag overwritten by child
- noRRSetupTest("echo", "times", "--strtwo=child", "one", "two")
-
- if flags2b != "child" {
- t.Errorf("flag value should be child, %s given", flags2b)
- }
-
- if flags2a != "two" {
- t.Errorf("unset flag should have default value, expecting two, given %s", flags2a)
- }
-
- // Testing flag with invalid input
- r = noRRSetupTest("echo", "-i10E")
-
- if r.Error == nil {
- t.Errorf("invalid input should generate error")
- }
- if !strings.Contains(r.Error.Error(), "invalid syntax") {
- t.Errorf("Wrong error message displayed, \n %s", r.Error)
- }
-}
-
-func TestTrailingCommandFlags(t *testing.T) {
- x := fullSetupTest("echo", "two", "-x")
-
- if x.Error == nil {
- t.Errorf("invalid flag should generate error")
- }
-}
-
-func TestInvalidSubcommandFlags(t *testing.T) {
- cmd := initializeWithRootCmd()
- cmd.AddCommand(cmdTimes)
-
- result := simpleTester(cmd, "times", "--inttwo=2", "--badflag=bar")
- // given that we are not checking here result.Error we check for
- // stock usage message
- checkResultContains(t, result, "cobra-test times [# times]")
- if strings.Contains(result.Error.Error(), "unknown flag: --inttwo") {
- t.Errorf("invalid --badflag flag shouldn't fail on 'unknown' --inttwo flag")
- }
-
-}
-
-func TestSubcommandExecuteC(t *testing.T) {
- cmd := initializeWithRootCmd()
- double := &Command{
- Use: "double message",
- Run: func(c *Command, args []string) {
- msg := strings.Join(args, " ")
- c.Println(msg, msg)
- },
- }
-
- echo := &Command{
- Use: "echo message",
- Run: func(c *Command, args []string) {
- msg := strings.Join(args, " ")
- c.Println(msg)
- },
- }
-
- cmd.AddCommand(double, echo)
-
- result := simpleTesterC(cmd, "double", "hello", "world")
- checkResultContains(t, result, "hello world hello world")
-
- if result.Command.Name() != "double" {
- t.Errorf("invalid cmd returned from ExecuteC: should be 'double' but got %s", result.Command.Name())
- }
-
- result = simpleTesterC(cmd, "echo", "msg", "to", "be", "echoed")
- checkResultContains(t, result, "msg to be echoed")
-
- if result.Command.Name() != "echo" {
- t.Errorf("invalid cmd returned from ExecuteC: should be 'echo' but got %s", result.Command.Name())
- }
-}
-
-func TestSubcommandArgEvaluation(t *testing.T) {
- cmd := initializeWithRootCmd()
-
- first := &Command{
- Use: "first",
- Run: func(cmd *Command, args []string) {
- },
- }
- cmd.AddCommand(first)
-
- second := &Command{
- Use: "second",
- Run: func(cmd *Command, args []string) {
- fmt.Fprintf(cmd.OutOrStdout(), "%v", args)
- },
- }
- first.AddCommand(second)
-
- result := simpleTester(cmd, "first", "second", "first", "third")
-
- expectedOutput := fmt.Sprint([]string{"first third"})
- if result.Output != expectedOutput {
- t.Errorf("exptected %v, got %v", expectedOutput, result.Output)
- }
-}
-
-func TestPersistentFlags(t *testing.T) {
- fullSetupTest("echo", "-s", "something", "-p", "more", "here")
-
- // persistentFlag should act like normal flag on its own command
- if strings.Join(te, " ") != "more here" {
- t.Errorf("flags didn't leave proper args remaining..%s given", te)
- }
- if flags1 != "something" {
- t.Errorf("string flag didn't get correct value, had %v", flags1)
- }
- if !flagbp {
- t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp)
- }
-
- // persistentFlag should act like normal flag on its own command
- fullSetupTest("echo", "times", "-s", "again", "-c", "-p", "one", "two")
-
- if strings.Join(tt, " ") != "one two" {
- t.Errorf("flags didn't leave proper args remaining. %s given", tt)
- }
-
- if flags1 != "again" {
- t.Errorf("string flag didn't get correct value, had %v", flags1)
- }
-
- if !flagb2 {
- t.Errorf("local flag not parsed correctly. Expected true, had %v", flagb2)
- }
- if !flagbp {
- t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp)
- }
-}
-
-func TestHelpCommand(t *testing.T) {
- x := fullSetupTest("help")
- checkResultContains(t, x, cmdRootWithRun.Long)
-
- x = fullSetupTest("help", "echo")
- checkResultContains(t, x, cmdEcho.Long)
-
- x = fullSetupTest("help", "echo", "times")
- checkResultContains(t, x, cmdTimes.Long)
-}
-
-func TestChildCommandHelp(t *testing.T) {
- c := noRRSetupTest("print", "--help")
- checkResultContains(t, c, strtwoParentHelp)
- r := noRRSetupTest("echo", "times", "--help")
- checkResultContains(t, r, strtwoChildHelp)
-}
-
-func TestNonRunChildHelp(t *testing.T) {
- x := noRRSetupTest("subnorun")
- checkResultContains(t, x, cmdSubNoRun.Long)
-}
-
-func TestRunnableRootCommand(t *testing.T) {
- x := fullSetupTest("")
-
- if !rootcalled {
- t.Errorf("Root Function was not called\n out:%v", x.Error)
- }
-}
-
-func TestVisitParents(t *testing.T) {
- c := &Command{Use: "app"}
- sub := &Command{Use: "sub"}
- dsub := &Command{Use: "dsub"}
- sub.AddCommand(dsub)
- c.AddCommand(sub)
- total := 0
- add := func(x *Command) {
- total++
- }
- sub.VisitParents(add)
- if total != 1 {
- t.Errorf("Should have visited 1 parent but visited %d", total)
- }
-
- total = 0
- dsub.VisitParents(add)
- if total != 2 {
- t.Errorf("Should have visited 2 parent but visited %d", total)
- }
-
- total = 0
- c.VisitParents(add)
- if total != 0 {
- t.Errorf("Should have not visited any parent but visited %d", total)
- }
-}
-
-func TestRunnableRootCommandNilInput(t *testing.T) {
- c := initializeWithRootCmd()
-
- buf := new(bytes.Buffer)
- // Testing flag with invalid input
- c.SetOutput(buf)
- cmdEcho.AddCommand(cmdTimes)
- c.AddCommand(cmdPrint, cmdEcho)
- c.SetArgs([]string{})
-
- err := c.Execute()
- if err != nil {
- t.Errorf("Execute() failed with %v", err)
- }
-
- if !rootcalled {
- t.Errorf("Root Function was not called")
- }
-}
-
-func TestRunnableRootCommandEmptyInput(t *testing.T) {
- args := []string{"", "--introot=12", ""}
- c := initializeWithRootCmd()
-
- buf := new(bytes.Buffer)
- // Testing flag with invalid input
- c.SetOutput(buf)
- cmdEcho.AddCommand(cmdTimes)
- c.AddCommand(cmdPrint, cmdEcho)
- c.SetArgs(args)
-
- c.Execute()
-
- if !rootcalled {
- t.Errorf("Root Function was not called.\nOutput was:\n%s\n", buf)
- }
-}
-
-func TestInvalidSubcommandWhenArgsAllowed(t *testing.T) {
- fullSetupTest("echo", "invalid-sub")
-
- if te[0] != "invalid-sub" {
- t.Errorf("Subcommand didn't work...")
- }
-}
-
-func TestRootFlags(t *testing.T) {
- fullSetupTest("-i", "17", "-b")
-
- if !flagbr {
- t.Errorf("flag value should be true, %v given", flagbr)
- }
-
- if flagir != 17 {
- t.Errorf("flag value should be 17, %d given", flagir)
- }
-}
-
-func TestRootHelp(t *testing.T) {
- x := fullSetupTest("--help")
-
- checkResultContains(t, x, "Available Commands:")
- checkResultContains(t, x, "for more information about a command")
-
- if strings.Contains(x.Output, "unknown flag: --help") {
- t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)
- }
-
- if strings.Contains(x.Output, cmdEcho.Use) {
- t.Errorf("--help shouldn't display subcommand's usage, Got: \n %s", x.Output)
- }
-
- x = fullSetupTest("echo", "--help")
-
- if strings.Contains(x.Output, cmdTimes.Use) {
- t.Errorf("--help shouldn't display subsubcommand's usage, Got: \n %s", x.Output)
- }
-
- checkResultContains(t, x, "Available Commands:")
- checkResultContains(t, x, "for more information about a command")
-
- if strings.Contains(x.Output, "unknown flag: --help") {
- t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)
- }
-
-}
-
-func TestFlagAccess(t *testing.T) {
- initialize()
-
- cmdEcho.AddCommand(cmdTimes)
- local := cmdTimes.LocalFlags()
- inherited := cmdTimes.InheritedFlags()
-
- for _, f := range []string{"inttwo", "strtwo", "booltwo"} {
- if local.Lookup(f) == nil {
- t.Errorf("LocalFlags expected to contain %s, Got: nil", f)
- }
- }
- if inherited.Lookup("strone") == nil {
- t.Errorf("InheritedFlags expected to contain strone, Got: nil")
- }
- if inherited.Lookup("strtwo") != nil {
- t.Errorf("InheritedFlags shouldn not contain overwritten flag strtwo")
- }
-}
-
-func TestNoNRunnableRootCommandNilInput(t *testing.T) {
- c := initialize()
-
- buf := new(bytes.Buffer)
- // Testing flag with invalid input
- c.SetOutput(buf)
- cmdEcho.AddCommand(cmdTimes)
- c.AddCommand(cmdPrint, cmdEcho)
- c.SetArgs([]string{})
-
- c.Execute()
-
- if !strings.Contains(buf.String(), cmdRootNoRun.Long) {
- t.Errorf("Expected to get help output, Got: \n %s", buf)
- }
-}
-
-func TestRootNoCommandHelp(t *testing.T) {
- x := rootOnlySetupTest("--help")
-
- checkResultOmits(t, x, "Available Commands:")
- checkResultOmits(t, x, "for more information about a command")
-
- if strings.Contains(x.Output, "unknown flag: --help") {
- t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)
- }
-
- x = rootOnlySetupTest("echo", "--help")
-
- checkResultOmits(t, x, "Available Commands:")
- checkResultOmits(t, x, "for more information about a command")
-
- if strings.Contains(x.Output, "unknown flag: --help") {
- t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)
- }
-}
-
-func TestRootUnknownCommand(t *testing.T) {
- r := noRRSetupTest("bogus")
- s := "Error: unknown command \"bogus\" for \"cobra-test\"\nRun 'cobra-test --help' for usage.\n"
-
- if r.Output != s {
- t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output)
- }
-
- r = noRRSetupTest("--strtwo=a", "bogus")
- if r.Output != s {
- t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output)
- }
-}
-
-func TestRootUnknownCommandSilenced(t *testing.T) {
- r := noRRSetupTestSilenced("bogus")
-
- if r.Output != "" {
- t.Errorf("Unexpected response.\nExpecting to be: \n\"\"\n Got:\n %q\n", r.Output)
- }
-
- r = noRRSetupTestSilenced("--strtwo=a", "bogus")
- if r.Output != "" {
- t.Errorf("Unexpected response.\nExpecting to be:\n\"\"\nGot:\n %q\n", r.Output)
- }
-}
-
-func TestRootSuggestions(t *testing.T) {
- outputWithSuggestions := "Error: unknown command \"%s\" for \"cobra-test\"\n\nDid you mean this?\n\t%s\n\nRun 'cobra-test --help' for usage.\n"
- outputWithoutSuggestions := "Error: unknown command \"%s\" for \"cobra-test\"\nRun 'cobra-test --help' for usage.\n"
-
- cmd := initializeWithRootCmd()
- cmd.AddCommand(cmdTimes)
-
- tests := map[string]string{
- "time": "times",
- "tiems": "times",
- "tims": "times",
- "timeS": "times",
- "rimes": "times",
- "ti": "times",
- "t": "times",
- "timely": "times",
- "ri": "",
- "timezone": "",
- "foo": "",
- "counts": "times",
- }
-
- for typo, suggestion := range tests {
- for _, suggestionsDisabled := range []bool{false, true} {
- cmd.DisableSuggestions = suggestionsDisabled
- result := simpleTester(cmd, typo)
- expected := ""
- if len(suggestion) == 0 || suggestionsDisabled {
- expected = fmt.Sprintf(outputWithoutSuggestions, typo)
- } else {
- expected = fmt.Sprintf(outputWithSuggestions, typo, suggestion)
- }
- if result.Output != expected {
- t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", expected, result.Output)
- }
- }
- }
-}
-
-func TestFlagsBeforeCommand(t *testing.T) {
- // short without space
- x := fullSetupTest("-i10", "echo")
- if x.Error != nil {
- t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
- }
-
- x = noRRSetupTest("echo", "-i=10")
- if x.Error != nil {
- t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error)
- }
-
- // long with equals
- x = noRRSetupTest("--intone=123", "echo", "one", "two")
- if x.Error != nil {
- t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error)
- }
-
- // With parsing error properly reported
- x = fullSetupTest("-i10E", "echo")
- if !strings.Contains(x.Error.Error(), "invalid syntax") {
- t.Errorf("Wrong error message displayed, \n %s", x.Error)
- }
-}
-
-func TestRemoveCommand(t *testing.T) {
- versionUsed = 0
- c := initializeWithRootCmd()
- c.AddCommand(cmdVersion1)
- c.RemoveCommand(cmdVersion1)
- x := fullTester(c, "version")
- if x.Error == nil {
- t.Errorf("Removed command should not have been called\n")
- return
- }
-}
-
-func TestCommandWithoutSubcommands(t *testing.T) {
- c := initializeWithRootCmd()
-
- x := simpleTester(c, "")
- if x.Error != nil {
- t.Errorf("Calling command without subcommands should not have error: %v", x.Error)
- return
- }
-}
-
-func TestCommandWithoutSubcommandsWithArg(t *testing.T) {
- c := initializeWithRootCmd()
- expectedArgs := []string{"arg"}
-
- x := simpleTester(c, "arg")
- if x.Error != nil {
- t.Errorf("Calling command without subcommands but with arg should not have error: %v", x.Error)
- return
- }
- if !reflect.DeepEqual(expectedArgs, tr) {
- t.Errorf("Calling command without subcommands but with arg has wrong args: expected: %v, actual: %v", expectedArgs, tr)
- return
- }
-}
-
-func TestReplaceCommandWithRemove(t *testing.T) {
- versionUsed = 0
- c := initializeWithRootCmd()
- c.AddCommand(cmdVersion1)
- c.RemoveCommand(cmdVersion1)
- c.AddCommand(cmdVersion2)
- x := fullTester(c, "version")
- if x.Error != nil {
- t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
- return
- }
- if versionUsed == 1 {
- t.Errorf("Removed command shouldn't be called\n")
- }
- if versionUsed != 2 {
- t.Errorf("Replacing command should have been called but didn't\n")
- }
-}
-
-func TestDeprecatedSub(t *testing.T) {
- c := fullSetupTest("deprecated")
-
- checkResultContains(t, c, cmdDeprecated.Deprecated)
-}
-
-func TestPreRun(t *testing.T) {
- noRRSetupTest("echo", "one", "two")
- if echoPre == nil || echoPersPre == nil {
- t.Error("PreRun or PersistentPreRun not called")
- }
- if rootPersPre != nil || timesPersPre != nil {
- t.Error("Wrong *Pre functions called!")
- }
-
- noRRSetupTest("echo", "times", "one", "two")
- if timesPersPre == nil {
- t.Error("PreRun or PersistentPreRun not called")
- }
- if echoPre != nil || echoPersPre != nil || rootPersPre != nil {
- t.Error("Wrong *Pre functions called!")
- }
-
- noRRSetupTest("print", "one", "two")
- if rootPersPre == nil {
- t.Error("Parent PersistentPreRun not called but should not have been")
- }
- if echoPre != nil || echoPersPre != nil || timesPersPre != nil {
- t.Error("Wrong *Pre functions called!")
- }
-}
-
-// Check if cmdEchoSub gets PersistentPreRun from rootCmd even if is added last
-func TestPeristentPreRunPropagation(t *testing.T) {
- rootCmd := initialize()
-
- // First add the cmdEchoSub to cmdPrint
- cmdPrint.AddCommand(cmdEchoSub)
- // Now add cmdPrint to rootCmd
- rootCmd.AddCommand(cmdPrint)
-
- rootCmd.SetArgs([]string{"print", "echosub", "lala"})
- rootCmd.Execute()
-
- if len(rootPersPre) == 0 || rootPersPre[0] != "lala" {
- t.Error("RootCmd PersistentPreRun not called but should have been")
- }
-}
-
-func TestGlobalNormFuncPropagation(t *testing.T) {
- normFunc := func(f *pflag.FlagSet, name string) pflag.NormalizedName {
- return pflag.NormalizedName(name)
- }
-
- rootCmd := initialize()
- rootCmd.AddCommand(cmdEcho)
-
- rootCmd.SetGlobalNormalizationFunc(normFunc)
- if reflect.ValueOf(normFunc).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() {
- t.Error("rootCmd seems to have a wrong normalization function")
- }
-
- // Also check it propagates retroactively
- if reflect.ValueOf(normFunc).Pointer() != reflect.ValueOf(cmdEcho.GlobalNormalizationFunc()).Pointer() {
- t.Error("cmdEcho should have had the normalization function of rootCmd")
- }
-
- // First add the cmdEchoSub to cmdPrint
- cmdPrint.AddCommand(cmdEchoSub)
- if cmdPrint.GlobalNormalizationFunc() != nil && cmdEchoSub.GlobalNormalizationFunc() != nil {
- t.Error("cmdPrint and cmdEchoSub should had no normalization functions")
- }
-
- // Now add cmdPrint to rootCmd
- rootCmd.AddCommand(cmdPrint)
- if reflect.ValueOf(cmdPrint.GlobalNormalizationFunc()).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() ||
- reflect.ValueOf(cmdEchoSub.GlobalNormalizationFunc()).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() {
- t.Error("cmdPrint and cmdEchoSub should had the normalization function of rootCmd")
- }
-}
-
-func TestNormPassedOnLocal(t *testing.T) {
- n := func(f *pflag.FlagSet, name string) pflag.NormalizedName {
- return pflag.NormalizedName(strings.ToUpper(name))
- }
-
- cmd := &Command{}
- flagVal := false
-
- cmd.Flags().BoolVar(&flagVal, "flagname", true, "this is a dummy flag")
- cmd.SetGlobalNormalizationFunc(n)
- if cmd.LocalFlags().Lookup("flagname") != cmd.LocalFlags().Lookup("FLAGNAME") {
- t.Error("Normalization function should be passed on to Local flag set")
- }
-}
-
-func TestNormPassedOnInherited(t *testing.T) {
- n := func(f *pflag.FlagSet, name string) pflag.NormalizedName {
- return pflag.NormalizedName(strings.ToUpper(name))
- }
-
- cmd, childBefore, childAfter := &Command{}, &Command{}, &Command{}
- flagVal := false
- cmd.AddCommand(childBefore)
-
- cmd.PersistentFlags().BoolVar(&flagVal, "flagname", true, "this is a dummy flag")
- cmd.SetGlobalNormalizationFunc(n)
-
- cmd.AddCommand(childAfter)
-
- if f := childBefore.InheritedFlags(); f.Lookup("flagname") == nil || f.Lookup("flagname") != f.Lookup("FLAGNAME") {
- t.Error("Normalization function should be passed on to inherited flag set in command added before flag")
- }
- if f := childAfter.InheritedFlags(); f.Lookup("flagname") == nil || f.Lookup("flagname") != f.Lookup("FLAGNAME") {
- t.Error("Normalization function should be passed on to inherited flag set in command added after flag")
- }
-}
-
-// Related to https://github.com/spf13/cobra/issues/521.
-func TestNormConsistent(t *testing.T) {
- n := func(f *pflag.FlagSet, name string) pflag.NormalizedName {
- return pflag.NormalizedName(strings.ToUpper(name))
- }
- id := func(f *pflag.FlagSet, name string) pflag.NormalizedName {
- return pflag.NormalizedName(name)
- }
-
- cmd := &Command{}
- flagVal := false
-
- cmd.Flags().BoolVar(&flagVal, "flagname", true, "this is a dummy flag")
- // Build local flag set
- cmd.LocalFlags()
-
- cmd.SetGlobalNormalizationFunc(n)
- cmd.SetGlobalNormalizationFunc(id)
-
- if cmd.LocalFlags().Lookup("flagname") == cmd.LocalFlags().Lookup("FLAGNAME") {
- t.Error("Normalizing flag names should not result in duplicate flags")
- }
-}
-
-func TestFlagOnPflagCommandLine(t *testing.T) {
- flagName := "flagOnCommandLine"
- pflag.String(flagName, "", "about my flag")
- r := fullSetupTest("--help")
-
- checkResultContains(t, r, flagName)
-
- // Reset pflag.CommandLine flagset.
- pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)
-}
-
-func TestAddTemplateFunctions(t *testing.T) {
- AddTemplateFunc("t", func() bool { return true })
- AddTemplateFuncs(template.FuncMap{
- "f": func() bool { return false },
- "h": func() string { return "Hello," },
- "w": func() string { return "world." }})
-
- const usage = "Hello, world."
-
- c := &Command{}
- c.SetUsageTemplate(`{{if t}}{{h}}{{end}}{{if f}}{{h}}{{end}} {{w}}`)
-
- if us := c.UsageString(); us != usage {
- t.Errorf("c.UsageString() != \"%s\", is \"%s\"", usage, us)
- }
-}
-
-func TestUsageIsNotPrintedTwice(t *testing.T) {
- var cmd = &Command{Use: "root"}
- var sub = &Command{Use: "sub"}
- cmd.AddCommand(sub)
-
- r := simpleTester(cmd, "")
- if strings.Count(r.Output, "Usage:") != 1 {
- t.Error("Usage output is not printed exactly once")
- }
-}
-
-func BenchmarkInheritedFlags(b *testing.B) {
- initialize()
- cmdEcho.AddCommand(cmdTimes)
- b.ResetTimer()
-
- for i := 0; i < b.N; i++ {
- cmdTimes.InheritedFlags()
- }
-}
-
-func BenchmarkLocalFlags(b *testing.B) {
- initialize()
- cmdEcho.AddCommand(cmdTimes)
- b.ResetTimer()
-
- for i := 0; i < b.N; i++ {
- cmdTimes.LocalFlags()
- }
-}
diff --git a/vendor/github.com/spf13/cobra/command.go b/vendor/github.com/spf13/cobra/command.go
deleted file mode 100644
index 58e6ceb..0000000
--- a/vendor/github.com/spf13/cobra/command.go
+++ /dev/null
@@ -1,1409 +0,0 @@
-// Copyright © 2013 Steve Francia .
-//
-// 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 cobra is a commander providing a simple interface to create powerful modern CLI interfaces.
-// In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code.
-package cobra
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
- "path/filepath"
- "sort"
- "strings"
-
- flag "github.com/spf13/pflag"
-)
-
-// Command is just that, a command for your application.
-// E.g. 'go run ...' - 'run' is the command. Cobra requires
-// you to define the usage and description as part of your command
-// definition to ensure usability.
-type Command struct {
- // Use is the one-line usage message.
- Use string
-
- // Aliases is an array of aliases that can be used instead of the first word in Use.
- Aliases []string
-
- // SuggestFor is an array of command names for which this command will be suggested -
- // similar to aliases but only suggests.
- SuggestFor []string
-
- // Short is the short description shown in the 'help' output.
- Short string
-
- // Long is the long message shown in the 'help ' output.
- Long string
-
- // Example is examples of how to use the command.
- Example string
-
- // ValidArgs is list of all valid non-flag arguments that are accepted in bash completions
- ValidArgs []string
-
- // Expected arguments
- Args PositionalArgs
-
- // ArgAliases is List of aliases for ValidArgs.
- // These are not suggested to the user in the bash completion,
- // but accepted if entered manually.
- ArgAliases []string
-
- // BashCompletionFunction is custom functions used by the bash autocompletion generator.
- BashCompletionFunction string
-
- // Deprecated defines, if this command is deprecated and should print this string when used.
- Deprecated string
-
- // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.
- Hidden bool
-
- // Annotations are key/value pairs that can be used by applications to identify or
- // group commands.
- Annotations map[string]string
-
- // The *Run functions are executed in the following order:
- // * PersistentPreRun()
- // * PreRun()
- // * Run()
- // * PostRun()
- // * PersistentPostRun()
- // All functions get the same args, the arguments after the command name.
- //
- // PersistentPreRun: children of this command will inherit and execute.
- PersistentPreRun func(cmd *Command, args []string)
- // PersistentPreRunE: PersistentPreRun but returns an error.
- PersistentPreRunE func(cmd *Command, args []string) error
- // PreRun: children of this command will not inherit.
- PreRun func(cmd *Command, args []string)
- // PreRunE: PreRun but returns an error.
- PreRunE func(cmd *Command, args []string) error
- // Run: Typically the actual work function. Most commands will only implement this.
- Run func(cmd *Command, args []string)
- // RunE: Run but returns an error.
- RunE func(cmd *Command, args []string) error
- // PostRun: run after the Run command.
- PostRun func(cmd *Command, args []string)
- // PostRunE: PostRun but returns an error.
- PostRunE func(cmd *Command, args []string) error
- // PersistentPostRun: children of this command will inherit and execute after PostRun.
- PersistentPostRun func(cmd *Command, args []string)
- // PersistentPostRunE: PersistentPostRun but returns an error.
- PersistentPostRunE func(cmd *Command, args []string) error
-
- // SilenceErrors is an option to quiet errors down stream.
- SilenceErrors bool
-
- // SilenceUsage is an option to silence usage when an error occurs.
- SilenceUsage bool
-
- // DisableFlagParsing disables the flag parsing.
- // If this is true all flags will be passed to the command as arguments.
- DisableFlagParsing bool
-
- // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")
- // will be printed by generating docs for this command.
- DisableAutoGenTag bool
-
- // DisableSuggestions disables the suggestions based on Levenshtein distance
- // that go along with 'unknown command' messages.
- DisableSuggestions bool
- // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.
- // Must be > 0.
- SuggestionsMinimumDistance int
-
- // TraverseChildren parses flags on all parents before executing child command.
- TraverseChildren bool
-
- // commands is the list of commands supported by this program.
- commands []*Command
- // parent is a parent command for this command.
- parent *Command
- // Max lengths of commands' string lengths for use in padding.
- commandsMaxUseLen int
- commandsMaxCommandPathLen int
- commandsMaxNameLen int
- // commandsAreSorted defines, if command slice are sorted or not.
- commandsAreSorted bool
-
- // args is actual args parsed from flags.
- args []string
- // flagErrorBuf contains all error messages from pflag.
- flagErrorBuf *bytes.Buffer
- // flags is full set of flags.
- flags *flag.FlagSet
- // pflags contains persistent flags.
- pflags *flag.FlagSet
- // lflags contains local flags.
- lflags *flag.FlagSet
- // iflags contains inherited flags.
- iflags *flag.FlagSet
- // parentsPflags is all persistent flags of cmd's parents.
- parentsPflags *flag.FlagSet
- // globNormFunc is the global normalization function
- // that we can use on every pflag set and children commands
- globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName
-
- // output is an output writer defined by user.
- output io.Writer
- // usageFunc is usage func defined by user.
- usageFunc func(*Command) error
- // usageTemplate is usage template defined by user.
- usageTemplate string
- // flagErrorFunc is func defined by user and it's called when the parsing of
- // flags returns an error.
- flagErrorFunc func(*Command, error) error
- // helpTemplate is help template defined by user.
- helpTemplate string
- // helpFunc is help func defined by user.
- helpFunc func(*Command, []string)
- // helpCommand is command with usage 'help'. If it's not defined by user,
- // cobra uses default help command.
- helpCommand *Command
-}
-
-// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden
-// particularly useful when testing.
-func (c *Command) SetArgs(a []string) {
- c.args = a
-}
-
-// SetOutput sets the destination for usage and error messages.
-// If output is nil, os.Stderr is used.
-func (c *Command) SetOutput(output io.Writer) {
- c.output = output
-}
-
-// SetUsageFunc sets usage function. Usage can be defined by application.
-func (c *Command) SetUsageFunc(f func(*Command) error) {
- c.usageFunc = f
-}
-
-// SetUsageTemplate sets usage template. Can be defined by Application.
-func (c *Command) SetUsageTemplate(s string) {
- c.usageTemplate = s
-}
-
-// SetFlagErrorFunc sets a function to generate an error when flag parsing
-// fails.
-func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {
- c.flagErrorFunc = f
-}
-
-// SetHelpFunc sets help function. Can be defined by Application.
-func (c *Command) SetHelpFunc(f func(*Command, []string)) {
- c.helpFunc = f
-}
-
-// SetHelpCommand sets help command.
-func (c *Command) SetHelpCommand(cmd *Command) {
- c.helpCommand = cmd
-}
-
-// SetHelpTemplate sets help template to be used. Application can use it to set custom template.
-func (c *Command) SetHelpTemplate(s string) {
- c.helpTemplate = s
-}
-
-// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.
-// The user should not have a cyclic dependency on commands.
-func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {
- c.Flags().SetNormalizeFunc(n)
- c.PersistentFlags().SetNormalizeFunc(n)
- c.globNormFunc = n
-
- for _, command := range c.commands {
- command.SetGlobalNormalizationFunc(n)
- }
-}
-
-// OutOrStdout returns output to stdout.
-func (c *Command) OutOrStdout() io.Writer {
- return c.getOut(os.Stdout)
-}
-
-// OutOrStderr returns output to stderr
-func (c *Command) OutOrStderr() io.Writer {
- return c.getOut(os.Stderr)
-}
-
-func (c *Command) getOut(def io.Writer) io.Writer {
- if c.output != nil {
- return c.output
- }
- if c.HasParent() {
- return c.parent.getOut(def)
- }
- return def
-}
-
-// UsageFunc returns either the function set by SetUsageFunc for this command
-// or a parent, or it returns a default usage function.
-func (c *Command) UsageFunc() (f func(*Command) error) {
- if c.usageFunc != nil {
- return c.usageFunc
- }
- if c.HasParent() {
- return c.Parent().UsageFunc()
- }
- return func(c *Command) error {
- c.mergePersistentFlags()
- err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c)
- if err != nil {
- c.Println(err)
- }
- return err
- }
-}
-
-// Usage puts out the usage for the command.
-// Used when a user provides invalid input.
-// Can be defined by user by overriding UsageFunc.
-func (c *Command) Usage() error {
- return c.UsageFunc()(c)
-}
-
-// HelpFunc returns either the function set by SetHelpFunc for this command
-// or a parent, or it returns a function with default help behavior.
-func (c *Command) HelpFunc() func(*Command, []string) {
- if c.helpFunc != nil {
- return c.helpFunc
- }
- if c.HasParent() {
- return c.Parent().HelpFunc()
- }
- return func(c *Command, a []string) {
- c.mergePersistentFlags()
- err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)
- if err != nil {
- c.Println(err)
- }
- }
-}
-
-// Help puts out the help for the command.
-// Used when a user calls help [command].
-// Can be defined by user by overriding HelpFunc.
-func (c *Command) Help() error {
- c.HelpFunc()(c, []string{})
- return nil
-}
-
-// UsageString return usage string.
-func (c *Command) UsageString() string {
- tmpOutput := c.output
- bb := new(bytes.Buffer)
- c.SetOutput(bb)
- c.Usage()
- c.output = tmpOutput
- return bb.String()
-}
-
-// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this
-// command or a parent, or it returns a function which returns the original
-// error.
-func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {
- if c.flagErrorFunc != nil {
- return c.flagErrorFunc
- }
-
- if c.HasParent() {
- return c.parent.FlagErrorFunc()
- }
- return func(c *Command, err error) error {
- return err
- }
-}
-
-var minUsagePadding = 25
-
-// UsagePadding return padding for the usage.
-func (c *Command) UsagePadding() int {
- if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {
- return minUsagePadding
- }
- return c.parent.commandsMaxUseLen
-}
-
-var minCommandPathPadding = 11
-
-// CommandPathPadding return padding for the command path.
-func (c *Command) CommandPathPadding() int {
- if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {
- return minCommandPathPadding
- }
- return c.parent.commandsMaxCommandPathLen
-}
-
-var minNamePadding = 11
-
-// NamePadding returns padding for the name.
-func (c *Command) NamePadding() int {
- if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {
- return minNamePadding
- }
- return c.parent.commandsMaxNameLen
-}
-
-// UsageTemplate returns usage template for the command.
-func (c *Command) UsageTemplate() string {
- if c.usageTemplate != "" {
- return c.usageTemplate
- }
-
- if c.HasParent() {
- return c.parent.UsageTemplate()
- }
- return `Usage:{{if .Runnable}}
- {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
- {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}
-
-Aliases:
- {{.NameAndAliases}}{{end}}{{if .HasExample}}
-
-Examples:
-{{.Example}}{{end}}{{if .HasAvailableSubCommands}}
-
-Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
- {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
-
-Flags:
-{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
-
-Global Flags:
-{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}
-
-Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
- {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
-
-Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
-`
-}
-
-// HelpTemplate return help template for the command.
-func (c *Command) HelpTemplate() string {
- if c.helpTemplate != "" {
- return c.helpTemplate
- }
-
- if c.HasParent() {
- return c.parent.HelpTemplate()
- }
- return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}
-
-{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`
-}
-
-func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {
- flag := fs.Lookup(name)
- if flag == nil {
- return false
- }
- return flag.NoOptDefVal != ""
-}
-
-func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {
- if len(name) == 0 {
- return false
- }
-
- flag := fs.ShorthandLookup(name[:1])
- if flag == nil {
- return false
- }
- return flag.NoOptDefVal != ""
-}
-
-func stripFlags(args []string, c *Command) []string {
- if len(args) == 0 {
- return args
- }
- c.mergePersistentFlags()
-
- commands := []string{}
- flags := c.Flags()
-
-Loop:
- for len(args) > 0 {
- s := args[0]
- args = args[1:]
- switch {
- case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):
- // If '--flag arg' then
- // delete arg from args.
- fallthrough // (do the same as below)
- case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):
- // If '-f arg' then
- // delete 'arg' from args or break the loop if len(args) <= 1.
- if len(args) <= 1 {
- break Loop
- } else {
- args = args[1:]
- continue
- }
- case s != "" && !strings.HasPrefix(s, "-"):
- commands = append(commands, s)
- }
- }
-
- return commands
-}
-
-// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like
-// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).
-func argsMinusFirstX(args []string, x string) []string {
- for i, y := range args {
- if x == y {
- ret := []string{}
- ret = append(ret, args[:i]...)
- ret = append(ret, args[i+1:]...)
- return ret
- }
- }
- return args
-}
-
-func isFlagArg(arg string) bool {
- return ((len(arg) >= 3 && arg[1] == '-') ||
- (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))
-}
-
-// Find the target command given the args and command tree
-// Meant to be run on the highest node. Only searches down.
-func (c *Command) Find(args []string) (*Command, []string, error) {
- var innerfind func(*Command, []string) (*Command, []string)
-
- innerfind = func(c *Command, innerArgs []string) (*Command, []string) {
- argsWOflags := stripFlags(innerArgs, c)
- if len(argsWOflags) == 0 {
- return c, innerArgs
- }
- nextSubCmd := argsWOflags[0]
-
- cmd := c.findNext(nextSubCmd)
- if cmd != nil {
- return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))
- }
- return c, innerArgs
- }
-
- commandFound, a := innerfind(c, args)
- if commandFound.Args == nil {
- return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound))
- }
- return commandFound, a, nil
-}
-
-func (c *Command) findSuggestions(arg string) string {
- if c.DisableSuggestions {
- return ""
- }
- if c.SuggestionsMinimumDistance <= 0 {
- c.SuggestionsMinimumDistance = 2
- }
- suggestionsString := ""
- if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {
- suggestionsString += "\n\nDid you mean this?\n"
- for _, s := range suggestions {
- suggestionsString += fmt.Sprintf("\t%v\n", s)
- }
- }
- return suggestionsString
-}
-
-func (c *Command) findNext(next string) *Command {
- matches := make([]*Command, 0)
- for _, cmd := range c.commands {
- if cmd.Name() == next || cmd.HasAlias(next) {
- return cmd
- }
- if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) {
- matches = append(matches, cmd)
- }
- }
-
- if len(matches) == 1 {
- return matches[0]
- }
- return nil
-}
-
-// Traverse the command tree to find the command, and parse args for
-// each parent.
-func (c *Command) Traverse(args []string) (*Command, []string, error) {
- flags := []string{}
- inFlag := false
-
- for i, arg := range args {
- switch {
- // A long flag with a space separated value
- case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="):
- // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'
- inFlag = !hasNoOptDefVal(arg[2:], c.Flags())
- flags = append(flags, arg)
- continue
- // A short flag with a space separated value
- case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()):
- inFlag = true
- flags = append(flags, arg)
- continue
- // The value for a flag
- case inFlag:
- inFlag = false
- flags = append(flags, arg)
- continue
- // A flag without a value, or with an `=` separated value
- case isFlagArg(arg):
- flags = append(flags, arg)
- continue
- }
-
- cmd := c.findNext(arg)
- if cmd == nil {
- return c, args, nil
- }
-
- if err := c.ParseFlags(flags); err != nil {
- return nil, args, err
- }
- return cmd.Traverse(args[i+1:])
- }
- return c, args, nil
-}
-
-// SuggestionsFor provides suggestions for the typedName.
-func (c *Command) SuggestionsFor(typedName string) []string {
- suggestions := []string{}
- for _, cmd := range c.commands {
- if cmd.IsAvailableCommand() {
- levenshteinDistance := ld(typedName, cmd.Name(), true)
- suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance
- suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))
- if suggestByLevenshtein || suggestByPrefix {
- suggestions = append(suggestions, cmd.Name())
- }
- for _, explicitSuggestion := range cmd.SuggestFor {
- if strings.EqualFold(typedName, explicitSuggestion) {
- suggestions = append(suggestions, cmd.Name())
- }
- }
- }
- }
- return suggestions
-}
-
-// VisitParents visits all parents of the command and invokes fn on each parent.
-func (c *Command) VisitParents(fn func(*Command)) {
- if c.HasParent() {
- fn(c.Parent())
- c.Parent().VisitParents(fn)
- }
-}
-
-// Root finds root command.
-func (c *Command) Root() *Command {
- if c.HasParent() {
- return c.Parent().Root()
- }
- return c
-}
-
-// ArgsLenAtDash will return the length of f.Args at the moment when a -- was
-// found during arg parsing. This allows your program to know which args were
-// before the -- and which came after. (Description from
-// https://godoc.org/github.com/spf13/pflag#FlagSet.ArgsLenAtDash).
-func (c *Command) ArgsLenAtDash() int {
- return c.Flags().ArgsLenAtDash()
-}
-
-func (c *Command) execute(a []string) (err error) {
- if c == nil {
- return fmt.Errorf("Called Execute() on a nil Command")
- }
-
- if len(c.Deprecated) > 0 {
- c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)
- }
-
- // initialize help flag as the last point possible to allow for user
- // overriding
- c.InitDefaultHelpFlag()
-
- err = c.ParseFlags(a)
- if err != nil {
- return c.FlagErrorFunc()(c, err)
- }
-
- // If help is called, regardless of other flags, return we want help.
- // Also say we need help if the command isn't runnable.
- helpVal, err := c.Flags().GetBool("help")
- if err != nil {
- // should be impossible to get here as we always declare a help
- // flag in InitDefaultHelpFlag()
- c.Println("\"help\" flag declared as non-bool. Please correct your code")
- return err
- }
-
- if helpVal || !c.Runnable() {
- return flag.ErrHelp
- }
-
- c.preRun()
-
- argWoFlags := c.Flags().Args()
- if c.DisableFlagParsing {
- argWoFlags = a
- }
-
- if err := c.ValidateArgs(argWoFlags); err != nil {
- return err
- }
-
- for p := c; p != nil; p = p.Parent() {
- if p.PersistentPreRunE != nil {
- if err := p.PersistentPreRunE(c, argWoFlags); err != nil {
- return err
- }
- break
- } else if p.PersistentPreRun != nil {
- p.PersistentPreRun(c, argWoFlags)
- break
- }
- }
- if c.PreRunE != nil {
- if err := c.PreRunE(c, argWoFlags); err != nil {
- return err
- }
- } else if c.PreRun != nil {
- c.PreRun(c, argWoFlags)
- }
-
- if err := c.validateRequiredFlags(); err != nil {
- return err
- }
- if c.RunE != nil {
- if err := c.RunE(c, argWoFlags); err != nil {
- return err
- }
- } else {
- c.Run(c, argWoFlags)
- }
- if c.PostRunE != nil {
- if err := c.PostRunE(c, argWoFlags); err != nil {
- return err
- }
- } else if c.PostRun != nil {
- c.PostRun(c, argWoFlags)
- }
- for p := c; p != nil; p = p.Parent() {
- if p.PersistentPostRunE != nil {
- if err := p.PersistentPostRunE(c, argWoFlags); err != nil {
- return err
- }
- break
- } else if p.PersistentPostRun != nil {
- p.PersistentPostRun(c, argWoFlags)
- break
- }
- }
-
- return nil
-}
-
-func (c *Command) preRun() {
- for _, x := range initializers {
- x()
- }
-}
-
-// Execute uses the args (os.Args[1:] by default)
-// and run through the command tree finding appropriate matches
-// for commands and then corresponding flags.
-func (c *Command) Execute() error {
- _, err := c.ExecuteC()
- return err
-}
-
-// ExecuteC executes the command.
-func (c *Command) ExecuteC() (cmd *Command, err error) {
- // Regardless of what command execute is called on, run on Root only
- if c.HasParent() {
- return c.Root().ExecuteC()
- }
-
- // windows hook
- if preExecHookFn != nil {
- preExecHookFn(c)
- }
-
- // initialize help as the last point possible to allow for user
- // overriding
- c.InitDefaultHelpCmd()
-
- var args []string
-
- // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155
- if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {
- args = os.Args[1:]
- } else {
- args = c.args
- }
-
- var flags []string
- if c.TraverseChildren {
- cmd, flags, err = c.Traverse(args)
- } else {
- cmd, flags, err = c.Find(args)
- }
- if err != nil {
- // If found parse to a subcommand and then failed, talk about the subcommand
- if cmd != nil {
- c = cmd
- }
- if !c.SilenceErrors {
- c.Println("Error:", err.Error())
- c.Printf("Run '%v --help' for usage.\n", c.CommandPath())
- }
- return c, err
- }
-
- err = cmd.execute(flags)
- if err != nil {
- // Always show help if requested, even if SilenceErrors is in
- // effect
- if err == flag.ErrHelp {
- cmd.HelpFunc()(cmd, args)
- return cmd, nil
- }
-
- // If root command has SilentErrors flagged,
- // all subcommands should respect it
- if !cmd.SilenceErrors && !c.SilenceErrors {
- c.Println("Error:", err.Error())
- }
-
- // If root command has SilentUsage flagged,
- // all subcommands should respect it
- if !cmd.SilenceUsage && !c.SilenceUsage {
- c.Println(cmd.UsageString())
- }
- }
- return cmd, err
-}
-
-func (c *Command) ValidateArgs(args []string) error {
- if c.Args == nil {
- return nil
- }
- return c.Args(c, args)
-}
-
-func (c *Command) validateRequiredFlags() error {
- flags := c.Flags()
- missingFlagNames := []string{}
- flags.VisitAll(func(pflag *flag.Flag) {
- requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag]
- if !found {
- return
- }
- if (requiredAnnotation[0] == "true") && !pflag.Changed {
- missingFlagNames = append(missingFlagNames, pflag.Name)
- }
- })
-
- if len(missingFlagNames) > 0 {
- return fmt.Errorf(`Required flag(s) "%s" have/has not been set`, strings.Join(missingFlagNames, `", "`))
- }
- return nil
-}
-
-// InitDefaultHelpFlag adds default help flag to c.
-// It is called automatically by executing the c or by calling help and usage.
-// If c already has help flag, it will do nothing.
-func (c *Command) InitDefaultHelpFlag() {
- c.mergePersistentFlags()
- if c.Flags().Lookup("help") == nil {
- usage := "help for "
- if c.Name() == "" {
- usage += "this command"
- } else {
- usage += c.Name()
- }
- c.Flags().BoolP("help", "h", false, usage)
- }
-}
-
-// InitDefaultHelpCmd adds default help command to c.
-// It is called automatically by executing the c or by calling help and usage.
-// If c already has help command or c has no subcommands, it will do nothing.
-func (c *Command) InitDefaultHelpCmd() {
- if !c.HasSubCommands() {
- return
- }
-
- if c.helpCommand == nil {
- c.helpCommand = &Command{
- Use: "help [command]",
- Short: "Help about any command",
- Long: `Help provides help for any command in the application.
-Simply type ` + c.Name() + ` help [path to command] for full details.`,
-
- Run: func(c *Command, args []string) {
- cmd, _, e := c.Root().Find(args)
- if cmd == nil || e != nil {
- c.Printf("Unknown help topic %#q\n", args)
- c.Root().Usage()
- } else {
- cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown
- cmd.Help()
- }
- },
- }
- }
- c.RemoveCommand(c.helpCommand)
- c.AddCommand(c.helpCommand)
-}
-
-// ResetCommands used for testing.
-func (c *Command) ResetCommands() {
- c.parent = nil
- c.commands = nil
- c.helpCommand = nil
- c.parentsPflags = nil
-}
-
-// Sorts commands by their names.
-type commandSorterByName []*Command
-
-func (c commandSorterByName) Len() int { return len(c) }
-func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
-func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }
-
-// Commands returns a sorted slice of child commands.
-func (c *Command) Commands() []*Command {
- // do not sort commands if it already sorted or sorting was disabled
- if EnableCommandSorting && !c.commandsAreSorted {
- sort.Sort(commandSorterByName(c.commands))
- c.commandsAreSorted = true
- }
- return c.commands
-}
-
-// AddCommand adds one or more commands to this parent command.
-func (c *Command) AddCommand(cmds ...*Command) {
- for i, x := range cmds {
- if cmds[i] == c {
- panic("Command can't be a child of itself")
- }
- cmds[i].parent = c
- // update max lengths
- usageLen := len(x.Use)
- if usageLen > c.commandsMaxUseLen {
- c.commandsMaxUseLen = usageLen
- }
- commandPathLen := len(x.CommandPath())
- if commandPathLen > c.commandsMaxCommandPathLen {
- c.commandsMaxCommandPathLen = commandPathLen
- }
- nameLen := len(x.Name())
- if nameLen > c.commandsMaxNameLen {
- c.commandsMaxNameLen = nameLen
- }
- // If global normalization function exists, update all children
- if c.globNormFunc != nil {
- x.SetGlobalNormalizationFunc(c.globNormFunc)
- }
- c.commands = append(c.commands, x)
- c.commandsAreSorted = false
- }
-}
-
-// RemoveCommand removes one or more commands from a parent command.
-func (c *Command) RemoveCommand(cmds ...*Command) {
- commands := []*Command{}
-main:
- for _, command := range c.commands {
- for _, cmd := range cmds {
- if command == cmd {
- command.parent = nil
- continue main
- }
- }
- commands = append(commands, command)
- }
- c.commands = commands
- // recompute all lengths
- c.commandsMaxUseLen = 0
- c.commandsMaxCommandPathLen = 0
- c.commandsMaxNameLen = 0
- for _, command := range c.commands {
- usageLen := len(command.Use)
- if usageLen > c.commandsMaxUseLen {
- c.commandsMaxUseLen = usageLen
- }
- commandPathLen := len(command.CommandPath())
- if commandPathLen > c.commandsMaxCommandPathLen {
- c.commandsMaxCommandPathLen = commandPathLen
- }
- nameLen := len(command.Name())
- if nameLen > c.commandsMaxNameLen {
- c.commandsMaxNameLen = nameLen
- }
- }
-}
-
-// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.
-func (c *Command) Print(i ...interface{}) {
- fmt.Fprint(c.OutOrStderr(), i...)
-}
-
-// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.
-func (c *Command) Println(i ...interface{}) {
- c.Print(fmt.Sprintln(i...))
-}
-
-// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.
-func (c *Command) Printf(format string, i ...interface{}) {
- c.Print(fmt.Sprintf(format, i...))
-}
-
-// CommandPath returns the full path to this command.
-func (c *Command) CommandPath() string {
- if c.HasParent() {
- return c.Parent().CommandPath() + " " + c.Name()
- }
- return c.Name()
-}
-
-// UseLine puts out the full usage for a given command (including parents).
-func (c *Command) UseLine() string {
- var useline string
- if c.HasParent() {
- useline = c.parent.CommandPath() + " " + c.Use
- } else {
- useline = c.Use
- }
- if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {
- useline += " [flags]"
- }
- return useline
-}
-
-// DebugFlags used to determine which flags have been assigned to which commands
-// and which persist.
-func (c *Command) DebugFlags() {
- c.Println("DebugFlags called on", c.Name())
- var debugflags func(*Command)
-
- debugflags = func(x *Command) {
- if x.HasFlags() || x.HasPersistentFlags() {
- c.Println(x.Name())
- }
- if x.HasFlags() {
- x.flags.VisitAll(func(f *flag.Flag) {
- if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil {
- c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")
- } else {
- c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")
- }
- })
- }
- if x.HasPersistentFlags() {
- x.pflags.VisitAll(func(f *flag.Flag) {
- if x.HasFlags() {
- if x.flags.Lookup(f.Name) == nil {
- c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")
- }
- } else {
- c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")
- }
- })
- }
- c.Println(x.flagErrorBuf)
- if x.HasSubCommands() {
- for _, y := range x.commands {
- debugflags(y)
- }
- }
- }
-
- debugflags(c)
-}
-
-// Name returns the command's name: the first word in the use line.
-func (c *Command) Name() string {
- name := c.Use
- i := strings.Index(name, " ")
- if i >= 0 {
- name = name[:i]
- }
- return name
-}
-
-// HasAlias determines if a given string is an alias of the command.
-func (c *Command) HasAlias(s string) bool {
- for _, a := range c.Aliases {
- if a == s {
- return true
- }
- }
- return false
-}
-
-// hasNameOrAliasPrefix returns true if the Name or any of aliases start
-// with prefix
-func (c *Command) hasNameOrAliasPrefix(prefix string) bool {
- if strings.HasPrefix(c.Name(), prefix) {
- return true
- }
- for _, alias := range c.Aliases {
- if strings.HasPrefix(alias, prefix) {
- return true
- }
- }
- return false
-}
-
-// NameAndAliases returns a list of the command name and all aliases
-func (c *Command) NameAndAliases() string {
- return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")
-}
-
-// HasExample determines if the command has example.
-func (c *Command) HasExample() bool {
- return len(c.Example) > 0
-}
-
-// Runnable determines if the command is itself runnable.
-func (c *Command) Runnable() bool {
- return c.Run != nil || c.RunE != nil
-}
-
-// HasSubCommands determines if the command has children commands.
-func (c *Command) HasSubCommands() bool {
- return len(c.commands) > 0
-}
-
-// IsAvailableCommand determines if a command is available as a non-help command
-// (this includes all non deprecated/hidden commands).
-func (c *Command) IsAvailableCommand() bool {
- if len(c.Deprecated) != 0 || c.Hidden {
- return false
- }
-
- if c.HasParent() && c.Parent().helpCommand == c {
- return false
- }
-
- if c.Runnable() || c.HasAvailableSubCommands() {
- return true
- }
-
- return false
-}
-
-// IsAdditionalHelpTopicCommand determines if a command is an additional
-// help topic command; additional help topic command is determined by the
-// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that
-// are runnable/hidden/deprecated.
-// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.
-func (c *Command) IsAdditionalHelpTopicCommand() bool {
- // if a command is runnable, deprecated, or hidden it is not a 'help' command
- if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {
- return false
- }
-
- // if any non-help sub commands are found, the command is not a 'help' command
- for _, sub := range c.commands {
- if !sub.IsAdditionalHelpTopicCommand() {
- return false
- }
- }
-
- // the command either has no sub commands, or no non-help sub commands
- return true
-}
-
-// HasHelpSubCommands determines if a command has any available 'help' sub commands
-// that need to be shown in the usage/help default template under 'additional help
-// topics'.
-func (c *Command) HasHelpSubCommands() bool {
- // return true on the first found available 'help' sub command
- for _, sub := range c.commands {
- if sub.IsAdditionalHelpTopicCommand() {
- return true
- }
- }
-
- // the command either has no sub commands, or no available 'help' sub commands
- return false
-}
-
-// HasAvailableSubCommands determines if a command has available sub commands that
-// need to be shown in the usage/help default template under 'available commands'.
-func (c *Command) HasAvailableSubCommands() bool {
- // return true on the first found available (non deprecated/help/hidden)
- // sub command
- for _, sub := range c.commands {
- if sub.IsAvailableCommand() {
- return true
- }
- }
-
- // the command either has no sub comamnds, or no available (non deprecated/help/hidden)
- // sub commands
- return false
-}
-
-// HasParent determines if the command is a child command.
-func (c *Command) HasParent() bool {
- return c.parent != nil
-}
-
-// GlobalNormalizationFunc returns the global normalization function or nil if doesn't exists.
-func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {
- return c.globNormFunc
-}
-
-// Flags returns the complete FlagSet that applies
-// to this command (local and persistent declared here and by all parents).
-func (c *Command) Flags() *flag.FlagSet {
- if c.flags == nil {
- c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
- if c.flagErrorBuf == nil {
- c.flagErrorBuf = new(bytes.Buffer)
- }
- c.flags.SetOutput(c.flagErrorBuf)
- }
-
- return c.flags
-}
-
-// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.
-func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {
- persistentFlags := c.PersistentFlags()
-
- out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
- c.LocalFlags().VisitAll(func(f *flag.Flag) {
- if persistentFlags.Lookup(f.Name) == nil {
- out.AddFlag(f)
- }
- })
- return out
-}
-
-// LocalFlags returns the local FlagSet specifically set in the current command.
-func (c *Command) LocalFlags() *flag.FlagSet {
- c.mergePersistentFlags()
-
- if c.lflags == nil {
- c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
- if c.flagErrorBuf == nil {
- c.flagErrorBuf = new(bytes.Buffer)
- }
- c.lflags.SetOutput(c.flagErrorBuf)
- }
- c.lflags.SortFlags = c.Flags().SortFlags
- if c.globNormFunc != nil {
- c.lflags.SetNormalizeFunc(c.globNormFunc)
- }
-
- addToLocal := func(f *flag.Flag) {
- if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil {
- c.lflags.AddFlag(f)
- }
- }
- c.Flags().VisitAll(addToLocal)
- c.PersistentFlags().VisitAll(addToLocal)
- return c.lflags
-}
-
-// InheritedFlags returns all flags which were inherited from parents commands.
-func (c *Command) InheritedFlags() *flag.FlagSet {
- c.mergePersistentFlags()
-
- if c.iflags == nil {
- c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
- if c.flagErrorBuf == nil {
- c.flagErrorBuf = new(bytes.Buffer)
- }
- c.iflags.SetOutput(c.flagErrorBuf)
- }
-
- local := c.LocalFlags()
- if c.globNormFunc != nil {
- c.iflags.SetNormalizeFunc(c.globNormFunc)
- }
-
- c.parentsPflags.VisitAll(func(f *flag.Flag) {
- if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {
- c.iflags.AddFlag(f)
- }
- })
- return c.iflags
-}
-
-// NonInheritedFlags returns all flags which were not inherited from parent commands.
-func (c *Command) NonInheritedFlags() *flag.FlagSet {
- return c.LocalFlags()
-}
-
-// PersistentFlags returns the persistent FlagSet specifically set in the current command.
-func (c *Command) PersistentFlags() *flag.FlagSet {
- if c.pflags == nil {
- c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
- if c.flagErrorBuf == nil {
- c.flagErrorBuf = new(bytes.Buffer)
- }
- c.pflags.SetOutput(c.flagErrorBuf)
- }
- return c.pflags
-}
-
-// ResetFlags is used in testing.
-func (c *Command) ResetFlags() {
- c.flagErrorBuf = new(bytes.Buffer)
- c.flagErrorBuf.Reset()
- c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
- c.flags.SetOutput(c.flagErrorBuf)
- c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
- c.pflags.SetOutput(c.flagErrorBuf)
-
- c.lflags = nil
- c.iflags = nil
- c.parentsPflags = nil
-}
-
-// HasFlags checks if the command contains any flags (local plus persistent from the entire structure).
-func (c *Command) HasFlags() bool {
- return c.Flags().HasFlags()
-}
-
-// HasPersistentFlags checks if the command contains persistent flags.
-func (c *Command) HasPersistentFlags() bool {
- return c.PersistentFlags().HasFlags()
-}
-
-// HasLocalFlags checks if the command has flags specifically declared locally.
-func (c *Command) HasLocalFlags() bool {
- return c.LocalFlags().HasFlags()
-}
-
-// HasInheritedFlags checks if the command has flags inherited from its parent command.
-func (c *Command) HasInheritedFlags() bool {
- return c.InheritedFlags().HasFlags()
-}
-
-// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire
-// structure) which are not hidden or deprecated.
-func (c *Command) HasAvailableFlags() bool {
- return c.Flags().HasAvailableFlags()
-}
-
-// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.
-func (c *Command) HasAvailablePersistentFlags() bool {
- return c.PersistentFlags().HasAvailableFlags()
-}
-
-// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden
-// or deprecated.
-func (c *Command) HasAvailableLocalFlags() bool {
- return c.LocalFlags().HasAvailableFlags()
-}
-
-// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are
-// not hidden or deprecated.
-func (c *Command) HasAvailableInheritedFlags() bool {
- return c.InheritedFlags().HasAvailableFlags()
-}
-
-// Flag climbs up the command tree looking for matching flag.
-func (c *Command) Flag(name string) (flag *flag.Flag) {
- flag = c.Flags().Lookup(name)
-
- if flag == nil {
- flag = c.persistentFlag(name)
- }
-
- return
-}
-
-// Recursively find matching persistent flag.
-func (c *Command) persistentFlag(name string) (flag *flag.Flag) {
- if c.HasPersistentFlags() {
- flag = c.PersistentFlags().Lookup(name)
- }
-
- if flag == nil {
- c.updateParentsPflags()
- flag = c.parentsPflags.Lookup(name)
- }
- return
-}
-
-// ParseFlags parses persistent flag tree and local flags.
-func (c *Command) ParseFlags(args []string) error {
- if c.DisableFlagParsing {
- return nil
- }
-
- if c.flagErrorBuf == nil {
- c.flagErrorBuf = new(bytes.Buffer)
- }
- beforeErrorBufLen := c.flagErrorBuf.Len()
- c.mergePersistentFlags()
- err := c.Flags().Parse(args)
- // Print warnings if they occurred (e.g. deprecated flag messages).
- if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {
- c.Print(c.flagErrorBuf.String())
- }
-
- return err
-}
-
-// Parent returns a commands parent command.
-func (c *Command) Parent() *Command {
- return c.parent
-}
-
-// mergePersistentFlags merges c.PersistentFlags() to c.Flags()
-// and adds missing persistent flags of all parents.
-func (c *Command) mergePersistentFlags() {
- c.updateParentsPflags()
- c.Flags().AddFlagSet(c.PersistentFlags())
- c.Flags().AddFlagSet(c.parentsPflags)
-}
-
-// updateParentsPflags updates c.parentsPflags by adding
-// new persistent flags of all parents.
-// If c.parentsPflags == nil, it makes new.
-func (c *Command) updateParentsPflags() {
- if c.parentsPflags == nil {
- c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
- c.parentsPflags.SetOutput(c.flagErrorBuf)
- c.parentsPflags.SortFlags = false
- }
-
- if c.globNormFunc != nil {
- c.parentsPflags.SetNormalizeFunc(c.globNormFunc)
- }
-
- c.Root().PersistentFlags().AddFlagSet(flag.CommandLine)
-
- c.VisitParents(func(parent *Command) {
- c.parentsPflags.AddFlagSet(parent.PersistentFlags())
- })
-}
diff --git a/vendor/github.com/spf13/cobra/command_notwin.go b/vendor/github.com/spf13/cobra/command_notwin.go
deleted file mode 100644
index 6159c1c..0000000
--- a/vendor/github.com/spf13/cobra/command_notwin.go
+++ /dev/null
@@ -1,5 +0,0 @@
-// +build !windows
-
-package cobra
-
-var preExecHookFn func(*Command)
diff --git a/vendor/github.com/spf13/cobra/command_test.go b/vendor/github.com/spf13/cobra/command_test.go
deleted file mode 100644
index dda355f..0000000
--- a/vendor/github.com/spf13/cobra/command_test.go
+++ /dev/null
@@ -1,526 +0,0 @@
-package cobra
-
-import (
- "bytes"
- "fmt"
- "os"
- "reflect"
- "strings"
- "testing"
-
- "github.com/spf13/pflag"
-)
-
-// test to ensure hidden commands run as intended
-func TestHiddenCommandExecutes(t *testing.T) {
-
- // ensure that outs does not already equal what the command will be setting it
- // to, if it did this test would not actually be testing anything...
- if outs == "hidden" {
- t.Errorf("outs should NOT EQUAL hidden")
- }
-
- cmdHidden.Execute()
-
- // upon running the command, the value of outs should now be 'hidden'
- if outs != "hidden" {
- t.Errorf("Hidden command failed to run!")
- }
-}
-
-// test to ensure hidden commands do not show up in usage/help text
-func TestHiddenCommandIsHidden(t *testing.T) {
- if cmdHidden.IsAvailableCommand() {
- t.Errorf("Hidden command found!")
- }
-}
-
-func TestStripFlags(t *testing.T) {
- tests := []struct {
- input []string
- output []string
- }{
- {
- []string{"foo", "bar"},
- []string{"foo", "bar"},
- },
- {
- []string{"foo", "--bar", "-b"},
- []string{"foo"},
- },
- {
- []string{"-b", "foo", "--bar", "bar"},
- []string{},
- },
- {
- []string{"-i10", "echo"},
- []string{"echo"},
- },
- {
- []string{"-i=10", "echo"},
- []string{"echo"},
- },
- {
- []string{"--int=100", "echo"},
- []string{"echo"},
- },
- {
- []string{"-ib", "echo", "-bfoo", "baz"},
- []string{"echo", "baz"},
- },
- {
- []string{"-i=baz", "bar", "-i", "foo", "blah"},
- []string{"bar", "blah"},
- },
- {
- []string{"--int=baz", "-bbar", "-i", "foo", "blah"},
- []string{"blah"},
- },
- {
- []string{"--cat", "bar", "-i", "foo", "blah"},
- []string{"bar", "blah"},
- },
- {
- []string{"-c", "bar", "-i", "foo", "blah"},
- []string{"bar", "blah"},
- },
- {
- []string{"--persist", "bar"},
- []string{"bar"},
- },
- {
- []string{"-p", "bar"},
- []string{"bar"},
- },
- }
-
- cmdPrint := &Command{
- Use: "print [string to print]",
- Short: "Print anything to the screen",
- Long: `an utterly useless command for testing.`,
- Run: func(cmd *Command, args []string) {
- tp = args
- },
- }
-
- var flagi int
- var flagstr string
- var flagbool bool
- cmdPrint.PersistentFlags().BoolVarP(&flagbool, "persist", "p", false, "help for persistent one")
- cmdPrint.Flags().IntVarP(&flagi, "int", "i", 345, "help message for flag int")
- cmdPrint.Flags().StringVarP(&flagstr, "bar", "b", "bar", "help message for flag string")
- cmdPrint.Flags().BoolVarP(&flagbool, "cat", "c", false, "help message for flag bool")
-
- for _, test := range tests {
- output := stripFlags(test.input, cmdPrint)
- if !reflect.DeepEqual(test.output, output) {
- t.Errorf("expected: %v, got: %v", test.output, output)
- }
- }
-}
-
-func TestDisableFlagParsing(t *testing.T) {
- targs := []string{}
- cmdPrint := &Command{
- DisableFlagParsing: true,
- Run: func(cmd *Command, args []string) {
- targs = args
- },
- }
- args := []string{"cmd", "-v", "-race", "-file", "foo.go"}
- cmdPrint.SetArgs(args)
- err := cmdPrint.Execute()
- if err != nil {
- t.Error(err)
- }
- if !reflect.DeepEqual(args, targs) {
- t.Errorf("expected: %v, got: %v", args, targs)
- }
-}
-
-func TestInitHelpFlagMergesFlags(t *testing.T) {
- usage := "custom flag"
- baseCmd := Command{Use: "testcmd"}
- baseCmd.PersistentFlags().Bool("help", false, usage)
- cmd := Command{Use: "do"}
- baseCmd.AddCommand(&cmd)
-
- cmd.InitDefaultHelpFlag()
- actual := cmd.Flags().Lookup("help").Usage
- if actual != usage {
- t.Fatalf("Expected the help flag from the base command with usage '%s', but got the default with usage '%s'", usage, actual)
- }
-}
-
-func TestCommandsAreSorted(t *testing.T) {
- EnableCommandSorting = true
-
- originalNames := []string{"middle", "zlast", "afirst"}
- expectedNames := []string{"afirst", "middle", "zlast"}
-
- var tmpCommand = &Command{Use: "tmp"}
-
- for _, name := range originalNames {
- tmpCommand.AddCommand(&Command{Use: name})
- }
-
- for i, c := range tmpCommand.Commands() {
- if expectedNames[i] != c.Name() {
- t.Errorf("expected: %s, got: %s", expectedNames[i], c.Name())
- }
- }
-
- EnableCommandSorting = true
-}
-
-func TestEnableCommandSortingIsDisabled(t *testing.T) {
- EnableCommandSorting = false
-
- originalNames := []string{"middle", "zlast", "afirst"}
-
- var tmpCommand = &Command{Use: "tmp"}
-
- for _, name := range originalNames {
- tmpCommand.AddCommand(&Command{Use: name})
- }
-
- for i, c := range tmpCommand.Commands() {
- if originalNames[i] != c.Name() {
- t.Errorf("expected: %s, got: %s", originalNames[i], c.Name())
- }
- }
-
- EnableCommandSorting = true
-}
-
-func TestSetOutput(t *testing.T) {
- cmd := &Command{}
- cmd.SetOutput(nil)
- if out := cmd.OutOrStdout(); out != os.Stdout {
- t.Fatalf("expected setting output to nil to revert back to stdout, got %v", out)
- }
-}
-
-func TestFlagErrorFunc(t *testing.T) {
- cmd := &Command{
- Use: "print",
- RunE: func(cmd *Command, args []string) error {
- return nil
- },
- }
- expectedFmt := "This is expected: %s"
-
- cmd.SetFlagErrorFunc(func(c *Command, err error) error {
- return fmt.Errorf(expectedFmt, err)
- })
- cmd.SetArgs([]string{"--bogus-flag"})
- cmd.SetOutput(new(bytes.Buffer))
-
- err := cmd.Execute()
-
- expected := fmt.Sprintf(expectedFmt, "unknown flag: --bogus-flag")
- if err.Error() != expected {
- t.Errorf("expected %v, got %v", expected, err.Error())
- }
-}
-
-// TestSortedFlags checks,
-// if cmd.LocalFlags() is unsorted when cmd.Flags().SortFlags set to false.
-// Related to https://github.com/spf13/cobra/issues/404.
-func TestSortedFlags(t *testing.T) {
- cmd := &Command{}
- cmd.Flags().SortFlags = false
- names := []string{"C", "B", "A", "D"}
- for _, name := range names {
- cmd.Flags().Bool(name, false, "")
- }
-
- i := 0
- cmd.LocalFlags().VisitAll(func(f *pflag.Flag) {
- if i == len(names) {
- return
- }
- if isStringInStringSlice(f.Name, names) {
- if names[i] != f.Name {
- t.Errorf("Incorrect order. Expected %v, got %v", names[i], f.Name)
- }
- i++
- }
- })
-}
-
-// contains checks, if s is in ss.
-func isStringInStringSlice(s string, ss []string) bool {
- for _, v := range ss {
- if v == s {
- return true
- }
- }
- return false
-}
-
-// TestHelpFlagInHelp checks,
-// if '--help' flag is shown in help for child (executing `parent help child`),
-// that has no other flags.
-// Related to https://github.com/spf13/cobra/issues/302.
-func TestHelpFlagInHelp(t *testing.T) {
- output := new(bytes.Buffer)
- parent := &Command{Use: "parent", Run: func(*Command, []string) {}}
- parent.SetOutput(output)
-
- child := &Command{Use: "child", Run: func(*Command, []string) {}}
- parent.AddCommand(child)
-
- parent.SetArgs([]string{"help", "child"})
- err := parent.Execute()
- if err != nil {
- t.Fatal(err)
- }
-
- if !strings.Contains(output.String(), "[flags]") {
- t.Errorf("\nExpecting to contain: %v\nGot: %v", "[flags]", output.String())
- }
-}
-
-// TestMergeCommandLineToFlags checks,
-// if pflag.CommandLine is correctly merged to c.Flags() after first call
-// of c.mergePersistentFlags.
-// Related to https://github.com/spf13/cobra/issues/443.
-func TestMergeCommandLineToFlags(t *testing.T) {
- pflag.Bool("boolflag", false, "")
- c := &Command{Use: "c", Run: func(*Command, []string) {}}
- c.mergePersistentFlags()
- if c.Flags().Lookup("boolflag") == nil {
- t.Fatal("Expecting to have flag from CommandLine in c.Flags()")
- }
-
- // Reset pflag.CommandLine flagset.
- pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)
-}
-
-// TestUseDeprecatedFlags checks,
-// if cobra.Execute() prints a message, if a deprecated flag is used.
-// Related to https://github.com/spf13/cobra/issues/463.
-func TestUseDeprecatedFlags(t *testing.T) {
- c := &Command{Use: "c", Run: func(*Command, []string) {}}
- output := new(bytes.Buffer)
- c.SetOutput(output)
- c.Flags().BoolP("deprecated", "d", false, "deprecated flag")
- c.Flags().MarkDeprecated("deprecated", "This flag is deprecated")
-
- c.SetArgs([]string{"c", "-d"})
- if err := c.Execute(); err != nil {
- t.Error("Unexpected error:", err)
- }
- if !strings.Contains(output.String(), "This flag is deprecated") {
- t.Errorf("Expected to contain deprecated message, but got %q", output.String())
- }
-}
-
-// TestSetHelpCommand checks, if SetHelpCommand works correctly.
-func TestSetHelpCommand(t *testing.T) {
- c := &Command{Use: "c", Run: func(*Command, []string) {}}
- output := new(bytes.Buffer)
- c.SetOutput(output)
- c.SetArgs([]string{"help"})
-
- // Help will not be shown, if c has no subcommands.
- c.AddCommand(&Command{
- Use: "empty",
- Run: func(cmd *Command, args []string) {},
- })
-
- correctMessage := "WORKS"
- c.SetHelpCommand(&Command{
- Use: "help [command]",
- Short: "Help about any command",
- Long: `Help provides help for any command in the application.
- Simply type ` + c.Name() + ` help [path to command] for full details.`,
- Run: func(c *Command, args []string) { c.Print(correctMessage) },
- })
-
- if err := c.Execute(); err != nil {
- t.Error("Unexpected error:", err)
- }
-
- if output.String() != correctMessage {
- t.Errorf("Expected to contain %q message, but got %q", correctMessage, output.String())
- }
-}
-
-func TestTraverseWithParentFlags(t *testing.T) {
- cmd := &Command{
- Use: "do",
- TraverseChildren: true,
- }
- cmd.Flags().String("foo", "", "foo things")
- cmd.Flags().BoolP("goo", "g", false, "foo things")
-
- sub := &Command{Use: "next"}
- sub.Flags().String("add", "", "add things")
- cmd.AddCommand(sub)
-
- c, args, err := cmd.Traverse([]string{"-g", "--foo", "ok", "next", "--add"})
- if err != nil {
- t.Fatalf("Expected no error: %s", err)
- }
- if len(args) != 1 && args[0] != "--add" {
- t.Fatalf("wrong args %s", args)
- }
- if c.Name() != sub.Name() {
- t.Fatalf("wrong command %q expected %q", c.Name(), sub.Name())
- }
-}
-
-func TestTraverseNoParentFlags(t *testing.T) {
- cmd := &Command{
- Use: "do",
- TraverseChildren: true,
- }
- cmd.Flags().String("foo", "", "foo things")
-
- sub := &Command{Use: "next"}
- sub.Flags().String("add", "", "add things")
- cmd.AddCommand(sub)
-
- c, args, err := cmd.Traverse([]string{"next"})
- if err != nil {
- t.Fatalf("Expected no error: %s", err)
- }
- if len(args) != 0 {
- t.Fatalf("wrong args %s", args)
- }
- if c.Name() != sub.Name() {
- t.Fatalf("wrong command %q expected %q", c.Name(), sub.Name())
- }
-}
-
-func TestTraverseWithBadParentFlags(t *testing.T) {
- cmd := &Command{
- Use: "do",
- TraverseChildren: true,
- }
- sub := &Command{Use: "next"}
- sub.Flags().String("add", "", "add things")
- cmd.AddCommand(sub)
-
- expected := "got unknown flag: --add"
-
- c, _, err := cmd.Traverse([]string{"--add", "ok", "next"})
- if err == nil || strings.Contains(err.Error(), expected) {
- t.Fatalf("Expected error %s got %s", expected, err)
- }
- if c != nil {
- t.Fatalf("Expected nil command")
- }
-}
-
-func TestTraverseWithBadChildFlag(t *testing.T) {
- cmd := &Command{
- Use: "do",
- TraverseChildren: true,
- }
- cmd.Flags().String("foo", "", "foo things")
-
- sub := &Command{Use: "next"}
- cmd.AddCommand(sub)
-
- // Expect no error because the last commands args shouldn't be parsed in
- // Traverse
- c, args, err := cmd.Traverse([]string{"next", "--add"})
- if err != nil {
- t.Fatalf("Expected no error: %s", err)
- }
- if len(args) != 1 && args[0] != "--add" {
- t.Fatalf("wrong args %s", args)
- }
- if c.Name() != sub.Name() {
- t.Fatalf("wrong command %q expected %q", c.Name(), sub.Name())
- }
-}
-
-func TestTraverseWithTwoSubcommands(t *testing.T) {
- cmd := &Command{
- Use: "do",
- TraverseChildren: true,
- }
-
- sub := &Command{
- Use: "sub",
- TraverseChildren: true,
- }
- cmd.AddCommand(sub)
-
- subsub := &Command{
- Use: "subsub",
- }
- sub.AddCommand(subsub)
-
- c, _, err := cmd.Traverse([]string{"sub", "subsub"})
- if err != nil {
- t.Fatalf("Expected no error: %s", err)
- }
- if c.Name() != subsub.Name() {
- t.Fatalf("wrong command %q expected %q", c.Name(), subsub.Name())
- }
-}
-
-func TestRequiredFlags(t *testing.T) {
- c := &Command{Use: "c", Run: func(*Command, []string) {}}
- output := new(bytes.Buffer)
- c.SetOutput(output)
- c.Flags().String("foo1", "", "required foo1")
- c.MarkFlagRequired("foo1")
- c.Flags().String("foo2", "", "required foo2")
- c.MarkFlagRequired("foo2")
- c.Flags().String("bar", "", "optional bar")
-
- expected := fmt.Sprintf("Required flag(s) %q, %q have/has not been set", "foo1", "foo2")
-
- if err := c.Execute(); err != nil {
- if err.Error() != expected {
- t.Errorf("expected %v, got %v", expected, err.Error())
- }
- }
-}
-
-func TestPersistentRequiredFlags(t *testing.T) {
- parent := &Command{Use: "parent", Run: func(*Command, []string) {}}
- output := new(bytes.Buffer)
- parent.SetOutput(output)
- parent.PersistentFlags().String("foo1", "", "required foo1")
- parent.MarkPersistentFlagRequired("foo1")
- parent.PersistentFlags().String("foo2", "", "required foo2")
- parent.MarkPersistentFlagRequired("foo2")
- parent.Flags().String("foo3", "", "optional foo3")
-
- child := &Command{Use: "child", Run: func(*Command, []string) {}}
- child.Flags().String("bar1", "", "required bar1")
- child.MarkFlagRequired("bar1")
- child.Flags().String("bar2", "", "required bar2")
- child.MarkFlagRequired("bar2")
- child.Flags().String("bar3", "", "optional bar3")
-
- parent.AddCommand(child)
- parent.SetArgs([]string{"child"})
-
- expected := fmt.Sprintf("Required flag(s) %q, %q, %q, %q have/has not been set", "bar1", "bar2", "foo1", "foo2")
-
- if err := parent.Execute(); err != nil {
- if err.Error() != expected {
- t.Errorf("expected %v, got %v", expected, err.Error())
- }
- }
-}
-
-// TestUpdateName checks if c.Name() updates on changed c.Use.
-// Related to https://github.com/spf13/cobra/pull/422#discussion_r143918343.
-func TestUpdateName(t *testing.T) {
- c := &Command{Use: "name xyz"}
- originalName := c.Name()
-
- c.Use = "changedName abc"
- if originalName == c.Name() || c.Name() != "changedName" {
- t.Error("c.Name() should be updated on changed c.Use")
- }
-}
diff --git a/vendor/github.com/spf13/cobra/command_win.go b/vendor/github.com/spf13/cobra/command_win.go
deleted file mode 100644
index edec728..0000000
--- a/vendor/github.com/spf13/cobra/command_win.go
+++ /dev/null
@@ -1,20 +0,0 @@
-// +build windows
-
-package cobra
-
-import (
- "os"
- "time"
-
- "github.com/inconshreveable/mousetrap"
-)
-
-var preExecHookFn = preExecHook
-
-func preExecHook(c *Command) {
- if MousetrapHelpText != "" && mousetrap.StartedByExplorer() {
- c.Print(MousetrapHelpText)
- time.Sleep(5 * time.Second)
- os.Exit(1)
- }
-}
diff --git a/vendor/github.com/spf13/cobra/zsh_completions.go b/vendor/github.com/spf13/cobra/zsh_completions.go
deleted file mode 100644
index 889c22e..0000000
--- a/vendor/github.com/spf13/cobra/zsh_completions.go
+++ /dev/null
@@ -1,126 +0,0 @@
-package cobra
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
- "strings"
-)
-
-// GenZshCompletionFile generates zsh completion file.
-func (c *Command) GenZshCompletionFile(filename string) error {
- outFile, err := os.Create(filename)
- if err != nil {
- return err
- }
- defer outFile.Close()
-
- return c.GenZshCompletion(outFile)
-}
-
-// GenZshCompletion generates a zsh completion file and writes to the passed writer.
-func (c *Command) GenZshCompletion(w io.Writer) error {
- buf := new(bytes.Buffer)
-
- writeHeader(buf, c)
- maxDepth := maxDepth(c)
- writeLevelMapping(buf, maxDepth)
- writeLevelCases(buf, maxDepth, c)
-
- _, err := buf.WriteTo(w)
- return err
-}
-
-func writeHeader(w io.Writer, cmd *Command) {
- fmt.Fprintf(w, "#compdef %s\n\n", cmd.Name())
-}
-
-func maxDepth(c *Command) int {
- if len(c.Commands()) == 0 {
- return 0
- }
- maxDepthSub := 0
- for _, s := range c.Commands() {
- subDepth := maxDepth(s)
- if subDepth > maxDepthSub {
- maxDepthSub = subDepth
- }
- }
- return 1 + maxDepthSub
-}
-
-func writeLevelMapping(w io.Writer, numLevels int) {
- fmt.Fprintln(w, `_arguments \`)
- for i := 1; i <= numLevels; i++ {
- fmt.Fprintf(w, ` '%d: :->level%d' \`, i, i)
- fmt.Fprintln(w)
- }
- fmt.Fprintf(w, ` '%d: :%s'`, numLevels+1, "_files")
- fmt.Fprintln(w)
-}
-
-func writeLevelCases(w io.Writer, maxDepth int, root *Command) {
- fmt.Fprintln(w, "case $state in")
- defer fmt.Fprintln(w, "esac")
-
- for i := 1; i <= maxDepth; i++ {
- fmt.Fprintf(w, " level%d)\n", i)
- writeLevel(w, root, i)
- fmt.Fprintln(w, " ;;")
- }
- fmt.Fprintln(w, " *)")
- fmt.Fprintln(w, " _arguments '*: :_files'")
- fmt.Fprintln(w, " ;;")
-}
-
-func writeLevel(w io.Writer, root *Command, i int) {
- fmt.Fprintf(w, " case $words[%d] in\n", i)
- defer fmt.Fprintln(w, " esac")
-
- commands := filterByLevel(root, i)
- byParent := groupByParent(commands)
-
- for p, c := range byParent {
- names := names(c)
- fmt.Fprintf(w, " %s)\n", p)
- fmt.Fprintf(w, " _arguments '%d: :(%s)'\n", i, strings.Join(names, " "))
- fmt.Fprintln(w, " ;;")
- }
- fmt.Fprintln(w, " *)")
- fmt.Fprintln(w, " _arguments '*: :_files'")
- fmt.Fprintln(w, " ;;")
-
-}
-
-func filterByLevel(c *Command, l int) []*Command {
- cs := make([]*Command, 0)
- if l == 0 {
- cs = append(cs, c)
- return cs
- }
- for _, s := range c.Commands() {
- cs = append(cs, filterByLevel(s, l-1)...)
- }
- return cs
-}
-
-func groupByParent(commands []*Command) map[string][]*Command {
- m := make(map[string][]*Command)
- for _, c := range commands {
- parent := c.Parent()
- if parent == nil {
- continue
- }
- m[parent.Name()] = append(m[parent.Name()], c)
- }
- return m
-}
-
-func names(commands []*Command) []string {
- ns := make([]string, len(commands))
- for i, c := range commands {
- ns[i] = c.Name()
- }
- return ns
-}
diff --git a/vendor/github.com/spf13/cobra/zsh_completions_test.go b/vendor/github.com/spf13/cobra/zsh_completions_test.go
deleted file mode 100644
index 08b8515..0000000
--- a/vendor/github.com/spf13/cobra/zsh_completions_test.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package cobra
-
-import (
- "bytes"
- "strings"
- "testing"
-)
-
-func TestZshCompletion(t *testing.T) {
- tcs := []struct {
- name string
- root *Command
- expectedExpressions []string
- }{
- {
- name: "trivial",
- root: &Command{Use: "trivialapp"},
- expectedExpressions: []string{"#compdef trivial"},
- },
- {
- name: "linear",
- root: func() *Command {
- r := &Command{Use: "linear"}
-
- sub1 := &Command{Use: "sub1"}
- r.AddCommand(sub1)
-
- sub2 := &Command{Use: "sub2"}
- sub1.AddCommand(sub2)
-
- sub3 := &Command{Use: "sub3"}
- sub2.AddCommand(sub3)
- return r
- }(),
- expectedExpressions: []string{"sub1", "sub2", "sub3"},
- },
- {
- name: "flat",
- root: func() *Command {
- r := &Command{Use: "flat"}
- r.AddCommand(&Command{Use: "c1"})
- r.AddCommand(&Command{Use: "c2"})
- return r
- }(),
- expectedExpressions: []string{"(c1 c2)"},
- },
- {
- name: "tree",
- root: func() *Command {
- r := &Command{Use: "tree"}
-
- sub1 := &Command{Use: "sub1"}
- r.AddCommand(sub1)
-
- sub11 := &Command{Use: "sub11"}
- sub12 := &Command{Use: "sub12"}
-
- sub1.AddCommand(sub11)
- sub1.AddCommand(sub12)
-
- sub2 := &Command{Use: "sub2"}
- r.AddCommand(sub2)
-
- sub21 := &Command{Use: "sub21"}
- sub22 := &Command{Use: "sub22"}
-
- sub2.AddCommand(sub21)
- sub2.AddCommand(sub22)
-
- return r
- }(),
- expectedExpressions: []string{"(sub11 sub12)", "(sub21 sub22)"},
- },
- }
-
- for _, tc := range tcs {
- t.Run(tc.name, func(t *testing.T) {
- buf := new(bytes.Buffer)
- tc.root.GenZshCompletion(buf)
- completion := buf.String()
- for _, expectedExpression := range tc.expectedExpressions {
- if !strings.Contains(completion, expectedExpression) {
- t.Errorf("expected completion to contain '%v' somewhere; got '%v'", expectedExpression, completion)
- }
- }
- })
- }
-}
diff --git a/vendor/github.com/spf13/jwalterweatherman/.gitignore b/vendor/github.com/spf13/jwalterweatherman/.gitignore
deleted file mode 100644
index 0026861..0000000
--- a/vendor/github.com/spf13/jwalterweatherman/.gitignore
+++ /dev/null
@@ -1,22 +0,0 @@
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-*.exe
diff --git a/vendor/github.com/spf13/jwalterweatherman/LICENSE b/vendor/github.com/spf13/jwalterweatherman/LICENSE
deleted file mode 100644
index 4527efb..0000000
--- a/vendor/github.com/spf13/jwalterweatherman/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2014 Steve Francia
-
-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.
\ No newline at end of file
diff --git a/vendor/github.com/spf13/jwalterweatherman/README.md b/vendor/github.com/spf13/jwalterweatherman/README.md
deleted file mode 100644
index 350a968..0000000
--- a/vendor/github.com/spf13/jwalterweatherman/README.md
+++ /dev/null
@@ -1,148 +0,0 @@
-jWalterWeatherman
-=================
-
-Seamless printing to the terminal (stdout) and logging to a io.Writer
-(file) that’s as easy to use as fmt.Println.
-
-
-Graphic by [JonnyEtc](http://jonnyetc.deviantart.com/art/And-That-s-Why-You-Always-Leave-a-Note-315311422)
-
-JWW is primarily a wrapper around the excellent standard log library. It
-provides a few advantages over using the standard log library alone.
-
-1. Ready to go out of the box.
-2. One library for both printing to the terminal and logging (to files).
-3. Really easy to log to either a temp file or a file you specify.
-
-
-I really wanted a very straightforward library that could seamlessly do
-the following things.
-
-1. Replace all the println, printf, etc statements thought my code with
- something more useful
-2. Allow the user to easily control what levels are printed to stdout
-3. Allow the user to easily control what levels are logged
-4. Provide an easy mechanism (like fmt.Println) to print info to the user
- which can be easily logged as well
-5. Due to 2 & 3 provide easy verbose mode for output and logs
-6. Not have any unnecessary initialization cruft. Just use it.
-
-# Usage
-
-## Step 1. Use it
-Put calls throughout your source based on type of feedback.
-No initialization or setup needs to happen. Just start calling things.
-
-Available Loggers are:
-
- * TRACE
- * DEBUG
- * INFO
- * WARN
- * ERROR
- * CRITICAL
- * FATAL
-
-These each are loggers based on the log standard library and follow the
-standard usage. Eg.
-
-```go
- import (
- jww "github.com/spf13/jwalterweatherman"
- )
-
- ...
-
- if err != nil {
-
- // This is a pretty serious error and the user should know about
- // it. It will be printed to the terminal as well as logged under the
- // default thresholds.
-
- jww.ERROR.Println(err)
- }
-
- if err2 != nil {
- // This error isn’t going to materially change the behavior of the
- // application, but it’s something that may not be what the user
- // expects. Under the default thresholds, Warn will be logged, but
- // not printed to the terminal.
-
- jww.WARN.Println(err2)
- }
-
- // Information that’s relevant to what’s happening, but not very
- // important for the user. Under the default thresholds this will be
- // discarded.
-
- jww.INFO.Printf("information %q", response)
-
-```
-
-NOTE: You can also use the library in a non-global setting by creating an instance of a Notebook:
-
-```go
-notepad = jww.NewNotepad(jww.LevelInfo, jww.LevelTrace, os.Stdout, ioutil.Discard, "", log.Ldate|log.Ltime)
-notepad.WARN.Println("Some warning"")
-```
-
-_Why 7 levels?_
-
-Maybe you think that 7 levels are too much for any application... and you
-are probably correct. Just because there are seven levels doesn’t mean
-that you should be using all 7 levels. Pick the right set for your needs.
-Remember they only have to mean something to your project.
-
-## Step 2. Optionally configure JWW
-
-Under the default thresholds :
-
- * Debug, Trace & Info goto /dev/null
- * Warn and above is logged (when a log file/io.Writer is provided)
- * Error and above is printed to the terminal (stdout)
-
-### Changing the thresholds
-
-The threshold can be changed at any time, but will only affect calls that
-execute after the change was made.
-
-This is very useful if your application has a verbose mode. Of course you
-can decide what verbose means to you or even have multiple levels of
-verbosity.
-
-
-```go
- import (
- jww "github.com/spf13/jwalterweatherman"
- )
-
- if Verbose {
- jww.SetLogThreshold(jww.LevelTrace)
- jww.SetStdoutThreshold(jww.LevelInfo)
- }
-```
-
-Note that JWW's own internal output uses log levels as well, so set the log
-level before making any other calls if you want to see what it's up to.
-
-
-### Setting a log file
-
-JWW can log to any `io.Writer`:
-
-
-```go
-
- jww.SetLogOutput(customWriter)
-
-```
-
-
-# More information
-
-This is an early release. I’ve been using it for a while and this is the
-third interface I’ve tried. I like this one pretty well, but no guarantees
-that it won’t change a bit.
-
-I wrote this for use in [hugo](http://hugo.spf13.com). If you are looking
-for a static website engine that’s super fast please checkout Hugo.
diff --git a/vendor/github.com/spf13/jwalterweatherman/default_notepad.go b/vendor/github.com/spf13/jwalterweatherman/default_notepad.go
deleted file mode 100644
index bcb7634..0000000
--- a/vendor/github.com/spf13/jwalterweatherman/default_notepad.go
+++ /dev/null
@@ -1,113 +0,0 @@
-// Copyright © 2016 Steve Francia .
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-package jwalterweatherman
-
-import (
- "io"
- "io/ioutil"
- "log"
- "os"
-)
-
-var (
- TRACE *log.Logger
- DEBUG *log.Logger
- INFO *log.Logger
- WARN *log.Logger
- ERROR *log.Logger
- CRITICAL *log.Logger
- FATAL *log.Logger
-
- LOG *log.Logger
- FEEDBACK *Feedback
-
- defaultNotepad *Notepad
-)
-
-func reloadDefaultNotepad() {
- TRACE = defaultNotepad.TRACE
- DEBUG = defaultNotepad.DEBUG
- INFO = defaultNotepad.INFO
- WARN = defaultNotepad.WARN
- ERROR = defaultNotepad.ERROR
- CRITICAL = defaultNotepad.CRITICAL
- FATAL = defaultNotepad.FATAL
-
- LOG = defaultNotepad.LOG
- FEEDBACK = defaultNotepad.FEEDBACK
-}
-
-func init() {
- defaultNotepad = NewNotepad(LevelError, LevelWarn, os.Stdout, ioutil.Discard, "", log.Ldate|log.Ltime)
- reloadDefaultNotepad()
-}
-
-// SetLogThreshold set the log threshold for the default notepad. Trace by default.
-func SetLogThreshold(threshold Threshold) {
- defaultNotepad.SetLogThreshold(threshold)
- reloadDefaultNotepad()
-}
-
-// SetLogOutput set the log output for the default notepad. Discarded by default.
-func SetLogOutput(handle io.Writer) {
- defaultNotepad.SetLogOutput(handle)
- reloadDefaultNotepad()
-}
-
-// SetStdoutThreshold set the standard output threshold for the default notepad.
-// Info by default.
-func SetStdoutThreshold(threshold Threshold) {
- defaultNotepad.SetStdoutThreshold(threshold)
- reloadDefaultNotepad()
-}
-
-// SetPrefix set the prefix for the default logger. Empty by default.
-func SetPrefix(prefix string) {
- defaultNotepad.SetPrefix(prefix)
- reloadDefaultNotepad()
-}
-
-// SetFlags set the flags for the default logger. "log.Ldate | log.Ltime" by default.
-func SetFlags(flags int) {
- defaultNotepad.SetFlags(flags)
- reloadDefaultNotepad()
-}
-
-// Level returns the current global log threshold.
-func LogThreshold() Threshold {
- return defaultNotepad.logThreshold
-}
-
-// Level returns the current global output threshold.
-func StdoutThreshold() Threshold {
- return defaultNotepad.stdoutThreshold
-}
-
-// GetStdoutThreshold returns the defined Treshold for the log logger.
-func GetLogThreshold() Threshold {
- return defaultNotepad.GetLogThreshold()
-}
-
-// GetStdoutThreshold returns the Treshold for the stdout logger.
-func GetStdoutThreshold() Threshold {
- return defaultNotepad.GetStdoutThreshold()
-}
-
-// LogCountForLevel returns the number of log invocations for a given threshold.
-func LogCountForLevel(l Threshold) uint64 {
- return defaultNotepad.LogCountForLevel(l)
-}
-
-// LogCountForLevelsGreaterThanorEqualTo returns the number of log invocations
-// greater than or equal to a given threshold.
-func LogCountForLevelsGreaterThanorEqualTo(threshold Threshold) uint64 {
- return defaultNotepad.LogCountForLevelsGreaterThanorEqualTo(threshold)
-}
-
-// ResetLogCounters resets the invocation counters for all levels.
-func ResetLogCounters() {
- defaultNotepad.ResetLogCounters()
-}
diff --git a/vendor/github.com/spf13/jwalterweatherman/default_notepad_test.go b/vendor/github.com/spf13/jwalterweatherman/default_notepad_test.go
deleted file mode 100644
index 2670c8d..0000000
--- a/vendor/github.com/spf13/jwalterweatherman/default_notepad_test.go
+++ /dev/null
@@ -1,102 +0,0 @@
-// Copyright © 2016 Steve Francia .
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-package jwalterweatherman
-
-import (
- "bytes"
- "io/ioutil"
- "sync"
- "testing"
-
- "github.com/stretchr/testify/require"
-)
-
-func TestThresholds(t *testing.T) {
- SetStdoutThreshold(LevelError)
- require.Equal(t, StdoutThreshold(), LevelError)
- SetLogThreshold(LevelCritical)
- require.Equal(t, LogThreshold(), LevelCritical)
- require.NotEqual(t, StdoutThreshold(), LevelCritical)
- SetStdoutThreshold(LevelWarn)
- require.Equal(t, StdoutThreshold(), LevelWarn)
-}
-
-func TestDefaultLogging(t *testing.T) {
- var outputBuf, logBuf bytes.Buffer
-
- defaultNotepad.logHandle = &logBuf
- defaultNotepad.outHandle = &outputBuf
-
- SetLogThreshold(LevelWarn)
- SetStdoutThreshold(LevelError)
-
- FATAL.Println("fatal err")
- CRITICAL.Println("critical err")
- ERROR.Println("an error")
- WARN.Println("a warning")
- INFO.Println("information")
- DEBUG.Println("debugging info")
- TRACE.Println("trace")
-
- require.Contains(t, logBuf.String(), "fatal err")
- require.Contains(t, logBuf.String(), "critical err")
- require.Contains(t, logBuf.String(), "an error")
- require.Contains(t, logBuf.String(), "a warning")
- require.NotContains(t, logBuf.String(), "information")
- require.NotContains(t, logBuf.String(), "debugging info")
- require.NotContains(t, logBuf.String(), "trace")
-
- require.Contains(t, outputBuf.String(), "fatal err")
- require.Contains(t, outputBuf.String(), "critical err")
- require.Contains(t, outputBuf.String(), "an error")
- require.NotContains(t, outputBuf.String(), "a warning")
- require.NotContains(t, outputBuf.String(), "information")
- require.NotContains(t, outputBuf.String(), "debugging info")
- require.NotContains(t, outputBuf.String(), "trace")
-}
-
-func TestLogCounter(t *testing.T) {
- defaultNotepad.logHandle = ioutil.Discard
- defaultNotepad.outHandle = ioutil.Discard
-
- SetLogThreshold(LevelTrace)
- SetStdoutThreshold(LevelTrace)
-
- FATAL.Println("fatal err")
- CRITICAL.Println("critical err")
- WARN.Println("a warning")
- WARN.Println("another warning")
- INFO.Println("information")
- DEBUG.Println("debugging info")
- TRACE.Println("trace")
-
- wg := &sync.WaitGroup{}
-
- for i := 0; i < 10; i++ {
- wg.Add(1)
- go func() {
- defer wg.Done()
- for j := 0; j < 10; j++ {
- ERROR.Println("error", j)
- // check for data races
- require.True(t, LogCountForLevel(LevelError) > uint64(j))
- require.True(t, LogCountForLevelsGreaterThanorEqualTo(LevelError) > uint64(j))
- }
- }()
-
- }
-
- wg.Wait()
-
- require.Equal(t, uint64(1), LogCountForLevel(LevelFatal))
- require.Equal(t, uint64(1), LogCountForLevel(LevelCritical))
- require.Equal(t, uint64(2), LogCountForLevel(LevelWarn))
- require.Equal(t, uint64(1), LogCountForLevel(LevelInfo))
- require.Equal(t, uint64(1), LogCountForLevel(LevelDebug))
- require.Equal(t, uint64(1), LogCountForLevel(LevelTrace))
- require.Equal(t, uint64(100), LogCountForLevel(LevelError))
- require.Equal(t, uint64(102), LogCountForLevelsGreaterThanorEqualTo(LevelError))
-}
diff --git a/vendor/github.com/spf13/jwalterweatherman/log_counter.go b/vendor/github.com/spf13/jwalterweatherman/log_counter.go
deleted file mode 100644
index 11423ac..0000000
--- a/vendor/github.com/spf13/jwalterweatherman/log_counter.go
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright © 2016 Steve Francia .
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-package jwalterweatherman
-
-import (
- "sync/atomic"
-)
-
-type logCounter struct {
- counter uint64
-}
-
-func (c *logCounter) incr() {
- atomic.AddUint64(&c.counter, 1)
-}
-
-func (c *logCounter) resetCounter() {
- atomic.StoreUint64(&c.counter, 0)
-}
-
-func (c *logCounter) getCount() uint64 {
- return atomic.LoadUint64(&c.counter)
-}
-
-func (c *logCounter) Write(p []byte) (n int, err error) {
- c.incr()
- return len(p), nil
-}
-
-// LogCountForLevel returns the number of log invocations for a given threshold.
-func (n *Notepad) LogCountForLevel(l Threshold) uint64 {
- return n.logCounters[l].getCount()
-}
-
-// LogCountForLevelsGreaterThanorEqualTo returns the number of log invocations
-// greater than or equal to a given threshold.
-func (n *Notepad) LogCountForLevelsGreaterThanorEqualTo(threshold Threshold) uint64 {
- var cnt uint64
-
- for i := int(threshold); i < len(n.logCounters); i++ {
- cnt += n.LogCountForLevel(Threshold(i))
- }
-
- return cnt
-}
-
-// ResetLogCounters resets the invocation counters for all levels.
-func (n *Notepad) ResetLogCounters() {
- for _, np := range n.logCounters {
- np.resetCounter()
- }
-}
diff --git a/vendor/github.com/spf13/jwalterweatherman/notepad.go b/vendor/github.com/spf13/jwalterweatherman/notepad.go
deleted file mode 100644
index ae5aaf7..0000000
--- a/vendor/github.com/spf13/jwalterweatherman/notepad.go
+++ /dev/null
@@ -1,194 +0,0 @@
-// Copyright © 2016 Steve Francia .
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-package jwalterweatherman
-
-import (
- "fmt"
- "io"
- "log"
-)
-
-type Threshold int
-
-func (t Threshold) String() string {
- return prefixes[t]
-}
-
-const (
- LevelTrace Threshold = iota
- LevelDebug
- LevelInfo
- LevelWarn
- LevelError
- LevelCritical
- LevelFatal
-)
-
-var prefixes map[Threshold]string = map[Threshold]string{
- LevelTrace: "TRACE",
- LevelDebug: "DEBUG",
- LevelInfo: "INFO",
- LevelWarn: "WARN",
- LevelError: "ERROR",
- LevelCritical: "CRITICAL",
- LevelFatal: "FATAL",
-}
-
-// Notepad is where you leave a note!
-type Notepad struct {
- TRACE *log.Logger
- DEBUG *log.Logger
- INFO *log.Logger
- WARN *log.Logger
- ERROR *log.Logger
- CRITICAL *log.Logger
- FATAL *log.Logger
-
- LOG *log.Logger
- FEEDBACK *Feedback
-
- loggers [7]**log.Logger
- logHandle io.Writer
- outHandle io.Writer
- logThreshold Threshold
- stdoutThreshold Threshold
- prefix string
- flags int
-
- // One per Threshold
- logCounters [7]*logCounter
-}
-
-// NewNotepad create a new notepad.
-func NewNotepad(outThreshold Threshold, logThreshold Threshold, outHandle, logHandle io.Writer, prefix string, flags int) *Notepad {
- n := &Notepad{}
-
- n.loggers = [7]**log.Logger{&n.TRACE, &n.DEBUG, &n.INFO, &n.WARN, &n.ERROR, &n.CRITICAL, &n.FATAL}
- n.outHandle = outHandle
- n.logHandle = logHandle
- n.stdoutThreshold = outThreshold
- n.logThreshold = logThreshold
-
- if len(prefix) != 0 {
- n.prefix = "[" + prefix + "] "
- } else {
- n.prefix = ""
- }
-
- n.flags = flags
-
- n.LOG = log.New(n.logHandle,
- "LOG: ",
- n.flags)
- n.FEEDBACK = &Feedback{out: log.New(outHandle, "", 0), log: n.LOG}
-
- n.init()
- return n
-}
-
-// init creates the loggers for each level depending on the notepad thresholds.
-func (n *Notepad) init() {
- logAndOut := io.MultiWriter(n.outHandle, n.logHandle)
-
- for t, logger := range n.loggers {
- threshold := Threshold(t)
- counter := &logCounter{}
- n.logCounters[t] = counter
- prefix := n.prefix + threshold.String() + " "
-
- switch {
- case threshold >= n.logThreshold && threshold >= n.stdoutThreshold:
- *logger = log.New(io.MultiWriter(counter, logAndOut), prefix, n.flags)
-
- case threshold >= n.logThreshold:
- *logger = log.New(io.MultiWriter(counter, n.logHandle), prefix, n.flags)
-
- case threshold >= n.stdoutThreshold:
- *logger = log.New(io.MultiWriter(counter, n.outHandle), prefix, n.flags)
-
- default:
- // counter doesn't care about prefix and flags, so don't use them
- // for performance.
- *logger = log.New(counter, "", 0)
- }
- }
-}
-
-// SetLogThreshold changes the threshold above which messages are written to the
-// log file.
-func (n *Notepad) SetLogThreshold(threshold Threshold) {
- n.logThreshold = threshold
- n.init()
-}
-
-// SetLogOutput changes the file where log messages are written.
-func (n *Notepad) SetLogOutput(handle io.Writer) {
- n.logHandle = handle
- n.init()
-}
-
-// GetStdoutThreshold returns the defined Treshold for the log logger.
-func (n *Notepad) GetLogThreshold() Threshold {
- return n.logThreshold
-}
-
-// SetStdoutThreshold changes the threshold above which messages are written to the
-// standard output.
-func (n *Notepad) SetStdoutThreshold(threshold Threshold) {
- n.stdoutThreshold = threshold
- n.init()
-}
-
-// GetStdoutThreshold returns the Treshold for the stdout logger.
-func (n *Notepad) GetStdoutThreshold() Threshold {
- return n.stdoutThreshold
-}
-
-// SetPrefix changes the prefix used by the notepad. Prefixes are displayed between
-// brackets at the beginning of the line. An empty prefix won't be displayed at all.
-func (n *Notepad) SetPrefix(prefix string) {
- if len(prefix) != 0 {
- n.prefix = "[" + prefix + "] "
- } else {
- n.prefix = ""
- }
- n.init()
-}
-
-// SetFlags choose which flags the logger will display (after prefix and message
-// level). See the package log for more informations on this.
-func (n *Notepad) SetFlags(flags int) {
- n.flags = flags
- n.init()
-}
-
-// Feedback writes plainly to the outHandle while
-// logging with the standard extra information (date, file, etc).
-type Feedback struct {
- out *log.Logger
- log *log.Logger
-}
-
-func (fb *Feedback) Println(v ...interface{}) {
- fb.output(fmt.Sprintln(v...))
-}
-
-func (fb *Feedback) Printf(format string, v ...interface{}) {
- fb.output(fmt.Sprintf(format, v...))
-}
-
-func (fb *Feedback) Print(v ...interface{}) {
- fb.output(fmt.Sprint(v...))
-}
-
-func (fb *Feedback) output(s string) {
- if fb.out != nil {
- fb.out.Output(2, s)
- }
- if fb.log != nil {
- fb.log.Output(2, s)
- }
-}
diff --git a/vendor/github.com/spf13/jwalterweatherman/notepad_test.go b/vendor/github.com/spf13/jwalterweatherman/notepad_test.go
deleted file mode 100644
index 69ad6f8..0000000
--- a/vendor/github.com/spf13/jwalterweatherman/notepad_test.go
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright © 2016 Steve Francia .
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-package jwalterweatherman
-
-import (
- "bytes"
- "testing"
-
- "github.com/stretchr/testify/require"
-)
-
-func TestNotepad(t *testing.T) {
- var logHandle, outHandle bytes.Buffer
-
- n := NewNotepad(LevelCritical, LevelError, &outHandle, &logHandle, "TestNotePad", 0)
-
- require.Equal(t, LevelCritical, n.GetStdoutThreshold())
- require.Equal(t, LevelError, n.GetLogThreshold())
-
- n.DEBUG.Println("Some debug")
- n.ERROR.Println("Some error")
- n.CRITICAL.Println("Some critical error")
-
- require.Contains(t, logHandle.String(), "[TestNotePad] ERROR Some error")
- require.NotContains(t, logHandle.String(), "Some debug")
- require.NotContains(t, outHandle.String(), "Some error")
- require.Contains(t, outHandle.String(), "Some critical error")
-
- require.Equal(t, n.LogCountForLevel(LevelError), uint64(1))
- require.Equal(t, n.LogCountForLevel(LevelDebug), uint64(1))
- require.Equal(t, n.LogCountForLevel(LevelTrace), uint64(0))
-}
-
-func TestThresholdString(t *testing.T) {
- require.Equal(t, LevelError.String(), "ERROR")
- require.Equal(t, LevelTrace.String(), "TRACE")
-}
-
-func BenchmarkLogPrintOnlyToCounter(b *testing.B) {
- var logHandle, outHandle bytes.Buffer
- n := NewNotepad(LevelCritical, LevelCritical, &outHandle, &logHandle, "TestNotePad", 0)
-
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- n.INFO.Print("Test")
- }
-}
diff --git a/vendor/github.com/spf13/pflag/.gitignore b/vendor/github.com/spf13/pflag/.gitignore
deleted file mode 100644
index c3da290..0000000
--- a/vendor/github.com/spf13/pflag/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-.idea/*
-
diff --git a/vendor/github.com/spf13/pflag/.travis.yml b/vendor/github.com/spf13/pflag/.travis.yml
deleted file mode 100644
index f8a63b3..0000000
--- a/vendor/github.com/spf13/pflag/.travis.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-sudo: false
-
-language: go
-
-go:
- - 1.7.3
- - 1.8.1
- - tip
-
-matrix:
- allow_failures:
- - go: tip
-
-install:
- - go get github.com/golang/lint/golint
- - export PATH=$GOPATH/bin:$PATH
- - go install ./...
-
-script:
- - verify/all.sh -v
- - go test ./...
diff --git a/vendor/github.com/spf13/pflag/LICENSE b/vendor/github.com/spf13/pflag/LICENSE
deleted file mode 100644
index 63ed1cf..0000000
--- a/vendor/github.com/spf13/pflag/LICENSE
+++ /dev/null
@@ -1,28 +0,0 @@
-Copyright (c) 2012 Alex Ogier. All rights reserved.
-Copyright (c) 2012 The Go Authors. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- * Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
- * Neither the name of Google Inc. nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/vendor/github.com/spf13/pflag/README.md b/vendor/github.com/spf13/pflag/README.md
deleted file mode 100644
index b052414..0000000
--- a/vendor/github.com/spf13/pflag/README.md
+++ /dev/null
@@ -1,296 +0,0 @@
-[](https://travis-ci.org/spf13/pflag)
-[](https://goreportcard.com/report/github.com/spf13/pflag)
-[](https://godoc.org/github.com/spf13/pflag)
-
-## Description
-
-pflag is a drop-in replacement for Go's flag package, implementing
-POSIX/GNU-style --flags.
-
-pflag is compatible with the [GNU extensions to the POSIX recommendations
-for command-line options][1]. For a more precise description, see the
-"Command-line flag syntax" section below.
-
-[1]: http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
-
-pflag is available under the same style of BSD license as the Go language,
-which can be found in the LICENSE file.
-
-## Installation
-
-pflag is available using the standard `go get` command.
-
-Install by running:
-
- go get github.com/spf13/pflag
-
-Run tests by running:
-
- go test github.com/spf13/pflag
-
-## Usage
-
-pflag is a drop-in replacement of Go's native flag package. If you import
-pflag under the name "flag" then all code should continue to function
-with no changes.
-
-``` go
-import flag "github.com/spf13/pflag"
-```
-
-There is one exception to this: if you directly instantiate the Flag struct
-there is one more field "Shorthand" that you will need to set.
-Most code never instantiates this struct directly, and instead uses
-functions such as String(), BoolVar(), and Var(), and is therefore
-unaffected.
-
-Define flags using flag.String(), Bool(), Int(), etc.
-
-This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
-
-``` go
-var ip *int = flag.Int("flagname", 1234, "help message for flagname")
-```
-
-If you like, you can bind the flag to a variable using the Var() functions.
-
-``` go
-var flagvar int
-func init() {
- flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
-}
-```
-
-Or you can create custom flags that satisfy the Value interface (with
-pointer receivers) and couple them to flag parsing by
-
-``` go
-flag.Var(&flagVal, "name", "help message for flagname")
-```
-
-For such flags, the default value is just the initial value of the variable.
-
-After all flags are defined, call
-
-``` go
-flag.Parse()
-```
-
-to parse the command line into the defined flags.
-
-Flags may then be used directly. If you're using the flags themselves,
-they are all pointers; if you bind to variables, they're values.
-
-``` go
-fmt.Println("ip has value ", *ip)
-fmt.Println("flagvar has value ", flagvar)
-```
-
-There are helpers function to get values later if you have the FlagSet but
-it was difficult to keep up with all of the flag pointers in your code.
-If you have a pflag.FlagSet with a flag called 'flagname' of type int you
-can use GetInt() to get the int value. But notice that 'flagname' must exist
-and it must be an int. GetString("flagname") will fail.
-
-``` go
-i, err := flagset.GetInt("flagname")
-```
-
-After parsing, the arguments after the flag are available as the
-slice flag.Args() or individually as flag.Arg(i).
-The arguments are indexed from 0 through flag.NArg()-1.
-
-The pflag package also defines some new functions that are not in flag,
-that give one-letter shorthands for flags. You can use these by appending
-'P' to the name of any function that defines a flag.
-
-``` go
-var ip = flag.IntP("flagname", "f", 1234, "help message")
-var flagvar bool
-func init() {
- flag.BoolVarP(&flagvar, "boolname", "b", true, "help message")
-}
-flag.VarP(&flagVal, "varname", "v", "help message")
-```
-
-Shorthand letters can be used with single dashes on the command line.
-Boolean shorthand flags can be combined with other shorthand flags.
-
-The default set of command-line flags is controlled by
-top-level functions. The FlagSet type allows one to define
-independent sets of flags, such as to implement subcommands
-in a command-line interface. The methods of FlagSet are
-analogous to the top-level functions for the command-line
-flag set.
-
-## Setting no option default values for flags
-
-After you create a flag it is possible to set the pflag.NoOptDefVal for
-the given flag. Doing this changes the meaning of the flag slightly. If
-a flag has a NoOptDefVal and the flag is set on the command line without
-an option the flag will be set to the NoOptDefVal. For example given:
-
-``` go
-var ip = flag.IntP("flagname", "f", 1234, "help message")
-flag.Lookup("flagname").NoOptDefVal = "4321"
-```
-
-Would result in something like
-
-| Parsed Arguments | Resulting Value |
-| ------------- | ------------- |
-| --flagname=1357 | ip=1357 |
-| --flagname | ip=4321 |
-| [nothing] | ip=1234 |
-
-## Command line flag syntax
-
-```
---flag // boolean flags, or flags with no option default values
---flag x // only on flags without a default value
---flag=x
-```
-
-Unlike the flag package, a single dash before an option means something
-different than a double dash. Single dashes signify a series of shorthand
-letters for flags. All but the last shorthand letter must be boolean flags
-or a flag with a default value
-
-```
-// boolean or flags where the 'no option default value' is set
--f
--f=true
--abc
-but
--b true is INVALID
-
-// non-boolean and flags without a 'no option default value'
--n 1234
--n=1234
--n1234
-
-// mixed
--abcs "hello"
--absd="hello"
--abcs1234
-```
-
-Flag parsing stops after the terminator "--". Unlike the flag package,
-flags can be interspersed with arguments anywhere on the command line
-before this terminator.
-
-Integer flags accept 1234, 0664, 0x1234 and may be negative.
-Boolean flags (in their long form) accept 1, 0, t, f, true, false,
-TRUE, FALSE, True, False.
-Duration flags accept any input valid for time.ParseDuration.
-
-## Mutating or "Normalizing" Flag names
-
-It is possible to set a custom flag name 'normalization function.' It allows flag names to be mutated both when created in the code and when used on the command line to some 'normalized' form. The 'normalized' form is used for comparison. Two examples of using the custom normalization func follow.
-
-**Example #1**: You want -, _, and . in flags to compare the same. aka --my-flag == --my_flag == --my.flag
-
-``` go
-func wordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
- from := []string{"-", "_"}
- to := "."
- for _, sep := range from {
- name = strings.Replace(name, sep, to, -1)
- }
- return pflag.NormalizedName(name)
-}
-
-myFlagSet.SetNormalizeFunc(wordSepNormalizeFunc)
-```
-
-**Example #2**: You want to alias two flags. aka --old-flag-name == --new-flag-name
-
-``` go
-func aliasNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
- switch name {
- case "old-flag-name":
- name = "new-flag-name"
- break
- }
- return pflag.NormalizedName(name)
-}
-
-myFlagSet.SetNormalizeFunc(aliasNormalizeFunc)
-```
-
-## Deprecating a flag or its shorthand
-It is possible to deprecate a flag, or just its shorthand. Deprecating a flag/shorthand hides it from help text and prints a usage message when the deprecated flag/shorthand is used.
-
-**Example #1**: You want to deprecate a flag named "badflag" as well as inform the users what flag they should use instead.
-```go
-// deprecate a flag by specifying its name and a usage message
-flags.MarkDeprecated("badflag", "please use --good-flag instead")
-```
-This hides "badflag" from help text, and prints `Flag --badflag has been deprecated, please use --good-flag instead` when "badflag" is used.
-
-**Example #2**: You want to keep a flag name "noshorthandflag" but deprecate its shortname "n".
-```go
-// deprecate a flag shorthand by specifying its flag name and a usage message
-flags.MarkShorthandDeprecated("noshorthandflag", "please use --noshorthandflag only")
-```
-This hides the shortname "n" from help text, and prints `Flag shorthand -n has been deprecated, please use --noshorthandflag only` when the shorthand "n" is used.
-
-Note that usage message is essential here, and it should not be empty.
-
-## Hidden flags
-It is possible to mark a flag as hidden, meaning it will still function as normal, however will not show up in usage/help text.
-
-**Example**: You have a flag named "secretFlag" that you need for internal use only and don't want it showing up in help text, or for its usage text to be available.
-```go
-// hide a flag by specifying its name
-flags.MarkHidden("secretFlag")
-```
-
-## Disable sorting of flags
-`pflag` allows you to disable sorting of flags for help and usage message.
-
-**Example**:
-```go
-flags.BoolP("verbose", "v", false, "verbose output")
-flags.String("coolflag", "yeaah", "it's really cool flag")
-flags.Int("usefulflag", 777, "sometimes it's very useful")
-flags.SortFlags = false
-flags.PrintDefaults()
-```
-**Output**:
-```
- -v, --verbose verbose output
- --coolflag string it's really cool flag (default "yeaah")
- --usefulflag int sometimes it's very useful (default 777)
-```
-
-
-## Supporting Go flags when using pflag
-In order to support flags defined using Go's `flag` package, they must be added to the `pflag` flagset. This is usually necessary
-to support flags defined by third-party dependencies (e.g. `golang/glog`).
-
-**Example**: You want to add the Go flags to the `CommandLine` flagset
-```go
-import (
- goflag "flag"
- flag "github.com/spf13/pflag"
-)
-
-var ip *int = flag.Int("flagname", 1234, "help message for flagname")
-
-func main() {
- flag.CommandLine.AddGoFlagSet(goflag.CommandLine)
- flag.Parse()
-}
-```
-
-## More info
-
-You can see the full reference documentation of the pflag package
-[at godoc.org][3], or through go's standard documentation system by
-running `godoc -http=:6060` and browsing to
-[http://localhost:6060/pkg/github.com/spf13/pflag][2] after
-installation.
-
-[2]: http://localhost:6060/pkg/github.com/spf13/pflag
-[3]: http://godoc.org/github.com/spf13/pflag
diff --git a/vendor/github.com/spf13/pflag/bool.go b/vendor/github.com/spf13/pflag/bool.go
deleted file mode 100644
index c4c5c0b..0000000
--- a/vendor/github.com/spf13/pflag/bool.go
+++ /dev/null
@@ -1,94 +0,0 @@
-package pflag
-
-import "strconv"
-
-// optional interface to indicate boolean flags that can be
-// supplied without "=value" text
-type boolFlag interface {
- Value
- IsBoolFlag() bool
-}
-
-// -- bool Value
-type boolValue bool
-
-func newBoolValue(val bool, p *bool) *boolValue {
- *p = val
- return (*boolValue)(p)
-}
-
-func (b *boolValue) Set(s string) error {
- v, err := strconv.ParseBool(s)
- *b = boolValue(v)
- return err
-}
-
-func (b *boolValue) Type() string {
- return "bool"
-}
-
-func (b *boolValue) String() string { return strconv.FormatBool(bool(*b)) }
-
-func (b *boolValue) IsBoolFlag() bool { return true }
-
-func boolConv(sval string) (interface{}, error) {
- return strconv.ParseBool(sval)
-}
-
-// GetBool return the bool value of a flag with the given name
-func (f *FlagSet) GetBool(name string) (bool, error) {
- val, err := f.getFlagType(name, "bool", boolConv)
- if err != nil {
- return false, err
- }
- return val.(bool), nil
-}
-
-// BoolVar defines a bool flag with specified name, default value, and usage string.
-// The argument p points to a bool variable in which to store the value of the flag.
-func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {
- f.BoolVarP(p, name, "", value, usage)
-}
-
-// BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) {
- flag := f.VarPF(newBoolValue(value, p), name, shorthand, usage)
- flag.NoOptDefVal = "true"
-}
-
-// BoolVar defines a bool flag with specified name, default value, and usage string.
-// The argument p points to a bool variable in which to store the value of the flag.
-func BoolVar(p *bool, name string, value bool, usage string) {
- BoolVarP(p, name, "", value, usage)
-}
-
-// BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash.
-func BoolVarP(p *bool, name, shorthand string, value bool, usage string) {
- flag := CommandLine.VarPF(newBoolValue(value, p), name, shorthand, usage)
- flag.NoOptDefVal = "true"
-}
-
-// Bool defines a bool flag with specified name, default value, and usage string.
-// The return value is the address of a bool variable that stores the value of the flag.
-func (f *FlagSet) Bool(name string, value bool, usage string) *bool {
- return f.BoolP(name, "", value, usage)
-}
-
-// BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool {
- p := new(bool)
- f.BoolVarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Bool defines a bool flag with specified name, default value, and usage string.
-// The return value is the address of a bool variable that stores the value of the flag.
-func Bool(name string, value bool, usage string) *bool {
- return BoolP(name, "", value, usage)
-}
-
-// BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash.
-func BoolP(name, shorthand string, value bool, usage string) *bool {
- b := CommandLine.BoolP(name, shorthand, value, usage)
- return b
-}
diff --git a/vendor/github.com/spf13/pflag/bool_slice.go b/vendor/github.com/spf13/pflag/bool_slice.go
deleted file mode 100644
index 5af02f1..0000000
--- a/vendor/github.com/spf13/pflag/bool_slice.go
+++ /dev/null
@@ -1,147 +0,0 @@
-package pflag
-
-import (
- "io"
- "strconv"
- "strings"
-)
-
-// -- boolSlice Value
-type boolSliceValue struct {
- value *[]bool
- changed bool
-}
-
-func newBoolSliceValue(val []bool, p *[]bool) *boolSliceValue {
- bsv := new(boolSliceValue)
- bsv.value = p
- *bsv.value = val
- return bsv
-}
-
-// Set converts, and assigns, the comma-separated boolean argument string representation as the []bool value of this flag.
-// If Set is called on a flag that already has a []bool assigned, the newly converted values will be appended.
-func (s *boolSliceValue) Set(val string) error {
-
- // remove all quote characters
- rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "")
-
- // read flag arguments with CSV parser
- boolStrSlice, err := readAsCSV(rmQuote.Replace(val))
- if err != nil && err != io.EOF {
- return err
- }
-
- // parse boolean values into slice
- out := make([]bool, 0, len(boolStrSlice))
- for _, boolStr := range boolStrSlice {
- b, err := strconv.ParseBool(strings.TrimSpace(boolStr))
- if err != nil {
- return err
- }
- out = append(out, b)
- }
-
- if !s.changed {
- *s.value = out
- } else {
- *s.value = append(*s.value, out...)
- }
-
- s.changed = true
-
- return nil
-}
-
-// Type returns a string that uniquely represents this flag's type.
-func (s *boolSliceValue) Type() string {
- return "boolSlice"
-}
-
-// String defines a "native" format for this boolean slice flag value.
-func (s *boolSliceValue) String() string {
-
- boolStrSlice := make([]string, len(*s.value))
- for i, b := range *s.value {
- boolStrSlice[i] = strconv.FormatBool(b)
- }
-
- out, _ := writeAsCSV(boolStrSlice)
-
- return "[" + out + "]"
-}
-
-func boolSliceConv(val string) (interface{}, error) {
- val = strings.Trim(val, "[]")
- // Empty string would cause a slice with one (empty) entry
- if len(val) == 0 {
- return []bool{}, nil
- }
- ss := strings.Split(val, ",")
- out := make([]bool, len(ss))
- for i, t := range ss {
- var err error
- out[i], err = strconv.ParseBool(t)
- if err != nil {
- return nil, err
- }
- }
- return out, nil
-}
-
-// GetBoolSlice returns the []bool value of a flag with the given name.
-func (f *FlagSet) GetBoolSlice(name string) ([]bool, error) {
- val, err := f.getFlagType(name, "boolSlice", boolSliceConv)
- if err != nil {
- return []bool{}, err
- }
- return val.([]bool), nil
-}
-
-// BoolSliceVar defines a boolSlice flag with specified name, default value, and usage string.
-// The argument p points to a []bool variable in which to store the value of the flag.
-func (f *FlagSet) BoolSliceVar(p *[]bool, name string, value []bool, usage string) {
- f.VarP(newBoolSliceValue(value, p), name, "", usage)
-}
-
-// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) {
- f.VarP(newBoolSliceValue(value, p), name, shorthand, usage)
-}
-
-// BoolSliceVar defines a []bool flag with specified name, default value, and usage string.
-// The argument p points to a []bool variable in which to store the value of the flag.
-func BoolSliceVar(p *[]bool, name string, value []bool, usage string) {
- CommandLine.VarP(newBoolSliceValue(value, p), name, "", usage)
-}
-
-// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash.
-func BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) {
- CommandLine.VarP(newBoolSliceValue(value, p), name, shorthand, usage)
-}
-
-// BoolSlice defines a []bool flag with specified name, default value, and usage string.
-// The return value is the address of a []bool variable that stores the value of the flag.
-func (f *FlagSet) BoolSlice(name string, value []bool, usage string) *[]bool {
- p := []bool{}
- f.BoolSliceVarP(&p, name, "", value, usage)
- return &p
-}
-
-// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool {
- p := []bool{}
- f.BoolSliceVarP(&p, name, shorthand, value, usage)
- return &p
-}
-
-// BoolSlice defines a []bool flag with specified name, default value, and usage string.
-// The return value is the address of a []bool variable that stores the value of the flag.
-func BoolSlice(name string, value []bool, usage string) *[]bool {
- return CommandLine.BoolSliceP(name, "", value, usage)
-}
-
-// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash.
-func BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool {
- return CommandLine.BoolSliceP(name, shorthand, value, usage)
-}
diff --git a/vendor/github.com/spf13/pflag/bool_slice_test.go b/vendor/github.com/spf13/pflag/bool_slice_test.go
deleted file mode 100644
index b617dd2..0000000
--- a/vendor/github.com/spf13/pflag/bool_slice_test.go
+++ /dev/null
@@ -1,215 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "strconv"
- "strings"
- "testing"
-)
-
-func setUpBSFlagSet(bsp *[]bool) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.BoolSliceVar(bsp, "bs", []bool{}, "Command separated list!")
- return f
-}
-
-func setUpBSFlagSetWithDefault(bsp *[]bool) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.BoolSliceVar(bsp, "bs", []bool{false, true}, "Command separated list!")
- return f
-}
-
-func TestEmptyBS(t *testing.T) {
- var bs []bool
- f := setUpBSFlagSet(&bs)
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- getBS, err := f.GetBoolSlice("bs")
- if err != nil {
- t.Fatal("got an error from GetBoolSlice():", err)
- }
- if len(getBS) != 0 {
- t.Fatalf("got bs %v with len=%d but expected length=0", getBS, len(getBS))
- }
-}
-
-func TestBS(t *testing.T) {
- var bs []bool
- f := setUpBSFlagSet(&bs)
-
- vals := []string{"1", "F", "TRUE", "0"}
- arg := fmt.Sprintf("--bs=%s", strings.Join(vals, ","))
- err := f.Parse([]string{arg})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range bs {
- b, err := strconv.ParseBool(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if b != v {
- t.Fatalf("expected is[%d] to be %s but got: %t", i, vals[i], v)
- }
- }
- getBS, err := f.GetBoolSlice("bs")
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- for i, v := range getBS {
- b, err := strconv.ParseBool(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if b != v {
- t.Fatalf("expected bs[%d] to be %s but got: %t from GetBoolSlice", i, vals[i], v)
- }
- }
-}
-
-func TestBSDefault(t *testing.T) {
- var bs []bool
- f := setUpBSFlagSetWithDefault(&bs)
-
- vals := []string{"false", "T"}
-
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range bs {
- b, err := strconv.ParseBool(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if b != v {
- t.Fatalf("expected bs[%d] to be %t from GetBoolSlice but got: %t", i, b, v)
- }
- }
-
- getBS, err := f.GetBoolSlice("bs")
- if err != nil {
- t.Fatal("got an error from GetBoolSlice():", err)
- }
- for i, v := range getBS {
- b, err := strconv.ParseBool(vals[i])
- if err != nil {
- t.Fatal("got an error from GetBoolSlice():", err)
- }
- if b != v {
- t.Fatalf("expected bs[%d] to be %t from GetBoolSlice but got: %t", i, b, v)
- }
- }
-}
-
-func TestBSWithDefault(t *testing.T) {
- var bs []bool
- f := setUpBSFlagSetWithDefault(&bs)
-
- vals := []string{"FALSE", "1"}
- arg := fmt.Sprintf("--bs=%s", strings.Join(vals, ","))
- err := f.Parse([]string{arg})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range bs {
- b, err := strconv.ParseBool(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if b != v {
- t.Fatalf("expected bs[%d] to be %t but got: %t", i, b, v)
- }
- }
-
- getBS, err := f.GetBoolSlice("bs")
- if err != nil {
- t.Fatal("got an error from GetBoolSlice():", err)
- }
- for i, v := range getBS {
- b, err := strconv.ParseBool(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if b != v {
- t.Fatalf("expected bs[%d] to be %t from GetBoolSlice but got: %t", i, b, v)
- }
- }
-}
-
-func TestBSCalledTwice(t *testing.T) {
- var bs []bool
- f := setUpBSFlagSet(&bs)
-
- in := []string{"T,F", "T"}
- expected := []bool{true, false, true}
- argfmt := "--bs=%s"
- arg1 := fmt.Sprintf(argfmt, in[0])
- arg2 := fmt.Sprintf(argfmt, in[1])
- err := f.Parse([]string{arg1, arg2})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range bs {
- if expected[i] != v {
- t.Fatalf("expected bs[%d] to be %t but got %t", i, expected[i], v)
- }
- }
-}
-
-func TestBSBadQuoting(t *testing.T) {
-
- tests := []struct {
- Want []bool
- FlagArg []string
- }{
- {
- Want: []bool{true, false, true},
- FlagArg: []string{"1", "0", "true"},
- },
- {
- Want: []bool{true, false},
- FlagArg: []string{"True", "F"},
- },
- {
- Want: []bool{true, false},
- FlagArg: []string{"T", "0"},
- },
- {
- Want: []bool{true, false},
- FlagArg: []string{"1", "0"},
- },
- {
- Want: []bool{true, false, false},
- FlagArg: []string{"true,false", "false"},
- },
- {
- Want: []bool{true, false, false, true, false, true, false},
- FlagArg: []string{`"true,false,false,1,0, T"`, " false "},
- },
- {
- Want: []bool{false, false, true, false, true, false, true},
- FlagArg: []string{`"0, False, T,false , true,F"`, "true"},
- },
- }
-
- for i, test := range tests {
-
- var bs []bool
- f := setUpBSFlagSet(&bs)
-
- if err := f.Parse([]string{fmt.Sprintf("--bs=%s", strings.Join(test.FlagArg, ","))}); err != nil {
- t.Fatalf("flag parsing failed with error: %s\nparsing:\t%#v\nwant:\t\t%#v",
- err, test.FlagArg, test.Want[i])
- }
-
- for j, b := range bs {
- if b != test.Want[j] {
- t.Fatalf("bad value parsed for test %d on bool %d:\nwant:\t%t\ngot:\t%t", i, j, test.Want[j], b)
- }
- }
- }
-}
diff --git a/vendor/github.com/spf13/pflag/bool_test.go b/vendor/github.com/spf13/pflag/bool_test.go
deleted file mode 100644
index a4319e7..0000000
--- a/vendor/github.com/spf13/pflag/bool_test.go
+++ /dev/null
@@ -1,179 +0,0 @@
-// Copyright 2009 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 pflag
-
-import (
- "bytes"
- "strconv"
- "testing"
-)
-
-// This value can be a boolean ("true", "false") or "maybe"
-type triStateValue int
-
-const (
- triStateFalse triStateValue = 0
- triStateTrue triStateValue = 1
- triStateMaybe triStateValue = 2
-)
-
-const strTriStateMaybe = "maybe"
-
-func (v *triStateValue) IsBoolFlag() bool {
- return true
-}
-
-func (v *triStateValue) Get() interface{} {
- return triStateValue(*v)
-}
-
-func (v *triStateValue) Set(s string) error {
- if s == strTriStateMaybe {
- *v = triStateMaybe
- return nil
- }
- boolVal, err := strconv.ParseBool(s)
- if boolVal {
- *v = triStateTrue
- } else {
- *v = triStateFalse
- }
- return err
-}
-
-func (v *triStateValue) String() string {
- if *v == triStateMaybe {
- return strTriStateMaybe
- }
- return strconv.FormatBool(*v == triStateTrue)
-}
-
-// The type of the flag as required by the pflag.Value interface
-func (v *triStateValue) Type() string {
- return "version"
-}
-
-func setUpFlagSet(tristate *triStateValue) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- *tristate = triStateFalse
- flag := f.VarPF(tristate, "tristate", "t", "tristate value (true, maybe or false)")
- flag.NoOptDefVal = "true"
- return f
-}
-
-func TestExplicitTrue(t *testing.T) {
- var tristate triStateValue
- f := setUpFlagSet(&tristate)
- err := f.Parse([]string{"--tristate=true"})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- if tristate != triStateTrue {
- t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead")
- }
-}
-
-func TestImplicitTrue(t *testing.T) {
- var tristate triStateValue
- f := setUpFlagSet(&tristate)
- err := f.Parse([]string{"--tristate"})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- if tristate != triStateTrue {
- t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead")
- }
-}
-
-func TestShortFlag(t *testing.T) {
- var tristate triStateValue
- f := setUpFlagSet(&tristate)
- err := f.Parse([]string{"-t"})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- if tristate != triStateTrue {
- t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead")
- }
-}
-
-func TestShortFlagExtraArgument(t *testing.T) {
- var tristate triStateValue
- f := setUpFlagSet(&tristate)
- // The"maybe"turns into an arg, since short boolean options will only do true/false
- err := f.Parse([]string{"-t", "maybe"})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- if tristate != triStateTrue {
- t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead")
- }
- args := f.Args()
- if len(args) != 1 || args[0] != "maybe" {
- t.Fatal("expected an extra 'maybe' argument to stick around")
- }
-}
-
-func TestExplicitMaybe(t *testing.T) {
- var tristate triStateValue
- f := setUpFlagSet(&tristate)
- err := f.Parse([]string{"--tristate=maybe"})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- if tristate != triStateMaybe {
- t.Fatal("expected", triStateMaybe, "(triStateMaybe) but got", tristate, "instead")
- }
-}
-
-func TestExplicitFalse(t *testing.T) {
- var tristate triStateValue
- f := setUpFlagSet(&tristate)
- err := f.Parse([]string{"--tristate=false"})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- if tristate != triStateFalse {
- t.Fatal("expected", triStateFalse, "(triStateFalse) but got", tristate, "instead")
- }
-}
-
-func TestImplicitFalse(t *testing.T) {
- var tristate triStateValue
- f := setUpFlagSet(&tristate)
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- if tristate != triStateFalse {
- t.Fatal("expected", triStateFalse, "(triStateFalse) but got", tristate, "instead")
- }
-}
-
-func TestInvalidValue(t *testing.T) {
- var tristate triStateValue
- f := setUpFlagSet(&tristate)
- var buf bytes.Buffer
- f.SetOutput(&buf)
- err := f.Parse([]string{"--tristate=invalid"})
- if err == nil {
- t.Fatal("expected an error but did not get any, tristate has value", tristate)
- }
-}
-
-func TestBoolP(t *testing.T) {
- b := BoolP("bool", "b", false, "bool value in CommandLine")
- c := BoolP("c", "c", false, "other bool value")
- args := []string{"--bool"}
- if err := CommandLine.Parse(args); err != nil {
- t.Error("expected no error, got ", err)
- }
- if *b != true {
- t.Errorf("expected b=true got b=%v", *b)
- }
- if *c != false {
- t.Errorf("expect c=false got c=%v", *c)
- }
-}
diff --git a/vendor/github.com/spf13/pflag/count.go b/vendor/github.com/spf13/pflag/count.go
deleted file mode 100644
index 250a438..0000000
--- a/vendor/github.com/spf13/pflag/count.go
+++ /dev/null
@@ -1,96 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- count Value
-type countValue int
-
-func newCountValue(val int, p *int) *countValue {
- *p = val
- return (*countValue)(p)
-}
-
-func (i *countValue) Set(s string) error {
- v, err := strconv.ParseInt(s, 0, 64)
- // -1 means that no specific value was passed, so increment
- if v == -1 {
- *i = countValue(*i + 1)
- } else {
- *i = countValue(v)
- }
- return err
-}
-
-func (i *countValue) Type() string {
- return "count"
-}
-
-func (i *countValue) String() string { return strconv.Itoa(int(*i)) }
-
-func countConv(sval string) (interface{}, error) {
- i, err := strconv.Atoi(sval)
- if err != nil {
- return nil, err
- }
- return i, nil
-}
-
-// GetCount return the int value of a flag with the given name
-func (f *FlagSet) GetCount(name string) (int, error) {
- val, err := f.getFlagType(name, "count", countConv)
- if err != nil {
- return 0, err
- }
- return val.(int), nil
-}
-
-// CountVar defines a count flag with specified name, default value, and usage string.
-// The argument p points to an int variable in which to store the value of the flag.
-// A count flag will add 1 to its value evey time it is found on the command line
-func (f *FlagSet) CountVar(p *int, name string, usage string) {
- f.CountVarP(p, name, "", usage)
-}
-
-// CountVarP is like CountVar only take a shorthand for the flag name.
-func (f *FlagSet) CountVarP(p *int, name, shorthand string, usage string) {
- flag := f.VarPF(newCountValue(0, p), name, shorthand, usage)
- flag.NoOptDefVal = "-1"
-}
-
-// CountVar like CountVar only the flag is placed on the CommandLine instead of a given flag set
-func CountVar(p *int, name string, usage string) {
- CommandLine.CountVar(p, name, usage)
-}
-
-// CountVarP is like CountVar only take a shorthand for the flag name.
-func CountVarP(p *int, name, shorthand string, usage string) {
- CommandLine.CountVarP(p, name, shorthand, usage)
-}
-
-// Count defines a count flag with specified name, default value, and usage string.
-// The return value is the address of an int variable that stores the value of the flag.
-// A count flag will add 1 to its value evey time it is found on the command line
-func (f *FlagSet) Count(name string, usage string) *int {
- p := new(int)
- f.CountVarP(p, name, "", usage)
- return p
-}
-
-// CountP is like Count only takes a shorthand for the flag name.
-func (f *FlagSet) CountP(name, shorthand string, usage string) *int {
- p := new(int)
- f.CountVarP(p, name, shorthand, usage)
- return p
-}
-
-// Count defines a count flag with specified name, default value, and usage string.
-// The return value is the address of an int variable that stores the value of the flag.
-// A count flag will add 1 to its value evey time it is found on the command line
-func Count(name string, usage string) *int {
- return CommandLine.CountP(name, "", usage)
-}
-
-// CountP is like Count only takes a shorthand for the flag name.
-func CountP(name, shorthand string, usage string) *int {
- return CommandLine.CountP(name, shorthand, usage)
-}
diff --git a/vendor/github.com/spf13/pflag/count_test.go b/vendor/github.com/spf13/pflag/count_test.go
deleted file mode 100644
index 460d96a..0000000
--- a/vendor/github.com/spf13/pflag/count_test.go
+++ /dev/null
@@ -1,52 +0,0 @@
-package pflag
-
-import (
- "os"
- "testing"
-)
-
-func setUpCount(c *int) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.CountVarP(c, "verbose", "v", "a counter")
- return f
-}
-
-func TestCount(t *testing.T) {
- testCases := []struct {
- input []string
- success bool
- expected int
- }{
- {[]string{"-vvv"}, true, 3},
- {[]string{"-v", "-v", "-v"}, true, 3},
- {[]string{"-v", "--verbose", "-v"}, true, 3},
- {[]string{"-v=3", "-v"}, true, 4},
- {[]string{"-v=a"}, false, 0},
- }
-
- devnull, _ := os.Open(os.DevNull)
- os.Stderr = devnull
- for i := range testCases {
- var count int
- f := setUpCount(&count)
-
- tc := &testCases[i]
-
- err := f.Parse(tc.input)
- if err != nil && tc.success == true {
- t.Errorf("expected success, got %q", err)
- continue
- } else if err == nil && tc.success == false {
- t.Errorf("expected failure, got success")
- continue
- } else if tc.success {
- c, err := f.GetCount("verbose")
- if err != nil {
- t.Errorf("Got error trying to fetch the counter flag")
- }
- if c != tc.expected {
- t.Errorf("expected %q, got %q", tc.expected, c)
- }
- }
- }
-}
diff --git a/vendor/github.com/spf13/pflag/duration.go b/vendor/github.com/spf13/pflag/duration.go
deleted file mode 100644
index e9debef..0000000
--- a/vendor/github.com/spf13/pflag/duration.go
+++ /dev/null
@@ -1,86 +0,0 @@
-package pflag
-
-import (
- "time"
-)
-
-// -- time.Duration Value
-type durationValue time.Duration
-
-func newDurationValue(val time.Duration, p *time.Duration) *durationValue {
- *p = val
- return (*durationValue)(p)
-}
-
-func (d *durationValue) Set(s string) error {
- v, err := time.ParseDuration(s)
- *d = durationValue(v)
- return err
-}
-
-func (d *durationValue) Type() string {
- return "duration"
-}
-
-func (d *durationValue) String() string { return (*time.Duration)(d).String() }
-
-func durationConv(sval string) (interface{}, error) {
- return time.ParseDuration(sval)
-}
-
-// GetDuration return the duration value of a flag with the given name
-func (f *FlagSet) GetDuration(name string) (time.Duration, error) {
- val, err := f.getFlagType(name, "duration", durationConv)
- if err != nil {
- return 0, err
- }
- return val.(time.Duration), nil
-}
-
-// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
-// The argument p points to a time.Duration variable in which to store the value of the flag.
-func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
- f.VarP(newDurationValue(value, p), name, "", usage)
-}
-
-// DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) {
- f.VarP(newDurationValue(value, p), name, shorthand, usage)
-}
-
-// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
-// The argument p points to a time.Duration variable in which to store the value of the flag.
-func DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
- CommandLine.VarP(newDurationValue(value, p), name, "", usage)
-}
-
-// DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash.
-func DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) {
- CommandLine.VarP(newDurationValue(value, p), name, shorthand, usage)
-}
-
-// Duration defines a time.Duration flag with specified name, default value, and usage string.
-// The return value is the address of a time.Duration variable that stores the value of the flag.
-func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration {
- p := new(time.Duration)
- f.DurationVarP(p, name, "", value, usage)
- return p
-}
-
-// DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration {
- p := new(time.Duration)
- f.DurationVarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Duration defines a time.Duration flag with specified name, default value, and usage string.
-// The return value is the address of a time.Duration variable that stores the value of the flag.
-func Duration(name string, value time.Duration, usage string) *time.Duration {
- return CommandLine.DurationP(name, "", value, usage)
-}
-
-// DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash.
-func DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration {
- return CommandLine.DurationP(name, shorthand, value, usage)
-}
diff --git a/vendor/github.com/spf13/pflag/example_test.go b/vendor/github.com/spf13/pflag/example_test.go
deleted file mode 100644
index abd7806..0000000
--- a/vendor/github.com/spf13/pflag/example_test.go
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright 2012 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 pflag_test
-
-import (
- "fmt"
-
- "github.com/spf13/pflag"
-)
-
-func ExampleShorthandLookup() {
- name := "verbose"
- short := name[:1]
-
- pflag.BoolP(name, short, false, "verbose output")
-
- // len(short) must be == 1
- flag := pflag.ShorthandLookup(short)
-
- fmt.Println(flag.Name)
-}
-
-func ExampleFlagSet_ShorthandLookup() {
- name := "verbose"
- short := name[:1]
-
- fs := pflag.NewFlagSet("Example", pflag.ContinueOnError)
- fs.BoolP(name, short, false, "verbose output")
-
- // len(short) must be == 1
- flag := fs.ShorthandLookup(short)
-
- fmt.Println(flag.Name)
-}
diff --git a/vendor/github.com/spf13/pflag/export_test.go b/vendor/github.com/spf13/pflag/export_test.go
deleted file mode 100644
index 9318fee..0000000
--- a/vendor/github.com/spf13/pflag/export_test.go
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2010 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 pflag
-
-import (
- "io/ioutil"
- "os"
-)
-
-// Additional routines compiled into the package only during testing.
-
-// ResetForTesting clears all flag state and sets the usage function as directed.
-// After calling ResetForTesting, parse errors in flag handling will not
-// exit the program.
-func ResetForTesting(usage func()) {
- CommandLine = &FlagSet{
- name: os.Args[0],
- errorHandling: ContinueOnError,
- output: ioutil.Discard,
- }
- Usage = usage
-}
-
-// GetCommandLine returns the default FlagSet.
-func GetCommandLine() *FlagSet {
- return CommandLine
-}
diff --git a/vendor/github.com/spf13/pflag/flag.go b/vendor/github.com/spf13/pflag/flag.go
deleted file mode 100644
index 6f1fc30..0000000
--- a/vendor/github.com/spf13/pflag/flag.go
+++ /dev/null
@@ -1,1128 +0,0 @@
-// Copyright 2009 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 pflag is a drop-in replacement for Go's flag package, implementing
-POSIX/GNU-style --flags.
-
-pflag is compatible with the GNU extensions to the POSIX recommendations
-for command-line options. See
-http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
-
-Usage:
-
-pflag is a drop-in replacement of Go's native flag package. If you import
-pflag under the name "flag" then all code should continue to function
-with no changes.
-
- import flag "github.com/spf13/pflag"
-
-There is one exception to this: if you directly instantiate the Flag struct
-there is one more field "Shorthand" that you will need to set.
-Most code never instantiates this struct directly, and instead uses
-functions such as String(), BoolVar(), and Var(), and is therefore
-unaffected.
-
-Define flags using flag.String(), Bool(), Int(), etc.
-
-This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
- var ip = flag.Int("flagname", 1234, "help message for flagname")
-If you like, you can bind the flag to a variable using the Var() functions.
- var flagvar int
- func init() {
- flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
- }
-Or you can create custom flags that satisfy the Value interface (with
-pointer receivers) and couple them to flag parsing by
- flag.Var(&flagVal, "name", "help message for flagname")
-For such flags, the default value is just the initial value of the variable.
-
-After all flags are defined, call
- flag.Parse()
-to parse the command line into the defined flags.
-
-Flags may then be used directly. If you're using the flags themselves,
-they are all pointers; if you bind to variables, they're values.
- fmt.Println("ip has value ", *ip)
- fmt.Println("flagvar has value ", flagvar)
-
-After parsing, the arguments after the flag are available as the
-slice flag.Args() or individually as flag.Arg(i).
-The arguments are indexed from 0 through flag.NArg()-1.
-
-The pflag package also defines some new functions that are not in flag,
-that give one-letter shorthands for flags. You can use these by appending
-'P' to the name of any function that defines a flag.
- var ip = flag.IntP("flagname", "f", 1234, "help message")
- var flagvar bool
- func init() {
- flag.BoolVarP("boolname", "b", true, "help message")
- }
- flag.VarP(&flagVar, "varname", "v", 1234, "help message")
-Shorthand letters can be used with single dashes on the command line.
-Boolean shorthand flags can be combined with other shorthand flags.
-
-Command line flag syntax:
- --flag // boolean flags only
- --flag=x
-
-Unlike the flag package, a single dash before an option means something
-different than a double dash. Single dashes signify a series of shorthand
-letters for flags. All but the last shorthand letter must be boolean flags.
- // boolean flags
- -f
- -abc
- // non-boolean flags
- -n 1234
- -Ifile
- // mixed
- -abcs "hello"
- -abcn1234
-
-Flag parsing stops after the terminator "--". Unlike the flag package,
-flags can be interspersed with arguments anywhere on the command line
-before this terminator.
-
-Integer flags accept 1234, 0664, 0x1234 and may be negative.
-Boolean flags (in their long form) accept 1, 0, t, f, true, false,
-TRUE, FALSE, True, False.
-Duration flags accept any input valid for time.ParseDuration.
-
-The default set of command-line flags is controlled by
-top-level functions. The FlagSet type allows one to define
-independent sets of flags, such as to implement subcommands
-in a command-line interface. The methods of FlagSet are
-analogous to the top-level functions for the command-line
-flag set.
-*/
-package pflag
-
-import (
- "bytes"
- "errors"
- "fmt"
- "io"
- "os"
- "sort"
- "strings"
-)
-
-// ErrHelp is the error returned if the flag -help is invoked but no such flag is defined.
-var ErrHelp = errors.New("pflag: help requested")
-
-// ErrorHandling defines how to handle flag parsing errors.
-type ErrorHandling int
-
-const (
- // ContinueOnError will return an err from Parse() if an error is found
- ContinueOnError ErrorHandling = iota
- // ExitOnError will call os.Exit(2) if an error is found when parsing
- ExitOnError
- // PanicOnError will panic() if an error is found when parsing flags
- PanicOnError
-)
-
-// NormalizedName is a flag name that has been normalized according to rules
-// for the FlagSet (e.g. making '-' and '_' equivalent).
-type NormalizedName string
-
-// A FlagSet represents a set of defined flags.
-type FlagSet struct {
- // Usage is the function called when an error occurs while parsing flags.
- // The field is a function (not a method) that may be changed to point to
- // a custom error handler.
- Usage func()
-
- // SortFlags is used to indicate, if user wants to have sorted flags in
- // help/usage messages.
- SortFlags bool
-
- name string
- parsed bool
- actual map[NormalizedName]*Flag
- orderedActual []*Flag
- sortedActual []*Flag
- formal map[NormalizedName]*Flag
- orderedFormal []*Flag
- sortedFormal []*Flag
- shorthands map[byte]*Flag
- args []string // arguments after flags
- argsLenAtDash int // len(args) when a '--' was located when parsing, or -1 if no --
- errorHandling ErrorHandling
- output io.Writer // nil means stderr; use out() accessor
- interspersed bool // allow interspersed option/non-option args
- normalizeNameFunc func(f *FlagSet, name string) NormalizedName
-}
-
-// A Flag represents the state of a flag.
-type Flag struct {
- Name string // name as it appears on command line
- Shorthand string // one-letter abbreviated flag
- Usage string // help message
- Value Value // value as set
- DefValue string // default value (as text); for usage message
- Changed bool // If the user set the value (or if left to default)
- NoOptDefVal string // default value (as text); if the flag is on the command line without any options
- Deprecated string // If this flag is deprecated, this string is the new or now thing to use
- Hidden bool // used by cobra.Command to allow flags to be hidden from help/usage text
- ShorthandDeprecated string // If the shorthand of this flag is deprecated, this string is the new or now thing to use
- Annotations map[string][]string // used by cobra.Command bash autocomple code
-}
-
-// Value is the interface to the dynamic value stored in a flag.
-// (The default value is represented as a string.)
-type Value interface {
- String() string
- Set(string) error
- Type() string
-}
-
-// sortFlags returns the flags as a slice in lexicographical sorted order.
-func sortFlags(flags map[NormalizedName]*Flag) []*Flag {
- list := make(sort.StringSlice, len(flags))
- i := 0
- for k := range flags {
- list[i] = string(k)
- i++
- }
- list.Sort()
- result := make([]*Flag, len(list))
- for i, name := range list {
- result[i] = flags[NormalizedName(name)]
- }
- return result
-}
-
-// SetNormalizeFunc allows you to add a function which can translate flag names.
-// Flags added to the FlagSet will be translated and then when anything tries to
-// look up the flag that will also be translated. So it would be possible to create
-// a flag named "getURL" and have it translated to "geturl". A user could then pass
-// "--getUrl" which may also be translated to "geturl" and everything will work.
-func (f *FlagSet) SetNormalizeFunc(n func(f *FlagSet, name string) NormalizedName) {
- f.normalizeNameFunc = n
- f.sortedFormal = f.sortedFormal[:0]
- for k, v := range f.orderedFormal {
- delete(f.formal, NormalizedName(v.Name))
- nname := f.normalizeFlagName(v.Name)
- v.Name = string(nname)
- f.formal[nname] = v
- f.orderedFormal[k] = v
- }
-}
-
-// GetNormalizeFunc returns the previously set NormalizeFunc of a function which
-// does no translation, if not set previously.
-func (f *FlagSet) GetNormalizeFunc() func(f *FlagSet, name string) NormalizedName {
- if f.normalizeNameFunc != nil {
- return f.normalizeNameFunc
- }
- return func(f *FlagSet, name string) NormalizedName { return NormalizedName(name) }
-}
-
-func (f *FlagSet) normalizeFlagName(name string) NormalizedName {
- n := f.GetNormalizeFunc()
- return n(f, name)
-}
-
-func (f *FlagSet) out() io.Writer {
- if f.output == nil {
- return os.Stderr
- }
- return f.output
-}
-
-// SetOutput sets the destination for usage and error messages.
-// If output is nil, os.Stderr is used.
-func (f *FlagSet) SetOutput(output io.Writer) {
- f.output = output
-}
-
-// VisitAll visits the flags in lexicographical order or
-// in primordial order if f.SortFlags is false, calling fn for each.
-// It visits all flags, even those not set.
-func (f *FlagSet) VisitAll(fn func(*Flag)) {
- if len(f.formal) == 0 {
- return
- }
-
- var flags []*Flag
- if f.SortFlags {
- if len(f.formal) != len(f.sortedFormal) {
- f.sortedFormal = sortFlags(f.formal)
- }
- flags = f.sortedFormal
- } else {
- flags = f.orderedFormal
- }
-
- for _, flag := range flags {
- fn(flag)
- }
-}
-
-// HasFlags returns a bool to indicate if the FlagSet has any flags definied.
-func (f *FlagSet) HasFlags() bool {
- return len(f.formal) > 0
-}
-
-// HasAvailableFlags returns a bool to indicate if the FlagSet has any flags
-// definied that are not hidden or deprecated.
-func (f *FlagSet) HasAvailableFlags() bool {
- for _, flag := range f.formal {
- if !flag.Hidden && len(flag.Deprecated) == 0 {
- return true
- }
- }
- return false
-}
-
-// VisitAll visits the command-line flags in lexicographical order or
-// in primordial order if f.SortFlags is false, calling fn for each.
-// It visits all flags, even those not set.
-func VisitAll(fn func(*Flag)) {
- CommandLine.VisitAll(fn)
-}
-
-// Visit visits the flags in lexicographical order or
-// in primordial order if f.SortFlags is false, calling fn for each.
-// It visits only those flags that have been set.
-func (f *FlagSet) Visit(fn func(*Flag)) {
- if len(f.actual) == 0 {
- return
- }
-
- var flags []*Flag
- if f.SortFlags {
- if len(f.actual) != len(f.sortedActual) {
- f.sortedActual = sortFlags(f.actual)
- }
- flags = f.sortedActual
- } else {
- flags = f.orderedActual
- }
-
- for _, flag := range flags {
- fn(flag)
- }
-}
-
-// Visit visits the command-line flags in lexicographical order or
-// in primordial order if f.SortFlags is false, calling fn for each.
-// It visits only those flags that have been set.
-func Visit(fn func(*Flag)) {
- CommandLine.Visit(fn)
-}
-
-// Lookup returns the Flag structure of the named flag, returning nil if none exists.
-func (f *FlagSet) Lookup(name string) *Flag {
- return f.lookup(f.normalizeFlagName(name))
-}
-
-// ShorthandLookup returns the Flag structure of the short handed flag,
-// returning nil if none exists.
-// It panics, if len(name) > 1.
-func (f *FlagSet) ShorthandLookup(name string) *Flag {
- if name == "" {
- return nil
- }
- if len(name) > 1 {
- msg := fmt.Sprintf("can not look up shorthand which is more than one ASCII character: %q", name)
- fmt.Fprintf(f.out(), msg)
- panic(msg)
- }
- c := name[0]
- return f.shorthands[c]
-}
-
-// lookup returns the Flag structure of the named flag, returning nil if none exists.
-func (f *FlagSet) lookup(name NormalizedName) *Flag {
- return f.formal[name]
-}
-
-// func to return a given type for a given flag name
-func (f *FlagSet) getFlagType(name string, ftype string, convFunc func(sval string) (interface{}, error)) (interface{}, error) {
- flag := f.Lookup(name)
- if flag == nil {
- err := fmt.Errorf("flag accessed but not defined: %s", name)
- return nil, err
- }
-
- if flag.Value.Type() != ftype {
- err := fmt.Errorf("trying to get %s value of flag of type %s", ftype, flag.Value.Type())
- return nil, err
- }
-
- sval := flag.Value.String()
- result, err := convFunc(sval)
- if err != nil {
- return nil, err
- }
- return result, nil
-}
-
-// ArgsLenAtDash will return the length of f.Args at the moment when a -- was
-// found during arg parsing. This allows your program to know which args were
-// before the -- and which came after.
-func (f *FlagSet) ArgsLenAtDash() int {
- return f.argsLenAtDash
-}
-
-// MarkDeprecated indicated that a flag is deprecated in your program. It will
-// continue to function but will not show up in help or usage messages. Using
-// this flag will also print the given usageMessage.
-func (f *FlagSet) MarkDeprecated(name string, usageMessage string) error {
- flag := f.Lookup(name)
- if flag == nil {
- return fmt.Errorf("flag %q does not exist", name)
- }
- if usageMessage == "" {
- return fmt.Errorf("deprecated message for flag %q must be set", name)
- }
- flag.Deprecated = usageMessage
- return nil
-}
-
-// MarkShorthandDeprecated will mark the shorthand of a flag deprecated in your
-// program. It will continue to function but will not show up in help or usage
-// messages. Using this flag will also print the given usageMessage.
-func (f *FlagSet) MarkShorthandDeprecated(name string, usageMessage string) error {
- flag := f.Lookup(name)
- if flag == nil {
- return fmt.Errorf("flag %q does not exist", name)
- }
- if usageMessage == "" {
- return fmt.Errorf("deprecated message for flag %q must be set", name)
- }
- flag.ShorthandDeprecated = usageMessage
- return nil
-}
-
-// MarkHidden sets a flag to 'hidden' in your program. It will continue to
-// function but will not show up in help or usage messages.
-func (f *FlagSet) MarkHidden(name string) error {
- flag := f.Lookup(name)
- if flag == nil {
- return fmt.Errorf("flag %q does not exist", name)
- }
- flag.Hidden = true
- return nil
-}
-
-// Lookup returns the Flag structure of the named command-line flag,
-// returning nil if none exists.
-func Lookup(name string) *Flag {
- return CommandLine.Lookup(name)
-}
-
-// ShorthandLookup returns the Flag structure of the short handed flag,
-// returning nil if none exists.
-func ShorthandLookup(name string) *Flag {
- return CommandLine.ShorthandLookup(name)
-}
-
-// Set sets the value of the named flag.
-func (f *FlagSet) Set(name, value string) error {
- normalName := f.normalizeFlagName(name)
- flag, ok := f.formal[normalName]
- if !ok {
- return fmt.Errorf("no such flag -%v", name)
- }
-
- err := flag.Value.Set(value)
- if err != nil {
- var flagName string
- if flag.Shorthand != "" && flag.ShorthandDeprecated == "" {
- flagName = fmt.Sprintf("-%s, --%s", flag.Shorthand, flag.Name)
- } else {
- flagName = fmt.Sprintf("--%s", flag.Name)
- }
- return fmt.Errorf("invalid argument %q for %q flag: %v", value, flagName, err)
- }
-
- if f.actual == nil {
- f.actual = make(map[NormalizedName]*Flag)
- }
- f.actual[normalName] = flag
- f.orderedActual = append(f.orderedActual, flag)
-
- flag.Changed = true
-
- if flag.Deprecated != "" {
- fmt.Fprintf(f.out(), "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated)
- }
- return nil
-}
-
-// SetAnnotation allows one to set arbitrary annotations on a flag in the FlagSet.
-// This is sometimes used by spf13/cobra programs which want to generate additional
-// bash completion information.
-func (f *FlagSet) SetAnnotation(name, key string, values []string) error {
- normalName := f.normalizeFlagName(name)
- flag, ok := f.formal[normalName]
- if !ok {
- return fmt.Errorf("no such flag -%v", name)
- }
- if flag.Annotations == nil {
- flag.Annotations = map[string][]string{}
- }
- flag.Annotations[key] = values
- return nil
-}
-
-// Changed returns true if the flag was explicitly set during Parse() and false
-// otherwise
-func (f *FlagSet) Changed(name string) bool {
- flag := f.Lookup(name)
- // If a flag doesn't exist, it wasn't changed....
- if flag == nil {
- return false
- }
- return flag.Changed
-}
-
-// Set sets the value of the named command-line flag.
-func Set(name, value string) error {
- return CommandLine.Set(name, value)
-}
-
-// PrintDefaults prints, to standard error unless configured
-// otherwise, the default values of all defined flags in the set.
-func (f *FlagSet) PrintDefaults() {
- usages := f.FlagUsages()
- fmt.Fprint(f.out(), usages)
-}
-
-// defaultIsZeroValue returns true if the default value for this flag represents
-// a zero value.
-func (f *Flag) defaultIsZeroValue() bool {
- switch f.Value.(type) {
- case boolFlag:
- return f.DefValue == "false"
- case *durationValue:
- // Beginning in Go 1.7, duration zero values are "0s"
- return f.DefValue == "0" || f.DefValue == "0s"
- case *intValue, *int8Value, *int32Value, *int64Value, *uintValue, *uint8Value, *uint16Value, *uint32Value, *uint64Value, *countValue, *float32Value, *float64Value:
- return f.DefValue == "0"
- case *stringValue:
- return f.DefValue == ""
- case *ipValue, *ipMaskValue, *ipNetValue:
- return f.DefValue == ""
- case *intSliceValue, *stringSliceValue, *stringArrayValue:
- return f.DefValue == "[]"
- default:
- switch f.Value.String() {
- case "false":
- return true
- case "":
- return true
- case "":
- return true
- case "0":
- return true
- }
- return false
- }
-}
-
-// UnquoteUsage extracts a back-quoted name from the usage
-// string for a flag and returns it and the un-quoted usage.
-// Given "a `name` to show" it returns ("name", "a name to show").
-// If there are no back quotes, the name is an educated guess of the
-// type of the flag's value, or the empty string if the flag is boolean.
-func UnquoteUsage(flag *Flag) (name string, usage string) {
- // Look for a back-quoted name, but avoid the strings package.
- usage = flag.Usage
- for i := 0; i < len(usage); i++ {
- if usage[i] == '`' {
- for j := i + 1; j < len(usage); j++ {
- if usage[j] == '`' {
- name = usage[i+1 : j]
- usage = usage[:i] + name + usage[j+1:]
- return name, usage
- }
- }
- break // Only one back quote; use type name.
- }
- }
-
- name = flag.Value.Type()
- switch name {
- case "bool":
- name = ""
- case "float64":
- name = "float"
- case "int64":
- name = "int"
- case "uint64":
- name = "uint"
- }
-
- return
-}
-
-// Splits the string `s` on whitespace into an initial substring up to
-// `i` runes in length and the remainder. Will go `slop` over `i` if
-// that encompasses the entire string (which allows the caller to
-// avoid short orphan words on the final line).
-func wrapN(i, slop int, s string) (string, string) {
- if i+slop > len(s) {
- return s, ""
- }
-
- w := strings.LastIndexAny(s[:i], " \t")
- if w <= 0 {
- return s, ""
- }
-
- return s[:w], s[w+1:]
-}
-
-// Wraps the string `s` to a maximum width `w` with leading indent
-// `i`. The first line is not indented (this is assumed to be done by
-// caller). Pass `w` == 0 to do no wrapping
-func wrap(i, w int, s string) string {
- if w == 0 {
- return s
- }
-
- // space between indent i and end of line width w into which
- // we should wrap the text.
- wrap := w - i
-
- var r, l string
-
- // Not enough space for sensible wrapping. Wrap as a block on
- // the next line instead.
- if wrap < 24 {
- i = 16
- wrap = w - i
- r += "\n" + strings.Repeat(" ", i)
- }
- // If still not enough space then don't even try to wrap.
- if wrap < 24 {
- return s
- }
-
- // Try to avoid short orphan words on the final line, by
- // allowing wrapN to go a bit over if that would fit in the
- // remainder of the line.
- slop := 5
- wrap = wrap - slop
-
- // Handle first line, which is indented by the caller (or the
- // special case above)
- l, s = wrapN(wrap, slop, s)
- r = r + l
-
- // Now wrap the rest
- for s != "" {
- var t string
-
- t, s = wrapN(wrap, slop, s)
- r = r + "\n" + strings.Repeat(" ", i) + t
- }
-
- return r
-
-}
-
-// FlagUsagesWrapped returns a string containing the usage information
-// for all flags in the FlagSet. Wrapped to `cols` columns (0 for no
-// wrapping)
-func (f *FlagSet) FlagUsagesWrapped(cols int) string {
- buf := new(bytes.Buffer)
-
- lines := make([]string, 0, len(f.formal))
-
- maxlen := 0
- f.VisitAll(func(flag *Flag) {
- if flag.Deprecated != "" || flag.Hidden {
- return
- }
-
- line := ""
- if flag.Shorthand != "" && flag.ShorthandDeprecated == "" {
- line = fmt.Sprintf(" -%s, --%s", flag.Shorthand, flag.Name)
- } else {
- line = fmt.Sprintf(" --%s", flag.Name)
- }
-
- varname, usage := UnquoteUsage(flag)
- if varname != "" {
- line += " " + varname
- }
- if flag.NoOptDefVal != "" {
- switch flag.Value.Type() {
- case "string":
- line += fmt.Sprintf("[=\"%s\"]", flag.NoOptDefVal)
- case "bool":
- if flag.NoOptDefVal != "true" {
- line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
- }
- default:
- line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
- }
- }
-
- // This special character will be replaced with spacing once the
- // correct alignment is calculated
- line += "\x00"
- if len(line) > maxlen {
- maxlen = len(line)
- }
-
- line += usage
- if !flag.defaultIsZeroValue() {
- if flag.Value.Type() == "string" {
- line += fmt.Sprintf(" (default %q)", flag.DefValue)
- } else {
- line += fmt.Sprintf(" (default %s)", flag.DefValue)
- }
- }
-
- lines = append(lines, line)
- })
-
- for _, line := range lines {
- sidx := strings.Index(line, "\x00")
- spacing := strings.Repeat(" ", maxlen-sidx)
- // maxlen + 2 comes from + 1 for the \x00 and + 1 for the (deliberate) off-by-one in maxlen-sidx
- fmt.Fprintln(buf, line[:sidx], spacing, wrap(maxlen+2, cols, line[sidx+1:]))
- }
-
- return buf.String()
-}
-
-// FlagUsages returns a string containing the usage information for all flags in
-// the FlagSet
-func (f *FlagSet) FlagUsages() string {
- return f.FlagUsagesWrapped(0)
-}
-
-// PrintDefaults prints to standard error the default values of all defined command-line flags.
-func PrintDefaults() {
- CommandLine.PrintDefaults()
-}
-
-// defaultUsage is the default function to print a usage message.
-func defaultUsage(f *FlagSet) {
- fmt.Fprintf(f.out(), "Usage of %s:\n", f.name)
- f.PrintDefaults()
-}
-
-// NOTE: Usage is not just defaultUsage(CommandLine)
-// because it serves (via godoc flag Usage) as the example
-// for how to write your own usage function.
-
-// Usage prints to standard error a usage message documenting all defined command-line flags.
-// The function is a variable that may be changed to point to a custom function.
-// By default it prints a simple header and calls PrintDefaults; for details about the
-// format of the output and how to control it, see the documentation for PrintDefaults.
-var Usage = func() {
- fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
- PrintDefaults()
-}
-
-// NFlag returns the number of flags that have been set.
-func (f *FlagSet) NFlag() int { return len(f.actual) }
-
-// NFlag returns the number of command-line flags that have been set.
-func NFlag() int { return len(CommandLine.actual) }
-
-// Arg returns the i'th argument. Arg(0) is the first remaining argument
-// after flags have been processed.
-func (f *FlagSet) Arg(i int) string {
- if i < 0 || i >= len(f.args) {
- return ""
- }
- return f.args[i]
-}
-
-// Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
-// after flags have been processed.
-func Arg(i int) string {
- return CommandLine.Arg(i)
-}
-
-// NArg is the number of arguments remaining after flags have been processed.
-func (f *FlagSet) NArg() int { return len(f.args) }
-
-// NArg is the number of arguments remaining after flags have been processed.
-func NArg() int { return len(CommandLine.args) }
-
-// Args returns the non-flag arguments.
-func (f *FlagSet) Args() []string { return f.args }
-
-// Args returns the non-flag command-line arguments.
-func Args() []string { return CommandLine.args }
-
-// Var defines a flag with the specified name and usage string. The type and
-// value of the flag are represented by the first argument, of type Value, which
-// typically holds a user-defined implementation of Value. For instance, the
-// caller could create a flag that turns a comma-separated string into a slice
-// of strings by giving the slice the methods of Value; in particular, Set would
-// decompose the comma-separated string into the slice.
-func (f *FlagSet) Var(value Value, name string, usage string) {
- f.VarP(value, name, "", usage)
-}
-
-// VarPF is like VarP, but returns the flag created
-func (f *FlagSet) VarPF(value Value, name, shorthand, usage string) *Flag {
- // Remember the default value as a string; it won't change.
- flag := &Flag{
- Name: name,
- Shorthand: shorthand,
- Usage: usage,
- Value: value,
- DefValue: value.String(),
- }
- f.AddFlag(flag)
- return flag
-}
-
-// VarP is like Var, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) VarP(value Value, name, shorthand, usage string) {
- f.VarPF(value, name, shorthand, usage)
-}
-
-// AddFlag will add the flag to the FlagSet
-func (f *FlagSet) AddFlag(flag *Flag) {
- normalizedFlagName := f.normalizeFlagName(flag.Name)
-
- _, alreadyThere := f.formal[normalizedFlagName]
- if alreadyThere {
- msg := fmt.Sprintf("%s flag redefined: %s", f.name, flag.Name)
- fmt.Fprintln(f.out(), msg)
- panic(msg) // Happens only if flags are declared with identical names
- }
- if f.formal == nil {
- f.formal = make(map[NormalizedName]*Flag)
- }
-
- flag.Name = string(normalizedFlagName)
- f.formal[normalizedFlagName] = flag
- f.orderedFormal = append(f.orderedFormal, flag)
-
- if flag.Shorthand == "" {
- return
- }
- if len(flag.Shorthand) > 1 {
- msg := fmt.Sprintf("%q shorthand is more than one ASCII character", flag.Shorthand)
- fmt.Fprintf(f.out(), msg)
- panic(msg)
- }
- if f.shorthands == nil {
- f.shorthands = make(map[byte]*Flag)
- }
- c := flag.Shorthand[0]
- used, alreadyThere := f.shorthands[c]
- if alreadyThere {
- msg := fmt.Sprintf("unable to redefine %q shorthand in %q flagset: it's already used for %q flag", c, f.name, used.Name)
- fmt.Fprintf(f.out(), msg)
- panic(msg)
- }
- f.shorthands[c] = flag
-}
-
-// AddFlagSet adds one FlagSet to another. If a flag is already present in f
-// the flag from newSet will be ignored.
-func (f *FlagSet) AddFlagSet(newSet *FlagSet) {
- if newSet == nil {
- return
- }
- newSet.VisitAll(func(flag *Flag) {
- if f.Lookup(flag.Name) == nil {
- f.AddFlag(flag)
- }
- })
-}
-
-// Var defines a flag with the specified name and usage string. The type and
-// value of the flag are represented by the first argument, of type Value, which
-// typically holds a user-defined implementation of Value. For instance, the
-// caller could create a flag that turns a comma-separated string into a slice
-// of strings by giving the slice the methods of Value; in particular, Set would
-// decompose the comma-separated string into the slice.
-func Var(value Value, name string, usage string) {
- CommandLine.VarP(value, name, "", usage)
-}
-
-// VarP is like Var, but accepts a shorthand letter that can be used after a single dash.
-func VarP(value Value, name, shorthand, usage string) {
- CommandLine.VarP(value, name, shorthand, usage)
-}
-
-// failf prints to standard error a formatted error and usage message and
-// returns the error.
-func (f *FlagSet) failf(format string, a ...interface{}) error {
- err := fmt.Errorf(format, a...)
- fmt.Fprintln(f.out(), err)
- f.usage()
- return err
-}
-
-// usage calls the Usage method for the flag set, or the usage function if
-// the flag set is CommandLine.
-func (f *FlagSet) usage() {
- if f == CommandLine {
- Usage()
- } else if f.Usage == nil {
- defaultUsage(f)
- } else {
- f.Usage()
- }
-}
-
-func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []string, err error) {
- a = args
- name := s[2:]
- if len(name) == 0 || name[0] == '-' || name[0] == '=' {
- err = f.failf("bad flag syntax: %s", s)
- return
- }
-
- split := strings.SplitN(name, "=", 2)
- name = split[0]
- flag, exists := f.formal[f.normalizeFlagName(name)]
- if !exists {
- if name == "help" { // special case for nice help message.
- f.usage()
- return a, ErrHelp
- }
- err = f.failf("unknown flag: --%s", name)
- return
- }
-
- var value string
- if len(split) == 2 {
- // '--flag=arg'
- value = split[1]
- } else if flag.NoOptDefVal != "" {
- // '--flag' (arg was optional)
- value = flag.NoOptDefVal
- } else if len(a) > 0 {
- // '--flag arg'
- value = a[0]
- a = a[1:]
- } else {
- // '--flag' (arg was required)
- err = f.failf("flag needs an argument: %s", s)
- return
- }
-
- err = fn(flag, value)
- return
-}
-
-func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parseFunc) (outShorts string, outArgs []string, err error) {
- if strings.HasPrefix(shorthands, "test.") {
- return
- }
-
- outArgs = args
- outShorts = shorthands[1:]
- c := shorthands[0]
-
- flag, exists := f.shorthands[c]
- if !exists {
- if c == 'h' { // special case for nice help message.
- f.usage()
- err = ErrHelp
- return
- }
- err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands)
- return
- }
-
- var value string
- if len(shorthands) > 2 && shorthands[1] == '=' {
- // '-f=arg'
- value = shorthands[2:]
- outShorts = ""
- } else if flag.NoOptDefVal != "" {
- // '-f' (arg was optional)
- value = flag.NoOptDefVal
- } else if len(shorthands) > 1 {
- // '-farg'
- value = shorthands[1:]
- outShorts = ""
- } else if len(args) > 0 {
- // '-f arg'
- value = args[0]
- outArgs = args[1:]
- } else {
- // '-f' (arg was required)
- err = f.failf("flag needs an argument: %q in -%s", c, shorthands)
- return
- }
-
- if flag.ShorthandDeprecated != "" {
- fmt.Fprintf(f.out(), "Flag shorthand -%s has been deprecated, %s\n", flag.Shorthand, flag.ShorthandDeprecated)
- }
-
- err = fn(flag, value)
- return
-}
-
-func (f *FlagSet) parseShortArg(s string, args []string, fn parseFunc) (a []string, err error) {
- a = args
- shorthands := s[1:]
-
- // "shorthands" can be a series of shorthand letters of flags (e.g. "-vvv").
- for len(shorthands) > 0 {
- shorthands, a, err = f.parseSingleShortArg(shorthands, args, fn)
- if err != nil {
- return
- }
- }
-
- return
-}
-
-func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) {
- for len(args) > 0 {
- s := args[0]
- args = args[1:]
- if len(s) == 0 || s[0] != '-' || len(s) == 1 {
- if !f.interspersed {
- f.args = append(f.args, s)
- f.args = append(f.args, args...)
- return nil
- }
- f.args = append(f.args, s)
- continue
- }
-
- if s[1] == '-' {
- if len(s) == 2 { // "--" terminates the flags
- f.argsLenAtDash = len(f.args)
- f.args = append(f.args, args...)
- break
- }
- args, err = f.parseLongArg(s, args, fn)
- } else {
- args, err = f.parseShortArg(s, args, fn)
- }
- if err != nil {
- return
- }
- }
- return
-}
-
-// Parse parses flag definitions from the argument list, which should not
-// include the command name. Must be called after all flags in the FlagSet
-// are defined and before flags are accessed by the program.
-// The return value will be ErrHelp if -help was set but not defined.
-func (f *FlagSet) Parse(arguments []string) error {
- f.parsed = true
-
- if len(arguments) < 0 {
- return nil
- }
-
- f.args = make([]string, 0, len(arguments))
-
- set := func(flag *Flag, value string) error {
- return f.Set(flag.Name, value)
- }
-
- err := f.parseArgs(arguments, set)
- if err != nil {
- switch f.errorHandling {
- case ContinueOnError:
- return err
- case ExitOnError:
- os.Exit(2)
- case PanicOnError:
- panic(err)
- }
- }
- return nil
-}
-
-type parseFunc func(flag *Flag, value string) error
-
-// ParseAll parses flag definitions from the argument list, which should not
-// include the command name. The arguments for fn are flag and value. Must be
-// called after all flags in the FlagSet are defined and before flags are
-// accessed by the program. The return value will be ErrHelp if -help was set
-// but not defined.
-func (f *FlagSet) ParseAll(arguments []string, fn func(flag *Flag, value string) error) error {
- f.parsed = true
- f.args = make([]string, 0, len(arguments))
-
- err := f.parseArgs(arguments, fn)
- if err != nil {
- switch f.errorHandling {
- case ContinueOnError:
- return err
- case ExitOnError:
- os.Exit(2)
- case PanicOnError:
- panic(err)
- }
- }
- return nil
-}
-
-// Parsed reports whether f.Parse has been called.
-func (f *FlagSet) Parsed() bool {
- return f.parsed
-}
-
-// Parse parses the command-line flags from os.Args[1:]. Must be called
-// after all flags are defined and before flags are accessed by the program.
-func Parse() {
- // Ignore errors; CommandLine is set for ExitOnError.
- CommandLine.Parse(os.Args[1:])
-}
-
-// ParseAll parses the command-line flags from os.Args[1:] and called fn for each.
-// The arguments for fn are flag and value. Must be called after all flags are
-// defined and before flags are accessed by the program.
-func ParseAll(fn func(flag *Flag, value string) error) {
- // Ignore errors; CommandLine is set for ExitOnError.
- CommandLine.ParseAll(os.Args[1:], fn)
-}
-
-// SetInterspersed sets whether to support interspersed option/non-option arguments.
-func SetInterspersed(interspersed bool) {
- CommandLine.SetInterspersed(interspersed)
-}
-
-// Parsed returns true if the command-line flags have been parsed.
-func Parsed() bool {
- return CommandLine.Parsed()
-}
-
-// CommandLine is the default set of command-line flags, parsed from os.Args.
-var CommandLine = NewFlagSet(os.Args[0], ExitOnError)
-
-// NewFlagSet returns a new, empty flag set with the specified name,
-// error handling property and SortFlags set to true.
-func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
- f := &FlagSet{
- name: name,
- errorHandling: errorHandling,
- argsLenAtDash: -1,
- interspersed: true,
- SortFlags: true,
- }
- return f
-}
-
-// SetInterspersed sets whether to support interspersed option/non-option arguments.
-func (f *FlagSet) SetInterspersed(interspersed bool) {
- f.interspersed = interspersed
-}
-
-// Init sets the name and error handling property for a flag set.
-// By default, the zero FlagSet uses an empty name and the
-// ContinueOnError error handling policy.
-func (f *FlagSet) Init(name string, errorHandling ErrorHandling) {
- f.name = name
- f.errorHandling = errorHandling
- f.argsLenAtDash = -1
-}
diff --git a/vendor/github.com/spf13/pflag/flag_test.go b/vendor/github.com/spf13/pflag/flag_test.go
deleted file mode 100644
index c3def0f..0000000
--- a/vendor/github.com/spf13/pflag/flag_test.go
+++ /dev/null
@@ -1,1085 +0,0 @@
-// Copyright 2009 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 pflag
-
-import (
- "bytes"
- "fmt"
- "io"
- "io/ioutil"
- "net"
- "os"
- "reflect"
- "sort"
- "strconv"
- "strings"
- "testing"
- "time"
-)
-
-var (
- testBool = Bool("test_bool", false, "bool value")
- testInt = Int("test_int", 0, "int value")
- testInt64 = Int64("test_int64", 0, "int64 value")
- testUint = Uint("test_uint", 0, "uint value")
- testUint64 = Uint64("test_uint64", 0, "uint64 value")
- testString = String("test_string", "0", "string value")
- testFloat = Float64("test_float64", 0, "float64 value")
- testDuration = Duration("test_duration", 0, "time.Duration value")
- testOptionalInt = Int("test_optional_int", 0, "optional int value")
- normalizeFlagNameInvocations = 0
-)
-
-func boolString(s string) string {
- if s == "0" {
- return "false"
- }
- return "true"
-}
-
-func TestEverything(t *testing.T) {
- m := make(map[string]*Flag)
- desired := "0"
- visitor := func(f *Flag) {
- if len(f.Name) > 5 && f.Name[0:5] == "test_" {
- m[f.Name] = f
- ok := false
- switch {
- case f.Value.String() == desired:
- ok = true
- case f.Name == "test_bool" && f.Value.String() == boolString(desired):
- ok = true
- case f.Name == "test_duration" && f.Value.String() == desired+"s":
- ok = true
- }
- if !ok {
- t.Error("Visit: bad value", f.Value.String(), "for", f.Name)
- }
- }
- }
- VisitAll(visitor)
- if len(m) != 9 {
- t.Error("VisitAll misses some flags")
- for k, v := range m {
- t.Log(k, *v)
- }
- }
- m = make(map[string]*Flag)
- Visit(visitor)
- if len(m) != 0 {
- t.Errorf("Visit sees unset flags")
- for k, v := range m {
- t.Log(k, *v)
- }
- }
- // Now set all flags
- Set("test_bool", "true")
- Set("test_int", "1")
- Set("test_int64", "1")
- Set("test_uint", "1")
- Set("test_uint64", "1")
- Set("test_string", "1")
- Set("test_float64", "1")
- Set("test_duration", "1s")
- Set("test_optional_int", "1")
- desired = "1"
- Visit(visitor)
- if len(m) != 9 {
- t.Error("Visit fails after set")
- for k, v := range m {
- t.Log(k, *v)
- }
- }
- // Now test they're visited in sort order.
- var flagNames []string
- Visit(func(f *Flag) { flagNames = append(flagNames, f.Name) })
- if !sort.StringsAreSorted(flagNames) {
- t.Errorf("flag names not sorted: %v", flagNames)
- }
-}
-
-func TestUsage(t *testing.T) {
- called := false
- ResetForTesting(func() { called = true })
- if GetCommandLine().Parse([]string{"--x"}) == nil {
- t.Error("parse did not fail for unknown flag")
- }
- if !called {
- t.Error("did not call Usage for unknown flag")
- }
-}
-
-func TestAddFlagSet(t *testing.T) {
- oldSet := NewFlagSet("old", ContinueOnError)
- newSet := NewFlagSet("new", ContinueOnError)
-
- oldSet.String("flag1", "flag1", "flag1")
- oldSet.String("flag2", "flag2", "flag2")
-
- newSet.String("flag2", "flag2", "flag2")
- newSet.String("flag3", "flag3", "flag3")
-
- oldSet.AddFlagSet(newSet)
-
- if len(oldSet.formal) != 3 {
- t.Errorf("Unexpected result adding a FlagSet to a FlagSet %v", oldSet)
- }
-}
-
-func TestAnnotation(t *testing.T) {
- f := NewFlagSet("shorthand", ContinueOnError)
-
- if err := f.SetAnnotation("missing-flag", "key", nil); err == nil {
- t.Errorf("Expected error setting annotation on non-existent flag")
- }
-
- f.StringP("stringa", "a", "", "string value")
- if err := f.SetAnnotation("stringa", "key", nil); err != nil {
- t.Errorf("Unexpected error setting new nil annotation: %v", err)
- }
- if annotation := f.Lookup("stringa").Annotations["key"]; annotation != nil {
- t.Errorf("Unexpected annotation: %v", annotation)
- }
-
- f.StringP("stringb", "b", "", "string2 value")
- if err := f.SetAnnotation("stringb", "key", []string{"value1"}); err != nil {
- t.Errorf("Unexpected error setting new annotation: %v", err)
- }
- if annotation := f.Lookup("stringb").Annotations["key"]; !reflect.DeepEqual(annotation, []string{"value1"}) {
- t.Errorf("Unexpected annotation: %v", annotation)
- }
-
- if err := f.SetAnnotation("stringb", "key", []string{"value2"}); err != nil {
- t.Errorf("Unexpected error updating annotation: %v", err)
- }
- if annotation := f.Lookup("stringb").Annotations["key"]; !reflect.DeepEqual(annotation, []string{"value2"}) {
- t.Errorf("Unexpected annotation: %v", annotation)
- }
-}
-
-func testParse(f *FlagSet, t *testing.T) {
- if f.Parsed() {
- t.Error("f.Parse() = true before Parse")
- }
- boolFlag := f.Bool("bool", false, "bool value")
- bool2Flag := f.Bool("bool2", false, "bool2 value")
- bool3Flag := f.Bool("bool3", false, "bool3 value")
- intFlag := f.Int("int", 0, "int value")
- int8Flag := f.Int8("int8", 0, "int value")
- int32Flag := f.Int32("int32", 0, "int value")
- int64Flag := f.Int64("int64", 0, "int64 value")
- uintFlag := f.Uint("uint", 0, "uint value")
- uint8Flag := f.Uint8("uint8", 0, "uint value")
- uint16Flag := f.Uint16("uint16", 0, "uint value")
- uint32Flag := f.Uint32("uint32", 0, "uint value")
- uint64Flag := f.Uint64("uint64", 0, "uint64 value")
- stringFlag := f.String("string", "0", "string value")
- float32Flag := f.Float32("float32", 0, "float32 value")
- float64Flag := f.Float64("float64", 0, "float64 value")
- ipFlag := f.IP("ip", net.ParseIP("127.0.0.1"), "ip value")
- maskFlag := f.IPMask("mask", ParseIPv4Mask("0.0.0.0"), "mask value")
- durationFlag := f.Duration("duration", 5*time.Second, "time.Duration value")
- optionalIntNoValueFlag := f.Int("optional-int-no-value", 0, "int value")
- f.Lookup("optional-int-no-value").NoOptDefVal = "9"
- optionalIntWithValueFlag := f.Int("optional-int-with-value", 0, "int value")
- f.Lookup("optional-int-no-value").NoOptDefVal = "9"
- extra := "one-extra-argument"
- args := []string{
- "--bool",
- "--bool2=true",
- "--bool3=false",
- "--int=22",
- "--int8=-8",
- "--int32=-32",
- "--int64=0x23",
- "--uint", "24",
- "--uint8=8",
- "--uint16=16",
- "--uint32=32",
- "--uint64=25",
- "--string=hello",
- "--float32=-172e12",
- "--float64=2718e28",
- "--ip=10.11.12.13",
- "--mask=255.255.255.0",
- "--duration=2m",
- "--optional-int-no-value",
- "--optional-int-with-value=42",
- extra,
- }
- if err := f.Parse(args); err != nil {
- t.Fatal(err)
- }
- if !f.Parsed() {
- t.Error("f.Parse() = false after Parse")
- }
- if *boolFlag != true {
- t.Error("bool flag should be true, is ", *boolFlag)
- }
- if v, err := f.GetBool("bool"); err != nil || v != *boolFlag {
- t.Error("GetBool does not work.")
- }
- if *bool2Flag != true {
- t.Error("bool2 flag should be true, is ", *bool2Flag)
- }
- if *bool3Flag != false {
- t.Error("bool3 flag should be false, is ", *bool2Flag)
- }
- if *intFlag != 22 {
- t.Error("int flag should be 22, is ", *intFlag)
- }
- if v, err := f.GetInt("int"); err != nil || v != *intFlag {
- t.Error("GetInt does not work.")
- }
- if *int8Flag != -8 {
- t.Error("int8 flag should be 0x23, is ", *int8Flag)
- }
- if v, err := f.GetInt8("int8"); err != nil || v != *int8Flag {
- t.Error("GetInt8 does not work.")
- }
- if *int32Flag != -32 {
- t.Error("int32 flag should be 0x23, is ", *int32Flag)
- }
- if v, err := f.GetInt32("int32"); err != nil || v != *int32Flag {
- t.Error("GetInt32 does not work.")
- }
- if *int64Flag != 0x23 {
- t.Error("int64 flag should be 0x23, is ", *int64Flag)
- }
- if v, err := f.GetInt64("int64"); err != nil || v != *int64Flag {
- t.Error("GetInt64 does not work.")
- }
- if *uintFlag != 24 {
- t.Error("uint flag should be 24, is ", *uintFlag)
- }
- if v, err := f.GetUint("uint"); err != nil || v != *uintFlag {
- t.Error("GetUint does not work.")
- }
- if *uint8Flag != 8 {
- t.Error("uint8 flag should be 8, is ", *uint8Flag)
- }
- if v, err := f.GetUint8("uint8"); err != nil || v != *uint8Flag {
- t.Error("GetUint8 does not work.")
- }
- if *uint16Flag != 16 {
- t.Error("uint16 flag should be 16, is ", *uint16Flag)
- }
- if v, err := f.GetUint16("uint16"); err != nil || v != *uint16Flag {
- t.Error("GetUint16 does not work.")
- }
- if *uint32Flag != 32 {
- t.Error("uint32 flag should be 32, is ", *uint32Flag)
- }
- if v, err := f.GetUint32("uint32"); err != nil || v != *uint32Flag {
- t.Error("GetUint32 does not work.")
- }
- if *uint64Flag != 25 {
- t.Error("uint64 flag should be 25, is ", *uint64Flag)
- }
- if v, err := f.GetUint64("uint64"); err != nil || v != *uint64Flag {
- t.Error("GetUint64 does not work.")
- }
- if *stringFlag != "hello" {
- t.Error("string flag should be `hello`, is ", *stringFlag)
- }
- if v, err := f.GetString("string"); err != nil || v != *stringFlag {
- t.Error("GetString does not work.")
- }
- if *float32Flag != -172e12 {
- t.Error("float32 flag should be -172e12, is ", *float32Flag)
- }
- if v, err := f.GetFloat32("float32"); err != nil || v != *float32Flag {
- t.Errorf("GetFloat32 returned %v but float32Flag was %v", v, *float32Flag)
- }
- if *float64Flag != 2718e28 {
- t.Error("float64 flag should be 2718e28, is ", *float64Flag)
- }
- if v, err := f.GetFloat64("float64"); err != nil || v != *float64Flag {
- t.Errorf("GetFloat64 returned %v but float64Flag was %v", v, *float64Flag)
- }
- if !(*ipFlag).Equal(net.ParseIP("10.11.12.13")) {
- t.Error("ip flag should be 10.11.12.13, is ", *ipFlag)
- }
- if v, err := f.GetIP("ip"); err != nil || !v.Equal(*ipFlag) {
- t.Errorf("GetIP returned %v but ipFlag was %v", v, *ipFlag)
- }
- if (*maskFlag).String() != ParseIPv4Mask("255.255.255.0").String() {
- t.Error("mask flag should be 255.255.255.0, is ", (*maskFlag).String())
- }
- if v, err := f.GetIPv4Mask("mask"); err != nil || v.String() != (*maskFlag).String() {
- t.Errorf("GetIP returned %v maskFlag was %v error was %v", v, *maskFlag, err)
- }
- if *durationFlag != 2*time.Minute {
- t.Error("duration flag should be 2m, is ", *durationFlag)
- }
- if v, err := f.GetDuration("duration"); err != nil || v != *durationFlag {
- t.Error("GetDuration does not work.")
- }
- if _, err := f.GetInt("duration"); err == nil {
- t.Error("GetInt parsed a time.Duration?!?!")
- }
- if *optionalIntNoValueFlag != 9 {
- t.Error("optional int flag should be the default value, is ", *optionalIntNoValueFlag)
- }
- if *optionalIntWithValueFlag != 42 {
- t.Error("optional int flag should be 42, is ", *optionalIntWithValueFlag)
- }
- if len(f.Args()) != 1 {
- t.Error("expected one argument, got", len(f.Args()))
- } else if f.Args()[0] != extra {
- t.Errorf("expected argument %q got %q", extra, f.Args()[0])
- }
-}
-
-func testParseAll(f *FlagSet, t *testing.T) {
- if f.Parsed() {
- t.Error("f.Parse() = true before Parse")
- }
- f.BoolP("boola", "a", false, "bool value")
- f.BoolP("boolb", "b", false, "bool2 value")
- f.BoolP("boolc", "c", false, "bool3 value")
- f.BoolP("boold", "d", false, "bool4 value")
- f.StringP("stringa", "s", "0", "string value")
- f.StringP("stringz", "z", "0", "string value")
- f.StringP("stringx", "x", "0", "string value")
- f.StringP("stringy", "y", "0", "string value")
- f.Lookup("stringx").NoOptDefVal = "1"
- args := []string{
- "-ab",
- "-cs=xx",
- "--stringz=something",
- "-d=true",
- "-x",
- "-y",
- "ee",
- }
- want := []string{
- "boola", "true",
- "boolb", "true",
- "boolc", "true",
- "stringa", "xx",
- "stringz", "something",
- "boold", "true",
- "stringx", "1",
- "stringy", "ee",
- }
- got := []string{}
- store := func(flag *Flag, value string) error {
- got = append(got, flag.Name)
- if len(value) > 0 {
- got = append(got, value)
- }
- return nil
- }
- if err := f.ParseAll(args, store); err != nil {
- t.Errorf("expected no error, got %s", err)
- }
- if !f.Parsed() {
- t.Errorf("f.Parse() = false after Parse")
- }
- if !reflect.DeepEqual(got, want) {
- t.Errorf("f.ParseAll() fail to restore the args")
- t.Errorf("Got: %v", got)
- t.Errorf("Want: %v", want)
- }
-}
-
-func TestShorthand(t *testing.T) {
- f := NewFlagSet("shorthand", ContinueOnError)
- if f.Parsed() {
- t.Error("f.Parse() = true before Parse")
- }
- boolaFlag := f.BoolP("boola", "a", false, "bool value")
- boolbFlag := f.BoolP("boolb", "b", false, "bool2 value")
- boolcFlag := f.BoolP("boolc", "c", false, "bool3 value")
- booldFlag := f.BoolP("boold", "d", false, "bool4 value")
- stringaFlag := f.StringP("stringa", "s", "0", "string value")
- stringzFlag := f.StringP("stringz", "z", "0", "string value")
- extra := "interspersed-argument"
- notaflag := "--i-look-like-a-flag"
- args := []string{
- "-ab",
- extra,
- "-cs",
- "hello",
- "-z=something",
- "-d=true",
- "--",
- notaflag,
- }
- f.SetOutput(ioutil.Discard)
- if err := f.Parse(args); err != nil {
- t.Error("expected no error, got ", err)
- }
- if !f.Parsed() {
- t.Error("f.Parse() = false after Parse")
- }
- if *boolaFlag != true {
- t.Error("boola flag should be true, is ", *boolaFlag)
- }
- if *boolbFlag != true {
- t.Error("boolb flag should be true, is ", *boolbFlag)
- }
- if *boolcFlag != true {
- t.Error("boolc flag should be true, is ", *boolcFlag)
- }
- if *booldFlag != true {
- t.Error("boold flag should be true, is ", *booldFlag)
- }
- if *stringaFlag != "hello" {
- t.Error("stringa flag should be `hello`, is ", *stringaFlag)
- }
- if *stringzFlag != "something" {
- t.Error("stringz flag should be `something`, is ", *stringzFlag)
- }
- if len(f.Args()) != 2 {
- t.Error("expected one argument, got", len(f.Args()))
- } else if f.Args()[0] != extra {
- t.Errorf("expected argument %q got %q", extra, f.Args()[0])
- } else if f.Args()[1] != notaflag {
- t.Errorf("expected argument %q got %q", notaflag, f.Args()[1])
- }
- if f.ArgsLenAtDash() != 1 {
- t.Errorf("expected argsLenAtDash %d got %d", f.ArgsLenAtDash(), 1)
- }
-}
-
-func TestShorthandLookup(t *testing.T) {
- f := NewFlagSet("shorthand", ContinueOnError)
- if f.Parsed() {
- t.Error("f.Parse() = true before Parse")
- }
- f.BoolP("boola", "a", false, "bool value")
- f.BoolP("boolb", "b", false, "bool2 value")
- args := []string{
- "-ab",
- }
- f.SetOutput(ioutil.Discard)
- if err := f.Parse(args); err != nil {
- t.Error("expected no error, got ", err)
- }
- if !f.Parsed() {
- t.Error("f.Parse() = false after Parse")
- }
- flag := f.ShorthandLookup("a")
- if flag == nil {
- t.Errorf("f.ShorthandLookup(\"a\") returned nil")
- }
- if flag.Name != "boola" {
- t.Errorf("f.ShorthandLookup(\"a\") found %q instead of \"boola\"", flag.Name)
- }
- flag = f.ShorthandLookup("")
- if flag != nil {
- t.Errorf("f.ShorthandLookup(\"\") did not return nil")
- }
- defer func() {
- recover()
- }()
- flag = f.ShorthandLookup("ab")
- // should NEVER get here. lookup should panic. defer'd func should recover it.
- t.Errorf("f.ShorthandLookup(\"ab\") did not panic")
-}
-
-func TestParse(t *testing.T) {
- ResetForTesting(func() { t.Error("bad parse") })
- testParse(GetCommandLine(), t)
-}
-
-func TestParseAll(t *testing.T) {
- ResetForTesting(func() { t.Error("bad parse") })
- testParseAll(GetCommandLine(), t)
-}
-
-func TestFlagSetParse(t *testing.T) {
- testParse(NewFlagSet("test", ContinueOnError), t)
-}
-
-func TestChangedHelper(t *testing.T) {
- f := NewFlagSet("changedtest", ContinueOnError)
- f.Bool("changed", false, "changed bool")
- f.Bool("settrue", true, "true to true")
- f.Bool("setfalse", false, "false to false")
- f.Bool("unchanged", false, "unchanged bool")
-
- args := []string{"--changed", "--settrue", "--setfalse=false"}
- if err := f.Parse(args); err != nil {
- t.Error("f.Parse() = false after Parse")
- }
- if !f.Changed("changed") {
- t.Errorf("--changed wasn't changed!")
- }
- if !f.Changed("settrue") {
- t.Errorf("--settrue wasn't changed!")
- }
- if !f.Changed("setfalse") {
- t.Errorf("--setfalse wasn't changed!")
- }
- if f.Changed("unchanged") {
- t.Errorf("--unchanged was changed!")
- }
- if f.Changed("invalid") {
- t.Errorf("--invalid was changed!")
- }
- if f.ArgsLenAtDash() != -1 {
- t.Errorf("Expected argsLenAtDash: %d but got %d", -1, f.ArgsLenAtDash())
- }
-}
-
-func replaceSeparators(name string, from []string, to string) string {
- result := name
- for _, sep := range from {
- result = strings.Replace(result, sep, to, -1)
- }
- // Type convert to indicate normalization has been done.
- return result
-}
-
-func wordSepNormalizeFunc(f *FlagSet, name string) NormalizedName {
- seps := []string{"-", "_"}
- name = replaceSeparators(name, seps, ".")
- normalizeFlagNameInvocations++
-
- return NormalizedName(name)
-}
-
-func testWordSepNormalizedNames(args []string, t *testing.T) {
- f := NewFlagSet("normalized", ContinueOnError)
- if f.Parsed() {
- t.Error("f.Parse() = true before Parse")
- }
- withDashFlag := f.Bool("with-dash-flag", false, "bool value")
- // Set this after some flags have been added and before others.
- f.SetNormalizeFunc(wordSepNormalizeFunc)
- withUnderFlag := f.Bool("with_under_flag", false, "bool value")
- withBothFlag := f.Bool("with-both_flag", false, "bool value")
- if err := f.Parse(args); err != nil {
- t.Fatal(err)
- }
- if !f.Parsed() {
- t.Error("f.Parse() = false after Parse")
- }
- if *withDashFlag != true {
- t.Error("withDashFlag flag should be true, is ", *withDashFlag)
- }
- if *withUnderFlag != true {
- t.Error("withUnderFlag flag should be true, is ", *withUnderFlag)
- }
- if *withBothFlag != true {
- t.Error("withBothFlag flag should be true, is ", *withBothFlag)
- }
-}
-
-func TestWordSepNormalizedNames(t *testing.T) {
- args := []string{
- "--with-dash-flag",
- "--with-under-flag",
- "--with-both-flag",
- }
- testWordSepNormalizedNames(args, t)
-
- args = []string{
- "--with_dash_flag",
- "--with_under_flag",
- "--with_both_flag",
- }
- testWordSepNormalizedNames(args, t)
-
- args = []string{
- "--with-dash_flag",
- "--with-under_flag",
- "--with-both_flag",
- }
- testWordSepNormalizedNames(args, t)
-}
-
-func aliasAndWordSepFlagNames(f *FlagSet, name string) NormalizedName {
- seps := []string{"-", "_"}
-
- oldName := replaceSeparators("old-valid_flag", seps, ".")
- newName := replaceSeparators("valid-flag", seps, ".")
-
- name = replaceSeparators(name, seps, ".")
- switch name {
- case oldName:
- name = newName
- break
- }
-
- return NormalizedName(name)
-}
-
-func TestCustomNormalizedNames(t *testing.T) {
- f := NewFlagSet("normalized", ContinueOnError)
- if f.Parsed() {
- t.Error("f.Parse() = true before Parse")
- }
-
- validFlag := f.Bool("valid-flag", false, "bool value")
- f.SetNormalizeFunc(aliasAndWordSepFlagNames)
- someOtherFlag := f.Bool("some-other-flag", false, "bool value")
-
- args := []string{"--old_valid_flag", "--some-other_flag"}
- if err := f.Parse(args); err != nil {
- t.Fatal(err)
- }
-
- if *validFlag != true {
- t.Errorf("validFlag is %v even though we set the alias --old_valid_falg", *validFlag)
- }
- if *someOtherFlag != true {
- t.Error("someOtherFlag should be true, is ", *someOtherFlag)
- }
-}
-
-// Every flag we add, the name (displayed also in usage) should normalized
-func TestNormalizationFuncShouldChangeFlagName(t *testing.T) {
- // Test normalization after addition
- f := NewFlagSet("normalized", ContinueOnError)
-
- f.Bool("valid_flag", false, "bool value")
- if f.Lookup("valid_flag").Name != "valid_flag" {
- t.Error("The new flag should have the name 'valid_flag' instead of ", f.Lookup("valid_flag").Name)
- }
-
- f.SetNormalizeFunc(wordSepNormalizeFunc)
- if f.Lookup("valid_flag").Name != "valid.flag" {
- t.Error("The new flag should have the name 'valid.flag' instead of ", f.Lookup("valid_flag").Name)
- }
-
- // Test normalization before addition
- f = NewFlagSet("normalized", ContinueOnError)
- f.SetNormalizeFunc(wordSepNormalizeFunc)
-
- f.Bool("valid_flag", false, "bool value")
- if f.Lookup("valid_flag").Name != "valid.flag" {
- t.Error("The new flag should have the name 'valid.flag' instead of ", f.Lookup("valid_flag").Name)
- }
-}
-
-// Declare a user-defined flag type.
-type flagVar []string
-
-func (f *flagVar) String() string {
- return fmt.Sprint([]string(*f))
-}
-
-func (f *flagVar) Set(value string) error {
- *f = append(*f, value)
- return nil
-}
-
-func (f *flagVar) Type() string {
- return "flagVar"
-}
-
-func TestUserDefined(t *testing.T) {
- var flags FlagSet
- flags.Init("test", ContinueOnError)
- var v flagVar
- flags.VarP(&v, "v", "v", "usage")
- if err := flags.Parse([]string{"--v=1", "-v2", "-v", "3"}); err != nil {
- t.Error(err)
- }
- if len(v) != 3 {
- t.Fatal("expected 3 args; got ", len(v))
- }
- expect := "[1 2 3]"
- if v.String() != expect {
- t.Errorf("expected value %q got %q", expect, v.String())
- }
-}
-
-func TestSetOutput(t *testing.T) {
- var flags FlagSet
- var buf bytes.Buffer
- flags.SetOutput(&buf)
- flags.Init("test", ContinueOnError)
- flags.Parse([]string{"--unknown"})
- if out := buf.String(); !strings.Contains(out, "--unknown") {
- t.Logf("expected output mentioning unknown; got %q", out)
- }
-}
-
-// This tests that one can reset the flags. This still works but not well, and is
-// superseded by FlagSet.
-func TestChangingArgs(t *testing.T) {
- ResetForTesting(func() { t.Fatal("bad parse") })
- oldArgs := os.Args
- defer func() { os.Args = oldArgs }()
- os.Args = []string{"cmd", "--before", "subcmd"}
- before := Bool("before", false, "")
- if err := GetCommandLine().Parse(os.Args[1:]); err != nil {
- t.Fatal(err)
- }
- cmd := Arg(0)
- os.Args = []string{"subcmd", "--after", "args"}
- after := Bool("after", false, "")
- Parse()
- args := Args()
-
- if !*before || cmd != "subcmd" || !*after || len(args) != 1 || args[0] != "args" {
- t.Fatalf("expected true subcmd true [args] got %v %v %v %v", *before, cmd, *after, args)
- }
-}
-
-// Test that -help invokes the usage message and returns ErrHelp.
-func TestHelp(t *testing.T) {
- var helpCalled = false
- fs := NewFlagSet("help test", ContinueOnError)
- fs.Usage = func() { helpCalled = true }
- var flag bool
- fs.BoolVar(&flag, "flag", false, "regular flag")
- // Regular flag invocation should work
- err := fs.Parse([]string{"--flag=true"})
- if err != nil {
- t.Fatal("expected no error; got ", err)
- }
- if !flag {
- t.Error("flag was not set by --flag")
- }
- if helpCalled {
- t.Error("help called for regular flag")
- helpCalled = false // reset for next test
- }
- // Help flag should work as expected.
- err = fs.Parse([]string{"--help"})
- if err == nil {
- t.Fatal("error expected")
- }
- if err != ErrHelp {
- t.Fatal("expected ErrHelp; got ", err)
- }
- if !helpCalled {
- t.Fatal("help was not called")
- }
- // If we define a help flag, that should override.
- var help bool
- fs.BoolVar(&help, "help", false, "help flag")
- helpCalled = false
- err = fs.Parse([]string{"--help"})
- if err != nil {
- t.Fatal("expected no error for defined --help; got ", err)
- }
- if helpCalled {
- t.Fatal("help was called; should not have been for defined help flag")
- }
-}
-
-func TestNoInterspersed(t *testing.T) {
- f := NewFlagSet("test", ContinueOnError)
- f.SetInterspersed(false)
- f.Bool("true", true, "always true")
- f.Bool("false", false, "always false")
- err := f.Parse([]string{"--true", "break", "--false"})
- if err != nil {
- t.Fatal("expected no error; got ", err)
- }
- args := f.Args()
- if len(args) != 2 || args[0] != "break" || args[1] != "--false" {
- t.Fatal("expected interspersed options/non-options to fail")
- }
-}
-
-func TestTermination(t *testing.T) {
- f := NewFlagSet("termination", ContinueOnError)
- boolFlag := f.BoolP("bool", "l", false, "bool value")
- if f.Parsed() {
- t.Error("f.Parse() = true before Parse")
- }
- arg1 := "ls"
- arg2 := "-l"
- args := []string{
- "--",
- arg1,
- arg2,
- }
- f.SetOutput(ioutil.Discard)
- if err := f.Parse(args); err != nil {
- t.Fatal("expected no error; got ", err)
- }
- if !f.Parsed() {
- t.Error("f.Parse() = false after Parse")
- }
- if *boolFlag {
- t.Error("expected boolFlag=false, got true")
- }
- if len(f.Args()) != 2 {
- t.Errorf("expected 2 arguments, got %d: %v", len(f.Args()), f.Args())
- }
- if f.Args()[0] != arg1 {
- t.Errorf("expected argument %q got %q", arg1, f.Args()[0])
- }
- if f.Args()[1] != arg2 {
- t.Errorf("expected argument %q got %q", arg2, f.Args()[1])
- }
- if f.ArgsLenAtDash() != 0 {
- t.Errorf("expected argsLenAtDash %d got %d", 0, f.ArgsLenAtDash())
- }
-}
-
-func TestDeprecatedFlagInDocs(t *testing.T) {
- f := NewFlagSet("bob", ContinueOnError)
- f.Bool("badflag", true, "always true")
- f.MarkDeprecated("badflag", "use --good-flag instead")
-
- out := new(bytes.Buffer)
- f.SetOutput(out)
- f.PrintDefaults()
-
- if strings.Contains(out.String(), "badflag") {
- t.Errorf("found deprecated flag in usage!")
- }
-}
-
-func TestDeprecatedFlagShorthandInDocs(t *testing.T) {
- f := NewFlagSet("bob", ContinueOnError)
- name := "noshorthandflag"
- f.BoolP(name, "n", true, "always true")
- f.MarkShorthandDeprecated("noshorthandflag", fmt.Sprintf("use --%s instead", name))
-
- out := new(bytes.Buffer)
- f.SetOutput(out)
- f.PrintDefaults()
-
- if strings.Contains(out.String(), "-n,") {
- t.Errorf("found deprecated flag shorthand in usage!")
- }
-}
-
-func parseReturnStderr(t *testing.T, f *FlagSet, args []string) (string, error) {
- oldStderr := os.Stderr
- r, w, _ := os.Pipe()
- os.Stderr = w
-
- err := f.Parse(args)
-
- outC := make(chan string)
- // copy the output in a separate goroutine so printing can't block indefinitely
- go func() {
- var buf bytes.Buffer
- io.Copy(&buf, r)
- outC <- buf.String()
- }()
-
- w.Close()
- os.Stderr = oldStderr
- out := <-outC
-
- return out, err
-}
-
-func TestDeprecatedFlagUsage(t *testing.T) {
- f := NewFlagSet("bob", ContinueOnError)
- f.Bool("badflag", true, "always true")
- usageMsg := "use --good-flag instead"
- f.MarkDeprecated("badflag", usageMsg)
-
- args := []string{"--badflag"}
- out, err := parseReturnStderr(t, f, args)
- if err != nil {
- t.Fatal("expected no error; got ", err)
- }
-
- if !strings.Contains(out, usageMsg) {
- t.Errorf("usageMsg not printed when using a deprecated flag!")
- }
-}
-
-func TestDeprecatedFlagShorthandUsage(t *testing.T) {
- f := NewFlagSet("bob", ContinueOnError)
- name := "noshorthandflag"
- f.BoolP(name, "n", true, "always true")
- usageMsg := fmt.Sprintf("use --%s instead", name)
- f.MarkShorthandDeprecated(name, usageMsg)
-
- args := []string{"-n"}
- out, err := parseReturnStderr(t, f, args)
- if err != nil {
- t.Fatal("expected no error; got ", err)
- }
-
- if !strings.Contains(out, usageMsg) {
- t.Errorf("usageMsg not printed when using a deprecated flag!")
- }
-}
-
-func TestDeprecatedFlagUsageNormalized(t *testing.T) {
- f := NewFlagSet("bob", ContinueOnError)
- f.Bool("bad-double_flag", true, "always true")
- f.SetNormalizeFunc(wordSepNormalizeFunc)
- usageMsg := "use --good-flag instead"
- f.MarkDeprecated("bad_double-flag", usageMsg)
-
- args := []string{"--bad_double_flag"}
- out, err := parseReturnStderr(t, f, args)
- if err != nil {
- t.Fatal("expected no error; got ", err)
- }
-
- if !strings.Contains(out, usageMsg) {
- t.Errorf("usageMsg not printed when using a deprecated flag!")
- }
-}
-
-// Name normalization function should be called only once on flag addition
-func TestMultipleNormalizeFlagNameInvocations(t *testing.T) {
- normalizeFlagNameInvocations = 0
-
- f := NewFlagSet("normalized", ContinueOnError)
- f.SetNormalizeFunc(wordSepNormalizeFunc)
- f.Bool("with_under_flag", false, "bool value")
-
- if normalizeFlagNameInvocations != 1 {
- t.Fatal("Expected normalizeFlagNameInvocations to be 1; got ", normalizeFlagNameInvocations)
- }
-}
-
-//
-func TestHiddenFlagInUsage(t *testing.T) {
- f := NewFlagSet("bob", ContinueOnError)
- f.Bool("secretFlag", true, "shhh")
- f.MarkHidden("secretFlag")
-
- out := new(bytes.Buffer)
- f.SetOutput(out)
- f.PrintDefaults()
-
- if strings.Contains(out.String(), "secretFlag") {
- t.Errorf("found hidden flag in usage!")
- }
-}
-
-//
-func TestHiddenFlagUsage(t *testing.T) {
- f := NewFlagSet("bob", ContinueOnError)
- f.Bool("secretFlag", true, "shhh")
- f.MarkHidden("secretFlag")
-
- args := []string{"--secretFlag"}
- out, err := parseReturnStderr(t, f, args)
- if err != nil {
- t.Fatal("expected no error; got ", err)
- }
-
- if strings.Contains(out, "shhh") {
- t.Errorf("usage message printed when using a hidden flag!")
- }
-}
-
-const defaultOutput = ` --A for bootstrapping, allow 'any' type
- --Alongflagname disable bounds checking
- -C, --CCC a boolean defaulting to true (default true)
- --D path set relative path for local imports
- -E, --EEE num[=1234] a num with NoOptDefVal (default 4321)
- --F number a non-zero number (default 2.7)
- --G float a float that defaults to zero
- --IP ip IP address with no default
- --IPMask ipMask Netmask address with no default
- --IPNet ipNet IP network with no default
- --Ints intSlice int slice with zero default
- --N int a non-zero int (default 27)
- --ND1 string[="bar"] a string with NoOptDefVal (default "foo")
- --ND2 num[=4321] a num with NoOptDefVal (default 1234)
- --StringArray stringArray string array with zero default
- --StringSlice stringSlice string slice with zero default
- --Z int an int that defaults to zero
- --custom custom custom Value implementation
- --customP custom a VarP with default (default 10)
- --maxT timeout set timeout for dial
-`
-
-// Custom value that satisfies the Value interface.
-type customValue int
-
-func (cv *customValue) String() string { return fmt.Sprintf("%v", *cv) }
-
-func (cv *customValue) Set(s string) error {
- v, err := strconv.ParseInt(s, 0, 64)
- *cv = customValue(v)
- return err
-}
-
-func (cv *customValue) Type() string { return "custom" }
-
-func TestPrintDefaults(t *testing.T) {
- fs := NewFlagSet("print defaults test", ContinueOnError)
- var buf bytes.Buffer
- fs.SetOutput(&buf)
- fs.Bool("A", false, "for bootstrapping, allow 'any' type")
- fs.Bool("Alongflagname", false, "disable bounds checking")
- fs.BoolP("CCC", "C", true, "a boolean defaulting to true")
- fs.String("D", "", "set relative `path` for local imports")
- fs.Float64("F", 2.7, "a non-zero `number`")
- fs.Float64("G", 0, "a float that defaults to zero")
- fs.Int("N", 27, "a non-zero int")
- fs.IntSlice("Ints", []int{}, "int slice with zero default")
- fs.IP("IP", nil, "IP address with no default")
- fs.IPMask("IPMask", nil, "Netmask address with no default")
- fs.IPNet("IPNet", net.IPNet{}, "IP network with no default")
- fs.Int("Z", 0, "an int that defaults to zero")
- fs.Duration("maxT", 0, "set `timeout` for dial")
- fs.String("ND1", "foo", "a string with NoOptDefVal")
- fs.Lookup("ND1").NoOptDefVal = "bar"
- fs.Int("ND2", 1234, "a `num` with NoOptDefVal")
- fs.Lookup("ND2").NoOptDefVal = "4321"
- fs.IntP("EEE", "E", 4321, "a `num` with NoOptDefVal")
- fs.ShorthandLookup("E").NoOptDefVal = "1234"
- fs.StringSlice("StringSlice", []string{}, "string slice with zero default")
- fs.StringArray("StringArray", []string{}, "string array with zero default")
-
- var cv customValue
- fs.Var(&cv, "custom", "custom Value implementation")
-
- cv2 := customValue(10)
- fs.VarP(&cv2, "customP", "", "a VarP with default")
-
- fs.PrintDefaults()
- got := buf.String()
- if got != defaultOutput {
- fmt.Println("\n" + got)
- fmt.Println("\n" + defaultOutput)
- t.Errorf("got %q want %q\n", got, defaultOutput)
- }
-}
-
-func TestVisitAllFlagOrder(t *testing.T) {
- fs := NewFlagSet("TestVisitAllFlagOrder", ContinueOnError)
- fs.SortFlags = false
- // https://github.com/spf13/pflag/issues/120
- fs.SetNormalizeFunc(func(f *FlagSet, name string) NormalizedName {
- return NormalizedName(name)
- })
-
- names := []string{"C", "B", "A", "D"}
- for _, name := range names {
- fs.Bool(name, false, "")
- }
-
- i := 0
- fs.VisitAll(func(f *Flag) {
- if names[i] != f.Name {
- t.Errorf("Incorrect order. Expected %v, got %v", names[i], f.Name)
- }
- i++
- })
-}
-
-func TestVisitFlagOrder(t *testing.T) {
- fs := NewFlagSet("TestVisitFlagOrder", ContinueOnError)
- fs.SortFlags = false
- names := []string{"C", "B", "A", "D"}
- for _, name := range names {
- fs.Bool(name, false, "")
- fs.Set(name, "true")
- }
-
- i := 0
- fs.Visit(func(f *Flag) {
- if names[i] != f.Name {
- t.Errorf("Incorrect order. Expected %v, got %v", names[i], f.Name)
- }
- i++
- })
-}
diff --git a/vendor/github.com/spf13/pflag/float32.go b/vendor/github.com/spf13/pflag/float32.go
deleted file mode 100644
index a243f81..0000000
--- a/vendor/github.com/spf13/pflag/float32.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- float32 Value
-type float32Value float32
-
-func newFloat32Value(val float32, p *float32) *float32Value {
- *p = val
- return (*float32Value)(p)
-}
-
-func (f *float32Value) Set(s string) error {
- v, err := strconv.ParseFloat(s, 32)
- *f = float32Value(v)
- return err
-}
-
-func (f *float32Value) Type() string {
- return "float32"
-}
-
-func (f *float32Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 32) }
-
-func float32Conv(sval string) (interface{}, error) {
- v, err := strconv.ParseFloat(sval, 32)
- if err != nil {
- return 0, err
- }
- return float32(v), nil
-}
-
-// GetFloat32 return the float32 value of a flag with the given name
-func (f *FlagSet) GetFloat32(name string) (float32, error) {
- val, err := f.getFlagType(name, "float32", float32Conv)
- if err != nil {
- return 0, err
- }
- return val.(float32), nil
-}
-
-// Float32Var defines a float32 flag with specified name, default value, and usage string.
-// The argument p points to a float32 variable in which to store the value of the flag.
-func (f *FlagSet) Float32Var(p *float32, name string, value float32, usage string) {
- f.VarP(newFloat32Value(value, p), name, "", usage)
-}
-
-// Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Float32VarP(p *float32, name, shorthand string, value float32, usage string) {
- f.VarP(newFloat32Value(value, p), name, shorthand, usage)
-}
-
-// Float32Var defines a float32 flag with specified name, default value, and usage string.
-// The argument p points to a float32 variable in which to store the value of the flag.
-func Float32Var(p *float32, name string, value float32, usage string) {
- CommandLine.VarP(newFloat32Value(value, p), name, "", usage)
-}
-
-// Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash.
-func Float32VarP(p *float32, name, shorthand string, value float32, usage string) {
- CommandLine.VarP(newFloat32Value(value, p), name, shorthand, usage)
-}
-
-// Float32 defines a float32 flag with specified name, default value, and usage string.
-// The return value is the address of a float32 variable that stores the value of the flag.
-func (f *FlagSet) Float32(name string, value float32, usage string) *float32 {
- p := new(float32)
- f.Float32VarP(p, name, "", value, usage)
- return p
-}
-
-// Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Float32P(name, shorthand string, value float32, usage string) *float32 {
- p := new(float32)
- f.Float32VarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Float32 defines a float32 flag with specified name, default value, and usage string.
-// The return value is the address of a float32 variable that stores the value of the flag.
-func Float32(name string, value float32, usage string) *float32 {
- return CommandLine.Float32P(name, "", value, usage)
-}
-
-// Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash.
-func Float32P(name, shorthand string, value float32, usage string) *float32 {
- return CommandLine.Float32P(name, shorthand, value, usage)
-}
diff --git a/vendor/github.com/spf13/pflag/float64.go b/vendor/github.com/spf13/pflag/float64.go
deleted file mode 100644
index 04b5492..0000000
--- a/vendor/github.com/spf13/pflag/float64.go
+++ /dev/null
@@ -1,84 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- float64 Value
-type float64Value float64
-
-func newFloat64Value(val float64, p *float64) *float64Value {
- *p = val
- return (*float64Value)(p)
-}
-
-func (f *float64Value) Set(s string) error {
- v, err := strconv.ParseFloat(s, 64)
- *f = float64Value(v)
- return err
-}
-
-func (f *float64Value) Type() string {
- return "float64"
-}
-
-func (f *float64Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 64) }
-
-func float64Conv(sval string) (interface{}, error) {
- return strconv.ParseFloat(sval, 64)
-}
-
-// GetFloat64 return the float64 value of a flag with the given name
-func (f *FlagSet) GetFloat64(name string) (float64, error) {
- val, err := f.getFlagType(name, "float64", float64Conv)
- if err != nil {
- return 0, err
- }
- return val.(float64), nil
-}
-
-// Float64Var defines a float64 flag with specified name, default value, and usage string.
-// The argument p points to a float64 variable in which to store the value of the flag.
-func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) {
- f.VarP(newFloat64Value(value, p), name, "", usage)
-}
-
-// Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Float64VarP(p *float64, name, shorthand string, value float64, usage string) {
- f.VarP(newFloat64Value(value, p), name, shorthand, usage)
-}
-
-// Float64Var defines a float64 flag with specified name, default value, and usage string.
-// The argument p points to a float64 variable in which to store the value of the flag.
-func Float64Var(p *float64, name string, value float64, usage string) {
- CommandLine.VarP(newFloat64Value(value, p), name, "", usage)
-}
-
-// Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash.
-func Float64VarP(p *float64, name, shorthand string, value float64, usage string) {
- CommandLine.VarP(newFloat64Value(value, p), name, shorthand, usage)
-}
-
-// Float64 defines a float64 flag with specified name, default value, and usage string.
-// The return value is the address of a float64 variable that stores the value of the flag.
-func (f *FlagSet) Float64(name string, value float64, usage string) *float64 {
- p := new(float64)
- f.Float64VarP(p, name, "", value, usage)
- return p
-}
-
-// Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Float64P(name, shorthand string, value float64, usage string) *float64 {
- p := new(float64)
- f.Float64VarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Float64 defines a float64 flag with specified name, default value, and usage string.
-// The return value is the address of a float64 variable that stores the value of the flag.
-func Float64(name string, value float64, usage string) *float64 {
- return CommandLine.Float64P(name, "", value, usage)
-}
-
-// Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash.
-func Float64P(name, shorthand string, value float64, usage string) *float64 {
- return CommandLine.Float64P(name, shorthand, value, usage)
-}
diff --git a/vendor/github.com/spf13/pflag/golangflag.go b/vendor/github.com/spf13/pflag/golangflag.go
deleted file mode 100644
index c4f47eb..0000000
--- a/vendor/github.com/spf13/pflag/golangflag.go
+++ /dev/null
@@ -1,101 +0,0 @@
-// Copyright 2009 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 pflag
-
-import (
- goflag "flag"
- "reflect"
- "strings"
-)
-
-// flagValueWrapper implements pflag.Value around a flag.Value. The main
-// difference here is the addition of the Type method that returns a string
-// name of the type. As this is generally unknown, we approximate that with
-// reflection.
-type flagValueWrapper struct {
- inner goflag.Value
- flagType string
-}
-
-// We are just copying the boolFlag interface out of goflag as that is what
-// they use to decide if a flag should get "true" when no arg is given.
-type goBoolFlag interface {
- goflag.Value
- IsBoolFlag() bool
-}
-
-func wrapFlagValue(v goflag.Value) Value {
- // If the flag.Value happens to also be a pflag.Value, just use it directly.
- if pv, ok := v.(Value); ok {
- return pv
- }
-
- pv := &flagValueWrapper{
- inner: v,
- }
-
- t := reflect.TypeOf(v)
- if t.Kind() == reflect.Interface || t.Kind() == reflect.Ptr {
- t = t.Elem()
- }
-
- pv.flagType = strings.TrimSuffix(t.Name(), "Value")
- return pv
-}
-
-func (v *flagValueWrapper) String() string {
- return v.inner.String()
-}
-
-func (v *flagValueWrapper) Set(s string) error {
- return v.inner.Set(s)
-}
-
-func (v *flagValueWrapper) Type() string {
- return v.flagType
-}
-
-// PFlagFromGoFlag will return a *pflag.Flag given a *flag.Flag
-// If the *flag.Flag.Name was a single character (ex: `v`) it will be accessiblei
-// with both `-v` and `--v` in flags. If the golang flag was more than a single
-// character (ex: `verbose`) it will only be accessible via `--verbose`
-func PFlagFromGoFlag(goflag *goflag.Flag) *Flag {
- // Remember the default value as a string; it won't change.
- flag := &Flag{
- Name: goflag.Name,
- Usage: goflag.Usage,
- Value: wrapFlagValue(goflag.Value),
- // Looks like golang flags don't set DefValue correctly :-(
- //DefValue: goflag.DefValue,
- DefValue: goflag.Value.String(),
- }
- // Ex: if the golang flag was -v, allow both -v and --v to work
- if len(flag.Name) == 1 {
- flag.Shorthand = flag.Name
- }
- if fv, ok := goflag.Value.(goBoolFlag); ok && fv.IsBoolFlag() {
- flag.NoOptDefVal = "true"
- }
- return flag
-}
-
-// AddGoFlag will add the given *flag.Flag to the pflag.FlagSet
-func (f *FlagSet) AddGoFlag(goflag *goflag.Flag) {
- if f.Lookup(goflag.Name) != nil {
- return
- }
- newflag := PFlagFromGoFlag(goflag)
- f.AddFlag(newflag)
-}
-
-// AddGoFlagSet will add the given *flag.FlagSet to the pflag.FlagSet
-func (f *FlagSet) AddGoFlagSet(newSet *goflag.FlagSet) {
- if newSet == nil {
- return
- }
- newSet.VisitAll(func(goflag *goflag.Flag) {
- f.AddGoFlag(goflag)
- })
-}
diff --git a/vendor/github.com/spf13/pflag/golangflag_test.go b/vendor/github.com/spf13/pflag/golangflag_test.go
deleted file mode 100644
index 77e2d7d..0000000
--- a/vendor/github.com/spf13/pflag/golangflag_test.go
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright 2009 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 pflag
-
-import (
- goflag "flag"
- "testing"
-)
-
-func TestGoflags(t *testing.T) {
- goflag.String("stringFlag", "stringFlag", "stringFlag")
- goflag.Bool("boolFlag", false, "boolFlag")
-
- f := NewFlagSet("test", ContinueOnError)
-
- f.AddGoFlagSet(goflag.CommandLine)
- err := f.Parse([]string{"--stringFlag=bob", "--boolFlag"})
- if err != nil {
- t.Fatal("expected no error; get", err)
- }
-
- getString, err := f.GetString("stringFlag")
- if err != nil {
- t.Fatal("expected no error; get", err)
- }
- if getString != "bob" {
- t.Fatalf("expected getString=bob but got getString=%s", getString)
- }
-
- getBool, err := f.GetBool("boolFlag")
- if err != nil {
- t.Fatal("expected no error; get", err)
- }
- if getBool != true {
- t.Fatalf("expected getBool=true but got getBool=%v", getBool)
- }
-}
diff --git a/vendor/github.com/spf13/pflag/int.go b/vendor/github.com/spf13/pflag/int.go
deleted file mode 100644
index 1474b89..0000000
--- a/vendor/github.com/spf13/pflag/int.go
+++ /dev/null
@@ -1,84 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- int Value
-type intValue int
-
-func newIntValue(val int, p *int) *intValue {
- *p = val
- return (*intValue)(p)
-}
-
-func (i *intValue) Set(s string) error {
- v, err := strconv.ParseInt(s, 0, 64)
- *i = intValue(v)
- return err
-}
-
-func (i *intValue) Type() string {
- return "int"
-}
-
-func (i *intValue) String() string { return strconv.Itoa(int(*i)) }
-
-func intConv(sval string) (interface{}, error) {
- return strconv.Atoi(sval)
-}
-
-// GetInt return the int value of a flag with the given name
-func (f *FlagSet) GetInt(name string) (int, error) {
- val, err := f.getFlagType(name, "int", intConv)
- if err != nil {
- return 0, err
- }
- return val.(int), nil
-}
-
-// IntVar defines an int flag with specified name, default value, and usage string.
-// The argument p points to an int variable in which to store the value of the flag.
-func (f *FlagSet) IntVar(p *int, name string, value int, usage string) {
- f.VarP(newIntValue(value, p), name, "", usage)
-}
-
-// IntVarP is like IntVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) IntVarP(p *int, name, shorthand string, value int, usage string) {
- f.VarP(newIntValue(value, p), name, shorthand, usage)
-}
-
-// IntVar defines an int flag with specified name, default value, and usage string.
-// The argument p points to an int variable in which to store the value of the flag.
-func IntVar(p *int, name string, value int, usage string) {
- CommandLine.VarP(newIntValue(value, p), name, "", usage)
-}
-
-// IntVarP is like IntVar, but accepts a shorthand letter that can be used after a single dash.
-func IntVarP(p *int, name, shorthand string, value int, usage string) {
- CommandLine.VarP(newIntValue(value, p), name, shorthand, usage)
-}
-
-// Int defines an int flag with specified name, default value, and usage string.
-// The return value is the address of an int variable that stores the value of the flag.
-func (f *FlagSet) Int(name string, value int, usage string) *int {
- p := new(int)
- f.IntVarP(p, name, "", value, usage)
- return p
-}
-
-// IntP is like Int, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) IntP(name, shorthand string, value int, usage string) *int {
- p := new(int)
- f.IntVarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Int defines an int flag with specified name, default value, and usage string.
-// The return value is the address of an int variable that stores the value of the flag.
-func Int(name string, value int, usage string) *int {
- return CommandLine.IntP(name, "", value, usage)
-}
-
-// IntP is like Int, but accepts a shorthand letter that can be used after a single dash.
-func IntP(name, shorthand string, value int, usage string) *int {
- return CommandLine.IntP(name, shorthand, value, usage)
-}
diff --git a/vendor/github.com/spf13/pflag/int32.go b/vendor/github.com/spf13/pflag/int32.go
deleted file mode 100644
index 9b95944..0000000
--- a/vendor/github.com/spf13/pflag/int32.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- int32 Value
-type int32Value int32
-
-func newInt32Value(val int32, p *int32) *int32Value {
- *p = val
- return (*int32Value)(p)
-}
-
-func (i *int32Value) Set(s string) error {
- v, err := strconv.ParseInt(s, 0, 32)
- *i = int32Value(v)
- return err
-}
-
-func (i *int32Value) Type() string {
- return "int32"
-}
-
-func (i *int32Value) String() string { return strconv.FormatInt(int64(*i), 10) }
-
-func int32Conv(sval string) (interface{}, error) {
- v, err := strconv.ParseInt(sval, 0, 32)
- if err != nil {
- return 0, err
- }
- return int32(v), nil
-}
-
-// GetInt32 return the int32 value of a flag with the given name
-func (f *FlagSet) GetInt32(name string) (int32, error) {
- val, err := f.getFlagType(name, "int32", int32Conv)
- if err != nil {
- return 0, err
- }
- return val.(int32), nil
-}
-
-// Int32Var defines an int32 flag with specified name, default value, and usage string.
-// The argument p points to an int32 variable in which to store the value of the flag.
-func (f *FlagSet) Int32Var(p *int32, name string, value int32, usage string) {
- f.VarP(newInt32Value(value, p), name, "", usage)
-}
-
-// Int32VarP is like Int32Var, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Int32VarP(p *int32, name, shorthand string, value int32, usage string) {
- f.VarP(newInt32Value(value, p), name, shorthand, usage)
-}
-
-// Int32Var defines an int32 flag with specified name, default value, and usage string.
-// The argument p points to an int32 variable in which to store the value of the flag.
-func Int32Var(p *int32, name string, value int32, usage string) {
- CommandLine.VarP(newInt32Value(value, p), name, "", usage)
-}
-
-// Int32VarP is like Int32Var, but accepts a shorthand letter that can be used after a single dash.
-func Int32VarP(p *int32, name, shorthand string, value int32, usage string) {
- CommandLine.VarP(newInt32Value(value, p), name, shorthand, usage)
-}
-
-// Int32 defines an int32 flag with specified name, default value, and usage string.
-// The return value is the address of an int32 variable that stores the value of the flag.
-func (f *FlagSet) Int32(name string, value int32, usage string) *int32 {
- p := new(int32)
- f.Int32VarP(p, name, "", value, usage)
- return p
-}
-
-// Int32P is like Int32, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Int32P(name, shorthand string, value int32, usage string) *int32 {
- p := new(int32)
- f.Int32VarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Int32 defines an int32 flag with specified name, default value, and usage string.
-// The return value is the address of an int32 variable that stores the value of the flag.
-func Int32(name string, value int32, usage string) *int32 {
- return CommandLine.Int32P(name, "", value, usage)
-}
-
-// Int32P is like Int32, but accepts a shorthand letter that can be used after a single dash.
-func Int32P(name, shorthand string, value int32, usage string) *int32 {
- return CommandLine.Int32P(name, shorthand, value, usage)
-}
diff --git a/vendor/github.com/spf13/pflag/int64.go b/vendor/github.com/spf13/pflag/int64.go
deleted file mode 100644
index 0026d78..0000000
--- a/vendor/github.com/spf13/pflag/int64.go
+++ /dev/null
@@ -1,84 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- int64 Value
-type int64Value int64
-
-func newInt64Value(val int64, p *int64) *int64Value {
- *p = val
- return (*int64Value)(p)
-}
-
-func (i *int64Value) Set(s string) error {
- v, err := strconv.ParseInt(s, 0, 64)
- *i = int64Value(v)
- return err
-}
-
-func (i *int64Value) Type() string {
- return "int64"
-}
-
-func (i *int64Value) String() string { return strconv.FormatInt(int64(*i), 10) }
-
-func int64Conv(sval string) (interface{}, error) {
- return strconv.ParseInt(sval, 0, 64)
-}
-
-// GetInt64 return the int64 value of a flag with the given name
-func (f *FlagSet) GetInt64(name string) (int64, error) {
- val, err := f.getFlagType(name, "int64", int64Conv)
- if err != nil {
- return 0, err
- }
- return val.(int64), nil
-}
-
-// Int64Var defines an int64 flag with specified name, default value, and usage string.
-// The argument p points to an int64 variable in which to store the value of the flag.
-func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) {
- f.VarP(newInt64Value(value, p), name, "", usage)
-}
-
-// Int64VarP is like Int64Var, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Int64VarP(p *int64, name, shorthand string, value int64, usage string) {
- f.VarP(newInt64Value(value, p), name, shorthand, usage)
-}
-
-// Int64Var defines an int64 flag with specified name, default value, and usage string.
-// The argument p points to an int64 variable in which to store the value of the flag.
-func Int64Var(p *int64, name string, value int64, usage string) {
- CommandLine.VarP(newInt64Value(value, p), name, "", usage)
-}
-
-// Int64VarP is like Int64Var, but accepts a shorthand letter that can be used after a single dash.
-func Int64VarP(p *int64, name, shorthand string, value int64, usage string) {
- CommandLine.VarP(newInt64Value(value, p), name, shorthand, usage)
-}
-
-// Int64 defines an int64 flag with specified name, default value, and usage string.
-// The return value is the address of an int64 variable that stores the value of the flag.
-func (f *FlagSet) Int64(name string, value int64, usage string) *int64 {
- p := new(int64)
- f.Int64VarP(p, name, "", value, usage)
- return p
-}
-
-// Int64P is like Int64, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Int64P(name, shorthand string, value int64, usage string) *int64 {
- p := new(int64)
- f.Int64VarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Int64 defines an int64 flag with specified name, default value, and usage string.
-// The return value is the address of an int64 variable that stores the value of the flag.
-func Int64(name string, value int64, usage string) *int64 {
- return CommandLine.Int64P(name, "", value, usage)
-}
-
-// Int64P is like Int64, but accepts a shorthand letter that can be used after a single dash.
-func Int64P(name, shorthand string, value int64, usage string) *int64 {
- return CommandLine.Int64P(name, shorthand, value, usage)
-}
diff --git a/vendor/github.com/spf13/pflag/int8.go b/vendor/github.com/spf13/pflag/int8.go
deleted file mode 100644
index 4da9222..0000000
--- a/vendor/github.com/spf13/pflag/int8.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- int8 Value
-type int8Value int8
-
-func newInt8Value(val int8, p *int8) *int8Value {
- *p = val
- return (*int8Value)(p)
-}
-
-func (i *int8Value) Set(s string) error {
- v, err := strconv.ParseInt(s, 0, 8)
- *i = int8Value(v)
- return err
-}
-
-func (i *int8Value) Type() string {
- return "int8"
-}
-
-func (i *int8Value) String() string { return strconv.FormatInt(int64(*i), 10) }
-
-func int8Conv(sval string) (interface{}, error) {
- v, err := strconv.ParseInt(sval, 0, 8)
- if err != nil {
- return 0, err
- }
- return int8(v), nil
-}
-
-// GetInt8 return the int8 value of a flag with the given name
-func (f *FlagSet) GetInt8(name string) (int8, error) {
- val, err := f.getFlagType(name, "int8", int8Conv)
- if err != nil {
- return 0, err
- }
- return val.(int8), nil
-}
-
-// Int8Var defines an int8 flag with specified name, default value, and usage string.
-// The argument p points to an int8 variable in which to store the value of the flag.
-func (f *FlagSet) Int8Var(p *int8, name string, value int8, usage string) {
- f.VarP(newInt8Value(value, p), name, "", usage)
-}
-
-// Int8VarP is like Int8Var, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Int8VarP(p *int8, name, shorthand string, value int8, usage string) {
- f.VarP(newInt8Value(value, p), name, shorthand, usage)
-}
-
-// Int8Var defines an int8 flag with specified name, default value, and usage string.
-// The argument p points to an int8 variable in which to store the value of the flag.
-func Int8Var(p *int8, name string, value int8, usage string) {
- CommandLine.VarP(newInt8Value(value, p), name, "", usage)
-}
-
-// Int8VarP is like Int8Var, but accepts a shorthand letter that can be used after a single dash.
-func Int8VarP(p *int8, name, shorthand string, value int8, usage string) {
- CommandLine.VarP(newInt8Value(value, p), name, shorthand, usage)
-}
-
-// Int8 defines an int8 flag with specified name, default value, and usage string.
-// The return value is the address of an int8 variable that stores the value of the flag.
-func (f *FlagSet) Int8(name string, value int8, usage string) *int8 {
- p := new(int8)
- f.Int8VarP(p, name, "", value, usage)
- return p
-}
-
-// Int8P is like Int8, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Int8P(name, shorthand string, value int8, usage string) *int8 {
- p := new(int8)
- f.Int8VarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Int8 defines an int8 flag with specified name, default value, and usage string.
-// The return value is the address of an int8 variable that stores the value of the flag.
-func Int8(name string, value int8, usage string) *int8 {
- return CommandLine.Int8P(name, "", value, usage)
-}
-
-// Int8P is like Int8, but accepts a shorthand letter that can be used after a single dash.
-func Int8P(name, shorthand string, value int8, usage string) *int8 {
- return CommandLine.Int8P(name, shorthand, value, usage)
-}
diff --git a/vendor/github.com/spf13/pflag/int_slice.go b/vendor/github.com/spf13/pflag/int_slice.go
deleted file mode 100644
index 1e7c9ed..0000000
--- a/vendor/github.com/spf13/pflag/int_slice.go
+++ /dev/null
@@ -1,128 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "strconv"
- "strings"
-)
-
-// -- intSlice Value
-type intSliceValue struct {
- value *[]int
- changed bool
-}
-
-func newIntSliceValue(val []int, p *[]int) *intSliceValue {
- isv := new(intSliceValue)
- isv.value = p
- *isv.value = val
- return isv
-}
-
-func (s *intSliceValue) Set(val string) error {
- ss := strings.Split(val, ",")
- out := make([]int, len(ss))
- for i, d := range ss {
- var err error
- out[i], err = strconv.Atoi(d)
- if err != nil {
- return err
- }
-
- }
- if !s.changed {
- *s.value = out
- } else {
- *s.value = append(*s.value, out...)
- }
- s.changed = true
- return nil
-}
-
-func (s *intSliceValue) Type() string {
- return "intSlice"
-}
-
-func (s *intSliceValue) String() string {
- out := make([]string, len(*s.value))
- for i, d := range *s.value {
- out[i] = fmt.Sprintf("%d", d)
- }
- return "[" + strings.Join(out, ",") + "]"
-}
-
-func intSliceConv(val string) (interface{}, error) {
- val = strings.Trim(val, "[]")
- // Empty string would cause a slice with one (empty) entry
- if len(val) == 0 {
- return []int{}, nil
- }
- ss := strings.Split(val, ",")
- out := make([]int, len(ss))
- for i, d := range ss {
- var err error
- out[i], err = strconv.Atoi(d)
- if err != nil {
- return nil, err
- }
-
- }
- return out, nil
-}
-
-// GetIntSlice return the []int value of a flag with the given name
-func (f *FlagSet) GetIntSlice(name string) ([]int, error) {
- val, err := f.getFlagType(name, "intSlice", intSliceConv)
- if err != nil {
- return []int{}, err
- }
- return val.([]int), nil
-}
-
-// IntSliceVar defines a intSlice flag with specified name, default value, and usage string.
-// The argument p points to a []int variable in which to store the value of the flag.
-func (f *FlagSet) IntSliceVar(p *[]int, name string, value []int, usage string) {
- f.VarP(newIntSliceValue(value, p), name, "", usage)
-}
-
-// IntSliceVarP is like IntSliceVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) IntSliceVarP(p *[]int, name, shorthand string, value []int, usage string) {
- f.VarP(newIntSliceValue(value, p), name, shorthand, usage)
-}
-
-// IntSliceVar defines a int[] flag with specified name, default value, and usage string.
-// The argument p points to a int[] variable in which to store the value of the flag.
-func IntSliceVar(p *[]int, name string, value []int, usage string) {
- CommandLine.VarP(newIntSliceValue(value, p), name, "", usage)
-}
-
-// IntSliceVarP is like IntSliceVar, but accepts a shorthand letter that can be used after a single dash.
-func IntSliceVarP(p *[]int, name, shorthand string, value []int, usage string) {
- CommandLine.VarP(newIntSliceValue(value, p), name, shorthand, usage)
-}
-
-// IntSlice defines a []int flag with specified name, default value, and usage string.
-// The return value is the address of a []int variable that stores the value of the flag.
-func (f *FlagSet) IntSlice(name string, value []int, usage string) *[]int {
- p := []int{}
- f.IntSliceVarP(&p, name, "", value, usage)
- return &p
-}
-
-// IntSliceP is like IntSlice, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) IntSliceP(name, shorthand string, value []int, usage string) *[]int {
- p := []int{}
- f.IntSliceVarP(&p, name, shorthand, value, usage)
- return &p
-}
-
-// IntSlice defines a []int flag with specified name, default value, and usage string.
-// The return value is the address of a []int variable that stores the value of the flag.
-func IntSlice(name string, value []int, usage string) *[]int {
- return CommandLine.IntSliceP(name, "", value, usage)
-}
-
-// IntSliceP is like IntSlice, but accepts a shorthand letter that can be used after a single dash.
-func IntSliceP(name, shorthand string, value []int, usage string) *[]int {
- return CommandLine.IntSliceP(name, shorthand, value, usage)
-}
diff --git a/vendor/github.com/spf13/pflag/int_slice_test.go b/vendor/github.com/spf13/pflag/int_slice_test.go
deleted file mode 100644
index 745aecb..0000000
--- a/vendor/github.com/spf13/pflag/int_slice_test.go
+++ /dev/null
@@ -1,165 +0,0 @@
-// Copyright 2009 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 pflag
-
-import (
- "fmt"
- "strconv"
- "strings"
- "testing"
-)
-
-func setUpISFlagSet(isp *[]int) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.IntSliceVar(isp, "is", []int{}, "Command separated list!")
- return f
-}
-
-func setUpISFlagSetWithDefault(isp *[]int) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.IntSliceVar(isp, "is", []int{0, 1}, "Command separated list!")
- return f
-}
-
-func TestEmptyIS(t *testing.T) {
- var is []int
- f := setUpISFlagSet(&is)
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- getIS, err := f.GetIntSlice("is")
- if err != nil {
- t.Fatal("got an error from GetIntSlice():", err)
- }
- if len(getIS) != 0 {
- t.Fatalf("got is %v with len=%d but expected length=0", getIS, len(getIS))
- }
-}
-
-func TestIS(t *testing.T) {
- var is []int
- f := setUpISFlagSet(&is)
-
- vals := []string{"1", "2", "4", "3"}
- arg := fmt.Sprintf("--is=%s", strings.Join(vals, ","))
- err := f.Parse([]string{arg})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range is {
- d, err := strconv.Atoi(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if d != v {
- t.Fatalf("expected is[%d] to be %s but got: %d", i, vals[i], v)
- }
- }
- getIS, err := f.GetIntSlice("is")
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- for i, v := range getIS {
- d, err := strconv.Atoi(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if d != v {
- t.Fatalf("expected is[%d] to be %s but got: %d from GetIntSlice", i, vals[i], v)
- }
- }
-}
-
-func TestISDefault(t *testing.T) {
- var is []int
- f := setUpISFlagSetWithDefault(&is)
-
- vals := []string{"0", "1"}
-
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range is {
- d, err := strconv.Atoi(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if d != v {
- t.Fatalf("expected is[%d] to be %d but got: %d", i, d, v)
- }
- }
-
- getIS, err := f.GetIntSlice("is")
- if err != nil {
- t.Fatal("got an error from GetIntSlice():", err)
- }
- for i, v := range getIS {
- d, err := strconv.Atoi(vals[i])
- if err != nil {
- t.Fatal("got an error from GetIntSlice():", err)
- }
- if d != v {
- t.Fatalf("expected is[%d] to be %d from GetIntSlice but got: %d", i, d, v)
- }
- }
-}
-
-func TestISWithDefault(t *testing.T) {
- var is []int
- f := setUpISFlagSetWithDefault(&is)
-
- vals := []string{"1", "2"}
- arg := fmt.Sprintf("--is=%s", strings.Join(vals, ","))
- err := f.Parse([]string{arg})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range is {
- d, err := strconv.Atoi(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if d != v {
- t.Fatalf("expected is[%d] to be %d but got: %d", i, d, v)
- }
- }
-
- getIS, err := f.GetIntSlice("is")
- if err != nil {
- t.Fatal("got an error from GetIntSlice():", err)
- }
- for i, v := range getIS {
- d, err := strconv.Atoi(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if d != v {
- t.Fatalf("expected is[%d] to be %d from GetIntSlice but got: %d", i, d, v)
- }
- }
-}
-
-func TestISCalledTwice(t *testing.T) {
- var is []int
- f := setUpISFlagSet(&is)
-
- in := []string{"1,2", "3"}
- expected := []int{1, 2, 3}
- argfmt := "--is=%s"
- arg1 := fmt.Sprintf(argfmt, in[0])
- arg2 := fmt.Sprintf(argfmt, in[1])
- err := f.Parse([]string{arg1, arg2})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range is {
- if expected[i] != v {
- t.Fatalf("expected is[%d] to be %d but got: %d", i, expected[i], v)
- }
- }
-}
diff --git a/vendor/github.com/spf13/pflag/ip.go b/vendor/github.com/spf13/pflag/ip.go
deleted file mode 100644
index 3d414ba..0000000
--- a/vendor/github.com/spf13/pflag/ip.go
+++ /dev/null
@@ -1,94 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "net"
- "strings"
-)
-
-// -- net.IP value
-type ipValue net.IP
-
-func newIPValue(val net.IP, p *net.IP) *ipValue {
- *p = val
- return (*ipValue)(p)
-}
-
-func (i *ipValue) String() string { return net.IP(*i).String() }
-func (i *ipValue) Set(s string) error {
- ip := net.ParseIP(strings.TrimSpace(s))
- if ip == nil {
- return fmt.Errorf("failed to parse IP: %q", s)
- }
- *i = ipValue(ip)
- return nil
-}
-
-func (i *ipValue) Type() string {
- return "ip"
-}
-
-func ipConv(sval string) (interface{}, error) {
- ip := net.ParseIP(sval)
- if ip != nil {
- return ip, nil
- }
- return nil, fmt.Errorf("invalid string being converted to IP address: %s", sval)
-}
-
-// GetIP return the net.IP value of a flag with the given name
-func (f *FlagSet) GetIP(name string) (net.IP, error) {
- val, err := f.getFlagType(name, "ip", ipConv)
- if err != nil {
- return nil, err
- }
- return val.(net.IP), nil
-}
-
-// IPVar defines an net.IP flag with specified name, default value, and usage string.
-// The argument p points to an net.IP variable in which to store the value of the flag.
-func (f *FlagSet) IPVar(p *net.IP, name string, value net.IP, usage string) {
- f.VarP(newIPValue(value, p), name, "", usage)
-}
-
-// IPVarP is like IPVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) {
- f.VarP(newIPValue(value, p), name, shorthand, usage)
-}
-
-// IPVar defines an net.IP flag with specified name, default value, and usage string.
-// The argument p points to an net.IP variable in which to store the value of the flag.
-func IPVar(p *net.IP, name string, value net.IP, usage string) {
- CommandLine.VarP(newIPValue(value, p), name, "", usage)
-}
-
-// IPVarP is like IPVar, but accepts a shorthand letter that can be used after a single dash.
-func IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) {
- CommandLine.VarP(newIPValue(value, p), name, shorthand, usage)
-}
-
-// IP defines an net.IP flag with specified name, default value, and usage string.
-// The return value is the address of an net.IP variable that stores the value of the flag.
-func (f *FlagSet) IP(name string, value net.IP, usage string) *net.IP {
- p := new(net.IP)
- f.IPVarP(p, name, "", value, usage)
- return p
-}
-
-// IPP is like IP, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) IPP(name, shorthand string, value net.IP, usage string) *net.IP {
- p := new(net.IP)
- f.IPVarP(p, name, shorthand, value, usage)
- return p
-}
-
-// IP defines an net.IP flag with specified name, default value, and usage string.
-// The return value is the address of an net.IP variable that stores the value of the flag.
-func IP(name string, value net.IP, usage string) *net.IP {
- return CommandLine.IPP(name, "", value, usage)
-}
-
-// IPP is like IP, but accepts a shorthand letter that can be used after a single dash.
-func IPP(name, shorthand string, value net.IP, usage string) *net.IP {
- return CommandLine.IPP(name, shorthand, value, usage)
-}
diff --git a/vendor/github.com/spf13/pflag/ip_slice.go b/vendor/github.com/spf13/pflag/ip_slice.go
deleted file mode 100644
index 7dd196f..0000000
--- a/vendor/github.com/spf13/pflag/ip_slice.go
+++ /dev/null
@@ -1,148 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "io"
- "net"
- "strings"
-)
-
-// -- ipSlice Value
-type ipSliceValue struct {
- value *[]net.IP
- changed bool
-}
-
-func newIPSliceValue(val []net.IP, p *[]net.IP) *ipSliceValue {
- ipsv := new(ipSliceValue)
- ipsv.value = p
- *ipsv.value = val
- return ipsv
-}
-
-// Set converts, and assigns, the comma-separated IP argument string representation as the []net.IP value of this flag.
-// If Set is called on a flag that already has a []net.IP assigned, the newly converted values will be appended.
-func (s *ipSliceValue) Set(val string) error {
-
- // remove all quote characters
- rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "")
-
- // read flag arguments with CSV parser
- ipStrSlice, err := readAsCSV(rmQuote.Replace(val))
- if err != nil && err != io.EOF {
- return err
- }
-
- // parse ip values into slice
- out := make([]net.IP, 0, len(ipStrSlice))
- for _, ipStr := range ipStrSlice {
- ip := net.ParseIP(strings.TrimSpace(ipStr))
- if ip == nil {
- return fmt.Errorf("invalid string being converted to IP address: %s", ipStr)
- }
- out = append(out, ip)
- }
-
- if !s.changed {
- *s.value = out
- } else {
- *s.value = append(*s.value, out...)
- }
-
- s.changed = true
-
- return nil
-}
-
-// Type returns a string that uniquely represents this flag's type.
-func (s *ipSliceValue) Type() string {
- return "ipSlice"
-}
-
-// String defines a "native" format for this net.IP slice flag value.
-func (s *ipSliceValue) String() string {
-
- ipStrSlice := make([]string, len(*s.value))
- for i, ip := range *s.value {
- ipStrSlice[i] = ip.String()
- }
-
- out, _ := writeAsCSV(ipStrSlice)
-
- return "[" + out + "]"
-}
-
-func ipSliceConv(val string) (interface{}, error) {
- val = strings.Trim(val, "[]")
- // Emtpy string would cause a slice with one (empty) entry
- if len(val) == 0 {
- return []net.IP{}, nil
- }
- ss := strings.Split(val, ",")
- out := make([]net.IP, len(ss))
- for i, sval := range ss {
- ip := net.ParseIP(strings.TrimSpace(sval))
- if ip == nil {
- return nil, fmt.Errorf("invalid string being converted to IP address: %s", sval)
- }
- out[i] = ip
- }
- return out, nil
-}
-
-// GetIPSlice returns the []net.IP value of a flag with the given name
-func (f *FlagSet) GetIPSlice(name string) ([]net.IP, error) {
- val, err := f.getFlagType(name, "ipSlice", ipSliceConv)
- if err != nil {
- return []net.IP{}, err
- }
- return val.([]net.IP), nil
-}
-
-// IPSliceVar defines a ipSlice flag with specified name, default value, and usage string.
-// The argument p points to a []net.IP variable in which to store the value of the flag.
-func (f *FlagSet) IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) {
- f.VarP(newIPSliceValue(value, p), name, "", usage)
-}
-
-// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) {
- f.VarP(newIPSliceValue(value, p), name, shorthand, usage)
-}
-
-// IPSliceVar defines a []net.IP flag with specified name, default value, and usage string.
-// The argument p points to a []net.IP variable in which to store the value of the flag.
-func IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) {
- CommandLine.VarP(newIPSliceValue(value, p), name, "", usage)
-}
-
-// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash.
-func IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) {
- CommandLine.VarP(newIPSliceValue(value, p), name, shorthand, usage)
-}
-
-// IPSlice defines a []net.IP flag with specified name, default value, and usage string.
-// The return value is the address of a []net.IP variable that stores the value of that flag.
-func (f *FlagSet) IPSlice(name string, value []net.IP, usage string) *[]net.IP {
- p := []net.IP{}
- f.IPSliceVarP(&p, name, "", value, usage)
- return &p
-}
-
-// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP {
- p := []net.IP{}
- f.IPSliceVarP(&p, name, shorthand, value, usage)
- return &p
-}
-
-// IPSlice defines a []net.IP flag with specified name, default value, and usage string.
-// The return value is the address of a []net.IP variable that stores the value of the flag.
-func IPSlice(name string, value []net.IP, usage string) *[]net.IP {
- return CommandLine.IPSliceP(name, "", value, usage)
-}
-
-// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash.
-func IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP {
- return CommandLine.IPSliceP(name, shorthand, value, usage)
-}
diff --git a/vendor/github.com/spf13/pflag/ip_slice_test.go b/vendor/github.com/spf13/pflag/ip_slice_test.go
deleted file mode 100644
index b0c681c..0000000
--- a/vendor/github.com/spf13/pflag/ip_slice_test.go
+++ /dev/null
@@ -1,222 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "net"
- "strings"
- "testing"
-)
-
-func setUpIPSFlagSet(ipsp *[]net.IP) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.IPSliceVar(ipsp, "ips", []net.IP{}, "Command separated list!")
- return f
-}
-
-func setUpIPSFlagSetWithDefault(ipsp *[]net.IP) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.IPSliceVar(ipsp, "ips",
- []net.IP{
- net.ParseIP("192.168.1.1"),
- net.ParseIP("0:0:0:0:0:0:0:1"),
- },
- "Command separated list!")
- return f
-}
-
-func TestEmptyIP(t *testing.T) {
- var ips []net.IP
- f := setUpIPSFlagSet(&ips)
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- getIPS, err := f.GetIPSlice("ips")
- if err != nil {
- t.Fatal("got an error from GetIPSlice():", err)
- }
- if len(getIPS) != 0 {
- t.Fatalf("got ips %v with len=%d but expected length=0", getIPS, len(getIPS))
- }
-}
-
-func TestIPS(t *testing.T) {
- var ips []net.IP
- f := setUpIPSFlagSet(&ips)
-
- vals := []string{"192.168.1.1", "10.0.0.1", "0:0:0:0:0:0:0:2"}
- arg := fmt.Sprintf("--ips=%s", strings.Join(vals, ","))
- err := f.Parse([]string{arg})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range ips {
- if ip := net.ParseIP(vals[i]); ip == nil {
- t.Fatalf("invalid string being converted to IP address: %s", vals[i])
- } else if !ip.Equal(v) {
- t.Fatalf("expected ips[%d] to be %s but got: %s from GetIPSlice", i, vals[i], v)
- }
- }
-}
-
-func TestIPSDefault(t *testing.T) {
- var ips []net.IP
- f := setUpIPSFlagSetWithDefault(&ips)
-
- vals := []string{"192.168.1.1", "0:0:0:0:0:0:0:1"}
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range ips {
- if ip := net.ParseIP(vals[i]); ip == nil {
- t.Fatalf("invalid string being converted to IP address: %s", vals[i])
- } else if !ip.Equal(v) {
- t.Fatalf("expected ips[%d] to be %s but got: %s", i, vals[i], v)
- }
- }
-
- getIPS, err := f.GetIPSlice("ips")
- if err != nil {
- t.Fatal("got an error from GetIPSlice")
- }
- for i, v := range getIPS {
- if ip := net.ParseIP(vals[i]); ip == nil {
- t.Fatalf("invalid string being converted to IP address: %s", vals[i])
- } else if !ip.Equal(v) {
- t.Fatalf("expected ips[%d] to be %s but got: %s", i, vals[i], v)
- }
- }
-}
-
-func TestIPSWithDefault(t *testing.T) {
- var ips []net.IP
- f := setUpIPSFlagSetWithDefault(&ips)
-
- vals := []string{"192.168.1.1", "0:0:0:0:0:0:0:1"}
- arg := fmt.Sprintf("--ips=%s", strings.Join(vals, ","))
- err := f.Parse([]string{arg})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range ips {
- if ip := net.ParseIP(vals[i]); ip == nil {
- t.Fatalf("invalid string being converted to IP address: %s", vals[i])
- } else if !ip.Equal(v) {
- t.Fatalf("expected ips[%d] to be %s but got: %s", i, vals[i], v)
- }
- }
-
- getIPS, err := f.GetIPSlice("ips")
- if err != nil {
- t.Fatal("got an error from GetIPSlice")
- }
- for i, v := range getIPS {
- if ip := net.ParseIP(vals[i]); ip == nil {
- t.Fatalf("invalid string being converted to IP address: %s", vals[i])
- } else if !ip.Equal(v) {
- t.Fatalf("expected ips[%d] to be %s but got: %s", i, vals[i], v)
- }
- }
-}
-
-func TestIPSCalledTwice(t *testing.T) {
- var ips []net.IP
- f := setUpIPSFlagSet(&ips)
-
- in := []string{"192.168.1.2,0:0:0:0:0:0:0:1", "10.0.0.1"}
- expected := []net.IP{net.ParseIP("192.168.1.2"), net.ParseIP("0:0:0:0:0:0:0:1"), net.ParseIP("10.0.0.1")}
- argfmt := "ips=%s"
- arg1 := fmt.Sprintf(argfmt, in[0])
- arg2 := fmt.Sprintf(argfmt, in[1])
- err := f.Parse([]string{arg1, arg2})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range ips {
- if !expected[i].Equal(v) {
- t.Fatalf("expected ips[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-}
-
-func TestIPSBadQuoting(t *testing.T) {
-
- tests := []struct {
- Want []net.IP
- FlagArg []string
- }{
- {
- Want: []net.IP{
- net.ParseIP("a4ab:61d:f03e:5d7d:fad7:d4c2:a1a5:568"),
- net.ParseIP("203.107.49.208"),
- net.ParseIP("14.57.204.90"),
- },
- FlagArg: []string{
- "a4ab:61d:f03e:5d7d:fad7:d4c2:a1a5:568",
- "203.107.49.208",
- "14.57.204.90",
- },
- },
- {
- Want: []net.IP{
- net.ParseIP("204.228.73.195"),
- net.ParseIP("86.141.15.94"),
- },
- FlagArg: []string{
- "204.228.73.195",
- "86.141.15.94",
- },
- },
- {
- Want: []net.IP{
- net.ParseIP("c70c:db36:3001:890f:c6ea:3f9b:7a39:cc3f"),
- net.ParseIP("4d17:1d6e:e699:bd7a:88c5:5e7e:ac6a:4472"),
- },
- FlagArg: []string{
- "c70c:db36:3001:890f:c6ea:3f9b:7a39:cc3f",
- "4d17:1d6e:e699:bd7a:88c5:5e7e:ac6a:4472",
- },
- },
- {
- Want: []net.IP{
- net.ParseIP("5170:f971:cfac:7be3:512a:af37:952c:bc33"),
- net.ParseIP("93.21.145.140"),
- net.ParseIP("2cac:61d3:c5ff:6caf:73e0:1b1a:c336:c1ca"),
- },
- FlagArg: []string{
- " 5170:f971:cfac:7be3:512a:af37:952c:bc33 , 93.21.145.140 ",
- "2cac:61d3:c5ff:6caf:73e0:1b1a:c336:c1ca",
- },
- },
- {
- Want: []net.IP{
- net.ParseIP("2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"),
- net.ParseIP("2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"),
- net.ParseIP("2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"),
- net.ParseIP("2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"),
- },
- FlagArg: []string{
- `"2e5e:66b2:6441:848:5b74:76ea:574c:3a7b, 2e5e:66b2:6441:848:5b74:76ea:574c:3a7b,2e5e:66b2:6441:848:5b74:76ea:574c:3a7b "`,
- " 2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"},
- },
- }
-
- for i, test := range tests {
-
- var ips []net.IP
- f := setUpIPSFlagSet(&ips)
-
- if err := f.Parse([]string{fmt.Sprintf("--ips=%s", strings.Join(test.FlagArg, ","))}); err != nil {
- t.Fatalf("flag parsing failed with error: %s\nparsing:\t%#v\nwant:\t\t%s",
- err, test.FlagArg, test.Want[i])
- }
-
- for j, b := range ips {
- if !b.Equal(test.Want[j]) {
- t.Fatalf("bad value parsed for test %d on net.IP %d:\nwant:\t%s\ngot:\t%s", i, j, test.Want[j], b)
- }
- }
- }
-}
diff --git a/vendor/github.com/spf13/pflag/ip_test.go b/vendor/github.com/spf13/pflag/ip_test.go
deleted file mode 100644
index 1fec50e..0000000
--- a/vendor/github.com/spf13/pflag/ip_test.go
+++ /dev/null
@@ -1,63 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "net"
- "os"
- "testing"
-)
-
-func setUpIP(ip *net.IP) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.IPVar(ip, "address", net.ParseIP("0.0.0.0"), "IP Address")
- return f
-}
-
-func TestIP(t *testing.T) {
- testCases := []struct {
- input string
- success bool
- expected string
- }{
- {"0.0.0.0", true, "0.0.0.0"},
- {" 0.0.0.0 ", true, "0.0.0.0"},
- {"1.2.3.4", true, "1.2.3.4"},
- {"127.0.0.1", true, "127.0.0.1"},
- {"255.255.255.255", true, "255.255.255.255"},
- {"", false, ""},
- {"0", false, ""},
- {"localhost", false, ""},
- {"0.0.0", false, ""},
- {"0.0.0.", false, ""},
- {"0.0.0.0.", false, ""},
- {"0.0.0.256", false, ""},
- {"0 . 0 . 0 . 0", false, ""},
- }
-
- devnull, _ := os.Open(os.DevNull)
- os.Stderr = devnull
- for i := range testCases {
- var addr net.IP
- f := setUpIP(&addr)
-
- tc := &testCases[i]
-
- arg := fmt.Sprintf("--address=%s", tc.input)
- err := f.Parse([]string{arg})
- if err != nil && tc.success == true {
- t.Errorf("expected success, got %q", err)
- continue
- } else if err == nil && tc.success == false {
- t.Errorf("expected failure")
- continue
- } else if tc.success {
- ip, err := f.GetIP("address")
- if err != nil {
- t.Errorf("Got error trying to fetch the IP flag: %v", err)
- }
- if ip.String() != tc.expected {
- t.Errorf("expected %q, got %q", tc.expected, ip.String())
- }
- }
- }
-}
diff --git a/vendor/github.com/spf13/pflag/ipmask.go b/vendor/github.com/spf13/pflag/ipmask.go
deleted file mode 100644
index 5bd44bd..0000000
--- a/vendor/github.com/spf13/pflag/ipmask.go
+++ /dev/null
@@ -1,122 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "net"
- "strconv"
-)
-
-// -- net.IPMask value
-type ipMaskValue net.IPMask
-
-func newIPMaskValue(val net.IPMask, p *net.IPMask) *ipMaskValue {
- *p = val
- return (*ipMaskValue)(p)
-}
-
-func (i *ipMaskValue) String() string { return net.IPMask(*i).String() }
-func (i *ipMaskValue) Set(s string) error {
- ip := ParseIPv4Mask(s)
- if ip == nil {
- return fmt.Errorf("failed to parse IP mask: %q", s)
- }
- *i = ipMaskValue(ip)
- return nil
-}
-
-func (i *ipMaskValue) Type() string {
- return "ipMask"
-}
-
-// ParseIPv4Mask written in IP form (e.g. 255.255.255.0).
-// This function should really belong to the net package.
-func ParseIPv4Mask(s string) net.IPMask {
- mask := net.ParseIP(s)
- if mask == nil {
- if len(s) != 8 {
- return nil
- }
- // net.IPMask.String() actually outputs things like ffffff00
- // so write a horrible parser for that as well :-(
- m := []int{}
- for i := 0; i < 4; i++ {
- b := "0x" + s[2*i:2*i+2]
- d, err := strconv.ParseInt(b, 0, 0)
- if err != nil {
- return nil
- }
- m = append(m, int(d))
- }
- s := fmt.Sprintf("%d.%d.%d.%d", m[0], m[1], m[2], m[3])
- mask = net.ParseIP(s)
- if mask == nil {
- return nil
- }
- }
- return net.IPv4Mask(mask[12], mask[13], mask[14], mask[15])
-}
-
-func parseIPv4Mask(sval string) (interface{}, error) {
- mask := ParseIPv4Mask(sval)
- if mask == nil {
- return nil, fmt.Errorf("unable to parse %s as net.IPMask", sval)
- }
- return mask, nil
-}
-
-// GetIPv4Mask return the net.IPv4Mask value of a flag with the given name
-func (f *FlagSet) GetIPv4Mask(name string) (net.IPMask, error) {
- val, err := f.getFlagType(name, "ipMask", parseIPv4Mask)
- if err != nil {
- return nil, err
- }
- return val.(net.IPMask), nil
-}
-
-// IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string.
-// The argument p points to an net.IPMask variable in which to store the value of the flag.
-func (f *FlagSet) IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) {
- f.VarP(newIPMaskValue(value, p), name, "", usage)
-}
-
-// IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) {
- f.VarP(newIPMaskValue(value, p), name, shorthand, usage)
-}
-
-// IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string.
-// The argument p points to an net.IPMask variable in which to store the value of the flag.
-func IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) {
- CommandLine.VarP(newIPMaskValue(value, p), name, "", usage)
-}
-
-// IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash.
-func IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) {
- CommandLine.VarP(newIPMaskValue(value, p), name, shorthand, usage)
-}
-
-// IPMask defines an net.IPMask flag with specified name, default value, and usage string.
-// The return value is the address of an net.IPMask variable that stores the value of the flag.
-func (f *FlagSet) IPMask(name string, value net.IPMask, usage string) *net.IPMask {
- p := new(net.IPMask)
- f.IPMaskVarP(p, name, "", value, usage)
- return p
-}
-
-// IPMaskP is like IPMask, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask {
- p := new(net.IPMask)
- f.IPMaskVarP(p, name, shorthand, value, usage)
- return p
-}
-
-// IPMask defines an net.IPMask flag with specified name, default value, and usage string.
-// The return value is the address of an net.IPMask variable that stores the value of the flag.
-func IPMask(name string, value net.IPMask, usage string) *net.IPMask {
- return CommandLine.IPMaskP(name, "", value, usage)
-}
-
-// IPMaskP is like IP, but accepts a shorthand letter that can be used after a single dash.
-func IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask {
- return CommandLine.IPMaskP(name, shorthand, value, usage)
-}
diff --git a/vendor/github.com/spf13/pflag/ipnet.go b/vendor/github.com/spf13/pflag/ipnet.go
deleted file mode 100644
index e2c1b8b..0000000
--- a/vendor/github.com/spf13/pflag/ipnet.go
+++ /dev/null
@@ -1,98 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "net"
- "strings"
-)
-
-// IPNet adapts net.IPNet for use as a flag.
-type ipNetValue net.IPNet
-
-func (ipnet ipNetValue) String() string {
- n := net.IPNet(ipnet)
- return n.String()
-}
-
-func (ipnet *ipNetValue) Set(value string) error {
- _, n, err := net.ParseCIDR(strings.TrimSpace(value))
- if err != nil {
- return err
- }
- *ipnet = ipNetValue(*n)
- return nil
-}
-
-func (*ipNetValue) Type() string {
- return "ipNet"
-}
-
-func newIPNetValue(val net.IPNet, p *net.IPNet) *ipNetValue {
- *p = val
- return (*ipNetValue)(p)
-}
-
-func ipNetConv(sval string) (interface{}, error) {
- _, n, err := net.ParseCIDR(strings.TrimSpace(sval))
- if err == nil {
- return *n, nil
- }
- return nil, fmt.Errorf("invalid string being converted to IPNet: %s", sval)
-}
-
-// GetIPNet return the net.IPNet value of a flag with the given name
-func (f *FlagSet) GetIPNet(name string) (net.IPNet, error) {
- val, err := f.getFlagType(name, "ipNet", ipNetConv)
- if err != nil {
- return net.IPNet{}, err
- }
- return val.(net.IPNet), nil
-}
-
-// IPNetVar defines an net.IPNet flag with specified name, default value, and usage string.
-// The argument p points to an net.IPNet variable in which to store the value of the flag.
-func (f *FlagSet) IPNetVar(p *net.IPNet, name string, value net.IPNet, usage string) {
- f.VarP(newIPNetValue(value, p), name, "", usage)
-}
-
-// IPNetVarP is like IPNetVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) IPNetVarP(p *net.IPNet, name, shorthand string, value net.IPNet, usage string) {
- f.VarP(newIPNetValue(value, p), name, shorthand, usage)
-}
-
-// IPNetVar defines an net.IPNet flag with specified name, default value, and usage string.
-// The argument p points to an net.IPNet variable in which to store the value of the flag.
-func IPNetVar(p *net.IPNet, name string, value net.IPNet, usage string) {
- CommandLine.VarP(newIPNetValue(value, p), name, "", usage)
-}
-
-// IPNetVarP is like IPNetVar, but accepts a shorthand letter that can be used after a single dash.
-func IPNetVarP(p *net.IPNet, name, shorthand string, value net.IPNet, usage string) {
- CommandLine.VarP(newIPNetValue(value, p), name, shorthand, usage)
-}
-
-// IPNet defines an net.IPNet flag with specified name, default value, and usage string.
-// The return value is the address of an net.IPNet variable that stores the value of the flag.
-func (f *FlagSet) IPNet(name string, value net.IPNet, usage string) *net.IPNet {
- p := new(net.IPNet)
- f.IPNetVarP(p, name, "", value, usage)
- return p
-}
-
-// IPNetP is like IPNet, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) IPNetP(name, shorthand string, value net.IPNet, usage string) *net.IPNet {
- p := new(net.IPNet)
- f.IPNetVarP(p, name, shorthand, value, usage)
- return p
-}
-
-// IPNet defines an net.IPNet flag with specified name, default value, and usage string.
-// The return value is the address of an net.IPNet variable that stores the value of the flag.
-func IPNet(name string, value net.IPNet, usage string) *net.IPNet {
- return CommandLine.IPNetP(name, "", value, usage)
-}
-
-// IPNetP is like IPNet, but accepts a shorthand letter that can be used after a single dash.
-func IPNetP(name, shorthand string, value net.IPNet, usage string) *net.IPNet {
- return CommandLine.IPNetP(name, shorthand, value, usage)
-}
diff --git a/vendor/github.com/spf13/pflag/ipnet_test.go b/vendor/github.com/spf13/pflag/ipnet_test.go
deleted file mode 100644
index 335b6fa..0000000
--- a/vendor/github.com/spf13/pflag/ipnet_test.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "net"
- "os"
- "testing"
-)
-
-func setUpIPNet(ip *net.IPNet) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- _, def, _ := net.ParseCIDR("0.0.0.0/0")
- f.IPNetVar(ip, "address", *def, "IP Address")
- return f
-}
-
-func TestIPNet(t *testing.T) {
- testCases := []struct {
- input string
- success bool
- expected string
- }{
- {"0.0.0.0/0", true, "0.0.0.0/0"},
- {" 0.0.0.0/0 ", true, "0.0.0.0/0"},
- {"1.2.3.4/8", true, "1.0.0.0/8"},
- {"127.0.0.1/16", true, "127.0.0.0/16"},
- {"255.255.255.255/19", true, "255.255.224.0/19"},
- {"255.255.255.255/32", true, "255.255.255.255/32"},
- {"", false, ""},
- {"/0", false, ""},
- {"0", false, ""},
- {"0/0", false, ""},
- {"localhost/0", false, ""},
- {"0.0.0/4", false, ""},
- {"0.0.0./8", false, ""},
- {"0.0.0.0./12", false, ""},
- {"0.0.0.256/16", false, ""},
- {"0.0.0.0 /20", false, ""},
- {"0.0.0.0/ 24", false, ""},
- {"0 . 0 . 0 . 0 / 28", false, ""},
- {"0.0.0.0/33", false, ""},
- }
-
- devnull, _ := os.Open(os.DevNull)
- os.Stderr = devnull
- for i := range testCases {
- var addr net.IPNet
- f := setUpIPNet(&addr)
-
- tc := &testCases[i]
-
- arg := fmt.Sprintf("--address=%s", tc.input)
- err := f.Parse([]string{arg})
- if err != nil && tc.success == true {
- t.Errorf("expected success, got %q", err)
- continue
- } else if err == nil && tc.success == false {
- t.Errorf("expected failure")
- continue
- } else if tc.success {
- ip, err := f.GetIPNet("address")
- if err != nil {
- t.Errorf("Got error trying to fetch the IP flag: %v", err)
- }
- if ip.String() != tc.expected {
- t.Errorf("expected %q, got %q", tc.expected, ip.String())
- }
- }
- }
-}
diff --git a/vendor/github.com/spf13/pflag/string.go b/vendor/github.com/spf13/pflag/string.go
deleted file mode 100644
index 04e0a26..0000000
--- a/vendor/github.com/spf13/pflag/string.go
+++ /dev/null
@@ -1,80 +0,0 @@
-package pflag
-
-// -- string Value
-type stringValue string
-
-func newStringValue(val string, p *string) *stringValue {
- *p = val
- return (*stringValue)(p)
-}
-
-func (s *stringValue) Set(val string) error {
- *s = stringValue(val)
- return nil
-}
-func (s *stringValue) Type() string {
- return "string"
-}
-
-func (s *stringValue) String() string { return string(*s) }
-
-func stringConv(sval string) (interface{}, error) {
- return sval, nil
-}
-
-// GetString return the string value of a flag with the given name
-func (f *FlagSet) GetString(name string) (string, error) {
- val, err := f.getFlagType(name, "string", stringConv)
- if err != nil {
- return "", err
- }
- return val.(string), nil
-}
-
-// StringVar defines a string flag with specified name, default value, and usage string.
-// The argument p points to a string variable in which to store the value of the flag.
-func (f *FlagSet) StringVar(p *string, name string, value string, usage string) {
- f.VarP(newStringValue(value, p), name, "", usage)
-}
-
-// StringVarP is like StringVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) StringVarP(p *string, name, shorthand string, value string, usage string) {
- f.VarP(newStringValue(value, p), name, shorthand, usage)
-}
-
-// StringVar defines a string flag with specified name, default value, and usage string.
-// The argument p points to a string variable in which to store the value of the flag.
-func StringVar(p *string, name string, value string, usage string) {
- CommandLine.VarP(newStringValue(value, p), name, "", usage)
-}
-
-// StringVarP is like StringVar, but accepts a shorthand letter that can be used after a single dash.
-func StringVarP(p *string, name, shorthand string, value string, usage string) {
- CommandLine.VarP(newStringValue(value, p), name, shorthand, usage)
-}
-
-// String defines a string flag with specified name, default value, and usage string.
-// The return value is the address of a string variable that stores the value of the flag.
-func (f *FlagSet) String(name string, value string, usage string) *string {
- p := new(string)
- f.StringVarP(p, name, "", value, usage)
- return p
-}
-
-// StringP is like String, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) StringP(name, shorthand string, value string, usage string) *string {
- p := new(string)
- f.StringVarP(p, name, shorthand, value, usage)
- return p
-}
-
-// String defines a string flag with specified name, default value, and usage string.
-// The return value is the address of a string variable that stores the value of the flag.
-func String(name string, value string, usage string) *string {
- return CommandLine.StringP(name, "", value, usage)
-}
-
-// StringP is like String, but accepts a shorthand letter that can be used after a single dash.
-func StringP(name, shorthand string, value string, usage string) *string {
- return CommandLine.StringP(name, shorthand, value, usage)
-}
diff --git a/vendor/github.com/spf13/pflag/string_array.go b/vendor/github.com/spf13/pflag/string_array.go
deleted file mode 100644
index 276b7ed..0000000
--- a/vendor/github.com/spf13/pflag/string_array.go
+++ /dev/null
@@ -1,103 +0,0 @@
-package pflag
-
-// -- stringArray Value
-type stringArrayValue struct {
- value *[]string
- changed bool
-}
-
-func newStringArrayValue(val []string, p *[]string) *stringArrayValue {
- ssv := new(stringArrayValue)
- ssv.value = p
- *ssv.value = val
- return ssv
-}
-
-func (s *stringArrayValue) Set(val string) error {
- if !s.changed {
- *s.value = []string{val}
- s.changed = true
- } else {
- *s.value = append(*s.value, val)
- }
- return nil
-}
-
-func (s *stringArrayValue) Type() string {
- return "stringArray"
-}
-
-func (s *stringArrayValue) String() string {
- str, _ := writeAsCSV(*s.value)
- return "[" + str + "]"
-}
-
-func stringArrayConv(sval string) (interface{}, error) {
- sval = sval[1 : len(sval)-1]
- // An empty string would cause a array with one (empty) string
- if len(sval) == 0 {
- return []string{}, nil
- }
- return readAsCSV(sval)
-}
-
-// GetStringArray return the []string value of a flag with the given name
-func (f *FlagSet) GetStringArray(name string) ([]string, error) {
- val, err := f.getFlagType(name, "stringArray", stringArrayConv)
- if err != nil {
- return []string{}, err
- }
- return val.([]string), nil
-}
-
-// StringArrayVar defines a string flag with specified name, default value, and usage string.
-// The argument p points to a []string variable in which to store the values of the multiple flags.
-// The value of each argument will not try to be separated by comma
-func (f *FlagSet) StringArrayVar(p *[]string, name string, value []string, usage string) {
- f.VarP(newStringArrayValue(value, p), name, "", usage)
-}
-
-// StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) StringArrayVarP(p *[]string, name, shorthand string, value []string, usage string) {
- f.VarP(newStringArrayValue(value, p), name, shorthand, usage)
-}
-
-// StringArrayVar defines a string flag with specified name, default value, and usage string.
-// The argument p points to a []string variable in which to store the value of the flag.
-// The value of each argument will not try to be separated by comma
-func StringArrayVar(p *[]string, name string, value []string, usage string) {
- CommandLine.VarP(newStringArrayValue(value, p), name, "", usage)
-}
-
-// StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash.
-func StringArrayVarP(p *[]string, name, shorthand string, value []string, usage string) {
- CommandLine.VarP(newStringArrayValue(value, p), name, shorthand, usage)
-}
-
-// StringArray defines a string flag with specified name, default value, and usage string.
-// The return value is the address of a []string variable that stores the value of the flag.
-// The value of each argument will not try to be separated by comma
-func (f *FlagSet) StringArray(name string, value []string, usage string) *[]string {
- p := []string{}
- f.StringArrayVarP(&p, name, "", value, usage)
- return &p
-}
-
-// StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) StringArrayP(name, shorthand string, value []string, usage string) *[]string {
- p := []string{}
- f.StringArrayVarP(&p, name, shorthand, value, usage)
- return &p
-}
-
-// StringArray defines a string flag with specified name, default value, and usage string.
-// The return value is the address of a []string variable that stores the value of the flag.
-// The value of each argument will not try to be separated by comma
-func StringArray(name string, value []string, usage string) *[]string {
- return CommandLine.StringArrayP(name, "", value, usage)
-}
-
-// StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash.
-func StringArrayP(name, shorthand string, value []string, usage string) *[]string {
- return CommandLine.StringArrayP(name, shorthand, value, usage)
-}
diff --git a/vendor/github.com/spf13/pflag/string_array_test.go b/vendor/github.com/spf13/pflag/string_array_test.go
deleted file mode 100644
index 1ceac8c..0000000
--- a/vendor/github.com/spf13/pflag/string_array_test.go
+++ /dev/null
@@ -1,233 +0,0 @@
-// Copyright 2009 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 pflag
-
-import (
- "fmt"
- "testing"
-)
-
-func setUpSAFlagSet(sap *[]string) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.StringArrayVar(sap, "sa", []string{}, "Command separated list!")
- return f
-}
-
-func setUpSAFlagSetWithDefault(sap *[]string) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.StringArrayVar(sap, "sa", []string{"default", "values"}, "Command separated list!")
- return f
-}
-
-func TestEmptySA(t *testing.T) {
- var sa []string
- f := setUpSAFlagSet(&sa)
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- getSA, err := f.GetStringArray("sa")
- if err != nil {
- t.Fatal("got an error from GetStringArray():", err)
- }
- if len(getSA) != 0 {
- t.Fatalf("got sa %v with len=%d but expected length=0", getSA, len(getSA))
- }
-}
-
-func TestEmptySAValue(t *testing.T) {
- var sa []string
- f := setUpSAFlagSet(&sa)
- err := f.Parse([]string{"--sa="})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- getSA, err := f.GetStringArray("sa")
- if err != nil {
- t.Fatal("got an error from GetStringArray():", err)
- }
- if len(getSA) != 0 {
- t.Fatalf("got sa %v with len=%d but expected length=0", getSA, len(getSA))
- }
-}
-
-func TestSADefault(t *testing.T) {
- var sa []string
- f := setUpSAFlagSetWithDefault(&sa)
-
- vals := []string{"default", "values"}
-
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range sa {
- if vals[i] != v {
- t.Fatalf("expected sa[%d] to be %s but got: %s", i, vals[i], v)
- }
- }
-
- getSA, err := f.GetStringArray("sa")
- if err != nil {
- t.Fatal("got an error from GetStringArray():", err)
- }
- for i, v := range getSA {
- if vals[i] != v {
- t.Fatalf("expected sa[%d] to be %s from GetStringArray but got: %s", i, vals[i], v)
- }
- }
-}
-
-func TestSAWithDefault(t *testing.T) {
- var sa []string
- f := setUpSAFlagSetWithDefault(&sa)
-
- val := "one"
- arg := fmt.Sprintf("--sa=%s", val)
- err := f.Parse([]string{arg})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(sa) != 1 {
- t.Fatalf("expected number of values to be %d but %d", 1, len(sa))
- }
-
- if sa[0] != val {
- t.Fatalf("expected value to be %s but got: %s", sa[0], val)
- }
-
- getSA, err := f.GetStringArray("sa")
- if err != nil {
- t.Fatal("got an error from GetStringArray():", err)
- }
-
- if len(getSA) != 1 {
- t.Fatalf("expected number of values to be %d but %d", 1, len(getSA))
- }
-
- if getSA[0] != val {
- t.Fatalf("expected value to be %s but got: %s", getSA[0], val)
- }
-}
-
-func TestSACalledTwice(t *testing.T) {
- var sa []string
- f := setUpSAFlagSet(&sa)
-
- in := []string{"one", "two"}
- expected := []string{"one", "two"}
- argfmt := "--sa=%s"
- arg1 := fmt.Sprintf(argfmt, in[0])
- arg2 := fmt.Sprintf(argfmt, in[1])
- err := f.Parse([]string{arg1, arg2})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(expected) != len(sa) {
- t.Fatalf("expected number of sa to be %d but got: %d", len(expected), len(sa))
- }
- for i, v := range sa {
- if expected[i] != v {
- t.Fatalf("expected sa[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-
- values, err := f.GetStringArray("sa")
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(expected) != len(values) {
- t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(sa))
- }
- for i, v := range values {
- if expected[i] != v {
- t.Fatalf("expected got sa[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-}
-
-func TestSAWithSpecialChar(t *testing.T) {
- var sa []string
- f := setUpSAFlagSet(&sa)
-
- in := []string{"one,two", `"three"`, `"four,five",six`, "seven eight"}
- expected := []string{"one,two", `"three"`, `"four,five",six`, "seven eight"}
- argfmt := "--sa=%s"
- arg1 := fmt.Sprintf(argfmt, in[0])
- arg2 := fmt.Sprintf(argfmt, in[1])
- arg3 := fmt.Sprintf(argfmt, in[2])
- arg4 := fmt.Sprintf(argfmt, in[3])
- err := f.Parse([]string{arg1, arg2, arg3, arg4})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(expected) != len(sa) {
- t.Fatalf("expected number of sa to be %d but got: %d", len(expected), len(sa))
- }
- for i, v := range sa {
- if expected[i] != v {
- t.Fatalf("expected sa[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-
- values, err := f.GetStringArray("sa")
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(expected) != len(values) {
- t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values))
- }
- for i, v := range values {
- if expected[i] != v {
- t.Fatalf("expected got sa[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-}
-
-func TestSAWithSquareBrackets(t *testing.T) {
- var sa []string
- f := setUpSAFlagSet(&sa)
-
- in := []string{"][]-[", "[a-z]", "[a-z]+"}
- expected := []string{"][]-[", "[a-z]", "[a-z]+"}
- argfmt := "--sa=%s"
- arg1 := fmt.Sprintf(argfmt, in[0])
- arg2 := fmt.Sprintf(argfmt, in[1])
- arg3 := fmt.Sprintf(argfmt, in[2])
- err := f.Parse([]string{arg1, arg2, arg3})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(expected) != len(sa) {
- t.Fatalf("expected number of sa to be %d but got: %d", len(expected), len(sa))
- }
- for i, v := range sa {
- if expected[i] != v {
- t.Fatalf("expected sa[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-
- values, err := f.GetStringArray("sa")
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(expected) != len(values) {
- t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values))
- }
- for i, v := range values {
- if expected[i] != v {
- t.Fatalf("expected got sa[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-}
diff --git a/vendor/github.com/spf13/pflag/string_slice.go b/vendor/github.com/spf13/pflag/string_slice.go
deleted file mode 100644
index 05eee75..0000000
--- a/vendor/github.com/spf13/pflag/string_slice.go
+++ /dev/null
@@ -1,129 +0,0 @@
-package pflag
-
-import (
- "bytes"
- "encoding/csv"
- "strings"
-)
-
-// -- stringSlice Value
-type stringSliceValue struct {
- value *[]string
- changed bool
-}
-
-func newStringSliceValue(val []string, p *[]string) *stringSliceValue {
- ssv := new(stringSliceValue)
- ssv.value = p
- *ssv.value = val
- return ssv
-}
-
-func readAsCSV(val string) ([]string, error) {
- if val == "" {
- return []string{}, nil
- }
- stringReader := strings.NewReader(val)
- csvReader := csv.NewReader(stringReader)
- return csvReader.Read()
-}
-
-func writeAsCSV(vals []string) (string, error) {
- b := &bytes.Buffer{}
- w := csv.NewWriter(b)
- err := w.Write(vals)
- if err != nil {
- return "", err
- }
- w.Flush()
- return strings.TrimSuffix(b.String(), "\n"), nil
-}
-
-func (s *stringSliceValue) Set(val string) error {
- v, err := readAsCSV(val)
- if err != nil {
- return err
- }
- if !s.changed {
- *s.value = v
- } else {
- *s.value = append(*s.value, v...)
- }
- s.changed = true
- return nil
-}
-
-func (s *stringSliceValue) Type() string {
- return "stringSlice"
-}
-
-func (s *stringSliceValue) String() string {
- str, _ := writeAsCSV(*s.value)
- return "[" + str + "]"
-}
-
-func stringSliceConv(sval string) (interface{}, error) {
- sval = sval[1 : len(sval)-1]
- // An empty string would cause a slice with one (empty) string
- if len(sval) == 0 {
- return []string{}, nil
- }
- return readAsCSV(sval)
-}
-
-// GetStringSlice return the []string value of a flag with the given name
-func (f *FlagSet) GetStringSlice(name string) ([]string, error) {
- val, err := f.getFlagType(name, "stringSlice", stringSliceConv)
- if err != nil {
- return []string{}, err
- }
- return val.([]string), nil
-}
-
-// StringSliceVar defines a string flag with specified name, default value, and usage string.
-// The argument p points to a []string variable in which to store the value of the flag.
-func (f *FlagSet) StringSliceVar(p *[]string, name string, value []string, usage string) {
- f.VarP(newStringSliceValue(value, p), name, "", usage)
-}
-
-// StringSliceVarP is like StringSliceVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) StringSliceVarP(p *[]string, name, shorthand string, value []string, usage string) {
- f.VarP(newStringSliceValue(value, p), name, shorthand, usage)
-}
-
-// StringSliceVar defines a string flag with specified name, default value, and usage string.
-// The argument p points to a []string variable in which to store the value of the flag.
-func StringSliceVar(p *[]string, name string, value []string, usage string) {
- CommandLine.VarP(newStringSliceValue(value, p), name, "", usage)
-}
-
-// StringSliceVarP is like StringSliceVar, but accepts a shorthand letter that can be used after a single dash.
-func StringSliceVarP(p *[]string, name, shorthand string, value []string, usage string) {
- CommandLine.VarP(newStringSliceValue(value, p), name, shorthand, usage)
-}
-
-// StringSlice defines a string flag with specified name, default value, and usage string.
-// The return value is the address of a []string variable that stores the value of the flag.
-func (f *FlagSet) StringSlice(name string, value []string, usage string) *[]string {
- p := []string{}
- f.StringSliceVarP(&p, name, "", value, usage)
- return &p
-}
-
-// StringSliceP is like StringSlice, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) StringSliceP(name, shorthand string, value []string, usage string) *[]string {
- p := []string{}
- f.StringSliceVarP(&p, name, shorthand, value, usage)
- return &p
-}
-
-// StringSlice defines a string flag with specified name, default value, and usage string.
-// The return value is the address of a []string variable that stores the value of the flag.
-func StringSlice(name string, value []string, usage string) *[]string {
- return CommandLine.StringSliceP(name, "", value, usage)
-}
-
-// StringSliceP is like StringSlice, but accepts a shorthand letter that can be used after a single dash.
-func StringSliceP(name, shorthand string, value []string, usage string) *[]string {
- return CommandLine.StringSliceP(name, shorthand, value, usage)
-}
diff --git a/vendor/github.com/spf13/pflag/string_slice_test.go b/vendor/github.com/spf13/pflag/string_slice_test.go
deleted file mode 100644
index c41f3bd..0000000
--- a/vendor/github.com/spf13/pflag/string_slice_test.go
+++ /dev/null
@@ -1,253 +0,0 @@
-// Copyright 2009 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 pflag
-
-import (
- "fmt"
- "strings"
- "testing"
-)
-
-func setUpSSFlagSet(ssp *[]string) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.StringSliceVar(ssp, "ss", []string{}, "Command separated list!")
- return f
-}
-
-func setUpSSFlagSetWithDefault(ssp *[]string) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.StringSliceVar(ssp, "ss", []string{"default", "values"}, "Command separated list!")
- return f
-}
-
-func TestEmptySS(t *testing.T) {
- var ss []string
- f := setUpSSFlagSet(&ss)
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- getSS, err := f.GetStringSlice("ss")
- if err != nil {
- t.Fatal("got an error from GetStringSlice():", err)
- }
- if len(getSS) != 0 {
- t.Fatalf("got ss %v with len=%d but expected length=0", getSS, len(getSS))
- }
-}
-
-func TestEmptySSValue(t *testing.T) {
- var ss []string
- f := setUpSSFlagSet(&ss)
- err := f.Parse([]string{"--ss="})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- getSS, err := f.GetStringSlice("ss")
- if err != nil {
- t.Fatal("got an error from GetStringSlice():", err)
- }
- if len(getSS) != 0 {
- t.Fatalf("got ss %v with len=%d but expected length=0", getSS, len(getSS))
- }
-}
-
-func TestSS(t *testing.T) {
- var ss []string
- f := setUpSSFlagSet(&ss)
-
- vals := []string{"one", "two", "4", "3"}
- arg := fmt.Sprintf("--ss=%s", strings.Join(vals, ","))
- err := f.Parse([]string{arg})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range ss {
- if vals[i] != v {
- t.Fatalf("expected ss[%d] to be %s but got: %s", i, vals[i], v)
- }
- }
-
- getSS, err := f.GetStringSlice("ss")
- if err != nil {
- t.Fatal("got an error from GetStringSlice():", err)
- }
- for i, v := range getSS {
- if vals[i] != v {
- t.Fatalf("expected ss[%d] to be %s from GetStringSlice but got: %s", i, vals[i], v)
- }
- }
-}
-
-func TestSSDefault(t *testing.T) {
- var ss []string
- f := setUpSSFlagSetWithDefault(&ss)
-
- vals := []string{"default", "values"}
-
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range ss {
- if vals[i] != v {
- t.Fatalf("expected ss[%d] to be %s but got: %s", i, vals[i], v)
- }
- }
-
- getSS, err := f.GetStringSlice("ss")
- if err != nil {
- t.Fatal("got an error from GetStringSlice():", err)
- }
- for i, v := range getSS {
- if vals[i] != v {
- t.Fatalf("expected ss[%d] to be %s from GetStringSlice but got: %s", i, vals[i], v)
- }
- }
-}
-
-func TestSSWithDefault(t *testing.T) {
- var ss []string
- f := setUpSSFlagSetWithDefault(&ss)
-
- vals := []string{"one", "two", "4", "3"}
- arg := fmt.Sprintf("--ss=%s", strings.Join(vals, ","))
- err := f.Parse([]string{arg})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range ss {
- if vals[i] != v {
- t.Fatalf("expected ss[%d] to be %s but got: %s", i, vals[i], v)
- }
- }
-
- getSS, err := f.GetStringSlice("ss")
- if err != nil {
- t.Fatal("got an error from GetStringSlice():", err)
- }
- for i, v := range getSS {
- if vals[i] != v {
- t.Fatalf("expected ss[%d] to be %s from GetStringSlice but got: %s", i, vals[i], v)
- }
- }
-}
-
-func TestSSCalledTwice(t *testing.T) {
- var ss []string
- f := setUpSSFlagSet(&ss)
-
- in := []string{"one,two", "three"}
- expected := []string{"one", "two", "three"}
- argfmt := "--ss=%s"
- arg1 := fmt.Sprintf(argfmt, in[0])
- arg2 := fmt.Sprintf(argfmt, in[1])
- err := f.Parse([]string{arg1, arg2})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(expected) != len(ss) {
- t.Fatalf("expected number of ss to be %d but got: %d", len(expected), len(ss))
- }
- for i, v := range ss {
- if expected[i] != v {
- t.Fatalf("expected ss[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-
- values, err := f.GetStringSlice("ss")
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(expected) != len(values) {
- t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(ss))
- }
- for i, v := range values {
- if expected[i] != v {
- t.Fatalf("expected got ss[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-}
-
-func TestSSWithComma(t *testing.T) {
- var ss []string
- f := setUpSSFlagSet(&ss)
-
- in := []string{`"one,two"`, `"three"`, `"four,five",six`}
- expected := []string{"one,two", "three", "four,five", "six"}
- argfmt := "--ss=%s"
- arg1 := fmt.Sprintf(argfmt, in[0])
- arg2 := fmt.Sprintf(argfmt, in[1])
- arg3 := fmt.Sprintf(argfmt, in[2])
- err := f.Parse([]string{arg1, arg2, arg3})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(expected) != len(ss) {
- t.Fatalf("expected number of ss to be %d but got: %d", len(expected), len(ss))
- }
- for i, v := range ss {
- if expected[i] != v {
- t.Fatalf("expected ss[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-
- values, err := f.GetStringSlice("ss")
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(expected) != len(values) {
- t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values))
- }
- for i, v := range values {
- if expected[i] != v {
- t.Fatalf("expected got ss[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-}
-
-func TestSSWithSquareBrackets(t *testing.T) {
- var ss []string
- f := setUpSSFlagSet(&ss)
-
- in := []string{`"[a-z]"`, `"[a-z]+"`}
- expected := []string{"[a-z]", "[a-z]+"}
- argfmt := "--ss=%s"
- arg1 := fmt.Sprintf(argfmt, in[0])
- arg2 := fmt.Sprintf(argfmt, in[1])
- err := f.Parse([]string{arg1, arg2})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(expected) != len(ss) {
- t.Fatalf("expected number of ss to be %d but got: %d", len(expected), len(ss))
- }
- for i, v := range ss {
- if expected[i] != v {
- t.Fatalf("expected ss[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-
- values, err := f.GetStringSlice("ss")
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(expected) != len(values) {
- t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values))
- }
- for i, v := range values {
- if expected[i] != v {
- t.Fatalf("expected got ss[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-}
diff --git a/vendor/github.com/spf13/pflag/uint.go b/vendor/github.com/spf13/pflag/uint.go
deleted file mode 100644
index dcbc2b7..0000000
--- a/vendor/github.com/spf13/pflag/uint.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- uint Value
-type uintValue uint
-
-func newUintValue(val uint, p *uint) *uintValue {
- *p = val
- return (*uintValue)(p)
-}
-
-func (i *uintValue) Set(s string) error {
- v, err := strconv.ParseUint(s, 0, 64)
- *i = uintValue(v)
- return err
-}
-
-func (i *uintValue) Type() string {
- return "uint"
-}
-
-func (i *uintValue) String() string { return strconv.FormatUint(uint64(*i), 10) }
-
-func uintConv(sval string) (interface{}, error) {
- v, err := strconv.ParseUint(sval, 0, 0)
- if err != nil {
- return 0, err
- }
- return uint(v), nil
-}
-
-// GetUint return the uint value of a flag with the given name
-func (f *FlagSet) GetUint(name string) (uint, error) {
- val, err := f.getFlagType(name, "uint", uintConv)
- if err != nil {
- return 0, err
- }
- return val.(uint), nil
-}
-
-// UintVar defines a uint flag with specified name, default value, and usage string.
-// The argument p points to a uint variable in which to store the value of the flag.
-func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) {
- f.VarP(newUintValue(value, p), name, "", usage)
-}
-
-// UintVarP is like UintVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) UintVarP(p *uint, name, shorthand string, value uint, usage string) {
- f.VarP(newUintValue(value, p), name, shorthand, usage)
-}
-
-// UintVar defines a uint flag with specified name, default value, and usage string.
-// The argument p points to a uint variable in which to store the value of the flag.
-func UintVar(p *uint, name string, value uint, usage string) {
- CommandLine.VarP(newUintValue(value, p), name, "", usage)
-}
-
-// UintVarP is like UintVar, but accepts a shorthand letter that can be used after a single dash.
-func UintVarP(p *uint, name, shorthand string, value uint, usage string) {
- CommandLine.VarP(newUintValue(value, p), name, shorthand, usage)
-}
-
-// Uint defines a uint flag with specified name, default value, and usage string.
-// The return value is the address of a uint variable that stores the value of the flag.
-func (f *FlagSet) Uint(name string, value uint, usage string) *uint {
- p := new(uint)
- f.UintVarP(p, name, "", value, usage)
- return p
-}
-
-// UintP is like Uint, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) UintP(name, shorthand string, value uint, usage string) *uint {
- p := new(uint)
- f.UintVarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Uint defines a uint flag with specified name, default value, and usage string.
-// The return value is the address of a uint variable that stores the value of the flag.
-func Uint(name string, value uint, usage string) *uint {
- return CommandLine.UintP(name, "", value, usage)
-}
-
-// UintP is like Uint, but accepts a shorthand letter that can be used after a single dash.
-func UintP(name, shorthand string, value uint, usage string) *uint {
- return CommandLine.UintP(name, shorthand, value, usage)
-}
diff --git a/vendor/github.com/spf13/pflag/uint16.go b/vendor/github.com/spf13/pflag/uint16.go
deleted file mode 100644
index 7e9914e..0000000
--- a/vendor/github.com/spf13/pflag/uint16.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- uint16 value
-type uint16Value uint16
-
-func newUint16Value(val uint16, p *uint16) *uint16Value {
- *p = val
- return (*uint16Value)(p)
-}
-
-func (i *uint16Value) Set(s string) error {
- v, err := strconv.ParseUint(s, 0, 16)
- *i = uint16Value(v)
- return err
-}
-
-func (i *uint16Value) Type() string {
- return "uint16"
-}
-
-func (i *uint16Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
-
-func uint16Conv(sval string) (interface{}, error) {
- v, err := strconv.ParseUint(sval, 0, 16)
- if err != nil {
- return 0, err
- }
- return uint16(v), nil
-}
-
-// GetUint16 return the uint16 value of a flag with the given name
-func (f *FlagSet) GetUint16(name string) (uint16, error) {
- val, err := f.getFlagType(name, "uint16", uint16Conv)
- if err != nil {
- return 0, err
- }
- return val.(uint16), nil
-}
-
-// Uint16Var defines a uint flag with specified name, default value, and usage string.
-// The argument p points to a uint variable in which to store the value of the flag.
-func (f *FlagSet) Uint16Var(p *uint16, name string, value uint16, usage string) {
- f.VarP(newUint16Value(value, p), name, "", usage)
-}
-
-// Uint16VarP is like Uint16Var, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) {
- f.VarP(newUint16Value(value, p), name, shorthand, usage)
-}
-
-// Uint16Var defines a uint flag with specified name, default value, and usage string.
-// The argument p points to a uint variable in which to store the value of the flag.
-func Uint16Var(p *uint16, name string, value uint16, usage string) {
- CommandLine.VarP(newUint16Value(value, p), name, "", usage)
-}
-
-// Uint16VarP is like Uint16Var, but accepts a shorthand letter that can be used after a single dash.
-func Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) {
- CommandLine.VarP(newUint16Value(value, p), name, shorthand, usage)
-}
-
-// Uint16 defines a uint flag with specified name, default value, and usage string.
-// The return value is the address of a uint variable that stores the value of the flag.
-func (f *FlagSet) Uint16(name string, value uint16, usage string) *uint16 {
- p := new(uint16)
- f.Uint16VarP(p, name, "", value, usage)
- return p
-}
-
-// Uint16P is like Uint16, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Uint16P(name, shorthand string, value uint16, usage string) *uint16 {
- p := new(uint16)
- f.Uint16VarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Uint16 defines a uint flag with specified name, default value, and usage string.
-// The return value is the address of a uint variable that stores the value of the flag.
-func Uint16(name string, value uint16, usage string) *uint16 {
- return CommandLine.Uint16P(name, "", value, usage)
-}
-
-// Uint16P is like Uint16, but accepts a shorthand letter that can be used after a single dash.
-func Uint16P(name, shorthand string, value uint16, usage string) *uint16 {
- return CommandLine.Uint16P(name, shorthand, value, usage)
-}
diff --git a/vendor/github.com/spf13/pflag/uint32.go b/vendor/github.com/spf13/pflag/uint32.go
deleted file mode 100644
index d802453..0000000
--- a/vendor/github.com/spf13/pflag/uint32.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- uint32 value
-type uint32Value uint32
-
-func newUint32Value(val uint32, p *uint32) *uint32Value {
- *p = val
- return (*uint32Value)(p)
-}
-
-func (i *uint32Value) Set(s string) error {
- v, err := strconv.ParseUint(s, 0, 32)
- *i = uint32Value(v)
- return err
-}
-
-func (i *uint32Value) Type() string {
- return "uint32"
-}
-
-func (i *uint32Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
-
-func uint32Conv(sval string) (interface{}, error) {
- v, err := strconv.ParseUint(sval, 0, 32)
- if err != nil {
- return 0, err
- }
- return uint32(v), nil
-}
-
-// GetUint32 return the uint32 value of a flag with the given name
-func (f *FlagSet) GetUint32(name string) (uint32, error) {
- val, err := f.getFlagType(name, "uint32", uint32Conv)
- if err != nil {
- return 0, err
- }
- return val.(uint32), nil
-}
-
-// Uint32Var defines a uint32 flag with specified name, default value, and usage string.
-// The argument p points to a uint32 variable in which to store the value of the flag.
-func (f *FlagSet) Uint32Var(p *uint32, name string, value uint32, usage string) {
- f.VarP(newUint32Value(value, p), name, "", usage)
-}
-
-// Uint32VarP is like Uint32Var, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) {
- f.VarP(newUint32Value(value, p), name, shorthand, usage)
-}
-
-// Uint32Var defines a uint32 flag with specified name, default value, and usage string.
-// The argument p points to a uint32 variable in which to store the value of the flag.
-func Uint32Var(p *uint32, name string, value uint32, usage string) {
- CommandLine.VarP(newUint32Value(value, p), name, "", usage)
-}
-
-// Uint32VarP is like Uint32Var, but accepts a shorthand letter that can be used after a single dash.
-func Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) {
- CommandLine.VarP(newUint32Value(value, p), name, shorthand, usage)
-}
-
-// Uint32 defines a uint32 flag with specified name, default value, and usage string.
-// The return value is the address of a uint32 variable that stores the value of the flag.
-func (f *FlagSet) Uint32(name string, value uint32, usage string) *uint32 {
- p := new(uint32)
- f.Uint32VarP(p, name, "", value, usage)
- return p
-}
-
-// Uint32P is like Uint32, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Uint32P(name, shorthand string, value uint32, usage string) *uint32 {
- p := new(uint32)
- f.Uint32VarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Uint32 defines a uint32 flag with specified name, default value, and usage string.
-// The return value is the address of a uint32 variable that stores the value of the flag.
-func Uint32(name string, value uint32, usage string) *uint32 {
- return CommandLine.Uint32P(name, "", value, usage)
-}
-
-// Uint32P is like Uint32, but accepts a shorthand letter that can be used after a single dash.
-func Uint32P(name, shorthand string, value uint32, usage string) *uint32 {
- return CommandLine.Uint32P(name, shorthand, value, usage)
-}
diff --git a/vendor/github.com/spf13/pflag/uint64.go b/vendor/github.com/spf13/pflag/uint64.go
deleted file mode 100644
index f62240f..0000000
--- a/vendor/github.com/spf13/pflag/uint64.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- uint64 Value
-type uint64Value uint64
-
-func newUint64Value(val uint64, p *uint64) *uint64Value {
- *p = val
- return (*uint64Value)(p)
-}
-
-func (i *uint64Value) Set(s string) error {
- v, err := strconv.ParseUint(s, 0, 64)
- *i = uint64Value(v)
- return err
-}
-
-func (i *uint64Value) Type() string {
- return "uint64"
-}
-
-func (i *uint64Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
-
-func uint64Conv(sval string) (interface{}, error) {
- v, err := strconv.ParseUint(sval, 0, 64)
- if err != nil {
- return 0, err
- }
- return uint64(v), nil
-}
-
-// GetUint64 return the uint64 value of a flag with the given name
-func (f *FlagSet) GetUint64(name string) (uint64, error) {
- val, err := f.getFlagType(name, "uint64", uint64Conv)
- if err != nil {
- return 0, err
- }
- return val.(uint64), nil
-}
-
-// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
-// The argument p points to a uint64 variable in which to store the value of the flag.
-func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) {
- f.VarP(newUint64Value(value, p), name, "", usage)
-}
-
-// Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) {
- f.VarP(newUint64Value(value, p), name, shorthand, usage)
-}
-
-// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
-// The argument p points to a uint64 variable in which to store the value of the flag.
-func Uint64Var(p *uint64, name string, value uint64, usage string) {
- CommandLine.VarP(newUint64Value(value, p), name, "", usage)
-}
-
-// Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash.
-func Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) {
- CommandLine.VarP(newUint64Value(value, p), name, shorthand, usage)
-}
-
-// Uint64 defines a uint64 flag with specified name, default value, and usage string.
-// The return value is the address of a uint64 variable that stores the value of the flag.
-func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 {
- p := new(uint64)
- f.Uint64VarP(p, name, "", value, usage)
- return p
-}
-
-// Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Uint64P(name, shorthand string, value uint64, usage string) *uint64 {
- p := new(uint64)
- f.Uint64VarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Uint64 defines a uint64 flag with specified name, default value, and usage string.
-// The return value is the address of a uint64 variable that stores the value of the flag.
-func Uint64(name string, value uint64, usage string) *uint64 {
- return CommandLine.Uint64P(name, "", value, usage)
-}
-
-// Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash.
-func Uint64P(name, shorthand string, value uint64, usage string) *uint64 {
- return CommandLine.Uint64P(name, shorthand, value, usage)
-}
diff --git a/vendor/github.com/spf13/pflag/uint8.go b/vendor/github.com/spf13/pflag/uint8.go
deleted file mode 100644
index bb0e83c..0000000
--- a/vendor/github.com/spf13/pflag/uint8.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package pflag
-
-import "strconv"
-
-// -- uint8 Value
-type uint8Value uint8
-
-func newUint8Value(val uint8, p *uint8) *uint8Value {
- *p = val
- return (*uint8Value)(p)
-}
-
-func (i *uint8Value) Set(s string) error {
- v, err := strconv.ParseUint(s, 0, 8)
- *i = uint8Value(v)
- return err
-}
-
-func (i *uint8Value) Type() string {
- return "uint8"
-}
-
-func (i *uint8Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
-
-func uint8Conv(sval string) (interface{}, error) {
- v, err := strconv.ParseUint(sval, 0, 8)
- if err != nil {
- return 0, err
- }
- return uint8(v), nil
-}
-
-// GetUint8 return the uint8 value of a flag with the given name
-func (f *FlagSet) GetUint8(name string) (uint8, error) {
- val, err := f.getFlagType(name, "uint8", uint8Conv)
- if err != nil {
- return 0, err
- }
- return val.(uint8), nil
-}
-
-// Uint8Var defines a uint8 flag with specified name, default value, and usage string.
-// The argument p points to a uint8 variable in which to store the value of the flag.
-func (f *FlagSet) Uint8Var(p *uint8, name string, value uint8, usage string) {
- f.VarP(newUint8Value(value, p), name, "", usage)
-}
-
-// Uint8VarP is like Uint8Var, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) {
- f.VarP(newUint8Value(value, p), name, shorthand, usage)
-}
-
-// Uint8Var defines a uint8 flag with specified name, default value, and usage string.
-// The argument p points to a uint8 variable in which to store the value of the flag.
-func Uint8Var(p *uint8, name string, value uint8, usage string) {
- CommandLine.VarP(newUint8Value(value, p), name, "", usage)
-}
-
-// Uint8VarP is like Uint8Var, but accepts a shorthand letter that can be used after a single dash.
-func Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) {
- CommandLine.VarP(newUint8Value(value, p), name, shorthand, usage)
-}
-
-// Uint8 defines a uint8 flag with specified name, default value, and usage string.
-// The return value is the address of a uint8 variable that stores the value of the flag.
-func (f *FlagSet) Uint8(name string, value uint8, usage string) *uint8 {
- p := new(uint8)
- f.Uint8VarP(p, name, "", value, usage)
- return p
-}
-
-// Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) Uint8P(name, shorthand string, value uint8, usage string) *uint8 {
- p := new(uint8)
- f.Uint8VarP(p, name, shorthand, value, usage)
- return p
-}
-
-// Uint8 defines a uint8 flag with specified name, default value, and usage string.
-// The return value is the address of a uint8 variable that stores the value of the flag.
-func Uint8(name string, value uint8, usage string) *uint8 {
- return CommandLine.Uint8P(name, "", value, usage)
-}
-
-// Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash.
-func Uint8P(name, shorthand string, value uint8, usage string) *uint8 {
- return CommandLine.Uint8P(name, shorthand, value, usage)
-}
diff --git a/vendor/github.com/spf13/pflag/uint_slice.go b/vendor/github.com/spf13/pflag/uint_slice.go
deleted file mode 100644
index edd94c6..0000000
--- a/vendor/github.com/spf13/pflag/uint_slice.go
+++ /dev/null
@@ -1,126 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "strconv"
- "strings"
-)
-
-// -- uintSlice Value
-type uintSliceValue struct {
- value *[]uint
- changed bool
-}
-
-func newUintSliceValue(val []uint, p *[]uint) *uintSliceValue {
- uisv := new(uintSliceValue)
- uisv.value = p
- *uisv.value = val
- return uisv
-}
-
-func (s *uintSliceValue) Set(val string) error {
- ss := strings.Split(val, ",")
- out := make([]uint, len(ss))
- for i, d := range ss {
- u, err := strconv.ParseUint(d, 10, 0)
- if err != nil {
- return err
- }
- out[i] = uint(u)
- }
- if !s.changed {
- *s.value = out
- } else {
- *s.value = append(*s.value, out...)
- }
- s.changed = true
- return nil
-}
-
-func (s *uintSliceValue) Type() string {
- return "uintSlice"
-}
-
-func (s *uintSliceValue) String() string {
- out := make([]string, len(*s.value))
- for i, d := range *s.value {
- out[i] = fmt.Sprintf("%d", d)
- }
- return "[" + strings.Join(out, ",") + "]"
-}
-
-func uintSliceConv(val string) (interface{}, error) {
- val = strings.Trim(val, "[]")
- // Empty string would cause a slice with one (empty) entry
- if len(val) == 0 {
- return []uint{}, nil
- }
- ss := strings.Split(val, ",")
- out := make([]uint, len(ss))
- for i, d := range ss {
- u, err := strconv.ParseUint(d, 10, 0)
- if err != nil {
- return nil, err
- }
- out[i] = uint(u)
- }
- return out, nil
-}
-
-// GetUintSlice returns the []uint value of a flag with the given name.
-func (f *FlagSet) GetUintSlice(name string) ([]uint, error) {
- val, err := f.getFlagType(name, "uintSlice", uintSliceConv)
- if err != nil {
- return []uint{}, err
- }
- return val.([]uint), nil
-}
-
-// UintSliceVar defines a uintSlice flag with specified name, default value, and usage string.
-// The argument p points to a []uint variable in which to store the value of the flag.
-func (f *FlagSet) UintSliceVar(p *[]uint, name string, value []uint, usage string) {
- f.VarP(newUintSliceValue(value, p), name, "", usage)
-}
-
-// UintSliceVarP is like UintSliceVar, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) UintSliceVarP(p *[]uint, name, shorthand string, value []uint, usage string) {
- f.VarP(newUintSliceValue(value, p), name, shorthand, usage)
-}
-
-// UintSliceVar defines a uint[] flag with specified name, default value, and usage string.
-// The argument p points to a uint[] variable in which to store the value of the flag.
-func UintSliceVar(p *[]uint, name string, value []uint, usage string) {
- CommandLine.VarP(newUintSliceValue(value, p), name, "", usage)
-}
-
-// UintSliceVarP is like the UintSliceVar, but accepts a shorthand letter that can be used after a single dash.
-func UintSliceVarP(p *[]uint, name, shorthand string, value []uint, usage string) {
- CommandLine.VarP(newUintSliceValue(value, p), name, shorthand, usage)
-}
-
-// UintSlice defines a []uint flag with specified name, default value, and usage string.
-// The return value is the address of a []uint variable that stores the value of the flag.
-func (f *FlagSet) UintSlice(name string, value []uint, usage string) *[]uint {
- p := []uint{}
- f.UintSliceVarP(&p, name, "", value, usage)
- return &p
-}
-
-// UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash.
-func (f *FlagSet) UintSliceP(name, shorthand string, value []uint, usage string) *[]uint {
- p := []uint{}
- f.UintSliceVarP(&p, name, shorthand, value, usage)
- return &p
-}
-
-// UintSlice defines a []uint flag with specified name, default value, and usage string.
-// The return value is the address of a []uint variable that stores the value of the flag.
-func UintSlice(name string, value []uint, usage string) *[]uint {
- return CommandLine.UintSliceP(name, "", value, usage)
-}
-
-// UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash.
-func UintSliceP(name, shorthand string, value []uint, usage string) *[]uint {
- return CommandLine.UintSliceP(name, shorthand, value, usage)
-}
diff --git a/vendor/github.com/spf13/pflag/uint_slice_test.go b/vendor/github.com/spf13/pflag/uint_slice_test.go
deleted file mode 100644
index db1a19d..0000000
--- a/vendor/github.com/spf13/pflag/uint_slice_test.go
+++ /dev/null
@@ -1,161 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "strconv"
- "strings"
- "testing"
-)
-
-func setUpUISFlagSet(uisp *[]uint) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.UintSliceVar(uisp, "uis", []uint{}, "Command separated list!")
- return f
-}
-
-func setUpUISFlagSetWithDefault(uisp *[]uint) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.UintSliceVar(uisp, "uis", []uint{0, 1}, "Command separated list!")
- return f
-}
-
-func TestEmptyUIS(t *testing.T) {
- var uis []uint
- f := setUpUISFlagSet(&uis)
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- getUIS, err := f.GetUintSlice("uis")
- if err != nil {
- t.Fatal("got an error from GetUintSlice():", err)
- }
- if len(getUIS) != 0 {
- t.Fatalf("got is %v with len=%d but expected length=0", getUIS, len(getUIS))
- }
-}
-
-func TestUIS(t *testing.T) {
- var uis []uint
- f := setUpUISFlagSet(&uis)
-
- vals := []string{"1", "2", "4", "3"}
- arg := fmt.Sprintf("--uis=%s", strings.Join(vals, ","))
- err := f.Parse([]string{arg})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range uis {
- u, err := strconv.ParseUint(vals[i], 10, 0)
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if uint(u) != v {
- t.Fatalf("expected uis[%d] to be %s but got %d", i, vals[i], v)
- }
- }
- getUIS, err := f.GetUintSlice("uis")
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- for i, v := range getUIS {
- u, err := strconv.ParseUint(vals[i], 10, 0)
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if uint(u) != v {
- t.Fatalf("expected uis[%d] to be %s but got: %d from GetUintSlice", i, vals[i], v)
- }
- }
-}
-
-func TestUISDefault(t *testing.T) {
- var uis []uint
- f := setUpUISFlagSetWithDefault(&uis)
-
- vals := []string{"0", "1"}
-
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range uis {
- u, err := strconv.ParseUint(vals[i], 10, 0)
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if uint(u) != v {
- t.Fatalf("expect uis[%d] to be %d but got: %d", i, u, v)
- }
- }
-
- getUIS, err := f.GetUintSlice("uis")
- if err != nil {
- t.Fatal("got an error from GetUintSlice():", err)
- }
- for i, v := range getUIS {
- u, err := strconv.ParseUint(vals[i], 10, 0)
- if err != nil {
- t.Fatal("got an error from GetIntSlice():", err)
- }
- if uint(u) != v {
- t.Fatalf("expected uis[%d] to be %d from GetUintSlice but got: %d", i, u, v)
- }
- }
-}
-
-func TestUISWithDefault(t *testing.T) {
- var uis []uint
- f := setUpUISFlagSetWithDefault(&uis)
-
- vals := []string{"1", "2"}
- arg := fmt.Sprintf("--uis=%s", strings.Join(vals, ","))
- err := f.Parse([]string{arg})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range uis {
- u, err := strconv.ParseUint(vals[i], 10, 0)
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if uint(u) != v {
- t.Fatalf("expected uis[%d] to be %d from GetUintSlice but got: %d", i, u, v)
- }
- }
-
- getUIS, err := f.GetUintSlice("uis")
- if err != nil {
- t.Fatal("got an error from GetUintSlice():", err)
- }
- for i, v := range getUIS {
- u, err := strconv.ParseUint(vals[i], 10, 0)
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if uint(u) != v {
- t.Fatalf("expected uis[%d] to be %d from GetUintSlice but got: %d", i, u, v)
- }
- }
-}
-
-func TestUISCalledTwice(t *testing.T) {
- var uis []uint
- f := setUpUISFlagSet(&uis)
-
- in := []string{"1,2", "3"}
- expected := []int{1, 2, 3}
- argfmt := "--uis=%s"
- arg1 := fmt.Sprintf(argfmt, in[0])
- arg2 := fmt.Sprintf(argfmt, in[1])
- err := f.Parse([]string{arg1, arg2})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range uis {
- if uint(expected[i]) != v {
- t.Fatalf("expected uis[%d] to be %d but got: %d", i, expected[i], v)
- }
- }
-}
diff --git a/vendor/github.com/spf13/viper/.gitignore b/vendor/github.com/spf13/viper/.gitignore
deleted file mode 100644
index 352a34a..0000000
--- a/vendor/github.com/spf13/viper/.gitignore
+++ /dev/null
@@ -1,24 +0,0 @@
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-*.exe
-*.test
-*.bench
\ No newline at end of file
diff --git a/vendor/github.com/spf13/viper/.travis.yml b/vendor/github.com/spf13/viper/.travis.yml
deleted file mode 100644
index f1deac3..0000000
--- a/vendor/github.com/spf13/viper/.travis.yml
+++ /dev/null
@@ -1,27 +0,0 @@
-go_import_path: github.com/spf13/viper
-
-language: go
-go:
- - 1.7.5
- - 1.8
- - tip
-
-os:
- - linux
- - osx
-
-matrix:
- allow_failures:
- - go: tip
- fast_finish: true
-
-script:
- - go install ./...
- - diff -u <(echo -n) <(gofmt -d .)
- - go test -v ./...
-
-after_success:
- - go get -u -d github.com/spf13/hugo
- - cd $GOPATH/src/github.com/spf13/hugo && make && ./hugo -s docs && cd -
-
-sudo: false
diff --git a/vendor/github.com/spf13/viper/LICENSE b/vendor/github.com/spf13/viper/LICENSE
deleted file mode 100644
index 4527efb..0000000
--- a/vendor/github.com/spf13/viper/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2014 Steve Francia
-
-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.
\ No newline at end of file
diff --git a/vendor/github.com/spf13/viper/README.md b/vendor/github.com/spf13/viper/README.md
deleted file mode 100644
index 848d92d..0000000
--- a/vendor/github.com/spf13/viper/README.md
+++ /dev/null
@@ -1,643 +0,0 @@
-
-
-Go configuration with fangs!
-
-Many Go projects are built using Viper including:
-
-* [Hugo](http://gohugo.io)
-* [EMC RexRay](http://rexray.readthedocs.org/en/stable/)
-* [Imgur’s Incus](https://github.com/Imgur/incus)
-* [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack)
-* [Docker Notary](https://github.com/docker/Notary)
-* [BloomApi](https://www.bloomapi.com/)
-* [doctl](https://github.com/digitalocean/doctl)
-* [Clairctl](https://github.com/jgsqware/clairctl)
-
-[](https://travis-ci.org/spf13/viper) [](https://gitter.im/spf13/viper?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [](https://godoc.org/github.com/spf13/viper)
-
-
-## What is Viper?
-
-Viper is a complete configuration solution for Go applications including 12-Factor apps. It is designed
-to work within an application, and can handle all types of configuration needs
-and formats. It supports:
-
-* setting defaults
-* reading from JSON, TOML, YAML, HCL, and Java properties config files
-* live watching and re-reading of config files (optional)
-* reading from environment variables
-* reading from remote config systems (etcd or Consul), and watching changes
-* reading from command line flags
-* reading from buffer
-* setting explicit values
-
-Viper can be thought of as a registry for all of your applications
-configuration needs.
-
-## Why Viper?
-
-When building a modern application, you don’t want to worry about
-configuration file formats; you want to focus on building awesome software.
-Viper is here to help with that.
-
-Viper does the following for you:
-
-1. Find, load, and unmarshal a configuration file in JSON, TOML, YAML, HCL, or Java properties formats.
-2. Provide a mechanism to set default values for your different
- configuration options.
-3. Provide a mechanism to set override values for options specified through
- command line flags.
-4. Provide an alias system to easily rename parameters without breaking existing
- code.
-5. Make it easy to tell the difference between when a user has provided a
- command line or config file which is the same as the default.
-
-Viper uses the following precedence order. Each item takes precedence over the
-item below it:
-
- * explicit call to Set
- * flag
- * env
- * config
- * key/value store
- * default
-
-Viper configuration keys are case insensitive.
-
-## Putting Values into Viper
-
-### Establishing Defaults
-
-A good configuration system will support default values. A default value is not
-required for a key, but it’s useful in the event that a key hasn’t been set via
-config file, environment variable, remote configuration or flag.
-
-Examples:
-
-```go
-viper.SetDefault("ContentDir", "content")
-viper.SetDefault("LayoutDir", "layouts")
-viper.SetDefault("Taxonomies", map[string]string{"tag": "tags", "category": "categories"})
-```
-
-### Reading Config Files
-
-Viper requires minimal configuration so it knows where to look for config files.
-Viper supports JSON, TOML, YAML, HCL, and Java Properties files. Viper can search multiple paths, but
-currently a single Viper instance only supports a single configuration file.
-Viper does not default to any configuration search paths leaving defaults decision
-to an application.
-
-Here is an example of how to use Viper to search for and read a configuration file.
-None of the specific paths are required, but at least one path should be provided
-where a configuration file is expected.
-
-```go
-viper.SetConfigName("config") // name of config file (without extension)
-viper.AddConfigPath("/etc/appname/") // path to look for the config file in
-viper.AddConfigPath("$HOME/.appname") // call multiple times to add many search paths
-viper.AddConfigPath(".") // optionally look for config in the working directory
-err := viper.ReadInConfig() // Find and read the config file
-if err != nil { // Handle errors reading the config file
- panic(fmt.Errorf("Fatal error config file: %s \n", err))
-}
-```
-
-### Watching and re-reading config files
-
-Viper supports the ability to have your application live read a config file while running.
-
-Gone are the days of needing to restart a server to have a config take effect,
-viper powered applications can read an update to a config file while running and
-not miss a beat.
-
-Simply tell the viper instance to watchConfig.
-Optionally you can provide a function for Viper to run each time a change occurs.
-
-**Make sure you add all of the configPaths prior to calling `WatchConfig()`**
-
-```go
-viper.WatchConfig()
-viper.OnConfigChange(func(e fsnotify.Event) {
- fmt.Println("Config file changed:", e.Name)
-})
-```
-
-### Reading Config from io.Reader
-
-Viper predefines many configuration sources such as files, environment
-variables, flags, and remote K/V store, but you are not bound to them. You can
-also implement your own required configuration source and feed it to viper.
-
-```go
-viper.SetConfigType("yaml") // or viper.SetConfigType("YAML")
-
-// any approach to require this configuration into your program.
-var yamlExample = []byte(`
-Hacker: true
-name: steve
-hobbies:
-- skateboarding
-- snowboarding
-- go
-clothing:
- jacket: leather
- trousers: denim
-age: 35
-eyes : brown
-beard: true
-`)
-
-viper.ReadConfig(bytes.NewBuffer(yamlExample))
-
-viper.Get("name") // this would be "steve"
-```
-
-### Setting Overrides
-
-These could be from a command line flag, or from your own application logic.
-
-```go
-viper.Set("Verbose", true)
-viper.Set("LogFile", LogFile)
-```
-
-### Registering and Using Aliases
-
-Aliases permit a single value to be referenced by multiple keys
-
-```go
-viper.RegisterAlias("loud", "Verbose")
-
-viper.Set("verbose", true) // same result as next line
-viper.Set("loud", true) // same result as prior line
-
-viper.GetBool("loud") // true
-viper.GetBool("verbose") // true
-```
-
-### Working with Environment Variables
-
-Viper has full support for environment variables. This enables 12 factor
-applications out of the box. There are four methods that exist to aid working
-with ENV:
-
- * `AutomaticEnv()`
- * `BindEnv(string...) : error`
- * `SetEnvPrefix(string)`
- * `SetEnvReplacer(string...) *strings.Replacer`
-
-_When working with ENV variables, it’s important to recognize that Viper
-treats ENV variables as case sensitive._
-
-Viper provides a mechanism to try to ensure that ENV variables are unique. By
-using `SetEnvPrefix`, you can tell Viper to use add a prefix while reading from
-the environment variables. Both `BindEnv` and `AutomaticEnv` will use this
-prefix.
-
-`BindEnv` takes one or two parameters. The first parameter is the key name, the
-second is the name of the environment variable. The name of the environment
-variable is case sensitive. If the ENV variable name is not provided, then
-Viper will automatically assume that the key name matches the ENV variable name,
-but the ENV variable is IN ALL CAPS. When you explicitly provide the ENV
-variable name, it **does not** automatically add the prefix.
-
-One important thing to recognize when working with ENV variables is that the
-value will be read each time it is accessed. Viper does not fix the value when
-the `BindEnv` is called.
-
-`AutomaticEnv` is a powerful helper especially when combined with
-`SetEnvPrefix`. When called, Viper will check for an environment variable any
-time a `viper.Get` request is made. It will apply the following rules. It will
-check for a environment variable with a name matching the key uppercased and
-prefixed with the `EnvPrefix` if set.
-
-`SetEnvReplacer` allows you to use a `strings.Replacer` object to rewrite Env
-keys to an extent. This is useful if you want to use `-` or something in your
-`Get()` calls, but want your environmental variables to use `_` delimiters. An
-example of using it can be found in `viper_test.go`.
-
-#### Env example
-
-```go
-SetEnvPrefix("spf") // will be uppercased automatically
-BindEnv("id")
-
-os.Setenv("SPF_ID", "13") // typically done outside of the app
-
-id := Get("id") // 13
-```
-
-### Working with Flags
-
-Viper has the ability to bind to flags. Specifically, Viper supports `Pflags`
-as used in the [Cobra](https://github.com/spf13/cobra) library.
-
-Like `BindEnv`, the value is not set when the binding method is called, but when
-it is accessed. This means you can bind as early as you want, even in an
-`init()` function.
-
-For individual flags, the `BindPFlag()` method provides this functionality.
-
-Example:
-
-```go
-serverCmd.Flags().Int("port", 1138, "Port to run Application server on")
-viper.BindPFlag("port", serverCmd.Flags().Lookup("port"))
-```
-
-You can also bind an existing set of pflags (pflag.FlagSet):
-
-Example:
-
-```go
-pflag.Int("flagname", 1234, "help message for flagname")
-
-pflag.Parse()
-viper.BindPFlags(pflag.CommandLine)
-
-i := viper.GetInt("flagname") // retrieve values from viper instead of pflag
-```
-
-The use of [pflag](https://github.com/spf13/pflag/) in Viper does not preclude
-the use of other packages that use the [flag](https://golang.org/pkg/flag/)
-package from the standard library. The pflag package can handle the flags
-defined for the flag package by importing these flags. This is accomplished
-by a calling a convenience function provided by the pflag package called
-AddGoFlagSet().
-
-Example:
-
-```go
-package main
-
-import (
- "flag"
- "github.com/spf13/pflag"
-)
-
-func main() {
-
- // using standard library "flag" package
- flag.Int("flagname", 1234, "help message for flagname")
-
- pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
- pflag.Parse()
- viper.BindPFlags(pflag.CommandLine)
-
- i := viper.GetInt("flagname") // retrieve value from viper
-
- ...
-}
-```
-
-#### Flag interfaces
-
-Viper provides two Go interfaces to bind other flag systems if you don’t use `Pflags`.
-
-`FlagValue` represents a single flag. This is a very simple example on how to implement this interface:
-
-```go
-type myFlag struct {}
-func (f myFlag) HasChanged() bool { return false }
-func (f myFlag) Name() string { return "my-flag-name" }
-func (f myFlag) ValueString() string { return "my-flag-value" }
-func (f myFlag) ValueType() string { return "string" }
-```
-
-Once your flag implements this interface, you can simply tell Viper to bind it:
-
-```go
-viper.BindFlagValue("my-flag-name", myFlag{})
-```
-
-`FlagValueSet` represents a group of flags. This is a very simple example on how to implement this interface:
-
-```go
-type myFlagSet struct {
- flags []myFlag
-}
-
-func (f myFlagSet) VisitAll(fn func(FlagValue)) {
- for _, flag := range flags {
- fn(flag)
- }
-}
-```
-
-Once your flag set implements this interface, you can simply tell Viper to bind it:
-
-```go
-fSet := myFlagSet{
- flags: []myFlag{myFlag{}, myFlag{}},
-}
-viper.BindFlagValues("my-flags", fSet)
-```
-
-### Remote Key/Value Store Support
-
-To enable remote support in Viper, do a blank import of the `viper/remote`
-package:
-
-`import _ "github.com/spf13/viper/remote"`
-
-Viper will read a config string (as JSON, TOML, YAML or HCL) retrieved from a path
-in a Key/Value store such as etcd or Consul. These values take precedence over
-default values, but are overridden by configuration values retrieved from disk,
-flags, or environment variables.
-
-Viper uses [crypt](https://github.com/xordataexchange/crypt) to retrieve
-configuration from the K/V store, which means that you can store your
-configuration values encrypted and have them automatically decrypted if you have
-the correct gpg keyring. Encryption is optional.
-
-You can use remote configuration in conjunction with local configuration, or
-independently of it.
-
-`crypt` has a command-line helper that you can use to put configurations in your
-K/V store. `crypt` defaults to etcd on http://127.0.0.1:4001.
-
-```bash
-$ go get github.com/xordataexchange/crypt/bin/crypt
-$ crypt set -plaintext /config/hugo.json /Users/hugo/settings/config.json
-```
-
-Confirm that your value was set:
-
-```bash
-$ crypt get -plaintext /config/hugo.json
-```
-
-See the `crypt` documentation for examples of how to set encrypted values, or
-how to use Consul.
-
-### Remote Key/Value Store Example - Unencrypted
-
-```go
-viper.AddRemoteProvider("etcd", "http://127.0.0.1:4001","/config/hugo.json")
-viper.SetConfigType("json") // because there is no file extension in a stream of bytes, supported extensions are "json", "toml", "yaml", "yml", "properties", "props", "prop"
-err := viper.ReadRemoteConfig()
-```
-
-### Remote Key/Value Store Example - Encrypted
-
-```go
-viper.AddSecureRemoteProvider("etcd","http://127.0.0.1:4001","/config/hugo.json","/etc/secrets/mykeyring.gpg")
-viper.SetConfigType("json") // because there is no file extension in a stream of bytes, supported extensions are "json", "toml", "yaml", "yml", "properties", "props", "prop"
-err := viper.ReadRemoteConfig()
-```
-
-### Watching Changes in etcd - Unencrypted
-
-```go
-// alternatively, you can create a new viper instance.
-var runtime_viper = viper.New()
-
-runtime_viper.AddRemoteProvider("etcd", "http://127.0.0.1:4001", "/config/hugo.yml")
-runtime_viper.SetConfigType("yaml") // because there is no file extension in a stream of bytes, supported extensions are "json", "toml", "yaml", "yml", "properties", "props", "prop"
-
-// read from remote config the first time.
-err := runtime_viper.ReadRemoteConfig()
-
-// unmarshal config
-runtime_viper.Unmarshal(&runtime_conf)
-
-// open a goroutine to watch remote changes forever
-go func(){
- for {
- time.Sleep(time.Second * 5) // delay after each request
-
- // currently, only tested with etcd support
- err := runtime_viper.WatchRemoteConfig()
- if err != nil {
- log.Errorf("unable to read remote config: %v", err)
- continue
- }
-
- // unmarshal new config into our runtime config struct. you can also use channel
- // to implement a signal to notify the system of the changes
- runtime_viper.Unmarshal(&runtime_conf)
- }
-}()
-```
-
-## Getting Values From Viper
-
-In Viper, there are a few ways to get a value depending on the value’s type.
-The following functions and methods exist:
-
- * `Get(key string) : interface{}`
- * `GetBool(key string) : bool`
- * `GetFloat64(key string) : float64`
- * `GetInt(key string) : int`
- * `GetString(key string) : string`
- * `GetStringMap(key string) : map[string]interface{}`
- * `GetStringMapString(key string) : map[string]string`
- * `GetStringSlice(key string) : []string`
- * `GetTime(key string) : time.Time`
- * `GetDuration(key string) : time.Duration`
- * `IsSet(key string) : bool`
-
-One important thing to recognize is that each Get function will return a zero
-value if it’s not found. To check if a given key exists, the `IsSet()` method
-has been provided.
-
-Example:
-```go
-viper.GetString("logfile") // case-insensitive Setting & Getting
-if viper.GetBool("verbose") {
- fmt.Println("verbose enabled")
-}
-```
-### Accessing nested keys
-
-The accessor methods also accept formatted paths to deeply nested keys. For
-example, if the following JSON file is loaded:
-
-```json
-{
- "host": {
- "address": "localhost",
- "port": 5799
- },
- "datastore": {
- "metric": {
- "host": "127.0.0.1",
- "port": 3099
- },
- "warehouse": {
- "host": "198.0.0.1",
- "port": 2112
- }
- }
-}
-
-```
-
-Viper can access a nested field by passing a `.` delimited path of keys:
-
-```go
-GetString("datastore.metric.host") // (returns "127.0.0.1")
-```
-
-This obeys the precedence rules established above; the search for the path
-will cascade through the remaining configuration registries until found.
-
-For example, given this configuration file, both `datastore.metric.host` and
-`datastore.metric.port` are already defined (and may be overridden). If in addition
-`datastore.metric.protocol` was defined in the defaults, Viper would also find it.
-
-However, if `datastore.metric` was overridden (by a flag, an environment variable,
-the `Set()` method, …) with an immediate value, then all sub-keys of
-`datastore.metric` become undefined, they are “shadowed” by the higher-priority
-configuration level.
-
-Lastly, if there exists a key that matches the delimited key path, its value
-will be returned instead. E.g.
-
-```json
-{
- "datastore.metric.host": "0.0.0.0",
- "host": {
- "address": "localhost",
- "port": 5799
- },
- "datastore": {
- "metric": {
- "host": "127.0.0.1",
- "port": 3099
- },
- "warehouse": {
- "host": "198.0.0.1",
- "port": 2112
- }
- }
-}
-
-GetString("datastore.metric.host") // returns "0.0.0.0"
-```
-
-### Extract sub-tree
-
-Extract sub-tree from Viper.
-
-For example, `viper` represents:
-
-```json
-app:
- cache1:
- max-items: 100
- item-size: 64
- cache2:
- max-items: 200
- item-size: 80
-```
-
-After executing:
-
-```go
-subv := viper.Sub("app.cache1")
-```
-
-`subv` represents:
-
-```json
-max-items: 100
-item-size: 64
-```
-
-Suppose we have:
-
-```go
-func NewCache(cfg *Viper) *Cache {...}
-```
-
-which creates a cache based on config information formatted as `subv`.
-Now it’s easy to create these 2 caches separately as:
-
-```go
-cfg1 := viper.Sub("app.cache1")
-cache1 := NewCache(cfg1)
-
-cfg2 := viper.Sub("app.cache2")
-cache2 := NewCache(cfg2)
-```
-
-### Unmarshaling
-
-You also have the option of Unmarshaling all or a specific value to a struct, map,
-etc.
-
-There are two methods to do this:
-
- * `Unmarshal(rawVal interface{}) : error`
- * `UnmarshalKey(key string, rawVal interface{}) : error`
-
-Example:
-
-```go
-type config struct {
- Port int
- Name string
- PathMap string `mapstructure:"path_map"`
-}
-
-var C config
-
-err := Unmarshal(&C)
-if err != nil {
- t.Fatalf("unable to decode into struct, %v", err)
-}
-```
-
-## Viper or Vipers?
-
-Viper comes ready to use out of the box. There is no configuration or
-initialization needed to begin using Viper. Since most applications will want
-to use a single central repository for their configuration, the viper package
-provides this. It is similar to a singleton.
-
-In all of the examples above, they demonstrate using viper in its singleton
-style approach.
-
-### Working with multiple vipers
-
-You can also create many different vipers for use in your application. Each will
-have its own unique set of configurations and values. Each can read from a
-different config file, key value store, etc. All of the functions that viper
-package supports are mirrored as methods on a viper.
-
-Example:
-
-```go
-x := viper.New()
-y := viper.New()
-
-x.SetDefault("ContentDir", "content")
-y.SetDefault("ContentDir", "foobar")
-
-//...
-```
-
-When working with multiple vipers, it is up to the user to keep track of the
-different vipers.
-
-## Q & A
-
-Q: Why not INI files?
-
-A: Ini files are pretty awful. There’s no standard format, and they are hard to
-validate. Viper is designed to work with JSON, TOML or YAML files. If someone
-really wants to add this feature, I’d be happy to merge it. It’s easy to specify
-which formats your application will permit.
-
-Q: Why is it called “Viper”?
-
-A: Viper is designed to be a [companion](http://en.wikipedia.org/wiki/Viper_(G.I._Joe))
-to [Cobra](https://github.com/spf13/cobra). While both can operate completely
-independently, together they make a powerful pair to handle much of your
-application foundation needs.
-
-Q: Why is it called “Cobra”?
-
-A: Is there a better name for a [commander](http://en.wikipedia.org/wiki/Cobra_Commander)?
diff --git a/vendor/github.com/spf13/viper/flags.go b/vendor/github.com/spf13/viper/flags.go
deleted file mode 100644
index dd32f4e..0000000
--- a/vendor/github.com/spf13/viper/flags.go
+++ /dev/null
@@ -1,57 +0,0 @@
-package viper
-
-import "github.com/spf13/pflag"
-
-// FlagValueSet is an interface that users can implement
-// to bind a set of flags to viper.
-type FlagValueSet interface {
- VisitAll(fn func(FlagValue))
-}
-
-// FlagValue is an interface that users can implement
-// to bind different flags to viper.
-type FlagValue interface {
- HasChanged() bool
- Name() string
- ValueString() string
- ValueType() string
-}
-
-// pflagValueSet is a wrapper around *pflag.ValueSet
-// that implements FlagValueSet.
-type pflagValueSet struct {
- flags *pflag.FlagSet
-}
-
-// VisitAll iterates over all *pflag.Flag inside the *pflag.FlagSet.
-func (p pflagValueSet) VisitAll(fn func(flag FlagValue)) {
- p.flags.VisitAll(func(flag *pflag.Flag) {
- fn(pflagValue{flag})
- })
-}
-
-// pflagValue is a wrapper aroung *pflag.flag
-// that implements FlagValue
-type pflagValue struct {
- flag *pflag.Flag
-}
-
-// HasChanges returns whether the flag has changes or not.
-func (p pflagValue) HasChanged() bool {
- return p.flag.Changed
-}
-
-// Name returns the name of the flag.
-func (p pflagValue) Name() string {
- return p.flag.Name
-}
-
-// ValueString returns the value of the flag as a string.
-func (p pflagValue) ValueString() string {
- return p.flag.Value.String()
-}
-
-// ValueType returns the type of the flag as a string.
-func (p pflagValue) ValueType() string {
- return p.flag.Value.Type()
-}
diff --git a/vendor/github.com/spf13/viper/flags_test.go b/vendor/github.com/spf13/viper/flags_test.go
deleted file mode 100644
index 0b976b6..0000000
--- a/vendor/github.com/spf13/viper/flags_test.go
+++ /dev/null
@@ -1,65 +0,0 @@
-package viper
-
-import (
- "testing"
-
- "github.com/spf13/pflag"
- "github.com/stretchr/testify/assert"
-)
-
-func TestBindFlagValueSet(t *testing.T) {
- flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
-
- var testValues = map[string]*string{
- "host": nil,
- "port": nil,
- "endpoint": nil,
- }
-
- var mutatedTestValues = map[string]string{
- "host": "localhost",
- "port": "6060",
- "endpoint": "/public",
- }
-
- for name := range testValues {
- testValues[name] = flagSet.String(name, "", "test")
- }
-
- flagValueSet := pflagValueSet{flagSet}
-
- err := BindFlagValues(flagValueSet)
- if err != nil {
- t.Fatalf("error binding flag set, %v", err)
- }
-
- flagSet.VisitAll(func(flag *pflag.Flag) {
- flag.Value.Set(mutatedTestValues[flag.Name])
- flag.Changed = true
- })
-
- for name, expected := range mutatedTestValues {
- assert.Equal(t, Get(name), expected)
- }
-}
-
-func TestBindFlagValue(t *testing.T) {
- var testString = "testing"
- var testValue = newStringValue(testString, &testString)
-
- flag := &pflag.Flag{
- Name: "testflag",
- Value: testValue,
- Changed: false,
- }
-
- flagValue := pflagValue{flag}
- BindFlagValue("testvalue", flagValue)
-
- assert.Equal(t, testString, Get("testvalue"))
-
- flag.Value.Set("testing_mutate")
- flag.Changed = true //hack for pflag usage
-
- assert.Equal(t, "testing_mutate", Get("testvalue"))
-}
diff --git a/vendor/github.com/spf13/viper/overrides_test.go b/vendor/github.com/spf13/viper/overrides_test.go
deleted file mode 100644
index dd2aa9b..0000000
--- a/vendor/github.com/spf13/viper/overrides_test.go
+++ /dev/null
@@ -1,173 +0,0 @@
-package viper
-
-import (
- "fmt"
- "strings"
- "testing"
-
- "github.com/spf13/cast"
- "github.com/stretchr/testify/assert"
-)
-
-type layer int
-
-const (
- defaultLayer layer = iota + 1
- overrideLayer
-)
-
-func TestNestedOverrides(t *testing.T) {
- assert := assert.New(t)
- var v *Viper
-
- // Case 0: value overridden by a value
- overrideDefault(assert, "tom", 10, "tom", 20) // "tom" is first given 10 as default value, then overridden by 20
- override(assert, "tom", 10, "tom", 20) // "tom" is first given value 10, then overridden by 20
- overrideDefault(assert, "tom.age", 10, "tom.age", 20)
- override(assert, "tom.age", 10, "tom.age", 20)
- overrideDefault(assert, "sawyer.tom.age", 10, "sawyer.tom.age", 20)
- override(assert, "sawyer.tom.age", 10, "sawyer.tom.age", 20)
-
- // Case 1: key:value overridden by a value
- v = overrideDefault(assert, "tom.age", 10, "tom", "boy") // "tom.age" is first given 10 as default value, then "tom" is overridden by "boy"
- assert.Nil(v.Get("tom.age")) // "tom.age" should not exist anymore
- v = override(assert, "tom.age", 10, "tom", "boy")
- assert.Nil(v.Get("tom.age"))
-
- // Case 2: value overridden by a key:value
- overrideDefault(assert, "tom", "boy", "tom.age", 10) // "tom" is first given "boy" as default value, then "tom" is overridden by map{"age":10}
- override(assert, "tom.age", 10, "tom", "boy")
-
- // Case 3: key:value overridden by a key:value
- v = overrideDefault(assert, "tom.size", 4, "tom.age", 10)
- assert.Equal(4, v.Get("tom.size")) // value should still be reachable
- v = override(assert, "tom.size", 4, "tom.age", 10)
- assert.Equal(4, v.Get("tom.size"))
- deepCheckValue(assert, v, overrideLayer, []string{"tom", "size"}, 4)
-
- // Case 4: key:value overridden by a map
- v = overrideDefault(assert, "tom.size", 4, "tom", map[string]interface{}{"age": 10}) // "tom.size" is first given "4" as default value, then "tom" is overridden by map{"age":10}
- assert.Equal(4, v.Get("tom.size")) // "tom.size" should still be reachable
- assert.Equal(10, v.Get("tom.age")) // new value should be there
- deepCheckValue(assert, v, overrideLayer, []string{"tom", "age"}, 10) // new value should be there
- v = override(assert, "tom.size", 4, "tom", map[string]interface{}{"age": 10})
- assert.Nil(v.Get("tom.size"))
- assert.Equal(10, v.Get("tom.age"))
- deepCheckValue(assert, v, overrideLayer, []string{"tom", "age"}, 10)
-
- // Case 5: array overridden by a value
- overrideDefault(assert, "tom", []int{10, 20}, "tom", 30)
- override(assert, "tom", []int{10, 20}, "tom", 30)
- overrideDefault(assert, "tom.age", []int{10, 20}, "tom.age", 30)
- override(assert, "tom.age", []int{10, 20}, "tom.age", 30)
-
- // Case 6: array overridden by an array
- overrideDefault(assert, "tom", []int{10, 20}, "tom", []int{30, 40})
- override(assert, "tom", []int{10, 20}, "tom", []int{30, 40})
- overrideDefault(assert, "tom.age", []int{10, 20}, "tom.age", []int{30, 40})
- v = override(assert, "tom.age", []int{10, 20}, "tom.age", []int{30, 40})
- // explicit array merge:
- s, ok := v.Get("tom.age").([]int)
- if assert.True(ok, "tom[\"age\"] is not a slice") {
- v.Set("tom.age", append(s, []int{50, 60}...))
- assert.Equal([]int{30, 40, 50, 60}, v.Get("tom.age"))
- deepCheckValue(assert, v, overrideLayer, []string{"tom", "age"}, []int{30, 40, 50, 60})
- }
-}
-
-func overrideDefault(assert *assert.Assertions, firstPath string, firstValue interface{}, secondPath string, secondValue interface{}) *Viper {
- return overrideFromLayer(defaultLayer, assert, firstPath, firstValue, secondPath, secondValue)
-}
-func override(assert *assert.Assertions, firstPath string, firstValue interface{}, secondPath string, secondValue interface{}) *Viper {
- return overrideFromLayer(overrideLayer, assert, firstPath, firstValue, secondPath, secondValue)
-}
-
-// overrideFromLayer performs the sequential override and low-level checks.
-//
-// First assignment is made on layer l for path firstPath with value firstValue,
-// the second one on the override layer (i.e., with the Set() function)
-// for path secondPath with value secondValue.
-//
-// firstPath and secondPath can include an arbitrary number of dots to indicate
-// a nested element.
-//
-// After each assignment, the value is checked, retrieved both by its full path
-// and by its key sequence (successive maps).
-func overrideFromLayer(l layer, assert *assert.Assertions, firstPath string, firstValue interface{}, secondPath string, secondValue interface{}) *Viper {
- v := New()
- firstKeys := strings.Split(firstPath, v.keyDelim)
- if assert == nil ||
- len(firstKeys) == 0 || len(firstKeys[0]) == 0 {
- return v
- }
-
- // Set and check first value
- switch l {
- case defaultLayer:
- v.SetDefault(firstPath, firstValue)
- case overrideLayer:
- v.Set(firstPath, firstValue)
- default:
- return v
- }
- assert.Equal(firstValue, v.Get(firstPath))
- deepCheckValue(assert, v, l, firstKeys, firstValue)
-
- // Override and check new value
- secondKeys := strings.Split(secondPath, v.keyDelim)
- if len(secondKeys) == 0 || len(secondKeys[0]) == 0 {
- return v
- }
- v.Set(secondPath, secondValue)
- assert.Equal(secondValue, v.Get(secondPath))
- deepCheckValue(assert, v, overrideLayer, secondKeys, secondValue)
-
- return v
-}
-
-// deepCheckValue checks that all given keys correspond to a valid path in the
-// configuration map of the given layer, and that the final value equals the one given
-func deepCheckValue(assert *assert.Assertions, v *Viper, l layer, keys []string, value interface{}) {
- if assert == nil || v == nil ||
- len(keys) == 0 || len(keys[0]) == 0 {
- return
- }
-
- // init
- var val interface{}
- var ms string
- switch l {
- case defaultLayer:
- val = v.defaults
- ms = "v.defaults"
- case overrideLayer:
- val = v.override
- ms = "v.override"
- }
-
- // loop through map
- var m map[string]interface{}
- err := false
- for _, k := range keys {
- if val == nil {
- assert.Fail(fmt.Sprintf("%s is not a map[string]interface{}", ms))
- return
- }
-
- // deep scan of the map to get the final value
- switch val.(type) {
- case map[interface{}]interface{}:
- m = cast.ToStringMap(val)
- case map[string]interface{}:
- m = val.(map[string]interface{})
- default:
- assert.Fail(fmt.Sprintf("%s is not a map[string]interface{}", ms))
- return
- }
- ms = ms + "[\"" + k + "\"]"
- val = m[k]
- }
- if !err {
- assert.Equal(value, val)
- }
-}
diff --git a/vendor/github.com/spf13/viper/util.go b/vendor/github.com/spf13/viper/util.go
deleted file mode 100644
index 3ebada9..0000000
--- a/vendor/github.com/spf13/viper/util.go
+++ /dev/null
@@ -1,282 +0,0 @@
-// Copyright © 2014 Steve Francia .
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-// Viper is a application configuration system.
-// It believes that applications can be configured a variety of ways
-// via flags, ENVIRONMENT variables, configuration files retrieved
-// from the file system, or a remote key/value store.
-
-package viper
-
-import (
- "bytes"
- "encoding/json"
- "fmt"
- "io"
- "os"
- "path/filepath"
- "runtime"
- "strings"
- "unicode"
-
- "github.com/hashicorp/hcl"
- "github.com/magiconair/properties"
- toml "github.com/pelletier/go-toml"
- "github.com/spf13/cast"
- jww "github.com/spf13/jwalterweatherman"
- "gopkg.in/yaml.v2"
-)
-
-// ConfigParseError denotes failing to parse configuration file.
-type ConfigParseError struct {
- err error
-}
-
-// Error returns the formatted configuration error.
-func (pe ConfigParseError) Error() string {
- return fmt.Sprintf("While parsing config: %s", pe.err.Error())
-}
-
-// toCaseInsensitiveValue checks if the value is a map;
-// if so, create a copy and lower-case the keys recursively.
-func toCaseInsensitiveValue(value interface{}) interface{} {
- switch v := value.(type) {
- case map[interface{}]interface{}:
- value = copyAndInsensitiviseMap(cast.ToStringMap(v))
- case map[string]interface{}:
- value = copyAndInsensitiviseMap(v)
- }
-
- return value
-}
-
-// copyAndInsensitiviseMap behaves like insensitiviseMap, but creates a copy of
-// any map it makes case insensitive.
-func copyAndInsensitiviseMap(m map[string]interface{}) map[string]interface{} {
- nm := make(map[string]interface{})
-
- for key, val := range m {
- lkey := strings.ToLower(key)
- switch v := val.(type) {
- case map[interface{}]interface{}:
- nm[lkey] = copyAndInsensitiviseMap(cast.ToStringMap(v))
- case map[string]interface{}:
- nm[lkey] = copyAndInsensitiviseMap(v)
- default:
- nm[lkey] = v
- }
- }
-
- return nm
-}
-
-func insensitiviseMap(m map[string]interface{}) {
- for key, val := range m {
- switch val.(type) {
- case map[interface{}]interface{}:
- // nested map: cast and recursively insensitivise
- val = cast.ToStringMap(val)
- insensitiviseMap(val.(map[string]interface{}))
- case map[string]interface{}:
- // nested map: recursively insensitivise
- insensitiviseMap(val.(map[string]interface{}))
- }
-
- lower := strings.ToLower(key)
- if key != lower {
- // remove old key (not lower-cased)
- delete(m, key)
- }
- // update map
- m[lower] = val
- }
-}
-
-func absPathify(inPath string) string {
- jww.INFO.Println("Trying to resolve absolute path to", inPath)
-
- if strings.HasPrefix(inPath, "$HOME") {
- inPath = userHomeDir() + inPath[5:]
- }
-
- if strings.HasPrefix(inPath, "$") {
- end := strings.Index(inPath, string(os.PathSeparator))
- inPath = os.Getenv(inPath[1:end]) + inPath[end:]
- }
-
- if filepath.IsAbs(inPath) {
- return filepath.Clean(inPath)
- }
-
- p, err := filepath.Abs(inPath)
- if err == nil {
- return filepath.Clean(p)
- }
-
- jww.ERROR.Println("Couldn't discover absolute path")
- jww.ERROR.Println(err)
- return ""
-}
-
-// Check if File / Directory Exists
-func exists(path string) (bool, error) {
- _, err := v.fs.Stat(path)
- if err == nil {
- return true, nil
- }
- if os.IsNotExist(err) {
- return false, nil
- }
- return false, err
-}
-
-func stringInSlice(a string, list []string) bool {
- for _, b := range list {
- if b == a {
- return true
- }
- }
- return false
-}
-
-func userHomeDir() string {
- if runtime.GOOS == "windows" {
- home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
- if home == "" {
- home = os.Getenv("USERPROFILE")
- }
- return home
- }
- return os.Getenv("HOME")
-}
-
-func unmarshallConfigReader(in io.Reader, c map[string]interface{}, configType string) error {
- buf := new(bytes.Buffer)
- buf.ReadFrom(in)
-
- switch strings.ToLower(configType) {
- case "yaml", "yml":
- if err := yaml.Unmarshal(buf.Bytes(), &c); err != nil {
- return ConfigParseError{err}
- }
-
- case "json":
- if err := json.Unmarshal(buf.Bytes(), &c); err != nil {
- return ConfigParseError{err}
- }
-
- case "hcl":
- obj, err := hcl.Parse(string(buf.Bytes()))
- if err != nil {
- return ConfigParseError{err}
- }
- if err = hcl.DecodeObject(&c, obj); err != nil {
- return ConfigParseError{err}
- }
-
- case "toml":
- tree, err := toml.LoadReader(buf)
- if err != nil {
- return ConfigParseError{err}
- }
- tmap := tree.ToMap()
- for k, v := range tmap {
- c[k] = v
- }
-
- case "properties", "props", "prop":
- var p *properties.Properties
- var err error
- if p, err = properties.Load(buf.Bytes(), properties.UTF8); err != nil {
- return ConfigParseError{err}
- }
- for _, key := range p.Keys() {
- value, _ := p.Get(key)
- // recursively build nested maps
- path := strings.Split(key, ".")
- lastKey := strings.ToLower(path[len(path)-1])
- deepestMap := deepSearch(c, path[0:len(path)-1])
- // set innermost value
- deepestMap[lastKey] = value
- }
- }
-
- insensitiviseMap(c)
- return nil
-}
-
-func safeMul(a, b uint) uint {
- c := a * b
- if a > 1 && b > 1 && c/b != a {
- return 0
- }
- return c
-}
-
-// parseSizeInBytes converts strings like 1GB or 12 mb into an unsigned integer number of bytes
-func parseSizeInBytes(sizeStr string) uint {
- sizeStr = strings.TrimSpace(sizeStr)
- lastChar := len(sizeStr) - 1
- multiplier := uint(1)
-
- if lastChar > 0 {
- if sizeStr[lastChar] == 'b' || sizeStr[lastChar] == 'B' {
- if lastChar > 1 {
- switch unicode.ToLower(rune(sizeStr[lastChar-1])) {
- case 'k':
- multiplier = 1 << 10
- sizeStr = strings.TrimSpace(sizeStr[:lastChar-1])
- case 'm':
- multiplier = 1 << 20
- sizeStr = strings.TrimSpace(sizeStr[:lastChar-1])
- case 'g':
- multiplier = 1 << 30
- sizeStr = strings.TrimSpace(sizeStr[:lastChar-1])
- default:
- multiplier = 1
- sizeStr = strings.TrimSpace(sizeStr[:lastChar])
- }
- }
- }
- }
-
- size := cast.ToInt(sizeStr)
- if size < 0 {
- size = 0
- }
-
- return safeMul(uint(size), multiplier)
-}
-
-// deepSearch scans deep maps, following the key indexes listed in the
-// sequence "path".
-// The last value is expected to be another map, and is returned.
-//
-// In case intermediate keys do not exist, or map to a non-map value,
-// a new map is created and inserted, and the search continues from there:
-// the initial map "m" may be modified!
-func deepSearch(m map[string]interface{}, path []string) map[string]interface{} {
- for _, k := range path {
- m2, ok := m[k]
- if !ok {
- // intermediate key does not exist
- // => create it and continue from there
- m3 := make(map[string]interface{})
- m[k] = m3
- m = m3
- continue
- }
- m3, ok := m2.(map[string]interface{})
- if !ok {
- // intermediate key is a value
- // => replace with a new map
- m3 = make(map[string]interface{})
- m[k] = m3
- }
- // continue search from here
- m = m3
- }
- return m
-}
diff --git a/vendor/github.com/spf13/viper/util_test.go b/vendor/github.com/spf13/viper/util_test.go
deleted file mode 100644
index 0af80bb..0000000
--- a/vendor/github.com/spf13/viper/util_test.go
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright © 2016 Steve Francia .
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-// Viper is a application configuration system.
-// It believes that applications can be configured a variety of ways
-// via flags, ENVIRONMENT variables, configuration files retrieved
-// from the file system, or a remote key/value store.
-
-package viper
-
-import (
- "reflect"
- "testing"
-)
-
-func TestCopyAndInsensitiviseMap(t *testing.T) {
- var (
- given = map[string]interface{}{
- "Foo": 32,
- "Bar": map[interface{}]interface {
- }{
- "ABc": "A",
- "cDE": "B"},
- }
- expected = map[string]interface{}{
- "foo": 32,
- "bar": map[string]interface {
- }{
- "abc": "A",
- "cde": "B"},
- }
- )
-
- got := copyAndInsensitiviseMap(given)
-
- if !reflect.DeepEqual(got, expected) {
- t.Fatalf("Got %q\nexpected\n%q", got, expected)
- }
-
- if _, ok := given["foo"]; ok {
- t.Fatal("Input map changed")
- }
-
- if _, ok := given["bar"]; ok {
- t.Fatal("Input map changed")
- }
-
- m := given["Bar"].(map[interface{}]interface{})
- if _, ok := m["ABc"]; !ok {
- t.Fatal("Input map changed")
- }
-}
diff --git a/vendor/github.com/spf13/viper/viper.go b/vendor/github.com/spf13/viper/viper.go
deleted file mode 100644
index 2a221e5..0000000
--- a/vendor/github.com/spf13/viper/viper.go
+++ /dev/null
@@ -1,1571 +0,0 @@
-// Copyright © 2014 Steve Francia .
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-// Viper is a application configuration system.
-// It believes that applications can be configured a variety of ways
-// via flags, ENVIRONMENT variables, configuration files retrieved
-// from the file system, or a remote key/value store.
-
-// Each item takes precedence over the item below it:
-
-// overrides
-// flag
-// env
-// config
-// key/value store
-// default
-
-package viper
-
-import (
- "bytes"
- "encoding/csv"
- "fmt"
- "io"
- "log"
- "os"
- "path/filepath"
- "reflect"
- "strings"
- "time"
-
- "github.com/fsnotify/fsnotify"
- "github.com/mitchellh/mapstructure"
- "github.com/spf13/afero"
- "github.com/spf13/cast"
- jww "github.com/spf13/jwalterweatherman"
- "github.com/spf13/pflag"
-)
-
-var v *Viper
-
-type RemoteResponse struct {
- Value []byte
- Error error
-}
-
-func init() {
- v = New()
-}
-
-type remoteConfigFactory interface {
- Get(rp RemoteProvider) (io.Reader, error)
- Watch(rp RemoteProvider) (io.Reader, error)
- WatchChannel(rp RemoteProvider) (<-chan *RemoteResponse, chan bool)
-}
-
-// RemoteConfig is optional, see the remote package
-var RemoteConfig remoteConfigFactory
-
-// UnsupportedConfigError denotes encountering an unsupported
-// configuration filetype.
-type UnsupportedConfigError string
-
-// Error returns the formatted configuration error.
-func (str UnsupportedConfigError) Error() string {
- return fmt.Sprintf("Unsupported Config Type %q", string(str))
-}
-
-// UnsupportedRemoteProviderError denotes encountering an unsupported remote
-// provider. Currently only etcd and Consul are supported.
-type UnsupportedRemoteProviderError string
-
-// Error returns the formatted remote provider error.
-func (str UnsupportedRemoteProviderError) Error() string {
- return fmt.Sprintf("Unsupported Remote Provider Type %q", string(str))
-}
-
-// RemoteConfigError denotes encountering an error while trying to
-// pull the configuration from the remote provider.
-type RemoteConfigError string
-
-// Error returns the formatted remote provider error
-func (rce RemoteConfigError) Error() string {
- return fmt.Sprintf("Remote Configurations Error: %s", string(rce))
-}
-
-// ConfigFileNotFoundError denotes failing to find configuration file.
-type ConfigFileNotFoundError struct {
- name, locations string
-}
-
-// Error returns the formatted configuration error.
-func (fnfe ConfigFileNotFoundError) Error() string {
- return fmt.Sprintf("Config File %q Not Found in %q", fnfe.name, fnfe.locations)
-}
-
-// Viper is a prioritized configuration registry. It
-// maintains a set of configuration sources, fetches
-// values to populate those, and provides them according
-// to the source's priority.
-// The priority of the sources is the following:
-// 1. overrides
-// 2. flags
-// 3. env. variables
-// 4. config file
-// 5. key/value store
-// 6. defaults
-//
-// For example, if values from the following sources were loaded:
-//
-// Defaults : {
-// "secret": "",
-// "user": "default",
-// "endpoint": "https://localhost"
-// }
-// Config : {
-// "user": "root"
-// "secret": "defaultsecret"
-// }
-// Env : {
-// "secret": "somesecretkey"
-// }
-//
-// The resulting config will have the following values:
-//
-// {
-// "secret": "somesecretkey",
-// "user": "root",
-// "endpoint": "https://localhost"
-// }
-type Viper struct {
- // Delimiter that separates a list of keys
- // used to access a nested value in one go
- keyDelim string
-
- // A set of paths to look for the config file in
- configPaths []string
-
- // The filesystem to read config from.
- fs afero.Fs
-
- // A set of remote providers to search for the configuration
- remoteProviders []*defaultRemoteProvider
-
- // Name of file to look for inside the path
- configName string
- configFile string
- configType string
- envPrefix string
-
- automaticEnvApplied bool
- envKeyReplacer *strings.Replacer
-
- config map[string]interface{}
- override map[string]interface{}
- defaults map[string]interface{}
- kvstore map[string]interface{}
- pflags map[string]FlagValue
- env map[string]string
- aliases map[string]string
- typeByDefValue bool
-
- onConfigChange func(fsnotify.Event)
-}
-
-// New returns an initialized Viper instance.
-func New() *Viper {
- v := new(Viper)
- v.keyDelim = "."
- v.configName = "config"
- v.fs = afero.NewOsFs()
- v.config = make(map[string]interface{})
- v.override = make(map[string]interface{})
- v.defaults = make(map[string]interface{})
- v.kvstore = make(map[string]interface{})
- v.pflags = make(map[string]FlagValue)
- v.env = make(map[string]string)
- v.aliases = make(map[string]string)
- v.typeByDefValue = false
-
- return v
-}
-
-// Intended for testing, will reset all to default settings.
-// In the public interface for the viper package so applications
-// can use it in their testing as well.
-func Reset() {
- v = New()
- SupportedExts = []string{"json", "toml", "yaml", "yml", "hcl"}
- SupportedRemoteProviders = []string{"etcd", "consul"}
-}
-
-type defaultRemoteProvider struct {
- provider string
- endpoint string
- path string
- secretKeyring string
-}
-
-func (rp defaultRemoteProvider) Provider() string {
- return rp.provider
-}
-
-func (rp defaultRemoteProvider) Endpoint() string {
- return rp.endpoint
-}
-
-func (rp defaultRemoteProvider) Path() string {
- return rp.path
-}
-
-func (rp defaultRemoteProvider) SecretKeyring() string {
- return rp.secretKeyring
-}
-
-// RemoteProvider stores the configuration necessary
-// to connect to a remote key/value store.
-// Optional secretKeyring to unencrypt encrypted values
-// can be provided.
-type RemoteProvider interface {
- Provider() string
- Endpoint() string
- Path() string
- SecretKeyring() string
-}
-
-// SupportedExts are universally supported extensions.
-var SupportedExts = []string{"json", "toml", "yaml", "yml", "properties", "props", "prop", "hcl"}
-
-// SupportedRemoteProviders are universally supported remote providers.
-var SupportedRemoteProviders = []string{"etcd", "consul"}
-
-func OnConfigChange(run func(in fsnotify.Event)) { v.OnConfigChange(run) }
-func (v *Viper) OnConfigChange(run func(in fsnotify.Event)) {
- v.onConfigChange = run
-}
-
-func WatchConfig() { v.WatchConfig() }
-func (v *Viper) WatchConfig() {
- go func() {
- watcher, err := fsnotify.NewWatcher()
- if err != nil {
- log.Fatal(err)
- }
- defer watcher.Close()
-
- // we have to watch the entire directory to pick up renames/atomic saves in a cross-platform way
- filename, err := v.getConfigFile()
- if err != nil {
- log.Println("error:", err)
- return
- }
-
- configFile := filepath.Clean(filename)
- configDir, _ := filepath.Split(configFile)
-
- done := make(chan bool)
- go func() {
- for {
- select {
- case event := <-watcher.Events:
- // we only care about the config file
- if filepath.Clean(event.Name) == configFile {
- if event.Op&fsnotify.Write == fsnotify.Write || event.Op&fsnotify.Create == fsnotify.Create {
- err := v.ReadInConfig()
- if err != nil {
- log.Println("error:", err)
- }
- v.onConfigChange(event)
- }
- }
- case err := <-watcher.Errors:
- log.Println("error:", err)
- }
- }
- }()
-
- watcher.Add(configDir)
- <-done
- }()
-}
-
-// SetConfigFile explicitly defines the path, name and extension of the config file.
-// Viper will use this and not check any of the config paths.
-func SetConfigFile(in string) { v.SetConfigFile(in) }
-func (v *Viper) SetConfigFile(in string) {
- if in != "" {
- v.configFile = in
- }
-}
-
-// SetEnvPrefix defines a prefix that ENVIRONMENT variables will use.
-// E.g. if your prefix is "spf", the env registry will look for env
-// variables that start with "SPF_".
-func SetEnvPrefix(in string) { v.SetEnvPrefix(in) }
-func (v *Viper) SetEnvPrefix(in string) {
- if in != "" {
- v.envPrefix = in
- }
-}
-
-func (v *Viper) mergeWithEnvPrefix(in string) string {
- if v.envPrefix != "" {
- return strings.ToUpper(v.envPrefix + "_" + in)
- }
-
- return strings.ToUpper(in)
-}
-
-// TODO: should getEnv logic be moved into find(). Can generalize the use of
-// rewriting keys many things, Ex: Get('someKey') -> some_key
-// (camel case to snake case for JSON keys perhaps)
-
-// getEnv is a wrapper around os.Getenv which replaces characters in the original
-// key. This allows env vars which have different keys than the config object
-// keys.
-func (v *Viper) getEnv(key string) string {
- if v.envKeyReplacer != nil {
- key = v.envKeyReplacer.Replace(key)
- }
- return os.Getenv(key)
-}
-
-// ConfigFileUsed returns the file used to populate the config registry.
-func ConfigFileUsed() string { return v.ConfigFileUsed() }
-func (v *Viper) ConfigFileUsed() string { return v.configFile }
-
-// AddConfigPath adds a path for Viper to search for the config file in.
-// Can be called multiple times to define multiple search paths.
-func AddConfigPath(in string) { v.AddConfigPath(in) }
-func (v *Viper) AddConfigPath(in string) {
- if in != "" {
- absin := absPathify(in)
- jww.INFO.Println("adding", absin, "to paths to search")
- if !stringInSlice(absin, v.configPaths) {
- v.configPaths = append(v.configPaths, absin)
- }
- }
-}
-
-// AddRemoteProvider adds a remote configuration source.
-// Remote Providers are searched in the order they are added.
-// provider is a string value, "etcd" or "consul" are currently supported.
-// endpoint is the url. etcd requires http://ip:port consul requires ip:port
-// path is the path in the k/v store to retrieve configuration
-// To retrieve a config file called myapp.json from /configs/myapp.json
-// you should set path to /configs and set config name (SetConfigName()) to
-// "myapp"
-func AddRemoteProvider(provider, endpoint, path string) error {
- return v.AddRemoteProvider(provider, endpoint, path)
-}
-func (v *Viper) AddRemoteProvider(provider, endpoint, path string) error {
- if !stringInSlice(provider, SupportedRemoteProviders) {
- return UnsupportedRemoteProviderError(provider)
- }
- if provider != "" && endpoint != "" {
- jww.INFO.Printf("adding %s:%s to remote provider list", provider, endpoint)
- rp := &defaultRemoteProvider{
- endpoint: endpoint,
- provider: provider,
- path: path,
- }
- if !v.providerPathExists(rp) {
- v.remoteProviders = append(v.remoteProviders, rp)
- }
- }
- return nil
-}
-
-// AddSecureRemoteProvider adds a remote configuration source.
-// Secure Remote Providers are searched in the order they are added.
-// provider is a string value, "etcd" or "consul" are currently supported.
-// endpoint is the url. etcd requires http://ip:port consul requires ip:port
-// secretkeyring is the filepath to your openpgp secret keyring. e.g. /etc/secrets/myring.gpg
-// path is the path in the k/v store to retrieve configuration
-// To retrieve a config file called myapp.json from /configs/myapp.json
-// you should set path to /configs and set config name (SetConfigName()) to
-// "myapp"
-// Secure Remote Providers are implemented with github.com/xordataexchange/crypt
-func AddSecureRemoteProvider(provider, endpoint, path, secretkeyring string) error {
- return v.AddSecureRemoteProvider(provider, endpoint, path, secretkeyring)
-}
-
-func (v *Viper) AddSecureRemoteProvider(provider, endpoint, path, secretkeyring string) error {
- if !stringInSlice(provider, SupportedRemoteProviders) {
- return UnsupportedRemoteProviderError(provider)
- }
- if provider != "" && endpoint != "" {
- jww.INFO.Printf("adding %s:%s to remote provider list", provider, endpoint)
- rp := &defaultRemoteProvider{
- endpoint: endpoint,
- provider: provider,
- path: path,
- secretKeyring: secretkeyring,
- }
- if !v.providerPathExists(rp) {
- v.remoteProviders = append(v.remoteProviders, rp)
- }
- }
- return nil
-}
-
-func (v *Viper) providerPathExists(p *defaultRemoteProvider) bool {
- for _, y := range v.remoteProviders {
- if reflect.DeepEqual(y, p) {
- return true
- }
- }
- return false
-}
-
-// searchMap recursively searches for a value for path in source map.
-// Returns nil if not found.
-// Note: This assumes that the path entries and map keys are lower cased.
-func (v *Viper) searchMap(source map[string]interface{}, path []string) interface{} {
- if len(path) == 0 {
- return source
- }
-
- next, ok := source[path[0]]
- if ok {
- // Fast path
- if len(path) == 1 {
- return next
- }
-
- // Nested case
- switch next.(type) {
- case map[interface{}]interface{}:
- return v.searchMap(cast.ToStringMap(next), path[1:])
- case map[string]interface{}:
- // Type assertion is safe here since it is only reached
- // if the type of `next` is the same as the type being asserted
- return v.searchMap(next.(map[string]interface{}), path[1:])
- default:
- // got a value but nested key expected, return "nil" for not found
- return nil
- }
- }
- return nil
-}
-
-// searchMapWithPathPrefixes recursively searches for a value for path in source map.
-//
-// While searchMap() considers each path element as a single map key, this
-// function searches for, and prioritizes, merged path elements.
-// e.g., if in the source, "foo" is defined with a sub-key "bar", and "foo.bar"
-// is also defined, this latter value is returned for path ["foo", "bar"].
-//
-// This should be useful only at config level (other maps may not contain dots
-// in their keys).
-//
-// Note: This assumes that the path entries and map keys are lower cased.
-func (v *Viper) searchMapWithPathPrefixes(source map[string]interface{}, path []string) interface{} {
- if len(path) == 0 {
- return source
- }
-
- // search for path prefixes, starting from the longest one
- for i := len(path); i > 0; i-- {
- prefixKey := strings.ToLower(strings.Join(path[0:i], v.keyDelim))
-
- next, ok := source[prefixKey]
- if ok {
- // Fast path
- if i == len(path) {
- return next
- }
-
- // Nested case
- var val interface{}
- switch next.(type) {
- case map[interface{}]interface{}:
- val = v.searchMapWithPathPrefixes(cast.ToStringMap(next), path[i:])
- case map[string]interface{}:
- // Type assertion is safe here since it is only reached
- // if the type of `next` is the same as the type being asserted
- val = v.searchMapWithPathPrefixes(next.(map[string]interface{}), path[i:])
- default:
- // got a value but nested key expected, do nothing and look for next prefix
- }
- if val != nil {
- return val
- }
- }
- }
-
- // not found
- return nil
-}
-
-// isPathShadowedInDeepMap makes sure the given path is not shadowed somewhere
-// on its path in the map.
-// e.g., if "foo.bar" has a value in the given map, it “shadows”
-// "foo.bar.baz" in a lower-priority map
-func (v *Viper) isPathShadowedInDeepMap(path []string, m map[string]interface{}) string {
- var parentVal interface{}
- for i := 1; i < len(path); i++ {
- parentVal = v.searchMap(m, path[0:i])
- if parentVal == nil {
- // not found, no need to add more path elements
- return ""
- }
- switch parentVal.(type) {
- case map[interface{}]interface{}:
- continue
- case map[string]interface{}:
- continue
- default:
- // parentVal is a regular value which shadows "path"
- return strings.Join(path[0:i], v.keyDelim)
- }
- }
- return ""
-}
-
-// isPathShadowedInFlatMap makes sure the given path is not shadowed somewhere
-// in a sub-path of the map.
-// e.g., if "foo.bar" has a value in the given map, it “shadows”
-// "foo.bar.baz" in a lower-priority map
-func (v *Viper) isPathShadowedInFlatMap(path []string, mi interface{}) string {
- // unify input map
- var m map[string]interface{}
- switch mi.(type) {
- case map[string]string, map[string]FlagValue:
- m = cast.ToStringMap(mi)
- default:
- return ""
- }
-
- // scan paths
- var parentKey string
- for i := 1; i < len(path); i++ {
- parentKey = strings.Join(path[0:i], v.keyDelim)
- if _, ok := m[parentKey]; ok {
- return parentKey
- }
- }
- return ""
-}
-
-// isPathShadowedInAutoEnv makes sure the given path is not shadowed somewhere
-// in the environment, when automatic env is on.
-// e.g., if "foo.bar" has a value in the environment, it “shadows”
-// "foo.bar.baz" in a lower-priority map
-func (v *Viper) isPathShadowedInAutoEnv(path []string) string {
- var parentKey string
- var val string
- for i := 1; i < len(path); i++ {
- parentKey = strings.Join(path[0:i], v.keyDelim)
- if val = v.getEnv(v.mergeWithEnvPrefix(parentKey)); val != "" {
- return parentKey
- }
- }
- return ""
-}
-
-// SetTypeByDefaultValue enables or disables the inference of a key value's
-// type when the Get function is used based upon a key's default value as
-// opposed to the value returned based on the normal fetch logic.
-//
-// For example, if a key has a default value of []string{} and the same key
-// is set via an environment variable to "a b c", a call to the Get function
-// would return a string slice for the key if the key's type is inferred by
-// the default value and the Get function would return:
-//
-// []string {"a", "b", "c"}
-//
-// Otherwise the Get function would return:
-//
-// "a b c"
-func SetTypeByDefaultValue(enable bool) { v.SetTypeByDefaultValue(enable) }
-func (v *Viper) SetTypeByDefaultValue(enable bool) {
- v.typeByDefValue = enable
-}
-
-// GetViper gets the global Viper instance.
-func GetViper() *Viper {
- return v
-}
-
-// Get can retrieve any value given the key to use.
-// Get is case-insensitive for a key.
-// Get has the behavior of returning the value associated with the first
-// place from where it is set. Viper will check in the following order:
-// override, flag, env, config file, key/value store, default
-//
-// Get returns an interface. For a specific value use one of the Get____ methods.
-func Get(key string) interface{} { return v.Get(key) }
-func (v *Viper) Get(key string) interface{} {
- lcaseKey := strings.ToLower(key)
- val := v.find(lcaseKey)
- if val == nil {
- return nil
- }
-
- if v.typeByDefValue {
- // TODO(bep) this branch isn't covered by a single test.
- valType := val
- path := strings.Split(lcaseKey, v.keyDelim)
- defVal := v.searchMap(v.defaults, path)
- if defVal != nil {
- valType = defVal
- }
-
- switch valType.(type) {
- case bool:
- return cast.ToBool(val)
- case string:
- return cast.ToString(val)
- case int64, int32, int16, int8, int:
- return cast.ToInt(val)
- case float64, float32:
- return cast.ToFloat64(val)
- case time.Time:
- return cast.ToTime(val)
- case time.Duration:
- return cast.ToDuration(val)
- case []string:
- return cast.ToStringSlice(val)
- }
- }
-
- return val
-}
-
-// Sub returns new Viper instance representing a sub tree of this instance.
-// Sub is case-insensitive for a key.
-func Sub(key string) *Viper { return v.Sub(key) }
-func (v *Viper) Sub(key string) *Viper {
- subv := New()
- data := v.Get(key)
- if data == nil {
- return nil
- }
-
- if reflect.TypeOf(data).Kind() == reflect.Map {
- subv.config = cast.ToStringMap(data)
- return subv
- }
- return nil
-}
-
-// GetString returns the value associated with the key as a string.
-func GetString(key string) string { return v.GetString(key) }
-func (v *Viper) GetString(key string) string {
- return cast.ToString(v.Get(key))
-}
-
-// GetBool returns the value associated with the key as a boolean.
-func GetBool(key string) bool { return v.GetBool(key) }
-func (v *Viper) GetBool(key string) bool {
- return cast.ToBool(v.Get(key))
-}
-
-// GetInt returns the value associated with the key as an integer.
-func GetInt(key string) int { return v.GetInt(key) }
-func (v *Viper) GetInt(key string) int {
- return cast.ToInt(v.Get(key))
-}
-
-// GetInt64 returns the value associated with the key as an integer.
-func GetInt64(key string) int64 { return v.GetInt64(key) }
-func (v *Viper) GetInt64(key string) int64 {
- return cast.ToInt64(v.Get(key))
-}
-
-// GetFloat64 returns the value associated with the key as a float64.
-func GetFloat64(key string) float64 { return v.GetFloat64(key) }
-func (v *Viper) GetFloat64(key string) float64 {
- return cast.ToFloat64(v.Get(key))
-}
-
-// GetTime returns the value associated with the key as time.
-func GetTime(key string) time.Time { return v.GetTime(key) }
-func (v *Viper) GetTime(key string) time.Time {
- return cast.ToTime(v.Get(key))
-}
-
-// GetDuration returns the value associated with the key as a duration.
-func GetDuration(key string) time.Duration { return v.GetDuration(key) }
-func (v *Viper) GetDuration(key string) time.Duration {
- return cast.ToDuration(v.Get(key))
-}
-
-// GetStringSlice returns the value associated with the key as a slice of strings.
-func GetStringSlice(key string) []string { return v.GetStringSlice(key) }
-func (v *Viper) GetStringSlice(key string) []string {
- return cast.ToStringSlice(v.Get(key))
-}
-
-// GetStringMap returns the value associated with the key as a map of interfaces.
-func GetStringMap(key string) map[string]interface{} { return v.GetStringMap(key) }
-func (v *Viper) GetStringMap(key string) map[string]interface{} {
- return cast.ToStringMap(v.Get(key))
-}
-
-// GetStringMapString returns the value associated with the key as a map of strings.
-func GetStringMapString(key string) map[string]string { return v.GetStringMapString(key) }
-func (v *Viper) GetStringMapString(key string) map[string]string {
- return cast.ToStringMapString(v.Get(key))
-}
-
-// GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.
-func GetStringMapStringSlice(key string) map[string][]string { return v.GetStringMapStringSlice(key) }
-func (v *Viper) GetStringMapStringSlice(key string) map[string][]string {
- return cast.ToStringMapStringSlice(v.Get(key))
-}
-
-// GetSizeInBytes returns the size of the value associated with the given key
-// in bytes.
-func GetSizeInBytes(key string) uint { return v.GetSizeInBytes(key) }
-func (v *Viper) GetSizeInBytes(key string) uint {
- sizeStr := cast.ToString(v.Get(key))
- return parseSizeInBytes(sizeStr)
-}
-
-// UnmarshalKey takes a single key and unmarshals it into a Struct.
-func UnmarshalKey(key string, rawVal interface{}) error { return v.UnmarshalKey(key, rawVal) }
-func (v *Viper) UnmarshalKey(key string, rawVal interface{}) error {
- err := decode(v.Get(key), defaultDecoderConfig(rawVal))
-
- if err != nil {
- return err
- }
-
- v.insensitiviseMaps()
-
- return nil
-}
-
-// Unmarshal unmarshals the config into a Struct. Make sure that the tags
-// on the fields of the structure are properly set.
-func Unmarshal(rawVal interface{}) error { return v.Unmarshal(rawVal) }
-func (v *Viper) Unmarshal(rawVal interface{}) error {
- err := decode(v.AllSettings(), defaultDecoderConfig(rawVal))
-
- if err != nil {
- return err
- }
-
- v.insensitiviseMaps()
-
- return nil
-}
-
-// defaultDecoderConfig returns default mapsstructure.DecoderConfig with suppot
-// of time.Duration values
-func defaultDecoderConfig(output interface{}) *mapstructure.DecoderConfig {
- return &mapstructure.DecoderConfig{
- Metadata: nil,
- Result: output,
- WeaklyTypedInput: true,
- DecodeHook: mapstructure.StringToTimeDurationHookFunc(),
- }
-}
-
-// A wrapper around mapstructure.Decode that mimics the WeakDecode functionality
-func decode(input interface{}, config *mapstructure.DecoderConfig) error {
- decoder, err := mapstructure.NewDecoder(config)
- if err != nil {
- return err
- }
- return decoder.Decode(input)
-}
-
-// UnmarshalExact unmarshals the config into a Struct, erroring if a field is nonexistent
-// in the destination struct.
-func (v *Viper) UnmarshalExact(rawVal interface{}) error {
- config := defaultDecoderConfig(rawVal)
- config.ErrorUnused = true
-
- err := decode(v.AllSettings(), config)
-
- if err != nil {
- return err
- }
-
- v.insensitiviseMaps()
-
- return nil
-}
-
-// BindPFlags binds a full flag set to the configuration, using each flag's long
-// name as the config key.
-func BindPFlags(flags *pflag.FlagSet) error { return v.BindPFlags(flags) }
-func (v *Viper) BindPFlags(flags *pflag.FlagSet) error {
- return v.BindFlagValues(pflagValueSet{flags})
-}
-
-// BindPFlag binds a specific key to a pflag (as used by cobra).
-// Example (where serverCmd is a Cobra instance):
-//
-// serverCmd.Flags().Int("port", 1138, "Port to run Application server on")
-// Viper.BindPFlag("port", serverCmd.Flags().Lookup("port"))
-//
-func BindPFlag(key string, flag *pflag.Flag) error { return v.BindPFlag(key, flag) }
-func (v *Viper) BindPFlag(key string, flag *pflag.Flag) error {
- return v.BindFlagValue(key, pflagValue{flag})
-}
-
-// BindFlagValues binds a full FlagValue set to the configuration, using each flag's long
-// name as the config key.
-func BindFlagValues(flags FlagValueSet) error { return v.BindFlagValues(flags) }
-func (v *Viper) BindFlagValues(flags FlagValueSet) (err error) {
- flags.VisitAll(func(flag FlagValue) {
- if err = v.BindFlagValue(flag.Name(), flag); err != nil {
- return
- }
- })
- return nil
-}
-
-// BindFlagValue binds a specific key to a FlagValue.
-// Example (where serverCmd is a Cobra instance):
-//
-// serverCmd.Flags().Int("port", 1138, "Port to run Application server on")
-// Viper.BindFlagValue("port", serverCmd.Flags().Lookup("port"))
-//
-func BindFlagValue(key string, flag FlagValue) error { return v.BindFlagValue(key, flag) }
-func (v *Viper) BindFlagValue(key string, flag FlagValue) error {
- if flag == nil {
- return fmt.Errorf("flag for %q is nil", key)
- }
- v.pflags[strings.ToLower(key)] = flag
- return nil
-}
-
-// BindEnv binds a Viper key to a ENV variable.
-// ENV variables are case sensitive.
-// If only a key is provided, it will use the env key matching the key, uppercased.
-// EnvPrefix will be used when set when env name is not provided.
-func BindEnv(input ...string) error { return v.BindEnv(input...) }
-func (v *Viper) BindEnv(input ...string) error {
- var key, envkey string
- if len(input) == 0 {
- return fmt.Errorf("BindEnv missing key to bind to")
- }
-
- key = strings.ToLower(input[0])
-
- if len(input) == 1 {
- envkey = v.mergeWithEnvPrefix(key)
- } else {
- envkey = input[1]
- }
-
- v.env[key] = envkey
-
- return nil
-}
-
-// Given a key, find the value.
-// Viper will check in the following order:
-// flag, env, config file, key/value store, default.
-// Viper will check to see if an alias exists first.
-// Note: this assumes a lower-cased key given.
-func (v *Viper) find(lcaseKey string) interface{} {
-
- var (
- val interface{}
- exists bool
- path = strings.Split(lcaseKey, v.keyDelim)
- nested = len(path) > 1
- )
-
- // compute the path through the nested maps to the nested value
- if nested && v.isPathShadowedInDeepMap(path, castMapStringToMapInterface(v.aliases)) != "" {
- return nil
- }
-
- // if the requested key is an alias, then return the proper key
- lcaseKey = v.realKey(lcaseKey)
- path = strings.Split(lcaseKey, v.keyDelim)
- nested = len(path) > 1
-
- // Set() override first
- val = v.searchMap(v.override, path)
- if val != nil {
- return val
- }
- if nested && v.isPathShadowedInDeepMap(path, v.override) != "" {
- return nil
- }
-
- // PFlag override next
- flag, exists := v.pflags[lcaseKey]
- if exists && flag.HasChanged() {
- switch flag.ValueType() {
- case "int", "int8", "int16", "int32", "int64":
- return cast.ToInt(flag.ValueString())
- case "bool":
- return cast.ToBool(flag.ValueString())
- case "stringSlice":
- s := strings.TrimPrefix(flag.ValueString(), "[")
- s = strings.TrimSuffix(s, "]")
- res, _ := readAsCSV(s)
- return res
- default:
- return flag.ValueString()
- }
- }
- if nested && v.isPathShadowedInFlatMap(path, v.pflags) != "" {
- return nil
- }
-
- // Env override next
- if v.automaticEnvApplied {
- // even if it hasn't been registered, if automaticEnv is used,
- // check any Get request
- if val = v.getEnv(v.mergeWithEnvPrefix(lcaseKey)); val != "" {
- return val
- }
- if nested && v.isPathShadowedInAutoEnv(path) != "" {
- return nil
- }
- }
- envkey, exists := v.env[lcaseKey]
- if exists {
- if val = v.getEnv(envkey); val != "" {
- return val
- }
- }
- if nested && v.isPathShadowedInFlatMap(path, v.env) != "" {
- return nil
- }
-
- // Config file next
- val = v.searchMapWithPathPrefixes(v.config, path)
- if val != nil {
- return val
- }
- if nested && v.isPathShadowedInDeepMap(path, v.config) != "" {
- return nil
- }
-
- // K/V store next
- val = v.searchMap(v.kvstore, path)
- if val != nil {
- return val
- }
- if nested && v.isPathShadowedInDeepMap(path, v.kvstore) != "" {
- return nil
- }
-
- // Default next
- val = v.searchMap(v.defaults, path)
- if val != nil {
- return val
- }
- if nested && v.isPathShadowedInDeepMap(path, v.defaults) != "" {
- return nil
- }
-
- // last chance: if no other value is returned and a flag does exist for the value,
- // get the flag's value even if the flag's value has not changed
- if flag, exists := v.pflags[lcaseKey]; exists {
- switch flag.ValueType() {
- case "int", "int8", "int16", "int32", "int64":
- return cast.ToInt(flag.ValueString())
- case "bool":
- return cast.ToBool(flag.ValueString())
- case "stringSlice":
- s := strings.TrimPrefix(flag.ValueString(), "[")
- s = strings.TrimSuffix(s, "]")
- res, _ := readAsCSV(s)
- return res
- default:
- return flag.ValueString()
- }
- }
- // last item, no need to check shadowing
-
- return nil
-}
-
-func readAsCSV(val string) ([]string, error) {
- if val == "" {
- return []string{}, nil
- }
- stringReader := strings.NewReader(val)
- csvReader := csv.NewReader(stringReader)
- return csvReader.Read()
-}
-
-// IsSet checks to see if the key has been set in any of the data locations.
-// IsSet is case-insensitive for a key.
-func IsSet(key string) bool { return v.IsSet(key) }
-func (v *Viper) IsSet(key string) bool {
- lcaseKey := strings.ToLower(key)
- val := v.find(lcaseKey)
- return val != nil
-}
-
-// AutomaticEnv has Viper check ENV variables for all.
-// keys set in config, default & flags
-func AutomaticEnv() { v.AutomaticEnv() }
-func (v *Viper) AutomaticEnv() {
- v.automaticEnvApplied = true
-}
-
-// SetEnvKeyReplacer sets the strings.Replacer on the viper object
-// Useful for mapping an environmental variable to a key that does
-// not match it.
-func SetEnvKeyReplacer(r *strings.Replacer) { v.SetEnvKeyReplacer(r) }
-func (v *Viper) SetEnvKeyReplacer(r *strings.Replacer) {
- v.envKeyReplacer = r
-}
-
-// Aliases provide another accessor for the same key.
-// This enables one to change a name without breaking the application
-func RegisterAlias(alias string, key string) { v.RegisterAlias(alias, key) }
-func (v *Viper) RegisterAlias(alias string, key string) {
- v.registerAlias(alias, strings.ToLower(key))
-}
-
-func (v *Viper) registerAlias(alias string, key string) {
- alias = strings.ToLower(alias)
- if alias != key && alias != v.realKey(key) {
- _, exists := v.aliases[alias]
-
- if !exists {
- // if we alias something that exists in one of the maps to another
- // name, we'll never be able to get that value using the original
- // name, so move the config value to the new realkey.
- if val, ok := v.config[alias]; ok {
- delete(v.config, alias)
- v.config[key] = val
- }
- if val, ok := v.kvstore[alias]; ok {
- delete(v.kvstore, alias)
- v.kvstore[key] = val
- }
- if val, ok := v.defaults[alias]; ok {
- delete(v.defaults, alias)
- v.defaults[key] = val
- }
- if val, ok := v.override[alias]; ok {
- delete(v.override, alias)
- v.override[key] = val
- }
- v.aliases[alias] = key
- }
- } else {
- jww.WARN.Println("Creating circular reference alias", alias, key, v.realKey(key))
- }
-}
-
-func (v *Viper) realKey(key string) string {
- newkey, exists := v.aliases[key]
- if exists {
- jww.DEBUG.Println("Alias", key, "to", newkey)
- return v.realKey(newkey)
- }
- return key
-}
-
-// InConfig checks to see if the given key (or an alias) is in the config file.
-func InConfig(key string) bool { return v.InConfig(key) }
-func (v *Viper) InConfig(key string) bool {
- // if the requested key is an alias, then return the proper key
- key = v.realKey(key)
-
- _, exists := v.config[key]
- return exists
-}
-
-// SetDefault sets the default value for this key.
-// SetDefault is case-insensitive for a key.
-// Default only used when no value is provided by the user via flag, config or ENV.
-func SetDefault(key string, value interface{}) { v.SetDefault(key, value) }
-func (v *Viper) SetDefault(key string, value interface{}) {
- // If alias passed in, then set the proper default
- key = v.realKey(strings.ToLower(key))
- value = toCaseInsensitiveValue(value)
-
- path := strings.Split(key, v.keyDelim)
- lastKey := strings.ToLower(path[len(path)-1])
- deepestMap := deepSearch(v.defaults, path[0:len(path)-1])
-
- // set innermost value
- deepestMap[lastKey] = value
-}
-
-// Set sets the value for the key in the override regiser.
-// Set is case-insensitive for a key.
-// Will be used instead of values obtained via
-// flags, config file, ENV, default, or key/value store.
-func Set(key string, value interface{}) { v.Set(key, value) }
-func (v *Viper) Set(key string, value interface{}) {
- // If alias passed in, then set the proper override
- key = v.realKey(strings.ToLower(key))
- value = toCaseInsensitiveValue(value)
-
- path := strings.Split(key, v.keyDelim)
- lastKey := strings.ToLower(path[len(path)-1])
- deepestMap := deepSearch(v.override, path[0:len(path)-1])
-
- // set innermost value
- deepestMap[lastKey] = value
-}
-
-// ReadInConfig will discover and load the configuration file from disk
-// and key/value stores, searching in one of the defined paths.
-func ReadInConfig() error { return v.ReadInConfig() }
-func (v *Viper) ReadInConfig() error {
- jww.INFO.Println("Attempting to read in config file")
- filename, err := v.getConfigFile()
- if err != nil {
- return err
- }
-
- if !stringInSlice(v.getConfigType(), SupportedExts) {
- return UnsupportedConfigError(v.getConfigType())
- }
-
- file, err := afero.ReadFile(v.fs, filename)
- if err != nil {
- return err
- }
-
- config := make(map[string]interface{})
-
- err = v.unmarshalReader(bytes.NewReader(file), config)
- if err != nil {
- return err
- }
-
- v.config = config
- return nil
-}
-
-// MergeInConfig merges a new configuration with an existing config.
-func MergeInConfig() error { return v.MergeInConfig() }
-func (v *Viper) MergeInConfig() error {
- jww.INFO.Println("Attempting to merge in config file")
- filename, err := v.getConfigFile()
- if err != nil {
- return err
- }
-
- if !stringInSlice(v.getConfigType(), SupportedExts) {
- return UnsupportedConfigError(v.getConfigType())
- }
-
- file, err := afero.ReadFile(v.fs, filename)
- if err != nil {
- return err
- }
-
- return v.MergeConfig(bytes.NewReader(file))
-}
-
-// ReadConfig will read a configuration file, setting existing keys to nil if the
-// key does not exist in the file.
-func ReadConfig(in io.Reader) error { return v.ReadConfig(in) }
-func (v *Viper) ReadConfig(in io.Reader) error {
- v.config = make(map[string]interface{})
- return v.unmarshalReader(in, v.config)
-}
-
-// MergeConfig merges a new configuration with an existing config.
-func MergeConfig(in io.Reader) error { return v.MergeConfig(in) }
-func (v *Viper) MergeConfig(in io.Reader) error {
- if v.config == nil {
- v.config = make(map[string]interface{})
- }
- cfg := make(map[string]interface{})
- if err := v.unmarshalReader(in, cfg); err != nil {
- return err
- }
- mergeMaps(cfg, v.config, nil)
- return nil
-}
-
-func keyExists(k string, m map[string]interface{}) string {
- lk := strings.ToLower(k)
- for mk := range m {
- lmk := strings.ToLower(mk)
- if lmk == lk {
- return mk
- }
- }
- return ""
-}
-
-func castToMapStringInterface(
- src map[interface{}]interface{}) map[string]interface{} {
- tgt := map[string]interface{}{}
- for k, v := range src {
- tgt[fmt.Sprintf("%v", k)] = v
- }
- return tgt
-}
-
-func castMapStringToMapInterface(src map[string]string) map[string]interface{} {
- tgt := map[string]interface{}{}
- for k, v := range src {
- tgt[k] = v
- }
- return tgt
-}
-
-func castMapFlagToMapInterface(src map[string]FlagValue) map[string]interface{} {
- tgt := map[string]interface{}{}
- for k, v := range src {
- tgt[k] = v
- }
- return tgt
-}
-
-// mergeMaps merges two maps. The `itgt` parameter is for handling go-yaml's
-// insistence on parsing nested structures as `map[interface{}]interface{}`
-// instead of using a `string` as the key for nest structures beyond one level
-// deep. Both map types are supported as there is a go-yaml fork that uses
-// `map[string]interface{}` instead.
-func mergeMaps(
- src, tgt map[string]interface{}, itgt map[interface{}]interface{}) {
- for sk, sv := range src {
- tk := keyExists(sk, tgt)
- if tk == "" {
- jww.TRACE.Printf("tk=\"\", tgt[%s]=%v", sk, sv)
- tgt[sk] = sv
- if itgt != nil {
- itgt[sk] = sv
- }
- continue
- }
-
- tv, ok := tgt[tk]
- if !ok {
- jww.TRACE.Printf("tgt[%s] != ok, tgt[%s]=%v", tk, sk, sv)
- tgt[sk] = sv
- if itgt != nil {
- itgt[sk] = sv
- }
- continue
- }
-
- svType := reflect.TypeOf(sv)
- tvType := reflect.TypeOf(tv)
- if svType != tvType {
- jww.ERROR.Printf(
- "svType != tvType; key=%s, st=%v, tt=%v, sv=%v, tv=%v",
- sk, svType, tvType, sv, tv)
- continue
- }
-
- jww.TRACE.Printf("processing key=%s, st=%v, tt=%v, sv=%v, tv=%v",
- sk, svType, tvType, sv, tv)
-
- switch ttv := tv.(type) {
- case map[interface{}]interface{}:
- jww.TRACE.Printf("merging maps (must convert)")
- tsv := sv.(map[interface{}]interface{})
- ssv := castToMapStringInterface(tsv)
- stv := castToMapStringInterface(ttv)
- mergeMaps(ssv, stv, ttv)
- case map[string]interface{}:
- jww.TRACE.Printf("merging maps")
- mergeMaps(sv.(map[string]interface{}), ttv, nil)
- default:
- jww.TRACE.Printf("setting value")
- tgt[tk] = sv
- if itgt != nil {
- itgt[tk] = sv
- }
- }
- }
-}
-
-// ReadRemoteConfig attempts to get configuration from a remote source
-// and read it in the remote configuration registry.
-func ReadRemoteConfig() error { return v.ReadRemoteConfig() }
-func (v *Viper) ReadRemoteConfig() error {
- return v.getKeyValueConfig()
-}
-
-func WatchRemoteConfig() error { return v.WatchRemoteConfig() }
-func (v *Viper) WatchRemoteConfig() error {
- return v.watchKeyValueConfig()
-}
-
-func (v *Viper) WatchRemoteConfigOnChannel() error {
- return v.watchKeyValueConfigOnChannel()
-}
-
-// Unmarshal a Reader into a map.
-// Should probably be an unexported function.
-func unmarshalReader(in io.Reader, c map[string]interface{}) error {
- return v.unmarshalReader(in, c)
-}
-
-func (v *Viper) unmarshalReader(in io.Reader, c map[string]interface{}) error {
- return unmarshallConfigReader(in, c, v.getConfigType())
-}
-
-func (v *Viper) insensitiviseMaps() {
- insensitiviseMap(v.config)
- insensitiviseMap(v.defaults)
- insensitiviseMap(v.override)
- insensitiviseMap(v.kvstore)
-}
-
-// Retrieve the first found remote configuration.
-func (v *Viper) getKeyValueConfig() error {
- if RemoteConfig == nil {
- return RemoteConfigError("Enable the remote features by doing a blank import of the viper/remote package: '_ github.com/spf13/viper/remote'")
- }
-
- for _, rp := range v.remoteProviders {
- val, err := v.getRemoteConfig(rp)
- if err != nil {
- continue
- }
- v.kvstore = val
- return nil
- }
- return RemoteConfigError("No Files Found")
-}
-
-func (v *Viper) getRemoteConfig(provider RemoteProvider) (map[string]interface{}, error) {
- reader, err := RemoteConfig.Get(provider)
- if err != nil {
- return nil, err
- }
- err = v.unmarshalReader(reader, v.kvstore)
- return v.kvstore, err
-}
-
-// Retrieve the first found remote configuration.
-func (v *Viper) watchKeyValueConfigOnChannel() error {
- for _, rp := range v.remoteProviders {
- respc, _ := RemoteConfig.WatchChannel(rp)
- //Todo: Add quit channel
- go func(rc <-chan *RemoteResponse) {
- for {
- b := <-rc
- reader := bytes.NewReader(b.Value)
- v.unmarshalReader(reader, v.kvstore)
- }
- }(respc)
- return nil
- }
- return RemoteConfigError("No Files Found")
-}
-
-// Retrieve the first found remote configuration.
-func (v *Viper) watchKeyValueConfig() error {
- for _, rp := range v.remoteProviders {
- val, err := v.watchRemoteConfig(rp)
- if err != nil {
- continue
- }
- v.kvstore = val
- return nil
- }
- return RemoteConfigError("No Files Found")
-}
-
-func (v *Viper) watchRemoteConfig(provider RemoteProvider) (map[string]interface{}, error) {
- reader, err := RemoteConfig.Watch(provider)
- if err != nil {
- return nil, err
- }
- err = v.unmarshalReader(reader, v.kvstore)
- return v.kvstore, err
-}
-
-// AllKeys returns all keys holding a value, regardless of where they are set.
-// Nested keys are returned with a v.keyDelim (= ".") separator
-func AllKeys() []string { return v.AllKeys() }
-func (v *Viper) AllKeys() []string {
- m := map[string]bool{}
- // add all paths, by order of descending priority to ensure correct shadowing
- m = v.flattenAndMergeMap(m, castMapStringToMapInterface(v.aliases), "")
- m = v.flattenAndMergeMap(m, v.override, "")
- m = v.mergeFlatMap(m, castMapFlagToMapInterface(v.pflags))
- m = v.mergeFlatMap(m, castMapStringToMapInterface(v.env))
- m = v.flattenAndMergeMap(m, v.config, "")
- m = v.flattenAndMergeMap(m, v.kvstore, "")
- m = v.flattenAndMergeMap(m, v.defaults, "")
-
- // convert set of paths to list
- a := []string{}
- for x := range m {
- a = append(a, x)
- }
- return a
-}
-
-// flattenAndMergeMap recursively flattens the given map into a map[string]bool
-// of key paths (used as a set, easier to manipulate than a []string):
-// - each path is merged into a single key string, delimited with v.keyDelim (= ".")
-// - if a path is shadowed by an earlier value in the initial shadow map,
-// it is skipped.
-// The resulting set of paths is merged to the given shadow set at the same time.
-func (v *Viper) flattenAndMergeMap(shadow map[string]bool, m map[string]interface{}, prefix string) map[string]bool {
- if shadow != nil && prefix != "" && shadow[prefix] {
- // prefix is shadowed => nothing more to flatten
- return shadow
- }
- if shadow == nil {
- shadow = make(map[string]bool)
- }
-
- var m2 map[string]interface{}
- if prefix != "" {
- prefix += v.keyDelim
- }
- for k, val := range m {
- fullKey := prefix + k
- switch val.(type) {
- case map[string]interface{}:
- m2 = val.(map[string]interface{})
- case map[interface{}]interface{}:
- m2 = cast.ToStringMap(val)
- default:
- // immediate value
- shadow[strings.ToLower(fullKey)] = true
- continue
- }
- // recursively merge to shadow map
- shadow = v.flattenAndMergeMap(shadow, m2, fullKey)
- }
- return shadow
-}
-
-// mergeFlatMap merges the given maps, excluding values of the second map
-// shadowed by values from the first map.
-func (v *Viper) mergeFlatMap(shadow map[string]bool, m map[string]interface{}) map[string]bool {
- // scan keys
-outer:
- for k, _ := range m {
- path := strings.Split(k, v.keyDelim)
- // scan intermediate paths
- var parentKey string
- for i := 1; i < len(path); i++ {
- parentKey = strings.Join(path[0:i], v.keyDelim)
- if shadow[parentKey] {
- // path is shadowed, continue
- continue outer
- }
- }
- // add key
- shadow[strings.ToLower(k)] = true
- }
- return shadow
-}
-
-// AllSettings merges all settings and returns them as a map[string]interface{}.
-func AllSettings() map[string]interface{} { return v.AllSettings() }
-func (v *Viper) AllSettings() map[string]interface{} {
- m := map[string]interface{}{}
- // start from the list of keys, and construct the map one value at a time
- for _, k := range v.AllKeys() {
- value := v.Get(k)
- if value == nil {
- // should not happen, since AllKeys() returns only keys holding a value,
- // check just in case anything changes
- continue
- }
- path := strings.Split(k, v.keyDelim)
- lastKey := strings.ToLower(path[len(path)-1])
- deepestMap := deepSearch(m, path[0:len(path)-1])
- // set innermost value
- deepestMap[lastKey] = value
- }
- return m
-}
-
-// SetFs sets the filesystem to use to read configuration.
-func SetFs(fs afero.Fs) { v.SetFs(fs) }
-func (v *Viper) SetFs(fs afero.Fs) {
- v.fs = fs
-}
-
-// SetConfigName sets name for the config file.
-// Does not include extension.
-func SetConfigName(in string) { v.SetConfigName(in) }
-func (v *Viper) SetConfigName(in string) {
- if in != "" {
- v.configName = in
- v.configFile = ""
- }
-}
-
-// SetConfigType sets the type of the configuration returned by the
-// remote source, e.g. "json".
-func SetConfigType(in string) { v.SetConfigType(in) }
-func (v *Viper) SetConfigType(in string) {
- if in != "" {
- v.configType = in
- }
-}
-
-func (v *Viper) getConfigType() string {
- if v.configType != "" {
- return v.configType
- }
-
- cf, err := v.getConfigFile()
- if err != nil {
- return ""
- }
-
- ext := filepath.Ext(cf)
-
- if len(ext) > 1 {
- return ext[1:]
- }
-
- return ""
-}
-
-func (v *Viper) getConfigFile() (string, error) {
- // if explicitly set, then use it
- if v.configFile != "" {
- return v.configFile, nil
- }
-
- cf, err := v.findConfigFile()
- if err != nil {
- return "", err
- }
-
- v.configFile = cf
- return v.getConfigFile()
-}
-
-func (v *Viper) searchInPath(in string) (filename string) {
- jww.DEBUG.Println("Searching for config in ", in)
- for _, ext := range SupportedExts {
- jww.DEBUG.Println("Checking for", filepath.Join(in, v.configName+"."+ext))
- if b, _ := exists(filepath.Join(in, v.configName+"."+ext)); b {
- jww.DEBUG.Println("Found: ", filepath.Join(in, v.configName+"."+ext))
- return filepath.Join(in, v.configName+"."+ext)
- }
- }
-
- return ""
-}
-
-// Search all configPaths for any config file.
-// Returns the first path that exists (and is a config file).
-func (v *Viper) findConfigFile() (string, error) {
- jww.INFO.Println("Searching for config in ", v.configPaths)
-
- for _, cp := range v.configPaths {
- file := v.searchInPath(cp)
- if file != "" {
- return file, nil
- }
- }
- return "", ConfigFileNotFoundError{v.configName, fmt.Sprintf("%s", v.configPaths)}
-}
-
-// Debug prints all configuration registries for debugging
-// purposes.
-func Debug() { v.Debug() }
-func (v *Viper) Debug() {
- fmt.Printf("Aliases:\n%#v\n", v.aliases)
- fmt.Printf("Override:\n%#v\n", v.override)
- fmt.Printf("PFlags:\n%#v\n", v.pflags)
- fmt.Printf("Env:\n%#v\n", v.env)
- fmt.Printf("Key/Value Store:\n%#v\n", v.kvstore)
- fmt.Printf("Config:\n%#v\n", v.config)
- fmt.Printf("Defaults:\n%#v\n", v.defaults)
-}
diff --git a/vendor/github.com/spf13/viper/viper_test.go b/vendor/github.com/spf13/viper/viper_test.go
deleted file mode 100644
index 774ca11..0000000
--- a/vendor/github.com/spf13/viper/viper_test.go
+++ /dev/null
@@ -1,1221 +0,0 @@
-// Copyright © 2014 Steve Francia .
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-package viper
-
-import (
- "bytes"
- "fmt"
- "io"
- "io/ioutil"
- "os"
- "path"
- "reflect"
- "sort"
- "strings"
- "testing"
- "time"
-
- "github.com/spf13/cast"
-
- "github.com/spf13/pflag"
- "github.com/stretchr/testify/assert"
-)
-
-var yamlExample = []byte(`Hacker: true
-name: steve
-hobbies:
-- skateboarding
-- snowboarding
-- go
-clothing:
- jacket: leather
- trousers: denim
- pants:
- size: large
-age: 35
-eyes : brown
-beard: true
-`)
-
-var yamlExampleWithExtras = []byte(`Existing: true
-Bogus: true
-`)
-
-type testUnmarshalExtra struct {
- Existing bool
-}
-
-var tomlExample = []byte(`
-title = "TOML Example"
-
-[owner]
-organization = "MongoDB"
-Bio = "MongoDB Chief Developer Advocate & Hacker at Large"
-dob = 1979-05-27T07:32:00Z # First class dates? Why not?`)
-
-var jsonExample = []byte(`{
-"id": "0001",
-"type": "donut",
-"name": "Cake",
-"ppu": 0.55,
-"batters": {
- "batter": [
- { "type": "Regular" },
- { "type": "Chocolate" },
- { "type": "Blueberry" },
- { "type": "Devil's Food" }
- ]
- }
-}`)
-
-var hclExample = []byte(`
-id = "0001"
-type = "donut"
-name = "Cake"
-ppu = 0.55
-foos {
- foo {
- key = 1
- }
- foo {
- key = 2
- }
- foo {
- key = 3
- }
- foo {
- key = 4
- }
-}`)
-
-var propertiesExample = []byte(`
-p_id: 0001
-p_type: donut
-p_name: Cake
-p_ppu: 0.55
-p_batters.batter.type: Regular
-`)
-
-var remoteExample = []byte(`{
-"id":"0002",
-"type":"cronut",
-"newkey":"remote"
-}`)
-
-func initConfigs() {
- Reset()
- var r io.Reader
- SetConfigType("yaml")
- r = bytes.NewReader(yamlExample)
- unmarshalReader(r, v.config)
-
- SetConfigType("json")
- r = bytes.NewReader(jsonExample)
- unmarshalReader(r, v.config)
-
- SetConfigType("hcl")
- r = bytes.NewReader(hclExample)
- unmarshalReader(r, v.config)
-
- SetConfigType("properties")
- r = bytes.NewReader(propertiesExample)
- unmarshalReader(r, v.config)
-
- SetConfigType("toml")
- r = bytes.NewReader(tomlExample)
- unmarshalReader(r, v.config)
-
- SetConfigType("json")
- remote := bytes.NewReader(remoteExample)
- unmarshalReader(remote, v.kvstore)
-}
-
-func initConfig(typ, config string) {
- Reset()
- SetConfigType(typ)
- r := strings.NewReader(config)
-
- if err := unmarshalReader(r, v.config); err != nil {
- panic(err)
- }
-}
-
-func initYAML() {
- initConfig("yaml", string(yamlExample))
-}
-
-func initJSON() {
- Reset()
- SetConfigType("json")
- r := bytes.NewReader(jsonExample)
-
- unmarshalReader(r, v.config)
-}
-
-func initProperties() {
- Reset()
- SetConfigType("properties")
- r := bytes.NewReader(propertiesExample)
-
- unmarshalReader(r, v.config)
-}
-
-func initTOML() {
- Reset()
- SetConfigType("toml")
- r := bytes.NewReader(tomlExample)
-
- unmarshalReader(r, v.config)
-}
-
-func initHcl() {
- Reset()
- SetConfigType("hcl")
- r := bytes.NewReader(hclExample)
-
- unmarshalReader(r, v.config)
-}
-
-// make directories for testing
-func initDirs(t *testing.T) (string, string, func()) {
-
- var (
- testDirs = []string{`a a`, `b`, `c\c`, `D_`}
- config = `improbable`
- )
-
- root, err := ioutil.TempDir("", "")
-
- cleanup := true
- defer func() {
- if cleanup {
- os.Chdir("..")
- os.RemoveAll(root)
- }
- }()
-
- assert.Nil(t, err)
-
- err = os.Chdir(root)
- assert.Nil(t, err)
-
- for _, dir := range testDirs {
- err = os.Mkdir(dir, 0750)
- assert.Nil(t, err)
-
- err = ioutil.WriteFile(
- path.Join(dir, config+".toml"),
- []byte("key = \"value is "+dir+"\"\n"),
- 0640)
- assert.Nil(t, err)
- }
-
- cleanup = false
- return root, config, func() {
- os.Chdir("..")
- os.RemoveAll(root)
- }
-}
-
-//stubs for PFlag Values
-type stringValue string
-
-func newStringValue(val string, p *string) *stringValue {
- *p = val
- return (*stringValue)(p)
-}
-
-func (s *stringValue) Set(val string) error {
- *s = stringValue(val)
- return nil
-}
-
-func (s *stringValue) Type() string {
- return "string"
-}
-
-func (s *stringValue) String() string {
- return fmt.Sprintf("%s", *s)
-}
-
-func TestBasics(t *testing.T) {
- SetConfigFile("/tmp/config.yaml")
- filename, err := v.getConfigFile()
- assert.Equal(t, "/tmp/config.yaml", filename)
- assert.NoError(t, err)
-}
-
-func TestDefault(t *testing.T) {
- SetDefault("age", 45)
- assert.Equal(t, 45, Get("age"))
-
- SetDefault("clothing.jacket", "slacks")
- assert.Equal(t, "slacks", Get("clothing.jacket"))
-
- SetConfigType("yaml")
- err := ReadConfig(bytes.NewBuffer(yamlExample))
-
- assert.NoError(t, err)
- assert.Equal(t, "leather", Get("clothing.jacket"))
-}
-
-func TestUnmarshalling(t *testing.T) {
- SetConfigType("yaml")
- r := bytes.NewReader(yamlExample)
-
- unmarshalReader(r, v.config)
- assert.True(t, InConfig("name"))
- assert.False(t, InConfig("state"))
- assert.Equal(t, "steve", Get("name"))
- assert.Equal(t, []interface{}{"skateboarding", "snowboarding", "go"}, Get("hobbies"))
- assert.Equal(t, map[string]interface{}{"jacket": "leather", "trousers": "denim", "pants": map[string]interface{}{"size": "large"}}, Get("clothing"))
- assert.Equal(t, 35, Get("age"))
-}
-
-func TestUnmarshalExact(t *testing.T) {
- vip := New()
- target := &testUnmarshalExtra{}
- vip.SetConfigType("yaml")
- r := bytes.NewReader(yamlExampleWithExtras)
- vip.ReadConfig(r)
- err := vip.UnmarshalExact(target)
- if err == nil {
- t.Fatal("UnmarshalExact should error when populating a struct from a conf that contains unused fields")
- }
-}
-
-func TestOverrides(t *testing.T) {
- Set("age", 40)
- assert.Equal(t, 40, Get("age"))
-}
-
-func TestDefaultPost(t *testing.T) {
- assert.NotEqual(t, "NYC", Get("state"))
- SetDefault("state", "NYC")
- assert.Equal(t, "NYC", Get("state"))
-}
-
-func TestAliases(t *testing.T) {
- RegisterAlias("years", "age")
- assert.Equal(t, 40, Get("years"))
- Set("years", 45)
- assert.Equal(t, 45, Get("age"))
-}
-
-func TestAliasInConfigFile(t *testing.T) {
- // the config file specifies "beard". If we make this an alias for
- // "hasbeard", we still want the old config file to work with beard.
- RegisterAlias("beard", "hasbeard")
- assert.Equal(t, true, Get("hasbeard"))
- Set("hasbeard", false)
- assert.Equal(t, false, Get("beard"))
-}
-
-func TestYML(t *testing.T) {
- initYAML()
- assert.Equal(t, "steve", Get("name"))
-}
-
-func TestJSON(t *testing.T) {
- initJSON()
- assert.Equal(t, "0001", Get("id"))
-}
-
-func TestProperties(t *testing.T) {
- initProperties()
- assert.Equal(t, "0001", Get("p_id"))
-}
-
-func TestTOML(t *testing.T) {
- initTOML()
- assert.Equal(t, "TOML Example", Get("title"))
-}
-
-func TestHCL(t *testing.T) {
- initHcl()
- assert.Equal(t, "0001", Get("id"))
- assert.Equal(t, 0.55, Get("ppu"))
- assert.Equal(t, "donut", Get("type"))
- assert.Equal(t, "Cake", Get("name"))
- Set("id", "0002")
- assert.Equal(t, "0002", Get("id"))
- assert.NotEqual(t, "cronut", Get("type"))
-}
-
-func TestRemotePrecedence(t *testing.T) {
- initJSON()
-
- remote := bytes.NewReader(remoteExample)
- assert.Equal(t, "0001", Get("id"))
- unmarshalReader(remote, v.kvstore)
- assert.Equal(t, "0001", Get("id"))
- assert.NotEqual(t, "cronut", Get("type"))
- assert.Equal(t, "remote", Get("newkey"))
- Set("newkey", "newvalue")
- assert.NotEqual(t, "remote", Get("newkey"))
- assert.Equal(t, "newvalue", Get("newkey"))
- Set("newkey", "remote")
-}
-
-func TestEnv(t *testing.T) {
- initJSON()
-
- BindEnv("id")
- BindEnv("f", "FOOD")
-
- os.Setenv("ID", "13")
- os.Setenv("FOOD", "apple")
- os.Setenv("NAME", "crunk")
-
- assert.Equal(t, "13", Get("id"))
- assert.Equal(t, "apple", Get("f"))
- assert.Equal(t, "Cake", Get("name"))
-
- AutomaticEnv()
-
- assert.Equal(t, "crunk", Get("name"))
-
-}
-
-func TestEnvPrefix(t *testing.T) {
- initJSON()
-
- SetEnvPrefix("foo") // will be uppercased automatically
- BindEnv("id")
- BindEnv("f", "FOOD") // not using prefix
-
- os.Setenv("FOO_ID", "13")
- os.Setenv("FOOD", "apple")
- os.Setenv("FOO_NAME", "crunk")
-
- assert.Equal(t, "13", Get("id"))
- assert.Equal(t, "apple", Get("f"))
- assert.Equal(t, "Cake", Get("name"))
-
- AutomaticEnv()
-
- assert.Equal(t, "crunk", Get("name"))
-}
-
-func TestAutoEnv(t *testing.T) {
- Reset()
-
- AutomaticEnv()
- os.Setenv("FOO_BAR", "13")
- assert.Equal(t, "13", Get("foo_bar"))
-}
-
-func TestAutoEnvWithPrefix(t *testing.T) {
- Reset()
-
- AutomaticEnv()
- SetEnvPrefix("Baz")
- os.Setenv("BAZ_BAR", "13")
- assert.Equal(t, "13", Get("bar"))
-}
-
-func TestSetEnvReplacer(t *testing.T) {
- Reset()
-
- AutomaticEnv()
- os.Setenv("REFRESH_INTERVAL", "30s")
-
- replacer := strings.NewReplacer("-", "_")
- SetEnvKeyReplacer(replacer)
-
- assert.Equal(t, "30s", Get("refresh-interval"))
-}
-
-func TestAllKeys(t *testing.T) {
- initConfigs()
-
- ks := sort.StringSlice{"title", "newkey", "owner.organization", "owner.dob", "owner.bio", "name", "beard", "ppu", "batters.batter", "hobbies", "clothing.jacket", "clothing.trousers", "clothing.pants.size", "age", "hacker", "id", "type", "eyes", "p_id", "p_ppu", "p_batters.batter.type", "p_type", "p_name", "foos"}
- dob, _ := time.Parse(time.RFC3339, "1979-05-27T07:32:00Z")
- all := map[string]interface{}{"owner": map[string]interface{}{"organization": "MongoDB", "bio": "MongoDB Chief Developer Advocate & Hacker at Large", "dob": dob}, "title": "TOML Example", "ppu": 0.55, "eyes": "brown", "clothing": map[string]interface{}{"trousers": "denim", "jacket": "leather", "pants": map[string]interface{}{"size": "large"}}, "id": "0001", "batters": map[string]interface{}{"batter": []interface{}{map[string]interface{}{"type": "Regular"}, map[string]interface{}{"type": "Chocolate"}, map[string]interface{}{"type": "Blueberry"}, map[string]interface{}{"type": "Devil's Food"}}}, "hacker": true, "beard": true, "hobbies": []interface{}{"skateboarding", "snowboarding", "go"}, "age": 35, "type": "donut", "newkey": "remote", "name": "Cake", "p_id": "0001", "p_ppu": "0.55", "p_name": "Cake", "p_batters": map[string]interface{}{"batter": map[string]interface{}{"type": "Regular"}}, "p_type": "donut", "foos": []map[string]interface{}{map[string]interface{}{"foo": []map[string]interface{}{map[string]interface{}{"key": 1}, map[string]interface{}{"key": 2}, map[string]interface{}{"key": 3}, map[string]interface{}{"key": 4}}}}}
-
- var allkeys sort.StringSlice
- allkeys = AllKeys()
- allkeys.Sort()
- ks.Sort()
-
- assert.Equal(t, ks, allkeys)
- assert.Equal(t, all, AllSettings())
-}
-
-func TestAllKeysWithEnv(t *testing.T) {
- v := New()
-
- // bind and define environment variables (including a nested one)
- v.BindEnv("id")
- v.BindEnv("foo.bar")
- v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
- os.Setenv("ID", "13")
- os.Setenv("FOO_BAR", "baz")
-
- expectedKeys := sort.StringSlice{"id", "foo.bar"}
- expectedKeys.Sort()
- keys := sort.StringSlice(v.AllKeys())
- keys.Sort()
- assert.Equal(t, expectedKeys, keys)
-}
-
-func TestAliasesOfAliases(t *testing.T) {
- Set("Title", "Checking Case")
- RegisterAlias("Foo", "Bar")
- RegisterAlias("Bar", "Title")
- assert.Equal(t, "Checking Case", Get("FOO"))
-}
-
-func TestRecursiveAliases(t *testing.T) {
- RegisterAlias("Baz", "Roo")
- RegisterAlias("Roo", "baz")
-}
-
-func TestUnmarshal(t *testing.T) {
- SetDefault("port", 1313)
- Set("name", "Steve")
- Set("duration", "1s1ms")
-
- type config struct {
- Port int
- Name string
- Duration time.Duration
- }
-
- var C config
-
- err := Unmarshal(&C)
- if err != nil {
- t.Fatalf("unable to decode into struct, %v", err)
- }
-
- assert.Equal(t, &config{Name: "Steve", Port: 1313, Duration: time.Second + time.Millisecond}, &C)
-
- Set("port", 1234)
- err = Unmarshal(&C)
- if err != nil {
- t.Fatalf("unable to decode into struct, %v", err)
- }
- assert.Equal(t, &config{Name: "Steve", Port: 1234, Duration: time.Second + time.Millisecond}, &C)
-}
-
-func TestBindPFlags(t *testing.T) {
- v := New() // create independent Viper object
- flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
-
- var testValues = map[string]*string{
- "host": nil,
- "port": nil,
- "endpoint": nil,
- }
-
- var mutatedTestValues = map[string]string{
- "host": "localhost",
- "port": "6060",
- "endpoint": "/public",
- }
-
- for name := range testValues {
- testValues[name] = flagSet.String(name, "", "test")
- }
-
- err := v.BindPFlags(flagSet)
- if err != nil {
- t.Fatalf("error binding flag set, %v", err)
- }
-
- flagSet.VisitAll(func(flag *pflag.Flag) {
- flag.Value.Set(mutatedTestValues[flag.Name])
- flag.Changed = true
- })
-
- for name, expected := range mutatedTestValues {
- assert.Equal(t, expected, v.Get(name))
- }
-
-}
-
-func TestBindPFlagsStringSlice(t *testing.T) {
- for _, testValue := range []struct {
- Expected []string
- Value string
- }{
- {[]string{}, ""},
- {[]string{"jeden"}, "jeden"},
- {[]string{"dwa", "trzy"}, "dwa,trzy"},
- {[]string{"cztery", "piec , szesc"}, "cztery,\"piec , szesc\""}} {
-
- for _, changed := range []bool{true, false} {
- v := New() // create independent Viper object
- flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
- flagSet.StringSlice("stringslice", testValue.Expected, "test")
- flagSet.Visit(func(f *pflag.Flag) {
- if len(testValue.Value) > 0 {
- f.Value.Set(testValue.Value)
- f.Changed = changed
- }
- })
-
- err := v.BindPFlags(flagSet)
- if err != nil {
- t.Fatalf("error binding flag set, %v", err)
- }
-
- type TestStr struct {
- StringSlice []string
- }
- val := &TestStr{}
- if err := v.Unmarshal(val); err != nil {
- t.Fatalf("%+#v cannot unmarshal: %s", testValue.Value, err)
- }
- assert.Equal(t, testValue.Expected, val.StringSlice)
- }
- }
-}
-
-func TestBindPFlag(t *testing.T) {
- var testString = "testing"
- var testValue = newStringValue(testString, &testString)
-
- flag := &pflag.Flag{
- Name: "testflag",
- Value: testValue,
- Changed: false,
- }
-
- BindPFlag("testvalue", flag)
-
- assert.Equal(t, testString, Get("testvalue"))
-
- flag.Value.Set("testing_mutate")
- flag.Changed = true //hack for pflag usage
-
- assert.Equal(t, "testing_mutate", Get("testvalue"))
-
-}
-
-func TestBoundCaseSensitivity(t *testing.T) {
- assert.Equal(t, "brown", Get("eyes"))
-
- BindEnv("eYEs", "TURTLE_EYES")
- os.Setenv("TURTLE_EYES", "blue")
-
- assert.Equal(t, "blue", Get("eyes"))
-
- var testString = "green"
- var testValue = newStringValue(testString, &testString)
-
- flag := &pflag.Flag{
- Name: "eyeballs",
- Value: testValue,
- Changed: true,
- }
-
- BindPFlag("eYEs", flag)
- assert.Equal(t, "green", Get("eyes"))
-
-}
-
-func TestSizeInBytes(t *testing.T) {
- input := map[string]uint{
- "": 0,
- "b": 0,
- "12 bytes": 0,
- "200000000000gb": 0,
- "12 b": 12,
- "43 MB": 43 * (1 << 20),
- "10mb": 10 * (1 << 20),
- "1gb": 1 << 30,
- }
-
- for str, expected := range input {
- assert.Equal(t, expected, parseSizeInBytes(str), str)
- }
-}
-
-func TestFindsNestedKeys(t *testing.T) {
- initConfigs()
- dob, _ := time.Parse(time.RFC3339, "1979-05-27T07:32:00Z")
-
- Set("super", map[string]interface{}{
- "deep": map[string]interface{}{
- "nested": "value",
- },
- })
-
- expected := map[string]interface{}{
- "super": map[string]interface{}{
- "deep": map[string]interface{}{
- "nested": "value",
- },
- },
- "super.deep": map[string]interface{}{
- "nested": "value",
- },
- "super.deep.nested": "value",
- "owner.organization": "MongoDB",
- "batters.batter": []interface{}{
- map[string]interface{}{
- "type": "Regular",
- },
- map[string]interface{}{
- "type": "Chocolate",
- },
- map[string]interface{}{
- "type": "Blueberry",
- },
- map[string]interface{}{
- "type": "Devil's Food",
- },
- },
- "hobbies": []interface{}{
- "skateboarding", "snowboarding", "go",
- },
- "title": "TOML Example",
- "newkey": "remote",
- "batters": map[string]interface{}{
- "batter": []interface{}{
- map[string]interface{}{
- "type": "Regular",
- },
- map[string]interface{}{
- "type": "Chocolate",
- }, map[string]interface{}{
- "type": "Blueberry",
- }, map[string]interface{}{
- "type": "Devil's Food",
- },
- },
- },
- "eyes": "brown",
- "age": 35,
- "owner": map[string]interface{}{
- "organization": "MongoDB",
- "bio": "MongoDB Chief Developer Advocate & Hacker at Large",
- "dob": dob,
- },
- "owner.bio": "MongoDB Chief Developer Advocate & Hacker at Large",
- "type": "donut",
- "id": "0001",
- "name": "Cake",
- "hacker": true,
- "ppu": 0.55,
- "clothing": map[string]interface{}{
- "jacket": "leather",
- "trousers": "denim",
- "pants": map[string]interface{}{
- "size": "large",
- },
- },
- "clothing.jacket": "leather",
- "clothing.pants.size": "large",
- "clothing.trousers": "denim",
- "owner.dob": dob,
- "beard": true,
- "foos": []map[string]interface{}{
- map[string]interface{}{
- "foo": []map[string]interface{}{
- map[string]interface{}{
- "key": 1,
- },
- map[string]interface{}{
- "key": 2,
- },
- map[string]interface{}{
- "key": 3,
- },
- map[string]interface{}{
- "key": 4,
- },
- },
- },
- },
- }
-
- for key, expectedValue := range expected {
-
- assert.Equal(t, expectedValue, v.Get(key))
- }
-
-}
-
-func TestReadBufConfig(t *testing.T) {
- v := New()
- v.SetConfigType("yaml")
- v.ReadConfig(bytes.NewBuffer(yamlExample))
- t.Log(v.AllKeys())
-
- assert.True(t, v.InConfig("name"))
- assert.False(t, v.InConfig("state"))
- assert.Equal(t, "steve", v.Get("name"))
- assert.Equal(t, []interface{}{"skateboarding", "snowboarding", "go"}, v.Get("hobbies"))
- assert.Equal(t, map[string]interface{}{"jacket": "leather", "trousers": "denim", "pants": map[string]interface{}{"size": "large"}}, v.Get("clothing"))
- assert.Equal(t, 35, v.Get("age"))
-}
-
-func TestIsSet(t *testing.T) {
- v := New()
- v.SetConfigType("yaml")
- v.ReadConfig(bytes.NewBuffer(yamlExample))
- assert.True(t, v.IsSet("clothing.jacket"))
- assert.False(t, v.IsSet("clothing.jackets"))
- assert.False(t, v.IsSet("helloworld"))
- v.Set("helloworld", "fubar")
- assert.True(t, v.IsSet("helloworld"))
-}
-
-func TestDirsSearch(t *testing.T) {
-
- root, config, cleanup := initDirs(t)
- defer cleanup()
-
- v := New()
- v.SetConfigName(config)
- v.SetDefault(`key`, `default`)
-
- entries, err := ioutil.ReadDir(root)
- for _, e := range entries {
- if e.IsDir() {
- v.AddConfigPath(e.Name())
- }
- }
-
- err = v.ReadInConfig()
- assert.Nil(t, err)
-
- assert.Equal(t, `value is `+path.Base(v.configPaths[0]), v.GetString(`key`))
-}
-
-func TestWrongDirsSearchNotFound(t *testing.T) {
-
- _, config, cleanup := initDirs(t)
- defer cleanup()
-
- v := New()
- v.SetConfigName(config)
- v.SetDefault(`key`, `default`)
-
- v.AddConfigPath(`whattayoutalkingbout`)
- v.AddConfigPath(`thispathaintthere`)
-
- err := v.ReadInConfig()
- assert.Equal(t, reflect.TypeOf(ConfigFileNotFoundError{"", ""}), reflect.TypeOf(err))
-
- // Even though config did not load and the error might have
- // been ignored by the client, the default still loads
- assert.Equal(t, `default`, v.GetString(`key`))
-}
-
-func TestWrongDirsSearchNotFoundForMerge(t *testing.T) {
-
- _, config, cleanup := initDirs(t)
- defer cleanup()
-
- v := New()
- v.SetConfigName(config)
- v.SetDefault(`key`, `default`)
-
- v.AddConfigPath(`whattayoutalkingbout`)
- v.AddConfigPath(`thispathaintthere`)
-
- err := v.MergeInConfig()
- assert.Equal(t, reflect.TypeOf(ConfigFileNotFoundError{"", ""}), reflect.TypeOf(err))
-
- // Even though config did not load and the error might have
- // been ignored by the client, the default still loads
- assert.Equal(t, `default`, v.GetString(`key`))
-}
-
-func TestSub(t *testing.T) {
- v := New()
- v.SetConfigType("yaml")
- v.ReadConfig(bytes.NewBuffer(yamlExample))
-
- subv := v.Sub("clothing")
- assert.Equal(t, v.Get("clothing.pants.size"), subv.Get("pants.size"))
-
- subv = v.Sub("clothing.pants")
- assert.Equal(t, v.Get("clothing.pants.size"), subv.Get("size"))
-
- subv = v.Sub("clothing.pants.size")
- assert.Equal(t, (*Viper)(nil), subv)
-
- subv = v.Sub("missing.key")
- assert.Equal(t, (*Viper)(nil), subv)
-}
-
-var yamlMergeExampleTgt = []byte(`
-hello:
- pop: 37890
- lagrenum: 765432101234567
- world:
- - us
- - uk
- - fr
- - de
-`)
-
-var yamlMergeExampleSrc = []byte(`
-hello:
- pop: 45000
- lagrenum: 7654321001234567
- universe:
- - mw
- - ad
-fu: bar
-`)
-
-func TestMergeConfig(t *testing.T) {
- v := New()
- v.SetConfigType("yml")
- if err := v.ReadConfig(bytes.NewBuffer(yamlMergeExampleTgt)); err != nil {
- t.Fatal(err)
- }
-
- if pop := v.GetInt("hello.pop"); pop != 37890 {
- t.Fatalf("pop != 37890, = %d", pop)
- }
-
- if pop := v.GetInt("hello.lagrenum"); pop != 765432101234567 {
- t.Fatalf("lagrenum != 765432101234567, = %d", pop)
- }
-
- if pop := v.GetInt64("hello.lagrenum"); pop != int64(765432101234567) {
- t.Fatalf("int64 lagrenum != 765432101234567, = %d", pop)
- }
-
- if world := v.GetStringSlice("hello.world"); len(world) != 4 {
- t.Fatalf("len(world) != 4, = %d", len(world))
- }
-
- if fu := v.GetString("fu"); fu != "" {
- t.Fatalf("fu != \"\", = %s", fu)
- }
-
- if err := v.MergeConfig(bytes.NewBuffer(yamlMergeExampleSrc)); err != nil {
- t.Fatal(err)
- }
-
- if pop := v.GetInt("hello.pop"); pop != 45000 {
- t.Fatalf("pop != 45000, = %d", pop)
- }
-
- if pop := v.GetInt("hello.lagrenum"); pop != 7654321001234567 {
- t.Fatalf("lagrenum != 7654321001234567, = %d", pop)
- }
-
- if pop := v.GetInt64("hello.lagrenum"); pop != int64(7654321001234567) {
- t.Fatalf("int64 lagrenum != 7654321001234567, = %d", pop)
- }
-
- if world := v.GetStringSlice("hello.world"); len(world) != 4 {
- t.Fatalf("len(world) != 4, = %d", len(world))
- }
-
- if universe := v.GetStringSlice("hello.universe"); len(universe) != 2 {
- t.Fatalf("len(universe) != 2, = %d", len(universe))
- }
-
- if fu := v.GetString("fu"); fu != "bar" {
- t.Fatalf("fu != \"bar\", = %s", fu)
- }
-}
-
-func TestMergeConfigNoMerge(t *testing.T) {
- v := New()
- v.SetConfigType("yml")
- if err := v.ReadConfig(bytes.NewBuffer(yamlMergeExampleTgt)); err != nil {
- t.Fatal(err)
- }
-
- if pop := v.GetInt("hello.pop"); pop != 37890 {
- t.Fatalf("pop != 37890, = %d", pop)
- }
-
- if world := v.GetStringSlice("hello.world"); len(world) != 4 {
- t.Fatalf("len(world) != 4, = %d", len(world))
- }
-
- if fu := v.GetString("fu"); fu != "" {
- t.Fatalf("fu != \"\", = %s", fu)
- }
-
- if err := v.ReadConfig(bytes.NewBuffer(yamlMergeExampleSrc)); err != nil {
- t.Fatal(err)
- }
-
- if pop := v.GetInt("hello.pop"); pop != 45000 {
- t.Fatalf("pop != 45000, = %d", pop)
- }
-
- if world := v.GetStringSlice("hello.world"); len(world) != 0 {
- t.Fatalf("len(world) != 0, = %d", len(world))
- }
-
- if universe := v.GetStringSlice("hello.universe"); len(universe) != 2 {
- t.Fatalf("len(universe) != 2, = %d", len(universe))
- }
-
- if fu := v.GetString("fu"); fu != "bar" {
- t.Fatalf("fu != \"bar\", = %s", fu)
- }
-}
-
-func TestUnmarshalingWithAliases(t *testing.T) {
- v := New()
- v.SetDefault("ID", 1)
- v.Set("name", "Steve")
- v.Set("lastname", "Owen")
-
- v.RegisterAlias("UserID", "ID")
- v.RegisterAlias("Firstname", "name")
- v.RegisterAlias("Surname", "lastname")
-
- type config struct {
- ID int
- FirstName string
- Surname string
- }
-
- var C config
- err := v.Unmarshal(&C)
- if err != nil {
- t.Fatalf("unable to decode into struct, %v", err)
- }
-
- assert.Equal(t, &config{ID: 1, FirstName: "Steve", Surname: "Owen"}, &C)
-}
-
-func TestSetConfigNameClearsFileCache(t *testing.T) {
- SetConfigFile("/tmp/config.yaml")
- SetConfigName("default")
- f, err := v.getConfigFile()
- if err == nil {
- t.Fatalf("config file cache should have been cleared")
- }
- assert.Empty(t, f)
-}
-
-func TestShadowedNestedValue(t *testing.T) {
-
- config := `name: steve
-clothing:
- jacket: leather
- trousers: denim
- pants:
- size: large
-`
- initConfig("yaml", config)
-
- assert.Equal(t, "steve", GetString("name"))
-
- polyester := "polyester"
- SetDefault("clothing.shirt", polyester)
- SetDefault("clothing.jacket.price", 100)
-
- assert.Equal(t, "leather", GetString("clothing.jacket"))
- assert.Nil(t, Get("clothing.jacket.price"))
- assert.Equal(t, polyester, GetString("clothing.shirt"))
-
- clothingSettings := AllSettings()["clothing"].(map[string]interface{})
- assert.Equal(t, "leather", clothingSettings["jacket"])
- assert.Equal(t, polyester, clothingSettings["shirt"])
-}
-
-func TestDotParameter(t *testing.T) {
- initJSON()
- // shoud take precedence over batters defined in jsonExample
- r := bytes.NewReader([]byte(`{ "batters.batter": [ { "type": "Small" } ] }`))
- unmarshalReader(r, v.config)
-
- actual := Get("batters.batter")
- expected := []interface{}{map[string]interface{}{"type": "Small"}}
- assert.Equal(t, expected, actual)
-}
-
-func TestCaseInsensitive(t *testing.T) {
- for _, config := range []struct {
- typ string
- content string
- }{
- {"yaml", `
-aBcD: 1
-eF:
- gH: 2
- iJk: 3
- Lm:
- nO: 4
- P:
- Q: 5
- R: 6
-`},
- {"json", `{
- "aBcD": 1,
- "eF": {
- "iJk": 3,
- "Lm": {
- "P": {
- "Q": 5,
- "R": 6
- },
- "nO": 4
- },
- "gH": 2
- }
-}`},
- {"toml", `aBcD = 1
-[eF]
-gH = 2
-iJk = 3
-[eF.Lm]
-nO = 4
-[eF.Lm.P]
-Q = 5
-R = 6
-`},
- } {
- doTestCaseInsensitive(t, config.typ, config.content)
- }
-}
-
-func TestCaseInsensitiveSet(t *testing.T) {
- Reset()
- m1 := map[string]interface{}{
- "Foo": 32,
- "Bar": map[interface{}]interface {
- }{
- "ABc": "A",
- "cDE": "B"},
- }
-
- m2 := map[string]interface{}{
- "Foo": 52,
- "Bar": map[interface{}]interface {
- }{
- "bCd": "A",
- "eFG": "B"},
- }
-
- Set("Given1", m1)
- Set("Number1", 42)
-
- SetDefault("Given2", m2)
- SetDefault("Number2", 52)
-
- // Verify SetDefault
- if v := Get("number2"); v != 52 {
- t.Fatalf("Expected 52 got %q", v)
- }
-
- if v := Get("given2.foo"); v != 52 {
- t.Fatalf("Expected 52 got %q", v)
- }
-
- if v := Get("given2.bar.bcd"); v != "A" {
- t.Fatalf("Expected A got %q", v)
- }
-
- if _, ok := m2["Foo"]; !ok {
- t.Fatal("Input map changed")
- }
-
- // Verify Set
- if v := Get("number1"); v != 42 {
- t.Fatalf("Expected 42 got %q", v)
- }
-
- if v := Get("given1.foo"); v != 32 {
- t.Fatalf("Expected 32 got %q", v)
- }
-
- if v := Get("given1.bar.abc"); v != "A" {
- t.Fatalf("Expected A got %q", v)
- }
-
- if _, ok := m1["Foo"]; !ok {
- t.Fatal("Input map changed")
- }
-}
-
-func TestParseNested(t *testing.T) {
- type duration struct {
- Delay time.Duration
- }
-
- type item struct {
- Name string
- Delay time.Duration
- Nested duration
- }
-
- config := `[[parent]]
- delay="100ms"
- [parent.nested]
- delay="200ms"
-`
- initConfig("toml", config)
-
- var items []item
- err := v.UnmarshalKey("parent", &items)
- if err != nil {
- t.Fatalf("unable to decode into struct, %v", err)
- }
-
- assert.Equal(t, 1, len(items))
- assert.Equal(t, 100*time.Millisecond, items[0].Delay)
- assert.Equal(t, 200*time.Millisecond, items[0].Nested.Delay)
-}
-
-func doTestCaseInsensitive(t *testing.T, typ, config string) {
- initConfig(typ, config)
- Set("RfD", true)
- assert.Equal(t, true, Get("rfd"))
- assert.Equal(t, true, Get("rFD"))
- assert.Equal(t, 1, cast.ToInt(Get("abcd")))
- assert.Equal(t, 1, cast.ToInt(Get("Abcd")))
- assert.Equal(t, 2, cast.ToInt(Get("ef.gh")))
- assert.Equal(t, 3, cast.ToInt(Get("ef.ijk")))
- assert.Equal(t, 4, cast.ToInt(Get("ef.lm.no")))
- assert.Equal(t, 5, cast.ToInt(Get("ef.lm.p.q")))
-
-}
-
-func BenchmarkGetBool(b *testing.B) {
- key := "BenchmarkGetBool"
- v = New()
- v.Set(key, true)
-
- for i := 0; i < b.N; i++ {
- if !v.GetBool(key) {
- b.Fatal("GetBool returned false")
- }
- }
-}
-
-func BenchmarkGet(b *testing.B) {
- key := "BenchmarkGet"
- v = New()
- v.Set(key, true)
-
- for i := 0; i < b.N; i++ {
- if !v.Get(key).(bool) {
- b.Fatal("Get returned false")
- }
- }
-}
-
-// This is the "perfect result" for the above.
-func BenchmarkGetBoolFromMap(b *testing.B) {
- m := make(map[string]bool)
- key := "BenchmarkGetBool"
- m[key] = true
-
- for i := 0; i < b.N; i++ {
- if !m[key] {
- b.Fatal("Map value was false")
- }
- }
-}
diff --git a/vendor/github.com/ssor/bom/.travis.yml b/vendor/github.com/ssor/bom/.travis.yml
deleted file mode 100644
index 6c7f48e..0000000
--- a/vendor/github.com/ssor/bom/.travis.yml
+++ /dev/null
@@ -1,14 +0,0 @@
-language: go
-go:
- - tip
- - 1.8
- - 1.7
- - 1.6
- - 1.5
- - 1.4
- - 1.3
- - 1.2
-notifications:
- email:
- on_success: change
- on_failure: always
diff --git a/vendor/github.com/ssor/bom/LICENSE b/vendor/github.com/ssor/bom/LICENSE
deleted file mode 100644
index 374f685..0000000
--- a/vendor/github.com/ssor/bom/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-MIT License
-
-Copyright (c) 2017 Asher
-
-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.
diff --git a/vendor/github.com/ssor/bom/README.md b/vendor/github.com/ssor/bom/README.md
deleted file mode 100644
index 2dcc289..0000000
--- a/vendor/github.com/ssor/bom/README.md
+++ /dev/null
@@ -1,23 +0,0 @@
-# bom
-small tools for cleaning bom from byte array or reader
-
-
-## Installation
-
-```sh
-$ go get github.com/ssor/bom
-```
-
-## How to Use
-
-
-```
- bs := []byte{bom0, bom1, bom2, 0x11}
- result := CleanBom(bs)
-```
-
-```
- bs := []byte{bom0, bom1, bom2, 0x11}
- result := NewReaderWithoutBom(bytes.NewReader(bs))
-
-```
\ No newline at end of file
diff --git a/vendor/github.com/ssor/bom/bom.go b/vendor/github.com/ssor/bom/bom.go
deleted file mode 100644
index 907ea98..0000000
--- a/vendor/github.com/ssor/bom/bom.go
+++ /dev/null
@@ -1,34 +0,0 @@
-package bom
-
-import (
- "bytes"
- "io"
- "io/ioutil"
-)
-
-const (
- bom0 = 0xef
- bom1 = 0xbb
- bom2 = 0xbf
-)
-
-// CleanBom returns b with the 3 byte BOM stripped off the front if it is present.
-// If the BOM is not present, then b is returned.
-func CleanBom(b []byte) []byte {
- if len(b) >= 3 &&
- b[0] == bom0 &&
- b[1] == bom1 &&
- b[2] == bom2 {
- return b[3:]
- }
- return b
-}
-
-// NewReaderWithoutBom returns an io.Reader that will skip over initial UTF-8 byte order marks.
-func NewReaderWithoutBom(r io.Reader) (io.Reader, error) {
- bs, err := ioutil.ReadAll(r)
- if err != nil {
- return nil, err
- }
- return bytes.NewReader(CleanBom(bs)), nil
-}
diff --git a/vendor/github.com/ssor/bom/bom_test.go b/vendor/github.com/ssor/bom/bom_test.go
deleted file mode 100644
index 0bc000b..0000000
--- a/vendor/github.com/ssor/bom/bom_test.go
+++ /dev/null
@@ -1,55 +0,0 @@
-package bom
-
-import (
- "bytes"
- "io/ioutil"
- "testing"
-)
-
-var (
- test_cases = []struct {
- src []byte
- expected []byte
- }{
- {
- []byte{bom0, bom1, bom2}, []byte{},
- },
- {
- []byte{0x33, bom0, bom1, bom2}, []byte{0x33, bom0, bom1, bom2},
- },
- {
- []byte{bom0, bom1}, []byte{bom0, bom1},
- },
- {
- []byte{bom0, bom2}, []byte{bom0, bom2},
- },
- {
- []byte{bom0, bom1, bom2, 0x11}, []byte{0x11},
- },
- }
-)
-
-func TestNewReaderWithoutBom(t *testing.T) {
- for index, test_case := range test_cases {
- result, err := NewReaderWithoutBom(bytes.NewReader(test_case.src))
- if err != nil {
- t.Fatal(err)
- }
- bs, err := ioutil.ReadAll(result)
- if err != nil {
- t.Fatal(err)
- }
- if bytes.Compare(bs, test_case.expected) != 0 {
- t.Fatalf("The %d th test_case failed", index)
- }
- }
-
-}
-func TestCleanBom(t *testing.T) {
- for index, test_case := range test_cases {
- result := CleanBom(test_case.src)
- if bytes.Compare(result, test_case.expected) != 0 {
- t.Fatalf("The %d th test_case failed", index)
- }
- }
-}
diff --git a/vendor/github.com/vanng822/css/.gitignore b/vendor/github.com/vanng822/css/.gitignore
deleted file mode 100644
index 580e4ae..0000000
--- a/vendor/github.com/vanng822/css/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-/src/
-/pkg/
-/bin/
diff --git a/vendor/github.com/vanng822/css/.travis.yml b/vendor/github.com/vanng822/css/.travis.yml
deleted file mode 100644
index 48059cb..0000000
--- a/vendor/github.com/vanng822/css/.travis.yml
+++ /dev/null
@@ -1,16 +0,0 @@
-language: golang
-
-go:
- - 1.4
-
-env:
- global:
- - GOPATH="$HOME/gopath"
- - PATH="$HOME/gopath/bin:$HOME/bin:$PATH"
-
-install:
- - go get github.com/gorilla/css/scanner
- - go get github.com/stretchr/testify/assert
-
-script:
- - go test -v
diff --git a/vendor/github.com/vanng822/css/LICENSE b/vendor/github.com/vanng822/css/LICENSE
deleted file mode 100644
index e6e86a6..0000000
--- a/vendor/github.com/vanng822/css/LICENSE
+++ /dev/null
@@ -1,23 +0,0 @@
-Copyright (c) 2015 Nguyen Van Nhu
-
-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.
-
diff --git a/vendor/github.com/vanng822/css/README.md b/vendor/github.com/vanng822/css/README.md
deleted file mode 100644
index a44caca..0000000
--- a/vendor/github.com/vanng822/css/README.md
+++ /dev/null
@@ -1,23 +0,0 @@
-# css
-
-Package css is for parsing css stylesheet.
-
-# Document
-
-[](https://godoc.org/github.com/vanng822/css)
-
-# example
-
- import (
- "github.com/vanng822/css"
- "fmt"
- )
- func main() {
- csstext = "td {width: 100px; height: 100px;}"
- ss := css.Parse(csstext)
- rules := ss.GetCSSRuleList()
- for _, rule := range rules {
- fmt.Println(rule.Style.SelectorText)
- fmt.Println(rule.Style.Styles)
- }
- }
\ No newline at end of file
diff --git a/vendor/github.com/vanng822/css/block_parser.go b/vendor/github.com/vanng822/css/block_parser.go
deleted file mode 100644
index 8a22e85..0000000
--- a/vendor/github.com/vanng822/css/block_parser.go
+++ /dev/null
@@ -1,140 +0,0 @@
-package css
-
-import (
- //"fmt"
- "github.com/gorilla/css/scanner"
- "strings"
-)
-
-type blockParserContext struct {
- State State
- NowProperty string
- NowValue string
- NowImportant int
-}
-
-// ParseBlock take a string of a css block,
-// parses it and returns a map of css style declarations.
-func ParseBlock(csstext string) map[string]*CSSStyleDeclaration {
- s := scanner.New(csstext)
- return parseBlock(s)
-}
-
-func parseBlock(s *scanner.Scanner) map[string]*CSSStyleDeclaration {
- /* block : '{' S* [ any | block | ATKEYWORD S* | ';' S* ]* '}' S*;
- property : IDENT;
- value : [ any | block | ATKEYWORD S* ]+;
- any : [ IDENT | NUMBER | PERCENTAGE | DIMENSION | STRING
- | DELIM | URI | HASH | UNICODE-RANGE | INCLUDES
- | DASHMATCH | ':' | FUNCTION S* [any|unused]* ')'
- | '(' S* [any|unused]* ')' | '[' S* [any|unused]* ']'
- ] S*;
- */
- decls := make(map[string]*CSSStyleDeclaration)
-
- context := &blockParserContext{
- State: STATE_NONE,
- NowProperty: "",
- NowValue: "",
- NowImportant: 0,
- }
-
- for {
- token := s.Next()
-
- //fmt.Printf("BLOCK(%d): %s:'%s'\n", context.State, token.Type.String(), token.Value)
-
- if token.Type == scanner.TokenError {
- break
- }
-
- if token.Type == scanner.TokenEOF {
- if context.State == STATE_VALUE {
- // we are ending without ; or }
- // this can happen when we parse only css declaration
- decl := NewCSSStyleDeclaration(context.NowProperty, strings.TrimSpace(context.NowValue), context.NowImportant)
- decls[context.NowProperty] = decl
- }
- break
- }
-
- switch token.Type {
-
- case scanner.TokenS:
- if context.State == STATE_VALUE {
- context.NowValue += token.Value
- }
- case scanner.TokenIdent:
- if context.State == STATE_NONE {
- context.State = STATE_PROPERTY
- context.NowProperty = strings.TrimSpace(token.Value)
- break
- }
- if token.Value == "important" {
- context.NowImportant = 1
- } else {
- context.NowValue += token.Value
- }
- case scanner.TokenChar:
- if context.State == STATE_NONE {
- if token.Value == "{" {
- break
- }
- }
- if context.State == STATE_PROPERTY {
- if token.Value == ":" {
- context.State = STATE_VALUE
- }
- // CHAR and STATE_PROPERTY but not : then weird
- // break to ignore it
- break
- }
- // should be no state or value
- if token.Value == ";" {
- decl := NewCSSStyleDeclaration(context.NowProperty, strings.TrimSpace(context.NowValue), context.NowImportant)
- decls[context.NowProperty] = decl
- context.NowProperty = ""
- context.NowValue = ""
- context.NowImportant = 0
- context.State = STATE_NONE
- } else if token.Value == "}" { // last property in a block can have optional ;
- if context.State == STATE_VALUE {
- // only valid if state is still VALUE, could be ;}
- decl := NewCSSStyleDeclaration(context.NowProperty, strings.TrimSpace(context.NowValue), context.NowImportant)
- decls[context.NowProperty] = decl
- }
- // we are done
- return decls
- } else if token.Value != "!" {
- context.NowValue += token.Value
- }
- break
-
- // any
- case scanner.TokenNumber:
- fallthrough
- case scanner.TokenPercentage:
- fallthrough
- case scanner.TokenDimension:
- fallthrough
- case scanner.TokenString:
- fallthrough
- case scanner.TokenURI:
- fallthrough
- case scanner.TokenHash:
- fallthrough
- case scanner.TokenUnicodeRange:
- fallthrough
- case scanner.TokenIncludes:
- fallthrough
- case scanner.TokenDashMatch:
- fallthrough
- case scanner.TokenFunction:
- fallthrough
- case scanner.TokenSubstringMatch:
- context.NowValue += token.Value
- }
- }
-
- return decls
-}
diff --git a/vendor/github.com/vanng822/css/block_parser_test.go b/vendor/github.com/vanng822/css/block_parser_test.go
deleted file mode 100644
index 516f89a..0000000
--- a/vendor/github.com/vanng822/css/block_parser_test.go
+++ /dev/null
@@ -1,50 +0,0 @@
-package css
-
-import (
- "github.com/stretchr/testify/assert"
- "testing"
- //"fmt"
-)
-
-func TestParseBlock(t *testing.T) {
- css := ParseBlock(`
- font-family: "Source Sans Pro", Arial, sans-serif;
- font-size: 27px;
- line-height: 35px;`)
-
- assert.Equal(t, len(css), 3)
- assert.Equal(t, "35px", css["line-height"].Value)
-}
-
-func TestParseBlockOneLine(t *testing.T) {
- css := ParseBlock("font-family: \"Source Sans Pro\", Arial, sans-serif; font-size: 27px;")
-
- assert.Equal(t, len(css), 2)
- assert.Equal(t, "27px", css["font-size"].Value)
- assert.Equal(t, "\"Source Sans Pro\", Arial, sans-serif", css["font-family"].Value)
-}
-
-func TestParseBlockBlankEnd(t *testing.T) {
- css := ParseBlock("font-size: 27px; width: 10px")
-
- assert.Equal(t, len(css), 2)
- assert.Equal(t, "27px", css["font-size"].Value)
- assert.Equal(t, "10px", css["width"].Value)
-}
-
-func TestParseBlockInportant(t *testing.T) {
- css := ParseBlock("font-size: 27px; width: 10px !important")
-
- assert.Equal(t, len(css), 2)
- assert.Equal(t, "27px", css["font-size"].Value)
- assert.Equal(t, "10px", css["width"].Value)
- assert.Equal(t, 1, css["width"].Important)
-}
-
-func TestParseBlockWithBraces(t *testing.T) {
- css := ParseBlock("{ font-size: 27px; width: 10px }")
-
- assert.Equal(t, len(css), 2)
- assert.Equal(t, "27px", css["font-size"].Value)
- assert.Equal(t, "10px", css["width"].Value)
-}
\ No newline at end of file
diff --git a/vendor/github.com/vanng822/css/charset_parser.go b/vendor/github.com/vanng822/css/charset_parser.go
deleted file mode 100644
index c2bee19..0000000
--- a/vendor/github.com/vanng822/css/charset_parser.go
+++ /dev/null
@@ -1,51 +0,0 @@
-package css
-
-import (
- //"fmt"
- "github.com/gorilla/css/scanner"
- "strings"
-)
-
-func newCharsetRule(statement string) *CSSRule {
- statement = strings.TrimSpace(statement)
- if statement != "" {
- rule := NewRule(CHARSET_RULE)
- rule.Style.SelectorText = statement
- return rule
- }
-
- return nil
-}
-
-func parseCharset(s *scanner.Scanner) *CSSRule {
- /*
-
- Syntax:
- @charset charset;
-
- Example:
- @charset "UTF-8";
-
- */
-
- var statement string
- for {
- token := s.Next()
-
- //fmt.Printf("Import: %s:'%s'\n", token.Type.String(), token.Value)
-
- if token.Type == scanner.TokenEOF || token.Type == scanner.TokenError {
- return nil
- }
- // take everything for now
- switch token.Type {
- case scanner.TokenChar:
- if token.Value == ";" {
- return newCharsetRule(statement)
- }
- statement += token.Value
- default:
- statement += token.Value
- }
- }
-}
diff --git a/vendor/github.com/vanng822/css/charset_parser_test.go b/vendor/github.com/vanng822/css/charset_parser_test.go
deleted file mode 100644
index 2ed1a25..0000000
--- a/vendor/github.com/vanng822/css/charset_parser_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-package css
-
-import (
- "github.com/gorilla/css/scanner"
- "github.com/stretchr/testify/assert"
- "testing"
-)
-
-func TestCharsetDoubleQ(t *testing.T) {
- css := Parse(`@charset "UTF-8";`)
-
- assert.Equal(t, css.CssRuleList[0].Style.SelectorText, "\"UTF-8\"")
- assert.Equal(t, css.CssRuleList[0].Type, CHARSET_RULE)
-}
-
-func TestCharsetSingleQ(t *testing.T) {
- css := Parse(`@charset 'iso-8859-15';`)
-
- assert.Equal(t, css.CssRuleList[0].Style.SelectorText, "'iso-8859-15'")
- assert.Equal(t, css.CssRuleList[0].Type, CHARSET_RULE)
-}
-
-func TestCharsetIgnore(t *testing.T) {
- css := parseCharset(scanner.New(` 'iso-8859-15'`))
-
- assert.Nil(t, css)
-}
diff --git a/vendor/github.com/vanng822/css/doc.go b/vendor/github.com/vanng822/css/doc.go
deleted file mode 100644
index 9d3f663..0000000
--- a/vendor/github.com/vanng822/css/doc.go
+++ /dev/null
@@ -1,16 +0,0 @@
-// Package css is for parsing css stylesheet.
-//
-// import (
-// "github.com/vanng822/css"
-// "fmt"
-// )
-// func main() {
-// csstext = "td {width: 100px; height: 100px;}"
-// ss := css.Parse(csstext)
-// rules := ss.GetCSSRuleList()
-// for _, rule := range rules {
-// fmt.Println(rule.Style.SelectorText)
-// fmt.Println(rule.Style.Styles)
-// }
-// }
-package css
\ No newline at end of file
diff --git a/vendor/github.com/vanng822/css/import_parser.go b/vendor/github.com/vanng822/css/import_parser.go
deleted file mode 100644
index 0549d45..0000000
--- a/vendor/github.com/vanng822/css/import_parser.go
+++ /dev/null
@@ -1,56 +0,0 @@
-package css
-
-import (
- //"fmt"
- "github.com/gorilla/css/scanner"
- "strings"
-)
-
-func newImportRule(statement string) *CSSRule {
- statement = strings.TrimSpace(statement)
- if statement != "" {
- rule := NewRule(IMPORT_RULE)
- rule.Style.SelectorText = statement
- return rule
- }
-
- return nil
-}
-
-func parseImport(s *scanner.Scanner) *CSSRule {
- /*
- Syntax:
- @import url; or
- @import url list-of-media-queries;
-
- Example:
- @import url("fineprint.css") print;
- @import url("bluish.css") projection, tv;
- @import 'custom.css';
- @import url("chrome://communicator/skin/");
- @import "common.css" screen, projection;
- @import url('landscape.css') screen and (orientation:landscape);
-
- */
-
- var statement string
- for {
- token := s.Next()
-
- //fmt.Printf("Import: %s:'%s'\n", token.Type.String(), token.Value)
-
- if token.Type == scanner.TokenEOF || token.Type == scanner.TokenError {
- return nil
- }
- // take everything for now
- switch token.Type {
- case scanner.TokenChar:
- if token.Value == ";" {
- return newImportRule(statement)
- }
- statement += token.Value
- default:
- statement += token.Value
- }
- }
-}
diff --git a/vendor/github.com/vanng822/css/import_parser_test.go b/vendor/github.com/vanng822/css/import_parser_test.go
deleted file mode 100644
index 70753b5..0000000
--- a/vendor/github.com/vanng822/css/import_parser_test.go
+++ /dev/null
@@ -1,35 +0,0 @@
-package css
-
-import (
- "github.com/gorilla/css/scanner"
- "github.com/stretchr/testify/assert"
- "testing"
-)
-
-func TestImport(t *testing.T) {
- css := Parse(`@import url("fineprint.css") print;
- @import url("bluish.css") projection, tv;
- @import 'custom.css';
- @import url("chrome://communicator/skin/");
- @import "common.css" screen, projection;
- @import url('landscape.css') screen and (orientation:landscape);`)
-
- assert.Equal(t, css.CssRuleList[0].Style.SelectorText, "url(\"fineprint.css\") print")
- assert.Equal(t, css.CssRuleList[1].Style.SelectorText, "url(\"bluish.css\") projection, tv")
- assert.Equal(t, css.CssRuleList[2].Style.SelectorText, "'custom.css'")
- assert.Equal(t, css.CssRuleList[3].Style.SelectorText, "url(\"chrome://communicator/skin/\")")
- assert.Equal(t, css.CssRuleList[4].Style.SelectorText, "\"common.css\" screen, projection")
- assert.Equal(t, css.CssRuleList[5].Style.SelectorText, "url('landscape.css') screen and (orientation:landscape)")
-
- assert.Equal(t, css.CssRuleList[0].Type, IMPORT_RULE)
- assert.Equal(t, css.CssRuleList[1].Type, IMPORT_RULE)
- assert.Equal(t, css.CssRuleList[2].Type, IMPORT_RULE)
- assert.Equal(t, css.CssRuleList[3].Type, IMPORT_RULE)
- assert.Equal(t, css.CssRuleList[4].Type, IMPORT_RULE)
- assert.Equal(t, css.CssRuleList[5].Type, IMPORT_RULE)
-}
-
-func TestImportIgnore(t *testing.T) {
- css := parseImport(scanner.New(` url("fineprint.css") print`))
- assert.Nil(t, css)
-}
diff --git a/vendor/github.com/vanng822/css/parser.go b/vendor/github.com/vanng822/css/parser.go
deleted file mode 100644
index a609120..0000000
--- a/vendor/github.com/vanng822/css/parser.go
+++ /dev/null
@@ -1,154 +0,0 @@
-package css
-
-import (
- "fmt"
- "github.com/gorilla/css/scanner"
- "strings"
-)
-
-/*
- stylesheet : [ CDO | CDC | S | statement ]*;
- statement : ruleset | at-rule;
- at-rule : ATKEYWORD S* any* [ block | ';' S* ];
- block : '{' S* [ any | block | ATKEYWORD S* | ';' S* ]* '}' S*;
- ruleset : selector? '{' S* declaration? [ ';' S* declaration? ]* '}' S*;
- selector : any+;
- declaration : property S* ':' S* value;
- property : IDENT;
- value : [ any | block | ATKEYWORD S* ]+;
- any : [ IDENT | NUMBER | PERCENTAGE | DIMENSION | STRING
- | DELIM | URI | HASH | UNICODE-RANGE | INCLUDES
- | DASHMATCH | ':' | FUNCTION S* [any|unused]* ')'
- | '(' S* [any|unused]* ')' | '[' S* [any|unused]* ']'
- ] S*;
- unused : block | ATKEYWORD S* | ';' S* | CDO S* | CDC S*;
-*/
-
-type State int
-
-const (
- STATE_NONE State = iota
- STATE_SELECTOR
- STATE_PROPERTY
- STATE_VALUE
-)
-
-type parserContext struct {
- State State
- NowSelectorText string
- NowRuleType RuleType
- CurrentRule *CSSRule
- CurrentMediaRule *CSSRule
-}
-
-func resetContextStyleRule(context *parserContext) {
- context.CurrentRule = nil
- context.NowSelectorText = ""
- context.NowRuleType = STYLE_RULE
- context.State = STATE_NONE
-}
-
-func parseRule(context *parserContext, s *scanner.Scanner, css *CSSStyleSheet) {
- context.CurrentRule = NewRule(context.NowRuleType)
- context.NowSelectorText += parseSelector(s)
- context.CurrentRule.Style.SelectorText = strings.TrimSpace(context.NowSelectorText)
- context.CurrentRule.Style.Styles = parseBlock(s)
- if context.CurrentMediaRule != nil {
- context.CurrentMediaRule.Rules = append(context.CurrentMediaRule.Rules, context.CurrentRule)
- } else {
- css.CssRuleList = append(css.CssRuleList, context.CurrentRule)
- }
-}
-
-// Parse takes a string of valid css rules, stylesheet,
-// and parses it. Be aware this function has poor error handling
-// so you should have valid syntax in your css
-func Parse(csstext string) *CSSStyleSheet {
- context := &parserContext{
- State: STATE_NONE,
- NowSelectorText: "",
- NowRuleType: STYLE_RULE,
- CurrentMediaRule: nil,
- }
-
- css := &CSSStyleSheet{}
- css.CssRuleList = make([]*CSSRule, 0)
- s := scanner.New(csstext)
-
- for {
- token := s.Next()
-
- //fmt.Printf("Parse(%d): %s:'%s'\n", context.State, token.Type.String(), token.Value)
-
- if token.Type == scanner.TokenEOF || token.Type == scanner.TokenError {
- break
- }
-
- switch token.Type {
- case scanner.TokenCDO:
- break
- case scanner.TokenCDC:
- break
- case scanner.TokenComment:
- break
- case scanner.TokenS:
- break
- case scanner.TokenAtKeyword:
- switch token.Value {
- case "@media":
- context.NowRuleType = MEDIA_RULE
- case "@font-face":
- // Parse as normal rule, would be nice to parse according to syntax
- // https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face
- context.NowRuleType = FONT_FACE_RULE
- parseRule(context, s, css)
- resetContextStyleRule(context)
- case "@import":
- // No validation
- // https://developer.mozilla.org/en-US/docs/Web/CSS/@import
- rule := parseImport(s)
- if rule != nil {
- css.CssRuleList = append(css.CssRuleList, rule)
- }
- resetContextStyleRule(context)
- case "@charset":
- // No validation
- // https://developer.mozilla.org/en-US/docs/Web/CSS/@charset
- rule := parseCharset(s)
- if rule != nil {
- css.CssRuleList = append(css.CssRuleList, rule)
- }
- resetContextStyleRule(context)
-
- case "@page":
- context.NowRuleType = PAGE_RULE
- parseRule(context, s, css)
- resetContextStyleRule(context)
- default:
- panic(fmt.Sprintf("At rule '%s' is not supported", token.Value))
- }
- default:
- if context.State == STATE_NONE {
- if token.Value == "}" && context.CurrentMediaRule != nil {
- // close media rule
- css.CssRuleList = append(css.CssRuleList, context.CurrentMediaRule)
- context.CurrentMediaRule = nil
- break
- }
- }
-
- if context.NowRuleType == MEDIA_RULE {
- context.CurrentMediaRule = NewRule(context.NowRuleType)
- context.CurrentMediaRule.Style.SelectorText = strings.TrimSpace(token.Value + parseSelector(s))
- resetContextStyleRule(context)
- break
- } else {
- context.NowSelectorText += token.Value
- parseRule(context, s, css)
- resetContextStyleRule(context)
- break
- }
- }
- }
- return css
-}
diff --git a/vendor/github.com/vanng822/css/parser_media_test.go b/vendor/github.com/vanng822/css/parser_media_test.go
deleted file mode 100644
index 72f3401..0000000
--- a/vendor/github.com/vanng822/css/parser_media_test.go
+++ /dev/null
@@ -1,103 +0,0 @@
-package css
-
-import (
- //"fmt"
- "github.com/stretchr/testify/assert"
- "testing"
-)
-
-func TestMedia(t *testing.T) {
- css := Parse(`@media only screen and (max-width: 600px) {
- table[class="body"] img {
- width: auto !important;
- height: auto !important
- }
- table[class="body"] center {
- min-width: 0 !important
- }
- table[class="body"] .container {
- width: 95% !important
- }
- table[class="body"] .row {
- width: 100% !important;
- display: block !important
- }
- }`)
-
- //fmt.Println(css)
- assert.Equal(t, css.CssRuleList[0].Style.SelectorText, "only screen and (max-width: 600px)")
- assert.Equal(t, css.CssRuleList[0].Type, MEDIA_RULE)
- assert.Equal(t, len(css.CssRuleList[0].Rules), 4)
- assert.Equal(t, css.CssRuleList[0].Rules[0].Style.SelectorText, "table[class=\"body\"] img")
- assert.Equal(t, css.CssRuleList[0].Rules[0].Style.Styles["height"].Value, "auto")
- assert.Equal(t, css.CssRuleList[0].Rules[0].Style.Styles["height"].Important, 1)
- assert.Equal(t, css.CssRuleList[0].Rules[1].Style.SelectorText, "table[class=\"body\"] center")
- assert.Equal(t, css.CssRuleList[0].Rules[2].Style.SelectorText, "table[class=\"body\"] .container")
- assert.Equal(t, css.CssRuleList[0].Rules[3].Style.SelectorText, "table[class=\"body\"] .row")
-
-}
-
-func TestMediaMulti(t *testing.T) {
- css := Parse(`
- table.one {
- width: 30px;
- }
- @media only screen and (max-width: 600px) {
- table[class="body"] img {
- width: auto !important;
- height: auto !important
- }
- table[class="body"] center {
- min-width: 0 !important
- }
- table[class="body"] .container {
- width: 95% !important
- }
- table[class="body"] .row {
- width: 100% !important;
- display: block !important
- }
- }
- @media all and (min-width: 48em) {
- blockquote {
- font-size: 34px;
- line-height: 40px;
- padding-top: 2px;
- padding-bottom: 3px;
- }
- }
- table.two {
- width: 80px;
- }`)
-
- assert.Equal(t, len(css.CssRuleList), 4)
-
- assert.Equal(t, css.CssRuleList[0].Style.SelectorText, "table.one")
- assert.Equal(t, css.CssRuleList[0].Type, STYLE_RULE)
- assert.Equal(t, css.CssRuleList[0].Style.Styles["width"].Value, "30px")
- assert.Equal(t, len(css.CssRuleList[0].Rules), 0)
-
- assert.Equal(t, css.CssRuleList[1].Style.SelectorText, "only screen and (max-width: 600px)")
- assert.Equal(t, css.CssRuleList[1].Type, MEDIA_RULE)
- assert.Equal(t, len(css.CssRuleList[1].Rules), 4)
- assert.Equal(t, css.CssRuleList[1].Rules[0].Style.SelectorText, "table[class=\"body\"] img")
- assert.Equal(t, css.CssRuleList[1].Rules[0].Style.Styles["height"].Value, "auto")
- assert.Equal(t, css.CssRuleList[1].Rules[0].Style.Styles["height"].Important, 1)
- assert.Equal(t, css.CssRuleList[1].Rules[1].Style.SelectorText, "table[class=\"body\"] center")
- assert.Equal(t, css.CssRuleList[1].Rules[2].Style.SelectorText, "table[class=\"body\"] .container")
- assert.Equal(t, css.CssRuleList[1].Rules[3].Style.SelectorText, "table[class=\"body\"] .row")
-
- assert.Equal(t, css.CssRuleList[2].Style.SelectorText, "all and (min-width: 48em)")
- assert.Equal(t, css.CssRuleList[2].Type, MEDIA_RULE)
- assert.Equal(t, css.CssRuleList[2].Rules[0].Style.SelectorText, "blockquote")
- assert.Equal(t, css.CssRuleList[2].Rules[0].Style.Styles["font-size"].Value, "34px")
- assert.Equal(t, css.CssRuleList[2].Rules[0].Style.Styles["line-height"].Value, "40px")
- assert.Equal(t, css.CssRuleList[2].Rules[0].Style.Styles["padding-top"].Value, "2px")
- assert.Equal(t, css.CssRuleList[2].Rules[0].Style.Styles["padding-bottom"].Value, "3px")
- assert.Equal(t, len(css.CssRuleList[2].Rules), 1)
-
- assert.Equal(t, css.CssRuleList[3].Style.SelectorText, "table.two")
- assert.Equal(t, css.CssRuleList[3].Type, STYLE_RULE)
- assert.Equal(t, css.CssRuleList[3].Style.Styles["width"].Value, "80px")
- assert.Equal(t, len(css.CssRuleList[3].Rules), 0)
-}
diff --git a/vendor/github.com/vanng822/css/parser_selector_test.go b/vendor/github.com/vanng822/css/parser_selector_test.go
deleted file mode 100644
index 054fa1e..0000000
--- a/vendor/github.com/vanng822/css/parser_selector_test.go
+++ /dev/null
@@ -1,175 +0,0 @@
-package css
-
-import (
- "fmt"
- "github.com/stretchr/testify/assert"
- "testing"
-)
-
-func TestMultipleSelectors(t *testing.T) {
- css := Parse(`div .a {
- font-size: 150%;
- }
- p .b {
- font-size: 250%;
- }`)
-
- assert.Equal(t, css.CssRuleList[0].Style.SelectorText, "div .a")
- assert.Equal(t, css.CssRuleList[1].Style.SelectorText, "p .b")
-
-}
-
-func TestIdSelector(t *testing.T) {
- css := Parse("#div { color: red;}")
-
- assert.Equal(t, css.CssRuleList[0].Style.Styles["color"].Value, "red")
- assert.Equal(t, css.CssRuleList[0].Style.SelectorText, "#div")
-}
-
-func TestClassSelector(t *testing.T) {
- css := Parse(".div { color: green;}")
-
- assert.Equal(t, css.CssRuleList[0].Style.Styles["color"].Value, "green")
- assert.Equal(t, css.CssRuleList[0].Style.SelectorText, ".div")
-}
-
-func TestStarSelector(t *testing.T) {
- css := Parse("* { text-rendering: optimizelegibility; }")
-
- assert.Equal(t, "optimizelegibility", css.CssRuleList[0].Style.Styles["text-rendering"].Value)
- assert.Equal(t, css.CssRuleList[0].Style.SelectorText, "*")
-}
-
-func TestStarSelectorMulti(t *testing.T) {
- css := Parse(`div .a {
- font-size: 150%;
- }
- * { text-rendering: optimizelegibility; }`)
-
- assert.Equal(t, "150%", css.CssRuleList[0].Style.Styles["font-size"].Value)
- assert.Equal(t, css.CssRuleList[0].Style.SelectorText, "div .a")
-
- assert.Equal(t, "optimizelegibility", css.CssRuleList[1].Style.Styles["text-rendering"].Value)
- assert.Equal(t, css.CssRuleList[1].Style.SelectorText, "*")
-}
-
-func TestMixedClassSelectors(t *testing.T) {
- selectors := []string{".footer__content_wrapper--last",
- "table[class=\"body\"] .footer__content td",
- "table[class=\"body\"] td.footer__link_wrapper--first",
- "table[class=\"body\"] td.footer__link_wrapper--last"}
-
- for _, selector := range selectors {
- css := Parse(fmt.Sprintf(` %s {
- border-collapse: separate;
- padding: 10px 0 0
- }`, selector))
-
- assert.Equal(t, "separate", css.CssRuleList[0].Style.Styles["border-collapse"].Value)
- assert.Equal(t, "10px 0 0", css.CssRuleList[0].Style.Styles["padding"].Value)
- assert.Equal(t, css.CssRuleList[0].Style.SelectorText, selector)
- }
-}
-
-func TestGenericSelectors(t *testing.T) {
- selectors := []string{
- "p ~ ul",
- "div > p",
- "div > p",
- "div p",
- "div, p",
- "[target]",
- "[target=_blank]",
- "[title~=flower]",
- "[lang|=en]",
- "a[href^=\"https\"]",
- "a[href$=\".pdf\"]",
- "a[href*=\"css\"]",
- ".header + .content",
- "#firstname",
- "table[class=\"body\"] .footer__content td",
- "table[class=\"body\"] td.footer__link_wrapper--first"}
-
- for _, selector := range selectors {
- css := Parse(fmt.Sprintf(` %s {
- border-collapse: separate;
- padding: 10px 0 0
- }`, selector))
-
- assert.Equal(t, "separate", css.CssRuleList[0].Style.Styles["border-collapse"].Value)
- assert.Equal(t, "10px 0 0", css.CssRuleList[0].Style.Styles["padding"].Value)
- assert.Equal(t, css.CssRuleList[0].Style.SelectorText, selector)
- }
-}
-
-func TestFilterSelectors(t *testing.T) {
- selectors := []string{
- "a:active",
- "p::after",
- "p::before",
- "input:checked",
- "input:disabled",
- "input:in-range",
- "input:invalid",
- "input:optional",
- "input:read-only",
- "input:enabled",
- "p:empty",
- "p:first-child",
- "p::first-letter",
- "p::first-line",
- "p:first-of-type",
- "input:focus",
- "a:hover",
- "p:lang(it)",
- "p:last-child",
- "p:last-of-type",
- "a:link",
- ":not(p)",
- "p:nth-child(2)",
- "p:nth-last-child(2)",
- "p:only-of-type",
- "p:only-child",
- "p:nth-last-of-type(2)",
- "div:not(:nth-child(1))",
- "div:not(:not(:first-child))",
- ":root",
- "::selection",
- "#news:target"}
-
- for _, selector := range selectors {
- css := Parse(fmt.Sprintf(` %s {
- border-collapse: separate;
- padding: 10px 0 0
- }`, selector))
-
- assert.Equal(t, "separate", css.CssRuleList[0].Style.Styles["border-collapse"].Value)
- assert.Equal(t, "10px 0 0", css.CssRuleList[0].Style.Styles["padding"].Value)
- assert.Equal(t, css.CssRuleList[0].Style.SelectorText, selector)
- }
-}
-
-func TestFontFace(t *testing.T) {
- css := Parse(`@font-face {
- font-family: "Bitstream Vera Serif Bold";
- src: url("https://mdn.mozillademos.org/files/2468/VeraSeBd.ttf");
- }
-
- body { font-family: "Bitstream Vera Serif Bold", serif }`)
-
- assert.Equal(t, css.CssRuleList[0].Style.SelectorText, "")
- assert.Equal(t, css.CssRuleList[0].Style.Styles["font-family"].Value, "\"Bitstream Vera Serif Bold\"")
- assert.Equal(t, css.CssRuleList[0].Style.Styles["src"].Value, "url(\"https://mdn.mozillademos.org/files/2468/VeraSeBd.ttf\")")
- assert.Equal(t, css.CssRuleList[1].Style.Styles["font-family"].Value, "\"Bitstream Vera Serif Bold\", serif")
- assert.Equal(t, css.CssRuleList[0].Type, FONT_FACE_RULE)
-}
-
-func TestPage(t *testing.T) {
- css := Parse(`@page :first {
- margin: 2in 3in;
- }`)
-
- assert.Equal(t, css.CssRuleList[0].Style.SelectorText, ":first")
- assert.Equal(t, css.CssRuleList[0].Style.Styles["margin"].Value, "2in 3in")
- assert.Equal(t, css.CssRuleList[0].Type, PAGE_RULE)
-}
diff --git a/vendor/github.com/vanng822/css/parser_test.go b/vendor/github.com/vanng822/css/parser_test.go
deleted file mode 100644
index 4088c59..0000000
--- a/vendor/github.com/vanng822/css/parser_test.go
+++ /dev/null
@@ -1,148 +0,0 @@
-package css
-
-import (
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-func TestWithoutImpotant(t *testing.T) {
- css := Parse(`div .a { font-size: 150%;}`)
- assert.Equal(t, css.CssRuleList[0].Style.Styles["font-size"].Value, "150%")
- assert.Equal(t, css.CssRuleList[0].Style.Styles["font-size"].Property, "font-size")
- assert.Equal(t, css.CssRuleList[0].Style.Styles["font-size"].Important, 0)
- assert.Equal(t, css.CssRuleList[0].Style.SelectorText, "div .a")
-
-}
-
-func TestWithImpotant(t *testing.T) {
- css := Parse("div .a { font-size: 150% !important;}")
- assert.Equal(t, css.CssRuleList[0].Style.Styles["font-size"].Value, "150%")
- assert.Equal(t, css.CssRuleList[0].Style.Styles["font-size"].Property, "font-size")
- assert.Equal(t, css.CssRuleList[0].Style.Styles["font-size"].Important, 1)
- assert.Equal(t, css.CssRuleList[0].Style.SelectorText, "div .a")
-}
-
-func TestMultipleDeclarations(t *testing.T) {
- css := Parse(`div .a {
- font-size: 150%;
- width: 100%
- }`)
- assert.Equal(t, css.CssRuleList[0].Style.Styles["font-size"].Value, "150%")
- assert.Equal(t, css.CssRuleList[0].Style.Styles["font-size"].Property, "font-size")
- assert.Equal(t, css.CssRuleList[0].Style.Styles["font-size"].Important, 0)
- assert.Equal(t, css.CssRuleList[0].Style.Styles["width"].Value, "100%")
- assert.Equal(t, css.CssRuleList[0].Style.Styles["width"].Property, "width")
- assert.Equal(t, css.CssRuleList[0].Style.Styles["width"].Important, 0)
- assert.Equal(t, css.CssRuleList[0].Style.SelectorText, "div .a")
-}
-
-func TestValuePx(t *testing.T) {
- css := Parse("div .a { font-size: 45px;}")
- assert.Equal(t, css.CssRuleList[0].Style.Styles["font-size"].Value, "45px")
-}
-
-func TestValueEm(t *testing.T) {
- css := Parse("div .a { font-size: 45em;}")
- assert.Equal(t, css.CssRuleList[0].Style.Styles["font-size"].Value, "45em")
-}
-
-func TestValueHex(t *testing.T) {
- css := Parse("div .a { color: #123456;}")
- assert.Equal(t, css.CssRuleList[0].Style.Styles["color"].Value, "#123456")
-}
-
-func TestValueRGBFunction(t *testing.T) {
- css := Parse(".color{ color: rgb(1,2,3);}")
-
- assert.Equal(t, css.CssRuleList[0].Style.Styles["color"].Value, "rgb(1,2,3)")
- assert.Equal(t, css.CssRuleList[0].Style.SelectorText, ".color")
-}
-
-func TestValueString(t *testing.T) {
- css := Parse("div .center { text-align: center; }")
-
- assert.Equal(t, css.CssRuleList[0].Style.Styles["text-align"].Value, "center")
-}
-
-func TestValueWhiteSpace(t *testing.T) {
- css := Parse(".div { padding: 10px 0 0 10px}")
-
- assert.Equal(t, "10px 0 0 10px", css.CssRuleList[0].Style.Styles["padding"].Value)
- assert.Equal(t, css.CssRuleList[0].Style.SelectorText, ".div")
-}
-
-func TestValueMixed(t *testing.T) {
- css := Parse(`td {
- padding: 0 12px 0 10px;
- border-right: 1px solid white
- }`)
-
- assert.Equal(t, "0 12px 0 10px", css.CssRuleList[0].Style.Styles["padding"].Value)
- assert.Equal(t, "1px solid white", css.CssRuleList[0].Style.Styles["border-right"].Value)
- assert.Equal(t, css.CssRuleList[0].Style.SelectorText, "td")
-}
-
-func TestQuoteValue(t *testing.T) {
- css := Parse(`blockquote {
- font-family: "Source Sans Pro", Arial, sans-serif;
- font-size: 27px;
- line-height: 35px;}`)
-
- assert.Equal(t, "\"Source Sans Pro\", Arial, sans-serif", css.CssRuleList[0].Style.Styles["font-family"].Value)
- assert.Equal(t, "27px", css.CssRuleList[0].Style.Styles["font-size"].Value)
- assert.Equal(t, "35px", css.CssRuleList[0].Style.Styles["line-height"].Value)
- assert.Equal(t, css.CssRuleList[0].Style.SelectorText, "blockquote")
-}
-
-func TestDashClassname(t *testing.T) {
- css := Parse(`.content {
- padding: 0px;
- }
- .content-wrap {
- padding: 2px;
- }`)
-
- assert.Equal(t, ".content", css.CssRuleList[0].Style.SelectorText)
- assert.Equal(t, ".content-wrap", css.CssRuleList[1].Style.SelectorText)
- assert.Equal(t, "0px", css.CssRuleList[0].Style.Styles["padding"].Value)
- assert.Equal(t, "2px", css.CssRuleList[1].Style.Styles["padding"].Value)
-}
-
-func TestNotSupportedAtRule(t *testing.T) {
- rules := []string{
- `@keyframes mymove {
- 0% {top: 0px;}
- 25% {top: 200px;}
- 50% {top: 100px;}
- 75% {top: 200px;}
- 100% {top: 0px;}
- }`,
- `@-webkit-keyframes mymove {
- 0% {top: 0px;}
- 25% {top: 200px;}
- 50% {top: 100px;}
- 75% {top: 200px;}
- 100% {top: 0px;}
- } `,
- `@counter-style winners-list {
- system: fixed;
- symbols: url(gold-medal.svg) url(silver-medal.svg) url(bronze-medal.svg);
- suffix: " ";
- }`,
- `@namespace url(http://www.w3.org/1999/xhtml);`,
- `@document url(http://www.w3.org/),
- url-prefix(http://www.w3.org/Style/),
- domain(mozilla.org),
- regexp("https:.*")
- {
-
- body { color: purple; background: yellow; }
- }`,
- }
- for _, rule := range rules {
- assert.Panics(t, func() {
- Parse(rule)
- })
- }
-}
diff --git a/vendor/github.com/vanng822/css/rule.go b/vendor/github.com/vanng822/css/rule.go
deleted file mode 100644
index 36d8589..0000000
--- a/vendor/github.com/vanng822/css/rule.go
+++ /dev/null
@@ -1,43 +0,0 @@
-package css
-
-import ()
-
-type RuleType int
-
-const (
- STYLE_RULE RuleType = iota
- CHARSET_RULE
- IMPORT_RULE
- MEDIA_RULE
- FONT_FACE_RULE
- PAGE_RULE
-
-)
-
-var ruleTypeNames = map[RuleType]string{
- STYLE_RULE: "",
- MEDIA_RULE: "@media",
- CHARSET_RULE: "@charset",
- IMPORT_RULE: "@import",
- FONT_FACE_RULE: "@font-face",
- PAGE_RULE: "@page",
-}
-
-func (rt RuleType) Text() string {
- return ruleTypeNames[rt]
-}
-
-type CSSRule struct {
- Type RuleType
- Style CSSStyleRule
- Rules []*CSSRule
-}
-
-func NewRule(ruleType RuleType) *CSSRule {
- r := &CSSRule{
- Type: ruleType,
- }
- r.Style.Styles = make(map[string]*CSSStyleDeclaration)
- r.Rules = make([]*CSSRule, 0)
- return r
-}
diff --git a/vendor/github.com/vanng822/css/rule_test.go b/vendor/github.com/vanng822/css/rule_test.go
deleted file mode 100644
index edc839d..0000000
--- a/vendor/github.com/vanng822/css/rule_test.go
+++ /dev/null
@@ -1,16 +0,0 @@
-package css
-
-import (
- "github.com/stretchr/testify/assert"
- "testing"
-)
-
-func TestRuleTypeString(t *testing.T) {
- assert.Equal(t, STYLE_RULE.Text(), "")
- assert.Equal(t, CHARSET_RULE.Text(), "@charset")
- assert.Equal(t, IMPORT_RULE.Text(), "@import")
- assert.Equal(t, MEDIA_RULE.Text(), "@media")
- assert.Equal(t, FONT_FACE_RULE.Text(), "@font-face")
- assert.Equal(t, PAGE_RULE.Text(), "@page")
-}
-
diff --git a/vendor/github.com/vanng822/css/selector_parser.go b/vendor/github.com/vanng822/css/selector_parser.go
deleted file mode 100644
index d47afed..0000000
--- a/vendor/github.com/vanng822/css/selector_parser.go
+++ /dev/null
@@ -1,69 +0,0 @@
-package css
-
-import (
- //"fmt"
- "github.com/gorilla/css/scanner"
-)
-
-func parseSelector(s *scanner.Scanner) string {
- /*
- selector : any+;
- any : [ IDENT | NUMBER | PERCENTAGE | DIMENSION | STRING
- | DELIM | URI | HASH | UNICODE-RANGE | INCLUDES
- | DASHMATCH | ':' | FUNCTION S* [any|unused]* ')'
- | '(' S* [any|unused]* ')' | '[' S* [any|unused]* ']'
- ] S*;
- */
-
- selector := ""
-
- for {
- token := s.Next()
-
- //fmt.Printf("SELECTOR: %s:'%s'\n", token.Type.String(), token.Value)
-
- if token.Type == scanner.TokenError || token.Type == scanner.TokenEOF {
- break
- }
-
- switch token.Type {
- case scanner.TokenChar:
- if token.Value == "{" {
- return selector
- }
- fallthrough
- case scanner.TokenIdent:
- fallthrough
- case scanner.TokenS:
- fallthrough
- case scanner.TokenNumber:
- fallthrough
- case scanner.TokenPercentage:
- fallthrough
- case scanner.TokenDimension:
- fallthrough
- case scanner.TokenString:
- fallthrough
- case scanner.TokenURI:
- fallthrough
- case scanner.TokenHash:
- fallthrough
- case scanner.TokenUnicodeRange:
- fallthrough
- case scanner.TokenIncludes:
- fallthrough
- case scanner.TokenDashMatch:
- fallthrough
- case scanner.TokenFunction:
- fallthrough
- case scanner.TokenSuffixMatch:
- fallthrough
- case scanner.TokenPrefixMatch:
- fallthrough
- case scanner.TokenSubstringMatch:
- selector += token.Value
- }
- }
-
- return selector
-}
diff --git a/vendor/github.com/vanng822/css/styledeclaration.go b/vendor/github.com/vanng822/css/styledeclaration.go
deleted file mode 100644
index febd83f..0000000
--- a/vendor/github.com/vanng822/css/styledeclaration.go
+++ /dev/null
@@ -1,26 +0,0 @@
-package css
-
-import (
- "fmt"
-)
-
-type CSSStyleDeclaration struct {
- Property string
- Value string
- Important int
-}
-
-func NewCSSStyleDeclaration(property, value string, important int) *CSSStyleDeclaration {
- return &CSSStyleDeclaration{
- Property: property,
- Value: value,
- Important: important,
- }
-}
-
-func (decl *CSSStyleDeclaration) Text() string {
- if decl.Important == 1 {
- return fmt.Sprintf("%s: %s !important", decl.Property, decl.Value)
- }
- return fmt.Sprintf("%s: %s", decl.Property, decl.Value)
-}
diff --git a/vendor/github.com/vanng822/css/styledeclaration_test.go b/vendor/github.com/vanng822/css/styledeclaration_test.go
deleted file mode 100644
index fb0de76..0000000
--- a/vendor/github.com/vanng822/css/styledeclaration_test.go
+++ /dev/null
@@ -1,16 +0,0 @@
-package css
-
-import (
- "github.com/stretchr/testify/assert"
- "testing"
-)
-
-func TestDeclWithImportan(t *testing.T) {
- decl := NewCSSStyleDeclaration("width", "100%", 1)
- assert.Equal(t, decl.Text(), "width: 100% !important")
-}
-
-func TestDeclWithoutImportan(t *testing.T) {
- decl := NewCSSStyleDeclaration("width", "100%", 0)
- assert.Equal(t, decl.Text(), "width: 100%")
-}
\ No newline at end of file
diff --git a/vendor/github.com/vanng822/css/stylerule.go b/vendor/github.com/vanng822/css/stylerule.go
deleted file mode 100644
index 9396fe4..0000000
--- a/vendor/github.com/vanng822/css/stylerule.go
+++ /dev/null
@@ -1,24 +0,0 @@
-package css
-
-import (
- "fmt"
- "sort"
- "strings"
-)
-
-type CSSStyleRule struct {
- SelectorText string
- Styles map[string]*CSSStyleDeclaration
-}
-
-func (sr *CSSStyleRule) Text() string {
- decls := make([]string, 0, len(sr.Styles))
-
- for _, s := range sr.Styles {
- decls = append(decls, s.Text())
- }
-
- sort.Strings(decls)
-
- return fmt.Sprintf("%s {\n%s\n}", sr.SelectorText, strings.Join(decls, ";\n"))
-}
diff --git a/vendor/github.com/vanng822/css/stylerule_test.go b/vendor/github.com/vanng822/css/stylerule_test.go
deleted file mode 100644
index 86ee6ac..0000000
--- a/vendor/github.com/vanng822/css/stylerule_test.go
+++ /dev/null
@@ -1,16 +0,0 @@
-package css
-
-import (
- "github.com/stretchr/testify/assert"
- "testing"
-)
-
-func TestStyleRuleText(t *testing.T) {
- sr := CSSStyleRule{}
- sr.SelectorText = ".box"
- sr.Styles = make(map[string]*CSSStyleDeclaration)
- sr.Styles["width"] = NewCSSStyleDeclaration("width", "10px", 0)
- sr.Styles["height"] = NewCSSStyleDeclaration("height", "100px", 0)
-
- assert.Equal(t, sr.Text(), ".box {\nheight: 100px;\nwidth: 10px\n}")
-}
\ No newline at end of file
diff --git a/vendor/github.com/vanng822/css/stylesheet.go b/vendor/github.com/vanng822/css/stylesheet.go
deleted file mode 100644
index c560963..0000000
--- a/vendor/github.com/vanng822/css/stylesheet.go
+++ /dev/null
@@ -1,13 +0,0 @@
-package css
-
-import ()
-
-type CSSStyleSheet struct {
- Type string
- Media string
- CssRuleList []*CSSRule
-}
-
-func (ss *CSSStyleSheet) GetCSSRuleList() []*CSSRule {
- return ss.CssRuleList
-}
diff --git a/vendor/github.com/vanng822/go-premailer/.gitignore b/vendor/github.com/vanng822/go-premailer/.gitignore
deleted file mode 100644
index 56b7df6..0000000
--- a/vendor/github.com/vanng822/go-premailer/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-/pkg/
-.project
-/src/
diff --git a/vendor/github.com/vanng822/go-premailer/.travis.yml b/vendor/github.com/vanng822/go-premailer/.travis.yml
deleted file mode 100644
index a17f5f7..0000000
--- a/vendor/github.com/vanng822/go-premailer/.travis.yml
+++ /dev/null
@@ -1,22 +0,0 @@
-language: golang
-
-go:
- - 1.5
- - 1.6
- - 1.7
- - 1.8
- - tip
-
-env:
- global:
- - GOPATH="$HOME/gopath"
- - PATH="$HOME/gopath/bin:$HOME/bin:$PATH"
-
-install:
- - go get github.com/vanng822/css
- - go get github.com/PuerkitoBio/goquery
- - go get golang.org/x/net/html
- - go get github.com/stretchr/testify/assert
-
-script:
- - cd premailer && go test -v
diff --git a/vendor/github.com/vanng822/go-premailer/LICENSE b/vendor/github.com/vanng822/go-premailer/LICENSE
deleted file mode 100644
index e6e86a6..0000000
--- a/vendor/github.com/vanng822/go-premailer/LICENSE
+++ /dev/null
@@ -1,23 +0,0 @@
-Copyright (c) 2015 Nguyen Van Nhu
-
-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.
-
diff --git a/vendor/github.com/vanng822/go-premailer/README.md b/vendor/github.com/vanng822/go-premailer/README.md
deleted file mode 100644
index 46dc776..0000000
--- a/vendor/github.com/vanng822/go-premailer/README.md
+++ /dev/null
@@ -1,80 +0,0 @@
-# go-premailer
-
-Inline styling for html in golang
-
-# Document
-
-[](https://godoc.org/github.com/vanng822/go-premailer/premailer)
-
-# install
-
- go get github.com/vanng822/go-premailer/premailer
-
-# Example
-
- import (
- "fmt"
- "github.com/vanng822/go-premailer/premailer"
- "log"
- )
-
- func main() {
- prem := premailer.NewPremailerFromFile(inputFile, premailer.NewOptions())
- html, err := prem.Transform()
- if err != nil {
- log.Fatal(err)
- }
-
- fmt.Println(html)
- }
-
-## Input
-
-
-
- Title
-
-
-
- Hi!
- Yes!
-
-
-
-## Output
-
-
-
- Title
-
-
- Hi!
- Yes!
-
-
-
-
-
-# Commandline
-
- > go run main.go -i your_email.html
- > go run main.go -i your_mail.html -o process_mail.html
-
-# Demo
-
-http://premailer.isgoodness.com/
-
-# Conversion endpoint
-
-http://premailer.isgoodness.com/convert
-
- request POST:
- html: your mail
- cssToAttributes: true|false
- removeClasses: true|false
- response:
- {result: output}
-
\ No newline at end of file
diff --git a/vendor/github.com/vanng822/go-premailer/premailer/doc.go b/vendor/github.com/vanng822/go-premailer/premailer/doc.go
deleted file mode 100644
index 5bd47cc..0000000
--- a/vendor/github.com/vanng822/go-premailer/premailer/doc.go
+++ /dev/null
@@ -1,45 +0,0 @@
-// Package premailer is for inline styling.
-//
-// import (
-// "fmt"
-// "github.com/vanng822/go-premailer/premailer"
-// "log"
-// )
-//
-// func main() {
-// prem := premailer.NewPremailerFromFile(inputFile, premailer.NewOptions())
-// html, err := prem.Transform()
-// if err != nil {
-// log.Fatal(err)
-// }
-//
-// fmt.Println(html)
-// }
-// // Input
-//
-//
-//
-// Title
-//
-//
-//
-// Hi!
-// Yes!
-//
-//
-//
-// // Output
-//
-//
-//
-// Title
-//
-//
-// Hi!
-// Yes!
-//
-//
-package premailer
diff --git a/vendor/github.com/vanng822/go-premailer/premailer/element.go b/vendor/github.com/vanng822/go-premailer/premailer/element.go
deleted file mode 100644
index 25aa848..0000000
--- a/vendor/github.com/vanng822/go-premailer/premailer/element.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package premailer
-
-import (
- "fmt"
- "github.com/PuerkitoBio/goquery"
- "github.com/vanng822/css"
- "sort"
- "strings"
-)
-
-type elementRules struct {
- element *goquery.Selection
- rules []*styleRule
- cssToAttributes bool
-}
-
-func (er *elementRules) inline() {
- inline, _ := er.element.Attr("style")
-
- var inlineStyles map[string]*css.CSSStyleDeclaration
- if inline != "" {
- inlineStyles = css.ParseBlock(inline)
- }
-
- styles := make(map[string]string)
- for _, rule := range er.rules {
- for prop, s := range rule.styles {
- styles[prop] = s.Value
- }
- }
-
- if len(inlineStyles) > 0 {
- for prop, s := range inlineStyles {
- styles[prop] = s.Value
- }
- }
-
- final := make([]string, 0, len(styles))
- for p, v := range styles {
- final = append(final, fmt.Sprintf("%s:%s", p, v))
- if er.cssToAttributes {
- er.style_to_basic_html_attribute(p, v)
- }
- }
-
- sort.Strings(final)
- style := strings.Join(final, ";")
- if style != "" {
- er.element.SetAttr("style", style)
- }
-
-}
-
-func (er *elementRules) style_to_basic_html_attribute(prop, value string) {
- switch prop {
- case "text-align":
- er.element.SetAttr("align", value)
- case "vertical-align":
- er.element.SetAttr("valign", value)
- case "background-color":
- er.element.SetAttr("bgcolor", value)
- case "width":
- fallthrough
- case "height":
- if strings.HasSuffix(value, "px") {
- value = value[:len(value)-2]
- }
- er.element.SetAttr(prop, value)
- }
-}
diff --git a/vendor/github.com/vanng822/go-premailer/premailer/main_test.go b/vendor/github.com/vanng822/go-premailer/premailer/main_test.go
deleted file mode 100644
index 94033fb..0000000
--- a/vendor/github.com/vanng822/go-premailer/premailer/main_test.go
+++ /dev/null
@@ -1,16 +0,0 @@
-package premailer
-
-import (
- "fmt"
- "os"
- "testing"
-)
-
-func TestMain(m *testing.M) {
- fmt.Println("Test starting")
- args := os.Args[:]
- retCode := m.Run()
- os.Args = args
- fmt.Println("Test ending")
- os.Exit(retCode)
-}
diff --git a/vendor/github.com/vanng822/go-premailer/premailer/options.go b/vendor/github.com/vanng822/go-premailer/premailer/options.go
deleted file mode 100644
index e5fd3b8..0000000
--- a/vendor/github.com/vanng822/go-premailer/premailer/options.go
+++ /dev/null
@@ -1,20 +0,0 @@
-package premailer
-
-import ()
-
-// Options for controlling behaviour
-type Options struct {
- // Remove class attribute from element
- // Default false
- RemoveClasses bool
- // Copy related CSS properties into HTML attributes (e.g. background-color to bgcolor)
- // Default true
- CssToAttributes bool
-}
-
-// NewOptions return an Options instance with default value
-func NewOptions() *Options {
- options := &Options{}
- options.CssToAttributes = true
- return options
-}
diff --git a/vendor/github.com/vanng822/go-premailer/premailer/premailer.go b/vendor/github.com/vanng822/go-premailer/premailer/premailer.go
deleted file mode 100644
index 9bec367..0000000
--- a/vendor/github.com/vanng822/go-premailer/premailer/premailer.go
+++ /dev/null
@@ -1,208 +0,0 @@
-package premailer
-
-import (
- "fmt"
- "log"
- "regexp"
- "sort"
- "strconv"
- "strings"
- "sync"
-
- "github.com/PuerkitoBio/goquery"
- "github.com/vanng822/css"
- "golang.org/x/net/html"
-)
-
-// Inteface of Premailer
-type Premailer interface {
- // Transform process and inlining css
- // It start to collect the rules in the document style tags
- // Calculate specificity and sort the rules based on that
- // It then collects the affected elements
- // And applies the rules on those
- // The leftover rules will put back into a style element
- Transform() (string, error)
-}
-
-var unmergableSelector = regexp.MustCompile("(?i)\\:{1,2}(visited|active|hover|focus|link|root|in-range|invalid|valid|after|before|selection|target|first\\-(line|letter))|^\\@")
-var notSupportedSelector = regexp.MustCompile("(?i)\\:(checked|disabled|enabled|lang)")
-
-type premailer struct {
- doc *goquery.Document
- elIdAttr string
- elements map[string]*elementRules
- rules []*styleRule
- leftover []*css.CSSRule
- allRules [][]*css.CSSRule
- elementId int
- processed bool
- options *Options
-}
-
-// NewPremailer return a new instance of Premailer
-// It take a Document as argument and it shouldn't be nil
-func NewPremailer(doc *goquery.Document, options *Options) Premailer {
- pr := premailer{}
- pr.doc = doc
- pr.rules = make([]*styleRule, 0)
- pr.allRules = make([][]*css.CSSRule, 0)
- pr.leftover = make([]*css.CSSRule, 0)
- pr.elements = make(map[string]*elementRules)
- pr.elIdAttr = "pr-el-id"
- if options == nil {
- options = NewOptions()
- }
- pr.options = options
- return &pr
-}
-
-func (pr *premailer) sortRules() {
- ruleIndex := 0
- for ruleSetIndex, rules := range pr.allRules {
- if rules == nil {
- continue
- }
- for _, rule := range rules {
- if rule.Type != css.STYLE_RULE {
- pr.leftover = append(pr.leftover, rule)
- continue
- }
- normalStyles := make(map[string]*css.CSSStyleDeclaration)
- importantStyles := make(map[string]*css.CSSStyleDeclaration)
-
- for prop, s := range rule.Style.Styles {
- if s.Important == 1 {
- importantStyles[prop] = s
- } else {
- normalStyles[prop] = s
- }
- }
-
- selectors := strings.Split(rule.Style.SelectorText, ",")
- for _, selector := range selectors {
- if unmergableSelector.MatchString(selector) || notSupportedSelector.MatchString(selector) {
- // cause longer css
- pr.leftover = append(pr.leftover, copyRule(selector, rule))
- continue
- }
- if strings.Contains(selector, "*") {
- // keep this?
- pr.leftover = append(pr.leftover, copyRule(selector, rule))
- continue
- }
- if len(normalStyles) > 0 {
- pr.rules = append(pr.rules, &styleRule{makeSpecificity(0, ruleSetIndex, ruleIndex, selector), selector, normalStyles})
- ruleIndex += 1
- }
- if len(importantStyles) > 0 {
- pr.rules = append(pr.rules, &styleRule{makeSpecificity(1, ruleSetIndex, ruleIndex, selector), selector, importantStyles})
- ruleIndex += 1
- }
- }
- }
- }
- sort.Sort(bySpecificity(pr.rules))
-}
-
-func (pr *premailer) collectRules() {
- var wg sync.WaitGroup
- pr.doc.Find("style:not([data-premailer='ignore'])").Each(func(_ int, s *goquery.Selection) {
- if _, exist := s.Attr("media"); exist {
- return
- }
- wg.Add(1)
- pr.allRules = append(pr.allRules, nil)
- go func(ruleSetIndex int) {
- defer func() {
- wg.Done()
- if r := recover(); r != nil {
- pr.allRules[ruleSetIndex] = nil
- log.Println("Got error when passing css")
- log.Println(r)
- }
- }()
- ss := css.Parse(s.Text())
- pr.allRules[ruleSetIndex] = ss.GetCSSRuleList()
- s.ReplaceWithHtml("")
- }(len(pr.allRules) - 1)
- })
- wg.Wait()
-
-}
-
-func (pr *premailer) collectElements() {
- for _, rule := range pr.rules {
- pr.doc.Find(rule.selector).Each(func(_ int, s *goquery.Selection) {
- if id, exist := s.Attr(pr.elIdAttr); exist {
- pr.elements[id].rules = append(pr.elements[id].rules, rule)
- } else {
- id := strconv.Itoa(pr.elementId)
- s.SetAttr(pr.elIdAttr, id)
- rules := make([]*styleRule, 0)
- rules = append(rules, rule)
- pr.elements[id] = &elementRules{element: s, rules: rules, cssToAttributes: pr.options.CssToAttributes}
- pr.elementId += 1
- }
- })
-
- }
-}
-
-func (pr *premailer) applyInline() {
- for _, element := range pr.elements {
- element.inline()
- element.element.RemoveAttr(pr.elIdAttr)
- if pr.options.RemoveClasses {
- element.element.RemoveAttr("class")
- }
- }
-}
-
-func (pr *premailer) addLeftover() {
- if len(pr.leftover) > 0 {
- headNode := pr.doc.Find("head")
-
- styleNode := &html.Node{}
- styleNode.Type = html.ElementNode
- styleNode.Data = "style"
- styleNode.Attr = []html.Attribute{html.Attribute{Key: "type", Val: "text/css"}}
- cssNode := &html.Node{}
- cssData := make([]string, 0, len(pr.leftover))
- for _, rule := range pr.leftover {
- if rule.Type == css.MEDIA_RULE {
- mcssData := make([]string, 0, len(rule.Rules))
- for _, mrule := range rule.Rules {
- mcssData = append(mcssData, makeRuleImportant(mrule))
- }
- cssData = append(cssData, fmt.Sprintf("%s %s{\n%s\n}\n",
- rule.Type.Text(),
- rule.Style.SelectorText,
- strings.Join(mcssData, "\n")))
- } else {
- cssData = append(cssData, makeRuleImportant(rule))
- }
- }
- cssNode.Data = strings.Join(cssData, "")
- cssNode.Type = html.TextNode
- styleNode.AppendChild(cssNode)
- headNode.AppendNodes(styleNode)
- }
-}
-
-// Transform process and inlining css
-// It start to collect the rules in the document style tags
-// Calculate specificity and sort the rules based on that
-// It then collects the affected elements
-// And applies the rules on those
-// The leftover rules will put back into a style element
-func (pr *premailer) Transform() (string, error) {
- if !pr.processed {
- pr.collectRules()
- pr.sortRules()
- pr.collectElements()
- pr.applyInline()
- pr.addLeftover()
- }
- return pr.doc.Html()
-}
diff --git a/vendor/github.com/vanng822/go-premailer/premailer/premailer_from_file.go b/vendor/github.com/vanng822/go-premailer/premailer/premailer_from_file.go
deleted file mode 100644
index acd42f8..0000000
--- a/vendor/github.com/vanng822/go-premailer/premailer/premailer_from_file.go
+++ /dev/null
@@ -1,24 +0,0 @@
-package premailer
-
-import (
- "github.com/PuerkitoBio/goquery"
- "os"
-)
-
-// NewPremailerFromFile take an filename
-// Read the content of this file
-// and create a goquery.Document
-// and then create and Premailer instance.
-// It will panic if any error happens
-func NewPremailerFromFile(filename string, options *Options) Premailer {
- fd, err := os.Open(filename)
- if err != nil {
- panic(err)
- }
- defer fd.Close()
- d, err := goquery.NewDocumentFromReader(fd)
- if err != nil {
- panic(err)
- }
- return NewPremailer(d, options)
-}
diff --git a/vendor/github.com/vanng822/go-premailer/premailer/premailer_from_file_test.go b/vendor/github.com/vanng822/go-premailer/premailer/premailer_from_file_test.go
deleted file mode 100644
index 6236e91..0000000
--- a/vendor/github.com/vanng822/go-premailer/premailer/premailer_from_file_test.go
+++ /dev/null
@@ -1,24 +0,0 @@
-package premailer
-
-import (
- "github.com/stretchr/testify/assert"
- "testing"
-)
-
-func TestBasicHTMLFromFile(t *testing.T) {
- p := NewPremailerFromFile("data/markup_test.html", nil)
- result_html, err := p.Transform()
- assert.Nil(t, err)
-
- assert.Contains(t, result_html, "Hi! ")
- assert.Contains(t, result_html, "There ")
- assert.Contains(t, result_html, "Hello ")
- assert.Contains(t, result_html, "Yes!
")
- assert.Contains(t, result_html, "Green color
")
-}
-
-func TestFromFilePanic(t *testing.T) {
- assert.Panics(t, func() {
- NewPremailerFromFile("data/blablabla.html", nil)
- })
-}
diff --git a/vendor/github.com/vanng822/go-premailer/premailer/premailer_from_string.go b/vendor/github.com/vanng822/go-premailer/premailer/premailer_from_string.go
deleted file mode 100644
index 68c04c9..0000000
--- a/vendor/github.com/vanng822/go-premailer/premailer/premailer_from_string.go
+++ /dev/null
@@ -1,19 +0,0 @@
-package premailer
-
-import (
- "github.com/PuerkitoBio/goquery"
- "strings"
-)
-
-// NewPremailerFromString take in a document in string format
-// and create a goquery.Document
-// and then create and Premailer instance.
-// It will panic if any error happens
-func NewPremailerFromString(doc string, options *Options) Premailer {
- read := strings.NewReader(doc)
- d, err := goquery.NewDocumentFromReader(read)
- if err != nil {
- panic(err)
- }
- return NewPremailer(d, options)
-}
diff --git a/vendor/github.com/vanng822/go-premailer/premailer/premailer_test.go b/vendor/github.com/vanng822/go-premailer/premailer/premailer_test.go
deleted file mode 100644
index c93dbc2..0000000
--- a/vendor/github.com/vanng822/go-premailer/premailer/premailer_test.go
+++ /dev/null
@@ -1,406 +0,0 @@
-package premailer
-
-import (
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-func TestBasicHTML(t *testing.T) {
- html := `
-
- Title
-
-
-
- Hi!
- There
- Hello
- Yes!
- Green color
-
- `
-
- p := NewPremailerFromString(html, nil)
- result_html, err := p.Transform()
- assert.Nil(t, err)
-
- assert.Contains(t, result_html, "Hi! ")
- assert.Contains(t, result_html, "There ")
- assert.Contains(t, result_html, "Hello ")
- assert.Contains(t, result_html, "Yes!
")
- assert.Contains(t, result_html, "Green color
")
-}
-
-func TestDataPremailerIgnore(t *testing.T) {
- html := `
-
- Title
-
-
-
- Hi!
- Yes!
-
- `
-
- p := NewPremailerFromString(html, nil)
- result_html, err := p.Transform()
- assert.Nil(t, err)
-
- assert.Contains(t, result_html, "Hi! ")
- assert.Contains(t, result_html, "Yes!
")
-}
-
-func TestWithInline(t *testing.T) {
- html := `
-
- Title
-
-
-
- Hi!
- Yes!
-
- `
-
- p := NewPremailerFromString(html, nil)
- result_html, err := p.Transform()
- assert.Nil(t, err)
-
- assert.Contains(t, result_html, "Hi! ")
- assert.Contains(t, result_html, "Yes!
")
- assert.NotContains(t, result_html, "
-
-
- Hi!
-
- Yes!
- No!
-
-
- `
-
- p := NewPremailerFromString(html, nil)
- result_html, err := p.Transform()
- assert.Nil(t, err)
-
- assert.Contains(t, result_html, "Yes! ")
- assert.Contains(t, result_html, "
-
-
- Hi!
- Yes!
-
- `
-
- options := &Options{}
- options.RemoveClasses = true
- p := NewPremailerFromString(html, options)
- result_html, err := p.Transform()
- assert.Nil(t, err)
-
- assert.Contains(t, result_html, "Hi! ")
- assert.Contains(t, result_html, "Yes!
")
-}
-
-func TestCssToAttributesFalse(t *testing.T) {
- html := `
-
- Title
-
-
-
- Hi!
- Yes!
-
- `
-
- options := &Options{}
- options.CssToAttributes = false
- p := NewPremailerFromString(html, options)
- result_html, err := p.Transform()
- assert.Nil(t, err)
-
- assert.Contains(t, result_html, "Hi! ")
- assert.Contains(t, result_html, "Yes!
")
-}
-
-func TestWithImportant(t *testing.T) {
- html := `
-
- Title
-
-
-
- Hi!
- Yes!
-
- `
-
- p := NewPremailerFromString(html, NewOptions())
- result_html, err := p.Transform()
- assert.Nil(t, err)
-
- assert.Contains(t, result_html, "Hi! ")
- assert.Contains(t, result_html, "Yes!
")
-}
-
-func TestWithMediaRule(t *testing.T) {
- html := `
-
- Title
-
-
-
- Hi!
- Yes!
-
- `
-
- p := NewPremailerFromString(html, NewOptions())
- result_html, err := p.Transform()
- assert.Nil(t, err)
-
- assert.Contains(t, result_html, "Hi! ")
- assert.Contains(t, result_html, "Yes!
")
-
- assert.Contains(t, result_html, "@media all and (min-width: 62em){")
- assert.Contains(t, result_html, "font-size: 55px !important;")
- assert.Contains(t, result_html, "line-height: 60px !important;")
- assert.Contains(t, result_html, "padding-bottom: 5px !important;")
- assert.Contains(t, result_html, "padding-top: 0 !important")
-}
-
-func TestWithMediaAttribute(t *testing.T) {
- html := `
-
- Title
-
-
-
-
-
- Hi!
- Yes!
-
- `
-
- p := NewPremailerFromString(html, NewOptions())
- result_html, err := p.Transform()
- assert.Nil(t, err)
-
- assert.Contains(t, result_html, "Hi! ")
- assert.Contains(t, result_html, "Yes!
")
-
- assert.Contains(t, result_html, "
-
-
-
-
- Hi!
- Yes!
-
-