├── Godeps ├── _workspace │ ├── .gitignore │ └── src │ │ └── github.com │ │ ├── stretchr │ │ └── testify │ │ │ ├── assert │ │ │ ├── assertion_forward.go.tmpl │ │ │ ├── errors.go │ │ │ ├── forward_assertions.go │ │ │ ├── doc.go │ │ │ ├── http_assertions.go │ │ │ ├── assertion_forward.go │ │ │ └── assertions.go │ │ │ ├── LICENSE │ │ │ └── LICENCE.txt │ │ ├── joyt │ │ └── godate │ │ │ ├── .gitignore │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ └── godate.go │ │ ├── davecgh │ │ └── go-spew │ │ │ ├── LICENSE │ │ │ └── spew │ │ │ ├── bypasssafe.go │ │ │ ├── bypass.go │ │ │ ├── spew.go │ │ │ ├── doc.go │ │ │ ├── common.go │ │ │ ├── format.go │ │ │ ├── config.go │ │ │ └── dump.go │ │ └── pmezard │ │ └── go-difflib │ │ ├── LICENSE │ │ └── difflib │ │ └── difflib.go ├── Readme └── Godeps.json ├── .travis.yml ├── .gitignore ├── README.md ├── timeparser_test.go └── timeparser.go /Godeps/_workspace/.gitignore: -------------------------------------------------------------------------------- 1 | /pkg 2 | /bin 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | sudo: false 4 | 5 | go: 6 | - 1.5 7 | - 1.6 8 | - tip 9 | 10 | script: 11 | - go test -v ./... -------------------------------------------------------------------------------- /Godeps/Readme: -------------------------------------------------------------------------------- 1 | This directory tree is generated automatically by godep. 2 | 3 | Please do not edit. 4 | 5 | See https://github.com/tools/godep for more information. 6 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/stretchr/testify/assert/assertion_forward.go.tmpl: -------------------------------------------------------------------------------- 1 | {{.CommentWithoutT "a"}} 2 | func (a *Assertions) {{.DocInfo.Name}}({{.Params}}) bool { 3 | return {{.DocInfo.Name}}(a.t, {{.ForwardedParams}}) 4 | } 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | 24 | .DS_Store -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/joyt/godate/.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | *.prof 25 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/stretchr/testify/assert/errors.go: -------------------------------------------------------------------------------- 1 | package assert 2 | 3 | import ( 4 | "errors" 5 | ) 6 | 7 | // AnError is an error instance useful for testing. If the code does not care 8 | // about error specifics, and only needs to return the error for example, this 9 | // error should be used to make the test code more readable. 10 | var AnError = errors.New("assert.AnError general error for testing") 11 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions.go: -------------------------------------------------------------------------------- 1 | package assert 2 | 3 | // Assertions provides assertion methods around the 4 | // TestingT interface. 5 | type Assertions struct { 6 | t TestingT 7 | } 8 | 9 | // New makes a new Assertions object for the specified TestingT. 10 | func New(t TestingT) *Assertions { 11 | return &Assertions{ 12 | t: t, 13 | } 14 | } 15 | 16 | //go:generate go run ../_codegen/main.go -output-package=assert -template=assertion_forward.go.tmpl 17 | -------------------------------------------------------------------------------- /Godeps/Godeps.json: -------------------------------------------------------------------------------- 1 | { 2 | "ImportPath": "github.com/coccyx/timeparser", 3 | "GoVersion": "go1.5", 4 | "GodepVersion": "v74", 5 | "Deps": [ 6 | { 7 | "ImportPath": "github.com/davecgh/go-spew/spew", 8 | "Comment": "v1.0.0", 9 | "Rev": "6cf5744a041a0022271cefed95ba843f6d87fd51" 10 | }, 11 | { 12 | "ImportPath": "github.com/joyt/godate", 13 | "Rev": "7151572574a7c217932a48e0b23c111631e7181c" 14 | }, 15 | { 16 | "ImportPath": "github.com/pmezard/go-difflib/difflib", 17 | "Comment": "v1.0.0", 18 | "Rev": "792786c7400a136282c1664665ae0a8db921c6c2" 19 | }, 20 | { 21 | "ImportPath": "github.com/stretchr/testify/assert", 22 | "Comment": "v1.1.3-19-gd77da35", 23 | "Rev": "d77da356e56a7428ad25149ca77381849a6a5232" 24 | } 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/davecgh/go-spew/LICENSE: -------------------------------------------------------------------------------- 1 | ISC License 2 | 3 | Copyright (c) 2012-2013 Dave Collins 4 | 5 | Permission to use, copy, modify, and distribute this software for any 6 | purpose with or without fee is hereby granted, provided that the above 7 | copyright notice and this permission notice appear in all copies. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 10 | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 11 | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 12 | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 13 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 14 | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 15 | OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 16 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/joyt/godate/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Joy Tao 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/stretchr/testify/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell 2 | 3 | Please consider promoting this project if you find it useful. 4 | 5 | Permission is hereby granted, free of charge, to any person 6 | obtaining a copy of this software and associated documentation 7 | files (the "Software"), to deal in the Software without restriction, 8 | including without limitation the rights to use, copy, modify, merge, 9 | publish, distribute, sublicense, and/or sell copies of the Software, 10 | and to permit persons to whom the Software is furnished to do so, 11 | subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included 14 | in all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 18 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 20 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT 21 | OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE 22 | OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 23 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/stretchr/testify/LICENCE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell 2 | 3 | Please consider promoting this project if you find it useful. 4 | 5 | Permission is hereby granted, free of charge, to any person 6 | obtaining a copy of this software and associated documentation 7 | files (the "Software"), to deal in the Software without restriction, 8 | including without limitation the rights to use, copy, modify, merge, 9 | publish, distribute, sublicense, and/or sell copies of the Software, 10 | and to permit persons to whom the Software is furnished to do so, 11 | subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included 14 | in all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 18 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 20 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT 21 | OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE 22 | OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Timeparser 2 | ========== 3 | 4 | [![Build Status](https://travis-ci.org/coccyx/timeparser.svg)](https://travis-ci.org/coccyx/timeparser) [![Go Report Card](https://goreportcard.com/badge/github.com/coccyx/timeparser)](https://goreportcard.com/report/github.com/coccyx/timeparser) [![GoDoc](https://godoc.org/github.com/coccyx/timeparser?status.svg)](https://godoc.org/github.com/coccyx/timeparser) 5 | 6 | Go (golang) package for parsing time in Splunk's relative time syntax. [See docs for format documentation](https://docs.splunk.com/Documentation/Splunk/6.4.3/SearchReference/SearchTimeModifiers), but here's some examples: 7 | 8 | | Time | Description | 9 | |------------------|------------------------------------------------------------------------------------| 10 | | -1m | One minute ago | 11 | | +30m | 30 minutes from now | 12 | | -4h@h | Four hours ago, snapped to the hour | 13 | | -1week@week+1day | One week ago, snapped to Monday (1 day after Sunday, which is the default snap to) | 14 | 15 | 16 | For details, see the [API documentation](http://godoc.org/github.com/coccyx/timeparser). -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/pmezard/go-difflib/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013, Patrick Mezard 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are 6 | met: 7 | 8 | Redistributions of source code must retain the above copyright 9 | notice, this list of conditions and the following disclaimer. 10 | Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | The names of its contributors may not be used to endorse or promote 14 | products derived from this software without specific prior written 15 | permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 18 | IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 19 | TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 20 | PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 23 | TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 24 | PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 25 | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 26 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/stretchr/testify/assert/doc.go: -------------------------------------------------------------------------------- 1 | // Package assert provides a set of comprehensive testing tools for use with the normal Go testing system. 2 | // 3 | // Example Usage 4 | // 5 | // The following is a complete example using assert in a standard test function: 6 | // import ( 7 | // "testing" 8 | // "github.com/stretchr/testify/assert" 9 | // ) 10 | // 11 | // func TestSomething(t *testing.T) { 12 | // 13 | // var a string = "Hello" 14 | // var b string = "Hello" 15 | // 16 | // assert.Equal(t, a, b, "The two words should be the same.") 17 | // 18 | // } 19 | // 20 | // if you assert many times, use the format below: 21 | // 22 | // import ( 23 | // "testing" 24 | // "github.com/stretchr/testify/assert" 25 | // ) 26 | // 27 | // func TestSomething(t *testing.T) { 28 | // assert := assert.New(t) 29 | // 30 | // var a string = "Hello" 31 | // var b string = "Hello" 32 | // 33 | // assert.Equal(a, b, "The two words should be the same.") 34 | // } 35 | // 36 | // Assertions 37 | // 38 | // Assertions allow you to easily write test code, and are global funcs in the `assert` package. 39 | // All assertion functions take, as the first argument, the `*testing.T` object provided by the 40 | // testing framework. This allows the assertion funcs to write the failings and other details to 41 | // the correct place. 42 | // 43 | // Every assertion function also takes an optional string message as the final argument, 44 | // allowing custom error messages to be appended to the message the assertion method outputs. 45 | package assert 46 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/davecgh/go-spew/spew/bypasssafe.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015 Dave Collins 2 | // 3 | // Permission to use, copy, modify, and distribute this software for any 4 | // purpose with or without fee is hereby granted, provided that the above 5 | // copyright notice and this permission notice appear in all copies. 6 | // 7 | // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 8 | // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 9 | // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 10 | // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 11 | // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 12 | // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 13 | // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 14 | 15 | // NOTE: Due to the following build constraints, this file will only be compiled 16 | // when either the code is running on Google App Engine or "-tags disableunsafe" 17 | // is added to the go build command line. 18 | // +build appengine disableunsafe 19 | 20 | package spew 21 | 22 | import "reflect" 23 | 24 | const ( 25 | // UnsafeDisabled is a build-time constant which specifies whether or 26 | // not access to the unsafe package is available. 27 | UnsafeDisabled = true 28 | ) 29 | 30 | // unsafeReflectValue typically converts the passed reflect.Value into a one 31 | // that bypasses the typical safety restrictions preventing access to 32 | // unaddressable and unexported data. However, doing this relies on access to 33 | // the unsafe package. This is a stub version which simply returns the passed 34 | // reflect.Value when the unsafe package is not available. 35 | func unsafeReflectValue(v reflect.Value) reflect.Value { 36 | return v 37 | } 38 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/joyt/godate/README.md: -------------------------------------------------------------------------------- 1 | # godate 2 | Golang package for intelligently parsing date strings like javascript's Date.parse() and getting the layout of date strings. 3 | Fully compatible with the native time package. 4 | 5 | This package is still under development. 6 | 7 | # Usage 8 | ### Installation 9 | ``` 10 | go get github.com/joyt/godate 11 | ``` 12 | 13 | In your program: 14 | ```go 15 | var timestamp time.Time 16 | var err error 17 | timestamp, err = date.Parse("Mar 14 2003") 18 | ``` 19 | 20 | ## Example 21 | ```go 22 | import ( 23 | "github.com/joyt/godate" 24 | "time" 25 | "fmt" 26 | ) 27 | 28 | func main() { 29 | var t time.Time 30 | 31 | t = date.MustParse("Aug 31 1999") 32 | fmt.Println(t) 33 | // Prints 1999-08-31 00:00:00 +0000 UTC 34 | 35 | t = date.MustParse("Tuesday, August 31, 1999") 36 | fmt.Println(t) 37 | // Prints 1999-08-31 00:00:00 +0000 UTC 38 | 39 | t = date.MustParse("Tue 31 Aug '99") 40 | fmt.Println(t) 41 | // Prints 1999-08-31 00:00:00 +0000 UTC 42 | 43 | t = date.MustParse("08/31/1999") 44 | fmt.Println(t) 45 | // Prints 1999-08-31 00:00:00 +0000 UTC 46 | 47 | t = date.MustParse("8/31/1999 20:05") 48 | fmt.Println(t) 49 | // Prints 1999-08-31 21:05:00 +0000 UTC 50 | 51 | t = date.MustParse("31/08/1999 8:05pm") 52 | fmt.Println(t) 53 | // Prints 1999-08-31 21:05:00 +0000 UTC 54 | 55 | t = date.MustParse("8/31/1999 8:05PM EST") 56 | fmt.Println(t) 57 | // Prints 1999-08-31 21:05:00 -0400 EDT 58 | 59 | t = date.MustParse("Aug-1999") 60 | fmt.Println(t) 61 | // Prints 1999-08-01 00:00:00 +0000 UTC 62 | } 63 | ``` 64 | 65 | # Notes 66 | 67 | The parser is extremely lenient, and will try to interpret whatever it is given as a date as much as possible. 68 | 69 | In cases where the meaning of the date is ambiguous (such as 6/09, which could mean Jun 9th or Jun 2009), the parser generally defaults to the higher resolution date (Jun 9th). An exception is made for dates without separators such as "200609", where the parser will always try to assume the year is first (200609 -> Sep 2006, NOT Jun 20th 2009). 70 | -------------------------------------------------------------------------------- /timeparser_test.go: -------------------------------------------------------------------------------- 1 | package timeparser 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | "time" 7 | 8 | "github.com/stretchr/testify/assert" 9 | ) 10 | 11 | func TestTimeParser(t *testing.T) { 12 | _ = fmt.Sprintf("foo") // Just to avoid annoying warnings 13 | 14 | loc, _ := time.LoadLocation("Local") 15 | n := time.Date(2001, 10, 20, 12, 0, 0, 100000, loc) 16 | 17 | now := func() time.Time { 18 | return n 19 | } 20 | 21 | // Test Now 22 | tn, _ := TimeParserNow("now", now) 23 | assert.Equal(t, n, tn) 24 | 25 | // Test -1h 26 | x := n.Add(time.Duration(1) * time.Hour * -1) 27 | tn, _ = TimeParserNow("-1h", now) 28 | assert.Equal(t, x, tn) 29 | 30 | // Test -10s 31 | x = n.Add(time.Duration(10) * time.Second * -1) 32 | tn, _ = TimeParserNow("-10s", now) 33 | assert.Equal(t, x, tn) 34 | 35 | // Test -59m 36 | x = n.Add(time.Duration(59) * time.Minute * -1) 37 | tn, _ = TimeParserNow("-59m", now) 38 | assert.Equal(t, x, tn) 39 | 40 | // Test +1day 41 | x = n.AddDate(0, 0, 1) 42 | tn, _ = TimeParserNow("+1day", now) 43 | assert.Equal(t, x, tn) 44 | 45 | // Test Snapto sec 46 | x = n.Add(time.Duration(1) * time.Second * -1) 47 | x = time.Date(x.Year(), x.Month(), x.Day(), x.Hour(), x.Minute(), x.Second(), 0, loc) 48 | tn, _ = TimeParserNow("-1s@s", now) 49 | assert.Equal(t, x, tn) 50 | 51 | // Test Snapto min 52 | x = n.Add(time.Duration(1) * time.Minute * -1) 53 | x = time.Date(x.Year(), x.Month(), x.Day(), x.Hour(), x.Minute(), x.Second(), 0, loc) 54 | tn, _ = TimeParserNow("-1s@m", now) 55 | assert.Equal(t, x, tn) 56 | 57 | // Test Snapto hour 58 | x = n.Add(time.Duration(1) * time.Hour * -1) 59 | x = time.Date(x.Year(), x.Month(), x.Day(), x.Hour(), x.Minute(), x.Second(), 0, loc) 60 | tn, _ = TimeParserNow("-1s@h", now) 61 | assert.Equal(t, x, tn) 62 | 63 | // Test Snapto day 64 | x = time.Date(2001, 10, 20, 0, 0, 0, 0, loc) 65 | tn, _ = TimeParserNow("-1h@d", now) 66 | assert.Equal(t, x, tn) 67 | 68 | // Test Snapto month 69 | x = time.Date(2001, 10, 1, 0, 0, 0, 0, loc) 70 | tn, _ = TimeParserNow("-1h@mon", now) 71 | assert.Equal(t, x, tn) 72 | 73 | // Test Snapto quarter 74 | x = time.Date(2001, 9, 1, 0, 0, 0, 0, loc) 75 | tn, _ = TimeParserNow("-1h@qtr", now) 76 | assert.Equal(t, x, tn) 77 | 78 | // Test Snapto year 79 | x = time.Date(2001, 1, 1, 0, 0, 0, 0, loc) 80 | tn, _ = TimeParserNow("-1h@year", now) 81 | assert.Equal(t, x, tn) 82 | 83 | // Test Snapto year with math 84 | x = time.Date(2001, 2, 1, 0, 0, 0, 0, loc) 85 | tn, _ = TimeParserNow("-1h@year+1mon", now) 86 | assert.Equal(t, x, tn) 87 | 88 | // Test Snapto weekday 89 | x = time.Date(2001, 10, 14, 0, 0, 0, 0, loc) 90 | tn, _ = TimeParserNow("-1h@w0", now) 91 | assert.Equal(t, x, tn) 92 | } 93 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/stretchr/testify/assert/http_assertions.go: -------------------------------------------------------------------------------- 1 | package assert 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "net/http/httptest" 7 | "net/url" 8 | "strings" 9 | ) 10 | 11 | // httpCode is a helper that returns HTTP code of the response. It returns -1 12 | // if building a new request fails. 13 | func httpCode(handler http.HandlerFunc, method, url string, values url.Values) int { 14 | w := httptest.NewRecorder() 15 | req, err := http.NewRequest(method, url+"?"+values.Encode(), nil) 16 | if err != nil { 17 | return -1 18 | } 19 | handler(w, req) 20 | return w.Code 21 | } 22 | 23 | // HTTPSuccess asserts that a specified handler returns a success status code. 24 | // 25 | // assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) 26 | // 27 | // Returns whether the assertion was successful (true) or not (false). 28 | func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool { 29 | code := httpCode(handler, method, url, values) 30 | if code == -1 { 31 | return false 32 | } 33 | return code >= http.StatusOK && code <= http.StatusPartialContent 34 | } 35 | 36 | // HTTPRedirect asserts that a specified handler returns a redirect status code. 37 | // 38 | // assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} 39 | // 40 | // Returns whether the assertion was successful (true) or not (false). 41 | func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool { 42 | code := httpCode(handler, method, url, values) 43 | if code == -1 { 44 | return false 45 | } 46 | return code >= http.StatusMultipleChoices && code <= http.StatusTemporaryRedirect 47 | } 48 | 49 | // HTTPError asserts that a specified handler returns an error status code. 50 | // 51 | // assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} 52 | // 53 | // Returns whether the assertion was successful (true) or not (false). 54 | func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool { 55 | code := httpCode(handler, method, url, values) 56 | if code == -1 { 57 | return false 58 | } 59 | return code >= http.StatusBadRequest 60 | } 61 | 62 | // HTTPBody is a helper that returns HTTP body of the response. It returns 63 | // empty string if building a new request fails. 64 | func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string { 65 | w := httptest.NewRecorder() 66 | req, err := http.NewRequest(method, url+"?"+values.Encode(), nil) 67 | if err != nil { 68 | return "" 69 | } 70 | handler(w, req) 71 | return w.Body.String() 72 | } 73 | 74 | // HTTPBodyContains asserts that a specified handler returns a 75 | // body that contains a string. 76 | // 77 | // assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") 78 | // 79 | // Returns whether the assertion was successful (true) or not (false). 80 | func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}) bool { 81 | body := HTTPBody(handler, method, url, values) 82 | 83 | contains := strings.Contains(body, fmt.Sprint(str)) 84 | if !contains { 85 | Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) 86 | } 87 | 88 | return contains 89 | } 90 | 91 | // HTTPBodyNotContains asserts that a specified handler returns a 92 | // body that does not contain a string. 93 | // 94 | // assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") 95 | // 96 | // Returns whether the assertion was successful (true) or not (false). 97 | func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}) bool { 98 | body := HTTPBody(handler, method, url, values) 99 | 100 | contains := strings.Contains(body, fmt.Sprint(str)) 101 | if contains { 102 | Fail(t, "Expected response body for %s to NOT contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body) 103 | } 104 | 105 | return !contains 106 | } 107 | -------------------------------------------------------------------------------- /timeparser.go: -------------------------------------------------------------------------------- 1 | // Package timeparser implements Splunk's relative time syntax, or attempts to guess as 2 | // best as possible if not relative time. 3 | package timeparser 4 | 5 | import ( 6 | "fmt" 7 | godate "github.com/joyt/godate" 8 | "math" 9 | "regexp" 10 | "strconv" 11 | "time" 12 | ) 13 | 14 | var ( 15 | unitsre string = "(seconds|second|secs|sec|minutes|minute|min|hours|hour|hrs|hr|days|day|weeks|week|w[0-6]|months|month|mon|quarters|quarter|qtrs|qtr|years|year|yrs|yr|s|h|m|d|w|y|w|q)" 16 | reltimere string = "(?i)(?P[+-]*)(?P\\d{1,})(?P" + unitsre + "{1})(([\\@](?P" + unitsre + "{1})((?P[+-])(?P\\d+)(?P" + unitsre + "{1}))*)*)" 17 | re *regexp.Regexp = regexp.MustCompile(reltimere) 18 | now = time.Now 19 | loc *time.Location 20 | 21 | secs = map[string]bool{"s": true, "sec": true, "secs": true, "second": true, "seconds": true} 22 | mins = map[string]bool{"m": true, "min": true, "minute": true, "minutes": true} 23 | hours = map[string]bool{"h": true, "hr": true, "hrs": true, "hour": true, "hours": true} 24 | days = map[string]bool{"d": true, "day": true, "days": true} 25 | weeks = map[string]bool{"w": true, "week": true, "weeks": true, 26 | "w0": true, "w1": true, "w2": true, "w3": true, "w4": true, "w5": true, "w6": true} 27 | months = map[string]bool{"mon": true, "month": true, "months": true} 28 | quarters = map[string]bool{"q": true, "qtr": true, "qtrs": true, "quarter": true, "quarters": true} 29 | years = map[string]bool{"y": true, "yr": true, "yrs": true, "year": true, "years": true} 30 | ) 31 | 32 | func init() { 33 | loc, _ = time.LoadLocation("Local") 34 | } 35 | 36 | // TimeParser returns a parsed time based on the current time in the local time zone 37 | func TimeParser(ts string) (time.Time, error) { 38 | return TimeParserNowInLocation(ts, now, loc) 39 | } 40 | 41 | // TimeParser returns a parsed time based on now returned from the passed callback in the local time zone 42 | func TimeParserNow(ts string, now func() time.Time) (time.Time, error) { 43 | return TimeParserNowInLocation(ts, now, loc) 44 | } 45 | 46 | // TimeParser returns a parsed time based on the current time in the passed time zone 47 | func TimeParserInLocation(ts string, loc *time.Location) (time.Time, error) { 48 | return TimeParserNowInLocation(ts, now, loc) 49 | } 50 | 51 | // TimeParser returns a parsed time based on now returned from the passed callback in the passed time zone 52 | func TimeParserNowInLocation(ts string, now func() time.Time, loc *time.Location) (time.Time, error) { 53 | if ts == "now" { 54 | return now(), nil 55 | } else { 56 | if ts[:1] == "+" || ts[:1] == "-" { 57 | ret := now() 58 | 59 | match := re.FindStringSubmatch(ts) 60 | results := make(map[string]string) 61 | for i, name := range re.SubexpNames() { 62 | if i != 0 { 63 | results[name] = match[i] 64 | } 65 | } 66 | 67 | // Handle first part of the time string 68 | if len(results["plusminus"]) != 0 && len(results["num"]) != 0 && len(results["unit"]) != 0 { 69 | timeParserTimeMath(results["plusminus"], results["num"], results["unit"], &ret) 70 | 71 | snapunit := results["snapunit"] 72 | if len(snapunit) > 0 { 73 | switch { 74 | case secs[snapunit]: 75 | ret = time.Date(ret.Year(), ret.Month(), ret.Day(), ret.Hour(), ret.Minute(), ret.Second(), 0, loc) 76 | case mins[snapunit]: 77 | ret = time.Date(ret.Year(), ret.Month(), ret.Day(), ret.Hour(), ret.Minute(), 0, 0, loc) 78 | case hours[snapunit]: 79 | ret = time.Date(ret.Year(), ret.Month(), ret.Day(), ret.Hour(), 0, 0, 0, loc) 80 | case days[snapunit]: 81 | ret = time.Date(ret.Year(), ret.Month(), ret.Day(), 0, 0, 0, 0, loc) 82 | case weeks[snapunit]: 83 | // Only w[0-6] have length of 2 84 | if len(snapunit) == 2 { 85 | wdnum, err := strconv.Atoi(snapunit[1:2]) 86 | if err != nil { 87 | return ret, err 88 | } 89 | wd := int(ret.Weekday()) 90 | 91 | if wdnum <= wd { 92 | ret = ret.Add(time.Duration(24*(wdnum-wd)) * time.Hour) 93 | ret = time.Date(ret.Year(), ret.Month(), ret.Day(), 0, 0, 0, 0, loc) 94 | } else { 95 | ret = ret.Add(time.Duration(24*7*-1) * time.Hour) 96 | ret = ret.Add(time.Duration(24*-1*wd) * time.Hour) 97 | ret = ret.Add(time.Duration(24*wdnum) * time.Hour) 98 | ret = time.Date(ret.Year(), ret.Month(), ret.Day(), 0, 0, 0, 0, loc) 99 | } 100 | } 101 | case months[snapunit]: 102 | ret = time.Date(ret.Year(), ret.Month(), 1, 0, 0, 0, 0, loc) 103 | case quarters[snapunit]: 104 | tmonth := int(math.Floor(float64(ret.Month()/3)) * 3) 105 | ret = time.Date(ret.Year(), time.Month(tmonth), 1, 0, 0, 0, 0, loc) 106 | case years[snapunit]: 107 | ret = time.Date(ret.Year(), 1, 1, 0, 0, 0, 0, loc) 108 | } 109 | 110 | if len(results["snapplusminus"]) != 0 && len(results["snaprelnum"]) != 0 && len(results["snaprelunit"]) != 0 { 111 | timeParserTimeMath(results["snapplusminus"], results["snaprelnum"], results["snaprelunit"], &ret) 112 | } 113 | } 114 | return ret, nil 115 | } 116 | } else { // We're not a relative time, so try our best to interpret the date passed 117 | return godate.ParseInLocation(ts, loc) 118 | } 119 | } 120 | return now(), fmt.Errorf("Got to the end but didn't return") 121 | } 122 | 123 | func timeParserTimeMath(plusminus string, numstr string, unit string, ret *time.Time) { 124 | num, _ := strconv.Atoi(numstr) 125 | if plusminus == "-" { 126 | num *= -1 127 | } 128 | 129 | switch { 130 | case secs[unit]: 131 | *ret = ret.Add(time.Duration(num) * time.Second) 132 | case mins[unit]: 133 | *ret = ret.Add(time.Duration(num) * time.Minute) 134 | case hours[unit]: 135 | *ret = ret.Add(time.Duration(num) * time.Hour) 136 | case days[unit]: 137 | *ret = ret.AddDate(0, 0, num) 138 | case weeks[unit]: 139 | *ret = ret.AddDate(0, 0, num*7) 140 | case months[unit]: 141 | *ret = ret.AddDate(0, num, 0) 142 | case quarters[unit]: 143 | *ret = ret.AddDate(0, num*3, 0) 144 | case years[unit]: 145 | *ret = ret.AddDate(num, 0, 0) 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/davecgh/go-spew/spew/bypass.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015 Dave Collins 2 | // 3 | // Permission to use, copy, modify, and distribute this software for any 4 | // purpose with or without fee is hereby granted, provided that the above 5 | // copyright notice and this permission notice appear in all copies. 6 | // 7 | // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 8 | // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 9 | // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 10 | // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 11 | // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 12 | // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 13 | // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 14 | 15 | // NOTE: Due to the following build constraints, this file will only be compiled 16 | // when the code is not running on Google App Engine and "-tags disableunsafe" 17 | // is not added to the go build command line. 18 | // +build !appengine,!disableunsafe 19 | 20 | package spew 21 | 22 | import ( 23 | "reflect" 24 | "unsafe" 25 | ) 26 | 27 | const ( 28 | // UnsafeDisabled is a build-time constant which specifies whether or 29 | // not access to the unsafe package is available. 30 | UnsafeDisabled = false 31 | 32 | // ptrSize is the size of a pointer on the current arch. 33 | ptrSize = unsafe.Sizeof((*byte)(nil)) 34 | ) 35 | 36 | var ( 37 | // offsetPtr, offsetScalar, and offsetFlag are the offsets for the 38 | // internal reflect.Value fields. These values are valid before golang 39 | // commit ecccf07e7f9d which changed the format. The are also valid 40 | // after commit 82f48826c6c7 which changed the format again to mirror 41 | // the original format. Code in the init function updates these offsets 42 | // as necessary. 43 | offsetPtr = uintptr(ptrSize) 44 | offsetScalar = uintptr(0) 45 | offsetFlag = uintptr(ptrSize * 2) 46 | 47 | // flagKindWidth and flagKindShift indicate various bits that the 48 | // reflect package uses internally to track kind information. 49 | // 50 | // flagRO indicates whether or not the value field of a reflect.Value is 51 | // read-only. 52 | // 53 | // flagIndir indicates whether the value field of a reflect.Value is 54 | // the actual data or a pointer to the data. 55 | // 56 | // These values are valid before golang commit 90a7c3c86944 which 57 | // changed their positions. Code in the init function updates these 58 | // flags as necessary. 59 | flagKindWidth = uintptr(5) 60 | flagKindShift = uintptr(flagKindWidth - 1) 61 | flagRO = uintptr(1 << 0) 62 | flagIndir = uintptr(1 << 1) 63 | ) 64 | 65 | func init() { 66 | // Older versions of reflect.Value stored small integers directly in the 67 | // ptr field (which is named val in the older versions). Versions 68 | // between commits ecccf07e7f9d and 82f48826c6c7 added a new field named 69 | // scalar for this purpose which unfortunately came before the flag 70 | // field, so the offset of the flag field is different for those 71 | // versions. 72 | // 73 | // This code constructs a new reflect.Value from a known small integer 74 | // and checks if the size of the reflect.Value struct indicates it has 75 | // the scalar field. When it does, the offsets are updated accordingly. 76 | vv := reflect.ValueOf(0xf00) 77 | if unsafe.Sizeof(vv) == (ptrSize * 4) { 78 | offsetScalar = ptrSize * 2 79 | offsetFlag = ptrSize * 3 80 | } 81 | 82 | // Commit 90a7c3c86944 changed the flag positions such that the low 83 | // order bits are the kind. This code extracts the kind from the flags 84 | // field and ensures it's the correct type. When it's not, the flag 85 | // order has been changed to the newer format, so the flags are updated 86 | // accordingly. 87 | upf := unsafe.Pointer(uintptr(unsafe.Pointer(&vv)) + offsetFlag) 88 | upfv := *(*uintptr)(upf) 89 | flagKindMask := uintptr((1<>flagKindShift != uintptr(reflect.Int) { 91 | flagKindShift = 0 92 | flagRO = 1 << 5 93 | flagIndir = 1 << 6 94 | 95 | // Commit adf9b30e5594 modified the flags to separate the 96 | // flagRO flag into two bits which specifies whether or not the 97 | // field is embedded. This causes flagIndir to move over a bit 98 | // and means that flagRO is the combination of either of the 99 | // original flagRO bit and the new bit. 100 | // 101 | // This code detects the change by extracting what used to be 102 | // the indirect bit to ensure it's set. When it's not, the flag 103 | // order has been changed to the newer format, so the flags are 104 | // updated accordingly. 105 | if upfv&flagIndir == 0 { 106 | flagRO = 3 << 5 107 | flagIndir = 1 << 7 108 | } 109 | } 110 | } 111 | 112 | // unsafeReflectValue converts the passed reflect.Value into a one that bypasses 113 | // the typical safety restrictions preventing access to unaddressable and 114 | // unexported data. It works by digging the raw pointer to the underlying 115 | // value out of the protected value and generating a new unprotected (unsafe) 116 | // reflect.Value to it. 117 | // 118 | // This allows us to check for implementations of the Stringer and error 119 | // interfaces to be used for pretty printing ordinarily unaddressable and 120 | // inaccessible values such as unexported struct fields. 121 | func unsafeReflectValue(v reflect.Value) (rv reflect.Value) { 122 | indirects := 1 123 | vt := v.Type() 124 | upv := unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetPtr) 125 | rvf := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetFlag)) 126 | if rvf&flagIndir != 0 { 127 | vt = reflect.PtrTo(v.Type()) 128 | indirects++ 129 | } else if offsetScalar != 0 { 130 | // The value is in the scalar field when it's not one of the 131 | // reference types. 132 | switch vt.Kind() { 133 | case reflect.Uintptr: 134 | case reflect.Chan: 135 | case reflect.Func: 136 | case reflect.Map: 137 | case reflect.Ptr: 138 | case reflect.UnsafePointer: 139 | default: 140 | upv = unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + 141 | offsetScalar) 142 | } 143 | } 144 | 145 | pv := reflect.NewAt(vt, upv) 146 | rv = pv 147 | for i := 0; i < indirects; i++ { 148 | rv = rv.Elem() 149 | } 150 | return rv 151 | } 152 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/davecgh/go-spew/spew/spew.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013 Dave Collins 3 | * 4 | * Permission to use, copy, modify, and distribute this software for any 5 | * purpose with or without fee is hereby granted, provided that the above 6 | * copyright notice and this permission notice appear in all copies. 7 | * 8 | * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 9 | * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 10 | * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 11 | * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 12 | * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 13 | * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 14 | * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 15 | */ 16 | 17 | package spew 18 | 19 | import ( 20 | "fmt" 21 | "io" 22 | ) 23 | 24 | // Errorf is a wrapper for fmt.Errorf that treats each argument as if it were 25 | // passed with a default Formatter interface returned by NewFormatter. It 26 | // returns the formatted string as a value that satisfies error. See 27 | // NewFormatter for formatting details. 28 | // 29 | // This function is shorthand for the following syntax: 30 | // 31 | // fmt.Errorf(format, spew.NewFormatter(a), spew.NewFormatter(b)) 32 | func Errorf(format string, a ...interface{}) (err error) { 33 | return fmt.Errorf(format, convertArgs(a)...) 34 | } 35 | 36 | // Fprint is a wrapper for fmt.Fprint that treats each argument as if it were 37 | // passed with a default Formatter interface returned by NewFormatter. It 38 | // returns the number of bytes written and any write error encountered. See 39 | // NewFormatter for formatting details. 40 | // 41 | // This function is shorthand for the following syntax: 42 | // 43 | // fmt.Fprint(w, spew.NewFormatter(a), spew.NewFormatter(b)) 44 | func Fprint(w io.Writer, a ...interface{}) (n int, err error) { 45 | return fmt.Fprint(w, convertArgs(a)...) 46 | } 47 | 48 | // Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were 49 | // passed with a default Formatter interface returned by NewFormatter. It 50 | // returns the number of bytes written and any write error encountered. See 51 | // NewFormatter for formatting details. 52 | // 53 | // This function is shorthand for the following syntax: 54 | // 55 | // fmt.Fprintf(w, format, spew.NewFormatter(a), spew.NewFormatter(b)) 56 | func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { 57 | return fmt.Fprintf(w, format, convertArgs(a)...) 58 | } 59 | 60 | // Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it 61 | // passed with a default Formatter interface returned by NewFormatter. See 62 | // NewFormatter for formatting details. 63 | // 64 | // This function is shorthand for the following syntax: 65 | // 66 | // fmt.Fprintln(w, spew.NewFormatter(a), spew.NewFormatter(b)) 67 | func Fprintln(w io.Writer, a ...interface{}) (n int, err error) { 68 | return fmt.Fprintln(w, convertArgs(a)...) 69 | } 70 | 71 | // Print is a wrapper for fmt.Print that treats each argument as if it were 72 | // passed with a default Formatter interface returned by NewFormatter. It 73 | // returns the number of bytes written and any write error encountered. See 74 | // NewFormatter for formatting details. 75 | // 76 | // This function is shorthand for the following syntax: 77 | // 78 | // fmt.Print(spew.NewFormatter(a), spew.NewFormatter(b)) 79 | func Print(a ...interface{}) (n int, err error) { 80 | return fmt.Print(convertArgs(a)...) 81 | } 82 | 83 | // Printf is a wrapper for fmt.Printf that treats each argument as if it were 84 | // passed with a default Formatter interface returned by NewFormatter. It 85 | // returns the number of bytes written and any write error encountered. See 86 | // NewFormatter for formatting details. 87 | // 88 | // This function is shorthand for the following syntax: 89 | // 90 | // fmt.Printf(format, spew.NewFormatter(a), spew.NewFormatter(b)) 91 | func Printf(format string, a ...interface{}) (n int, err error) { 92 | return fmt.Printf(format, convertArgs(a)...) 93 | } 94 | 95 | // Println is a wrapper for fmt.Println that treats each argument as if it were 96 | // passed with a default Formatter interface returned by NewFormatter. It 97 | // returns the number of bytes written and any write error encountered. See 98 | // NewFormatter for formatting details. 99 | // 100 | // This function is shorthand for the following syntax: 101 | // 102 | // fmt.Println(spew.NewFormatter(a), spew.NewFormatter(b)) 103 | func Println(a ...interface{}) (n int, err error) { 104 | return fmt.Println(convertArgs(a)...) 105 | } 106 | 107 | // Sprint is a wrapper for fmt.Sprint that treats each argument as if it were 108 | // passed with a default Formatter interface returned by NewFormatter. It 109 | // returns the resulting string. See NewFormatter for formatting details. 110 | // 111 | // This function is shorthand for the following syntax: 112 | // 113 | // fmt.Sprint(spew.NewFormatter(a), spew.NewFormatter(b)) 114 | func Sprint(a ...interface{}) string { 115 | return fmt.Sprint(convertArgs(a)...) 116 | } 117 | 118 | // Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were 119 | // passed with a default Formatter interface returned by NewFormatter. It 120 | // returns the resulting string. See NewFormatter for formatting details. 121 | // 122 | // This function is shorthand for the following syntax: 123 | // 124 | // fmt.Sprintf(format, spew.NewFormatter(a), spew.NewFormatter(b)) 125 | func Sprintf(format string, a ...interface{}) string { 126 | return fmt.Sprintf(format, convertArgs(a)...) 127 | } 128 | 129 | // Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it 130 | // were passed with a default Formatter interface returned by NewFormatter. It 131 | // returns the resulting string. See NewFormatter for formatting details. 132 | // 133 | // This function is shorthand for the following syntax: 134 | // 135 | // fmt.Sprintln(spew.NewFormatter(a), spew.NewFormatter(b)) 136 | func Sprintln(a ...interface{}) string { 137 | return fmt.Sprintln(convertArgs(a)...) 138 | } 139 | 140 | // convertArgs accepts a slice of arguments and returns a slice of the same 141 | // length with each argument converted to a default spew Formatter interface. 142 | func convertArgs(args []interface{}) (formatters []interface{}) { 143 | formatters = make([]interface{}, len(args)) 144 | for index, arg := range args { 145 | formatters[index] = NewFormatter(arg) 146 | } 147 | return formatters 148 | } 149 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/davecgh/go-spew/spew/doc.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013 Dave Collins 3 | * 4 | * Permission to use, copy, modify, and distribute this software for any 5 | * purpose with or without fee is hereby granted, provided that the above 6 | * copyright notice and this permission notice appear in all copies. 7 | * 8 | * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 9 | * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 10 | * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 11 | * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 12 | * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 13 | * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 14 | * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 15 | */ 16 | 17 | /* 18 | Package spew implements a deep pretty printer for Go data structures to aid in 19 | debugging. 20 | 21 | A quick overview of the additional features spew provides over the built-in 22 | printing facilities for Go data types are as follows: 23 | 24 | * Pointers are dereferenced and followed 25 | * Circular data structures are detected and handled properly 26 | * Custom Stringer/error interfaces are optionally invoked, including 27 | on unexported types 28 | * Custom types which only implement the Stringer/error interfaces via 29 | a pointer receiver are optionally invoked when passing non-pointer 30 | variables 31 | * Byte arrays and slices are dumped like the hexdump -C command which 32 | includes offsets, byte values in hex, and ASCII output (only when using 33 | Dump style) 34 | 35 | There are two different approaches spew allows for dumping Go data structures: 36 | 37 | * Dump style which prints with newlines, customizable indentation, 38 | and additional debug information such as types and all pointer addresses 39 | used to indirect to the final value 40 | * A custom Formatter interface that integrates cleanly with the standard fmt 41 | package and replaces %v, %+v, %#v, and %#+v to provide inline printing 42 | similar to the default %v while providing the additional functionality 43 | outlined above and passing unsupported format verbs such as %x and %q 44 | along to fmt 45 | 46 | Quick Start 47 | 48 | This section demonstrates how to quickly get started with spew. See the 49 | sections below for further details on formatting and configuration options. 50 | 51 | To dump a variable with full newlines, indentation, type, and pointer 52 | information use Dump, Fdump, or Sdump: 53 | spew.Dump(myVar1, myVar2, ...) 54 | spew.Fdump(someWriter, myVar1, myVar2, ...) 55 | str := spew.Sdump(myVar1, myVar2, ...) 56 | 57 | Alternatively, if you would prefer to use format strings with a compacted inline 58 | printing style, use the convenience wrappers Printf, Fprintf, etc with 59 | %v (most compact), %+v (adds pointer addresses), %#v (adds types), or 60 | %#+v (adds types and pointer addresses): 61 | spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) 62 | spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) 63 | spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) 64 | spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) 65 | 66 | Configuration Options 67 | 68 | Configuration of spew is handled by fields in the ConfigState type. For 69 | convenience, all of the top-level functions use a global state available 70 | via the spew.Config global. 71 | 72 | It is also possible to create a ConfigState instance that provides methods 73 | equivalent to the top-level functions. This allows concurrent configuration 74 | options. See the ConfigState documentation for more details. 75 | 76 | The following configuration options are available: 77 | * Indent 78 | String to use for each indentation level for Dump functions. 79 | It is a single space by default. A popular alternative is "\t". 80 | 81 | * MaxDepth 82 | Maximum number of levels to descend into nested data structures. 83 | There is no limit by default. 84 | 85 | * DisableMethods 86 | Disables invocation of error and Stringer interface methods. 87 | Method invocation is enabled by default. 88 | 89 | * DisablePointerMethods 90 | Disables invocation of error and Stringer interface methods on types 91 | which only accept pointer receivers from non-pointer variables. 92 | Pointer method invocation is enabled by default. 93 | 94 | * ContinueOnMethod 95 | Enables recursion into types after invoking error and Stringer interface 96 | methods. Recursion after method invocation is disabled by default. 97 | 98 | * SortKeys 99 | Specifies map keys should be sorted before being printed. Use 100 | this to have a more deterministic, diffable output. Note that 101 | only native types (bool, int, uint, floats, uintptr and string) 102 | and types which implement error or Stringer interfaces are 103 | supported with other types sorted according to the 104 | reflect.Value.String() output which guarantees display 105 | stability. Natural map order is used by default. 106 | 107 | * SpewKeys 108 | Specifies that, as a last resort attempt, map keys should be 109 | spewed to strings and sorted by those strings. This is only 110 | considered if SortKeys is true. 111 | 112 | Dump Usage 113 | 114 | Simply call spew.Dump with a list of variables you want to dump: 115 | 116 | spew.Dump(myVar1, myVar2, ...) 117 | 118 | You may also call spew.Fdump if you would prefer to output to an arbitrary 119 | io.Writer. For example, to dump to standard error: 120 | 121 | spew.Fdump(os.Stderr, myVar1, myVar2, ...) 122 | 123 | A third option is to call spew.Sdump to get the formatted output as a string: 124 | 125 | str := spew.Sdump(myVar1, myVar2, ...) 126 | 127 | Sample Dump Output 128 | 129 | See the Dump example for details on the setup of the types and variables being 130 | shown here. 131 | 132 | (main.Foo) { 133 | unexportedField: (*main.Bar)(0xf84002e210)({ 134 | flag: (main.Flag) flagTwo, 135 | data: (uintptr) 136 | }), 137 | ExportedField: (map[interface {}]interface {}) (len=1) { 138 | (string) (len=3) "one": (bool) true 139 | } 140 | } 141 | 142 | Byte (and uint8) arrays and slices are displayed uniquely like the hexdump -C 143 | command as shown. 144 | ([]uint8) (len=32 cap=32) { 145 | 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | 146 | 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| 147 | 00000020 31 32 |12| 148 | } 149 | 150 | Custom Formatter 151 | 152 | Spew provides a custom formatter that implements the fmt.Formatter interface 153 | so that it integrates cleanly with standard fmt package printing functions. The 154 | formatter is useful for inline printing of smaller data types similar to the 155 | standard %v format specifier. 156 | 157 | The custom formatter only responds to the %v (most compact), %+v (adds pointer 158 | addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb 159 | combinations. Any other verbs such as %x and %q will be sent to the the 160 | standard fmt package for formatting. In addition, the custom formatter ignores 161 | the width and precision arguments (however they will still work on the format 162 | specifiers not handled by the custom formatter). 163 | 164 | Custom Formatter Usage 165 | 166 | The simplest way to make use of the spew custom formatter is to call one of the 167 | convenience functions such as spew.Printf, spew.Println, or spew.Printf. The 168 | functions have syntax you are most likely already familiar with: 169 | 170 | spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) 171 | spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) 172 | spew.Println(myVar, myVar2) 173 | spew.Fprintf(os.Stderr, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) 174 | spew.Fprintf(os.Stderr, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) 175 | 176 | See the Index for the full list convenience functions. 177 | 178 | Sample Formatter Output 179 | 180 | Double pointer to a uint8: 181 | %v: <**>5 182 | %+v: <**>(0xf8400420d0->0xf8400420c8)5 183 | %#v: (**uint8)5 184 | %#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5 185 | 186 | Pointer to circular struct with a uint8 field and a pointer to itself: 187 | %v: <*>{1 <*>} 188 | %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)} 189 | %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)} 190 | %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)} 191 | 192 | See the Printf example for details on the setup of variables being shown 193 | here. 194 | 195 | Errors 196 | 197 | Since it is possible for custom Stringer/error interfaces to panic, spew 198 | detects them and handles them internally by printing the panic information 199 | inline with the output. Since spew is intended to provide deep pretty printing 200 | capabilities on structures, it intentionally does not return any errors. 201 | */ 202 | package spew 203 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/davecgh/go-spew/spew/common.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013 Dave Collins 3 | * 4 | * Permission to use, copy, modify, and distribute this software for any 5 | * purpose with or without fee is hereby granted, provided that the above 6 | * copyright notice and this permission notice appear in all copies. 7 | * 8 | * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 9 | * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 10 | * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 11 | * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 12 | * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 13 | * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 14 | * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 15 | */ 16 | 17 | package spew 18 | 19 | import ( 20 | "bytes" 21 | "fmt" 22 | "io" 23 | "reflect" 24 | "sort" 25 | "strconv" 26 | ) 27 | 28 | // Some constants in the form of bytes to avoid string overhead. This mirrors 29 | // the technique used in the fmt package. 30 | var ( 31 | panicBytes = []byte("(PANIC=") 32 | plusBytes = []byte("+") 33 | iBytes = []byte("i") 34 | trueBytes = []byte("true") 35 | falseBytes = []byte("false") 36 | interfaceBytes = []byte("(interface {})") 37 | commaNewlineBytes = []byte(",\n") 38 | newlineBytes = []byte("\n") 39 | openBraceBytes = []byte("{") 40 | openBraceNewlineBytes = []byte("{\n") 41 | closeBraceBytes = []byte("}") 42 | asteriskBytes = []byte("*") 43 | colonBytes = []byte(":") 44 | colonSpaceBytes = []byte(": ") 45 | openParenBytes = []byte("(") 46 | closeParenBytes = []byte(")") 47 | spaceBytes = []byte(" ") 48 | pointerChainBytes = []byte("->") 49 | nilAngleBytes = []byte("") 50 | maxNewlineBytes = []byte("\n") 51 | maxShortBytes = []byte("") 52 | circularBytes = []byte("") 53 | circularShortBytes = []byte("") 54 | invalidAngleBytes = []byte("") 55 | openBracketBytes = []byte("[") 56 | closeBracketBytes = []byte("]") 57 | percentBytes = []byte("%") 58 | precisionBytes = []byte(".") 59 | openAngleBytes = []byte("<") 60 | closeAngleBytes = []byte(">") 61 | openMapBytes = []byte("map[") 62 | closeMapBytes = []byte("]") 63 | lenEqualsBytes = []byte("len=") 64 | capEqualsBytes = []byte("cap=") 65 | ) 66 | 67 | // hexDigits is used to map a decimal value to a hex digit. 68 | var hexDigits = "0123456789abcdef" 69 | 70 | // catchPanic handles any panics that might occur during the handleMethods 71 | // calls. 72 | func catchPanic(w io.Writer, v reflect.Value) { 73 | if err := recover(); err != nil { 74 | w.Write(panicBytes) 75 | fmt.Fprintf(w, "%v", err) 76 | w.Write(closeParenBytes) 77 | } 78 | } 79 | 80 | // handleMethods attempts to call the Error and String methods on the underlying 81 | // type the passed reflect.Value represents and outputes the result to Writer w. 82 | // 83 | // It handles panics in any called methods by catching and displaying the error 84 | // as the formatted value. 85 | func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) { 86 | // We need an interface to check if the type implements the error or 87 | // Stringer interface. However, the reflect package won't give us an 88 | // interface on certain things like unexported struct fields in order 89 | // to enforce visibility rules. We use unsafe, when it's available, 90 | // to bypass these restrictions since this package does not mutate the 91 | // values. 92 | if !v.CanInterface() { 93 | if UnsafeDisabled { 94 | return false 95 | } 96 | 97 | v = unsafeReflectValue(v) 98 | } 99 | 100 | // Choose whether or not to do error and Stringer interface lookups against 101 | // the base type or a pointer to the base type depending on settings. 102 | // Technically calling one of these methods with a pointer receiver can 103 | // mutate the value, however, types which choose to satisify an error or 104 | // Stringer interface with a pointer receiver should not be mutating their 105 | // state inside these interface methods. 106 | if !cs.DisablePointerMethods && !UnsafeDisabled && !v.CanAddr() { 107 | v = unsafeReflectValue(v) 108 | } 109 | if v.CanAddr() { 110 | v = v.Addr() 111 | } 112 | 113 | // Is it an error or Stringer? 114 | switch iface := v.Interface().(type) { 115 | case error: 116 | defer catchPanic(w, v) 117 | if cs.ContinueOnMethod { 118 | w.Write(openParenBytes) 119 | w.Write([]byte(iface.Error())) 120 | w.Write(closeParenBytes) 121 | w.Write(spaceBytes) 122 | return false 123 | } 124 | 125 | w.Write([]byte(iface.Error())) 126 | return true 127 | 128 | case fmt.Stringer: 129 | defer catchPanic(w, v) 130 | if cs.ContinueOnMethod { 131 | w.Write(openParenBytes) 132 | w.Write([]byte(iface.String())) 133 | w.Write(closeParenBytes) 134 | w.Write(spaceBytes) 135 | return false 136 | } 137 | w.Write([]byte(iface.String())) 138 | return true 139 | } 140 | return false 141 | } 142 | 143 | // printBool outputs a boolean value as true or false to Writer w. 144 | func printBool(w io.Writer, val bool) { 145 | if val { 146 | w.Write(trueBytes) 147 | } else { 148 | w.Write(falseBytes) 149 | } 150 | } 151 | 152 | // printInt outputs a signed integer value to Writer w. 153 | func printInt(w io.Writer, val int64, base int) { 154 | w.Write([]byte(strconv.FormatInt(val, base))) 155 | } 156 | 157 | // printUint outputs an unsigned integer value to Writer w. 158 | func printUint(w io.Writer, val uint64, base int) { 159 | w.Write([]byte(strconv.FormatUint(val, base))) 160 | } 161 | 162 | // printFloat outputs a floating point value using the specified precision, 163 | // which is expected to be 32 or 64bit, to Writer w. 164 | func printFloat(w io.Writer, val float64, precision int) { 165 | w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision))) 166 | } 167 | 168 | // printComplex outputs a complex value using the specified float precision 169 | // for the real and imaginary parts to Writer w. 170 | func printComplex(w io.Writer, c complex128, floatPrecision int) { 171 | r := real(c) 172 | w.Write(openParenBytes) 173 | w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision))) 174 | i := imag(c) 175 | if i >= 0 { 176 | w.Write(plusBytes) 177 | } 178 | w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision))) 179 | w.Write(iBytes) 180 | w.Write(closeParenBytes) 181 | } 182 | 183 | // printHexPtr outputs a uintptr formatted as hexidecimal with a leading '0x' 184 | // prefix to Writer w. 185 | func printHexPtr(w io.Writer, p uintptr) { 186 | // Null pointer. 187 | num := uint64(p) 188 | if num == 0 { 189 | w.Write(nilAngleBytes) 190 | return 191 | } 192 | 193 | // Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix 194 | buf := make([]byte, 18) 195 | 196 | // It's simpler to construct the hex string right to left. 197 | base := uint64(16) 198 | i := len(buf) - 1 199 | for num >= base { 200 | buf[i] = hexDigits[num%base] 201 | num /= base 202 | i-- 203 | } 204 | buf[i] = hexDigits[num] 205 | 206 | // Add '0x' prefix. 207 | i-- 208 | buf[i] = 'x' 209 | i-- 210 | buf[i] = '0' 211 | 212 | // Strip unused leading bytes. 213 | buf = buf[i:] 214 | w.Write(buf) 215 | } 216 | 217 | // valuesSorter implements sort.Interface to allow a slice of reflect.Value 218 | // elements to be sorted. 219 | type valuesSorter struct { 220 | values []reflect.Value 221 | strings []string // either nil or same len and values 222 | cs *ConfigState 223 | } 224 | 225 | // newValuesSorter initializes a valuesSorter instance, which holds a set of 226 | // surrogate keys on which the data should be sorted. It uses flags in 227 | // ConfigState to decide if and how to populate those surrogate keys. 228 | func newValuesSorter(values []reflect.Value, cs *ConfigState) sort.Interface { 229 | vs := &valuesSorter{values: values, cs: cs} 230 | if canSortSimply(vs.values[0].Kind()) { 231 | return vs 232 | } 233 | if !cs.DisableMethods { 234 | vs.strings = make([]string, len(values)) 235 | for i := range vs.values { 236 | b := bytes.Buffer{} 237 | if !handleMethods(cs, &b, vs.values[i]) { 238 | vs.strings = nil 239 | break 240 | } 241 | vs.strings[i] = b.String() 242 | } 243 | } 244 | if vs.strings == nil && cs.SpewKeys { 245 | vs.strings = make([]string, len(values)) 246 | for i := range vs.values { 247 | vs.strings[i] = Sprintf("%#v", vs.values[i].Interface()) 248 | } 249 | } 250 | return vs 251 | } 252 | 253 | // canSortSimply tests whether a reflect.Kind is a primitive that can be sorted 254 | // directly, or whether it should be considered for sorting by surrogate keys 255 | // (if the ConfigState allows it). 256 | func canSortSimply(kind reflect.Kind) bool { 257 | // This switch parallels valueSortLess, except for the default case. 258 | switch kind { 259 | case reflect.Bool: 260 | return true 261 | case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: 262 | return true 263 | case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: 264 | return true 265 | case reflect.Float32, reflect.Float64: 266 | return true 267 | case reflect.String: 268 | return true 269 | case reflect.Uintptr: 270 | return true 271 | case reflect.Array: 272 | return true 273 | } 274 | return false 275 | } 276 | 277 | // Len returns the number of values in the slice. It is part of the 278 | // sort.Interface implementation. 279 | func (s *valuesSorter) Len() int { 280 | return len(s.values) 281 | } 282 | 283 | // Swap swaps the values at the passed indices. It is part of the 284 | // sort.Interface implementation. 285 | func (s *valuesSorter) Swap(i, j int) { 286 | s.values[i], s.values[j] = s.values[j], s.values[i] 287 | if s.strings != nil { 288 | s.strings[i], s.strings[j] = s.strings[j], s.strings[i] 289 | } 290 | } 291 | 292 | // valueSortLess returns whether the first value should sort before the second 293 | // value. It is used by valueSorter.Less as part of the sort.Interface 294 | // implementation. 295 | func valueSortLess(a, b reflect.Value) bool { 296 | switch a.Kind() { 297 | case reflect.Bool: 298 | return !a.Bool() && b.Bool() 299 | case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: 300 | return a.Int() < b.Int() 301 | case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: 302 | return a.Uint() < b.Uint() 303 | case reflect.Float32, reflect.Float64: 304 | return a.Float() < b.Float() 305 | case reflect.String: 306 | return a.String() < b.String() 307 | case reflect.Uintptr: 308 | return a.Uint() < b.Uint() 309 | case reflect.Array: 310 | // Compare the contents of both arrays. 311 | l := a.Len() 312 | for i := 0; i < l; i++ { 313 | av := a.Index(i) 314 | bv := b.Index(i) 315 | if av.Interface() == bv.Interface() { 316 | continue 317 | } 318 | return valueSortLess(av, bv) 319 | } 320 | } 321 | return a.String() < b.String() 322 | } 323 | 324 | // Less returns whether the value at index i should sort before the 325 | // value at index j. It is part of the sort.Interface implementation. 326 | func (s *valuesSorter) Less(i, j int) bool { 327 | if s.strings == nil { 328 | return valueSortLess(s.values[i], s.values[j]) 329 | } 330 | return s.strings[i] < s.strings[j] 331 | } 332 | 333 | // sortValues is a sort function that handles both native types and any type that 334 | // can be converted to error or Stringer. Other inputs are sorted according to 335 | // their Value.String() value to ensure display stability. 336 | func sortValues(values []reflect.Value, cs *ConfigState) { 337 | if len(values) == 0 { 338 | return 339 | } 340 | sort.Sort(newValuesSorter(values, cs)) 341 | } 342 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/davecgh/go-spew/spew/format.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013 Dave Collins 3 | * 4 | * Permission to use, copy, modify, and distribute this software for any 5 | * purpose with or without fee is hereby granted, provided that the above 6 | * copyright notice and this permission notice appear in all copies. 7 | * 8 | * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 9 | * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 10 | * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 11 | * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 12 | * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 13 | * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 14 | * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 15 | */ 16 | 17 | package spew 18 | 19 | import ( 20 | "bytes" 21 | "fmt" 22 | "reflect" 23 | "strconv" 24 | "strings" 25 | ) 26 | 27 | // supportedFlags is a list of all the character flags supported by fmt package. 28 | const supportedFlags = "0-+# " 29 | 30 | // formatState implements the fmt.Formatter interface and contains information 31 | // about the state of a formatting operation. The NewFormatter function can 32 | // be used to get a new Formatter which can be used directly as arguments 33 | // in standard fmt package printing calls. 34 | type formatState struct { 35 | value interface{} 36 | fs fmt.State 37 | depth int 38 | pointers map[uintptr]int 39 | ignoreNextType bool 40 | cs *ConfigState 41 | } 42 | 43 | // buildDefaultFormat recreates the original format string without precision 44 | // and width information to pass in to fmt.Sprintf in the case of an 45 | // unrecognized type. Unless new types are added to the language, this 46 | // function won't ever be called. 47 | func (f *formatState) buildDefaultFormat() (format string) { 48 | buf := bytes.NewBuffer(percentBytes) 49 | 50 | for _, flag := range supportedFlags { 51 | if f.fs.Flag(int(flag)) { 52 | buf.WriteRune(flag) 53 | } 54 | } 55 | 56 | buf.WriteRune('v') 57 | 58 | format = buf.String() 59 | return format 60 | } 61 | 62 | // constructOrigFormat recreates the original format string including precision 63 | // and width information to pass along to the standard fmt package. This allows 64 | // automatic deferral of all format strings this package doesn't support. 65 | func (f *formatState) constructOrigFormat(verb rune) (format string) { 66 | buf := bytes.NewBuffer(percentBytes) 67 | 68 | for _, flag := range supportedFlags { 69 | if f.fs.Flag(int(flag)) { 70 | buf.WriteRune(flag) 71 | } 72 | } 73 | 74 | if width, ok := f.fs.Width(); ok { 75 | buf.WriteString(strconv.Itoa(width)) 76 | } 77 | 78 | if precision, ok := f.fs.Precision(); ok { 79 | buf.Write(precisionBytes) 80 | buf.WriteString(strconv.Itoa(precision)) 81 | } 82 | 83 | buf.WriteRune(verb) 84 | 85 | format = buf.String() 86 | return format 87 | } 88 | 89 | // unpackValue returns values inside of non-nil interfaces when possible and 90 | // ensures that types for values which have been unpacked from an interface 91 | // are displayed when the show types flag is also set. 92 | // This is useful for data types like structs, arrays, slices, and maps which 93 | // can contain varying types packed inside an interface. 94 | func (f *formatState) unpackValue(v reflect.Value) reflect.Value { 95 | if v.Kind() == reflect.Interface { 96 | f.ignoreNextType = false 97 | if !v.IsNil() { 98 | v = v.Elem() 99 | } 100 | } 101 | return v 102 | } 103 | 104 | // formatPtr handles formatting of pointers by indirecting them as necessary. 105 | func (f *formatState) formatPtr(v reflect.Value) { 106 | // Display nil if top level pointer is nil. 107 | showTypes := f.fs.Flag('#') 108 | if v.IsNil() && (!showTypes || f.ignoreNextType) { 109 | f.fs.Write(nilAngleBytes) 110 | return 111 | } 112 | 113 | // Remove pointers at or below the current depth from map used to detect 114 | // circular refs. 115 | for k, depth := range f.pointers { 116 | if depth >= f.depth { 117 | delete(f.pointers, k) 118 | } 119 | } 120 | 121 | // Keep list of all dereferenced pointers to possibly show later. 122 | pointerChain := make([]uintptr, 0) 123 | 124 | // Figure out how many levels of indirection there are by derferencing 125 | // pointers and unpacking interfaces down the chain while detecting circular 126 | // references. 127 | nilFound := false 128 | cycleFound := false 129 | indirects := 0 130 | ve := v 131 | for ve.Kind() == reflect.Ptr { 132 | if ve.IsNil() { 133 | nilFound = true 134 | break 135 | } 136 | indirects++ 137 | addr := ve.Pointer() 138 | pointerChain = append(pointerChain, addr) 139 | if pd, ok := f.pointers[addr]; ok && pd < f.depth { 140 | cycleFound = true 141 | indirects-- 142 | break 143 | } 144 | f.pointers[addr] = f.depth 145 | 146 | ve = ve.Elem() 147 | if ve.Kind() == reflect.Interface { 148 | if ve.IsNil() { 149 | nilFound = true 150 | break 151 | } 152 | ve = ve.Elem() 153 | } 154 | } 155 | 156 | // Display type or indirection level depending on flags. 157 | if showTypes && !f.ignoreNextType { 158 | f.fs.Write(openParenBytes) 159 | f.fs.Write(bytes.Repeat(asteriskBytes, indirects)) 160 | f.fs.Write([]byte(ve.Type().String())) 161 | f.fs.Write(closeParenBytes) 162 | } else { 163 | if nilFound || cycleFound { 164 | indirects += strings.Count(ve.Type().String(), "*") 165 | } 166 | f.fs.Write(openAngleBytes) 167 | f.fs.Write([]byte(strings.Repeat("*", indirects))) 168 | f.fs.Write(closeAngleBytes) 169 | } 170 | 171 | // Display pointer information depending on flags. 172 | if f.fs.Flag('+') && (len(pointerChain) > 0) { 173 | f.fs.Write(openParenBytes) 174 | for i, addr := range pointerChain { 175 | if i > 0 { 176 | f.fs.Write(pointerChainBytes) 177 | } 178 | printHexPtr(f.fs, addr) 179 | } 180 | f.fs.Write(closeParenBytes) 181 | } 182 | 183 | // Display dereferenced value. 184 | switch { 185 | case nilFound == true: 186 | f.fs.Write(nilAngleBytes) 187 | 188 | case cycleFound == true: 189 | f.fs.Write(circularShortBytes) 190 | 191 | default: 192 | f.ignoreNextType = true 193 | f.format(ve) 194 | } 195 | } 196 | 197 | // format is the main workhorse for providing the Formatter interface. It 198 | // uses the passed reflect value to figure out what kind of object we are 199 | // dealing with and formats it appropriately. It is a recursive function, 200 | // however circular data structures are detected and handled properly. 201 | func (f *formatState) format(v reflect.Value) { 202 | // Handle invalid reflect values immediately. 203 | kind := v.Kind() 204 | if kind == reflect.Invalid { 205 | f.fs.Write(invalidAngleBytes) 206 | return 207 | } 208 | 209 | // Handle pointers specially. 210 | if kind == reflect.Ptr { 211 | f.formatPtr(v) 212 | return 213 | } 214 | 215 | // Print type information unless already handled elsewhere. 216 | if !f.ignoreNextType && f.fs.Flag('#') { 217 | f.fs.Write(openParenBytes) 218 | f.fs.Write([]byte(v.Type().String())) 219 | f.fs.Write(closeParenBytes) 220 | } 221 | f.ignoreNextType = false 222 | 223 | // Call Stringer/error interfaces if they exist and the handle methods 224 | // flag is enabled. 225 | if !f.cs.DisableMethods { 226 | if (kind != reflect.Invalid) && (kind != reflect.Interface) { 227 | if handled := handleMethods(f.cs, f.fs, v); handled { 228 | return 229 | } 230 | } 231 | } 232 | 233 | switch kind { 234 | case reflect.Invalid: 235 | // Do nothing. We should never get here since invalid has already 236 | // been handled above. 237 | 238 | case reflect.Bool: 239 | printBool(f.fs, v.Bool()) 240 | 241 | case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: 242 | printInt(f.fs, v.Int(), 10) 243 | 244 | case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: 245 | printUint(f.fs, v.Uint(), 10) 246 | 247 | case reflect.Float32: 248 | printFloat(f.fs, v.Float(), 32) 249 | 250 | case reflect.Float64: 251 | printFloat(f.fs, v.Float(), 64) 252 | 253 | case reflect.Complex64: 254 | printComplex(f.fs, v.Complex(), 32) 255 | 256 | case reflect.Complex128: 257 | printComplex(f.fs, v.Complex(), 64) 258 | 259 | case reflect.Slice: 260 | if v.IsNil() { 261 | f.fs.Write(nilAngleBytes) 262 | break 263 | } 264 | fallthrough 265 | 266 | case reflect.Array: 267 | f.fs.Write(openBracketBytes) 268 | f.depth++ 269 | if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { 270 | f.fs.Write(maxShortBytes) 271 | } else { 272 | numEntries := v.Len() 273 | for i := 0; i < numEntries; i++ { 274 | if i > 0 { 275 | f.fs.Write(spaceBytes) 276 | } 277 | f.ignoreNextType = true 278 | f.format(f.unpackValue(v.Index(i))) 279 | } 280 | } 281 | f.depth-- 282 | f.fs.Write(closeBracketBytes) 283 | 284 | case reflect.String: 285 | f.fs.Write([]byte(v.String())) 286 | 287 | case reflect.Interface: 288 | // The only time we should get here is for nil interfaces due to 289 | // unpackValue calls. 290 | if v.IsNil() { 291 | f.fs.Write(nilAngleBytes) 292 | } 293 | 294 | case reflect.Ptr: 295 | // Do nothing. We should never get here since pointers have already 296 | // been handled above. 297 | 298 | case reflect.Map: 299 | // nil maps should be indicated as different than empty maps 300 | if v.IsNil() { 301 | f.fs.Write(nilAngleBytes) 302 | break 303 | } 304 | 305 | f.fs.Write(openMapBytes) 306 | f.depth++ 307 | if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { 308 | f.fs.Write(maxShortBytes) 309 | } else { 310 | keys := v.MapKeys() 311 | if f.cs.SortKeys { 312 | sortValues(keys, f.cs) 313 | } 314 | for i, key := range keys { 315 | if i > 0 { 316 | f.fs.Write(spaceBytes) 317 | } 318 | f.ignoreNextType = true 319 | f.format(f.unpackValue(key)) 320 | f.fs.Write(colonBytes) 321 | f.ignoreNextType = true 322 | f.format(f.unpackValue(v.MapIndex(key))) 323 | } 324 | } 325 | f.depth-- 326 | f.fs.Write(closeMapBytes) 327 | 328 | case reflect.Struct: 329 | numFields := v.NumField() 330 | f.fs.Write(openBraceBytes) 331 | f.depth++ 332 | if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { 333 | f.fs.Write(maxShortBytes) 334 | } else { 335 | vt := v.Type() 336 | for i := 0; i < numFields; i++ { 337 | if i > 0 { 338 | f.fs.Write(spaceBytes) 339 | } 340 | vtf := vt.Field(i) 341 | if f.fs.Flag('+') || f.fs.Flag('#') { 342 | f.fs.Write([]byte(vtf.Name)) 343 | f.fs.Write(colonBytes) 344 | } 345 | f.format(f.unpackValue(v.Field(i))) 346 | } 347 | } 348 | f.depth-- 349 | f.fs.Write(closeBraceBytes) 350 | 351 | case reflect.Uintptr: 352 | printHexPtr(f.fs, uintptr(v.Uint())) 353 | 354 | case reflect.UnsafePointer, reflect.Chan, reflect.Func: 355 | printHexPtr(f.fs, v.Pointer()) 356 | 357 | // There were not any other types at the time this code was written, but 358 | // fall back to letting the default fmt package handle it if any get added. 359 | default: 360 | format := f.buildDefaultFormat() 361 | if v.CanInterface() { 362 | fmt.Fprintf(f.fs, format, v.Interface()) 363 | } else { 364 | fmt.Fprintf(f.fs, format, v.String()) 365 | } 366 | } 367 | } 368 | 369 | // Format satisfies the fmt.Formatter interface. See NewFormatter for usage 370 | // details. 371 | func (f *formatState) Format(fs fmt.State, verb rune) { 372 | f.fs = fs 373 | 374 | // Use standard formatting for verbs that are not v. 375 | if verb != 'v' { 376 | format := f.constructOrigFormat(verb) 377 | fmt.Fprintf(fs, format, f.value) 378 | return 379 | } 380 | 381 | if f.value == nil { 382 | if fs.Flag('#') { 383 | fs.Write(interfaceBytes) 384 | } 385 | fs.Write(nilAngleBytes) 386 | return 387 | } 388 | 389 | f.format(reflect.ValueOf(f.value)) 390 | } 391 | 392 | // newFormatter is a helper function to consolidate the logic from the various 393 | // public methods which take varying config states. 394 | func newFormatter(cs *ConfigState, v interface{}) fmt.Formatter { 395 | fs := &formatState{value: v, cs: cs} 396 | fs.pointers = make(map[uintptr]int) 397 | return fs 398 | } 399 | 400 | /* 401 | NewFormatter returns a custom formatter that satisfies the fmt.Formatter 402 | interface. As a result, it integrates cleanly with standard fmt package 403 | printing functions. The formatter is useful for inline printing of smaller data 404 | types similar to the standard %v format specifier. 405 | 406 | The custom formatter only responds to the %v (most compact), %+v (adds pointer 407 | addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb 408 | combinations. Any other verbs such as %x and %q will be sent to the the 409 | standard fmt package for formatting. In addition, the custom formatter ignores 410 | the width and precision arguments (however they will still work on the format 411 | specifiers not handled by the custom formatter). 412 | 413 | Typically this function shouldn't be called directly. It is much easier to make 414 | use of the custom formatter by calling one of the convenience functions such as 415 | Printf, Println, or Fprintf. 416 | */ 417 | func NewFormatter(v interface{}) fmt.Formatter { 418 | return newFormatter(&Config, v) 419 | } 420 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/joyt/godate/godate.go: -------------------------------------------------------------------------------- 1 | package date 2 | 3 | import ( 4 | "bytes" 5 | "errors" 6 | "fmt" 7 | "regexp" 8 | "strings" 9 | "time" 10 | ) 11 | 12 | const ( 13 | formatyyyyMMdd = "__06.01._2" 14 | formatyyyyMdd = "__06.1._2" 15 | formatyyyyMMMdd = "__06.Jan._2" 16 | formatyyyyMMMMdd = "__06.January._2" 17 | formatMMddyyyy = "01._2.__06" 18 | formatMddyyyy = "1._2.__06" 19 | formatMMMddyyyy = "Jan._2.__06" 20 | formatMMMMddyyyy = "January._2.__06" 21 | formatddMMyyyy = "_2.01.__06" 22 | formatddMyyyy = "_2.1.__06" 23 | formatddMMMyyyy = "_2.Jan.__06" 24 | formatddMMMMyyyy = "_2.January.__06" 25 | 26 | formatyyyyMM = "__06.01" 27 | formatyyyyM = "__06.1" 28 | formatyyyyMMM = "__06.Jan" 29 | formatyyyyMMMM = "__06.January" 30 | formatMMyyyy = "01.__06" 31 | formatMyyyy = "1.__06" 32 | formatMMMyyyy = "Jan.__06" 33 | formatMMMMyyyy = "January.__06" 34 | 35 | formatMMdd = "01._2" // Always chosen over ddMM if both are possible. 36 | formatMdd = "1._2" // Always chosen over ddMM if both are possible. 37 | formatMMMdd = "Jan._2" 38 | formatMMMMdd = "January._2" 39 | formatddMM = "_2.01" 40 | formatddM = "_2.1" 41 | formatddMMM = "_2.Jan" 42 | formatddMMMM = "_2.January" 43 | 44 | formatHHmmss = "15:04:05" 45 | formatHHmm = "15:04" 46 | formathhmmssa = "03:04:05pm" 47 | formathhmma = "03:04pm" 48 | formathmmssa = "3:04:05pm" 49 | formathmma = "3:04pm" 50 | 51 | formatzzz = "MST" 52 | formatZZZ = "-0700" 53 | formatZZZZ = "GMT-07:00" 54 | // TODO: Handle Z format timezones outside of standard. 55 | 56 | formatEEE = "Mon" 57 | formatEEEE = "Monday" 58 | ) 59 | 60 | var ( 61 | separatorRegex = regexp.MustCompile("[^a-zA-Z0-9]+") 62 | timezoneRegex = regexp.MustCompile("[A-Z]{2,4}T") 63 | timezoneNumericRegex = regexp.MustCompile("((GMT)|Z)?[-+][0-9]{2}:?[0-9]{2}") 64 | 65 | // TODO: Nov and Mar may conflict with some timezones. 66 | months = []string{"january", "februrary", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"} 67 | monthsShort = []string{"jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"} 68 | daysOfWeekShort = []string{"mon", "tue", "wed", "thu", "fri", "sat", "sun"} 69 | daysOfWeek = []string{"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"} 70 | 71 | standardDateFormats = []string{ 72 | time.RFC1123, 73 | time.RFC1123Z, 74 | time.RFC3339, 75 | time.RFC3339Nano, 76 | time.RFC822, 77 | time.RFC822Z, 78 | time.RFC850, 79 | time.RubyDate, 80 | time.UnixDate, 81 | time.Kitchen, 82 | time.ANSIC, 83 | time.Stamp, 84 | time.StampMilli, 85 | time.StampMicro, 86 | time.StampNano, 87 | } 88 | dateFormatsWithShortMonth = []string{ 89 | formatyyyyMMMdd, 90 | formatMMMddyyyy, 91 | formatddMMMyyyy, 92 | formatMMMdd, 93 | formatddMMM, 94 | formatMMMyyyy, 95 | formatyyyyMMM, 96 | } 97 | dateFormatsWithLongMonth = []string{ 98 | formatyyyyMMMMdd, 99 | formatMMMMddyyyy, 100 | formatddMMMMyyyy, 101 | formatMMMMdd, 102 | formatddMMMM, 103 | formatMMMMyyyy, 104 | formatyyyyMMMM, 105 | } 106 | dateFormatsNumeric = []string{ 107 | formatMddyyyy, 108 | formatMMddyyyy, 109 | formatddMMyyyy, 110 | formatddMyyyy, 111 | formatyyyyMMdd, 112 | formatyyyyMdd, 113 | formatMMdd, 114 | formatMdd, 115 | formatddMM, 116 | formatddM, 117 | formatMMyyyy, 118 | formatMyyyy, 119 | formatyyyyMM, 120 | formatyyyyM, 121 | } 122 | dateFormatsNumericYearFirst = []string{ 123 | formatyyyyMM, 124 | formatyyyyM, 125 | formatyyyyMMdd, 126 | formatyyyyMdd, 127 | formatMddyyyy, 128 | formatMMddyyyy, 129 | formatddMMyyyy, 130 | formatddMyyyy, 131 | formatMMyyyy, 132 | formatMyyyy, 133 | formatMMdd, 134 | formatMdd, 135 | formatddMM, 136 | formatddM, 137 | } 138 | timeFormats = []string{ 139 | formatHHmmss, 140 | formatHHmm, 141 | formathhmmssa, 142 | formathhmma, 143 | formathmmssa, 144 | formathmma, 145 | } 146 | timeZoneFormats = []string{ 147 | formatzzz, 148 | formatZZZ, 149 | formatZZZZ, 150 | } 151 | ) 152 | 153 | func init() { 154 | timezoneRegex.Longest() 155 | timezoneNumericRegex.Longest() 156 | separatorRegex.Longest() 157 | } 158 | 159 | // Parse attempts to parse this string as a timestamp, returning an error 160 | // if it cannot. Example inputs: "July 9 1977", "07/9/1977 5:03pm". 161 | // Assumes UTC if a timezone is not provided. 162 | func Parse(s string) (time.Time, error) { 163 | d, _, err := ParseAndGetLayout(s) 164 | return d, err 165 | } 166 | 167 | // MustParse is like Parse except it panics if the string is not parseable. 168 | func MustParse(s string) time.Time { 169 | d, err := Parse(s) 170 | if err != nil { 171 | panic(err) 172 | } 173 | return d 174 | } 175 | 176 | // ParseInLocation is like Parse except it uses the given location when parsing the date. 177 | func ParseInLocation(s string, loc *time.Location) (time.Time, error) { 178 | _, l, err := ParseAndGetLayout(s) 179 | if err != nil { 180 | return time.Time{}, err 181 | } 182 | t, err := time.ParseInLocation(l, s, loc) 183 | return t, err 184 | } 185 | 186 | // ParseAndGetLayout attempts to parse this string as a timestamp 187 | // and if successful, returns the timestamp and the layout of the 188 | // string. 189 | func ParseAndGetLayout(date string) (time.Time, string, error) { 190 | if len(strings.TrimSpace(date)) == 0 { 191 | return time.Time{}, "", errors.New("Empty string cannot be parsed to date") 192 | } 193 | // Check standard date formats first. 194 | for _, f := range standardDateFormats { 195 | if t, err := time.Parse(f, date); err == nil { 196 | return t, f, nil 197 | } 198 | } 199 | s := strings.ToLower(date) 200 | layout := &bytes.Buffer{} 201 | prefix := getPrefix(s) 202 | layout.WriteString(prefix) 203 | s = strings.TrimPrefix(s, prefix) 204 | 205 | // Check for day of week. 206 | for _, d := range daysOfWeek { 207 | if strings.HasPrefix(s, d) { 208 | s = strings.TrimPrefix(s, d) 209 | layout.WriteString(formatEEEE) 210 | } 211 | } 212 | for _, d := range daysOfWeekShort { 213 | if strings.HasPrefix(s, d) { 214 | s = strings.TrimPrefix(s, d) 215 | layout.WriteString(formatEEE) 216 | } 217 | } 218 | 219 | // Get rid of prefix and suffix. 220 | prefix = getPrefix(s) 221 | separators := separatorRegex.FindAllStringSubmatch(s, -1) 222 | if len(prefix) > 0 { 223 | s = strings.TrimPrefix(s, prefix) 224 | layout.WriteString(prefix) 225 | separators = separators[1:] 226 | } 227 | var suffix string 228 | if len(separators) > 0 && strings.HasSuffix(s, separators[len(separators)-1][0]) { 229 | suffix = separators[len(separators)-1][0] 230 | s = strings.TrimSuffix(s, suffix) 231 | separators = separators[:len(separators)-1] 232 | } 233 | 234 | // Narrow down formats needed to check. 235 | // TODO: Make more efficient by checking fewer formats variations. 236 | var formats []string 237 | containsTime := containsTime(date) 238 | containsTimezone := containsTimezone(date) 239 | var onlyTime bool 240 | if containsLongMonth(s) { 241 | formats = dateFormatsWithLongMonth 242 | } else if containsShortMonth(s) { 243 | formats = dateFormatsWithShortMonth 244 | } else if (len(separators) <= 3 && containsTime && containsTimezone) || (len(separators) <= 2 && containsTime) { 245 | if containsTimezone { 246 | formats = getCombinations(timeFormats, timeZoneFormats, false) 247 | } else { 248 | formats = timeFormats 249 | } 250 | onlyTime = true 251 | } else if len(separators) == 0 { 252 | // If the date is all munged together, assume year is first rather than month. 253 | formats = dateFormatsNumericYearFirst 254 | } else { 255 | formats = dateFormatsNumeric 256 | } 257 | if containsTimezone { 258 | // time.Parse only accepts uppercase timezones names, so need to convert back. 259 | if tz := timezoneRegex.FindStringSubmatch(date); len(tz) > 0 { 260 | s = strings.Replace(s, strings.ToLower(tz[0]), tz[0], -1) 261 | } 262 | } 263 | 264 | // Check possible formats. 265 | for _, f := range formats { 266 | variations := getVariations(f, containsTime && !onlyTime, containsTimezone && !onlyTime) 267 | var correct string 268 | for _, v := range variations { 269 | if strings.Contains(v, ":") { 270 | v = strings.Replace(v, ":", ".", -1) 271 | } 272 | l := formatWithSeparators(v, separators) 273 | if _, err := time.Parse(l, s); err == nil { 274 | correct = l 275 | break 276 | } 277 | } 278 | if len(correct) > 0 { 279 | layout.WriteString(correct) 280 | break 281 | } 282 | } 283 | layout.WriteString(suffix) 284 | 285 | // Return Date and format. 286 | date = strings.Replace(date, "AM", "am", -1) 287 | date = strings.Replace(date, "PM", "pm", -1) 288 | t, err := time.Parse(layout.String(), date) 289 | if err != nil { 290 | return time.Time{}, "", err 291 | } 292 | return t, layout.String(), err 293 | } 294 | 295 | // Layout returns the layout of this date, appropriate for use 296 | // with the Go time package, for example "Jan 02 2006". 297 | // See http://golang.org/pkg/time/ for more examples. 298 | func Layout(s string) string { 299 | _, l, err := ParseAndGetLayout(s) 300 | if err == nil { 301 | return l 302 | } 303 | return "" 304 | } 305 | 306 | // LayoutUnicode returns the layout of this date according to the 307 | // Unicode standard: http://www.unicode.org/reports/tr35/tr35-19.html#Date_Format_Patterns 308 | // NOT TESTED. 309 | func LayoutUnicode(s string) string { 310 | _, l, err := ParseAndGetLayout(s) 311 | if err == nil { 312 | return ConvertGoLayoutToUnicode(l) 313 | } 314 | return "" 315 | } 316 | 317 | // ConvertGoLayoutToUnicode converts the given time layout string 318 | // to on using the Unicode standard prescribed in 319 | // http://www.unicode.org/reports/tr35/tr35-19.html#Date_Format_Patterns 320 | // NOT TESTED. 321 | func ConvertGoLayoutToUnicode(layout string) string { 322 | // Year 323 | layout = strings.Replace(layout, "20", "yy", -1) 324 | layout = strings.Replace(layout, "06", "yy", -1) 325 | 326 | // Month 327 | layout = strings.Replace(layout, "January", "MMMM", -1) 328 | layout = strings.Replace(layout, "Jan", "MMM", -1) 329 | layout = strings.Replace(layout, "01", "MM", -1) 330 | layout = strings.Replace(layout, "1", "M", -1) 331 | 332 | // Day 333 | layout = strings.Replace(layout, "02", "dd", -1) 334 | layout = strings.Replace(layout, "_2", "d", -1) 335 | 336 | // Weekday 337 | layout = strings.Replace(layout, "Mon", "EEE", -1) 338 | layout = strings.Replace(layout, "Monday", "EEEE", -1) 339 | 340 | // Hour 341 | layout = strings.Replace(layout, "03", "hh", -1) 342 | layout = strings.Replace(layout, "3", "h", -1) 343 | layout = strings.Replace(layout, "15", "HH", -1) 344 | layout = strings.Replace(layout, "PM", "a", -1) 345 | 346 | // Minute 347 | layout = strings.Replace(layout, "04", "mm", -1) 348 | 349 | // Second 350 | layout = strings.Replace(layout, "05", "ss", -1) 351 | 352 | // Timezone 353 | layout = strings.Replace(layout, "MST", "zzz", -1) 354 | layout = strings.Replace(layout, "-0700", "ZZZ", -1) 355 | layout = strings.Replace(layout, "GMT-07:00", "ZZZZ", -1) 356 | 357 | return layout 358 | } 359 | 360 | // Private Methods 361 | 362 | func getVariations(f string, includeTime, includeTimezone bool) []string { 363 | var v []string 364 | if strings.Contains(f, "__") { 365 | v = []string{strings.Replace(f, "__", "20", 1), strings.Replace(f, "__", "", 1)} 366 | } else { 367 | v = []string{f} 368 | } 369 | l := len(v) 370 | for i := 0; i < l; i++ { 371 | if strings.Contains(v[i], "_") { 372 | v = append(v, strings.Replace(v[i], "_", "0", -1)) 373 | } 374 | } 375 | if includeTime { 376 | if includeTimezone { 377 | times := getCombinations(timeFormats, timeZoneFormats, false) 378 | v = getCombinations(v, times, true) 379 | } else { 380 | v = getCombinations(v, timeFormats, true) 381 | } 382 | } 383 | return v 384 | } 385 | 386 | func getCombinations(a, b []string, switchOrder bool) []string { 387 | var res []string 388 | for _, s := range a { 389 | for _, s2 := range b { 390 | res = append(res, fmt.Sprintf("%s.%s", s, s2)) 391 | if switchOrder { 392 | res = append(res, fmt.Sprintf("%s.%s", s2, s)) 393 | } 394 | } 395 | } 396 | return res 397 | } 398 | 399 | func getPrefix(s string) string { 400 | firstMatch := separatorRegex.FindStringSubmatchIndex(s) 401 | if len(firstMatch) == 0 { 402 | return "" 403 | } 404 | if firstMatch[0] == 0 { 405 | return s[:firstMatch[1]] 406 | } 407 | return "" 408 | } 409 | 410 | func containsShortMonth(s string) bool { 411 | for _, m := range monthsShort { 412 | if strings.Contains(s, m) { 413 | return true 414 | } 415 | } 416 | return false 417 | } 418 | 419 | func containsLongMonth(s string) bool { 420 | for _, m := range months { 421 | if strings.Contains(s, m) { 422 | return true 423 | } 424 | } 425 | return false 426 | } 427 | 428 | func containsTime(s string) bool { 429 | return strings.Contains(s, ":") 430 | } 431 | 432 | func containsTimezone(s string) bool { 433 | return (timezoneRegex.MatchString(s) || timezoneNumericRegex.MatchString(s)) && 434 | !(strings.Contains(s, "SEPT") || strings.Contains(s, "OCT") || strings.Contains(s, "SAT")) 435 | } 436 | 437 | func formatWithSeparators(f string, sep [][]string) string { 438 | if len(sep) == 0 { 439 | return strings.Replace(f, ".", "", -1) 440 | } 441 | for i := 0; i < len(sep); i++ { 442 | s := sep[i][0] 443 | if s == "." { 444 | s = "." 445 | } 446 | f = strings.Replace(f, ".", s, 1) 447 | } 448 | return strings.Replace(f, ".", ".", -1) 449 | } 450 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/davecgh/go-spew/spew/config.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013 Dave Collins 3 | * 4 | * Permission to use, copy, modify, and distribute this software for any 5 | * purpose with or without fee is hereby granted, provided that the above 6 | * copyright notice and this permission notice appear in all copies. 7 | * 8 | * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 9 | * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 10 | * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 11 | * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 12 | * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 13 | * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 14 | * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 15 | */ 16 | 17 | package spew 18 | 19 | import ( 20 | "bytes" 21 | "fmt" 22 | "io" 23 | "os" 24 | ) 25 | 26 | // ConfigState houses the configuration options used by spew to format and 27 | // display values. There is a global instance, Config, that is used to control 28 | // all top-level Formatter and Dump functionality. Each ConfigState instance 29 | // provides methods equivalent to the top-level functions. 30 | // 31 | // The zero value for ConfigState provides no indentation. You would typically 32 | // want to set it to a space or a tab. 33 | // 34 | // Alternatively, you can use NewDefaultConfig to get a ConfigState instance 35 | // with default settings. See the documentation of NewDefaultConfig for default 36 | // values. 37 | type ConfigState struct { 38 | // Indent specifies the string to use for each indentation level. The 39 | // global config instance that all top-level functions use set this to a 40 | // single space by default. If you would like more indentation, you might 41 | // set this to a tab with "\t" or perhaps two spaces with " ". 42 | Indent string 43 | 44 | // MaxDepth controls the maximum number of levels to descend into nested 45 | // data structures. The default, 0, means there is no limit. 46 | // 47 | // NOTE: Circular data structures are properly detected, so it is not 48 | // necessary to set this value unless you specifically want to limit deeply 49 | // nested data structures. 50 | MaxDepth int 51 | 52 | // DisableMethods specifies whether or not error and Stringer interfaces are 53 | // invoked for types that implement them. 54 | DisableMethods bool 55 | 56 | // DisablePointerMethods specifies whether or not to check for and invoke 57 | // error and Stringer interfaces on types which only accept a pointer 58 | // receiver when the current type is not a pointer. 59 | // 60 | // NOTE: This might be an unsafe action since calling one of these methods 61 | // with a pointer receiver could technically mutate the value, however, 62 | // in practice, types which choose to satisify an error or Stringer 63 | // interface with a pointer receiver should not be mutating their state 64 | // inside these interface methods. As a result, this option relies on 65 | // access to the unsafe package, so it will not have any effect when 66 | // running in environments without access to the unsafe package such as 67 | // Google App Engine or with the "disableunsafe" build tag specified. 68 | DisablePointerMethods bool 69 | 70 | // ContinueOnMethod specifies whether or not recursion should continue once 71 | // a custom error or Stringer interface is invoked. The default, false, 72 | // means it will print the results of invoking the custom error or Stringer 73 | // interface and return immediately instead of continuing to recurse into 74 | // the internals of the data type. 75 | // 76 | // NOTE: This flag does not have any effect if method invocation is disabled 77 | // via the DisableMethods or DisablePointerMethods options. 78 | ContinueOnMethod bool 79 | 80 | // SortKeys specifies map keys should be sorted before being printed. Use 81 | // this to have a more deterministic, diffable output. Note that only 82 | // native types (bool, int, uint, floats, uintptr and string) and types 83 | // that support the error or Stringer interfaces (if methods are 84 | // enabled) are supported, with other types sorted according to the 85 | // reflect.Value.String() output which guarantees display stability. 86 | SortKeys bool 87 | 88 | // SpewKeys specifies that, as a last resort attempt, map keys should 89 | // be spewed to strings and sorted by those strings. This is only 90 | // considered if SortKeys is true. 91 | SpewKeys bool 92 | } 93 | 94 | // Config is the active configuration of the top-level functions. 95 | // The configuration can be changed by modifying the contents of spew.Config. 96 | var Config = ConfigState{Indent: " "} 97 | 98 | // Errorf is a wrapper for fmt.Errorf that treats each argument as if it were 99 | // passed with a Formatter interface returned by c.NewFormatter. It returns 100 | // the formatted string as a value that satisfies error. See NewFormatter 101 | // for formatting details. 102 | // 103 | // This function is shorthand for the following syntax: 104 | // 105 | // fmt.Errorf(format, c.NewFormatter(a), c.NewFormatter(b)) 106 | func (c *ConfigState) Errorf(format string, a ...interface{}) (err error) { 107 | return fmt.Errorf(format, c.convertArgs(a)...) 108 | } 109 | 110 | // Fprint is a wrapper for fmt.Fprint that treats each argument as if it were 111 | // passed with a Formatter interface returned by c.NewFormatter. It returns 112 | // the number of bytes written and any write error encountered. See 113 | // NewFormatter for formatting details. 114 | // 115 | // This function is shorthand for the following syntax: 116 | // 117 | // fmt.Fprint(w, c.NewFormatter(a), c.NewFormatter(b)) 118 | func (c *ConfigState) Fprint(w io.Writer, a ...interface{}) (n int, err error) { 119 | return fmt.Fprint(w, c.convertArgs(a)...) 120 | } 121 | 122 | // Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were 123 | // passed with a Formatter interface returned by c.NewFormatter. It returns 124 | // the number of bytes written and any write error encountered. See 125 | // NewFormatter for formatting details. 126 | // 127 | // This function is shorthand for the following syntax: 128 | // 129 | // fmt.Fprintf(w, format, c.NewFormatter(a), c.NewFormatter(b)) 130 | func (c *ConfigState) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { 131 | return fmt.Fprintf(w, format, c.convertArgs(a)...) 132 | } 133 | 134 | // Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it 135 | // passed with a Formatter interface returned by c.NewFormatter. See 136 | // NewFormatter for formatting details. 137 | // 138 | // This function is shorthand for the following syntax: 139 | // 140 | // fmt.Fprintln(w, c.NewFormatter(a), c.NewFormatter(b)) 141 | func (c *ConfigState) Fprintln(w io.Writer, a ...interface{}) (n int, err error) { 142 | return fmt.Fprintln(w, c.convertArgs(a)...) 143 | } 144 | 145 | // Print is a wrapper for fmt.Print that treats each argument as if it were 146 | // passed with a Formatter interface returned by c.NewFormatter. It returns 147 | // the number of bytes written and any write error encountered. See 148 | // NewFormatter for formatting details. 149 | // 150 | // This function is shorthand for the following syntax: 151 | // 152 | // fmt.Print(c.NewFormatter(a), c.NewFormatter(b)) 153 | func (c *ConfigState) Print(a ...interface{}) (n int, err error) { 154 | return fmt.Print(c.convertArgs(a)...) 155 | } 156 | 157 | // Printf is a wrapper for fmt.Printf that treats each argument as if it were 158 | // passed with a Formatter interface returned by c.NewFormatter. It returns 159 | // the number of bytes written and any write error encountered. See 160 | // NewFormatter for formatting details. 161 | // 162 | // This function is shorthand for the following syntax: 163 | // 164 | // fmt.Printf(format, c.NewFormatter(a), c.NewFormatter(b)) 165 | func (c *ConfigState) Printf(format string, a ...interface{}) (n int, err error) { 166 | return fmt.Printf(format, c.convertArgs(a)...) 167 | } 168 | 169 | // Println is a wrapper for fmt.Println that treats each argument as if it were 170 | // passed with a Formatter interface returned by c.NewFormatter. It returns 171 | // the number of bytes written and any write error encountered. See 172 | // NewFormatter for formatting details. 173 | // 174 | // This function is shorthand for the following syntax: 175 | // 176 | // fmt.Println(c.NewFormatter(a), c.NewFormatter(b)) 177 | func (c *ConfigState) Println(a ...interface{}) (n int, err error) { 178 | return fmt.Println(c.convertArgs(a)...) 179 | } 180 | 181 | // Sprint is a wrapper for fmt.Sprint that treats each argument as if it were 182 | // passed with a Formatter interface returned by c.NewFormatter. It returns 183 | // the resulting string. See NewFormatter for formatting details. 184 | // 185 | // This function is shorthand for the following syntax: 186 | // 187 | // fmt.Sprint(c.NewFormatter(a), c.NewFormatter(b)) 188 | func (c *ConfigState) Sprint(a ...interface{}) string { 189 | return fmt.Sprint(c.convertArgs(a)...) 190 | } 191 | 192 | // Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were 193 | // passed with a Formatter interface returned by c.NewFormatter. It returns 194 | // the resulting string. See NewFormatter for formatting details. 195 | // 196 | // This function is shorthand for the following syntax: 197 | // 198 | // fmt.Sprintf(format, c.NewFormatter(a), c.NewFormatter(b)) 199 | func (c *ConfigState) Sprintf(format string, a ...interface{}) string { 200 | return fmt.Sprintf(format, c.convertArgs(a)...) 201 | } 202 | 203 | // Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it 204 | // were passed with a Formatter interface returned by c.NewFormatter. It 205 | // returns the resulting string. See NewFormatter for formatting details. 206 | // 207 | // This function is shorthand for the following syntax: 208 | // 209 | // fmt.Sprintln(c.NewFormatter(a), c.NewFormatter(b)) 210 | func (c *ConfigState) Sprintln(a ...interface{}) string { 211 | return fmt.Sprintln(c.convertArgs(a)...) 212 | } 213 | 214 | /* 215 | NewFormatter returns a custom formatter that satisfies the fmt.Formatter 216 | interface. As a result, it integrates cleanly with standard fmt package 217 | printing functions. The formatter is useful for inline printing of smaller data 218 | types similar to the standard %v format specifier. 219 | 220 | The custom formatter only responds to the %v (most compact), %+v (adds pointer 221 | addresses), %#v (adds types), and %#+v (adds types and pointer addresses) verb 222 | combinations. Any other verbs such as %x and %q will be sent to the the 223 | standard fmt package for formatting. In addition, the custom formatter ignores 224 | the width and precision arguments (however they will still work on the format 225 | specifiers not handled by the custom formatter). 226 | 227 | Typically this function shouldn't be called directly. It is much easier to make 228 | use of the custom formatter by calling one of the convenience functions such as 229 | c.Printf, c.Println, or c.Printf. 230 | */ 231 | func (c *ConfigState) NewFormatter(v interface{}) fmt.Formatter { 232 | return newFormatter(c, v) 233 | } 234 | 235 | // Fdump formats and displays the passed arguments to io.Writer w. It formats 236 | // exactly the same as Dump. 237 | func (c *ConfigState) Fdump(w io.Writer, a ...interface{}) { 238 | fdump(c, w, a...) 239 | } 240 | 241 | /* 242 | Dump displays the passed parameters to standard out with newlines, customizable 243 | indentation, and additional debug information such as complete types and all 244 | pointer addresses used to indirect to the final value. It provides the 245 | following features over the built-in printing facilities provided by the fmt 246 | package: 247 | 248 | * Pointers are dereferenced and followed 249 | * Circular data structures are detected and handled properly 250 | * Custom Stringer/error interfaces are optionally invoked, including 251 | on unexported types 252 | * Custom types which only implement the Stringer/error interfaces via 253 | a pointer receiver are optionally invoked when passing non-pointer 254 | variables 255 | * Byte arrays and slices are dumped like the hexdump -C command which 256 | includes offsets, byte values in hex, and ASCII output 257 | 258 | The configuration options are controlled by modifying the public members 259 | of c. See ConfigState for options documentation. 260 | 261 | See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to 262 | get the formatted result as a string. 263 | */ 264 | func (c *ConfigState) Dump(a ...interface{}) { 265 | fdump(c, os.Stdout, a...) 266 | } 267 | 268 | // Sdump returns a string with the passed arguments formatted exactly the same 269 | // as Dump. 270 | func (c *ConfigState) Sdump(a ...interface{}) string { 271 | var buf bytes.Buffer 272 | fdump(c, &buf, a...) 273 | return buf.String() 274 | } 275 | 276 | // convertArgs accepts a slice of arguments and returns a slice of the same 277 | // length with each argument converted to a spew Formatter interface using 278 | // the ConfigState associated with s. 279 | func (c *ConfigState) convertArgs(args []interface{}) (formatters []interface{}) { 280 | formatters = make([]interface{}, len(args)) 281 | for index, arg := range args { 282 | formatters[index] = newFormatter(c, arg) 283 | } 284 | return formatters 285 | } 286 | 287 | // NewDefaultConfig returns a ConfigState with the following default settings. 288 | // 289 | // Indent: " " 290 | // MaxDepth: 0 291 | // DisableMethods: false 292 | // DisablePointerMethods: false 293 | // ContinueOnMethod: false 294 | // SortKeys: false 295 | func NewDefaultConfig() *ConfigState { 296 | return &ConfigState{Indent: " "} 297 | } 298 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/stretchr/testify/assert/assertion_forward.go: -------------------------------------------------------------------------------- 1 | /* 2 | * CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen 3 | * THIS FILE MUST NOT BE EDITED BY HAND 4 | */ 5 | 6 | package assert 7 | 8 | import ( 9 | 10 | http "net/http" 11 | url "net/url" 12 | time "time" 13 | ) 14 | 15 | 16 | // Condition uses a Comparison to assert a complex condition. 17 | func (a *Assertions) Condition(comp Comparison, msgAndArgs ...interface{}) bool { 18 | return Condition(a.t, comp, msgAndArgs...) 19 | } 20 | 21 | 22 | // Contains asserts that the specified string, list(array, slice...) or map contains the 23 | // specified substring or element. 24 | // 25 | // a.Contains("Hello World", "World", "But 'Hello World' does contain 'World'") 26 | // a.Contains(["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'") 27 | // a.Contains({"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'") 28 | // 29 | // Returns whether the assertion was successful (true) or not (false). 30 | func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { 31 | return Contains(a.t, s, contains, msgAndArgs...) 32 | } 33 | 34 | 35 | // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either 36 | // a slice or a channel with len == 0. 37 | // 38 | // a.Empty(obj) 39 | // 40 | // Returns whether the assertion was successful (true) or not (false). 41 | func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) bool { 42 | return Empty(a.t, object, msgAndArgs...) 43 | } 44 | 45 | 46 | // Equal asserts that two objects are equal. 47 | // 48 | // a.Equal(123, 123, "123 and 123 should be equal") 49 | // 50 | // Returns whether the assertion was successful (true) or not (false). 51 | func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { 52 | return Equal(a.t, expected, actual, msgAndArgs...) 53 | } 54 | 55 | 56 | // EqualError asserts that a function returned an error (i.e. not `nil`) 57 | // and that it is equal to the provided error. 58 | // 59 | // actualObj, err := SomeFunction() 60 | // if assert.Error(t, err, "An error was expected") { 61 | // assert.Equal(t, err, expectedError) 62 | // } 63 | // 64 | // Returns whether the assertion was successful (true) or not (false). 65 | func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) bool { 66 | return EqualError(a.t, theError, errString, msgAndArgs...) 67 | } 68 | 69 | 70 | // EqualValues asserts that two objects are equal or convertable to the same types 71 | // and equal. 72 | // 73 | // a.EqualValues(uint32(123), int32(123), "123 and 123 should be equal") 74 | // 75 | // Returns whether the assertion was successful (true) or not (false). 76 | func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { 77 | return EqualValues(a.t, expected, actual, msgAndArgs...) 78 | } 79 | 80 | 81 | // Error asserts that a function returned an error (i.e. not `nil`). 82 | // 83 | // actualObj, err := SomeFunction() 84 | // if a.Error(err, "An error was expected") { 85 | // assert.Equal(t, err, expectedError) 86 | // } 87 | // 88 | // Returns whether the assertion was successful (true) or not (false). 89 | func (a *Assertions) Error(err error, msgAndArgs ...interface{}) bool { 90 | return Error(a.t, err, msgAndArgs...) 91 | } 92 | 93 | 94 | // Exactly asserts that two objects are equal is value and type. 95 | // 96 | // a.Exactly(int32(123), int64(123), "123 and 123 should NOT be equal") 97 | // 98 | // Returns whether the assertion was successful (true) or not (false). 99 | func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { 100 | return Exactly(a.t, expected, actual, msgAndArgs...) 101 | } 102 | 103 | 104 | // Fail reports a failure through 105 | func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) bool { 106 | return Fail(a.t, failureMessage, msgAndArgs...) 107 | } 108 | 109 | 110 | // FailNow fails test 111 | func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) bool { 112 | return FailNow(a.t, failureMessage, msgAndArgs...) 113 | } 114 | 115 | 116 | // False asserts that the specified value is false. 117 | // 118 | // a.False(myBool, "myBool should be false") 119 | // 120 | // Returns whether the assertion was successful (true) or not (false). 121 | func (a *Assertions) False(value bool, msgAndArgs ...interface{}) bool { 122 | return False(a.t, value, msgAndArgs...) 123 | } 124 | 125 | 126 | // HTTPBodyContains asserts that a specified handler returns a 127 | // body that contains a string. 128 | // 129 | // a.HTTPBodyContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky") 130 | // 131 | // Returns whether the assertion was successful (true) or not (false). 132 | func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) bool { 133 | return HTTPBodyContains(a.t, handler, method, url, values, str) 134 | } 135 | 136 | 137 | // HTTPBodyNotContains asserts that a specified handler returns a 138 | // body that does not contain a string. 139 | // 140 | // a.HTTPBodyNotContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky") 141 | // 142 | // Returns whether the assertion was successful (true) or not (false). 143 | func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) bool { 144 | return HTTPBodyNotContains(a.t, handler, method, url, values, str) 145 | } 146 | 147 | 148 | // HTTPError asserts that a specified handler returns an error status code. 149 | // 150 | // a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} 151 | // 152 | // Returns whether the assertion was successful (true) or not (false). 153 | func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values) bool { 154 | return HTTPError(a.t, handler, method, url, values) 155 | } 156 | 157 | 158 | // HTTPRedirect asserts that a specified handler returns a redirect status code. 159 | // 160 | // a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} 161 | // 162 | // Returns whether the assertion was successful (true) or not (false). 163 | func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values) bool { 164 | return HTTPRedirect(a.t, handler, method, url, values) 165 | } 166 | 167 | 168 | // HTTPSuccess asserts that a specified handler returns a success status code. 169 | // 170 | // a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) 171 | // 172 | // Returns whether the assertion was successful (true) or not (false). 173 | func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values) bool { 174 | return HTTPSuccess(a.t, handler, method, url, values) 175 | } 176 | 177 | 178 | // Implements asserts that an object is implemented by the specified interface. 179 | // 180 | // a.Implements((*MyInterface)(nil), new(MyObject), "MyObject") 181 | func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { 182 | return Implements(a.t, interfaceObject, object, msgAndArgs...) 183 | } 184 | 185 | 186 | // InDelta asserts that the two numerals are within delta of each other. 187 | // 188 | // a.InDelta(math.Pi, (22 / 7.0), 0.01) 189 | // 190 | // Returns whether the assertion was successful (true) or not (false). 191 | func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { 192 | return InDelta(a.t, expected, actual, delta, msgAndArgs...) 193 | } 194 | 195 | 196 | // InDeltaSlice is the same as InDelta, except it compares two slices. 197 | func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { 198 | return InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...) 199 | } 200 | 201 | 202 | // InEpsilon asserts that expected and actual have a relative error less than epsilon 203 | // 204 | // Returns whether the assertion was successful (true) or not (false). 205 | func (a *Assertions) InEpsilon(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { 206 | return InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) 207 | } 208 | 209 | 210 | // InEpsilonSlice is the same as InEpsilon, except it compares two slices. 211 | func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { 212 | return InEpsilonSlice(a.t, expected, actual, delta, msgAndArgs...) 213 | } 214 | 215 | 216 | // IsType asserts that the specified objects are of the same type. 217 | func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { 218 | return IsType(a.t, expectedType, object, msgAndArgs...) 219 | } 220 | 221 | 222 | // JSONEq asserts that two JSON strings are equivalent. 223 | // 224 | // a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) 225 | // 226 | // Returns whether the assertion was successful (true) or not (false). 227 | func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) bool { 228 | return JSONEq(a.t, expected, actual, msgAndArgs...) 229 | } 230 | 231 | 232 | // Len asserts that the specified object has specific length. 233 | // Len also fails if the object has a type that len() not accept. 234 | // 235 | // a.Len(mySlice, 3, "The size of slice is not 3") 236 | // 237 | // Returns whether the assertion was successful (true) or not (false). 238 | func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) bool { 239 | return Len(a.t, object, length, msgAndArgs...) 240 | } 241 | 242 | 243 | // Nil asserts that the specified object is nil. 244 | // 245 | // a.Nil(err, "err should be nothing") 246 | // 247 | // Returns whether the assertion was successful (true) or not (false). 248 | func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) bool { 249 | return Nil(a.t, object, msgAndArgs...) 250 | } 251 | 252 | 253 | // NoError asserts that a function returned no error (i.e. `nil`). 254 | // 255 | // actualObj, err := SomeFunction() 256 | // if a.NoError(err) { 257 | // assert.Equal(t, actualObj, expectedObj) 258 | // } 259 | // 260 | // Returns whether the assertion was successful (true) or not (false). 261 | func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) bool { 262 | return NoError(a.t, err, msgAndArgs...) 263 | } 264 | 265 | 266 | // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the 267 | // specified substring or element. 268 | // 269 | // a.NotContains("Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") 270 | // a.NotContains(["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'") 271 | // a.NotContains({"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'") 272 | // 273 | // Returns whether the assertion was successful (true) or not (false). 274 | func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { 275 | return NotContains(a.t, s, contains, msgAndArgs...) 276 | } 277 | 278 | 279 | // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either 280 | // a slice or a channel with len == 0. 281 | // 282 | // if a.NotEmpty(obj) { 283 | // assert.Equal(t, "two", obj[1]) 284 | // } 285 | // 286 | // Returns whether the assertion was successful (true) or not (false). 287 | func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) bool { 288 | return NotEmpty(a.t, object, msgAndArgs...) 289 | } 290 | 291 | 292 | // NotEqual asserts that the specified values are NOT equal. 293 | // 294 | // a.NotEqual(obj1, obj2, "two objects shouldn't be equal") 295 | // 296 | // Returns whether the assertion was successful (true) or not (false). 297 | func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { 298 | return NotEqual(a.t, expected, actual, msgAndArgs...) 299 | } 300 | 301 | 302 | // NotNil asserts that the specified object is not nil. 303 | // 304 | // a.NotNil(err, "err should be something") 305 | // 306 | // Returns whether the assertion was successful (true) or not (false). 307 | func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) bool { 308 | return NotNil(a.t, object, msgAndArgs...) 309 | } 310 | 311 | 312 | // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. 313 | // 314 | // a.NotPanics(func(){ 315 | // RemainCalm() 316 | // }, "Calling RemainCalm() should NOT panic") 317 | // 318 | // Returns whether the assertion was successful (true) or not (false). 319 | func (a *Assertions) NotPanics(f PanicTestFunc, msgAndArgs ...interface{}) bool { 320 | return NotPanics(a.t, f, msgAndArgs...) 321 | } 322 | 323 | 324 | // NotRegexp asserts that a specified regexp does not match a string. 325 | // 326 | // a.NotRegexp(regexp.MustCompile("starts"), "it's starting") 327 | // a.NotRegexp("^start", "it's not starting") 328 | // 329 | // Returns whether the assertion was successful (true) or not (false). 330 | func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { 331 | return NotRegexp(a.t, rx, str, msgAndArgs...) 332 | } 333 | 334 | 335 | // NotZero asserts that i is not the zero value for its type and returns the truth. 336 | func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) bool { 337 | return NotZero(a.t, i, msgAndArgs...) 338 | } 339 | 340 | 341 | // Panics asserts that the code inside the specified PanicTestFunc panics. 342 | // 343 | // a.Panics(func(){ 344 | // GoCrazy() 345 | // }, "Calling GoCrazy() should panic") 346 | // 347 | // Returns whether the assertion was successful (true) or not (false). 348 | func (a *Assertions) Panics(f PanicTestFunc, msgAndArgs ...interface{}) bool { 349 | return Panics(a.t, f, msgAndArgs...) 350 | } 351 | 352 | 353 | // Regexp asserts that a specified regexp matches a string. 354 | // 355 | // a.Regexp(regexp.MustCompile("start"), "it's starting") 356 | // a.Regexp("start...$", "it's not starting") 357 | // 358 | // Returns whether the assertion was successful (true) or not (false). 359 | func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { 360 | return Regexp(a.t, rx, str, msgAndArgs...) 361 | } 362 | 363 | 364 | // True asserts that the specified value is true. 365 | // 366 | // a.True(myBool, "myBool should be true") 367 | // 368 | // Returns whether the assertion was successful (true) or not (false). 369 | func (a *Assertions) True(value bool, msgAndArgs ...interface{}) bool { 370 | return True(a.t, value, msgAndArgs...) 371 | } 372 | 373 | 374 | // WithinDuration asserts that the two times are within duration delta of each other. 375 | // 376 | // a.WithinDuration(time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") 377 | // 378 | // Returns whether the assertion was successful (true) or not (false). 379 | func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { 380 | return WithinDuration(a.t, expected, actual, delta, msgAndArgs...) 381 | } 382 | 383 | 384 | // Zero asserts that i is the zero value for its type and returns the truth. 385 | func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) bool { 386 | return Zero(a.t, i, msgAndArgs...) 387 | } 388 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dump.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013 Dave Collins 3 | * 4 | * Permission to use, copy, modify, and distribute this software for any 5 | * purpose with or without fee is hereby granted, provided that the above 6 | * copyright notice and this permission notice appear in all copies. 7 | * 8 | * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 9 | * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 10 | * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 11 | * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 12 | * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 13 | * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 14 | * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 15 | */ 16 | 17 | package spew 18 | 19 | import ( 20 | "bytes" 21 | "encoding/hex" 22 | "fmt" 23 | "io" 24 | "os" 25 | "reflect" 26 | "regexp" 27 | "strconv" 28 | "strings" 29 | ) 30 | 31 | var ( 32 | // uint8Type is a reflect.Type representing a uint8. It is used to 33 | // convert cgo types to uint8 slices for hexdumping. 34 | uint8Type = reflect.TypeOf(uint8(0)) 35 | 36 | // cCharRE is a regular expression that matches a cgo char. 37 | // It is used to detect character arrays to hexdump them. 38 | cCharRE = regexp.MustCompile("^.*\\._Ctype_char$") 39 | 40 | // cUnsignedCharRE is a regular expression that matches a cgo unsigned 41 | // char. It is used to detect unsigned character arrays to hexdump 42 | // them. 43 | cUnsignedCharRE = regexp.MustCompile("^.*\\._Ctype_unsignedchar$") 44 | 45 | // cUint8tCharRE is a regular expression that matches a cgo uint8_t. 46 | // It is used to detect uint8_t arrays to hexdump them. 47 | cUint8tCharRE = regexp.MustCompile("^.*\\._Ctype_uint8_t$") 48 | ) 49 | 50 | // dumpState contains information about the state of a dump operation. 51 | type dumpState struct { 52 | w io.Writer 53 | depth int 54 | pointers map[uintptr]int 55 | ignoreNextType bool 56 | ignoreNextIndent bool 57 | cs *ConfigState 58 | } 59 | 60 | // indent performs indentation according to the depth level and cs.Indent 61 | // option. 62 | func (d *dumpState) indent() { 63 | if d.ignoreNextIndent { 64 | d.ignoreNextIndent = false 65 | return 66 | } 67 | d.w.Write(bytes.Repeat([]byte(d.cs.Indent), d.depth)) 68 | } 69 | 70 | // unpackValue returns values inside of non-nil interfaces when possible. 71 | // This is useful for data types like structs, arrays, slices, and maps which 72 | // can contain varying types packed inside an interface. 73 | func (d *dumpState) unpackValue(v reflect.Value) reflect.Value { 74 | if v.Kind() == reflect.Interface && !v.IsNil() { 75 | v = v.Elem() 76 | } 77 | return v 78 | } 79 | 80 | // dumpPtr handles formatting of pointers by indirecting them as necessary. 81 | func (d *dumpState) dumpPtr(v reflect.Value) { 82 | // Remove pointers at or below the current depth from map used to detect 83 | // circular refs. 84 | for k, depth := range d.pointers { 85 | if depth >= d.depth { 86 | delete(d.pointers, k) 87 | } 88 | } 89 | 90 | // Keep list of all dereferenced pointers to show later. 91 | pointerChain := make([]uintptr, 0) 92 | 93 | // Figure out how many levels of indirection there are by dereferencing 94 | // pointers and unpacking interfaces down the chain while detecting circular 95 | // references. 96 | nilFound := false 97 | cycleFound := false 98 | indirects := 0 99 | ve := v 100 | for ve.Kind() == reflect.Ptr { 101 | if ve.IsNil() { 102 | nilFound = true 103 | break 104 | } 105 | indirects++ 106 | addr := ve.Pointer() 107 | pointerChain = append(pointerChain, addr) 108 | if pd, ok := d.pointers[addr]; ok && pd < d.depth { 109 | cycleFound = true 110 | indirects-- 111 | break 112 | } 113 | d.pointers[addr] = d.depth 114 | 115 | ve = ve.Elem() 116 | if ve.Kind() == reflect.Interface { 117 | if ve.IsNil() { 118 | nilFound = true 119 | break 120 | } 121 | ve = ve.Elem() 122 | } 123 | } 124 | 125 | // Display type information. 126 | d.w.Write(openParenBytes) 127 | d.w.Write(bytes.Repeat(asteriskBytes, indirects)) 128 | d.w.Write([]byte(ve.Type().String())) 129 | d.w.Write(closeParenBytes) 130 | 131 | // Display pointer information. 132 | if len(pointerChain) > 0 { 133 | d.w.Write(openParenBytes) 134 | for i, addr := range pointerChain { 135 | if i > 0 { 136 | d.w.Write(pointerChainBytes) 137 | } 138 | printHexPtr(d.w, addr) 139 | } 140 | d.w.Write(closeParenBytes) 141 | } 142 | 143 | // Display dereferenced value. 144 | d.w.Write(openParenBytes) 145 | switch { 146 | case nilFound == true: 147 | d.w.Write(nilAngleBytes) 148 | 149 | case cycleFound == true: 150 | d.w.Write(circularBytes) 151 | 152 | default: 153 | d.ignoreNextType = true 154 | d.dump(ve) 155 | } 156 | d.w.Write(closeParenBytes) 157 | } 158 | 159 | // dumpSlice handles formatting of arrays and slices. Byte (uint8 under 160 | // reflection) arrays and slices are dumped in hexdump -C fashion. 161 | func (d *dumpState) dumpSlice(v reflect.Value) { 162 | // Determine whether this type should be hex dumped or not. Also, 163 | // for types which should be hexdumped, try to use the underlying data 164 | // first, then fall back to trying to convert them to a uint8 slice. 165 | var buf []uint8 166 | doConvert := false 167 | doHexDump := false 168 | numEntries := v.Len() 169 | if numEntries > 0 { 170 | vt := v.Index(0).Type() 171 | vts := vt.String() 172 | switch { 173 | // C types that need to be converted. 174 | case cCharRE.MatchString(vts): 175 | fallthrough 176 | case cUnsignedCharRE.MatchString(vts): 177 | fallthrough 178 | case cUint8tCharRE.MatchString(vts): 179 | doConvert = true 180 | 181 | // Try to use existing uint8 slices and fall back to converting 182 | // and copying if that fails. 183 | case vt.Kind() == reflect.Uint8: 184 | // We need an addressable interface to convert the type 185 | // to a byte slice. However, the reflect package won't 186 | // give us an interface on certain things like 187 | // unexported struct fields in order to enforce 188 | // visibility rules. We use unsafe, when available, to 189 | // bypass these restrictions since this package does not 190 | // mutate the values. 191 | vs := v 192 | if !vs.CanInterface() || !vs.CanAddr() { 193 | vs = unsafeReflectValue(vs) 194 | } 195 | if !UnsafeDisabled { 196 | vs = vs.Slice(0, numEntries) 197 | 198 | // Use the existing uint8 slice if it can be 199 | // type asserted. 200 | iface := vs.Interface() 201 | if slice, ok := iface.([]uint8); ok { 202 | buf = slice 203 | doHexDump = true 204 | break 205 | } 206 | } 207 | 208 | // The underlying data needs to be converted if it can't 209 | // be type asserted to a uint8 slice. 210 | doConvert = true 211 | } 212 | 213 | // Copy and convert the underlying type if needed. 214 | if doConvert && vt.ConvertibleTo(uint8Type) { 215 | // Convert and copy each element into a uint8 byte 216 | // slice. 217 | buf = make([]uint8, numEntries) 218 | for i := 0; i < numEntries; i++ { 219 | vv := v.Index(i) 220 | buf[i] = uint8(vv.Convert(uint8Type).Uint()) 221 | } 222 | doHexDump = true 223 | } 224 | } 225 | 226 | // Hexdump the entire slice as needed. 227 | if doHexDump { 228 | indent := strings.Repeat(d.cs.Indent, d.depth) 229 | str := indent + hex.Dump(buf) 230 | str = strings.Replace(str, "\n", "\n"+indent, -1) 231 | str = strings.TrimRight(str, d.cs.Indent) 232 | d.w.Write([]byte(str)) 233 | return 234 | } 235 | 236 | // Recursively call dump for each item. 237 | for i := 0; i < numEntries; i++ { 238 | d.dump(d.unpackValue(v.Index(i))) 239 | if i < (numEntries - 1) { 240 | d.w.Write(commaNewlineBytes) 241 | } else { 242 | d.w.Write(newlineBytes) 243 | } 244 | } 245 | } 246 | 247 | // dump is the main workhorse for dumping a value. It uses the passed reflect 248 | // value to figure out what kind of object we are dealing with and formats it 249 | // appropriately. It is a recursive function, however circular data structures 250 | // are detected and handled properly. 251 | func (d *dumpState) dump(v reflect.Value) { 252 | // Handle invalid reflect values immediately. 253 | kind := v.Kind() 254 | if kind == reflect.Invalid { 255 | d.w.Write(invalidAngleBytes) 256 | return 257 | } 258 | 259 | // Handle pointers specially. 260 | if kind == reflect.Ptr { 261 | d.indent() 262 | d.dumpPtr(v) 263 | return 264 | } 265 | 266 | // Print type information unless already handled elsewhere. 267 | if !d.ignoreNextType { 268 | d.indent() 269 | d.w.Write(openParenBytes) 270 | d.w.Write([]byte(v.Type().String())) 271 | d.w.Write(closeParenBytes) 272 | d.w.Write(spaceBytes) 273 | } 274 | d.ignoreNextType = false 275 | 276 | // Display length and capacity if the built-in len and cap functions 277 | // work with the value's kind and the len/cap itself is non-zero. 278 | valueLen, valueCap := 0, 0 279 | switch v.Kind() { 280 | case reflect.Array, reflect.Slice, reflect.Chan: 281 | valueLen, valueCap = v.Len(), v.Cap() 282 | case reflect.Map, reflect.String: 283 | valueLen = v.Len() 284 | } 285 | if valueLen != 0 || valueCap != 0 { 286 | d.w.Write(openParenBytes) 287 | if valueLen != 0 { 288 | d.w.Write(lenEqualsBytes) 289 | printInt(d.w, int64(valueLen), 10) 290 | } 291 | if valueCap != 0 { 292 | if valueLen != 0 { 293 | d.w.Write(spaceBytes) 294 | } 295 | d.w.Write(capEqualsBytes) 296 | printInt(d.w, int64(valueCap), 10) 297 | } 298 | d.w.Write(closeParenBytes) 299 | d.w.Write(spaceBytes) 300 | } 301 | 302 | // Call Stringer/error interfaces if they exist and the handle methods flag 303 | // is enabled 304 | if !d.cs.DisableMethods { 305 | if (kind != reflect.Invalid) && (kind != reflect.Interface) { 306 | if handled := handleMethods(d.cs, d.w, v); handled { 307 | return 308 | } 309 | } 310 | } 311 | 312 | switch kind { 313 | case reflect.Invalid: 314 | // Do nothing. We should never get here since invalid has already 315 | // been handled above. 316 | 317 | case reflect.Bool: 318 | printBool(d.w, v.Bool()) 319 | 320 | case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: 321 | printInt(d.w, v.Int(), 10) 322 | 323 | case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: 324 | printUint(d.w, v.Uint(), 10) 325 | 326 | case reflect.Float32: 327 | printFloat(d.w, v.Float(), 32) 328 | 329 | case reflect.Float64: 330 | printFloat(d.w, v.Float(), 64) 331 | 332 | case reflect.Complex64: 333 | printComplex(d.w, v.Complex(), 32) 334 | 335 | case reflect.Complex128: 336 | printComplex(d.w, v.Complex(), 64) 337 | 338 | case reflect.Slice: 339 | if v.IsNil() { 340 | d.w.Write(nilAngleBytes) 341 | break 342 | } 343 | fallthrough 344 | 345 | case reflect.Array: 346 | d.w.Write(openBraceNewlineBytes) 347 | d.depth++ 348 | if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { 349 | d.indent() 350 | d.w.Write(maxNewlineBytes) 351 | } else { 352 | d.dumpSlice(v) 353 | } 354 | d.depth-- 355 | d.indent() 356 | d.w.Write(closeBraceBytes) 357 | 358 | case reflect.String: 359 | d.w.Write([]byte(strconv.Quote(v.String()))) 360 | 361 | case reflect.Interface: 362 | // The only time we should get here is for nil interfaces due to 363 | // unpackValue calls. 364 | if v.IsNil() { 365 | d.w.Write(nilAngleBytes) 366 | } 367 | 368 | case reflect.Ptr: 369 | // Do nothing. We should never get here since pointers have already 370 | // been handled above. 371 | 372 | case reflect.Map: 373 | // nil maps should be indicated as different than empty maps 374 | if v.IsNil() { 375 | d.w.Write(nilAngleBytes) 376 | break 377 | } 378 | 379 | d.w.Write(openBraceNewlineBytes) 380 | d.depth++ 381 | if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { 382 | d.indent() 383 | d.w.Write(maxNewlineBytes) 384 | } else { 385 | numEntries := v.Len() 386 | keys := v.MapKeys() 387 | if d.cs.SortKeys { 388 | sortValues(keys, d.cs) 389 | } 390 | for i, key := range keys { 391 | d.dump(d.unpackValue(key)) 392 | d.w.Write(colonSpaceBytes) 393 | d.ignoreNextIndent = true 394 | d.dump(d.unpackValue(v.MapIndex(key))) 395 | if i < (numEntries - 1) { 396 | d.w.Write(commaNewlineBytes) 397 | } else { 398 | d.w.Write(newlineBytes) 399 | } 400 | } 401 | } 402 | d.depth-- 403 | d.indent() 404 | d.w.Write(closeBraceBytes) 405 | 406 | case reflect.Struct: 407 | d.w.Write(openBraceNewlineBytes) 408 | d.depth++ 409 | if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { 410 | d.indent() 411 | d.w.Write(maxNewlineBytes) 412 | } else { 413 | vt := v.Type() 414 | numFields := v.NumField() 415 | for i := 0; i < numFields; i++ { 416 | d.indent() 417 | vtf := vt.Field(i) 418 | d.w.Write([]byte(vtf.Name)) 419 | d.w.Write(colonSpaceBytes) 420 | d.ignoreNextIndent = true 421 | d.dump(d.unpackValue(v.Field(i))) 422 | if i < (numFields - 1) { 423 | d.w.Write(commaNewlineBytes) 424 | } else { 425 | d.w.Write(newlineBytes) 426 | } 427 | } 428 | } 429 | d.depth-- 430 | d.indent() 431 | d.w.Write(closeBraceBytes) 432 | 433 | case reflect.Uintptr: 434 | printHexPtr(d.w, uintptr(v.Uint())) 435 | 436 | case reflect.UnsafePointer, reflect.Chan, reflect.Func: 437 | printHexPtr(d.w, v.Pointer()) 438 | 439 | // There were not any other types at the time this code was written, but 440 | // fall back to letting the default fmt package handle it in case any new 441 | // types are added. 442 | default: 443 | if v.CanInterface() { 444 | fmt.Fprintf(d.w, "%v", v.Interface()) 445 | } else { 446 | fmt.Fprintf(d.w, "%v", v.String()) 447 | } 448 | } 449 | } 450 | 451 | // fdump is a helper function to consolidate the logic from the various public 452 | // methods which take varying writers and config states. 453 | func fdump(cs *ConfigState, w io.Writer, a ...interface{}) { 454 | for _, arg := range a { 455 | if arg == nil { 456 | w.Write(interfaceBytes) 457 | w.Write(spaceBytes) 458 | w.Write(nilAngleBytes) 459 | w.Write(newlineBytes) 460 | continue 461 | } 462 | 463 | d := dumpState{w: w, cs: cs} 464 | d.pointers = make(map[uintptr]int) 465 | d.dump(reflect.ValueOf(arg)) 466 | d.w.Write(newlineBytes) 467 | } 468 | } 469 | 470 | // Fdump formats and displays the passed arguments to io.Writer w. It formats 471 | // exactly the same as Dump. 472 | func Fdump(w io.Writer, a ...interface{}) { 473 | fdump(&Config, w, a...) 474 | } 475 | 476 | // Sdump returns a string with the passed arguments formatted exactly the same 477 | // as Dump. 478 | func Sdump(a ...interface{}) string { 479 | var buf bytes.Buffer 480 | fdump(&Config, &buf, a...) 481 | return buf.String() 482 | } 483 | 484 | /* 485 | Dump displays the passed parameters to standard out with newlines, customizable 486 | indentation, and additional debug information such as complete types and all 487 | pointer addresses used to indirect to the final value. It provides the 488 | following features over the built-in printing facilities provided by the fmt 489 | package: 490 | 491 | * Pointers are dereferenced and followed 492 | * Circular data structures are detected and handled properly 493 | * Custom Stringer/error interfaces are optionally invoked, including 494 | on unexported types 495 | * Custom types which only implement the Stringer/error interfaces via 496 | a pointer receiver are optionally invoked when passing non-pointer 497 | variables 498 | * Byte arrays and slices are dumped like the hexdump -C command which 499 | includes offsets, byte values in hex, and ASCII output 500 | 501 | The configuration options are controlled by an exported package global, 502 | spew.Config. See ConfigState for options documentation. 503 | 504 | See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to 505 | get the formatted result as a string. 506 | */ 507 | func Dump(a ...interface{}) { 508 | fdump(&Config, os.Stdout, a...) 509 | } 510 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/pmezard/go-difflib/difflib/difflib.go: -------------------------------------------------------------------------------- 1 | // Package difflib is a partial port of Python difflib module. 2 | // 3 | // It provides tools to compare sequences of strings and generate textual diffs. 4 | // 5 | // The following class and functions have been ported: 6 | // 7 | // - SequenceMatcher 8 | // 9 | // - unified_diff 10 | // 11 | // - context_diff 12 | // 13 | // Getting unified diffs was the main goal of the port. Keep in mind this code 14 | // is mostly suitable to output text differences in a human friendly way, there 15 | // are no guarantees generated diffs are consumable by patch(1). 16 | package difflib 17 | 18 | import ( 19 | "bufio" 20 | "bytes" 21 | "fmt" 22 | "io" 23 | "strings" 24 | ) 25 | 26 | func min(a, b int) int { 27 | if a < b { 28 | return a 29 | } 30 | return b 31 | } 32 | 33 | func max(a, b int) int { 34 | if a > b { 35 | return a 36 | } 37 | return b 38 | } 39 | 40 | func calculateRatio(matches, length int) float64 { 41 | if length > 0 { 42 | return 2.0 * float64(matches) / float64(length) 43 | } 44 | return 1.0 45 | } 46 | 47 | type Match struct { 48 | A int 49 | B int 50 | Size int 51 | } 52 | 53 | type OpCode struct { 54 | Tag byte 55 | I1 int 56 | I2 int 57 | J1 int 58 | J2 int 59 | } 60 | 61 | // SequenceMatcher compares sequence of strings. The basic 62 | // algorithm predates, and is a little fancier than, an algorithm 63 | // published in the late 1980's by Ratcliff and Obershelp under the 64 | // hyperbolic name "gestalt pattern matching". The basic idea is to find 65 | // the longest contiguous matching subsequence that contains no "junk" 66 | // elements (R-O doesn't address junk). The same idea is then applied 67 | // recursively to the pieces of the sequences to the left and to the right 68 | // of the matching subsequence. This does not yield minimal edit 69 | // sequences, but does tend to yield matches that "look right" to people. 70 | // 71 | // SequenceMatcher tries to compute a "human-friendly diff" between two 72 | // sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the 73 | // longest *contiguous* & junk-free matching subsequence. That's what 74 | // catches peoples' eyes. The Windows(tm) windiff has another interesting 75 | // notion, pairing up elements that appear uniquely in each sequence. 76 | // That, and the method here, appear to yield more intuitive difference 77 | // reports than does diff. This method appears to be the least vulnerable 78 | // to synching up on blocks of "junk lines", though (like blank lines in 79 | // ordinary text files, or maybe "

" lines in HTML files). That may be 80 | // because this is the only method of the 3 that has a *concept* of 81 | // "junk" . 82 | // 83 | // Timing: Basic R-O is cubic time worst case and quadratic time expected 84 | // case. SequenceMatcher is quadratic time for the worst case and has 85 | // expected-case behavior dependent in a complicated way on how many 86 | // elements the sequences have in common; best case time is linear. 87 | type SequenceMatcher struct { 88 | a []string 89 | b []string 90 | b2j map[string][]int 91 | IsJunk func(string) bool 92 | autoJunk bool 93 | bJunk map[string]struct{} 94 | matchingBlocks []Match 95 | fullBCount map[string]int 96 | bPopular map[string]struct{} 97 | opCodes []OpCode 98 | } 99 | 100 | func NewMatcher(a, b []string) *SequenceMatcher { 101 | m := SequenceMatcher{autoJunk: true} 102 | m.SetSeqs(a, b) 103 | return &m 104 | } 105 | 106 | func NewMatcherWithJunk(a, b []string, autoJunk bool, 107 | isJunk func(string) bool) *SequenceMatcher { 108 | 109 | m := SequenceMatcher{IsJunk: isJunk, autoJunk: autoJunk} 110 | m.SetSeqs(a, b) 111 | return &m 112 | } 113 | 114 | // Set two sequences to be compared. 115 | func (m *SequenceMatcher) SetSeqs(a, b []string) { 116 | m.SetSeq1(a) 117 | m.SetSeq2(b) 118 | } 119 | 120 | // Set the first sequence to be compared. The second sequence to be compared is 121 | // not changed. 122 | // 123 | // SequenceMatcher computes and caches detailed information about the second 124 | // sequence, so if you want to compare one sequence S against many sequences, 125 | // use .SetSeq2(s) once and call .SetSeq1(x) repeatedly for each of the other 126 | // sequences. 127 | // 128 | // See also SetSeqs() and SetSeq2(). 129 | func (m *SequenceMatcher) SetSeq1(a []string) { 130 | if &a == &m.a { 131 | return 132 | } 133 | m.a = a 134 | m.matchingBlocks = nil 135 | m.opCodes = nil 136 | } 137 | 138 | // Set the second sequence to be compared. The first sequence to be compared is 139 | // not changed. 140 | func (m *SequenceMatcher) SetSeq2(b []string) { 141 | if &b == &m.b { 142 | return 143 | } 144 | m.b = b 145 | m.matchingBlocks = nil 146 | m.opCodes = nil 147 | m.fullBCount = nil 148 | m.chainB() 149 | } 150 | 151 | func (m *SequenceMatcher) chainB() { 152 | // Populate line -> index mapping 153 | b2j := map[string][]int{} 154 | for i, s := range m.b { 155 | indices := b2j[s] 156 | indices = append(indices, i) 157 | b2j[s] = indices 158 | } 159 | 160 | // Purge junk elements 161 | m.bJunk = map[string]struct{}{} 162 | if m.IsJunk != nil { 163 | junk := m.bJunk 164 | for s, _ := range b2j { 165 | if m.IsJunk(s) { 166 | junk[s] = struct{}{} 167 | } 168 | } 169 | for s, _ := range junk { 170 | delete(b2j, s) 171 | } 172 | } 173 | 174 | // Purge remaining popular elements 175 | popular := map[string]struct{}{} 176 | n := len(m.b) 177 | if m.autoJunk && n >= 200 { 178 | ntest := n/100 + 1 179 | for s, indices := range b2j { 180 | if len(indices) > ntest { 181 | popular[s] = struct{}{} 182 | } 183 | } 184 | for s, _ := range popular { 185 | delete(b2j, s) 186 | } 187 | } 188 | m.bPopular = popular 189 | m.b2j = b2j 190 | } 191 | 192 | func (m *SequenceMatcher) isBJunk(s string) bool { 193 | _, ok := m.bJunk[s] 194 | return ok 195 | } 196 | 197 | // Find longest matching block in a[alo:ahi] and b[blo:bhi]. 198 | // 199 | // If IsJunk is not defined: 200 | // 201 | // Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where 202 | // alo <= i <= i+k <= ahi 203 | // blo <= j <= j+k <= bhi 204 | // and for all (i',j',k') meeting those conditions, 205 | // k >= k' 206 | // i <= i' 207 | // and if i == i', j <= j' 208 | // 209 | // In other words, of all maximal matching blocks, return one that 210 | // starts earliest in a, and of all those maximal matching blocks that 211 | // start earliest in a, return the one that starts earliest in b. 212 | // 213 | // If IsJunk is defined, first the longest matching block is 214 | // determined as above, but with the additional restriction that no 215 | // junk element appears in the block. Then that block is extended as 216 | // far as possible by matching (only) junk elements on both sides. So 217 | // the resulting block never matches on junk except as identical junk 218 | // happens to be adjacent to an "interesting" match. 219 | // 220 | // If no blocks match, return (alo, blo, 0). 221 | func (m *SequenceMatcher) findLongestMatch(alo, ahi, blo, bhi int) Match { 222 | // CAUTION: stripping common prefix or suffix would be incorrect. 223 | // E.g., 224 | // ab 225 | // acab 226 | // Longest matching block is "ab", but if common prefix is 227 | // stripped, it's "a" (tied with "b"). UNIX(tm) diff does so 228 | // strip, so ends up claiming that ab is changed to acab by 229 | // inserting "ca" in the middle. That's minimal but unintuitive: 230 | // "it's obvious" that someone inserted "ac" at the front. 231 | // Windiff ends up at the same place as diff, but by pairing up 232 | // the unique 'b's and then matching the first two 'a's. 233 | besti, bestj, bestsize := alo, blo, 0 234 | 235 | // find longest junk-free match 236 | // during an iteration of the loop, j2len[j] = length of longest 237 | // junk-free match ending with a[i-1] and b[j] 238 | j2len := map[int]int{} 239 | for i := alo; i != ahi; i++ { 240 | // look at all instances of a[i] in b; note that because 241 | // b2j has no junk keys, the loop is skipped if a[i] is junk 242 | newj2len := map[int]int{} 243 | for _, j := range m.b2j[m.a[i]] { 244 | // a[i] matches b[j] 245 | if j < blo { 246 | continue 247 | } 248 | if j >= bhi { 249 | break 250 | } 251 | k := j2len[j-1] + 1 252 | newj2len[j] = k 253 | if k > bestsize { 254 | besti, bestj, bestsize = i-k+1, j-k+1, k 255 | } 256 | } 257 | j2len = newj2len 258 | } 259 | 260 | // Extend the best by non-junk elements on each end. In particular, 261 | // "popular" non-junk elements aren't in b2j, which greatly speeds 262 | // the inner loop above, but also means "the best" match so far 263 | // doesn't contain any junk *or* popular non-junk elements. 264 | for besti > alo && bestj > blo && !m.isBJunk(m.b[bestj-1]) && 265 | m.a[besti-1] == m.b[bestj-1] { 266 | besti, bestj, bestsize = besti-1, bestj-1, bestsize+1 267 | } 268 | for besti+bestsize < ahi && bestj+bestsize < bhi && 269 | !m.isBJunk(m.b[bestj+bestsize]) && 270 | m.a[besti+bestsize] == m.b[bestj+bestsize] { 271 | bestsize += 1 272 | } 273 | 274 | // Now that we have a wholly interesting match (albeit possibly 275 | // empty!), we may as well suck up the matching junk on each 276 | // side of it too. Can't think of a good reason not to, and it 277 | // saves post-processing the (possibly considerable) expense of 278 | // figuring out what to do with it. In the case of an empty 279 | // interesting match, this is clearly the right thing to do, 280 | // because no other kind of match is possible in the regions. 281 | for besti > alo && bestj > blo && m.isBJunk(m.b[bestj-1]) && 282 | m.a[besti-1] == m.b[bestj-1] { 283 | besti, bestj, bestsize = besti-1, bestj-1, bestsize+1 284 | } 285 | for besti+bestsize < ahi && bestj+bestsize < bhi && 286 | m.isBJunk(m.b[bestj+bestsize]) && 287 | m.a[besti+bestsize] == m.b[bestj+bestsize] { 288 | bestsize += 1 289 | } 290 | 291 | return Match{A: besti, B: bestj, Size: bestsize} 292 | } 293 | 294 | // Return list of triples describing matching subsequences. 295 | // 296 | // Each triple is of the form (i, j, n), and means that 297 | // a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in 298 | // i and in j. It's also guaranteed that if (i, j, n) and (i', j', n') are 299 | // adjacent triples in the list, and the second is not the last triple in the 300 | // list, then i+n != i' or j+n != j'. IOW, adjacent triples never describe 301 | // adjacent equal blocks. 302 | // 303 | // The last triple is a dummy, (len(a), len(b), 0), and is the only 304 | // triple with n==0. 305 | func (m *SequenceMatcher) GetMatchingBlocks() []Match { 306 | if m.matchingBlocks != nil { 307 | return m.matchingBlocks 308 | } 309 | 310 | var matchBlocks func(alo, ahi, blo, bhi int, matched []Match) []Match 311 | matchBlocks = func(alo, ahi, blo, bhi int, matched []Match) []Match { 312 | match := m.findLongestMatch(alo, ahi, blo, bhi) 313 | i, j, k := match.A, match.B, match.Size 314 | if match.Size > 0 { 315 | if alo < i && blo < j { 316 | matched = matchBlocks(alo, i, blo, j, matched) 317 | } 318 | matched = append(matched, match) 319 | if i+k < ahi && j+k < bhi { 320 | matched = matchBlocks(i+k, ahi, j+k, bhi, matched) 321 | } 322 | } 323 | return matched 324 | } 325 | matched := matchBlocks(0, len(m.a), 0, len(m.b), nil) 326 | 327 | // It's possible that we have adjacent equal blocks in the 328 | // matching_blocks list now. 329 | nonAdjacent := []Match{} 330 | i1, j1, k1 := 0, 0, 0 331 | for _, b := range matched { 332 | // Is this block adjacent to i1, j1, k1? 333 | i2, j2, k2 := b.A, b.B, b.Size 334 | if i1+k1 == i2 && j1+k1 == j2 { 335 | // Yes, so collapse them -- this just increases the length of 336 | // the first block by the length of the second, and the first 337 | // block so lengthened remains the block to compare against. 338 | k1 += k2 339 | } else { 340 | // Not adjacent. Remember the first block (k1==0 means it's 341 | // the dummy we started with), and make the second block the 342 | // new block to compare against. 343 | if k1 > 0 { 344 | nonAdjacent = append(nonAdjacent, Match{i1, j1, k1}) 345 | } 346 | i1, j1, k1 = i2, j2, k2 347 | } 348 | } 349 | if k1 > 0 { 350 | nonAdjacent = append(nonAdjacent, Match{i1, j1, k1}) 351 | } 352 | 353 | nonAdjacent = append(nonAdjacent, Match{len(m.a), len(m.b), 0}) 354 | m.matchingBlocks = nonAdjacent 355 | return m.matchingBlocks 356 | } 357 | 358 | // Return list of 5-tuples describing how to turn a into b. 359 | // 360 | // Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple 361 | // has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the 362 | // tuple preceding it, and likewise for j1 == the previous j2. 363 | // 364 | // The tags are characters, with these meanings: 365 | // 366 | // 'r' (replace): a[i1:i2] should be replaced by b[j1:j2] 367 | // 368 | // 'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case. 369 | // 370 | // 'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case. 371 | // 372 | // 'e' (equal): a[i1:i2] == b[j1:j2] 373 | func (m *SequenceMatcher) GetOpCodes() []OpCode { 374 | if m.opCodes != nil { 375 | return m.opCodes 376 | } 377 | i, j := 0, 0 378 | matching := m.GetMatchingBlocks() 379 | opCodes := make([]OpCode, 0, len(matching)) 380 | for _, m := range matching { 381 | // invariant: we've pumped out correct diffs to change 382 | // a[:i] into b[:j], and the next matching block is 383 | // a[ai:ai+size] == b[bj:bj+size]. So we need to pump 384 | // out a diff to change a[i:ai] into b[j:bj], pump out 385 | // the matching block, and move (i,j) beyond the match 386 | ai, bj, size := m.A, m.B, m.Size 387 | tag := byte(0) 388 | if i < ai && j < bj { 389 | tag = 'r' 390 | } else if i < ai { 391 | tag = 'd' 392 | } else if j < bj { 393 | tag = 'i' 394 | } 395 | if tag > 0 { 396 | opCodes = append(opCodes, OpCode{tag, i, ai, j, bj}) 397 | } 398 | i, j = ai+size, bj+size 399 | // the list of matching blocks is terminated by a 400 | // sentinel with size 0 401 | if size > 0 { 402 | opCodes = append(opCodes, OpCode{'e', ai, i, bj, j}) 403 | } 404 | } 405 | m.opCodes = opCodes 406 | return m.opCodes 407 | } 408 | 409 | // Isolate change clusters by eliminating ranges with no changes. 410 | // 411 | // Return a generator of groups with up to n lines of context. 412 | // Each group is in the same format as returned by GetOpCodes(). 413 | func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode { 414 | if n < 0 { 415 | n = 3 416 | } 417 | codes := m.GetOpCodes() 418 | if len(codes) == 0 { 419 | codes = []OpCode{OpCode{'e', 0, 1, 0, 1}} 420 | } 421 | // Fixup leading and trailing groups if they show no changes. 422 | if codes[0].Tag == 'e' { 423 | c := codes[0] 424 | i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 425 | codes[0] = OpCode{c.Tag, max(i1, i2-n), i2, max(j1, j2-n), j2} 426 | } 427 | if codes[len(codes)-1].Tag == 'e' { 428 | c := codes[len(codes)-1] 429 | i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 430 | codes[len(codes)-1] = OpCode{c.Tag, i1, min(i2, i1+n), j1, min(j2, j1+n)} 431 | } 432 | nn := n + n 433 | groups := [][]OpCode{} 434 | group := []OpCode{} 435 | for _, c := range codes { 436 | i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 437 | // End the current group and start a new one whenever 438 | // there is a large range with no changes. 439 | if c.Tag == 'e' && i2-i1 > nn { 440 | group = append(group, OpCode{c.Tag, i1, min(i2, i1+n), 441 | j1, min(j2, j1+n)}) 442 | groups = append(groups, group) 443 | group = []OpCode{} 444 | i1, j1 = max(i1, i2-n), max(j1, j2-n) 445 | } 446 | group = append(group, OpCode{c.Tag, i1, i2, j1, j2}) 447 | } 448 | if len(group) > 0 && !(len(group) == 1 && group[0].Tag == 'e') { 449 | groups = append(groups, group) 450 | } 451 | return groups 452 | } 453 | 454 | // Return a measure of the sequences' similarity (float in [0,1]). 455 | // 456 | // Where T is the total number of elements in both sequences, and 457 | // M is the number of matches, this is 2.0*M / T. 458 | // Note that this is 1 if the sequences are identical, and 0 if 459 | // they have nothing in common. 460 | // 461 | // .Ratio() is expensive to compute if you haven't already computed 462 | // .GetMatchingBlocks() or .GetOpCodes(), in which case you may 463 | // want to try .QuickRatio() or .RealQuickRation() first to get an 464 | // upper bound. 465 | func (m *SequenceMatcher) Ratio() float64 { 466 | matches := 0 467 | for _, m := range m.GetMatchingBlocks() { 468 | matches += m.Size 469 | } 470 | return calculateRatio(matches, len(m.a)+len(m.b)) 471 | } 472 | 473 | // Return an upper bound on ratio() relatively quickly. 474 | // 475 | // This isn't defined beyond that it is an upper bound on .Ratio(), and 476 | // is faster to compute. 477 | func (m *SequenceMatcher) QuickRatio() float64 { 478 | // viewing a and b as multisets, set matches to the cardinality 479 | // of their intersection; this counts the number of matches 480 | // without regard to order, so is clearly an upper bound 481 | if m.fullBCount == nil { 482 | m.fullBCount = map[string]int{} 483 | for _, s := range m.b { 484 | m.fullBCount[s] = m.fullBCount[s] + 1 485 | } 486 | } 487 | 488 | // avail[x] is the number of times x appears in 'b' less the 489 | // number of times we've seen it in 'a' so far ... kinda 490 | avail := map[string]int{} 491 | matches := 0 492 | for _, s := range m.a { 493 | n, ok := avail[s] 494 | if !ok { 495 | n = m.fullBCount[s] 496 | } 497 | avail[s] = n - 1 498 | if n > 0 { 499 | matches += 1 500 | } 501 | } 502 | return calculateRatio(matches, len(m.a)+len(m.b)) 503 | } 504 | 505 | // Return an upper bound on ratio() very quickly. 506 | // 507 | // This isn't defined beyond that it is an upper bound on .Ratio(), and 508 | // is faster to compute than either .Ratio() or .QuickRatio(). 509 | func (m *SequenceMatcher) RealQuickRatio() float64 { 510 | la, lb := len(m.a), len(m.b) 511 | return calculateRatio(min(la, lb), la+lb) 512 | } 513 | 514 | // Convert range to the "ed" format 515 | func formatRangeUnified(start, stop int) string { 516 | // Per the diff spec at http://www.unix.org/single_unix_specification/ 517 | beginning := start + 1 // lines start numbering with one 518 | length := stop - start 519 | if length == 1 { 520 | return fmt.Sprintf("%d", beginning) 521 | } 522 | if length == 0 { 523 | beginning -= 1 // empty ranges begin at line just before the range 524 | } 525 | return fmt.Sprintf("%d,%d", beginning, length) 526 | } 527 | 528 | // Unified diff parameters 529 | type UnifiedDiff struct { 530 | A []string // First sequence lines 531 | FromFile string // First file name 532 | FromDate string // First file time 533 | B []string // Second sequence lines 534 | ToFile string // Second file name 535 | ToDate string // Second file time 536 | Eol string // Headers end of line, defaults to LF 537 | Context int // Number of context lines 538 | } 539 | 540 | // Compare two sequences of lines; generate the delta as a unified diff. 541 | // 542 | // Unified diffs are a compact way of showing line changes and a few 543 | // lines of context. The number of context lines is set by 'n' which 544 | // defaults to three. 545 | // 546 | // By default, the diff control lines (those with ---, +++, or @@) are 547 | // created with a trailing newline. This is helpful so that inputs 548 | // created from file.readlines() result in diffs that are suitable for 549 | // file.writelines() since both the inputs and outputs have trailing 550 | // newlines. 551 | // 552 | // For inputs that do not have trailing newlines, set the lineterm 553 | // argument to "" so that the output will be uniformly newline free. 554 | // 555 | // The unidiff format normally has a header for filenames and modification 556 | // times. Any or all of these may be specified using strings for 557 | // 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'. 558 | // The modification times are normally expressed in the ISO 8601 format. 559 | func WriteUnifiedDiff(writer io.Writer, diff UnifiedDiff) error { 560 | buf := bufio.NewWriter(writer) 561 | defer buf.Flush() 562 | wf := func(format string, args ...interface{}) error { 563 | _, err := buf.WriteString(fmt.Sprintf(format, args...)) 564 | return err 565 | } 566 | ws := func(s string) error { 567 | _, err := buf.WriteString(s) 568 | return err 569 | } 570 | 571 | if len(diff.Eol) == 0 { 572 | diff.Eol = "\n" 573 | } 574 | 575 | started := false 576 | m := NewMatcher(diff.A, diff.B) 577 | for _, g := range m.GetGroupedOpCodes(diff.Context) { 578 | if !started { 579 | started = true 580 | fromDate := "" 581 | if len(diff.FromDate) > 0 { 582 | fromDate = "\t" + diff.FromDate 583 | } 584 | toDate := "" 585 | if len(diff.ToDate) > 0 { 586 | toDate = "\t" + diff.ToDate 587 | } 588 | if diff.FromFile != "" || diff.ToFile != "" { 589 | err := wf("--- %s%s%s", diff.FromFile, fromDate, diff.Eol) 590 | if err != nil { 591 | return err 592 | } 593 | err = wf("+++ %s%s%s", diff.ToFile, toDate, diff.Eol) 594 | if err != nil { 595 | return err 596 | } 597 | } 598 | } 599 | first, last := g[0], g[len(g)-1] 600 | range1 := formatRangeUnified(first.I1, last.I2) 601 | range2 := formatRangeUnified(first.J1, last.J2) 602 | if err := wf("@@ -%s +%s @@%s", range1, range2, diff.Eol); err != nil { 603 | return err 604 | } 605 | for _, c := range g { 606 | i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 607 | if c.Tag == 'e' { 608 | for _, line := range diff.A[i1:i2] { 609 | if err := ws(" " + line); err != nil { 610 | return err 611 | } 612 | } 613 | continue 614 | } 615 | if c.Tag == 'r' || c.Tag == 'd' { 616 | for _, line := range diff.A[i1:i2] { 617 | if err := ws("-" + line); err != nil { 618 | return err 619 | } 620 | } 621 | } 622 | if c.Tag == 'r' || c.Tag == 'i' { 623 | for _, line := range diff.B[j1:j2] { 624 | if err := ws("+" + line); err != nil { 625 | return err 626 | } 627 | } 628 | } 629 | } 630 | } 631 | return nil 632 | } 633 | 634 | // Like WriteUnifiedDiff but returns the diff a string. 635 | func GetUnifiedDiffString(diff UnifiedDiff) (string, error) { 636 | w := &bytes.Buffer{} 637 | err := WriteUnifiedDiff(w, diff) 638 | return string(w.Bytes()), err 639 | } 640 | 641 | // Convert range to the "ed" format. 642 | func formatRangeContext(start, stop int) string { 643 | // Per the diff spec at http://www.unix.org/single_unix_specification/ 644 | beginning := start + 1 // lines start numbering with one 645 | length := stop - start 646 | if length == 0 { 647 | beginning -= 1 // empty ranges begin at line just before the range 648 | } 649 | if length <= 1 { 650 | return fmt.Sprintf("%d", beginning) 651 | } 652 | return fmt.Sprintf("%d,%d", beginning, beginning+length-1) 653 | } 654 | 655 | type ContextDiff UnifiedDiff 656 | 657 | // Compare two sequences of lines; generate the delta as a context diff. 658 | // 659 | // Context diffs are a compact way of showing line changes and a few 660 | // lines of context. The number of context lines is set by diff.Context 661 | // which defaults to three. 662 | // 663 | // By default, the diff control lines (those with *** or ---) are 664 | // created with a trailing newline. 665 | // 666 | // For inputs that do not have trailing newlines, set the diff.Eol 667 | // argument to "" so that the output will be uniformly newline free. 668 | // 669 | // The context diff format normally has a header for filenames and 670 | // modification times. Any or all of these may be specified using 671 | // strings for diff.FromFile, diff.ToFile, diff.FromDate, diff.ToDate. 672 | // The modification times are normally expressed in the ISO 8601 format. 673 | // If not specified, the strings default to blanks. 674 | func WriteContextDiff(writer io.Writer, diff ContextDiff) error { 675 | buf := bufio.NewWriter(writer) 676 | defer buf.Flush() 677 | var diffErr error 678 | wf := func(format string, args ...interface{}) { 679 | _, err := buf.WriteString(fmt.Sprintf(format, args...)) 680 | if diffErr == nil && err != nil { 681 | diffErr = err 682 | } 683 | } 684 | ws := func(s string) { 685 | _, err := buf.WriteString(s) 686 | if diffErr == nil && err != nil { 687 | diffErr = err 688 | } 689 | } 690 | 691 | if len(diff.Eol) == 0 { 692 | diff.Eol = "\n" 693 | } 694 | 695 | prefix := map[byte]string{ 696 | 'i': "+ ", 697 | 'd': "- ", 698 | 'r': "! ", 699 | 'e': " ", 700 | } 701 | 702 | started := false 703 | m := NewMatcher(diff.A, diff.B) 704 | for _, g := range m.GetGroupedOpCodes(diff.Context) { 705 | if !started { 706 | started = true 707 | fromDate := "" 708 | if len(diff.FromDate) > 0 { 709 | fromDate = "\t" + diff.FromDate 710 | } 711 | toDate := "" 712 | if len(diff.ToDate) > 0 { 713 | toDate = "\t" + diff.ToDate 714 | } 715 | if diff.FromFile != "" || diff.ToFile != "" { 716 | wf("*** %s%s%s", diff.FromFile, fromDate, diff.Eol) 717 | wf("--- %s%s%s", diff.ToFile, toDate, diff.Eol) 718 | } 719 | } 720 | 721 | first, last := g[0], g[len(g)-1] 722 | ws("***************" + diff.Eol) 723 | 724 | range1 := formatRangeContext(first.I1, last.I2) 725 | wf("*** %s ****%s", range1, diff.Eol) 726 | for _, c := range g { 727 | if c.Tag == 'r' || c.Tag == 'd' { 728 | for _, cc := range g { 729 | if cc.Tag == 'i' { 730 | continue 731 | } 732 | for _, line := range diff.A[cc.I1:cc.I2] { 733 | ws(prefix[cc.Tag] + line) 734 | } 735 | } 736 | break 737 | } 738 | } 739 | 740 | range2 := formatRangeContext(first.J1, last.J2) 741 | wf("--- %s ----%s", range2, diff.Eol) 742 | for _, c := range g { 743 | if c.Tag == 'r' || c.Tag == 'i' { 744 | for _, cc := range g { 745 | if cc.Tag == 'd' { 746 | continue 747 | } 748 | for _, line := range diff.B[cc.J1:cc.J2] { 749 | ws(prefix[cc.Tag] + line) 750 | } 751 | } 752 | break 753 | } 754 | } 755 | } 756 | return diffErr 757 | } 758 | 759 | // Like WriteContextDiff but returns the diff a string. 760 | func GetContextDiffString(diff ContextDiff) (string, error) { 761 | w := &bytes.Buffer{} 762 | err := WriteContextDiff(w, diff) 763 | return string(w.Bytes()), err 764 | } 765 | 766 | // Split a string on "\n" while preserving them. The output can be used 767 | // as input for UnifiedDiff and ContextDiff structures. 768 | func SplitLines(s string) []string { 769 | lines := strings.SplitAfter(s, "\n") 770 | lines[len(lines)-1] += "\n" 771 | return lines 772 | } 773 | -------------------------------------------------------------------------------- /Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions.go: -------------------------------------------------------------------------------- 1 | package assert 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "encoding/json" 7 | "fmt" 8 | "math" 9 | "reflect" 10 | "regexp" 11 | "runtime" 12 | "strings" 13 | "time" 14 | "unicode" 15 | "unicode/utf8" 16 | 17 | "github.com/davecgh/go-spew/spew" 18 | "github.com/pmezard/go-difflib/difflib" 19 | ) 20 | 21 | // TestingT is an interface wrapper around *testing.T 22 | type TestingT interface { 23 | Errorf(format string, args ...interface{}) 24 | } 25 | 26 | // Comparison a custom function that returns true on success and false on failure 27 | type Comparison func() (success bool) 28 | 29 | /* 30 | Helper functions 31 | */ 32 | 33 | // ObjectsAreEqual determines if two objects are considered equal. 34 | // 35 | // This function does no assertion of any kind. 36 | func ObjectsAreEqual(expected, actual interface{}) bool { 37 | 38 | if expected == nil || actual == nil { 39 | return expected == actual 40 | } 41 | 42 | return reflect.DeepEqual(expected, actual) 43 | 44 | } 45 | 46 | // ObjectsAreEqualValues gets whether two objects are equal, or if their 47 | // values are equal. 48 | func ObjectsAreEqualValues(expected, actual interface{}) bool { 49 | if ObjectsAreEqual(expected, actual) { 50 | return true 51 | } 52 | 53 | actualType := reflect.TypeOf(actual) 54 | if actualType == nil { 55 | return false 56 | } 57 | expectedValue := reflect.ValueOf(expected) 58 | if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { 59 | // Attempt comparison after type conversion 60 | return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) 61 | } 62 | 63 | return false 64 | } 65 | 66 | /* CallerInfo is necessary because the assert functions use the testing object 67 | internally, causing it to print the file:line of the assert method, rather than where 68 | the problem actually occured in calling code.*/ 69 | 70 | // CallerInfo returns an array of strings containing the file and line number 71 | // of each stack frame leading from the current test to the assert call that 72 | // failed. 73 | func CallerInfo() []string { 74 | 75 | pc := uintptr(0) 76 | file := "" 77 | line := 0 78 | ok := false 79 | name := "" 80 | 81 | callers := []string{} 82 | for i := 0; ; i++ { 83 | pc, file, line, ok = runtime.Caller(i) 84 | if !ok { 85 | return nil 86 | } 87 | 88 | // This is a huge edge case, but it will panic if this is the case, see #180 89 | if file == "" { 90 | break 91 | } 92 | 93 | parts := strings.Split(file, "/") 94 | dir := parts[len(parts)-2] 95 | file = parts[len(parts)-1] 96 | if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" { 97 | callers = append(callers, fmt.Sprintf("%s:%d", file, line)) 98 | } 99 | 100 | f := runtime.FuncForPC(pc) 101 | if f == nil { 102 | break 103 | } 104 | name = f.Name() 105 | // Drop the package 106 | segments := strings.Split(name, ".") 107 | name = segments[len(segments)-1] 108 | if isTest(name, "Test") || 109 | isTest(name, "Benchmark") || 110 | isTest(name, "Example") { 111 | break 112 | } 113 | } 114 | 115 | return callers 116 | } 117 | 118 | // Stolen from the `go test` tool. 119 | // isTest tells whether name looks like a test (or benchmark, according to prefix). 120 | // It is a Test (say) if there is a character after Test that is not a lower-case letter. 121 | // We don't want TesticularCancer. 122 | func isTest(name, prefix string) bool { 123 | if !strings.HasPrefix(name, prefix) { 124 | return false 125 | } 126 | if len(name) == len(prefix) { // "Test" is ok 127 | return true 128 | } 129 | rune, _ := utf8.DecodeRuneInString(name[len(prefix):]) 130 | return !unicode.IsLower(rune) 131 | } 132 | 133 | // getWhitespaceString returns a string that is long enough to overwrite the default 134 | // output from the go testing framework. 135 | func getWhitespaceString() string { 136 | 137 | _, file, line, ok := runtime.Caller(1) 138 | if !ok { 139 | return "" 140 | } 141 | parts := strings.Split(file, "/") 142 | file = parts[len(parts)-1] 143 | 144 | return strings.Repeat(" ", len(fmt.Sprintf("%s:%d: ", file, line))) 145 | 146 | } 147 | 148 | func messageFromMsgAndArgs(msgAndArgs ...interface{}) string { 149 | if len(msgAndArgs) == 0 || msgAndArgs == nil { 150 | return "" 151 | } 152 | if len(msgAndArgs) == 1 { 153 | return msgAndArgs[0].(string) 154 | } 155 | if len(msgAndArgs) > 1 { 156 | return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...) 157 | } 158 | return "" 159 | } 160 | 161 | // Indents all lines of the message by appending a number of tabs to each line, in an output format compatible with Go's 162 | // test printing (see inner comment for specifics) 163 | func indentMessageLines(message string, tabs int) string { 164 | outBuf := new(bytes.Buffer) 165 | 166 | for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ { 167 | if i != 0 { 168 | outBuf.WriteRune('\n') 169 | } 170 | for ii := 0; ii < tabs; ii++ { 171 | outBuf.WriteRune('\t') 172 | // Bizarrely, all lines except the first need one fewer tabs prepended, so deliberately advance the counter 173 | // by 1 prematurely. 174 | if ii == 0 && i > 0 { 175 | ii++ 176 | } 177 | } 178 | outBuf.WriteString(scanner.Text()) 179 | } 180 | 181 | return outBuf.String() 182 | } 183 | 184 | type failNower interface { 185 | FailNow() 186 | } 187 | 188 | // FailNow fails test 189 | func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { 190 | Fail(t, failureMessage, msgAndArgs...) 191 | 192 | // We cannot extend TestingT with FailNow() and 193 | // maintain backwards compatibility, so we fallback 194 | // to panicking when FailNow is not available in 195 | // TestingT. 196 | // See issue #263 197 | 198 | if t, ok := t.(failNower); ok { 199 | t.FailNow() 200 | } else { 201 | panic("test failed and t is missing `FailNow()`") 202 | } 203 | return false 204 | } 205 | 206 | // Fail reports a failure through 207 | func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { 208 | 209 | message := messageFromMsgAndArgs(msgAndArgs...) 210 | 211 | errorTrace := strings.Join(CallerInfo(), "\n\r\t\t\t") 212 | if len(message) > 0 { 213 | t.Errorf("\r%s\r\tError Trace:\t%s\n"+ 214 | "\r\tError:%s\n"+ 215 | "\r\tMessages:\t%s\n\r", 216 | getWhitespaceString(), 217 | errorTrace, 218 | indentMessageLines(failureMessage, 2), 219 | message) 220 | } else { 221 | t.Errorf("\r%s\r\tError Trace:\t%s\n"+ 222 | "\r\tError:%s\n\r", 223 | getWhitespaceString(), 224 | errorTrace, 225 | indentMessageLines(failureMessage, 2)) 226 | } 227 | 228 | return false 229 | } 230 | 231 | // Implements asserts that an object is implemented by the specified interface. 232 | // 233 | // assert.Implements(t, (*MyInterface)(nil), new(MyObject), "MyObject") 234 | func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { 235 | 236 | interfaceType := reflect.TypeOf(interfaceObject).Elem() 237 | 238 | if !reflect.TypeOf(object).Implements(interfaceType) { 239 | return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...) 240 | } 241 | 242 | return true 243 | 244 | } 245 | 246 | // IsType asserts that the specified objects are of the same type. 247 | func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { 248 | 249 | if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) { 250 | return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...) 251 | } 252 | 253 | return true 254 | } 255 | 256 | // Equal asserts that two objects are equal. 257 | // 258 | // assert.Equal(t, 123, 123, "123 and 123 should be equal") 259 | // 260 | // Returns whether the assertion was successful (true) or not (false). 261 | func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { 262 | 263 | if !ObjectsAreEqual(expected, actual) { 264 | diff := diff(expected, actual) 265 | return Fail(t, fmt.Sprintf("Not equal: %#v (expected)\n"+ 266 | " != %#v (actual)%s", expected, actual, diff), msgAndArgs...) 267 | } 268 | 269 | return true 270 | 271 | } 272 | 273 | // EqualValues asserts that two objects are equal or convertable to the same types 274 | // and equal. 275 | // 276 | // assert.EqualValues(t, uint32(123), int32(123), "123 and 123 should be equal") 277 | // 278 | // Returns whether the assertion was successful (true) or not (false). 279 | func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { 280 | 281 | if !ObjectsAreEqualValues(expected, actual) { 282 | return Fail(t, fmt.Sprintf("Not equal: %#v (expected)\n"+ 283 | " != %#v (actual)", expected, actual), msgAndArgs...) 284 | } 285 | 286 | return true 287 | 288 | } 289 | 290 | // Exactly asserts that two objects are equal is value and type. 291 | // 292 | // assert.Exactly(t, int32(123), int64(123), "123 and 123 should NOT be equal") 293 | // 294 | // Returns whether the assertion was successful (true) or not (false). 295 | func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { 296 | 297 | aType := reflect.TypeOf(expected) 298 | bType := reflect.TypeOf(actual) 299 | 300 | if aType != bType { 301 | return Fail(t, fmt.Sprintf("Types expected to match exactly\n\r\t%v != %v", aType, bType), msgAndArgs...) 302 | } 303 | 304 | return Equal(t, expected, actual, msgAndArgs...) 305 | 306 | } 307 | 308 | // NotNil asserts that the specified object is not nil. 309 | // 310 | // assert.NotNil(t, err, "err should be something") 311 | // 312 | // Returns whether the assertion was successful (true) or not (false). 313 | func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { 314 | if !isNil(object) { 315 | return true 316 | } 317 | return Fail(t, "Expected value not to be nil.", msgAndArgs...) 318 | } 319 | 320 | // isNil checks if a specified object is nil or not, without Failing. 321 | func isNil(object interface{}) bool { 322 | if object == nil { 323 | return true 324 | } 325 | 326 | value := reflect.ValueOf(object) 327 | kind := value.Kind() 328 | if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() { 329 | return true 330 | } 331 | 332 | return false 333 | } 334 | 335 | // Nil asserts that the specified object is nil. 336 | // 337 | // assert.Nil(t, err, "err should be nothing") 338 | // 339 | // Returns whether the assertion was successful (true) or not (false). 340 | func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { 341 | if isNil(object) { 342 | return true 343 | } 344 | return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...) 345 | } 346 | 347 | var numericZeros = []interface{}{ 348 | int(0), 349 | int8(0), 350 | int16(0), 351 | int32(0), 352 | int64(0), 353 | uint(0), 354 | uint8(0), 355 | uint16(0), 356 | uint32(0), 357 | uint64(0), 358 | float32(0), 359 | float64(0), 360 | } 361 | 362 | // isEmpty gets whether the specified object is considered empty or not. 363 | func isEmpty(object interface{}) bool { 364 | 365 | if object == nil { 366 | return true 367 | } else if object == "" { 368 | return true 369 | } else if object == false { 370 | return true 371 | } 372 | 373 | for _, v := range numericZeros { 374 | if object == v { 375 | return true 376 | } 377 | } 378 | 379 | objValue := reflect.ValueOf(object) 380 | 381 | switch objValue.Kind() { 382 | case reflect.Map: 383 | fallthrough 384 | case reflect.Slice, reflect.Chan: 385 | { 386 | return (objValue.Len() == 0) 387 | } 388 | case reflect.Struct: 389 | switch object.(type) { 390 | case time.Time: 391 | return object.(time.Time).IsZero() 392 | } 393 | case reflect.Ptr: 394 | { 395 | if objValue.IsNil() { 396 | return true 397 | } 398 | switch object.(type) { 399 | case *time.Time: 400 | return object.(*time.Time).IsZero() 401 | default: 402 | return false 403 | } 404 | } 405 | } 406 | return false 407 | } 408 | 409 | // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either 410 | // a slice or a channel with len == 0. 411 | // 412 | // assert.Empty(t, obj) 413 | // 414 | // Returns whether the assertion was successful (true) or not (false). 415 | func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { 416 | 417 | pass := isEmpty(object) 418 | if !pass { 419 | Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...) 420 | } 421 | 422 | return pass 423 | 424 | } 425 | 426 | // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either 427 | // a slice or a channel with len == 0. 428 | // 429 | // if assert.NotEmpty(t, obj) { 430 | // assert.Equal(t, "two", obj[1]) 431 | // } 432 | // 433 | // Returns whether the assertion was successful (true) or not (false). 434 | func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { 435 | 436 | pass := !isEmpty(object) 437 | if !pass { 438 | Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...) 439 | } 440 | 441 | return pass 442 | 443 | } 444 | 445 | // getLen try to get length of object. 446 | // return (false, 0) if impossible. 447 | func getLen(x interface{}) (ok bool, length int) { 448 | v := reflect.ValueOf(x) 449 | defer func() { 450 | if e := recover(); e != nil { 451 | ok = false 452 | } 453 | }() 454 | return true, v.Len() 455 | } 456 | 457 | // Len asserts that the specified object has specific length. 458 | // Len also fails if the object has a type that len() not accept. 459 | // 460 | // assert.Len(t, mySlice, 3, "The size of slice is not 3") 461 | // 462 | // Returns whether the assertion was successful (true) or not (false). 463 | func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool { 464 | ok, l := getLen(object) 465 | if !ok { 466 | return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...) 467 | } 468 | 469 | if l != length { 470 | return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...) 471 | } 472 | return true 473 | } 474 | 475 | // True asserts that the specified value is true. 476 | // 477 | // assert.True(t, myBool, "myBool should be true") 478 | // 479 | // Returns whether the assertion was successful (true) or not (false). 480 | func True(t TestingT, value bool, msgAndArgs ...interface{}) bool { 481 | 482 | if value != true { 483 | return Fail(t, "Should be true", msgAndArgs...) 484 | } 485 | 486 | return true 487 | 488 | } 489 | 490 | // False asserts that the specified value is false. 491 | // 492 | // assert.False(t, myBool, "myBool should be false") 493 | // 494 | // Returns whether the assertion was successful (true) or not (false). 495 | func False(t TestingT, value bool, msgAndArgs ...interface{}) bool { 496 | 497 | if value != false { 498 | return Fail(t, "Should be false", msgAndArgs...) 499 | } 500 | 501 | return true 502 | 503 | } 504 | 505 | // NotEqual asserts that the specified values are NOT equal. 506 | // 507 | // assert.NotEqual(t, obj1, obj2, "two objects shouldn't be equal") 508 | // 509 | // Returns whether the assertion was successful (true) or not (false). 510 | func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { 511 | 512 | if ObjectsAreEqual(expected, actual) { 513 | return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...) 514 | } 515 | 516 | return true 517 | 518 | } 519 | 520 | // containsElement try loop over the list check if the list includes the element. 521 | // return (false, false) if impossible. 522 | // return (true, false) if element was not found. 523 | // return (true, true) if element was found. 524 | func includeElement(list interface{}, element interface{}) (ok, found bool) { 525 | 526 | listValue := reflect.ValueOf(list) 527 | elementValue := reflect.ValueOf(element) 528 | defer func() { 529 | if e := recover(); e != nil { 530 | ok = false 531 | found = false 532 | } 533 | }() 534 | 535 | if reflect.TypeOf(list).Kind() == reflect.String { 536 | return true, strings.Contains(listValue.String(), elementValue.String()) 537 | } 538 | 539 | if reflect.TypeOf(list).Kind() == reflect.Map { 540 | mapKeys := listValue.MapKeys() 541 | for i := 0; i < len(mapKeys); i++ { 542 | if ObjectsAreEqual(mapKeys[i].Interface(), element) { 543 | return true, true 544 | } 545 | } 546 | return true, false 547 | } 548 | 549 | for i := 0; i < listValue.Len(); i++ { 550 | if ObjectsAreEqual(listValue.Index(i).Interface(), element) { 551 | return true, true 552 | } 553 | } 554 | return true, false 555 | 556 | } 557 | 558 | // Contains asserts that the specified string, list(array, slice...) or map contains the 559 | // specified substring or element. 560 | // 561 | // assert.Contains(t, "Hello World", "World", "But 'Hello World' does contain 'World'") 562 | // assert.Contains(t, ["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'") 563 | // assert.Contains(t, {"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'") 564 | // 565 | // Returns whether the assertion was successful (true) or not (false). 566 | func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { 567 | 568 | ok, found := includeElement(s, contains) 569 | if !ok { 570 | return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) 571 | } 572 | if !found { 573 | return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...) 574 | } 575 | 576 | return true 577 | 578 | } 579 | 580 | // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the 581 | // specified substring or element. 582 | // 583 | // assert.NotContains(t, "Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") 584 | // assert.NotContains(t, ["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'") 585 | // assert.NotContains(t, {"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'") 586 | // 587 | // Returns whether the assertion was successful (true) or not (false). 588 | func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { 589 | 590 | ok, found := includeElement(s, contains) 591 | if !ok { 592 | return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) 593 | } 594 | if found { 595 | return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...) 596 | } 597 | 598 | return true 599 | 600 | } 601 | 602 | // Condition uses a Comparison to assert a complex condition. 603 | func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool { 604 | result := comp() 605 | if !result { 606 | Fail(t, "Condition failed!", msgAndArgs...) 607 | } 608 | return result 609 | } 610 | 611 | // PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics 612 | // methods, and represents a simple func that takes no arguments, and returns nothing. 613 | type PanicTestFunc func() 614 | 615 | // didPanic returns true if the function passed to it panics. Otherwise, it returns false. 616 | func didPanic(f PanicTestFunc) (bool, interface{}) { 617 | 618 | didPanic := false 619 | var message interface{} 620 | func() { 621 | 622 | defer func() { 623 | if message = recover(); message != nil { 624 | didPanic = true 625 | } 626 | }() 627 | 628 | // call the target function 629 | f() 630 | 631 | }() 632 | 633 | return didPanic, message 634 | 635 | } 636 | 637 | // Panics asserts that the code inside the specified PanicTestFunc panics. 638 | // 639 | // assert.Panics(t, func(){ 640 | // GoCrazy() 641 | // }, "Calling GoCrazy() should panic") 642 | // 643 | // Returns whether the assertion was successful (true) or not (false). 644 | func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { 645 | 646 | if funcDidPanic, panicValue := didPanic(f); !funcDidPanic { 647 | return Fail(t, fmt.Sprintf("func %#v should panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...) 648 | } 649 | 650 | return true 651 | } 652 | 653 | // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. 654 | // 655 | // assert.NotPanics(t, func(){ 656 | // RemainCalm() 657 | // }, "Calling RemainCalm() should NOT panic") 658 | // 659 | // Returns whether the assertion was successful (true) or not (false). 660 | func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { 661 | 662 | if funcDidPanic, panicValue := didPanic(f); funcDidPanic { 663 | return Fail(t, fmt.Sprintf("func %#v should not panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...) 664 | } 665 | 666 | return true 667 | } 668 | 669 | // WithinDuration asserts that the two times are within duration delta of each other. 670 | // 671 | // assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") 672 | // 673 | // Returns whether the assertion was successful (true) or not (false). 674 | func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { 675 | 676 | dt := expected.Sub(actual) 677 | if dt < -delta || dt > delta { 678 | return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) 679 | } 680 | 681 | return true 682 | } 683 | 684 | func toFloat(x interface{}) (float64, bool) { 685 | var xf float64 686 | xok := true 687 | 688 | switch xn := x.(type) { 689 | case uint8: 690 | xf = float64(xn) 691 | case uint16: 692 | xf = float64(xn) 693 | case uint32: 694 | xf = float64(xn) 695 | case uint64: 696 | xf = float64(xn) 697 | case int: 698 | xf = float64(xn) 699 | case int8: 700 | xf = float64(xn) 701 | case int16: 702 | xf = float64(xn) 703 | case int32: 704 | xf = float64(xn) 705 | case int64: 706 | xf = float64(xn) 707 | case float32: 708 | xf = float64(xn) 709 | case float64: 710 | xf = float64(xn) 711 | default: 712 | xok = false 713 | } 714 | 715 | return xf, xok 716 | } 717 | 718 | // InDelta asserts that the two numerals are within delta of each other. 719 | // 720 | // assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) 721 | // 722 | // Returns whether the assertion was successful (true) or not (false). 723 | func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { 724 | 725 | af, aok := toFloat(expected) 726 | bf, bok := toFloat(actual) 727 | 728 | if !aok || !bok { 729 | return Fail(t, fmt.Sprintf("Parameters must be numerical"), msgAndArgs...) 730 | } 731 | 732 | if math.IsNaN(af) { 733 | return Fail(t, fmt.Sprintf("Actual must not be NaN"), msgAndArgs...) 734 | } 735 | 736 | if math.IsNaN(bf) { 737 | return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...) 738 | } 739 | 740 | dt := af - bf 741 | if dt < -delta || dt > delta { 742 | return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) 743 | } 744 | 745 | return true 746 | } 747 | 748 | // InDeltaSlice is the same as InDelta, except it compares two slices. 749 | func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { 750 | if expected == nil || actual == nil || 751 | reflect.TypeOf(actual).Kind() != reflect.Slice || 752 | reflect.TypeOf(expected).Kind() != reflect.Slice { 753 | return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...) 754 | } 755 | 756 | actualSlice := reflect.ValueOf(actual) 757 | expectedSlice := reflect.ValueOf(expected) 758 | 759 | for i := 0; i < actualSlice.Len(); i++ { 760 | result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta) 761 | if !result { 762 | return result 763 | } 764 | } 765 | 766 | return true 767 | } 768 | 769 | func calcRelativeError(expected, actual interface{}) (float64, error) { 770 | af, aok := toFloat(expected) 771 | if !aok { 772 | return 0, fmt.Errorf("expected value %q cannot be converted to float", expected) 773 | } 774 | if af == 0 { 775 | return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error") 776 | } 777 | bf, bok := toFloat(actual) 778 | if !bok { 779 | return 0, fmt.Errorf("expected value %q cannot be converted to float", actual) 780 | } 781 | 782 | return math.Abs(af-bf) / math.Abs(af), nil 783 | } 784 | 785 | // InEpsilon asserts that expected and actual have a relative error less than epsilon 786 | // 787 | // Returns whether the assertion was successful (true) or not (false). 788 | func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { 789 | actualEpsilon, err := calcRelativeError(expected, actual) 790 | if err != nil { 791 | return Fail(t, err.Error(), msgAndArgs...) 792 | } 793 | if actualEpsilon > epsilon { 794 | return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+ 795 | " < %#v (actual)", actualEpsilon, epsilon), msgAndArgs...) 796 | } 797 | 798 | return true 799 | } 800 | 801 | // InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. 802 | func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { 803 | if expected == nil || actual == nil || 804 | reflect.TypeOf(actual).Kind() != reflect.Slice || 805 | reflect.TypeOf(expected).Kind() != reflect.Slice { 806 | return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...) 807 | } 808 | 809 | actualSlice := reflect.ValueOf(actual) 810 | expectedSlice := reflect.ValueOf(expected) 811 | 812 | for i := 0; i < actualSlice.Len(); i++ { 813 | result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon) 814 | if !result { 815 | return result 816 | } 817 | } 818 | 819 | return true 820 | } 821 | 822 | /* 823 | Errors 824 | */ 825 | 826 | // NoError asserts that a function returned no error (i.e. `nil`). 827 | // 828 | // actualObj, err := SomeFunction() 829 | // if assert.NoError(t, err) { 830 | // assert.Equal(t, actualObj, expectedObj) 831 | // } 832 | // 833 | // Returns whether the assertion was successful (true) or not (false). 834 | func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool { 835 | if err != nil { 836 | return Fail(t, fmt.Sprintf("Received unexpected error %q", err), msgAndArgs...) 837 | } 838 | 839 | return true 840 | } 841 | 842 | // Error asserts that a function returned an error (i.e. not `nil`). 843 | // 844 | // actualObj, err := SomeFunction() 845 | // if assert.Error(t, err, "An error was expected") { 846 | // assert.Equal(t, err, expectedError) 847 | // } 848 | // 849 | // Returns whether the assertion was successful (true) or not (false). 850 | func Error(t TestingT, err error, msgAndArgs ...interface{}) bool { 851 | 852 | message := messageFromMsgAndArgs(msgAndArgs...) 853 | if err == nil { 854 | return Fail(t, "An error is expected but got nil. %s", message) 855 | } 856 | 857 | return true 858 | } 859 | 860 | // EqualError asserts that a function returned an error (i.e. not `nil`) 861 | // and that it is equal to the provided error. 862 | // 863 | // actualObj, err := SomeFunction() 864 | // if assert.Error(t, err, "An error was expected") { 865 | // assert.Equal(t, err, expectedError) 866 | // } 867 | // 868 | // Returns whether the assertion was successful (true) or not (false). 869 | func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool { 870 | 871 | message := messageFromMsgAndArgs(msgAndArgs...) 872 | if !NotNil(t, theError, "An error is expected but got nil. %s", message) { 873 | return false 874 | } 875 | s := "An error with value \"%s\" is expected but got \"%s\". %s" 876 | return Equal(t, errString, theError.Error(), 877 | s, errString, theError.Error(), message) 878 | } 879 | 880 | // matchRegexp return true if a specified regexp matches a string. 881 | func matchRegexp(rx interface{}, str interface{}) bool { 882 | 883 | var r *regexp.Regexp 884 | if rr, ok := rx.(*regexp.Regexp); ok { 885 | r = rr 886 | } else { 887 | r = regexp.MustCompile(fmt.Sprint(rx)) 888 | } 889 | 890 | return (r.FindStringIndex(fmt.Sprint(str)) != nil) 891 | 892 | } 893 | 894 | // Regexp asserts that a specified regexp matches a string. 895 | // 896 | // assert.Regexp(t, regexp.MustCompile("start"), "it's starting") 897 | // assert.Regexp(t, "start...$", "it's not starting") 898 | // 899 | // Returns whether the assertion was successful (true) or not (false). 900 | func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { 901 | 902 | match := matchRegexp(rx, str) 903 | 904 | if !match { 905 | Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...) 906 | } 907 | 908 | return match 909 | } 910 | 911 | // NotRegexp asserts that a specified regexp does not match a string. 912 | // 913 | // assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") 914 | // assert.NotRegexp(t, "^start", "it's not starting") 915 | // 916 | // Returns whether the assertion was successful (true) or not (false). 917 | func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { 918 | match := matchRegexp(rx, str) 919 | 920 | if match { 921 | Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...) 922 | } 923 | 924 | return !match 925 | 926 | } 927 | 928 | // Zero asserts that i is the zero value for its type and returns the truth. 929 | func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool { 930 | if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { 931 | return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...) 932 | } 933 | return true 934 | } 935 | 936 | // NotZero asserts that i is not the zero value for its type and returns the truth. 937 | func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool { 938 | if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { 939 | return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...) 940 | } 941 | return true 942 | } 943 | 944 | // JSONEq asserts that two JSON strings are equivalent. 945 | // 946 | // assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) 947 | // 948 | // Returns whether the assertion was successful (true) or not (false). 949 | func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool { 950 | var expectedJSONAsInterface, actualJSONAsInterface interface{} 951 | 952 | if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil { 953 | return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...) 954 | } 955 | 956 | if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil { 957 | return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...) 958 | } 959 | 960 | return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...) 961 | } 962 | 963 | func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) { 964 | t := reflect.TypeOf(v) 965 | k := t.Kind() 966 | 967 | if k == reflect.Ptr { 968 | t = t.Elem() 969 | k = t.Kind() 970 | } 971 | return t, k 972 | } 973 | 974 | // diff returns a diff of both values as long as both are of the same type and 975 | // are a struct, map, slice or array. Otherwise it returns an empty string. 976 | func diff(expected interface{}, actual interface{}) string { 977 | if expected == nil || actual == nil { 978 | return "" 979 | } 980 | 981 | et, ek := typeAndKind(expected) 982 | at, _ := typeAndKind(actual) 983 | 984 | if et != at { 985 | return "" 986 | } 987 | 988 | if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array { 989 | return "" 990 | } 991 | 992 | spew.Config.SortKeys = true 993 | e := spew.Sdump(expected) 994 | a := spew.Sdump(actual) 995 | 996 | diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{ 997 | A: difflib.SplitLines(e), 998 | B: difflib.SplitLines(a), 999 | FromFile: "Expected", 1000 | FromDate: "", 1001 | ToFile: "Actual", 1002 | ToDate: "", 1003 | Context: 1, 1004 | }) 1005 | 1006 | return "\n\nDiff:\n" + diff 1007 | } 1008 | --------------------------------------------------------------------------------