From 2ea5c3b9fef3d3a3960271daaaf8c0b6812e4ca9 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sat, 5 Dec 2020 09:20:54 +0800 Subject: [PATCH 01/23] Some changes to fix recovery --- routers/routes/chi.go | 1 + 1 file changed, 1 insertion(+) diff --git a/routers/routes/chi.go b/routers/routes/chi.go index c0ac88957ee2b..7b3cf2034abdd 100644 --- a/routers/routes/chi.go +++ b/routers/routes/chi.go @@ -227,6 +227,7 @@ func RegisterInstallRoute(c chi.Router) { // We need at least one handler in chi so that it does not drop // our middleware: https://github.com/go-gitea/gitea/issues/13725#issuecomment-735244395 c.Get("/", func(w http.ResponseWriter, req *http.Request) { + panic("lll") m.ServeHTTP(w, req) }) From 3ad150b961852fda5100c5dc1d8de0a8bafa74fb Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sat, 5 Dec 2020 14:52:34 +0800 Subject: [PATCH 02/23] Move Recovery to middlewares --- modules/middlewares/cookie.go | 1 - modules/middlewares/recovery.go | 60 +++++++++++++++++++++++++++++++++ routers/routes/chi.go | 3 +- 3 files changed, 62 insertions(+), 2 deletions(-) create mode 100644 modules/middlewares/recovery.go diff --git a/modules/middlewares/cookie.go b/modules/middlewares/cookie.go index 80d0e3b453ef6..9ef03c205c03d 100644 --- a/modules/middlewares/cookie.go +++ b/modules/middlewares/cookie.go @@ -26,7 +26,6 @@ func NewCookie(name, value string, maxAge int) *http.Cookie { } // SetCookie set the cookies -// TODO: Copied from gitea.com/macaron/macaron and should be improved after macaron removed. func SetCookie(resp http.ResponseWriter, name string, value string, others ...interface{}) { cookie := http.Cookie{} cookie.Name = name diff --git a/modules/middlewares/recovery.go b/modules/middlewares/recovery.go new file mode 100644 index 0000000000000..2946660ae3768 --- /dev/null +++ b/modules/middlewares/recovery.go @@ -0,0 +1,60 @@ +// Copyright 2020 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package middlewares + +import ( + "fmt" + "net/http" + + "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/templates" + + "github.com/unrolled/render" +) + +// Recovery returns a middleware that recovers from any panics and writes a 500 and a log if so. +// Although similar to macaron.Recovery() the main difference is that this error will be created +// with the gitea 500 page. +func Recovery() func(next http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + rnd := render.New(render.Options{ + Extensions: []string{".tmpl"}, + Directory: "templates", + Funcs: templates.NewFuncMap(), + Asset: templates.GetAsset, + AssetNames: templates.GetAssetNames, + IsDevelopment: setting.RunMode != "prod", + }) + + return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + defer func() { + if err := recover(); err != nil { + combinedErr := fmt.Sprintf("PANIC: %v\n%s", err, string(log.Stack(2))) + log.Error("%v", combinedErr) + + lc := Locale(w, req) + + var ( + data = templates.Vars{ + "Language": lc.Language(), + "CurrentURL": setting.AppSubURL + req.URL.RequestURI(), + "i18n": lc, + } + ) + if setting.RunMode != "prod" { + data["ErrMsg"] = combinedErr + } + err := rnd.HTML(w, 500, "status/500", templates.BaseVars().Merge(data)) + if err != nil { + log.Error("%v", err) + } + } + }() + + next.ServeHTTP(w, req) + }) + } +} diff --git a/routers/routes/chi.go b/routers/routes/chi.go index 7b3cf2034abdd..edf9159754e1e 100644 --- a/routers/routes/chi.go +++ b/routers/routes/chi.go @@ -19,6 +19,7 @@ import ( "code.gitea.io/gitea/modules/httpcache" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/metrics" + "code.gitea.io/gitea/modules/middlewares" "code.gitea.io/gitea/modules/public" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/storage" @@ -196,7 +197,7 @@ func NewChi() chi.Router { Domain: setting.SessionConfig.Domain, })) - c.Use(Recovery()) + c.Use(middlewares.Recovery()) if setting.EnableAccessLog { setupAccessLogger(c) } From 9b0379bbb7286534d278356aa2155a456f46a2d9 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sat, 5 Dec 2020 14:57:58 +0800 Subject: [PATCH 03/23] Remove trace code --- routers/routes/chi.go | 1 - 1 file changed, 1 deletion(-) diff --git a/routers/routes/chi.go b/routers/routes/chi.go index edf9159754e1e..69c5d7d955c86 100644 --- a/routers/routes/chi.go +++ b/routers/routes/chi.go @@ -228,7 +228,6 @@ func RegisterInstallRoute(c chi.Router) { // We need at least one handler in chi so that it does not drop // our middleware: https://github.com/go-gitea/gitea/issues/13725#issuecomment-735244395 c.Get("/", func(w http.ResponseWriter, req *http.Request) { - panic("lll") m.ServeHTTP(w, req) }) From 5d29bee07589c53b4d5db85455119ce7308a4855 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sat, 19 Dec 2020 00:08:16 +0800 Subject: [PATCH 04/23] add session middleware and remove dependent on macaron for sso --- modules/middlewares/recovery.go | 60 --------------------------------- routers/routes/chi.go | 3 +- vendor/modules.txt | 3 ++ 3 files changed, 4 insertions(+), 62 deletions(-) delete mode 100644 modules/middlewares/recovery.go diff --git a/modules/middlewares/recovery.go b/modules/middlewares/recovery.go deleted file mode 100644 index 2946660ae3768..0000000000000 --- a/modules/middlewares/recovery.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2020 The Gitea Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. - -package middlewares - -import ( - "fmt" - "net/http" - - "code.gitea.io/gitea/modules/log" - "code.gitea.io/gitea/modules/setting" - "code.gitea.io/gitea/modules/templates" - - "github.com/unrolled/render" -) - -// Recovery returns a middleware that recovers from any panics and writes a 500 and a log if so. -// Although similar to macaron.Recovery() the main difference is that this error will be created -// with the gitea 500 page. -func Recovery() func(next http.Handler) http.Handler { - return func(next http.Handler) http.Handler { - rnd := render.New(render.Options{ - Extensions: []string{".tmpl"}, - Directory: "templates", - Funcs: templates.NewFuncMap(), - Asset: templates.GetAsset, - AssetNames: templates.GetAssetNames, - IsDevelopment: setting.RunMode != "prod", - }) - - return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - defer func() { - if err := recover(); err != nil { - combinedErr := fmt.Sprintf("PANIC: %v\n%s", err, string(log.Stack(2))) - log.Error("%v", combinedErr) - - lc := Locale(w, req) - - var ( - data = templates.Vars{ - "Language": lc.Language(), - "CurrentURL": setting.AppSubURL + req.URL.RequestURI(), - "i18n": lc, - } - ) - if setting.RunMode != "prod" { - data["ErrMsg"] = combinedErr - } - err := rnd.HTML(w, 500, "status/500", templates.BaseVars().Merge(data)) - if err != nil { - log.Error("%v", err) - } - } - }() - - next.ServeHTTP(w, req) - }) - } -} diff --git a/routers/routes/chi.go b/routers/routes/chi.go index 69c5d7d955c86..c0ac88957ee2b 100644 --- a/routers/routes/chi.go +++ b/routers/routes/chi.go @@ -19,7 +19,6 @@ import ( "code.gitea.io/gitea/modules/httpcache" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/metrics" - "code.gitea.io/gitea/modules/middlewares" "code.gitea.io/gitea/modules/public" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/storage" @@ -197,7 +196,7 @@ func NewChi() chi.Router { Domain: setting.SessionConfig.Domain, })) - c.Use(middlewares.Recovery()) + c.Use(Recovery()) if setting.EnableAccessLog { setupAccessLogger(c) } diff --git a/vendor/modules.txt b/vendor/modules.txt index 426b0dc9473a5..49f460690984a 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -10,10 +10,13 @@ code.gitea.io/sdk/gitea # gitea.com/go-chi/session v0.0.0-20201218134809-7209fa084f27 ## explicit gitea.com/go-chi/session +<<<<<<< HEAD gitea.com/go-chi/session/couchbase gitea.com/go-chi/session/memcache gitea.com/go-chi/session/mysql gitea.com/go-chi/session/postgres +======= +>>>>>>> 076710db1... add session middleware and remove dependent on macaron for sso # gitea.com/lunny/levelqueue v0.3.0 ## explicit gitea.com/lunny/levelqueue From 1aa27987cf888d57dec57f76fbb2ac47e98cc580 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sat, 19 Dec 2020 15:49:32 +0800 Subject: [PATCH 05/23] Fix panic 500 page rendering --- modules/options/static.go | 2 +- vendor/modules.txt | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/modules/options/static.go b/modules/options/static.go index 5f4ffdda78e49..ac5c749e3ce1f 100644 --- a/modules/options/static.go +++ b/modules/options/static.go @@ -133,7 +133,7 @@ func AssetNames() []string { realFS := Assets.(vfsgen۰FS) var results = make([]string, 0, len(realFS)) for k := range realFS { - results = append(results, k[1:]) + results = append(results, "templates/"+k[1:]) } return results } diff --git a/vendor/modules.txt b/vendor/modules.txt index 49f460690984a..be0223ab05ea0 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,3 +1,4 @@ + # cloud.google.com/go v0.67.0 cloud.google.com/go/compute/metadata # code.gitea.io/gitea-vet v0.2.1 @@ -10,13 +11,10 @@ code.gitea.io/sdk/gitea # gitea.com/go-chi/session v0.0.0-20201218134809-7209fa084f27 ## explicit gitea.com/go-chi/session -<<<<<<< HEAD gitea.com/go-chi/session/couchbase gitea.com/go-chi/session/memcache gitea.com/go-chi/session/mysql gitea.com/go-chi/session/postgres -======= ->>>>>>> 076710db1... add session middleware and remove dependent on macaron for sso # gitea.com/lunny/levelqueue v0.3.0 ## explicit gitea.com/lunny/levelqueue From 20ea01db9d11bedc9170ad9cd64ae8aeb6f7f310 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sat, 19 Dec 2020 16:21:21 +0800 Subject: [PATCH 06/23] Fix vendor --- vendor/modules.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/vendor/modules.txt b/vendor/modules.txt index be0223ab05ea0..426b0dc9473a5 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,4 +1,3 @@ - # cloud.google.com/go v0.67.0 cloud.google.com/go/compute/metadata # code.gitea.io/gitea-vet v0.2.1 From 3b6961fccf468e086785890ff0381ed3d1522bdf Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sat, 14 Nov 2020 14:54:06 +0800 Subject: [PATCH 07/23] Move install routes to chi --- go.mod | 2 + go.sum | 33 +- modules/context/context.go | 52 ++ routers/install.go | 115 +++- routers/routes/macaron.go | 9 - services/mailer/mail.go | 15 +- .../thedevsaddam/renderer/.travis.yml | 22 + .../thedevsaddam/renderer/CONTRIBUTING.md | 12 + .../thedevsaddam/renderer/LICENSE.md | 21 + .../thedevsaddam/renderer/README.md | 369 +++++++++++ .../thedevsaddam/renderer/renderer.go | 586 ++++++++++++++++++ vendor/modules.txt | 4 + 12 files changed, 1176 insertions(+), 64 deletions(-) create mode 100644 vendor/github.com/thedevsaddam/renderer/.travis.yml create mode 100644 vendor/github.com/thedevsaddam/renderer/CONTRIBUTING.md create mode 100644 vendor/github.com/thedevsaddam/renderer/LICENSE.md create mode 100644 vendor/github.com/thedevsaddam/renderer/README.md create mode 100644 vendor/github.com/thedevsaddam/renderer/renderer.go diff --git a/go.mod b/go.mod index 0d1ebc1915459..7b00a0f1d8d00 100644 --- a/go.mod +++ b/go.mod @@ -49,6 +49,7 @@ require ( github.com/google/go-github/v32 v32.1.0 github.com/google/uuid v1.1.2 github.com/gorilla/context v1.1.1 + github.com/gorilla/securecookie v1.1.1 github.com/hashicorp/go-retryablehttp v0.6.8 // indirect github.com/hashicorp/go-version v1.2.1 github.com/huandu/xstrings v1.3.2 @@ -92,6 +93,7 @@ require ( github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/stretchr/testify v1.6.1 github.com/syndtr/goleveldb v1.0.0 + github.com/thedevsaddam/renderer v1.2.0 github.com/tinylib/msgp v1.1.5 // indirect github.com/tstranex/u2f v1.0.0 github.com/ulikunitz/xz v0.5.8 // indirect diff --git a/go.sum b/go.sum index ad51f4c67a892..78b497d283289 100644 --- a/go.sum +++ b/go.sum @@ -1070,6 +1070,8 @@ github.com/syndtr/goleveldb v1.0.0/go.mod h1:ZVVdQEZoIme9iO1Ch2Jdy24qqXrMMOU6lpP github.com/tebeka/snowball v0.4.2/go.mod h1:4IfL14h1lvwZcp1sfXuuc7/7yCsvVffTWxWxCLfFpYg= github.com/tecbot/gorocksdb v0.0.0-20191217155057-f0fad39f321c h1:g+WoO5jjkqGAzHWCjJB1zZfXPIAaDpzXIEJ0eS6B5Ok= github.com/tecbot/gorocksdb v0.0.0-20191217155057-f0fad39f321c/go.mod h1:ahpPrc7HpcfEWDQRZEmnXMzHY03mLDYMCxeDzy46i+8= +github.com/thedevsaddam/renderer v1.2.0 h1:+N0J8t/s2uU2RxX2sZqq5NbaQhjwBjfovMU28ifX2F4= +github.com/thedevsaddam/renderer v1.2.0/go.mod h1:k/TdZXGcpCpHE/KNj//P2COcmYEfL8OV+IXDX0dvG+U= github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4= github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= github.com/tinylib/msgp v1.1.0/go.mod h1:+d+yLhGm8mzTaHzB+wgMYrodPfmZrzkirds8fDWklFE= @@ -1083,7 +1085,6 @@ github.com/tstranex/u2f v1.0.0 h1:HhJkSzDDlVSVIVt7pDJwCHQj67k7A5EeBgPmeD+pVsQ= github.com/tstranex/u2f v1.0.0/go.mod h1:eahSLaqAS0zsIEv80+vXT7WanXs7MQQDg3j3wGBSayo= github.com/ttacon/chalk v0.0.0-20160626202418-22c06c80ed31/go.mod h1:onvgF043R+lC5RZ8IT9rBXDaEDnpnw/Cl+HFiw+v/7Q= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= -github.com/ulikunitz/xz v0.5.6 h1:jGHAfXawEGZQ3blwU5wnWKQJvAraT7Ftq9EXjnXYgt8= github.com/ulikunitz/xz v0.5.6/go.mod h1:2bypXElzHzzJZwzH67Y6wb67pO62Rzfn7BSiF4ABRW8= github.com/ulikunitz/xz v0.5.7/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14= github.com/ulikunitz/xz v0.5.8 h1:ERv8V6GKqVi23rgu5cj9pVfVzJbOqAY2Ntl88O6c2nQ= @@ -1104,7 +1105,6 @@ github.com/urfave/cli v1.22.5 h1:lNq9sAHXK2qfdI8W+GRItjCEkI+2oR4d+MEHy1CKXoU= github.com/urfave/cli v1.22.5/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8= -github.com/willf/bitset v1.1.10 h1:NotGKqX0KwQ72NUzqrjZq5ipPNDQex9lo3WpaS8L2sc= github.com/willf/bitset v1.1.10/go.mod h1:RjeCKbqT1RxIR/KWY6phxZiaY1IyutSBfGjNPySAYV4= github.com/willf/bitset v1.1.11 h1:N7Z7E9UvjW+sGsEl7k/SJrvY2reP1A07MrGuCjIOjRE= github.com/willf/bitset v1.1.11/go.mod h1:83CECat5yLh5zVOf4P1ErAgKA5UDvKtgyUABdr3+MjI= @@ -1187,7 +1187,6 @@ golang.org/x/crypto v0.0.0-20200323165209-0ec3e9974c59/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a h1:vclmkQCjlDX5OydZ9wv8rBCcS0QyQY66Mpf/7BZbInM= golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897 h1:pLI5jrR7OSLijeIDcmRxNmw2api+jEfxLoykJVice/E= golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= @@ -1268,8 +1267,6 @@ golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81R golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200927032502-5d4f70055728/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20200930145003-4acb6c075d10 h1:YfxMZzv3PjGonQYNUaeU2+DhAdqOxerQ30JFB6WgAXo= -golang.org/x/net v0.0.0-20200930145003-4acb6c075d10/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200930145003-4acb6c075d10/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20201006153459-a7d1128ccaa0/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= @@ -1280,7 +1277,6 @@ golang.org/x/oauth2 v0.0.0-20181106182150-f42d05182288/go.mod h1:N/0e6XlmueqKjAG golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d h1:TzXSXBo42m9gQenoE3b9BGiEpg5IG2JkU5FkPIawgtw= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43 h1:ld7aEMNHoBnnDAX15v1T6z31v8HwR2A9FYOuAhWqkwc= golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= @@ -1331,10 +1327,8 @@ golang.org/x/sys v0.0.0-20191010194322-b09406accb47/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191220142924-d4481acd189f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -1351,16 +1345,11 @@ golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201015000850-e3ed0017c211 h1:9UQO31fZ+0aKQOFldThf7BKPMJTiBfWycGh/u3UoO88= golang.org/x/sys v0.0.0-20201015000850-e3ed0017c211/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201211090839-8ad439b19e0f h1:QdHQnPce6K4XQewki9WNbG5KOROuDzqO3NaYjI1cXJ0= golang.org/x/sys v0.0.0-20201211090839-8ad439b19e0f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -1370,7 +1359,6 @@ golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fq golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.4 h1:0YWbFKbhXG/wIiuHDSKpS0Iy7FSA+u45VtBMfQcFTTc= golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= @@ -1419,7 +1407,6 @@ golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapK golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200103221440-774c71fcf114/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= @@ -1430,29 +1417,18 @@ golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapK golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= golang.org/x/tools v0.0.0-20200325010219-a49f79bcc224/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= -golang.org/x/tools v0.0.0-20200325010219-a49f79bcc224/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= -golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200717024301-6ddee64345a6/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200717024301-6ddee64345a6/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= -golang.org/x/tools v0.0.0-20200921210052-fa0125251cc4 h1:v8Jgq9X6Es9K9otVr9jxENEJigepKMZgA9OmrIZDtFA= golang.org/x/tools v0.0.0-20200921210052-fa0125251cc4/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU= golang.org/x/tools v0.0.0-20200928182047-19e03678916f/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU= -golang.org/x/tools v0.0.0-20200929161345-d7fc70abf50f h1:18s2P7JILnVhIF2+ZtGJQ9czV5bvTsb13/UGtNPDbjA= golang.org/x/tools v0.0.0-20200929161345-d7fc70abf50f/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU= golang.org/x/tools v0.0.0-20201022035929-9cf592e881e9 h1:sEvmEcJVKBNUvgCUClbUQeHOAa9U0I2Ce1BooMvVCY4= golang.org/x/tools v0.0.0-20201022035929-9cf592e881e9/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= @@ -1490,7 +1466,6 @@ google.golang.org/appengine v1.6.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7 google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= google.golang.org/appengine v1.6.4/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/appengine v1.6.6 h1:lMO5rYAqUxkmaj76jAkRUvt5JZgFymx/+Q5Mzfivuhc= google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= @@ -1567,7 +1542,6 @@ gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8X gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/cheggaaa/pb.v1 v1.0.25/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o= gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df h1:n7WqCuqOuCbNr617RXOY0AWRXxgwEyPp2z+p0+hgMuE= @@ -1611,10 +1585,7 @@ honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9 mvdan.cc/xurls/v2 v2.2.0 h1:NSZPykBXJFCetGZykLAxaL6SIpvbVy/UFEniIfHAa8A= mvdan.cc/xurls/v2 v2.2.0/go.mod h1:EV1RMtya9D6G5DMYPGD8zTQzaHet6Jh8gFlRgGRJeO8= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= -rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= -rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= -rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0/go.mod h1:hI742Nqp5OhwiqlzhgfbWU4mW4yO10fP+LoT9WOswdU= diff --git a/modules/context/context.go b/modules/context/context.go index 1ee31e0ebbac3..505a19dd53010 100644 --- a/modules/context/context.go +++ b/modules/context/context.go @@ -21,6 +21,7 @@ import ( "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/translation" "code.gitea.io/gitea/modules/util" "gitea.com/macaron/cache" @@ -28,9 +29,60 @@ import ( "gitea.com/macaron/i18n" "gitea.com/macaron/macaron" "gitea.com/macaron/session" + "github.com/gorilla/securecookie" + "github.com/thedevsaddam/renderer" "github.com/unknwon/com" ) +// DefaultContext represents a context for basic routes +type DefaultContext struct { + Resp http.ResponseWriter + Req *http.Request + Data map[string]interface{} + Render *renderer.Render + translation.Locale +} + +// HTML wraps render HTML +func (ctx *DefaultContext) HTML(statusCode int, tmpl string) error { + return ctx.Render.HTML(ctx.Resp, statusCode, tmpl, ctx.Data) +} + +// HasError returns true if error occurs in form validation. +func (ctx *DefaultContext) HasError() bool { + hasErr, ok := ctx.Data["HasError"] + if !ok { + return false + } + return hasErr.(bool) +} + +// HasValue returns true if value of given name exists. +func (ctx *DefaultContext) HasValue(name string) bool { + _, ok := ctx.Data[name] + return ok +} + +// RenderWithErr used for page has form validation but need to prompt error to users. +func (ctx *DefaultContext) RenderWithErr(msg string, tpl string, form interface{}) { + if form != nil { + auth.AssignForm(form, ctx.Data) + } + //ctx.Flash.ErrorMsg = msg + //ctx.Data["Flash"] = ctx.Flash + ctx.HTML(200, tpl) +} + +// NewSecureCookie creates a secure cookie manager +func NewSecureCookie() *securecookie.SecureCookie { + // Hash keys should be at least 32 bytes long + var hashKey = []byte("very-secret") + // Block keys should be 16 bytes (AES-128) or 32 bytes (AES-256) long. + // Shorter keys may weaken the encryption used. + var blockKey = []byte("a-lot-secret") + return securecookie.New(hashKey, blockKey) +} + // Context represents context of a request. type Context struct { *macaron.Context diff --git a/routers/install.go b/routers/install.go index 50e929b6f368f..2896eaad80c8c 100644 --- a/routers/install.go +++ b/routers/install.go @@ -1,3 +1,4 @@ +// Copyright 2020 The Gitea Authors. All rights reserved. // Copyright 2014 The Gogs Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. @@ -15,11 +16,12 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/auth" "code.gitea.io/gitea/modules/base" - "code.gitea.io/gitea/modules/context" + gitea_context "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/generate" "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/translation" "code.gitea.io/gitea/modules/user" "code.gitea.io/gitea/modules/util" @@ -28,26 +30,109 @@ import ( const ( // tplInstall template for installation page - tplInstall base.TplName = "install" - tplPostInstall base.TplName = "post-install" + tplInstall = "install" + tplPostInstall = "post-install" ) +// InstallRoutes represents the install routes +func InstallRoutes() http.Handler { + r := chi.NewRouter() + r.Use(InstallInit) + r.Get("/", WrapInstall(Install)) + r.Post("/", WrapInstall(InstallPost)) + r.NotFound(func(w http.ResponseWriter, req *http.Request) { + http.Redirect(w, req, setting.AppURL, 302) + }) + return r +} + +// InstallContext represents a context for installation routes +type InstallContext = gitea_context.DefaultContext + // InstallInit prepare for rendering installation page -func InstallInit(ctx *context.Context) { - if setting.InstallLock { - ctx.Header().Add("Refresh", "1; url="+setting.AppURL+"user/login") - ctx.HTML(200, tplPostInstall) - return +func InstallInit(next http.Handler) http.Handler { + rnd := renderer.New( + renderer.Options{ + ParseGlobPattern: "templates/*.tmpl", + }, + ) + + return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { + if setting.InstallLock { + resp.Header().Add("Refresh", "1; url="+setting.AppURL+"user/login") + rnd.HTML(resp, 200, tplPostInstall, nil) + return + } + + var locale = Locale(resp, req) + + var ctx = InstallContext{ + Resp: resp, + Req: req, + Locale: locale, + Data: map[string]interface{}{ + "Title": locale.Tr("install.install"), + "PageIsInstall": true, + "DbOptions": setting.SupportedDatabases, + }, + Render: rnd, + } + + req = req.WithContext(context.WithValue(req.Context(), "install_context", &ctx)) + next.ServeHTTP(resp, req) + }) +} + +// Locale handle locale +func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale { + c := gitea_context.NewSecureCookie() + isNeedRedir := false + hasCookie := false + + // 1. Check URL arguments. + lang := req.URL.Query().Get("lang") + + // 2. Get language information from cookies. + if len(lang) == 0 { + lang = c.Cookie("lang") + hasCookie = true + } else { + isNeedRedir = true } - ctx.Data["Title"] = ctx.Tr("install.install") - ctx.Data["PageIsInstall"] = true + // Check again in case someone modify by purpose. + if !i18n.IsExist(lang) { + lang = "" + isNeedRedir = false + hasCookie = false + } + + // 3. Get language information from 'Accept-Language'. + // The first element in the list is chosen to be the default language automatically. + if len(lang) == 0 { + tags, _, _ := language.ParseAcceptLanguage(req.Header.Get("Accept-Language")) + tag, _, _ := translation.Match(tags...) + lang = tag.String() + isNeedRedir = false + } - ctx.Data["DbOptions"] = setting.SupportedDatabases + if !hasCookie { + req.SetCookie("lang", curLang.Lang, 1<<31-1, "/"+strings.TrimPrefix(opt.SubURL, "/"), opt.CookieDomain, opt.Secure, opt.CookieHttpOnly, cookie.SameSite(opt.SameSite)) + } + + return translation.NewLocale(lang) +} + +// WrapInstall converts an install route to a chi route +func WrapInstall(f func(ctx *InstallContext)) http.HandlerFunc { + return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { + ctx := req.Context().Value("install_context").(*InstallContext) + f(ctx) + }) } // Install render installation page -func Install(ctx *context.Context) { +func Install(ctx *InstallContext) { form := auth.InstallForm{} // Database settings @@ -117,11 +202,13 @@ func Install(ctx *context.Context) { form.NoReplyAddress = setting.Service.NoReplyAddress auth.AssignForm(form, ctx.Data) - ctx.HTML(200, tplInstall) + ctx.Render.HTML(ctx.Resp, 200, tplInstall, ctx.Data) } // InstallPost response for submit install items -func InstallPost(ctx *context.Context, form auth.InstallForm) { +func InstallPost(ctx *InstallContext) { + var form auth.InstallForm + var err error ctx.Data["CurDbOption"] = form.DbType diff --git a/routers/routes/macaron.go b/routers/routes/macaron.go index ca3599b7a0a52..1f9776c72dbec 100644 --- a/routers/routes/macaron.go +++ b/routers/routes/macaron.go @@ -135,15 +135,6 @@ func NewMacaron() *macaron.Macaron { return m } -// RegisterMacaronInstallRoute registers the install routes -func RegisterMacaronInstallRoute(m *macaron.Macaron) { - m.Combo("/", routers.InstallInit).Get(routers.Install). - Post(binding.BindIgnErr(auth.InstallForm{}), routers.InstallPost) - m.NotFound(func(ctx *context.Context) { - ctx.Redirect(setting.AppURL, 302) - }) -} - // RegisterMacaronRoutes routes routes to Macaron func RegisterMacaronRoutes(m *macaron.Macaron) { reqSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: true}) diff --git a/services/mailer/mail.go b/services/mailer/mail.go index b4217c046612b..ec3a5184c16f5 100644 --- a/services/mailer/mail.go +++ b/services/mailer/mail.go @@ -22,6 +22,7 @@ import ( "code.gitea.io/gitea/modules/markup/markdown" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/timeutil" + "code.gitea.io/gitea/modules/translation" "gopkg.in/gomail.v2" ) @@ -77,24 +78,18 @@ func SendUserMail(language string, u *models.User, tpl base.TplName, code, subje SendAsync(msg) } -// Locale represents an interface to translation -type Locale interface { - Language() string - Tr(string, ...interface{}) string -} - // SendActivateAccountMail sends an activation mail to the user (new user registration) -func SendActivateAccountMail(locale Locale, u *models.User) { +func SendActivateAccountMail(locale translation.Locale, u *models.User) { SendUserMail(locale.Language(), u, mailAuthActivate, u.GenerateActivateCode(), locale.Tr("mail.activate_account"), "activate account") } // SendResetPasswordMail sends a password reset mail to the user -func SendResetPasswordMail(locale Locale, u *models.User) { +func SendResetPasswordMail(locale translation.Locale, u *models.User) { SendUserMail(locale.Language(), u, mailAuthResetPassword, u.GenerateActivateCode(), locale.Tr("mail.reset_password"), "recover account") } // SendActivateEmailMail sends confirmation email to confirm new email address -func SendActivateEmailMail(locale Locale, u *models.User, email *models.EmailAddress) { +func SendActivateEmailMail(locale translation.Locale, u *models.User, email *models.EmailAddress) { data := map[string]interface{}{ "DisplayName": u.DisplayName(), "ActiveCodeLives": timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, locale.Language()), @@ -116,7 +111,7 @@ func SendActivateEmailMail(locale Locale, u *models.User, email *models.EmailAdd } // SendRegisterNotifyMail triggers a notify e-mail by admin created a account. -func SendRegisterNotifyMail(locale Locale, u *models.User) { +func SendRegisterNotifyMail(locale translation.Locale, u *models.User) { if setting.MailService == nil { log.Warn("SendRegisterNotifyMail is being invoked but mail service hasn't been initialized") return diff --git a/vendor/github.com/thedevsaddam/renderer/.travis.yml b/vendor/github.com/thedevsaddam/renderer/.travis.yml new file mode 100644 index 0000000000000..5d452e7cbf6de --- /dev/null +++ b/vendor/github.com/thedevsaddam/renderer/.travis.yml @@ -0,0 +1,22 @@ +language: go +sudo: false + +matrix: + include: + - go: 1.6 + - go: 1.7 + - go: 1.8 + - go: 1.9 + - go: 1.10.x + - go: 1.11.x + - go: tip + allow_failures: + - go: tip +before_install: + - go get github.com/mattn/goveralls +script: + - $GOPATH/bin/goveralls -service=travis-ci + - go get -t -v ./... + - diff -u <(echo -n) <(gofmt -d .) + - go vet $(go list ./... | grep -v /vendor/) + - go test -v -race ./... diff --git a/vendor/github.com/thedevsaddam/renderer/CONTRIBUTING.md b/vendor/github.com/thedevsaddam/renderer/CONTRIBUTING.md new file mode 100644 index 0000000000000..924384ce0139c --- /dev/null +++ b/vendor/github.com/thedevsaddam/renderer/CONTRIBUTING.md @@ -0,0 +1,12 @@ +# Contributing + +## Must follow the guide for issues + - Use the search tool before opening a new issue. + - Please provide source code and stack trace if you found a bug. + - Please review the existing issues and provide feedback to them + +## Pull Request Process + - Open your pull request against `dev` branch + - It should pass all tests in the available continuous integrations systems such as TravisCI. + - You should add/modify tests to cover your proposed code changes. + - If your pull request contains a new feature, please document it on the README. diff --git a/vendor/github.com/thedevsaddam/renderer/LICENSE.md b/vendor/github.com/thedevsaddam/renderer/LICENSE.md new file mode 100644 index 0000000000000..5786a9421b13c --- /dev/null +++ b/vendor/github.com/thedevsaddam/renderer/LICENSE.md @@ -0,0 +1,21 @@ +# The MIT License (MIT) + +Copyright (c) 2017 Saddam H + +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. diff --git a/vendor/github.com/thedevsaddam/renderer/README.md b/vendor/github.com/thedevsaddam/renderer/README.md new file mode 100644 index 0000000000000..7bbfd5de7b869 --- /dev/null +++ b/vendor/github.com/thedevsaddam/renderer/README.md @@ -0,0 +1,369 @@ +Package renderer +================== +[![Build Status](https://travis-ci.org/thedevsaddam/renderer.svg?branch=master)](https://travis-ci.org/thedevsaddam/renderer) +[![Project status](https://img.shields.io/badge/version-1.2-green.svg)](https://github.com/thedevsaddam/renderer/releases) +[![Go Report Card](https://goreportcard.com/badge/github.com/thedevsaddam/renderer)](https://goreportcard.com/report/github.com/thedevsaddam/renderer) +[![Coverage Status](https://coveralls.io/repos/github/thedevsaddam/renderer/badge.svg?branch=master)](https://coveralls.io/github/thedevsaddam/renderer?branch=master) +[![GoDoc](https://godoc.org/github.com/thedevsaddam/renderer?status.svg)](https://godoc.org/github.com/thedevsaddam/renderer) +[![License](https://img.shields.io/dub/l/vibe-d.svg)](https://github.com/thedevsaddam/renderer/blob/dev/LICENSE.md) + +Simple, lightweight and faster response (JSON, JSONP, XML, YAML, HTML, File) rendering package for Go + +### Installation + +Install the package using +```go +$ go get github.com/thedevsaddam/renderer/... +``` + +### Usage + +To use the package import it in your `*.go` code +```go +import "github.com/thedevsaddam/renderer" +``` +### Example + +```go +package main + +import ( + "io" + "log" + "net/http" + "os" + + "github.com/thedevsaddam/renderer" +) + +func main() { + rnd := renderer.New() + + mux := http.NewServeMux() + + usr := struct { + Name string + Age int + }{"John Doe", 30} + + // serving String as text/plain + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + rnd.String(w, http.StatusOK, "Welcome to renderer") + }) + + // serving success but no content + mux.HandleFunc("/no-content", func(w http.ResponseWriter, r *http.Request) { + rnd.NoContent(w) + }) + + // serving string as html + mux.HandleFunc("/html-string", func(w http.ResponseWriter, r *http.Request) { + rnd.HTMLString(w, http.StatusOK, "

Hello Renderer!

") + }) + + // serving JSON + mux.HandleFunc("/json", func(w http.ResponseWriter, r *http.Request) { + rnd.JSON(w, http.StatusOK, usr) + }) + + // serving JSONP + mux.HandleFunc("/jsonp", func(w http.ResponseWriter, r *http.Request) { + rnd.JSONP(w, http.StatusOK, "callback", usr) + }) + + // serving XML + mux.HandleFunc("/xml", func(w http.ResponseWriter, r *http.Request) { + rnd.XML(w, http.StatusOK, usr) + }) + + // serving YAML + mux.HandleFunc("/yaml", func(w http.ResponseWriter, r *http.Request) { + rnd.YAML(w, http.StatusOK, usr) + }) + + // serving File as arbitary binary data + mux.HandleFunc("/binary", func(w http.ResponseWriter, r *http.Request) { + var reader io.Reader + reader, _ = os.Open("../README.md") + rnd.Binary(w, http.StatusOK, reader, "readme.md", true) + }) + + // serving File as inline + mux.HandleFunc("/file-inline", func(w http.ResponseWriter, r *http.Request) { + rnd.FileView(w, http.StatusOK, "../README.md", "readme.md") + }) + + // serving File as attachment + mux.HandleFunc("/file-download", func(w http.ResponseWriter, r *http.Request) { + rnd.FileDownload(w, http.StatusOK, "../README.md", "readme.md") + }) + + // serving File from reader as inline + mux.HandleFunc("/file-reader", func(w http.ResponseWriter, r *http.Request) { + var reader io.Reader + reader, _ = os.Open("../README.md") + rnd.File(w, http.StatusOK, reader, "readme.md", true) + }) + + // serving custom response using render and chaining methods + mux.HandleFunc("/render", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set(renderer.ContentType, renderer.ContentText) + rnd.Render(w, http.StatusOK, []byte("Send the message as text response")) + }) + + port := ":9000" + log.Println("Listening on port", port) + http.ListenAndServe(port, mux) +} + +``` + +### How to render html template? + +Well, you can parse html template using `HTML`, `View`, `Template` any of these method. These are based on `html/template` package. + +When using `Template` method you can simply pass the base layouts, templates path as a slice of string. + +***Template example*** + +You can parse template on the fly using `Template` method. You can set delimiter, inject FuncMap easily. + +template/layout.tmpl +```html + + + {{ template "title" . }} + + + {{ template "content" . }} + + {{ block "sidebar" .}}{{end}} + +``` +template/index.tmpl +```html +{{ define "title" }}Home{{ end }} + +{{ define "content" }} +

Hello, {{ .Name | toUpper }}

+

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

+{{ end }} +``` +template/partial.tmpl +```html +{{define "sidebar"}} + simple sidebar code +{{end}} + +``` + +template.go +```go +package main + +import ( + "html/template" + "log" + "net/http" + "strings" + + "github.com/thedevsaddam/renderer" +) + +var rnd *renderer.Render + +func init() { + rnd = renderer.New() +} + +func toUpper(s string) string { + return strings.ToUpper(s) +} + +func handler(w http.ResponseWriter, r *http.Request) { + usr := struct { + Name string + Age int + }{"john doe", 30} + + tpls := []string{"template/layout.tmpl", "template/index.tmpl", "template/partial.tmpl"} + rnd.FuncMap(template.FuncMap{ + "toUpper": toUpper, + }) + err := rnd.Template(w, http.StatusOK, tpls, usr) + if err != nil { + log.Fatal(err) //respond with error page or message + } +} + +func main() { + http.HandleFunc("/", handler) + log.Println("Listening port: 9000") + http.ListenAndServe(":9000", nil) +} +``` + +***HTML example*** + +When using `HTML` you can parse a template directory using `pattern` and call the template by their name. See the example code below: + +html/index.html +```html +{{define "indexPage"}} + + {{template "header"}} + +

Index

+

Lorem ipsum dolor sit amet, consectetur adipisicing elit

+ + {{template "footer"}} + +{{end}} +``` + +html/header.html +```html +{{define "header"}} + + Header +

Header section

+ +{{end}} +``` + +html/footer.html +```html +{{define "footer"}} +
Copyright © 2020
+{{end}} +``` + +html.go +```go +package main + +import ( + "log" + "net/http" + + "github.com/thedevsaddam/renderer" +) + +var rnd *renderer.Render + +func init() { + rnd = renderer.New( + renderer.Options{ + ParseGlobPattern: "html/*.html", + }, + ) +} + +func handler(w http.ResponseWriter, r *http.Request) { + err := rnd.HTML(w, http.StatusOK, "indexPage", nil) + if err != nil { + log.Fatal(err) + } +} + +func main() { + http.HandleFunc("/", handler) + log.Println("Listening port: 9000") + http.ListenAndServe(":9000", nil) +} +``` + +***View example*** + +When using `View` for parsing template you can pass multiple layout and templates. Here template name will be the file name. See the example to get the idea. + +view/base.lout +```html + + + {{block "title" .}} {{end}} + + + {{ template "content" . }} + + +``` + +view/home.tpl +```html +{{define "title"}}Home{{end}} +{{define "content"}} +

Home page

+ +

+ Lorem ipsum dolor sit amet

+{{end}} +``` +view/about.tpl +```html +{{define "title"}}About Me{{end}} +{{define "content"}} +

This is About me page.

+
    + Lorem ipsum dolor sit amet, consectetur adipisicing elit, +
+

Home

+{{end}} +``` + +view.go +```go +package main + +import ( + "log" + "net/http" + + "github.com/thedevsaddam/renderer" +) + +var rnd *renderer.Render + +func init() { + rnd = renderer.New(renderer.Options{ + TemplateDir: "view", + }) +} + +func home(w http.ResponseWriter, r *http.Request) { + err := rnd.View(w, http.StatusOK, "home", nil) + if err != nil { + log.Fatal(err) + } +} + +func about(w http.ResponseWriter, r *http.Request) { + err := rnd.View(w, http.StatusOK, "about", nil) + if err != nil { + log.Fatal(err) + } +} + +func main() { + http.HandleFunc("/", home) + http.HandleFunc("/about", about) + log.Println("Listening port: 9000\n / is root \n /about is about page") + http.ListenAndServe(":9000", nil) +} +``` + +***Note:*** This is a wrapper on top of go built-in packages to provide syntactic sugar. + +### Contribution +Your suggestions will be more than appreciated. +[Read the contribution guide here](CONTRIBUTING.md) + +### See all [contributors](https://github.com/thedevsaddam/renderer/graphs/contributors) + +### Read [API doc](https://godoc.org/github.com/thedevsaddam/renderer) to know about ***Available options and Methods*** + +### **License** +The **renderer** is an open-source software licensed under the [MIT License](LICENSE.md). diff --git a/vendor/github.com/thedevsaddam/renderer/renderer.go b/vendor/github.com/thedevsaddam/renderer/renderer.go new file mode 100644 index 0000000000000..900d189897f4a --- /dev/null +++ b/vendor/github.com/thedevsaddam/renderer/renderer.go @@ -0,0 +1,586 @@ +// Copyright @2017 Saddam Hossain. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +// Package renderer implements frequently usages response render methods like JSON, JSONP, XML, YAML, HTML, FILE etc +// This package is useful when building REST api and to provide response to consumer + +// Package renderer documentaton contains the API for this package please follow the link below +package renderer + +import ( + "bytes" + "encoding/json" + "encoding/xml" + "errors" + "fmt" + "html/template" + "io" + "io/ioutil" + "log" + "net/http" + "os" + "path/filepath" + "strings" + + yaml "gopkg.in/yaml.v2" +) + +const ( + // ContentType represents content type + ContentType string = "Content-Type" + // ContentJSON represents content type application/json + ContentJSON string = "application/json" + // ContentJSONP represents content type application/javascript + ContentJSONP string = "application/javascript" + // ContentXML represents content type application/xml + ContentXML string = "application/xml" + // ContentYAML represents content type application/x-yaml + ContentYAML string = "application/x-yaml" + // ContentHTML represents content type text/html + ContentHTML string = "text/html" + // ContentText represents content type text/plain + ContentText string = "text/plain" + // ContentBinary represents content type application/octet-stream + ContentBinary string = "application/octet-stream" + + // ContentDisposition describes contentDisposition + ContentDisposition string = "Content-Disposition" + // contentDispositionInline describes content disposition type + contentDispositionInline string = "inline" + // contentDispositionAttachment describes content disposition type + contentDispositionAttachment string = "attachment" + + defaultCharSet string = "utf-8" + defaultJSONPrefix string = "" + defaultXMLPrefix string = `\n` + defaultTemplateExt string = "tpl" + defaultLayoutExt string = "lout" + defaultTemplateLeftDelim string = "{{" + defaultTemplateRightDelim string = "}}" +) + +type ( + // M describes handy type that represents data to send as response + M map[string]interface{} + + // Options describes an option type + Options struct { + // Charset represents the Response charset; default: utf-8 + Charset string + // ContentJSON represents the Content-Type for JSON + ContentJSON string + // ContentJSONP represents the Content-Type for JSONP + ContentJSONP string + // ContentXML represents the Content-Type for XML + ContentXML string + // ContentYAML represents the Content-Type for YAML + ContentYAML string + // ContentHTML represents the Content-Type for HTML + ContentHTML string + // ContentText represents the Content-Type for Text + ContentText string + // ContentBinary represents the Content-Type for octet-stream + ContentBinary string + + // UnEscapeHTML set UnEscapeHTML for JSON; default false + UnEscapeHTML bool + // DisableCharset set DisableCharset in Response Content-Type + DisableCharset bool + // Debug set the debug mode. if debug is true then every time "VIEW" call parse the templates + Debug bool + // JSONIndent set JSON Indent in response; default false + JSONIndent bool + // XMLIndent set XML Indent in response; default false + XMLIndent bool + + // JSONPrefix set Prefix in JSON response + JSONPrefix string + // XMLPrefix set Prefix in XML response + XMLPrefix string + + // TemplateDir set the Template directory + TemplateDir string + // TemplateExtension set the Template extension + TemplateExtension string + // LeftDelim set template left delimiter default is {{ + LeftDelim string + // RightDelim set template right delimiter default is }} + RightDelim string + // LayoutExtension set the Layout extension + LayoutExtension string + // FuncMap contain function map for template + FuncMap []template.FuncMap + // ParseGlobPattern contain parse glob pattern + ParseGlobPattern string + } + + // Render describes a renderer type + Render struct { + opts Options + templates map[string]*template.Template + globTemplates *template.Template + headers map[string]string + } +) + +// New return a new instance of a pointer to Render +func New(opts ...Options) *Render { + var opt Options + if opts != nil { + opt = opts[0] + } + + r := &Render{ + opts: opt, + templates: make(map[string]*template.Template), + } + + // build options for the Render instance + r.buildOptions() + + // if TemplateDir is not empty then call the parseTemplates + if r.opts.TemplateDir != "" { + r.parseTemplates() + } + + // ParseGlobPattern is not empty then parse template with pattern + if r.opts.ParseGlobPattern != "" { + r.parseGlob() + } + + return r +} + +// buildOptions builds the options and set deault values for options +func (r *Render) buildOptions() { + if r.opts.Charset == "" { + r.opts.Charset = defaultCharSet + } + + if r.opts.JSONPrefix == "" { + r.opts.JSONPrefix = defaultJSONPrefix + } + + if r.opts.XMLPrefix == "" { + r.opts.XMLPrefix = defaultXMLPrefix + } + + if r.opts.TemplateExtension == "" { + r.opts.TemplateExtension = "." + defaultTemplateExt + } else { + r.opts.TemplateExtension = "." + r.opts.TemplateExtension + } + + if r.opts.LayoutExtension == "" { + r.opts.LayoutExtension = "." + defaultLayoutExt + } else { + r.opts.LayoutExtension = "." + r.opts.LayoutExtension + } + + if r.opts.LeftDelim == "" { + r.opts.LeftDelim = defaultTemplateLeftDelim + } + + if r.opts.RightDelim == "" { + r.opts.RightDelim = defaultTemplateRightDelim + } + + r.opts.ContentJSON = ContentJSON + r.opts.ContentJSONP = ContentJSONP + r.opts.ContentXML = ContentXML + r.opts.ContentYAML = ContentYAML + r.opts.ContentHTML = ContentHTML + r.opts.ContentText = ContentText + r.opts.ContentBinary = ContentBinary + + if !r.opts.DisableCharset { + r.enableCharset() + } +} + +func (r *Render) enableCharset() { + r.opts.ContentJSON = fmt.Sprintf("%s; charset=%s", r.opts.ContentJSON, r.opts.Charset) + r.opts.ContentJSONP = fmt.Sprintf("%s; charset=%s", r.opts.ContentJSONP, r.opts.Charset) + r.opts.ContentXML = fmt.Sprintf("%s; charset=%s", r.opts.ContentXML, r.opts.Charset) + r.opts.ContentYAML = fmt.Sprintf("%s; charset=%s", r.opts.ContentYAML, r.opts.Charset) + r.opts.ContentHTML = fmt.Sprintf("%s; charset=%s", r.opts.ContentHTML, r.opts.Charset) + r.opts.ContentText = fmt.Sprintf("%s; charset=%s", r.opts.ContentText, r.opts.Charset) + r.opts.ContentBinary = fmt.Sprintf("%s; charset=%s", r.opts.ContentBinary, r.opts.Charset) +} + +// DisableCharset change the DisableCharset for JSON on the fly +func (r *Render) DisableCharset(b bool) *Render { + r.opts.DisableCharset = b + if !b { + r.buildOptions() + } + return r +} + +// JSONIndent change the JSONIndent for JSON on the fly +func (r *Render) JSONIndent(b bool) *Render { + r.opts.JSONIndent = b + return r +} + +// XMLIndent change the XMLIndent for XML on the fly +func (r *Render) XMLIndent(b bool) *Render { + r.opts.XMLIndent = b + return r +} + +// Charset change the Charset for response on the fly +func (r *Render) Charset(c string) *Render { + r.opts.Charset = c + return r +} + +// EscapeHTML change the EscapeHTML for JSON on the fly +func (r *Render) EscapeHTML(b bool) *Render { + r.opts.UnEscapeHTML = b + return r +} + +// Delims set template delimiter on the fly +func (r *Render) Delims(left, right string) *Render { + r.opts.LeftDelim = left + r.opts.RightDelim = right + return r +} + +// FuncMap set template FuncMap on the fly +func (r *Render) FuncMap(fmap template.FuncMap) *Render { + r.opts.FuncMap = append(r.opts.FuncMap, fmap) + return r +} + +// NoContent serve success but no content response +func (r *Render) NoContent(w http.ResponseWriter) error { + w.WriteHeader(http.StatusNoContent) + return nil +} + +// Render serve raw response where you have to build the headers, body +func (r *Render) Render(w http.ResponseWriter, status int, v interface{}) error { + w.WriteHeader(status) + _, err := w.Write(v.([]byte)) + return err +} + +// String serve string content as text/plain response +func (r *Render) String(w http.ResponseWriter, status int, v interface{}) error { + w.Header().Set(ContentType, r.opts.ContentText) + w.WriteHeader(status) + _, err := w.Write([]byte(v.(string))) + return err +} + +// json converts the data as bytes using json encoder +func (r *Render) json(v interface{}) ([]byte, error) { + var bs []byte + var err error + if r.opts.JSONIndent { + bs, err = json.MarshalIndent(v, "", " ") + } else { + bs, err = json.Marshal(v) + } + if err != nil { + return bs, err + } + if r.opts.UnEscapeHTML { + bs = bytes.Replace(bs, []byte("\\u003c"), []byte("<"), -1) + bs = bytes.Replace(bs, []byte("\\u003e"), []byte(">"), -1) + bs = bytes.Replace(bs, []byte("\\u0026"), []byte("&"), -1) + } + return bs, nil +} + +// JSON serve data as JSON as response +func (r *Render) JSON(w http.ResponseWriter, status int, v interface{}) error { + w.Header().Set(ContentType, r.opts.ContentJSON) + w.WriteHeader(status) + + bs, err := r.json(v) + if err != nil { + return err + } + if r.opts.JSONPrefix != "" { + w.Write([]byte(r.opts.JSONPrefix)) + } + _, err = w.Write(bs) + return err +} + +// JSONP serve data as JSONP response +func (r *Render) JSONP(w http.ResponseWriter, status int, callback string, v interface{}) error { + w.Header().Set(ContentType, r.opts.ContentJSONP) + w.WriteHeader(status) + + bs, err := r.json(v) + if err != nil { + return err + } + + if callback == "" { + return errors.New("renderer: callback can not bet empty") + } + + w.Write([]byte(callback + "(")) + _, err = w.Write(bs) + w.Write([]byte(");")) + + return err +} + +// XML serve data as XML response +func (r *Render) XML(w http.ResponseWriter, status int, v interface{}) error { + w.Header().Set(ContentType, r.opts.ContentXML) + w.WriteHeader(status) + var bs []byte + var err error + + if r.opts.XMLIndent { + bs, err = xml.MarshalIndent(v, "", " ") + } else { + bs, err = xml.Marshal(v) + } + if err != nil { + return err + } + if r.opts.XMLPrefix != "" { + w.Write([]byte(r.opts.XMLPrefix)) + } + _, err = w.Write(bs) + return err +} + +// YAML serve data as YAML response +func (r *Render) YAML(w http.ResponseWriter, status int, v interface{}) error { + w.Header().Set(ContentType, r.opts.ContentYAML) + w.WriteHeader(status) + + bs, err := yaml.Marshal(v) + if err != nil { + return err + } + _, err = w.Write(bs) + return err +} + +// HTMLString render string as html. Note: You must provide trusted html when using this method +func (r *Render) HTMLString(w http.ResponseWriter, status int, html string) error { + w.Header().Set(ContentType, r.opts.ContentHTML) + w.WriteHeader(status) + out := template.HTML(html) + _, err := w.Write([]byte(out)) + return err +} + +// HTML render html from template.Glob patterns and execute template by name. See README.md for detail example. +func (r *Render) HTML(w http.ResponseWriter, status int, name string, v interface{}) error { + w.Header().Set(ContentType, r.opts.ContentHTML) + w.WriteHeader(status) + + if name == "" { + return errors.New("renderer: template name not exist") + } + + if r.opts.Debug { + r.parseGlob() + } + + buf := new(bytes.Buffer) + defer buf.Reset() + + if err := r.globTemplates.ExecuteTemplate(buf, name, v); err != nil { + return err + } + _, err := w.Write(buf.Bytes()) + return err +} + +// Template build html from template and serve html content as response. See README.md for detail example. +func (r *Render) Template(w http.ResponseWriter, status int, tpls []string, v interface{}) error { + w.Header().Set(ContentType, r.opts.ContentHTML) + w.WriteHeader(status) + + tmain := template.New(filepath.Base(tpls[0])) + tmain.Delims(r.opts.LeftDelim, r.opts.RightDelim) + for _, fm := range r.opts.FuncMap { + tmain.Funcs(fm) + } + t := template.Must(tmain.ParseFiles(tpls...)) + + buf := new(bytes.Buffer) + defer buf.Reset() + + if err := t.Execute(buf, v); err != nil { + return err + } + _, err := w.Write(buf.Bytes()) + return err +} + +// View build html from template directory and serve html content as response. See README.md for detail example. +func (r *Render) View(w http.ResponseWriter, status int, name string, v interface{}) error { + w.Header().Set(ContentType, r.opts.ContentHTML) + w.WriteHeader(status) + + buf := new(bytes.Buffer) + defer buf.Reset() + + if r.opts.Debug { + r.parseTemplates() + } + + name += r.opts.TemplateExtension + tmpl, ok := r.templates[name] + if !ok { + return fmt.Errorf("renderer: template %s does not exist", name) + } + + if err := tmpl.Execute(buf, v); err != nil { + return err + } + + _, err := w.Write(buf.Bytes()) + return err +} + +// Binary serve file as application/octet-stream response; you may add ContentDisposition by your own. +func (r *Render) Binary(w http.ResponseWriter, status int, reader io.Reader, filename string, inline bool) error { + if inline { + w.Header().Set(ContentDisposition, fmt.Sprintf("%s; filename=%s", contentDispositionInline, filename)) + } else { + w.Header().Set(ContentDisposition, fmt.Sprintf("%s; filename=%s", contentDispositionAttachment, filename)) + } + w.Header().Set(ContentType, r.opts.ContentBinary) + w.WriteHeader(status) + bs, err := ioutil.ReadAll(reader) + if err != nil { + return err + } + + _, err = w.Write(bs) + return err +} + +// File serve file as response from io.Reader +func (r *Render) File(w http.ResponseWriter, status int, reader io.Reader, filename string, inline bool) error { + bs, err := ioutil.ReadAll(reader) + if err != nil { + return err + } + + // set headers + mime := http.DetectContentType(bs) + if inline { + w.Header().Set(ContentDisposition, fmt.Sprintf("%s; filename=%s", contentDispositionInline, filename)) + } else { + w.Header().Set(ContentDisposition, fmt.Sprintf("%s; filename=%s", contentDispositionAttachment, filename)) + } + w.Header().Set(ContentType, mime) + w.WriteHeader(status) + + _, err = w.Write(bs) + return err +} + +// file serve file as response +func (r *Render) file(w http.ResponseWriter, status int, fpath, name, contentDisposition string) error { + var bs []byte + var err error + bs, err = ioutil.ReadFile(fpath) + if err != nil { + return err + } + buf := bytes.NewBuffer(bs) + + // filename, ext, mimes + var fn, mime, ext string + fn, err = filepath.Abs(fpath) + ext = filepath.Ext(fpath) + if name != "" { + if !strings.HasSuffix(name, ext) { + fn = name + ext + } + } + + mime = http.DetectContentType(bs) + + // set headers + w.Header().Set(ContentType, mime) + w.Header().Set(ContentDisposition, fmt.Sprintf("%s; filename=%s", contentDisposition, fn)) + w.WriteHeader(status) + + if _, err = buf.WriteTo(w); err != nil { + return err + } + + _, err = w.Write(buf.Bytes()) + return err +} + +// FileView serve file as response with content-disposition value inline +func (r *Render) FileView(w http.ResponseWriter, status int, fpath, name string) error { + return r.file(w, status, fpath, name, contentDispositionInline) +} + +// FileDownload serve file as response with content-disposition value attachment +func (r *Render) FileDownload(w http.ResponseWriter, status int, fpath, name string) error { + return r.file(w, status, fpath, name, contentDispositionAttachment) +} + +// parseTemplates parse all the template in the directory +func (r *Render) parseTemplates() { + layouts, err := filepath.Glob(filepath.Join(r.opts.TemplateDir, "*"+r.opts.LayoutExtension)) + if err != nil { + panic(fmt.Errorf("renderer: %s", err.Error())) + } + + tpls, err := filepath.Glob(filepath.Join(r.opts.TemplateDir, "*"+r.opts.TemplateExtension)) + if err != nil { + panic(fmt.Errorf("renderer: %s", err.Error())) + } + + for _, tpl := range tpls { + files := append(layouts, tpl) + fn := filepath.Base(tpl) + // TODO: add FuncMap and Delims + // tmpl := template.New(fn) + // tmpl.Delims(r.opts.LeftDelim, r.opts.RightDelim) + // for _, fm := range r.opts.FuncMap { + // tmpl.Funcs(fm) + // } + r.templates[fn] = template.Must(template.ParseFiles(files...)) + } +} + +// parseGlob parse templates using ParseGlob +func (r *Render) parseGlob() { + tmpl := template.New("") + tmpl.Delims(r.opts.LeftDelim, r.opts.RightDelim) + for _, fm := range r.opts.FuncMap { + tmpl.Funcs(fm) + } + if !strings.Contains(r.opts.ParseGlobPattern, "*.") { + log.Fatal("renderer: invalid glob pattern!") + } + pf := strings.Split(r.opts.ParseGlobPattern, "*") + fPath := pf[0] + fExt := pf[1] + err := filepath.Walk(fPath, func(path string, info os.FileInfo, err error) error { + if strings.Contains(path, fExt) { + _, err = tmpl.ParseFiles(path) + if err != nil { + log.Println(err) + } + } + return err + }) + if err != nil { + log.Fatal(err) + } + r.globTemplates = tmpl +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 426b0dc9473a5..cf42eb29aa0ee 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -440,6 +440,7 @@ github.com/gorilla/handlers # github.com/gorilla/mux v1.7.3 github.com/gorilla/mux # github.com/gorilla/securecookie v1.1.1 +## explicit github.com/gorilla/securecookie # github.com/gorilla/sessions v1.2.0 github.com/gorilla/sessions @@ -732,6 +733,9 @@ github.com/syndtr/goleveldb/leveldb/opt github.com/syndtr/goleveldb/leveldb/storage github.com/syndtr/goleveldb/leveldb/table github.com/syndtr/goleveldb/leveldb/util +# github.com/thedevsaddam/renderer v1.2.0 +## explicit +github.com/thedevsaddam/renderer # github.com/tinylib/msgp v1.1.5 ## explicit github.com/tinylib/msgp/msgp From d5e6ed7ae137acac4db5c6ac36cd5af12d575f77 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Mon, 16 Nov 2020 08:09:39 +0800 Subject: [PATCH 08/23] Add session --- cmd/web.go | 2 +- go.mod | 2 +- go.sum | 2 + modules/context/context.go | 49 +- routers/install.go | 50 +- routers/routes/chi.go | 26 +- .../github.com/alexedwards/scs/v2/.travis.yml | 9 + vendor/github.com/alexedwards/scs/v2/LICENSE | 21 + .../github.com/alexedwards/scs/v2/README.md | 213 ++++++++ vendor/github.com/alexedwards/scs/v2/codec.go | 51 ++ vendor/github.com/alexedwards/scs/v2/data.go | 498 ++++++++++++++++++ vendor/github.com/alexedwards/scs/v2/go.mod | 3 + vendor/github.com/alexedwards/scs/v2/go.sum | 0 .../alexedwards/scs/v2/memstore/README.md | 74 +++ .../alexedwards/scs/v2/memstore/memstore.go | 124 +++++ .../github.com/alexedwards/scs/v2/session.go | 236 +++++++++ vendor/github.com/alexedwards/scs/v2/store.go | 25 + vendor/modules.txt | 5 +- 18 files changed, 1336 insertions(+), 54 deletions(-) create mode 100644 vendor/github.com/alexedwards/scs/v2/.travis.yml create mode 100644 vendor/github.com/alexedwards/scs/v2/LICENSE create mode 100644 vendor/github.com/alexedwards/scs/v2/README.md create mode 100644 vendor/github.com/alexedwards/scs/v2/codec.go create mode 100644 vendor/github.com/alexedwards/scs/v2/data.go create mode 100644 vendor/github.com/alexedwards/scs/v2/go.mod create mode 100644 vendor/github.com/alexedwards/scs/v2/go.sum create mode 100644 vendor/github.com/alexedwards/scs/v2/memstore/README.md create mode 100644 vendor/github.com/alexedwards/scs/v2/memstore/memstore.go create mode 100644 vendor/github.com/alexedwards/scs/v2/session.go create mode 100644 vendor/github.com/alexedwards/scs/v2/store.go diff --git a/cmd/web.go b/cmd/web.go index 063e41c94647b..f6c3c825c60c0 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -134,7 +134,7 @@ func runWeb(ctx *cli.Context) error { } } c := routes.NewChi() - routes.RegisterInstallRoute(c) + c.Mount("/", routers.InstallRoutes()) err := listen(c, false) select { case <-graceful.GetManager().IsShutdown(): diff --git a/go.mod b/go.mod index 7b00a0f1d8d00..4e76164b78d7a 100644 --- a/go.mod +++ b/go.mod @@ -21,6 +21,7 @@ require ( github.com/PuerkitoBio/goquery v1.5.1 github.com/RoaringBitmap/roaring v0.5.5 // indirect github.com/alecthomas/chroma v0.8.2 + github.com/alexedwards/scs/v2 v2.4.0 github.com/andybalholm/brotli v1.0.1 // indirect github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be // indirect github.com/blevesearch/bleve v1.0.14 @@ -49,7 +50,6 @@ require ( github.com/google/go-github/v32 v32.1.0 github.com/google/uuid v1.1.2 github.com/gorilla/context v1.1.1 - github.com/gorilla/securecookie v1.1.1 github.com/hashicorp/go-retryablehttp v0.6.8 // indirect github.com/hashicorp/go-version v1.2.1 github.com/huandu/xstrings v1.3.2 diff --git a/go.sum b/go.sum index 78b497d283289..6fc2967656dfd 100644 --- a/go.sum +++ b/go.sum @@ -128,6 +128,8 @@ github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuy github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= +github.com/alexedwards/scs/v2 v2.4.0 h1:XfnMamKnvp1muJVNr1WzikQTclopsBXWZtzz0NBjOK0= +github.com/alexedwards/scs/v2 v2.4.0/go.mod h1:ToaROZxyKukJKT/xLcVQAChi5k6+Pn1Gvmdl7h3RRj8= github.com/andybalholm/brotli v1.0.0/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y= github.com/andybalholm/brotli v1.0.1 h1:KqhlKozYbRtJvsPrrEeXcO+N2l6NYT5A2QAFmSULpEc= github.com/andybalholm/brotli v1.0.1/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y= diff --git a/modules/context/context.go b/modules/context/context.go index 505a19dd53010..40acaea2c3fb1 100644 --- a/modules/context/context.go +++ b/modules/context/context.go @@ -29,17 +29,18 @@ import ( "gitea.com/macaron/i18n" "gitea.com/macaron/macaron" "gitea.com/macaron/session" - "github.com/gorilla/securecookie" + "github.com/alexedwards/scs/v2" "github.com/thedevsaddam/renderer" "github.com/unknwon/com" ) // DefaultContext represents a context for basic routes type DefaultContext struct { - Resp http.ResponseWriter - Req *http.Request - Data map[string]interface{} - Render *renderer.Render + Resp http.ResponseWriter + Req *http.Request + Data map[string]interface{} + Render *renderer.Render + Sessions *scs.SessionManager translation.Locale } @@ -73,14 +74,36 @@ func (ctx *DefaultContext) RenderWithErr(msg string, tpl string, form interface{ ctx.HTML(200, tpl) } -// NewSecureCookie creates a secure cookie manager -func NewSecureCookie() *securecookie.SecureCookie { - // Hash keys should be at least 32 bytes long - var hashKey = []byte("very-secret") - // Block keys should be 16 bytes (AES-128) or 32 bytes (AES-256) long. - // Shorter keys may weaken the encryption used. - var blockKey = []byte("a-lot-secret") - return securecookie.New(hashKey, blockKey) +// SetSession sets session key value +func (ctx *DefaultContext) SetSession(key string, val interface{}) error { + ctx.Sessions.Put(ctx.Req.Context(), key, val) + return nil +} + +// GetSession gets session via key +func (ctx *DefaultContext) GetSession(key string) (interface{}, error) { + v := ctx.Sessions.Get(ctx.Req.Context(), key) + return v, nil +} + +// DestroySession deletes all the data of the session +func (ctx *DefaultContext) DestroySession() error { + ctx.Sessions.Destroy(ctx.Req.Context()) + return nil +} + +// NewCookie creates a cookie +func NewCookie(name, value string, maxAge int) *http.Cookie { + return &http.Cookie{ + Name: name, + Value: value, + HttpOnly: true, + Path: setting.SessionConfig.CookiePath, + Domain: setting.SessionConfig.Domain, + MaxAge: maxAge, + Secure: setting.SessionConfig.Secure, + //SameSite: , + } } // Context represents context of a request. diff --git a/routers/install.go b/routers/install.go index 2896eaad80c8c..ca89b5b701954 100644 --- a/routers/install.go +++ b/routers/install.go @@ -6,16 +6,17 @@ package routers import ( + "context" "fmt" "net/http" "os" "os/exec" "path/filepath" "strings" + "time" "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/auth" - "code.gitea.io/gitea/modules/base" gitea_context "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/generate" "code.gitea.io/gitea/modules/graceful" @@ -25,6 +26,11 @@ import ( "code.gitea.io/gitea/modules/user" "code.gitea.io/gitea/modules/util" + "github.com/alexedwards/scs/v2" + "github.com/go-chi/chi" + "github.com/thedevsaddam/renderer" + "github.com/unknwon/i18n" + "golang.org/x/text/language" "gopkg.in/ini.v1" ) @@ -37,7 +43,21 @@ const ( // InstallRoutes represents the install routes func InstallRoutes() http.Handler { r := chi.NewRouter() - r.Use(InstallInit) + sessionManager := scs.New() + sessionManager.Lifetime = time.Duration(setting.SessionConfig.Maxlifetime) + sessionManager.Cookie = scs.SessionCookie{ + Name: setting.SessionConfig.CookieName, + Domain: setting.SessionConfig.Domain, + HttpOnly: true, + Path: setting.SessionConfig.CookiePath, + Persist: true, + Secure: setting.SessionConfig.Secure, + //SameSite: setting.SessionConfig., + } + r.Use(sessionManager.LoadAndSave) + r.Use(func(next http.Handler) http.Handler { + return InstallInit(next, sessionManager) + }) r.Get("/", WrapInstall(Install)) r.Post("/", WrapInstall(InstallPost)) r.NotFound(func(w http.ResponseWriter, req *http.Request) { @@ -50,7 +70,7 @@ func InstallRoutes() http.Handler { type InstallContext = gitea_context.DefaultContext // InstallInit prepare for rendering installation page -func InstallInit(next http.Handler) http.Handler { +func InstallInit(next http.Handler, sessionManager *scs.SessionManager) http.Handler { rnd := renderer.New( renderer.Options{ ParseGlobPattern: "templates/*.tmpl", @@ -75,7 +95,8 @@ func InstallInit(next http.Handler) http.Handler { "PageIsInstall": true, "DbOptions": setting.SupportedDatabases, }, - Render: rnd, + Render: rnd, + Sessions: sessionManager, } req = req.WithContext(context.WithValue(req.Context(), "install_context", &ctx)) @@ -85,7 +106,6 @@ func InstallInit(next http.Handler) http.Handler { // Locale handle locale func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale { - c := gitea_context.NewSecureCookie() isNeedRedir := false hasCookie := false @@ -94,7 +114,8 @@ func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale { // 2. Get language information from cookies. if len(lang) == 0 { - lang = c.Cookie("lang") + ck, _ := req.Cookie("lang") + lang = ck.Value hasCookie = true } else { isNeedRedir = true @@ -117,7 +138,8 @@ func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale { } if !hasCookie { - req.SetCookie("lang", curLang.Lang, 1<<31-1, "/"+strings.TrimPrefix(opt.SubURL, "/"), opt.CookieDomain, opt.Secure, opt.CookieHttpOnly, cookie.SameSite(opt.SameSite)) + req.AddCookie(gitea_context.NewCookie("lang", lang, 1<<31-1)) + //req.SetCookie("lang", curLang.Lang, 1<<31-1, "/"+strings.TrimPrefix(opt.SubURL, "/"), opt.CookieDomain, opt.Secure, opt.CookieHttpOnly, cookie.SameSite(opt.SameSite)) } return translation.NewLocale(lang) @@ -478,21 +500,21 @@ func InstallPost(ctx *InstallContext) { } days := 86400 * setting.LogInRememberDays - ctx.SetCookie(setting.CookieUserName, u.Name, days, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true) - ctx.SetSuperSecureCookie(base.EncodeMD5(u.Rands+u.Passwd), - setting.CookieRememberName, u.Name, days, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true) + ctx.Req.AddCookie(gitea_context.NewCookie(setting.CookieUserName, u.Name, days)) + //ctx.SetSuperSecureCookie(base.EncodeMD5(u.Rands+u.Passwd), + // setting.CookieRememberName, u.Name, days, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true) // Auto-login for admin - if err = ctx.Session.Set("uid", u.ID); err != nil { + if err = ctx.SetSession("uid", u.ID); err != nil { ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form) return } - if err = ctx.Session.Set("uname", u.Name); err != nil { + if err = ctx.SetSession("uname", u.Name); err != nil { ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form) return } - if err = ctx.Session.Release(); err != nil { + if err = ctx.DestroySession(); err != nil { ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form) return } @@ -502,7 +524,7 @@ func InstallPost(ctx *InstallContext) { ctx.Flash.Success(ctx.Tr("install.install_success")) - ctx.Header().Add("Refresh", "1; url="+setting.AppURL+"user/login") + ctx.Resp.Header().Add("Refresh", "1; url="+setting.AppURL+"user/login") ctx.HTML(200, tplPostInstall) // Now get the http.Server from this request and shut it down diff --git a/routers/routes/chi.go b/routers/routes/chi.go index c0ac88957ee2b..c296ca39b54c0 100644 --- a/routers/routes/chi.go +++ b/routers/routes/chi.go @@ -219,30 +219,8 @@ func NewChi() chi.Router { return c } -// RegisterInstallRoute registers the install routes -func RegisterInstallRoute(c chi.Router) { - m := NewMacaron() - RegisterMacaronInstallRoute(m) - - // We need at least one handler in chi so that it does not drop - // our middleware: https://github.com/go-gitea/gitea/issues/13725#issuecomment-735244395 - c.Get("/", func(w http.ResponseWriter, req *http.Request) { - m.ServeHTTP(w, req) - }) - - c.NotFound(func(w http.ResponseWriter, req *http.Request) { - m.ServeHTTP(w, req) - }) - - c.MethodNotAllowed(func(w http.ResponseWriter, req *http.Request) { - m.ServeHTTP(w, req) - }) -} - -// NormalRoutes represents non install routes -func NormalRoutes() http.Handler { - r := chi.NewRouter() - +// RegisterRoutes registers gin routes +func RegisterRoutes(c chi.Router) { // for health check r.Head("/", func(w http.ResponseWriter, req *http.Request) { w.WriteHeader(http.StatusOK) diff --git a/vendor/github.com/alexedwards/scs/v2/.travis.yml b/vendor/github.com/alexedwards/scs/v2/.travis.yml new file mode 100644 index 0000000000000..1e825050d8461 --- /dev/null +++ b/vendor/github.com/alexedwards/scs/v2/.travis.yml @@ -0,0 +1,9 @@ +language: go + +go: +- 1.12.x +- 1.13.x +- 1.14.x +- tip + +script: go test -race . diff --git a/vendor/github.com/alexedwards/scs/v2/LICENSE b/vendor/github.com/alexedwards/scs/v2/LICENSE new file mode 100644 index 0000000000000..a428968947270 --- /dev/null +++ b/vendor/github.com/alexedwards/scs/v2/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Alex Edwards + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/alexedwards/scs/v2/README.md b/vendor/github.com/alexedwards/scs/v2/README.md new file mode 100644 index 0000000000000..864588d181124 --- /dev/null +++ b/vendor/github.com/alexedwards/scs/v2/README.md @@ -0,0 +1,213 @@ +# SCS: HTTP Session Management for Go + +[![GoDoc](https://godoc.org/github.com/alexedwards/scs?status.png)](https://pkg.go.dev/github.com/alexedwards/scs/v2?tab=doc) +[![Build status](https://travis-ci.org/alexedwards/stack.svg?branch=master)](https://travis-ci.org/alexedwards/scs) +[![Go report card](https://goreportcard.com/badge/github.com/alexedwards/scs)](https://goreportcard.com/report/github.com/alexedwards/scs) +[![Test coverage](http://gocover.io/_badge/github.com/alexedwards/scs)](https://gocover.io/github.com/alexedwards/scs) + + +## Features + +* Automatic loading and saving of session data via middleware. +* Choice of server-side session stores including PostgreSQL, MySQL, Redis, BadgerDB and BoltDB. Custom session stores are also supported. +* Supports multiple sessions per request, 'flash' messages, session token regeneration, and idle and absolute session timeouts. +* Easy to extend and customize. Communicate session tokens to/from clients in HTTP headers or request/response bodies. +* Efficient design. Smaller, faster and uses less memory than [gorilla/sessions](https://github.com/gorilla/sessions). + +## Instructions + +* [Installation](#installation) +* [Basic Use](#basic-use) +* [Configuring Session Behavior](#configuring-session-behavior) +* [Working with Session Data](#working-with-session-data) +* [Loading and Saving Sessions](#loading-and-saving-sessions) +* [Configuring the Session Store](#configuring-the-session-store) +* [Using Custom Session Stores](#using-custom-session-stores) +* [Preventing Session Fixation](#preventing-session-fixation) +* [Multiple Sessions per Request](#multiple-sessions-per-request) +* [Compatibility](#compatibility) + +### Installation + +This package requires Go 1.12 or newer. + +``` +$ go get github.com/alexedwards/scs/v2 +``` + +Note: If you're using the traditional `GOPATH` mechanism to manage dependencies, instead of modules, you'll need to `go get` and `import` `github.com/alexedwards/scs` without the `v2` suffix. + +Please use [versioned releases](https://github.com/alexedwards/scs/releases). Code in tip may contain experimental features which are subject to change. + +### Basic Use + +SCS implements a session management pattern following the [OWASP security guidelines](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Session_Management_Cheat_Sheet.md). Session data is stored on the server, and a randomly-generated unique session token (or *session ID*) is communicated to and from the client in a session cookie. + +```go +package main + +import ( + "io" + "net/http" + "time" + + "github.com/alexedwards/scs/v2" +) + +var sessionManager *scs.SessionManager + +func main() { + // Initialize a new session manager and configure the session lifetime. + sessionManager = scs.New() + sessionManager.Lifetime = 24 * time.Hour + + mux := http.NewServeMux() + mux.HandleFunc("/put", putHandler) + mux.HandleFunc("/get", getHandler) + + // Wrap your handlers with the LoadAndSave() middleware. + http.ListenAndServe(":4000", sessionManager.LoadAndSave(mux)) +} + +func putHandler(w http.ResponseWriter, r *http.Request) { + // Store a new key and value in the session data. + sessionManager.Put(r.Context(), "message", "Hello from a session!") +} + +func getHandler(w http.ResponseWriter, r *http.Request) { + // Use the GetString helper to retrieve the string value associated with a + // key. The zero value is returned if the key does not exist. + msg := sessionManager.GetString(r.Context(), "message") + io.WriteString(w, msg) +} +``` + +``` +$ curl -i --cookie-jar cj --cookie cj localhost:4000/put +HTTP/1.1 200 OK +Cache-Control: no-cache="Set-Cookie" +Set-Cookie: session=lHqcPNiQp_5diPxumzOklsSdE-MJ7zyU6kjch1Ee0UM; Path=/; Expires=Sat, 27 Apr 2019 10:28:20 GMT; Max-Age=86400; HttpOnly; SameSite=Lax +Vary: Cookie +Date: Fri, 26 Apr 2019 10:28:19 GMT +Content-Length: 0 + +$ curl -i --cookie-jar cj --cookie cj localhost:4000/get +HTTP/1.1 200 OK +Date: Fri, 26 Apr 2019 10:28:24 GMT +Content-Length: 21 +Content-Type: text/plain; charset=utf-8 + +Hello from a session! +``` + +### Configuring Session Behavior + +Session behavior can be configured via the `SessionManager` fields. + +```go +sessionManager = scs.New() +sessionManager.Lifetime = 3 * time.Hour +sessionManager.IdleTimeout = 20 * time.Minute +sessionManager.Cookie.Name = "session_id" +sessionManager.Cookie.Domain = "example.com" +sessionManager.Cookie.HttpOnly = true +sessionManager.Cookie.Path = "/example/" +sessionManager.Cookie.Persist = true +sessionManager.Cookie.SameSite = http.SameSiteStrictMode +sessionManager.Cookie.Secure = true +``` + +Documentation for all available settings and their default values can be [found here](https://godoc.org/github.com/alexedwards/scs#SessionManager). + +### Working with Session Data + +Data can be set using the [`Put()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.Put) method and retrieved with the [`Get()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.Get) method. A variety of helper methods like [`GetString()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.GetString), [`GetInt()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.GetInt) and [`GetBytes()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.GetBytes) are included for common data types. Please see [the documentation](https://godoc.org/github.com/alexedwards/scs#pkg-index) for a full list of helper methods. + +The [`Pop()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.Pop) method (and accompanying helpers for common data types) act like a one-time `Get()`, retrieving the data and removing it from the session in one step. These are useful if you want to implement 'flash' message functionality in your application, where messages are displayed to the user once only. + +Some other useful functions are [`Exists()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.Exists) (which returns a `bool` indicating whether or not a given key exists in the session data) and [`Keys()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.Keys) (which returns a sorted slice of keys in the session data). + +Individual data items can be deleted from the session using the [`Remove()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.Remove) method. Alternatively, all session data can de deleted by using the [`Destroy()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.Destroy) method. After calling `Destroy()`, any further operations in the same request cycle will result in a new session being created --- with a new session token and a new lifetime. + +Behind the scenes SCS uses gob encoding to store session data, so if you want to store custom types in the session data they must be [registered](https://golang.org/pkg/encoding/gob/#Register) with the encoding/gob package first. Struct fields of custom types must also be exported so that they are visible to the encoding/gob package. Please [see here](https://gist.github.com/alexedwards/d6eca7136f98ec12ad606e774d3abad3) for a working example. + +### Loading and Saving Sessions + +Most applications will use the [`LoadAndSave()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.LoadAndSave) middleware. This middleware takes care of loading and committing session data to the session store, and communicating the session token to/from the client in a cookie as necessary. + +If you want to customize the behavior (like communicating the session token to/from the client in a HTTP header, or creating a distributed lock on the session token for the duration of the request) you are encouraged to create your own alternative middleware using the code in [`LoadAndSave()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.LoadAndSave) as a template. An example is [given here](https://gist.github.com/alexedwards/cc6190195acfa466bf27f05aa5023f50). + +Or for more fine-grained control you can load and save sessions within your individual handlers (or from anywhere in your application). [See here](https://gist.github.com/alexedwards/0570e5a59677e278e13acb8ea53a3b30) for an example. + +### Configuring the Session Store + +By default SCS uses an in-memory store for session data. This is convenient (no setup!) and very fast, but all session data will be lost when your application is stopped or restarted. Therefore it's useful for applications where data loss is an acceptable trade off for fast performance, or for prototyping and testing purposes. In most production applications you will want to use a persistent session store like PostgreSQL or MySQL instead. + +The session stores currently included are shown in the table below. Please click the links for usage instructions and examples. + +| Package | | +|:------------------------------------------------------------------------------------- |----------------------------------------------------------------------------------| +| [badgerstore](https://github.com/alexedwards/scs/tree/master/badgerstore) | BadgerDB based session store | +| [boltstore](https://github.com/alexedwards/scs/tree/master/boltstore) | BoltDB based session store | +| [memstore](https://github.com/alexedwards/scs/tree/master/memstore) | In-memory session store (default) | +| [mysqlstore](https://github.com/alexedwards/scs/tree/master/mysqlstore) | MySQL based session store | +| [postgresstore](https://github.com/alexedwards/scs/tree/master/postgresstore) | PostgreSQL based session store | +| [redisstore](https://github.com/alexedwards/scs/tree/master/redisstore) | Redis based session store | +| [sqlite3store](https://github.com/alexedwards/scs/tree/master/sqlite3store) | SQLite3 based session store | + +Custom session stores are also supported. Please [see here](#using-custom-session-stores) for more information. + +### Using Custom Session Stores + +[`scs.Store`](https://godoc.org/github.com/alexedwards/scs#Store) defines the interface for custom session stores. Any object that implements this interface can be set as the store when configuring the session. + +```go +type Store interface { + // Delete should remove the session token and corresponding data from the + // session store. If the token does not exist then Delete should be a no-op + // and return nil (not an error). + Delete(token string) (err error) + + // Find should return the data for a session token from the store. If the + // session token is not found or is expired, the found return value should + // be false (and the err return value should be nil). Similarly, tampered + // or malformed tokens should result in a found return value of false and a + // nil err value. The err return value should be used for system errors only. + Find(token string) (b []byte, found bool, err error) + + // Commit should add the session token and data to the store, with the given + // expiry time. If the session token already exists, then the data and + // expiry time should be overwritten. + Commit(token string, b []byte, expiry time.Time) (err error) +} +``` + +### Preventing Session Fixation + +To help prevent session fixation attacks you should [renew the session token after any privilege level change](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Session_Management_Cheat_Sheet.md#renew-the-session-id-after-any-privilege-level-change). Commonly, this means that the session token must to be changed when a user logs in or out of your application. You can do this using the [`RenewToken()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.RenewToken) method like so: + +```go +func loginHandler(w http.ResponseWriter, r *http.Request) { + userID := 123 + + // First renew the session token... + err := sessionManager.RenewToken(r.Context()) + if err != nil { + http.Error(w, err.Error(), 500) + return + } + + // Then make the privilege-level change. + sessionManager.Put(r.Context(), "userID", userID) +} +``` + +### Multiple Sessions per Request + +It is possible for an application to support multiple sessions per request, with different lifetime lengths and even different stores. Please [see here for an example](https://gist.github.com/alexedwards/22535f758356bfaf96038fffad154824). + +### Compatibility + +This package requires Go 1.12 or newer. + +It is not compatible with the [Echo](https://echo.labstack.com/) framework. Please consider using the [Echo session manager](https://echo.labstack.com/middleware/session) instead. diff --git a/vendor/github.com/alexedwards/scs/v2/codec.go b/vendor/github.com/alexedwards/scs/v2/codec.go new file mode 100644 index 0000000000000..bcd9bbbeadb04 --- /dev/null +++ b/vendor/github.com/alexedwards/scs/v2/codec.go @@ -0,0 +1,51 @@ +package scs + +import ( + "bytes" + "encoding/gob" + "time" +) + +// Codec is the interface for encoding/decoding session data to and from a byte +// slice for use by the session store. +type Codec interface { + Encode(deadline time.Time, values map[string]interface{}) ([]byte, error) + Decode([]byte) (deadline time.Time, values map[string]interface{}, err error) +} + +// GobCodec is used for encoding/decoding session data to and from a byte +// slice using the encoding/gob package. +type GobCodec struct{} + +// Encode converts a session dealine and values into a byte slice. +func (GobCodec) Encode(deadline time.Time, values map[string]interface{}) ([]byte, error) { + aux := &struct { + Deadline time.Time + Values map[string]interface{} + }{ + Deadline: deadline, + Values: values, + } + + var b bytes.Buffer + if err := gob.NewEncoder(&b).Encode(&aux); err != nil { + return nil, err + } + + return b.Bytes(), nil +} + +// Decode converts a byte slice into a session deadline and values. +func (GobCodec) Decode(b []byte) (time.Time, map[string]interface{}, error) { + aux := &struct { + Deadline time.Time + Values map[string]interface{} + }{} + + r := bytes.NewReader(b) + if err := gob.NewDecoder(r).Decode(&aux); err != nil { + return time.Time{}, nil, err + } + + return aux.Deadline, aux.Values, nil +} diff --git a/vendor/github.com/alexedwards/scs/v2/data.go b/vendor/github.com/alexedwards/scs/v2/data.go new file mode 100644 index 0000000000000..1b65a324f3b7e --- /dev/null +++ b/vendor/github.com/alexedwards/scs/v2/data.go @@ -0,0 +1,498 @@ +package scs + +import ( + "context" + "crypto/rand" + "encoding/base64" + "fmt" + "sort" + "sync" + "sync/atomic" + "time" +) + +// Status represents the state of the session data during a request cycle. +type Status int + +const ( + // Unmodified indicates that the session data hasn't been changed in the + // current request cycle. + Unmodified Status = iota + + // Modified indicates that the session data has been changed in the current + // request cycle. + Modified + + // Destroyed indicates that the session data has been destroyed in the + // current request cycle. + Destroyed +) + +type sessionData struct { + deadline time.Time + status Status + token string + values map[string]interface{} + mu sync.Mutex +} + +func newSessionData(lifetime time.Duration) *sessionData { + return &sessionData{ + deadline: time.Now().Add(lifetime).UTC(), + status: Unmodified, + values: make(map[string]interface{}), + } +} + +// Load retrieves the session data for the given token from the session store, +// and returns a new context.Context containing the session data. If no matching +// token is found then this will create a new session. +// +// Most applications will use the LoadAndSave() middleware and will not need to +// use this method. +func (s *SessionManager) Load(ctx context.Context, token string) (context.Context, error) { + if _, ok := ctx.Value(s.contextKey).(*sessionData); ok { + return ctx, nil + } + + if token == "" { + return s.addSessionDataToContext(ctx, newSessionData(s.Lifetime)), nil + } + + b, found, err := s.Store.Find(token) + if err != nil { + return nil, err + } else if !found { + return s.addSessionDataToContext(ctx, newSessionData(s.Lifetime)), nil + } + + sd := &sessionData{ + status: Unmodified, + token: token, + } + if sd.deadline, sd.values, err = s.Codec.Decode(b); err != nil { + return nil, err + } + + // Mark the session data as modified if an idle timeout is being used. This + // will force the session data to be re-committed to the session store with + // a new expiry time. + if s.IdleTimeout > 0 { + sd.status = Modified + } + + return s.addSessionDataToContext(ctx, sd), nil +} + +// Commit saves the session data to the session store and returns the session +// token and expiry time. +// +// Most applications will use the LoadAndSave() middleware and will not need to +// use this method. +func (s *SessionManager) Commit(ctx context.Context) (string, time.Time, error) { + sd := s.getSessionDataFromContext(ctx) + + sd.mu.Lock() + defer sd.mu.Unlock() + + if sd.token == "" { + var err error + if sd.token, err = generateToken(); err != nil { + return "", time.Time{}, err + } + } + + b, err := s.Codec.Encode(sd.deadline, sd.values) + if err != nil { + return "", time.Time{}, err + } + + expiry := sd.deadline + if s.IdleTimeout > 0 { + ie := time.Now().Add(s.IdleTimeout).UTC() + if ie.Before(expiry) { + expiry = ie + } + } + + if err := s.Store.Commit(sd.token, b, expiry); err != nil { + return "", time.Time{}, err + } + + return sd.token, expiry, nil +} + +// Destroy deletes the session data from the session store and sets the session +// status to Destroyed. Any further operations in the same request cycle will +// result in a new session being created. +func (s *SessionManager) Destroy(ctx context.Context) error { + sd := s.getSessionDataFromContext(ctx) + + sd.mu.Lock() + defer sd.mu.Unlock() + + err := s.Store.Delete(sd.token) + if err != nil { + return err + } + + sd.status = Destroyed + + // Reset everything else to defaults. + sd.token = "" + sd.deadline = time.Now().Add(s.Lifetime).UTC() + for key := range sd.values { + delete(sd.values, key) + } + + return nil +} + +// Put adds a key and corresponding value to the session data. Any existing +// value for the key will be replaced. The session data status will be set to +// Modified. +func (s *SessionManager) Put(ctx context.Context, key string, val interface{}) { + sd := s.getSessionDataFromContext(ctx) + + sd.mu.Lock() + sd.values[key] = val + sd.status = Modified + sd.mu.Unlock() +} + +// Get returns the value for a given key from the session data. The return +// value has the type interface{} so will usually need to be type asserted +// before you can use it. For example: +// +// foo, ok := session.Get(r, "foo").(string) +// if !ok { +// return errors.New("type assertion to string failed") +// } +// +// Also see the GetString(), GetInt(), GetBytes() and other helper methods which +// wrap the type conversion for common types. +func (s *SessionManager) Get(ctx context.Context, key string) interface{} { + sd := s.getSessionDataFromContext(ctx) + + sd.mu.Lock() + defer sd.mu.Unlock() + + return sd.values[key] +} + +// Pop acts like a one-time Get. It returns the value for a given key from the +// session data and deletes the key and value from the session data. The +// session data status will be set to Modified. The return value has the type +// interface{} so will usually need to be type asserted before you can use it. +func (s *SessionManager) Pop(ctx context.Context, key string) interface{} { + sd := s.getSessionDataFromContext(ctx) + + sd.mu.Lock() + defer sd.mu.Unlock() + + val, exists := sd.values[key] + if !exists { + return nil + } + delete(sd.values, key) + sd.status = Modified + + return val +} + +// Remove deletes the given key and corresponding value from the session data. +// The session data status will be set to Modified. If the key is not present +// this operation is a no-op. +func (s *SessionManager) Remove(ctx context.Context, key string) { + sd := s.getSessionDataFromContext(ctx) + + sd.mu.Lock() + defer sd.mu.Unlock() + + _, exists := sd.values[key] + if !exists { + return + } + + delete(sd.values, key) + sd.status = Modified +} + +// Clear removes all data for the current session. The session token and +// lifetime are unaffected. If there is no data in the current session this is +// a no-op. +func (s *SessionManager) Clear(ctx context.Context) error { + sd := s.getSessionDataFromContext(ctx) + + sd.mu.Lock() + defer sd.mu.Unlock() + + if len(sd.values) == 0 { + return nil + } + + for key := range sd.values { + delete(sd.values, key) + } + sd.status = Modified + return nil +} + +// Exists returns true if the given key is present in the session data. +func (s *SessionManager) Exists(ctx context.Context, key string) bool { + sd := s.getSessionDataFromContext(ctx) + + sd.mu.Lock() + _, exists := sd.values[key] + sd.mu.Unlock() + + return exists +} + +// Keys returns a slice of all key names present in the session data, sorted +// alphabetically. If the data contains no data then an empty slice will be +// returned. +func (s *SessionManager) Keys(ctx context.Context) []string { + sd := s.getSessionDataFromContext(ctx) + + sd.mu.Lock() + keys := make([]string, len(sd.values)) + i := 0 + for key := range sd.values { + keys[i] = key + i++ + } + sd.mu.Unlock() + + sort.Strings(keys) + return keys +} + +// RenewToken updates the session data to have a new session token while +// retaining the current session data. The session lifetime is also reset and +// the session data status will be set to Modified. +// +// The old session token and accompanying data are deleted from the session store. +// +// To mitigate the risk of session fixation attacks, it's important that you call +// RenewToken before making any changes to privilege levels (e.g. login and +// logout operations). See https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Session_Management_Cheat_Sheet.md#renew-the-session-id-after-any-privilege-level-change +// for additional information. +func (s *SessionManager) RenewToken(ctx context.Context) error { + sd := s.getSessionDataFromContext(ctx) + + sd.mu.Lock() + defer sd.mu.Unlock() + + err := s.Store.Delete(sd.token) + if err != nil { + return err + } + + newToken, err := generateToken() + if err != nil { + return err + } + + sd.token = newToken + sd.deadline = time.Now().Add(s.Lifetime).UTC() + sd.status = Modified + + return nil +} + +// Status returns the current status of the session data. +func (s *SessionManager) Status(ctx context.Context) Status { + sd := s.getSessionDataFromContext(ctx) + + sd.mu.Lock() + defer sd.mu.Unlock() + + return sd.status +} + +// GetString returns the string value for a given key from the session data. +// The zero value for a string ("") is returned if the key does not exist or the +// value could not be type asserted to a string. +func (s *SessionManager) GetString(ctx context.Context, key string) string { + val := s.Get(ctx, key) + str, ok := val.(string) + if !ok { + return "" + } + return str +} + +// GetBool returns the bool value for a given key from the session data. The +// zero value for a bool (false) is returned if the key does not exist or the +// value could not be type asserted to a bool. +func (s *SessionManager) GetBool(ctx context.Context, key string) bool { + val := s.Get(ctx, key) + b, ok := val.(bool) + if !ok { + return false + } + return b +} + +// GetInt returns the int value for a given key from the session data. The +// zero value for an int (0) is returned if the key does not exist or the +// value could not be type asserted to an int. +func (s *SessionManager) GetInt(ctx context.Context, key string) int { + val := s.Get(ctx, key) + i, ok := val.(int) + if !ok { + return 0 + } + return i +} + +// GetFloat returns the float64 value for a given key from the session data. The +// zero value for an float64 (0) is returned if the key does not exist or the +// value could not be type asserted to a float64. +func (s *SessionManager) GetFloat(ctx context.Context, key string) float64 { + val := s.Get(ctx, key) + f, ok := val.(float64) + if !ok { + return 0 + } + return f +} + +// GetBytes returns the byte slice ([]byte) value for a given key from the session +// data. The zero value for a slice (nil) is returned if the key does not exist +// or could not be type asserted to []byte. +func (s *SessionManager) GetBytes(ctx context.Context, key string) []byte { + val := s.Get(ctx, key) + b, ok := val.([]byte) + if !ok { + return nil + } + return b +} + +// GetTime returns the time.Time value for a given key from the session data. The +// zero value for a time.Time object is returned if the key does not exist or the +// value could not be type asserted to a time.Time. This can be tested with the +// time.IsZero() method. +func (s *SessionManager) GetTime(ctx context.Context, key string) time.Time { + val := s.Get(ctx, key) + t, ok := val.(time.Time) + if !ok { + return time.Time{} + } + return t +} + +// PopString returns the string value for a given key and then deletes it from the +// session data. The session data status will be set to Modified. The zero +// value for a string ("") is returned if the key does not exist or the value +// could not be type asserted to a string. +func (s *SessionManager) PopString(ctx context.Context, key string) string { + val := s.Pop(ctx, key) + str, ok := val.(string) + if !ok { + return "" + } + return str +} + +// PopBool returns the bool value for a given key and then deletes it from the +// session data. The session data status will be set to Modified. The zero +// value for a bool (false) is returned if the key does not exist or the value +// could not be type asserted to a bool. +func (s *SessionManager) PopBool(ctx context.Context, key string) bool { + val := s.Pop(ctx, key) + b, ok := val.(bool) + if !ok { + return false + } + return b +} + +// PopInt returns the int value for a given key and then deletes it from the +// session data. The session data status will be set to Modified. The zero +// value for an int (0) is returned if the key does not exist or the value could +// not be type asserted to an int. +func (s *SessionManager) PopInt(ctx context.Context, key string) int { + val := s.Pop(ctx, key) + i, ok := val.(int) + if !ok { + return 0 + } + return i +} + +// PopFloat returns the float64 value for a given key and then deletes it from the +// session data. The session data status will be set to Modified. The zero +// value for an float64 (0) is returned if the key does not exist or the value +// could not be type asserted to a float64. +func (s *SessionManager) PopFloat(ctx context.Context, key string) float64 { + val := s.Pop(ctx, key) + f, ok := val.(float64) + if !ok { + return 0 + } + return f +} + +// PopBytes returns the byte slice ([]byte) value for a given key and then +// deletes it from the from the session data. The session data status will be +// set to Modified. The zero value for a slice (nil) is returned if the key does +// not exist or could not be type asserted to []byte. +func (s *SessionManager) PopBytes(ctx context.Context, key string) []byte { + val := s.Pop(ctx, key) + b, ok := val.([]byte) + if !ok { + return nil + } + return b +} + +// PopTime returns the time.Time value for a given key and then deletes it from +// the session data. The session data status will be set to Modified. The zero +// value for a time.Time object is returned if the key does not exist or the +// value could not be type asserted to a time.Time. +func (s *SessionManager) PopTime(ctx context.Context, key string) time.Time { + val := s.Pop(ctx, key) + t, ok := val.(time.Time) + if !ok { + return time.Time{} + } + return t +} + +func (s *SessionManager) addSessionDataToContext(ctx context.Context, sd *sessionData) context.Context { + return context.WithValue(ctx, s.contextKey, sd) +} + +func (s *SessionManager) getSessionDataFromContext(ctx context.Context) *sessionData { + c, ok := ctx.Value(s.contextKey).(*sessionData) + if !ok { + panic("scs: no session data in context") + } + return c +} + +func generateToken() (string, error) { + b := make([]byte, 32) + _, err := rand.Read(b) + if err != nil { + return "", err + } + return base64.RawURLEncoding.EncodeToString(b), nil +} + +type contextKey string + +var ( + contextKeyID uint64 + contextKeyIDMutex = &sync.Mutex{} +) + +func generateContextKey() contextKey { + contextKeyIDMutex.Lock() + defer contextKeyIDMutex.Unlock() + atomic.AddUint64(&contextKeyID, 1) + return contextKey(fmt.Sprintf("session.%d", contextKeyID)) +} diff --git a/vendor/github.com/alexedwards/scs/v2/go.mod b/vendor/github.com/alexedwards/scs/v2/go.mod new file mode 100644 index 0000000000000..16a2ee639e60a --- /dev/null +++ b/vendor/github.com/alexedwards/scs/v2/go.mod @@ -0,0 +1,3 @@ +module github.com/alexedwards/scs/v2 + +go 1.12 diff --git a/vendor/github.com/alexedwards/scs/v2/go.sum b/vendor/github.com/alexedwards/scs/v2/go.sum new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/vendor/github.com/alexedwards/scs/v2/memstore/README.md b/vendor/github.com/alexedwards/scs/v2/memstore/README.md new file mode 100644 index 0000000000000..e33f550383b87 --- /dev/null +++ b/vendor/github.com/alexedwards/scs/v2/memstore/README.md @@ -0,0 +1,74 @@ +# memstore + +An in-memory session store for [SCS](https://github.com/alexedwards/scs). + + +Because memstore uses in-memory storage only, all session data will be lost when your application is stopped or restarted. Therefore it should only be used in applications where data loss is an acceptable trade off for fast performance, or for prototyping and testing purposes. + +## Example + +```go +package main + +import ( + "io" + "net/http" + + "github.com/alexedwards/scs/v2" + "github.com/alexedwards/scs/v2/memstore" +) + +var sessionManager *scs.SessionManager + +func main() { + // Initialize a new session manager and configure it to use memstore as + // the session store. + sessionManager = scs.New() + sessionManager.Store = memstore.New() + + mux := http.NewServeMux() + mux.HandleFunc("/put", putHandler) + mux.HandleFunc("/get", getHandler) + + http.ListenAndServe(":4000", sessionManager.LoadAndSave(mux)) +} + +func putHandler(w http.ResponseWriter, r *http.Request) { + sessionManager.Put(r.Context(), "message", "Hello from a session!") +} + +func getHandler(w http.ResponseWriter, r *http.Request) { + msg := sessionManager.GetString(r.Context(), "message") + io.WriteString(w, msg) +} +``` + +## Expired Session Cleanup + +This package provides a background 'cleanup' goroutine to delete expired session data. This stops the database table from holding on to invalid sessions indefinitely and growing unnecessarily large. By default the cleanup runs once every minute. You can change this by using the `NewWithCleanupInterval()` function to initialize your session store. For example: + +```go +// Run a cleanup every 30 seconds. +memstore.NewWithCleanupInterval(db, 30*time.Second) + +// Disable the cleanup goroutine by setting the cleanup interval to zero. +memstore.NewWithCleanupInterval(db, 0) +``` + +### Terminating the Cleanup Goroutine + +It's rare that the cleanup goroutine needs to be terminated --- it is generally intended to be long-lived and run for the lifetime of your application. + +However, there may be occasions when your use of a session store instance is transient. A common example would be using it in a short-lived test function. In this scenario, the cleanup goroutine (which will run forever) will prevent the session store instance from being garbage collected even after the test function has finished. You can prevent this by either disabling the cleanup goroutine altogether (as described above) or by stopping it using the `StopCleanup()` method. For example: + +```go +func TestExample(t *testing.T) { + store := memstore.New() + defer store.StopCleanup() + + sessionManager = scs.New() + sessionManager.Store = store + + // Run test... +} +``` \ No newline at end of file diff --git a/vendor/github.com/alexedwards/scs/v2/memstore/memstore.go b/vendor/github.com/alexedwards/scs/v2/memstore/memstore.go new file mode 100644 index 0000000000000..563df7e5bd801 --- /dev/null +++ b/vendor/github.com/alexedwards/scs/v2/memstore/memstore.go @@ -0,0 +1,124 @@ +package memstore + +import ( + "sync" + "time" +) + +type item struct { + object []byte + expiration int64 +} + +// MemStore represents the session store. +type MemStore struct { + items map[string]item + mu sync.RWMutex + stopCleanup chan bool +} + +// New returns a new MemStore instance, with a background cleanup goroutine that +// runs every minute to remove expired session data. +func New() *MemStore { + return NewWithCleanupInterval(time.Minute) +} + +// NewWithCleanupInterval returns a new MemStore instance. The cleanupInterval +// parameter controls how frequently expired session data is removed by the +// background cleanup goroutine. Setting it to 0 prevents the cleanup goroutine +// from running (i.e. expired sessions will not be removed). +func NewWithCleanupInterval(cleanupInterval time.Duration) *MemStore { + m := &MemStore{ + items: make(map[string]item), + } + + if cleanupInterval > 0 { + go m.startCleanup(cleanupInterval) + } + + return m +} + +// Find returns the data for a given session token from the MemStore instance. +// If the session token is not found or is expired, the returned exists flag will +// be set to false. +func (m *MemStore) Find(token string) ([]byte, bool, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + item, found := m.items[token] + if !found { + return nil, false, nil + } + + if time.Now().UnixNano() > item.expiration { + return nil, false, nil + } + + return item.object, true, nil +} + +// Commit adds a session token and data to the MemStore instance with the given +// expiry time. If the session token already exists, then the data and expiry +// time are updated. +func (m *MemStore) Commit(token string, b []byte, expiry time.Time) error { + m.mu.Lock() + m.items[token] = item{ + object: b, + expiration: expiry.UnixNano(), + } + m.mu.Unlock() + + return nil +} + +// Delete removes a session token and corresponding data from the MemStore +// instance. +func (m *MemStore) Delete(token string) error { + m.mu.Lock() + delete(m.items, token) + m.mu.Unlock() + + return nil +} + +func (m *MemStore) startCleanup(interval time.Duration) { + m.stopCleanup = make(chan bool) + ticker := time.NewTicker(interval) + for { + select { + case <-ticker.C: + m.deleteExpired() + case <-m.stopCleanup: + ticker.Stop() + return + } + } +} + +// StopCleanup terminates the background cleanup goroutine for the MemStore +// instance. It's rare to terminate this; generally MemStore instances and +// their cleanup goroutines are intended to be long-lived and run for the lifetime +// of your application. +// +// There may be occasions though when your use of the MemStore is transient. +// An example is creating a new MemStore instance in a test function. In this +// scenario, the cleanup goroutine (which will run forever) will prevent the +// MemStore object from being garbage collected even after the test function +// has finished. You can prevent this by manually calling StopCleanup. +func (m *MemStore) StopCleanup() { + if m.stopCleanup != nil { + m.stopCleanup <- true + } +} + +func (m *MemStore) deleteExpired() { + now := time.Now().UnixNano() + m.mu.Lock() + for token, item := range m.items { + if now > item.expiration { + delete(m.items, token) + } + } + m.mu.Unlock() +} diff --git a/vendor/github.com/alexedwards/scs/v2/session.go b/vendor/github.com/alexedwards/scs/v2/session.go new file mode 100644 index 0000000000000..0cdc08a8fb250 --- /dev/null +++ b/vendor/github.com/alexedwards/scs/v2/session.go @@ -0,0 +1,236 @@ +package scs + +import ( + "bufio" + "bytes" + "log" + "net" + "net/http" + "time" + + "github.com/alexedwards/scs/v2/memstore" +) + +// Deprecated: Session is a backwards-compatible alias for SessionManager. +type Session = SessionManager + +// SessionManager holds the configuration settings for your sessions. +type SessionManager struct { + // IdleTimeout controls the maximum length of time a session can be inactive + // before it expires. For example, some applications may wish to set this so + // there is a timeout after 20 minutes of inactivity. By default IdleTimeout + // is not set and there is no inactivity timeout. + IdleTimeout time.Duration + + // Lifetime controls the maximum length of time that a session is valid for + // before it expires. The lifetime is an 'absolute expiry' which is set when + // the session is first created and does not change. The default value is 24 + // hours. + Lifetime time.Duration + + // Store controls the session store where the session data is persisted. + Store Store + + // Cookie contains the configuration settings for session cookies. + Cookie SessionCookie + + // Codec controls the encoder/decoder used to transform session data to a + // byte slice for use by the session store. By default session data is + // encoded/decoded using encoding/gob. + Codec Codec + + // ErrorFunc allows you to control behavior when an error is encountered by + // the LoadAndSave middleware. The default behavior is for a HTTP 500 + // "Internal Server Error" message to be sent to the client and the error + // logged using Go's standard logger. If a custom ErrorFunc is set, then + // control will be passed to this instead. A typical use would be to provide + // a function which logs the error and returns a customized HTML error page. + ErrorFunc func(http.ResponseWriter, *http.Request, error) + + // contextKey is the key used to set and retrieve the session data from a + // context.Context. It's automatically generated to ensure uniqueness. + contextKey contextKey +} + +// SessionCookie contains the configuration settings for session cookies. +type SessionCookie struct { + // Name sets the name of the session cookie. It should not contain + // whitespace, commas, colons, semicolons, backslashes, the equals sign or + // control characters as per RFC6265. The default cookie name is "session". + // If your application uses two different sessions, you must make sure that + // the cookie name for each is unique. + Name string + + // Domain sets the 'Domain' attribute on the session cookie. By default + // it will be set to the domain name that the cookie was issued from. + Domain string + + // HttpOnly sets the 'HttpOnly' attribute on the session cookie. The + // default value is true. + HttpOnly bool + + // Path sets the 'Path' attribute on the session cookie. The default value + // is "/". Passing the empty string "" will result in it being set to the + // path that the cookie was issued from. + Path string + + // Persist sets whether the session cookie should be persistent or not + // (i.e. whether it should be retained after a user closes their browser). + // The default value is true, which means that the session cookie will not + // be destroyed when the user closes their browser and the appropriate + // 'Expires' and 'MaxAge' values will be added to the session cookie. + Persist bool + + // SameSite controls the value of the 'SameSite' attribute on the session + // cookie. By default this is set to 'SameSite=Lax'. If you want no SameSite + // attribute or value in the session cookie then you should set this to 0. + SameSite http.SameSite + + // Secure sets the 'Secure' attribute on the session cookie. The default + // value is false. It's recommended that you set this to true and serve all + // requests over HTTPS in production environments. + // See https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Session_Management_Cheat_Sheet.md#transport-layer-security. + Secure bool +} + +// New returns a new session manager with the default options. It is safe for +// concurrent use. +func New() *SessionManager { + s := &SessionManager{ + IdleTimeout: 0, + Lifetime: 24 * time.Hour, + Store: memstore.New(), + Codec: GobCodec{}, + ErrorFunc: defaultErrorFunc, + contextKey: generateContextKey(), + Cookie: SessionCookie{ + Name: "session", + Domain: "", + HttpOnly: true, + Path: "/", + Persist: true, + Secure: false, + SameSite: http.SameSiteLaxMode, + }, + } + return s +} + +// Deprecated: NewSession is a backwards-compatible alias for New. Use the New +// function instead. +func NewSession() *SessionManager { + return New() +} + +// LoadAndSave provides middleware which automatically loads and saves session +// data for the current request, and communicates the session token to and from +// the client in a cookie. +func (s *SessionManager) LoadAndSave(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var token string + cookie, err := r.Cookie(s.Cookie.Name) + if err == nil { + token = cookie.Value + } + + ctx, err := s.Load(r.Context(), token) + if err != nil { + s.ErrorFunc(w, r, err) + return + } + + sr := r.WithContext(ctx) + bw := &bufferedResponseWriter{ResponseWriter: w} + next.ServeHTTP(bw, sr) + + if sr.MultipartForm != nil { + sr.MultipartForm.RemoveAll() + } + + switch s.Status(ctx) { + case Modified: + token, expiry, err := s.Commit(ctx) + if err != nil { + s.ErrorFunc(w, r, err) + return + } + s.writeSessionCookie(w, token, expiry) + case Destroyed: + s.writeSessionCookie(w, "", time.Time{}) + } + + if bw.code != 0 { + w.WriteHeader(bw.code) + } + w.Write(bw.buf.Bytes()) + }) +} + +func (s *SessionManager) writeSessionCookie(w http.ResponseWriter, token string, expiry time.Time) { + cookie := &http.Cookie{ + Name: s.Cookie.Name, + Value: token, + Path: s.Cookie.Path, + Domain: s.Cookie.Domain, + Secure: s.Cookie.Secure, + HttpOnly: s.Cookie.HttpOnly, + SameSite: s.Cookie.SameSite, + } + + if expiry.IsZero() { + cookie.Expires = time.Unix(1, 0) + cookie.MaxAge = -1 + } else if s.Cookie.Persist { + cookie.Expires = time.Unix(expiry.Unix()+1, 0) // Round up to the nearest second. + cookie.MaxAge = int(time.Until(expiry).Seconds() + 1) // Round up to the nearest second. + } + + w.Header().Add("Set-Cookie", cookie.String()) + addHeaderIfMissing(w, "Cache-Control", `no-cache="Set-Cookie"`) + addHeaderIfMissing(w, "Vary", "Cookie") + +} + +func addHeaderIfMissing(w http.ResponseWriter, key, value string) { + for _, h := range w.Header()[key] { + if h == value { + return + } + } + w.Header().Add(key, value) +} + +func defaultErrorFunc(w http.ResponseWriter, r *http.Request, err error) { + log.Output(2, err.Error()) + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) +} + +type bufferedResponseWriter struct { + http.ResponseWriter + buf bytes.Buffer + code int + wroteHeader bool +} + +func (bw *bufferedResponseWriter) Write(b []byte) (int, error) { + return bw.buf.Write(b) +} + +func (bw *bufferedResponseWriter) WriteHeader(code int) { + if !bw.wroteHeader { + bw.code = code + bw.wroteHeader = true + } +} + +func (bw *bufferedResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + hj := bw.ResponseWriter.(http.Hijacker) + return hj.Hijack() +} + +func (bw *bufferedResponseWriter) Push(target string, opts *http.PushOptions) error { + if pusher, ok := bw.ResponseWriter.(http.Pusher); ok { + return pusher.Push(target, opts) + } + return http.ErrNotSupported +} diff --git a/vendor/github.com/alexedwards/scs/v2/store.go b/vendor/github.com/alexedwards/scs/v2/store.go new file mode 100644 index 0000000000000..18448fd2af307 --- /dev/null +++ b/vendor/github.com/alexedwards/scs/v2/store.go @@ -0,0 +1,25 @@ +package scs + +import ( + "time" +) + +// Store is the interface for session stores. +type Store interface { + // Delete should remove the session token and corresponding data from the + // session store. If the token does not exist then Delete should be a no-op + // and return nil (not an error). + Delete(token string) (err error) + + // Find should return the data for a session token from the store. If the + // session token is not found or is expired, the found return value should + // be false (and the err return value should be nil). Similarly, tampered + // or malformed tokens should result in a found return value of false and a + // nil err value. The err return value should be used for system errors only. + Find(token string) (b []byte, found bool, err error) + + // Commit should add the session token and data to the store, with the given + // expiry time. If the session token already exists, then the data and + // expiry time should be overwritten. + Commit(token string, b []byte, expiry time.Time) (err error) +} diff --git a/vendor/modules.txt b/vendor/modules.txt index cf42eb29aa0ee..075a4ac179371 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -109,6 +109,10 @@ github.com/alecthomas/chroma/lexers/x github.com/alecthomas/chroma/lexers/y github.com/alecthomas/chroma/lexers/z github.com/alecthomas/chroma/styles +# github.com/alexedwards/scs/v2 v2.4.0 +## explicit +github.com/alexedwards/scs/v2 +github.com/alexedwards/scs/v2/memstore # github.com/andybalholm/brotli v1.0.1 ## explicit github.com/andybalholm/brotli @@ -440,7 +444,6 @@ github.com/gorilla/handlers # github.com/gorilla/mux v1.7.3 github.com/gorilla/mux # github.com/gorilla/securecookie v1.1.1 -## explicit github.com/gorilla/securecookie # github.com/gorilla/sessions v1.2.0 github.com/gorilla/sessions From 4dce1daa6f1da2b4db4a3c4f0236c2447c4eba62 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Mon, 16 Nov 2020 21:18:53 +0800 Subject: [PATCH 09/23] Add flash --- modules/context/context.go | 28 ++++++++++++++++++++++++++-- routers/install.go | 20 ++++++++++++-------- 2 files changed, 38 insertions(+), 10 deletions(-) diff --git a/modules/context/context.go b/modules/context/context.go index 40acaea2c3fb1..b0669a6d65d61 100644 --- a/modules/context/context.go +++ b/modules/context/context.go @@ -34,6 +34,20 @@ import ( "github.com/unknwon/com" ) +// flashes enumerates all the flash types +const ( + SuccessFlash = "success" + ErrorFlash = "error" + WarnFlash = "warning" + InfoFlash = "info" +) + +// Flash represents flashs +type Flash struct { + MessageType string + Message string +} + // DefaultContext represents a context for basic routes type DefaultContext struct { Resp http.ResponseWriter @@ -42,6 +56,7 @@ type DefaultContext struct { Render *renderer.Render Sessions *scs.SessionManager translation.Locale + flash *Flash } // HTML wraps render HTML @@ -69,8 +84,7 @@ func (ctx *DefaultContext) RenderWithErr(msg string, tpl string, form interface{ if form != nil { auth.AssignForm(form, ctx.Data) } - //ctx.Flash.ErrorMsg = msg - //ctx.Data["Flash"] = ctx.Flash + ctx.Flash(ErrorFlash, msg) ctx.HTML(200, tpl) } @@ -92,6 +106,16 @@ func (ctx *DefaultContext) DestroySession() error { return nil } +// Flash set message to flash +func (ctx *DefaultContext) Flash(tp, v string) { + if ctx.flash == nil { + ctx.flash = &Flash{} + } + ctx.flash.MessageType = tp + ctx.flash.Message = v + ctx.Data["Flash"] = ctx.flash +} + // NewCookie creates a cookie func NewCookie(name, value string, maxAge int) *http.Cookie { return &http.Cookie{ diff --git a/routers/install.go b/routers/install.go index ca89b5b701954..1a58088d828ac 100644 --- a/routers/install.go +++ b/routers/install.go @@ -22,6 +22,7 @@ import ( "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" + gitea_templates "code.gitea.io/gitea/modules/templates" "code.gitea.io/gitea/modules/translation" "code.gitea.io/gitea/modules/user" "code.gitea.io/gitea/modules/util" @@ -73,7 +74,10 @@ type InstallContext = gitea_context.DefaultContext func InstallInit(next http.Handler, sessionManager *scs.SessionManager) http.Handler { rnd := renderer.New( renderer.Options{ - ParseGlobPattern: "templates/*.tmpl", + TemplateDir: "./templates", + TemplateExtension: ".tmpl", + //ParseGlobPattern: "templates/*.tmpl", + FuncMap: gitea_templates.NewFuncMap(), }, ) @@ -106,7 +110,7 @@ func InstallInit(next http.Handler, sessionManager *scs.SessionManager) http.Han // Locale handle locale func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale { - isNeedRedir := false + //isNeedRedir := false hasCookie := false // 1. Check URL arguments. @@ -118,13 +122,13 @@ func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale { lang = ck.Value hasCookie = true } else { - isNeedRedir = true + //isNeedRedir = true } // Check again in case someone modify by purpose. if !i18n.IsExist(lang) { lang = "" - isNeedRedir = false + //isNeedRedir = false hasCookie = false } @@ -134,12 +138,11 @@ func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale { tags, _, _ := language.ParseAcceptLanguage(req.Header.Get("Accept-Language")) tag, _, _ := translation.Match(tags...) lang = tag.String() - isNeedRedir = false + //isNeedRedir = false } if !hasCookie { req.AddCookie(gitea_context.NewCookie("lang", lang, 1<<31-1)) - //req.SetCookie("lang", curLang.Lang, 1<<31-1, "/"+strings.TrimPrefix(opt.SubURL, "/"), opt.CookieDomain, opt.Secure, opt.CookieHttpOnly, cookie.SameSite(opt.SameSite)) } return translation.NewLocale(lang) @@ -224,7 +227,8 @@ func Install(ctx *InstallContext) { form.NoReplyAddress = setting.Service.NoReplyAddress auth.AssignForm(form, ctx.Data) - ctx.Render.HTML(ctx.Resp, 200, tplInstall, ctx.Data) + fmt.Println("-------", tplInstall, ctx.Data) + ctx.HTML(200, tplInstall) } // InstallPost response for submit install items @@ -522,7 +526,7 @@ func InstallPost(ctx *InstallContext) { log.Info("First-time run install finished!") - ctx.Flash.Success(ctx.Tr("install.install_success")) + ctx.Flash(gitea_context.SuccessFlash, ctx.Tr("install.install_success")) ctx.Resp.Header().Add("Refresh", "1; url="+setting.AppURL+"user/login") ctx.HTML(200, tplPostInstall) From 15e3c6f8faefdae5bb8a7620d86f44fd7b1222da Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Mon, 16 Nov 2020 21:49:41 +0800 Subject: [PATCH 10/23] Fix NormalRoutes --- routers/routes/chi.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/routers/routes/chi.go b/routers/routes/chi.go index c296ca39b54c0..fe7b60fbabb45 100644 --- a/routers/routes/chi.go +++ b/routers/routes/chi.go @@ -219,8 +219,10 @@ func NewChi() chi.Router { return c } -// RegisterRoutes registers gin routes -func RegisterRoutes(c chi.Router) { +// NormalRoutes represents non install routes +func NormalRoutes() http.Handler { + r := chi.NewRouter() + // for health check r.Head("/", func(w http.ResponseWriter, req *http.Request) { w.WriteHeader(http.StatusOK) From 20336c596703d86195e960ff9df7d3f47dff3761 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Mon, 16 Nov 2020 22:03:45 +0800 Subject: [PATCH 11/23] Fix lint --- modules/context/context.go | 5 ++--- routers/install.go | 17 ++++++++--------- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/modules/context/context.go b/modules/context/context.go index b0669a6d65d61..8215e386c42db 100644 --- a/modules/context/context.go +++ b/modules/context/context.go @@ -85,7 +85,7 @@ func (ctx *DefaultContext) RenderWithErr(msg string, tpl string, form interface{ auth.AssignForm(form, ctx.Data) } ctx.Flash(ErrorFlash, msg) - ctx.HTML(200, tpl) + _ = ctx.HTML(200, tpl) } // SetSession sets session key value @@ -102,8 +102,7 @@ func (ctx *DefaultContext) GetSession(key string) (interface{}, error) { // DestroySession deletes all the data of the session func (ctx *DefaultContext) DestroySession() error { - ctx.Sessions.Destroy(ctx.Req.Context()) - return nil + return ctx.Sessions.Destroy(ctx.Req.Context()) } // Flash set message to flash diff --git a/routers/install.go b/routers/install.go index 1a58088d828ac..79472bf7bc3fc 100644 --- a/routers/install.go +++ b/routers/install.go @@ -41,6 +41,10 @@ const ( tplPostInstall = "post-install" ) +var ( + installContextKey interface{} = "install_context" +) + // InstallRoutes represents the install routes func InstallRoutes() http.Handler { r := chi.NewRouter() @@ -103,14 +107,13 @@ func InstallInit(next http.Handler, sessionManager *scs.SessionManager) http.Han Sessions: sessionManager, } - req = req.WithContext(context.WithValue(req.Context(), "install_context", &ctx)) + req = req.WithContext(context.WithValue(req.Context(), installContextKey, &ctx)) next.ServeHTTP(resp, req) }) } // Locale handle locale func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale { - //isNeedRedir := false hasCookie := false // 1. Check URL arguments. @@ -121,14 +124,11 @@ func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale { ck, _ := req.Cookie("lang") lang = ck.Value hasCookie = true - } else { - //isNeedRedir = true } // Check again in case someone modify by purpose. if !i18n.IsExist(lang) { lang = "" - //isNeedRedir = false hasCookie = false } @@ -138,7 +138,6 @@ func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale { tags, _, _ := language.ParseAcceptLanguage(req.Header.Get("Accept-Language")) tag, _, _ := translation.Match(tags...) lang = tag.String() - //isNeedRedir = false } if !hasCookie { @@ -151,7 +150,7 @@ func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale { // WrapInstall converts an install route to a chi route func WrapInstall(f func(ctx *InstallContext)) http.HandlerFunc { return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { - ctx := req.Context().Value("install_context").(*InstallContext) + ctx := req.Context().Value(installContextKey).(*InstallContext) f(ctx) }) } @@ -228,7 +227,7 @@ func Install(ctx *InstallContext) { auth.AssignForm(form, ctx.Data) fmt.Println("-------", tplInstall, ctx.Data) - ctx.HTML(200, tplInstall) + _ = ctx.HTML(200, tplInstall) } // InstallPost response for submit install items @@ -248,7 +247,7 @@ func InstallPost(ctx *InstallContext) { ctx.Data["Err_Admin"] = true } - ctx.HTML(200, tplInstall) + _ = ctx.HTML(200, tplInstall) return } From 200ec1819343d49b4516e5fdebd078d1669d25b0 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 17 Nov 2020 15:22:12 +0800 Subject: [PATCH 12/23] Fix lint --- routers/install.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/routers/install.go b/routers/install.go index 79472bf7bc3fc..e6693aaa1e35a 100644 --- a/routers/install.go +++ b/routers/install.go @@ -88,7 +88,7 @@ func InstallInit(next http.Handler, sessionManager *scs.SessionManager) http.Han return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { if setting.InstallLock { resp.Header().Add("Refresh", "1; url="+setting.AppURL+"user/login") - rnd.HTML(resp, 200, tplPostInstall, nil) + _ = rnd.HTML(resp, 200, tplPostInstall, nil) return } @@ -528,7 +528,10 @@ func InstallPost(ctx *InstallContext) { ctx.Flash(gitea_context.SuccessFlash, ctx.Tr("install.install_success")) ctx.Resp.Header().Add("Refresh", "1; url="+setting.AppURL+"user/login") - ctx.HTML(200, tplPostInstall) + if err := ctx.HTML(200, tplPostInstall); err != nil { + http.Error(ctx.Resp, fmt.Sprintf("render %s failed: %v", tplPostInstall, err), 500) + return + } // Now get the http.Server from this request and shut it down // NB: This is not our hammerable graceful shutdown this is http.Server.Shutdown From 58e7a33467f07c4c22df2c2bc62ffa281fa46935 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 17 Nov 2020 16:20:01 +0800 Subject: [PATCH 13/23] Use github.com/unrolled/render as render --- go.mod | 1 + modules/context/context.go | 4 +- routers/install.go | 24 +- .../thedevsaddam/renderer/.travis.yml | 22 - .../thedevsaddam/renderer/CONTRIBUTING.md | 12 - .../thedevsaddam/renderer/LICENSE.md | 21 - .../thedevsaddam/renderer/README.md | 369 ----------- .../thedevsaddam/renderer/renderer.go | 586 ------------------ vendor/modules.txt | 7 + 9 files changed, 23 insertions(+), 1023 deletions(-) delete mode 100644 vendor/github.com/thedevsaddam/renderer/.travis.yml delete mode 100644 vendor/github.com/thedevsaddam/renderer/CONTRIBUTING.md delete mode 100644 vendor/github.com/thedevsaddam/renderer/LICENSE.md delete mode 100644 vendor/github.com/thedevsaddam/renderer/README.md delete mode 100644 vendor/github.com/thedevsaddam/renderer/renderer.go diff --git a/go.mod b/go.mod index 4e76164b78d7a..40704dc731fff 100644 --- a/go.mod +++ b/go.mod @@ -95,6 +95,7 @@ require ( github.com/syndtr/goleveldb v1.0.0 github.com/thedevsaddam/renderer v1.2.0 github.com/tinylib/msgp v1.1.5 // indirect + github.com/tecbot/gorocksdb v0.0.0-20181010114359-8752a9433481 // indirect github.com/tstranex/u2f v1.0.0 github.com/ulikunitz/xz v0.5.8 // indirect github.com/unknwon/com v1.0.1 diff --git a/modules/context/context.go b/modules/context/context.go index 8215e386c42db..340e4e580d2de 100644 --- a/modules/context/context.go +++ b/modules/context/context.go @@ -30,8 +30,8 @@ import ( "gitea.com/macaron/macaron" "gitea.com/macaron/session" "github.com/alexedwards/scs/v2" - "github.com/thedevsaddam/renderer" "github.com/unknwon/com" + "github.com/unrolled/render" ) // flashes enumerates all the flash types @@ -53,7 +53,7 @@ type DefaultContext struct { Resp http.ResponseWriter Req *http.Request Data map[string]interface{} - Render *renderer.Render + Render *render.Render Sessions *scs.SessionManager translation.Locale flash *Flash diff --git a/routers/install.go b/routers/install.go index e6693aaa1e35a..eb8fa4f1aa12c 100644 --- a/routers/install.go +++ b/routers/install.go @@ -29,8 +29,9 @@ import ( "github.com/alexedwards/scs/v2" "github.com/go-chi/chi" - "github.com/thedevsaddam/renderer" + "github.com/unknwon/com" "github.com/unknwon/i18n" + "github.com/unrolled/render" "golang.org/x/text/language" "gopkg.in/ini.v1" ) @@ -76,14 +77,11 @@ type InstallContext = gitea_context.DefaultContext // InstallInit prepare for rendering installation page func InstallInit(next http.Handler, sessionManager *scs.SessionManager) http.Handler { - rnd := renderer.New( - renderer.Options{ - TemplateDir: "./templates", - TemplateExtension: ".tmpl", - //ParseGlobPattern: "templates/*.tmpl", - FuncMap: gitea_templates.NewFuncMap(), - }, - ) + rnd := render.New(render.Options{ + Directory: "templates", + Extensions: []string{".tmpl"}, + Funcs: gitea_templates.NewFuncMap(), + }) return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { if setting.InstallLock { @@ -93,7 +91,7 @@ func InstallInit(next http.Handler, sessionManager *scs.SessionManager) http.Han } var locale = Locale(resp, req) - + var startTime = time.Now() var ctx = InstallContext{ Resp: resp, Req: req, @@ -102,6 +100,11 @@ func InstallInit(next http.Handler, sessionManager *scs.SessionManager) http.Han "Title": locale.Tr("install.install"), "PageIsInstall": true, "DbOptions": setting.SupportedDatabases, + "i18n": locale, + "PageStartTime": startTime, + "TmplLoadTimes": func() string { + return time.Now().Sub(startTime).String() + }, }, Render: rnd, Sessions: sessionManager, @@ -226,7 +229,6 @@ func Install(ctx *InstallContext) { form.NoReplyAddress = setting.Service.NoReplyAddress auth.AssignForm(form, ctx.Data) - fmt.Println("-------", tplInstall, ctx.Data) _ = ctx.HTML(200, tplInstall) } diff --git a/vendor/github.com/thedevsaddam/renderer/.travis.yml b/vendor/github.com/thedevsaddam/renderer/.travis.yml deleted file mode 100644 index 5d452e7cbf6de..0000000000000 --- a/vendor/github.com/thedevsaddam/renderer/.travis.yml +++ /dev/null @@ -1,22 +0,0 @@ -language: go -sudo: false - -matrix: - include: - - go: 1.6 - - go: 1.7 - - go: 1.8 - - go: 1.9 - - go: 1.10.x - - go: 1.11.x - - go: tip - allow_failures: - - go: tip -before_install: - - go get github.com/mattn/goveralls -script: - - $GOPATH/bin/goveralls -service=travis-ci - - go get -t -v ./... - - diff -u <(echo -n) <(gofmt -d .) - - go vet $(go list ./... | grep -v /vendor/) - - go test -v -race ./... diff --git a/vendor/github.com/thedevsaddam/renderer/CONTRIBUTING.md b/vendor/github.com/thedevsaddam/renderer/CONTRIBUTING.md deleted file mode 100644 index 924384ce0139c..0000000000000 --- a/vendor/github.com/thedevsaddam/renderer/CONTRIBUTING.md +++ /dev/null @@ -1,12 +0,0 @@ -# Contributing - -## Must follow the guide for issues - - Use the search tool before opening a new issue. - - Please provide source code and stack trace if you found a bug. - - Please review the existing issues and provide feedback to them - -## Pull Request Process - - Open your pull request against `dev` branch - - It should pass all tests in the available continuous integrations systems such as TravisCI. - - You should add/modify tests to cover your proposed code changes. - - If your pull request contains a new feature, please document it on the README. diff --git a/vendor/github.com/thedevsaddam/renderer/LICENSE.md b/vendor/github.com/thedevsaddam/renderer/LICENSE.md deleted file mode 100644 index 5786a9421b13c..0000000000000 --- a/vendor/github.com/thedevsaddam/renderer/LICENSE.md +++ /dev/null @@ -1,21 +0,0 @@ -# The MIT License (MIT) - -Copyright (c) 2017 Saddam H - -> Permission is hereby granted, free of charge, to any person obtaining a copy -> of this software and associated documentation files (the "Software"), to deal -> in the Software without restriction, including without limitation the rights -> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -> copies of the Software, and to permit persons to whom the Software is -> furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in -> all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -> THE SOFTWARE. diff --git a/vendor/github.com/thedevsaddam/renderer/README.md b/vendor/github.com/thedevsaddam/renderer/README.md deleted file mode 100644 index 7bbfd5de7b869..0000000000000 --- a/vendor/github.com/thedevsaddam/renderer/README.md +++ /dev/null @@ -1,369 +0,0 @@ -Package renderer -================== -[![Build Status](https://travis-ci.org/thedevsaddam/renderer.svg?branch=master)](https://travis-ci.org/thedevsaddam/renderer) -[![Project status](https://img.shields.io/badge/version-1.2-green.svg)](https://github.com/thedevsaddam/renderer/releases) -[![Go Report Card](https://goreportcard.com/badge/github.com/thedevsaddam/renderer)](https://goreportcard.com/report/github.com/thedevsaddam/renderer) -[![Coverage Status](https://coveralls.io/repos/github/thedevsaddam/renderer/badge.svg?branch=master)](https://coveralls.io/github/thedevsaddam/renderer?branch=master) -[![GoDoc](https://godoc.org/github.com/thedevsaddam/renderer?status.svg)](https://godoc.org/github.com/thedevsaddam/renderer) -[![License](https://img.shields.io/dub/l/vibe-d.svg)](https://github.com/thedevsaddam/renderer/blob/dev/LICENSE.md) - -Simple, lightweight and faster response (JSON, JSONP, XML, YAML, HTML, File) rendering package for Go - -### Installation - -Install the package using -```go -$ go get github.com/thedevsaddam/renderer/... -``` - -### Usage - -To use the package import it in your `*.go` code -```go -import "github.com/thedevsaddam/renderer" -``` -### Example - -```go -package main - -import ( - "io" - "log" - "net/http" - "os" - - "github.com/thedevsaddam/renderer" -) - -func main() { - rnd := renderer.New() - - mux := http.NewServeMux() - - usr := struct { - Name string - Age int - }{"John Doe", 30} - - // serving String as text/plain - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - rnd.String(w, http.StatusOK, "Welcome to renderer") - }) - - // serving success but no content - mux.HandleFunc("/no-content", func(w http.ResponseWriter, r *http.Request) { - rnd.NoContent(w) - }) - - // serving string as html - mux.HandleFunc("/html-string", func(w http.ResponseWriter, r *http.Request) { - rnd.HTMLString(w, http.StatusOK, "

Hello Renderer!

") - }) - - // serving JSON - mux.HandleFunc("/json", func(w http.ResponseWriter, r *http.Request) { - rnd.JSON(w, http.StatusOK, usr) - }) - - // serving JSONP - mux.HandleFunc("/jsonp", func(w http.ResponseWriter, r *http.Request) { - rnd.JSONP(w, http.StatusOK, "callback", usr) - }) - - // serving XML - mux.HandleFunc("/xml", func(w http.ResponseWriter, r *http.Request) { - rnd.XML(w, http.StatusOK, usr) - }) - - // serving YAML - mux.HandleFunc("/yaml", func(w http.ResponseWriter, r *http.Request) { - rnd.YAML(w, http.StatusOK, usr) - }) - - // serving File as arbitary binary data - mux.HandleFunc("/binary", func(w http.ResponseWriter, r *http.Request) { - var reader io.Reader - reader, _ = os.Open("../README.md") - rnd.Binary(w, http.StatusOK, reader, "readme.md", true) - }) - - // serving File as inline - mux.HandleFunc("/file-inline", func(w http.ResponseWriter, r *http.Request) { - rnd.FileView(w, http.StatusOK, "../README.md", "readme.md") - }) - - // serving File as attachment - mux.HandleFunc("/file-download", func(w http.ResponseWriter, r *http.Request) { - rnd.FileDownload(w, http.StatusOK, "../README.md", "readme.md") - }) - - // serving File from reader as inline - mux.HandleFunc("/file-reader", func(w http.ResponseWriter, r *http.Request) { - var reader io.Reader - reader, _ = os.Open("../README.md") - rnd.File(w, http.StatusOK, reader, "readme.md", true) - }) - - // serving custom response using render and chaining methods - mux.HandleFunc("/render", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set(renderer.ContentType, renderer.ContentText) - rnd.Render(w, http.StatusOK, []byte("Send the message as text response")) - }) - - port := ":9000" - log.Println("Listening on port", port) - http.ListenAndServe(port, mux) -} - -``` - -### How to render html template? - -Well, you can parse html template using `HTML`, `View`, `Template` any of these method. These are based on `html/template` package. - -When using `Template` method you can simply pass the base layouts, templates path as a slice of string. - -***Template example*** - -You can parse template on the fly using `Template` method. You can set delimiter, inject FuncMap easily. - -template/layout.tmpl -```html - - - {{ template "title" . }} - - - {{ template "content" . }} - - {{ block "sidebar" .}}{{end}} - -``` -template/index.tmpl -```html -{{ define "title" }}Home{{ end }} - -{{ define "content" }} -

Hello, {{ .Name | toUpper }}

-

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

-{{ end }} -``` -template/partial.tmpl -```html -{{define "sidebar"}} - simple sidebar code -{{end}} - -``` - -template.go -```go -package main - -import ( - "html/template" - "log" - "net/http" - "strings" - - "github.com/thedevsaddam/renderer" -) - -var rnd *renderer.Render - -func init() { - rnd = renderer.New() -} - -func toUpper(s string) string { - return strings.ToUpper(s) -} - -func handler(w http.ResponseWriter, r *http.Request) { - usr := struct { - Name string - Age int - }{"john doe", 30} - - tpls := []string{"template/layout.tmpl", "template/index.tmpl", "template/partial.tmpl"} - rnd.FuncMap(template.FuncMap{ - "toUpper": toUpper, - }) - err := rnd.Template(w, http.StatusOK, tpls, usr) - if err != nil { - log.Fatal(err) //respond with error page or message - } -} - -func main() { - http.HandleFunc("/", handler) - log.Println("Listening port: 9000") - http.ListenAndServe(":9000", nil) -} -``` - -***HTML example*** - -When using `HTML` you can parse a template directory using `pattern` and call the template by their name. See the example code below: - -html/index.html -```html -{{define "indexPage"}} - - {{template "header"}} - -

Index

-

Lorem ipsum dolor sit amet, consectetur adipisicing elit

- - {{template "footer"}} - -{{end}} -``` - -html/header.html -```html -{{define "header"}} - - Header -

Header section

- -{{end}} -``` - -html/footer.html -```html -{{define "footer"}} -
Copyright © 2020
-{{end}} -``` - -html.go -```go -package main - -import ( - "log" - "net/http" - - "github.com/thedevsaddam/renderer" -) - -var rnd *renderer.Render - -func init() { - rnd = renderer.New( - renderer.Options{ - ParseGlobPattern: "html/*.html", - }, - ) -} - -func handler(w http.ResponseWriter, r *http.Request) { - err := rnd.HTML(w, http.StatusOK, "indexPage", nil) - if err != nil { - log.Fatal(err) - } -} - -func main() { - http.HandleFunc("/", handler) - log.Println("Listening port: 9000") - http.ListenAndServe(":9000", nil) -} -``` - -***View example*** - -When using `View` for parsing template you can pass multiple layout and templates. Here template name will be the file name. See the example to get the idea. - -view/base.lout -```html - - - {{block "title" .}} {{end}} - - - {{ template "content" . }} - - -``` - -view/home.tpl -```html -{{define "title"}}Home{{end}} -{{define "content"}} -

Home page

- -

- Lorem ipsum dolor sit amet

-{{end}} -``` -view/about.tpl -```html -{{define "title"}}About Me{{end}} -{{define "content"}} -

This is About me page.

-
    - Lorem ipsum dolor sit amet, consectetur adipisicing elit, -
-

Home

-{{end}} -``` - -view.go -```go -package main - -import ( - "log" - "net/http" - - "github.com/thedevsaddam/renderer" -) - -var rnd *renderer.Render - -func init() { - rnd = renderer.New(renderer.Options{ - TemplateDir: "view", - }) -} - -func home(w http.ResponseWriter, r *http.Request) { - err := rnd.View(w, http.StatusOK, "home", nil) - if err != nil { - log.Fatal(err) - } -} - -func about(w http.ResponseWriter, r *http.Request) { - err := rnd.View(w, http.StatusOK, "about", nil) - if err != nil { - log.Fatal(err) - } -} - -func main() { - http.HandleFunc("/", home) - http.HandleFunc("/about", about) - log.Println("Listening port: 9000\n / is root \n /about is about page") - http.ListenAndServe(":9000", nil) -} -``` - -***Note:*** This is a wrapper on top of go built-in packages to provide syntactic sugar. - -### Contribution -Your suggestions will be more than appreciated. -[Read the contribution guide here](CONTRIBUTING.md) - -### See all [contributors](https://github.com/thedevsaddam/renderer/graphs/contributors) - -### Read [API doc](https://godoc.org/github.com/thedevsaddam/renderer) to know about ***Available options and Methods*** - -### **License** -The **renderer** is an open-source software licensed under the [MIT License](LICENSE.md). diff --git a/vendor/github.com/thedevsaddam/renderer/renderer.go b/vendor/github.com/thedevsaddam/renderer/renderer.go deleted file mode 100644 index 900d189897f4a..0000000000000 --- a/vendor/github.com/thedevsaddam/renderer/renderer.go +++ /dev/null @@ -1,586 +0,0 @@ -// Copyright @2017 Saddam Hossain. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. - -// Package renderer implements frequently usages response render methods like JSON, JSONP, XML, YAML, HTML, FILE etc -// This package is useful when building REST api and to provide response to consumer - -// Package renderer documentaton contains the API for this package please follow the link below -package renderer - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "errors" - "fmt" - "html/template" - "io" - "io/ioutil" - "log" - "net/http" - "os" - "path/filepath" - "strings" - - yaml "gopkg.in/yaml.v2" -) - -const ( - // ContentType represents content type - ContentType string = "Content-Type" - // ContentJSON represents content type application/json - ContentJSON string = "application/json" - // ContentJSONP represents content type application/javascript - ContentJSONP string = "application/javascript" - // ContentXML represents content type application/xml - ContentXML string = "application/xml" - // ContentYAML represents content type application/x-yaml - ContentYAML string = "application/x-yaml" - // ContentHTML represents content type text/html - ContentHTML string = "text/html" - // ContentText represents content type text/plain - ContentText string = "text/plain" - // ContentBinary represents content type application/octet-stream - ContentBinary string = "application/octet-stream" - - // ContentDisposition describes contentDisposition - ContentDisposition string = "Content-Disposition" - // contentDispositionInline describes content disposition type - contentDispositionInline string = "inline" - // contentDispositionAttachment describes content disposition type - contentDispositionAttachment string = "attachment" - - defaultCharSet string = "utf-8" - defaultJSONPrefix string = "" - defaultXMLPrefix string = `\n` - defaultTemplateExt string = "tpl" - defaultLayoutExt string = "lout" - defaultTemplateLeftDelim string = "{{" - defaultTemplateRightDelim string = "}}" -) - -type ( - // M describes handy type that represents data to send as response - M map[string]interface{} - - // Options describes an option type - Options struct { - // Charset represents the Response charset; default: utf-8 - Charset string - // ContentJSON represents the Content-Type for JSON - ContentJSON string - // ContentJSONP represents the Content-Type for JSONP - ContentJSONP string - // ContentXML represents the Content-Type for XML - ContentXML string - // ContentYAML represents the Content-Type for YAML - ContentYAML string - // ContentHTML represents the Content-Type for HTML - ContentHTML string - // ContentText represents the Content-Type for Text - ContentText string - // ContentBinary represents the Content-Type for octet-stream - ContentBinary string - - // UnEscapeHTML set UnEscapeHTML for JSON; default false - UnEscapeHTML bool - // DisableCharset set DisableCharset in Response Content-Type - DisableCharset bool - // Debug set the debug mode. if debug is true then every time "VIEW" call parse the templates - Debug bool - // JSONIndent set JSON Indent in response; default false - JSONIndent bool - // XMLIndent set XML Indent in response; default false - XMLIndent bool - - // JSONPrefix set Prefix in JSON response - JSONPrefix string - // XMLPrefix set Prefix in XML response - XMLPrefix string - - // TemplateDir set the Template directory - TemplateDir string - // TemplateExtension set the Template extension - TemplateExtension string - // LeftDelim set template left delimiter default is {{ - LeftDelim string - // RightDelim set template right delimiter default is }} - RightDelim string - // LayoutExtension set the Layout extension - LayoutExtension string - // FuncMap contain function map for template - FuncMap []template.FuncMap - // ParseGlobPattern contain parse glob pattern - ParseGlobPattern string - } - - // Render describes a renderer type - Render struct { - opts Options - templates map[string]*template.Template - globTemplates *template.Template - headers map[string]string - } -) - -// New return a new instance of a pointer to Render -func New(opts ...Options) *Render { - var opt Options - if opts != nil { - opt = opts[0] - } - - r := &Render{ - opts: opt, - templates: make(map[string]*template.Template), - } - - // build options for the Render instance - r.buildOptions() - - // if TemplateDir is not empty then call the parseTemplates - if r.opts.TemplateDir != "" { - r.parseTemplates() - } - - // ParseGlobPattern is not empty then parse template with pattern - if r.opts.ParseGlobPattern != "" { - r.parseGlob() - } - - return r -} - -// buildOptions builds the options and set deault values for options -func (r *Render) buildOptions() { - if r.opts.Charset == "" { - r.opts.Charset = defaultCharSet - } - - if r.opts.JSONPrefix == "" { - r.opts.JSONPrefix = defaultJSONPrefix - } - - if r.opts.XMLPrefix == "" { - r.opts.XMLPrefix = defaultXMLPrefix - } - - if r.opts.TemplateExtension == "" { - r.opts.TemplateExtension = "." + defaultTemplateExt - } else { - r.opts.TemplateExtension = "." + r.opts.TemplateExtension - } - - if r.opts.LayoutExtension == "" { - r.opts.LayoutExtension = "." + defaultLayoutExt - } else { - r.opts.LayoutExtension = "." + r.opts.LayoutExtension - } - - if r.opts.LeftDelim == "" { - r.opts.LeftDelim = defaultTemplateLeftDelim - } - - if r.opts.RightDelim == "" { - r.opts.RightDelim = defaultTemplateRightDelim - } - - r.opts.ContentJSON = ContentJSON - r.opts.ContentJSONP = ContentJSONP - r.opts.ContentXML = ContentXML - r.opts.ContentYAML = ContentYAML - r.opts.ContentHTML = ContentHTML - r.opts.ContentText = ContentText - r.opts.ContentBinary = ContentBinary - - if !r.opts.DisableCharset { - r.enableCharset() - } -} - -func (r *Render) enableCharset() { - r.opts.ContentJSON = fmt.Sprintf("%s; charset=%s", r.opts.ContentJSON, r.opts.Charset) - r.opts.ContentJSONP = fmt.Sprintf("%s; charset=%s", r.opts.ContentJSONP, r.opts.Charset) - r.opts.ContentXML = fmt.Sprintf("%s; charset=%s", r.opts.ContentXML, r.opts.Charset) - r.opts.ContentYAML = fmt.Sprintf("%s; charset=%s", r.opts.ContentYAML, r.opts.Charset) - r.opts.ContentHTML = fmt.Sprintf("%s; charset=%s", r.opts.ContentHTML, r.opts.Charset) - r.opts.ContentText = fmt.Sprintf("%s; charset=%s", r.opts.ContentText, r.opts.Charset) - r.opts.ContentBinary = fmt.Sprintf("%s; charset=%s", r.opts.ContentBinary, r.opts.Charset) -} - -// DisableCharset change the DisableCharset for JSON on the fly -func (r *Render) DisableCharset(b bool) *Render { - r.opts.DisableCharset = b - if !b { - r.buildOptions() - } - return r -} - -// JSONIndent change the JSONIndent for JSON on the fly -func (r *Render) JSONIndent(b bool) *Render { - r.opts.JSONIndent = b - return r -} - -// XMLIndent change the XMLIndent for XML on the fly -func (r *Render) XMLIndent(b bool) *Render { - r.opts.XMLIndent = b - return r -} - -// Charset change the Charset for response on the fly -func (r *Render) Charset(c string) *Render { - r.opts.Charset = c - return r -} - -// EscapeHTML change the EscapeHTML for JSON on the fly -func (r *Render) EscapeHTML(b bool) *Render { - r.opts.UnEscapeHTML = b - return r -} - -// Delims set template delimiter on the fly -func (r *Render) Delims(left, right string) *Render { - r.opts.LeftDelim = left - r.opts.RightDelim = right - return r -} - -// FuncMap set template FuncMap on the fly -func (r *Render) FuncMap(fmap template.FuncMap) *Render { - r.opts.FuncMap = append(r.opts.FuncMap, fmap) - return r -} - -// NoContent serve success but no content response -func (r *Render) NoContent(w http.ResponseWriter) error { - w.WriteHeader(http.StatusNoContent) - return nil -} - -// Render serve raw response where you have to build the headers, body -func (r *Render) Render(w http.ResponseWriter, status int, v interface{}) error { - w.WriteHeader(status) - _, err := w.Write(v.([]byte)) - return err -} - -// String serve string content as text/plain response -func (r *Render) String(w http.ResponseWriter, status int, v interface{}) error { - w.Header().Set(ContentType, r.opts.ContentText) - w.WriteHeader(status) - _, err := w.Write([]byte(v.(string))) - return err -} - -// json converts the data as bytes using json encoder -func (r *Render) json(v interface{}) ([]byte, error) { - var bs []byte - var err error - if r.opts.JSONIndent { - bs, err = json.MarshalIndent(v, "", " ") - } else { - bs, err = json.Marshal(v) - } - if err != nil { - return bs, err - } - if r.opts.UnEscapeHTML { - bs = bytes.Replace(bs, []byte("\\u003c"), []byte("<"), -1) - bs = bytes.Replace(bs, []byte("\\u003e"), []byte(">"), -1) - bs = bytes.Replace(bs, []byte("\\u0026"), []byte("&"), -1) - } - return bs, nil -} - -// JSON serve data as JSON as response -func (r *Render) JSON(w http.ResponseWriter, status int, v interface{}) error { - w.Header().Set(ContentType, r.opts.ContentJSON) - w.WriteHeader(status) - - bs, err := r.json(v) - if err != nil { - return err - } - if r.opts.JSONPrefix != "" { - w.Write([]byte(r.opts.JSONPrefix)) - } - _, err = w.Write(bs) - return err -} - -// JSONP serve data as JSONP response -func (r *Render) JSONP(w http.ResponseWriter, status int, callback string, v interface{}) error { - w.Header().Set(ContentType, r.opts.ContentJSONP) - w.WriteHeader(status) - - bs, err := r.json(v) - if err != nil { - return err - } - - if callback == "" { - return errors.New("renderer: callback can not bet empty") - } - - w.Write([]byte(callback + "(")) - _, err = w.Write(bs) - w.Write([]byte(");")) - - return err -} - -// XML serve data as XML response -func (r *Render) XML(w http.ResponseWriter, status int, v interface{}) error { - w.Header().Set(ContentType, r.opts.ContentXML) - w.WriteHeader(status) - var bs []byte - var err error - - if r.opts.XMLIndent { - bs, err = xml.MarshalIndent(v, "", " ") - } else { - bs, err = xml.Marshal(v) - } - if err != nil { - return err - } - if r.opts.XMLPrefix != "" { - w.Write([]byte(r.opts.XMLPrefix)) - } - _, err = w.Write(bs) - return err -} - -// YAML serve data as YAML response -func (r *Render) YAML(w http.ResponseWriter, status int, v interface{}) error { - w.Header().Set(ContentType, r.opts.ContentYAML) - w.WriteHeader(status) - - bs, err := yaml.Marshal(v) - if err != nil { - return err - } - _, err = w.Write(bs) - return err -} - -// HTMLString render string as html. Note: You must provide trusted html when using this method -func (r *Render) HTMLString(w http.ResponseWriter, status int, html string) error { - w.Header().Set(ContentType, r.opts.ContentHTML) - w.WriteHeader(status) - out := template.HTML(html) - _, err := w.Write([]byte(out)) - return err -} - -// HTML render html from template.Glob patterns and execute template by name. See README.md for detail example. -func (r *Render) HTML(w http.ResponseWriter, status int, name string, v interface{}) error { - w.Header().Set(ContentType, r.opts.ContentHTML) - w.WriteHeader(status) - - if name == "" { - return errors.New("renderer: template name not exist") - } - - if r.opts.Debug { - r.parseGlob() - } - - buf := new(bytes.Buffer) - defer buf.Reset() - - if err := r.globTemplates.ExecuteTemplate(buf, name, v); err != nil { - return err - } - _, err := w.Write(buf.Bytes()) - return err -} - -// Template build html from template and serve html content as response. See README.md for detail example. -func (r *Render) Template(w http.ResponseWriter, status int, tpls []string, v interface{}) error { - w.Header().Set(ContentType, r.opts.ContentHTML) - w.WriteHeader(status) - - tmain := template.New(filepath.Base(tpls[0])) - tmain.Delims(r.opts.LeftDelim, r.opts.RightDelim) - for _, fm := range r.opts.FuncMap { - tmain.Funcs(fm) - } - t := template.Must(tmain.ParseFiles(tpls...)) - - buf := new(bytes.Buffer) - defer buf.Reset() - - if err := t.Execute(buf, v); err != nil { - return err - } - _, err := w.Write(buf.Bytes()) - return err -} - -// View build html from template directory and serve html content as response. See README.md for detail example. -func (r *Render) View(w http.ResponseWriter, status int, name string, v interface{}) error { - w.Header().Set(ContentType, r.opts.ContentHTML) - w.WriteHeader(status) - - buf := new(bytes.Buffer) - defer buf.Reset() - - if r.opts.Debug { - r.parseTemplates() - } - - name += r.opts.TemplateExtension - tmpl, ok := r.templates[name] - if !ok { - return fmt.Errorf("renderer: template %s does not exist", name) - } - - if err := tmpl.Execute(buf, v); err != nil { - return err - } - - _, err := w.Write(buf.Bytes()) - return err -} - -// Binary serve file as application/octet-stream response; you may add ContentDisposition by your own. -func (r *Render) Binary(w http.ResponseWriter, status int, reader io.Reader, filename string, inline bool) error { - if inline { - w.Header().Set(ContentDisposition, fmt.Sprintf("%s; filename=%s", contentDispositionInline, filename)) - } else { - w.Header().Set(ContentDisposition, fmt.Sprintf("%s; filename=%s", contentDispositionAttachment, filename)) - } - w.Header().Set(ContentType, r.opts.ContentBinary) - w.WriteHeader(status) - bs, err := ioutil.ReadAll(reader) - if err != nil { - return err - } - - _, err = w.Write(bs) - return err -} - -// File serve file as response from io.Reader -func (r *Render) File(w http.ResponseWriter, status int, reader io.Reader, filename string, inline bool) error { - bs, err := ioutil.ReadAll(reader) - if err != nil { - return err - } - - // set headers - mime := http.DetectContentType(bs) - if inline { - w.Header().Set(ContentDisposition, fmt.Sprintf("%s; filename=%s", contentDispositionInline, filename)) - } else { - w.Header().Set(ContentDisposition, fmt.Sprintf("%s; filename=%s", contentDispositionAttachment, filename)) - } - w.Header().Set(ContentType, mime) - w.WriteHeader(status) - - _, err = w.Write(bs) - return err -} - -// file serve file as response -func (r *Render) file(w http.ResponseWriter, status int, fpath, name, contentDisposition string) error { - var bs []byte - var err error - bs, err = ioutil.ReadFile(fpath) - if err != nil { - return err - } - buf := bytes.NewBuffer(bs) - - // filename, ext, mimes - var fn, mime, ext string - fn, err = filepath.Abs(fpath) - ext = filepath.Ext(fpath) - if name != "" { - if !strings.HasSuffix(name, ext) { - fn = name + ext - } - } - - mime = http.DetectContentType(bs) - - // set headers - w.Header().Set(ContentType, mime) - w.Header().Set(ContentDisposition, fmt.Sprintf("%s; filename=%s", contentDisposition, fn)) - w.WriteHeader(status) - - if _, err = buf.WriteTo(w); err != nil { - return err - } - - _, err = w.Write(buf.Bytes()) - return err -} - -// FileView serve file as response with content-disposition value inline -func (r *Render) FileView(w http.ResponseWriter, status int, fpath, name string) error { - return r.file(w, status, fpath, name, contentDispositionInline) -} - -// FileDownload serve file as response with content-disposition value attachment -func (r *Render) FileDownload(w http.ResponseWriter, status int, fpath, name string) error { - return r.file(w, status, fpath, name, contentDispositionAttachment) -} - -// parseTemplates parse all the template in the directory -func (r *Render) parseTemplates() { - layouts, err := filepath.Glob(filepath.Join(r.opts.TemplateDir, "*"+r.opts.LayoutExtension)) - if err != nil { - panic(fmt.Errorf("renderer: %s", err.Error())) - } - - tpls, err := filepath.Glob(filepath.Join(r.opts.TemplateDir, "*"+r.opts.TemplateExtension)) - if err != nil { - panic(fmt.Errorf("renderer: %s", err.Error())) - } - - for _, tpl := range tpls { - files := append(layouts, tpl) - fn := filepath.Base(tpl) - // TODO: add FuncMap and Delims - // tmpl := template.New(fn) - // tmpl.Delims(r.opts.LeftDelim, r.opts.RightDelim) - // for _, fm := range r.opts.FuncMap { - // tmpl.Funcs(fm) - // } - r.templates[fn] = template.Must(template.ParseFiles(files...)) - } -} - -// parseGlob parse templates using ParseGlob -func (r *Render) parseGlob() { - tmpl := template.New("") - tmpl.Delims(r.opts.LeftDelim, r.opts.RightDelim) - for _, fm := range r.opts.FuncMap { - tmpl.Funcs(fm) - } - if !strings.Contains(r.opts.ParseGlobPattern, "*.") { - log.Fatal("renderer: invalid glob pattern!") - } - pf := strings.Split(r.opts.ParseGlobPattern, "*") - fPath := pf[0] - fExt := pf[1] - err := filepath.Walk(fPath, func(path string, info os.FileInfo, err error) error { - if strings.Contains(path, fExt) { - _, err = tmpl.ParseFiles(path) - if err != nil { - log.Println(err) - } - } - return err - }) - if err != nil { - log.Fatal(err) - } - r.globTemplates = tmpl -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 075a4ac179371..3aa47f6835925 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -736,10 +736,17 @@ github.com/syndtr/goleveldb/leveldb/opt github.com/syndtr/goleveldb/leveldb/storage github.com/syndtr/goleveldb/leveldb/table github.com/syndtr/goleveldb/leveldb/util +<<<<<<< HEAD # github.com/thedevsaddam/renderer v1.2.0 ## explicit github.com/thedevsaddam/renderer # github.com/tinylib/msgp v1.1.5 +======= +# github.com/tinylib/msgp v1.1.5 +# github.com/tecbot/gorocksdb v0.0.0-20181010114359-8752a9433481 +## explicit +# github.com/tinylib/msgp v1.1.2 +>>>>>>> 2af2659f2... Use github.com/unrolled/render as render ## explicit github.com/tinylib/msgp/msgp # github.com/toqueteos/webbrowser v1.2.0 From 4a61fdcd2325138c125e973719cb92e59bedab06 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 17 Nov 2020 16:39:55 +0800 Subject: [PATCH 14/23] Move default context to a standalone file --- modules/context/context.go | 98 -------------------------------- modules/context/default.go | 111 +++++++++++++++++++++++++++++++++++++ routers/install.go | 1 - 3 files changed, 111 insertions(+), 99 deletions(-) create mode 100644 modules/context/default.go diff --git a/modules/context/context.go b/modules/context/context.go index 340e4e580d2de..1ee31e0ebbac3 100644 --- a/modules/context/context.go +++ b/modules/context/context.go @@ -21,7 +21,6 @@ import ( "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" - "code.gitea.io/gitea/modules/translation" "code.gitea.io/gitea/modules/util" "gitea.com/macaron/cache" @@ -29,106 +28,9 @@ import ( "gitea.com/macaron/i18n" "gitea.com/macaron/macaron" "gitea.com/macaron/session" - "github.com/alexedwards/scs/v2" "github.com/unknwon/com" - "github.com/unrolled/render" ) -// flashes enumerates all the flash types -const ( - SuccessFlash = "success" - ErrorFlash = "error" - WarnFlash = "warning" - InfoFlash = "info" -) - -// Flash represents flashs -type Flash struct { - MessageType string - Message string -} - -// DefaultContext represents a context for basic routes -type DefaultContext struct { - Resp http.ResponseWriter - Req *http.Request - Data map[string]interface{} - Render *render.Render - Sessions *scs.SessionManager - translation.Locale - flash *Flash -} - -// HTML wraps render HTML -func (ctx *DefaultContext) HTML(statusCode int, tmpl string) error { - return ctx.Render.HTML(ctx.Resp, statusCode, tmpl, ctx.Data) -} - -// HasError returns true if error occurs in form validation. -func (ctx *DefaultContext) HasError() bool { - hasErr, ok := ctx.Data["HasError"] - if !ok { - return false - } - return hasErr.(bool) -} - -// HasValue returns true if value of given name exists. -func (ctx *DefaultContext) HasValue(name string) bool { - _, ok := ctx.Data[name] - return ok -} - -// RenderWithErr used for page has form validation but need to prompt error to users. -func (ctx *DefaultContext) RenderWithErr(msg string, tpl string, form interface{}) { - if form != nil { - auth.AssignForm(form, ctx.Data) - } - ctx.Flash(ErrorFlash, msg) - _ = ctx.HTML(200, tpl) -} - -// SetSession sets session key value -func (ctx *DefaultContext) SetSession(key string, val interface{}) error { - ctx.Sessions.Put(ctx.Req.Context(), key, val) - return nil -} - -// GetSession gets session via key -func (ctx *DefaultContext) GetSession(key string) (interface{}, error) { - v := ctx.Sessions.Get(ctx.Req.Context(), key) - return v, nil -} - -// DestroySession deletes all the data of the session -func (ctx *DefaultContext) DestroySession() error { - return ctx.Sessions.Destroy(ctx.Req.Context()) -} - -// Flash set message to flash -func (ctx *DefaultContext) Flash(tp, v string) { - if ctx.flash == nil { - ctx.flash = &Flash{} - } - ctx.flash.MessageType = tp - ctx.flash.Message = v - ctx.Data["Flash"] = ctx.flash -} - -// NewCookie creates a cookie -func NewCookie(name, value string, maxAge int) *http.Cookie { - return &http.Cookie{ - Name: name, - Value: value, - HttpOnly: true, - Path: setting.SessionConfig.CookiePath, - Domain: setting.SessionConfig.Domain, - MaxAge: maxAge, - Secure: setting.SessionConfig.Secure, - //SameSite: , - } -} - // Context represents context of a request. type Context struct { *macaron.Context diff --git a/modules/context/default.go b/modules/context/default.go new file mode 100644 index 0000000000000..63bf89dd93a27 --- /dev/null +++ b/modules/context/default.go @@ -0,0 +1,111 @@ +// Copyright 2020 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package context + +import ( + "net/http" + + "code.gitea.io/gitea/modules/auth" + "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/translation" + + "github.com/alexedwards/scs/v2" + "github.com/unrolled/render" +) + +// flashes enumerates all the flash types +const ( + SuccessFlash = "success" + ErrorFlash = "error" + WarnFlash = "warning" + InfoFlash = "info" +) + +// Flash represents flashs +type Flash struct { + MessageType string + Message string +} + +// DefaultContext represents a context for basic routes, all other context should +// be derived from the context but not add more fields on this context +type DefaultContext struct { + Resp http.ResponseWriter + Req *http.Request + Data map[string]interface{} + Render *render.Render + Sessions *scs.SessionManager + translation.Locale + flash *Flash +} + +// HTML wraps render HTML +func (ctx *DefaultContext) HTML(statusCode int, tmpl string) error { + return ctx.Render.HTML(ctx.Resp, statusCode, tmpl, ctx.Data) +} + +// HasError returns true if error occurs in form validation. +func (ctx *DefaultContext) HasError() bool { + hasErr, ok := ctx.Data["HasError"] + if !ok { + return false + } + return hasErr.(bool) +} + +// HasValue returns true if value of given name exists. +func (ctx *DefaultContext) HasValue(name string) bool { + _, ok := ctx.Data[name] + return ok +} + +// RenderWithErr used for page has form validation but need to prompt error to users. +func (ctx *DefaultContext) RenderWithErr(msg string, tpl string, form interface{}) { + if form != nil { + auth.AssignForm(form, ctx.Data) + } + ctx.Flash(ErrorFlash, msg) + _ = ctx.HTML(200, tpl) +} + +// SetSession sets session key value +func (ctx *DefaultContext) SetSession(key string, val interface{}) error { + ctx.Sessions.Put(ctx.Req.Context(), key, val) + return nil +} + +// GetSession gets session via key +func (ctx *DefaultContext) GetSession(key string) (interface{}, error) { + v := ctx.Sessions.Get(ctx.Req.Context(), key) + return v, nil +} + +// DestroySession deletes all the data of the session +func (ctx *DefaultContext) DestroySession() error { + return ctx.Sessions.Destroy(ctx.Req.Context()) +} + +// Flash set message to flash +func (ctx *DefaultContext) Flash(tp, v string) { + if ctx.flash == nil { + ctx.flash = &Flash{} + } + ctx.flash.MessageType = tp + ctx.flash.Message = v + ctx.Data["Flash"] = ctx.flash +} + +// NewCookie creates a cookie +func NewCookie(name, value string, maxAge int) *http.Cookie { + return &http.Cookie{ + Name: name, + Value: value, + HttpOnly: true, + Path: setting.SessionConfig.CookiePath, + Domain: setting.SessionConfig.Domain, + MaxAge: maxAge, + Secure: setting.SessionConfig.Secure, + } +} diff --git a/routers/install.go b/routers/install.go index eb8fa4f1aa12c..0b60179197e21 100644 --- a/routers/install.go +++ b/routers/install.go @@ -58,7 +58,6 @@ func InstallRoutes() http.Handler { Path: setting.SessionConfig.CookiePath, Persist: true, Secure: setting.SessionConfig.Secure, - //SameSite: setting.SessionConfig., } r.Use(sessionManager.LoadAndSave) r.Use(func(next http.Handler) http.Handler { From 9ae736795bd98b06634c06a760de2eea6fd7894f Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 17 Nov 2020 23:28:00 +0800 Subject: [PATCH 15/23] Move sessions to context --- modules/context/default.go | 53 ++++++++++++++++++++++++++++++++++++++ routers/install.go | 53 +++----------------------------------- 2 files changed, 57 insertions(+), 49 deletions(-) diff --git a/modules/context/default.go b/modules/context/default.go index 63bf89dd93a27..69005c5a4ff96 100644 --- a/modules/context/default.go +++ b/modules/context/default.go @@ -6,12 +6,15 @@ package context import ( "net/http" + "time" "code.gitea.io/gitea/modules/auth" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/translation" + "golang.org/x/text/language" "github.com/alexedwards/scs/v2" + "github.com/unknwon/i18n" "github.com/unrolled/render" ) @@ -97,6 +100,56 @@ func (ctx *DefaultContext) Flash(tp, v string) { ctx.Data["Flash"] = ctx.flash } +// NewSessions creates a session manager +func NewSessions() *scs.SessionManager { + sessionManager := scs.New() + sessionManager.Lifetime = time.Duration(setting.SessionConfig.Maxlifetime) + sessionManager.Cookie = scs.SessionCookie{ + Name: setting.SessionConfig.CookieName, + Domain: setting.SessionConfig.Domain, + HttpOnly: true, + Path: setting.SessionConfig.CookiePath, + Persist: true, + Secure: setting.SessionConfig.Secure, + } + return sessionManager +} + +// Locale handle locale +func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale { + hasCookie := false + + // 1. Check URL arguments. + lang := req.URL.Query().Get("lang") + + // 2. Get language information from cookies. + if len(lang) == 0 { + ck, _ := req.Cookie("lang") + lang = ck.Value + hasCookie = true + } + + // Check again in case someone modify by purpose. + if !i18n.IsExist(lang) { + lang = "" + hasCookie = false + } + + // 3. Get language information from 'Accept-Language'. + // The first element in the list is chosen to be the default language automatically. + if len(lang) == 0 { + tags, _, _ := language.ParseAcceptLanguage(req.Header.Get("Accept-Language")) + tag, _, _ := translation.Match(tags...) + lang = tag.String() + } + + if !hasCookie { + req.AddCookie(NewCookie("lang", lang, 1<<31-1)) + } + + return translation.NewLocale(lang) +} + // NewCookie creates a cookie func NewCookie(name, value string, maxAge int) *http.Cookie { return &http.Cookie{ diff --git a/routers/install.go b/routers/install.go index 0b60179197e21..16b0f240cb179 100644 --- a/routers/install.go +++ b/routers/install.go @@ -23,16 +23,13 @@ import ( "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" gitea_templates "code.gitea.io/gitea/modules/templates" - "code.gitea.io/gitea/modules/translation" "code.gitea.io/gitea/modules/user" "code.gitea.io/gitea/modules/util" "github.com/alexedwards/scs/v2" "github.com/go-chi/chi" "github.com/unknwon/com" - "github.com/unknwon/i18n" "github.com/unrolled/render" - "golang.org/x/text/language" "gopkg.in/ini.v1" ) @@ -49,16 +46,7 @@ var ( // InstallRoutes represents the install routes func InstallRoutes() http.Handler { r := chi.NewRouter() - sessionManager := scs.New() - sessionManager.Lifetime = time.Duration(setting.SessionConfig.Maxlifetime) - sessionManager.Cookie = scs.SessionCookie{ - Name: setting.SessionConfig.CookieName, - Domain: setting.SessionConfig.Domain, - HttpOnly: true, - Path: setting.SessionConfig.CookiePath, - Persist: true, - Secure: setting.SessionConfig.Secure, - } + sessionManager := gitea_context.NewSessions() r.Use(sessionManager.LoadAndSave) r.Use(func(next http.Handler) http.Handler { return InstallInit(next, sessionManager) @@ -89,7 +77,7 @@ func InstallInit(next http.Handler, sessionManager *scs.SessionManager) http.Han return } - var locale = Locale(resp, req) + var locale = gitea_context.Locale(resp, req) var startTime = time.Now() var ctx = InstallContext{ Resp: resp, @@ -100,6 +88,8 @@ func InstallInit(next http.Handler, sessionManager *scs.SessionManager) http.Han "PageIsInstall": true, "DbOptions": setting.SupportedDatabases, "i18n": locale, + "Language": locale.Language(), + "CurrentURL": setting.AppSubURL + req.URL.RequestURI(), "PageStartTime": startTime, "TmplLoadTimes": func() string { return time.Now().Sub(startTime).String() @@ -114,41 +104,6 @@ func InstallInit(next http.Handler, sessionManager *scs.SessionManager) http.Han }) } -// Locale handle locale -func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale { - hasCookie := false - - // 1. Check URL arguments. - lang := req.URL.Query().Get("lang") - - // 2. Get language information from cookies. - if len(lang) == 0 { - ck, _ := req.Cookie("lang") - lang = ck.Value - hasCookie = true - } - - // Check again in case someone modify by purpose. - if !i18n.IsExist(lang) { - lang = "" - hasCookie = false - } - - // 3. Get language information from 'Accept-Language'. - // The first element in the list is chosen to be the default language automatically. - if len(lang) == 0 { - tags, _, _ := language.ParseAcceptLanguage(req.Header.Get("Accept-Language")) - tag, _, _ := translation.Match(tags...) - lang = tag.String() - } - - if !hasCookie { - req.AddCookie(gitea_context.NewCookie("lang", lang, 1<<31-1)) - } - - return translation.NewLocale(lang) -} - // WrapInstall converts an install route to a chi route func WrapInstall(f func(ctx *InstallContext)) http.HandlerFunc { return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { From 76600f85806f04fe092c89a8b6da06694edce7e5 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 24 Nov 2020 08:03:26 +0800 Subject: [PATCH 16/23] Fix lint --- routers/install.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/routers/install.go b/routers/install.go index 16b0f240cb179..8c62a76b7a396 100644 --- a/routers/install.go +++ b/routers/install.go @@ -92,7 +92,7 @@ func InstallInit(next http.Handler, sessionManager *scs.SessionManager) http.Han "CurrentURL": setting.AppSubURL + req.URL.RequestURI(), "PageStartTime": startTime, "TmplLoadTimes": func() string { - return time.Now().Sub(startTime).String() + return time.Since(startTime).String() }, }, Render: rnd, From e0ec551f1037c22a2c08e43d5076cb78eb0884f3 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sun, 29 Nov 2020 22:00:02 +0800 Subject: [PATCH 17/23] Add binding --- go.mod | 1 + modules/auth/user_form.go | 54 - modules/context/default.go | 29 +- modules/context/install.go | 27 + modules/forms/forms.go | 139 ++ modules/forms/install.go | 68 + modules/middlewares/binding/README.md | 5 + modules/middlewares/binding/bind_test.go | 57 + modules/middlewares/binding/binding.go | 708 +++++++++ modules/middlewares/binding/common_test.go | 127 ++ .../middlewares/binding/errorhandler_test.go | 162 ++ modules/middlewares/binding/errors.go | 159 ++ modules/middlewares/binding/errors_test.go | 115 ++ modules/middlewares/binding/file_test.go | 191 +++ modules/middlewares/binding/form_test.go | 282 ++++ modules/middlewares/binding/json_test.go | 240 +++ modules/middlewares/binding/misc_test.go | 123 ++ modules/middlewares/binding/multipart_test.go | 155 ++ modules/middlewares/binding/validate_test.go | 412 +++++ routers/install.go | 40 +- routers/routes/macaron.go | 2 - templates/base/alert_new.tmpl | 15 + templates/install.tmpl | 2 +- vendor/github.com/gopherjs/gopherjs/LICENSE | 24 + vendor/github.com/gopherjs/gopherjs/js/js.go | 168 ++ vendor/github.com/jtolds/gls/LICENSE | 18 + vendor/github.com/jtolds/gls/README.md | 89 ++ vendor/github.com/jtolds/gls/context.go | 153 ++ vendor/github.com/jtolds/gls/gen_sym.go | 21 + vendor/github.com/jtolds/gls/gid.go | 25 + vendor/github.com/jtolds/gls/id_pool.go | 34 + vendor/github.com/jtolds/gls/stack_tags.go | 147 ++ vendor/github.com/jtolds/gls/stack_tags_js.go | 75 + .../github.com/jtolds/gls/stack_tags_main.go | 30 + .../smartystreets/assertions/.gitignore | 4 + .../smartystreets/assertions/.travis.yml | 23 + .../smartystreets/assertions/CONTRIBUTING.md | 12 + .../smartystreets/assertions/LICENSE.md | 23 + .../smartystreets/assertions/Makefile | 14 + .../smartystreets/assertions/README.md | 4 + .../smartystreets/assertions/collections.go | 244 +++ .../smartystreets/assertions/doc.go | 109 ++ .../smartystreets/assertions/equal_method.go | 75 + .../smartystreets/assertions/equality.go | 331 ++++ .../smartystreets/assertions/equality_diff.go | 37 + .../smartystreets/assertions/filter.go | 31 + .../smartystreets/assertions/go.mod | 3 + .../assertions/internal/go-diff/AUTHORS | 25 + .../assertions/internal/go-diff/CONTRIBUTORS | 32 + .../assertions/internal/go-diff/LICENSE | 20 + .../internal/go-diff/diffmatchpatch/diff.go | 1345 +++++++++++++++++ .../go-diff/diffmatchpatch/diffmatchpatch.go | 46 + .../internal/go-diff/diffmatchpatch/match.go | 160 ++ .../go-diff/diffmatchpatch/mathutil.go | 23 + .../diffmatchpatch/operation_string.go | 17 + .../internal/go-diff/diffmatchpatch/patch.go | 556 +++++++ .../go-diff/diffmatchpatch/stringutil.go | 88 ++ .../assertions/internal/go-render/LICENSE | 27 + .../internal/go-render/render/render.go | 481 ++++++ .../internal/go-render/render/render_time.go | 26 + .../internal/oglematchers/.gitignore | 5 + .../internal/oglematchers/.travis.yml | 4 + .../assertions/internal/oglematchers/LICENSE | 202 +++ .../internal/oglematchers/README.md | 58 + .../internal/oglematchers/any_of.go | 94 ++ .../internal/oglematchers/contains.go | 61 + .../internal/oglematchers/deep_equals.go | 88 ++ .../internal/oglematchers/equals.go | 541 +++++++ .../internal/oglematchers/greater_or_equal.go | 39 + .../internal/oglematchers/greater_than.go | 39 + .../internal/oglematchers/less_or_equal.go | 41 + .../internal/oglematchers/less_than.go | 152 ++ .../internal/oglematchers/matcher.go | 86 ++ .../assertions/internal/oglematchers/not.go | 53 + .../oglematchers/transform_description.go | 36 + .../smartystreets/assertions/messages.go | 108 ++ .../smartystreets/assertions/panic.go | 128 ++ .../smartystreets/assertions/quantity.go | 141 ++ .../smartystreets/assertions/serializer.go | 70 + .../smartystreets/assertions/strings.go | 227 +++ .../smartystreets/assertions/time.go | 218 +++ .../smartystreets/assertions/type.go | 154 ++ .../smartystreets/goconvey/LICENSE.md | 23 + .../goconvey/convey/assertions.go | 71 + .../smartystreets/goconvey/convey/context.go | 272 ++++ .../goconvey/convey/convey.goconvey | 4 + .../goconvey/convey/discovery.go | 103 ++ .../smartystreets/goconvey/convey/doc.go | 218 +++ .../goconvey/convey/gotest/utils.go | 28 + .../smartystreets/goconvey/convey/init.go | 81 + .../goconvey/convey/nilReporter.go | 15 + .../goconvey/convey/reporting/console.go | 16 + .../goconvey/convey/reporting/doc.go | 5 + .../goconvey/convey/reporting/dot.go | 40 + .../goconvey/convey/reporting/gotest.go | 33 + .../goconvey/convey/reporting/init.go | 94 ++ .../goconvey/convey/reporting/json.go | 88 ++ .../goconvey/convey/reporting/printer.go | 60 + .../goconvey/convey/reporting/problems.go | 80 + .../goconvey/convey/reporting/reporter.go | 39 + .../convey/reporting/reporting.goconvey | 2 + .../goconvey/convey/reporting/reports.go | 179 +++ .../goconvey/convey/reporting/statistics.go | 108 ++ .../goconvey/convey/reporting/story.go | 73 + vendor/modules.txt | 14 + 105 files changed, 11751 insertions(+), 93 deletions(-) create mode 100644 modules/context/install.go create mode 100644 modules/forms/forms.go create mode 100644 modules/forms/install.go create mode 100644 modules/middlewares/binding/README.md create mode 100644 modules/middlewares/binding/bind_test.go create mode 100644 modules/middlewares/binding/binding.go create mode 100755 modules/middlewares/binding/common_test.go create mode 100755 modules/middlewares/binding/errorhandler_test.go create mode 100644 modules/middlewares/binding/errors.go create mode 100755 modules/middlewares/binding/errors_test.go create mode 100755 modules/middlewares/binding/file_test.go create mode 100755 modules/middlewares/binding/form_test.go create mode 100755 modules/middlewares/binding/json_test.go create mode 100755 modules/middlewares/binding/misc_test.go create mode 100755 modules/middlewares/binding/multipart_test.go create mode 100755 modules/middlewares/binding/validate_test.go create mode 100644 templates/base/alert_new.tmpl create mode 100644 vendor/github.com/gopherjs/gopherjs/LICENSE create mode 100644 vendor/github.com/gopherjs/gopherjs/js/js.go create mode 100644 vendor/github.com/jtolds/gls/LICENSE create mode 100644 vendor/github.com/jtolds/gls/README.md create mode 100644 vendor/github.com/jtolds/gls/context.go create mode 100644 vendor/github.com/jtolds/gls/gen_sym.go create mode 100644 vendor/github.com/jtolds/gls/gid.go create mode 100644 vendor/github.com/jtolds/gls/id_pool.go create mode 100644 vendor/github.com/jtolds/gls/stack_tags.go create mode 100644 vendor/github.com/jtolds/gls/stack_tags_js.go create mode 100644 vendor/github.com/jtolds/gls/stack_tags_main.go create mode 100644 vendor/github.com/smartystreets/assertions/.gitignore create mode 100644 vendor/github.com/smartystreets/assertions/.travis.yml create mode 100644 vendor/github.com/smartystreets/assertions/CONTRIBUTING.md create mode 100644 vendor/github.com/smartystreets/assertions/LICENSE.md create mode 100644 vendor/github.com/smartystreets/assertions/Makefile create mode 100644 vendor/github.com/smartystreets/assertions/README.md create mode 100644 vendor/github.com/smartystreets/assertions/collections.go create mode 100644 vendor/github.com/smartystreets/assertions/doc.go create mode 100644 vendor/github.com/smartystreets/assertions/equal_method.go create mode 100644 vendor/github.com/smartystreets/assertions/equality.go create mode 100644 vendor/github.com/smartystreets/assertions/equality_diff.go create mode 100644 vendor/github.com/smartystreets/assertions/filter.go create mode 100644 vendor/github.com/smartystreets/assertions/go.mod create mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/AUTHORS create mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/CONTRIBUTORS create mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/LICENSE create mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/diff.go create mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/diffmatchpatch.go create mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/match.go create mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/mathutil.go create mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/operation_string.go create mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/patch.go create mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/stringutil.go create mode 100644 vendor/github.com/smartystreets/assertions/internal/go-render/LICENSE create mode 100644 vendor/github.com/smartystreets/assertions/internal/go-render/render/render.go create mode 100644 vendor/github.com/smartystreets/assertions/internal/go-render/render/render_time.go create mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/.gitignore create mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/.travis.yml create mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/LICENSE create mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/README.md create mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/any_of.go create mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/contains.go create mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/deep_equals.go create mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/equals.go create mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/greater_or_equal.go create mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/greater_than.go create mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/less_or_equal.go create mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/less_than.go create mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/matcher.go create mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/not.go create mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/transform_description.go create mode 100644 vendor/github.com/smartystreets/assertions/messages.go create mode 100644 vendor/github.com/smartystreets/assertions/panic.go create mode 100644 vendor/github.com/smartystreets/assertions/quantity.go create mode 100644 vendor/github.com/smartystreets/assertions/serializer.go create mode 100644 vendor/github.com/smartystreets/assertions/strings.go create mode 100644 vendor/github.com/smartystreets/assertions/time.go create mode 100644 vendor/github.com/smartystreets/assertions/type.go create mode 100644 vendor/github.com/smartystreets/goconvey/LICENSE.md create mode 100644 vendor/github.com/smartystreets/goconvey/convey/assertions.go create mode 100644 vendor/github.com/smartystreets/goconvey/convey/context.go create mode 100644 vendor/github.com/smartystreets/goconvey/convey/convey.goconvey create mode 100644 vendor/github.com/smartystreets/goconvey/convey/discovery.go create mode 100644 vendor/github.com/smartystreets/goconvey/convey/doc.go create mode 100644 vendor/github.com/smartystreets/goconvey/convey/gotest/utils.go create mode 100644 vendor/github.com/smartystreets/goconvey/convey/init.go create mode 100644 vendor/github.com/smartystreets/goconvey/convey/nilReporter.go create mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/console.go create mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/doc.go create mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/dot.go create mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/gotest.go create mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/init.go create mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/json.go create mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/printer.go create mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/problems.go create mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/reporter.go create mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/reporting.goconvey create mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/reports.go create mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/statistics.go create mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/story.go diff --git a/go.mod b/go.mod index 40704dc731fff..0588a10390722 100644 --- a/go.mod +++ b/go.mod @@ -89,6 +89,7 @@ require ( github.com/sergi/go-diff v1.1.0 github.com/shurcooL/httpfs v0.0.0-20190707220628-8d4bc4ba7749 // indirect github.com/shurcooL/vfsgen v0.0.0-20200824052919-0d455de96546 + github.com/smartystreets/goconvey v1.6.4 github.com/spf13/viper v1.7.1 // indirect github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/stretchr/testify v1.6.1 diff --git a/modules/auth/user_form.go b/modules/auth/user_form.go index b94b8e0a4ebc6..4c15a193e7006 100644 --- a/modules/auth/user_form.go +++ b/modules/auth/user_form.go @@ -15,60 +15,6 @@ import ( "gitea.com/macaron/macaron" ) -// InstallForm form for installation page -type InstallForm struct { - DbType string `binding:"Required"` - DbHost string - DbUser string - DbPasswd string - DbName string - SSLMode string - Charset string `binding:"Required;In(utf8,utf8mb4)"` - DbPath string - DbSchema string - - AppName string `binding:"Required" locale:"install.app_name"` - RepoRootPath string `binding:"Required"` - LFSRootPath string - RunUser string `binding:"Required"` - Domain string `binding:"Required"` - SSHPort int - HTTPPort string `binding:"Required"` - AppURL string `binding:"Required"` - LogRootPath string `binding:"Required"` - - SMTPHost string - SMTPFrom string - SMTPUser string `binding:"OmitEmpty;MaxSize(254)" locale:"install.mailer_user"` - SMTPPasswd string - RegisterConfirm bool - MailNotify bool - - OfflineMode bool - DisableGravatar bool - EnableFederatedAvatar bool - EnableOpenIDSignIn bool - EnableOpenIDSignUp bool - DisableRegistration bool - AllowOnlyExternalRegistration bool - EnableCaptcha bool - RequireSignInView bool - DefaultKeepEmailPrivate bool - DefaultAllowCreateOrganization bool - DefaultEnableTimetracking bool - NoReplyAddress string - - AdminName string `binding:"OmitEmpty;AlphaDashDot;MaxSize(30)" locale:"install.admin_name"` - AdminPasswd string `binding:"OmitEmpty;MaxSize(255)" locale:"install.admin_password"` - AdminConfirmPasswd string - AdminEmail string `binding:"OmitEmpty;MinSize(3);MaxSize(254);Include(@)" locale:"install.admin_email"` -} - -// Validate validates the fields -func (f *InstallForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { - return validate(errs, ctx.Data, f, ctx.Locale) -} - // _____ ____ _________________ ___ // / _ \ | | \__ ___/ | \ // / /_\ \| | / | | / ~ \ diff --git a/modules/context/default.go b/modules/context/default.go index 69005c5a4ff96..5eb0747f1546f 100644 --- a/modules/context/default.go +++ b/modules/context/default.go @@ -9,28 +9,26 @@ import ( "time" "code.gitea.io/gitea/modules/auth" + "code.gitea.io/gitea/modules/middlewares/binding" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/translation" - "golang.org/x/text/language" "github.com/alexedwards/scs/v2" "github.com/unknwon/i18n" "github.com/unrolled/render" + "golang.org/x/text/language" ) // flashes enumerates all the flash types const ( - SuccessFlash = "success" - ErrorFlash = "error" - WarnFlash = "warning" - InfoFlash = "info" + SuccessFlash = "SuccessMsg" + ErrorFlash = "ErrorMsg" + WarnFlash = "WarningMsg" + InfoFlash = "InfoMsg" ) // Flash represents flashs -type Flash struct { - MessageType string - Message string -} +type Flash map[string]string // DefaultContext represents a context for basic routes, all other context should // be derived from the context but not add more fields on this context @@ -41,7 +39,7 @@ type DefaultContext struct { Render *render.Render Sessions *scs.SessionManager translation.Locale - flash *Flash + flash Flash } // HTML wraps render HTML @@ -49,6 +47,11 @@ func (ctx *DefaultContext) HTML(statusCode int, tmpl string) error { return ctx.Render.HTML(ctx.Resp, statusCode, tmpl, ctx.Data) } +// Bind binding a form to a struct +func (ctx *DefaultContext) Bind(form interface{}) binding.Errors { + return binding.Bind(ctx.Req, form) +} + // HasError returns true if error occurs in form validation. func (ctx *DefaultContext) HasError() bool { hasErr, ok := ctx.Data["HasError"] @@ -93,10 +96,10 @@ func (ctx *DefaultContext) DestroySession() error { // Flash set message to flash func (ctx *DefaultContext) Flash(tp, v string) { if ctx.flash == nil { - ctx.flash = &Flash{} + ctx.flash = make(Flash) } - ctx.flash.MessageType = tp - ctx.flash.Message = v + ctx.flash[tp] = v + ctx.Data[tp] = v ctx.Data["Flash"] = ctx.flash } diff --git a/modules/context/install.go b/modules/context/install.go new file mode 100644 index 0000000000000..f7aa073d8ccbc --- /dev/null +++ b/modules/context/install.go @@ -0,0 +1,27 @@ +// Copyright 2020 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package context + +import ( + "context" + "net/http" +) + +// InstallContext represents a context for installation routes +type InstallContext = DefaultContext + +var ( + installContextKey interface{} = "install_context" +) + +// WithInstallContext set up install context in request +func WithInstallContext(req *http.Request, ctx *InstallContext) *http.Request { + return req.WithContext(context.WithValue(req.Context(), installContextKey, ctx)) +} + +// GetInstallContext retrieves install context from request +func GetInstallContext(req *http.Request) *InstallContext { + return req.Context().Value(installContextKey).(*InstallContext) +} diff --git a/modules/forms/forms.go b/modules/forms/forms.go new file mode 100644 index 0000000000000..4dccfeda08701 --- /dev/null +++ b/modules/forms/forms.go @@ -0,0 +1,139 @@ +// Copyright 2020 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package forms + +import ( + "reflect" + "strings" + + "code.gitea.io/gitea/modules/middlewares/binding" + "code.gitea.io/gitea/modules/translation" + "code.gitea.io/gitea/modules/validation" + + "github.com/unknwon/com" +) + +// Form form binding interface +type Form interface { + binding.Validator +} + +// AssignForm assign form values back to the template data. +func AssignForm(form interface{}, data map[string]interface{}) { + typ := reflect.TypeOf(form) + val := reflect.ValueOf(form) + + if typ.Kind() == reflect.Ptr { + typ = typ.Elem() + val = val.Elem() + } + + for i := 0; i < typ.NumField(); i++ { + field := typ.Field(i) + + fieldName := field.Tag.Get("form") + // Allow ignored fields in the struct + if fieldName == "-" { + continue + } else if len(fieldName) == 0 { + fieldName = com.ToSnakeCase(field.Name) + } + + data[fieldName] = val.Field(i).Interface() + } +} + +func getRuleBody(field reflect.StructField, prefix string) string { + for _, rule := range strings.Split(field.Tag.Get("binding"), ";") { + if strings.HasPrefix(rule, prefix) { + return rule[len(prefix) : len(rule)-1] + } + } + return "" +} + +// GetSize get size int form tag +func GetSize(field reflect.StructField) string { + return getRuleBody(field, "Size(") +} + +// GetMinSize get minimal size in form tag +func GetMinSize(field reflect.StructField) string { + return getRuleBody(field, "MinSize(") +} + +// GetMaxSize get max size in form tag +func GetMaxSize(field reflect.StructField) string { + return getRuleBody(field, "MaxSize(") +} + +// GetInclude get include in form tag +func GetInclude(field reflect.StructField) string { + return getRuleBody(field, "Include(") +} + +func validate(errs binding.Errors, data map[string]interface{}, f Form, l translation.Locale) binding.Errors { + if errs.Len() == 0 { + return errs + } + + data["HasError"] = true + // If the field with name errs[0].FieldNames[0] is not found in form + // somehow, some code later on will panic on Data["ErrorMsg"].(string). + // So initialize it to some default. + data["ErrorMsg"] = l.Tr("form.unknown_error") + AssignForm(f, data) + + typ := reflect.TypeOf(f) + val := reflect.ValueOf(f) + + if typ.Kind() == reflect.Ptr { + typ = typ.Elem() + val = val.Elem() + } + + if field, ok := typ.FieldByName(errs[0].FieldNames[0]); ok { + fieldName := field.Tag.Get("form") + if fieldName != "-" { + data["Err_"+field.Name] = true + + trName := field.Tag.Get("locale") + if len(trName) == 0 { + trName = l.Tr("form." + field.Name) + } else { + trName = l.Tr(trName) + } + + switch errs[0].Classification { + case binding.ERR_REQUIRED: + data["ErrorMsg"] = trName + l.Tr("form.require_error") + case binding.ERR_ALPHA_DASH: + data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_error") + case binding.ERR_ALPHA_DASH_DOT: + data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_dot_error") + case validation.ErrGitRefName: + data["ErrorMsg"] = trName + l.Tr("form.git_ref_name_error") + case binding.ERR_SIZE: + data["ErrorMsg"] = trName + l.Tr("form.size_error", GetSize(field)) + case binding.ERR_MIN_SIZE: + data["ErrorMsg"] = trName + l.Tr("form.min_size_error", GetMinSize(field)) + case binding.ERR_MAX_SIZE: + data["ErrorMsg"] = trName + l.Tr("form.max_size_error", GetMaxSize(field)) + case binding.ERR_EMAIL: + data["ErrorMsg"] = trName + l.Tr("form.email_error") + case binding.ERR_URL: + data["ErrorMsg"] = trName + l.Tr("form.url_error") + case binding.ERR_INCLUDE: + data["ErrorMsg"] = trName + l.Tr("form.include_error", GetInclude(field)) + case validation.ErrGlobPattern: + data["ErrorMsg"] = trName + l.Tr("form.glob_pattern_error", errs[0].Message) + default: + data["ErrorMsg"] = l.Tr("form.unknown_error") + " " + errs[0].Classification + } + return errs + } + } + return errs +} diff --git a/modules/forms/install.go b/modules/forms/install.go new file mode 100644 index 0000000000000..af84de2ef9d10 --- /dev/null +++ b/modules/forms/install.go @@ -0,0 +1,68 @@ +// Copyright 2014 The Gogs Authors. All rights reserved. +// Copyright 2018 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package forms + +import ( + "net/http" + + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/modules/middlewares/binding" +) + +// InstallForm form for installation page +type InstallForm struct { + DbType string `binding:"Required"` + DbHost string + DbUser string + DbPasswd string + DbName string + SSLMode string + Charset string `binding:"Required;In(utf8,utf8mb4)"` + DbPath string + DbSchema string + + AppName string `binding:"Required" locale:"install.app_name"` + RepoRootPath string `binding:"Required"` + LFSRootPath string + RunUser string `binding:"Required"` + Domain string `binding:"Required"` + SSHPort int + HTTPPort string `binding:"Required"` + AppURL string `binding:"Required"` + LogRootPath string `binding:"Required"` + + SMTPHost string + SMTPFrom string + SMTPUser string `binding:"OmitEmpty;MaxSize(254)" locale:"install.mailer_user"` + SMTPPasswd string + RegisterConfirm bool + MailNotify bool + + OfflineMode bool + DisableGravatar bool + EnableFederatedAvatar bool + EnableOpenIDSignIn bool + EnableOpenIDSignUp bool + DisableRegistration bool + AllowOnlyExternalRegistration bool + EnableCaptcha bool + RequireSignInView bool + DefaultKeepEmailPrivate bool + DefaultAllowCreateOrganization bool + DefaultEnableTimetracking bool + NoReplyAddress string + + AdminName string `binding:"OmitEmpty;AlphaDashDot;MaxSize(30)" locale:"install.admin_name"` + AdminPasswd string `binding:"OmitEmpty;MaxSize(255)" locale:"install.admin_password"` + AdminConfirmPasswd string + AdminEmail string `binding:"OmitEmpty;MinSize(3);MaxSize(254);Include(@)" locale:"install.admin_email"` +} + +// Validate validates the fields +func (f *InstallForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { + ctx := context.GetInstallContext(req) + return validate(errs, ctx.Data, f, ctx.Locale) +} diff --git a/modules/middlewares/binding/README.md b/modules/middlewares/binding/README.md new file mode 100644 index 0000000000000..80ea7637359d7 --- /dev/null +++ b/modules/middlewares/binding/README.md @@ -0,0 +1,5 @@ +Middleware binding provides request data binding and validation for net/http, It's a fork of [Macaron](https://github.com/go-macaron/macaron). + +## License + +This project is under the Apache License, Version 2.0. See the [LICENSE](LICENSE) file for the full license text. \ No newline at end of file diff --git a/modules/middlewares/binding/bind_test.go b/modules/middlewares/binding/bind_test.go new file mode 100644 index 0000000000000..318ea7d7f96cd --- /dev/null +++ b/modules/middlewares/binding/bind_test.go @@ -0,0 +1,57 @@ +// Copyright 2014 Martini Authors +// Copyright 2014 The Macaron Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"): you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. + +package binding + +import ( + "testing" + + . "github.com/smartystreets/goconvey/convey" +) + +func Test_Bind(t *testing.T) { + Convey("Bind test", t, func() { + Convey("Bind form", func() { + for _, testCase := range formTestCases { + performFormTest(t, Bind, testCase) + } + }) + + Convey("Bind JSON", func() { + for _, testCase := range jsonTestCases { + performJsonTest(t, Bind, testCase) + } + }) + + Convey("Bind multipart form", func() { + for _, testCase := range multipartFormTestCases { + performMultipartFormTest(t, Bind, testCase) + } + }) + + Convey("Bind with file", func() { + for _, testCase := range fileTestCases { + performFileTest(t, Bind, testCase) + performFileTest(t, BindIgnErr, testCase) + } + }) + }) +} + +func Test_Version(t *testing.T) { + Convey("Get package version", t, func() { + So(Version(), ShouldEqual, _VERSION) + }) +} diff --git a/modules/middlewares/binding/binding.go b/modules/middlewares/binding/binding.go new file mode 100644 index 0000000000000..4c0ecb9baf10a --- /dev/null +++ b/modules/middlewares/binding/binding.go @@ -0,0 +1,708 @@ +// Copyright 2014 Martini Authors +// Copyright 2014 The Macaron Authors +// Copyright 2020 The Gitea Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"): you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. + +// Package binding is a middleware that provides request data binding and validation for Macaron. +package binding + +import ( + "encoding/json" + "fmt" + "io" + "mime/multipart" + "net/http" + "net/url" + "reflect" + "regexp" + "strconv" + "strings" + "unicode/utf8" + + "github.com/unknwon/com" +) + +// Bind wraps up the functionality of the Form and Json middleware +// according to the Content-Type and verb of the request. +// A Content-Type is required for POST and PUT requests. +// Bind invokes the ErrorHandler middleware to bail out if errors +// occurred. If you want to perform your own error handling, use +// Form or Json middleware directly. An interface pointer can +// be added as a second argument in order to map the struct to +// a specific interface. +func Bind(req *http.Request, obj interface{}) Errors { + contentType := req.Header.Get("Content-Type") + if req.Method == "POST" || req.Method == "PUT" || len(contentType) > 0 { + switch { + case strings.Contains(contentType, "form-urlencoded"): + return Form(req, obj) + case strings.Contains(contentType, "multipart/form-data"): + return MultipartForm(req, obj) + case strings.Contains(contentType, "json"): + return JSON(req, obj) + default: + var errors Errors + if contentType == "" { + errors.Add([]string{}, ERR_CONTENT_TYPE, "Empty Content-Type") + } else { + errors.Add([]string{}, ERR_CONTENT_TYPE, "Unsupported Content-Type") + } + return errors + } + } else { + return Form(req, obj) + } +} + +const ( + _JSON_CONTENT_TYPE = "application/json; charset=utf-8" + STATUS_UNPROCESSABLE_ENTITY = 422 +) + +// errorHandler simply counts the number of errors in the +// context and, if more than 0, writes a response with an +// error code and a JSON payload describing the errors. +// The response will have a JSON content-type. +// Middleware remaining on the stack will not even see the request +// if, by this point, there are any errors. +// This is a "default" handler, of sorts, and you are +// welcome to use your own instead. The Bind middleware +// invokes this automatically for convenience. +func errorHandler(errs Errors, rw http.ResponseWriter) { + if len(errs) > 0 { + rw.Header().Set("Content-Type", _JSON_CONTENT_TYPE) + if errs.Has(ERR_DESERIALIZATION) { + rw.WriteHeader(http.StatusBadRequest) + } else if errs.Has(ERR_CONTENT_TYPE) { + rw.WriteHeader(http.StatusUnsupportedMediaType) + } else { + rw.WriteHeader(STATUS_UNPROCESSABLE_ENTITY) + } + errOutput, _ := json.Marshal(errs) + rw.Write(errOutput) + return + } +} + +// Form is middleware to deserialize form-urlencoded data from the request. +// It gets data from the form-urlencoded body, if present, or from the +// query string. It uses the http.Request.ParseForm() method +// to perform deserialization, then reflection is used to map each field +// into the struct with the proper type. Structs with primitive slice types +// (bool, float, int, string) can support deserialization of repeated form +// keys, for example: key=val1&key=val2&key=val3 +// An interface pointer can be added as a second argument in order +// to map the struct to a specific interface. +func Form(req *http.Request, formStruct interface{}) Errors { + var errors Errors + + ensurePointer(formStruct) + formStructV := reflect.ValueOf(formStruct) + parseErr := req.ParseForm() + + // Format validation of the request body or the URL would add considerable overhead, + // and ParseForm does not complain when URL encoding is off. + // Because an empty request body or url can also mean absence of all needed values, + // it is not in all cases a bad request, so let's return 422. + if parseErr != nil { + errors.Add([]string{}, ERR_DESERIALIZATION, parseErr.Error()) + } + errors = mapForm(formStructV, req.Form, nil, errors) + return append(errors, Validate(req, formStruct)...) +} + +// MaxMemory represents maximum amount of memory to use when parsing a multipart form. +// Set this to whatever value you prefer; default is 10 MB. +var MaxMemory = int64(1024 * 1024 * 10) + +// MultipartForm works much like Form, except it can parse multipart forms +// and handle file uploads. Like the other deserialization middleware handlers, +// you can pass in an interface to make the interface available for injection +// into other handlers later. +func MultipartForm(req *http.Request, formStruct interface{}) Errors { + var errors Errors + ensurePointer(formStruct) + formStructV := reflect.ValueOf(formStruct) + // This if check is necessary due to https://github.com/martini-contrib/csrf/issues/6 + if req.MultipartForm == nil { + // Workaround for multipart forms returning nil instead of an error + // when content is not multipart; see https://code.google.com/p/go/issues/detail?id=6334 + if multipartReader, err := req.MultipartReader(); err != nil { + errors.Add([]string{}, ERR_DESERIALIZATION, err.Error()) + } else { + form, parseErr := multipartReader.ReadForm(MaxMemory) + if parseErr != nil { + errors.Add([]string{}, ERR_DESERIALIZATION, parseErr.Error()) + } + + if req.Form == nil { + req.ParseForm() + } + for k, v := range form.Value { + req.Form[k] = append(req.Form[k], v...) + } + + req.MultipartForm = form + } + } + errors = mapForm(formStructV, req.MultipartForm.Value, req.MultipartForm.File, errors) + return append(errors, Validate(req, formStruct)...) +} + +// JSON is middleware to deserialize a JSON payload from the request +// into the struct that is passed in. The resulting struct is then +// validated, but no error handling is actually performed here. +// An interface pointer can be added as a second argument in order +// to map the struct to a specific interface. +func JSON(req *http.Request, jsonStruct interface{}) Errors { + var errors Errors + ensurePointer(jsonStruct) + + if req.Body != nil { + defer req.Body.Close() + err := json.NewDecoder(req.Body).Decode(jsonStruct) + if err != nil && err != io.EOF { + errors.Add([]string{}, ERR_DESERIALIZATION, err.Error()) + } + } + return append(errors, Validate(req, jsonStruct)...) +} + +// RawValidate is same as Validate but does not require a HTTP context, +// and can be used independently just for validation. +// This function does not support Validator interface. +func RawValidate(obj interface{}) Errors { + var errs Errors + v := reflect.ValueOf(obj) + k := v.Kind() + if k == reflect.Interface || k == reflect.Ptr { + v = v.Elem() + k = v.Kind() + } + if k == reflect.Slice || k == reflect.Array { + for i := 0; i < v.Len(); i++ { + e := v.Index(i).Interface() + errs = validateStruct(errs, e) + } + } else { + errs = validateStruct(errs, obj) + } + return errs +} + +// Validate is middleware to enforce required fields. If the struct +// passed in implements Validator, then the user-defined Validate method +// is executed, and its errors are mapped to the context. This middleware +// performs no error handling: it merely detects errors and maps them. +func Validate(req *http.Request, obj interface{}) Errors { + var errs Errors + v := reflect.ValueOf(obj) + k := v.Kind() + if k == reflect.Interface || k == reflect.Ptr { + v = v.Elem() + k = v.Kind() + } + if k == reflect.Slice || k == reflect.Array { + for i := 0; i < v.Len(); i++ { + e := v.Index(i).Interface() + errs = validateStruct(errs, e) + if validator, ok := e.(Validator); ok { + errs = validator.Validate(req, errs) + } + } + } else { + errs = validateStruct(errs, obj) + if validator, ok := obj.(Validator); ok { + errs = validator.Validate(req, errs) + } + } + return errs +} + +var ( + AlphaDashPattern = regexp.MustCompile("[^\\d\\w-_]") + AlphaDashDotPattern = regexp.MustCompile("[^\\d\\w-_\\.]") + EmailPattern = regexp.MustCompile("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[a-zA-Z0-9](?:[\\w-]*[\\w])?") +) + +// Copied from github.com/asaskevich/govalidator. +const _MAX_URL_RUNE_COUNT = 2083 +const _MIN_URL_RUNE_COUNT = 3 + +var ( + urlSchemaRx = `((ftp|tcp|udp|wss?|https?):\/\/)` + urlUsernameRx = `(\S+(:\S*)?@)` + urlIPRx = `([1-9]\d?|1\d\d|2[01]\d|22[0-3])(\.(1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.([0-9]\d?|1\d\d|2[0-4]\d|25[0-4]))` + ipRx = `(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))` + urlSubdomainRx = `((www\.)|([a-zA-Z0-9]([-\.][-\._a-zA-Z0-9]+)*))` + urlPortRx = `(:(\d{1,5}))` + urlPathRx = `((\/|\?|#)[^\s]*)` + URLPattern = regexp.MustCompile(`^` + urlSchemaRx + `?` + urlUsernameRx + `?` + `((` + urlIPRx + `|(\[` + ipRx + `\])|(([a-zA-Z0-9]([a-zA-Z0-9-_]+)?[a-zA-Z0-9]([-\.][a-zA-Z0-9]+)*)|(` + urlSubdomainRx + `?))?(([a-zA-Z\x{00a1}-\x{ffff}0-9]+-?-?)*[a-zA-Z\x{00a1}-\x{ffff}0-9]+)(?:\.([a-zA-Z\x{00a1}-\x{ffff}]{1,}))?))\.?` + urlPortRx + `?` + urlPathRx + `?$`) +) + +// IsURL check if the string is an URL. +func isURL(str string) bool { + if str == "" || utf8.RuneCountInString(str) >= _MAX_URL_RUNE_COUNT || len(str) <= _MIN_URL_RUNE_COUNT || strings.HasPrefix(str, ".") { + return false + } + u, err := url.Parse(str) + if err != nil { + return false + } + if strings.HasPrefix(u.Host, ".") { + return false + } + if u.Host == "" && (u.Path != "" && !strings.Contains(u.Path, ".")) { + return false + } + return URLPattern.MatchString(str) + +} + +type ( + // Rule represents a validation rule. + Rule struct { + // IsMatch checks if rule matches. + IsMatch func(string) bool + // IsValid applies validation rule to condition. + IsValid func(Errors, string, interface{}) (bool, Errors) + } + + // ParamRule does same thing as Rule but passes rule itself to IsValid method. + ParamRule struct { + // IsMatch checks if rule matches. + IsMatch func(string) bool + // IsValid applies validation rule to condition. + IsValid func(Errors, string, string, interface{}) (bool, Errors) + } + + // RuleMapper and ParamRuleMapper represent validation rule mappers, + // it allwos users to add custom validation rules. + RuleMapper []*Rule + ParamRuleMapper []*ParamRule +) + +var ruleMapper RuleMapper +var paramRuleMapper ParamRuleMapper + +// AddRule adds new validation rule. +func AddRule(r *Rule) { + ruleMapper = append(ruleMapper, r) +} + +// AddParamRule adds new validation rule. +func AddParamRule(r *ParamRule) { + paramRuleMapper = append(paramRuleMapper, r) +} + +func in(fieldValue interface{}, arr string) bool { + val := fmt.Sprintf("%v", fieldValue) + vals := strings.Split(arr, ",") + isIn := false + for _, v := range vals { + if v == val { + isIn = true + break + } + } + return isIn +} + +func parseFormName(raw, actual string) string { + if len(actual) > 0 { + return actual + } + return nameMapper(raw) +} + +// Performs required field checking on a struct +func validateStruct(errors Errors, obj interface{}) Errors { + typ := reflect.TypeOf(obj) + val := reflect.ValueOf(obj) + + if typ.Kind() == reflect.Ptr { + typ = typ.Elem() + val = val.Elem() + } + + for i := 0; i < typ.NumField(); i++ { + field := typ.Field(i) + + // Allow ignored fields in the struct + if field.Tag.Get("form") == "-" || !val.Field(i).CanInterface() { + continue + } + + fieldVal := val.Field(i) + fieldValue := fieldVal.Interface() + zero := reflect.Zero(field.Type).Interface() + + // Validate nested and embedded structs (if pointer, only do so if not nil) + if field.Type.Kind() == reflect.Struct || + (field.Type.Kind() == reflect.Ptr && !reflect.DeepEqual(zero, fieldValue) && + field.Type.Elem().Kind() == reflect.Struct) { + errors = validateStruct(errors, fieldValue) + } + errors = validateField(errors, zero, field, fieldVal, fieldValue) + } + return errors +} + +func validateField(errors Errors, zero interface{}, field reflect.StructField, fieldVal reflect.Value, fieldValue interface{}) Errors { + if fieldVal.Kind() == reflect.Slice { + for i := 0; i < fieldVal.Len(); i++ { + sliceVal := fieldVal.Index(i) + if sliceVal.Kind() == reflect.Ptr { + sliceVal = sliceVal.Elem() + } + + sliceValue := sliceVal.Interface() + zero := reflect.Zero(sliceVal.Type()).Interface() + if sliceVal.Kind() == reflect.Struct || + (sliceVal.Kind() == reflect.Ptr && !reflect.DeepEqual(zero, sliceValue) && + sliceVal.Elem().Kind() == reflect.Struct) { + errors = validateStruct(errors, sliceValue) + } + /* Apply validation rules to each item in a slice. ISSUE #3 + else { + errors = validateField(errors, zero, field, sliceVal, sliceValue) + }*/ + } + } + +VALIDATE_RULES: + for _, rule := range strings.Split(field.Tag.Get("binding"), ";") { + if len(rule) == 0 { + continue + } + + switch { + case rule == "OmitEmpty": + if reflect.DeepEqual(zero, fieldValue) { + break VALIDATE_RULES + } + case rule == "Required": + v := reflect.ValueOf(fieldValue) + if v.Kind() == reflect.Slice { + if v.Len() == 0 { + errors.Add([]string{field.Name}, ERR_REQUIRED, "Required") + break VALIDATE_RULES + } + + continue + } + + if reflect.DeepEqual(zero, fieldValue) { + errors.Add([]string{field.Name}, ERR_REQUIRED, "Required") + break VALIDATE_RULES + } + case rule == "AlphaDash": + if AlphaDashPattern.MatchString(fmt.Sprintf("%v", fieldValue)) { + errors.Add([]string{field.Name}, ERR_ALPHA_DASH, "AlphaDash") + break VALIDATE_RULES + } + case rule == "AlphaDashDot": + if AlphaDashDotPattern.MatchString(fmt.Sprintf("%v", fieldValue)) { + errors.Add([]string{field.Name}, ERR_ALPHA_DASH_DOT, "AlphaDashDot") + break VALIDATE_RULES + } + case strings.HasPrefix(rule, "Size("): + size, _ := strconv.Atoi(rule[5 : len(rule)-1]) + if str, ok := fieldValue.(string); ok && utf8.RuneCountInString(str) != size { + errors.Add([]string{field.Name}, ERR_SIZE, "Size") + break VALIDATE_RULES + } + v := reflect.ValueOf(fieldValue) + if v.Kind() == reflect.Slice && v.Len() != size { + errors.Add([]string{field.Name}, ERR_SIZE, "Size") + break VALIDATE_RULES + } + case strings.HasPrefix(rule, "MinSize("): + min, _ := strconv.Atoi(rule[8 : len(rule)-1]) + if str, ok := fieldValue.(string); ok && utf8.RuneCountInString(str) < min { + errors.Add([]string{field.Name}, ERR_MIN_SIZE, "MinSize") + break VALIDATE_RULES + } + v := reflect.ValueOf(fieldValue) + if v.Kind() == reflect.Slice && v.Len() < min { + errors.Add([]string{field.Name}, ERR_MIN_SIZE, "MinSize") + break VALIDATE_RULES + } + case strings.HasPrefix(rule, "MaxSize("): + max, _ := strconv.Atoi(rule[8 : len(rule)-1]) + if str, ok := fieldValue.(string); ok && utf8.RuneCountInString(str) > max { + errors.Add([]string{field.Name}, ERR_MAX_SIZE, "MaxSize") + break VALIDATE_RULES + } + v := reflect.ValueOf(fieldValue) + if v.Kind() == reflect.Slice && v.Len() > max { + errors.Add([]string{field.Name}, ERR_MAX_SIZE, "MaxSize") + break VALIDATE_RULES + } + case strings.HasPrefix(rule, "Range("): + nums := strings.Split(rule[6:len(rule)-1], ",") + if len(nums) != 2 { + break VALIDATE_RULES + } + val := com.StrTo(fmt.Sprintf("%v", fieldValue)).MustInt() + if val < com.StrTo(nums[0]).MustInt() || val > com.StrTo(nums[1]).MustInt() { + errors.Add([]string{field.Name}, ERR_RANGE, "Range") + break VALIDATE_RULES + } + case rule == "Email": + if !EmailPattern.MatchString(fmt.Sprintf("%v", fieldValue)) { + errors.Add([]string{field.Name}, ERR_EMAIL, "Email") + break VALIDATE_RULES + } + case rule == "Url": + str := fmt.Sprintf("%v", fieldValue) + if len(str) == 0 { + continue + } else if !isURL(str) { + errors.Add([]string{field.Name}, ERR_URL, "Url") + break VALIDATE_RULES + } + case strings.HasPrefix(rule, "In("): + if !in(fieldValue, rule[3:len(rule)-1]) { + errors.Add([]string{field.Name}, ERR_IN, "In") + break VALIDATE_RULES + } + case strings.HasPrefix(rule, "NotIn("): + if in(fieldValue, rule[6:len(rule)-1]) { + errors.Add([]string{field.Name}, ERR_NOT_INT, "NotIn") + break VALIDATE_RULES + } + case strings.HasPrefix(rule, "Include("): + if !strings.Contains(fmt.Sprintf("%v", fieldValue), rule[8:len(rule)-1]) { + errors.Add([]string{field.Name}, ERR_INCLUDE, "Include") + break VALIDATE_RULES + } + case strings.HasPrefix(rule, "Exclude("): + if strings.Contains(fmt.Sprintf("%v", fieldValue), rule[8:len(rule)-1]) { + errors.Add([]string{field.Name}, ERR_EXCLUDE, "Exclude") + break VALIDATE_RULES + } + case strings.HasPrefix(rule, "Default("): + if reflect.DeepEqual(zero, fieldValue) { + if fieldVal.CanAddr() { + errors = setWithProperType(field.Type.Kind(), rule[8:len(rule)-1], fieldVal, field.Tag.Get("form"), errors) + } else { + errors.Add([]string{field.Name}, ERR_EXCLUDE, "Default") + break VALIDATE_RULES + } + } + default: + // Apply custom validation rules + var isValid bool + for i := range ruleMapper { + if ruleMapper[i].IsMatch(rule) { + isValid, errors = ruleMapper[i].IsValid(errors, field.Name, fieldValue) + if !isValid { + break VALIDATE_RULES + } + } + } + for i := range paramRuleMapper { + if paramRuleMapper[i].IsMatch(rule) { + isValid, errors = paramRuleMapper[i].IsValid(errors, rule, field.Name, fieldValue) + if !isValid { + break VALIDATE_RULES + } + } + } + } + } + return errors +} + +// NameMapper represents a form tag name mapper. +type NameMapper func(string) string + +var ( + nameMapper = func(field string) string { + newstr := make([]rune, 0, len(field)) + for i, chr := range field { + if isUpper := 'A' <= chr && chr <= 'Z'; isUpper { + if i > 0 { + newstr = append(newstr, '_') + } + chr -= ('A' - 'a') + } + newstr = append(newstr, chr) + } + return string(newstr) + } +) + +// SetNameMapper sets name mapper. +func SetNameMapper(nm NameMapper) { + nameMapper = nm +} + +// Takes values from the form data and puts them into a struct +func mapForm(formStruct reflect.Value, form map[string][]string, + formfile map[string][]*multipart.FileHeader, errors Errors) Errors { + + if formStruct.Kind() == reflect.Ptr { + formStruct = formStruct.Elem() + } + typ := formStruct.Type() + + for i := 0; i < typ.NumField(); i++ { + typeField := typ.Field(i) + structField := formStruct.Field(i) + + if typeField.Type.Kind() == reflect.Ptr && typeField.Anonymous { + structField.Set(reflect.New(typeField.Type.Elem())) + errors = mapForm(structField.Elem(), form, formfile, errors) + if reflect.DeepEqual(structField.Elem().Interface(), reflect.Zero(structField.Elem().Type()).Interface()) { + structField.Set(reflect.Zero(structField.Type())) + } + } else if typeField.Type.Kind() == reflect.Struct { + errors = mapForm(structField, form, formfile, errors) + } + + inputFieldName := parseFormName(typeField.Name, typeField.Tag.Get("form")) + if len(inputFieldName) == 0 || !structField.CanSet() { + continue + } + + inputValue, exists := form[inputFieldName] + if exists { + numElems := len(inputValue) + if structField.Kind() == reflect.Slice && numElems > 0 { + sliceOf := structField.Type().Elem().Kind() + slice := reflect.MakeSlice(structField.Type(), numElems, numElems) + for i := 0; i < numElems; i++ { + errors = setWithProperType(sliceOf, inputValue[i], slice.Index(i), inputFieldName, errors) + } + formStruct.Field(i).Set(slice) + } else { + errors = setWithProperType(typeField.Type.Kind(), inputValue[0], structField, inputFieldName, errors) + } + continue + } + + inputFile, exists := formfile[inputFieldName] + if !exists { + continue + } + fhType := reflect.TypeOf((*multipart.FileHeader)(nil)) + numElems := len(inputFile) + if structField.Kind() == reflect.Slice && numElems > 0 && structField.Type().Elem() == fhType { + slice := reflect.MakeSlice(structField.Type(), numElems, numElems) + for i := 0; i < numElems; i++ { + slice.Index(i).Set(reflect.ValueOf(inputFile[i])) + } + structField.Set(slice) + } else if structField.Type() == fhType { + structField.Set(reflect.ValueOf(inputFile[0])) + } + } + return errors +} + +// This sets the value in a struct of an indeterminate type to the +// matching value from the request (via Form middleware) in the +// same type, so that not all deserialized values have to be strings. +// Supported types are string, int, float, and bool. +func setWithProperType(valueKind reflect.Kind, val string, structField reflect.Value, nameInTag string, errors Errors) Errors { + switch valueKind { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + if val == "" { + val = "0" + } + intVal, err := strconv.ParseInt(val, 10, 64) + if err != nil { + errors.Add([]string{nameInTag}, ERR_INTERGER_TYPE, "Value could not be parsed as integer") + } else { + structField.SetInt(intVal) + } + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + if val == "" { + val = "0" + } + uintVal, err := strconv.ParseUint(val, 10, 64) + if err != nil { + errors.Add([]string{nameInTag}, ERR_INTERGER_TYPE, "Value could not be parsed as unsigned integer") + } else { + structField.SetUint(uintVal) + } + case reflect.Bool: + if val == "on" { + structField.SetBool(true) + break + } + + if val == "" { + val = "false" + } + boolVal, err := strconv.ParseBool(val) + if err != nil { + errors.Add([]string{nameInTag}, ERR_BOOLEAN_TYPE, "Value could not be parsed as boolean") + } else if boolVal { + structField.SetBool(true) + } + case reflect.Float32: + if val == "" { + val = "0.0" + } + floatVal, err := strconv.ParseFloat(val, 32) + if err != nil { + errors.Add([]string{nameInTag}, ERR_FLOAT_TYPE, "Value could not be parsed as 32-bit float") + } else { + structField.SetFloat(floatVal) + } + case reflect.Float64: + if val == "" { + val = "0.0" + } + floatVal, err := strconv.ParseFloat(val, 64) + if err != nil { + errors.Add([]string{nameInTag}, ERR_FLOAT_TYPE, "Value could not be parsed as 64-bit float") + } else { + structField.SetFloat(floatVal) + } + case reflect.String: + structField.SetString(val) + } + return errors +} + +// Pointers must be bind to. +func ensurePointer(obj interface{}) { + if reflect.TypeOf(obj).Kind() != reflect.Ptr { + panic("Pointers are only accepted as binding models") + } +} + +type ( + // ErrorHandler is the interface that has custom error handling process. + ErrorHandler interface { + // Error handles validation errors with custom process. + Error(*http.Request, Errors) + } + + // Validator is the interface that handles some rudimentary + // request validation logic so your application doesn't have to. + Validator interface { + // Validate validates that the request is OK. It is recommended + // that validation be limited to checking values for syntax and + // semantics, enough to know that you can make sense of the request + // in your application. For example, you might verify that a credit + // card number matches a valid pattern, but you probably wouldn't + // perform an actual credit card authorization here. + Validate(*http.Request, Errors) Errors + } +) diff --git a/modules/middlewares/binding/common_test.go b/modules/middlewares/binding/common_test.go new file mode 100755 index 0000000000000..bff229758ddaf --- /dev/null +++ b/modules/middlewares/binding/common_test.go @@ -0,0 +1,127 @@ +// Copyright 2014 Martini Authors +// Copyright 2014 The Macaron Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"): you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. + +package binding + +import ( + "mime/multipart" + + "gitea.com/macaron/macaron" +) + +// These types are mostly contrived examples, but they're used +// across many test cases. The idea is to cover all the scenarios +// that this binding package might encounter in actual use. +type ( + // For basic test cases with a required field + Post struct { + Title string `form:"title" json:"title" binding:"Required"` + Content string `form:"content" json:"content"` + } + + // To be used as a nested struct (with a required field) + Person struct { + Name string `form:"name" json:"name" binding:"Required"` + Email string `form:"email" json:"email"` + } + + // For advanced test cases: multiple values, embedded + // and nested structs, an ignored field, and single + // and multiple file uploads + BlogPost struct { + Post + Id int `binding:"Required"` // JSON not specified here for test coverage + Ignored string `form:"-" json:"-"` + Ratings []int `form:"rating" json:"ratings"` + Author Person `json:"author"` + Coauthor *Person `json:"coauthor"` + HeaderImage *multipart.FileHeader + Pictures []*multipart.FileHeader `form:"picture"` + unexported string `form:"unexported"` + } + + EmbedPerson struct { + *Person + } + + SadForm struct { + AlphaDash string `form:"AlphaDash" binding:"AlphaDash"` + AlphaDashDot string `form:"AlphaDashDot" binding:"AlphaDashDot"` + Size string `form:"Size" binding:"Size(1)"` + SizeSlice []string `form:"SizeSlice" binding:"Size(1)"` + MinSize string `form:"MinSize" binding:"MinSize(5)"` + MinSizeSlice []string `form:"MinSizeSlice" binding:"MinSize(5)"` + MaxSize string `form:"MaxSize" binding:"MaxSize(1)"` + MaxSizeSlice []string `form:"MaxSizeSlice" binding:"MaxSize(1)"` + Range int `form:"Range" binding:"Range(1,2)"` + RangeInvalid int `form:"RangeInvalid" binding:"Range(1)"` + Email string `binding:"Email"` + Url string `form:"Url" binding:"Url"` + UrlEmpty string `form:"UrlEmpty" binding:"Url"` + In string `form:"In" binding:"Default(0);In(1,2,3)"` + InInvalid string `form:"InInvalid" binding:"In(1,2,3)"` + NotIn string `form:"NotIn" binding:"NotIn(1,2,3)"` + Include string `form:"Include" binding:"Include(a)"` + Exclude string `form:"Exclude" binding:"Exclude(a)"` + Empty string `binding:"OmitEmpty"` + } + + Group struct { + Name string `json:"name" binding:"Required"` + People []Person `json:"people" binding:"MinSize(1)"` + } + + CustomErrorHandle struct { + Rule `binding:"CustomRule"` + } + + // The common function signature of the handlers going under test. + handlerFunc func(interface{}, ...interface{}) macaron.Handler + + // Used for testing mapping an interface to the context + // If used (withInterface = true in the testCases), a modeler + // should be mapped to the context as well as BlogPost, meaning + // you can receive a modeler in your application instead of a + // concrete BlogPost. + modeler interface { + Model() string + } +) + +func (p Post) Validate(ctx *macaron.Context, errs Errors) Errors { + if len(p.Title) < 10 { + errs = append(errs, Error{ + FieldNames: []string{"title"}, + Classification: "LengthError", + Message: "Life is too short", + }) + } + return errs +} + +func (p Post) Model() string { + return p.Title +} + +func (g Group) Model() string { + return g.Name +} + +func (_ CustomErrorHandle) Error(_ *macaron.Context, _ Errors) {} + +const ( + testRoute = "/test" + formContentType = "application/x-www-form-urlencoded" +) diff --git a/modules/middlewares/binding/errorhandler_test.go b/modules/middlewares/binding/errorhandler_test.go new file mode 100755 index 0000000000000..b74a812eac38f --- /dev/null +++ b/modules/middlewares/binding/errorhandler_test.go @@ -0,0 +1,162 @@ +// Copyright 2014 Martini Authors +// Copyright 2014 The Macaron Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"): you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. + +package binding + +import ( + "io/ioutil" + "net/http" + "net/http/httptest" + "testing" + + . "github.com/smartystreets/goconvey/convey" +) + +var errorTestCases = []errorTestCase{ + { + description: "No errors", + errors: Errors{}, + expected: errorTestResult{ + statusCode: http.StatusOK, + }, + }, + { + description: "Deserialization error", + errors: Errors{ + { + Classification: ERR_DESERIALIZATION, + Message: "Some parser error here", + }, + }, + expected: errorTestResult{ + statusCode: http.StatusBadRequest, + contentType: _JSON_CONTENT_TYPE, + body: `[{"classification":"DeserializationError","message":"Some parser error here"}]`, + }, + }, + { + description: "Content-Type error", + errors: Errors{ + { + Classification: ERR_CONTENT_TYPE, + Message: "Empty Content-Type", + }, + }, + expected: errorTestResult{ + statusCode: http.StatusUnsupportedMediaType, + contentType: _JSON_CONTENT_TYPE, + body: `[{"classification":"ContentTypeError","message":"Empty Content-Type"}]`, + }, + }, + { + description: "Requirement error", + errors: Errors{ + { + FieldNames: []string{"some_field"}, + Classification: ERR_REQUIRED, + Message: "Required", + }, + }, + expected: errorTestResult{ + statusCode: STATUS_UNPROCESSABLE_ENTITY, + contentType: _JSON_CONTENT_TYPE, + body: `[{"fieldNames":["some_field"],"classification":"RequiredError","message":"Required"}]`, + }, + }, + { + description: "Bad header error", + errors: Errors{ + { + Classification: "HeaderError", + Message: "The X-Something header must be specified", + }, + }, + expected: errorTestResult{ + statusCode: STATUS_UNPROCESSABLE_ENTITY, + contentType: _JSON_CONTENT_TYPE, + body: `[{"classification":"HeaderError","message":"The X-Something header must be specified"}]`, + }, + }, + { + description: "Custom field error", + errors: Errors{ + { + FieldNames: []string{"month", "year"}, + Classification: "DateError", + Message: "The month and year must be in the future", + }, + }, + expected: errorTestResult{ + statusCode: STATUS_UNPROCESSABLE_ENTITY, + contentType: _JSON_CONTENT_TYPE, + body: `[{"fieldNames":["month","year"],"classification":"DateError","message":"The month and year must be in the future"}]`, + }, + }, + { + description: "Multiple errors", + errors: Errors{ + { + FieldNames: []string{"foo"}, + Classification: ERR_REQUIRED, + Message: "Required", + }, + { + FieldNames: []string{"foo"}, + Classification: "LengthError", + Message: "The length of the 'foo' field is too short", + }, + }, + expected: errorTestResult{ + statusCode: STATUS_UNPROCESSABLE_ENTITY, + contentType: _JSON_CONTENT_TYPE, + body: `[{"fieldNames":["foo"],"classification":"RequiredError","message":"Required"},{"fieldNames":["foo"],"classification":"LengthError","message":"The length of the 'foo' field is too short"}]`, + }, + }, +} + +func Test_ErrorHandler(t *testing.T) { + Convey("Error handler", t, func() { + for _, testCase := range errorTestCases { + performErrorTest(t, testCase) + } + }) +} + +func performErrorTest(t *testing.T, testCase errorTestCase) { + resp := httptest.NewRecorder() + + errorHandler(testCase.errors, resp) + + So(resp.Code, ShouldEqual, testCase.expected.statusCode) + So(resp.Header().Get("Content-Type"), ShouldEqual, testCase.expected.contentType) + + actualBody, err := ioutil.ReadAll(resp.Body) + So(err, ShouldBeNil) + So(string(actualBody), ShouldEqual, testCase.expected.body) +} + +type ( + errorTestCase struct { + description string + errors Errors + expected errorTestResult + } + + errorTestResult struct { + statusCode int + contentType string + body string + } +) diff --git a/modules/middlewares/binding/errors.go b/modules/middlewares/binding/errors.go new file mode 100644 index 0000000000000..8cbe44a9d1726 --- /dev/null +++ b/modules/middlewares/binding/errors.go @@ -0,0 +1,159 @@ +// Copyright 2014 Martini Authors +// Copyright 2014 The Macaron Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"): you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. + +package binding + +const ( + // Type mismatch errors. + ERR_CONTENT_TYPE = "ContentTypeError" + ERR_DESERIALIZATION = "DeserializationError" + ERR_INTERGER_TYPE = "IntegerTypeError" + ERR_BOOLEAN_TYPE = "BooleanTypeError" + ERR_FLOAT_TYPE = "FloatTypeError" + + // Validation errors. + ERR_REQUIRED = "RequiredError" + ERR_ALPHA_DASH = "AlphaDashError" + ERR_ALPHA_DASH_DOT = "AlphaDashDotError" + ERR_SIZE = "SizeError" + ERR_MIN_SIZE = "MinSizeError" + ERR_MAX_SIZE = "MaxSizeError" + ERR_RANGE = "RangeError" + ERR_EMAIL = "EmailError" + ERR_URL = "UrlError" + ERR_IN = "InError" + ERR_NOT_INT = "NotInError" + ERR_INCLUDE = "IncludeError" + ERR_EXCLUDE = "ExcludeError" + ERR_DEFAULT = "DefaultError" +) + +type ( + // Errors may be generated during deserialization, binding, + // or validation. This type is mapped to the context so you + // can inject it into your own handlers and use it in your + // application if you want all your errors to look the same. + Errors []Error + + Error struct { + // An error supports zero or more field names, because an + // error can morph three ways: (1) it can indicate something + // wrong with the request as a whole, (2) it can point to a + // specific problem with a particular input field, or (3) it + // can span multiple related input fields. + FieldNames []string `json:"fieldNames,omitempty"` + + // The classification is like an error code, convenient to + // use when processing or categorizing an error programmatically. + // It may also be called the "kind" of error. + Classification string `json:"classification,omitempty"` + + // Message should be human-readable and detailed enough to + // pinpoint and resolve the problem, but it should be brief. For + // example, a payload of 100 objects in a JSON array might have + // an error in the 41st object. The message should help the + // end user find and fix the error with their request. + Message string `json:"message,omitempty"` + } +) + +// Add adds an error associated with the fields indicated +// by fieldNames, with the given classification and message. +func (e *Errors) Add(fieldNames []string, classification, message string) { + *e = append(*e, Error{ + FieldNames: fieldNames, + Classification: classification, + Message: message, + }) +} + +// Len returns the number of errors. +func (e *Errors) Len() int { + return len(*e) +} + +// Has determines whether an Errors slice has an Error with +// a given classification in it; it does not search on messages +// or field names. +func (e *Errors) Has(class string) bool { + for _, err := range *e { + if err.Kind() == class { + return true + } + } + return false +} + +/* +// WithClass gets a copy of errors that are classified by the +// the given classification. +func (e *Errors) WithClass(classification string) Errors { + var errs Errors + for _, err := range *e { + if err.Kind() == classification { + errs = append(errs, err) + } + } + return errs +} + +// ForField gets a copy of errors that are associated with the +// field by the given name. +func (e *Errors) ForField(name string) Errors { + var errs Errors + for _, err := range *e { + for _, fieldName := range err.Fields() { + if fieldName == name { + errs = append(errs, err) + break + } + } + } + return errs +} + +// Get gets errors of a particular class for the specified +// field name. +func (e *Errors) Get(class, fieldName string) Errors { + var errs Errors + for _, err := range *e { + if err.Kind() == class { + for _, nameOfField := range err.Fields() { + if nameOfField == fieldName { + errs = append(errs, err) + break + } + } + } + } + return errs +} +*/ + +// Fields returns the list of field names this error is +// associated with. +func (e Error) Fields() []string { + return e.FieldNames +} + +// Kind returns this error's classification. +func (e Error) Kind() string { + return e.Classification +} + +// Error returns this error's message. +func (e Error) Error() string { + return e.Message +} diff --git a/modules/middlewares/binding/errors_test.go b/modules/middlewares/binding/errors_test.go new file mode 100755 index 0000000000000..0e9659c374847 --- /dev/null +++ b/modules/middlewares/binding/errors_test.go @@ -0,0 +1,115 @@ +// Copyright 2014 Martini Authors +// Copyright 2014 The Macaron Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"): you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. + +package binding + +import ( + "fmt" + "testing" + + . "github.com/smartystreets/goconvey/convey" +) + +func Test_ErrorsAdd(t *testing.T) { + Convey("Add new error", t, func() { + var actual Errors + expected := Errors{ + Error{ + FieldNames: []string{"Field1", "Field2"}, + Classification: "ErrorClass", + Message: "Some message", + }, + } + + actual.Add(expected[0].FieldNames, expected[0].Classification, expected[0].Message) + + So(len(actual), ShouldEqual, 1) + So(fmt.Sprintf("%#v", actual), ShouldEqual, fmt.Sprintf("%#v", expected)) + }) +} + +func Test_ErrorsLen(t *testing.T) { + Convey("Get number of errors", t, func() { + So(errorsTestSet.Len(), ShouldEqual, len(errorsTestSet)) + }) +} + +func Test_ErrorsHas(t *testing.T) { + Convey("Check error class", t, func() { + So(errorsTestSet.Has("ClassA"), ShouldBeTrue) + So(errorsTestSet.Has("ClassQ"), ShouldBeFalse) + }) +} + +func Test_ErrorGetters(t *testing.T) { + Convey("Get error detail", t, func() { + err := Error{ + FieldNames: []string{"field1", "field2"}, + Classification: "ErrorClass", + Message: "The message", + } + + fieldsActual := err.Fields() + + So(len(fieldsActual), ShouldEqual, 2) + So(fieldsActual[0], ShouldEqual, "field1") + So(fieldsActual[1], ShouldEqual, "field2") + + So(err.Kind(), ShouldEqual, "ErrorClass") + So(err.Error(), ShouldEqual, "The message") + }) +} + +/* +func TestErrorsWithClass(t *testing.T) { + expected := Errors{ + errorsTestSet[0], + errorsTestSet[3], + } + actualStr := fmt.Sprintf("%#v", errorsTestSet.WithClass("ClassA")) + expectedStr := fmt.Sprintf("%#v", expected) + if actualStr != expectedStr { + t.Errorf("Expected:\n%s\nbut got:\n%s", expectedStr, actualStr) + } +} +*/ + +var errorsTestSet = Errors{ + Error{ + FieldNames: []string{}, + Classification: "ClassA", + Message: "Foobar", + }, + Error{ + FieldNames: []string{}, + Classification: "ClassB", + Message: "Foo", + }, + Error{ + FieldNames: []string{"field1", "field2"}, + Classification: "ClassB", + Message: "Foobar", + }, + Error{ + FieldNames: []string{"field2"}, + Classification: "ClassA", + Message: "Foobar", + }, + Error{ + FieldNames: []string{"field2"}, + Classification: "ClassB", + Message: "Foobar", + }, +} diff --git a/modules/middlewares/binding/file_test.go b/modules/middlewares/binding/file_test.go new file mode 100755 index 0000000000000..be2fc547215cf --- /dev/null +++ b/modules/middlewares/binding/file_test.go @@ -0,0 +1,191 @@ +// Copyright 2014 Martini Authors +// Copyright 2014 The Macaron Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"): you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. + +package binding + +import ( + "bytes" + "mime/multipart" + "net/http" + "net/http/httptest" + "testing" + + . "github.com/smartystreets/goconvey/convey" + "gitea.com/macaron/macaron" +) + +var fileTestCases = []fileTestCase{ + { + description: "Single file", + singleFile: &fileInfo{ + fileName: "message.txt", + data: "All your binding are belong to us", + }, + }, + { + description: "Multiple files", + multipleFiles: []*fileInfo{ + &fileInfo{ + fileName: "cool-gopher-fact.txt", + data: "Did you know? https://plus.google.com/+MatthewHolt/posts/GmVfd6TPJ51", + }, + &fileInfo{ + fileName: "gophercon2014.txt", + data: "@bradfitz has a Go time machine: https://twitter.com/mholt6/status/459463953395875840", + }, + }, + }, + { + description: "Single file and multiple files", + singleFile: &fileInfo{ + fileName: "social media.txt", + data: "Hey, you should follow @mholt6 (Twitter) or +MatthewHolt (Google+)", + }, + multipleFiles: []*fileInfo{ + &fileInfo{ + fileName: "thank you!", + data: "Also, thanks to all the contributors of this package!", + }, + &fileInfo{ + fileName: "btw...", + data: "This tool translates JSON into Go structs: http://mholt.github.io/json-to-go/", + }, + }, + }, +} + +func Test_FileUploads(t *testing.T) { + Convey("Test file upload", t, func() { + for _, testCase := range fileTestCases { + performFileTest(t, MultipartForm, testCase) + } + }) +} + +func performFileTest(t *testing.T, binder handlerFunc, testCase fileTestCase) { + httpRecorder := httptest.NewRecorder() + m := macaron.Classic() + + fileTestHandler := func(actual BlogPost, errs Errors) { + assertFileAsExpected(t, testCase, actual.HeaderImage, testCase.singleFile) + So(len(testCase.multipleFiles), ShouldEqual, len(actual.Pictures)) + + for i, expectedFile := range testCase.multipleFiles { + if i >= len(actual.Pictures) { + break + } + assertFileAsExpected(t, testCase, actual.Pictures[i], expectedFile) + } + } + + m.Post(testRoute, binder(BlogPost{}), func(actual BlogPost, errs Errors) { + fileTestHandler(actual, errs) + }) + + m.ServeHTTP(httpRecorder, buildRequestWithFile(testCase)) + + switch httpRecorder.Code { + case http.StatusNotFound: + panic("Routing is messed up in test fixture (got 404): check methods and paths") + case http.StatusInternalServerError: + panic("Something bad happened on '" + testCase.description + "'") + } +} + +func assertFileAsExpected(t *testing.T, testCase fileTestCase, actual *multipart.FileHeader, expected *fileInfo) { + if expected == nil && actual == nil { + return + } + + if expected != nil && actual == nil { + So(actual, ShouldNotBeNil) + return + } else if expected == nil && actual != nil { + So(actual, ShouldBeNil) + return + } + + So(actual.Filename, ShouldEqual, expected.fileName) + So(unpackFileHeaderData(actual), ShouldEqual, expected.data) +} + +func buildRequestWithFile(testCase fileTestCase) *http.Request { + b := &bytes.Buffer{} + w := multipart.NewWriter(b) + + if testCase.singleFile != nil { + formFileSingle, err := w.CreateFormFile("header_image", testCase.singleFile.fileName) + if err != nil { + panic("Could not create FormFile (single file): " + err.Error()) + } + formFileSingle.Write([]byte(testCase.singleFile.data)) + } + + for _, file := range testCase.multipleFiles { + formFileMultiple, err := w.CreateFormFile("picture", file.fileName) + if err != nil { + panic("Could not create FormFile (multiple files): " + err.Error()) + } + formFileMultiple.Write([]byte(file.data)) + } + + err := w.Close() + if err != nil { + panic("Could not close multipart writer: " + err.Error()) + } + + req, err := http.NewRequest("POST", testRoute, b) + if err != nil { + panic("Could not create file upload request: " + err.Error()) + } + + req.Header.Set("Content-Type", w.FormDataContentType()) + + return req +} + +func unpackFileHeaderData(fh *multipart.FileHeader) string { + if fh == nil { + return "" + } + + f, err := fh.Open() + if err != nil { + panic("Could not open file header:" + err.Error()) + } + defer f.Close() + + var fb bytes.Buffer + _, err = fb.ReadFrom(f) + if err != nil { + panic("Could not read from file header:" + err.Error()) + } + + return fb.String() +} + +type ( + fileTestCase struct { + description string + input BlogPost + singleFile *fileInfo + multipleFiles []*fileInfo + } + + fileInfo struct { + fileName string + data string + } +) diff --git a/modules/middlewares/binding/form_test.go b/modules/middlewares/binding/form_test.go new file mode 100755 index 0000000000000..bd92e27d5606e --- /dev/null +++ b/modules/middlewares/binding/form_test.go @@ -0,0 +1,282 @@ +// Copyright 2014 Martini Authors +// Copyright 2014 The Macaron Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"): you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. + +package binding + +import ( + "fmt" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + + . "github.com/smartystreets/goconvey/convey" + "gitea.com/macaron/macaron" +) + +var formTestCases = []formTestCase{ + { + description: "Happy path", + shouldSucceed: true, + payload: `title=Glorious+Post+Title&content=Lorem+ipsum+dolor+sit+amet`, + contentType: formContentType, + expected: Post{Title: "Glorious Post Title", Content: "Lorem ipsum dolor sit amet"}, + }, + { + description: "Happy path with interface", + shouldSucceed: true, + withInterface: true, + payload: `title=Glorious+Post+Title&content=Lorem+ipsum+dolor+sit+amet`, + contentType: formContentType, + expected: Post{Title: "Glorious Post Title", Content: "Lorem ipsum dolor sit amet"}, + }, + { + description: "Empty payload", + shouldSucceed: false, + payload: ``, + contentType: formContentType, + expected: Post{}, + }, + { + description: "Empty content type", + shouldSucceed: false, + payload: `title=Glorious+Post+Title&content=Lorem+ipsum+dolor+sit+amet`, + contentType: ``, + expected: Post{}, + }, + { + description: "Malformed form body", + shouldSucceed: false, + payload: `title=%2`, + contentType: formContentType, + expected: Post{}, + }, + { + description: "With nested and embedded structs", + shouldSucceed: true, + payload: `title=Glorious+Post+Title&id=1&name=Matt+Holt`, + contentType: formContentType, + expected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1, Author: Person{Name: "Matt Holt"}}, + }, + { + description: "Required embedded struct field not specified", + shouldSucceed: false, + payload: `id=1&name=Matt+Holt`, + contentType: formContentType, + expected: BlogPost{Id: 1, Author: Person{Name: "Matt Holt"}}, + }, + { + description: "Required nested struct field not specified", + shouldSucceed: false, + payload: `title=Glorious+Post+Title&id=1`, + contentType: formContentType, + expected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1}, + }, + { + description: "Multiple values into slice", + shouldSucceed: true, + payload: `title=Glorious+Post+Title&id=1&name=Matt+Holt&rating=4&rating=3&rating=5`, + contentType: formContentType, + expected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1, Author: Person{Name: "Matt Holt"}, Ratings: []int{4, 3, 5}}, + }, + { + description: "Unexported field", + shouldSucceed: true, + payload: `title=Glorious+Post+Title&id=1&name=Matt+Holt&unexported=foo`, + contentType: formContentType, + expected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1, Author: Person{Name: "Matt Holt"}}, + }, + { + description: "Query string POST", + shouldSucceed: true, + payload: `title=Glorious+Post+Title&content=Lorem+ipsum+dolor+sit+amet`, + contentType: formContentType, + expected: Post{Title: "Glorious Post Title", Content: "Lorem ipsum dolor sit amet"}, + }, + { + description: "Query string with Content-Type (POST request)", + shouldSucceed: true, + queryString: "?title=Glorious+Post+Title&content=Lorem+ipsum+dolor+sit+amet", + payload: ``, + contentType: formContentType, + expected: Post{Title: "Glorious Post Title", Content: "Lorem ipsum dolor sit amet"}, + }, + { + description: "Query string without Content-Type (GET request)", + shouldSucceed: true, + method: "GET", + queryString: "?title=Glorious+Post+Title&content=Lorem+ipsum+dolor+sit+amet", + payload: ``, + expected: Post{Title: "Glorious Post Title", Content: "Lorem ipsum dolor sit amet"}, + }, + { + description: "Embed struct pointer", + shouldSucceed: true, + deepEqual: true, + method: "GET", + queryString: "?name=Glorious+Post+Title&email=Lorem+ipsum+dolor+sit+amet", + payload: ``, + expected: EmbedPerson{&Person{Name: "Glorious Post Title", Email: "Lorem ipsum dolor sit amet"}}, + }, + { + description: "Embed struct pointer remain nil if not binded", + shouldSucceed: true, + deepEqual: true, + method: "GET", + queryString: "?", + payload: ``, + expected: EmbedPerson{nil}, + }, + { + description: "Custom error handler", + shouldSucceed: true, + deepEqual: true, + method: "GET", + queryString: "?", + payload: ``, + expected: CustomErrorHandle{}, + }, +} + +func init() { + AddRule(&Rule{ + func(rule string) bool { + return rule == "CustomRule" + }, + func(errs Errors, _ string, _ interface{}) (bool, Errors) { + return false, errs + }, + }) + SetNameMapper(nameMapper) +} + +func Test_Form(t *testing.T) { + Convey("Test form", t, func() { + for _, testCase := range formTestCases { + performFormTest(t, Form, testCase) + } + }) +} + +func performFormTest(t *testing.T, binder handlerFunc, testCase formTestCase) { + resp := httptest.NewRecorder() + m := macaron.Classic() + + formTestHandler := func(actual interface{}, errs Errors) { + if testCase.shouldSucceed && len(errs) > 0 { + So(len(errs), ShouldEqual, 0) + } else if !testCase.shouldSucceed && len(errs) == 0 { + So(len(errs), ShouldNotEqual, 0) + } + expString := fmt.Sprintf("%+v", testCase.expected) + actString := fmt.Sprintf("%+v", actual) + if actString != expString && !(testCase.deepEqual && reflect.DeepEqual(testCase.expected, actual)) { + So(actString, ShouldEqual, expString) + } + } + + switch testCase.expected.(type) { + case Post: + if testCase.withInterface { + m.Post(testRoute, binder(Post{}, (*modeler)(nil)), func(actual Post, iface modeler, errs Errors) { + So(actual.Title, ShouldEqual, iface.Model()) + formTestHandler(actual, errs) + }) + } else { + m.Post(testRoute, binder(Post{}), func(actual Post, errs Errors) { + formTestHandler(actual, errs) + }) + m.Get(testRoute, binder(Post{}), func(actual Post, errs Errors) { + formTestHandler(actual, errs) + }) + } + + case BlogPost: + if testCase.withInterface { + m.Post(testRoute, binder(BlogPost{}, (*modeler)(nil)), func(actual BlogPost, iface modeler, errs Errors) { + So(actual.Title, ShouldEqual, iface.Model()) + formTestHandler(actual, errs) + }) + } else { + m.Post(testRoute, binder(BlogPost{}), func(actual BlogPost, errs Errors) { + formTestHandler(actual, errs) + }) + } + + case EmbedPerson: + m.Post(testRoute, binder(EmbedPerson{}), func(actual EmbedPerson, errs Errors) { + formTestHandler(actual, errs) + }) + m.Get(testRoute, binder(EmbedPerson{}), func(actual EmbedPerson, errs Errors) { + formTestHandler(actual, errs) + }) + case CustomErrorHandle: + m.Get(testRoute, binder(CustomErrorHandle{}), func(actual CustomErrorHandle, errs Errors) { + formTestHandler(actual, errs) + }) + } + + if len(testCase.method) == 0 { + testCase.method = "POST" + } + + req, err := http.NewRequest(testCase.method, testRoute+testCase.queryString, strings.NewReader(testCase.payload)) + if err != nil { + panic(err) + } + req.Header.Set("Content-Type", testCase.contentType) + + m.ServeHTTP(resp, req) + + switch resp.Code { + case http.StatusNotFound: + panic("Routing is messed up in test fixture (got 404): check methods and paths") + case http.StatusInternalServerError: + panic("Something bad happened on '" + testCase.description + "'") + } +} + +type ( + formTestCase struct { + description string + shouldSucceed bool + deepEqual bool + withInterface bool + queryString string + payload string + contentType string + expected interface{} + method string + } +) + +type defaultForm struct { + Default string `binding:"Default(hello world)"` +} + +func Test_Default(t *testing.T) { + Convey("Test default value", t, func() { + m := macaron.Classic() + m.Get("/", Bind(defaultForm{}), func(f defaultForm) { + So(f.Default, ShouldEqual, "hello world") + }) + resp := httptest.NewRecorder() + req, err := http.NewRequest("GET", "/", nil) + So(err, ShouldBeNil) + + m.ServeHTTP(resp, req) + }) +} diff --git a/modules/middlewares/binding/json_test.go b/modules/middlewares/binding/json_test.go new file mode 100755 index 0000000000000..3603e85b8adc5 --- /dev/null +++ b/modules/middlewares/binding/json_test.go @@ -0,0 +1,240 @@ +// Copyright 2014 Martini Authors +// Copyright 2014 The Macaron Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"): you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. + +package binding + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + . "github.com/smartystreets/goconvey/convey" + "gitea.com/macaron/macaron" +) + +var jsonTestCases = []jsonTestCase{ + { + description: "Happy path", + shouldSucceedOnJson: true, + payload: `{"title": "Glorious Post Title", "content": "Lorem ipsum dolor sit amet"}`, + contentType: _JSON_CONTENT_TYPE, + expected: Post{Title: "Glorious Post Title", Content: "Lorem ipsum dolor sit amet"}, + }, + { + description: "Happy path with interface", + shouldSucceedOnJson: true, + withInterface: true, + payload: `{"title": "Glorious Post Title", "content": "Lorem ipsum dolor sit amet"}`, + contentType: _JSON_CONTENT_TYPE, + expected: Post{Title: "Glorious Post Title", Content: "Lorem ipsum dolor sit amet"}, + }, + { + description: "Nil payload", + shouldSucceedOnJson: false, + payload: `-nil-`, + contentType: _JSON_CONTENT_TYPE, + expected: Post{}, + }, + { + description: "Empty payload", + shouldSucceedOnJson: false, + payload: ``, + contentType: _JSON_CONTENT_TYPE, + expected: Post{}, + }, + { + description: "Empty content type", + shouldSucceedOnJson: true, + shouldFailOnBind: true, + payload: `{"title": "Glorious Post Title", "content": "Lorem ipsum dolor sit amet"}`, + contentType: ``, + expected: Post{Title: "Glorious Post Title", Content: "Lorem ipsum dolor sit amet"}, + }, + { + description: "Unsupported content type", + shouldSucceedOnJson: true, + shouldFailOnBind: true, + payload: `{"title": "Glorious Post Title", "content": "Lorem ipsum dolor sit amet"}`, + contentType: `BoGuS`, + expected: Post{Title: "Glorious Post Title", Content: "Lorem ipsum dolor sit amet"}, + }, + { + description: "Malformed JSON", + shouldSucceedOnJson: false, + payload: `{"title":"foo"`, + contentType: _JSON_CONTENT_TYPE, + expected: Post{}, + }, + { + description: "Deserialization with nested and embedded struct", + shouldSucceedOnJson: true, + payload: `{"title":"Glorious Post Title", "id":1, "author":{"name":"Matt Holt"}}`, + contentType: _JSON_CONTENT_TYPE, + expected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1, Author: Person{Name: "Matt Holt"}}, + }, + { + description: "Deserialization with nested and embedded struct with interface", + shouldSucceedOnJson: true, + withInterface: true, + payload: `{"title":"Glorious Post Title", "id":1, "author":{"name":"Matt Holt"}}`, + contentType: _JSON_CONTENT_TYPE, + expected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1, Author: Person{Name: "Matt Holt"}}, + }, + { + description: "Required nested struct field not specified", + shouldSucceedOnJson: false, + payload: `{"title":"Glorious Post Title", "id":1, "author":{}}`, + contentType: _JSON_CONTENT_TYPE, + expected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1}, + }, + { + description: "Required embedded struct field not specified", + shouldSucceedOnJson: false, + payload: `{"id":1, "author":{"name":"Matt Holt"}}`, + contentType: _JSON_CONTENT_TYPE, + expected: BlogPost{Id: 1, Author: Person{Name: "Matt Holt"}}, + }, + { + description: "Slice of Posts", + shouldSucceedOnJson: true, + payload: `[{"title": "First Post"}, {"title": "Second Post"}]`, + contentType: _JSON_CONTENT_TYPE, + expected: []Post{Post{Title: "First Post"}, Post{Title: "Second Post"}}, + }, + { + description: "Slice of structs", + shouldSucceedOnJson: true, + payload: `{"name": "group1", "people": [{"name":"awoods"}, {"name": "anthony"}]}`, + contentType: _JSON_CONTENT_TYPE, + expected: Group{Name: "group1", People: []Person{Person{Name: "awoods"}, Person{Name: "anthony"}}}, + }, +} + +func Test_Json(t *testing.T) { + Convey("Test JSON", t, func() { + for _, testCase := range jsonTestCases { + performJsonTest(t, Json, testCase) + } + }) +} + +func performJsonTest(t *testing.T, binder handlerFunc, testCase jsonTestCase) { + var payload io.Reader + httpRecorder := httptest.NewRecorder() + m := macaron.Classic() + + jsonTestHandler := func(actual interface{}, errs Errors) { + if testCase.shouldSucceedOnJson && len(errs) > 0 { + So(len(errs), ShouldEqual, 0) + } else if !testCase.shouldSucceedOnJson && len(errs) == 0 { + So(len(errs), ShouldNotEqual, 0) + } + So(fmt.Sprintf("%+v", actual), ShouldEqual, fmt.Sprintf("%+v", testCase.expected)) + } + + switch testCase.expected.(type) { + case []Post: + if testCase.withInterface { + m.Post(testRoute, binder([]Post{}, (*modeler)(nil)), func(actual []Post, iface modeler, errs Errors) { + + for _, a := range actual { + So(a.Title, ShouldEqual, iface.Model()) + jsonTestHandler(a, errs) + } + }) + } else { + m.Post(testRoute, binder([]Post{}), func(actual []Post, errs Errors) { + jsonTestHandler(actual, errs) + }) + } + + case Post: + if testCase.withInterface { + m.Post(testRoute, binder(Post{}, (*modeler)(nil)), func(actual Post, iface modeler, errs Errors) { + So(actual.Title, ShouldEqual, iface.Model()) + jsonTestHandler(actual, errs) + }) + } else { + m.Post(testRoute, binder(Post{}), func(actual Post, errs Errors) { + jsonTestHandler(actual, errs) + }) + } + + case BlogPost: + if testCase.withInterface { + m.Post(testRoute, binder(BlogPost{}, (*modeler)(nil)), func(actual BlogPost, iface modeler, errs Errors) { + So(actual.Title, ShouldEqual, iface.Model()) + jsonTestHandler(actual, errs) + }) + } else { + m.Post(testRoute, binder(BlogPost{}), func(actual BlogPost, errs Errors) { + jsonTestHandler(actual, errs) + }) + } + case Group: + if testCase.withInterface { + m.Post(testRoute, binder(Group{}, (*modeler)(nil)), func(actual Group, iface modeler, errs Errors) { + So(actual.Name, ShouldEqual, iface.Model()) + jsonTestHandler(actual, errs) + }) + } else { + m.Post(testRoute, binder(Group{}), func(actual Group, errs Errors) { + jsonTestHandler(actual, errs) + }) + } + } + + if testCase.payload == "-nil-" { + payload = nil + } else { + payload = strings.NewReader(testCase.payload) + } + + req, err := http.NewRequest("POST", testRoute, payload) + if err != nil { + panic(err) + } + req.Header.Set("Content-Type", testCase.contentType) + + m.ServeHTTP(httpRecorder, req) + + switch httpRecorder.Code { + case http.StatusNotFound: + panic("Routing is messed up in test fixture (got 404): check method and path") + case http.StatusInternalServerError: + panic("Something bad happened on '" + testCase.description + "'") + default: + if testCase.shouldSucceedOnJson && + httpRecorder.Code != http.StatusOK && + !testCase.shouldFailOnBind { + So(httpRecorder.Code, ShouldEqual, http.StatusOK) + } + } +} + +type ( + jsonTestCase struct { + description string + withInterface bool + shouldSucceedOnJson bool + shouldFailOnBind bool + payload string + contentType string + expected interface{} + } +) diff --git a/modules/middlewares/binding/misc_test.go b/modules/middlewares/binding/misc_test.go new file mode 100755 index 0000000000000..d8f4aaf7f85d0 --- /dev/null +++ b/modules/middlewares/binding/misc_test.go @@ -0,0 +1,123 @@ +// Copyright 2014 Martini Authors +// Copyright 2014 The Macaron Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"): you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. + +package binding + +import ( + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + + . "github.com/smartystreets/goconvey/convey" + "gitea.com/macaron/macaron" +) + +// When binding from Form data, testing the type of data to bind +// and converting a string into that type is tedious, so these tests +// cover all those cases. +func Test_SetWithProperType(t *testing.T) { + Convey("Set with proper type", t, func() { + testInputs := map[string]string{ + "successful": `integer=-1&integer8=-8&integer16=-16&integer32=-32&integer64=-64&uinteger=1&uinteger8=8&uinteger16=16&uinteger32=32&uinteger64=64&boolean_1=true&fl32_1=32.3232&fl64_1=-64.6464646464&str=string`, + "errorful": `integer=&integer8=asdf&integer16=--&integer32=&integer64=dsf&uinteger=&uinteger8=asdf&uinteger16=+&uinteger32= 32 &uinteger64=+%20+&boolean_1=&boolean_2=asdf&fl32_1=asdf&fl32_2=&fl64_1=&fl64_2=asdfstr`, + } + + expectedOutputs := map[string]Everything{ + "successful": Everything{ + Integer: -1, + Integer8: -8, + Integer16: -16, + Integer32: -32, + Integer64: -64, + Uinteger: 1, + Uinteger8: 8, + Uinteger16: 16, + Uinteger32: 32, + Uinteger64: 64, + Boolean_1: true, + Fl32_1: 32.3232, + Fl64_1: -64.6464646464, + Str: "string", + }, + "errorful": Everything{}, + } + + for key, testCase := range testInputs { + httpRecorder := httptest.NewRecorder() + m := macaron.Classic() + + m.Post(testRoute, Form(Everything{}), func(actual Everything, errs Errors) { + So(fmt.Sprintf("%+v", actual), ShouldEqual, fmt.Sprintf("%+v", expectedOutputs[key])) + if key == "errorful" { + So(errs, ShouldHaveLength, 10) + } else { + So(errs, ShouldHaveLength, 0) + } + }) + req, err := http.NewRequest("POST", testRoute, strings.NewReader(testCase)) + if err != nil { + panic(err) + } + req.Header.Set("Content-Type", formContentType) + m.ServeHTTP(httpRecorder, req) + } + }) +} + +// Each binder middleware should assert that the struct passed in is not +// a pointer (to avoid race conditions) +func Test_EnsureNotPointer(t *testing.T) { + Convey("Ensure field is not a pointer", t, func() { + shouldPanic := func() { + defer func() { + So(recover(), ShouldNotBeNil) + }() + ensureNotPointer(&Post{}) + } + + shouldNotPanic := func() { + defer func() { + So(recover(), ShouldBeNil) + }() + ensureNotPointer(Post{}) + } + + shouldPanic() + shouldNotPanic() + }) +} + +// Used in testing setWithProperType; kind of clunky... +type Everything struct { + Integer int `form:"integer"` + Integer8 int8 `form:"integer8"` + Integer16 int16 `form:"integer16"` + Integer32 int32 `form:"integer32"` + Integer64 int64 `form:"integer64"` + Uinteger uint `form:"uinteger"` + Uinteger8 uint8 `form:"uinteger8"` + Uinteger16 uint16 `form:"uinteger16"` + Uinteger32 uint32 `form:"uinteger32"` + Uinteger64 uint64 `form:"uinteger64"` + Boolean_1 bool `form:"boolean_1"` + Boolean_2 bool `form:"boolean_2"` + Fl32_1 float32 `form:"fl32_1"` + Fl32_2 float32 `form:"fl32_2"` + Fl64_1 float64 `form:"fl64_1"` + Fl64_2 float64 `form:"fl64_2"` + Str string `form:"str"` +} diff --git a/modules/middlewares/binding/multipart_test.go b/modules/middlewares/binding/multipart_test.go new file mode 100755 index 0000000000000..9b74a8eb27d64 --- /dev/null +++ b/modules/middlewares/binding/multipart_test.go @@ -0,0 +1,155 @@ +// Copyright 2014 Martini Authors +// Copyright 2014 The Macaron Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"): you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. + +package binding + +import ( + "bytes" + "fmt" + "mime/multipart" + "net/http" + "net/http/httptest" + "strconv" + "testing" + + . "github.com/smartystreets/goconvey/convey" + "gitea.com/macaron/macaron" +) + +var multipartFormTestCases = []multipartFormTestCase{ + { + description: "Happy multipart form path", + shouldSucceed: true, + inputAndExpected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1, Author: Person{Name: "Matt Holt"}}, + }, + { + description: "FormValue called before req.MultipartReader(); see https://github.com/martini-contrib/csrf/issues/6", + shouldSucceed: true, + callFormValueBefore: true, + inputAndExpected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1, Author: Person{Name: "Matt Holt"}}, + }, + { + description: "Empty payload", + shouldSucceed: false, + inputAndExpected: BlogPost{}, + }, + { + description: "Missing required field (Id)", + shouldSucceed: false, + inputAndExpected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Author: Person{Name: "Matt Holt"}}, + }, + { + description: "Required embedded struct field not specified", + shouldSucceed: false, + inputAndExpected: BlogPost{Id: 1, Author: Person{Name: "Matt Holt"}}, + }, + { + description: "Required nested struct field not specified", + shouldSucceed: false, + inputAndExpected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1}, + }, + { + description: "Multiple values", + shouldSucceed: true, + inputAndExpected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1, Author: Person{Name: "Matt Holt"}, Ratings: []int{3, 5, 4}}, + }, + { + description: "Bad multipart encoding", + shouldSucceed: false, + malformEncoding: true, + }, +} + +func Test_MultipartForm(t *testing.T) { + Convey("Test multipart form", t, func() { + for _, testCase := range multipartFormTestCases { + performMultipartFormTest(t, MultipartForm, testCase) + } + }) +} + +func performMultipartFormTest(t *testing.T, binder handlerFunc, testCase multipartFormTestCase) { + httpRecorder := httptest.NewRecorder() + m := macaron.Classic() + + m.Post(testRoute, binder(BlogPost{}), func(actual BlogPost, errs Errors) { + if testCase.shouldSucceed && len(errs) > 0 { + So(len(errs), ShouldEqual, 0) + } else if !testCase.shouldSucceed && len(errs) == 0 { + So(len(errs), ShouldNotEqual, 0) + } + So(fmt.Sprintf("%+v", actual), ShouldEqual, fmt.Sprintf("%+v", testCase.inputAndExpected)) + }) + + multipartPayload, mpWriter := makeMultipartPayload(testCase) + + req, err := http.NewRequest("POST", testRoute, multipartPayload) + if err != nil { + panic(err) + } + + req.Header.Add("Content-Type", mpWriter.FormDataContentType()) + + err = mpWriter.Close() + if err != nil { + panic(err) + } + + if testCase.callFormValueBefore { + req.FormValue("foo") + } + + m.ServeHTTP(httpRecorder, req) + + switch httpRecorder.Code { + case http.StatusNotFound: + panic("Routing is messed up in test fixture (got 404): check methods and paths") + case http.StatusInternalServerError: + panic("Something bad happened on '" + testCase.description + "'") + } +} + +// Writes the input from a test case into a buffer using the multipart writer. +func makeMultipartPayload(testCase multipartFormTestCase) (*bytes.Buffer, *multipart.Writer) { + body := &bytes.Buffer{} + writer := multipart.NewWriter(body) + if testCase.malformEncoding { + // TODO: Break the multipart form parser which is apparently impervious!! + // (Get it to return an error. Trying to get 100% test coverage.) + body.Write([]byte(`--` + writer.Boundary() + `\nContent-Disposition: form-data; name="foo"\n\n--` + writer.Boundary() + `--`)) + return body, writer + } else { + writer.WriteField("title", testCase.inputAndExpected.Title) + writer.WriteField("content", testCase.inputAndExpected.Content) + writer.WriteField("id", strconv.Itoa(testCase.inputAndExpected.Id)) + writer.WriteField("ignored", testCase.inputAndExpected.Ignored) + for _, value := range testCase.inputAndExpected.Ratings { + writer.WriteField("rating", strconv.Itoa(value)) + } + writer.WriteField("name", testCase.inputAndExpected.Author.Name) + writer.WriteField("email", testCase.inputAndExpected.Author.Email) + return body, writer + } +} + +type ( + multipartFormTestCase struct { + description string + shouldSucceed bool + inputAndExpected BlogPost + malformEncoding bool + callFormValueBefore bool + } +) diff --git a/modules/middlewares/binding/validate_test.go b/modules/middlewares/binding/validate_test.go new file mode 100755 index 0000000000000..926594f6a3c0b --- /dev/null +++ b/modules/middlewares/binding/validate_test.go @@ -0,0 +1,412 @@ +// Copyright 2014 Martini Authors +// Copyright 2014 The Macaron Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"): you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. + +package binding + +import ( + "fmt" + "net/http" + "net/http/httptest" + "testing" + + . "github.com/smartystreets/goconvey/convey" + "gitea.com/macaron/macaron" +) + +var validationTestCases = []validationTestCase{ + { + description: "No errors", + data: BlogPost{ + Id: 1, + Post: Post{ + Title: "Behold The Title!", + Content: "And some content", + }, + Author: Person{ + Name: "Matt Holt", + }, + }, + expectedErrors: Errors{}, + }, + { + description: "ID required", + data: BlogPost{ + Post: Post{ + Title: "Behold The Title!", + Content: "And some content", + }, + Author: Person{ + Name: "Matt Holt", + }, + }, + expectedErrors: Errors{ + Error{ + FieldNames: []string{"id"}, + Classification: ERR_REQUIRED, + Message: "Required", + }, + }, + }, + { + description: "Embedded struct field required", + data: BlogPost{ + Id: 1, + Post: Post{ + Content: "Content given, but title is required", + }, + Author: Person{ + Name: "Matt Holt", + }, + }, + expectedErrors: Errors{ + Error{ + FieldNames: []string{"title"}, + Classification: ERR_REQUIRED, + Message: "Required", + }, + Error{ + FieldNames: []string{"title"}, + Classification: "LengthError", + Message: "Life is too short", + }, + }, + }, + { + description: "Nested struct field required", + data: BlogPost{ + Id: 1, + Post: Post{ + Title: "Behold The Title!", + Content: "And some content", + }, + }, + expectedErrors: Errors{ + Error{ + FieldNames: []string{"name"}, + Classification: ERR_REQUIRED, + Message: "Required", + }, + }, + }, + { + description: "Required field missing in nested struct pointer", + data: BlogPost{ + Id: 1, + Post: Post{ + Title: "Behold The Title!", + Content: "And some content", + }, + Author: Person{ + Name: "Matt Holt", + }, + Coauthor: &Person{}, + }, + expectedErrors: Errors{ + Error{ + FieldNames: []string{"name"}, + Classification: ERR_REQUIRED, + Message: "Required", + }, + }, + }, + { + description: "All required fields specified in nested struct pointer", + data: BlogPost{ + Id: 1, + Post: Post{ + Title: "Behold The Title!", + Content: "And some content", + }, + Author: Person{ + Name: "Matt Holt", + }, + Coauthor: &Person{ + Name: "Jeremy Saenz", + }, + }, + expectedErrors: Errors{}, + }, + { + description: "Custom validation should put an error", + data: BlogPost{ + Id: 1, + Post: Post{ + Title: "Too short", + Content: "And some content", + }, + Author: Person{ + Name: "Matt Holt", + }, + }, + expectedErrors: Errors{ + Error{ + FieldNames: []string{"title"}, + Classification: "LengthError", + Message: "Life is too short", + }, + }, + }, + { + description: "List Validation", + data: []BlogPost{ + BlogPost{ + Id: 1, + Post: Post{ + Title: "First Post", + Content: "And some content", + }, + Author: Person{ + Name: "Leeor Aharon", + }, + }, + BlogPost{ + Id: 2, + Post: Post{ + Title: "Second Post", + Content: "And some content", + }, + Author: Person{ + Name: "Leeor Aharon", + }, + }, + }, + expectedErrors: Errors{}, + }, + { + description: "List Validation w/ Errors", + data: []BlogPost{ + BlogPost{ + Id: 1, + Post: Post{ + Title: "First Post", + Content: "And some content", + }, + Author: Person{ + Name: "Leeor Aharon", + }, + }, + BlogPost{ + Id: 2, + Post: Post{ + Title: "Too Short", + Content: "And some content", + }, + Author: Person{ + Name: "Leeor Aharon", + }, + }, + }, + expectedErrors: Errors{ + Error{ + FieldNames: []string{"title"}, + Classification: "LengthError", + Message: "Life is too short", + }, + }, + }, + { + description: "List of invalid custom validations", + data: []SadForm{ + SadForm{ + AlphaDash: ",", + AlphaDashDot: ",", + Size: "123", + SizeSlice: []string{"1", "2", "3"}, + MinSize: ",", + MinSizeSlice: []string{",", ","}, + MaxSize: ",,", + MaxSizeSlice: []string{",", ","}, + Range: 3, + Email: ",", + Url: ",", + UrlEmpty: "", + InInvalid: "4", + NotIn: "1", + Include: "def", + Exclude: "abc", + }, + }, + expectedErrors: Errors{ + Error{ + FieldNames: []string{"AlphaDash"}, + Classification: "AlphaDashError", + Message: "AlphaDash", + }, + Error{ + FieldNames: []string{"AlphaDashDot"}, + Classification: "AlphaDashDot", + Message: "AlphaDashDot", + }, + Error{ + FieldNames: []string{"Size"}, + Classification: "Size", + Message: "Size", + }, + Error{ + FieldNames: []string{"Size"}, + Classification: "Size", + Message: "Size", + }, + Error{ + FieldNames: []string{"MinSize"}, + Classification: "MinSize", + Message: "MinSize", + }, + Error{ + FieldNames: []string{"MinSize"}, + Classification: "MinSize", + Message: "MinSize", + }, + Error{ + FieldNames: []string{"MaxSize"}, + Classification: "MaxSize", + Message: "MaxSize", + }, + Error{ + FieldNames: []string{"MaxSize"}, + Classification: "MaxSize", + Message: "MaxSize", + }, + Error{ + FieldNames: []string{"Range"}, + Classification: "Range", + Message: "Range", + }, + Error{ + FieldNames: []string{"Email"}, + Classification: "Email", + Message: "Email", + }, + Error{ + FieldNames: []string{"Url"}, + Classification: "Url", + Message: "Url", + }, + Error{ + FieldNames: []string{"Default"}, + Classification: "Default", + Message: "Default", + }, + Error{ + FieldNames: []string{"InInvalid"}, + Classification: "In", + Message: "In", + }, + Error{ + FieldNames: []string{"NotIn"}, + Classification: "NotIn", + Message: "NotIn", + }, + Error{ + FieldNames: []string{"Include"}, + Classification: "Include", + Message: "Include", + }, + Error{ + FieldNames: []string{"Exclude"}, + Classification: "Exclude", + Message: "Exclude", + }, + }, + }, + { + description: "List of valid custom validations", + data: []SadForm{ + SadForm{ + AlphaDash: "123-456", + AlphaDashDot: "123.456", + Size: "1", + SizeSlice: []string{"1"}, + MinSize: "12345", + MinSizeSlice: []string{"1", "2", "3", "4", "5"}, + MaxSize: "1", + MaxSizeSlice: []string{"1"}, + Range: 2, + In: "1", + InInvalid: "1", + Email: "123@456.com", + Url: "http://123.456", + Include: "abc", + }, + }, + }, + { + description: "slice of structs Validation", + data: Group{ + Name: "group1", + People: []Person{ + Person{Name: "anthony"}, + Person{Name: "awoods"}, + }, + }, + expectedErrors: Errors{}, + }, + { + description: "slice of structs Validation failer", + data: Group{ + Name: "group1", + People: []Person{ + Person{Name: "anthony"}, + Person{Name: ""}, + }, + }, + expectedErrors: Errors{ + Error{ + FieldNames: []string{"name"}, + Classification: ERR_REQUIRED, + Message: "Required", + }, + }, + }, +} + +func Test_Validation(t *testing.T) { + Convey("Test validation", t, func() { + for _, testCase := range validationTestCases { + performValidationTest(t, testCase) + } + }) +} + +func performValidationTest(t *testing.T, testCase validationTestCase) { + httpRecorder := httptest.NewRecorder() + m := macaron.Classic() + + m.Post(testRoute, Validate(testCase.data), func(actual Errors) { + So(fmt.Sprintf("%+v", actual), ShouldEqual, fmt.Sprintf("%+v", testCase.expectedErrors)) + }) + + req, err := http.NewRequest("POST", testRoute, nil) + if err != nil { + panic(err) + } + + m.ServeHTTP(httpRecorder, req) + + switch httpRecorder.Code { + case http.StatusNotFound: + panic("Routing is messed up in test fixture (got 404): check methods and paths") + case http.StatusInternalServerError: + panic("Something bad happened on '" + testCase.description + "'") + } +} + +type ( + validationTestCase struct { + description string + data interface{} + expectedErrors Errors + } +) diff --git a/routers/install.go b/routers/install.go index 8c62a76b7a396..9b5831a9601e8 100644 --- a/routers/install.go +++ b/routers/install.go @@ -6,7 +6,6 @@ package routers import ( - "context" "fmt" "net/http" "os" @@ -16,8 +15,8 @@ import ( "time" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/modules/auth" - gitea_context "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/modules/forms" "code.gitea.io/gitea/modules/generate" "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/log" @@ -39,14 +38,10 @@ const ( tplPostInstall = "post-install" ) -var ( - installContextKey interface{} = "install_context" -) - // InstallRoutes represents the install routes func InstallRoutes() http.Handler { r := chi.NewRouter() - sessionManager := gitea_context.NewSessions() + sessionManager := context.NewSessions() r.Use(sessionManager.LoadAndSave) r.Use(func(next http.Handler) http.Handler { return InstallInit(next, sessionManager) @@ -59,9 +54,6 @@ func InstallRoutes() http.Handler { return r } -// InstallContext represents a context for installation routes -type InstallContext = gitea_context.DefaultContext - // InstallInit prepare for rendering installation page func InstallInit(next http.Handler, sessionManager *scs.SessionManager) http.Handler { rnd := render.New(render.Options{ @@ -77,9 +69,9 @@ func InstallInit(next http.Handler, sessionManager *scs.SessionManager) http.Han return } - var locale = gitea_context.Locale(resp, req) + var locale = context.Locale(resp, req) var startTime = time.Now() - var ctx = InstallContext{ + var ctx = context.InstallContext{ Resp: resp, Req: req, Locale: locale, @@ -99,22 +91,23 @@ func InstallInit(next http.Handler, sessionManager *scs.SessionManager) http.Han Sessions: sessionManager, } - req = req.WithContext(context.WithValue(req.Context(), installContextKey, &ctx)) + req = context.WithInstallContext(req, &ctx) + ctx.Req = req next.ServeHTTP(resp, req) }) } // WrapInstall converts an install route to a chi route -func WrapInstall(f func(ctx *InstallContext)) http.HandlerFunc { +func WrapInstall(f func(ctx *context.InstallContext)) http.HandlerFunc { return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { - ctx := req.Context().Value(installContextKey).(*InstallContext) + ctx := context.GetInstallContext(req) f(ctx) }) } // Install render installation page -func Install(ctx *InstallContext) { - form := auth.InstallForm{} +func Install(ctx *context.InstallContext) { + form := forms.InstallForm{} // Database settings form.DbHost = setting.Database.Host @@ -182,13 +175,14 @@ func Install(ctx *InstallContext) { form.DefaultEnableTimetracking = setting.Service.DefaultEnableTimetracking form.NoReplyAddress = setting.Service.NoReplyAddress - auth.AssignForm(form, ctx.Data) + forms.AssignForm(form, ctx.Data) _ = ctx.HTML(200, tplInstall) } // InstallPost response for submit install items -func InstallPost(ctx *InstallContext) { - var form auth.InstallForm +func InstallPost(ctx *context.InstallContext) { + var form forms.InstallForm + _ = ctx.Bind(&form) var err error ctx.Data["CurDbOption"] = form.DbType @@ -459,7 +453,7 @@ func InstallPost(ctx *InstallContext) { } days := 86400 * setting.LogInRememberDays - ctx.Req.AddCookie(gitea_context.NewCookie(setting.CookieUserName, u.Name, days)) + ctx.Req.AddCookie(context.NewCookie(setting.CookieUserName, u.Name, days)) //ctx.SetSuperSecureCookie(base.EncodeMD5(u.Rands+u.Passwd), // setting.CookieRememberName, u.Name, days, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true) @@ -481,7 +475,7 @@ func InstallPost(ctx *InstallContext) { log.Info("First-time run install finished!") - ctx.Flash(gitea_context.SuccessFlash, ctx.Tr("install.install_success")) + ctx.Flash(context.SuccessFlash, ctx.Tr("install.install_success")) ctx.Resp.Header().Add("Refresh", "1; url="+setting.AppURL+"user/login") if err := ctx.HTML(200, tplPostInstall); err != nil { diff --git a/routers/routes/macaron.go b/routers/routes/macaron.go index 1f9776c72dbec..5515019edfcd7 100644 --- a/routers/routes/macaron.go +++ b/routers/routes/macaron.go @@ -188,8 +188,6 @@ func RegisterMacaronRoutes(m *macaron.Macaron) { m.Get("/organizations", routers.ExploreOrganizations) m.Get("/code", routers.ExploreCode) }, ignSignIn) - m.Combo("/install", routers.InstallInit).Get(routers.Install). - Post(bindIgnErr(auth.InstallForm{}), routers.InstallPost) m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues) m.Get("/milestones", reqSignIn, reqMilestonesDashboardPageEnabled, user.Milestones) diff --git a/templates/base/alert_new.tmpl b/templates/base/alert_new.tmpl new file mode 100644 index 0000000000000..0cbd8bb396e90 --- /dev/null +++ b/templates/base/alert_new.tmpl @@ -0,0 +1,15 @@ +{{if .ErrorMsg}} +
+

{{.ErrorMsg | Str2html}}

+
+{{end}} +{{if .SuccessMsg}} +
+

{{.SuccessMsg | Str2html}}

+
+{{end}} +{{if .InfoMsg}} +
+

{{.InfoMsg | Str2html}}

+
+{{end}} diff --git a/templates/install.tmpl b/templates/install.tmpl index 62aaeaed9a351..f3825241b1152 100644 --- a/templates/install.tmpl +++ b/templates/install.tmpl @@ -6,7 +6,7 @@ {{.i18n.Tr "install.title"}}
- {{template "base/alert" .}} + {{template "base/alert_new" .}}

{{.i18n.Tr "install.docker_helper" "https://docs.gitea.io/en-us/install-with-docker/" | Safe}}

diff --git a/vendor/github.com/gopherjs/gopherjs/LICENSE b/vendor/github.com/gopherjs/gopherjs/LICENSE new file mode 100644 index 0000000000000..d496fef109260 --- /dev/null +++ b/vendor/github.com/gopherjs/gopherjs/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2013 Richard Musiol. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/gopherjs/gopherjs/js/js.go b/vendor/github.com/gopherjs/gopherjs/js/js.go new file mode 100644 index 0000000000000..3fbf1d88c6098 --- /dev/null +++ b/vendor/github.com/gopherjs/gopherjs/js/js.go @@ -0,0 +1,168 @@ +// Package js provides functions for interacting with native JavaScript APIs. Calls to these functions are treated specially by GopherJS and translated directly to their corresponding JavaScript syntax. +// +// Use MakeWrapper to expose methods to JavaScript. When passing values directly, the following type conversions are performed: +// +// | Go type | JavaScript type | Conversions back to interface{} | +// | --------------------- | --------------------- | ------------------------------- | +// | bool | Boolean | bool | +// | integers and floats | Number | float64 | +// | string | String | string | +// | []int8 | Int8Array | []int8 | +// | []int16 | Int16Array | []int16 | +// | []int32, []int | Int32Array | []int | +// | []uint8 | Uint8Array | []uint8 | +// | []uint16 | Uint16Array | []uint16 | +// | []uint32, []uint | Uint32Array | []uint | +// | []float32 | Float32Array | []float32 | +// | []float64 | Float64Array | []float64 | +// | all other slices | Array | []interface{} | +// | arrays | see slice type | see slice type | +// | functions | Function | func(...interface{}) *js.Object | +// | time.Time | Date | time.Time | +// | - | instanceof Node | *js.Object | +// | maps, structs | instanceof Object | map[string]interface{} | +// +// Additionally, for a struct containing a *js.Object field, only the content of the field will be passed to JavaScript and vice versa. +package js + +// Object is a container for a native JavaScript object. Calls to its methods are treated specially by GopherJS and translated directly to their JavaScript syntax. A nil pointer to Object is equal to JavaScript's "null". Object can not be used as a map key. +type Object struct{ object *Object } + +// Get returns the object's property with the given key. +func (o *Object) Get(key string) *Object { return o.object.Get(key) } + +// Set assigns the value to the object's property with the given key. +func (o *Object) Set(key string, value interface{}) { o.object.Set(key, value) } + +// Delete removes the object's property with the given key. +func (o *Object) Delete(key string) { o.object.Delete(key) } + +// Length returns the object's "length" property, converted to int. +func (o *Object) Length() int { return o.object.Length() } + +// Index returns the i'th element of an array. +func (o *Object) Index(i int) *Object { return o.object.Index(i) } + +// SetIndex sets the i'th element of an array. +func (o *Object) SetIndex(i int, value interface{}) { o.object.SetIndex(i, value) } + +// Call calls the object's method with the given name. +func (o *Object) Call(name string, args ...interface{}) *Object { return o.object.Call(name, args...) } + +// Invoke calls the object itself. This will fail if it is not a function. +func (o *Object) Invoke(args ...interface{}) *Object { return o.object.Invoke(args...) } + +// New creates a new instance of this type object. This will fail if it not a function (constructor). +func (o *Object) New(args ...interface{}) *Object { return o.object.New(args...) } + +// Bool returns the object converted to bool according to JavaScript type conversions. +func (o *Object) Bool() bool { return o.object.Bool() } + +// String returns the object converted to string according to JavaScript type conversions. +func (o *Object) String() string { return o.object.String() } + +// Int returns the object converted to int according to JavaScript type conversions (parseInt). +func (o *Object) Int() int { return o.object.Int() } + +// Int64 returns the object converted to int64 according to JavaScript type conversions (parseInt). +func (o *Object) Int64() int64 { return o.object.Int64() } + +// Uint64 returns the object converted to uint64 according to JavaScript type conversions (parseInt). +func (o *Object) Uint64() uint64 { return o.object.Uint64() } + +// Float returns the object converted to float64 according to JavaScript type conversions (parseFloat). +func (o *Object) Float() float64 { return o.object.Float() } + +// Interface returns the object converted to interface{}. See table in package comment for details. +func (o *Object) Interface() interface{} { return o.object.Interface() } + +// Unsafe returns the object as an uintptr, which can be converted via unsafe.Pointer. Not intended for public use. +func (o *Object) Unsafe() uintptr { return o.object.Unsafe() } + +// Error encapsulates JavaScript errors. Those are turned into a Go panic and may be recovered, giving an *Error that holds the JavaScript error object. +type Error struct { + *Object +} + +// Error returns the message of the encapsulated JavaScript error object. +func (err *Error) Error() string { + return "JavaScript error: " + err.Get("message").String() +} + +// Stack returns the stack property of the encapsulated JavaScript error object. +func (err *Error) Stack() string { + return err.Get("stack").String() +} + +// Global gives JavaScript's global object ("window" for browsers and "GLOBAL" for Node.js). +var Global *Object + +// Module gives the value of the "module" variable set by Node.js. Hint: Set a module export with 'js.Module.Get("exports").Set("exportName", ...)'. +var Module *Object + +// Undefined gives the JavaScript value "undefined". +var Undefined *Object + +// Debugger gets compiled to JavaScript's "debugger;" statement. +func Debugger() {} + +// InternalObject returns the internal JavaScript object that represents i. Not intended for public use. +func InternalObject(i interface{}) *Object { + return nil +} + +// MakeFunc wraps a function and gives access to the values of JavaScript's "this" and "arguments" keywords. +func MakeFunc(fn func(this *Object, arguments []*Object) interface{}) *Object { + return Global.Call("$makeFunc", InternalObject(fn)) +} + +// Keys returns the keys of the given JavaScript object. +func Keys(o *Object) []string { + if o == nil || o == Undefined { + return nil + } + a := Global.Get("Object").Call("keys", o) + s := make([]string, a.Length()) + for i := 0; i < a.Length(); i++ { + s[i] = a.Index(i).String() + } + return s +} + +// MakeWrapper creates a JavaScript object which has wrappers for the exported methods of i. Use explicit getter and setter methods to expose struct fields to JavaScript. +func MakeWrapper(i interface{}) *Object { + v := InternalObject(i) + o := Global.Get("Object").New() + o.Set("__internal_object__", v) + methods := v.Get("constructor").Get("methods") + for i := 0; i < methods.Length(); i++ { + m := methods.Index(i) + if m.Get("pkg").String() != "" { // not exported + continue + } + o.Set(m.Get("name").String(), func(args ...*Object) *Object { + return Global.Call("$externalizeFunction", v.Get(m.Get("prop").String()), m.Get("typ"), true).Call("apply", v, args) + }) + } + return o +} + +// NewArrayBuffer creates a JavaScript ArrayBuffer from a byte slice. +func NewArrayBuffer(b []byte) *Object { + slice := InternalObject(b) + offset := slice.Get("$offset").Int() + length := slice.Get("$length").Int() + return slice.Get("$array").Get("buffer").Call("slice", offset, offset+length) +} + +// M is a simple map type. It is intended as a shorthand for JavaScript objects (before conversion). +type M map[string]interface{} + +// S is a simple slice type. It is intended as a shorthand for JavaScript arrays (before conversion). +type S []interface{} + +func init() { + // avoid dead code elimination + e := Error{} + _ = e +} diff --git a/vendor/github.com/jtolds/gls/LICENSE b/vendor/github.com/jtolds/gls/LICENSE new file mode 100644 index 0000000000000..9b4a822d92c5f --- /dev/null +++ b/vendor/github.com/jtolds/gls/LICENSE @@ -0,0 +1,18 @@ +Copyright (c) 2013, Space Monkey, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/jtolds/gls/README.md b/vendor/github.com/jtolds/gls/README.md new file mode 100644 index 0000000000000..4ebb692fb1899 --- /dev/null +++ b/vendor/github.com/jtolds/gls/README.md @@ -0,0 +1,89 @@ +gls +=== + +Goroutine local storage + +### IMPORTANT NOTE ### + +It is my duty to point you to https://blog.golang.org/context, which is how +Google solves all of the problems you'd perhaps consider using this package +for at scale. + +One downside to Google's approach is that *all* of your functions must have +a new first argument, but after clearing that hurdle everything else is much +better. + +If you aren't interested in this warning, read on. + +### Huhwaht? Why? ### + +Every so often, a thread shows up on the +[golang-nuts](https://groups.google.com/d/forum/golang-nuts) asking for some +form of goroutine-local-storage, or some kind of goroutine id, or some kind of +context. There are a few valid use cases for goroutine-local-storage, one of +the most prominent being log line context. One poster was interested in being +able to log an HTTP request context id in every log line in the same goroutine +as the incoming HTTP request, without having to change every library and +function call he was interested in logging. + +This would be pretty useful. Provided that you could get some kind of +goroutine-local-storage, you could call +[log.SetOutput](http://golang.org/pkg/log/#SetOutput) with your own logging +writer that checks goroutine-local-storage for some context information and +adds that context to your log lines. + +But alas, Andrew Gerrand's typically diplomatic answer to the question of +goroutine-local variables was: + +> We wouldn't even be having this discussion if thread local storage wasn't +> useful. But every feature comes at a cost, and in my opinion the cost of +> threadlocals far outweighs their benefits. They're just not a good fit for +> Go. + +So, yeah, that makes sense. That's a pretty good reason for why the language +won't support a specific and (relatively) unuseful feature that requires some +runtime changes, just for the sake of a little bit of log improvement. + +But does Go require runtime changes? + +### How it works ### + +Go has pretty fantastic introspective and reflective features, but one thing Go +doesn't give you is any kind of access to the stack pointer, or frame pointer, +or goroutine id, or anything contextual about your current stack. It gives you +access to your list of callers, but only along with program counters, which are +fixed at compile time. + +But it does give you the stack. + +So, we define 16 special functions and embed base-16 tags into the stack using +the call order of those 16 functions. Then, we can read our tags back out of +the stack looking at the callers list. + +We then use these tags as an index into a traditional map for implementing +this library. + +### What are people saying? ### + +"Wow, that's horrifying." + +"This is the most terrible thing I have seen in a very long time." + +"Where is it getting a context from? Is this serializing all the requests? +What the heck is the client being bound to? What are these tags? Why does he +need callers? Oh god no. No no no." + +### Docs ### + +Please see the docs at http://godoc.org/github.com/jtolds/gls + +### Related ### + +If you're okay relying on the string format of the current runtime stacktrace +including a unique goroutine id (not guaranteed by the spec or anything, but +very unlikely to change within a Go release), you might be able to squeeze +out a bit more performance by using this similar library, inspired by some +code Brad Fitzpatrick wrote for debugging his HTTP/2 library: +https://github.com/tylerb/gls (in contrast, jtolds/gls doesn't require +any knowledge of the string format of the runtime stacktrace, which +probably adds unnecessary overhead). diff --git a/vendor/github.com/jtolds/gls/context.go b/vendor/github.com/jtolds/gls/context.go new file mode 100644 index 0000000000000..618a171061335 --- /dev/null +++ b/vendor/github.com/jtolds/gls/context.go @@ -0,0 +1,153 @@ +// Package gls implements goroutine-local storage. +package gls + +import ( + "sync" +) + +var ( + mgrRegistry = make(map[*ContextManager]bool) + mgrRegistryMtx sync.RWMutex +) + +// Values is simply a map of key types to value types. Used by SetValues to +// set multiple values at once. +type Values map[interface{}]interface{} + +// ContextManager is the main entrypoint for interacting with +// Goroutine-local-storage. You can have multiple independent ContextManagers +// at any given time. ContextManagers are usually declared globally for a given +// class of context variables. You should use NewContextManager for +// construction. +type ContextManager struct { + mtx sync.Mutex + values map[uint]Values +} + +// NewContextManager returns a brand new ContextManager. It also registers the +// new ContextManager in the ContextManager registry which is used by the Go +// method. ContextManagers are typically defined globally at package scope. +func NewContextManager() *ContextManager { + mgr := &ContextManager{values: make(map[uint]Values)} + mgrRegistryMtx.Lock() + defer mgrRegistryMtx.Unlock() + mgrRegistry[mgr] = true + return mgr +} + +// Unregister removes a ContextManager from the global registry, used by the +// Go method. Only intended for use when you're completely done with a +// ContextManager. Use of Unregister at all is rare. +func (m *ContextManager) Unregister() { + mgrRegistryMtx.Lock() + defer mgrRegistryMtx.Unlock() + delete(mgrRegistry, m) +} + +// SetValues takes a collection of values and a function to call for those +// values to be set in. Anything further down the stack will have the set +// values available through GetValue. SetValues will add new values or replace +// existing values of the same key and will not mutate or change values for +// previous stack frames. +// SetValues is slow (makes a copy of all current and new values for the new +// gls-context) in order to reduce the amount of lookups GetValue requires. +func (m *ContextManager) SetValues(new_values Values, context_call func()) { + if len(new_values) == 0 { + context_call() + return + } + + mutated_keys := make([]interface{}, 0, len(new_values)) + mutated_vals := make(Values, len(new_values)) + + EnsureGoroutineId(func(gid uint) { + m.mtx.Lock() + state, found := m.values[gid] + if !found { + state = make(Values, len(new_values)) + m.values[gid] = state + } + m.mtx.Unlock() + + for key, new_val := range new_values { + mutated_keys = append(mutated_keys, key) + if old_val, ok := state[key]; ok { + mutated_vals[key] = old_val + } + state[key] = new_val + } + + defer func() { + if !found { + m.mtx.Lock() + delete(m.values, gid) + m.mtx.Unlock() + return + } + + for _, key := range mutated_keys { + if val, ok := mutated_vals[key]; ok { + state[key] = val + } else { + delete(state, key) + } + } + }() + + context_call() + }) +} + +// GetValue will return a previously set value, provided that the value was set +// by SetValues somewhere higher up the stack. If the value is not found, ok +// will be false. +func (m *ContextManager) GetValue(key interface{}) ( + value interface{}, ok bool) { + gid, ok := GetGoroutineId() + if !ok { + return nil, false + } + + m.mtx.Lock() + state, found := m.values[gid] + m.mtx.Unlock() + + if !found { + return nil, false + } + value, ok = state[key] + return value, ok +} + +func (m *ContextManager) getValues() Values { + gid, ok := GetGoroutineId() + if !ok { + return nil + } + m.mtx.Lock() + state, _ := m.values[gid] + m.mtx.Unlock() + return state +} + +// Go preserves ContextManager values and Goroutine-local-storage across new +// goroutine invocations. The Go method makes a copy of all existing values on +// all registered context managers and makes sure they are still set after +// kicking off the provided function in a new goroutine. If you don't use this +// Go method instead of the standard 'go' keyword, you will lose values in +// ContextManagers, as goroutines have brand new stacks. +func Go(cb func()) { + mgrRegistryMtx.RLock() + defer mgrRegistryMtx.RUnlock() + + for mgr := range mgrRegistry { + values := mgr.getValues() + if len(values) > 0 { + cb = func(mgr *ContextManager, cb func()) func() { + return func() { mgr.SetValues(values, cb) } + }(mgr, cb) + } + } + + go cb() +} diff --git a/vendor/github.com/jtolds/gls/gen_sym.go b/vendor/github.com/jtolds/gls/gen_sym.go new file mode 100644 index 0000000000000..7f615cce937dd --- /dev/null +++ b/vendor/github.com/jtolds/gls/gen_sym.go @@ -0,0 +1,21 @@ +package gls + +import ( + "sync" +) + +var ( + keyMtx sync.Mutex + keyCounter uint64 +) + +// ContextKey is a throwaway value you can use as a key to a ContextManager +type ContextKey struct{ id uint64 } + +// GenSym will return a brand new, never-before-used ContextKey +func GenSym() ContextKey { + keyMtx.Lock() + defer keyMtx.Unlock() + keyCounter += 1 + return ContextKey{id: keyCounter} +} diff --git a/vendor/github.com/jtolds/gls/gid.go b/vendor/github.com/jtolds/gls/gid.go new file mode 100644 index 0000000000000..c16bf3a554f97 --- /dev/null +++ b/vendor/github.com/jtolds/gls/gid.go @@ -0,0 +1,25 @@ +package gls + +var ( + stackTagPool = &idPool{} +) + +// Will return this goroutine's identifier if set. If you always need a +// goroutine identifier, you should use EnsureGoroutineId which will make one +// if there isn't one already. +func GetGoroutineId() (gid uint, ok bool) { + return readStackTag() +} + +// Will call cb with the current goroutine identifier. If one hasn't already +// been generated, one will be created and set first. The goroutine identifier +// might be invalid after cb returns. +func EnsureGoroutineId(cb func(gid uint)) { + if gid, ok := readStackTag(); ok { + cb(gid) + return + } + gid := stackTagPool.Acquire() + defer stackTagPool.Release(gid) + addStackTag(gid, func() { cb(gid) }) +} diff --git a/vendor/github.com/jtolds/gls/id_pool.go b/vendor/github.com/jtolds/gls/id_pool.go new file mode 100644 index 0000000000000..b7974ae0026e7 --- /dev/null +++ b/vendor/github.com/jtolds/gls/id_pool.go @@ -0,0 +1,34 @@ +package gls + +// though this could probably be better at keeping ids smaller, the goal of +// this class is to keep a registry of the smallest unique integer ids +// per-process possible + +import ( + "sync" +) + +type idPool struct { + mtx sync.Mutex + released []uint + max_id uint +} + +func (p *idPool) Acquire() (id uint) { + p.mtx.Lock() + defer p.mtx.Unlock() + if len(p.released) > 0 { + id = p.released[len(p.released)-1] + p.released = p.released[:len(p.released)-1] + return id + } + id = p.max_id + p.max_id++ + return id +} + +func (p *idPool) Release(id uint) { + p.mtx.Lock() + defer p.mtx.Unlock() + p.released = append(p.released, id) +} diff --git a/vendor/github.com/jtolds/gls/stack_tags.go b/vendor/github.com/jtolds/gls/stack_tags.go new file mode 100644 index 0000000000000..37bbd3347ad58 --- /dev/null +++ b/vendor/github.com/jtolds/gls/stack_tags.go @@ -0,0 +1,147 @@ +package gls + +// so, basically, we're going to encode integer tags in base-16 on the stack + +const ( + bitWidth = 4 + stackBatchSize = 16 +) + +var ( + pc_lookup = make(map[uintptr]int8, 17) + mark_lookup [16]func(uint, func()) +) + +func init() { + setEntries := func(f func(uint, func()), v int8) { + var ptr uintptr + f(0, func() { + ptr = findPtr() + }) + pc_lookup[ptr] = v + if v >= 0 { + mark_lookup[v] = f + } + } + setEntries(github_com_jtolds_gls_markS, -0x1) + setEntries(github_com_jtolds_gls_mark0, 0x0) + setEntries(github_com_jtolds_gls_mark1, 0x1) + setEntries(github_com_jtolds_gls_mark2, 0x2) + setEntries(github_com_jtolds_gls_mark3, 0x3) + setEntries(github_com_jtolds_gls_mark4, 0x4) + setEntries(github_com_jtolds_gls_mark5, 0x5) + setEntries(github_com_jtolds_gls_mark6, 0x6) + setEntries(github_com_jtolds_gls_mark7, 0x7) + setEntries(github_com_jtolds_gls_mark8, 0x8) + setEntries(github_com_jtolds_gls_mark9, 0x9) + setEntries(github_com_jtolds_gls_markA, 0xa) + setEntries(github_com_jtolds_gls_markB, 0xb) + setEntries(github_com_jtolds_gls_markC, 0xc) + setEntries(github_com_jtolds_gls_markD, 0xd) + setEntries(github_com_jtolds_gls_markE, 0xe) + setEntries(github_com_jtolds_gls_markF, 0xf) +} + +func addStackTag(tag uint, context_call func()) { + if context_call == nil { + return + } + github_com_jtolds_gls_markS(tag, context_call) +} + +// these private methods are named this horrendous name so gopherjs support +// is easier. it shouldn't add any runtime cost in non-js builds. + +//go:noinline +func github_com_jtolds_gls_markS(tag uint, cb func()) { _m(tag, cb) } + +//go:noinline +func github_com_jtolds_gls_mark0(tag uint, cb func()) { _m(tag, cb) } + +//go:noinline +func github_com_jtolds_gls_mark1(tag uint, cb func()) { _m(tag, cb) } + +//go:noinline +func github_com_jtolds_gls_mark2(tag uint, cb func()) { _m(tag, cb) } + +//go:noinline +func github_com_jtolds_gls_mark3(tag uint, cb func()) { _m(tag, cb) } + +//go:noinline +func github_com_jtolds_gls_mark4(tag uint, cb func()) { _m(tag, cb) } + +//go:noinline +func github_com_jtolds_gls_mark5(tag uint, cb func()) { _m(tag, cb) } + +//go:noinline +func github_com_jtolds_gls_mark6(tag uint, cb func()) { _m(tag, cb) } + +//go:noinline +func github_com_jtolds_gls_mark7(tag uint, cb func()) { _m(tag, cb) } + +//go:noinline +func github_com_jtolds_gls_mark8(tag uint, cb func()) { _m(tag, cb) } + +//go:noinline +func github_com_jtolds_gls_mark9(tag uint, cb func()) { _m(tag, cb) } + +//go:noinline +func github_com_jtolds_gls_markA(tag uint, cb func()) { _m(tag, cb) } + +//go:noinline +func github_com_jtolds_gls_markB(tag uint, cb func()) { _m(tag, cb) } + +//go:noinline +func github_com_jtolds_gls_markC(tag uint, cb func()) { _m(tag, cb) } + +//go:noinline +func github_com_jtolds_gls_markD(tag uint, cb func()) { _m(tag, cb) } + +//go:noinline +func github_com_jtolds_gls_markE(tag uint, cb func()) { _m(tag, cb) } + +//go:noinline +func github_com_jtolds_gls_markF(tag uint, cb func()) { _m(tag, cb) } + +func _m(tag_remainder uint, cb func()) { + if tag_remainder == 0 { + cb() + } else { + mark_lookup[tag_remainder&0xf](tag_remainder>>bitWidth, cb) + } +} + +func readStackTag() (tag uint, ok bool) { + var current_tag uint + offset := 0 + for { + batch, next_offset := getStack(offset, stackBatchSize) + for _, pc := range batch { + val, ok := pc_lookup[pc] + if !ok { + continue + } + if val < 0 { + return current_tag, true + } + current_tag <<= bitWidth + current_tag += uint(val) + } + if next_offset == 0 { + break + } + offset = next_offset + } + return 0, false +} + +func (m *ContextManager) preventInlining() { + // dunno if findPtr or getStack are likely to get inlined in a future release + // of go, but if they are inlined and their callers are inlined, that could + // hork some things. let's do our best to explain to the compiler that we + // really don't want those two functions inlined by saying they could change + // at any time. assumes preventInlining doesn't get compiled out. + // this whole thing is probably overkill. + findPtr = m.values[0][0].(func() uintptr) + getStack = m.values[0][1].(func(int, int) ([]uintptr, int)) +} diff --git a/vendor/github.com/jtolds/gls/stack_tags_js.go b/vendor/github.com/jtolds/gls/stack_tags_js.go new file mode 100644 index 0000000000000..c4e8b801d31d0 --- /dev/null +++ b/vendor/github.com/jtolds/gls/stack_tags_js.go @@ -0,0 +1,75 @@ +// +build js + +package gls + +// This file is used for GopherJS builds, which don't have normal runtime +// stack trace support + +import ( + "strconv" + "strings" + + "github.com/gopherjs/gopherjs/js" +) + +const ( + jsFuncNamePrefix = "github_com_jtolds_gls_mark" +) + +func jsMarkStack() (f []uintptr) { + lines := strings.Split( + js.Global.Get("Error").New().Get("stack").String(), "\n") + f = make([]uintptr, 0, len(lines)) + for i, line := range lines { + line = strings.TrimSpace(line) + if line == "" { + continue + } + if i == 0 { + if line != "Error" { + panic("didn't understand js stack trace") + } + continue + } + fields := strings.Fields(line) + if len(fields) < 2 || fields[0] != "at" { + panic("didn't understand js stack trace") + } + + pos := strings.Index(fields[1], jsFuncNamePrefix) + if pos < 0 { + continue + } + pos += len(jsFuncNamePrefix) + if pos >= len(fields[1]) { + panic("didn't understand js stack trace") + } + char := string(fields[1][pos]) + switch char { + case "S": + f = append(f, uintptr(0)) + default: + val, err := strconv.ParseUint(char, 16, 8) + if err != nil { + panic("didn't understand js stack trace") + } + f = append(f, uintptr(val)+1) + } + } + return f +} + +// variables to prevent inlining +var ( + findPtr = func() uintptr { + funcs := jsMarkStack() + if len(funcs) == 0 { + panic("failed to find function pointer") + } + return funcs[0] + } + + getStack = func(offset, amount int) (stack []uintptr, next_offset int) { + return jsMarkStack(), 0 + } +) diff --git a/vendor/github.com/jtolds/gls/stack_tags_main.go b/vendor/github.com/jtolds/gls/stack_tags_main.go new file mode 100644 index 0000000000000..4da89e44f8e8d --- /dev/null +++ b/vendor/github.com/jtolds/gls/stack_tags_main.go @@ -0,0 +1,30 @@ +// +build !js + +package gls + +// This file is used for standard Go builds, which have the expected runtime +// support + +import ( + "runtime" +) + +var ( + findPtr = func() uintptr { + var pc [1]uintptr + n := runtime.Callers(4, pc[:]) + if n != 1 { + panic("failed to find function pointer") + } + return pc[0] + } + + getStack = func(offset, amount int) (stack []uintptr, next_offset int) { + stack = make([]uintptr, amount) + stack = stack[:runtime.Callers(offset, stack)] + if len(stack) < amount { + return stack, 0 + } + return stack, offset + len(stack) + } +) diff --git a/vendor/github.com/smartystreets/assertions/.gitignore b/vendor/github.com/smartystreets/assertions/.gitignore new file mode 100644 index 0000000000000..1f088e844d480 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/.gitignore @@ -0,0 +1,4 @@ +/.idea +/coverage.* +.DS_Store +*.iml diff --git a/vendor/github.com/smartystreets/assertions/.travis.yml b/vendor/github.com/smartystreets/assertions/.travis.yml new file mode 100644 index 0000000000000..d4e3e1f0fb8dc --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/.travis.yml @@ -0,0 +1,23 @@ +dist: bionic + +language: go + +go: + - 1.x + +env: + - GO111MODULE=on + +script: + - make build + +after_success: + - bash <(curl -s https://codecov.io/bash) + +git: + depth: 1 + +cache: + directories: + - $HOME/.cache/go-build + - $HOME/gopath/pkg/mod diff --git a/vendor/github.com/smartystreets/assertions/CONTRIBUTING.md b/vendor/github.com/smartystreets/assertions/CONTRIBUTING.md new file mode 100644 index 0000000000000..1820ecb331011 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/CONTRIBUTING.md @@ -0,0 +1,12 @@ +# Contributing + +In general, the code posted to the [SmartyStreets github organization](https://github.com/smartystreets) is created to solve specific problems at SmartyStreets that are ancillary to our core products in the address verification industry and may or may not be useful to other organizations or developers. Our reason for posting said code isn't necessarily to solicit feedback or contributions from the community but more as a showcase of some of the approaches to solving problems we have adopted. + +Having stated that, we do consider issues raised by other githubbers as well as contributions submitted via pull requests. When submitting such a pull request, please follow these guidelines: + +- _Look before you leap:_ If the changes you plan to make are significant, it's in everyone's best interest for you to discuss them with a SmartyStreets team member prior to opening a pull request. +- _License and ownership:_ If modifying the `LICENSE.md` file, limit your changes to fixing typographical mistakes. Do NOT modify the actual terms in the license or the copyright by **SmartyStreets, LLC**. Code submitted to SmartyStreets projects becomes property of SmartyStreets and must be compatible with the associated license. +- _Testing:_ If the code you are submitting resides in packages/modules covered by automated tests, be sure to add passing tests that cover your changes and assert expected behavior and state. Submit the additional test cases as part of your change set. +- _Style:_ Match your approach to **naming** and **formatting** with the surrounding code. Basically, the code you submit shouldn't stand out. + - "Naming" refers to such constructs as variables, methods, functions, classes, structs, interfaces, packages, modules, directories, files, etc... + - "Formatting" refers to such constructs as whitespace, horizontal line length, vertical function length, vertical file length, indentation, curly braces, etc... diff --git a/vendor/github.com/smartystreets/assertions/LICENSE.md b/vendor/github.com/smartystreets/assertions/LICENSE.md new file mode 100644 index 0000000000000..8ea6f945521d7 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/LICENSE.md @@ -0,0 +1,23 @@ +Copyright (c) 2016 SmartyStreets, LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +NOTE: Various optional and subordinate components carry their own licensing +requirements and restrictions. Use of those components is subject to the terms +and conditions outlined the respective license of each component. diff --git a/vendor/github.com/smartystreets/assertions/Makefile b/vendor/github.com/smartystreets/assertions/Makefile new file mode 100644 index 0000000000000..5c27b7ba0ddc4 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/Makefile @@ -0,0 +1,14 @@ +#!/usr/bin/make -f + +test: fmt + go test -timeout=1s -race -cover -short -count=1 ./... + +fmt: + go fmt ./... + +compile: + go build ./... + +build: test compile + +.PHONY: test compile build diff --git a/vendor/github.com/smartystreets/assertions/README.md b/vendor/github.com/smartystreets/assertions/README.md new file mode 100644 index 0000000000000..10c8d20138fdb --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/README.md @@ -0,0 +1,4 @@ +[![Build Status](https://travis-ci.org/smartystreets/assertions.svg?branch=master)](https://travis-ci.org/smartystreets/assertions) +[![Code Coverage](https://codecov.io/gh/smartystreets/assertions/branch/master/graph/badge.svg)](https://codecov.io/gh/smartystreets/assertions) +[![Go Report Card](https://goreportcard.com/badge/github.com/smartystreets/assertions)](https://goreportcard.com/report/github.com/smartystreets/assertions) +[![GoDoc](https://godoc.org/github.com/smartystreets/assertions?status.svg)](http://godoc.org/github.com/smartystreets/assertions) diff --git a/vendor/github.com/smartystreets/assertions/collections.go b/vendor/github.com/smartystreets/assertions/collections.go new file mode 100644 index 0000000000000..b534d4bafab7c --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/collections.go @@ -0,0 +1,244 @@ +package assertions + +import ( + "fmt" + "reflect" + + "github.com/smartystreets/assertions/internal/oglematchers" +) + +// ShouldContain receives exactly two parameters. The first is a slice and the +// second is a proposed member. Membership is determined using ShouldEqual. +func ShouldContain(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } + + if matchError := oglematchers.Contains(expected[0]).Matches(actual); matchError != nil { + typeName := reflect.TypeOf(actual) + + if fmt.Sprintf("%v", matchError) == "which is not a slice or array" { + return fmt.Sprintf(shouldHaveBeenAValidCollection, typeName) + } + return fmt.Sprintf(shouldHaveContained, typeName, expected[0]) + } + return success +} + +// ShouldNotContain receives exactly two parameters. The first is a slice and the +// second is a proposed member. Membership is determinied using ShouldEqual. +func ShouldNotContain(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } + typeName := reflect.TypeOf(actual) + + if matchError := oglematchers.Contains(expected[0]).Matches(actual); matchError != nil { + if fmt.Sprintf("%v", matchError) == "which is not a slice or array" { + return fmt.Sprintf(shouldHaveBeenAValidCollection, typeName) + } + return success + } + return fmt.Sprintf(shouldNotHaveContained, typeName, expected[0]) +} + +// ShouldContainKey receives exactly two parameters. The first is a map and the +// second is a proposed key. Keys are compared with a simple '=='. +func ShouldContainKey(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } + + keys, isMap := mapKeys(actual) + if !isMap { + return fmt.Sprintf(shouldHaveBeenAValidMap, reflect.TypeOf(actual)) + } + + if !keyFound(keys, expected[0]) { + return fmt.Sprintf(shouldHaveContainedKey, reflect.TypeOf(actual), expected) + } + + return "" +} + +// ShouldNotContainKey receives exactly two parameters. The first is a map and the +// second is a proposed absent key. Keys are compared with a simple '=='. +func ShouldNotContainKey(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } + + keys, isMap := mapKeys(actual) + if !isMap { + return fmt.Sprintf(shouldHaveBeenAValidMap, reflect.TypeOf(actual)) + } + + if keyFound(keys, expected[0]) { + return fmt.Sprintf(shouldNotHaveContainedKey, reflect.TypeOf(actual), expected) + } + + return "" +} + +func mapKeys(m interface{}) ([]reflect.Value, bool) { + value := reflect.ValueOf(m) + if value.Kind() != reflect.Map { + return nil, false + } + return value.MapKeys(), true +} +func keyFound(keys []reflect.Value, expectedKey interface{}) bool { + found := false + for _, key := range keys { + if key.Interface() == expectedKey { + found = true + } + } + return found +} + +// ShouldBeIn receives at least 2 parameters. The first is a proposed member of the collection +// that is passed in either as the second parameter, or of the collection that is comprised +// of all the remaining parameters. This assertion ensures that the proposed member is in +// the collection (using ShouldEqual). +func ShouldBeIn(actual interface{}, expected ...interface{}) string { + if fail := atLeast(1, expected); fail != success { + return fail + } + + if len(expected) == 1 { + return shouldBeIn(actual, expected[0]) + } + return shouldBeIn(actual, expected) +} +func shouldBeIn(actual interface{}, expected interface{}) string { + if matchError := oglematchers.Contains(actual).Matches(expected); matchError != nil { + return fmt.Sprintf(shouldHaveBeenIn, actual, reflect.TypeOf(expected)) + } + return success +} + +// ShouldNotBeIn receives at least 2 parameters. The first is a proposed member of the collection +// that is passed in either as the second parameter, or of the collection that is comprised +// of all the remaining parameters. This assertion ensures that the proposed member is NOT in +// the collection (using ShouldEqual). +func ShouldNotBeIn(actual interface{}, expected ...interface{}) string { + if fail := atLeast(1, expected); fail != success { + return fail + } + + if len(expected) == 1 { + return shouldNotBeIn(actual, expected[0]) + } + return shouldNotBeIn(actual, expected) +} +func shouldNotBeIn(actual interface{}, expected interface{}) string { + if matchError := oglematchers.Contains(actual).Matches(expected); matchError == nil { + return fmt.Sprintf(shouldNotHaveBeenIn, actual, reflect.TypeOf(expected)) + } + return success +} + +// ShouldBeEmpty receives a single parameter (actual) and determines whether or not +// calling len(actual) would return `0`. It obeys the rules specified by the len +// function for determining length: http://golang.org/pkg/builtin/#len +func ShouldBeEmpty(actual interface{}, expected ...interface{}) string { + if fail := need(0, expected); fail != success { + return fail + } + + if actual == nil { + return success + } + + value := reflect.ValueOf(actual) + switch value.Kind() { + case reflect.Slice: + if value.Len() == 0 { + return success + } + case reflect.Chan: + if value.Len() == 0 { + return success + } + case reflect.Map: + if value.Len() == 0 { + return success + } + case reflect.String: + if value.Len() == 0 { + return success + } + case reflect.Ptr: + elem := value.Elem() + kind := elem.Kind() + if (kind == reflect.Slice || kind == reflect.Array) && elem.Len() == 0 { + return success + } + } + + return fmt.Sprintf(shouldHaveBeenEmpty, actual) +} + +// ShouldNotBeEmpty receives a single parameter (actual) and determines whether or not +// calling len(actual) would return a value greater than zero. It obeys the rules +// specified by the `len` function for determining length: http://golang.org/pkg/builtin/#len +func ShouldNotBeEmpty(actual interface{}, expected ...interface{}) string { + if fail := need(0, expected); fail != success { + return fail + } + + if empty := ShouldBeEmpty(actual, expected...); empty != success { + return success + } + return fmt.Sprintf(shouldNotHaveBeenEmpty, actual) +} + +// ShouldHaveLength receives 2 parameters. The first is a collection to check +// the length of, the second being the expected length. It obeys the rules +// specified by the len function for determining length: +// http://golang.org/pkg/builtin/#len +func ShouldHaveLength(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } + + var expectedLen int64 + lenValue := reflect.ValueOf(expected[0]) + switch lenValue.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + expectedLen = lenValue.Int() + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + expectedLen = int64(lenValue.Uint()) + default: + return fmt.Sprintf(shouldHaveBeenAValidInteger, reflect.TypeOf(expected[0])) + } + + if expectedLen < 0 { + return fmt.Sprintf(shouldHaveBeenAValidLength, expected[0]) + } + + value := reflect.ValueOf(actual) + switch value.Kind() { + case reflect.Slice, + reflect.Chan, + reflect.Map, + reflect.String: + if int64(value.Len()) == expectedLen { + return success + } else { + return fmt.Sprintf(shouldHaveHadLength, expectedLen, value.Len(), actual) + } + case reflect.Ptr: + elem := value.Elem() + kind := elem.Kind() + if kind == reflect.Slice || kind == reflect.Array { + if int64(elem.Len()) == expectedLen { + return success + } else { + return fmt.Sprintf(shouldHaveHadLength, expectedLen, elem.Len(), actual) + } + } + } + return fmt.Sprintf(shouldHaveBeenAValidCollection, reflect.TypeOf(actual)) +} diff --git a/vendor/github.com/smartystreets/assertions/doc.go b/vendor/github.com/smartystreets/assertions/doc.go new file mode 100644 index 0000000000000..ba30a9261ac96 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/doc.go @@ -0,0 +1,109 @@ +// Package assertions contains the implementations for all assertions which +// are referenced in goconvey's `convey` package +// (github.com/smartystreets/goconvey/convey) and gunit (github.com/smartystreets/gunit) +// for use with the So(...) method. +// They can also be used in traditional Go test functions and even in +// applications. +// +// https://smartystreets.com +// +// Many of the assertions lean heavily on work done by Aaron Jacobs in his excellent oglematchers library. +// (https://github.com/jacobsa/oglematchers) +// The ShouldResemble assertion leans heavily on work done by Daniel Jacques in his very helpful go-render library. +// (https://github.com/luci/go-render) +package assertions + +import ( + "fmt" + "runtime" +) + +// By default we use a no-op serializer. The actual Serializer provides a JSON +// representation of failure results on selected assertions so the goconvey +// web UI can display a convenient diff. +var serializer Serializer = new(noopSerializer) + +// GoConveyMode provides control over JSON serialization of failures. When +// using the assertions in this package from the convey package JSON results +// are very helpful and can be rendered in a DIFF view. In that case, this function +// will be called with a true value to enable the JSON serialization. By default, +// the assertions in this package will not serializer a JSON result, making +// standalone usage more convenient. +func GoConveyMode(yes bool) { + if yes { + serializer = newSerializer() + } else { + serializer = new(noopSerializer) + } +} + +type testingT interface { + Error(args ...interface{}) +} + +type Assertion struct { + t testingT + failed bool +} + +// New swallows the *testing.T struct and prints failed assertions using t.Error. +// Example: assertions.New(t).So(1, should.Equal, 1) +func New(t testingT) *Assertion { + return &Assertion{t: t} +} + +// Failed reports whether any calls to So (on this Assertion instance) have failed. +func (this *Assertion) Failed() bool { + return this.failed +} + +// So calls the standalone So function and additionally, calls t.Error in failure scenarios. +func (this *Assertion) So(actual interface{}, assert assertion, expected ...interface{}) bool { + ok, result := So(actual, assert, expected...) + if !ok { + this.failed = true + _, file, line, _ := runtime.Caller(1) + this.t.Error(fmt.Sprintf("\n%s:%d\n%s", file, line, result)) + } + return ok +} + +// So is a convenience function (as opposed to an inconvenience function?) +// for running assertions on arbitrary arguments in any context, be it for testing or even +// application logging. It allows you to perform assertion-like behavior (and get nicely +// formatted messages detailing discrepancies) but without the program blowing up or panicking. +// All that is required is to import this package and call `So` with one of the assertions +// exported by this package as the second parameter. +// The first return parameter is a boolean indicating if the assertion was true. The second +// return parameter is the well-formatted message showing why an assertion was incorrect, or +// blank if the assertion was correct. +// +// Example: +// +// if ok, message := So(x, ShouldBeGreaterThan, y); !ok { +// log.Println(message) +// } +// +// For an alternative implementation of So (that provides more flexible return options) +// see the `So` function in the package at github.com/smartystreets/assertions/assert. +func So(actual interface{}, assert assertion, expected ...interface{}) (bool, string) { + if result := so(actual, assert, expected...); len(result) == 0 { + return true, result + } else { + return false, result + } +} + +// so is like So, except that it only returns the string message, which is blank if the +// assertion passed. Used to facilitate testing. +func so(actual interface{}, assert func(interface{}, ...interface{}) string, expected ...interface{}) string { + return assert(actual, expected...) +} + +// assertion is an alias for a function with a signature that the So() +// function can handle. Any future or custom assertions should conform to this +// method signature. The return value should be an empty string if the assertion +// passes and a well-formed failure message if not. +type assertion func(actual interface{}, expected ...interface{}) string + +//////////////////////////////////////////////////////////////////////////// diff --git a/vendor/github.com/smartystreets/assertions/equal_method.go b/vendor/github.com/smartystreets/assertions/equal_method.go new file mode 100644 index 0000000000000..c4fc38fab5e77 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/equal_method.go @@ -0,0 +1,75 @@ +package assertions + +import "reflect" + +type equalityMethodSpecification struct { + a interface{} + b interface{} + + aType reflect.Type + bType reflect.Type + + equalMethod reflect.Value +} + +func newEqualityMethodSpecification(a, b interface{}) *equalityMethodSpecification { + return &equalityMethodSpecification{ + a: a, + b: b, + } +} + +func (this *equalityMethodSpecification) IsSatisfied() bool { + if !this.bothAreSameType() { + return false + } + if !this.typeHasEqualMethod() { + return false + } + if !this.equalMethodReceivesSameTypeForComparison() { + return false + } + if !this.equalMethodReturnsBool() { + return false + } + return true +} + +func (this *equalityMethodSpecification) bothAreSameType() bool { + this.aType = reflect.TypeOf(this.a) + if this.aType == nil { + return false + } + if this.aType.Kind() == reflect.Ptr { + this.aType = this.aType.Elem() + } + this.bType = reflect.TypeOf(this.b) + return this.aType == this.bType +} +func (this *equalityMethodSpecification) typeHasEqualMethod() bool { + aInstance := reflect.ValueOf(this.a) + this.equalMethod = aInstance.MethodByName("Equal") + return this.equalMethod != reflect.Value{} +} + +func (this *equalityMethodSpecification) equalMethodReceivesSameTypeForComparison() bool { + signature := this.equalMethod.Type() + return signature.NumIn() == 1 && signature.In(0) == this.aType +} + +func (this *equalityMethodSpecification) equalMethodReturnsBool() bool { + signature := this.equalMethod.Type() + return signature.NumOut() == 1 && signature.Out(0) == reflect.TypeOf(true) +} + +func (this *equalityMethodSpecification) AreEqual() bool { + a := reflect.ValueOf(this.a) + b := reflect.ValueOf(this.b) + return areEqual(a, b) && areEqual(b, a) +} +func areEqual(receiver reflect.Value, argument reflect.Value) bool { + equalMethod := receiver.MethodByName("Equal") + argumentList := []reflect.Value{argument} + result := equalMethod.Call(argumentList) + return result[0].Bool() +} diff --git a/vendor/github.com/smartystreets/assertions/equality.go b/vendor/github.com/smartystreets/assertions/equality.go new file mode 100644 index 0000000000000..37a49f4e255a5 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/equality.go @@ -0,0 +1,331 @@ +package assertions + +import ( + "encoding/json" + "errors" + "fmt" + "math" + "reflect" + "strings" + + "github.com/smartystreets/assertions/internal/go-render/render" + "github.com/smartystreets/assertions/internal/oglematchers" +) + +// ShouldEqual receives exactly two parameters and does an equality check +// using the following semantics: +// 1. If the expected and actual values implement an Equal method in the form +// `func (this T) Equal(that T) bool` then call the method. If true, they are equal. +// 2. The expected and actual values are judged equal or not by oglematchers.Equals. +func ShouldEqual(actual interface{}, expected ...interface{}) string { + if message := need(1, expected); message != success { + return message + } + return shouldEqual(actual, expected[0]) +} +func shouldEqual(actual, expected interface{}) (message string) { + defer func() { + if r := recover(); r != nil { + message = serializer.serialize(expected, actual, composeEqualityMismatchMessage(expected, actual)) + } + }() + + if spec := newEqualityMethodSpecification(expected, actual); spec.IsSatisfied() && spec.AreEqual() { + return success + } else if matchError := oglematchers.Equals(expected).Matches(actual); matchError == nil { + return success + } + + return serializer.serialize(expected, actual, composeEqualityMismatchMessage(expected, actual)) +} +func composeEqualityMismatchMessage(expected, actual interface{}) string { + var ( + renderedExpected = fmt.Sprintf("%v", expected) + renderedActual = fmt.Sprintf("%v", actual) + ) + + if renderedExpected != renderedActual { + return fmt.Sprintf(shouldHaveBeenEqual+composePrettyDiff(renderedExpected, renderedActual), expected, actual) + } else if reflect.TypeOf(expected) != reflect.TypeOf(actual) { + return fmt.Sprintf(shouldHaveBeenEqualTypeMismatch, expected, expected, actual, actual) + } else { + return fmt.Sprintf(shouldHaveBeenEqualNoResemblance, renderedExpected) + } +} + +// ShouldNotEqual receives exactly two parameters and does an inequality check. +// See ShouldEqual for details on how equality is determined. +func ShouldNotEqual(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } else if ShouldEqual(actual, expected[0]) == success { + return fmt.Sprintf(shouldNotHaveBeenEqual, actual, expected[0]) + } + return success +} + +// ShouldAlmostEqual makes sure that two parameters are close enough to being equal. +// The acceptable delta may be specified with a third argument, +// or a very small default delta will be used. +func ShouldAlmostEqual(actual interface{}, expected ...interface{}) string { + actualFloat, expectedFloat, deltaFloat, err := cleanAlmostEqualInput(actual, expected...) + + if err != "" { + return err + } + + if math.Abs(actualFloat-expectedFloat) <= deltaFloat { + return success + } else { + return fmt.Sprintf(shouldHaveBeenAlmostEqual, actualFloat, expectedFloat) + } +} + +// ShouldNotAlmostEqual is the inverse of ShouldAlmostEqual +func ShouldNotAlmostEqual(actual interface{}, expected ...interface{}) string { + actualFloat, expectedFloat, deltaFloat, err := cleanAlmostEqualInput(actual, expected...) + + if err != "" { + return err + } + + if math.Abs(actualFloat-expectedFloat) > deltaFloat { + return success + } else { + return fmt.Sprintf(shouldHaveNotBeenAlmostEqual, actualFloat, expectedFloat) + } +} + +func cleanAlmostEqualInput(actual interface{}, expected ...interface{}) (float64, float64, float64, string) { + deltaFloat := 0.0000000001 + + if len(expected) == 0 { + return 0.0, 0.0, 0.0, "This assertion requires exactly one comparison value and an optional delta (you provided neither)" + } else if len(expected) == 2 { + delta, err := getFloat(expected[1]) + + if err != nil { + return 0.0, 0.0, 0.0, "The delta value " + err.Error() + } + + deltaFloat = delta + } else if len(expected) > 2 { + return 0.0, 0.0, 0.0, "This assertion requires exactly one comparison value and an optional delta (you provided more values)" + } + + actualFloat, err := getFloat(actual) + if err != nil { + return 0.0, 0.0, 0.0, "The actual value " + err.Error() + } + + expectedFloat, err := getFloat(expected[0]) + if err != nil { + return 0.0, 0.0, 0.0, "The comparison value " + err.Error() + } + + return actualFloat, expectedFloat, deltaFloat, "" +} + +// returns the float value of any real number, or error if it is not a numerical type +func getFloat(num interface{}) (float64, error) { + numValue := reflect.ValueOf(num) + numKind := numValue.Kind() + + if numKind == reflect.Int || + numKind == reflect.Int8 || + numKind == reflect.Int16 || + numKind == reflect.Int32 || + numKind == reflect.Int64 { + return float64(numValue.Int()), nil + } else if numKind == reflect.Uint || + numKind == reflect.Uint8 || + numKind == reflect.Uint16 || + numKind == reflect.Uint32 || + numKind == reflect.Uint64 { + return float64(numValue.Uint()), nil + } else if numKind == reflect.Float32 || + numKind == reflect.Float64 { + return numValue.Float(), nil + } else { + return 0.0, errors.New("must be a numerical type, but was: " + numKind.String()) + } +} + +// ShouldEqualJSON receives exactly two parameters and does an equality check by marshalling to JSON +func ShouldEqualJSON(actual interface{}, expected ...interface{}) string { + if message := need(1, expected); message != success { + return message + } + + expectedString, expectedErr := remarshal(expected[0].(string)) + if expectedErr != nil { + return "Expected value not valid JSON: " + expectedErr.Error() + } + + actualString, actualErr := remarshal(actual.(string)) + if actualErr != nil { + return "Actual value not valid JSON: " + actualErr.Error() + } + + return ShouldEqual(actualString, expectedString) +} +func remarshal(value string) (string, error) { + var structured interface{} + err := json.Unmarshal([]byte(value), &structured) + if err != nil { + return "", err + } + canonical, _ := json.Marshal(structured) + return string(canonical), nil +} + +// ShouldResemble receives exactly two parameters and does a deep equal check (see reflect.DeepEqual) +func ShouldResemble(actual interface{}, expected ...interface{}) string { + if message := need(1, expected); message != success { + return message + } + + if matchError := oglematchers.DeepEquals(expected[0]).Matches(actual); matchError != nil { + renderedExpected, renderedActual := render.Render(expected[0]), render.Render(actual) + message := fmt.Sprintf(shouldHaveResembled, renderedExpected, renderedActual) + + composePrettyDiff(renderedExpected, renderedActual) + return serializer.serializeDetailed(expected[0], actual, message) + } + + return success +} + +// ShouldNotResemble receives exactly two parameters and does an inverse deep equal check (see reflect.DeepEqual) +func ShouldNotResemble(actual interface{}, expected ...interface{}) string { + if message := need(1, expected); message != success { + return message + } else if ShouldResemble(actual, expected[0]) == success { + return fmt.Sprintf(shouldNotHaveResembled, render.Render(actual), render.Render(expected[0])) + } + return success +} + +// ShouldPointTo receives exactly two parameters and checks to see that they point to the same address. +func ShouldPointTo(actual interface{}, expected ...interface{}) string { + if message := need(1, expected); message != success { + return message + } + return shouldPointTo(actual, expected[0]) + +} +func shouldPointTo(actual, expected interface{}) string { + actualValue := reflect.ValueOf(actual) + expectedValue := reflect.ValueOf(expected) + + if ShouldNotBeNil(actual) != success { + return fmt.Sprintf(shouldHaveBeenNonNilPointer, "first", "nil") + } else if ShouldNotBeNil(expected) != success { + return fmt.Sprintf(shouldHaveBeenNonNilPointer, "second", "nil") + } else if actualValue.Kind() != reflect.Ptr { + return fmt.Sprintf(shouldHaveBeenNonNilPointer, "first", "not") + } else if expectedValue.Kind() != reflect.Ptr { + return fmt.Sprintf(shouldHaveBeenNonNilPointer, "second", "not") + } else if ShouldEqual(actualValue.Pointer(), expectedValue.Pointer()) != success { + actualAddress := reflect.ValueOf(actual).Pointer() + expectedAddress := reflect.ValueOf(expected).Pointer() + return serializer.serialize(expectedAddress, actualAddress, fmt.Sprintf(shouldHavePointedTo, + actual, actualAddress, + expected, expectedAddress)) + } + return success +} + +// ShouldNotPointTo receives exactly two parameters and checks to see that they point to different addresess. +func ShouldNotPointTo(actual interface{}, expected ...interface{}) string { + if message := need(1, expected); message != success { + return message + } + compare := ShouldPointTo(actual, expected[0]) + if strings.HasPrefix(compare, shouldBePointers) { + return compare + } else if compare == success { + return fmt.Sprintf(shouldNotHavePointedTo, actual, expected[0], reflect.ValueOf(actual).Pointer()) + } + return success +} + +// ShouldBeNil receives a single parameter and ensures that it is nil. +func ShouldBeNil(actual interface{}, expected ...interface{}) string { + if fail := need(0, expected); fail != success { + return fail + } else if actual == nil { + return success + } else if interfaceHasNilValue(actual) { + return success + } + return fmt.Sprintf(shouldHaveBeenNil, actual) +} +func interfaceHasNilValue(actual interface{}) bool { + value := reflect.ValueOf(actual) + kind := value.Kind() + nilable := kind == reflect.Slice || + kind == reflect.Chan || + kind == reflect.Func || + kind == reflect.Ptr || + kind == reflect.Map + + // Careful: reflect.Value.IsNil() will panic unless it's an interface, chan, map, func, slice, or ptr + // Reference: http://golang.org/pkg/reflect/#Value.IsNil + return nilable && value.IsNil() +} + +// ShouldNotBeNil receives a single parameter and ensures that it is not nil. +func ShouldNotBeNil(actual interface{}, expected ...interface{}) string { + if fail := need(0, expected); fail != success { + return fail + } else if ShouldBeNil(actual) == success { + return fmt.Sprintf(shouldNotHaveBeenNil, actual) + } + return success +} + +// ShouldBeTrue receives a single parameter and ensures that it is true. +func ShouldBeTrue(actual interface{}, expected ...interface{}) string { + if fail := need(0, expected); fail != success { + return fail + } else if actual != true { + return fmt.Sprintf(shouldHaveBeenTrue, actual) + } + return success +} + +// ShouldBeFalse receives a single parameter and ensures that it is false. +func ShouldBeFalse(actual interface{}, expected ...interface{}) string { + if fail := need(0, expected); fail != success { + return fail + } else if actual != false { + return fmt.Sprintf(shouldHaveBeenFalse, actual) + } + return success +} + +// ShouldBeZeroValue receives a single parameter and ensures that it is +// the Go equivalent of the default value, or "zero" value. +func ShouldBeZeroValue(actual interface{}, expected ...interface{}) string { + if fail := need(0, expected); fail != success { + return fail + } + zeroVal := reflect.Zero(reflect.TypeOf(actual)).Interface() + if !reflect.DeepEqual(zeroVal, actual) { + return serializer.serialize(zeroVal, actual, fmt.Sprintf(shouldHaveBeenZeroValue, actual)) + } + return success +} + +// ShouldBeZeroValue receives a single parameter and ensures that it is NOT +// the Go equivalent of the default value, or "zero" value. +func ShouldNotBeZeroValue(actual interface{}, expected ...interface{}) string { + if fail := need(0, expected); fail != success { + return fail + } + zeroVal := reflect.Zero(reflect.TypeOf(actual)).Interface() + if reflect.DeepEqual(zeroVal, actual) { + return serializer.serialize(zeroVal, actual, fmt.Sprintf(shouldNotHaveBeenZeroValue, actual)) + } + return success +} diff --git a/vendor/github.com/smartystreets/assertions/equality_diff.go b/vendor/github.com/smartystreets/assertions/equality_diff.go new file mode 100644 index 0000000000000..bd698ff62bdae --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/equality_diff.go @@ -0,0 +1,37 @@ +package assertions + +import ( + "fmt" + + "github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch" +) + +func composePrettyDiff(expected, actual string) string { + diff := diffmatchpatch.New() + diffs := diff.DiffMain(expected, actual, false) + if prettyDiffIsLikelyToBeHelpful(diffs) { + return fmt.Sprintf("\nDiff: '%s'", diff.DiffPrettyText(diffs)) + } + return "" +} + +// prettyDiffIsLikelyToBeHelpful returns true if the diff listing contains +// more 'equal' segments than 'deleted'/'inserted' segments. +func prettyDiffIsLikelyToBeHelpful(diffs []diffmatchpatch.Diff) bool { + equal, deleted, inserted := measureDiffTypeLengths(diffs) + return equal > deleted && equal > inserted +} + +func measureDiffTypeLengths(diffs []diffmatchpatch.Diff) (equal, deleted, inserted int) { + for _, segment := range diffs { + switch segment.Type { + case diffmatchpatch.DiffEqual: + equal += len(segment.Text) + case diffmatchpatch.DiffDelete: + deleted += len(segment.Text) + case diffmatchpatch.DiffInsert: + inserted += len(segment.Text) + } + } + return equal, deleted, inserted +} diff --git a/vendor/github.com/smartystreets/assertions/filter.go b/vendor/github.com/smartystreets/assertions/filter.go new file mode 100644 index 0000000000000..cbf75667253e8 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/filter.go @@ -0,0 +1,31 @@ +package assertions + +import "fmt" + +const ( + success = "" + needExactValues = "This assertion requires exactly %d comparison values (you provided %d)." + needNonEmptyCollection = "This assertion requires at least 1 comparison value (you provided 0)." + needFewerValues = "This assertion allows %d or fewer comparison values (you provided %d)." +) + +func need(needed int, expected []interface{}) string { + if len(expected) != needed { + return fmt.Sprintf(needExactValues, needed, len(expected)) + } + return success +} + +func atLeast(minimum int, expected []interface{}) string { + if len(expected) < minimum { + return needNonEmptyCollection + } + return success +} + +func atMost(max int, expected []interface{}) string { + if len(expected) > max { + return fmt.Sprintf(needFewerValues, max, len(expected)) + } + return success +} diff --git a/vendor/github.com/smartystreets/assertions/go.mod b/vendor/github.com/smartystreets/assertions/go.mod new file mode 100644 index 0000000000000..3e0f123cbdfa9 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/go.mod @@ -0,0 +1,3 @@ +module github.com/smartystreets/assertions + +go 1.13 diff --git a/vendor/github.com/smartystreets/assertions/internal/go-diff/AUTHORS b/vendor/github.com/smartystreets/assertions/internal/go-diff/AUTHORS new file mode 100644 index 0000000000000..2d7bb2bf5728e --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/go-diff/AUTHORS @@ -0,0 +1,25 @@ +# This is the official list of go-diff authors for copyright purposes. +# This file is distinct from the CONTRIBUTORS files. +# See the latter for an explanation. + +# Names should be added to this file as +# Name or Organization +# The email address is not required for organizations. + +# Please keep the list sorted. + +Danny Yoo +James Kolb +Jonathan Amsterdam +Markus Zimmermann +Matt Kovars +Örjan Persson +Osman Masood +Robert Carlsen +Rory Flynn +Sergi Mansilla +Shatrugna Sadhu +Shawn Smith +Stas Maksimov +Tor Arvid Lund +Zac Bergquist diff --git a/vendor/github.com/smartystreets/assertions/internal/go-diff/CONTRIBUTORS b/vendor/github.com/smartystreets/assertions/internal/go-diff/CONTRIBUTORS new file mode 100644 index 0000000000000..369e3d55190a0 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/go-diff/CONTRIBUTORS @@ -0,0 +1,32 @@ +# This is the official list of people who can contribute +# (and typically have contributed) code to the go-diff +# repository. +# +# The AUTHORS file lists the copyright holders; this file +# lists people. For example, ACME Inc. employees would be listed here +# but not in AUTHORS, because ACME Inc. would hold the copyright. +# +# When adding J Random Contributor's name to this file, +# either J's name or J's organization's name should be +# added to the AUTHORS file. +# +# Names should be added to this file like so: +# Name +# +# Please keep the list sorted. + +Danny Yoo +James Kolb +Jonathan Amsterdam +Markus Zimmermann +Matt Kovars +Örjan Persson +Osman Masood +Robert Carlsen +Rory Flynn +Sergi Mansilla +Shatrugna Sadhu +Shawn Smith +Stas Maksimov +Tor Arvid Lund +Zac Bergquist diff --git a/vendor/github.com/smartystreets/assertions/internal/go-diff/LICENSE b/vendor/github.com/smartystreets/assertions/internal/go-diff/LICENSE new file mode 100644 index 0000000000000..937942c2b2c4c --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/go-diff/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2012-2016 The go-diff Authors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + diff --git a/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/diff.go b/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/diff.go new file mode 100644 index 0000000000000..cb25b4375750e --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/diff.go @@ -0,0 +1,1345 @@ +// Copyright (c) 2012-2016 The go-diff authors. All rights reserved. +// https://github.com/sergi/go-diff +// See the included LICENSE file for license details. +// +// go-diff is a Go implementation of Google's Diff, Match, and Patch library +// Original library is Copyright (c) 2006 Google Inc. +// http://code.google.com/p/google-diff-match-patch/ + +package diffmatchpatch + +import ( + "bytes" + "errors" + "fmt" + "html" + "math" + "net/url" + "regexp" + "strconv" + "strings" + "time" + "unicode/utf8" +) + +// Operation defines the operation of a diff item. +type Operation int8 + +//go:generate stringer -type=Operation -trimprefix=Diff + +const ( + // DiffDelete item represents a delete diff. + DiffDelete Operation = -1 + // DiffInsert item represents an insert diff. + DiffInsert Operation = 1 + // DiffEqual item represents an equal diff. + DiffEqual Operation = 0 +) + +// Diff represents one diff operation +type Diff struct { + Type Operation + Text string +} + +// splice removes amount elements from slice at index index, replacing them with elements. +func splice(slice []Diff, index int, amount int, elements ...Diff) []Diff { + if len(elements) == amount { + // Easy case: overwrite the relevant items. + copy(slice[index:], elements) + return slice + } + if len(elements) < amount { + // Fewer new items than old. + // Copy in the new items. + copy(slice[index:], elements) + // Shift the remaining items left. + copy(slice[index+len(elements):], slice[index+amount:]) + // Calculate the new end of the slice. + end := len(slice) - amount + len(elements) + // Zero stranded elements at end so that they can be garbage collected. + tail := slice[end:] + for i := range tail { + tail[i] = Diff{} + } + return slice[:end] + } + // More new items than old. + // Make room in slice for new elements. + // There's probably an even more efficient way to do this, + // but this is simple and clear. + need := len(slice) - amount + len(elements) + for len(slice) < need { + slice = append(slice, Diff{}) + } + // Shift slice elements right to make room for new elements. + copy(slice[index+len(elements):], slice[index+amount:]) + // Copy in new elements. + copy(slice[index:], elements) + return slice +} + +// DiffMain finds the differences between two texts. +// If an invalid UTF-8 sequence is encountered, it will be replaced by the Unicode replacement character. +func (dmp *DiffMatchPatch) DiffMain(text1, text2 string, checklines bool) []Diff { + return dmp.DiffMainRunes([]rune(text1), []rune(text2), checklines) +} + +// DiffMainRunes finds the differences between two rune sequences. +// If an invalid UTF-8 sequence is encountered, it will be replaced by the Unicode replacement character. +func (dmp *DiffMatchPatch) DiffMainRunes(text1, text2 []rune, checklines bool) []Diff { + var deadline time.Time + if dmp.DiffTimeout > 0 { + deadline = time.Now().Add(dmp.DiffTimeout) + } + return dmp.diffMainRunes(text1, text2, checklines, deadline) +} + +func (dmp *DiffMatchPatch) diffMainRunes(text1, text2 []rune, checklines bool, deadline time.Time) []Diff { + if runesEqual(text1, text2) { + var diffs []Diff + if len(text1) > 0 { + diffs = append(diffs, Diff{DiffEqual, string(text1)}) + } + return diffs + } + // Trim off common prefix (speedup). + commonlength := commonPrefixLength(text1, text2) + commonprefix := text1[:commonlength] + text1 = text1[commonlength:] + text2 = text2[commonlength:] + + // Trim off common suffix (speedup). + commonlength = commonSuffixLength(text1, text2) + commonsuffix := text1[len(text1)-commonlength:] + text1 = text1[:len(text1)-commonlength] + text2 = text2[:len(text2)-commonlength] + + // Compute the diff on the middle block. + diffs := dmp.diffCompute(text1, text2, checklines, deadline) + + // Restore the prefix and suffix. + if len(commonprefix) != 0 { + diffs = append([]Diff{Diff{DiffEqual, string(commonprefix)}}, diffs...) + } + if len(commonsuffix) != 0 { + diffs = append(diffs, Diff{DiffEqual, string(commonsuffix)}) + } + + return dmp.DiffCleanupMerge(diffs) +} + +// diffCompute finds the differences between two rune slices. Assumes that the texts do not have any common prefix or suffix. +func (dmp *DiffMatchPatch) diffCompute(text1, text2 []rune, checklines bool, deadline time.Time) []Diff { + diffs := []Diff{} + if len(text1) == 0 { + // Just add some text (speedup). + return append(diffs, Diff{DiffInsert, string(text2)}) + } else if len(text2) == 0 { + // Just delete some text (speedup). + return append(diffs, Diff{DiffDelete, string(text1)}) + } + + var longtext, shorttext []rune + if len(text1) > len(text2) { + longtext = text1 + shorttext = text2 + } else { + longtext = text2 + shorttext = text1 + } + + if i := runesIndex(longtext, shorttext); i != -1 { + op := DiffInsert + // Swap insertions for deletions if diff is reversed. + if len(text1) > len(text2) { + op = DiffDelete + } + // Shorter text is inside the longer text (speedup). + return []Diff{ + Diff{op, string(longtext[:i])}, + Diff{DiffEqual, string(shorttext)}, + Diff{op, string(longtext[i+len(shorttext):])}, + } + } else if len(shorttext) == 1 { + // Single character string. + // After the previous speedup, the character can't be an equality. + return []Diff{ + Diff{DiffDelete, string(text1)}, + Diff{DiffInsert, string(text2)}, + } + // Check to see if the problem can be split in two. + } else if hm := dmp.diffHalfMatch(text1, text2); hm != nil { + // A half-match was found, sort out the return data. + text1A := hm[0] + text1B := hm[1] + text2A := hm[2] + text2B := hm[3] + midCommon := hm[4] + // Send both pairs off for separate processing. + diffsA := dmp.diffMainRunes(text1A, text2A, checklines, deadline) + diffsB := dmp.diffMainRunes(text1B, text2B, checklines, deadline) + // Merge the results. + diffs := diffsA + diffs = append(diffs, Diff{DiffEqual, string(midCommon)}) + diffs = append(diffs, diffsB...) + return diffs + } else if checklines && len(text1) > 100 && len(text2) > 100 { + return dmp.diffLineMode(text1, text2, deadline) + } + return dmp.diffBisect(text1, text2, deadline) +} + +// diffLineMode does a quick line-level diff on both []runes, then rediff the parts for greater accuracy. This speedup can produce non-minimal diffs. +func (dmp *DiffMatchPatch) diffLineMode(text1, text2 []rune, deadline time.Time) []Diff { + // Scan the text on a line-by-line basis first. + text1, text2, linearray := dmp.diffLinesToRunes(text1, text2) + + diffs := dmp.diffMainRunes(text1, text2, false, deadline) + + // Convert the diff back to original text. + diffs = dmp.DiffCharsToLines(diffs, linearray) + // Eliminate freak matches (e.g. blank lines) + diffs = dmp.DiffCleanupSemantic(diffs) + + // Rediff any replacement blocks, this time character-by-character. + // Add a dummy entry at the end. + diffs = append(diffs, Diff{DiffEqual, ""}) + + pointer := 0 + countDelete := 0 + countInsert := 0 + + // NOTE: Rune slices are slower than using strings in this case. + textDelete := "" + textInsert := "" + + for pointer < len(diffs) { + switch diffs[pointer].Type { + case DiffInsert: + countInsert++ + textInsert += diffs[pointer].Text + case DiffDelete: + countDelete++ + textDelete += diffs[pointer].Text + case DiffEqual: + // Upon reaching an equality, check for prior redundancies. + if countDelete >= 1 && countInsert >= 1 { + // Delete the offending records and add the merged ones. + diffs = splice(diffs, pointer-countDelete-countInsert, + countDelete+countInsert) + + pointer = pointer - countDelete - countInsert + a := dmp.diffMainRunes([]rune(textDelete), []rune(textInsert), false, deadline) + for j := len(a) - 1; j >= 0; j-- { + diffs = splice(diffs, pointer, 0, a[j]) + } + pointer = pointer + len(a) + } + + countInsert = 0 + countDelete = 0 + textDelete = "" + textInsert = "" + } + pointer++ + } + + return diffs[:len(diffs)-1] // Remove the dummy entry at the end. +} + +// DiffBisect finds the 'middle snake' of a diff, split the problem in two and return the recursively constructed diff. +// If an invalid UTF-8 sequence is encountered, it will be replaced by the Unicode replacement character. +// See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations. +func (dmp *DiffMatchPatch) DiffBisect(text1, text2 string, deadline time.Time) []Diff { + // Unused in this code, but retained for interface compatibility. + return dmp.diffBisect([]rune(text1), []rune(text2), deadline) +} + +// diffBisect finds the 'middle snake' of a diff, splits the problem in two and returns the recursively constructed diff. +// See Myers's 1986 paper: An O(ND) Difference Algorithm and Its Variations. +func (dmp *DiffMatchPatch) diffBisect(runes1, runes2 []rune, deadline time.Time) []Diff { + // Cache the text lengths to prevent multiple calls. + runes1Len, runes2Len := len(runes1), len(runes2) + + maxD := (runes1Len + runes2Len + 1) / 2 + vOffset := maxD + vLength := 2 * maxD + + v1 := make([]int, vLength) + v2 := make([]int, vLength) + for i := range v1 { + v1[i] = -1 + v2[i] = -1 + } + v1[vOffset+1] = 0 + v2[vOffset+1] = 0 + + delta := runes1Len - runes2Len + // If the total number of characters is odd, then the front path will collide with the reverse path. + front := (delta%2 != 0) + // Offsets for start and end of k loop. Prevents mapping of space beyond the grid. + k1start := 0 + k1end := 0 + k2start := 0 + k2end := 0 + for d := 0; d < maxD; d++ { + // Bail out if deadline is reached. + if !deadline.IsZero() && d%16 == 0 && time.Now().After(deadline) { + break + } + + // Walk the front path one step. + for k1 := -d + k1start; k1 <= d-k1end; k1 += 2 { + k1Offset := vOffset + k1 + var x1 int + + if k1 == -d || (k1 != d && v1[k1Offset-1] < v1[k1Offset+1]) { + x1 = v1[k1Offset+1] + } else { + x1 = v1[k1Offset-1] + 1 + } + + y1 := x1 - k1 + for x1 < runes1Len && y1 < runes2Len { + if runes1[x1] != runes2[y1] { + break + } + x1++ + y1++ + } + v1[k1Offset] = x1 + if x1 > runes1Len { + // Ran off the right of the graph. + k1end += 2 + } else if y1 > runes2Len { + // Ran off the bottom of the graph. + k1start += 2 + } else if front { + k2Offset := vOffset + delta - k1 + if k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] != -1 { + // Mirror x2 onto top-left coordinate system. + x2 := runes1Len - v2[k2Offset] + if x1 >= x2 { + // Overlap detected. + return dmp.diffBisectSplit(runes1, runes2, x1, y1, deadline) + } + } + } + } + // Walk the reverse path one step. + for k2 := -d + k2start; k2 <= d-k2end; k2 += 2 { + k2Offset := vOffset + k2 + var x2 int + if k2 == -d || (k2 != d && v2[k2Offset-1] < v2[k2Offset+1]) { + x2 = v2[k2Offset+1] + } else { + x2 = v2[k2Offset-1] + 1 + } + var y2 = x2 - k2 + for x2 < runes1Len && y2 < runes2Len { + if runes1[runes1Len-x2-1] != runes2[runes2Len-y2-1] { + break + } + x2++ + y2++ + } + v2[k2Offset] = x2 + if x2 > runes1Len { + // Ran off the left of the graph. + k2end += 2 + } else if y2 > runes2Len { + // Ran off the top of the graph. + k2start += 2 + } else if !front { + k1Offset := vOffset + delta - k2 + if k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] != -1 { + x1 := v1[k1Offset] + y1 := vOffset + x1 - k1Offset + // Mirror x2 onto top-left coordinate system. + x2 = runes1Len - x2 + if x1 >= x2 { + // Overlap detected. + return dmp.diffBisectSplit(runes1, runes2, x1, y1, deadline) + } + } + } + } + } + // Diff took too long and hit the deadline or number of diffs equals number of characters, no commonality at all. + return []Diff{ + Diff{DiffDelete, string(runes1)}, + Diff{DiffInsert, string(runes2)}, + } +} + +func (dmp *DiffMatchPatch) diffBisectSplit(runes1, runes2 []rune, x, y int, + deadline time.Time) []Diff { + runes1a := runes1[:x] + runes2a := runes2[:y] + runes1b := runes1[x:] + runes2b := runes2[y:] + + // Compute both diffs serially. + diffs := dmp.diffMainRunes(runes1a, runes2a, false, deadline) + diffsb := dmp.diffMainRunes(runes1b, runes2b, false, deadline) + + return append(diffs, diffsb...) +} + +// DiffLinesToChars splits two texts into a list of strings, and educes the texts to a string of hashes where each Unicode character represents one line. +// It's slightly faster to call DiffLinesToRunes first, followed by DiffMainRunes. +func (dmp *DiffMatchPatch) DiffLinesToChars(text1, text2 string) (string, string, []string) { + chars1, chars2, lineArray := dmp.DiffLinesToRunes(text1, text2) + return string(chars1), string(chars2), lineArray +} + +// DiffLinesToRunes splits two texts into a list of runes. Each rune represents one line. +func (dmp *DiffMatchPatch) DiffLinesToRunes(text1, text2 string) ([]rune, []rune, []string) { + // '\x00' is a valid character, but various debuggers don't like it. So we'll insert a junk entry to avoid generating a null character. + lineArray := []string{""} // e.g. lineArray[4] == 'Hello\n' + lineHash := map[string]int{} // e.g. lineHash['Hello\n'] == 4 + + chars1 := dmp.diffLinesToRunesMunge(text1, &lineArray, lineHash) + chars2 := dmp.diffLinesToRunesMunge(text2, &lineArray, lineHash) + + return chars1, chars2, lineArray +} + +func (dmp *DiffMatchPatch) diffLinesToRunes(text1, text2 []rune) ([]rune, []rune, []string) { + return dmp.DiffLinesToRunes(string(text1), string(text2)) +} + +// diffLinesToRunesMunge splits a text into an array of strings, and reduces the texts to a []rune where each Unicode character represents one line. +// We use strings instead of []runes as input mainly because you can't use []rune as a map key. +func (dmp *DiffMatchPatch) diffLinesToRunesMunge(text string, lineArray *[]string, lineHash map[string]int) []rune { + // Walk the text, pulling out a substring for each line. text.split('\n') would would temporarily double our memory footprint. Modifying text would create many large strings to garbage collect. + lineStart := 0 + lineEnd := -1 + runes := []rune{} + + for lineEnd < len(text)-1 { + lineEnd = indexOf(text, "\n", lineStart) + + if lineEnd == -1 { + lineEnd = len(text) - 1 + } + + line := text[lineStart : lineEnd+1] + lineStart = lineEnd + 1 + lineValue, ok := lineHash[line] + + if ok { + runes = append(runes, rune(lineValue)) + } else { + *lineArray = append(*lineArray, line) + lineHash[line] = len(*lineArray) - 1 + runes = append(runes, rune(len(*lineArray)-1)) + } + } + + return runes +} + +// DiffCharsToLines rehydrates the text in a diff from a string of line hashes to real lines of text. +func (dmp *DiffMatchPatch) DiffCharsToLines(diffs []Diff, lineArray []string) []Diff { + hydrated := make([]Diff, 0, len(diffs)) + for _, aDiff := range diffs { + chars := aDiff.Text + text := make([]string, len(chars)) + + for i, r := range chars { + text[i] = lineArray[r] + } + + aDiff.Text = strings.Join(text, "") + hydrated = append(hydrated, aDiff) + } + return hydrated +} + +// DiffCommonPrefix determines the common prefix length of two strings. +func (dmp *DiffMatchPatch) DiffCommonPrefix(text1, text2 string) int { + // Unused in this code, but retained for interface compatibility. + return commonPrefixLength([]rune(text1), []rune(text2)) +} + +// DiffCommonSuffix determines the common suffix length of two strings. +func (dmp *DiffMatchPatch) DiffCommonSuffix(text1, text2 string) int { + // Unused in this code, but retained for interface compatibility. + return commonSuffixLength([]rune(text1), []rune(text2)) +} + +// commonPrefixLength returns the length of the common prefix of two rune slices. +func commonPrefixLength(text1, text2 []rune) int { + // Linear search. See comment in commonSuffixLength. + n := 0 + for ; n < len(text1) && n < len(text2); n++ { + if text1[n] != text2[n] { + return n + } + } + return n +} + +// commonSuffixLength returns the length of the common suffix of two rune slices. +func commonSuffixLength(text1, text2 []rune) int { + // Use linear search rather than the binary search discussed at https://neil.fraser.name/news/2007/10/09/. + // See discussion at https://github.com/sergi/go-diff/issues/54. + i1 := len(text1) + i2 := len(text2) + for n := 0; ; n++ { + i1-- + i2-- + if i1 < 0 || i2 < 0 || text1[i1] != text2[i2] { + return n + } + } +} + +// DiffCommonOverlap determines if the suffix of one string is the prefix of another. +func (dmp *DiffMatchPatch) DiffCommonOverlap(text1 string, text2 string) int { + // Cache the text lengths to prevent multiple calls. + text1Length := len(text1) + text2Length := len(text2) + // Eliminate the null case. + if text1Length == 0 || text2Length == 0 { + return 0 + } + // Truncate the longer string. + if text1Length > text2Length { + text1 = text1[text1Length-text2Length:] + } else if text1Length < text2Length { + text2 = text2[0:text1Length] + } + textLength := int(math.Min(float64(text1Length), float64(text2Length))) + // Quick check for the worst case. + if text1 == text2 { + return textLength + } + + // Start by looking for a single character match and increase length until no match is found. Performance analysis: http://neil.fraser.name/news/2010/11/04/ + best := 0 + length := 1 + for { + pattern := text1[textLength-length:] + found := strings.Index(text2, pattern) + if found == -1 { + break + } + length += found + if found == 0 || text1[textLength-length:] == text2[0:length] { + best = length + length++ + } + } + + return best +} + +// DiffHalfMatch checks whether the two texts share a substring which is at least half the length of the longer text. This speedup can produce non-minimal diffs. +func (dmp *DiffMatchPatch) DiffHalfMatch(text1, text2 string) []string { + // Unused in this code, but retained for interface compatibility. + runeSlices := dmp.diffHalfMatch([]rune(text1), []rune(text2)) + if runeSlices == nil { + return nil + } + + result := make([]string, len(runeSlices)) + for i, r := range runeSlices { + result[i] = string(r) + } + return result +} + +func (dmp *DiffMatchPatch) diffHalfMatch(text1, text2 []rune) [][]rune { + if dmp.DiffTimeout <= 0 { + // Don't risk returning a non-optimal diff if we have unlimited time. + return nil + } + + var longtext, shorttext []rune + if len(text1) > len(text2) { + longtext = text1 + shorttext = text2 + } else { + longtext = text2 + shorttext = text1 + } + + if len(longtext) < 4 || len(shorttext)*2 < len(longtext) { + return nil // Pointless. + } + + // First check if the second quarter is the seed for a half-match. + hm1 := dmp.diffHalfMatchI(longtext, shorttext, int(float64(len(longtext)+3)/4)) + + // Check again based on the third quarter. + hm2 := dmp.diffHalfMatchI(longtext, shorttext, int(float64(len(longtext)+1)/2)) + + hm := [][]rune{} + if hm1 == nil && hm2 == nil { + return nil + } else if hm2 == nil { + hm = hm1 + } else if hm1 == nil { + hm = hm2 + } else { + // Both matched. Select the longest. + if len(hm1[4]) > len(hm2[4]) { + hm = hm1 + } else { + hm = hm2 + } + } + + // A half-match was found, sort out the return data. + if len(text1) > len(text2) { + return hm + } + + return [][]rune{hm[2], hm[3], hm[0], hm[1], hm[4]} +} + +// diffHalfMatchI checks if a substring of shorttext exist within longtext such that the substring is at least half the length of longtext? +// Returns a slice containing the prefix of longtext, the suffix of longtext, the prefix of shorttext, the suffix of shorttext and the common middle, or null if there was no match. +func (dmp *DiffMatchPatch) diffHalfMatchI(l, s []rune, i int) [][]rune { + var bestCommonA []rune + var bestCommonB []rune + var bestCommonLen int + var bestLongtextA []rune + var bestLongtextB []rune + var bestShorttextA []rune + var bestShorttextB []rune + + // Start with a 1/4 length substring at position i as a seed. + seed := l[i : i+len(l)/4] + + for j := runesIndexOf(s, seed, 0); j != -1; j = runesIndexOf(s, seed, j+1) { + prefixLength := commonPrefixLength(l[i:], s[j:]) + suffixLength := commonSuffixLength(l[:i], s[:j]) + + if bestCommonLen < suffixLength+prefixLength { + bestCommonA = s[j-suffixLength : j] + bestCommonB = s[j : j+prefixLength] + bestCommonLen = len(bestCommonA) + len(bestCommonB) + bestLongtextA = l[:i-suffixLength] + bestLongtextB = l[i+prefixLength:] + bestShorttextA = s[:j-suffixLength] + bestShorttextB = s[j+prefixLength:] + } + } + + if bestCommonLen*2 < len(l) { + return nil + } + + return [][]rune{ + bestLongtextA, + bestLongtextB, + bestShorttextA, + bestShorttextB, + append(bestCommonA, bestCommonB...), + } +} + +// DiffCleanupSemantic reduces the number of edits by eliminating semantically trivial equalities. +func (dmp *DiffMatchPatch) DiffCleanupSemantic(diffs []Diff) []Diff { + changes := false + // Stack of indices where equalities are found. + equalities := make([]int, 0, len(diffs)) + + var lastequality string + // Always equal to diffs[equalities[equalitiesLength - 1]][1] + var pointer int // Index of current position. + // Number of characters that changed prior to the equality. + var lengthInsertions1, lengthDeletions1 int + // Number of characters that changed after the equality. + var lengthInsertions2, lengthDeletions2 int + + for pointer < len(diffs) { + if diffs[pointer].Type == DiffEqual { + // Equality found. + equalities = append(equalities, pointer) + lengthInsertions1 = lengthInsertions2 + lengthDeletions1 = lengthDeletions2 + lengthInsertions2 = 0 + lengthDeletions2 = 0 + lastequality = diffs[pointer].Text + } else { + // An insertion or deletion. + + if diffs[pointer].Type == DiffInsert { + lengthInsertions2 += len(diffs[pointer].Text) + } else { + lengthDeletions2 += len(diffs[pointer].Text) + } + // Eliminate an equality that is smaller or equal to the edits on both sides of it. + difference1 := int(math.Max(float64(lengthInsertions1), float64(lengthDeletions1))) + difference2 := int(math.Max(float64(lengthInsertions2), float64(lengthDeletions2))) + if len(lastequality) > 0 && + (len(lastequality) <= difference1) && + (len(lastequality) <= difference2) { + // Duplicate record. + insPoint := equalities[len(equalities)-1] + diffs = splice(diffs, insPoint, 0, Diff{DiffDelete, lastequality}) + + // Change second copy to insert. + diffs[insPoint+1].Type = DiffInsert + // Throw away the equality we just deleted. + equalities = equalities[:len(equalities)-1] + + if len(equalities) > 0 { + equalities = equalities[:len(equalities)-1] + } + pointer = -1 + if len(equalities) > 0 { + pointer = equalities[len(equalities)-1] + } + + lengthInsertions1 = 0 // Reset the counters. + lengthDeletions1 = 0 + lengthInsertions2 = 0 + lengthDeletions2 = 0 + lastequality = "" + changes = true + } + } + pointer++ + } + + // Normalize the diff. + if changes { + diffs = dmp.DiffCleanupMerge(diffs) + } + diffs = dmp.DiffCleanupSemanticLossless(diffs) + // Find any overlaps between deletions and insertions. + // e.g: abcxxxxxxdef + // -> abcxxxdef + // e.g: xxxabcdefxxx + // -> defxxxabc + // Only extract an overlap if it is as big as the edit ahead or behind it. + pointer = 1 + for pointer < len(diffs) { + if diffs[pointer-1].Type == DiffDelete && + diffs[pointer].Type == DiffInsert { + deletion := diffs[pointer-1].Text + insertion := diffs[pointer].Text + overlapLength1 := dmp.DiffCommonOverlap(deletion, insertion) + overlapLength2 := dmp.DiffCommonOverlap(insertion, deletion) + if overlapLength1 >= overlapLength2 { + if float64(overlapLength1) >= float64(len(deletion))/2 || + float64(overlapLength1) >= float64(len(insertion))/2 { + + // Overlap found. Insert an equality and trim the surrounding edits. + diffs = splice(diffs, pointer, 0, Diff{DiffEqual, insertion[:overlapLength1]}) + diffs[pointer-1].Text = + deletion[0 : len(deletion)-overlapLength1] + diffs[pointer+1].Text = insertion[overlapLength1:] + pointer++ + } + } else { + if float64(overlapLength2) >= float64(len(deletion))/2 || + float64(overlapLength2) >= float64(len(insertion))/2 { + // Reverse overlap found. Insert an equality and swap and trim the surrounding edits. + overlap := Diff{DiffEqual, deletion[:overlapLength2]} + diffs = splice(diffs, pointer, 0, overlap) + diffs[pointer-1].Type = DiffInsert + diffs[pointer-1].Text = insertion[0 : len(insertion)-overlapLength2] + diffs[pointer+1].Type = DiffDelete + diffs[pointer+1].Text = deletion[overlapLength2:] + pointer++ + } + } + pointer++ + } + pointer++ + } + + return diffs +} + +// Define some regex patterns for matching boundaries. +var ( + nonAlphaNumericRegex = regexp.MustCompile(`[^a-zA-Z0-9]`) + whitespaceRegex = regexp.MustCompile(`\s`) + linebreakRegex = regexp.MustCompile(`[\r\n]`) + blanklineEndRegex = regexp.MustCompile(`\n\r?\n$`) + blanklineStartRegex = regexp.MustCompile(`^\r?\n\r?\n`) +) + +// diffCleanupSemanticScore computes a score representing whether the internal boundary falls on logical boundaries. +// Scores range from 6 (best) to 0 (worst). Closure, but does not reference any external variables. +func diffCleanupSemanticScore(one, two string) int { + if len(one) == 0 || len(two) == 0 { + // Edges are the best. + return 6 + } + + // Each port of this function behaves slightly differently due to subtle differences in each language's definition of things like 'whitespace'. Since this function's purpose is largely cosmetic, the choice has been made to use each language's native features rather than force total conformity. + rune1, _ := utf8.DecodeLastRuneInString(one) + rune2, _ := utf8.DecodeRuneInString(two) + char1 := string(rune1) + char2 := string(rune2) + + nonAlphaNumeric1 := nonAlphaNumericRegex.MatchString(char1) + nonAlphaNumeric2 := nonAlphaNumericRegex.MatchString(char2) + whitespace1 := nonAlphaNumeric1 && whitespaceRegex.MatchString(char1) + whitespace2 := nonAlphaNumeric2 && whitespaceRegex.MatchString(char2) + lineBreak1 := whitespace1 && linebreakRegex.MatchString(char1) + lineBreak2 := whitespace2 && linebreakRegex.MatchString(char2) + blankLine1 := lineBreak1 && blanklineEndRegex.MatchString(one) + blankLine2 := lineBreak2 && blanklineEndRegex.MatchString(two) + + if blankLine1 || blankLine2 { + // Five points for blank lines. + return 5 + } else if lineBreak1 || lineBreak2 { + // Four points for line breaks. + return 4 + } else if nonAlphaNumeric1 && !whitespace1 && whitespace2 { + // Three points for end of sentences. + return 3 + } else if whitespace1 || whitespace2 { + // Two points for whitespace. + return 2 + } else if nonAlphaNumeric1 || nonAlphaNumeric2 { + // One point for non-alphanumeric. + return 1 + } + return 0 +} + +// DiffCleanupSemanticLossless looks for single edits surrounded on both sides by equalities which can be shifted sideways to align the edit to a word boundary. +// E.g: The cat came. -> The cat came. +func (dmp *DiffMatchPatch) DiffCleanupSemanticLossless(diffs []Diff) []Diff { + pointer := 1 + + // Intentionally ignore the first and last element (don't need checking). + for pointer < len(diffs)-1 { + if diffs[pointer-1].Type == DiffEqual && + diffs[pointer+1].Type == DiffEqual { + + // This is a single edit surrounded by equalities. + equality1 := diffs[pointer-1].Text + edit := diffs[pointer].Text + equality2 := diffs[pointer+1].Text + + // First, shift the edit as far left as possible. + commonOffset := dmp.DiffCommonSuffix(equality1, edit) + if commonOffset > 0 { + commonString := edit[len(edit)-commonOffset:] + equality1 = equality1[0 : len(equality1)-commonOffset] + edit = commonString + edit[:len(edit)-commonOffset] + equality2 = commonString + equality2 + } + + // Second, step character by character right, looking for the best fit. + bestEquality1 := equality1 + bestEdit := edit + bestEquality2 := equality2 + bestScore := diffCleanupSemanticScore(equality1, edit) + + diffCleanupSemanticScore(edit, equality2) + + for len(edit) != 0 && len(equality2) != 0 { + _, sz := utf8.DecodeRuneInString(edit) + if len(equality2) < sz || edit[:sz] != equality2[:sz] { + break + } + equality1 += edit[:sz] + edit = edit[sz:] + equality2[:sz] + equality2 = equality2[sz:] + score := diffCleanupSemanticScore(equality1, edit) + + diffCleanupSemanticScore(edit, equality2) + // The >= encourages trailing rather than leading whitespace on edits. + if score >= bestScore { + bestScore = score + bestEquality1 = equality1 + bestEdit = edit + bestEquality2 = equality2 + } + } + + if diffs[pointer-1].Text != bestEquality1 { + // We have an improvement, save it back to the diff. + if len(bestEquality1) != 0 { + diffs[pointer-1].Text = bestEquality1 + } else { + diffs = splice(diffs, pointer-1, 1) + pointer-- + } + + diffs[pointer].Text = bestEdit + if len(bestEquality2) != 0 { + diffs[pointer+1].Text = bestEquality2 + } else { + diffs = append(diffs[:pointer+1], diffs[pointer+2:]...) + pointer-- + } + } + } + pointer++ + } + + return diffs +} + +// DiffCleanupEfficiency reduces the number of edits by eliminating operationally trivial equalities. +func (dmp *DiffMatchPatch) DiffCleanupEfficiency(diffs []Diff) []Diff { + changes := false + // Stack of indices where equalities are found. + type equality struct { + data int + next *equality + } + var equalities *equality + // Always equal to equalities[equalitiesLength-1][1] + lastequality := "" + pointer := 0 // Index of current position. + // Is there an insertion operation before the last equality. + preIns := false + // Is there a deletion operation before the last equality. + preDel := false + // Is there an insertion operation after the last equality. + postIns := false + // Is there a deletion operation after the last equality. + postDel := false + for pointer < len(diffs) { + if diffs[pointer].Type == DiffEqual { // Equality found. + if len(diffs[pointer].Text) < dmp.DiffEditCost && + (postIns || postDel) { + // Candidate found. + equalities = &equality{ + data: pointer, + next: equalities, + } + preIns = postIns + preDel = postDel + lastequality = diffs[pointer].Text + } else { + // Not a candidate, and can never become one. + equalities = nil + lastequality = "" + } + postIns = false + postDel = false + } else { // An insertion or deletion. + if diffs[pointer].Type == DiffDelete { + postDel = true + } else { + postIns = true + } + + // Five types to be split: + // ABXYCD + // AXCD + // ABXC + // AXCD + // ABXC + var sumPres int + if preIns { + sumPres++ + } + if preDel { + sumPres++ + } + if postIns { + sumPres++ + } + if postDel { + sumPres++ + } + if len(lastequality) > 0 && + ((preIns && preDel && postIns && postDel) || + ((len(lastequality) < dmp.DiffEditCost/2) && sumPres == 3)) { + + insPoint := equalities.data + + // Duplicate record. + diffs = splice(diffs, insPoint, 0, Diff{DiffDelete, lastequality}) + + // Change second copy to insert. + diffs[insPoint+1].Type = DiffInsert + // Throw away the equality we just deleted. + equalities = equalities.next + lastequality = "" + + if preIns && preDel { + // No changes made which could affect previous entry, keep going. + postIns = true + postDel = true + equalities = nil + } else { + if equalities != nil { + equalities = equalities.next + } + if equalities != nil { + pointer = equalities.data + } else { + pointer = -1 + } + postIns = false + postDel = false + } + changes = true + } + } + pointer++ + } + + if changes { + diffs = dmp.DiffCleanupMerge(diffs) + } + + return diffs +} + +// DiffCleanupMerge reorders and merges like edit sections. Merge equalities. +// Any edit section can move as long as it doesn't cross an equality. +func (dmp *DiffMatchPatch) DiffCleanupMerge(diffs []Diff) []Diff { + // Add a dummy entry at the end. + diffs = append(diffs, Diff{DiffEqual, ""}) + pointer := 0 + countDelete := 0 + countInsert := 0 + commonlength := 0 + textDelete := []rune(nil) + textInsert := []rune(nil) + + for pointer < len(diffs) { + switch diffs[pointer].Type { + case DiffInsert: + countInsert++ + textInsert = append(textInsert, []rune(diffs[pointer].Text)...) + pointer++ + break + case DiffDelete: + countDelete++ + textDelete = append(textDelete, []rune(diffs[pointer].Text)...) + pointer++ + break + case DiffEqual: + // Upon reaching an equality, check for prior redundancies. + if countDelete+countInsert > 1 { + if countDelete != 0 && countInsert != 0 { + // Factor out any common prefixies. + commonlength = commonPrefixLength(textInsert, textDelete) + if commonlength != 0 { + x := pointer - countDelete - countInsert + if x > 0 && diffs[x-1].Type == DiffEqual { + diffs[x-1].Text += string(textInsert[:commonlength]) + } else { + diffs = append([]Diff{Diff{DiffEqual, string(textInsert[:commonlength])}}, diffs...) + pointer++ + } + textInsert = textInsert[commonlength:] + textDelete = textDelete[commonlength:] + } + // Factor out any common suffixies. + commonlength = commonSuffixLength(textInsert, textDelete) + if commonlength != 0 { + insertIndex := len(textInsert) - commonlength + deleteIndex := len(textDelete) - commonlength + diffs[pointer].Text = string(textInsert[insertIndex:]) + diffs[pointer].Text + textInsert = textInsert[:insertIndex] + textDelete = textDelete[:deleteIndex] + } + } + // Delete the offending records and add the merged ones. + if countDelete == 0 { + diffs = splice(diffs, pointer-countInsert, + countDelete+countInsert, + Diff{DiffInsert, string(textInsert)}) + } else if countInsert == 0 { + diffs = splice(diffs, pointer-countDelete, + countDelete+countInsert, + Diff{DiffDelete, string(textDelete)}) + } else { + diffs = splice(diffs, pointer-countDelete-countInsert, + countDelete+countInsert, + Diff{DiffDelete, string(textDelete)}, + Diff{DiffInsert, string(textInsert)}) + } + + pointer = pointer - countDelete - countInsert + 1 + if countDelete != 0 { + pointer++ + } + if countInsert != 0 { + pointer++ + } + } else if pointer != 0 && diffs[pointer-1].Type == DiffEqual { + // Merge this equality with the previous one. + diffs[pointer-1].Text += diffs[pointer].Text + diffs = append(diffs[:pointer], diffs[pointer+1:]...) + } else { + pointer++ + } + countInsert = 0 + countDelete = 0 + textDelete = nil + textInsert = nil + break + } + } + + if len(diffs[len(diffs)-1].Text) == 0 { + diffs = diffs[0 : len(diffs)-1] // Remove the dummy entry at the end. + } + + // Second pass: look for single edits surrounded on both sides by equalities which can be shifted sideways to eliminate an equality. E.g: ABAC -> ABAC + changes := false + pointer = 1 + // Intentionally ignore the first and last element (don't need checking). + for pointer < (len(diffs) - 1) { + if diffs[pointer-1].Type == DiffEqual && + diffs[pointer+1].Type == DiffEqual { + // This is a single edit surrounded by equalities. + if strings.HasSuffix(diffs[pointer].Text, diffs[pointer-1].Text) { + // Shift the edit over the previous equality. + diffs[pointer].Text = diffs[pointer-1].Text + + diffs[pointer].Text[:len(diffs[pointer].Text)-len(diffs[pointer-1].Text)] + diffs[pointer+1].Text = diffs[pointer-1].Text + diffs[pointer+1].Text + diffs = splice(diffs, pointer-1, 1) + changes = true + } else if strings.HasPrefix(diffs[pointer].Text, diffs[pointer+1].Text) { + // Shift the edit over the next equality. + diffs[pointer-1].Text += diffs[pointer+1].Text + diffs[pointer].Text = + diffs[pointer].Text[len(diffs[pointer+1].Text):] + diffs[pointer+1].Text + diffs = splice(diffs, pointer+1, 1) + changes = true + } + } + pointer++ + } + + // If shifts were made, the diff needs reordering and another shift sweep. + if changes { + diffs = dmp.DiffCleanupMerge(diffs) + } + + return diffs +} + +// DiffXIndex returns the equivalent location in s2. +func (dmp *DiffMatchPatch) DiffXIndex(diffs []Diff, loc int) int { + chars1 := 0 + chars2 := 0 + lastChars1 := 0 + lastChars2 := 0 + lastDiff := Diff{} + for i := 0; i < len(diffs); i++ { + aDiff := diffs[i] + if aDiff.Type != DiffInsert { + // Equality or deletion. + chars1 += len(aDiff.Text) + } + if aDiff.Type != DiffDelete { + // Equality or insertion. + chars2 += len(aDiff.Text) + } + if chars1 > loc { + // Overshot the location. + lastDiff = aDiff + break + } + lastChars1 = chars1 + lastChars2 = chars2 + } + if lastDiff.Type == DiffDelete { + // The location was deleted. + return lastChars2 + } + // Add the remaining character length. + return lastChars2 + (loc - lastChars1) +} + +// DiffPrettyHtml converts a []Diff into a pretty HTML report. +// It is intended as an example from which to write one's own display functions. +func (dmp *DiffMatchPatch) DiffPrettyHtml(diffs []Diff) string { + var buff bytes.Buffer + for _, diff := range diffs { + text := strings.Replace(html.EscapeString(diff.Text), "\n", "¶
", -1) + switch diff.Type { + case DiffInsert: + _, _ = buff.WriteString("") + _, _ = buff.WriteString(text) + _, _ = buff.WriteString("") + case DiffDelete: + _, _ = buff.WriteString("") + _, _ = buff.WriteString(text) + _, _ = buff.WriteString("") + case DiffEqual: + _, _ = buff.WriteString("") + _, _ = buff.WriteString(text) + _, _ = buff.WriteString("") + } + } + return buff.String() +} + +// DiffPrettyText converts a []Diff into a colored text report. +func (dmp *DiffMatchPatch) DiffPrettyText(diffs []Diff) string { + var buff bytes.Buffer + for _, diff := range diffs { + text := diff.Text + + switch diff.Type { + case DiffInsert: + _, _ = buff.WriteString("\x1b[32m") + _, _ = buff.WriteString(text) + _, _ = buff.WriteString("\x1b[0m") + case DiffDelete: + _, _ = buff.WriteString("\x1b[31m") + _, _ = buff.WriteString(text) + _, _ = buff.WriteString("\x1b[0m") + case DiffEqual: + _, _ = buff.WriteString(text) + } + } + + return buff.String() +} + +// DiffText1 computes and returns the source text (all equalities and deletions). +func (dmp *DiffMatchPatch) DiffText1(diffs []Diff) string { + //StringBuilder text = new StringBuilder() + var text bytes.Buffer + + for _, aDiff := range diffs { + if aDiff.Type != DiffInsert { + _, _ = text.WriteString(aDiff.Text) + } + } + return text.String() +} + +// DiffText2 computes and returns the destination text (all equalities and insertions). +func (dmp *DiffMatchPatch) DiffText2(diffs []Diff) string { + var text bytes.Buffer + + for _, aDiff := range diffs { + if aDiff.Type != DiffDelete { + _, _ = text.WriteString(aDiff.Text) + } + } + return text.String() +} + +// DiffLevenshtein computes the Levenshtein distance that is the number of inserted, deleted or substituted characters. +func (dmp *DiffMatchPatch) DiffLevenshtein(diffs []Diff) int { + levenshtein := 0 + insertions := 0 + deletions := 0 + + for _, aDiff := range diffs { + switch aDiff.Type { + case DiffInsert: + insertions += utf8.RuneCountInString(aDiff.Text) + case DiffDelete: + deletions += utf8.RuneCountInString(aDiff.Text) + case DiffEqual: + // A deletion and an insertion is one substitution. + levenshtein += max(insertions, deletions) + insertions = 0 + deletions = 0 + } + } + + levenshtein += max(insertions, deletions) + return levenshtein +} + +// DiffToDelta crushes the diff into an encoded string which describes the operations required to transform text1 into text2. +// E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'. Operations are tab-separated. Inserted text is escaped using %xx notation. +func (dmp *DiffMatchPatch) DiffToDelta(diffs []Diff) string { + var text bytes.Buffer + for _, aDiff := range diffs { + switch aDiff.Type { + case DiffInsert: + _, _ = text.WriteString("+") + _, _ = text.WriteString(strings.Replace(url.QueryEscape(aDiff.Text), "+", " ", -1)) + _, _ = text.WriteString("\t") + break + case DiffDelete: + _, _ = text.WriteString("-") + _, _ = text.WriteString(strconv.Itoa(utf8.RuneCountInString(aDiff.Text))) + _, _ = text.WriteString("\t") + break + case DiffEqual: + _, _ = text.WriteString("=") + _, _ = text.WriteString(strconv.Itoa(utf8.RuneCountInString(aDiff.Text))) + _, _ = text.WriteString("\t") + break + } + } + delta := text.String() + if len(delta) != 0 { + // Strip off trailing tab character. + delta = delta[0 : utf8.RuneCountInString(delta)-1] + delta = unescaper.Replace(delta) + } + return delta +} + +// DiffFromDelta given the original text1, and an encoded string which describes the operations required to transform text1 into text2, comAdde the full diff. +func (dmp *DiffMatchPatch) DiffFromDelta(text1 string, delta string) (diffs []Diff, err error) { + i := 0 + runes := []rune(text1) + + for _, token := range strings.Split(delta, "\t") { + if len(token) == 0 { + // Blank tokens are ok (from a trailing \t). + continue + } + + // Each token begins with a one character parameter which specifies the operation of this token (delete, insert, equality). + param := token[1:] + + switch op := token[0]; op { + case '+': + // Decode would Diff all "+" to " " + param = strings.Replace(param, "+", "%2b", -1) + param, err = url.QueryUnescape(param) + if err != nil { + return nil, err + } + if !utf8.ValidString(param) { + return nil, fmt.Errorf("invalid UTF-8 token: %q", param) + } + + diffs = append(diffs, Diff{DiffInsert, param}) + case '=', '-': + n, err := strconv.ParseInt(param, 10, 0) + if err != nil { + return nil, err + } else if n < 0 { + return nil, errors.New("Negative number in DiffFromDelta: " + param) + } + + i += int(n) + // Break out if we are out of bounds, go1.6 can't handle this very well + if i > len(runes) { + break + } + // Remember that string slicing is by byte - we want by rune here. + text := string(runes[i-int(n) : i]) + + if op == '=' { + diffs = append(diffs, Diff{DiffEqual, text}) + } else { + diffs = append(diffs, Diff{DiffDelete, text}) + } + default: + // Anything else is an error. + return nil, errors.New("Invalid diff operation in DiffFromDelta: " + string(token[0])) + } + } + + if i != len(runes) { + return nil, fmt.Errorf("Delta length (%v) is different from source text length (%v)", i, len(text1)) + } + + return diffs, nil +} diff --git a/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/diffmatchpatch.go b/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/diffmatchpatch.go new file mode 100644 index 0000000000000..d3acc32ce13a0 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/diffmatchpatch.go @@ -0,0 +1,46 @@ +// Copyright (c) 2012-2016 The go-diff authors. All rights reserved. +// https://github.com/sergi/go-diff +// See the included LICENSE file for license details. +// +// go-diff is a Go implementation of Google's Diff, Match, and Patch library +// Original library is Copyright (c) 2006 Google Inc. +// http://code.google.com/p/google-diff-match-patch/ + +// Package diffmatchpatch offers robust algorithms to perform the operations required for synchronizing plain text. +package diffmatchpatch + +import ( + "time" +) + +// DiffMatchPatch holds the configuration for diff-match-patch operations. +type DiffMatchPatch struct { + // Number of seconds to map a diff before giving up (0 for infinity). + DiffTimeout time.Duration + // Cost of an empty edit operation in terms of edit characters. + DiffEditCost int + // How far to search for a match (0 = exact location, 1000+ = broad match). A match this many characters away from the expected location will add 1.0 to the score (0.0 is a perfect match). + MatchDistance int + // When deleting a large block of text (over ~64 characters), how close do the contents have to be to match the expected contents. (0.0 = perfection, 1.0 = very loose). Note that MatchThreshold controls how closely the end points of a delete need to match. + PatchDeleteThreshold float64 + // Chunk size for context length. + PatchMargin int + // The number of bits in an int. + MatchMaxBits int + // At what point is no match declared (0.0 = perfection, 1.0 = very loose). + MatchThreshold float64 +} + +// New creates a new DiffMatchPatch object with default parameters. +func New() *DiffMatchPatch { + // Defaults. + return &DiffMatchPatch{ + DiffTimeout: time.Second, + DiffEditCost: 4, + MatchThreshold: 0.5, + MatchDistance: 1000, + PatchDeleteThreshold: 0.5, + PatchMargin: 4, + MatchMaxBits: 32, + } +} diff --git a/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/match.go b/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/match.go new file mode 100644 index 0000000000000..17374e109fef2 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/match.go @@ -0,0 +1,160 @@ +// Copyright (c) 2012-2016 The go-diff authors. All rights reserved. +// https://github.com/sergi/go-diff +// See the included LICENSE file for license details. +// +// go-diff is a Go implementation of Google's Diff, Match, and Patch library +// Original library is Copyright (c) 2006 Google Inc. +// http://code.google.com/p/google-diff-match-patch/ + +package diffmatchpatch + +import ( + "math" +) + +// MatchMain locates the best instance of 'pattern' in 'text' near 'loc'. +// Returns -1 if no match found. +func (dmp *DiffMatchPatch) MatchMain(text, pattern string, loc int) int { + // Check for null inputs not needed since null can't be passed in C#. + + loc = int(math.Max(0, math.Min(float64(loc), float64(len(text))))) + if text == pattern { + // Shortcut (potentially not guaranteed by the algorithm) + return 0 + } else if len(text) == 0 { + // Nothing to match. + return -1 + } else if loc+len(pattern) <= len(text) && text[loc:loc+len(pattern)] == pattern { + // Perfect match at the perfect spot! (Includes case of null pattern) + return loc + } + // Do a fuzzy compare. + return dmp.MatchBitap(text, pattern, loc) +} + +// MatchBitap locates the best instance of 'pattern' in 'text' near 'loc' using the Bitap algorithm. +// Returns -1 if no match was found. +func (dmp *DiffMatchPatch) MatchBitap(text, pattern string, loc int) int { + // Initialise the alphabet. + s := dmp.MatchAlphabet(pattern) + + // Highest score beyond which we give up. + scoreThreshold := dmp.MatchThreshold + // Is there a nearby exact match? (speedup) + bestLoc := indexOf(text, pattern, loc) + if bestLoc != -1 { + scoreThreshold = math.Min(dmp.matchBitapScore(0, bestLoc, loc, + pattern), scoreThreshold) + // What about in the other direction? (speedup) + bestLoc = lastIndexOf(text, pattern, loc+len(pattern)) + if bestLoc != -1 { + scoreThreshold = math.Min(dmp.matchBitapScore(0, bestLoc, loc, + pattern), scoreThreshold) + } + } + + // Initialise the bit arrays. + matchmask := 1 << uint((len(pattern) - 1)) + bestLoc = -1 + + var binMin, binMid int + binMax := len(pattern) + len(text) + lastRd := []int{} + for d := 0; d < len(pattern); d++ { + // Scan for the best match; each iteration allows for one more error. Run a binary search to determine how far from 'loc' we can stray at this error level. + binMin = 0 + binMid = binMax + for binMin < binMid { + if dmp.matchBitapScore(d, loc+binMid, loc, pattern) <= scoreThreshold { + binMin = binMid + } else { + binMax = binMid + } + binMid = (binMax-binMin)/2 + binMin + } + // Use the result from this iteration as the maximum for the next. + binMax = binMid + start := int(math.Max(1, float64(loc-binMid+1))) + finish := int(math.Min(float64(loc+binMid), float64(len(text))) + float64(len(pattern))) + + rd := make([]int, finish+2) + rd[finish+1] = (1 << uint(d)) - 1 + + for j := finish; j >= start; j-- { + var charMatch int + if len(text) <= j-1 { + // Out of range. + charMatch = 0 + } else if _, ok := s[text[j-1]]; !ok { + charMatch = 0 + } else { + charMatch = s[text[j-1]] + } + + if d == 0 { + // First pass: exact match. + rd[j] = ((rd[j+1] << 1) | 1) & charMatch + } else { + // Subsequent passes: fuzzy match. + rd[j] = ((rd[j+1]<<1)|1)&charMatch | (((lastRd[j+1] | lastRd[j]) << 1) | 1) | lastRd[j+1] + } + if (rd[j] & matchmask) != 0 { + score := dmp.matchBitapScore(d, j-1, loc, pattern) + // This match will almost certainly be better than any existing match. But check anyway. + if score <= scoreThreshold { + // Told you so. + scoreThreshold = score + bestLoc = j - 1 + if bestLoc > loc { + // When passing loc, don't exceed our current distance from loc. + start = int(math.Max(1, float64(2*loc-bestLoc))) + } else { + // Already passed loc, downhill from here on in. + break + } + } + } + } + if dmp.matchBitapScore(d+1, loc, loc, pattern) > scoreThreshold { + // No hope for a (better) match at greater error levels. + break + } + lastRd = rd + } + return bestLoc +} + +// matchBitapScore computes and returns the score for a match with e errors and x location. +func (dmp *DiffMatchPatch) matchBitapScore(e, x, loc int, pattern string) float64 { + accuracy := float64(e) / float64(len(pattern)) + proximity := math.Abs(float64(loc - x)) + if dmp.MatchDistance == 0 { + // Dodge divide by zero error. + if proximity == 0 { + return accuracy + } + + return 1.0 + } + return accuracy + (proximity / float64(dmp.MatchDistance)) +} + +// MatchAlphabet initialises the alphabet for the Bitap algorithm. +func (dmp *DiffMatchPatch) MatchAlphabet(pattern string) map[byte]int { + s := map[byte]int{} + charPattern := []byte(pattern) + for _, c := range charPattern { + _, ok := s[c] + if !ok { + s[c] = 0 + } + } + i := 0 + + for _, c := range charPattern { + value := s[c] | int(uint(1)< y { + return x + } + return y +} diff --git a/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/operation_string.go b/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/operation_string.go new file mode 100644 index 0000000000000..533ec0da7b344 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/operation_string.go @@ -0,0 +1,17 @@ +// Code generated by "stringer -type=Operation -trimprefix=Diff"; DO NOT EDIT. + +package diffmatchpatch + +import "fmt" + +const _Operation_name = "DeleteEqualInsert" + +var _Operation_index = [...]uint8{0, 6, 11, 17} + +func (i Operation) String() string { + i -= -1 + if i < 0 || i >= Operation(len(_Operation_index)-1) { + return fmt.Sprintf("Operation(%d)", i+-1) + } + return _Operation_name[_Operation_index[i]:_Operation_index[i+1]] +} diff --git a/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/patch.go b/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/patch.go new file mode 100644 index 0000000000000..223c43c426807 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/patch.go @@ -0,0 +1,556 @@ +// Copyright (c) 2012-2016 The go-diff authors. All rights reserved. +// https://github.com/sergi/go-diff +// See the included LICENSE file for license details. +// +// go-diff is a Go implementation of Google's Diff, Match, and Patch library +// Original library is Copyright (c) 2006 Google Inc. +// http://code.google.com/p/google-diff-match-patch/ + +package diffmatchpatch + +import ( + "bytes" + "errors" + "math" + "net/url" + "regexp" + "strconv" + "strings" +) + +// Patch represents one patch operation. +type Patch struct { + diffs []Diff + Start1 int + Start2 int + Length1 int + Length2 int +} + +// String emulates GNU diff's format. +// Header: @@ -382,8 +481,9 @@ +// Indices are printed as 1-based, not 0-based. +func (p *Patch) String() string { + var coords1, coords2 string + + if p.Length1 == 0 { + coords1 = strconv.Itoa(p.Start1) + ",0" + } else if p.Length1 == 1 { + coords1 = strconv.Itoa(p.Start1 + 1) + } else { + coords1 = strconv.Itoa(p.Start1+1) + "," + strconv.Itoa(p.Length1) + } + + if p.Length2 == 0 { + coords2 = strconv.Itoa(p.Start2) + ",0" + } else if p.Length2 == 1 { + coords2 = strconv.Itoa(p.Start2 + 1) + } else { + coords2 = strconv.Itoa(p.Start2+1) + "," + strconv.Itoa(p.Length2) + } + + var text bytes.Buffer + _, _ = text.WriteString("@@ -" + coords1 + " +" + coords2 + " @@\n") + + // Escape the body of the patch with %xx notation. + for _, aDiff := range p.diffs { + switch aDiff.Type { + case DiffInsert: + _, _ = text.WriteString("+") + case DiffDelete: + _, _ = text.WriteString("-") + case DiffEqual: + _, _ = text.WriteString(" ") + } + + _, _ = text.WriteString(strings.Replace(url.QueryEscape(aDiff.Text), "+", " ", -1)) + _, _ = text.WriteString("\n") + } + + return unescaper.Replace(text.String()) +} + +// PatchAddContext increases the context until it is unique, but doesn't let the pattern expand beyond MatchMaxBits. +func (dmp *DiffMatchPatch) PatchAddContext(patch Patch, text string) Patch { + if len(text) == 0 { + return patch + } + + pattern := text[patch.Start2 : patch.Start2+patch.Length1] + padding := 0 + + // Look for the first and last matches of pattern in text. If two different matches are found, increase the pattern length. + for strings.Index(text, pattern) != strings.LastIndex(text, pattern) && + len(pattern) < dmp.MatchMaxBits-2*dmp.PatchMargin { + padding += dmp.PatchMargin + maxStart := max(0, patch.Start2-padding) + minEnd := min(len(text), patch.Start2+patch.Length1+padding) + pattern = text[maxStart:minEnd] + } + // Add one chunk for good luck. + padding += dmp.PatchMargin + + // Add the prefix. + prefix := text[max(0, patch.Start2-padding):patch.Start2] + if len(prefix) != 0 { + patch.diffs = append([]Diff{Diff{DiffEqual, prefix}}, patch.diffs...) + } + // Add the suffix. + suffix := text[patch.Start2+patch.Length1 : min(len(text), patch.Start2+patch.Length1+padding)] + if len(suffix) != 0 { + patch.diffs = append(patch.diffs, Diff{DiffEqual, suffix}) + } + + // Roll back the start points. + patch.Start1 -= len(prefix) + patch.Start2 -= len(prefix) + // Extend the lengths. + patch.Length1 += len(prefix) + len(suffix) + patch.Length2 += len(prefix) + len(suffix) + + return patch +} + +// PatchMake computes a list of patches. +func (dmp *DiffMatchPatch) PatchMake(opt ...interface{}) []Patch { + if len(opt) == 1 { + diffs, _ := opt[0].([]Diff) + text1 := dmp.DiffText1(diffs) + return dmp.PatchMake(text1, diffs) + } else if len(opt) == 2 { + text1 := opt[0].(string) + switch t := opt[1].(type) { + case string: + diffs := dmp.DiffMain(text1, t, true) + if len(diffs) > 2 { + diffs = dmp.DiffCleanupSemantic(diffs) + diffs = dmp.DiffCleanupEfficiency(diffs) + } + return dmp.PatchMake(text1, diffs) + case []Diff: + return dmp.patchMake2(text1, t) + } + } else if len(opt) == 3 { + return dmp.PatchMake(opt[0], opt[2]) + } + return []Patch{} +} + +// patchMake2 computes a list of patches to turn text1 into text2. +// text2 is not provided, diffs are the delta between text1 and text2. +func (dmp *DiffMatchPatch) patchMake2(text1 string, diffs []Diff) []Patch { + // Check for null inputs not needed since null can't be passed in C#. + patches := []Patch{} + if len(diffs) == 0 { + return patches // Get rid of the null case. + } + + patch := Patch{} + charCount1 := 0 // Number of characters into the text1 string. + charCount2 := 0 // Number of characters into the text2 string. + // Start with text1 (prepatchText) and apply the diffs until we arrive at text2 (postpatchText). We recreate the patches one by one to determine context info. + prepatchText := text1 + postpatchText := text1 + + for i, aDiff := range diffs { + if len(patch.diffs) == 0 && aDiff.Type != DiffEqual { + // A new patch starts here. + patch.Start1 = charCount1 + patch.Start2 = charCount2 + } + + switch aDiff.Type { + case DiffInsert: + patch.diffs = append(patch.diffs, aDiff) + patch.Length2 += len(aDiff.Text) + postpatchText = postpatchText[:charCount2] + + aDiff.Text + postpatchText[charCount2:] + case DiffDelete: + patch.Length1 += len(aDiff.Text) + patch.diffs = append(patch.diffs, aDiff) + postpatchText = postpatchText[:charCount2] + postpatchText[charCount2+len(aDiff.Text):] + case DiffEqual: + if len(aDiff.Text) <= 2*dmp.PatchMargin && + len(patch.diffs) != 0 && i != len(diffs)-1 { + // Small equality inside a patch. + patch.diffs = append(patch.diffs, aDiff) + patch.Length1 += len(aDiff.Text) + patch.Length2 += len(aDiff.Text) + } + if len(aDiff.Text) >= 2*dmp.PatchMargin { + // Time for a new patch. + if len(patch.diffs) != 0 { + patch = dmp.PatchAddContext(patch, prepatchText) + patches = append(patches, patch) + patch = Patch{} + // Unlike Unidiff, our patch lists have a rolling context. http://code.google.com/p/google-diff-match-patch/wiki/Unidiff Update prepatch text & pos to reflect the application of the just completed patch. + prepatchText = postpatchText + charCount1 = charCount2 + } + } + } + + // Update the current character count. + if aDiff.Type != DiffInsert { + charCount1 += len(aDiff.Text) + } + if aDiff.Type != DiffDelete { + charCount2 += len(aDiff.Text) + } + } + + // Pick up the leftover patch if not empty. + if len(patch.diffs) != 0 { + patch = dmp.PatchAddContext(patch, prepatchText) + patches = append(patches, patch) + } + + return patches +} + +// PatchDeepCopy returns an array that is identical to a given an array of patches. +func (dmp *DiffMatchPatch) PatchDeepCopy(patches []Patch) []Patch { + patchesCopy := []Patch{} + for _, aPatch := range patches { + patchCopy := Patch{} + for _, aDiff := range aPatch.diffs { + patchCopy.diffs = append(patchCopy.diffs, Diff{ + aDiff.Type, + aDiff.Text, + }) + } + patchCopy.Start1 = aPatch.Start1 + patchCopy.Start2 = aPatch.Start2 + patchCopy.Length1 = aPatch.Length1 + patchCopy.Length2 = aPatch.Length2 + patchesCopy = append(patchesCopy, patchCopy) + } + return patchesCopy +} + +// PatchApply merges a set of patches onto the text. Returns a patched text, as well as an array of true/false values indicating which patches were applied. +func (dmp *DiffMatchPatch) PatchApply(patches []Patch, text string) (string, []bool) { + if len(patches) == 0 { + return text, []bool{} + } + + // Deep copy the patches so that no changes are made to originals. + patches = dmp.PatchDeepCopy(patches) + + nullPadding := dmp.PatchAddPadding(patches) + text = nullPadding + text + nullPadding + patches = dmp.PatchSplitMax(patches) + + x := 0 + // delta keeps track of the offset between the expected and actual location of the previous patch. If there are patches expected at positions 10 and 20, but the first patch was found at 12, delta is 2 and the second patch has an effective expected position of 22. + delta := 0 + results := make([]bool, len(patches)) + for _, aPatch := range patches { + expectedLoc := aPatch.Start2 + delta + text1 := dmp.DiffText1(aPatch.diffs) + var startLoc int + endLoc := -1 + if len(text1) > dmp.MatchMaxBits { + // PatchSplitMax will only provide an oversized pattern in the case of a monster delete. + startLoc = dmp.MatchMain(text, text1[:dmp.MatchMaxBits], expectedLoc) + if startLoc != -1 { + endLoc = dmp.MatchMain(text, + text1[len(text1)-dmp.MatchMaxBits:], expectedLoc+len(text1)-dmp.MatchMaxBits) + if endLoc == -1 || startLoc >= endLoc { + // Can't find valid trailing context. Drop this patch. + startLoc = -1 + } + } + } else { + startLoc = dmp.MatchMain(text, text1, expectedLoc) + } + if startLoc == -1 { + // No match found. :( + results[x] = false + // Subtract the delta for this failed patch from subsequent patches. + delta -= aPatch.Length2 - aPatch.Length1 + } else { + // Found a match. :) + results[x] = true + delta = startLoc - expectedLoc + var text2 string + if endLoc == -1 { + text2 = text[startLoc:int(math.Min(float64(startLoc+len(text1)), float64(len(text))))] + } else { + text2 = text[startLoc:int(math.Min(float64(endLoc+dmp.MatchMaxBits), float64(len(text))))] + } + if text1 == text2 { + // Perfect match, just shove the Replacement text in. + text = text[:startLoc] + dmp.DiffText2(aPatch.diffs) + text[startLoc+len(text1):] + } else { + // Imperfect match. Run a diff to get a framework of equivalent indices. + diffs := dmp.DiffMain(text1, text2, false) + if len(text1) > dmp.MatchMaxBits && float64(dmp.DiffLevenshtein(diffs))/float64(len(text1)) > dmp.PatchDeleteThreshold { + // The end points match, but the content is unacceptably bad. + results[x] = false + } else { + diffs = dmp.DiffCleanupSemanticLossless(diffs) + index1 := 0 + for _, aDiff := range aPatch.diffs { + if aDiff.Type != DiffEqual { + index2 := dmp.DiffXIndex(diffs, index1) + if aDiff.Type == DiffInsert { + // Insertion + text = text[:startLoc+index2] + aDiff.Text + text[startLoc+index2:] + } else if aDiff.Type == DiffDelete { + // Deletion + startIndex := startLoc + index2 + text = text[:startIndex] + + text[startIndex+dmp.DiffXIndex(diffs, index1+len(aDiff.Text))-index2:] + } + } + if aDiff.Type != DiffDelete { + index1 += len(aDiff.Text) + } + } + } + } + } + x++ + } + // Strip the padding off. + text = text[len(nullPadding) : len(nullPadding)+(len(text)-2*len(nullPadding))] + return text, results +} + +// PatchAddPadding adds some padding on text start and end so that edges can match something. +// Intended to be called only from within patchApply. +func (dmp *DiffMatchPatch) PatchAddPadding(patches []Patch) string { + paddingLength := dmp.PatchMargin + nullPadding := "" + for x := 1; x <= paddingLength; x++ { + nullPadding += string(x) + } + + // Bump all the patches forward. + for i := range patches { + patches[i].Start1 += paddingLength + patches[i].Start2 += paddingLength + } + + // Add some padding on start of first diff. + if len(patches[0].diffs) == 0 || patches[0].diffs[0].Type != DiffEqual { + // Add nullPadding equality. + patches[0].diffs = append([]Diff{Diff{DiffEqual, nullPadding}}, patches[0].diffs...) + patches[0].Start1 -= paddingLength // Should be 0. + patches[0].Start2 -= paddingLength // Should be 0. + patches[0].Length1 += paddingLength + patches[0].Length2 += paddingLength + } else if paddingLength > len(patches[0].diffs[0].Text) { + // Grow first equality. + extraLength := paddingLength - len(patches[0].diffs[0].Text) + patches[0].diffs[0].Text = nullPadding[len(patches[0].diffs[0].Text):] + patches[0].diffs[0].Text + patches[0].Start1 -= extraLength + patches[0].Start2 -= extraLength + patches[0].Length1 += extraLength + patches[0].Length2 += extraLength + } + + // Add some padding on end of last diff. + last := len(patches) - 1 + if len(patches[last].diffs) == 0 || patches[last].diffs[len(patches[last].diffs)-1].Type != DiffEqual { + // Add nullPadding equality. + patches[last].diffs = append(patches[last].diffs, Diff{DiffEqual, nullPadding}) + patches[last].Length1 += paddingLength + patches[last].Length2 += paddingLength + } else if paddingLength > len(patches[last].diffs[len(patches[last].diffs)-1].Text) { + // Grow last equality. + lastDiff := patches[last].diffs[len(patches[last].diffs)-1] + extraLength := paddingLength - len(lastDiff.Text) + patches[last].diffs[len(patches[last].diffs)-1].Text += nullPadding[:extraLength] + patches[last].Length1 += extraLength + patches[last].Length2 += extraLength + } + + return nullPadding +} + +// PatchSplitMax looks through the patches and breaks up any which are longer than the maximum limit of the match algorithm. +// Intended to be called only from within patchApply. +func (dmp *DiffMatchPatch) PatchSplitMax(patches []Patch) []Patch { + patchSize := dmp.MatchMaxBits + for x := 0; x < len(patches); x++ { + if patches[x].Length1 <= patchSize { + continue + } + bigpatch := patches[x] + // Remove the big old patch. + patches = append(patches[:x], patches[x+1:]...) + x-- + + Start1 := bigpatch.Start1 + Start2 := bigpatch.Start2 + precontext := "" + for len(bigpatch.diffs) != 0 { + // Create one of several smaller patches. + patch := Patch{} + empty := true + patch.Start1 = Start1 - len(precontext) + patch.Start2 = Start2 - len(precontext) + if len(precontext) != 0 { + patch.Length1 = len(precontext) + patch.Length2 = len(precontext) + patch.diffs = append(patch.diffs, Diff{DiffEqual, precontext}) + } + for len(bigpatch.diffs) != 0 && patch.Length1 < patchSize-dmp.PatchMargin { + diffType := bigpatch.diffs[0].Type + diffText := bigpatch.diffs[0].Text + if diffType == DiffInsert { + // Insertions are harmless. + patch.Length2 += len(diffText) + Start2 += len(diffText) + patch.diffs = append(patch.diffs, bigpatch.diffs[0]) + bigpatch.diffs = bigpatch.diffs[1:] + empty = false + } else if diffType == DiffDelete && len(patch.diffs) == 1 && patch.diffs[0].Type == DiffEqual && len(diffText) > 2*patchSize { + // This is a large deletion. Let it pass in one chunk. + patch.Length1 += len(diffText) + Start1 += len(diffText) + empty = false + patch.diffs = append(patch.diffs, Diff{diffType, diffText}) + bigpatch.diffs = bigpatch.diffs[1:] + } else { + // Deletion or equality. Only take as much as we can stomach. + diffText = diffText[:min(len(diffText), patchSize-patch.Length1-dmp.PatchMargin)] + + patch.Length1 += len(diffText) + Start1 += len(diffText) + if diffType == DiffEqual { + patch.Length2 += len(diffText) + Start2 += len(diffText) + } else { + empty = false + } + patch.diffs = append(patch.diffs, Diff{diffType, diffText}) + if diffText == bigpatch.diffs[0].Text { + bigpatch.diffs = bigpatch.diffs[1:] + } else { + bigpatch.diffs[0].Text = + bigpatch.diffs[0].Text[len(diffText):] + } + } + } + // Compute the head context for the next patch. + precontext = dmp.DiffText2(patch.diffs) + precontext = precontext[max(0, len(precontext)-dmp.PatchMargin):] + + postcontext := "" + // Append the end context for this patch. + if len(dmp.DiffText1(bigpatch.diffs)) > dmp.PatchMargin { + postcontext = dmp.DiffText1(bigpatch.diffs)[:dmp.PatchMargin] + } else { + postcontext = dmp.DiffText1(bigpatch.diffs) + } + + if len(postcontext) != 0 { + patch.Length1 += len(postcontext) + patch.Length2 += len(postcontext) + if len(patch.diffs) != 0 && patch.diffs[len(patch.diffs)-1].Type == DiffEqual { + patch.diffs[len(patch.diffs)-1].Text += postcontext + } else { + patch.diffs = append(patch.diffs, Diff{DiffEqual, postcontext}) + } + } + if !empty { + x++ + patches = append(patches[:x], append([]Patch{patch}, patches[x:]...)...) + } + } + } + return patches +} + +// PatchToText takes a list of patches and returns a textual representation. +func (dmp *DiffMatchPatch) PatchToText(patches []Patch) string { + var text bytes.Buffer + for _, aPatch := range patches { + _, _ = text.WriteString(aPatch.String()) + } + return text.String() +} + +// PatchFromText parses a textual representation of patches and returns a List of Patch objects. +func (dmp *DiffMatchPatch) PatchFromText(textline string) ([]Patch, error) { + patches := []Patch{} + if len(textline) == 0 { + return patches, nil + } + text := strings.Split(textline, "\n") + textPointer := 0 + patchHeader := regexp.MustCompile("^@@ -(\\d+),?(\\d*) \\+(\\d+),?(\\d*) @@$") + + var patch Patch + var sign uint8 + var line string + for textPointer < len(text) { + + if !patchHeader.MatchString(text[textPointer]) { + return patches, errors.New("Invalid patch string: " + text[textPointer]) + } + + patch = Patch{} + m := patchHeader.FindStringSubmatch(text[textPointer]) + + patch.Start1, _ = strconv.Atoi(m[1]) + if len(m[2]) == 0 { + patch.Start1-- + patch.Length1 = 1 + } else if m[2] == "0" { + patch.Length1 = 0 + } else { + patch.Start1-- + patch.Length1, _ = strconv.Atoi(m[2]) + } + + patch.Start2, _ = strconv.Atoi(m[3]) + + if len(m[4]) == 0 { + patch.Start2-- + patch.Length2 = 1 + } else if m[4] == "0" { + patch.Length2 = 0 + } else { + patch.Start2-- + patch.Length2, _ = strconv.Atoi(m[4]) + } + textPointer++ + + for textPointer < len(text) { + if len(text[textPointer]) > 0 { + sign = text[textPointer][0] + } else { + textPointer++ + continue + } + + line = text[textPointer][1:] + line = strings.Replace(line, "+", "%2b", -1) + line, _ = url.QueryUnescape(line) + if sign == '-' { + // Deletion. + patch.diffs = append(patch.diffs, Diff{DiffDelete, line}) + } else if sign == '+' { + // Insertion. + patch.diffs = append(patch.diffs, Diff{DiffInsert, line}) + } else if sign == ' ' { + // Minor equality. + patch.diffs = append(patch.diffs, Diff{DiffEqual, line}) + } else if sign == '@' { + // Start of next patch. + break + } else { + // WTF? + return patches, errors.New("Invalid patch mode '" + string(sign) + "' in: " + string(line)) + } + textPointer++ + } + + patches = append(patches, patch) + } + return patches, nil +} diff --git a/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/stringutil.go b/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/stringutil.go new file mode 100644 index 0000000000000..265f29cc7e595 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/stringutil.go @@ -0,0 +1,88 @@ +// Copyright (c) 2012-2016 The go-diff authors. All rights reserved. +// https://github.com/sergi/go-diff +// See the included LICENSE file for license details. +// +// go-diff is a Go implementation of Google's Diff, Match, and Patch library +// Original library is Copyright (c) 2006 Google Inc. +// http://code.google.com/p/google-diff-match-patch/ + +package diffmatchpatch + +import ( + "strings" + "unicode/utf8" +) + +// unescaper unescapes selected chars for compatibility with JavaScript's encodeURI. +// In speed critical applications this could be dropped since the receiving application will certainly decode these fine. Note that this function is case-sensitive. Thus "%3F" would not be unescaped. But this is ok because it is only called with the output of HttpUtility.UrlEncode which returns lowercase hex. Example: "%3f" -> "?", "%24" -> "$", etc. +var unescaper = strings.NewReplacer( + "%21", "!", "%7E", "~", "%27", "'", + "%28", "(", "%29", ")", "%3B", ";", + "%2F", "/", "%3F", "?", "%3A", ":", + "%40", "@", "%26", "&", "%3D", "=", + "%2B", "+", "%24", "$", "%2C", ",", "%23", "#", "%2A", "*") + +// indexOf returns the first index of pattern in str, starting at str[i]. +func indexOf(str string, pattern string, i int) int { + if i > len(str)-1 { + return -1 + } + if i <= 0 { + return strings.Index(str, pattern) + } + ind := strings.Index(str[i:], pattern) + if ind == -1 { + return -1 + } + return ind + i +} + +// lastIndexOf returns the last index of pattern in str, starting at str[i]. +func lastIndexOf(str string, pattern string, i int) int { + if i < 0 { + return -1 + } + if i >= len(str) { + return strings.LastIndex(str, pattern) + } + _, size := utf8.DecodeRuneInString(str[i:]) + return strings.LastIndex(str[:i+size], pattern) +} + +// runesIndexOf returns the index of pattern in target, starting at target[i]. +func runesIndexOf(target, pattern []rune, i int) int { + if i > len(target)-1 { + return -1 + } + if i <= 0 { + return runesIndex(target, pattern) + } + ind := runesIndex(target[i:], pattern) + if ind == -1 { + return -1 + } + return ind + i +} + +func runesEqual(r1, r2 []rune) bool { + if len(r1) != len(r2) { + return false + } + for i, c := range r1 { + if c != r2[i] { + return false + } + } + return true +} + +// runesIndex is the equivalent of strings.Index for rune slices. +func runesIndex(r1, r2 []rune) int { + last := len(r1) - len(r2) + for i := 0; i <= last; i++ { + if runesEqual(r1[i:i+len(r2)], r2) { + return i + } + } + return -1 +} diff --git a/vendor/github.com/smartystreets/assertions/internal/go-render/LICENSE b/vendor/github.com/smartystreets/assertions/internal/go-render/LICENSE new file mode 100644 index 0000000000000..6280ff0e06b4c --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/go-render/LICENSE @@ -0,0 +1,27 @@ +// Copyright (c) 2015 The Chromium Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/smartystreets/assertions/internal/go-render/render/render.go b/vendor/github.com/smartystreets/assertions/internal/go-render/render/render.go new file mode 100644 index 0000000000000..313611ef0c45e --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/go-render/render/render.go @@ -0,0 +1,481 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package render + +import ( + "bytes" + "fmt" + "reflect" + "sort" + "strconv" +) + +var builtinTypeMap = map[reflect.Kind]string{ + reflect.Bool: "bool", + reflect.Complex128: "complex128", + reflect.Complex64: "complex64", + reflect.Float32: "float32", + reflect.Float64: "float64", + reflect.Int16: "int16", + reflect.Int32: "int32", + reflect.Int64: "int64", + reflect.Int8: "int8", + reflect.Int: "int", + reflect.String: "string", + reflect.Uint16: "uint16", + reflect.Uint32: "uint32", + reflect.Uint64: "uint64", + reflect.Uint8: "uint8", + reflect.Uint: "uint", + reflect.Uintptr: "uintptr", +} + +var builtinTypeSet = map[string]struct{}{} + +func init() { + for _, v := range builtinTypeMap { + builtinTypeSet[v] = struct{}{} + } +} + +var typeOfString = reflect.TypeOf("") +var typeOfInt = reflect.TypeOf(int(1)) +var typeOfUint = reflect.TypeOf(uint(1)) +var typeOfFloat = reflect.TypeOf(10.1) + +// Render converts a structure to a string representation. Unline the "%#v" +// format string, this resolves pointer types' contents in structs, maps, and +// slices/arrays and prints their field values. +func Render(v interface{}) string { + buf := bytes.Buffer{} + s := (*traverseState)(nil) + s.render(&buf, 0, reflect.ValueOf(v), false) + return buf.String() +} + +// renderPointer is called to render a pointer value. +// +// This is overridable so that the test suite can have deterministic pointer +// values in its expectations. +var renderPointer = func(buf *bytes.Buffer, p uintptr) { + fmt.Fprintf(buf, "0x%016x", p) +} + +// traverseState is used to note and avoid recursion as struct members are being +// traversed. +// +// traverseState is allowed to be nil. Specifically, the root state is nil. +type traverseState struct { + parent *traverseState + ptr uintptr +} + +func (s *traverseState) forkFor(ptr uintptr) *traverseState { + for cur := s; cur != nil; cur = cur.parent { + if ptr == cur.ptr { + return nil + } + } + + fs := &traverseState{ + parent: s, + ptr: ptr, + } + return fs +} + +func (s *traverseState) render(buf *bytes.Buffer, ptrs int, v reflect.Value, implicit bool) { + if v.Kind() == reflect.Invalid { + buf.WriteString("nil") + return + } + vt := v.Type() + + // If the type being rendered is a potentially recursive type (a type that + // can contain itself as a member), we need to avoid recursion. + // + // If we've already seen this type before, mark that this is the case and + // write a recursion placeholder instead of actually rendering it. + // + // If we haven't seen it before, fork our `seen` tracking so any higher-up + // renderers will also render it at least once, then mark that we've seen it + // to avoid recursing on lower layers. + pe := uintptr(0) + vk := vt.Kind() + switch vk { + case reflect.Ptr: + // Since structs and arrays aren't pointers, they can't directly be + // recursed, but they can contain pointers to themselves. Record their + // pointer to avoid this. + switch v.Elem().Kind() { + case reflect.Struct, reflect.Array: + pe = v.Pointer() + } + + case reflect.Slice, reflect.Map: + pe = v.Pointer() + } + if pe != 0 { + s = s.forkFor(pe) + if s == nil { + buf.WriteString("") + return + } + } + + isAnon := func(t reflect.Type) bool { + if t.Name() != "" { + if _, ok := builtinTypeSet[t.Name()]; !ok { + return false + } + } + return t.Kind() != reflect.Interface + } + + switch vk { + case reflect.Struct: + if !implicit { + writeType(buf, ptrs, vt) + } + buf.WriteRune('{') + if rendered, ok := renderTime(v); ok { + buf.WriteString(rendered) + } else { + structAnon := vt.Name() == "" + for i := 0; i < vt.NumField(); i++ { + if i > 0 { + buf.WriteString(", ") + } + anon := structAnon && isAnon(vt.Field(i).Type) + + if !anon { + buf.WriteString(vt.Field(i).Name) + buf.WriteRune(':') + } + + s.render(buf, 0, v.Field(i), anon) + } + } + buf.WriteRune('}') + + case reflect.Slice: + if v.IsNil() { + if !implicit { + writeType(buf, ptrs, vt) + buf.WriteString("(nil)") + } else { + buf.WriteString("nil") + } + return + } + fallthrough + + case reflect.Array: + if !implicit { + writeType(buf, ptrs, vt) + } + anon := vt.Name() == "" && isAnon(vt.Elem()) + buf.WriteString("{") + for i := 0; i < v.Len(); i++ { + if i > 0 { + buf.WriteString(", ") + } + + s.render(buf, 0, v.Index(i), anon) + } + buf.WriteRune('}') + + case reflect.Map: + if !implicit { + writeType(buf, ptrs, vt) + } + if v.IsNil() { + buf.WriteString("(nil)") + } else { + buf.WriteString("{") + + mkeys := v.MapKeys() + tryAndSortMapKeys(vt, mkeys) + + kt := vt.Key() + keyAnon := typeOfString.ConvertibleTo(kt) || typeOfInt.ConvertibleTo(kt) || typeOfUint.ConvertibleTo(kt) || typeOfFloat.ConvertibleTo(kt) + valAnon := vt.Name() == "" && isAnon(vt.Elem()) + for i, mk := range mkeys { + if i > 0 { + buf.WriteString(", ") + } + + s.render(buf, 0, mk, keyAnon) + buf.WriteString(":") + s.render(buf, 0, v.MapIndex(mk), valAnon) + } + buf.WriteRune('}') + } + + case reflect.Ptr: + ptrs++ + fallthrough + case reflect.Interface: + if v.IsNil() { + writeType(buf, ptrs, v.Type()) + buf.WriteString("(nil)") + } else { + s.render(buf, ptrs, v.Elem(), false) + } + + case reflect.Chan, reflect.Func, reflect.UnsafePointer: + writeType(buf, ptrs, vt) + buf.WriteRune('(') + renderPointer(buf, v.Pointer()) + buf.WriteRune(')') + + default: + tstr := vt.String() + implicit = implicit || (ptrs == 0 && builtinTypeMap[vk] == tstr) + if !implicit { + writeType(buf, ptrs, vt) + buf.WriteRune('(') + } + + switch vk { + case reflect.String: + fmt.Fprintf(buf, "%q", v.String()) + case reflect.Bool: + fmt.Fprintf(buf, "%v", v.Bool()) + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + fmt.Fprintf(buf, "%d", v.Int()) + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + fmt.Fprintf(buf, "%d", v.Uint()) + + case reflect.Float32, reflect.Float64: + fmt.Fprintf(buf, "%g", v.Float()) + + case reflect.Complex64, reflect.Complex128: + fmt.Fprintf(buf, "%g", v.Complex()) + } + + if !implicit { + buf.WriteRune(')') + } + } +} + +func writeType(buf *bytes.Buffer, ptrs int, t reflect.Type) { + parens := ptrs > 0 + switch t.Kind() { + case reflect.Chan, reflect.Func, reflect.UnsafePointer: + parens = true + } + + if parens { + buf.WriteRune('(') + for i := 0; i < ptrs; i++ { + buf.WriteRune('*') + } + } + + switch t.Kind() { + case reflect.Ptr: + if ptrs == 0 { + // This pointer was referenced from within writeType (e.g., as part of + // rendering a list), and so hasn't had its pointer asterisk accounted + // for. + buf.WriteRune('*') + } + writeType(buf, 0, t.Elem()) + + case reflect.Interface: + if n := t.Name(); n != "" { + buf.WriteString(t.String()) + } else { + buf.WriteString("interface{}") + } + + case reflect.Array: + buf.WriteRune('[') + buf.WriteString(strconv.FormatInt(int64(t.Len()), 10)) + buf.WriteRune(']') + writeType(buf, 0, t.Elem()) + + case reflect.Slice: + if t == reflect.SliceOf(t.Elem()) { + buf.WriteString("[]") + writeType(buf, 0, t.Elem()) + } else { + // Custom slice type, use type name. + buf.WriteString(t.String()) + } + + case reflect.Map: + if t == reflect.MapOf(t.Key(), t.Elem()) { + buf.WriteString("map[") + writeType(buf, 0, t.Key()) + buf.WriteRune(']') + writeType(buf, 0, t.Elem()) + } else { + // Custom map type, use type name. + buf.WriteString(t.String()) + } + + default: + buf.WriteString(t.String()) + } + + if parens { + buf.WriteRune(')') + } +} + +type cmpFn func(a, b reflect.Value) int + +type sortableValueSlice struct { + cmp cmpFn + elements []reflect.Value +} + +func (s sortableValueSlice) Len() int { + return len(s.elements) +} + +func (s sortableValueSlice) Less(i, j int) bool { + return s.cmp(s.elements[i], s.elements[j]) < 0 +} + +func (s sortableValueSlice) Swap(i, j int) { + s.elements[i], s.elements[j] = s.elements[j], s.elements[i] +} + +// cmpForType returns a cmpFn which sorts the data for some type t in the same +// order that a go-native map key is compared for equality. +func cmpForType(t reflect.Type) cmpFn { + switch t.Kind() { + case reflect.String: + return func(av, bv reflect.Value) int { + a, b := av.String(), bv.String() + if a < b { + return -1 + } else if a > b { + return 1 + } + return 0 + } + + case reflect.Bool: + return func(av, bv reflect.Value) int { + a, b := av.Bool(), bv.Bool() + if !a && b { + return -1 + } else if a && !b { + return 1 + } + return 0 + } + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return func(av, bv reflect.Value) int { + a, b := av.Int(), bv.Int() + if a < b { + return -1 + } else if a > b { + return 1 + } + return 0 + } + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, + reflect.Uint64, reflect.Uintptr, reflect.UnsafePointer: + return func(av, bv reflect.Value) int { + a, b := av.Uint(), bv.Uint() + if a < b { + return -1 + } else if a > b { + return 1 + } + return 0 + } + + case reflect.Float32, reflect.Float64: + return func(av, bv reflect.Value) int { + a, b := av.Float(), bv.Float() + if a < b { + return -1 + } else if a > b { + return 1 + } + return 0 + } + + case reflect.Interface: + return func(av, bv reflect.Value) int { + a, b := av.InterfaceData(), bv.InterfaceData() + if a[0] < b[0] { + return -1 + } else if a[0] > b[0] { + return 1 + } + if a[1] < b[1] { + return -1 + } else if a[1] > b[1] { + return 1 + } + return 0 + } + + case reflect.Complex64, reflect.Complex128: + return func(av, bv reflect.Value) int { + a, b := av.Complex(), bv.Complex() + if real(a) < real(b) { + return -1 + } else if real(a) > real(b) { + return 1 + } + if imag(a) < imag(b) { + return -1 + } else if imag(a) > imag(b) { + return 1 + } + return 0 + } + + case reflect.Ptr, reflect.Chan: + return func(av, bv reflect.Value) int { + a, b := av.Pointer(), bv.Pointer() + if a < b { + return -1 + } else if a > b { + return 1 + } + return 0 + } + + case reflect.Struct: + cmpLst := make([]cmpFn, t.NumField()) + for i := range cmpLst { + cmpLst[i] = cmpForType(t.Field(i).Type) + } + return func(a, b reflect.Value) int { + for i, cmp := range cmpLst { + if rslt := cmp(a.Field(i), b.Field(i)); rslt != 0 { + return rslt + } + } + return 0 + } + } + + return nil +} + +func tryAndSortMapKeys(mt reflect.Type, k []reflect.Value) { + if cmp := cmpForType(mt.Key()); cmp != nil { + sort.Sort(sortableValueSlice{cmp, k}) + } +} diff --git a/vendor/github.com/smartystreets/assertions/internal/go-render/render/render_time.go b/vendor/github.com/smartystreets/assertions/internal/go-render/render/render_time.go new file mode 100644 index 0000000000000..990c75d0ffb5d --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/go-render/render/render_time.go @@ -0,0 +1,26 @@ +package render + +import ( + "reflect" + "time" +) + +func renderTime(value reflect.Value) (string, bool) { + if instant, ok := convertTime(value); !ok { + return "", false + } else if instant.IsZero() { + return "0", true + } else { + return instant.String(), true + } +} + +func convertTime(value reflect.Value) (t time.Time, ok bool) { + if value.Type() == timeType { + defer func() { recover() }() + t, ok = value.Interface().(time.Time) + } + return +} + +var timeType = reflect.TypeOf(time.Time{}) diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/.gitignore b/vendor/github.com/smartystreets/assertions/internal/oglematchers/.gitignore new file mode 100644 index 0000000000000..dd8fc7468f4a5 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/oglematchers/.gitignore @@ -0,0 +1,5 @@ +*.6 +6.out +_obj/ +_test/ +_testmain.go diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/.travis.yml b/vendor/github.com/smartystreets/assertions/internal/oglematchers/.travis.yml new file mode 100644 index 0000000000000..b97211926e8dc --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/oglematchers/.travis.yml @@ -0,0 +1,4 @@ +# Cf. http://docs.travis-ci.com/user/getting-started/ +# Cf. http://docs.travis-ci.com/user/languages/go/ + +language: go diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/LICENSE b/vendor/github.com/smartystreets/assertions/internal/oglematchers/LICENSE new file mode 100644 index 0000000000000..d645695673349 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/oglematchers/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/README.md b/vendor/github.com/smartystreets/assertions/internal/oglematchers/README.md new file mode 100644 index 0000000000000..215a2bb7a8bb7 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/oglematchers/README.md @@ -0,0 +1,58 @@ +[![GoDoc](https://godoc.org/github.com/smartystreets/assertions/internal/oglematchers?status.svg)](https://godoc.org/github.com/smartystreets/assertions/internal/oglematchers) + +`oglematchers` is a package for the Go programming language containing a set of +matchers, useful in a testing or mocking framework, inspired by and mostly +compatible with [Google Test][googletest] for C++ and +[Google JS Test][google-js-test]. The package is used by the +[ogletest][ogletest] testing framework and [oglemock][oglemock] mocking +framework, which may be more directly useful to you, but can be generically used +elsewhere as well. + +A "matcher" is simply an object with a `Matches` method defining a set of golang +values matched by the matcher, and a `Description` method describing that set. +For example, here are some matchers: + +```go +// Numbers +Equals(17.13) +LessThan(19) + +// Strings +Equals("taco") +HasSubstr("burrito") +MatchesRegex("t.*o") + +// Combining matchers +AnyOf(LessThan(17), GreaterThan(19)) +``` + +There are lots more; see [here][reference] for a reference. You can also add +your own simply by implementing the `oglematchers.Matcher` interface. + + +Installation +------------ + +First, make sure you have installed Go 1.0.2 or newer. See +[here][golang-install] for instructions. + +Use the following command to install `oglematchers` and keep it up to date: + + go get -u github.com/smartystreets/assertions/internal/oglematchers + + +Documentation +------------- + +See [here][reference] for documentation. Alternatively, you can install the +package and then use `godoc`: + + godoc github.com/smartystreets/assertions/internal/oglematchers + + +[reference]: http://godoc.org/github.com/smartystreets/assertions/internal/oglematchers +[golang-install]: http://golang.org/doc/install.html +[googletest]: http://code.google.com/p/googletest/ +[google-js-test]: http://code.google.com/p/google-js-test/ +[ogletest]: http://github.com/smartystreets/assertions/internal/ogletest +[oglemock]: http://github.com/smartystreets/assertions/internal/oglemock diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/any_of.go b/vendor/github.com/smartystreets/assertions/internal/oglematchers/any_of.go new file mode 100644 index 0000000000000..2918b51f21afd --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/oglematchers/any_of.go @@ -0,0 +1,94 @@ +// Copyright 2011 Aaron Jacobs. All Rights Reserved. +// Author: aaronjjacobs@gmail.com (Aaron Jacobs) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package oglematchers + +import ( + "errors" + "fmt" + "reflect" + "strings" +) + +// AnyOf accepts a set of values S and returns a matcher that follows the +// algorithm below when considering a candidate c: +// +// 1. If there exists a value m in S such that m implements the Matcher +// interface and m matches c, return true. +// +// 2. Otherwise, if there exists a value v in S such that v does not implement +// the Matcher interface and the matcher Equals(v) matches c, return true. +// +// 3. Otherwise, if there is a value m in S such that m implements the Matcher +// interface and m returns a fatal error for c, return that fatal error. +// +// 4. Otherwise, return false. +// +// This is akin to a logical OR operation for matchers, with non-matchers x +// being treated as Equals(x). +func AnyOf(vals ...interface{}) Matcher { + // Get ahold of a type variable for the Matcher interface. + var dummy *Matcher + matcherType := reflect.TypeOf(dummy).Elem() + + // Create a matcher for each value, or use the value itself if it's already a + // matcher. + wrapped := make([]Matcher, len(vals)) + for i, v := range vals { + t := reflect.TypeOf(v) + if t != nil && t.Implements(matcherType) { + wrapped[i] = v.(Matcher) + } else { + wrapped[i] = Equals(v) + } + } + + return &anyOfMatcher{wrapped} +} + +type anyOfMatcher struct { + wrapped []Matcher +} + +func (m *anyOfMatcher) Description() string { + wrappedDescs := make([]string, len(m.wrapped)) + for i, matcher := range m.wrapped { + wrappedDescs[i] = matcher.Description() + } + + return fmt.Sprintf("or(%s)", strings.Join(wrappedDescs, ", ")) +} + +func (m *anyOfMatcher) Matches(c interface{}) (err error) { + err = errors.New("") + + // Try each matcher in turn. + for _, matcher := range m.wrapped { + wrappedErr := matcher.Matches(c) + + // Return immediately if there's a match. + if wrappedErr == nil { + err = nil + return + } + + // Note the fatal error, if any. + if _, isFatal := wrappedErr.(*FatalError); isFatal { + err = wrappedErr + } + } + + return +} diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/contains.go b/vendor/github.com/smartystreets/assertions/internal/oglematchers/contains.go new file mode 100644 index 0000000000000..87f107d3921ff --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/oglematchers/contains.go @@ -0,0 +1,61 @@ +// Copyright 2012 Aaron Jacobs. All Rights Reserved. +// Author: aaronjjacobs@gmail.com (Aaron Jacobs) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package oglematchers + +import ( + "fmt" + "reflect" +) + +// Return a matcher that matches arrays slices with at least one element that +// matches the supplied argument. If the argument x is not itself a Matcher, +// this is equivalent to Contains(Equals(x)). +func Contains(x interface{}) Matcher { + var result containsMatcher + var ok bool + + if result.elementMatcher, ok = x.(Matcher); !ok { + result.elementMatcher = DeepEquals(x) + } + + return &result +} + +type containsMatcher struct { + elementMatcher Matcher +} + +func (m *containsMatcher) Description() string { + return fmt.Sprintf("contains: %s", m.elementMatcher.Description()) +} + +func (m *containsMatcher) Matches(candidate interface{}) error { + // The candidate must be a slice or an array. + v := reflect.ValueOf(candidate) + if v.Kind() != reflect.Slice && v.Kind() != reflect.Array { + return NewFatalError("which is not a slice or array") + } + + // Check each element. + for i := 0; i < v.Len(); i++ { + elem := v.Index(i) + if matchErr := m.elementMatcher.Matches(elem.Interface()); matchErr == nil { + return nil + } + } + + return fmt.Errorf("") +} diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/deep_equals.go b/vendor/github.com/smartystreets/assertions/internal/oglematchers/deep_equals.go new file mode 100644 index 0000000000000..1d91baef32e8f --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/oglematchers/deep_equals.go @@ -0,0 +1,88 @@ +// Copyright 2012 Aaron Jacobs. All Rights Reserved. +// Author: aaronjjacobs@gmail.com (Aaron Jacobs) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package oglematchers + +import ( + "bytes" + "errors" + "fmt" + "reflect" +) + +var byteSliceType reflect.Type = reflect.TypeOf([]byte{}) + +// DeepEquals returns a matcher that matches based on 'deep equality', as +// defined by the reflect package. This matcher requires that values have +// identical types to x. +func DeepEquals(x interface{}) Matcher { + return &deepEqualsMatcher{x} +} + +type deepEqualsMatcher struct { + x interface{} +} + +func (m *deepEqualsMatcher) Description() string { + xDesc := fmt.Sprintf("%v", m.x) + xValue := reflect.ValueOf(m.x) + + // Special case: fmt.Sprintf presents nil slices as "[]", but + // reflect.DeepEqual makes a distinction between nil and empty slices. Make + // this less confusing. + if xValue.Kind() == reflect.Slice && xValue.IsNil() { + xDesc = "" + } + + return fmt.Sprintf("deep equals: %s", xDesc) +} + +func (m *deepEqualsMatcher) Matches(c interface{}) error { + // Make sure the types match. + ct := reflect.TypeOf(c) + xt := reflect.TypeOf(m.x) + + if ct != xt { + return NewFatalError(fmt.Sprintf("which is of type %v", ct)) + } + + // Special case: handle byte slices more efficiently. + cValue := reflect.ValueOf(c) + xValue := reflect.ValueOf(m.x) + + if ct == byteSliceType && !cValue.IsNil() && !xValue.IsNil() { + xBytes := m.x.([]byte) + cBytes := c.([]byte) + + if bytes.Equal(cBytes, xBytes) { + return nil + } + + return errors.New("") + } + + // Defer to the reflect package. + if reflect.DeepEqual(m.x, c) { + return nil + } + + // Special case: if the comparison failed because c is the nil slice, given + // an indication of this (since its value is printed as "[]"). + if cValue.Kind() == reflect.Slice && cValue.IsNil() { + return errors.New("which is nil") + } + + return errors.New("") +} diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/equals.go b/vendor/github.com/smartystreets/assertions/internal/oglematchers/equals.go new file mode 100644 index 0000000000000..a510707b3c7ee --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/oglematchers/equals.go @@ -0,0 +1,541 @@ +// Copyright 2011 Aaron Jacobs. All Rights Reserved. +// Author: aaronjjacobs@gmail.com (Aaron Jacobs) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package oglematchers + +import ( + "errors" + "fmt" + "math" + "reflect" +) + +// Equals(x) returns a matcher that matches values v such that v and x are +// equivalent. This includes the case when the comparison v == x using Go's +// built-in comparison operator is legal (except for structs, which this +// matcher does not support), but for convenience the following rules also +// apply: +// +// * Type checking is done based on underlying types rather than actual +// types, so that e.g. two aliases for string can be compared: +// +// type stringAlias1 string +// type stringAlias2 string +// +// a := "taco" +// b := stringAlias1("taco") +// c := stringAlias2("taco") +// +// ExpectTrue(a == b) // Legal, passes +// ExpectTrue(b == c) // Illegal, doesn't compile +// +// ExpectThat(a, Equals(b)) // Passes +// ExpectThat(b, Equals(c)) // Passes +// +// * Values of numeric type are treated as if they were abstract numbers, and +// compared accordingly. Therefore Equals(17) will match int(17), +// int16(17), uint(17), float32(17), complex64(17), and so on. +// +// If you want a stricter matcher that contains no such cleverness, see +// IdenticalTo instead. +// +// Arrays are supported by this matcher, but do not participate in the +// exceptions above. Two arrays compared with this matcher must have identical +// types, and their element type must itself be comparable according to Go's == +// operator. +func Equals(x interface{}) Matcher { + v := reflect.ValueOf(x) + + // This matcher doesn't support structs. + if v.Kind() == reflect.Struct { + panic(fmt.Sprintf("oglematchers.Equals: unsupported kind %v", v.Kind())) + } + + // The == operator is not defined for non-nil slices. + if v.Kind() == reflect.Slice && v.Pointer() != uintptr(0) { + panic(fmt.Sprintf("oglematchers.Equals: non-nil slice")) + } + + return &equalsMatcher{v} +} + +type equalsMatcher struct { + expectedValue reflect.Value +} + +//////////////////////////////////////////////////////////////////////// +// Numeric types +//////////////////////////////////////////////////////////////////////// + +func isSignedInteger(v reflect.Value) bool { + k := v.Kind() + return k >= reflect.Int && k <= reflect.Int64 +} + +func isUnsignedInteger(v reflect.Value) bool { + k := v.Kind() + return k >= reflect.Uint && k <= reflect.Uintptr +} + +func isInteger(v reflect.Value) bool { + return isSignedInteger(v) || isUnsignedInteger(v) +} + +func isFloat(v reflect.Value) bool { + k := v.Kind() + return k == reflect.Float32 || k == reflect.Float64 +} + +func isComplex(v reflect.Value) bool { + k := v.Kind() + return k == reflect.Complex64 || k == reflect.Complex128 +} + +func checkAgainstInt64(e int64, c reflect.Value) (err error) { + err = errors.New("") + + switch { + case isSignedInteger(c): + if c.Int() == e { + err = nil + } + + case isUnsignedInteger(c): + u := c.Uint() + if u <= math.MaxInt64 && int64(u) == e { + err = nil + } + + // Turn around the various floating point types so that the checkAgainst* + // functions for them can deal with precision issues. + case isFloat(c), isComplex(c): + return Equals(c.Interface()).Matches(e) + + default: + err = NewFatalError("which is not numeric") + } + + return +} + +func checkAgainstUint64(e uint64, c reflect.Value) (err error) { + err = errors.New("") + + switch { + case isSignedInteger(c): + i := c.Int() + if i >= 0 && uint64(i) == e { + err = nil + } + + case isUnsignedInteger(c): + if c.Uint() == e { + err = nil + } + + // Turn around the various floating point types so that the checkAgainst* + // functions for them can deal with precision issues. + case isFloat(c), isComplex(c): + return Equals(c.Interface()).Matches(e) + + default: + err = NewFatalError("which is not numeric") + } + + return +} + +func checkAgainstFloat32(e float32, c reflect.Value) (err error) { + err = errors.New("") + + switch { + case isSignedInteger(c): + if float32(c.Int()) == e { + err = nil + } + + case isUnsignedInteger(c): + if float32(c.Uint()) == e { + err = nil + } + + case isFloat(c): + // Compare using float32 to avoid a false sense of precision; otherwise + // e.g. Equals(float32(0.1)) won't match float32(0.1). + if float32(c.Float()) == e { + err = nil + } + + case isComplex(c): + comp := c.Complex() + rl := real(comp) + im := imag(comp) + + // Compare using float32 to avoid a false sense of precision; otherwise + // e.g. Equals(float32(0.1)) won't match (0.1 + 0i). + if im == 0 && float32(rl) == e { + err = nil + } + + default: + err = NewFatalError("which is not numeric") + } + + return +} + +func checkAgainstFloat64(e float64, c reflect.Value) (err error) { + err = errors.New("") + + ck := c.Kind() + + switch { + case isSignedInteger(c): + if float64(c.Int()) == e { + err = nil + } + + case isUnsignedInteger(c): + if float64(c.Uint()) == e { + err = nil + } + + // If the actual value is lower precision, turn the comparison around so we + // apply the low-precision rules. Otherwise, e.g. Equals(0.1) may not match + // float32(0.1). + case ck == reflect.Float32 || ck == reflect.Complex64: + return Equals(c.Interface()).Matches(e) + + // Otherwise, compare with double precision. + case isFloat(c): + if c.Float() == e { + err = nil + } + + case isComplex(c): + comp := c.Complex() + rl := real(comp) + im := imag(comp) + + if im == 0 && rl == e { + err = nil + } + + default: + err = NewFatalError("which is not numeric") + } + + return +} + +func checkAgainstComplex64(e complex64, c reflect.Value) (err error) { + err = errors.New("") + realPart := real(e) + imaginaryPart := imag(e) + + switch { + case isInteger(c) || isFloat(c): + // If we have no imaginary part, then we should just compare against the + // real part. Otherwise, we can't be equal. + if imaginaryPart != 0 { + return + } + + return checkAgainstFloat32(realPart, c) + + case isComplex(c): + // Compare using complex64 to avoid a false sense of precision; otherwise + // e.g. Equals(0.1 + 0i) won't match float32(0.1). + if complex64(c.Complex()) == e { + err = nil + } + + default: + err = NewFatalError("which is not numeric") + } + + return +} + +func checkAgainstComplex128(e complex128, c reflect.Value) (err error) { + err = errors.New("") + realPart := real(e) + imaginaryPart := imag(e) + + switch { + case isInteger(c) || isFloat(c): + // If we have no imaginary part, then we should just compare against the + // real part. Otherwise, we can't be equal. + if imaginaryPart != 0 { + return + } + + return checkAgainstFloat64(realPart, c) + + case isComplex(c): + if c.Complex() == e { + err = nil + } + + default: + err = NewFatalError("which is not numeric") + } + + return +} + +//////////////////////////////////////////////////////////////////////// +// Other types +//////////////////////////////////////////////////////////////////////// + +func checkAgainstBool(e bool, c reflect.Value) (err error) { + if c.Kind() != reflect.Bool { + err = NewFatalError("which is not a bool") + return + } + + err = errors.New("") + if c.Bool() == e { + err = nil + } + return +} + +func checkAgainstChan(e reflect.Value, c reflect.Value) (err error) { + // Create a description of e's type, e.g. "chan int". + typeStr := fmt.Sprintf("%s %s", e.Type().ChanDir(), e.Type().Elem()) + + // Make sure c is a chan of the correct type. + if c.Kind() != reflect.Chan || + c.Type().ChanDir() != e.Type().ChanDir() || + c.Type().Elem() != e.Type().Elem() { + err = NewFatalError(fmt.Sprintf("which is not a %s", typeStr)) + return + } + + err = errors.New("") + if c.Pointer() == e.Pointer() { + err = nil + } + return +} + +func checkAgainstFunc(e reflect.Value, c reflect.Value) (err error) { + // Make sure c is a function. + if c.Kind() != reflect.Func { + err = NewFatalError("which is not a function") + return + } + + err = errors.New("") + if c.Pointer() == e.Pointer() { + err = nil + } + return +} + +func checkAgainstMap(e reflect.Value, c reflect.Value) (err error) { + // Make sure c is a map. + if c.Kind() != reflect.Map { + err = NewFatalError("which is not a map") + return + } + + err = errors.New("") + if c.Pointer() == e.Pointer() { + err = nil + } + return +} + +func checkAgainstPtr(e reflect.Value, c reflect.Value) (err error) { + // Create a description of e's type, e.g. "*int". + typeStr := fmt.Sprintf("*%v", e.Type().Elem()) + + // Make sure c is a pointer of the correct type. + if c.Kind() != reflect.Ptr || + c.Type().Elem() != e.Type().Elem() { + err = NewFatalError(fmt.Sprintf("which is not a %s", typeStr)) + return + } + + err = errors.New("") + if c.Pointer() == e.Pointer() { + err = nil + } + return +} + +func checkAgainstSlice(e reflect.Value, c reflect.Value) (err error) { + // Create a description of e's type, e.g. "[]int". + typeStr := fmt.Sprintf("[]%v", e.Type().Elem()) + + // Make sure c is a slice of the correct type. + if c.Kind() != reflect.Slice || + c.Type().Elem() != e.Type().Elem() { + err = NewFatalError(fmt.Sprintf("which is not a %s", typeStr)) + return + } + + err = errors.New("") + if c.Pointer() == e.Pointer() { + err = nil + } + return +} + +func checkAgainstString(e reflect.Value, c reflect.Value) (err error) { + // Make sure c is a string. + if c.Kind() != reflect.String { + err = NewFatalError("which is not a string") + return + } + + err = errors.New("") + if c.String() == e.String() { + err = nil + } + return +} + +func checkAgainstArray(e reflect.Value, c reflect.Value) (err error) { + // Create a description of e's type, e.g. "[2]int". + typeStr := fmt.Sprintf("%v", e.Type()) + + // Make sure c is the correct type. + if c.Type() != e.Type() { + err = NewFatalError(fmt.Sprintf("which is not %s", typeStr)) + return + } + + // Check for equality. + if e.Interface() != c.Interface() { + err = errors.New("") + return + } + + return +} + +func checkAgainstUnsafePointer(e reflect.Value, c reflect.Value) (err error) { + // Make sure c is a pointer. + if c.Kind() != reflect.UnsafePointer { + err = NewFatalError("which is not a unsafe.Pointer") + return + } + + err = errors.New("") + if c.Pointer() == e.Pointer() { + err = nil + } + return +} + +func checkForNil(c reflect.Value) (err error) { + err = errors.New("") + + // Make sure it is legal to call IsNil. + switch c.Kind() { + case reflect.Invalid: + case reflect.Chan: + case reflect.Func: + case reflect.Interface: + case reflect.Map: + case reflect.Ptr: + case reflect.Slice: + + default: + err = NewFatalError("which cannot be compared to nil") + return + } + + // Ask whether the value is nil. Handle a nil literal (kind Invalid) + // specially, since it's not legal to call IsNil there. + if c.Kind() == reflect.Invalid || c.IsNil() { + err = nil + } + return +} + +//////////////////////////////////////////////////////////////////////// +// Public implementation +//////////////////////////////////////////////////////////////////////// + +func (m *equalsMatcher) Matches(candidate interface{}) error { + e := m.expectedValue + c := reflect.ValueOf(candidate) + ek := e.Kind() + + switch { + case ek == reflect.Bool: + return checkAgainstBool(e.Bool(), c) + + case isSignedInteger(e): + return checkAgainstInt64(e.Int(), c) + + case isUnsignedInteger(e): + return checkAgainstUint64(e.Uint(), c) + + case ek == reflect.Float32: + return checkAgainstFloat32(float32(e.Float()), c) + + case ek == reflect.Float64: + return checkAgainstFloat64(e.Float(), c) + + case ek == reflect.Complex64: + return checkAgainstComplex64(complex64(e.Complex()), c) + + case ek == reflect.Complex128: + return checkAgainstComplex128(complex128(e.Complex()), c) + + case ek == reflect.Chan: + return checkAgainstChan(e, c) + + case ek == reflect.Func: + return checkAgainstFunc(e, c) + + case ek == reflect.Map: + return checkAgainstMap(e, c) + + case ek == reflect.Ptr: + return checkAgainstPtr(e, c) + + case ek == reflect.Slice: + return checkAgainstSlice(e, c) + + case ek == reflect.String: + return checkAgainstString(e, c) + + case ek == reflect.Array: + return checkAgainstArray(e, c) + + case ek == reflect.UnsafePointer: + return checkAgainstUnsafePointer(e, c) + + case ek == reflect.Invalid: + return checkForNil(c) + } + + panic(fmt.Sprintf("equalsMatcher.Matches: unexpected kind: %v", ek)) +} + +func (m *equalsMatcher) Description() string { + // Special case: handle nil. + if !m.expectedValue.IsValid() { + return "is nil" + } + + return fmt.Sprintf("%v", m.expectedValue.Interface()) +} diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/greater_or_equal.go b/vendor/github.com/smartystreets/assertions/internal/oglematchers/greater_or_equal.go new file mode 100644 index 0000000000000..4b9d103a38189 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/oglematchers/greater_or_equal.go @@ -0,0 +1,39 @@ +// Copyright 2011 Aaron Jacobs. All Rights Reserved. +// Author: aaronjjacobs@gmail.com (Aaron Jacobs) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package oglematchers + +import ( + "fmt" + "reflect" +) + +// GreaterOrEqual returns a matcher that matches integer, floating point, or +// strings values v such that v >= x. Comparison is not defined between numeric +// and string types, but is defined between all integer and floating point +// types. +// +// x must itself be an integer, floating point, or string type; otherwise, +// GreaterOrEqual will panic. +func GreaterOrEqual(x interface{}) Matcher { + desc := fmt.Sprintf("greater than or equal to %v", x) + + // Special case: make it clear that strings are strings. + if reflect.TypeOf(x).Kind() == reflect.String { + desc = fmt.Sprintf("greater than or equal to \"%s\"", x) + } + + return transformDescription(Not(LessThan(x)), desc) +} diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/greater_than.go b/vendor/github.com/smartystreets/assertions/internal/oglematchers/greater_than.go new file mode 100644 index 0000000000000..3eef32178f8c1 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/oglematchers/greater_than.go @@ -0,0 +1,39 @@ +// Copyright 2011 Aaron Jacobs. All Rights Reserved. +// Author: aaronjjacobs@gmail.com (Aaron Jacobs) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package oglematchers + +import ( + "fmt" + "reflect" +) + +// GreaterThan returns a matcher that matches integer, floating point, or +// strings values v such that v > x. Comparison is not defined between numeric +// and string types, but is defined between all integer and floating point +// types. +// +// x must itself be an integer, floating point, or string type; otherwise, +// GreaterThan will panic. +func GreaterThan(x interface{}) Matcher { + desc := fmt.Sprintf("greater than %v", x) + + // Special case: make it clear that strings are strings. + if reflect.TypeOf(x).Kind() == reflect.String { + desc = fmt.Sprintf("greater than \"%s\"", x) + } + + return transformDescription(Not(LessOrEqual(x)), desc) +} diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/less_or_equal.go b/vendor/github.com/smartystreets/assertions/internal/oglematchers/less_or_equal.go new file mode 100644 index 0000000000000..8402cdeaf0996 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/oglematchers/less_or_equal.go @@ -0,0 +1,41 @@ +// Copyright 2011 Aaron Jacobs. All Rights Reserved. +// Author: aaronjjacobs@gmail.com (Aaron Jacobs) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package oglematchers + +import ( + "fmt" + "reflect" +) + +// LessOrEqual returns a matcher that matches integer, floating point, or +// strings values v such that v <= x. Comparison is not defined between numeric +// and string types, but is defined between all integer and floating point +// types. +// +// x must itself be an integer, floating point, or string type; otherwise, +// LessOrEqual will panic. +func LessOrEqual(x interface{}) Matcher { + desc := fmt.Sprintf("less than or equal to %v", x) + + // Special case: make it clear that strings are strings. + if reflect.TypeOf(x).Kind() == reflect.String { + desc = fmt.Sprintf("less than or equal to \"%s\"", x) + } + + // Put LessThan last so that its error messages will be used in the event of + // failure. + return transformDescription(AnyOf(Equals(x), LessThan(x)), desc) +} diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/less_than.go b/vendor/github.com/smartystreets/assertions/internal/oglematchers/less_than.go new file mode 100644 index 0000000000000..8258e45d99d83 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/oglematchers/less_than.go @@ -0,0 +1,152 @@ +// Copyright 2011 Aaron Jacobs. All Rights Reserved. +// Author: aaronjjacobs@gmail.com (Aaron Jacobs) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package oglematchers + +import ( + "errors" + "fmt" + "math" + "reflect" +) + +// LessThan returns a matcher that matches integer, floating point, or strings +// values v such that v < x. Comparison is not defined between numeric and +// string types, but is defined between all integer and floating point types. +// +// x must itself be an integer, floating point, or string type; otherwise, +// LessThan will panic. +func LessThan(x interface{}) Matcher { + v := reflect.ValueOf(x) + kind := v.Kind() + + switch { + case isInteger(v): + case isFloat(v): + case kind == reflect.String: + + default: + panic(fmt.Sprintf("LessThan: unexpected kind %v", kind)) + } + + return &lessThanMatcher{v} +} + +type lessThanMatcher struct { + limit reflect.Value +} + +func (m *lessThanMatcher) Description() string { + // Special case: make it clear that strings are strings. + if m.limit.Kind() == reflect.String { + return fmt.Sprintf("less than \"%s\"", m.limit.String()) + } + + return fmt.Sprintf("less than %v", m.limit.Interface()) +} + +func compareIntegers(v1, v2 reflect.Value) (err error) { + err = errors.New("") + + switch { + case isSignedInteger(v1) && isSignedInteger(v2): + if v1.Int() < v2.Int() { + err = nil + } + return + + case isSignedInteger(v1) && isUnsignedInteger(v2): + if v1.Int() < 0 || uint64(v1.Int()) < v2.Uint() { + err = nil + } + return + + case isUnsignedInteger(v1) && isSignedInteger(v2): + if v1.Uint() <= math.MaxInt64 && int64(v1.Uint()) < v2.Int() { + err = nil + } + return + + case isUnsignedInteger(v1) && isUnsignedInteger(v2): + if v1.Uint() < v2.Uint() { + err = nil + } + return + } + + panic(fmt.Sprintf("compareIntegers: %v %v", v1, v2)) +} + +func getFloat(v reflect.Value) float64 { + switch { + case isSignedInteger(v): + return float64(v.Int()) + + case isUnsignedInteger(v): + return float64(v.Uint()) + + case isFloat(v): + return v.Float() + } + + panic(fmt.Sprintf("getFloat: %v", v)) +} + +func (m *lessThanMatcher) Matches(c interface{}) (err error) { + v1 := reflect.ValueOf(c) + v2 := m.limit + + err = errors.New("") + + // Handle strings as a special case. + if v1.Kind() == reflect.String && v2.Kind() == reflect.String { + if v1.String() < v2.String() { + err = nil + } + return + } + + // If we get here, we require that we are dealing with integers or floats. + v1Legal := isInteger(v1) || isFloat(v1) + v2Legal := isInteger(v2) || isFloat(v2) + if !v1Legal || !v2Legal { + err = NewFatalError("which is not comparable") + return + } + + // Handle the various comparison cases. + switch { + // Both integers + case isInteger(v1) && isInteger(v2): + return compareIntegers(v1, v2) + + // At least one float32 + case v1.Kind() == reflect.Float32 || v2.Kind() == reflect.Float32: + if float32(getFloat(v1)) < float32(getFloat(v2)) { + err = nil + } + return + + // At least one float64 + case v1.Kind() == reflect.Float64 || v2.Kind() == reflect.Float64: + if getFloat(v1) < getFloat(v2) { + err = nil + } + return + } + + // We shouldn't get here. + panic(fmt.Sprintf("lessThanMatcher.Matches: Shouldn't get here: %v %v", v1, v2)) +} diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/matcher.go b/vendor/github.com/smartystreets/assertions/internal/oglematchers/matcher.go new file mode 100644 index 0000000000000..78159a0727c0d --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/oglematchers/matcher.go @@ -0,0 +1,86 @@ +// Copyright 2011 Aaron Jacobs. All Rights Reserved. +// Author: aaronjjacobs@gmail.com (Aaron Jacobs) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package oglematchers provides a set of matchers useful in a testing or +// mocking framework. These matchers are inspired by and mostly compatible with +// Google Test for C++ and Google JS Test. +// +// This package is used by github.com/smartystreets/assertions/internal/ogletest and +// github.com/smartystreets/assertions/internal/oglemock, which may be more directly useful if you're not +// writing your own testing package or defining your own matchers. +package oglematchers + +// A Matcher is some predicate implicitly defining a set of values that it +// matches. For example, GreaterThan(17) matches all numeric values greater +// than 17, and HasSubstr("taco") matches all strings with the substring +// "taco". +// +// Matchers are typically exposed to tests via constructor functions like +// HasSubstr. In order to implement such a function you can either define your +// own matcher type or use NewMatcher. +type Matcher interface { + // Check whether the supplied value belongs to the the set defined by the + // matcher. Return a non-nil error if and only if it does not. + // + // The error describes why the value doesn't match. The error text is a + // relative clause that is suitable for being placed after the value. For + // example, a predicate that matches strings with a particular substring may, + // when presented with a numerical value, return the following error text: + // + // "which is not a string" + // + // Then the failure message may look like: + // + // Expected: has substring "taco" + // Actual: 17, which is not a string + // + // If the error is self-apparent based on the description of the matcher, the + // error text may be empty (but the error still non-nil). For example: + // + // Expected: 17 + // Actual: 19 + // + // If you are implementing a new matcher, see also the documentation on + // FatalError. + Matches(candidate interface{}) error + + // Description returns a string describing the property that values matching + // this matcher have, as a verb phrase where the subject is the value. For + // example, "is greather than 17" or "has substring "taco"". + Description() string +} + +// FatalError is an implementation of the error interface that may be returned +// from matchers, indicating the error should be propagated. Returning a +// *FatalError indicates that the matcher doesn't process values of the +// supplied type, or otherwise doesn't know how to handle the value. +// +// For example, if GreaterThan(17) returned false for the value "taco" without +// a fatal error, then Not(GreaterThan(17)) would return true. This is +// technically correct, but is surprising and may mask failures where the wrong +// sort of matcher is accidentally used. Instead, GreaterThan(17) can return a +// fatal error, which will be propagated by Not(). +type FatalError struct { + errorText string +} + +// NewFatalError creates a FatalError struct with the supplied error text. +func NewFatalError(s string) *FatalError { + return &FatalError{s} +} + +func (e *FatalError) Error() string { + return e.errorText +} diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/not.go b/vendor/github.com/smartystreets/assertions/internal/oglematchers/not.go new file mode 100644 index 0000000000000..623789fe28a83 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/oglematchers/not.go @@ -0,0 +1,53 @@ +// Copyright 2011 Aaron Jacobs. All Rights Reserved. +// Author: aaronjjacobs@gmail.com (Aaron Jacobs) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package oglematchers + +import ( + "errors" + "fmt" +) + +// Not returns a matcher that inverts the set of values matched by the wrapped +// matcher. It does not transform the result for values for which the wrapped +// matcher returns a fatal error. +func Not(m Matcher) Matcher { + return ¬Matcher{m} +} + +type notMatcher struct { + wrapped Matcher +} + +func (m *notMatcher) Matches(c interface{}) (err error) { + err = m.wrapped.Matches(c) + + // Did the wrapped matcher say yes? + if err == nil { + return errors.New("") + } + + // Did the wrapped matcher return a fatal error? + if _, isFatal := err.(*FatalError); isFatal { + return err + } + + // The wrapped matcher returned a non-fatal error. + return nil +} + +func (m *notMatcher) Description() string { + return fmt.Sprintf("not(%s)", m.wrapped.Description()) +} diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/transform_description.go b/vendor/github.com/smartystreets/assertions/internal/oglematchers/transform_description.go new file mode 100644 index 0000000000000..8ea2807c6f4e1 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/internal/oglematchers/transform_description.go @@ -0,0 +1,36 @@ +// Copyright 2011 Aaron Jacobs. All Rights Reserved. +// Author: aaronjjacobs@gmail.com (Aaron Jacobs) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package oglematchers + +// transformDescription returns a matcher that is equivalent to the supplied +// one, except that it has the supplied description instead of the one attached +// to the existing matcher. +func transformDescription(m Matcher, newDesc string) Matcher { + return &transformDescriptionMatcher{newDesc, m} +} + +type transformDescriptionMatcher struct { + desc string + wrappedMatcher Matcher +} + +func (m *transformDescriptionMatcher) Description() string { + return m.desc +} + +func (m *transformDescriptionMatcher) Matches(c interface{}) error { + return m.wrappedMatcher.Matches(c) +} diff --git a/vendor/github.com/smartystreets/assertions/messages.go b/vendor/github.com/smartystreets/assertions/messages.go new file mode 100644 index 0000000000000..178d7e4042415 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/messages.go @@ -0,0 +1,108 @@ +package assertions + +const ( + shouldHaveBeenEqual = "Expected: '%v'\nActual: '%v'\n(Should be equal)" + shouldHaveBeenEqualNoResemblance = "Both the actual and expected values render equally ('%s') and their types are the same. Try using ShouldResemble instead." + shouldNotHaveBeenEqual = "Expected '%v'\nto NOT equal '%v'\n(but it did)!" + shouldHaveBeenEqualTypeMismatch = "Expected: '%v' (%T)\nActual: '%v' (%T)\n(Should be equal, type mismatch)" + + shouldHaveBeenAlmostEqual = "Expected '%v' to almost equal '%v' (but it didn't)!" + shouldHaveNotBeenAlmostEqual = "Expected '%v' to NOT almost equal '%v' (but it did)!" + + shouldHaveResembled = "Expected: '%s'\nActual: '%s'\n(Should resemble)!" + shouldNotHaveResembled = "Expected '%#v'\nto NOT resemble '%#v'\n(but it did)!" + + shouldBePointers = "Both arguments should be pointers " + shouldHaveBeenNonNilPointer = shouldBePointers + "(the %s was %s)!" + shouldHavePointedTo = "Expected '%+v' (address: '%v') and '%+v' (address: '%v') to be the same address (but their weren't)!" + shouldNotHavePointedTo = "Expected '%+v' and '%+v' to be different references (but they matched: '%v')!" + + shouldHaveBeenNil = "Expected: nil\nActual: '%v'" + shouldNotHaveBeenNil = "Expected '%+v' to NOT be nil (but it was)!" + + shouldHaveBeenTrue = "Expected: true\nActual: %v" + shouldHaveBeenFalse = "Expected: false\nActual: %v" + + shouldHaveBeenZeroValue = "'%+v' should have been the zero value" //"Expected: (zero value)\nActual: %v" + shouldNotHaveBeenZeroValue = "'%+v' should NOT have been the zero value" + + shouldHaveBeenGreater = "Expected '%v' to be greater than '%v' (but it wasn't)!" + shouldHaveBeenGreaterOrEqual = "Expected '%v' to be greater than or equal to '%v' (but it wasn't)!" + + shouldHaveBeenLess = "Expected '%v' to be less than '%v' (but it wasn't)!" + shouldHaveBeenLessOrEqual = "Expected '%v' to be less than or equal to '%v' (but it wasn't)!" + + shouldHaveBeenBetween = "Expected '%v' to be between '%v' and '%v' (but it wasn't)!" + shouldNotHaveBeenBetween = "Expected '%v' NOT to be between '%v' and '%v' (but it was)!" + shouldHaveDifferentUpperAndLower = "The lower and upper bounds must be different values (they were both '%v')." + + shouldHaveBeenBetweenOrEqual = "Expected '%v' to be between '%v' and '%v' or equal to one of them (but it wasn't)!" + shouldNotHaveBeenBetweenOrEqual = "Expected '%v' NOT to be between '%v' and '%v' or equal to one of them (but it was)!" + + shouldHaveContained = "Expected the container (%v) to contain: '%v' (but it didn't)!" + shouldNotHaveContained = "Expected the container (%v) NOT to contain: '%v' (but it did)!" + shouldHaveBeenAValidCollection = "You must provide a valid container (was %v)!" + + shouldHaveContainedKey = "Expected the %v to contain the key: %v (but it didn't)!" + shouldNotHaveContainedKey = "Expected the %v NOT to contain the key: %v (but it did)!" + shouldHaveBeenAValidMap = "You must provide a valid map type (was %v)!" + + shouldHaveBeenIn = "Expected '%v' to be in the container (%v), but it wasn't!" + shouldNotHaveBeenIn = "Expected '%v' NOT to be in the container (%v), but it was!" + + shouldHaveBeenEmpty = "Expected %+v to be empty (but it wasn't)!" + shouldNotHaveBeenEmpty = "Expected %+v to NOT be empty (but it was)!" + + shouldHaveBeenAValidInteger = "You must provide a valid integer (was %v)!" + shouldHaveBeenAValidLength = "You must provide a valid positive integer (was %v)!" + shouldHaveHadLength = "Expected collection to have length equal to [%v], but it's length was [%v] instead! contents: %+v" + + shouldHaveStartedWith = "Expected '%v'\nto start with '%v'\n(but it didn't)!" + shouldNotHaveStartedWith = "Expected '%v'\nNOT to start with '%v'\n(but it did)!" + + shouldHaveEndedWith = "Expected '%v'\nto end with '%v'\n(but it didn't)!" + shouldNotHaveEndedWith = "Expected '%v'\nNOT to end with '%v'\n(but it did)!" + + shouldAllBeStrings = "All arguments to this assertion must be strings (you provided: %v)." + shouldBothBeStrings = "Both arguments to this assertion must be strings (you provided %v and %v)." + + shouldHaveContainedSubstring = "Expected '%s' to contain substring '%s' (but it didn't)!" + shouldNotHaveContainedSubstring = "Expected '%s' NOT to contain substring '%s' (but it did)!" + + shouldBeString = "The argument to this assertion must be a string (you provided %v)." + shouldHaveBeenBlank = "Expected '%s' to be blank (but it wasn't)!" + shouldNotHaveBeenBlank = "Expected value to NOT be blank (but it was)!" + + shouldUseVoidNiladicFunction = "You must provide a void, niladic function as the first argument!" + shouldHavePanicked = "Expected func() to panic (but it didn't)!" + shouldNotHavePanicked = "Expected func() NOT to panic (error: '%+v')!" + + shouldHavePanickedWith = "Expected func() to panic with '%v' (but it panicked with '%v')!" + shouldNotHavePanickedWith = "Expected func() NOT to panic with '%v' (but it did)!" + + shouldHaveBeenA = "Expected '%v' to be: '%v' (but was: '%v')!" + shouldNotHaveBeenA = "Expected '%v' to NOT be: '%v' (but it was)!" + + shouldHaveImplemented = "Expected: '%v interface support'\nActual: '%v' does not implement the interface!" + shouldNotHaveImplemented = "Expected '%v'\nto NOT implement '%v'\n(but it did)!" + shouldCompareWithInterfacePointer = "The expected value must be a pointer to an interface type (eg. *fmt.Stringer)" + shouldNotBeNilActual = "The actual value was 'nil' and should be a value or a pointer to a value!" + + shouldBeError = "Expected an error value (but was '%v' instead)!" + shouldBeErrorInvalidComparisonValue = "The final argument to this assertion must be a string or an error value (you provided: '%v')." + + shouldWrapInvalidTypes = "The first and last arguments to this assertion must both be error values (you provided: '%v' and '%v')." + + shouldUseTimes = "You must provide time instances as arguments to this assertion." + shouldUseTimeSlice = "You must provide a slice of time instances as the first argument to this assertion." + shouldUseDurationAndTime = "You must provide a duration and a time as arguments to this assertion." + + shouldHaveHappenedBefore = "Expected '%v' to happen before '%v' (it happened '%v' after)!" + shouldHaveHappenedAfter = "Expected '%v' to happen after '%v' (it happened '%v' before)!" + shouldHaveHappenedBetween = "Expected '%v' to happen between '%v' and '%v' (it happened '%v' outside threshold)!" + shouldNotHaveHappenedOnOrBetween = "Expected '%v' to NOT happen on or between '%v' and '%v' (but it did)!" + + // format params: incorrect-index, previous-index, previous-time, incorrect-index, incorrect-time + shouldHaveBeenChronological = "The 'Time' at index [%d] should have happened after the previous one (but it didn't!):\n [%d]: %s\n [%d]: %s (see, it happened before!)" + shouldNotHaveBeenchronological = "The provided times should NOT be chronological, but they were." +) diff --git a/vendor/github.com/smartystreets/assertions/panic.go b/vendor/github.com/smartystreets/assertions/panic.go new file mode 100644 index 0000000000000..d290d9f324e9c --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/panic.go @@ -0,0 +1,128 @@ +package assertions + +import ( + "errors" + "fmt" +) + +// ShouldPanic receives a void, niladic function and expects to recover a panic. +func ShouldPanic(actual interface{}, expected ...interface{}) (message string) { + if fail := need(0, expected); fail != success { + return fail + } + + action, _ := actual.(func()) + + if action == nil { + message = shouldUseVoidNiladicFunction + return + } + + defer func() { + recovered := recover() + if recovered == nil { + message = shouldHavePanicked + } else { + message = success + } + }() + action() + + return +} + +// ShouldNotPanic receives a void, niladic function and expects to execute the function without any panic. +func ShouldNotPanic(actual interface{}, expected ...interface{}) (message string) { + if fail := need(0, expected); fail != success { + return fail + } + + action, _ := actual.(func()) + + if action == nil { + message = shouldUseVoidNiladicFunction + return + } + + defer func() { + recovered := recover() + if recovered != nil { + message = fmt.Sprintf(shouldNotHavePanicked, recovered) + } else { + message = success + } + }() + action() + + return +} + +// ShouldPanicWith receives a void, niladic function and expects to recover a panic with the second argument as the content. +// If the expected value is an error and the recovered value is an error, errors.Is is used to compare them. +func ShouldPanicWith(actual interface{}, expected ...interface{}) (message string) { + if fail := need(1, expected); fail != success { + return fail + } + + action, _ := actual.(func()) + + if action == nil { + message = shouldUseVoidNiladicFunction + return + } + + defer func() { + recovered := recover() + if recovered == nil { + message = shouldHavePanicked + } else { + recoveredErr, errFound := recovered.(error) + expectedErr, expectedFound := expected[0].(error) + if errFound && expectedFound && errors.Is(recoveredErr, expectedErr) { + message = success + } else if equal := ShouldEqual(recovered, expected[0]); equal != success { + message = serializer.serialize(expected[0], recovered, fmt.Sprintf(shouldHavePanickedWith, expected[0], recovered)) + } else { + message = success + } + } + }() + action() + + return +} + +// ShouldNotPanicWith receives a void, niladic function and expects to recover a panic whose content differs from the second argument. +// If the expected value is an error and the recovered value is an error, errors.Is is used to compare them. +func ShouldNotPanicWith(actual interface{}, expected ...interface{}) (message string) { + if fail := need(1, expected); fail != success { + return fail + } + + action, _ := actual.(func()) + + if action == nil { + message = shouldUseVoidNiladicFunction + return + } + + defer func() { + recovered := recover() + if recovered == nil { + message = success + } else { + recoveredErr, errFound := recovered.(error) + expectedErr, expectedFound := expected[0].(error) + if errFound && expectedFound && errors.Is(recoveredErr, expectedErr) { + message = fmt.Sprintf(shouldNotHavePanickedWith, expected[0]) + } else if equal := ShouldEqual(recovered, expected[0]); equal == success { + message = fmt.Sprintf(shouldNotHavePanickedWith, expected[0]) + } else { + message = success + } + } + }() + action() + + return +} diff --git a/vendor/github.com/smartystreets/assertions/quantity.go b/vendor/github.com/smartystreets/assertions/quantity.go new file mode 100644 index 0000000000000..f28b0a062ba5c --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/quantity.go @@ -0,0 +1,141 @@ +package assertions + +import ( + "fmt" + + "github.com/smartystreets/assertions/internal/oglematchers" +) + +// ShouldBeGreaterThan receives exactly two parameters and ensures that the first is greater than the second. +func ShouldBeGreaterThan(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } + + if matchError := oglematchers.GreaterThan(expected[0]).Matches(actual); matchError != nil { + return fmt.Sprintf(shouldHaveBeenGreater, actual, expected[0]) + } + return success +} + +// ShouldBeGreaterThanOrEqualTo receives exactly two parameters and ensures that the first is greater than or equal to the second. +func ShouldBeGreaterThanOrEqualTo(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } else if matchError := oglematchers.GreaterOrEqual(expected[0]).Matches(actual); matchError != nil { + return fmt.Sprintf(shouldHaveBeenGreaterOrEqual, actual, expected[0]) + } + return success +} + +// ShouldBeLessThan receives exactly two parameters and ensures that the first is less than the second. +func ShouldBeLessThan(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } else if matchError := oglematchers.LessThan(expected[0]).Matches(actual); matchError != nil { + return fmt.Sprintf(shouldHaveBeenLess, actual, expected[0]) + } + return success +} + +// ShouldBeLessThan receives exactly two parameters and ensures that the first is less than or equal to the second. +func ShouldBeLessThanOrEqualTo(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } else if matchError := oglematchers.LessOrEqual(expected[0]).Matches(actual); matchError != nil { + return fmt.Sprintf(shouldHaveBeenLessOrEqual, actual, expected[0]) + } + return success +} + +// ShouldBeBetween receives exactly three parameters: an actual value, a lower bound, and an upper bound. +// It ensures that the actual value is between both bounds (but not equal to either of them). +func ShouldBeBetween(actual interface{}, expected ...interface{}) string { + if fail := need(2, expected); fail != success { + return fail + } + lower, upper, fail := deriveBounds(expected) + + if fail != success { + return fail + } else if !isBetween(actual, lower, upper) { + return fmt.Sprintf(shouldHaveBeenBetween, actual, lower, upper) + } + return success +} + +// ShouldNotBeBetween receives exactly three parameters: an actual value, a lower bound, and an upper bound. +// It ensures that the actual value is NOT between both bounds. +func ShouldNotBeBetween(actual interface{}, expected ...interface{}) string { + if fail := need(2, expected); fail != success { + return fail + } + lower, upper, fail := deriveBounds(expected) + + if fail != success { + return fail + } else if isBetween(actual, lower, upper) { + return fmt.Sprintf(shouldNotHaveBeenBetween, actual, lower, upper) + } + return success +} +func deriveBounds(values []interface{}) (lower interface{}, upper interface{}, fail string) { + lower = values[0] + upper = values[1] + + if ShouldNotEqual(lower, upper) != success { + return nil, nil, fmt.Sprintf(shouldHaveDifferentUpperAndLower, lower) + } else if ShouldBeLessThan(lower, upper) != success { + lower, upper = upper, lower + } + return lower, upper, success +} +func isBetween(value, lower, upper interface{}) bool { + if ShouldBeGreaterThan(value, lower) != success { + return false + } else if ShouldBeLessThan(value, upper) != success { + return false + } + return true +} + +// ShouldBeBetweenOrEqual receives exactly three parameters: an actual value, a lower bound, and an upper bound. +// It ensures that the actual value is between both bounds or equal to one of them. +func ShouldBeBetweenOrEqual(actual interface{}, expected ...interface{}) string { + if fail := need(2, expected); fail != success { + return fail + } + lower, upper, fail := deriveBounds(expected) + + if fail != success { + return fail + } else if !isBetweenOrEqual(actual, lower, upper) { + return fmt.Sprintf(shouldHaveBeenBetweenOrEqual, actual, lower, upper) + } + return success +} + +// ShouldNotBeBetweenOrEqual receives exactly three parameters: an actual value, a lower bound, and an upper bound. +// It ensures that the actual value is nopt between the bounds nor equal to either of them. +func ShouldNotBeBetweenOrEqual(actual interface{}, expected ...interface{}) string { + if fail := need(2, expected); fail != success { + return fail + } + lower, upper, fail := deriveBounds(expected) + + if fail != success { + return fail + } else if isBetweenOrEqual(actual, lower, upper) { + return fmt.Sprintf(shouldNotHaveBeenBetweenOrEqual, actual, lower, upper) + } + return success +} + +func isBetweenOrEqual(value, lower, upper interface{}) bool { + if ShouldBeGreaterThanOrEqualTo(value, lower) != success { + return false + } else if ShouldBeLessThanOrEqualTo(value, upper) != success { + return false + } + return true +} diff --git a/vendor/github.com/smartystreets/assertions/serializer.go b/vendor/github.com/smartystreets/assertions/serializer.go new file mode 100644 index 0000000000000..f1e3570edc489 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/serializer.go @@ -0,0 +1,70 @@ +package assertions + +import ( + "encoding/json" + "fmt" + "strings" + + "github.com/smartystreets/assertions/internal/go-render/render" +) + +type Serializer interface { + serialize(expected, actual interface{}, message string) string + serializeDetailed(expected, actual interface{}, message string) string +} + +type failureSerializer struct{} + +func (self *failureSerializer) serializeDetailed(expected, actual interface{}, message string) string { + if index := strings.Index(message, " Diff:"); index > 0 { + message = message[:index] + } + view := FailureView{ + Message: message, + Expected: render.Render(expected), + Actual: render.Render(actual), + } + serialized, _ := json.Marshal(view) + return string(serialized) +} + +func (self *failureSerializer) serialize(expected, actual interface{}, message string) string { + if index := strings.Index(message, " Diff:"); index > 0 { + message = message[:index] + } + view := FailureView{ + Message: message, + Expected: fmt.Sprintf("%+v", expected), + Actual: fmt.Sprintf("%+v", actual), + } + serialized, _ := json.Marshal(view) + return string(serialized) +} + +func newSerializer() *failureSerializer { + return &failureSerializer{} +} + +/////////////////////////////////////////////////////////////////////////////// + +// This struct is also declared in github.com/smartystreets/goconvey/convey/reporting. +// The json struct tags should be equal in both declarations. +type FailureView struct { + Message string `json:"Message"` + Expected string `json:"Expected"` + Actual string `json:"Actual"` +} + +/////////////////////////////////////////////////////// + +// noopSerializer just gives back the original message. This is useful when we are using +// the assertions from a context other than the GoConvey Web UI, that requires the JSON +// structure provided by the failureSerializer. +type noopSerializer struct{} + +func (self *noopSerializer) serialize(expected, actual interface{}, message string) string { + return message +} +func (self *noopSerializer) serializeDetailed(expected, actual interface{}, message string) string { + return message +} diff --git a/vendor/github.com/smartystreets/assertions/strings.go b/vendor/github.com/smartystreets/assertions/strings.go new file mode 100644 index 0000000000000..dbc3f04790e01 --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/strings.go @@ -0,0 +1,227 @@ +package assertions + +import ( + "fmt" + "reflect" + "strings" +) + +// ShouldStartWith receives exactly 2 string parameters and ensures that the first starts with the second. +func ShouldStartWith(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } + + value, valueIsString := actual.(string) + prefix, prefixIsString := expected[0].(string) + + if !valueIsString || !prefixIsString { + return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) + } + + return shouldStartWith(value, prefix) +} +func shouldStartWith(value, prefix string) string { + if !strings.HasPrefix(value, prefix) { + shortval := value + if len(shortval) > len(prefix) { + shortval = shortval[:len(prefix)] + "..." + } + return serializer.serialize(prefix, shortval, fmt.Sprintf(shouldHaveStartedWith, value, prefix)) + } + return success +} + +// ShouldNotStartWith receives exactly 2 string parameters and ensures that the first does not start with the second. +func ShouldNotStartWith(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } + + value, valueIsString := actual.(string) + prefix, prefixIsString := expected[0].(string) + + if !valueIsString || !prefixIsString { + return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) + } + + return shouldNotStartWith(value, prefix) +} +func shouldNotStartWith(value, prefix string) string { + if strings.HasPrefix(value, prefix) { + if value == "" { + value = "" + } + if prefix == "" { + prefix = "" + } + return fmt.Sprintf(shouldNotHaveStartedWith, value, prefix) + } + return success +} + +// ShouldEndWith receives exactly 2 string parameters and ensures that the first ends with the second. +func ShouldEndWith(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } + + value, valueIsString := actual.(string) + suffix, suffixIsString := expected[0].(string) + + if !valueIsString || !suffixIsString { + return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) + } + + return shouldEndWith(value, suffix) +} +func shouldEndWith(value, suffix string) string { + if !strings.HasSuffix(value, suffix) { + shortval := value + if len(shortval) > len(suffix) { + shortval = "..." + shortval[len(shortval)-len(suffix):] + } + return serializer.serialize(suffix, shortval, fmt.Sprintf(shouldHaveEndedWith, value, suffix)) + } + return success +} + +// ShouldEndWith receives exactly 2 string parameters and ensures that the first does not end with the second. +func ShouldNotEndWith(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } + + value, valueIsString := actual.(string) + suffix, suffixIsString := expected[0].(string) + + if !valueIsString || !suffixIsString { + return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) + } + + return shouldNotEndWith(value, suffix) +} +func shouldNotEndWith(value, suffix string) string { + if strings.HasSuffix(value, suffix) { + if value == "" { + value = "" + } + if suffix == "" { + suffix = "" + } + return fmt.Sprintf(shouldNotHaveEndedWith, value, suffix) + } + return success +} + +// ShouldContainSubstring receives exactly 2 string parameters and ensures that the first contains the second as a substring. +func ShouldContainSubstring(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } + + long, longOk := actual.(string) + short, shortOk := expected[0].(string) + + if !longOk || !shortOk { + return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) + } + + if !strings.Contains(long, short) { + return serializer.serialize(expected[0], actual, fmt.Sprintf(shouldHaveContainedSubstring, long, short)) + } + return success +} + +// ShouldNotContainSubstring receives exactly 2 string parameters and ensures that the first does NOT contain the second as a substring. +func ShouldNotContainSubstring(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } + + long, longOk := actual.(string) + short, shortOk := expected[0].(string) + + if !longOk || !shortOk { + return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) + } + + if strings.Contains(long, short) { + return fmt.Sprintf(shouldNotHaveContainedSubstring, long, short) + } + return success +} + +// ShouldBeBlank receives exactly 1 string parameter and ensures that it is equal to "". +func ShouldBeBlank(actual interface{}, expected ...interface{}) string { + if fail := need(0, expected); fail != success { + return fail + } + value, ok := actual.(string) + if !ok { + return fmt.Sprintf(shouldBeString, reflect.TypeOf(actual)) + } + if value != "" { + return serializer.serialize("", value, fmt.Sprintf(shouldHaveBeenBlank, value)) + } + return success +} + +// ShouldNotBeBlank receives exactly 1 string parameter and ensures that it is equal to "". +func ShouldNotBeBlank(actual interface{}, expected ...interface{}) string { + if fail := need(0, expected); fail != success { + return fail + } + value, ok := actual.(string) + if !ok { + return fmt.Sprintf(shouldBeString, reflect.TypeOf(actual)) + } + if value == "" { + return shouldNotHaveBeenBlank + } + return success +} + +// ShouldEqualWithout receives exactly 3 string parameters and ensures that the first is equal to the second +// after removing all instances of the third from the first using strings.Replace(first, third, "", -1). +func ShouldEqualWithout(actual interface{}, expected ...interface{}) string { + if fail := need(2, expected); fail != success { + return fail + } + actualString, ok1 := actual.(string) + expectedString, ok2 := expected[0].(string) + replace, ok3 := expected[1].(string) + + if !ok1 || !ok2 || !ok3 { + return fmt.Sprintf(shouldAllBeStrings, []reflect.Type{ + reflect.TypeOf(actual), + reflect.TypeOf(expected[0]), + reflect.TypeOf(expected[1]), + }) + } + + replaced := strings.Replace(actualString, replace, "", -1) + if replaced == expectedString { + return "" + } + + return fmt.Sprintf("Expected '%s' to equal '%s' but without any '%s' (but it didn't).", actualString, expectedString, replace) +} + +// ShouldEqualTrimSpace receives exactly 2 string parameters and ensures that the first is equal to the second +// after removing all leading and trailing whitespace using strings.TrimSpace(first). +func ShouldEqualTrimSpace(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } + + actualString, valueIsString := actual.(string) + _, value2IsString := expected[0].(string) + + if !valueIsString || !value2IsString { + return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) + } + + actualString = strings.TrimSpace(actualString) + return ShouldEqual(actualString, expected[0]) +} diff --git a/vendor/github.com/smartystreets/assertions/time.go b/vendor/github.com/smartystreets/assertions/time.go new file mode 100644 index 0000000000000..918ee2840e6df --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/time.go @@ -0,0 +1,218 @@ +package assertions + +import ( + "fmt" + "time" +) + +// ShouldHappenBefore receives exactly 2 time.Time arguments and asserts that the first happens before the second. +func ShouldHappenBefore(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } + actualTime, firstOk := actual.(time.Time) + expectedTime, secondOk := expected[0].(time.Time) + + if !firstOk || !secondOk { + return shouldUseTimes + } + + if !actualTime.Before(expectedTime) { + return fmt.Sprintf(shouldHaveHappenedBefore, actualTime, expectedTime, actualTime.Sub(expectedTime)) + } + + return success +} + +// ShouldHappenOnOrBefore receives exactly 2 time.Time arguments and asserts that the first happens on or before the second. +func ShouldHappenOnOrBefore(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } + actualTime, firstOk := actual.(time.Time) + expectedTime, secondOk := expected[0].(time.Time) + + if !firstOk || !secondOk { + return shouldUseTimes + } + + if actualTime.Equal(expectedTime) { + return success + } + return ShouldHappenBefore(actualTime, expectedTime) +} + +// ShouldHappenAfter receives exactly 2 time.Time arguments and asserts that the first happens after the second. +func ShouldHappenAfter(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } + actualTime, firstOk := actual.(time.Time) + expectedTime, secondOk := expected[0].(time.Time) + + if !firstOk || !secondOk { + return shouldUseTimes + } + if !actualTime.After(expectedTime) { + return fmt.Sprintf(shouldHaveHappenedAfter, actualTime, expectedTime, expectedTime.Sub(actualTime)) + } + return success +} + +// ShouldHappenOnOrAfter receives exactly 2 time.Time arguments and asserts that the first happens on or after the second. +func ShouldHappenOnOrAfter(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } + actualTime, firstOk := actual.(time.Time) + expectedTime, secondOk := expected[0].(time.Time) + + if !firstOk || !secondOk { + return shouldUseTimes + } + if actualTime.Equal(expectedTime) { + return success + } + return ShouldHappenAfter(actualTime, expectedTime) +} + +// ShouldHappenBetween receives exactly 3 time.Time arguments and asserts that the first happens between (not on) the second and third. +func ShouldHappenBetween(actual interface{}, expected ...interface{}) string { + if fail := need(2, expected); fail != success { + return fail + } + actualTime, firstOk := actual.(time.Time) + min, secondOk := expected[0].(time.Time) + max, thirdOk := expected[1].(time.Time) + + if !firstOk || !secondOk || !thirdOk { + return shouldUseTimes + } + + if !actualTime.After(min) { + return fmt.Sprintf(shouldHaveHappenedBetween, actualTime, min, max, min.Sub(actualTime)) + } + if !actualTime.Before(max) { + return fmt.Sprintf(shouldHaveHappenedBetween, actualTime, min, max, actualTime.Sub(max)) + } + return success +} + +// ShouldHappenOnOrBetween receives exactly 3 time.Time arguments and asserts that the first happens between or on the second and third. +func ShouldHappenOnOrBetween(actual interface{}, expected ...interface{}) string { + if fail := need(2, expected); fail != success { + return fail + } + actualTime, firstOk := actual.(time.Time) + min, secondOk := expected[0].(time.Time) + max, thirdOk := expected[1].(time.Time) + + if !firstOk || !secondOk || !thirdOk { + return shouldUseTimes + } + if actualTime.Equal(min) || actualTime.Equal(max) { + return success + } + return ShouldHappenBetween(actualTime, min, max) +} + +// ShouldNotHappenOnOrBetween receives exactly 3 time.Time arguments and asserts that the first +// does NOT happen between or on the second or third. +func ShouldNotHappenOnOrBetween(actual interface{}, expected ...interface{}) string { + if fail := need(2, expected); fail != success { + return fail + } + actualTime, firstOk := actual.(time.Time) + min, secondOk := expected[0].(time.Time) + max, thirdOk := expected[1].(time.Time) + + if !firstOk || !secondOk || !thirdOk { + return shouldUseTimes + } + if actualTime.Equal(min) || actualTime.Equal(max) { + return fmt.Sprintf(shouldNotHaveHappenedOnOrBetween, actualTime, min, max) + } + if actualTime.After(min) && actualTime.Before(max) { + return fmt.Sprintf(shouldNotHaveHappenedOnOrBetween, actualTime, min, max) + } + return success +} + +// ShouldHappenWithin receives a time.Time, a time.Duration, and a time.Time (3 arguments) +// and asserts that the first time.Time happens within or on the duration specified relative to +// the other time.Time. +func ShouldHappenWithin(actual interface{}, expected ...interface{}) string { + if fail := need(2, expected); fail != success { + return fail + } + actualTime, firstOk := actual.(time.Time) + tolerance, secondOk := expected[0].(time.Duration) + threshold, thirdOk := expected[1].(time.Time) + + if !firstOk || !secondOk || !thirdOk { + return shouldUseDurationAndTime + } + + min := threshold.Add(-tolerance) + max := threshold.Add(tolerance) + return ShouldHappenOnOrBetween(actualTime, min, max) +} + +// ShouldNotHappenWithin receives a time.Time, a time.Duration, and a time.Time (3 arguments) +// and asserts that the first time.Time does NOT happen within or on the duration specified relative to +// the other time.Time. +func ShouldNotHappenWithin(actual interface{}, expected ...interface{}) string { + if fail := need(2, expected); fail != success { + return fail + } + actualTime, firstOk := actual.(time.Time) + tolerance, secondOk := expected[0].(time.Duration) + threshold, thirdOk := expected[1].(time.Time) + + if !firstOk || !secondOk || !thirdOk { + return shouldUseDurationAndTime + } + + min := threshold.Add(-tolerance) + max := threshold.Add(tolerance) + return ShouldNotHappenOnOrBetween(actualTime, min, max) +} + +// ShouldBeChronological receives a []time.Time slice and asserts that they are +// in chronological order starting with the first time.Time as the earliest. +func ShouldBeChronological(actual interface{}, expected ...interface{}) string { + if fail := need(0, expected); fail != success { + return fail + } + + times, ok := actual.([]time.Time) + if !ok { + return shouldUseTimeSlice + } + + var previous time.Time + for i, current := range times { + if i > 0 && current.Before(previous) { + return fmt.Sprintf(shouldHaveBeenChronological, + i, i-1, previous.String(), i, current.String()) + } + previous = current + } + return "" +} + +// ShouldNotBeChronological receives a []time.Time slice and asserts that they are +// NOT in chronological order. +func ShouldNotBeChronological(actual interface{}, expected ...interface{}) string { + if fail := need(0, expected); fail != success { + return fail + } + if _, ok := actual.([]time.Time); !ok { + return shouldUseTimeSlice + } + result := ShouldBeChronological(actual, expected...) + if result != "" { + return "" + } + return shouldNotHaveBeenchronological +} diff --git a/vendor/github.com/smartystreets/assertions/type.go b/vendor/github.com/smartystreets/assertions/type.go new file mode 100644 index 0000000000000..1984fe89454fa --- /dev/null +++ b/vendor/github.com/smartystreets/assertions/type.go @@ -0,0 +1,154 @@ +package assertions + +import ( + "errors" + "fmt" + "reflect" +) + +// ShouldHaveSameTypeAs receives exactly two parameters and compares their underlying types for equality. +func ShouldHaveSameTypeAs(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } + + first := reflect.TypeOf(actual) + second := reflect.TypeOf(expected[0]) + + if first != second { + return serializer.serialize(second, first, fmt.Sprintf(shouldHaveBeenA, actual, second, first)) + } + + return success +} + +// ShouldNotHaveSameTypeAs receives exactly two parameters and compares their underlying types for inequality. +func ShouldNotHaveSameTypeAs(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } + + first := reflect.TypeOf(actual) + second := reflect.TypeOf(expected[0]) + + if (actual == nil && expected[0] == nil) || first == second { + return fmt.Sprintf(shouldNotHaveBeenA, actual, second) + } + return success +} + +// ShouldImplement receives exactly two parameters and ensures +// that the first implements the interface type of the second. +func ShouldImplement(actual interface{}, expectedList ...interface{}) string { + if fail := need(1, expectedList); fail != success { + return fail + } + + expected := expectedList[0] + if fail := ShouldBeNil(expected); fail != success { + return shouldCompareWithInterfacePointer + } + + if fail := ShouldNotBeNil(actual); fail != success { + return shouldNotBeNilActual + } + + var actualType reflect.Type + if reflect.TypeOf(actual).Kind() != reflect.Ptr { + actualType = reflect.PtrTo(reflect.TypeOf(actual)) + } else { + actualType = reflect.TypeOf(actual) + } + + expectedType := reflect.TypeOf(expected) + if fail := ShouldNotBeNil(expectedType); fail != success { + return shouldCompareWithInterfacePointer + } + + expectedInterface := expectedType.Elem() + + if !actualType.Implements(expectedInterface) { + return fmt.Sprintf(shouldHaveImplemented, expectedInterface, actualType) + } + return success +} + +// ShouldNotImplement receives exactly two parameters and ensures +// that the first does NOT implement the interface type of the second. +func ShouldNotImplement(actual interface{}, expectedList ...interface{}) string { + if fail := need(1, expectedList); fail != success { + return fail + } + + expected := expectedList[0] + if fail := ShouldBeNil(expected); fail != success { + return shouldCompareWithInterfacePointer + } + + if fail := ShouldNotBeNil(actual); fail != success { + return shouldNotBeNilActual + } + + var actualType reflect.Type + if reflect.TypeOf(actual).Kind() != reflect.Ptr { + actualType = reflect.PtrTo(reflect.TypeOf(actual)) + } else { + actualType = reflect.TypeOf(actual) + } + + expectedType := reflect.TypeOf(expected) + if fail := ShouldNotBeNil(expectedType); fail != success { + return shouldCompareWithInterfacePointer + } + + expectedInterface := expectedType.Elem() + + if actualType.Implements(expectedInterface) { + return fmt.Sprintf(shouldNotHaveImplemented, actualType, expectedInterface) + } + return success +} + +// ShouldBeError asserts that the first argument implements the error interface. +// It also compares the first argument against the second argument if provided +// (which must be an error message string or another error value). +func ShouldBeError(actual interface{}, expected ...interface{}) string { + if fail := atMost(1, expected); fail != success { + return fail + } + + if !isError(actual) { + return fmt.Sprintf(shouldBeError, reflect.TypeOf(actual)) + } + + if len(expected) == 0 { + return success + } + + if expected := expected[0]; !isString(expected) && !isError(expected) { + return fmt.Sprintf(shouldBeErrorInvalidComparisonValue, reflect.TypeOf(expected)) + } + return ShouldEqual(fmt.Sprint(actual), fmt.Sprint(expected[0])) +} + +// ShouldWrap asserts that the first argument (which must be an error value) +// 'wraps' the second/final argument (which must also be an error value). +// It relies on errors.Is to make the determination (https://golang.org/pkg/errors/#Is). +func ShouldWrap(actual interface{}, expected ...interface{}) string { + if fail := need(1, expected); fail != success { + return fail + } + + if !isError(actual) || !isError(expected[0]) { + return fmt.Sprintf(shouldWrapInvalidTypes, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) + } + + if !errors.Is(actual.(error), expected[0].(error)) { + return fmt.Sprintf(`Expected error("%s") to wrap error("%s") but it didn't.`, actual, expected[0]) + } + + return success +} + +func isString(value interface{}) bool { _, ok := value.(string); return ok } +func isError(value interface{}) bool { _, ok := value.(error); return ok } diff --git a/vendor/github.com/smartystreets/goconvey/LICENSE.md b/vendor/github.com/smartystreets/goconvey/LICENSE.md new file mode 100644 index 0000000000000..3f87a40e77306 --- /dev/null +++ b/vendor/github.com/smartystreets/goconvey/LICENSE.md @@ -0,0 +1,23 @@ +Copyright (c) 2016 SmartyStreets, LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +NOTE: Various optional and subordinate components carry their own licensing +requirements and restrictions. Use of those components is subject to the terms +and conditions outlined the respective license of each component. diff --git a/vendor/github.com/smartystreets/goconvey/convey/assertions.go b/vendor/github.com/smartystreets/goconvey/convey/assertions.go new file mode 100644 index 0000000000000..97e3bec82e7d6 --- /dev/null +++ b/vendor/github.com/smartystreets/goconvey/convey/assertions.go @@ -0,0 +1,71 @@ +package convey + +import "github.com/smartystreets/assertions" + +var ( + ShouldEqual = assertions.ShouldEqual + ShouldNotEqual = assertions.ShouldNotEqual + ShouldAlmostEqual = assertions.ShouldAlmostEqual + ShouldNotAlmostEqual = assertions.ShouldNotAlmostEqual + ShouldResemble = assertions.ShouldResemble + ShouldNotResemble = assertions.ShouldNotResemble + ShouldPointTo = assertions.ShouldPointTo + ShouldNotPointTo = assertions.ShouldNotPointTo + ShouldBeNil = assertions.ShouldBeNil + ShouldNotBeNil = assertions.ShouldNotBeNil + ShouldBeTrue = assertions.ShouldBeTrue + ShouldBeFalse = assertions.ShouldBeFalse + ShouldBeZeroValue = assertions.ShouldBeZeroValue + ShouldNotBeZeroValue = assertions.ShouldNotBeZeroValue + + ShouldBeGreaterThan = assertions.ShouldBeGreaterThan + ShouldBeGreaterThanOrEqualTo = assertions.ShouldBeGreaterThanOrEqualTo + ShouldBeLessThan = assertions.ShouldBeLessThan + ShouldBeLessThanOrEqualTo = assertions.ShouldBeLessThanOrEqualTo + ShouldBeBetween = assertions.ShouldBeBetween + ShouldNotBeBetween = assertions.ShouldNotBeBetween + ShouldBeBetweenOrEqual = assertions.ShouldBeBetweenOrEqual + ShouldNotBeBetweenOrEqual = assertions.ShouldNotBeBetweenOrEqual + + ShouldContain = assertions.ShouldContain + ShouldNotContain = assertions.ShouldNotContain + ShouldContainKey = assertions.ShouldContainKey + ShouldNotContainKey = assertions.ShouldNotContainKey + ShouldBeIn = assertions.ShouldBeIn + ShouldNotBeIn = assertions.ShouldNotBeIn + ShouldBeEmpty = assertions.ShouldBeEmpty + ShouldNotBeEmpty = assertions.ShouldNotBeEmpty + ShouldHaveLength = assertions.ShouldHaveLength + + ShouldStartWith = assertions.ShouldStartWith + ShouldNotStartWith = assertions.ShouldNotStartWith + ShouldEndWith = assertions.ShouldEndWith + ShouldNotEndWith = assertions.ShouldNotEndWith + ShouldBeBlank = assertions.ShouldBeBlank + ShouldNotBeBlank = assertions.ShouldNotBeBlank + ShouldContainSubstring = assertions.ShouldContainSubstring + ShouldNotContainSubstring = assertions.ShouldNotContainSubstring + + ShouldPanic = assertions.ShouldPanic + ShouldNotPanic = assertions.ShouldNotPanic + ShouldPanicWith = assertions.ShouldPanicWith + ShouldNotPanicWith = assertions.ShouldNotPanicWith + + ShouldHaveSameTypeAs = assertions.ShouldHaveSameTypeAs + ShouldNotHaveSameTypeAs = assertions.ShouldNotHaveSameTypeAs + ShouldImplement = assertions.ShouldImplement + ShouldNotImplement = assertions.ShouldNotImplement + + ShouldHappenBefore = assertions.ShouldHappenBefore + ShouldHappenOnOrBefore = assertions.ShouldHappenOnOrBefore + ShouldHappenAfter = assertions.ShouldHappenAfter + ShouldHappenOnOrAfter = assertions.ShouldHappenOnOrAfter + ShouldHappenBetween = assertions.ShouldHappenBetween + ShouldHappenOnOrBetween = assertions.ShouldHappenOnOrBetween + ShouldNotHappenOnOrBetween = assertions.ShouldNotHappenOnOrBetween + ShouldHappenWithin = assertions.ShouldHappenWithin + ShouldNotHappenWithin = assertions.ShouldNotHappenWithin + ShouldBeChronological = assertions.ShouldBeChronological + + ShouldBeError = assertions.ShouldBeError +) diff --git a/vendor/github.com/smartystreets/goconvey/convey/context.go b/vendor/github.com/smartystreets/goconvey/convey/context.go new file mode 100644 index 0000000000000..2c75c2d7b1b69 --- /dev/null +++ b/vendor/github.com/smartystreets/goconvey/convey/context.go @@ -0,0 +1,272 @@ +package convey + +import ( + "fmt" + + "github.com/jtolds/gls" + "github.com/smartystreets/goconvey/convey/reporting" +) + +type conveyErr struct { + fmt string + params []interface{} +} + +func (e *conveyErr) Error() string { + return fmt.Sprintf(e.fmt, e.params...) +} + +func conveyPanic(fmt string, params ...interface{}) { + panic(&conveyErr{fmt, params}) +} + +const ( + missingGoTest = `Top-level calls to Convey(...) need a reference to the *testing.T. + Hint: Convey("description here", t, func() { /* notice that the second argument was the *testing.T (t)! */ }) ` + extraGoTest = `Only the top-level call to Convey(...) needs a reference to the *testing.T.` + noStackContext = "Convey operation made without context on goroutine stack.\n" + + "Hint: Perhaps you meant to use `Convey(..., func(c C){...})` ?" + differentConveySituations = "Different set of Convey statements on subsequent pass!\nDid not expect %#v." + multipleIdenticalConvey = "Multiple convey suites with identical names: %#v" +) + +const ( + failureHalt = "___FAILURE_HALT___" + + nodeKey = "node" +) + +///////////////////////////////// Stack Context ///////////////////////////////// + +func getCurrentContext() *context { + ctx, ok := ctxMgr.GetValue(nodeKey) + if ok { + return ctx.(*context) + } + return nil +} + +func mustGetCurrentContext() *context { + ctx := getCurrentContext() + if ctx == nil { + conveyPanic(noStackContext) + } + return ctx +} + +//////////////////////////////////// Context //////////////////////////////////// + +// context magically handles all coordination of Convey's and So assertions. +// +// It is tracked on the stack as goroutine-local-storage with the gls package, +// or explicitly if the user decides to call convey like: +// +// Convey(..., func(c C) { +// c.So(...) +// }) +// +// This implements the `C` interface. +type context struct { + reporter reporting.Reporter + + children map[string]*context + + resets []func() + + executedOnce bool + expectChildRun *bool + complete bool + + focus bool + failureMode FailureMode +} + +// rootConvey is the main entry point to a test suite. This is called when +// there's no context in the stack already, and items must contain a `t` object, +// or this panics. +func rootConvey(items ...interface{}) { + entry := discover(items) + + if entry.Test == nil { + conveyPanic(missingGoTest) + } + + expectChildRun := true + ctx := &context{ + reporter: buildReporter(), + + children: make(map[string]*context), + + expectChildRun: &expectChildRun, + + focus: entry.Focus, + failureMode: defaultFailureMode.combine(entry.FailMode), + } + ctxMgr.SetValues(gls.Values{nodeKey: ctx}, func() { + ctx.reporter.BeginStory(reporting.NewStoryReport(entry.Test)) + defer ctx.reporter.EndStory() + + for ctx.shouldVisit() { + ctx.conveyInner(entry.Situation, entry.Func) + expectChildRun = true + } + }) +} + +//////////////////////////////////// Methods //////////////////////////////////// + +func (ctx *context) SkipConvey(items ...interface{}) { + ctx.Convey(items, skipConvey) +} + +func (ctx *context) FocusConvey(items ...interface{}) { + ctx.Convey(items, focusConvey) +} + +func (ctx *context) Convey(items ...interface{}) { + entry := discover(items) + + // we're a branch, or leaf (on the wind) + if entry.Test != nil { + conveyPanic(extraGoTest) + } + if ctx.focus && !entry.Focus { + return + } + + var inner_ctx *context + if ctx.executedOnce { + var ok bool + inner_ctx, ok = ctx.children[entry.Situation] + if !ok { + conveyPanic(differentConveySituations, entry.Situation) + } + } else { + if _, ok := ctx.children[entry.Situation]; ok { + conveyPanic(multipleIdenticalConvey, entry.Situation) + } + inner_ctx = &context{ + reporter: ctx.reporter, + + children: make(map[string]*context), + + expectChildRun: ctx.expectChildRun, + + focus: entry.Focus, + failureMode: ctx.failureMode.combine(entry.FailMode), + } + ctx.children[entry.Situation] = inner_ctx + } + + if inner_ctx.shouldVisit() { + ctxMgr.SetValues(gls.Values{nodeKey: inner_ctx}, func() { + inner_ctx.conveyInner(entry.Situation, entry.Func) + }) + } +} + +func (ctx *context) SkipSo(stuff ...interface{}) { + ctx.assertionReport(reporting.NewSkipReport()) +} + +func (ctx *context) So(actual interface{}, assert assertion, expected ...interface{}) { + if result := assert(actual, expected...); result == assertionSuccess { + ctx.assertionReport(reporting.NewSuccessReport()) + } else { + ctx.assertionReport(reporting.NewFailureReport(result)) + } +} + +func (ctx *context) Reset(action func()) { + /* TODO: Failure mode configuration */ + ctx.resets = append(ctx.resets, action) +} + +func (ctx *context) Print(items ...interface{}) (int, error) { + fmt.Fprint(ctx.reporter, items...) + return fmt.Print(items...) +} + +func (ctx *context) Println(items ...interface{}) (int, error) { + fmt.Fprintln(ctx.reporter, items...) + return fmt.Println(items...) +} + +func (ctx *context) Printf(format string, items ...interface{}) (int, error) { + fmt.Fprintf(ctx.reporter, format, items...) + return fmt.Printf(format, items...) +} + +//////////////////////////////////// Private //////////////////////////////////// + +// shouldVisit returns true iff we should traverse down into a Convey. Note +// that just because we don't traverse a Convey this time, doesn't mean that +// we may not traverse it on a subsequent pass. +func (c *context) shouldVisit() bool { + return !c.complete && *c.expectChildRun +} + +// conveyInner is the function which actually executes the user's anonymous test +// function body. At this point, Convey or RootConvey has decided that this +// function should actually run. +func (ctx *context) conveyInner(situation string, f func(C)) { + // Record/Reset state for next time. + defer func() { + ctx.executedOnce = true + + // This is only needed at the leaves, but there's no harm in also setting it + // when returning from branch Convey's + *ctx.expectChildRun = false + }() + + // Set up+tear down our scope for the reporter + ctx.reporter.Enter(reporting.NewScopeReport(situation)) + defer ctx.reporter.Exit() + + // Recover from any panics in f, and assign the `complete` status for this + // node of the tree. + defer func() { + ctx.complete = true + if problem := recover(); problem != nil { + if problem, ok := problem.(*conveyErr); ok { + panic(problem) + } + if problem != failureHalt { + ctx.reporter.Report(reporting.NewErrorReport(problem)) + } + } else { + for _, child := range ctx.children { + if !child.complete { + ctx.complete = false + return + } + } + } + }() + + // Resets are registered as the `f` function executes, so nil them here. + // All resets are run in registration order (FIFO). + ctx.resets = []func(){} + defer func() { + for _, r := range ctx.resets { + // panics handled by the previous defer + r() + } + }() + + if f == nil { + // if f is nil, this was either a Convey(..., nil), or a SkipConvey + ctx.reporter.Report(reporting.NewSkipReport()) + } else { + f(ctx) + } +} + +// assertionReport is a helper for So and SkipSo which makes the report and +// then possibly panics, depending on the current context's failureMode. +func (ctx *context) assertionReport(r *reporting.AssertionResult) { + ctx.reporter.Report(r) + if r.Failure != "" && ctx.failureMode == FailureHalts { + panic(failureHalt) + } +} diff --git a/vendor/github.com/smartystreets/goconvey/convey/convey.goconvey b/vendor/github.com/smartystreets/goconvey/convey/convey.goconvey new file mode 100644 index 0000000000000..a2d9327dc9164 --- /dev/null +++ b/vendor/github.com/smartystreets/goconvey/convey/convey.goconvey @@ -0,0 +1,4 @@ +#ignore +-timeout=1s +#-covermode=count +#-coverpkg=github.com/smartystreets/goconvey/convey,github.com/smartystreets/goconvey/convey/gotest,github.com/smartystreets/goconvey/convey/reporting \ No newline at end of file diff --git a/vendor/github.com/smartystreets/goconvey/convey/discovery.go b/vendor/github.com/smartystreets/goconvey/convey/discovery.go new file mode 100644 index 0000000000000..eb8d4cb2ceebe --- /dev/null +++ b/vendor/github.com/smartystreets/goconvey/convey/discovery.go @@ -0,0 +1,103 @@ +package convey + +type actionSpecifier uint8 + +const ( + noSpecifier actionSpecifier = iota + skipConvey + focusConvey +) + +type suite struct { + Situation string + Test t + Focus bool + Func func(C) // nil means skipped + FailMode FailureMode +} + +func newSuite(situation string, failureMode FailureMode, f func(C), test t, specifier actionSpecifier) *suite { + ret := &suite{ + Situation: situation, + Test: test, + Func: f, + FailMode: failureMode, + } + switch specifier { + case skipConvey: + ret.Func = nil + case focusConvey: + ret.Focus = true + } + return ret +} + +func discover(items []interface{}) *suite { + name, items := parseName(items) + test, items := parseGoTest(items) + failure, items := parseFailureMode(items) + action, items := parseAction(items) + specifier, items := parseSpecifier(items) + + if len(items) != 0 { + conveyPanic(parseError) + } + + return newSuite(name, failure, action, test, specifier) +} +func item(items []interface{}) interface{} { + if len(items) == 0 { + conveyPanic(parseError) + } + return items[0] +} +func parseName(items []interface{}) (string, []interface{}) { + if name, parsed := item(items).(string); parsed { + return name, items[1:] + } + conveyPanic(parseError) + panic("never get here") +} +func parseGoTest(items []interface{}) (t, []interface{}) { + if test, parsed := item(items).(t); parsed { + return test, items[1:] + } + return nil, items +} +func parseFailureMode(items []interface{}) (FailureMode, []interface{}) { + if mode, parsed := item(items).(FailureMode); parsed { + return mode, items[1:] + } + return FailureInherits, items +} +func parseAction(items []interface{}) (func(C), []interface{}) { + switch x := item(items).(type) { + case nil: + return nil, items[1:] + case func(C): + return x, items[1:] + case func(): + return func(C) { x() }, items[1:] + } + conveyPanic(parseError) + panic("never get here") +} +func parseSpecifier(items []interface{}) (actionSpecifier, []interface{}) { + if len(items) == 0 { + return noSpecifier, items + } + if spec, ok := items[0].(actionSpecifier); ok { + return spec, items[1:] + } + conveyPanic(parseError) + panic("never get here") +} + +// This interface allows us to pass the *testing.T struct +// throughout the internals of this package without ever +// having to import the "testing" package. +type t interface { + Fail() +} + +const parseError = "You must provide a name (string), then a *testing.T (if in outermost scope), an optional FailureMode, and then an action (func())." diff --git a/vendor/github.com/smartystreets/goconvey/convey/doc.go b/vendor/github.com/smartystreets/goconvey/convey/doc.go new file mode 100644 index 0000000000000..e4f7b51a86576 --- /dev/null +++ b/vendor/github.com/smartystreets/goconvey/convey/doc.go @@ -0,0 +1,218 @@ +// Package convey contains all of the public-facing entry points to this project. +// This means that it should never be required of the user to import any other +// packages from this project as they serve internal purposes. +package convey + +import "github.com/smartystreets/goconvey/convey/reporting" + +////////////////////////////////// suite ////////////////////////////////// + +// C is the Convey context which you can optionally obtain in your action +// by calling Convey like: +// +// Convey(..., func(c C) { +// ... +// }) +// +// See the documentation on Convey for more details. +// +// All methods in this context behave identically to the global functions of the +// same name in this package. +type C interface { + Convey(items ...interface{}) + SkipConvey(items ...interface{}) + FocusConvey(items ...interface{}) + + So(actual interface{}, assert assertion, expected ...interface{}) + SkipSo(stuff ...interface{}) + + Reset(action func()) + + Println(items ...interface{}) (int, error) + Print(items ...interface{}) (int, error) + Printf(format string, items ...interface{}) (int, error) +} + +// Convey is the method intended for use when declaring the scopes of +// a specification. Each scope has a description and a func() which may contain +// other calls to Convey(), Reset() or Should-style assertions. Convey calls can +// be nested as far as you see fit. +// +// IMPORTANT NOTE: The top-level Convey() within a Test method +// must conform to the following signature: +// +// Convey(description string, t *testing.T, action func()) +// +// All other calls should look like this (no need to pass in *testing.T): +// +// Convey(description string, action func()) +// +// Don't worry, goconvey will panic if you get it wrong so you can fix it. +// +// Additionally, you may explicitly obtain access to the Convey context by doing: +// +// Convey(description string, action func(c C)) +// +// You may need to do this if you want to pass the context through to a +// goroutine, or to close over the context in a handler to a library which +// calls your handler in a goroutine (httptest comes to mind). +// +// All Convey()-blocks also accept an optional parameter of FailureMode which sets +// how goconvey should treat failures for So()-assertions in the block and +// nested blocks. See the constants in this file for the available options. +// +// By default it will inherit from its parent block and the top-level blocks +// default to the FailureHalts setting. +// +// This parameter is inserted before the block itself: +// +// Convey(description string, t *testing.T, mode FailureMode, action func()) +// Convey(description string, mode FailureMode, action func()) +// +// See the examples package for, well, examples. +func Convey(items ...interface{}) { + if ctx := getCurrentContext(); ctx == nil { + rootConvey(items...) + } else { + ctx.Convey(items...) + } +} + +// SkipConvey is analogous to Convey except that the scope is not executed +// (which means that child scopes defined within this scope are not run either). +// The reporter will be notified that this step was skipped. +func SkipConvey(items ...interface{}) { + Convey(append(items, skipConvey)...) +} + +// FocusConvey is has the inverse effect of SkipConvey. If the top-level +// Convey is changed to `FocusConvey`, only nested scopes that are defined +// with FocusConvey will be run. The rest will be ignored completely. This +// is handy when debugging a large suite that runs a misbehaving function +// repeatedly as you can disable all but one of that function +// without swaths of `SkipConvey` calls, just a targeted chain of calls +// to FocusConvey. +func FocusConvey(items ...interface{}) { + Convey(append(items, focusConvey)...) +} + +// Reset registers a cleanup function to be run after each Convey() +// in the same scope. See the examples package for a simple use case. +func Reset(action func()) { + mustGetCurrentContext().Reset(action) +} + +/////////////////////////////////// Assertions /////////////////////////////////// + +// assertion is an alias for a function with a signature that the convey.So() +// method can handle. Any future or custom assertions should conform to this +// method signature. The return value should be an empty string if the assertion +// passes and a well-formed failure message if not. +type assertion func(actual interface{}, expected ...interface{}) string + +const assertionSuccess = "" + +// So is the means by which assertions are made against the system under test. +// The majority of exported names in the assertions package begin with the word +// 'Should' and describe how the first argument (actual) should compare with any +// of the final (expected) arguments. How many final arguments are accepted +// depends on the particular assertion that is passed in as the assert argument. +// See the examples package for use cases and the assertions package for +// documentation on specific assertion methods. A failing assertion will +// cause t.Fail() to be invoked--you should never call this method (or other +// failure-inducing methods) in your test code. Leave that to GoConvey. +func So(actual interface{}, assert assertion, expected ...interface{}) { + mustGetCurrentContext().So(actual, assert, expected...) +} + +// SkipSo is analogous to So except that the assertion that would have been passed +// to So is not executed and the reporter is notified that the assertion was skipped. +func SkipSo(stuff ...interface{}) { + mustGetCurrentContext().SkipSo() +} + +// FailureMode is a type which determines how the So() blocks should fail +// if their assertion fails. See constants further down for acceptable values +type FailureMode string + +const ( + + // FailureContinues is a failure mode which prevents failing + // So()-assertions from halting Convey-block execution, instead + // allowing the test to continue past failing So()-assertions. + FailureContinues FailureMode = "continue" + + // FailureHalts is the default setting for a top-level Convey()-block + // and will cause all failing So()-assertions to halt further execution + // in that test-arm and continue on to the next arm. + FailureHalts FailureMode = "halt" + + // FailureInherits is the default setting for failure-mode, it will + // default to the failure-mode of the parent block. You should never + // need to specify this mode in your tests.. + FailureInherits FailureMode = "inherits" +) + +func (f FailureMode) combine(other FailureMode) FailureMode { + if other == FailureInherits { + return f + } + return other +} + +var defaultFailureMode FailureMode = FailureHalts + +// SetDefaultFailureMode allows you to specify the default failure mode +// for all Convey blocks. It is meant to be used in an init function to +// allow the default mode to be changdd across all tests for an entire packgae +// but it can be used anywhere. +func SetDefaultFailureMode(mode FailureMode) { + if mode == FailureContinues || mode == FailureHalts { + defaultFailureMode = mode + } else { + panic("You may only use the constants named 'FailureContinues' and 'FailureHalts' as default failure modes.") + } +} + +//////////////////////////////////// Print functions //////////////////////////////////// + +// Print is analogous to fmt.Print (and it even calls fmt.Print). It ensures that +// output is aligned with the corresponding scopes in the web UI. +func Print(items ...interface{}) (written int, err error) { + return mustGetCurrentContext().Print(items...) +} + +// Print is analogous to fmt.Println (and it even calls fmt.Println). It ensures that +// output is aligned with the corresponding scopes in the web UI. +func Println(items ...interface{}) (written int, err error) { + return mustGetCurrentContext().Println(items...) +} + +// Print is analogous to fmt.Printf (and it even calls fmt.Printf). It ensures that +// output is aligned with the corresponding scopes in the web UI. +func Printf(format string, items ...interface{}) (written int, err error) { + return mustGetCurrentContext().Printf(format, items...) +} + +/////////////////////////////////////////////////////////////////////////////// + +// SuppressConsoleStatistics prevents automatic printing of console statistics. +// Calling PrintConsoleStatistics explicitly will force printing of statistics. +func SuppressConsoleStatistics() { + reporting.SuppressConsoleStatistics() +} + +// PrintConsoleStatistics may be called at any time to print assertion statistics. +// Generally, the best place to do this would be in a TestMain function, +// after all tests have been run. Something like this: +// +// func TestMain(m *testing.M) { +// convey.SuppressConsoleStatistics() +// result := m.Run() +// convey.PrintConsoleStatistics() +// os.Exit(result) +// } +// +func PrintConsoleStatistics() { + reporting.PrintConsoleStatistics() +} diff --git a/vendor/github.com/smartystreets/goconvey/convey/gotest/utils.go b/vendor/github.com/smartystreets/goconvey/convey/gotest/utils.go new file mode 100644 index 0000000000000..167c8fb74a432 --- /dev/null +++ b/vendor/github.com/smartystreets/goconvey/convey/gotest/utils.go @@ -0,0 +1,28 @@ +// Package gotest contains internal functionality. Although this package +// contains one or more exported names it is not intended for public +// consumption. See the examples package for how to use this project. +package gotest + +import ( + "runtime" + "strings" +) + +func ResolveExternalCaller() (file string, line int, name string) { + var caller_id uintptr + callers := runtime.Callers(0, callStack) + + for x := 0; x < callers; x++ { + caller_id, file, line, _ = runtime.Caller(x) + if strings.HasSuffix(file, "_test.go") || strings.HasSuffix(file, "_tests.go") { + name = runtime.FuncForPC(caller_id).Name() + return + } + } + file, line, name = "", -1, "" + return // panic? +} + +const maxStackDepth = 100 // This had better be enough... + +var callStack []uintptr = make([]uintptr, maxStackDepth, maxStackDepth) diff --git a/vendor/github.com/smartystreets/goconvey/convey/init.go b/vendor/github.com/smartystreets/goconvey/convey/init.go new file mode 100644 index 0000000000000..cb930a0db4f0d --- /dev/null +++ b/vendor/github.com/smartystreets/goconvey/convey/init.go @@ -0,0 +1,81 @@ +package convey + +import ( + "flag" + "os" + + "github.com/jtolds/gls" + "github.com/smartystreets/assertions" + "github.com/smartystreets/goconvey/convey/reporting" +) + +func init() { + assertions.GoConveyMode(true) + + declareFlags() + + ctxMgr = gls.NewContextManager() +} + +func declareFlags() { + flag.BoolVar(&json, "convey-json", false, "When true, emits results in JSON blocks. Default: 'false'") + flag.BoolVar(&silent, "convey-silent", false, "When true, all output from GoConvey is suppressed.") + flag.BoolVar(&story, "convey-story", false, "When true, emits story output, otherwise emits dot output. When not provided, this flag mirrors the value of the '-test.v' flag") + + if noStoryFlagProvided() { + story = verboseEnabled + } + + // FYI: flag.Parse() is called from the testing package. +} + +func noStoryFlagProvided() bool { + return !story && !storyDisabled +} + +func buildReporter() reporting.Reporter { + selectReporter := os.Getenv("GOCONVEY_REPORTER") + + switch { + case testReporter != nil: + return testReporter + case json || selectReporter == "json": + return reporting.BuildJsonReporter() + case silent || selectReporter == "silent": + return reporting.BuildSilentReporter() + case selectReporter == "dot": + // Story is turned on when verbose is set, so we need to check for dot reporter first. + return reporting.BuildDotReporter() + case story || selectReporter == "story": + return reporting.BuildStoryReporter() + default: + return reporting.BuildDotReporter() + } +} + +var ( + ctxMgr *gls.ContextManager + + // only set by internal tests + testReporter reporting.Reporter +) + +var ( + json bool + silent bool + story bool + + verboseEnabled = flagFound("-test.v=true") + storyDisabled = flagFound("-story=false") +) + +// flagFound parses the command line args manually for flags defined in other +// packages. Like the '-v' flag from the "testing" package, for instance. +func flagFound(flagValue string) bool { + for _, arg := range os.Args { + if arg == flagValue { + return true + } + } + return false +} diff --git a/vendor/github.com/smartystreets/goconvey/convey/nilReporter.go b/vendor/github.com/smartystreets/goconvey/convey/nilReporter.go new file mode 100644 index 0000000000000..777b2a51228f3 --- /dev/null +++ b/vendor/github.com/smartystreets/goconvey/convey/nilReporter.go @@ -0,0 +1,15 @@ +package convey + +import ( + "github.com/smartystreets/goconvey/convey/reporting" +) + +type nilReporter struct{} + +func (self *nilReporter) BeginStory(story *reporting.StoryReport) {} +func (self *nilReporter) Enter(scope *reporting.ScopeReport) {} +func (self *nilReporter) Report(report *reporting.AssertionResult) {} +func (self *nilReporter) Exit() {} +func (self *nilReporter) EndStory() {} +func (self *nilReporter) Write(p []byte) (int, error) { return len(p), nil } +func newNilReporter() *nilReporter { return &nilReporter{} } diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/console.go b/vendor/github.com/smartystreets/goconvey/convey/reporting/console.go new file mode 100644 index 0000000000000..7bf67dbb2b14c --- /dev/null +++ b/vendor/github.com/smartystreets/goconvey/convey/reporting/console.go @@ -0,0 +1,16 @@ +package reporting + +import ( + "fmt" + "io" +) + +type console struct{} + +func (self *console) Write(p []byte) (n int, err error) { + return fmt.Print(string(p)) +} + +func NewConsole() io.Writer { + return new(console) +} diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/doc.go b/vendor/github.com/smartystreets/goconvey/convey/reporting/doc.go new file mode 100644 index 0000000000000..a37d001946612 --- /dev/null +++ b/vendor/github.com/smartystreets/goconvey/convey/reporting/doc.go @@ -0,0 +1,5 @@ +// Package reporting contains internal functionality related +// to console reporting and output. Although this package has +// exported names is not intended for public consumption. See the +// examples package for how to use this project. +package reporting diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/dot.go b/vendor/github.com/smartystreets/goconvey/convey/reporting/dot.go new file mode 100644 index 0000000000000..47d57c6b0d961 --- /dev/null +++ b/vendor/github.com/smartystreets/goconvey/convey/reporting/dot.go @@ -0,0 +1,40 @@ +package reporting + +import "fmt" + +type dot struct{ out *Printer } + +func (self *dot) BeginStory(story *StoryReport) {} + +func (self *dot) Enter(scope *ScopeReport) {} + +func (self *dot) Report(report *AssertionResult) { + if report.Error != nil { + fmt.Print(redColor) + self.out.Insert(dotError) + } else if report.Failure != "" { + fmt.Print(yellowColor) + self.out.Insert(dotFailure) + } else if report.Skipped { + fmt.Print(yellowColor) + self.out.Insert(dotSkip) + } else { + fmt.Print(greenColor) + self.out.Insert(dotSuccess) + } + fmt.Print(resetColor) +} + +func (self *dot) Exit() {} + +func (self *dot) EndStory() {} + +func (self *dot) Write(content []byte) (written int, err error) { + return len(content), nil // no-op +} + +func NewDotReporter(out *Printer) *dot { + self := new(dot) + self.out = out + return self +} diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/gotest.go b/vendor/github.com/smartystreets/goconvey/convey/reporting/gotest.go new file mode 100644 index 0000000000000..c396e16b17a5a --- /dev/null +++ b/vendor/github.com/smartystreets/goconvey/convey/reporting/gotest.go @@ -0,0 +1,33 @@ +package reporting + +type gotestReporter struct{ test T } + +func (self *gotestReporter) BeginStory(story *StoryReport) { + self.test = story.Test +} + +func (self *gotestReporter) Enter(scope *ScopeReport) {} + +func (self *gotestReporter) Report(r *AssertionResult) { + if !passed(r) { + self.test.Fail() + } +} + +func (self *gotestReporter) Exit() {} + +func (self *gotestReporter) EndStory() { + self.test = nil +} + +func (self *gotestReporter) Write(content []byte) (written int, err error) { + return len(content), nil // no-op +} + +func NewGoTestReporter() *gotestReporter { + return new(gotestReporter) +} + +func passed(r *AssertionResult) bool { + return r.Error == nil && r.Failure == "" +} diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/init.go b/vendor/github.com/smartystreets/goconvey/convey/reporting/init.go new file mode 100644 index 0000000000000..99c3bd6d615ff --- /dev/null +++ b/vendor/github.com/smartystreets/goconvey/convey/reporting/init.go @@ -0,0 +1,94 @@ +package reporting + +import ( + "os" + "runtime" + "strings" +) + +func init() { + if !isColorableTerminal() { + monochrome() + } + + if runtime.GOOS == "windows" { + success, failure, error_ = dotSuccess, dotFailure, dotError + } +} + +func BuildJsonReporter() Reporter { + out := NewPrinter(NewConsole()) + return NewReporters( + NewGoTestReporter(), + NewJsonReporter(out)) +} +func BuildDotReporter() Reporter { + out := NewPrinter(NewConsole()) + return NewReporters( + NewGoTestReporter(), + NewDotReporter(out), + NewProblemReporter(out), + consoleStatistics) +} +func BuildStoryReporter() Reporter { + out := NewPrinter(NewConsole()) + return NewReporters( + NewGoTestReporter(), + NewStoryReporter(out), + NewProblemReporter(out), + consoleStatistics) +} +func BuildSilentReporter() Reporter { + out := NewPrinter(NewConsole()) + return NewReporters( + NewGoTestReporter(), + NewSilentProblemReporter(out)) +} + +var ( + newline = "\n" + success = "✔" + failure = "✘" + error_ = "🔥" + skip = "⚠" + dotSuccess = "." + dotFailure = "x" + dotError = "E" + dotSkip = "S" + errorTemplate = "* %s \nLine %d: - %v \n%s\n" + failureTemplate = "* %s \nLine %d:\n%s\n%s\n" +) + +var ( + greenColor = "\033[32m" + yellowColor = "\033[33m" + redColor = "\033[31m" + resetColor = "\033[0m" +) + +var consoleStatistics = NewStatisticsReporter(NewPrinter(NewConsole())) + +func SuppressConsoleStatistics() { consoleStatistics.Suppress() } +func PrintConsoleStatistics() { consoleStatistics.PrintSummary() } + +// QuietMode disables all console output symbols. This is only meant to be used +// for tests that are internal to goconvey where the output is distracting or +// otherwise not needed in the test output. +func QuietMode() { + success, failure, error_, skip, dotSuccess, dotFailure, dotError, dotSkip = "", "", "", "", "", "", "", "" +} + +func monochrome() { + greenColor, yellowColor, redColor, resetColor = "", "", "", "" +} + +func isColorableTerminal() bool { + return strings.Contains(os.Getenv("TERM"), "color") +} + +// This interface allows us to pass the *testing.T struct +// throughout the internals of this tool without ever +// having to import the "testing" package. +type T interface { + Fail() +} diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/json.go b/vendor/github.com/smartystreets/goconvey/convey/reporting/json.go new file mode 100644 index 0000000000000..f8526979f8551 --- /dev/null +++ b/vendor/github.com/smartystreets/goconvey/convey/reporting/json.go @@ -0,0 +1,88 @@ +// TODO: under unit test + +package reporting + +import ( + "bytes" + "encoding/json" + "fmt" + "strings" +) + +type JsonReporter struct { + out *Printer + currentKey []string + current *ScopeResult + index map[string]*ScopeResult + scopes []*ScopeResult +} + +func (self *JsonReporter) depth() int { return len(self.currentKey) } + +func (self *JsonReporter) BeginStory(story *StoryReport) {} + +func (self *JsonReporter) Enter(scope *ScopeReport) { + self.currentKey = append(self.currentKey, scope.Title) + ID := strings.Join(self.currentKey, "|") + if _, found := self.index[ID]; !found { + next := newScopeResult(scope.Title, self.depth(), scope.File, scope.Line) + self.scopes = append(self.scopes, next) + self.index[ID] = next + } + self.current = self.index[ID] +} + +func (self *JsonReporter) Report(report *AssertionResult) { + self.current.Assertions = append(self.current.Assertions, report) +} + +func (self *JsonReporter) Exit() { + self.currentKey = self.currentKey[:len(self.currentKey)-1] +} + +func (self *JsonReporter) EndStory() { + self.report() + self.reset() +} +func (self *JsonReporter) report() { + scopes := []string{} + for _, scope := range self.scopes { + serialized, err := json.Marshal(scope) + if err != nil { + self.out.Println(jsonMarshalFailure) + panic(err) + } + var buffer bytes.Buffer + json.Indent(&buffer, serialized, "", " ") + scopes = append(scopes, buffer.String()) + } + self.out.Print(fmt.Sprintf("%s\n%s,\n%s\n", OpenJson, strings.Join(scopes, ","), CloseJson)) +} +func (self *JsonReporter) reset() { + self.scopes = []*ScopeResult{} + self.index = map[string]*ScopeResult{} + self.currentKey = nil +} + +func (self *JsonReporter) Write(content []byte) (written int, err error) { + self.current.Output += string(content) + return len(content), nil +} + +func NewJsonReporter(out *Printer) *JsonReporter { + self := new(JsonReporter) + self.out = out + self.reset() + return self +} + +const OpenJson = ">->->OPEN-JSON->->->" // "⌦" +const CloseJson = "<-<-<-CLOSE-JSON<-<-<" // "⌫" +const jsonMarshalFailure = ` + +GOCONVEY_JSON_MARSHALL_FAILURE: There was an error when attempting to convert test results to JSON. +Please file a bug report and reference the code that caused this failure if possible. + +Here's the panic: + +` diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/printer.go b/vendor/github.com/smartystreets/goconvey/convey/reporting/printer.go new file mode 100644 index 0000000000000..3dac0d4d28357 --- /dev/null +++ b/vendor/github.com/smartystreets/goconvey/convey/reporting/printer.go @@ -0,0 +1,60 @@ +package reporting + +import ( + "fmt" + "io" + "strings" +) + +type Printer struct { + out io.Writer + prefix string +} + +func (self *Printer) Println(message string, values ...interface{}) { + formatted := self.format(message, values...) + newline + self.out.Write([]byte(formatted)) +} + +func (self *Printer) Print(message string, values ...interface{}) { + formatted := self.format(message, values...) + self.out.Write([]byte(formatted)) +} + +func (self *Printer) Insert(text string) { + self.out.Write([]byte(text)) +} + +func (self *Printer) format(message string, values ...interface{}) string { + var formatted string + if len(values) == 0 { + formatted = self.prefix + message + } else { + formatted = self.prefix + fmt_Sprintf(message, values...) + } + indented := strings.Replace(formatted, newline, newline+self.prefix, -1) + return strings.TrimRight(indented, space) +} + +// Extracting fmt.Sprintf to a separate variable circumvents go vet, which, as of go 1.10 is run with go test. +var fmt_Sprintf = fmt.Sprintf + +func (self *Printer) Indent() { + self.prefix += pad +} + +func (self *Printer) Dedent() { + if len(self.prefix) >= padLength { + self.prefix = self.prefix[:len(self.prefix)-padLength] + } +} + +func NewPrinter(out io.Writer) *Printer { + self := new(Printer) + self.out = out + return self +} + +const space = " " +const pad = space + space +const padLength = len(pad) diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/problems.go b/vendor/github.com/smartystreets/goconvey/convey/reporting/problems.go new file mode 100644 index 0000000000000..33d5e1476714f --- /dev/null +++ b/vendor/github.com/smartystreets/goconvey/convey/reporting/problems.go @@ -0,0 +1,80 @@ +package reporting + +import "fmt" + +type problem struct { + silent bool + out *Printer + errors []*AssertionResult + failures []*AssertionResult +} + +func (self *problem) BeginStory(story *StoryReport) {} + +func (self *problem) Enter(scope *ScopeReport) {} + +func (self *problem) Report(report *AssertionResult) { + if report.Error != nil { + self.errors = append(self.errors, report) + } else if report.Failure != "" { + self.failures = append(self.failures, report) + } +} + +func (self *problem) Exit() {} + +func (self *problem) EndStory() { + self.show(self.showErrors, redColor) + self.show(self.showFailures, yellowColor) + self.prepareForNextStory() +} +func (self *problem) show(display func(), color string) { + if !self.silent { + fmt.Print(color) + } + display() + if !self.silent { + fmt.Print(resetColor) + } + self.out.Dedent() +} +func (self *problem) showErrors() { + for i, e := range self.errors { + if i == 0 { + self.out.Println("\nErrors:\n") + self.out.Indent() + } + self.out.Println(errorTemplate, e.File, e.Line, e.Error, e.StackTrace) + } +} +func (self *problem) showFailures() { + for i, f := range self.failures { + if i == 0 { + self.out.Println("\nFailures:\n") + self.out.Indent() + } + self.out.Println(failureTemplate, f.File, f.Line, f.Failure, f.StackTrace) + } +} + +func (self *problem) Write(content []byte) (written int, err error) { + return len(content), nil // no-op +} + +func NewProblemReporter(out *Printer) *problem { + self := new(problem) + self.out = out + self.prepareForNextStory() + return self +} + +func NewSilentProblemReporter(out *Printer) *problem { + self := NewProblemReporter(out) + self.silent = true + return self +} + +func (self *problem) prepareForNextStory() { + self.errors = []*AssertionResult{} + self.failures = []*AssertionResult{} +} diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/reporter.go b/vendor/github.com/smartystreets/goconvey/convey/reporting/reporter.go new file mode 100644 index 0000000000000..cce6c5e438850 --- /dev/null +++ b/vendor/github.com/smartystreets/goconvey/convey/reporting/reporter.go @@ -0,0 +1,39 @@ +package reporting + +import "io" + +type Reporter interface { + BeginStory(story *StoryReport) + Enter(scope *ScopeReport) + Report(r *AssertionResult) + Exit() + EndStory() + io.Writer +} + +type reporters struct{ collection []Reporter } + +func (self *reporters) BeginStory(s *StoryReport) { self.foreach(func(r Reporter) { r.BeginStory(s) }) } +func (self *reporters) Enter(s *ScopeReport) { self.foreach(func(r Reporter) { r.Enter(s) }) } +func (self *reporters) Report(a *AssertionResult) { self.foreach(func(r Reporter) { r.Report(a) }) } +func (self *reporters) Exit() { self.foreach(func(r Reporter) { r.Exit() }) } +func (self *reporters) EndStory() { self.foreach(func(r Reporter) { r.EndStory() }) } + +func (self *reporters) Write(contents []byte) (written int, err error) { + self.foreach(func(r Reporter) { + written, err = r.Write(contents) + }) + return written, err +} + +func (self *reporters) foreach(action func(Reporter)) { + for _, r := range self.collection { + action(r) + } +} + +func NewReporters(collection ...Reporter) *reporters { + self := new(reporters) + self.collection = collection + return self +} diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/reporting.goconvey b/vendor/github.com/smartystreets/goconvey/convey/reporting/reporting.goconvey new file mode 100644 index 0000000000000..79982854b533a --- /dev/null +++ b/vendor/github.com/smartystreets/goconvey/convey/reporting/reporting.goconvey @@ -0,0 +1,2 @@ +#ignore +-timeout=1s diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/reports.go b/vendor/github.com/smartystreets/goconvey/convey/reporting/reports.go new file mode 100644 index 0000000000000..712e6ade625d2 --- /dev/null +++ b/vendor/github.com/smartystreets/goconvey/convey/reporting/reports.go @@ -0,0 +1,179 @@ +package reporting + +import ( + "encoding/json" + "fmt" + "runtime" + "strings" + + "github.com/smartystreets/goconvey/convey/gotest" +) + +////////////////// ScopeReport //////////////////// + +type ScopeReport struct { + Title string + File string + Line int +} + +func NewScopeReport(title string) *ScopeReport { + file, line, _ := gotest.ResolveExternalCaller() + self := new(ScopeReport) + self.Title = title + self.File = file + self.Line = line + return self +} + +////////////////// ScopeResult //////////////////// + +type ScopeResult struct { + Title string + File string + Line int + Depth int + Assertions []*AssertionResult + Output string +} + +func newScopeResult(title string, depth int, file string, line int) *ScopeResult { + self := new(ScopeResult) + self.Title = title + self.Depth = depth + self.File = file + self.Line = line + self.Assertions = []*AssertionResult{} + return self +} + +/////////////////// StoryReport ///////////////////// + +type StoryReport struct { + Test T + Name string + File string + Line int +} + +func NewStoryReport(test T) *StoryReport { + file, line, name := gotest.ResolveExternalCaller() + name = removePackagePath(name) + self := new(StoryReport) + self.Test = test + self.Name = name + self.File = file + self.Line = line + return self +} + +// name comes in looking like "github.com/smartystreets/goconvey/examples.TestName". +// We only want the stuff after the last '.', which is the name of the test function. +func removePackagePath(name string) string { + parts := strings.Split(name, ".") + return parts[len(parts)-1] +} + +/////////////////// FailureView //////////////////////// + +// This struct is also declared in github.com/smartystreets/assertions. +// The json struct tags should be equal in both declarations. +type FailureView struct { + Message string `json:"Message"` + Expected string `json:"Expected"` + Actual string `json:"Actual"` +} + +////////////////////AssertionResult ////////////////////// + +type AssertionResult struct { + File string + Line int + Expected string + Actual string + Failure string + Error interface{} + StackTrace string + Skipped bool +} + +func NewFailureReport(failure string) *AssertionResult { + report := new(AssertionResult) + report.File, report.Line = caller() + report.StackTrace = stackTrace() + parseFailure(failure, report) + return report +} +func parseFailure(failure string, report *AssertionResult) { + view := new(FailureView) + err := json.Unmarshal([]byte(failure), view) + if err == nil { + report.Failure = view.Message + report.Expected = view.Expected + report.Actual = view.Actual + } else { + report.Failure = failure + } +} +func NewErrorReport(err interface{}) *AssertionResult { + report := new(AssertionResult) + report.File, report.Line = caller() + report.StackTrace = fullStackTrace() + report.Error = fmt.Sprintf("%v", err) + return report +} +func NewSuccessReport() *AssertionResult { + return new(AssertionResult) +} +func NewSkipReport() *AssertionResult { + report := new(AssertionResult) + report.File, report.Line = caller() + report.StackTrace = fullStackTrace() + report.Skipped = true + return report +} + +func caller() (file string, line int) { + file, line, _ = gotest.ResolveExternalCaller() + return +} + +func stackTrace() string { + buffer := make([]byte, 1024*64) + n := runtime.Stack(buffer, false) + return removeInternalEntries(string(buffer[:n])) +} +func fullStackTrace() string { + buffer := make([]byte, 1024*64) + n := runtime.Stack(buffer, true) + return removeInternalEntries(string(buffer[:n])) +} +func removeInternalEntries(stack string) string { + lines := strings.Split(stack, newline) + filtered := []string{} + for _, line := range lines { + if !isExternal(line) { + filtered = append(filtered, line) + } + } + return strings.Join(filtered, newline) +} +func isExternal(line string) bool { + for _, p := range internalPackages { + if strings.Contains(line, p) { + return true + } + } + return false +} + +// NOTE: any new packages that host goconvey packages will need to be added here! +// An alternative is to scan the goconvey directory and then exclude stuff like +// the examples package but that's nasty too. +var internalPackages = []string{ + "goconvey/assertions", + "goconvey/convey", + "goconvey/execution", + "goconvey/gotest", + "goconvey/reporting", +} diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/statistics.go b/vendor/github.com/smartystreets/goconvey/convey/reporting/statistics.go new file mode 100644 index 0000000000000..c3ccd056a0bb0 --- /dev/null +++ b/vendor/github.com/smartystreets/goconvey/convey/reporting/statistics.go @@ -0,0 +1,108 @@ +package reporting + +import ( + "fmt" + "sync" +) + +func (self *statistics) BeginStory(story *StoryReport) {} + +func (self *statistics) Enter(scope *ScopeReport) {} + +func (self *statistics) Report(report *AssertionResult) { + self.Lock() + defer self.Unlock() + + if !self.failing && report.Failure != "" { + self.failing = true + } + if !self.erroring && report.Error != nil { + self.erroring = true + } + if report.Skipped { + self.skipped += 1 + } else { + self.total++ + } +} + +func (self *statistics) Exit() {} + +func (self *statistics) EndStory() { + self.Lock() + defer self.Unlock() + + if !self.suppressed { + self.printSummaryLocked() + } +} + +func (self *statistics) Suppress() { + self.Lock() + defer self.Unlock() + self.suppressed = true +} + +func (self *statistics) PrintSummary() { + self.Lock() + defer self.Unlock() + self.printSummaryLocked() +} + +func (self *statistics) printSummaryLocked() { + self.reportAssertionsLocked() + self.reportSkippedSectionsLocked() + self.completeReportLocked() +} +func (self *statistics) reportAssertionsLocked() { + self.decideColorLocked() + self.out.Print("\n%d total %s", self.total, plural("assertion", self.total)) +} +func (self *statistics) decideColorLocked() { + if self.failing && !self.erroring { + fmt.Print(yellowColor) + } else if self.erroring { + fmt.Print(redColor) + } else { + fmt.Print(greenColor) + } +} +func (self *statistics) reportSkippedSectionsLocked() { + if self.skipped > 0 { + fmt.Print(yellowColor) + self.out.Print(" (one or more sections skipped)") + } +} +func (self *statistics) completeReportLocked() { + fmt.Print(resetColor) + self.out.Print("\n") + self.out.Print("\n") +} + +func (self *statistics) Write(content []byte) (written int, err error) { + return len(content), nil // no-op +} + +func NewStatisticsReporter(out *Printer) *statistics { + self := statistics{} + self.out = out + return &self +} + +type statistics struct { + sync.Mutex + + out *Printer + total int + failing bool + erroring bool + skipped int + suppressed bool +} + +func plural(word string, count int) string { + if count == 1 { + return word + } + return word + "s" +} diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/story.go b/vendor/github.com/smartystreets/goconvey/convey/reporting/story.go new file mode 100644 index 0000000000000..9e73c971f8fb8 --- /dev/null +++ b/vendor/github.com/smartystreets/goconvey/convey/reporting/story.go @@ -0,0 +1,73 @@ +// TODO: in order for this reporter to be completely honest +// we need to retrofit to be more like the json reporter such that: +// 1. it maintains ScopeResult collections, which count assertions +// 2. it reports only after EndStory(), so that all tick marks +// are placed near the appropriate title. +// 3. Under unit test + +package reporting + +import ( + "fmt" + "strings" +) + +type story struct { + out *Printer + titlesById map[string]string + currentKey []string +} + +func (self *story) BeginStory(story *StoryReport) {} + +func (self *story) Enter(scope *ScopeReport) { + self.out.Indent() + + self.currentKey = append(self.currentKey, scope.Title) + ID := strings.Join(self.currentKey, "|") + + if _, found := self.titlesById[ID]; !found { + self.out.Println("") + self.out.Print(scope.Title) + self.out.Insert(" ") + self.titlesById[ID] = scope.Title + } +} + +func (self *story) Report(report *AssertionResult) { + if report.Error != nil { + fmt.Print(redColor) + self.out.Insert(error_) + } else if report.Failure != "" { + fmt.Print(yellowColor) + self.out.Insert(failure) + } else if report.Skipped { + fmt.Print(yellowColor) + self.out.Insert(skip) + } else { + fmt.Print(greenColor) + self.out.Insert(success) + } + fmt.Print(resetColor) +} + +func (self *story) Exit() { + self.out.Dedent() + self.currentKey = self.currentKey[:len(self.currentKey)-1] +} + +func (self *story) EndStory() { + self.titlesById = make(map[string]string) + self.out.Println("\n") +} + +func (self *story) Write(content []byte) (written int, err error) { + return len(content), nil // no-op +} + +func NewStoryReporter(out *Printer) *story { + self := new(story) + self.out = out + self.titlesById = make(map[string]string) + return self +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 3aa47f6835925..571e0353801a8 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -434,6 +434,8 @@ github.com/google/go-querystring/query # github.com/google/uuid v1.1.2 ## explicit github.com/google/uuid +# github.com/gopherjs/gopherjs v0.0.0-20190910122728-9d188e94fb99 +github.com/gopherjs/gopherjs/js # github.com/gorilla/context v1.1.1 ## explicit github.com/gorilla/context @@ -488,6 +490,8 @@ github.com/jessevdk/go-flags github.com/josharian/intern # github.com/json-iterator/go v1.1.10 github.com/json-iterator/go +# github.com/jtolds/gls v4.20.0+incompatible +github.com/jtolds/gls # github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 ## explicit github.com/kballard/go-shellquote @@ -699,6 +703,16 @@ github.com/shurcooL/sanitized_anchor_name github.com/shurcooL/vfsgen # github.com/siddontang/go-snappy v0.0.0-20140704025258-d8f7bb82a96d github.com/siddontang/go-snappy/snappy +# github.com/smartystreets/assertions v1.1.1 +github.com/smartystreets/assertions +github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch +github.com/smartystreets/assertions/internal/go-render/render +github.com/smartystreets/assertions/internal/oglematchers +# github.com/smartystreets/goconvey v1.6.4 +## explicit +github.com/smartystreets/goconvey/convey +github.com/smartystreets/goconvey/convey/gotest +github.com/smartystreets/goconvey/convey/reporting # github.com/spf13/afero v1.3.2 github.com/spf13/afero github.com/spf13/afero/mem From 29901cddccd2099cee3ee82547a58e564dbd9332 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sun, 20 Dec 2020 08:49:48 +0800 Subject: [PATCH 18/23] Use gitea.com/go-chi/session --- go.mod | 2 - go.sum | 2 - modules/context/default.go | 85 ++++---------------------------------- routers/install.go | 25 +++++++---- vendor/modules.txt | 7 ---- 5 files changed, 25 insertions(+), 96 deletions(-) diff --git a/go.mod b/go.mod index 0588a10390722..a21699b42c191 100644 --- a/go.mod +++ b/go.mod @@ -94,9 +94,7 @@ require ( github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/stretchr/testify v1.6.1 github.com/syndtr/goleveldb v1.0.0 - github.com/thedevsaddam/renderer v1.2.0 github.com/tinylib/msgp v1.1.5 // indirect - github.com/tecbot/gorocksdb v0.0.0-20181010114359-8752a9433481 // indirect github.com/tstranex/u2f v1.0.0 github.com/ulikunitz/xz v0.5.8 // indirect github.com/unknwon/com v1.0.1 diff --git a/go.sum b/go.sum index 6fc2967656dfd..011546c75d004 100644 --- a/go.sum +++ b/go.sum @@ -1072,8 +1072,6 @@ github.com/syndtr/goleveldb v1.0.0/go.mod h1:ZVVdQEZoIme9iO1Ch2Jdy24qqXrMMOU6lpP github.com/tebeka/snowball v0.4.2/go.mod h1:4IfL14h1lvwZcp1sfXuuc7/7yCsvVffTWxWxCLfFpYg= github.com/tecbot/gorocksdb v0.0.0-20191217155057-f0fad39f321c h1:g+WoO5jjkqGAzHWCjJB1zZfXPIAaDpzXIEJ0eS6B5Ok= github.com/tecbot/gorocksdb v0.0.0-20191217155057-f0fad39f321c/go.mod h1:ahpPrc7HpcfEWDQRZEmnXMzHY03mLDYMCxeDzy46i+8= -github.com/thedevsaddam/renderer v1.2.0 h1:+N0J8t/s2uU2RxX2sZqq5NbaQhjwBjfovMU28ifX2F4= -github.com/thedevsaddam/renderer v1.2.0/go.mod h1:k/TdZXGcpCpHE/KNj//P2COcmYEfL8OV+IXDX0dvG+U= github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4= github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= github.com/tinylib/msgp v1.1.0/go.mod h1:+d+yLhGm8mzTaHzB+wgMYrodPfmZrzkirds8fDWklFE= diff --git a/modules/context/default.go b/modules/context/default.go index 5eb0747f1546f..17342d714d4b4 100644 --- a/modules/context/default.go +++ b/modules/context/default.go @@ -6,17 +6,13 @@ package context import ( "net/http" - "time" "code.gitea.io/gitea/modules/auth" "code.gitea.io/gitea/modules/middlewares/binding" - "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/translation" - "github.com/alexedwards/scs/v2" - "github.com/unknwon/i18n" + "gitea.com/go-chi/session" "github.com/unrolled/render" - "golang.org/x/text/language" ) // flashes enumerates all the flash types @@ -33,11 +29,11 @@ type Flash map[string]string // DefaultContext represents a context for basic routes, all other context should // be derived from the context but not add more fields on this context type DefaultContext struct { - Resp http.ResponseWriter - Req *http.Request - Data map[string]interface{} - Render *render.Render - Sessions *scs.SessionManager + Resp http.ResponseWriter + Req *http.Request + Data map[string]interface{} + Render *render.Render + Session session.Store translation.Locale flash Flash } @@ -78,19 +74,19 @@ func (ctx *DefaultContext) RenderWithErr(msg string, tpl string, form interface{ // SetSession sets session key value func (ctx *DefaultContext) SetSession(key string, val interface{}) error { - ctx.Sessions.Put(ctx.Req.Context(), key, val) + ctx.Session.Set(key, val) return nil } // GetSession gets session via key func (ctx *DefaultContext) GetSession(key string) (interface{}, error) { - v := ctx.Sessions.Get(ctx.Req.Context(), key) + v := ctx.Session.Get(key) return v, nil } // DestroySession deletes all the data of the session func (ctx *DefaultContext) DestroySession() error { - return ctx.Sessions.Destroy(ctx.Req.Context()) + return ctx.Session.Release() } // Flash set message to flash @@ -102,66 +98,3 @@ func (ctx *DefaultContext) Flash(tp, v string) { ctx.Data[tp] = v ctx.Data["Flash"] = ctx.flash } - -// NewSessions creates a session manager -func NewSessions() *scs.SessionManager { - sessionManager := scs.New() - sessionManager.Lifetime = time.Duration(setting.SessionConfig.Maxlifetime) - sessionManager.Cookie = scs.SessionCookie{ - Name: setting.SessionConfig.CookieName, - Domain: setting.SessionConfig.Domain, - HttpOnly: true, - Path: setting.SessionConfig.CookiePath, - Persist: true, - Secure: setting.SessionConfig.Secure, - } - return sessionManager -} - -// Locale handle locale -func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale { - hasCookie := false - - // 1. Check URL arguments. - lang := req.URL.Query().Get("lang") - - // 2. Get language information from cookies. - if len(lang) == 0 { - ck, _ := req.Cookie("lang") - lang = ck.Value - hasCookie = true - } - - // Check again in case someone modify by purpose. - if !i18n.IsExist(lang) { - lang = "" - hasCookie = false - } - - // 3. Get language information from 'Accept-Language'. - // The first element in the list is chosen to be the default language automatically. - if len(lang) == 0 { - tags, _, _ := language.ParseAcceptLanguage(req.Header.Get("Accept-Language")) - tag, _, _ := translation.Match(tags...) - lang = tag.String() - } - - if !hasCookie { - req.AddCookie(NewCookie("lang", lang, 1<<31-1)) - } - - return translation.NewLocale(lang) -} - -// NewCookie creates a cookie -func NewCookie(name, value string, maxAge int) *http.Cookie { - return &http.Cookie{ - Name: name, - Value: value, - HttpOnly: true, - Path: setting.SessionConfig.CookiePath, - Domain: setting.SessionConfig.Domain, - MaxAge: maxAge, - Secure: setting.SessionConfig.Secure, - } -} diff --git a/routers/install.go b/routers/install.go index 9b5831a9601e8..a981ef460d776 100644 --- a/routers/install.go +++ b/routers/install.go @@ -20,10 +20,12 @@ import ( "code.gitea.io/gitea/modules/generate" "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/middlewares" "code.gitea.io/gitea/modules/setting" gitea_templates "code.gitea.io/gitea/modules/templates" "code.gitea.io/gitea/modules/user" "code.gitea.io/gitea/modules/util" + "gitea.com/go-chi/session" "github.com/alexedwards/scs/v2" "github.com/go-chi/chi" @@ -41,11 +43,16 @@ const ( // InstallRoutes represents the install routes func InstallRoutes() http.Handler { r := chi.NewRouter() - sessionManager := context.NewSessions() - r.Use(sessionManager.LoadAndSave) - r.Use(func(next http.Handler) http.Handler { - return InstallInit(next, sessionManager) - }) + r.Use(session.Sessioner(session.Options{ + Provider: setting.SessionConfig.Provider, + ProviderConfig: setting.SessionConfig.ProviderConfig, + CookieName: setting.SessionConfig.CookieName, + CookiePath: setting.SessionConfig.CookiePath, + Gclifetime: setting.SessionConfig.Gclifetime, + Maxlifetime: setting.SessionConfig.Maxlifetime, + Secure: setting.SessionConfig.Secure, + Domain: setting.SessionConfig.Domain, + })) r.Get("/", WrapInstall(Install)) r.Post("/", WrapInstall(InstallPost)) r.NotFound(func(w http.ResponseWriter, req *http.Request) { @@ -69,7 +76,7 @@ func InstallInit(next http.Handler, sessionManager *scs.SessionManager) http.Han return } - var locale = context.Locale(resp, req) + var locale = middlewares.Locale(resp, req) var startTime = time.Now() var ctx = context.InstallContext{ Resp: resp, @@ -87,8 +94,8 @@ func InstallInit(next http.Handler, sessionManager *scs.SessionManager) http.Han return time.Since(startTime).String() }, }, - Render: rnd, - Sessions: sessionManager, + Render: rnd, + Session: session.GetSession(req), } req = context.WithInstallContext(req, &ctx) @@ -453,7 +460,7 @@ func InstallPost(ctx *context.InstallContext) { } days := 86400 * setting.LogInRememberDays - ctx.Req.AddCookie(context.NewCookie(setting.CookieUserName, u.Name, days)) + ctx.Req.AddCookie(middlewares.NewCookie(setting.CookieUserName, u.Name, days)) //ctx.SetSuperSecureCookie(base.EncodeMD5(u.Rands+u.Passwd), // setting.CookieRememberName, u.Name, days, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true) diff --git a/vendor/modules.txt b/vendor/modules.txt index 571e0353801a8..5b4922ebc3ceb 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -750,17 +750,10 @@ github.com/syndtr/goleveldb/leveldb/opt github.com/syndtr/goleveldb/leveldb/storage github.com/syndtr/goleveldb/leveldb/table github.com/syndtr/goleveldb/leveldb/util -<<<<<<< HEAD -# github.com/thedevsaddam/renderer v1.2.0 -## explicit -github.com/thedevsaddam/renderer -# github.com/tinylib/msgp v1.1.5 -======= # github.com/tinylib/msgp v1.1.5 # github.com/tecbot/gorocksdb v0.0.0-20181010114359-8752a9433481 ## explicit # github.com/tinylib/msgp v1.1.2 ->>>>>>> 2af2659f2... Use github.com/unrolled/render as render ## explicit github.com/tinylib/msgp/msgp # github.com/toqueteos/webbrowser v1.2.0 From f6453689b451063a5c4fa75fa98c3674ce954856 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sun, 20 Dec 2020 11:12:15 +0800 Subject: [PATCH 19/23] Use gitea.com/go-chi/binding --- cmd/web.go | 2 +- go.mod | 3 +- go.sum | 4 +- modules/context/default.go | 17 +- modules/context/install.go | 27 - modules/forms/forms.go | 2 +- modules/forms/install.go | 5 +- modules/middlewares/binding/bind_test.go | 57 - modules/middlewares/binding/common_test.go | 127 -- .../middlewares/binding/errorhandler_test.go | 162 -- modules/middlewares/binding/errors_test.go | 115 -- modules/middlewares/binding/file_test.go | 191 --- modules/middlewares/binding/form_test.go | 282 ---- modules/middlewares/binding/json_test.go | 240 --- modules/middlewares/binding/misc_test.go | 123 -- modules/middlewares/binding/multipart_test.go | 155 -- modules/middlewares/binding/validate_test.go | 412 ----- routers/routes/chi.go | 34 +- routers/{ => routes}/install.go | 39 +- vendor/gitea.com/go-chi/binding/.drone.yml | 24 + vendor/gitea.com/go-chi/binding/.gitignore | 1 + vendor/gitea.com/go-chi/binding/LICENSE | 191 +++ .../gitea.com/go-chi}/binding/README.md | 0 .../gitea.com/go-chi}/binding/binding.go | 0 .../gitea.com/go-chi}/binding/errors.go | 0 vendor/gitea.com/go-chi/binding/go.mod | 10 + vendor/gitea.com/go-chi/binding/go.sum | 32 + .../github.com/alexedwards/scs/v2/.travis.yml | 9 - vendor/github.com/alexedwards/scs/v2/LICENSE | 21 - .../github.com/alexedwards/scs/v2/README.md | 213 --- vendor/github.com/alexedwards/scs/v2/codec.go | 51 - vendor/github.com/alexedwards/scs/v2/data.go | 498 ------ vendor/github.com/alexedwards/scs/v2/go.mod | 3 - vendor/github.com/alexedwards/scs/v2/go.sum | 0 .../alexedwards/scs/v2/memstore/README.md | 74 - .../alexedwards/scs/v2/memstore/memstore.go | 124 -- .../github.com/alexedwards/scs/v2/session.go | 236 --- vendor/github.com/alexedwards/scs/v2/store.go | 25 - vendor/github.com/gopherjs/gopherjs/LICENSE | 24 - vendor/github.com/gopherjs/gopherjs/js/js.go | 168 -- vendor/github.com/jtolds/gls/LICENSE | 18 - vendor/github.com/jtolds/gls/README.md | 89 -- vendor/github.com/jtolds/gls/context.go | 153 -- vendor/github.com/jtolds/gls/gen_sym.go | 21 - vendor/github.com/jtolds/gls/gid.go | 25 - vendor/github.com/jtolds/gls/id_pool.go | 34 - vendor/github.com/jtolds/gls/stack_tags.go | 147 -- vendor/github.com/jtolds/gls/stack_tags_js.go | 75 - .../github.com/jtolds/gls/stack_tags_main.go | 30 - .../smartystreets/assertions/.gitignore | 4 - .../smartystreets/assertions/.travis.yml | 23 - .../smartystreets/assertions/CONTRIBUTING.md | 12 - .../smartystreets/assertions/LICENSE.md | 23 - .../smartystreets/assertions/Makefile | 14 - .../smartystreets/assertions/README.md | 4 - .../smartystreets/assertions/collections.go | 244 --- .../smartystreets/assertions/doc.go | 109 -- .../smartystreets/assertions/equal_method.go | 75 - .../smartystreets/assertions/equality.go | 331 ---- .../smartystreets/assertions/equality_diff.go | 37 - .../smartystreets/assertions/filter.go | 31 - .../smartystreets/assertions/go.mod | 3 - .../assertions/internal/go-diff/AUTHORS | 25 - .../assertions/internal/go-diff/CONTRIBUTORS | 32 - .../assertions/internal/go-diff/LICENSE | 20 - .../internal/go-diff/diffmatchpatch/diff.go | 1345 ----------------- .../go-diff/diffmatchpatch/diffmatchpatch.go | 46 - .../internal/go-diff/diffmatchpatch/match.go | 160 -- .../go-diff/diffmatchpatch/mathutil.go | 23 - .../diffmatchpatch/operation_string.go | 17 - .../internal/go-diff/diffmatchpatch/patch.go | 556 ------- .../go-diff/diffmatchpatch/stringutil.go | 88 -- .../assertions/internal/go-render/LICENSE | 27 - .../internal/go-render/render/render.go | 481 ------ .../internal/go-render/render/render_time.go | 26 - .../internal/oglematchers/.gitignore | 5 - .../internal/oglematchers/.travis.yml | 4 - .../assertions/internal/oglematchers/LICENSE | 202 --- .../internal/oglematchers/README.md | 58 - .../internal/oglematchers/any_of.go | 94 -- .../internal/oglematchers/contains.go | 61 - .../internal/oglematchers/deep_equals.go | 88 -- .../internal/oglematchers/equals.go | 541 ------- .../internal/oglematchers/greater_or_equal.go | 39 - .../internal/oglematchers/greater_than.go | 39 - .../internal/oglematchers/less_or_equal.go | 41 - .../internal/oglematchers/less_than.go | 152 -- .../internal/oglematchers/matcher.go | 86 -- .../assertions/internal/oglematchers/not.go | 53 - .../oglematchers/transform_description.go | 36 - .../smartystreets/assertions/messages.go | 108 -- .../smartystreets/assertions/panic.go | 128 -- .../smartystreets/assertions/quantity.go | 141 -- .../smartystreets/assertions/serializer.go | 70 - .../smartystreets/assertions/strings.go | 227 --- .../smartystreets/assertions/time.go | 218 --- .../smartystreets/assertions/type.go | 154 -- .../smartystreets/goconvey/LICENSE.md | 23 - .../goconvey/convey/assertions.go | 71 - .../smartystreets/goconvey/convey/context.go | 272 ---- .../goconvey/convey/convey.goconvey | 4 - .../goconvey/convey/discovery.go | 103 -- .../smartystreets/goconvey/convey/doc.go | 218 --- .../goconvey/convey/gotest/utils.go | 28 - .../smartystreets/goconvey/convey/init.go | 81 - .../goconvey/convey/nilReporter.go | 15 - .../goconvey/convey/reporting/console.go | 16 - .../goconvey/convey/reporting/doc.go | 5 - .../goconvey/convey/reporting/dot.go | 40 - .../goconvey/convey/reporting/gotest.go | 33 - .../goconvey/convey/reporting/init.go | 94 -- .../goconvey/convey/reporting/json.go | 88 -- .../goconvey/convey/reporting/printer.go | 60 - .../goconvey/convey/reporting/problems.go | 80 - .../goconvey/convey/reporting/reporter.go | 39 - .../convey/reporting/reporting.goconvey | 2 - .../goconvey/convey/reporting/reports.go | 179 --- .../goconvey/convey/reporting/statistics.go | 108 -- .../goconvey/convey/reporting/story.go | 73 - vendor/modules.txt | 21 +- 120 files changed, 326 insertions(+), 11921 deletions(-) delete mode 100644 modules/context/install.go delete mode 100644 modules/middlewares/binding/bind_test.go delete mode 100755 modules/middlewares/binding/common_test.go delete mode 100755 modules/middlewares/binding/errorhandler_test.go delete mode 100755 modules/middlewares/binding/errors_test.go delete mode 100755 modules/middlewares/binding/file_test.go delete mode 100755 modules/middlewares/binding/form_test.go delete mode 100755 modules/middlewares/binding/json_test.go delete mode 100755 modules/middlewares/binding/misc_test.go delete mode 100755 modules/middlewares/binding/multipart_test.go delete mode 100755 modules/middlewares/binding/validate_test.go rename routers/{ => routes}/install.go (93%) create mode 100644 vendor/gitea.com/go-chi/binding/.drone.yml create mode 100644 vendor/gitea.com/go-chi/binding/.gitignore create mode 100644 vendor/gitea.com/go-chi/binding/LICENSE rename {modules/middlewares => vendor/gitea.com/go-chi}/binding/README.md (100%) rename {modules/middlewares => vendor/gitea.com/go-chi}/binding/binding.go (100%) rename {modules/middlewares => vendor/gitea.com/go-chi}/binding/errors.go (100%) create mode 100644 vendor/gitea.com/go-chi/binding/go.mod create mode 100644 vendor/gitea.com/go-chi/binding/go.sum delete mode 100644 vendor/github.com/alexedwards/scs/v2/.travis.yml delete mode 100644 vendor/github.com/alexedwards/scs/v2/LICENSE delete mode 100644 vendor/github.com/alexedwards/scs/v2/README.md delete mode 100644 vendor/github.com/alexedwards/scs/v2/codec.go delete mode 100644 vendor/github.com/alexedwards/scs/v2/data.go delete mode 100644 vendor/github.com/alexedwards/scs/v2/go.mod delete mode 100644 vendor/github.com/alexedwards/scs/v2/go.sum delete mode 100644 vendor/github.com/alexedwards/scs/v2/memstore/README.md delete mode 100644 vendor/github.com/alexedwards/scs/v2/memstore/memstore.go delete mode 100644 vendor/github.com/alexedwards/scs/v2/session.go delete mode 100644 vendor/github.com/alexedwards/scs/v2/store.go delete mode 100644 vendor/github.com/gopherjs/gopherjs/LICENSE delete mode 100644 vendor/github.com/gopherjs/gopherjs/js/js.go delete mode 100644 vendor/github.com/jtolds/gls/LICENSE delete mode 100644 vendor/github.com/jtolds/gls/README.md delete mode 100644 vendor/github.com/jtolds/gls/context.go delete mode 100644 vendor/github.com/jtolds/gls/gen_sym.go delete mode 100644 vendor/github.com/jtolds/gls/gid.go delete mode 100644 vendor/github.com/jtolds/gls/id_pool.go delete mode 100644 vendor/github.com/jtolds/gls/stack_tags.go delete mode 100644 vendor/github.com/jtolds/gls/stack_tags_js.go delete mode 100644 vendor/github.com/jtolds/gls/stack_tags_main.go delete mode 100644 vendor/github.com/smartystreets/assertions/.gitignore delete mode 100644 vendor/github.com/smartystreets/assertions/.travis.yml delete mode 100644 vendor/github.com/smartystreets/assertions/CONTRIBUTING.md delete mode 100644 vendor/github.com/smartystreets/assertions/LICENSE.md delete mode 100644 vendor/github.com/smartystreets/assertions/Makefile delete mode 100644 vendor/github.com/smartystreets/assertions/README.md delete mode 100644 vendor/github.com/smartystreets/assertions/collections.go delete mode 100644 vendor/github.com/smartystreets/assertions/doc.go delete mode 100644 vendor/github.com/smartystreets/assertions/equal_method.go delete mode 100644 vendor/github.com/smartystreets/assertions/equality.go delete mode 100644 vendor/github.com/smartystreets/assertions/equality_diff.go delete mode 100644 vendor/github.com/smartystreets/assertions/filter.go delete mode 100644 vendor/github.com/smartystreets/assertions/go.mod delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/AUTHORS delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/CONTRIBUTORS delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/LICENSE delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/diff.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/diffmatchpatch.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/match.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/mathutil.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/operation_string.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/patch.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/stringutil.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-render/LICENSE delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-render/render/render.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/go-render/render/render_time.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/.gitignore delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/.travis.yml delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/LICENSE delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/README.md delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/any_of.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/contains.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/deep_equals.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/equals.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/greater_or_equal.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/greater_than.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/less_or_equal.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/less_than.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/matcher.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/not.go delete mode 100644 vendor/github.com/smartystreets/assertions/internal/oglematchers/transform_description.go delete mode 100644 vendor/github.com/smartystreets/assertions/messages.go delete mode 100644 vendor/github.com/smartystreets/assertions/panic.go delete mode 100644 vendor/github.com/smartystreets/assertions/quantity.go delete mode 100644 vendor/github.com/smartystreets/assertions/serializer.go delete mode 100644 vendor/github.com/smartystreets/assertions/strings.go delete mode 100644 vendor/github.com/smartystreets/assertions/time.go delete mode 100644 vendor/github.com/smartystreets/assertions/type.go delete mode 100644 vendor/github.com/smartystreets/goconvey/LICENSE.md delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/assertions.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/context.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/convey.goconvey delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/discovery.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/doc.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/gotest/utils.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/init.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/nilReporter.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/console.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/doc.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/dot.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/gotest.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/init.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/json.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/printer.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/problems.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/reporter.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/reporting.goconvey delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/reports.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/statistics.go delete mode 100644 vendor/github.com/smartystreets/goconvey/convey/reporting/story.go diff --git a/cmd/web.go b/cmd/web.go index f6c3c825c60c0..c057b51847a60 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -134,7 +134,7 @@ func runWeb(ctx *cli.Context) error { } } c := routes.NewChi() - c.Mount("/", routers.InstallRoutes()) + c.Mount("/", routes.InstallRoutes()) err := listen(c, false) select { case <-graceful.GetManager().IsShutdown(): diff --git a/go.mod b/go.mod index a21699b42c191..2a71dbc92abe7 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.14 require ( code.gitea.io/gitea-vet v0.2.1 code.gitea.io/sdk/gitea v0.13.1 + gitea.com/go-chi/binding v0.0.0-20201220025549-f1056649c959 gitea.com/go-chi/session v0.0.0-20201218134809-7209fa084f27 gitea.com/lunny/levelqueue v0.3.0 gitea.com/macaron/binding v0.0.0-20190822013154-a5f53841ed2b @@ -21,7 +22,6 @@ require ( github.com/PuerkitoBio/goquery v1.5.1 github.com/RoaringBitmap/roaring v0.5.5 // indirect github.com/alecthomas/chroma v0.8.2 - github.com/alexedwards/scs/v2 v2.4.0 github.com/andybalholm/brotli v1.0.1 // indirect github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be // indirect github.com/blevesearch/bleve v1.0.14 @@ -89,7 +89,6 @@ require ( github.com/sergi/go-diff v1.1.0 github.com/shurcooL/httpfs v0.0.0-20190707220628-8d4bc4ba7749 // indirect github.com/shurcooL/vfsgen v0.0.0-20200824052919-0d455de96546 - github.com/smartystreets/goconvey v1.6.4 github.com/spf13/viper v1.7.1 // indirect github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/stretchr/testify v1.6.1 diff --git a/go.sum b/go.sum index 011546c75d004..b8d4218aa7526 100644 --- a/go.sum +++ b/go.sum @@ -40,6 +40,8 @@ code.gitea.io/gitea-vet v0.2.1/go.mod h1:zcNbT/aJEmivCAhfmkHOlT645KNOf9W2KnkLgFj code.gitea.io/sdk/gitea v0.13.1 h1:Y7bpH2iO6Q0KhhMJfjP/LZ0AmiYITeRQlCD8b0oYqhk= code.gitea.io/sdk/gitea v0.13.1/go.mod h1:z3uwDV/b9Ls47NGukYM9XhnHtqPh/J+t40lsUrR6JDY= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= +gitea.com/go-chi/binding v0.0.0-20201220025549-f1056649c959 h1:xcFbqqw8JUPTivvrwgDl5X1Chiby0gzASqbY5LmcOZ0= +gitea.com/go-chi/binding v0.0.0-20201220025549-f1056649c959/go.mod h1:2F9XqNn+FUSSG6yXlEF/KRQk9Rf99eEqJkGBcrp6APM= gitea.com/go-chi/session v0.0.0-20201218134809-7209fa084f27 h1:cdb1OTNXGLwQ55gg+9tIPWufdsnrHWcIq8Qs+j/E8JU= gitea.com/go-chi/session v0.0.0-20201218134809-7209fa084f27/go.mod h1:Ozg8IchVNb/Udg+ui39iHRYqVHSvf3C99ixdpLR8Vu0= gitea.com/lunny/levelqueue v0.3.0 h1:MHn1GuSZkxvVEDMyAPqlc7A3cOW+q8RcGhRgH/xtm6I= @@ -128,8 +130,6 @@ github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuy github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= -github.com/alexedwards/scs/v2 v2.4.0 h1:XfnMamKnvp1muJVNr1WzikQTclopsBXWZtzz0NBjOK0= -github.com/alexedwards/scs/v2 v2.4.0/go.mod h1:ToaROZxyKukJKT/xLcVQAChi5k6+Pn1Gvmdl7h3RRj8= github.com/andybalholm/brotli v1.0.0/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y= github.com/andybalholm/brotli v1.0.1 h1:KqhlKozYbRtJvsPrrEeXcO+N2l6NYT5A2QAFmSULpEc= github.com/andybalholm/brotli v1.0.1/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y= diff --git a/modules/context/default.go b/modules/context/default.go index 17342d714d4b4..4b35e70c3c452 100644 --- a/modules/context/default.go +++ b/modules/context/default.go @@ -5,12 +5,13 @@ package context import ( + "context" "net/http" "code.gitea.io/gitea/modules/auth" - "code.gitea.io/gitea/modules/middlewares/binding" "code.gitea.io/gitea/modules/translation" + "gitea.com/go-chi/binding" "gitea.com/go-chi/session" "github.com/unrolled/render" ) @@ -98,3 +99,17 @@ func (ctx *DefaultContext) Flash(tp, v string) { ctx.Data[tp] = v ctx.Data["Flash"] = ctx.flash } + +var ( + defaultContextKey interface{} = "default_context" +) + +// WithDefaultContext set up install context in request +func WithDefaultContext(req *http.Request, ctx *DefaultContext) *http.Request { + return req.WithContext(context.WithValue(req.Context(), defaultContextKey, ctx)) +} + +// GetDefaultContext retrieves install context from request +func GetDefaultContext(req *http.Request) *DefaultContext { + return req.Context().Value(defaultContextKey).(*DefaultContext) +} diff --git a/modules/context/install.go b/modules/context/install.go deleted file mode 100644 index f7aa073d8ccbc..0000000000000 --- a/modules/context/install.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2020 The Gitea Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. - -package context - -import ( - "context" - "net/http" -) - -// InstallContext represents a context for installation routes -type InstallContext = DefaultContext - -var ( - installContextKey interface{} = "install_context" -) - -// WithInstallContext set up install context in request -func WithInstallContext(req *http.Request, ctx *InstallContext) *http.Request { - return req.WithContext(context.WithValue(req.Context(), installContextKey, ctx)) -} - -// GetInstallContext retrieves install context from request -func GetInstallContext(req *http.Request) *InstallContext { - return req.Context().Value(installContextKey).(*InstallContext) -} diff --git a/modules/forms/forms.go b/modules/forms/forms.go index 4dccfeda08701..cd12a78c8e07a 100644 --- a/modules/forms/forms.go +++ b/modules/forms/forms.go @@ -8,10 +8,10 @@ import ( "reflect" "strings" - "code.gitea.io/gitea/modules/middlewares/binding" "code.gitea.io/gitea/modules/translation" "code.gitea.io/gitea/modules/validation" + "gitea.com/go-chi/binding" "github.com/unknwon/com" ) diff --git a/modules/forms/install.go b/modules/forms/install.go index af84de2ef9d10..477734841f1b8 100644 --- a/modules/forms/install.go +++ b/modules/forms/install.go @@ -9,7 +9,8 @@ import ( "net/http" "code.gitea.io/gitea/modules/context" - "code.gitea.io/gitea/modules/middlewares/binding" + + "gitea.com/go-chi/binding" ) // InstallForm form for installation page @@ -63,6 +64,6 @@ type InstallForm struct { // Validate validates the fields func (f *InstallForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { - ctx := context.GetInstallContext(req) + ctx := context.GetDefaultContext(req) return validate(errs, ctx.Data, f, ctx.Locale) } diff --git a/modules/middlewares/binding/bind_test.go b/modules/middlewares/binding/bind_test.go deleted file mode 100644 index 318ea7d7f96cd..0000000000000 --- a/modules/middlewares/binding/bind_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2014 Martini Authors -// Copyright 2014 The Macaron Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package binding - -import ( - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func Test_Bind(t *testing.T) { - Convey("Bind test", t, func() { - Convey("Bind form", func() { - for _, testCase := range formTestCases { - performFormTest(t, Bind, testCase) - } - }) - - Convey("Bind JSON", func() { - for _, testCase := range jsonTestCases { - performJsonTest(t, Bind, testCase) - } - }) - - Convey("Bind multipart form", func() { - for _, testCase := range multipartFormTestCases { - performMultipartFormTest(t, Bind, testCase) - } - }) - - Convey("Bind with file", func() { - for _, testCase := range fileTestCases { - performFileTest(t, Bind, testCase) - performFileTest(t, BindIgnErr, testCase) - } - }) - }) -} - -func Test_Version(t *testing.T) { - Convey("Get package version", t, func() { - So(Version(), ShouldEqual, _VERSION) - }) -} diff --git a/modules/middlewares/binding/common_test.go b/modules/middlewares/binding/common_test.go deleted file mode 100755 index bff229758ddaf..0000000000000 --- a/modules/middlewares/binding/common_test.go +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright 2014 Martini Authors -// Copyright 2014 The Macaron Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package binding - -import ( - "mime/multipart" - - "gitea.com/macaron/macaron" -) - -// These types are mostly contrived examples, but they're used -// across many test cases. The idea is to cover all the scenarios -// that this binding package might encounter in actual use. -type ( - // For basic test cases with a required field - Post struct { - Title string `form:"title" json:"title" binding:"Required"` - Content string `form:"content" json:"content"` - } - - // To be used as a nested struct (with a required field) - Person struct { - Name string `form:"name" json:"name" binding:"Required"` - Email string `form:"email" json:"email"` - } - - // For advanced test cases: multiple values, embedded - // and nested structs, an ignored field, and single - // and multiple file uploads - BlogPost struct { - Post - Id int `binding:"Required"` // JSON not specified here for test coverage - Ignored string `form:"-" json:"-"` - Ratings []int `form:"rating" json:"ratings"` - Author Person `json:"author"` - Coauthor *Person `json:"coauthor"` - HeaderImage *multipart.FileHeader - Pictures []*multipart.FileHeader `form:"picture"` - unexported string `form:"unexported"` - } - - EmbedPerson struct { - *Person - } - - SadForm struct { - AlphaDash string `form:"AlphaDash" binding:"AlphaDash"` - AlphaDashDot string `form:"AlphaDashDot" binding:"AlphaDashDot"` - Size string `form:"Size" binding:"Size(1)"` - SizeSlice []string `form:"SizeSlice" binding:"Size(1)"` - MinSize string `form:"MinSize" binding:"MinSize(5)"` - MinSizeSlice []string `form:"MinSizeSlice" binding:"MinSize(5)"` - MaxSize string `form:"MaxSize" binding:"MaxSize(1)"` - MaxSizeSlice []string `form:"MaxSizeSlice" binding:"MaxSize(1)"` - Range int `form:"Range" binding:"Range(1,2)"` - RangeInvalid int `form:"RangeInvalid" binding:"Range(1)"` - Email string `binding:"Email"` - Url string `form:"Url" binding:"Url"` - UrlEmpty string `form:"UrlEmpty" binding:"Url"` - In string `form:"In" binding:"Default(0);In(1,2,3)"` - InInvalid string `form:"InInvalid" binding:"In(1,2,3)"` - NotIn string `form:"NotIn" binding:"NotIn(1,2,3)"` - Include string `form:"Include" binding:"Include(a)"` - Exclude string `form:"Exclude" binding:"Exclude(a)"` - Empty string `binding:"OmitEmpty"` - } - - Group struct { - Name string `json:"name" binding:"Required"` - People []Person `json:"people" binding:"MinSize(1)"` - } - - CustomErrorHandle struct { - Rule `binding:"CustomRule"` - } - - // The common function signature of the handlers going under test. - handlerFunc func(interface{}, ...interface{}) macaron.Handler - - // Used for testing mapping an interface to the context - // If used (withInterface = true in the testCases), a modeler - // should be mapped to the context as well as BlogPost, meaning - // you can receive a modeler in your application instead of a - // concrete BlogPost. - modeler interface { - Model() string - } -) - -func (p Post) Validate(ctx *macaron.Context, errs Errors) Errors { - if len(p.Title) < 10 { - errs = append(errs, Error{ - FieldNames: []string{"title"}, - Classification: "LengthError", - Message: "Life is too short", - }) - } - return errs -} - -func (p Post) Model() string { - return p.Title -} - -func (g Group) Model() string { - return g.Name -} - -func (_ CustomErrorHandle) Error(_ *macaron.Context, _ Errors) {} - -const ( - testRoute = "/test" - formContentType = "application/x-www-form-urlencoded" -) diff --git a/modules/middlewares/binding/errorhandler_test.go b/modules/middlewares/binding/errorhandler_test.go deleted file mode 100755 index b74a812eac38f..0000000000000 --- a/modules/middlewares/binding/errorhandler_test.go +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright 2014 Martini Authors -// Copyright 2014 The Macaron Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package binding - -import ( - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -var errorTestCases = []errorTestCase{ - { - description: "No errors", - errors: Errors{}, - expected: errorTestResult{ - statusCode: http.StatusOK, - }, - }, - { - description: "Deserialization error", - errors: Errors{ - { - Classification: ERR_DESERIALIZATION, - Message: "Some parser error here", - }, - }, - expected: errorTestResult{ - statusCode: http.StatusBadRequest, - contentType: _JSON_CONTENT_TYPE, - body: `[{"classification":"DeserializationError","message":"Some parser error here"}]`, - }, - }, - { - description: "Content-Type error", - errors: Errors{ - { - Classification: ERR_CONTENT_TYPE, - Message: "Empty Content-Type", - }, - }, - expected: errorTestResult{ - statusCode: http.StatusUnsupportedMediaType, - contentType: _JSON_CONTENT_TYPE, - body: `[{"classification":"ContentTypeError","message":"Empty Content-Type"}]`, - }, - }, - { - description: "Requirement error", - errors: Errors{ - { - FieldNames: []string{"some_field"}, - Classification: ERR_REQUIRED, - Message: "Required", - }, - }, - expected: errorTestResult{ - statusCode: STATUS_UNPROCESSABLE_ENTITY, - contentType: _JSON_CONTENT_TYPE, - body: `[{"fieldNames":["some_field"],"classification":"RequiredError","message":"Required"}]`, - }, - }, - { - description: "Bad header error", - errors: Errors{ - { - Classification: "HeaderError", - Message: "The X-Something header must be specified", - }, - }, - expected: errorTestResult{ - statusCode: STATUS_UNPROCESSABLE_ENTITY, - contentType: _JSON_CONTENT_TYPE, - body: `[{"classification":"HeaderError","message":"The X-Something header must be specified"}]`, - }, - }, - { - description: "Custom field error", - errors: Errors{ - { - FieldNames: []string{"month", "year"}, - Classification: "DateError", - Message: "The month and year must be in the future", - }, - }, - expected: errorTestResult{ - statusCode: STATUS_UNPROCESSABLE_ENTITY, - contentType: _JSON_CONTENT_TYPE, - body: `[{"fieldNames":["month","year"],"classification":"DateError","message":"The month and year must be in the future"}]`, - }, - }, - { - description: "Multiple errors", - errors: Errors{ - { - FieldNames: []string{"foo"}, - Classification: ERR_REQUIRED, - Message: "Required", - }, - { - FieldNames: []string{"foo"}, - Classification: "LengthError", - Message: "The length of the 'foo' field is too short", - }, - }, - expected: errorTestResult{ - statusCode: STATUS_UNPROCESSABLE_ENTITY, - contentType: _JSON_CONTENT_TYPE, - body: `[{"fieldNames":["foo"],"classification":"RequiredError","message":"Required"},{"fieldNames":["foo"],"classification":"LengthError","message":"The length of the 'foo' field is too short"}]`, - }, - }, -} - -func Test_ErrorHandler(t *testing.T) { - Convey("Error handler", t, func() { - for _, testCase := range errorTestCases { - performErrorTest(t, testCase) - } - }) -} - -func performErrorTest(t *testing.T, testCase errorTestCase) { - resp := httptest.NewRecorder() - - errorHandler(testCase.errors, resp) - - So(resp.Code, ShouldEqual, testCase.expected.statusCode) - So(resp.Header().Get("Content-Type"), ShouldEqual, testCase.expected.contentType) - - actualBody, err := ioutil.ReadAll(resp.Body) - So(err, ShouldBeNil) - So(string(actualBody), ShouldEqual, testCase.expected.body) -} - -type ( - errorTestCase struct { - description string - errors Errors - expected errorTestResult - } - - errorTestResult struct { - statusCode int - contentType string - body string - } -) diff --git a/modules/middlewares/binding/errors_test.go b/modules/middlewares/binding/errors_test.go deleted file mode 100755 index 0e9659c374847..0000000000000 --- a/modules/middlewares/binding/errors_test.go +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright 2014 Martini Authors -// Copyright 2014 The Macaron Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package binding - -import ( - "fmt" - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func Test_ErrorsAdd(t *testing.T) { - Convey("Add new error", t, func() { - var actual Errors - expected := Errors{ - Error{ - FieldNames: []string{"Field1", "Field2"}, - Classification: "ErrorClass", - Message: "Some message", - }, - } - - actual.Add(expected[0].FieldNames, expected[0].Classification, expected[0].Message) - - So(len(actual), ShouldEqual, 1) - So(fmt.Sprintf("%#v", actual), ShouldEqual, fmt.Sprintf("%#v", expected)) - }) -} - -func Test_ErrorsLen(t *testing.T) { - Convey("Get number of errors", t, func() { - So(errorsTestSet.Len(), ShouldEqual, len(errorsTestSet)) - }) -} - -func Test_ErrorsHas(t *testing.T) { - Convey("Check error class", t, func() { - So(errorsTestSet.Has("ClassA"), ShouldBeTrue) - So(errorsTestSet.Has("ClassQ"), ShouldBeFalse) - }) -} - -func Test_ErrorGetters(t *testing.T) { - Convey("Get error detail", t, func() { - err := Error{ - FieldNames: []string{"field1", "field2"}, - Classification: "ErrorClass", - Message: "The message", - } - - fieldsActual := err.Fields() - - So(len(fieldsActual), ShouldEqual, 2) - So(fieldsActual[0], ShouldEqual, "field1") - So(fieldsActual[1], ShouldEqual, "field2") - - So(err.Kind(), ShouldEqual, "ErrorClass") - So(err.Error(), ShouldEqual, "The message") - }) -} - -/* -func TestErrorsWithClass(t *testing.T) { - expected := Errors{ - errorsTestSet[0], - errorsTestSet[3], - } - actualStr := fmt.Sprintf("%#v", errorsTestSet.WithClass("ClassA")) - expectedStr := fmt.Sprintf("%#v", expected) - if actualStr != expectedStr { - t.Errorf("Expected:\n%s\nbut got:\n%s", expectedStr, actualStr) - } -} -*/ - -var errorsTestSet = Errors{ - Error{ - FieldNames: []string{}, - Classification: "ClassA", - Message: "Foobar", - }, - Error{ - FieldNames: []string{}, - Classification: "ClassB", - Message: "Foo", - }, - Error{ - FieldNames: []string{"field1", "field2"}, - Classification: "ClassB", - Message: "Foobar", - }, - Error{ - FieldNames: []string{"field2"}, - Classification: "ClassA", - Message: "Foobar", - }, - Error{ - FieldNames: []string{"field2"}, - Classification: "ClassB", - Message: "Foobar", - }, -} diff --git a/modules/middlewares/binding/file_test.go b/modules/middlewares/binding/file_test.go deleted file mode 100755 index be2fc547215cf..0000000000000 --- a/modules/middlewares/binding/file_test.go +++ /dev/null @@ -1,191 +0,0 @@ -// Copyright 2014 Martini Authors -// Copyright 2014 The Macaron Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package binding - -import ( - "bytes" - "mime/multipart" - "net/http" - "net/http/httptest" - "testing" - - . "github.com/smartystreets/goconvey/convey" - "gitea.com/macaron/macaron" -) - -var fileTestCases = []fileTestCase{ - { - description: "Single file", - singleFile: &fileInfo{ - fileName: "message.txt", - data: "All your binding are belong to us", - }, - }, - { - description: "Multiple files", - multipleFiles: []*fileInfo{ - &fileInfo{ - fileName: "cool-gopher-fact.txt", - data: "Did you know? https://plus.google.com/+MatthewHolt/posts/GmVfd6TPJ51", - }, - &fileInfo{ - fileName: "gophercon2014.txt", - data: "@bradfitz has a Go time machine: https://twitter.com/mholt6/status/459463953395875840", - }, - }, - }, - { - description: "Single file and multiple files", - singleFile: &fileInfo{ - fileName: "social media.txt", - data: "Hey, you should follow @mholt6 (Twitter) or +MatthewHolt (Google+)", - }, - multipleFiles: []*fileInfo{ - &fileInfo{ - fileName: "thank you!", - data: "Also, thanks to all the contributors of this package!", - }, - &fileInfo{ - fileName: "btw...", - data: "This tool translates JSON into Go structs: http://mholt.github.io/json-to-go/", - }, - }, - }, -} - -func Test_FileUploads(t *testing.T) { - Convey("Test file upload", t, func() { - for _, testCase := range fileTestCases { - performFileTest(t, MultipartForm, testCase) - } - }) -} - -func performFileTest(t *testing.T, binder handlerFunc, testCase fileTestCase) { - httpRecorder := httptest.NewRecorder() - m := macaron.Classic() - - fileTestHandler := func(actual BlogPost, errs Errors) { - assertFileAsExpected(t, testCase, actual.HeaderImage, testCase.singleFile) - So(len(testCase.multipleFiles), ShouldEqual, len(actual.Pictures)) - - for i, expectedFile := range testCase.multipleFiles { - if i >= len(actual.Pictures) { - break - } - assertFileAsExpected(t, testCase, actual.Pictures[i], expectedFile) - } - } - - m.Post(testRoute, binder(BlogPost{}), func(actual BlogPost, errs Errors) { - fileTestHandler(actual, errs) - }) - - m.ServeHTTP(httpRecorder, buildRequestWithFile(testCase)) - - switch httpRecorder.Code { - case http.StatusNotFound: - panic("Routing is messed up in test fixture (got 404): check methods and paths") - case http.StatusInternalServerError: - panic("Something bad happened on '" + testCase.description + "'") - } -} - -func assertFileAsExpected(t *testing.T, testCase fileTestCase, actual *multipart.FileHeader, expected *fileInfo) { - if expected == nil && actual == nil { - return - } - - if expected != nil && actual == nil { - So(actual, ShouldNotBeNil) - return - } else if expected == nil && actual != nil { - So(actual, ShouldBeNil) - return - } - - So(actual.Filename, ShouldEqual, expected.fileName) - So(unpackFileHeaderData(actual), ShouldEqual, expected.data) -} - -func buildRequestWithFile(testCase fileTestCase) *http.Request { - b := &bytes.Buffer{} - w := multipart.NewWriter(b) - - if testCase.singleFile != nil { - formFileSingle, err := w.CreateFormFile("header_image", testCase.singleFile.fileName) - if err != nil { - panic("Could not create FormFile (single file): " + err.Error()) - } - formFileSingle.Write([]byte(testCase.singleFile.data)) - } - - for _, file := range testCase.multipleFiles { - formFileMultiple, err := w.CreateFormFile("picture", file.fileName) - if err != nil { - panic("Could not create FormFile (multiple files): " + err.Error()) - } - formFileMultiple.Write([]byte(file.data)) - } - - err := w.Close() - if err != nil { - panic("Could not close multipart writer: " + err.Error()) - } - - req, err := http.NewRequest("POST", testRoute, b) - if err != nil { - panic("Could not create file upload request: " + err.Error()) - } - - req.Header.Set("Content-Type", w.FormDataContentType()) - - return req -} - -func unpackFileHeaderData(fh *multipart.FileHeader) string { - if fh == nil { - return "" - } - - f, err := fh.Open() - if err != nil { - panic("Could not open file header:" + err.Error()) - } - defer f.Close() - - var fb bytes.Buffer - _, err = fb.ReadFrom(f) - if err != nil { - panic("Could not read from file header:" + err.Error()) - } - - return fb.String() -} - -type ( - fileTestCase struct { - description string - input BlogPost - singleFile *fileInfo - multipleFiles []*fileInfo - } - - fileInfo struct { - fileName string - data string - } -) diff --git a/modules/middlewares/binding/form_test.go b/modules/middlewares/binding/form_test.go deleted file mode 100755 index bd92e27d5606e..0000000000000 --- a/modules/middlewares/binding/form_test.go +++ /dev/null @@ -1,282 +0,0 @@ -// Copyright 2014 Martini Authors -// Copyright 2014 The Macaron Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package binding - -import ( - "fmt" - "net/http" - "net/http/httptest" - "reflect" - "strings" - "testing" - - . "github.com/smartystreets/goconvey/convey" - "gitea.com/macaron/macaron" -) - -var formTestCases = []formTestCase{ - { - description: "Happy path", - shouldSucceed: true, - payload: `title=Glorious+Post+Title&content=Lorem+ipsum+dolor+sit+amet`, - contentType: formContentType, - expected: Post{Title: "Glorious Post Title", Content: "Lorem ipsum dolor sit amet"}, - }, - { - description: "Happy path with interface", - shouldSucceed: true, - withInterface: true, - payload: `title=Glorious+Post+Title&content=Lorem+ipsum+dolor+sit+amet`, - contentType: formContentType, - expected: Post{Title: "Glorious Post Title", Content: "Lorem ipsum dolor sit amet"}, - }, - { - description: "Empty payload", - shouldSucceed: false, - payload: ``, - contentType: formContentType, - expected: Post{}, - }, - { - description: "Empty content type", - shouldSucceed: false, - payload: `title=Glorious+Post+Title&content=Lorem+ipsum+dolor+sit+amet`, - contentType: ``, - expected: Post{}, - }, - { - description: "Malformed form body", - shouldSucceed: false, - payload: `title=%2`, - contentType: formContentType, - expected: Post{}, - }, - { - description: "With nested and embedded structs", - shouldSucceed: true, - payload: `title=Glorious+Post+Title&id=1&name=Matt+Holt`, - contentType: formContentType, - expected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1, Author: Person{Name: "Matt Holt"}}, - }, - { - description: "Required embedded struct field not specified", - shouldSucceed: false, - payload: `id=1&name=Matt+Holt`, - contentType: formContentType, - expected: BlogPost{Id: 1, Author: Person{Name: "Matt Holt"}}, - }, - { - description: "Required nested struct field not specified", - shouldSucceed: false, - payload: `title=Glorious+Post+Title&id=1`, - contentType: formContentType, - expected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1}, - }, - { - description: "Multiple values into slice", - shouldSucceed: true, - payload: `title=Glorious+Post+Title&id=1&name=Matt+Holt&rating=4&rating=3&rating=5`, - contentType: formContentType, - expected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1, Author: Person{Name: "Matt Holt"}, Ratings: []int{4, 3, 5}}, - }, - { - description: "Unexported field", - shouldSucceed: true, - payload: `title=Glorious+Post+Title&id=1&name=Matt+Holt&unexported=foo`, - contentType: formContentType, - expected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1, Author: Person{Name: "Matt Holt"}}, - }, - { - description: "Query string POST", - shouldSucceed: true, - payload: `title=Glorious+Post+Title&content=Lorem+ipsum+dolor+sit+amet`, - contentType: formContentType, - expected: Post{Title: "Glorious Post Title", Content: "Lorem ipsum dolor sit amet"}, - }, - { - description: "Query string with Content-Type (POST request)", - shouldSucceed: true, - queryString: "?title=Glorious+Post+Title&content=Lorem+ipsum+dolor+sit+amet", - payload: ``, - contentType: formContentType, - expected: Post{Title: "Glorious Post Title", Content: "Lorem ipsum dolor sit amet"}, - }, - { - description: "Query string without Content-Type (GET request)", - shouldSucceed: true, - method: "GET", - queryString: "?title=Glorious+Post+Title&content=Lorem+ipsum+dolor+sit+amet", - payload: ``, - expected: Post{Title: "Glorious Post Title", Content: "Lorem ipsum dolor sit amet"}, - }, - { - description: "Embed struct pointer", - shouldSucceed: true, - deepEqual: true, - method: "GET", - queryString: "?name=Glorious+Post+Title&email=Lorem+ipsum+dolor+sit+amet", - payload: ``, - expected: EmbedPerson{&Person{Name: "Glorious Post Title", Email: "Lorem ipsum dolor sit amet"}}, - }, - { - description: "Embed struct pointer remain nil if not binded", - shouldSucceed: true, - deepEqual: true, - method: "GET", - queryString: "?", - payload: ``, - expected: EmbedPerson{nil}, - }, - { - description: "Custom error handler", - shouldSucceed: true, - deepEqual: true, - method: "GET", - queryString: "?", - payload: ``, - expected: CustomErrorHandle{}, - }, -} - -func init() { - AddRule(&Rule{ - func(rule string) bool { - return rule == "CustomRule" - }, - func(errs Errors, _ string, _ interface{}) (bool, Errors) { - return false, errs - }, - }) - SetNameMapper(nameMapper) -} - -func Test_Form(t *testing.T) { - Convey("Test form", t, func() { - for _, testCase := range formTestCases { - performFormTest(t, Form, testCase) - } - }) -} - -func performFormTest(t *testing.T, binder handlerFunc, testCase formTestCase) { - resp := httptest.NewRecorder() - m := macaron.Classic() - - formTestHandler := func(actual interface{}, errs Errors) { - if testCase.shouldSucceed && len(errs) > 0 { - So(len(errs), ShouldEqual, 0) - } else if !testCase.shouldSucceed && len(errs) == 0 { - So(len(errs), ShouldNotEqual, 0) - } - expString := fmt.Sprintf("%+v", testCase.expected) - actString := fmt.Sprintf("%+v", actual) - if actString != expString && !(testCase.deepEqual && reflect.DeepEqual(testCase.expected, actual)) { - So(actString, ShouldEqual, expString) - } - } - - switch testCase.expected.(type) { - case Post: - if testCase.withInterface { - m.Post(testRoute, binder(Post{}, (*modeler)(nil)), func(actual Post, iface modeler, errs Errors) { - So(actual.Title, ShouldEqual, iface.Model()) - formTestHandler(actual, errs) - }) - } else { - m.Post(testRoute, binder(Post{}), func(actual Post, errs Errors) { - formTestHandler(actual, errs) - }) - m.Get(testRoute, binder(Post{}), func(actual Post, errs Errors) { - formTestHandler(actual, errs) - }) - } - - case BlogPost: - if testCase.withInterface { - m.Post(testRoute, binder(BlogPost{}, (*modeler)(nil)), func(actual BlogPost, iface modeler, errs Errors) { - So(actual.Title, ShouldEqual, iface.Model()) - formTestHandler(actual, errs) - }) - } else { - m.Post(testRoute, binder(BlogPost{}), func(actual BlogPost, errs Errors) { - formTestHandler(actual, errs) - }) - } - - case EmbedPerson: - m.Post(testRoute, binder(EmbedPerson{}), func(actual EmbedPerson, errs Errors) { - formTestHandler(actual, errs) - }) - m.Get(testRoute, binder(EmbedPerson{}), func(actual EmbedPerson, errs Errors) { - formTestHandler(actual, errs) - }) - case CustomErrorHandle: - m.Get(testRoute, binder(CustomErrorHandle{}), func(actual CustomErrorHandle, errs Errors) { - formTestHandler(actual, errs) - }) - } - - if len(testCase.method) == 0 { - testCase.method = "POST" - } - - req, err := http.NewRequest(testCase.method, testRoute+testCase.queryString, strings.NewReader(testCase.payload)) - if err != nil { - panic(err) - } - req.Header.Set("Content-Type", testCase.contentType) - - m.ServeHTTP(resp, req) - - switch resp.Code { - case http.StatusNotFound: - panic("Routing is messed up in test fixture (got 404): check methods and paths") - case http.StatusInternalServerError: - panic("Something bad happened on '" + testCase.description + "'") - } -} - -type ( - formTestCase struct { - description string - shouldSucceed bool - deepEqual bool - withInterface bool - queryString string - payload string - contentType string - expected interface{} - method string - } -) - -type defaultForm struct { - Default string `binding:"Default(hello world)"` -} - -func Test_Default(t *testing.T) { - Convey("Test default value", t, func() { - m := macaron.Classic() - m.Get("/", Bind(defaultForm{}), func(f defaultForm) { - So(f.Default, ShouldEqual, "hello world") - }) - resp := httptest.NewRecorder() - req, err := http.NewRequest("GET", "/", nil) - So(err, ShouldBeNil) - - m.ServeHTTP(resp, req) - }) -} diff --git a/modules/middlewares/binding/json_test.go b/modules/middlewares/binding/json_test.go deleted file mode 100755 index 3603e85b8adc5..0000000000000 --- a/modules/middlewares/binding/json_test.go +++ /dev/null @@ -1,240 +0,0 @@ -// Copyright 2014 Martini Authors -// Copyright 2014 The Macaron Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package binding - -import ( - "fmt" - "io" - "net/http" - "net/http/httptest" - "strings" - "testing" - - . "github.com/smartystreets/goconvey/convey" - "gitea.com/macaron/macaron" -) - -var jsonTestCases = []jsonTestCase{ - { - description: "Happy path", - shouldSucceedOnJson: true, - payload: `{"title": "Glorious Post Title", "content": "Lorem ipsum dolor sit amet"}`, - contentType: _JSON_CONTENT_TYPE, - expected: Post{Title: "Glorious Post Title", Content: "Lorem ipsum dolor sit amet"}, - }, - { - description: "Happy path with interface", - shouldSucceedOnJson: true, - withInterface: true, - payload: `{"title": "Glorious Post Title", "content": "Lorem ipsum dolor sit amet"}`, - contentType: _JSON_CONTENT_TYPE, - expected: Post{Title: "Glorious Post Title", Content: "Lorem ipsum dolor sit amet"}, - }, - { - description: "Nil payload", - shouldSucceedOnJson: false, - payload: `-nil-`, - contentType: _JSON_CONTENT_TYPE, - expected: Post{}, - }, - { - description: "Empty payload", - shouldSucceedOnJson: false, - payload: ``, - contentType: _JSON_CONTENT_TYPE, - expected: Post{}, - }, - { - description: "Empty content type", - shouldSucceedOnJson: true, - shouldFailOnBind: true, - payload: `{"title": "Glorious Post Title", "content": "Lorem ipsum dolor sit amet"}`, - contentType: ``, - expected: Post{Title: "Glorious Post Title", Content: "Lorem ipsum dolor sit amet"}, - }, - { - description: "Unsupported content type", - shouldSucceedOnJson: true, - shouldFailOnBind: true, - payload: `{"title": "Glorious Post Title", "content": "Lorem ipsum dolor sit amet"}`, - contentType: `BoGuS`, - expected: Post{Title: "Glorious Post Title", Content: "Lorem ipsum dolor sit amet"}, - }, - { - description: "Malformed JSON", - shouldSucceedOnJson: false, - payload: `{"title":"foo"`, - contentType: _JSON_CONTENT_TYPE, - expected: Post{}, - }, - { - description: "Deserialization with nested and embedded struct", - shouldSucceedOnJson: true, - payload: `{"title":"Glorious Post Title", "id":1, "author":{"name":"Matt Holt"}}`, - contentType: _JSON_CONTENT_TYPE, - expected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1, Author: Person{Name: "Matt Holt"}}, - }, - { - description: "Deserialization with nested and embedded struct with interface", - shouldSucceedOnJson: true, - withInterface: true, - payload: `{"title":"Glorious Post Title", "id":1, "author":{"name":"Matt Holt"}}`, - contentType: _JSON_CONTENT_TYPE, - expected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1, Author: Person{Name: "Matt Holt"}}, - }, - { - description: "Required nested struct field not specified", - shouldSucceedOnJson: false, - payload: `{"title":"Glorious Post Title", "id":1, "author":{}}`, - contentType: _JSON_CONTENT_TYPE, - expected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1}, - }, - { - description: "Required embedded struct field not specified", - shouldSucceedOnJson: false, - payload: `{"id":1, "author":{"name":"Matt Holt"}}`, - contentType: _JSON_CONTENT_TYPE, - expected: BlogPost{Id: 1, Author: Person{Name: "Matt Holt"}}, - }, - { - description: "Slice of Posts", - shouldSucceedOnJson: true, - payload: `[{"title": "First Post"}, {"title": "Second Post"}]`, - contentType: _JSON_CONTENT_TYPE, - expected: []Post{Post{Title: "First Post"}, Post{Title: "Second Post"}}, - }, - { - description: "Slice of structs", - shouldSucceedOnJson: true, - payload: `{"name": "group1", "people": [{"name":"awoods"}, {"name": "anthony"}]}`, - contentType: _JSON_CONTENT_TYPE, - expected: Group{Name: "group1", People: []Person{Person{Name: "awoods"}, Person{Name: "anthony"}}}, - }, -} - -func Test_Json(t *testing.T) { - Convey("Test JSON", t, func() { - for _, testCase := range jsonTestCases { - performJsonTest(t, Json, testCase) - } - }) -} - -func performJsonTest(t *testing.T, binder handlerFunc, testCase jsonTestCase) { - var payload io.Reader - httpRecorder := httptest.NewRecorder() - m := macaron.Classic() - - jsonTestHandler := func(actual interface{}, errs Errors) { - if testCase.shouldSucceedOnJson && len(errs) > 0 { - So(len(errs), ShouldEqual, 0) - } else if !testCase.shouldSucceedOnJson && len(errs) == 0 { - So(len(errs), ShouldNotEqual, 0) - } - So(fmt.Sprintf("%+v", actual), ShouldEqual, fmt.Sprintf("%+v", testCase.expected)) - } - - switch testCase.expected.(type) { - case []Post: - if testCase.withInterface { - m.Post(testRoute, binder([]Post{}, (*modeler)(nil)), func(actual []Post, iface modeler, errs Errors) { - - for _, a := range actual { - So(a.Title, ShouldEqual, iface.Model()) - jsonTestHandler(a, errs) - } - }) - } else { - m.Post(testRoute, binder([]Post{}), func(actual []Post, errs Errors) { - jsonTestHandler(actual, errs) - }) - } - - case Post: - if testCase.withInterface { - m.Post(testRoute, binder(Post{}, (*modeler)(nil)), func(actual Post, iface modeler, errs Errors) { - So(actual.Title, ShouldEqual, iface.Model()) - jsonTestHandler(actual, errs) - }) - } else { - m.Post(testRoute, binder(Post{}), func(actual Post, errs Errors) { - jsonTestHandler(actual, errs) - }) - } - - case BlogPost: - if testCase.withInterface { - m.Post(testRoute, binder(BlogPost{}, (*modeler)(nil)), func(actual BlogPost, iface modeler, errs Errors) { - So(actual.Title, ShouldEqual, iface.Model()) - jsonTestHandler(actual, errs) - }) - } else { - m.Post(testRoute, binder(BlogPost{}), func(actual BlogPost, errs Errors) { - jsonTestHandler(actual, errs) - }) - } - case Group: - if testCase.withInterface { - m.Post(testRoute, binder(Group{}, (*modeler)(nil)), func(actual Group, iface modeler, errs Errors) { - So(actual.Name, ShouldEqual, iface.Model()) - jsonTestHandler(actual, errs) - }) - } else { - m.Post(testRoute, binder(Group{}), func(actual Group, errs Errors) { - jsonTestHandler(actual, errs) - }) - } - } - - if testCase.payload == "-nil-" { - payload = nil - } else { - payload = strings.NewReader(testCase.payload) - } - - req, err := http.NewRequest("POST", testRoute, payload) - if err != nil { - panic(err) - } - req.Header.Set("Content-Type", testCase.contentType) - - m.ServeHTTP(httpRecorder, req) - - switch httpRecorder.Code { - case http.StatusNotFound: - panic("Routing is messed up in test fixture (got 404): check method and path") - case http.StatusInternalServerError: - panic("Something bad happened on '" + testCase.description + "'") - default: - if testCase.shouldSucceedOnJson && - httpRecorder.Code != http.StatusOK && - !testCase.shouldFailOnBind { - So(httpRecorder.Code, ShouldEqual, http.StatusOK) - } - } -} - -type ( - jsonTestCase struct { - description string - withInterface bool - shouldSucceedOnJson bool - shouldFailOnBind bool - payload string - contentType string - expected interface{} - } -) diff --git a/modules/middlewares/binding/misc_test.go b/modules/middlewares/binding/misc_test.go deleted file mode 100755 index d8f4aaf7f85d0..0000000000000 --- a/modules/middlewares/binding/misc_test.go +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2014 Martini Authors -// Copyright 2014 The Macaron Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package binding - -import ( - "fmt" - "net/http" - "net/http/httptest" - "strings" - "testing" - - . "github.com/smartystreets/goconvey/convey" - "gitea.com/macaron/macaron" -) - -// When binding from Form data, testing the type of data to bind -// and converting a string into that type is tedious, so these tests -// cover all those cases. -func Test_SetWithProperType(t *testing.T) { - Convey("Set with proper type", t, func() { - testInputs := map[string]string{ - "successful": `integer=-1&integer8=-8&integer16=-16&integer32=-32&integer64=-64&uinteger=1&uinteger8=8&uinteger16=16&uinteger32=32&uinteger64=64&boolean_1=true&fl32_1=32.3232&fl64_1=-64.6464646464&str=string`, - "errorful": `integer=&integer8=asdf&integer16=--&integer32=&integer64=dsf&uinteger=&uinteger8=asdf&uinteger16=+&uinteger32= 32 &uinteger64=+%20+&boolean_1=&boolean_2=asdf&fl32_1=asdf&fl32_2=&fl64_1=&fl64_2=asdfstr`, - } - - expectedOutputs := map[string]Everything{ - "successful": Everything{ - Integer: -1, - Integer8: -8, - Integer16: -16, - Integer32: -32, - Integer64: -64, - Uinteger: 1, - Uinteger8: 8, - Uinteger16: 16, - Uinteger32: 32, - Uinteger64: 64, - Boolean_1: true, - Fl32_1: 32.3232, - Fl64_1: -64.6464646464, - Str: "string", - }, - "errorful": Everything{}, - } - - for key, testCase := range testInputs { - httpRecorder := httptest.NewRecorder() - m := macaron.Classic() - - m.Post(testRoute, Form(Everything{}), func(actual Everything, errs Errors) { - So(fmt.Sprintf("%+v", actual), ShouldEqual, fmt.Sprintf("%+v", expectedOutputs[key])) - if key == "errorful" { - So(errs, ShouldHaveLength, 10) - } else { - So(errs, ShouldHaveLength, 0) - } - }) - req, err := http.NewRequest("POST", testRoute, strings.NewReader(testCase)) - if err != nil { - panic(err) - } - req.Header.Set("Content-Type", formContentType) - m.ServeHTTP(httpRecorder, req) - } - }) -} - -// Each binder middleware should assert that the struct passed in is not -// a pointer (to avoid race conditions) -func Test_EnsureNotPointer(t *testing.T) { - Convey("Ensure field is not a pointer", t, func() { - shouldPanic := func() { - defer func() { - So(recover(), ShouldNotBeNil) - }() - ensureNotPointer(&Post{}) - } - - shouldNotPanic := func() { - defer func() { - So(recover(), ShouldBeNil) - }() - ensureNotPointer(Post{}) - } - - shouldPanic() - shouldNotPanic() - }) -} - -// Used in testing setWithProperType; kind of clunky... -type Everything struct { - Integer int `form:"integer"` - Integer8 int8 `form:"integer8"` - Integer16 int16 `form:"integer16"` - Integer32 int32 `form:"integer32"` - Integer64 int64 `form:"integer64"` - Uinteger uint `form:"uinteger"` - Uinteger8 uint8 `form:"uinteger8"` - Uinteger16 uint16 `form:"uinteger16"` - Uinteger32 uint32 `form:"uinteger32"` - Uinteger64 uint64 `form:"uinteger64"` - Boolean_1 bool `form:"boolean_1"` - Boolean_2 bool `form:"boolean_2"` - Fl32_1 float32 `form:"fl32_1"` - Fl32_2 float32 `form:"fl32_2"` - Fl64_1 float64 `form:"fl64_1"` - Fl64_2 float64 `form:"fl64_2"` - Str string `form:"str"` -} diff --git a/modules/middlewares/binding/multipart_test.go b/modules/middlewares/binding/multipart_test.go deleted file mode 100755 index 9b74a8eb27d64..0000000000000 --- a/modules/middlewares/binding/multipart_test.go +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright 2014 Martini Authors -// Copyright 2014 The Macaron Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package binding - -import ( - "bytes" - "fmt" - "mime/multipart" - "net/http" - "net/http/httptest" - "strconv" - "testing" - - . "github.com/smartystreets/goconvey/convey" - "gitea.com/macaron/macaron" -) - -var multipartFormTestCases = []multipartFormTestCase{ - { - description: "Happy multipart form path", - shouldSucceed: true, - inputAndExpected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1, Author: Person{Name: "Matt Holt"}}, - }, - { - description: "FormValue called before req.MultipartReader(); see https://github.com/martini-contrib/csrf/issues/6", - shouldSucceed: true, - callFormValueBefore: true, - inputAndExpected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1, Author: Person{Name: "Matt Holt"}}, - }, - { - description: "Empty payload", - shouldSucceed: false, - inputAndExpected: BlogPost{}, - }, - { - description: "Missing required field (Id)", - shouldSucceed: false, - inputAndExpected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Author: Person{Name: "Matt Holt"}}, - }, - { - description: "Required embedded struct field not specified", - shouldSucceed: false, - inputAndExpected: BlogPost{Id: 1, Author: Person{Name: "Matt Holt"}}, - }, - { - description: "Required nested struct field not specified", - shouldSucceed: false, - inputAndExpected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1}, - }, - { - description: "Multiple values", - shouldSucceed: true, - inputAndExpected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1, Author: Person{Name: "Matt Holt"}, Ratings: []int{3, 5, 4}}, - }, - { - description: "Bad multipart encoding", - shouldSucceed: false, - malformEncoding: true, - }, -} - -func Test_MultipartForm(t *testing.T) { - Convey("Test multipart form", t, func() { - for _, testCase := range multipartFormTestCases { - performMultipartFormTest(t, MultipartForm, testCase) - } - }) -} - -func performMultipartFormTest(t *testing.T, binder handlerFunc, testCase multipartFormTestCase) { - httpRecorder := httptest.NewRecorder() - m := macaron.Classic() - - m.Post(testRoute, binder(BlogPost{}), func(actual BlogPost, errs Errors) { - if testCase.shouldSucceed && len(errs) > 0 { - So(len(errs), ShouldEqual, 0) - } else if !testCase.shouldSucceed && len(errs) == 0 { - So(len(errs), ShouldNotEqual, 0) - } - So(fmt.Sprintf("%+v", actual), ShouldEqual, fmt.Sprintf("%+v", testCase.inputAndExpected)) - }) - - multipartPayload, mpWriter := makeMultipartPayload(testCase) - - req, err := http.NewRequest("POST", testRoute, multipartPayload) - if err != nil { - panic(err) - } - - req.Header.Add("Content-Type", mpWriter.FormDataContentType()) - - err = mpWriter.Close() - if err != nil { - panic(err) - } - - if testCase.callFormValueBefore { - req.FormValue("foo") - } - - m.ServeHTTP(httpRecorder, req) - - switch httpRecorder.Code { - case http.StatusNotFound: - panic("Routing is messed up in test fixture (got 404): check methods and paths") - case http.StatusInternalServerError: - panic("Something bad happened on '" + testCase.description + "'") - } -} - -// Writes the input from a test case into a buffer using the multipart writer. -func makeMultipartPayload(testCase multipartFormTestCase) (*bytes.Buffer, *multipart.Writer) { - body := &bytes.Buffer{} - writer := multipart.NewWriter(body) - if testCase.malformEncoding { - // TODO: Break the multipart form parser which is apparently impervious!! - // (Get it to return an error. Trying to get 100% test coverage.) - body.Write([]byte(`--` + writer.Boundary() + `\nContent-Disposition: form-data; name="foo"\n\n--` + writer.Boundary() + `--`)) - return body, writer - } else { - writer.WriteField("title", testCase.inputAndExpected.Title) - writer.WriteField("content", testCase.inputAndExpected.Content) - writer.WriteField("id", strconv.Itoa(testCase.inputAndExpected.Id)) - writer.WriteField("ignored", testCase.inputAndExpected.Ignored) - for _, value := range testCase.inputAndExpected.Ratings { - writer.WriteField("rating", strconv.Itoa(value)) - } - writer.WriteField("name", testCase.inputAndExpected.Author.Name) - writer.WriteField("email", testCase.inputAndExpected.Author.Email) - return body, writer - } -} - -type ( - multipartFormTestCase struct { - description string - shouldSucceed bool - inputAndExpected BlogPost - malformEncoding bool - callFormValueBefore bool - } -) diff --git a/modules/middlewares/binding/validate_test.go b/modules/middlewares/binding/validate_test.go deleted file mode 100755 index 926594f6a3c0b..0000000000000 --- a/modules/middlewares/binding/validate_test.go +++ /dev/null @@ -1,412 +0,0 @@ -// Copyright 2014 Martini Authors -// Copyright 2014 The Macaron Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package binding - -import ( - "fmt" - "net/http" - "net/http/httptest" - "testing" - - . "github.com/smartystreets/goconvey/convey" - "gitea.com/macaron/macaron" -) - -var validationTestCases = []validationTestCase{ - { - description: "No errors", - data: BlogPost{ - Id: 1, - Post: Post{ - Title: "Behold The Title!", - Content: "And some content", - }, - Author: Person{ - Name: "Matt Holt", - }, - }, - expectedErrors: Errors{}, - }, - { - description: "ID required", - data: BlogPost{ - Post: Post{ - Title: "Behold The Title!", - Content: "And some content", - }, - Author: Person{ - Name: "Matt Holt", - }, - }, - expectedErrors: Errors{ - Error{ - FieldNames: []string{"id"}, - Classification: ERR_REQUIRED, - Message: "Required", - }, - }, - }, - { - description: "Embedded struct field required", - data: BlogPost{ - Id: 1, - Post: Post{ - Content: "Content given, but title is required", - }, - Author: Person{ - Name: "Matt Holt", - }, - }, - expectedErrors: Errors{ - Error{ - FieldNames: []string{"title"}, - Classification: ERR_REQUIRED, - Message: "Required", - }, - Error{ - FieldNames: []string{"title"}, - Classification: "LengthError", - Message: "Life is too short", - }, - }, - }, - { - description: "Nested struct field required", - data: BlogPost{ - Id: 1, - Post: Post{ - Title: "Behold The Title!", - Content: "And some content", - }, - }, - expectedErrors: Errors{ - Error{ - FieldNames: []string{"name"}, - Classification: ERR_REQUIRED, - Message: "Required", - }, - }, - }, - { - description: "Required field missing in nested struct pointer", - data: BlogPost{ - Id: 1, - Post: Post{ - Title: "Behold The Title!", - Content: "And some content", - }, - Author: Person{ - Name: "Matt Holt", - }, - Coauthor: &Person{}, - }, - expectedErrors: Errors{ - Error{ - FieldNames: []string{"name"}, - Classification: ERR_REQUIRED, - Message: "Required", - }, - }, - }, - { - description: "All required fields specified in nested struct pointer", - data: BlogPost{ - Id: 1, - Post: Post{ - Title: "Behold The Title!", - Content: "And some content", - }, - Author: Person{ - Name: "Matt Holt", - }, - Coauthor: &Person{ - Name: "Jeremy Saenz", - }, - }, - expectedErrors: Errors{}, - }, - { - description: "Custom validation should put an error", - data: BlogPost{ - Id: 1, - Post: Post{ - Title: "Too short", - Content: "And some content", - }, - Author: Person{ - Name: "Matt Holt", - }, - }, - expectedErrors: Errors{ - Error{ - FieldNames: []string{"title"}, - Classification: "LengthError", - Message: "Life is too short", - }, - }, - }, - { - description: "List Validation", - data: []BlogPost{ - BlogPost{ - Id: 1, - Post: Post{ - Title: "First Post", - Content: "And some content", - }, - Author: Person{ - Name: "Leeor Aharon", - }, - }, - BlogPost{ - Id: 2, - Post: Post{ - Title: "Second Post", - Content: "And some content", - }, - Author: Person{ - Name: "Leeor Aharon", - }, - }, - }, - expectedErrors: Errors{}, - }, - { - description: "List Validation w/ Errors", - data: []BlogPost{ - BlogPost{ - Id: 1, - Post: Post{ - Title: "First Post", - Content: "And some content", - }, - Author: Person{ - Name: "Leeor Aharon", - }, - }, - BlogPost{ - Id: 2, - Post: Post{ - Title: "Too Short", - Content: "And some content", - }, - Author: Person{ - Name: "Leeor Aharon", - }, - }, - }, - expectedErrors: Errors{ - Error{ - FieldNames: []string{"title"}, - Classification: "LengthError", - Message: "Life is too short", - }, - }, - }, - { - description: "List of invalid custom validations", - data: []SadForm{ - SadForm{ - AlphaDash: ",", - AlphaDashDot: ",", - Size: "123", - SizeSlice: []string{"1", "2", "3"}, - MinSize: ",", - MinSizeSlice: []string{",", ","}, - MaxSize: ",,", - MaxSizeSlice: []string{",", ","}, - Range: 3, - Email: ",", - Url: ",", - UrlEmpty: "", - InInvalid: "4", - NotIn: "1", - Include: "def", - Exclude: "abc", - }, - }, - expectedErrors: Errors{ - Error{ - FieldNames: []string{"AlphaDash"}, - Classification: "AlphaDashError", - Message: "AlphaDash", - }, - Error{ - FieldNames: []string{"AlphaDashDot"}, - Classification: "AlphaDashDot", - Message: "AlphaDashDot", - }, - Error{ - FieldNames: []string{"Size"}, - Classification: "Size", - Message: "Size", - }, - Error{ - FieldNames: []string{"Size"}, - Classification: "Size", - Message: "Size", - }, - Error{ - FieldNames: []string{"MinSize"}, - Classification: "MinSize", - Message: "MinSize", - }, - Error{ - FieldNames: []string{"MinSize"}, - Classification: "MinSize", - Message: "MinSize", - }, - Error{ - FieldNames: []string{"MaxSize"}, - Classification: "MaxSize", - Message: "MaxSize", - }, - Error{ - FieldNames: []string{"MaxSize"}, - Classification: "MaxSize", - Message: "MaxSize", - }, - Error{ - FieldNames: []string{"Range"}, - Classification: "Range", - Message: "Range", - }, - Error{ - FieldNames: []string{"Email"}, - Classification: "Email", - Message: "Email", - }, - Error{ - FieldNames: []string{"Url"}, - Classification: "Url", - Message: "Url", - }, - Error{ - FieldNames: []string{"Default"}, - Classification: "Default", - Message: "Default", - }, - Error{ - FieldNames: []string{"InInvalid"}, - Classification: "In", - Message: "In", - }, - Error{ - FieldNames: []string{"NotIn"}, - Classification: "NotIn", - Message: "NotIn", - }, - Error{ - FieldNames: []string{"Include"}, - Classification: "Include", - Message: "Include", - }, - Error{ - FieldNames: []string{"Exclude"}, - Classification: "Exclude", - Message: "Exclude", - }, - }, - }, - { - description: "List of valid custom validations", - data: []SadForm{ - SadForm{ - AlphaDash: "123-456", - AlphaDashDot: "123.456", - Size: "1", - SizeSlice: []string{"1"}, - MinSize: "12345", - MinSizeSlice: []string{"1", "2", "3", "4", "5"}, - MaxSize: "1", - MaxSizeSlice: []string{"1"}, - Range: 2, - In: "1", - InInvalid: "1", - Email: "123@456.com", - Url: "http://123.456", - Include: "abc", - }, - }, - }, - { - description: "slice of structs Validation", - data: Group{ - Name: "group1", - People: []Person{ - Person{Name: "anthony"}, - Person{Name: "awoods"}, - }, - }, - expectedErrors: Errors{}, - }, - { - description: "slice of structs Validation failer", - data: Group{ - Name: "group1", - People: []Person{ - Person{Name: "anthony"}, - Person{Name: ""}, - }, - }, - expectedErrors: Errors{ - Error{ - FieldNames: []string{"name"}, - Classification: ERR_REQUIRED, - Message: "Required", - }, - }, - }, -} - -func Test_Validation(t *testing.T) { - Convey("Test validation", t, func() { - for _, testCase := range validationTestCases { - performValidationTest(t, testCase) - } - }) -} - -func performValidationTest(t *testing.T, testCase validationTestCase) { - httpRecorder := httptest.NewRecorder() - m := macaron.Classic() - - m.Post(testRoute, Validate(testCase.data), func(actual Errors) { - So(fmt.Sprintf("%+v", actual), ShouldEqual, fmt.Sprintf("%+v", testCase.expectedErrors)) - }) - - req, err := http.NewRequest("POST", testRoute, nil) - if err != nil { - panic(err) - } - - m.ServeHTTP(httpRecorder, req) - - switch httpRecorder.Code { - case http.StatusNotFound: - panic("Routing is messed up in test fixture (got 404): check methods and paths") - case http.StatusInternalServerError: - panic("Something bad happened on '" + testCase.description + "'") - } -} - -type ( - validationTestCase struct { - description string - data interface{} - expectedErrors Errors - } -) diff --git a/routers/routes/chi.go b/routers/routes/chi.go index fe7b60fbabb45..7659078d23844 100644 --- a/routers/routes/chi.go +++ b/routers/routes/chi.go @@ -16,6 +16,8 @@ import ( "text/template" "time" + "code.gitea.io/gitea/modules/auth" + gitea_context "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/httpcache" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/metrics" @@ -24,6 +26,7 @@ import ( "code.gitea.io/gitea/modules/storage" "code.gitea.io/gitea/routers" + "gitea.com/go-chi/binding" "gitea.com/go-chi/session" "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" @@ -176,7 +179,31 @@ func storageHandler(storageSetting setting.Storage, prefix string, objStore stor } } -// NewChi creates a chi Router +// Wrap converts an install route to a chi route +func Wrap(f func(ctx *gitea_context.DefaultContext)) http.HandlerFunc { + return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { + ctx := gitea_context.GetDefaultContext(req) + f(ctx) + }) +} + +// Bind binding an obj to a handler +func Bind(obj interface{}, handler http.HandlerFunc) http.HandlerFunc { + return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { + errs := binding.Bind(req, obj) + if errs.Len() > 0 { + ctx := gitea_context.GetDefaultContext(req) + ctx.Data["HasError"] = true + auth.AssignForm(obj, ctx.Data) + // FIXME: + //ctx.Flash(ErrorFlash, msg) + } + + handler(resp, req) + }) +} + +// NewChi creates a basic chi Router func NewChi() chi.Router { c := chi.NewRouter() c.Use(middleware.RealIP) @@ -213,15 +240,14 @@ func NewChi() chi.Router { }, )) - c.Use(storageHandler(setting.Avatar.Storage, "avatars", storage.Avatars)) - c.Use(storageHandler(setting.RepoAvatar.Storage, "repo-avatars", storage.RepoAvatars)) - return c } // NormalRoutes represents non install routes func NormalRoutes() http.Handler { r := chi.NewRouter() + r.Use(storageHandler(setting.Avatar.Storage, "avatars", storage.Avatars)) + r.Use(storageHandler(setting.RepoAvatar.Storage, "repo-avatars", storage.RepoAvatars)) // for health check r.Head("/", func(w http.ResponseWriter, req *http.Request) { diff --git a/routers/install.go b/routers/routes/install.go similarity index 93% rename from routers/install.go rename to routers/routes/install.go index a981ef460d776..fa3e9ab2ff911 100644 --- a/routers/install.go +++ b/routers/routes/install.go @@ -3,7 +3,7 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package routers +package routes import ( "fmt" @@ -25,9 +25,9 @@ import ( gitea_templates "code.gitea.io/gitea/modules/templates" "code.gitea.io/gitea/modules/user" "code.gitea.io/gitea/modules/util" + "code.gitea.io/gitea/routers" "gitea.com/go-chi/session" - "github.com/alexedwards/scs/v2" "github.com/go-chi/chi" "github.com/unknwon/com" "github.com/unrolled/render" @@ -43,18 +43,9 @@ const ( // InstallRoutes represents the install routes func InstallRoutes() http.Handler { r := chi.NewRouter() - r.Use(session.Sessioner(session.Options{ - Provider: setting.SessionConfig.Provider, - ProviderConfig: setting.SessionConfig.ProviderConfig, - CookieName: setting.SessionConfig.CookieName, - CookiePath: setting.SessionConfig.CookiePath, - Gclifetime: setting.SessionConfig.Gclifetime, - Maxlifetime: setting.SessionConfig.Maxlifetime, - Secure: setting.SessionConfig.Secure, - Domain: setting.SessionConfig.Domain, - })) - r.Get("/", WrapInstall(Install)) - r.Post("/", WrapInstall(InstallPost)) + r.Use(InstallInit) + r.Get("/", Wrap(Install)) + r.Post("/", Bind(&forms.InstallForm{}, Wrap(InstallPost))) r.NotFound(func(w http.ResponseWriter, req *http.Request) { http.Redirect(w, req, setting.AppURL, 302) }) @@ -62,7 +53,7 @@ func InstallRoutes() http.Handler { } // InstallInit prepare for rendering installation page -func InstallInit(next http.Handler, sessionManager *scs.SessionManager) http.Handler { +func InstallInit(next http.Handler) http.Handler { rnd := render.New(render.Options{ Directory: "templates", Extensions: []string{".tmpl"}, @@ -78,7 +69,7 @@ func InstallInit(next http.Handler, sessionManager *scs.SessionManager) http.Han var locale = middlewares.Locale(resp, req) var startTime = time.Now() - var ctx = context.InstallContext{ + var ctx = context.DefaultContext{ Resp: resp, Req: req, Locale: locale, @@ -98,22 +89,14 @@ func InstallInit(next http.Handler, sessionManager *scs.SessionManager) http.Han Session: session.GetSession(req), } - req = context.WithInstallContext(req, &ctx) + req = context.WithDefaultContext(req, &ctx) ctx.Req = req next.ServeHTTP(resp, req) }) } -// WrapInstall converts an install route to a chi route -func WrapInstall(f func(ctx *context.InstallContext)) http.HandlerFunc { - return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { - ctx := context.GetInstallContext(req) - f(ctx) - }) -} - // Install render installation page -func Install(ctx *context.InstallContext) { +func Install(ctx *context.DefaultContext) { form := forms.InstallForm{} // Database settings @@ -187,7 +170,7 @@ func Install(ctx *context.InstallContext) { } // InstallPost response for submit install items -func InstallPost(ctx *context.InstallContext) { +func InstallPost(ctx *context.DefaultContext) { var form forms.InstallForm _ = ctx.Bind(&form) @@ -436,7 +419,7 @@ func InstallPost(ctx *context.InstallContext) { } // Re-read settings - PostInstallInit(ctx.Req.Context()) + routers.PostInstallInit(ctx.Req.Context()) // Create admin account if len(form.AdminName) > 0 { diff --git a/vendor/gitea.com/go-chi/binding/.drone.yml b/vendor/gitea.com/go-chi/binding/.drone.yml new file mode 100644 index 0000000000000..9baf4f1cf7594 --- /dev/null +++ b/vendor/gitea.com/go-chi/binding/.drone.yml @@ -0,0 +1,24 @@ +kind: pipeline +name: go1-1-1 + +steps: +- name: test + image: golang:1.11 + environment: + GOPROXY: https://goproxy.cn + commands: + - go build -v + - go test -v -race -coverprofile=coverage.txt -covermode=atomic + +--- +kind: pipeline +name: go1-1-2 + +steps: +- name: test + image: golang:1.12 + environment: + GOPROXY: https://goproxy.cn + commands: + - go build -v + - go test -v -race -coverprofile=coverage.txt -covermode=atomic \ No newline at end of file diff --git a/vendor/gitea.com/go-chi/binding/.gitignore b/vendor/gitea.com/go-chi/binding/.gitignore new file mode 100644 index 0000000000000..485dee64bcfb4 --- /dev/null +++ b/vendor/gitea.com/go-chi/binding/.gitignore @@ -0,0 +1 @@ +.idea diff --git a/vendor/gitea.com/go-chi/binding/LICENSE b/vendor/gitea.com/go-chi/binding/LICENSE new file mode 100644 index 0000000000000..8405e89a0b120 --- /dev/null +++ b/vendor/gitea.com/go-chi/binding/LICENSE @@ -0,0 +1,191 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, "control" means (i) the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising +permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +"Object" form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +"submitted" means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +2. Grant of Copyright License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +3. Grant of Patent License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of +this License; and +You must cause any modified files to carry prominent notices stating that You +changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source form +of the Work, excluding those notices that do not pertain to any part of the +Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any +Derivative Works that You distribute must include a readable copy of the +attribution notices contained within such NOTICE file, excluding those notices +that do not pertain to any part of the Derivative Works, in at least one of the +following places: within a NOTICE text file distributed as part of the +Derivative Works; within the Source form or documentation, if provided along +with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents of +the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works that +You distribute, alongside or as an addendum to the NOTICE text from the Work, +provided that such additional attribution notices cannot be construed as +modifying the License. +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +5. Submission of Contributions. + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +6. Trademarks. + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +8. Limitation of Liability. + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets "[]" replaced with your own +identifying information. (Don't include the brackets!) The text should be +enclosed in the appropriate comment syntax for the file format. We also +recommend that a file or class name and description of purpose be included on +the same "printed page" as the copyright notice for easier identification within +third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/modules/middlewares/binding/README.md b/vendor/gitea.com/go-chi/binding/README.md similarity index 100% rename from modules/middlewares/binding/README.md rename to vendor/gitea.com/go-chi/binding/README.md diff --git a/modules/middlewares/binding/binding.go b/vendor/gitea.com/go-chi/binding/binding.go similarity index 100% rename from modules/middlewares/binding/binding.go rename to vendor/gitea.com/go-chi/binding/binding.go diff --git a/modules/middlewares/binding/errors.go b/vendor/gitea.com/go-chi/binding/errors.go similarity index 100% rename from modules/middlewares/binding/errors.go rename to vendor/gitea.com/go-chi/binding/errors.go diff --git a/vendor/gitea.com/go-chi/binding/go.mod b/vendor/gitea.com/go-chi/binding/go.mod new file mode 100644 index 0000000000000..194751d004269 --- /dev/null +++ b/vendor/gitea.com/go-chi/binding/go.mod @@ -0,0 +1,10 @@ +module gitea.com/go-chi/binding + +go 1.13 + +require ( + gitea.com/macaron/macaron v1.3.3-0.20190821202302-9646c0587edb + github.com/go-chi/chi v1.5.1 + github.com/smartystreets/goconvey v0.0.0-20190731233626-505e41936337 + github.com/unknwon/com v0.0.0-20190804042917-757f69c95f3e +) diff --git a/vendor/gitea.com/go-chi/binding/go.sum b/vendor/gitea.com/go-chi/binding/go.sum new file mode 100644 index 0000000000000..aa4f5c6da6b9f --- /dev/null +++ b/vendor/gitea.com/go-chi/binding/go.sum @@ -0,0 +1,32 @@ +gitea.com/macaron/inject v0.0.0-20190803172902-8375ba841591 h1:UbCTjPcLrNxR9LzKDjQBMT2zoxZuEnca1pZCpgeMuhQ= +gitea.com/macaron/inject v0.0.0-20190803172902-8375ba841591/go.mod h1:h6E4kLao1Yko6DOU6QDnQPcuoNzvbZqzj2mtPcEn1aM= +gitea.com/macaron/macaron v1.3.3-0.20190821202302-9646c0587edb h1:amL0md6orTj1tXY16ANzVU9FmzQB+W7aJwp8pVDbrmA= +gitea.com/macaron/macaron v1.3.3-0.20190821202302-9646c0587edb/go.mod h1:0coI+mSPSwbsyAbOuFllVS38awuk9mevhLD52l50Gjs= +github.com/go-chi/chi v1.5.1 h1:kfTK3Cxd/dkMu/rKs5ZceWYp+t5CtiE7vmaTv3LjC6w= +github.com/go-chi/chi v1.5.1/go.mod h1:REp24E+25iKvxgeTfHmdUoL5x15kBiDBlnIl5bCwe2k= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gopherjs/gopherjs v0.0.0-20181103185306-d547d1d9531e h1:JKmoR8x90Iww1ks85zJ1lfDGgIiMDuIptTOhJq+zKyg= +github.com/gopherjs/gopherjs v0.0.0-20181103185306-d547d1d9531e/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/jtolds/gls v4.2.1+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= +github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= +github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/assertions v0.0.0-20190116191733-b6c0e53d7304 h1:Jpy1PXuP99tXNrhbq2BaPz9B+jNAvH1JPQQpG/9GCXY= +github.com/smartystreets/assertions v0.0.0-20190116191733-b6c0e53d7304/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v0.0.0-20181108003508-044398e4856c/go.mod h1:XDJAKZRPZ1CvBcN2aX5YOUTYGHki24fSF0Iv48Ibg0s= +github.com/smartystreets/goconvey v0.0.0-20190731233626-505e41936337 h1:WN9BUFbdyOsSH/XohnWpXOlq9NBD5sGAB2FciQMUEe8= +github.com/smartystreets/goconvey v0.0.0-20190731233626-505e41936337/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= +github.com/unknwon/com v0.0.0-20190804042917-757f69c95f3e h1:GSGeB9EAKY2spCABz6xOX5DbxZEXolK+nBSvmsQwRjM= +github.com/unknwon/com v0.0.0-20190804042917-757f69c95f3e/go.mod h1:tOOxU81rwgoCLoOVVPHb6T/wt8HZygqH5id+GNnlCXM= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4 h1:HuIa8hRrWRSrqYzx1qI49NNxhdi2PrY7gxVSq1JjLDc= +golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +gopkg.in/ini.v1 v1.44.0 h1:YRJzTUp0kSYWUVFF5XAbDFfyiqwsl0Vb9R8TVP5eRi0= +gopkg.in/ini.v1 v1.44.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= diff --git a/vendor/github.com/alexedwards/scs/v2/.travis.yml b/vendor/github.com/alexedwards/scs/v2/.travis.yml deleted file mode 100644 index 1e825050d8461..0000000000000 --- a/vendor/github.com/alexedwards/scs/v2/.travis.yml +++ /dev/null @@ -1,9 +0,0 @@ -language: go - -go: -- 1.12.x -- 1.13.x -- 1.14.x -- tip - -script: go test -race . diff --git a/vendor/github.com/alexedwards/scs/v2/LICENSE b/vendor/github.com/alexedwards/scs/v2/LICENSE deleted file mode 100644 index a428968947270..0000000000000 --- a/vendor/github.com/alexedwards/scs/v2/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Alex Edwards - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/alexedwards/scs/v2/README.md b/vendor/github.com/alexedwards/scs/v2/README.md deleted file mode 100644 index 864588d181124..0000000000000 --- a/vendor/github.com/alexedwards/scs/v2/README.md +++ /dev/null @@ -1,213 +0,0 @@ -# SCS: HTTP Session Management for Go - -[![GoDoc](https://godoc.org/github.com/alexedwards/scs?status.png)](https://pkg.go.dev/github.com/alexedwards/scs/v2?tab=doc) -[![Build status](https://travis-ci.org/alexedwards/stack.svg?branch=master)](https://travis-ci.org/alexedwards/scs) -[![Go report card](https://goreportcard.com/badge/github.com/alexedwards/scs)](https://goreportcard.com/report/github.com/alexedwards/scs) -[![Test coverage](http://gocover.io/_badge/github.com/alexedwards/scs)](https://gocover.io/github.com/alexedwards/scs) - - -## Features - -* Automatic loading and saving of session data via middleware. -* Choice of server-side session stores including PostgreSQL, MySQL, Redis, BadgerDB and BoltDB. Custom session stores are also supported. -* Supports multiple sessions per request, 'flash' messages, session token regeneration, and idle and absolute session timeouts. -* Easy to extend and customize. Communicate session tokens to/from clients in HTTP headers or request/response bodies. -* Efficient design. Smaller, faster and uses less memory than [gorilla/sessions](https://github.com/gorilla/sessions). - -## Instructions - -* [Installation](#installation) -* [Basic Use](#basic-use) -* [Configuring Session Behavior](#configuring-session-behavior) -* [Working with Session Data](#working-with-session-data) -* [Loading and Saving Sessions](#loading-and-saving-sessions) -* [Configuring the Session Store](#configuring-the-session-store) -* [Using Custom Session Stores](#using-custom-session-stores) -* [Preventing Session Fixation](#preventing-session-fixation) -* [Multiple Sessions per Request](#multiple-sessions-per-request) -* [Compatibility](#compatibility) - -### Installation - -This package requires Go 1.12 or newer. - -``` -$ go get github.com/alexedwards/scs/v2 -``` - -Note: If you're using the traditional `GOPATH` mechanism to manage dependencies, instead of modules, you'll need to `go get` and `import` `github.com/alexedwards/scs` without the `v2` suffix. - -Please use [versioned releases](https://github.com/alexedwards/scs/releases). Code in tip may contain experimental features which are subject to change. - -### Basic Use - -SCS implements a session management pattern following the [OWASP security guidelines](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Session_Management_Cheat_Sheet.md). Session data is stored on the server, and a randomly-generated unique session token (or *session ID*) is communicated to and from the client in a session cookie. - -```go -package main - -import ( - "io" - "net/http" - "time" - - "github.com/alexedwards/scs/v2" -) - -var sessionManager *scs.SessionManager - -func main() { - // Initialize a new session manager and configure the session lifetime. - sessionManager = scs.New() - sessionManager.Lifetime = 24 * time.Hour - - mux := http.NewServeMux() - mux.HandleFunc("/put", putHandler) - mux.HandleFunc("/get", getHandler) - - // Wrap your handlers with the LoadAndSave() middleware. - http.ListenAndServe(":4000", sessionManager.LoadAndSave(mux)) -} - -func putHandler(w http.ResponseWriter, r *http.Request) { - // Store a new key and value in the session data. - sessionManager.Put(r.Context(), "message", "Hello from a session!") -} - -func getHandler(w http.ResponseWriter, r *http.Request) { - // Use the GetString helper to retrieve the string value associated with a - // key. The zero value is returned if the key does not exist. - msg := sessionManager.GetString(r.Context(), "message") - io.WriteString(w, msg) -} -``` - -``` -$ curl -i --cookie-jar cj --cookie cj localhost:4000/put -HTTP/1.1 200 OK -Cache-Control: no-cache="Set-Cookie" -Set-Cookie: session=lHqcPNiQp_5diPxumzOklsSdE-MJ7zyU6kjch1Ee0UM; Path=/; Expires=Sat, 27 Apr 2019 10:28:20 GMT; Max-Age=86400; HttpOnly; SameSite=Lax -Vary: Cookie -Date: Fri, 26 Apr 2019 10:28:19 GMT -Content-Length: 0 - -$ curl -i --cookie-jar cj --cookie cj localhost:4000/get -HTTP/1.1 200 OK -Date: Fri, 26 Apr 2019 10:28:24 GMT -Content-Length: 21 -Content-Type: text/plain; charset=utf-8 - -Hello from a session! -``` - -### Configuring Session Behavior - -Session behavior can be configured via the `SessionManager` fields. - -```go -sessionManager = scs.New() -sessionManager.Lifetime = 3 * time.Hour -sessionManager.IdleTimeout = 20 * time.Minute -sessionManager.Cookie.Name = "session_id" -sessionManager.Cookie.Domain = "example.com" -sessionManager.Cookie.HttpOnly = true -sessionManager.Cookie.Path = "/example/" -sessionManager.Cookie.Persist = true -sessionManager.Cookie.SameSite = http.SameSiteStrictMode -sessionManager.Cookie.Secure = true -``` - -Documentation for all available settings and their default values can be [found here](https://godoc.org/github.com/alexedwards/scs#SessionManager). - -### Working with Session Data - -Data can be set using the [`Put()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.Put) method and retrieved with the [`Get()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.Get) method. A variety of helper methods like [`GetString()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.GetString), [`GetInt()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.GetInt) and [`GetBytes()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.GetBytes) are included for common data types. Please see [the documentation](https://godoc.org/github.com/alexedwards/scs#pkg-index) for a full list of helper methods. - -The [`Pop()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.Pop) method (and accompanying helpers for common data types) act like a one-time `Get()`, retrieving the data and removing it from the session in one step. These are useful if you want to implement 'flash' message functionality in your application, where messages are displayed to the user once only. - -Some other useful functions are [`Exists()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.Exists) (which returns a `bool` indicating whether or not a given key exists in the session data) and [`Keys()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.Keys) (which returns a sorted slice of keys in the session data). - -Individual data items can be deleted from the session using the [`Remove()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.Remove) method. Alternatively, all session data can de deleted by using the [`Destroy()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.Destroy) method. After calling `Destroy()`, any further operations in the same request cycle will result in a new session being created --- with a new session token and a new lifetime. - -Behind the scenes SCS uses gob encoding to store session data, so if you want to store custom types in the session data they must be [registered](https://golang.org/pkg/encoding/gob/#Register) with the encoding/gob package first. Struct fields of custom types must also be exported so that they are visible to the encoding/gob package. Please [see here](https://gist.github.com/alexedwards/d6eca7136f98ec12ad606e774d3abad3) for a working example. - -### Loading and Saving Sessions - -Most applications will use the [`LoadAndSave()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.LoadAndSave) middleware. This middleware takes care of loading and committing session data to the session store, and communicating the session token to/from the client in a cookie as necessary. - -If you want to customize the behavior (like communicating the session token to/from the client in a HTTP header, or creating a distributed lock on the session token for the duration of the request) you are encouraged to create your own alternative middleware using the code in [`LoadAndSave()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.LoadAndSave) as a template. An example is [given here](https://gist.github.com/alexedwards/cc6190195acfa466bf27f05aa5023f50). - -Or for more fine-grained control you can load and save sessions within your individual handlers (or from anywhere in your application). [See here](https://gist.github.com/alexedwards/0570e5a59677e278e13acb8ea53a3b30) for an example. - -### Configuring the Session Store - -By default SCS uses an in-memory store for session data. This is convenient (no setup!) and very fast, but all session data will be lost when your application is stopped or restarted. Therefore it's useful for applications where data loss is an acceptable trade off for fast performance, or for prototyping and testing purposes. In most production applications you will want to use a persistent session store like PostgreSQL or MySQL instead. - -The session stores currently included are shown in the table below. Please click the links for usage instructions and examples. - -| Package | | -|:------------------------------------------------------------------------------------- |----------------------------------------------------------------------------------| -| [badgerstore](https://github.com/alexedwards/scs/tree/master/badgerstore) | BadgerDB based session store | -| [boltstore](https://github.com/alexedwards/scs/tree/master/boltstore) | BoltDB based session store | -| [memstore](https://github.com/alexedwards/scs/tree/master/memstore) | In-memory session store (default) | -| [mysqlstore](https://github.com/alexedwards/scs/tree/master/mysqlstore) | MySQL based session store | -| [postgresstore](https://github.com/alexedwards/scs/tree/master/postgresstore) | PostgreSQL based session store | -| [redisstore](https://github.com/alexedwards/scs/tree/master/redisstore) | Redis based session store | -| [sqlite3store](https://github.com/alexedwards/scs/tree/master/sqlite3store) | SQLite3 based session store | - -Custom session stores are also supported. Please [see here](#using-custom-session-stores) for more information. - -### Using Custom Session Stores - -[`scs.Store`](https://godoc.org/github.com/alexedwards/scs#Store) defines the interface for custom session stores. Any object that implements this interface can be set as the store when configuring the session. - -```go -type Store interface { - // Delete should remove the session token and corresponding data from the - // session store. If the token does not exist then Delete should be a no-op - // and return nil (not an error). - Delete(token string) (err error) - - // Find should return the data for a session token from the store. If the - // session token is not found or is expired, the found return value should - // be false (and the err return value should be nil). Similarly, tampered - // or malformed tokens should result in a found return value of false and a - // nil err value. The err return value should be used for system errors only. - Find(token string) (b []byte, found bool, err error) - - // Commit should add the session token and data to the store, with the given - // expiry time. If the session token already exists, then the data and - // expiry time should be overwritten. - Commit(token string, b []byte, expiry time.Time) (err error) -} -``` - -### Preventing Session Fixation - -To help prevent session fixation attacks you should [renew the session token after any privilege level change](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Session_Management_Cheat_Sheet.md#renew-the-session-id-after-any-privilege-level-change). Commonly, this means that the session token must to be changed when a user logs in or out of your application. You can do this using the [`RenewToken()`](https://godoc.org/github.com/alexedwards/scs#SessionManager.RenewToken) method like so: - -```go -func loginHandler(w http.ResponseWriter, r *http.Request) { - userID := 123 - - // First renew the session token... - err := sessionManager.RenewToken(r.Context()) - if err != nil { - http.Error(w, err.Error(), 500) - return - } - - // Then make the privilege-level change. - sessionManager.Put(r.Context(), "userID", userID) -} -``` - -### Multiple Sessions per Request - -It is possible for an application to support multiple sessions per request, with different lifetime lengths and even different stores. Please [see here for an example](https://gist.github.com/alexedwards/22535f758356bfaf96038fffad154824). - -### Compatibility - -This package requires Go 1.12 or newer. - -It is not compatible with the [Echo](https://echo.labstack.com/) framework. Please consider using the [Echo session manager](https://echo.labstack.com/middleware/session) instead. diff --git a/vendor/github.com/alexedwards/scs/v2/codec.go b/vendor/github.com/alexedwards/scs/v2/codec.go deleted file mode 100644 index bcd9bbbeadb04..0000000000000 --- a/vendor/github.com/alexedwards/scs/v2/codec.go +++ /dev/null @@ -1,51 +0,0 @@ -package scs - -import ( - "bytes" - "encoding/gob" - "time" -) - -// Codec is the interface for encoding/decoding session data to and from a byte -// slice for use by the session store. -type Codec interface { - Encode(deadline time.Time, values map[string]interface{}) ([]byte, error) - Decode([]byte) (deadline time.Time, values map[string]interface{}, err error) -} - -// GobCodec is used for encoding/decoding session data to and from a byte -// slice using the encoding/gob package. -type GobCodec struct{} - -// Encode converts a session dealine and values into a byte slice. -func (GobCodec) Encode(deadline time.Time, values map[string]interface{}) ([]byte, error) { - aux := &struct { - Deadline time.Time - Values map[string]interface{} - }{ - Deadline: deadline, - Values: values, - } - - var b bytes.Buffer - if err := gob.NewEncoder(&b).Encode(&aux); err != nil { - return nil, err - } - - return b.Bytes(), nil -} - -// Decode converts a byte slice into a session deadline and values. -func (GobCodec) Decode(b []byte) (time.Time, map[string]interface{}, error) { - aux := &struct { - Deadline time.Time - Values map[string]interface{} - }{} - - r := bytes.NewReader(b) - if err := gob.NewDecoder(r).Decode(&aux); err != nil { - return time.Time{}, nil, err - } - - return aux.Deadline, aux.Values, nil -} diff --git a/vendor/github.com/alexedwards/scs/v2/data.go b/vendor/github.com/alexedwards/scs/v2/data.go deleted file mode 100644 index 1b65a324f3b7e..0000000000000 --- a/vendor/github.com/alexedwards/scs/v2/data.go +++ /dev/null @@ -1,498 +0,0 @@ -package scs - -import ( - "context" - "crypto/rand" - "encoding/base64" - "fmt" - "sort" - "sync" - "sync/atomic" - "time" -) - -// Status represents the state of the session data during a request cycle. -type Status int - -const ( - // Unmodified indicates that the session data hasn't been changed in the - // current request cycle. - Unmodified Status = iota - - // Modified indicates that the session data has been changed in the current - // request cycle. - Modified - - // Destroyed indicates that the session data has been destroyed in the - // current request cycle. - Destroyed -) - -type sessionData struct { - deadline time.Time - status Status - token string - values map[string]interface{} - mu sync.Mutex -} - -func newSessionData(lifetime time.Duration) *sessionData { - return &sessionData{ - deadline: time.Now().Add(lifetime).UTC(), - status: Unmodified, - values: make(map[string]interface{}), - } -} - -// Load retrieves the session data for the given token from the session store, -// and returns a new context.Context containing the session data. If no matching -// token is found then this will create a new session. -// -// Most applications will use the LoadAndSave() middleware and will not need to -// use this method. -func (s *SessionManager) Load(ctx context.Context, token string) (context.Context, error) { - if _, ok := ctx.Value(s.contextKey).(*sessionData); ok { - return ctx, nil - } - - if token == "" { - return s.addSessionDataToContext(ctx, newSessionData(s.Lifetime)), nil - } - - b, found, err := s.Store.Find(token) - if err != nil { - return nil, err - } else if !found { - return s.addSessionDataToContext(ctx, newSessionData(s.Lifetime)), nil - } - - sd := &sessionData{ - status: Unmodified, - token: token, - } - if sd.deadline, sd.values, err = s.Codec.Decode(b); err != nil { - return nil, err - } - - // Mark the session data as modified if an idle timeout is being used. This - // will force the session data to be re-committed to the session store with - // a new expiry time. - if s.IdleTimeout > 0 { - sd.status = Modified - } - - return s.addSessionDataToContext(ctx, sd), nil -} - -// Commit saves the session data to the session store and returns the session -// token and expiry time. -// -// Most applications will use the LoadAndSave() middleware and will not need to -// use this method. -func (s *SessionManager) Commit(ctx context.Context) (string, time.Time, error) { - sd := s.getSessionDataFromContext(ctx) - - sd.mu.Lock() - defer sd.mu.Unlock() - - if sd.token == "" { - var err error - if sd.token, err = generateToken(); err != nil { - return "", time.Time{}, err - } - } - - b, err := s.Codec.Encode(sd.deadline, sd.values) - if err != nil { - return "", time.Time{}, err - } - - expiry := sd.deadline - if s.IdleTimeout > 0 { - ie := time.Now().Add(s.IdleTimeout).UTC() - if ie.Before(expiry) { - expiry = ie - } - } - - if err := s.Store.Commit(sd.token, b, expiry); err != nil { - return "", time.Time{}, err - } - - return sd.token, expiry, nil -} - -// Destroy deletes the session data from the session store and sets the session -// status to Destroyed. Any further operations in the same request cycle will -// result in a new session being created. -func (s *SessionManager) Destroy(ctx context.Context) error { - sd := s.getSessionDataFromContext(ctx) - - sd.mu.Lock() - defer sd.mu.Unlock() - - err := s.Store.Delete(sd.token) - if err != nil { - return err - } - - sd.status = Destroyed - - // Reset everything else to defaults. - sd.token = "" - sd.deadline = time.Now().Add(s.Lifetime).UTC() - for key := range sd.values { - delete(sd.values, key) - } - - return nil -} - -// Put adds a key and corresponding value to the session data. Any existing -// value for the key will be replaced. The session data status will be set to -// Modified. -func (s *SessionManager) Put(ctx context.Context, key string, val interface{}) { - sd := s.getSessionDataFromContext(ctx) - - sd.mu.Lock() - sd.values[key] = val - sd.status = Modified - sd.mu.Unlock() -} - -// Get returns the value for a given key from the session data. The return -// value has the type interface{} so will usually need to be type asserted -// before you can use it. For example: -// -// foo, ok := session.Get(r, "foo").(string) -// if !ok { -// return errors.New("type assertion to string failed") -// } -// -// Also see the GetString(), GetInt(), GetBytes() and other helper methods which -// wrap the type conversion for common types. -func (s *SessionManager) Get(ctx context.Context, key string) interface{} { - sd := s.getSessionDataFromContext(ctx) - - sd.mu.Lock() - defer sd.mu.Unlock() - - return sd.values[key] -} - -// Pop acts like a one-time Get. It returns the value for a given key from the -// session data and deletes the key and value from the session data. The -// session data status will be set to Modified. The return value has the type -// interface{} so will usually need to be type asserted before you can use it. -func (s *SessionManager) Pop(ctx context.Context, key string) interface{} { - sd := s.getSessionDataFromContext(ctx) - - sd.mu.Lock() - defer sd.mu.Unlock() - - val, exists := sd.values[key] - if !exists { - return nil - } - delete(sd.values, key) - sd.status = Modified - - return val -} - -// Remove deletes the given key and corresponding value from the session data. -// The session data status will be set to Modified. If the key is not present -// this operation is a no-op. -func (s *SessionManager) Remove(ctx context.Context, key string) { - sd := s.getSessionDataFromContext(ctx) - - sd.mu.Lock() - defer sd.mu.Unlock() - - _, exists := sd.values[key] - if !exists { - return - } - - delete(sd.values, key) - sd.status = Modified -} - -// Clear removes all data for the current session. The session token and -// lifetime are unaffected. If there is no data in the current session this is -// a no-op. -func (s *SessionManager) Clear(ctx context.Context) error { - sd := s.getSessionDataFromContext(ctx) - - sd.mu.Lock() - defer sd.mu.Unlock() - - if len(sd.values) == 0 { - return nil - } - - for key := range sd.values { - delete(sd.values, key) - } - sd.status = Modified - return nil -} - -// Exists returns true if the given key is present in the session data. -func (s *SessionManager) Exists(ctx context.Context, key string) bool { - sd := s.getSessionDataFromContext(ctx) - - sd.mu.Lock() - _, exists := sd.values[key] - sd.mu.Unlock() - - return exists -} - -// Keys returns a slice of all key names present in the session data, sorted -// alphabetically. If the data contains no data then an empty slice will be -// returned. -func (s *SessionManager) Keys(ctx context.Context) []string { - sd := s.getSessionDataFromContext(ctx) - - sd.mu.Lock() - keys := make([]string, len(sd.values)) - i := 0 - for key := range sd.values { - keys[i] = key - i++ - } - sd.mu.Unlock() - - sort.Strings(keys) - return keys -} - -// RenewToken updates the session data to have a new session token while -// retaining the current session data. The session lifetime is also reset and -// the session data status will be set to Modified. -// -// The old session token and accompanying data are deleted from the session store. -// -// To mitigate the risk of session fixation attacks, it's important that you call -// RenewToken before making any changes to privilege levels (e.g. login and -// logout operations). See https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Session_Management_Cheat_Sheet.md#renew-the-session-id-after-any-privilege-level-change -// for additional information. -func (s *SessionManager) RenewToken(ctx context.Context) error { - sd := s.getSessionDataFromContext(ctx) - - sd.mu.Lock() - defer sd.mu.Unlock() - - err := s.Store.Delete(sd.token) - if err != nil { - return err - } - - newToken, err := generateToken() - if err != nil { - return err - } - - sd.token = newToken - sd.deadline = time.Now().Add(s.Lifetime).UTC() - sd.status = Modified - - return nil -} - -// Status returns the current status of the session data. -func (s *SessionManager) Status(ctx context.Context) Status { - sd := s.getSessionDataFromContext(ctx) - - sd.mu.Lock() - defer sd.mu.Unlock() - - return sd.status -} - -// GetString returns the string value for a given key from the session data. -// The zero value for a string ("") is returned if the key does not exist or the -// value could not be type asserted to a string. -func (s *SessionManager) GetString(ctx context.Context, key string) string { - val := s.Get(ctx, key) - str, ok := val.(string) - if !ok { - return "" - } - return str -} - -// GetBool returns the bool value for a given key from the session data. The -// zero value for a bool (false) is returned if the key does not exist or the -// value could not be type asserted to a bool. -func (s *SessionManager) GetBool(ctx context.Context, key string) bool { - val := s.Get(ctx, key) - b, ok := val.(bool) - if !ok { - return false - } - return b -} - -// GetInt returns the int value for a given key from the session data. The -// zero value for an int (0) is returned if the key does not exist or the -// value could not be type asserted to an int. -func (s *SessionManager) GetInt(ctx context.Context, key string) int { - val := s.Get(ctx, key) - i, ok := val.(int) - if !ok { - return 0 - } - return i -} - -// GetFloat returns the float64 value for a given key from the session data. The -// zero value for an float64 (0) is returned if the key does not exist or the -// value could not be type asserted to a float64. -func (s *SessionManager) GetFloat(ctx context.Context, key string) float64 { - val := s.Get(ctx, key) - f, ok := val.(float64) - if !ok { - return 0 - } - return f -} - -// GetBytes returns the byte slice ([]byte) value for a given key from the session -// data. The zero value for a slice (nil) is returned if the key does not exist -// or could not be type asserted to []byte. -func (s *SessionManager) GetBytes(ctx context.Context, key string) []byte { - val := s.Get(ctx, key) - b, ok := val.([]byte) - if !ok { - return nil - } - return b -} - -// GetTime returns the time.Time value for a given key from the session data. The -// zero value for a time.Time object is returned if the key does not exist or the -// value could not be type asserted to a time.Time. This can be tested with the -// time.IsZero() method. -func (s *SessionManager) GetTime(ctx context.Context, key string) time.Time { - val := s.Get(ctx, key) - t, ok := val.(time.Time) - if !ok { - return time.Time{} - } - return t -} - -// PopString returns the string value for a given key and then deletes it from the -// session data. The session data status will be set to Modified. The zero -// value for a string ("") is returned if the key does not exist or the value -// could not be type asserted to a string. -func (s *SessionManager) PopString(ctx context.Context, key string) string { - val := s.Pop(ctx, key) - str, ok := val.(string) - if !ok { - return "" - } - return str -} - -// PopBool returns the bool value for a given key and then deletes it from the -// session data. The session data status will be set to Modified. The zero -// value for a bool (false) is returned if the key does not exist or the value -// could not be type asserted to a bool. -func (s *SessionManager) PopBool(ctx context.Context, key string) bool { - val := s.Pop(ctx, key) - b, ok := val.(bool) - if !ok { - return false - } - return b -} - -// PopInt returns the int value for a given key and then deletes it from the -// session data. The session data status will be set to Modified. The zero -// value for an int (0) is returned if the key does not exist or the value could -// not be type asserted to an int. -func (s *SessionManager) PopInt(ctx context.Context, key string) int { - val := s.Pop(ctx, key) - i, ok := val.(int) - if !ok { - return 0 - } - return i -} - -// PopFloat returns the float64 value for a given key and then deletes it from the -// session data. The session data status will be set to Modified. The zero -// value for an float64 (0) is returned if the key does not exist or the value -// could not be type asserted to a float64. -func (s *SessionManager) PopFloat(ctx context.Context, key string) float64 { - val := s.Pop(ctx, key) - f, ok := val.(float64) - if !ok { - return 0 - } - return f -} - -// PopBytes returns the byte slice ([]byte) value for a given key and then -// deletes it from the from the session data. The session data status will be -// set to Modified. The zero value for a slice (nil) is returned if the key does -// not exist or could not be type asserted to []byte. -func (s *SessionManager) PopBytes(ctx context.Context, key string) []byte { - val := s.Pop(ctx, key) - b, ok := val.([]byte) - if !ok { - return nil - } - return b -} - -// PopTime returns the time.Time value for a given key and then deletes it from -// the session data. The session data status will be set to Modified. The zero -// value for a time.Time object is returned if the key does not exist or the -// value could not be type asserted to a time.Time. -func (s *SessionManager) PopTime(ctx context.Context, key string) time.Time { - val := s.Pop(ctx, key) - t, ok := val.(time.Time) - if !ok { - return time.Time{} - } - return t -} - -func (s *SessionManager) addSessionDataToContext(ctx context.Context, sd *sessionData) context.Context { - return context.WithValue(ctx, s.contextKey, sd) -} - -func (s *SessionManager) getSessionDataFromContext(ctx context.Context) *sessionData { - c, ok := ctx.Value(s.contextKey).(*sessionData) - if !ok { - panic("scs: no session data in context") - } - return c -} - -func generateToken() (string, error) { - b := make([]byte, 32) - _, err := rand.Read(b) - if err != nil { - return "", err - } - return base64.RawURLEncoding.EncodeToString(b), nil -} - -type contextKey string - -var ( - contextKeyID uint64 - contextKeyIDMutex = &sync.Mutex{} -) - -func generateContextKey() contextKey { - contextKeyIDMutex.Lock() - defer contextKeyIDMutex.Unlock() - atomic.AddUint64(&contextKeyID, 1) - return contextKey(fmt.Sprintf("session.%d", contextKeyID)) -} diff --git a/vendor/github.com/alexedwards/scs/v2/go.mod b/vendor/github.com/alexedwards/scs/v2/go.mod deleted file mode 100644 index 16a2ee639e60a..0000000000000 --- a/vendor/github.com/alexedwards/scs/v2/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/alexedwards/scs/v2 - -go 1.12 diff --git a/vendor/github.com/alexedwards/scs/v2/go.sum b/vendor/github.com/alexedwards/scs/v2/go.sum deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/vendor/github.com/alexedwards/scs/v2/memstore/README.md b/vendor/github.com/alexedwards/scs/v2/memstore/README.md deleted file mode 100644 index e33f550383b87..0000000000000 --- a/vendor/github.com/alexedwards/scs/v2/memstore/README.md +++ /dev/null @@ -1,74 +0,0 @@ -# memstore - -An in-memory session store for [SCS](https://github.com/alexedwards/scs). - - -Because memstore uses in-memory storage only, all session data will be lost when your application is stopped or restarted. Therefore it should only be used in applications where data loss is an acceptable trade off for fast performance, or for prototyping and testing purposes. - -## Example - -```go -package main - -import ( - "io" - "net/http" - - "github.com/alexedwards/scs/v2" - "github.com/alexedwards/scs/v2/memstore" -) - -var sessionManager *scs.SessionManager - -func main() { - // Initialize a new session manager and configure it to use memstore as - // the session store. - sessionManager = scs.New() - sessionManager.Store = memstore.New() - - mux := http.NewServeMux() - mux.HandleFunc("/put", putHandler) - mux.HandleFunc("/get", getHandler) - - http.ListenAndServe(":4000", sessionManager.LoadAndSave(mux)) -} - -func putHandler(w http.ResponseWriter, r *http.Request) { - sessionManager.Put(r.Context(), "message", "Hello from a session!") -} - -func getHandler(w http.ResponseWriter, r *http.Request) { - msg := sessionManager.GetString(r.Context(), "message") - io.WriteString(w, msg) -} -``` - -## Expired Session Cleanup - -This package provides a background 'cleanup' goroutine to delete expired session data. This stops the database table from holding on to invalid sessions indefinitely and growing unnecessarily large. By default the cleanup runs once every minute. You can change this by using the `NewWithCleanupInterval()` function to initialize your session store. For example: - -```go -// Run a cleanup every 30 seconds. -memstore.NewWithCleanupInterval(db, 30*time.Second) - -// Disable the cleanup goroutine by setting the cleanup interval to zero. -memstore.NewWithCleanupInterval(db, 0) -``` - -### Terminating the Cleanup Goroutine - -It's rare that the cleanup goroutine needs to be terminated --- it is generally intended to be long-lived and run for the lifetime of your application. - -However, there may be occasions when your use of a session store instance is transient. A common example would be using it in a short-lived test function. In this scenario, the cleanup goroutine (which will run forever) will prevent the session store instance from being garbage collected even after the test function has finished. You can prevent this by either disabling the cleanup goroutine altogether (as described above) or by stopping it using the `StopCleanup()` method. For example: - -```go -func TestExample(t *testing.T) { - store := memstore.New() - defer store.StopCleanup() - - sessionManager = scs.New() - sessionManager.Store = store - - // Run test... -} -``` \ No newline at end of file diff --git a/vendor/github.com/alexedwards/scs/v2/memstore/memstore.go b/vendor/github.com/alexedwards/scs/v2/memstore/memstore.go deleted file mode 100644 index 563df7e5bd801..0000000000000 --- a/vendor/github.com/alexedwards/scs/v2/memstore/memstore.go +++ /dev/null @@ -1,124 +0,0 @@ -package memstore - -import ( - "sync" - "time" -) - -type item struct { - object []byte - expiration int64 -} - -// MemStore represents the session store. -type MemStore struct { - items map[string]item - mu sync.RWMutex - stopCleanup chan bool -} - -// New returns a new MemStore instance, with a background cleanup goroutine that -// runs every minute to remove expired session data. -func New() *MemStore { - return NewWithCleanupInterval(time.Minute) -} - -// NewWithCleanupInterval returns a new MemStore instance. The cleanupInterval -// parameter controls how frequently expired session data is removed by the -// background cleanup goroutine. Setting it to 0 prevents the cleanup goroutine -// from running (i.e. expired sessions will not be removed). -func NewWithCleanupInterval(cleanupInterval time.Duration) *MemStore { - m := &MemStore{ - items: make(map[string]item), - } - - if cleanupInterval > 0 { - go m.startCleanup(cleanupInterval) - } - - return m -} - -// Find returns the data for a given session token from the MemStore instance. -// If the session token is not found or is expired, the returned exists flag will -// be set to false. -func (m *MemStore) Find(token string) ([]byte, bool, error) { - m.mu.RLock() - defer m.mu.RUnlock() - - item, found := m.items[token] - if !found { - return nil, false, nil - } - - if time.Now().UnixNano() > item.expiration { - return nil, false, nil - } - - return item.object, true, nil -} - -// Commit adds a session token and data to the MemStore instance with the given -// expiry time. If the session token already exists, then the data and expiry -// time are updated. -func (m *MemStore) Commit(token string, b []byte, expiry time.Time) error { - m.mu.Lock() - m.items[token] = item{ - object: b, - expiration: expiry.UnixNano(), - } - m.mu.Unlock() - - return nil -} - -// Delete removes a session token and corresponding data from the MemStore -// instance. -func (m *MemStore) Delete(token string) error { - m.mu.Lock() - delete(m.items, token) - m.mu.Unlock() - - return nil -} - -func (m *MemStore) startCleanup(interval time.Duration) { - m.stopCleanup = make(chan bool) - ticker := time.NewTicker(interval) - for { - select { - case <-ticker.C: - m.deleteExpired() - case <-m.stopCleanup: - ticker.Stop() - return - } - } -} - -// StopCleanup terminates the background cleanup goroutine for the MemStore -// instance. It's rare to terminate this; generally MemStore instances and -// their cleanup goroutines are intended to be long-lived and run for the lifetime -// of your application. -// -// There may be occasions though when your use of the MemStore is transient. -// An example is creating a new MemStore instance in a test function. In this -// scenario, the cleanup goroutine (which will run forever) will prevent the -// MemStore object from being garbage collected even after the test function -// has finished. You can prevent this by manually calling StopCleanup. -func (m *MemStore) StopCleanup() { - if m.stopCleanup != nil { - m.stopCleanup <- true - } -} - -func (m *MemStore) deleteExpired() { - now := time.Now().UnixNano() - m.mu.Lock() - for token, item := range m.items { - if now > item.expiration { - delete(m.items, token) - } - } - m.mu.Unlock() -} diff --git a/vendor/github.com/alexedwards/scs/v2/session.go b/vendor/github.com/alexedwards/scs/v2/session.go deleted file mode 100644 index 0cdc08a8fb250..0000000000000 --- a/vendor/github.com/alexedwards/scs/v2/session.go +++ /dev/null @@ -1,236 +0,0 @@ -package scs - -import ( - "bufio" - "bytes" - "log" - "net" - "net/http" - "time" - - "github.com/alexedwards/scs/v2/memstore" -) - -// Deprecated: Session is a backwards-compatible alias for SessionManager. -type Session = SessionManager - -// SessionManager holds the configuration settings for your sessions. -type SessionManager struct { - // IdleTimeout controls the maximum length of time a session can be inactive - // before it expires. For example, some applications may wish to set this so - // there is a timeout after 20 minutes of inactivity. By default IdleTimeout - // is not set and there is no inactivity timeout. - IdleTimeout time.Duration - - // Lifetime controls the maximum length of time that a session is valid for - // before it expires. The lifetime is an 'absolute expiry' which is set when - // the session is first created and does not change. The default value is 24 - // hours. - Lifetime time.Duration - - // Store controls the session store where the session data is persisted. - Store Store - - // Cookie contains the configuration settings for session cookies. - Cookie SessionCookie - - // Codec controls the encoder/decoder used to transform session data to a - // byte slice for use by the session store. By default session data is - // encoded/decoded using encoding/gob. - Codec Codec - - // ErrorFunc allows you to control behavior when an error is encountered by - // the LoadAndSave middleware. The default behavior is for a HTTP 500 - // "Internal Server Error" message to be sent to the client and the error - // logged using Go's standard logger. If a custom ErrorFunc is set, then - // control will be passed to this instead. A typical use would be to provide - // a function which logs the error and returns a customized HTML error page. - ErrorFunc func(http.ResponseWriter, *http.Request, error) - - // contextKey is the key used to set and retrieve the session data from a - // context.Context. It's automatically generated to ensure uniqueness. - contextKey contextKey -} - -// SessionCookie contains the configuration settings for session cookies. -type SessionCookie struct { - // Name sets the name of the session cookie. It should not contain - // whitespace, commas, colons, semicolons, backslashes, the equals sign or - // control characters as per RFC6265. The default cookie name is "session". - // If your application uses two different sessions, you must make sure that - // the cookie name for each is unique. - Name string - - // Domain sets the 'Domain' attribute on the session cookie. By default - // it will be set to the domain name that the cookie was issued from. - Domain string - - // HttpOnly sets the 'HttpOnly' attribute on the session cookie. The - // default value is true. - HttpOnly bool - - // Path sets the 'Path' attribute on the session cookie. The default value - // is "/". Passing the empty string "" will result in it being set to the - // path that the cookie was issued from. - Path string - - // Persist sets whether the session cookie should be persistent or not - // (i.e. whether it should be retained after a user closes their browser). - // The default value is true, which means that the session cookie will not - // be destroyed when the user closes their browser and the appropriate - // 'Expires' and 'MaxAge' values will be added to the session cookie. - Persist bool - - // SameSite controls the value of the 'SameSite' attribute on the session - // cookie. By default this is set to 'SameSite=Lax'. If you want no SameSite - // attribute or value in the session cookie then you should set this to 0. - SameSite http.SameSite - - // Secure sets the 'Secure' attribute on the session cookie. The default - // value is false. It's recommended that you set this to true and serve all - // requests over HTTPS in production environments. - // See https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Session_Management_Cheat_Sheet.md#transport-layer-security. - Secure bool -} - -// New returns a new session manager with the default options. It is safe for -// concurrent use. -func New() *SessionManager { - s := &SessionManager{ - IdleTimeout: 0, - Lifetime: 24 * time.Hour, - Store: memstore.New(), - Codec: GobCodec{}, - ErrorFunc: defaultErrorFunc, - contextKey: generateContextKey(), - Cookie: SessionCookie{ - Name: "session", - Domain: "", - HttpOnly: true, - Path: "/", - Persist: true, - Secure: false, - SameSite: http.SameSiteLaxMode, - }, - } - return s -} - -// Deprecated: NewSession is a backwards-compatible alias for New. Use the New -// function instead. -func NewSession() *SessionManager { - return New() -} - -// LoadAndSave provides middleware which automatically loads and saves session -// data for the current request, and communicates the session token to and from -// the client in a cookie. -func (s *SessionManager) LoadAndSave(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var token string - cookie, err := r.Cookie(s.Cookie.Name) - if err == nil { - token = cookie.Value - } - - ctx, err := s.Load(r.Context(), token) - if err != nil { - s.ErrorFunc(w, r, err) - return - } - - sr := r.WithContext(ctx) - bw := &bufferedResponseWriter{ResponseWriter: w} - next.ServeHTTP(bw, sr) - - if sr.MultipartForm != nil { - sr.MultipartForm.RemoveAll() - } - - switch s.Status(ctx) { - case Modified: - token, expiry, err := s.Commit(ctx) - if err != nil { - s.ErrorFunc(w, r, err) - return - } - s.writeSessionCookie(w, token, expiry) - case Destroyed: - s.writeSessionCookie(w, "", time.Time{}) - } - - if bw.code != 0 { - w.WriteHeader(bw.code) - } - w.Write(bw.buf.Bytes()) - }) -} - -func (s *SessionManager) writeSessionCookie(w http.ResponseWriter, token string, expiry time.Time) { - cookie := &http.Cookie{ - Name: s.Cookie.Name, - Value: token, - Path: s.Cookie.Path, - Domain: s.Cookie.Domain, - Secure: s.Cookie.Secure, - HttpOnly: s.Cookie.HttpOnly, - SameSite: s.Cookie.SameSite, - } - - if expiry.IsZero() { - cookie.Expires = time.Unix(1, 0) - cookie.MaxAge = -1 - } else if s.Cookie.Persist { - cookie.Expires = time.Unix(expiry.Unix()+1, 0) // Round up to the nearest second. - cookie.MaxAge = int(time.Until(expiry).Seconds() + 1) // Round up to the nearest second. - } - - w.Header().Add("Set-Cookie", cookie.String()) - addHeaderIfMissing(w, "Cache-Control", `no-cache="Set-Cookie"`) - addHeaderIfMissing(w, "Vary", "Cookie") - -} - -func addHeaderIfMissing(w http.ResponseWriter, key, value string) { - for _, h := range w.Header()[key] { - if h == value { - return - } - } - w.Header().Add(key, value) -} - -func defaultErrorFunc(w http.ResponseWriter, r *http.Request, err error) { - log.Output(2, err.Error()) - http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) -} - -type bufferedResponseWriter struct { - http.ResponseWriter - buf bytes.Buffer - code int - wroteHeader bool -} - -func (bw *bufferedResponseWriter) Write(b []byte) (int, error) { - return bw.buf.Write(b) -} - -func (bw *bufferedResponseWriter) WriteHeader(code int) { - if !bw.wroteHeader { - bw.code = code - bw.wroteHeader = true - } -} - -func (bw *bufferedResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { - hj := bw.ResponseWriter.(http.Hijacker) - return hj.Hijack() -} - -func (bw *bufferedResponseWriter) Push(target string, opts *http.PushOptions) error { - if pusher, ok := bw.ResponseWriter.(http.Pusher); ok { - return pusher.Push(target, opts) - } - return http.ErrNotSupported -} diff --git a/vendor/github.com/alexedwards/scs/v2/store.go b/vendor/github.com/alexedwards/scs/v2/store.go deleted file mode 100644 index 18448fd2af307..0000000000000 --- a/vendor/github.com/alexedwards/scs/v2/store.go +++ /dev/null @@ -1,25 +0,0 @@ -package scs - -import ( - "time" -) - -// Store is the interface for session stores. -type Store interface { - // Delete should remove the session token and corresponding data from the - // session store. If the token does not exist then Delete should be a no-op - // and return nil (not an error). - Delete(token string) (err error) - - // Find should return the data for a session token from the store. If the - // session token is not found or is expired, the found return value should - // be false (and the err return value should be nil). Similarly, tampered - // or malformed tokens should result in a found return value of false and a - // nil err value. The err return value should be used for system errors only. - Find(token string) (b []byte, found bool, err error) - - // Commit should add the session token and data to the store, with the given - // expiry time. If the session token already exists, then the data and - // expiry time should be overwritten. - Commit(token string, b []byte, expiry time.Time) (err error) -} diff --git a/vendor/github.com/gopherjs/gopherjs/LICENSE b/vendor/github.com/gopherjs/gopherjs/LICENSE deleted file mode 100644 index d496fef109260..0000000000000 --- a/vendor/github.com/gopherjs/gopherjs/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -Copyright (c) 2013 Richard Musiol. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/gopherjs/gopherjs/js/js.go b/vendor/github.com/gopherjs/gopherjs/js/js.go deleted file mode 100644 index 3fbf1d88c6098..0000000000000 --- a/vendor/github.com/gopherjs/gopherjs/js/js.go +++ /dev/null @@ -1,168 +0,0 @@ -// Package js provides functions for interacting with native JavaScript APIs. Calls to these functions are treated specially by GopherJS and translated directly to their corresponding JavaScript syntax. -// -// Use MakeWrapper to expose methods to JavaScript. When passing values directly, the following type conversions are performed: -// -// | Go type | JavaScript type | Conversions back to interface{} | -// | --------------------- | --------------------- | ------------------------------- | -// | bool | Boolean | bool | -// | integers and floats | Number | float64 | -// | string | String | string | -// | []int8 | Int8Array | []int8 | -// | []int16 | Int16Array | []int16 | -// | []int32, []int | Int32Array | []int | -// | []uint8 | Uint8Array | []uint8 | -// | []uint16 | Uint16Array | []uint16 | -// | []uint32, []uint | Uint32Array | []uint | -// | []float32 | Float32Array | []float32 | -// | []float64 | Float64Array | []float64 | -// | all other slices | Array | []interface{} | -// | arrays | see slice type | see slice type | -// | functions | Function | func(...interface{}) *js.Object | -// | time.Time | Date | time.Time | -// | - | instanceof Node | *js.Object | -// | maps, structs | instanceof Object | map[string]interface{} | -// -// Additionally, for a struct containing a *js.Object field, only the content of the field will be passed to JavaScript and vice versa. -package js - -// Object is a container for a native JavaScript object. Calls to its methods are treated specially by GopherJS and translated directly to their JavaScript syntax. A nil pointer to Object is equal to JavaScript's "null". Object can not be used as a map key. -type Object struct{ object *Object } - -// Get returns the object's property with the given key. -func (o *Object) Get(key string) *Object { return o.object.Get(key) } - -// Set assigns the value to the object's property with the given key. -func (o *Object) Set(key string, value interface{}) { o.object.Set(key, value) } - -// Delete removes the object's property with the given key. -func (o *Object) Delete(key string) { o.object.Delete(key) } - -// Length returns the object's "length" property, converted to int. -func (o *Object) Length() int { return o.object.Length() } - -// Index returns the i'th element of an array. -func (o *Object) Index(i int) *Object { return o.object.Index(i) } - -// SetIndex sets the i'th element of an array. -func (o *Object) SetIndex(i int, value interface{}) { o.object.SetIndex(i, value) } - -// Call calls the object's method with the given name. -func (o *Object) Call(name string, args ...interface{}) *Object { return o.object.Call(name, args...) } - -// Invoke calls the object itself. This will fail if it is not a function. -func (o *Object) Invoke(args ...interface{}) *Object { return o.object.Invoke(args...) } - -// New creates a new instance of this type object. This will fail if it not a function (constructor). -func (o *Object) New(args ...interface{}) *Object { return o.object.New(args...) } - -// Bool returns the object converted to bool according to JavaScript type conversions. -func (o *Object) Bool() bool { return o.object.Bool() } - -// String returns the object converted to string according to JavaScript type conversions. -func (o *Object) String() string { return o.object.String() } - -// Int returns the object converted to int according to JavaScript type conversions (parseInt). -func (o *Object) Int() int { return o.object.Int() } - -// Int64 returns the object converted to int64 according to JavaScript type conversions (parseInt). -func (o *Object) Int64() int64 { return o.object.Int64() } - -// Uint64 returns the object converted to uint64 according to JavaScript type conversions (parseInt). -func (o *Object) Uint64() uint64 { return o.object.Uint64() } - -// Float returns the object converted to float64 according to JavaScript type conversions (parseFloat). -func (o *Object) Float() float64 { return o.object.Float() } - -// Interface returns the object converted to interface{}. See table in package comment for details. -func (o *Object) Interface() interface{} { return o.object.Interface() } - -// Unsafe returns the object as an uintptr, which can be converted via unsafe.Pointer. Not intended for public use. -func (o *Object) Unsafe() uintptr { return o.object.Unsafe() } - -// Error encapsulates JavaScript errors. Those are turned into a Go panic and may be recovered, giving an *Error that holds the JavaScript error object. -type Error struct { - *Object -} - -// Error returns the message of the encapsulated JavaScript error object. -func (err *Error) Error() string { - return "JavaScript error: " + err.Get("message").String() -} - -// Stack returns the stack property of the encapsulated JavaScript error object. -func (err *Error) Stack() string { - return err.Get("stack").String() -} - -// Global gives JavaScript's global object ("window" for browsers and "GLOBAL" for Node.js). -var Global *Object - -// Module gives the value of the "module" variable set by Node.js. Hint: Set a module export with 'js.Module.Get("exports").Set("exportName", ...)'. -var Module *Object - -// Undefined gives the JavaScript value "undefined". -var Undefined *Object - -// Debugger gets compiled to JavaScript's "debugger;" statement. -func Debugger() {} - -// InternalObject returns the internal JavaScript object that represents i. Not intended for public use. -func InternalObject(i interface{}) *Object { - return nil -} - -// MakeFunc wraps a function and gives access to the values of JavaScript's "this" and "arguments" keywords. -func MakeFunc(fn func(this *Object, arguments []*Object) interface{}) *Object { - return Global.Call("$makeFunc", InternalObject(fn)) -} - -// Keys returns the keys of the given JavaScript object. -func Keys(o *Object) []string { - if o == nil || o == Undefined { - return nil - } - a := Global.Get("Object").Call("keys", o) - s := make([]string, a.Length()) - for i := 0; i < a.Length(); i++ { - s[i] = a.Index(i).String() - } - return s -} - -// MakeWrapper creates a JavaScript object which has wrappers for the exported methods of i. Use explicit getter and setter methods to expose struct fields to JavaScript. -func MakeWrapper(i interface{}) *Object { - v := InternalObject(i) - o := Global.Get("Object").New() - o.Set("__internal_object__", v) - methods := v.Get("constructor").Get("methods") - for i := 0; i < methods.Length(); i++ { - m := methods.Index(i) - if m.Get("pkg").String() != "" { // not exported - continue - } - o.Set(m.Get("name").String(), func(args ...*Object) *Object { - return Global.Call("$externalizeFunction", v.Get(m.Get("prop").String()), m.Get("typ"), true).Call("apply", v, args) - }) - } - return o -} - -// NewArrayBuffer creates a JavaScript ArrayBuffer from a byte slice. -func NewArrayBuffer(b []byte) *Object { - slice := InternalObject(b) - offset := slice.Get("$offset").Int() - length := slice.Get("$length").Int() - return slice.Get("$array").Get("buffer").Call("slice", offset, offset+length) -} - -// M is a simple map type. It is intended as a shorthand for JavaScript objects (before conversion). -type M map[string]interface{} - -// S is a simple slice type. It is intended as a shorthand for JavaScript arrays (before conversion). -type S []interface{} - -func init() { - // avoid dead code elimination - e := Error{} - _ = e -} diff --git a/vendor/github.com/jtolds/gls/LICENSE b/vendor/github.com/jtolds/gls/LICENSE deleted file mode 100644 index 9b4a822d92c5f..0000000000000 --- a/vendor/github.com/jtolds/gls/LICENSE +++ /dev/null @@ -1,18 +0,0 @@ -Copyright (c) 2013, Space Monkey, Inc. - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/jtolds/gls/README.md b/vendor/github.com/jtolds/gls/README.md deleted file mode 100644 index 4ebb692fb1899..0000000000000 --- a/vendor/github.com/jtolds/gls/README.md +++ /dev/null @@ -1,89 +0,0 @@ -gls -=== - -Goroutine local storage - -### IMPORTANT NOTE ### - -It is my duty to point you to https://blog.golang.org/context, which is how -Google solves all of the problems you'd perhaps consider using this package -for at scale. - -One downside to Google's approach is that *all* of your functions must have -a new first argument, but after clearing that hurdle everything else is much -better. - -If you aren't interested in this warning, read on. - -### Huhwaht? Why? ### - -Every so often, a thread shows up on the -[golang-nuts](https://groups.google.com/d/forum/golang-nuts) asking for some -form of goroutine-local-storage, or some kind of goroutine id, or some kind of -context. There are a few valid use cases for goroutine-local-storage, one of -the most prominent being log line context. One poster was interested in being -able to log an HTTP request context id in every log line in the same goroutine -as the incoming HTTP request, without having to change every library and -function call he was interested in logging. - -This would be pretty useful. Provided that you could get some kind of -goroutine-local-storage, you could call -[log.SetOutput](http://golang.org/pkg/log/#SetOutput) with your own logging -writer that checks goroutine-local-storage for some context information and -adds that context to your log lines. - -But alas, Andrew Gerrand's typically diplomatic answer to the question of -goroutine-local variables was: - -> We wouldn't even be having this discussion if thread local storage wasn't -> useful. But every feature comes at a cost, and in my opinion the cost of -> threadlocals far outweighs their benefits. They're just not a good fit for -> Go. - -So, yeah, that makes sense. That's a pretty good reason for why the language -won't support a specific and (relatively) unuseful feature that requires some -runtime changes, just for the sake of a little bit of log improvement. - -But does Go require runtime changes? - -### How it works ### - -Go has pretty fantastic introspective and reflective features, but one thing Go -doesn't give you is any kind of access to the stack pointer, or frame pointer, -or goroutine id, or anything contextual about your current stack. It gives you -access to your list of callers, but only along with program counters, which are -fixed at compile time. - -But it does give you the stack. - -So, we define 16 special functions and embed base-16 tags into the stack using -the call order of those 16 functions. Then, we can read our tags back out of -the stack looking at the callers list. - -We then use these tags as an index into a traditional map for implementing -this library. - -### What are people saying? ### - -"Wow, that's horrifying." - -"This is the most terrible thing I have seen in a very long time." - -"Where is it getting a context from? Is this serializing all the requests? -What the heck is the client being bound to? What are these tags? Why does he -need callers? Oh god no. No no no." - -### Docs ### - -Please see the docs at http://godoc.org/github.com/jtolds/gls - -### Related ### - -If you're okay relying on the string format of the current runtime stacktrace -including a unique goroutine id (not guaranteed by the spec or anything, but -very unlikely to change within a Go release), you might be able to squeeze -out a bit more performance by using this similar library, inspired by some -code Brad Fitzpatrick wrote for debugging his HTTP/2 library: -https://github.com/tylerb/gls (in contrast, jtolds/gls doesn't require -any knowledge of the string format of the runtime stacktrace, which -probably adds unnecessary overhead). diff --git a/vendor/github.com/jtolds/gls/context.go b/vendor/github.com/jtolds/gls/context.go deleted file mode 100644 index 618a171061335..0000000000000 --- a/vendor/github.com/jtolds/gls/context.go +++ /dev/null @@ -1,153 +0,0 @@ -// Package gls implements goroutine-local storage. -package gls - -import ( - "sync" -) - -var ( - mgrRegistry = make(map[*ContextManager]bool) - mgrRegistryMtx sync.RWMutex -) - -// Values is simply a map of key types to value types. Used by SetValues to -// set multiple values at once. -type Values map[interface{}]interface{} - -// ContextManager is the main entrypoint for interacting with -// Goroutine-local-storage. You can have multiple independent ContextManagers -// at any given time. ContextManagers are usually declared globally for a given -// class of context variables. You should use NewContextManager for -// construction. -type ContextManager struct { - mtx sync.Mutex - values map[uint]Values -} - -// NewContextManager returns a brand new ContextManager. It also registers the -// new ContextManager in the ContextManager registry which is used by the Go -// method. ContextManagers are typically defined globally at package scope. -func NewContextManager() *ContextManager { - mgr := &ContextManager{values: make(map[uint]Values)} - mgrRegistryMtx.Lock() - defer mgrRegistryMtx.Unlock() - mgrRegistry[mgr] = true - return mgr -} - -// Unregister removes a ContextManager from the global registry, used by the -// Go method. Only intended for use when you're completely done with a -// ContextManager. Use of Unregister at all is rare. -func (m *ContextManager) Unregister() { - mgrRegistryMtx.Lock() - defer mgrRegistryMtx.Unlock() - delete(mgrRegistry, m) -} - -// SetValues takes a collection of values and a function to call for those -// values to be set in. Anything further down the stack will have the set -// values available through GetValue. SetValues will add new values or replace -// existing values of the same key and will not mutate or change values for -// previous stack frames. -// SetValues is slow (makes a copy of all current and new values for the new -// gls-context) in order to reduce the amount of lookups GetValue requires. -func (m *ContextManager) SetValues(new_values Values, context_call func()) { - if len(new_values) == 0 { - context_call() - return - } - - mutated_keys := make([]interface{}, 0, len(new_values)) - mutated_vals := make(Values, len(new_values)) - - EnsureGoroutineId(func(gid uint) { - m.mtx.Lock() - state, found := m.values[gid] - if !found { - state = make(Values, len(new_values)) - m.values[gid] = state - } - m.mtx.Unlock() - - for key, new_val := range new_values { - mutated_keys = append(mutated_keys, key) - if old_val, ok := state[key]; ok { - mutated_vals[key] = old_val - } - state[key] = new_val - } - - defer func() { - if !found { - m.mtx.Lock() - delete(m.values, gid) - m.mtx.Unlock() - return - } - - for _, key := range mutated_keys { - if val, ok := mutated_vals[key]; ok { - state[key] = val - } else { - delete(state, key) - } - } - }() - - context_call() - }) -} - -// GetValue will return a previously set value, provided that the value was set -// by SetValues somewhere higher up the stack. If the value is not found, ok -// will be false. -func (m *ContextManager) GetValue(key interface{}) ( - value interface{}, ok bool) { - gid, ok := GetGoroutineId() - if !ok { - return nil, false - } - - m.mtx.Lock() - state, found := m.values[gid] - m.mtx.Unlock() - - if !found { - return nil, false - } - value, ok = state[key] - return value, ok -} - -func (m *ContextManager) getValues() Values { - gid, ok := GetGoroutineId() - if !ok { - return nil - } - m.mtx.Lock() - state, _ := m.values[gid] - m.mtx.Unlock() - return state -} - -// Go preserves ContextManager values and Goroutine-local-storage across new -// goroutine invocations. The Go method makes a copy of all existing values on -// all registered context managers and makes sure they are still set after -// kicking off the provided function in a new goroutine. If you don't use this -// Go method instead of the standard 'go' keyword, you will lose values in -// ContextManagers, as goroutines have brand new stacks. -func Go(cb func()) { - mgrRegistryMtx.RLock() - defer mgrRegistryMtx.RUnlock() - - for mgr := range mgrRegistry { - values := mgr.getValues() - if len(values) > 0 { - cb = func(mgr *ContextManager, cb func()) func() { - return func() { mgr.SetValues(values, cb) } - }(mgr, cb) - } - } - - go cb() -} diff --git a/vendor/github.com/jtolds/gls/gen_sym.go b/vendor/github.com/jtolds/gls/gen_sym.go deleted file mode 100644 index 7f615cce937dd..0000000000000 --- a/vendor/github.com/jtolds/gls/gen_sym.go +++ /dev/null @@ -1,21 +0,0 @@ -package gls - -import ( - "sync" -) - -var ( - keyMtx sync.Mutex - keyCounter uint64 -) - -// ContextKey is a throwaway value you can use as a key to a ContextManager -type ContextKey struct{ id uint64 } - -// GenSym will return a brand new, never-before-used ContextKey -func GenSym() ContextKey { - keyMtx.Lock() - defer keyMtx.Unlock() - keyCounter += 1 - return ContextKey{id: keyCounter} -} diff --git a/vendor/github.com/jtolds/gls/gid.go b/vendor/github.com/jtolds/gls/gid.go deleted file mode 100644 index c16bf3a554f97..0000000000000 --- a/vendor/github.com/jtolds/gls/gid.go +++ /dev/null @@ -1,25 +0,0 @@ -package gls - -var ( - stackTagPool = &idPool{} -) - -// Will return this goroutine's identifier if set. If you always need a -// goroutine identifier, you should use EnsureGoroutineId which will make one -// if there isn't one already. -func GetGoroutineId() (gid uint, ok bool) { - return readStackTag() -} - -// Will call cb with the current goroutine identifier. If one hasn't already -// been generated, one will be created and set first. The goroutine identifier -// might be invalid after cb returns. -func EnsureGoroutineId(cb func(gid uint)) { - if gid, ok := readStackTag(); ok { - cb(gid) - return - } - gid := stackTagPool.Acquire() - defer stackTagPool.Release(gid) - addStackTag(gid, func() { cb(gid) }) -} diff --git a/vendor/github.com/jtolds/gls/id_pool.go b/vendor/github.com/jtolds/gls/id_pool.go deleted file mode 100644 index b7974ae0026e7..0000000000000 --- a/vendor/github.com/jtolds/gls/id_pool.go +++ /dev/null @@ -1,34 +0,0 @@ -package gls - -// though this could probably be better at keeping ids smaller, the goal of -// this class is to keep a registry of the smallest unique integer ids -// per-process possible - -import ( - "sync" -) - -type idPool struct { - mtx sync.Mutex - released []uint - max_id uint -} - -func (p *idPool) Acquire() (id uint) { - p.mtx.Lock() - defer p.mtx.Unlock() - if len(p.released) > 0 { - id = p.released[len(p.released)-1] - p.released = p.released[:len(p.released)-1] - return id - } - id = p.max_id - p.max_id++ - return id -} - -func (p *idPool) Release(id uint) { - p.mtx.Lock() - defer p.mtx.Unlock() - p.released = append(p.released, id) -} diff --git a/vendor/github.com/jtolds/gls/stack_tags.go b/vendor/github.com/jtolds/gls/stack_tags.go deleted file mode 100644 index 37bbd3347ad58..0000000000000 --- a/vendor/github.com/jtolds/gls/stack_tags.go +++ /dev/null @@ -1,147 +0,0 @@ -package gls - -// so, basically, we're going to encode integer tags in base-16 on the stack - -const ( - bitWidth = 4 - stackBatchSize = 16 -) - -var ( - pc_lookup = make(map[uintptr]int8, 17) - mark_lookup [16]func(uint, func()) -) - -func init() { - setEntries := func(f func(uint, func()), v int8) { - var ptr uintptr - f(0, func() { - ptr = findPtr() - }) - pc_lookup[ptr] = v - if v >= 0 { - mark_lookup[v] = f - } - } - setEntries(github_com_jtolds_gls_markS, -0x1) - setEntries(github_com_jtolds_gls_mark0, 0x0) - setEntries(github_com_jtolds_gls_mark1, 0x1) - setEntries(github_com_jtolds_gls_mark2, 0x2) - setEntries(github_com_jtolds_gls_mark3, 0x3) - setEntries(github_com_jtolds_gls_mark4, 0x4) - setEntries(github_com_jtolds_gls_mark5, 0x5) - setEntries(github_com_jtolds_gls_mark6, 0x6) - setEntries(github_com_jtolds_gls_mark7, 0x7) - setEntries(github_com_jtolds_gls_mark8, 0x8) - setEntries(github_com_jtolds_gls_mark9, 0x9) - setEntries(github_com_jtolds_gls_markA, 0xa) - setEntries(github_com_jtolds_gls_markB, 0xb) - setEntries(github_com_jtolds_gls_markC, 0xc) - setEntries(github_com_jtolds_gls_markD, 0xd) - setEntries(github_com_jtolds_gls_markE, 0xe) - setEntries(github_com_jtolds_gls_markF, 0xf) -} - -func addStackTag(tag uint, context_call func()) { - if context_call == nil { - return - } - github_com_jtolds_gls_markS(tag, context_call) -} - -// these private methods are named this horrendous name so gopherjs support -// is easier. it shouldn't add any runtime cost in non-js builds. - -//go:noinline -func github_com_jtolds_gls_markS(tag uint, cb func()) { _m(tag, cb) } - -//go:noinline -func github_com_jtolds_gls_mark0(tag uint, cb func()) { _m(tag, cb) } - -//go:noinline -func github_com_jtolds_gls_mark1(tag uint, cb func()) { _m(tag, cb) } - -//go:noinline -func github_com_jtolds_gls_mark2(tag uint, cb func()) { _m(tag, cb) } - -//go:noinline -func github_com_jtolds_gls_mark3(tag uint, cb func()) { _m(tag, cb) } - -//go:noinline -func github_com_jtolds_gls_mark4(tag uint, cb func()) { _m(tag, cb) } - -//go:noinline -func github_com_jtolds_gls_mark5(tag uint, cb func()) { _m(tag, cb) } - -//go:noinline -func github_com_jtolds_gls_mark6(tag uint, cb func()) { _m(tag, cb) } - -//go:noinline -func github_com_jtolds_gls_mark7(tag uint, cb func()) { _m(tag, cb) } - -//go:noinline -func github_com_jtolds_gls_mark8(tag uint, cb func()) { _m(tag, cb) } - -//go:noinline -func github_com_jtolds_gls_mark9(tag uint, cb func()) { _m(tag, cb) } - -//go:noinline -func github_com_jtolds_gls_markA(tag uint, cb func()) { _m(tag, cb) } - -//go:noinline -func github_com_jtolds_gls_markB(tag uint, cb func()) { _m(tag, cb) } - -//go:noinline -func github_com_jtolds_gls_markC(tag uint, cb func()) { _m(tag, cb) } - -//go:noinline -func github_com_jtolds_gls_markD(tag uint, cb func()) { _m(tag, cb) } - -//go:noinline -func github_com_jtolds_gls_markE(tag uint, cb func()) { _m(tag, cb) } - -//go:noinline -func github_com_jtolds_gls_markF(tag uint, cb func()) { _m(tag, cb) } - -func _m(tag_remainder uint, cb func()) { - if tag_remainder == 0 { - cb() - } else { - mark_lookup[tag_remainder&0xf](tag_remainder>>bitWidth, cb) - } -} - -func readStackTag() (tag uint, ok bool) { - var current_tag uint - offset := 0 - for { - batch, next_offset := getStack(offset, stackBatchSize) - for _, pc := range batch { - val, ok := pc_lookup[pc] - if !ok { - continue - } - if val < 0 { - return current_tag, true - } - current_tag <<= bitWidth - current_tag += uint(val) - } - if next_offset == 0 { - break - } - offset = next_offset - } - return 0, false -} - -func (m *ContextManager) preventInlining() { - // dunno if findPtr or getStack are likely to get inlined in a future release - // of go, but if they are inlined and their callers are inlined, that could - // hork some things. let's do our best to explain to the compiler that we - // really don't want those two functions inlined by saying they could change - // at any time. assumes preventInlining doesn't get compiled out. - // this whole thing is probably overkill. - findPtr = m.values[0][0].(func() uintptr) - getStack = m.values[0][1].(func(int, int) ([]uintptr, int)) -} diff --git a/vendor/github.com/jtolds/gls/stack_tags_js.go b/vendor/github.com/jtolds/gls/stack_tags_js.go deleted file mode 100644 index c4e8b801d31d0..0000000000000 --- a/vendor/github.com/jtolds/gls/stack_tags_js.go +++ /dev/null @@ -1,75 +0,0 @@ -// +build js - -package gls - -// This file is used for GopherJS builds, which don't have normal runtime -// stack trace support - -import ( - "strconv" - "strings" - - "github.com/gopherjs/gopherjs/js" -) - -const ( - jsFuncNamePrefix = "github_com_jtolds_gls_mark" -) - -func jsMarkStack() (f []uintptr) { - lines := strings.Split( - js.Global.Get("Error").New().Get("stack").String(), "\n") - f = make([]uintptr, 0, len(lines)) - for i, line := range lines { - line = strings.TrimSpace(line) - if line == "" { - continue - } - if i == 0 { - if line != "Error" { - panic("didn't understand js stack trace") - } - continue - } - fields := strings.Fields(line) - if len(fields) < 2 || fields[0] != "at" { - panic("didn't understand js stack trace") - } - - pos := strings.Index(fields[1], jsFuncNamePrefix) - if pos < 0 { - continue - } - pos += len(jsFuncNamePrefix) - if pos >= len(fields[1]) { - panic("didn't understand js stack trace") - } - char := string(fields[1][pos]) - switch char { - case "S": - f = append(f, uintptr(0)) - default: - val, err := strconv.ParseUint(char, 16, 8) - if err != nil { - panic("didn't understand js stack trace") - } - f = append(f, uintptr(val)+1) - } - } - return f -} - -// variables to prevent inlining -var ( - findPtr = func() uintptr { - funcs := jsMarkStack() - if len(funcs) == 0 { - panic("failed to find function pointer") - } - return funcs[0] - } - - getStack = func(offset, amount int) (stack []uintptr, next_offset int) { - return jsMarkStack(), 0 - } -) diff --git a/vendor/github.com/jtolds/gls/stack_tags_main.go b/vendor/github.com/jtolds/gls/stack_tags_main.go deleted file mode 100644 index 4da89e44f8e8d..0000000000000 --- a/vendor/github.com/jtolds/gls/stack_tags_main.go +++ /dev/null @@ -1,30 +0,0 @@ -// +build !js - -package gls - -// This file is used for standard Go builds, which have the expected runtime -// support - -import ( - "runtime" -) - -var ( - findPtr = func() uintptr { - var pc [1]uintptr - n := runtime.Callers(4, pc[:]) - if n != 1 { - panic("failed to find function pointer") - } - return pc[0] - } - - getStack = func(offset, amount int) (stack []uintptr, next_offset int) { - stack = make([]uintptr, amount) - stack = stack[:runtime.Callers(offset, stack)] - if len(stack) < amount { - return stack, 0 - } - return stack, offset + len(stack) - } -) diff --git a/vendor/github.com/smartystreets/assertions/.gitignore b/vendor/github.com/smartystreets/assertions/.gitignore deleted file mode 100644 index 1f088e844d480..0000000000000 --- a/vendor/github.com/smartystreets/assertions/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -/.idea -/coverage.* -.DS_Store -*.iml diff --git a/vendor/github.com/smartystreets/assertions/.travis.yml b/vendor/github.com/smartystreets/assertions/.travis.yml deleted file mode 100644 index d4e3e1f0fb8dc..0000000000000 --- a/vendor/github.com/smartystreets/assertions/.travis.yml +++ /dev/null @@ -1,23 +0,0 @@ -dist: bionic - -language: go - -go: - - 1.x - -env: - - GO111MODULE=on - -script: - - make build - -after_success: - - bash <(curl -s https://codecov.io/bash) - -git: - depth: 1 - -cache: - directories: - - $HOME/.cache/go-build - - $HOME/gopath/pkg/mod diff --git a/vendor/github.com/smartystreets/assertions/CONTRIBUTING.md b/vendor/github.com/smartystreets/assertions/CONTRIBUTING.md deleted file mode 100644 index 1820ecb331011..0000000000000 --- a/vendor/github.com/smartystreets/assertions/CONTRIBUTING.md +++ /dev/null @@ -1,12 +0,0 @@ -# Contributing - -In general, the code posted to the [SmartyStreets github organization](https://github.com/smartystreets) is created to solve specific problems at SmartyStreets that are ancillary to our core products in the address verification industry and may or may not be useful to other organizations or developers. Our reason for posting said code isn't necessarily to solicit feedback or contributions from the community but more as a showcase of some of the approaches to solving problems we have adopted. - -Having stated that, we do consider issues raised by other githubbers as well as contributions submitted via pull requests. When submitting such a pull request, please follow these guidelines: - -- _Look before you leap:_ If the changes you plan to make are significant, it's in everyone's best interest for you to discuss them with a SmartyStreets team member prior to opening a pull request. -- _License and ownership:_ If modifying the `LICENSE.md` file, limit your changes to fixing typographical mistakes. Do NOT modify the actual terms in the license or the copyright by **SmartyStreets, LLC**. Code submitted to SmartyStreets projects becomes property of SmartyStreets and must be compatible with the associated license. -- _Testing:_ If the code you are submitting resides in packages/modules covered by automated tests, be sure to add passing tests that cover your changes and assert expected behavior and state. Submit the additional test cases as part of your change set. -- _Style:_ Match your approach to **naming** and **formatting** with the surrounding code. Basically, the code you submit shouldn't stand out. - - "Naming" refers to such constructs as variables, methods, functions, classes, structs, interfaces, packages, modules, directories, files, etc... - - "Formatting" refers to such constructs as whitespace, horizontal line length, vertical function length, vertical file length, indentation, curly braces, etc... diff --git a/vendor/github.com/smartystreets/assertions/LICENSE.md b/vendor/github.com/smartystreets/assertions/LICENSE.md deleted file mode 100644 index 8ea6f945521d7..0000000000000 --- a/vendor/github.com/smartystreets/assertions/LICENSE.md +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2016 SmartyStreets, LLC - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - -NOTE: Various optional and subordinate components carry their own licensing -requirements and restrictions. Use of those components is subject to the terms -and conditions outlined the respective license of each component. diff --git a/vendor/github.com/smartystreets/assertions/Makefile b/vendor/github.com/smartystreets/assertions/Makefile deleted file mode 100644 index 5c27b7ba0ddc4..0000000000000 --- a/vendor/github.com/smartystreets/assertions/Makefile +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/make -f - -test: fmt - go test -timeout=1s -race -cover -short -count=1 ./... - -fmt: - go fmt ./... - -compile: - go build ./... - -build: test compile - -.PHONY: test compile build diff --git a/vendor/github.com/smartystreets/assertions/README.md b/vendor/github.com/smartystreets/assertions/README.md deleted file mode 100644 index 10c8d20138fdb..0000000000000 --- a/vendor/github.com/smartystreets/assertions/README.md +++ /dev/null @@ -1,4 +0,0 @@ -[![Build Status](https://travis-ci.org/smartystreets/assertions.svg?branch=master)](https://travis-ci.org/smartystreets/assertions) -[![Code Coverage](https://codecov.io/gh/smartystreets/assertions/branch/master/graph/badge.svg)](https://codecov.io/gh/smartystreets/assertions) -[![Go Report Card](https://goreportcard.com/badge/github.com/smartystreets/assertions)](https://goreportcard.com/report/github.com/smartystreets/assertions) -[![GoDoc](https://godoc.org/github.com/smartystreets/assertions?status.svg)](http://godoc.org/github.com/smartystreets/assertions) diff --git a/vendor/github.com/smartystreets/assertions/collections.go b/vendor/github.com/smartystreets/assertions/collections.go deleted file mode 100644 index b534d4bafab7c..0000000000000 --- a/vendor/github.com/smartystreets/assertions/collections.go +++ /dev/null @@ -1,244 +0,0 @@ -package assertions - -import ( - "fmt" - "reflect" - - "github.com/smartystreets/assertions/internal/oglematchers" -) - -// ShouldContain receives exactly two parameters. The first is a slice and the -// second is a proposed member. Membership is determined using ShouldEqual. -func ShouldContain(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - if matchError := oglematchers.Contains(expected[0]).Matches(actual); matchError != nil { - typeName := reflect.TypeOf(actual) - - if fmt.Sprintf("%v", matchError) == "which is not a slice or array" { - return fmt.Sprintf(shouldHaveBeenAValidCollection, typeName) - } - return fmt.Sprintf(shouldHaveContained, typeName, expected[0]) - } - return success -} - -// ShouldNotContain receives exactly two parameters. The first is a slice and the -// second is a proposed member. Membership is determinied using ShouldEqual. -func ShouldNotContain(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - typeName := reflect.TypeOf(actual) - - if matchError := oglematchers.Contains(expected[0]).Matches(actual); matchError != nil { - if fmt.Sprintf("%v", matchError) == "which is not a slice or array" { - return fmt.Sprintf(shouldHaveBeenAValidCollection, typeName) - } - return success - } - return fmt.Sprintf(shouldNotHaveContained, typeName, expected[0]) -} - -// ShouldContainKey receives exactly two parameters. The first is a map and the -// second is a proposed key. Keys are compared with a simple '=='. -func ShouldContainKey(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - keys, isMap := mapKeys(actual) - if !isMap { - return fmt.Sprintf(shouldHaveBeenAValidMap, reflect.TypeOf(actual)) - } - - if !keyFound(keys, expected[0]) { - return fmt.Sprintf(shouldHaveContainedKey, reflect.TypeOf(actual), expected) - } - - return "" -} - -// ShouldNotContainKey receives exactly two parameters. The first is a map and the -// second is a proposed absent key. Keys are compared with a simple '=='. -func ShouldNotContainKey(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - keys, isMap := mapKeys(actual) - if !isMap { - return fmt.Sprintf(shouldHaveBeenAValidMap, reflect.TypeOf(actual)) - } - - if keyFound(keys, expected[0]) { - return fmt.Sprintf(shouldNotHaveContainedKey, reflect.TypeOf(actual), expected) - } - - return "" -} - -func mapKeys(m interface{}) ([]reflect.Value, bool) { - value := reflect.ValueOf(m) - if value.Kind() != reflect.Map { - return nil, false - } - return value.MapKeys(), true -} -func keyFound(keys []reflect.Value, expectedKey interface{}) bool { - found := false - for _, key := range keys { - if key.Interface() == expectedKey { - found = true - } - } - return found -} - -// ShouldBeIn receives at least 2 parameters. The first is a proposed member of the collection -// that is passed in either as the second parameter, or of the collection that is comprised -// of all the remaining parameters. This assertion ensures that the proposed member is in -// the collection (using ShouldEqual). -func ShouldBeIn(actual interface{}, expected ...interface{}) string { - if fail := atLeast(1, expected); fail != success { - return fail - } - - if len(expected) == 1 { - return shouldBeIn(actual, expected[0]) - } - return shouldBeIn(actual, expected) -} -func shouldBeIn(actual interface{}, expected interface{}) string { - if matchError := oglematchers.Contains(actual).Matches(expected); matchError != nil { - return fmt.Sprintf(shouldHaveBeenIn, actual, reflect.TypeOf(expected)) - } - return success -} - -// ShouldNotBeIn receives at least 2 parameters. The first is a proposed member of the collection -// that is passed in either as the second parameter, or of the collection that is comprised -// of all the remaining parameters. This assertion ensures that the proposed member is NOT in -// the collection (using ShouldEqual). -func ShouldNotBeIn(actual interface{}, expected ...interface{}) string { - if fail := atLeast(1, expected); fail != success { - return fail - } - - if len(expected) == 1 { - return shouldNotBeIn(actual, expected[0]) - } - return shouldNotBeIn(actual, expected) -} -func shouldNotBeIn(actual interface{}, expected interface{}) string { - if matchError := oglematchers.Contains(actual).Matches(expected); matchError == nil { - return fmt.Sprintf(shouldNotHaveBeenIn, actual, reflect.TypeOf(expected)) - } - return success -} - -// ShouldBeEmpty receives a single parameter (actual) and determines whether or not -// calling len(actual) would return `0`. It obeys the rules specified by the len -// function for determining length: http://golang.org/pkg/builtin/#len -func ShouldBeEmpty(actual interface{}, expected ...interface{}) string { - if fail := need(0, expected); fail != success { - return fail - } - - if actual == nil { - return success - } - - value := reflect.ValueOf(actual) - switch value.Kind() { - case reflect.Slice: - if value.Len() == 0 { - return success - } - case reflect.Chan: - if value.Len() == 0 { - return success - } - case reflect.Map: - if value.Len() == 0 { - return success - } - case reflect.String: - if value.Len() == 0 { - return success - } - case reflect.Ptr: - elem := value.Elem() - kind := elem.Kind() - if (kind == reflect.Slice || kind == reflect.Array) && elem.Len() == 0 { - return success - } - } - - return fmt.Sprintf(shouldHaveBeenEmpty, actual) -} - -// ShouldNotBeEmpty receives a single parameter (actual) and determines whether or not -// calling len(actual) would return a value greater than zero. It obeys the rules -// specified by the `len` function for determining length: http://golang.org/pkg/builtin/#len -func ShouldNotBeEmpty(actual interface{}, expected ...interface{}) string { - if fail := need(0, expected); fail != success { - return fail - } - - if empty := ShouldBeEmpty(actual, expected...); empty != success { - return success - } - return fmt.Sprintf(shouldNotHaveBeenEmpty, actual) -} - -// ShouldHaveLength receives 2 parameters. The first is a collection to check -// the length of, the second being the expected length. It obeys the rules -// specified by the len function for determining length: -// http://golang.org/pkg/builtin/#len -func ShouldHaveLength(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - var expectedLen int64 - lenValue := reflect.ValueOf(expected[0]) - switch lenValue.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - expectedLen = lenValue.Int() - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - expectedLen = int64(lenValue.Uint()) - default: - return fmt.Sprintf(shouldHaveBeenAValidInteger, reflect.TypeOf(expected[0])) - } - - if expectedLen < 0 { - return fmt.Sprintf(shouldHaveBeenAValidLength, expected[0]) - } - - value := reflect.ValueOf(actual) - switch value.Kind() { - case reflect.Slice, - reflect.Chan, - reflect.Map, - reflect.String: - if int64(value.Len()) == expectedLen { - return success - } else { - return fmt.Sprintf(shouldHaveHadLength, expectedLen, value.Len(), actual) - } - case reflect.Ptr: - elem := value.Elem() - kind := elem.Kind() - if kind == reflect.Slice || kind == reflect.Array { - if int64(elem.Len()) == expectedLen { - return success - } else { - return fmt.Sprintf(shouldHaveHadLength, expectedLen, elem.Len(), actual) - } - } - } - return fmt.Sprintf(shouldHaveBeenAValidCollection, reflect.TypeOf(actual)) -} diff --git a/vendor/github.com/smartystreets/assertions/doc.go b/vendor/github.com/smartystreets/assertions/doc.go deleted file mode 100644 index ba30a9261ac96..0000000000000 --- a/vendor/github.com/smartystreets/assertions/doc.go +++ /dev/null @@ -1,109 +0,0 @@ -// Package assertions contains the implementations for all assertions which -// are referenced in goconvey's `convey` package -// (github.com/smartystreets/goconvey/convey) and gunit (github.com/smartystreets/gunit) -// for use with the So(...) method. -// They can also be used in traditional Go test functions and even in -// applications. -// -// https://smartystreets.com -// -// Many of the assertions lean heavily on work done by Aaron Jacobs in his excellent oglematchers library. -// (https://github.com/jacobsa/oglematchers) -// The ShouldResemble assertion leans heavily on work done by Daniel Jacques in his very helpful go-render library. -// (https://github.com/luci/go-render) -package assertions - -import ( - "fmt" - "runtime" -) - -// By default we use a no-op serializer. The actual Serializer provides a JSON -// representation of failure results on selected assertions so the goconvey -// web UI can display a convenient diff. -var serializer Serializer = new(noopSerializer) - -// GoConveyMode provides control over JSON serialization of failures. When -// using the assertions in this package from the convey package JSON results -// are very helpful and can be rendered in a DIFF view. In that case, this function -// will be called with a true value to enable the JSON serialization. By default, -// the assertions in this package will not serializer a JSON result, making -// standalone usage more convenient. -func GoConveyMode(yes bool) { - if yes { - serializer = newSerializer() - } else { - serializer = new(noopSerializer) - } -} - -type testingT interface { - Error(args ...interface{}) -} - -type Assertion struct { - t testingT - failed bool -} - -// New swallows the *testing.T struct and prints failed assertions using t.Error. -// Example: assertions.New(t).So(1, should.Equal, 1) -func New(t testingT) *Assertion { - return &Assertion{t: t} -} - -// Failed reports whether any calls to So (on this Assertion instance) have failed. -func (this *Assertion) Failed() bool { - return this.failed -} - -// So calls the standalone So function and additionally, calls t.Error in failure scenarios. -func (this *Assertion) So(actual interface{}, assert assertion, expected ...interface{}) bool { - ok, result := So(actual, assert, expected...) - if !ok { - this.failed = true - _, file, line, _ := runtime.Caller(1) - this.t.Error(fmt.Sprintf("\n%s:%d\n%s", file, line, result)) - } - return ok -} - -// So is a convenience function (as opposed to an inconvenience function?) -// for running assertions on arbitrary arguments in any context, be it for testing or even -// application logging. It allows you to perform assertion-like behavior (and get nicely -// formatted messages detailing discrepancies) but without the program blowing up or panicking. -// All that is required is to import this package and call `So` with one of the assertions -// exported by this package as the second parameter. -// The first return parameter is a boolean indicating if the assertion was true. The second -// return parameter is the well-formatted message showing why an assertion was incorrect, or -// blank if the assertion was correct. -// -// Example: -// -// if ok, message := So(x, ShouldBeGreaterThan, y); !ok { -// log.Println(message) -// } -// -// For an alternative implementation of So (that provides more flexible return options) -// see the `So` function in the package at github.com/smartystreets/assertions/assert. -func So(actual interface{}, assert assertion, expected ...interface{}) (bool, string) { - if result := so(actual, assert, expected...); len(result) == 0 { - return true, result - } else { - return false, result - } -} - -// so is like So, except that it only returns the string message, which is blank if the -// assertion passed. Used to facilitate testing. -func so(actual interface{}, assert func(interface{}, ...interface{}) string, expected ...interface{}) string { - return assert(actual, expected...) -} - -// assertion is an alias for a function with a signature that the So() -// function can handle. Any future or custom assertions should conform to this -// method signature. The return value should be an empty string if the assertion -// passes and a well-formed failure message if not. -type assertion func(actual interface{}, expected ...interface{}) string - -//////////////////////////////////////////////////////////////////////////// diff --git a/vendor/github.com/smartystreets/assertions/equal_method.go b/vendor/github.com/smartystreets/assertions/equal_method.go deleted file mode 100644 index c4fc38fab5e77..0000000000000 --- a/vendor/github.com/smartystreets/assertions/equal_method.go +++ /dev/null @@ -1,75 +0,0 @@ -package assertions - -import "reflect" - -type equalityMethodSpecification struct { - a interface{} - b interface{} - - aType reflect.Type - bType reflect.Type - - equalMethod reflect.Value -} - -func newEqualityMethodSpecification(a, b interface{}) *equalityMethodSpecification { - return &equalityMethodSpecification{ - a: a, - b: b, - } -} - -func (this *equalityMethodSpecification) IsSatisfied() bool { - if !this.bothAreSameType() { - return false - } - if !this.typeHasEqualMethod() { - return false - } - if !this.equalMethodReceivesSameTypeForComparison() { - return false - } - if !this.equalMethodReturnsBool() { - return false - } - return true -} - -func (this *equalityMethodSpecification) bothAreSameType() bool { - this.aType = reflect.TypeOf(this.a) - if this.aType == nil { - return false - } - if this.aType.Kind() == reflect.Ptr { - this.aType = this.aType.Elem() - } - this.bType = reflect.TypeOf(this.b) - return this.aType == this.bType -} -func (this *equalityMethodSpecification) typeHasEqualMethod() bool { - aInstance := reflect.ValueOf(this.a) - this.equalMethod = aInstance.MethodByName("Equal") - return this.equalMethod != reflect.Value{} -} - -func (this *equalityMethodSpecification) equalMethodReceivesSameTypeForComparison() bool { - signature := this.equalMethod.Type() - return signature.NumIn() == 1 && signature.In(0) == this.aType -} - -func (this *equalityMethodSpecification) equalMethodReturnsBool() bool { - signature := this.equalMethod.Type() - return signature.NumOut() == 1 && signature.Out(0) == reflect.TypeOf(true) -} - -func (this *equalityMethodSpecification) AreEqual() bool { - a := reflect.ValueOf(this.a) - b := reflect.ValueOf(this.b) - return areEqual(a, b) && areEqual(b, a) -} -func areEqual(receiver reflect.Value, argument reflect.Value) bool { - equalMethod := receiver.MethodByName("Equal") - argumentList := []reflect.Value{argument} - result := equalMethod.Call(argumentList) - return result[0].Bool() -} diff --git a/vendor/github.com/smartystreets/assertions/equality.go b/vendor/github.com/smartystreets/assertions/equality.go deleted file mode 100644 index 37a49f4e255a5..0000000000000 --- a/vendor/github.com/smartystreets/assertions/equality.go +++ /dev/null @@ -1,331 +0,0 @@ -package assertions - -import ( - "encoding/json" - "errors" - "fmt" - "math" - "reflect" - "strings" - - "github.com/smartystreets/assertions/internal/go-render/render" - "github.com/smartystreets/assertions/internal/oglematchers" -) - -// ShouldEqual receives exactly two parameters and does an equality check -// using the following semantics: -// 1. If the expected and actual values implement an Equal method in the form -// `func (this T) Equal(that T) bool` then call the method. If true, they are equal. -// 2. The expected and actual values are judged equal or not by oglematchers.Equals. -func ShouldEqual(actual interface{}, expected ...interface{}) string { - if message := need(1, expected); message != success { - return message - } - return shouldEqual(actual, expected[0]) -} -func shouldEqual(actual, expected interface{}) (message string) { - defer func() { - if r := recover(); r != nil { - message = serializer.serialize(expected, actual, composeEqualityMismatchMessage(expected, actual)) - } - }() - - if spec := newEqualityMethodSpecification(expected, actual); spec.IsSatisfied() && spec.AreEqual() { - return success - } else if matchError := oglematchers.Equals(expected).Matches(actual); matchError == nil { - return success - } - - return serializer.serialize(expected, actual, composeEqualityMismatchMessage(expected, actual)) -} -func composeEqualityMismatchMessage(expected, actual interface{}) string { - var ( - renderedExpected = fmt.Sprintf("%v", expected) - renderedActual = fmt.Sprintf("%v", actual) - ) - - if renderedExpected != renderedActual { - return fmt.Sprintf(shouldHaveBeenEqual+composePrettyDiff(renderedExpected, renderedActual), expected, actual) - } else if reflect.TypeOf(expected) != reflect.TypeOf(actual) { - return fmt.Sprintf(shouldHaveBeenEqualTypeMismatch, expected, expected, actual, actual) - } else { - return fmt.Sprintf(shouldHaveBeenEqualNoResemblance, renderedExpected) - } -} - -// ShouldNotEqual receives exactly two parameters and does an inequality check. -// See ShouldEqual for details on how equality is determined. -func ShouldNotEqual(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } else if ShouldEqual(actual, expected[0]) == success { - return fmt.Sprintf(shouldNotHaveBeenEqual, actual, expected[0]) - } - return success -} - -// ShouldAlmostEqual makes sure that two parameters are close enough to being equal. -// The acceptable delta may be specified with a third argument, -// or a very small default delta will be used. -func ShouldAlmostEqual(actual interface{}, expected ...interface{}) string { - actualFloat, expectedFloat, deltaFloat, err := cleanAlmostEqualInput(actual, expected...) - - if err != "" { - return err - } - - if math.Abs(actualFloat-expectedFloat) <= deltaFloat { - return success - } else { - return fmt.Sprintf(shouldHaveBeenAlmostEqual, actualFloat, expectedFloat) - } -} - -// ShouldNotAlmostEqual is the inverse of ShouldAlmostEqual -func ShouldNotAlmostEqual(actual interface{}, expected ...interface{}) string { - actualFloat, expectedFloat, deltaFloat, err := cleanAlmostEqualInput(actual, expected...) - - if err != "" { - return err - } - - if math.Abs(actualFloat-expectedFloat) > deltaFloat { - return success - } else { - return fmt.Sprintf(shouldHaveNotBeenAlmostEqual, actualFloat, expectedFloat) - } -} - -func cleanAlmostEqualInput(actual interface{}, expected ...interface{}) (float64, float64, float64, string) { - deltaFloat := 0.0000000001 - - if len(expected) == 0 { - return 0.0, 0.0, 0.0, "This assertion requires exactly one comparison value and an optional delta (you provided neither)" - } else if len(expected) == 2 { - delta, err := getFloat(expected[1]) - - if err != nil { - return 0.0, 0.0, 0.0, "The delta value " + err.Error() - } - - deltaFloat = delta - } else if len(expected) > 2 { - return 0.0, 0.0, 0.0, "This assertion requires exactly one comparison value and an optional delta (you provided more values)" - } - - actualFloat, err := getFloat(actual) - if err != nil { - return 0.0, 0.0, 0.0, "The actual value " + err.Error() - } - - expectedFloat, err := getFloat(expected[0]) - if err != nil { - return 0.0, 0.0, 0.0, "The comparison value " + err.Error() - } - - return actualFloat, expectedFloat, deltaFloat, "" -} - -// returns the float value of any real number, or error if it is not a numerical type -func getFloat(num interface{}) (float64, error) { - numValue := reflect.ValueOf(num) - numKind := numValue.Kind() - - if numKind == reflect.Int || - numKind == reflect.Int8 || - numKind == reflect.Int16 || - numKind == reflect.Int32 || - numKind == reflect.Int64 { - return float64(numValue.Int()), nil - } else if numKind == reflect.Uint || - numKind == reflect.Uint8 || - numKind == reflect.Uint16 || - numKind == reflect.Uint32 || - numKind == reflect.Uint64 { - return float64(numValue.Uint()), nil - } else if numKind == reflect.Float32 || - numKind == reflect.Float64 { - return numValue.Float(), nil - } else { - return 0.0, errors.New("must be a numerical type, but was: " + numKind.String()) - } -} - -// ShouldEqualJSON receives exactly two parameters and does an equality check by marshalling to JSON -func ShouldEqualJSON(actual interface{}, expected ...interface{}) string { - if message := need(1, expected); message != success { - return message - } - - expectedString, expectedErr := remarshal(expected[0].(string)) - if expectedErr != nil { - return "Expected value not valid JSON: " + expectedErr.Error() - } - - actualString, actualErr := remarshal(actual.(string)) - if actualErr != nil { - return "Actual value not valid JSON: " + actualErr.Error() - } - - return ShouldEqual(actualString, expectedString) -} -func remarshal(value string) (string, error) { - var structured interface{} - err := json.Unmarshal([]byte(value), &structured) - if err != nil { - return "", err - } - canonical, _ := json.Marshal(structured) - return string(canonical), nil -} - -// ShouldResemble receives exactly two parameters and does a deep equal check (see reflect.DeepEqual) -func ShouldResemble(actual interface{}, expected ...interface{}) string { - if message := need(1, expected); message != success { - return message - } - - if matchError := oglematchers.DeepEquals(expected[0]).Matches(actual); matchError != nil { - renderedExpected, renderedActual := render.Render(expected[0]), render.Render(actual) - message := fmt.Sprintf(shouldHaveResembled, renderedExpected, renderedActual) + - composePrettyDiff(renderedExpected, renderedActual) - return serializer.serializeDetailed(expected[0], actual, message) - } - - return success -} - -// ShouldNotResemble receives exactly two parameters and does an inverse deep equal check (see reflect.DeepEqual) -func ShouldNotResemble(actual interface{}, expected ...interface{}) string { - if message := need(1, expected); message != success { - return message - } else if ShouldResemble(actual, expected[0]) == success { - return fmt.Sprintf(shouldNotHaveResembled, render.Render(actual), render.Render(expected[0])) - } - return success -} - -// ShouldPointTo receives exactly two parameters and checks to see that they point to the same address. -func ShouldPointTo(actual interface{}, expected ...interface{}) string { - if message := need(1, expected); message != success { - return message - } - return shouldPointTo(actual, expected[0]) - -} -func shouldPointTo(actual, expected interface{}) string { - actualValue := reflect.ValueOf(actual) - expectedValue := reflect.ValueOf(expected) - - if ShouldNotBeNil(actual) != success { - return fmt.Sprintf(shouldHaveBeenNonNilPointer, "first", "nil") - } else if ShouldNotBeNil(expected) != success { - return fmt.Sprintf(shouldHaveBeenNonNilPointer, "second", "nil") - } else if actualValue.Kind() != reflect.Ptr { - return fmt.Sprintf(shouldHaveBeenNonNilPointer, "first", "not") - } else if expectedValue.Kind() != reflect.Ptr { - return fmt.Sprintf(shouldHaveBeenNonNilPointer, "second", "not") - } else if ShouldEqual(actualValue.Pointer(), expectedValue.Pointer()) != success { - actualAddress := reflect.ValueOf(actual).Pointer() - expectedAddress := reflect.ValueOf(expected).Pointer() - return serializer.serialize(expectedAddress, actualAddress, fmt.Sprintf(shouldHavePointedTo, - actual, actualAddress, - expected, expectedAddress)) - } - return success -} - -// ShouldNotPointTo receives exactly two parameters and checks to see that they point to different addresess. -func ShouldNotPointTo(actual interface{}, expected ...interface{}) string { - if message := need(1, expected); message != success { - return message - } - compare := ShouldPointTo(actual, expected[0]) - if strings.HasPrefix(compare, shouldBePointers) { - return compare - } else if compare == success { - return fmt.Sprintf(shouldNotHavePointedTo, actual, expected[0], reflect.ValueOf(actual).Pointer()) - } - return success -} - -// ShouldBeNil receives a single parameter and ensures that it is nil. -func ShouldBeNil(actual interface{}, expected ...interface{}) string { - if fail := need(0, expected); fail != success { - return fail - } else if actual == nil { - return success - } else if interfaceHasNilValue(actual) { - return success - } - return fmt.Sprintf(shouldHaveBeenNil, actual) -} -func interfaceHasNilValue(actual interface{}) bool { - value := reflect.ValueOf(actual) - kind := value.Kind() - nilable := kind == reflect.Slice || - kind == reflect.Chan || - kind == reflect.Func || - kind == reflect.Ptr || - kind == reflect.Map - - // Careful: reflect.Value.IsNil() will panic unless it's an interface, chan, map, func, slice, or ptr - // Reference: http://golang.org/pkg/reflect/#Value.IsNil - return nilable && value.IsNil() -} - -// ShouldNotBeNil receives a single parameter and ensures that it is not nil. -func ShouldNotBeNil(actual interface{}, expected ...interface{}) string { - if fail := need(0, expected); fail != success { - return fail - } else if ShouldBeNil(actual) == success { - return fmt.Sprintf(shouldNotHaveBeenNil, actual) - } - return success -} - -// ShouldBeTrue receives a single parameter and ensures that it is true. -func ShouldBeTrue(actual interface{}, expected ...interface{}) string { - if fail := need(0, expected); fail != success { - return fail - } else if actual != true { - return fmt.Sprintf(shouldHaveBeenTrue, actual) - } - return success -} - -// ShouldBeFalse receives a single parameter and ensures that it is false. -func ShouldBeFalse(actual interface{}, expected ...interface{}) string { - if fail := need(0, expected); fail != success { - return fail - } else if actual != false { - return fmt.Sprintf(shouldHaveBeenFalse, actual) - } - return success -} - -// ShouldBeZeroValue receives a single parameter and ensures that it is -// the Go equivalent of the default value, or "zero" value. -func ShouldBeZeroValue(actual interface{}, expected ...interface{}) string { - if fail := need(0, expected); fail != success { - return fail - } - zeroVal := reflect.Zero(reflect.TypeOf(actual)).Interface() - if !reflect.DeepEqual(zeroVal, actual) { - return serializer.serialize(zeroVal, actual, fmt.Sprintf(shouldHaveBeenZeroValue, actual)) - } - return success -} - -// ShouldBeZeroValue receives a single parameter and ensures that it is NOT -// the Go equivalent of the default value, or "zero" value. -func ShouldNotBeZeroValue(actual interface{}, expected ...interface{}) string { - if fail := need(0, expected); fail != success { - return fail - } - zeroVal := reflect.Zero(reflect.TypeOf(actual)).Interface() - if reflect.DeepEqual(zeroVal, actual) { - return serializer.serialize(zeroVal, actual, fmt.Sprintf(shouldNotHaveBeenZeroValue, actual)) - } - return success -} diff --git a/vendor/github.com/smartystreets/assertions/equality_diff.go b/vendor/github.com/smartystreets/assertions/equality_diff.go deleted file mode 100644 index bd698ff62bdae..0000000000000 --- a/vendor/github.com/smartystreets/assertions/equality_diff.go +++ /dev/null @@ -1,37 +0,0 @@ -package assertions - -import ( - "fmt" - - "github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch" -) - -func composePrettyDiff(expected, actual string) string { - diff := diffmatchpatch.New() - diffs := diff.DiffMain(expected, actual, false) - if prettyDiffIsLikelyToBeHelpful(diffs) { - return fmt.Sprintf("\nDiff: '%s'", diff.DiffPrettyText(diffs)) - } - return "" -} - -// prettyDiffIsLikelyToBeHelpful returns true if the diff listing contains -// more 'equal' segments than 'deleted'/'inserted' segments. -func prettyDiffIsLikelyToBeHelpful(diffs []diffmatchpatch.Diff) bool { - equal, deleted, inserted := measureDiffTypeLengths(diffs) - return equal > deleted && equal > inserted -} - -func measureDiffTypeLengths(diffs []diffmatchpatch.Diff) (equal, deleted, inserted int) { - for _, segment := range diffs { - switch segment.Type { - case diffmatchpatch.DiffEqual: - equal += len(segment.Text) - case diffmatchpatch.DiffDelete: - deleted += len(segment.Text) - case diffmatchpatch.DiffInsert: - inserted += len(segment.Text) - } - } - return equal, deleted, inserted -} diff --git a/vendor/github.com/smartystreets/assertions/filter.go b/vendor/github.com/smartystreets/assertions/filter.go deleted file mode 100644 index cbf75667253e8..0000000000000 --- a/vendor/github.com/smartystreets/assertions/filter.go +++ /dev/null @@ -1,31 +0,0 @@ -package assertions - -import "fmt" - -const ( - success = "" - needExactValues = "This assertion requires exactly %d comparison values (you provided %d)." - needNonEmptyCollection = "This assertion requires at least 1 comparison value (you provided 0)." - needFewerValues = "This assertion allows %d or fewer comparison values (you provided %d)." -) - -func need(needed int, expected []interface{}) string { - if len(expected) != needed { - return fmt.Sprintf(needExactValues, needed, len(expected)) - } - return success -} - -func atLeast(minimum int, expected []interface{}) string { - if len(expected) < minimum { - return needNonEmptyCollection - } - return success -} - -func atMost(max int, expected []interface{}) string { - if len(expected) > max { - return fmt.Sprintf(needFewerValues, max, len(expected)) - } - return success -} diff --git a/vendor/github.com/smartystreets/assertions/go.mod b/vendor/github.com/smartystreets/assertions/go.mod deleted file mode 100644 index 3e0f123cbdfa9..0000000000000 --- a/vendor/github.com/smartystreets/assertions/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/smartystreets/assertions - -go 1.13 diff --git a/vendor/github.com/smartystreets/assertions/internal/go-diff/AUTHORS b/vendor/github.com/smartystreets/assertions/internal/go-diff/AUTHORS deleted file mode 100644 index 2d7bb2bf5728e..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/go-diff/AUTHORS +++ /dev/null @@ -1,25 +0,0 @@ -# This is the official list of go-diff authors for copyright purposes. -# This file is distinct from the CONTRIBUTORS files. -# See the latter for an explanation. - -# Names should be added to this file as -# Name or Organization -# The email address is not required for organizations. - -# Please keep the list sorted. - -Danny Yoo -James Kolb -Jonathan Amsterdam -Markus Zimmermann -Matt Kovars -Örjan Persson -Osman Masood -Robert Carlsen -Rory Flynn -Sergi Mansilla -Shatrugna Sadhu -Shawn Smith -Stas Maksimov -Tor Arvid Lund -Zac Bergquist diff --git a/vendor/github.com/smartystreets/assertions/internal/go-diff/CONTRIBUTORS b/vendor/github.com/smartystreets/assertions/internal/go-diff/CONTRIBUTORS deleted file mode 100644 index 369e3d55190a0..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/go-diff/CONTRIBUTORS +++ /dev/null @@ -1,32 +0,0 @@ -# This is the official list of people who can contribute -# (and typically have contributed) code to the go-diff -# repository. -# -# The AUTHORS file lists the copyright holders; this file -# lists people. For example, ACME Inc. employees would be listed here -# but not in AUTHORS, because ACME Inc. would hold the copyright. -# -# When adding J Random Contributor's name to this file, -# either J's name or J's organization's name should be -# added to the AUTHORS file. -# -# Names should be added to this file like so: -# Name -# -# Please keep the list sorted. - -Danny Yoo -James Kolb -Jonathan Amsterdam -Markus Zimmermann -Matt Kovars -Örjan Persson -Osman Masood -Robert Carlsen -Rory Flynn -Sergi Mansilla -Shatrugna Sadhu -Shawn Smith -Stas Maksimov -Tor Arvid Lund -Zac Bergquist diff --git a/vendor/github.com/smartystreets/assertions/internal/go-diff/LICENSE b/vendor/github.com/smartystreets/assertions/internal/go-diff/LICENSE deleted file mode 100644 index 937942c2b2c4c..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/go-diff/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2012-2016 The go-diff Authors. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included -in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. - diff --git a/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/diff.go b/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/diff.go deleted file mode 100644 index cb25b4375750e..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/diff.go +++ /dev/null @@ -1,1345 +0,0 @@ -// Copyright (c) 2012-2016 The go-diff authors. All rights reserved. -// https://github.com/sergi/go-diff -// See the included LICENSE file for license details. -// -// go-diff is a Go implementation of Google's Diff, Match, and Patch library -// Original library is Copyright (c) 2006 Google Inc. -// http://code.google.com/p/google-diff-match-patch/ - -package diffmatchpatch - -import ( - "bytes" - "errors" - "fmt" - "html" - "math" - "net/url" - "regexp" - "strconv" - "strings" - "time" - "unicode/utf8" -) - -// Operation defines the operation of a diff item. -type Operation int8 - -//go:generate stringer -type=Operation -trimprefix=Diff - -const ( - // DiffDelete item represents a delete diff. - DiffDelete Operation = -1 - // DiffInsert item represents an insert diff. - DiffInsert Operation = 1 - // DiffEqual item represents an equal diff. - DiffEqual Operation = 0 -) - -// Diff represents one diff operation -type Diff struct { - Type Operation - Text string -} - -// splice removes amount elements from slice at index index, replacing them with elements. -func splice(slice []Diff, index int, amount int, elements ...Diff) []Diff { - if len(elements) == amount { - // Easy case: overwrite the relevant items. - copy(slice[index:], elements) - return slice - } - if len(elements) < amount { - // Fewer new items than old. - // Copy in the new items. - copy(slice[index:], elements) - // Shift the remaining items left. - copy(slice[index+len(elements):], slice[index+amount:]) - // Calculate the new end of the slice. - end := len(slice) - amount + len(elements) - // Zero stranded elements at end so that they can be garbage collected. - tail := slice[end:] - for i := range tail { - tail[i] = Diff{} - } - return slice[:end] - } - // More new items than old. - // Make room in slice for new elements. - // There's probably an even more efficient way to do this, - // but this is simple and clear. - need := len(slice) - amount + len(elements) - for len(slice) < need { - slice = append(slice, Diff{}) - } - // Shift slice elements right to make room for new elements. - copy(slice[index+len(elements):], slice[index+amount:]) - // Copy in new elements. - copy(slice[index:], elements) - return slice -} - -// DiffMain finds the differences between two texts. -// If an invalid UTF-8 sequence is encountered, it will be replaced by the Unicode replacement character. -func (dmp *DiffMatchPatch) DiffMain(text1, text2 string, checklines bool) []Diff { - return dmp.DiffMainRunes([]rune(text1), []rune(text2), checklines) -} - -// DiffMainRunes finds the differences between two rune sequences. -// If an invalid UTF-8 sequence is encountered, it will be replaced by the Unicode replacement character. -func (dmp *DiffMatchPatch) DiffMainRunes(text1, text2 []rune, checklines bool) []Diff { - var deadline time.Time - if dmp.DiffTimeout > 0 { - deadline = time.Now().Add(dmp.DiffTimeout) - } - return dmp.diffMainRunes(text1, text2, checklines, deadline) -} - -func (dmp *DiffMatchPatch) diffMainRunes(text1, text2 []rune, checklines bool, deadline time.Time) []Diff { - if runesEqual(text1, text2) { - var diffs []Diff - if len(text1) > 0 { - diffs = append(diffs, Diff{DiffEqual, string(text1)}) - } - return diffs - } - // Trim off common prefix (speedup). - commonlength := commonPrefixLength(text1, text2) - commonprefix := text1[:commonlength] - text1 = text1[commonlength:] - text2 = text2[commonlength:] - - // Trim off common suffix (speedup). - commonlength = commonSuffixLength(text1, text2) - commonsuffix := text1[len(text1)-commonlength:] - text1 = text1[:len(text1)-commonlength] - text2 = text2[:len(text2)-commonlength] - - // Compute the diff on the middle block. - diffs := dmp.diffCompute(text1, text2, checklines, deadline) - - // Restore the prefix and suffix. - if len(commonprefix) != 0 { - diffs = append([]Diff{Diff{DiffEqual, string(commonprefix)}}, diffs...) - } - if len(commonsuffix) != 0 { - diffs = append(diffs, Diff{DiffEqual, string(commonsuffix)}) - } - - return dmp.DiffCleanupMerge(diffs) -} - -// diffCompute finds the differences between two rune slices. Assumes that the texts do not have any common prefix or suffix. -func (dmp *DiffMatchPatch) diffCompute(text1, text2 []rune, checklines bool, deadline time.Time) []Diff { - diffs := []Diff{} - if len(text1) == 0 { - // Just add some text (speedup). - return append(diffs, Diff{DiffInsert, string(text2)}) - } else if len(text2) == 0 { - // Just delete some text (speedup). - return append(diffs, Diff{DiffDelete, string(text1)}) - } - - var longtext, shorttext []rune - if len(text1) > len(text2) { - longtext = text1 - shorttext = text2 - } else { - longtext = text2 - shorttext = text1 - } - - if i := runesIndex(longtext, shorttext); i != -1 { - op := DiffInsert - // Swap insertions for deletions if diff is reversed. - if len(text1) > len(text2) { - op = DiffDelete - } - // Shorter text is inside the longer text (speedup). - return []Diff{ - Diff{op, string(longtext[:i])}, - Diff{DiffEqual, string(shorttext)}, - Diff{op, string(longtext[i+len(shorttext):])}, - } - } else if len(shorttext) == 1 { - // Single character string. - // After the previous speedup, the character can't be an equality. - return []Diff{ - Diff{DiffDelete, string(text1)}, - Diff{DiffInsert, string(text2)}, - } - // Check to see if the problem can be split in two. - } else if hm := dmp.diffHalfMatch(text1, text2); hm != nil { - // A half-match was found, sort out the return data. - text1A := hm[0] - text1B := hm[1] - text2A := hm[2] - text2B := hm[3] - midCommon := hm[4] - // Send both pairs off for separate processing. - diffsA := dmp.diffMainRunes(text1A, text2A, checklines, deadline) - diffsB := dmp.diffMainRunes(text1B, text2B, checklines, deadline) - // Merge the results. - diffs := diffsA - diffs = append(diffs, Diff{DiffEqual, string(midCommon)}) - diffs = append(diffs, diffsB...) - return diffs - } else if checklines && len(text1) > 100 && len(text2) > 100 { - return dmp.diffLineMode(text1, text2, deadline) - } - return dmp.diffBisect(text1, text2, deadline) -} - -// diffLineMode does a quick line-level diff on both []runes, then rediff the parts for greater accuracy. This speedup can produce non-minimal diffs. -func (dmp *DiffMatchPatch) diffLineMode(text1, text2 []rune, deadline time.Time) []Diff { - // Scan the text on a line-by-line basis first. - text1, text2, linearray := dmp.diffLinesToRunes(text1, text2) - - diffs := dmp.diffMainRunes(text1, text2, false, deadline) - - // Convert the diff back to original text. - diffs = dmp.DiffCharsToLines(diffs, linearray) - // Eliminate freak matches (e.g. blank lines) - diffs = dmp.DiffCleanupSemantic(diffs) - - // Rediff any replacement blocks, this time character-by-character. - // Add a dummy entry at the end. - diffs = append(diffs, Diff{DiffEqual, ""}) - - pointer := 0 - countDelete := 0 - countInsert := 0 - - // NOTE: Rune slices are slower than using strings in this case. - textDelete := "" - textInsert := "" - - for pointer < len(diffs) { - switch diffs[pointer].Type { - case DiffInsert: - countInsert++ - textInsert += diffs[pointer].Text - case DiffDelete: - countDelete++ - textDelete += diffs[pointer].Text - case DiffEqual: - // Upon reaching an equality, check for prior redundancies. - if countDelete >= 1 && countInsert >= 1 { - // Delete the offending records and add the merged ones. - diffs = splice(diffs, pointer-countDelete-countInsert, - countDelete+countInsert) - - pointer = pointer - countDelete - countInsert - a := dmp.diffMainRunes([]rune(textDelete), []rune(textInsert), false, deadline) - for j := len(a) - 1; j >= 0; j-- { - diffs = splice(diffs, pointer, 0, a[j]) - } - pointer = pointer + len(a) - } - - countInsert = 0 - countDelete = 0 - textDelete = "" - textInsert = "" - } - pointer++ - } - - return diffs[:len(diffs)-1] // Remove the dummy entry at the end. -} - -// DiffBisect finds the 'middle snake' of a diff, split the problem in two and return the recursively constructed diff. -// If an invalid UTF-8 sequence is encountered, it will be replaced by the Unicode replacement character. -// See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations. -func (dmp *DiffMatchPatch) DiffBisect(text1, text2 string, deadline time.Time) []Diff { - // Unused in this code, but retained for interface compatibility. - return dmp.diffBisect([]rune(text1), []rune(text2), deadline) -} - -// diffBisect finds the 'middle snake' of a diff, splits the problem in two and returns the recursively constructed diff. -// See Myers's 1986 paper: An O(ND) Difference Algorithm and Its Variations. -func (dmp *DiffMatchPatch) diffBisect(runes1, runes2 []rune, deadline time.Time) []Diff { - // Cache the text lengths to prevent multiple calls. - runes1Len, runes2Len := len(runes1), len(runes2) - - maxD := (runes1Len + runes2Len + 1) / 2 - vOffset := maxD - vLength := 2 * maxD - - v1 := make([]int, vLength) - v2 := make([]int, vLength) - for i := range v1 { - v1[i] = -1 - v2[i] = -1 - } - v1[vOffset+1] = 0 - v2[vOffset+1] = 0 - - delta := runes1Len - runes2Len - // If the total number of characters is odd, then the front path will collide with the reverse path. - front := (delta%2 != 0) - // Offsets for start and end of k loop. Prevents mapping of space beyond the grid. - k1start := 0 - k1end := 0 - k2start := 0 - k2end := 0 - for d := 0; d < maxD; d++ { - // Bail out if deadline is reached. - if !deadline.IsZero() && d%16 == 0 && time.Now().After(deadline) { - break - } - - // Walk the front path one step. - for k1 := -d + k1start; k1 <= d-k1end; k1 += 2 { - k1Offset := vOffset + k1 - var x1 int - - if k1 == -d || (k1 != d && v1[k1Offset-1] < v1[k1Offset+1]) { - x1 = v1[k1Offset+1] - } else { - x1 = v1[k1Offset-1] + 1 - } - - y1 := x1 - k1 - for x1 < runes1Len && y1 < runes2Len { - if runes1[x1] != runes2[y1] { - break - } - x1++ - y1++ - } - v1[k1Offset] = x1 - if x1 > runes1Len { - // Ran off the right of the graph. - k1end += 2 - } else if y1 > runes2Len { - // Ran off the bottom of the graph. - k1start += 2 - } else if front { - k2Offset := vOffset + delta - k1 - if k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] != -1 { - // Mirror x2 onto top-left coordinate system. - x2 := runes1Len - v2[k2Offset] - if x1 >= x2 { - // Overlap detected. - return dmp.diffBisectSplit(runes1, runes2, x1, y1, deadline) - } - } - } - } - // Walk the reverse path one step. - for k2 := -d + k2start; k2 <= d-k2end; k2 += 2 { - k2Offset := vOffset + k2 - var x2 int - if k2 == -d || (k2 != d && v2[k2Offset-1] < v2[k2Offset+1]) { - x2 = v2[k2Offset+1] - } else { - x2 = v2[k2Offset-1] + 1 - } - var y2 = x2 - k2 - for x2 < runes1Len && y2 < runes2Len { - if runes1[runes1Len-x2-1] != runes2[runes2Len-y2-1] { - break - } - x2++ - y2++ - } - v2[k2Offset] = x2 - if x2 > runes1Len { - // Ran off the left of the graph. - k2end += 2 - } else if y2 > runes2Len { - // Ran off the top of the graph. - k2start += 2 - } else if !front { - k1Offset := vOffset + delta - k2 - if k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] != -1 { - x1 := v1[k1Offset] - y1 := vOffset + x1 - k1Offset - // Mirror x2 onto top-left coordinate system. - x2 = runes1Len - x2 - if x1 >= x2 { - // Overlap detected. - return dmp.diffBisectSplit(runes1, runes2, x1, y1, deadline) - } - } - } - } - } - // Diff took too long and hit the deadline or number of diffs equals number of characters, no commonality at all. - return []Diff{ - Diff{DiffDelete, string(runes1)}, - Diff{DiffInsert, string(runes2)}, - } -} - -func (dmp *DiffMatchPatch) diffBisectSplit(runes1, runes2 []rune, x, y int, - deadline time.Time) []Diff { - runes1a := runes1[:x] - runes2a := runes2[:y] - runes1b := runes1[x:] - runes2b := runes2[y:] - - // Compute both diffs serially. - diffs := dmp.diffMainRunes(runes1a, runes2a, false, deadline) - diffsb := dmp.diffMainRunes(runes1b, runes2b, false, deadline) - - return append(diffs, diffsb...) -} - -// DiffLinesToChars splits two texts into a list of strings, and educes the texts to a string of hashes where each Unicode character represents one line. -// It's slightly faster to call DiffLinesToRunes first, followed by DiffMainRunes. -func (dmp *DiffMatchPatch) DiffLinesToChars(text1, text2 string) (string, string, []string) { - chars1, chars2, lineArray := dmp.DiffLinesToRunes(text1, text2) - return string(chars1), string(chars2), lineArray -} - -// DiffLinesToRunes splits two texts into a list of runes. Each rune represents one line. -func (dmp *DiffMatchPatch) DiffLinesToRunes(text1, text2 string) ([]rune, []rune, []string) { - // '\x00' is a valid character, but various debuggers don't like it. So we'll insert a junk entry to avoid generating a null character. - lineArray := []string{""} // e.g. lineArray[4] == 'Hello\n' - lineHash := map[string]int{} // e.g. lineHash['Hello\n'] == 4 - - chars1 := dmp.diffLinesToRunesMunge(text1, &lineArray, lineHash) - chars2 := dmp.diffLinesToRunesMunge(text2, &lineArray, lineHash) - - return chars1, chars2, lineArray -} - -func (dmp *DiffMatchPatch) diffLinesToRunes(text1, text2 []rune) ([]rune, []rune, []string) { - return dmp.DiffLinesToRunes(string(text1), string(text2)) -} - -// diffLinesToRunesMunge splits a text into an array of strings, and reduces the texts to a []rune where each Unicode character represents one line. -// We use strings instead of []runes as input mainly because you can't use []rune as a map key. -func (dmp *DiffMatchPatch) diffLinesToRunesMunge(text string, lineArray *[]string, lineHash map[string]int) []rune { - // Walk the text, pulling out a substring for each line. text.split('\n') would would temporarily double our memory footprint. Modifying text would create many large strings to garbage collect. - lineStart := 0 - lineEnd := -1 - runes := []rune{} - - for lineEnd < len(text)-1 { - lineEnd = indexOf(text, "\n", lineStart) - - if lineEnd == -1 { - lineEnd = len(text) - 1 - } - - line := text[lineStart : lineEnd+1] - lineStart = lineEnd + 1 - lineValue, ok := lineHash[line] - - if ok { - runes = append(runes, rune(lineValue)) - } else { - *lineArray = append(*lineArray, line) - lineHash[line] = len(*lineArray) - 1 - runes = append(runes, rune(len(*lineArray)-1)) - } - } - - return runes -} - -// DiffCharsToLines rehydrates the text in a diff from a string of line hashes to real lines of text. -func (dmp *DiffMatchPatch) DiffCharsToLines(diffs []Diff, lineArray []string) []Diff { - hydrated := make([]Diff, 0, len(diffs)) - for _, aDiff := range diffs { - chars := aDiff.Text - text := make([]string, len(chars)) - - for i, r := range chars { - text[i] = lineArray[r] - } - - aDiff.Text = strings.Join(text, "") - hydrated = append(hydrated, aDiff) - } - return hydrated -} - -// DiffCommonPrefix determines the common prefix length of two strings. -func (dmp *DiffMatchPatch) DiffCommonPrefix(text1, text2 string) int { - // Unused in this code, but retained for interface compatibility. - return commonPrefixLength([]rune(text1), []rune(text2)) -} - -// DiffCommonSuffix determines the common suffix length of two strings. -func (dmp *DiffMatchPatch) DiffCommonSuffix(text1, text2 string) int { - // Unused in this code, but retained for interface compatibility. - return commonSuffixLength([]rune(text1), []rune(text2)) -} - -// commonPrefixLength returns the length of the common prefix of two rune slices. -func commonPrefixLength(text1, text2 []rune) int { - // Linear search. See comment in commonSuffixLength. - n := 0 - for ; n < len(text1) && n < len(text2); n++ { - if text1[n] != text2[n] { - return n - } - } - return n -} - -// commonSuffixLength returns the length of the common suffix of two rune slices. -func commonSuffixLength(text1, text2 []rune) int { - // Use linear search rather than the binary search discussed at https://neil.fraser.name/news/2007/10/09/. - // See discussion at https://github.com/sergi/go-diff/issues/54. - i1 := len(text1) - i2 := len(text2) - for n := 0; ; n++ { - i1-- - i2-- - if i1 < 0 || i2 < 0 || text1[i1] != text2[i2] { - return n - } - } -} - -// DiffCommonOverlap determines if the suffix of one string is the prefix of another. -func (dmp *DiffMatchPatch) DiffCommonOverlap(text1 string, text2 string) int { - // Cache the text lengths to prevent multiple calls. - text1Length := len(text1) - text2Length := len(text2) - // Eliminate the null case. - if text1Length == 0 || text2Length == 0 { - return 0 - } - // Truncate the longer string. - if text1Length > text2Length { - text1 = text1[text1Length-text2Length:] - } else if text1Length < text2Length { - text2 = text2[0:text1Length] - } - textLength := int(math.Min(float64(text1Length), float64(text2Length))) - // Quick check for the worst case. - if text1 == text2 { - return textLength - } - - // Start by looking for a single character match and increase length until no match is found. Performance analysis: http://neil.fraser.name/news/2010/11/04/ - best := 0 - length := 1 - for { - pattern := text1[textLength-length:] - found := strings.Index(text2, pattern) - if found == -1 { - break - } - length += found - if found == 0 || text1[textLength-length:] == text2[0:length] { - best = length - length++ - } - } - - return best -} - -// DiffHalfMatch checks whether the two texts share a substring which is at least half the length of the longer text. This speedup can produce non-minimal diffs. -func (dmp *DiffMatchPatch) DiffHalfMatch(text1, text2 string) []string { - // Unused in this code, but retained for interface compatibility. - runeSlices := dmp.diffHalfMatch([]rune(text1), []rune(text2)) - if runeSlices == nil { - return nil - } - - result := make([]string, len(runeSlices)) - for i, r := range runeSlices { - result[i] = string(r) - } - return result -} - -func (dmp *DiffMatchPatch) diffHalfMatch(text1, text2 []rune) [][]rune { - if dmp.DiffTimeout <= 0 { - // Don't risk returning a non-optimal diff if we have unlimited time. - return nil - } - - var longtext, shorttext []rune - if len(text1) > len(text2) { - longtext = text1 - shorttext = text2 - } else { - longtext = text2 - shorttext = text1 - } - - if len(longtext) < 4 || len(shorttext)*2 < len(longtext) { - return nil // Pointless. - } - - // First check if the second quarter is the seed for a half-match. - hm1 := dmp.diffHalfMatchI(longtext, shorttext, int(float64(len(longtext)+3)/4)) - - // Check again based on the third quarter. - hm2 := dmp.diffHalfMatchI(longtext, shorttext, int(float64(len(longtext)+1)/2)) - - hm := [][]rune{} - if hm1 == nil && hm2 == nil { - return nil - } else if hm2 == nil { - hm = hm1 - } else if hm1 == nil { - hm = hm2 - } else { - // Both matched. Select the longest. - if len(hm1[4]) > len(hm2[4]) { - hm = hm1 - } else { - hm = hm2 - } - } - - // A half-match was found, sort out the return data. - if len(text1) > len(text2) { - return hm - } - - return [][]rune{hm[2], hm[3], hm[0], hm[1], hm[4]} -} - -// diffHalfMatchI checks if a substring of shorttext exist within longtext such that the substring is at least half the length of longtext? -// Returns a slice containing the prefix of longtext, the suffix of longtext, the prefix of shorttext, the suffix of shorttext and the common middle, or null if there was no match. -func (dmp *DiffMatchPatch) diffHalfMatchI(l, s []rune, i int) [][]rune { - var bestCommonA []rune - var bestCommonB []rune - var bestCommonLen int - var bestLongtextA []rune - var bestLongtextB []rune - var bestShorttextA []rune - var bestShorttextB []rune - - // Start with a 1/4 length substring at position i as a seed. - seed := l[i : i+len(l)/4] - - for j := runesIndexOf(s, seed, 0); j != -1; j = runesIndexOf(s, seed, j+1) { - prefixLength := commonPrefixLength(l[i:], s[j:]) - suffixLength := commonSuffixLength(l[:i], s[:j]) - - if bestCommonLen < suffixLength+prefixLength { - bestCommonA = s[j-suffixLength : j] - bestCommonB = s[j : j+prefixLength] - bestCommonLen = len(bestCommonA) + len(bestCommonB) - bestLongtextA = l[:i-suffixLength] - bestLongtextB = l[i+prefixLength:] - bestShorttextA = s[:j-suffixLength] - bestShorttextB = s[j+prefixLength:] - } - } - - if bestCommonLen*2 < len(l) { - return nil - } - - return [][]rune{ - bestLongtextA, - bestLongtextB, - bestShorttextA, - bestShorttextB, - append(bestCommonA, bestCommonB...), - } -} - -// DiffCleanupSemantic reduces the number of edits by eliminating semantically trivial equalities. -func (dmp *DiffMatchPatch) DiffCleanupSemantic(diffs []Diff) []Diff { - changes := false - // Stack of indices where equalities are found. - equalities := make([]int, 0, len(diffs)) - - var lastequality string - // Always equal to diffs[equalities[equalitiesLength - 1]][1] - var pointer int // Index of current position. - // Number of characters that changed prior to the equality. - var lengthInsertions1, lengthDeletions1 int - // Number of characters that changed after the equality. - var lengthInsertions2, lengthDeletions2 int - - for pointer < len(diffs) { - if diffs[pointer].Type == DiffEqual { - // Equality found. - equalities = append(equalities, pointer) - lengthInsertions1 = lengthInsertions2 - lengthDeletions1 = lengthDeletions2 - lengthInsertions2 = 0 - lengthDeletions2 = 0 - lastequality = diffs[pointer].Text - } else { - // An insertion or deletion. - - if diffs[pointer].Type == DiffInsert { - lengthInsertions2 += len(diffs[pointer].Text) - } else { - lengthDeletions2 += len(diffs[pointer].Text) - } - // Eliminate an equality that is smaller or equal to the edits on both sides of it. - difference1 := int(math.Max(float64(lengthInsertions1), float64(lengthDeletions1))) - difference2 := int(math.Max(float64(lengthInsertions2), float64(lengthDeletions2))) - if len(lastequality) > 0 && - (len(lastequality) <= difference1) && - (len(lastequality) <= difference2) { - // Duplicate record. - insPoint := equalities[len(equalities)-1] - diffs = splice(diffs, insPoint, 0, Diff{DiffDelete, lastequality}) - - // Change second copy to insert. - diffs[insPoint+1].Type = DiffInsert - // Throw away the equality we just deleted. - equalities = equalities[:len(equalities)-1] - - if len(equalities) > 0 { - equalities = equalities[:len(equalities)-1] - } - pointer = -1 - if len(equalities) > 0 { - pointer = equalities[len(equalities)-1] - } - - lengthInsertions1 = 0 // Reset the counters. - lengthDeletions1 = 0 - lengthInsertions2 = 0 - lengthDeletions2 = 0 - lastequality = "" - changes = true - } - } - pointer++ - } - - // Normalize the diff. - if changes { - diffs = dmp.DiffCleanupMerge(diffs) - } - diffs = dmp.DiffCleanupSemanticLossless(diffs) - // Find any overlaps between deletions and insertions. - // e.g: abcxxxxxxdef - // -> abcxxxdef - // e.g: xxxabcdefxxx - // -> defxxxabc - // Only extract an overlap if it is as big as the edit ahead or behind it. - pointer = 1 - for pointer < len(diffs) { - if diffs[pointer-1].Type == DiffDelete && - diffs[pointer].Type == DiffInsert { - deletion := diffs[pointer-1].Text - insertion := diffs[pointer].Text - overlapLength1 := dmp.DiffCommonOverlap(deletion, insertion) - overlapLength2 := dmp.DiffCommonOverlap(insertion, deletion) - if overlapLength1 >= overlapLength2 { - if float64(overlapLength1) >= float64(len(deletion))/2 || - float64(overlapLength1) >= float64(len(insertion))/2 { - - // Overlap found. Insert an equality and trim the surrounding edits. - diffs = splice(diffs, pointer, 0, Diff{DiffEqual, insertion[:overlapLength1]}) - diffs[pointer-1].Text = - deletion[0 : len(deletion)-overlapLength1] - diffs[pointer+1].Text = insertion[overlapLength1:] - pointer++ - } - } else { - if float64(overlapLength2) >= float64(len(deletion))/2 || - float64(overlapLength2) >= float64(len(insertion))/2 { - // Reverse overlap found. Insert an equality and swap and trim the surrounding edits. - overlap := Diff{DiffEqual, deletion[:overlapLength2]} - diffs = splice(diffs, pointer, 0, overlap) - diffs[pointer-1].Type = DiffInsert - diffs[pointer-1].Text = insertion[0 : len(insertion)-overlapLength2] - diffs[pointer+1].Type = DiffDelete - diffs[pointer+1].Text = deletion[overlapLength2:] - pointer++ - } - } - pointer++ - } - pointer++ - } - - return diffs -} - -// Define some regex patterns for matching boundaries. -var ( - nonAlphaNumericRegex = regexp.MustCompile(`[^a-zA-Z0-9]`) - whitespaceRegex = regexp.MustCompile(`\s`) - linebreakRegex = regexp.MustCompile(`[\r\n]`) - blanklineEndRegex = regexp.MustCompile(`\n\r?\n$`) - blanklineStartRegex = regexp.MustCompile(`^\r?\n\r?\n`) -) - -// diffCleanupSemanticScore computes a score representing whether the internal boundary falls on logical boundaries. -// Scores range from 6 (best) to 0 (worst). Closure, but does not reference any external variables. -func diffCleanupSemanticScore(one, two string) int { - if len(one) == 0 || len(two) == 0 { - // Edges are the best. - return 6 - } - - // Each port of this function behaves slightly differently due to subtle differences in each language's definition of things like 'whitespace'. Since this function's purpose is largely cosmetic, the choice has been made to use each language's native features rather than force total conformity. - rune1, _ := utf8.DecodeLastRuneInString(one) - rune2, _ := utf8.DecodeRuneInString(two) - char1 := string(rune1) - char2 := string(rune2) - - nonAlphaNumeric1 := nonAlphaNumericRegex.MatchString(char1) - nonAlphaNumeric2 := nonAlphaNumericRegex.MatchString(char2) - whitespace1 := nonAlphaNumeric1 && whitespaceRegex.MatchString(char1) - whitespace2 := nonAlphaNumeric2 && whitespaceRegex.MatchString(char2) - lineBreak1 := whitespace1 && linebreakRegex.MatchString(char1) - lineBreak2 := whitespace2 && linebreakRegex.MatchString(char2) - blankLine1 := lineBreak1 && blanklineEndRegex.MatchString(one) - blankLine2 := lineBreak2 && blanklineEndRegex.MatchString(two) - - if blankLine1 || blankLine2 { - // Five points for blank lines. - return 5 - } else if lineBreak1 || lineBreak2 { - // Four points for line breaks. - return 4 - } else if nonAlphaNumeric1 && !whitespace1 && whitespace2 { - // Three points for end of sentences. - return 3 - } else if whitespace1 || whitespace2 { - // Two points for whitespace. - return 2 - } else if nonAlphaNumeric1 || nonAlphaNumeric2 { - // One point for non-alphanumeric. - return 1 - } - return 0 -} - -// DiffCleanupSemanticLossless looks for single edits surrounded on both sides by equalities which can be shifted sideways to align the edit to a word boundary. -// E.g: The cat came. -> The cat came. -func (dmp *DiffMatchPatch) DiffCleanupSemanticLossless(diffs []Diff) []Diff { - pointer := 1 - - // Intentionally ignore the first and last element (don't need checking). - for pointer < len(diffs)-1 { - if diffs[pointer-1].Type == DiffEqual && - diffs[pointer+1].Type == DiffEqual { - - // This is a single edit surrounded by equalities. - equality1 := diffs[pointer-1].Text - edit := diffs[pointer].Text - equality2 := diffs[pointer+1].Text - - // First, shift the edit as far left as possible. - commonOffset := dmp.DiffCommonSuffix(equality1, edit) - if commonOffset > 0 { - commonString := edit[len(edit)-commonOffset:] - equality1 = equality1[0 : len(equality1)-commonOffset] - edit = commonString + edit[:len(edit)-commonOffset] - equality2 = commonString + equality2 - } - - // Second, step character by character right, looking for the best fit. - bestEquality1 := equality1 - bestEdit := edit - bestEquality2 := equality2 - bestScore := diffCleanupSemanticScore(equality1, edit) + - diffCleanupSemanticScore(edit, equality2) - - for len(edit) != 0 && len(equality2) != 0 { - _, sz := utf8.DecodeRuneInString(edit) - if len(equality2) < sz || edit[:sz] != equality2[:sz] { - break - } - equality1 += edit[:sz] - edit = edit[sz:] + equality2[:sz] - equality2 = equality2[sz:] - score := diffCleanupSemanticScore(equality1, edit) + - diffCleanupSemanticScore(edit, equality2) - // The >= encourages trailing rather than leading whitespace on edits. - if score >= bestScore { - bestScore = score - bestEquality1 = equality1 - bestEdit = edit - bestEquality2 = equality2 - } - } - - if diffs[pointer-1].Text != bestEquality1 { - // We have an improvement, save it back to the diff. - if len(bestEquality1) != 0 { - diffs[pointer-1].Text = bestEquality1 - } else { - diffs = splice(diffs, pointer-1, 1) - pointer-- - } - - diffs[pointer].Text = bestEdit - if len(bestEquality2) != 0 { - diffs[pointer+1].Text = bestEquality2 - } else { - diffs = append(diffs[:pointer+1], diffs[pointer+2:]...) - pointer-- - } - } - } - pointer++ - } - - return diffs -} - -// DiffCleanupEfficiency reduces the number of edits by eliminating operationally trivial equalities. -func (dmp *DiffMatchPatch) DiffCleanupEfficiency(diffs []Diff) []Diff { - changes := false - // Stack of indices where equalities are found. - type equality struct { - data int - next *equality - } - var equalities *equality - // Always equal to equalities[equalitiesLength-1][1] - lastequality := "" - pointer := 0 // Index of current position. - // Is there an insertion operation before the last equality. - preIns := false - // Is there a deletion operation before the last equality. - preDel := false - // Is there an insertion operation after the last equality. - postIns := false - // Is there a deletion operation after the last equality. - postDel := false - for pointer < len(diffs) { - if diffs[pointer].Type == DiffEqual { // Equality found. - if len(diffs[pointer].Text) < dmp.DiffEditCost && - (postIns || postDel) { - // Candidate found. - equalities = &equality{ - data: pointer, - next: equalities, - } - preIns = postIns - preDel = postDel - lastequality = diffs[pointer].Text - } else { - // Not a candidate, and can never become one. - equalities = nil - lastequality = "" - } - postIns = false - postDel = false - } else { // An insertion or deletion. - if diffs[pointer].Type == DiffDelete { - postDel = true - } else { - postIns = true - } - - // Five types to be split: - // ABXYCD - // AXCD - // ABXC - // AXCD - // ABXC - var sumPres int - if preIns { - sumPres++ - } - if preDel { - sumPres++ - } - if postIns { - sumPres++ - } - if postDel { - sumPres++ - } - if len(lastequality) > 0 && - ((preIns && preDel && postIns && postDel) || - ((len(lastequality) < dmp.DiffEditCost/2) && sumPres == 3)) { - - insPoint := equalities.data - - // Duplicate record. - diffs = splice(diffs, insPoint, 0, Diff{DiffDelete, lastequality}) - - // Change second copy to insert. - diffs[insPoint+1].Type = DiffInsert - // Throw away the equality we just deleted. - equalities = equalities.next - lastequality = "" - - if preIns && preDel { - // No changes made which could affect previous entry, keep going. - postIns = true - postDel = true - equalities = nil - } else { - if equalities != nil { - equalities = equalities.next - } - if equalities != nil { - pointer = equalities.data - } else { - pointer = -1 - } - postIns = false - postDel = false - } - changes = true - } - } - pointer++ - } - - if changes { - diffs = dmp.DiffCleanupMerge(diffs) - } - - return diffs -} - -// DiffCleanupMerge reorders and merges like edit sections. Merge equalities. -// Any edit section can move as long as it doesn't cross an equality. -func (dmp *DiffMatchPatch) DiffCleanupMerge(diffs []Diff) []Diff { - // Add a dummy entry at the end. - diffs = append(diffs, Diff{DiffEqual, ""}) - pointer := 0 - countDelete := 0 - countInsert := 0 - commonlength := 0 - textDelete := []rune(nil) - textInsert := []rune(nil) - - for pointer < len(diffs) { - switch diffs[pointer].Type { - case DiffInsert: - countInsert++ - textInsert = append(textInsert, []rune(diffs[pointer].Text)...) - pointer++ - break - case DiffDelete: - countDelete++ - textDelete = append(textDelete, []rune(diffs[pointer].Text)...) - pointer++ - break - case DiffEqual: - // Upon reaching an equality, check for prior redundancies. - if countDelete+countInsert > 1 { - if countDelete != 0 && countInsert != 0 { - // Factor out any common prefixies. - commonlength = commonPrefixLength(textInsert, textDelete) - if commonlength != 0 { - x := pointer - countDelete - countInsert - if x > 0 && diffs[x-1].Type == DiffEqual { - diffs[x-1].Text += string(textInsert[:commonlength]) - } else { - diffs = append([]Diff{Diff{DiffEqual, string(textInsert[:commonlength])}}, diffs...) - pointer++ - } - textInsert = textInsert[commonlength:] - textDelete = textDelete[commonlength:] - } - // Factor out any common suffixies. - commonlength = commonSuffixLength(textInsert, textDelete) - if commonlength != 0 { - insertIndex := len(textInsert) - commonlength - deleteIndex := len(textDelete) - commonlength - diffs[pointer].Text = string(textInsert[insertIndex:]) + diffs[pointer].Text - textInsert = textInsert[:insertIndex] - textDelete = textDelete[:deleteIndex] - } - } - // Delete the offending records and add the merged ones. - if countDelete == 0 { - diffs = splice(diffs, pointer-countInsert, - countDelete+countInsert, - Diff{DiffInsert, string(textInsert)}) - } else if countInsert == 0 { - diffs = splice(diffs, pointer-countDelete, - countDelete+countInsert, - Diff{DiffDelete, string(textDelete)}) - } else { - diffs = splice(diffs, pointer-countDelete-countInsert, - countDelete+countInsert, - Diff{DiffDelete, string(textDelete)}, - Diff{DiffInsert, string(textInsert)}) - } - - pointer = pointer - countDelete - countInsert + 1 - if countDelete != 0 { - pointer++ - } - if countInsert != 0 { - pointer++ - } - } else if pointer != 0 && diffs[pointer-1].Type == DiffEqual { - // Merge this equality with the previous one. - diffs[pointer-1].Text += diffs[pointer].Text - diffs = append(diffs[:pointer], diffs[pointer+1:]...) - } else { - pointer++ - } - countInsert = 0 - countDelete = 0 - textDelete = nil - textInsert = nil - break - } - } - - if len(diffs[len(diffs)-1].Text) == 0 { - diffs = diffs[0 : len(diffs)-1] // Remove the dummy entry at the end. - } - - // Second pass: look for single edits surrounded on both sides by equalities which can be shifted sideways to eliminate an equality. E.g: ABAC -> ABAC - changes := false - pointer = 1 - // Intentionally ignore the first and last element (don't need checking). - for pointer < (len(diffs) - 1) { - if diffs[pointer-1].Type == DiffEqual && - diffs[pointer+1].Type == DiffEqual { - // This is a single edit surrounded by equalities. - if strings.HasSuffix(diffs[pointer].Text, diffs[pointer-1].Text) { - // Shift the edit over the previous equality. - diffs[pointer].Text = diffs[pointer-1].Text + - diffs[pointer].Text[:len(diffs[pointer].Text)-len(diffs[pointer-1].Text)] - diffs[pointer+1].Text = diffs[pointer-1].Text + diffs[pointer+1].Text - diffs = splice(diffs, pointer-1, 1) - changes = true - } else if strings.HasPrefix(diffs[pointer].Text, diffs[pointer+1].Text) { - // Shift the edit over the next equality. - diffs[pointer-1].Text += diffs[pointer+1].Text - diffs[pointer].Text = - diffs[pointer].Text[len(diffs[pointer+1].Text):] + diffs[pointer+1].Text - diffs = splice(diffs, pointer+1, 1) - changes = true - } - } - pointer++ - } - - // If shifts were made, the diff needs reordering and another shift sweep. - if changes { - diffs = dmp.DiffCleanupMerge(diffs) - } - - return diffs -} - -// DiffXIndex returns the equivalent location in s2. -func (dmp *DiffMatchPatch) DiffXIndex(diffs []Diff, loc int) int { - chars1 := 0 - chars2 := 0 - lastChars1 := 0 - lastChars2 := 0 - lastDiff := Diff{} - for i := 0; i < len(diffs); i++ { - aDiff := diffs[i] - if aDiff.Type != DiffInsert { - // Equality or deletion. - chars1 += len(aDiff.Text) - } - if aDiff.Type != DiffDelete { - // Equality or insertion. - chars2 += len(aDiff.Text) - } - if chars1 > loc { - // Overshot the location. - lastDiff = aDiff - break - } - lastChars1 = chars1 - lastChars2 = chars2 - } - if lastDiff.Type == DiffDelete { - // The location was deleted. - return lastChars2 - } - // Add the remaining character length. - return lastChars2 + (loc - lastChars1) -} - -// DiffPrettyHtml converts a []Diff into a pretty HTML report. -// It is intended as an example from which to write one's own display functions. -func (dmp *DiffMatchPatch) DiffPrettyHtml(diffs []Diff) string { - var buff bytes.Buffer - for _, diff := range diffs { - text := strings.Replace(html.EscapeString(diff.Text), "\n", "¶
", -1) - switch diff.Type { - case DiffInsert: - _, _ = buff.WriteString("") - _, _ = buff.WriteString(text) - _, _ = buff.WriteString("") - case DiffDelete: - _, _ = buff.WriteString("") - _, _ = buff.WriteString(text) - _, _ = buff.WriteString("") - case DiffEqual: - _, _ = buff.WriteString("") - _, _ = buff.WriteString(text) - _, _ = buff.WriteString("") - } - } - return buff.String() -} - -// DiffPrettyText converts a []Diff into a colored text report. -func (dmp *DiffMatchPatch) DiffPrettyText(diffs []Diff) string { - var buff bytes.Buffer - for _, diff := range diffs { - text := diff.Text - - switch diff.Type { - case DiffInsert: - _, _ = buff.WriteString("\x1b[32m") - _, _ = buff.WriteString(text) - _, _ = buff.WriteString("\x1b[0m") - case DiffDelete: - _, _ = buff.WriteString("\x1b[31m") - _, _ = buff.WriteString(text) - _, _ = buff.WriteString("\x1b[0m") - case DiffEqual: - _, _ = buff.WriteString(text) - } - } - - return buff.String() -} - -// DiffText1 computes and returns the source text (all equalities and deletions). -func (dmp *DiffMatchPatch) DiffText1(diffs []Diff) string { - //StringBuilder text = new StringBuilder() - var text bytes.Buffer - - for _, aDiff := range diffs { - if aDiff.Type != DiffInsert { - _, _ = text.WriteString(aDiff.Text) - } - } - return text.String() -} - -// DiffText2 computes and returns the destination text (all equalities and insertions). -func (dmp *DiffMatchPatch) DiffText2(diffs []Diff) string { - var text bytes.Buffer - - for _, aDiff := range diffs { - if aDiff.Type != DiffDelete { - _, _ = text.WriteString(aDiff.Text) - } - } - return text.String() -} - -// DiffLevenshtein computes the Levenshtein distance that is the number of inserted, deleted or substituted characters. -func (dmp *DiffMatchPatch) DiffLevenshtein(diffs []Diff) int { - levenshtein := 0 - insertions := 0 - deletions := 0 - - for _, aDiff := range diffs { - switch aDiff.Type { - case DiffInsert: - insertions += utf8.RuneCountInString(aDiff.Text) - case DiffDelete: - deletions += utf8.RuneCountInString(aDiff.Text) - case DiffEqual: - // A deletion and an insertion is one substitution. - levenshtein += max(insertions, deletions) - insertions = 0 - deletions = 0 - } - } - - levenshtein += max(insertions, deletions) - return levenshtein -} - -// DiffToDelta crushes the diff into an encoded string which describes the operations required to transform text1 into text2. -// E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'. Operations are tab-separated. Inserted text is escaped using %xx notation. -func (dmp *DiffMatchPatch) DiffToDelta(diffs []Diff) string { - var text bytes.Buffer - for _, aDiff := range diffs { - switch aDiff.Type { - case DiffInsert: - _, _ = text.WriteString("+") - _, _ = text.WriteString(strings.Replace(url.QueryEscape(aDiff.Text), "+", " ", -1)) - _, _ = text.WriteString("\t") - break - case DiffDelete: - _, _ = text.WriteString("-") - _, _ = text.WriteString(strconv.Itoa(utf8.RuneCountInString(aDiff.Text))) - _, _ = text.WriteString("\t") - break - case DiffEqual: - _, _ = text.WriteString("=") - _, _ = text.WriteString(strconv.Itoa(utf8.RuneCountInString(aDiff.Text))) - _, _ = text.WriteString("\t") - break - } - } - delta := text.String() - if len(delta) != 0 { - // Strip off trailing tab character. - delta = delta[0 : utf8.RuneCountInString(delta)-1] - delta = unescaper.Replace(delta) - } - return delta -} - -// DiffFromDelta given the original text1, and an encoded string which describes the operations required to transform text1 into text2, comAdde the full diff. -func (dmp *DiffMatchPatch) DiffFromDelta(text1 string, delta string) (diffs []Diff, err error) { - i := 0 - runes := []rune(text1) - - for _, token := range strings.Split(delta, "\t") { - if len(token) == 0 { - // Blank tokens are ok (from a trailing \t). - continue - } - - // Each token begins with a one character parameter which specifies the operation of this token (delete, insert, equality). - param := token[1:] - - switch op := token[0]; op { - case '+': - // Decode would Diff all "+" to " " - param = strings.Replace(param, "+", "%2b", -1) - param, err = url.QueryUnescape(param) - if err != nil { - return nil, err - } - if !utf8.ValidString(param) { - return nil, fmt.Errorf("invalid UTF-8 token: %q", param) - } - - diffs = append(diffs, Diff{DiffInsert, param}) - case '=', '-': - n, err := strconv.ParseInt(param, 10, 0) - if err != nil { - return nil, err - } else if n < 0 { - return nil, errors.New("Negative number in DiffFromDelta: " + param) - } - - i += int(n) - // Break out if we are out of bounds, go1.6 can't handle this very well - if i > len(runes) { - break - } - // Remember that string slicing is by byte - we want by rune here. - text := string(runes[i-int(n) : i]) - - if op == '=' { - diffs = append(diffs, Diff{DiffEqual, text}) - } else { - diffs = append(diffs, Diff{DiffDelete, text}) - } - default: - // Anything else is an error. - return nil, errors.New("Invalid diff operation in DiffFromDelta: " + string(token[0])) - } - } - - if i != len(runes) { - return nil, fmt.Errorf("Delta length (%v) is different from source text length (%v)", i, len(text1)) - } - - return diffs, nil -} diff --git a/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/diffmatchpatch.go b/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/diffmatchpatch.go deleted file mode 100644 index d3acc32ce13a0..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/diffmatchpatch.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) 2012-2016 The go-diff authors. All rights reserved. -// https://github.com/sergi/go-diff -// See the included LICENSE file for license details. -// -// go-diff is a Go implementation of Google's Diff, Match, and Patch library -// Original library is Copyright (c) 2006 Google Inc. -// http://code.google.com/p/google-diff-match-patch/ - -// Package diffmatchpatch offers robust algorithms to perform the operations required for synchronizing plain text. -package diffmatchpatch - -import ( - "time" -) - -// DiffMatchPatch holds the configuration for diff-match-patch operations. -type DiffMatchPatch struct { - // Number of seconds to map a diff before giving up (0 for infinity). - DiffTimeout time.Duration - // Cost of an empty edit operation in terms of edit characters. - DiffEditCost int - // How far to search for a match (0 = exact location, 1000+ = broad match). A match this many characters away from the expected location will add 1.0 to the score (0.0 is a perfect match). - MatchDistance int - // When deleting a large block of text (over ~64 characters), how close do the contents have to be to match the expected contents. (0.0 = perfection, 1.0 = very loose). Note that MatchThreshold controls how closely the end points of a delete need to match. - PatchDeleteThreshold float64 - // Chunk size for context length. - PatchMargin int - // The number of bits in an int. - MatchMaxBits int - // At what point is no match declared (0.0 = perfection, 1.0 = very loose). - MatchThreshold float64 -} - -// New creates a new DiffMatchPatch object with default parameters. -func New() *DiffMatchPatch { - // Defaults. - return &DiffMatchPatch{ - DiffTimeout: time.Second, - DiffEditCost: 4, - MatchThreshold: 0.5, - MatchDistance: 1000, - PatchDeleteThreshold: 0.5, - PatchMargin: 4, - MatchMaxBits: 32, - } -} diff --git a/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/match.go b/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/match.go deleted file mode 100644 index 17374e109fef2..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/match.go +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright (c) 2012-2016 The go-diff authors. All rights reserved. -// https://github.com/sergi/go-diff -// See the included LICENSE file for license details. -// -// go-diff is a Go implementation of Google's Diff, Match, and Patch library -// Original library is Copyright (c) 2006 Google Inc. -// http://code.google.com/p/google-diff-match-patch/ - -package diffmatchpatch - -import ( - "math" -) - -// MatchMain locates the best instance of 'pattern' in 'text' near 'loc'. -// Returns -1 if no match found. -func (dmp *DiffMatchPatch) MatchMain(text, pattern string, loc int) int { - // Check for null inputs not needed since null can't be passed in C#. - - loc = int(math.Max(0, math.Min(float64(loc), float64(len(text))))) - if text == pattern { - // Shortcut (potentially not guaranteed by the algorithm) - return 0 - } else if len(text) == 0 { - // Nothing to match. - return -1 - } else if loc+len(pattern) <= len(text) && text[loc:loc+len(pattern)] == pattern { - // Perfect match at the perfect spot! (Includes case of null pattern) - return loc - } - // Do a fuzzy compare. - return dmp.MatchBitap(text, pattern, loc) -} - -// MatchBitap locates the best instance of 'pattern' in 'text' near 'loc' using the Bitap algorithm. -// Returns -1 if no match was found. -func (dmp *DiffMatchPatch) MatchBitap(text, pattern string, loc int) int { - // Initialise the alphabet. - s := dmp.MatchAlphabet(pattern) - - // Highest score beyond which we give up. - scoreThreshold := dmp.MatchThreshold - // Is there a nearby exact match? (speedup) - bestLoc := indexOf(text, pattern, loc) - if bestLoc != -1 { - scoreThreshold = math.Min(dmp.matchBitapScore(0, bestLoc, loc, - pattern), scoreThreshold) - // What about in the other direction? (speedup) - bestLoc = lastIndexOf(text, pattern, loc+len(pattern)) - if bestLoc != -1 { - scoreThreshold = math.Min(dmp.matchBitapScore(0, bestLoc, loc, - pattern), scoreThreshold) - } - } - - // Initialise the bit arrays. - matchmask := 1 << uint((len(pattern) - 1)) - bestLoc = -1 - - var binMin, binMid int - binMax := len(pattern) + len(text) - lastRd := []int{} - for d := 0; d < len(pattern); d++ { - // Scan for the best match; each iteration allows for one more error. Run a binary search to determine how far from 'loc' we can stray at this error level. - binMin = 0 - binMid = binMax - for binMin < binMid { - if dmp.matchBitapScore(d, loc+binMid, loc, pattern) <= scoreThreshold { - binMin = binMid - } else { - binMax = binMid - } - binMid = (binMax-binMin)/2 + binMin - } - // Use the result from this iteration as the maximum for the next. - binMax = binMid - start := int(math.Max(1, float64(loc-binMid+1))) - finish := int(math.Min(float64(loc+binMid), float64(len(text))) + float64(len(pattern))) - - rd := make([]int, finish+2) - rd[finish+1] = (1 << uint(d)) - 1 - - for j := finish; j >= start; j-- { - var charMatch int - if len(text) <= j-1 { - // Out of range. - charMatch = 0 - } else if _, ok := s[text[j-1]]; !ok { - charMatch = 0 - } else { - charMatch = s[text[j-1]] - } - - if d == 0 { - // First pass: exact match. - rd[j] = ((rd[j+1] << 1) | 1) & charMatch - } else { - // Subsequent passes: fuzzy match. - rd[j] = ((rd[j+1]<<1)|1)&charMatch | (((lastRd[j+1] | lastRd[j]) << 1) | 1) | lastRd[j+1] - } - if (rd[j] & matchmask) != 0 { - score := dmp.matchBitapScore(d, j-1, loc, pattern) - // This match will almost certainly be better than any existing match. But check anyway. - if score <= scoreThreshold { - // Told you so. - scoreThreshold = score - bestLoc = j - 1 - if bestLoc > loc { - // When passing loc, don't exceed our current distance from loc. - start = int(math.Max(1, float64(2*loc-bestLoc))) - } else { - // Already passed loc, downhill from here on in. - break - } - } - } - } - if dmp.matchBitapScore(d+1, loc, loc, pattern) > scoreThreshold { - // No hope for a (better) match at greater error levels. - break - } - lastRd = rd - } - return bestLoc -} - -// matchBitapScore computes and returns the score for a match with e errors and x location. -func (dmp *DiffMatchPatch) matchBitapScore(e, x, loc int, pattern string) float64 { - accuracy := float64(e) / float64(len(pattern)) - proximity := math.Abs(float64(loc - x)) - if dmp.MatchDistance == 0 { - // Dodge divide by zero error. - if proximity == 0 { - return accuracy - } - - return 1.0 - } - return accuracy + (proximity / float64(dmp.MatchDistance)) -} - -// MatchAlphabet initialises the alphabet for the Bitap algorithm. -func (dmp *DiffMatchPatch) MatchAlphabet(pattern string) map[byte]int { - s := map[byte]int{} - charPattern := []byte(pattern) - for _, c := range charPattern { - _, ok := s[c] - if !ok { - s[c] = 0 - } - } - i := 0 - - for _, c := range charPattern { - value := s[c] | int(uint(1)< y { - return x - } - return y -} diff --git a/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/operation_string.go b/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/operation_string.go deleted file mode 100644 index 533ec0da7b344..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/operation_string.go +++ /dev/null @@ -1,17 +0,0 @@ -// Code generated by "stringer -type=Operation -trimprefix=Diff"; DO NOT EDIT. - -package diffmatchpatch - -import "fmt" - -const _Operation_name = "DeleteEqualInsert" - -var _Operation_index = [...]uint8{0, 6, 11, 17} - -func (i Operation) String() string { - i -= -1 - if i < 0 || i >= Operation(len(_Operation_index)-1) { - return fmt.Sprintf("Operation(%d)", i+-1) - } - return _Operation_name[_Operation_index[i]:_Operation_index[i+1]] -} diff --git a/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/patch.go b/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/patch.go deleted file mode 100644 index 223c43c426807..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/patch.go +++ /dev/null @@ -1,556 +0,0 @@ -// Copyright (c) 2012-2016 The go-diff authors. All rights reserved. -// https://github.com/sergi/go-diff -// See the included LICENSE file for license details. -// -// go-diff is a Go implementation of Google's Diff, Match, and Patch library -// Original library is Copyright (c) 2006 Google Inc. -// http://code.google.com/p/google-diff-match-patch/ - -package diffmatchpatch - -import ( - "bytes" - "errors" - "math" - "net/url" - "regexp" - "strconv" - "strings" -) - -// Patch represents one patch operation. -type Patch struct { - diffs []Diff - Start1 int - Start2 int - Length1 int - Length2 int -} - -// String emulates GNU diff's format. -// Header: @@ -382,8 +481,9 @@ -// Indices are printed as 1-based, not 0-based. -func (p *Patch) String() string { - var coords1, coords2 string - - if p.Length1 == 0 { - coords1 = strconv.Itoa(p.Start1) + ",0" - } else if p.Length1 == 1 { - coords1 = strconv.Itoa(p.Start1 + 1) - } else { - coords1 = strconv.Itoa(p.Start1+1) + "," + strconv.Itoa(p.Length1) - } - - if p.Length2 == 0 { - coords2 = strconv.Itoa(p.Start2) + ",0" - } else if p.Length2 == 1 { - coords2 = strconv.Itoa(p.Start2 + 1) - } else { - coords2 = strconv.Itoa(p.Start2+1) + "," + strconv.Itoa(p.Length2) - } - - var text bytes.Buffer - _, _ = text.WriteString("@@ -" + coords1 + " +" + coords2 + " @@\n") - - // Escape the body of the patch with %xx notation. - for _, aDiff := range p.diffs { - switch aDiff.Type { - case DiffInsert: - _, _ = text.WriteString("+") - case DiffDelete: - _, _ = text.WriteString("-") - case DiffEqual: - _, _ = text.WriteString(" ") - } - - _, _ = text.WriteString(strings.Replace(url.QueryEscape(aDiff.Text), "+", " ", -1)) - _, _ = text.WriteString("\n") - } - - return unescaper.Replace(text.String()) -} - -// PatchAddContext increases the context until it is unique, but doesn't let the pattern expand beyond MatchMaxBits. -func (dmp *DiffMatchPatch) PatchAddContext(patch Patch, text string) Patch { - if len(text) == 0 { - return patch - } - - pattern := text[patch.Start2 : patch.Start2+patch.Length1] - padding := 0 - - // Look for the first and last matches of pattern in text. If two different matches are found, increase the pattern length. - for strings.Index(text, pattern) != strings.LastIndex(text, pattern) && - len(pattern) < dmp.MatchMaxBits-2*dmp.PatchMargin { - padding += dmp.PatchMargin - maxStart := max(0, patch.Start2-padding) - minEnd := min(len(text), patch.Start2+patch.Length1+padding) - pattern = text[maxStart:minEnd] - } - // Add one chunk for good luck. - padding += dmp.PatchMargin - - // Add the prefix. - prefix := text[max(0, patch.Start2-padding):patch.Start2] - if len(prefix) != 0 { - patch.diffs = append([]Diff{Diff{DiffEqual, prefix}}, patch.diffs...) - } - // Add the suffix. - suffix := text[patch.Start2+patch.Length1 : min(len(text), patch.Start2+patch.Length1+padding)] - if len(suffix) != 0 { - patch.diffs = append(patch.diffs, Diff{DiffEqual, suffix}) - } - - // Roll back the start points. - patch.Start1 -= len(prefix) - patch.Start2 -= len(prefix) - // Extend the lengths. - patch.Length1 += len(prefix) + len(suffix) - patch.Length2 += len(prefix) + len(suffix) - - return patch -} - -// PatchMake computes a list of patches. -func (dmp *DiffMatchPatch) PatchMake(opt ...interface{}) []Patch { - if len(opt) == 1 { - diffs, _ := opt[0].([]Diff) - text1 := dmp.DiffText1(diffs) - return dmp.PatchMake(text1, diffs) - } else if len(opt) == 2 { - text1 := opt[0].(string) - switch t := opt[1].(type) { - case string: - diffs := dmp.DiffMain(text1, t, true) - if len(diffs) > 2 { - diffs = dmp.DiffCleanupSemantic(diffs) - diffs = dmp.DiffCleanupEfficiency(diffs) - } - return dmp.PatchMake(text1, diffs) - case []Diff: - return dmp.patchMake2(text1, t) - } - } else if len(opt) == 3 { - return dmp.PatchMake(opt[0], opt[2]) - } - return []Patch{} -} - -// patchMake2 computes a list of patches to turn text1 into text2. -// text2 is not provided, diffs are the delta between text1 and text2. -func (dmp *DiffMatchPatch) patchMake2(text1 string, diffs []Diff) []Patch { - // Check for null inputs not needed since null can't be passed in C#. - patches := []Patch{} - if len(diffs) == 0 { - return patches // Get rid of the null case. - } - - patch := Patch{} - charCount1 := 0 // Number of characters into the text1 string. - charCount2 := 0 // Number of characters into the text2 string. - // Start with text1 (prepatchText) and apply the diffs until we arrive at text2 (postpatchText). We recreate the patches one by one to determine context info. - prepatchText := text1 - postpatchText := text1 - - for i, aDiff := range diffs { - if len(patch.diffs) == 0 && aDiff.Type != DiffEqual { - // A new patch starts here. - patch.Start1 = charCount1 - patch.Start2 = charCount2 - } - - switch aDiff.Type { - case DiffInsert: - patch.diffs = append(patch.diffs, aDiff) - patch.Length2 += len(aDiff.Text) - postpatchText = postpatchText[:charCount2] + - aDiff.Text + postpatchText[charCount2:] - case DiffDelete: - patch.Length1 += len(aDiff.Text) - patch.diffs = append(patch.diffs, aDiff) - postpatchText = postpatchText[:charCount2] + postpatchText[charCount2+len(aDiff.Text):] - case DiffEqual: - if len(aDiff.Text) <= 2*dmp.PatchMargin && - len(patch.diffs) != 0 && i != len(diffs)-1 { - // Small equality inside a patch. - patch.diffs = append(patch.diffs, aDiff) - patch.Length1 += len(aDiff.Text) - patch.Length2 += len(aDiff.Text) - } - if len(aDiff.Text) >= 2*dmp.PatchMargin { - // Time for a new patch. - if len(patch.diffs) != 0 { - patch = dmp.PatchAddContext(patch, prepatchText) - patches = append(patches, patch) - patch = Patch{} - // Unlike Unidiff, our patch lists have a rolling context. http://code.google.com/p/google-diff-match-patch/wiki/Unidiff Update prepatch text & pos to reflect the application of the just completed patch. - prepatchText = postpatchText - charCount1 = charCount2 - } - } - } - - // Update the current character count. - if aDiff.Type != DiffInsert { - charCount1 += len(aDiff.Text) - } - if aDiff.Type != DiffDelete { - charCount2 += len(aDiff.Text) - } - } - - // Pick up the leftover patch if not empty. - if len(patch.diffs) != 0 { - patch = dmp.PatchAddContext(patch, prepatchText) - patches = append(patches, patch) - } - - return patches -} - -// PatchDeepCopy returns an array that is identical to a given an array of patches. -func (dmp *DiffMatchPatch) PatchDeepCopy(patches []Patch) []Patch { - patchesCopy := []Patch{} - for _, aPatch := range patches { - patchCopy := Patch{} - for _, aDiff := range aPatch.diffs { - patchCopy.diffs = append(patchCopy.diffs, Diff{ - aDiff.Type, - aDiff.Text, - }) - } - patchCopy.Start1 = aPatch.Start1 - patchCopy.Start2 = aPatch.Start2 - patchCopy.Length1 = aPatch.Length1 - patchCopy.Length2 = aPatch.Length2 - patchesCopy = append(patchesCopy, patchCopy) - } - return patchesCopy -} - -// PatchApply merges a set of patches onto the text. Returns a patched text, as well as an array of true/false values indicating which patches were applied. -func (dmp *DiffMatchPatch) PatchApply(patches []Patch, text string) (string, []bool) { - if len(patches) == 0 { - return text, []bool{} - } - - // Deep copy the patches so that no changes are made to originals. - patches = dmp.PatchDeepCopy(patches) - - nullPadding := dmp.PatchAddPadding(patches) - text = nullPadding + text + nullPadding - patches = dmp.PatchSplitMax(patches) - - x := 0 - // delta keeps track of the offset between the expected and actual location of the previous patch. If there are patches expected at positions 10 and 20, but the first patch was found at 12, delta is 2 and the second patch has an effective expected position of 22. - delta := 0 - results := make([]bool, len(patches)) - for _, aPatch := range patches { - expectedLoc := aPatch.Start2 + delta - text1 := dmp.DiffText1(aPatch.diffs) - var startLoc int - endLoc := -1 - if len(text1) > dmp.MatchMaxBits { - // PatchSplitMax will only provide an oversized pattern in the case of a monster delete. - startLoc = dmp.MatchMain(text, text1[:dmp.MatchMaxBits], expectedLoc) - if startLoc != -1 { - endLoc = dmp.MatchMain(text, - text1[len(text1)-dmp.MatchMaxBits:], expectedLoc+len(text1)-dmp.MatchMaxBits) - if endLoc == -1 || startLoc >= endLoc { - // Can't find valid trailing context. Drop this patch. - startLoc = -1 - } - } - } else { - startLoc = dmp.MatchMain(text, text1, expectedLoc) - } - if startLoc == -1 { - // No match found. :( - results[x] = false - // Subtract the delta for this failed patch from subsequent patches. - delta -= aPatch.Length2 - aPatch.Length1 - } else { - // Found a match. :) - results[x] = true - delta = startLoc - expectedLoc - var text2 string - if endLoc == -1 { - text2 = text[startLoc:int(math.Min(float64(startLoc+len(text1)), float64(len(text))))] - } else { - text2 = text[startLoc:int(math.Min(float64(endLoc+dmp.MatchMaxBits), float64(len(text))))] - } - if text1 == text2 { - // Perfect match, just shove the Replacement text in. - text = text[:startLoc] + dmp.DiffText2(aPatch.diffs) + text[startLoc+len(text1):] - } else { - // Imperfect match. Run a diff to get a framework of equivalent indices. - diffs := dmp.DiffMain(text1, text2, false) - if len(text1) > dmp.MatchMaxBits && float64(dmp.DiffLevenshtein(diffs))/float64(len(text1)) > dmp.PatchDeleteThreshold { - // The end points match, but the content is unacceptably bad. - results[x] = false - } else { - diffs = dmp.DiffCleanupSemanticLossless(diffs) - index1 := 0 - for _, aDiff := range aPatch.diffs { - if aDiff.Type != DiffEqual { - index2 := dmp.DiffXIndex(diffs, index1) - if aDiff.Type == DiffInsert { - // Insertion - text = text[:startLoc+index2] + aDiff.Text + text[startLoc+index2:] - } else if aDiff.Type == DiffDelete { - // Deletion - startIndex := startLoc + index2 - text = text[:startIndex] + - text[startIndex+dmp.DiffXIndex(diffs, index1+len(aDiff.Text))-index2:] - } - } - if aDiff.Type != DiffDelete { - index1 += len(aDiff.Text) - } - } - } - } - } - x++ - } - // Strip the padding off. - text = text[len(nullPadding) : len(nullPadding)+(len(text)-2*len(nullPadding))] - return text, results -} - -// PatchAddPadding adds some padding on text start and end so that edges can match something. -// Intended to be called only from within patchApply. -func (dmp *DiffMatchPatch) PatchAddPadding(patches []Patch) string { - paddingLength := dmp.PatchMargin - nullPadding := "" - for x := 1; x <= paddingLength; x++ { - nullPadding += string(x) - } - - // Bump all the patches forward. - for i := range patches { - patches[i].Start1 += paddingLength - patches[i].Start2 += paddingLength - } - - // Add some padding on start of first diff. - if len(patches[0].diffs) == 0 || patches[0].diffs[0].Type != DiffEqual { - // Add nullPadding equality. - patches[0].diffs = append([]Diff{Diff{DiffEqual, nullPadding}}, patches[0].diffs...) - patches[0].Start1 -= paddingLength // Should be 0. - patches[0].Start2 -= paddingLength // Should be 0. - patches[0].Length1 += paddingLength - patches[0].Length2 += paddingLength - } else if paddingLength > len(patches[0].diffs[0].Text) { - // Grow first equality. - extraLength := paddingLength - len(patches[0].diffs[0].Text) - patches[0].diffs[0].Text = nullPadding[len(patches[0].diffs[0].Text):] + patches[0].diffs[0].Text - patches[0].Start1 -= extraLength - patches[0].Start2 -= extraLength - patches[0].Length1 += extraLength - patches[0].Length2 += extraLength - } - - // Add some padding on end of last diff. - last := len(patches) - 1 - if len(patches[last].diffs) == 0 || patches[last].diffs[len(patches[last].diffs)-1].Type != DiffEqual { - // Add nullPadding equality. - patches[last].diffs = append(patches[last].diffs, Diff{DiffEqual, nullPadding}) - patches[last].Length1 += paddingLength - patches[last].Length2 += paddingLength - } else if paddingLength > len(patches[last].diffs[len(patches[last].diffs)-1].Text) { - // Grow last equality. - lastDiff := patches[last].diffs[len(patches[last].diffs)-1] - extraLength := paddingLength - len(lastDiff.Text) - patches[last].diffs[len(patches[last].diffs)-1].Text += nullPadding[:extraLength] - patches[last].Length1 += extraLength - patches[last].Length2 += extraLength - } - - return nullPadding -} - -// PatchSplitMax looks through the patches and breaks up any which are longer than the maximum limit of the match algorithm. -// Intended to be called only from within patchApply. -func (dmp *DiffMatchPatch) PatchSplitMax(patches []Patch) []Patch { - patchSize := dmp.MatchMaxBits - for x := 0; x < len(patches); x++ { - if patches[x].Length1 <= patchSize { - continue - } - bigpatch := patches[x] - // Remove the big old patch. - patches = append(patches[:x], patches[x+1:]...) - x-- - - Start1 := bigpatch.Start1 - Start2 := bigpatch.Start2 - precontext := "" - for len(bigpatch.diffs) != 0 { - // Create one of several smaller patches. - patch := Patch{} - empty := true - patch.Start1 = Start1 - len(precontext) - patch.Start2 = Start2 - len(precontext) - if len(precontext) != 0 { - patch.Length1 = len(precontext) - patch.Length2 = len(precontext) - patch.diffs = append(patch.diffs, Diff{DiffEqual, precontext}) - } - for len(bigpatch.diffs) != 0 && patch.Length1 < patchSize-dmp.PatchMargin { - diffType := bigpatch.diffs[0].Type - diffText := bigpatch.diffs[0].Text - if diffType == DiffInsert { - // Insertions are harmless. - patch.Length2 += len(diffText) - Start2 += len(diffText) - patch.diffs = append(patch.diffs, bigpatch.diffs[0]) - bigpatch.diffs = bigpatch.diffs[1:] - empty = false - } else if diffType == DiffDelete && len(patch.diffs) == 1 && patch.diffs[0].Type == DiffEqual && len(diffText) > 2*patchSize { - // This is a large deletion. Let it pass in one chunk. - patch.Length1 += len(diffText) - Start1 += len(diffText) - empty = false - patch.diffs = append(patch.diffs, Diff{diffType, diffText}) - bigpatch.diffs = bigpatch.diffs[1:] - } else { - // Deletion or equality. Only take as much as we can stomach. - diffText = diffText[:min(len(diffText), patchSize-patch.Length1-dmp.PatchMargin)] - - patch.Length1 += len(diffText) - Start1 += len(diffText) - if diffType == DiffEqual { - patch.Length2 += len(diffText) - Start2 += len(diffText) - } else { - empty = false - } - patch.diffs = append(patch.diffs, Diff{diffType, diffText}) - if diffText == bigpatch.diffs[0].Text { - bigpatch.diffs = bigpatch.diffs[1:] - } else { - bigpatch.diffs[0].Text = - bigpatch.diffs[0].Text[len(diffText):] - } - } - } - // Compute the head context for the next patch. - precontext = dmp.DiffText2(patch.diffs) - precontext = precontext[max(0, len(precontext)-dmp.PatchMargin):] - - postcontext := "" - // Append the end context for this patch. - if len(dmp.DiffText1(bigpatch.diffs)) > dmp.PatchMargin { - postcontext = dmp.DiffText1(bigpatch.diffs)[:dmp.PatchMargin] - } else { - postcontext = dmp.DiffText1(bigpatch.diffs) - } - - if len(postcontext) != 0 { - patch.Length1 += len(postcontext) - patch.Length2 += len(postcontext) - if len(patch.diffs) != 0 && patch.diffs[len(patch.diffs)-1].Type == DiffEqual { - patch.diffs[len(patch.diffs)-1].Text += postcontext - } else { - patch.diffs = append(patch.diffs, Diff{DiffEqual, postcontext}) - } - } - if !empty { - x++ - patches = append(patches[:x], append([]Patch{patch}, patches[x:]...)...) - } - } - } - return patches -} - -// PatchToText takes a list of patches and returns a textual representation. -func (dmp *DiffMatchPatch) PatchToText(patches []Patch) string { - var text bytes.Buffer - for _, aPatch := range patches { - _, _ = text.WriteString(aPatch.String()) - } - return text.String() -} - -// PatchFromText parses a textual representation of patches and returns a List of Patch objects. -func (dmp *DiffMatchPatch) PatchFromText(textline string) ([]Patch, error) { - patches := []Patch{} - if len(textline) == 0 { - return patches, nil - } - text := strings.Split(textline, "\n") - textPointer := 0 - patchHeader := regexp.MustCompile("^@@ -(\\d+),?(\\d*) \\+(\\d+),?(\\d*) @@$") - - var patch Patch - var sign uint8 - var line string - for textPointer < len(text) { - - if !patchHeader.MatchString(text[textPointer]) { - return patches, errors.New("Invalid patch string: " + text[textPointer]) - } - - patch = Patch{} - m := patchHeader.FindStringSubmatch(text[textPointer]) - - patch.Start1, _ = strconv.Atoi(m[1]) - if len(m[2]) == 0 { - patch.Start1-- - patch.Length1 = 1 - } else if m[2] == "0" { - patch.Length1 = 0 - } else { - patch.Start1-- - patch.Length1, _ = strconv.Atoi(m[2]) - } - - patch.Start2, _ = strconv.Atoi(m[3]) - - if len(m[4]) == 0 { - patch.Start2-- - patch.Length2 = 1 - } else if m[4] == "0" { - patch.Length2 = 0 - } else { - patch.Start2-- - patch.Length2, _ = strconv.Atoi(m[4]) - } - textPointer++ - - for textPointer < len(text) { - if len(text[textPointer]) > 0 { - sign = text[textPointer][0] - } else { - textPointer++ - continue - } - - line = text[textPointer][1:] - line = strings.Replace(line, "+", "%2b", -1) - line, _ = url.QueryUnescape(line) - if sign == '-' { - // Deletion. - patch.diffs = append(patch.diffs, Diff{DiffDelete, line}) - } else if sign == '+' { - // Insertion. - patch.diffs = append(patch.diffs, Diff{DiffInsert, line}) - } else if sign == ' ' { - // Minor equality. - patch.diffs = append(patch.diffs, Diff{DiffEqual, line}) - } else if sign == '@' { - // Start of next patch. - break - } else { - // WTF? - return patches, errors.New("Invalid patch mode '" + string(sign) + "' in: " + string(line)) - } - textPointer++ - } - - patches = append(patches, patch) - } - return patches, nil -} diff --git a/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/stringutil.go b/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/stringutil.go deleted file mode 100644 index 265f29cc7e595..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch/stringutil.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) 2012-2016 The go-diff authors. All rights reserved. -// https://github.com/sergi/go-diff -// See the included LICENSE file for license details. -// -// go-diff is a Go implementation of Google's Diff, Match, and Patch library -// Original library is Copyright (c) 2006 Google Inc. -// http://code.google.com/p/google-diff-match-patch/ - -package diffmatchpatch - -import ( - "strings" - "unicode/utf8" -) - -// unescaper unescapes selected chars for compatibility with JavaScript's encodeURI. -// In speed critical applications this could be dropped since the receiving application will certainly decode these fine. Note that this function is case-sensitive. Thus "%3F" would not be unescaped. But this is ok because it is only called with the output of HttpUtility.UrlEncode which returns lowercase hex. Example: "%3f" -> "?", "%24" -> "$", etc. -var unescaper = strings.NewReplacer( - "%21", "!", "%7E", "~", "%27", "'", - "%28", "(", "%29", ")", "%3B", ";", - "%2F", "/", "%3F", "?", "%3A", ":", - "%40", "@", "%26", "&", "%3D", "=", - "%2B", "+", "%24", "$", "%2C", ",", "%23", "#", "%2A", "*") - -// indexOf returns the first index of pattern in str, starting at str[i]. -func indexOf(str string, pattern string, i int) int { - if i > len(str)-1 { - return -1 - } - if i <= 0 { - return strings.Index(str, pattern) - } - ind := strings.Index(str[i:], pattern) - if ind == -1 { - return -1 - } - return ind + i -} - -// lastIndexOf returns the last index of pattern in str, starting at str[i]. -func lastIndexOf(str string, pattern string, i int) int { - if i < 0 { - return -1 - } - if i >= len(str) { - return strings.LastIndex(str, pattern) - } - _, size := utf8.DecodeRuneInString(str[i:]) - return strings.LastIndex(str[:i+size], pattern) -} - -// runesIndexOf returns the index of pattern in target, starting at target[i]. -func runesIndexOf(target, pattern []rune, i int) int { - if i > len(target)-1 { - return -1 - } - if i <= 0 { - return runesIndex(target, pattern) - } - ind := runesIndex(target[i:], pattern) - if ind == -1 { - return -1 - } - return ind + i -} - -func runesEqual(r1, r2 []rune) bool { - if len(r1) != len(r2) { - return false - } - for i, c := range r1 { - if c != r2[i] { - return false - } - } - return true -} - -// runesIndex is the equivalent of strings.Index for rune slices. -func runesIndex(r1, r2 []rune) int { - last := len(r1) - len(r2) - for i := 0; i <= last; i++ { - if runesEqual(r1[i:i+len(r2)], r2) { - return i - } - } - return -1 -} diff --git a/vendor/github.com/smartystreets/assertions/internal/go-render/LICENSE b/vendor/github.com/smartystreets/assertions/internal/go-render/LICENSE deleted file mode 100644 index 6280ff0e06b4c..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/go-render/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2015 The Chromium Authors. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/smartystreets/assertions/internal/go-render/render/render.go b/vendor/github.com/smartystreets/assertions/internal/go-render/render/render.go deleted file mode 100644 index 313611ef0c45e..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/go-render/render/render.go +++ /dev/null @@ -1,481 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package render - -import ( - "bytes" - "fmt" - "reflect" - "sort" - "strconv" -) - -var builtinTypeMap = map[reflect.Kind]string{ - reflect.Bool: "bool", - reflect.Complex128: "complex128", - reflect.Complex64: "complex64", - reflect.Float32: "float32", - reflect.Float64: "float64", - reflect.Int16: "int16", - reflect.Int32: "int32", - reflect.Int64: "int64", - reflect.Int8: "int8", - reflect.Int: "int", - reflect.String: "string", - reflect.Uint16: "uint16", - reflect.Uint32: "uint32", - reflect.Uint64: "uint64", - reflect.Uint8: "uint8", - reflect.Uint: "uint", - reflect.Uintptr: "uintptr", -} - -var builtinTypeSet = map[string]struct{}{} - -func init() { - for _, v := range builtinTypeMap { - builtinTypeSet[v] = struct{}{} - } -} - -var typeOfString = reflect.TypeOf("") -var typeOfInt = reflect.TypeOf(int(1)) -var typeOfUint = reflect.TypeOf(uint(1)) -var typeOfFloat = reflect.TypeOf(10.1) - -// Render converts a structure to a string representation. Unline the "%#v" -// format string, this resolves pointer types' contents in structs, maps, and -// slices/arrays and prints their field values. -func Render(v interface{}) string { - buf := bytes.Buffer{} - s := (*traverseState)(nil) - s.render(&buf, 0, reflect.ValueOf(v), false) - return buf.String() -} - -// renderPointer is called to render a pointer value. -// -// This is overridable so that the test suite can have deterministic pointer -// values in its expectations. -var renderPointer = func(buf *bytes.Buffer, p uintptr) { - fmt.Fprintf(buf, "0x%016x", p) -} - -// traverseState is used to note and avoid recursion as struct members are being -// traversed. -// -// traverseState is allowed to be nil. Specifically, the root state is nil. -type traverseState struct { - parent *traverseState - ptr uintptr -} - -func (s *traverseState) forkFor(ptr uintptr) *traverseState { - for cur := s; cur != nil; cur = cur.parent { - if ptr == cur.ptr { - return nil - } - } - - fs := &traverseState{ - parent: s, - ptr: ptr, - } - return fs -} - -func (s *traverseState) render(buf *bytes.Buffer, ptrs int, v reflect.Value, implicit bool) { - if v.Kind() == reflect.Invalid { - buf.WriteString("nil") - return - } - vt := v.Type() - - // If the type being rendered is a potentially recursive type (a type that - // can contain itself as a member), we need to avoid recursion. - // - // If we've already seen this type before, mark that this is the case and - // write a recursion placeholder instead of actually rendering it. - // - // If we haven't seen it before, fork our `seen` tracking so any higher-up - // renderers will also render it at least once, then mark that we've seen it - // to avoid recursing on lower layers. - pe := uintptr(0) - vk := vt.Kind() - switch vk { - case reflect.Ptr: - // Since structs and arrays aren't pointers, they can't directly be - // recursed, but they can contain pointers to themselves. Record their - // pointer to avoid this. - switch v.Elem().Kind() { - case reflect.Struct, reflect.Array: - pe = v.Pointer() - } - - case reflect.Slice, reflect.Map: - pe = v.Pointer() - } - if pe != 0 { - s = s.forkFor(pe) - if s == nil { - buf.WriteString("") - return - } - } - - isAnon := func(t reflect.Type) bool { - if t.Name() != "" { - if _, ok := builtinTypeSet[t.Name()]; !ok { - return false - } - } - return t.Kind() != reflect.Interface - } - - switch vk { - case reflect.Struct: - if !implicit { - writeType(buf, ptrs, vt) - } - buf.WriteRune('{') - if rendered, ok := renderTime(v); ok { - buf.WriteString(rendered) - } else { - structAnon := vt.Name() == "" - for i := 0; i < vt.NumField(); i++ { - if i > 0 { - buf.WriteString(", ") - } - anon := structAnon && isAnon(vt.Field(i).Type) - - if !anon { - buf.WriteString(vt.Field(i).Name) - buf.WriteRune(':') - } - - s.render(buf, 0, v.Field(i), anon) - } - } - buf.WriteRune('}') - - case reflect.Slice: - if v.IsNil() { - if !implicit { - writeType(buf, ptrs, vt) - buf.WriteString("(nil)") - } else { - buf.WriteString("nil") - } - return - } - fallthrough - - case reflect.Array: - if !implicit { - writeType(buf, ptrs, vt) - } - anon := vt.Name() == "" && isAnon(vt.Elem()) - buf.WriteString("{") - for i := 0; i < v.Len(); i++ { - if i > 0 { - buf.WriteString(", ") - } - - s.render(buf, 0, v.Index(i), anon) - } - buf.WriteRune('}') - - case reflect.Map: - if !implicit { - writeType(buf, ptrs, vt) - } - if v.IsNil() { - buf.WriteString("(nil)") - } else { - buf.WriteString("{") - - mkeys := v.MapKeys() - tryAndSortMapKeys(vt, mkeys) - - kt := vt.Key() - keyAnon := typeOfString.ConvertibleTo(kt) || typeOfInt.ConvertibleTo(kt) || typeOfUint.ConvertibleTo(kt) || typeOfFloat.ConvertibleTo(kt) - valAnon := vt.Name() == "" && isAnon(vt.Elem()) - for i, mk := range mkeys { - if i > 0 { - buf.WriteString(", ") - } - - s.render(buf, 0, mk, keyAnon) - buf.WriteString(":") - s.render(buf, 0, v.MapIndex(mk), valAnon) - } - buf.WriteRune('}') - } - - case reflect.Ptr: - ptrs++ - fallthrough - case reflect.Interface: - if v.IsNil() { - writeType(buf, ptrs, v.Type()) - buf.WriteString("(nil)") - } else { - s.render(buf, ptrs, v.Elem(), false) - } - - case reflect.Chan, reflect.Func, reflect.UnsafePointer: - writeType(buf, ptrs, vt) - buf.WriteRune('(') - renderPointer(buf, v.Pointer()) - buf.WriteRune(')') - - default: - tstr := vt.String() - implicit = implicit || (ptrs == 0 && builtinTypeMap[vk] == tstr) - if !implicit { - writeType(buf, ptrs, vt) - buf.WriteRune('(') - } - - switch vk { - case reflect.String: - fmt.Fprintf(buf, "%q", v.String()) - case reflect.Bool: - fmt.Fprintf(buf, "%v", v.Bool()) - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - fmt.Fprintf(buf, "%d", v.Int()) - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - fmt.Fprintf(buf, "%d", v.Uint()) - - case reflect.Float32, reflect.Float64: - fmt.Fprintf(buf, "%g", v.Float()) - - case reflect.Complex64, reflect.Complex128: - fmt.Fprintf(buf, "%g", v.Complex()) - } - - if !implicit { - buf.WriteRune(')') - } - } -} - -func writeType(buf *bytes.Buffer, ptrs int, t reflect.Type) { - parens := ptrs > 0 - switch t.Kind() { - case reflect.Chan, reflect.Func, reflect.UnsafePointer: - parens = true - } - - if parens { - buf.WriteRune('(') - for i := 0; i < ptrs; i++ { - buf.WriteRune('*') - } - } - - switch t.Kind() { - case reflect.Ptr: - if ptrs == 0 { - // This pointer was referenced from within writeType (e.g., as part of - // rendering a list), and so hasn't had its pointer asterisk accounted - // for. - buf.WriteRune('*') - } - writeType(buf, 0, t.Elem()) - - case reflect.Interface: - if n := t.Name(); n != "" { - buf.WriteString(t.String()) - } else { - buf.WriteString("interface{}") - } - - case reflect.Array: - buf.WriteRune('[') - buf.WriteString(strconv.FormatInt(int64(t.Len()), 10)) - buf.WriteRune(']') - writeType(buf, 0, t.Elem()) - - case reflect.Slice: - if t == reflect.SliceOf(t.Elem()) { - buf.WriteString("[]") - writeType(buf, 0, t.Elem()) - } else { - // Custom slice type, use type name. - buf.WriteString(t.String()) - } - - case reflect.Map: - if t == reflect.MapOf(t.Key(), t.Elem()) { - buf.WriteString("map[") - writeType(buf, 0, t.Key()) - buf.WriteRune(']') - writeType(buf, 0, t.Elem()) - } else { - // Custom map type, use type name. - buf.WriteString(t.String()) - } - - default: - buf.WriteString(t.String()) - } - - if parens { - buf.WriteRune(')') - } -} - -type cmpFn func(a, b reflect.Value) int - -type sortableValueSlice struct { - cmp cmpFn - elements []reflect.Value -} - -func (s sortableValueSlice) Len() int { - return len(s.elements) -} - -func (s sortableValueSlice) Less(i, j int) bool { - return s.cmp(s.elements[i], s.elements[j]) < 0 -} - -func (s sortableValueSlice) Swap(i, j int) { - s.elements[i], s.elements[j] = s.elements[j], s.elements[i] -} - -// cmpForType returns a cmpFn which sorts the data for some type t in the same -// order that a go-native map key is compared for equality. -func cmpForType(t reflect.Type) cmpFn { - switch t.Kind() { - case reflect.String: - return func(av, bv reflect.Value) int { - a, b := av.String(), bv.String() - if a < b { - return -1 - } else if a > b { - return 1 - } - return 0 - } - - case reflect.Bool: - return func(av, bv reflect.Value) int { - a, b := av.Bool(), bv.Bool() - if !a && b { - return -1 - } else if a && !b { - return 1 - } - return 0 - } - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return func(av, bv reflect.Value) int { - a, b := av.Int(), bv.Int() - if a < b { - return -1 - } else if a > b { - return 1 - } - return 0 - } - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, - reflect.Uint64, reflect.Uintptr, reflect.UnsafePointer: - return func(av, bv reflect.Value) int { - a, b := av.Uint(), bv.Uint() - if a < b { - return -1 - } else if a > b { - return 1 - } - return 0 - } - - case reflect.Float32, reflect.Float64: - return func(av, bv reflect.Value) int { - a, b := av.Float(), bv.Float() - if a < b { - return -1 - } else if a > b { - return 1 - } - return 0 - } - - case reflect.Interface: - return func(av, bv reflect.Value) int { - a, b := av.InterfaceData(), bv.InterfaceData() - if a[0] < b[0] { - return -1 - } else if a[0] > b[0] { - return 1 - } - if a[1] < b[1] { - return -1 - } else if a[1] > b[1] { - return 1 - } - return 0 - } - - case reflect.Complex64, reflect.Complex128: - return func(av, bv reflect.Value) int { - a, b := av.Complex(), bv.Complex() - if real(a) < real(b) { - return -1 - } else if real(a) > real(b) { - return 1 - } - if imag(a) < imag(b) { - return -1 - } else if imag(a) > imag(b) { - return 1 - } - return 0 - } - - case reflect.Ptr, reflect.Chan: - return func(av, bv reflect.Value) int { - a, b := av.Pointer(), bv.Pointer() - if a < b { - return -1 - } else if a > b { - return 1 - } - return 0 - } - - case reflect.Struct: - cmpLst := make([]cmpFn, t.NumField()) - for i := range cmpLst { - cmpLst[i] = cmpForType(t.Field(i).Type) - } - return func(a, b reflect.Value) int { - for i, cmp := range cmpLst { - if rslt := cmp(a.Field(i), b.Field(i)); rslt != 0 { - return rslt - } - } - return 0 - } - } - - return nil -} - -func tryAndSortMapKeys(mt reflect.Type, k []reflect.Value) { - if cmp := cmpForType(mt.Key()); cmp != nil { - sort.Sort(sortableValueSlice{cmp, k}) - } -} diff --git a/vendor/github.com/smartystreets/assertions/internal/go-render/render/render_time.go b/vendor/github.com/smartystreets/assertions/internal/go-render/render/render_time.go deleted file mode 100644 index 990c75d0ffb5d..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/go-render/render/render_time.go +++ /dev/null @@ -1,26 +0,0 @@ -package render - -import ( - "reflect" - "time" -) - -func renderTime(value reflect.Value) (string, bool) { - if instant, ok := convertTime(value); !ok { - return "", false - } else if instant.IsZero() { - return "0", true - } else { - return instant.String(), true - } -} - -func convertTime(value reflect.Value) (t time.Time, ok bool) { - if value.Type() == timeType { - defer func() { recover() }() - t, ok = value.Interface().(time.Time) - } - return -} - -var timeType = reflect.TypeOf(time.Time{}) diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/.gitignore b/vendor/github.com/smartystreets/assertions/internal/oglematchers/.gitignore deleted file mode 100644 index dd8fc7468f4a5..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/oglematchers/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -*.6 -6.out -_obj/ -_test/ -_testmain.go diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/.travis.yml b/vendor/github.com/smartystreets/assertions/internal/oglematchers/.travis.yml deleted file mode 100644 index b97211926e8dc..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/oglematchers/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -# Cf. http://docs.travis-ci.com/user/getting-started/ -# Cf. http://docs.travis-ci.com/user/languages/go/ - -language: go diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/LICENSE b/vendor/github.com/smartystreets/assertions/internal/oglematchers/LICENSE deleted file mode 100644 index d645695673349..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/oglematchers/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/README.md b/vendor/github.com/smartystreets/assertions/internal/oglematchers/README.md deleted file mode 100644 index 215a2bb7a8bb7..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/oglematchers/README.md +++ /dev/null @@ -1,58 +0,0 @@ -[![GoDoc](https://godoc.org/github.com/smartystreets/assertions/internal/oglematchers?status.svg)](https://godoc.org/github.com/smartystreets/assertions/internal/oglematchers) - -`oglematchers` is a package for the Go programming language containing a set of -matchers, useful in a testing or mocking framework, inspired by and mostly -compatible with [Google Test][googletest] for C++ and -[Google JS Test][google-js-test]. The package is used by the -[ogletest][ogletest] testing framework and [oglemock][oglemock] mocking -framework, which may be more directly useful to you, but can be generically used -elsewhere as well. - -A "matcher" is simply an object with a `Matches` method defining a set of golang -values matched by the matcher, and a `Description` method describing that set. -For example, here are some matchers: - -```go -// Numbers -Equals(17.13) -LessThan(19) - -// Strings -Equals("taco") -HasSubstr("burrito") -MatchesRegex("t.*o") - -// Combining matchers -AnyOf(LessThan(17), GreaterThan(19)) -``` - -There are lots more; see [here][reference] for a reference. You can also add -your own simply by implementing the `oglematchers.Matcher` interface. - - -Installation ------------- - -First, make sure you have installed Go 1.0.2 or newer. See -[here][golang-install] for instructions. - -Use the following command to install `oglematchers` and keep it up to date: - - go get -u github.com/smartystreets/assertions/internal/oglematchers - - -Documentation -------------- - -See [here][reference] for documentation. Alternatively, you can install the -package and then use `godoc`: - - godoc github.com/smartystreets/assertions/internal/oglematchers - - -[reference]: http://godoc.org/github.com/smartystreets/assertions/internal/oglematchers -[golang-install]: http://golang.org/doc/install.html -[googletest]: http://code.google.com/p/googletest/ -[google-js-test]: http://code.google.com/p/google-js-test/ -[ogletest]: http://github.com/smartystreets/assertions/internal/ogletest -[oglemock]: http://github.com/smartystreets/assertions/internal/oglemock diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/any_of.go b/vendor/github.com/smartystreets/assertions/internal/oglematchers/any_of.go deleted file mode 100644 index 2918b51f21afd..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/oglematchers/any_of.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "errors" - "fmt" - "reflect" - "strings" -) - -// AnyOf accepts a set of values S and returns a matcher that follows the -// algorithm below when considering a candidate c: -// -// 1. If there exists a value m in S such that m implements the Matcher -// interface and m matches c, return true. -// -// 2. Otherwise, if there exists a value v in S such that v does not implement -// the Matcher interface and the matcher Equals(v) matches c, return true. -// -// 3. Otherwise, if there is a value m in S such that m implements the Matcher -// interface and m returns a fatal error for c, return that fatal error. -// -// 4. Otherwise, return false. -// -// This is akin to a logical OR operation for matchers, with non-matchers x -// being treated as Equals(x). -func AnyOf(vals ...interface{}) Matcher { - // Get ahold of a type variable for the Matcher interface. - var dummy *Matcher - matcherType := reflect.TypeOf(dummy).Elem() - - // Create a matcher for each value, or use the value itself if it's already a - // matcher. - wrapped := make([]Matcher, len(vals)) - for i, v := range vals { - t := reflect.TypeOf(v) - if t != nil && t.Implements(matcherType) { - wrapped[i] = v.(Matcher) - } else { - wrapped[i] = Equals(v) - } - } - - return &anyOfMatcher{wrapped} -} - -type anyOfMatcher struct { - wrapped []Matcher -} - -func (m *anyOfMatcher) Description() string { - wrappedDescs := make([]string, len(m.wrapped)) - for i, matcher := range m.wrapped { - wrappedDescs[i] = matcher.Description() - } - - return fmt.Sprintf("or(%s)", strings.Join(wrappedDescs, ", ")) -} - -func (m *anyOfMatcher) Matches(c interface{}) (err error) { - err = errors.New("") - - // Try each matcher in turn. - for _, matcher := range m.wrapped { - wrappedErr := matcher.Matches(c) - - // Return immediately if there's a match. - if wrappedErr == nil { - err = nil - return - } - - // Note the fatal error, if any. - if _, isFatal := wrappedErr.(*FatalError); isFatal { - err = wrappedErr - } - } - - return -} diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/contains.go b/vendor/github.com/smartystreets/assertions/internal/oglematchers/contains.go deleted file mode 100644 index 87f107d3921ff..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/oglematchers/contains.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "fmt" - "reflect" -) - -// Return a matcher that matches arrays slices with at least one element that -// matches the supplied argument. If the argument x is not itself a Matcher, -// this is equivalent to Contains(Equals(x)). -func Contains(x interface{}) Matcher { - var result containsMatcher - var ok bool - - if result.elementMatcher, ok = x.(Matcher); !ok { - result.elementMatcher = DeepEquals(x) - } - - return &result -} - -type containsMatcher struct { - elementMatcher Matcher -} - -func (m *containsMatcher) Description() string { - return fmt.Sprintf("contains: %s", m.elementMatcher.Description()) -} - -func (m *containsMatcher) Matches(candidate interface{}) error { - // The candidate must be a slice or an array. - v := reflect.ValueOf(candidate) - if v.Kind() != reflect.Slice && v.Kind() != reflect.Array { - return NewFatalError("which is not a slice or array") - } - - // Check each element. - for i := 0; i < v.Len(); i++ { - elem := v.Index(i) - if matchErr := m.elementMatcher.Matches(elem.Interface()); matchErr == nil { - return nil - } - } - - return fmt.Errorf("") -} diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/deep_equals.go b/vendor/github.com/smartystreets/assertions/internal/oglematchers/deep_equals.go deleted file mode 100644 index 1d91baef32e8f..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/oglematchers/deep_equals.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 2012 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "bytes" - "errors" - "fmt" - "reflect" -) - -var byteSliceType reflect.Type = reflect.TypeOf([]byte{}) - -// DeepEquals returns a matcher that matches based on 'deep equality', as -// defined by the reflect package. This matcher requires that values have -// identical types to x. -func DeepEquals(x interface{}) Matcher { - return &deepEqualsMatcher{x} -} - -type deepEqualsMatcher struct { - x interface{} -} - -func (m *deepEqualsMatcher) Description() string { - xDesc := fmt.Sprintf("%v", m.x) - xValue := reflect.ValueOf(m.x) - - // Special case: fmt.Sprintf presents nil slices as "[]", but - // reflect.DeepEqual makes a distinction between nil and empty slices. Make - // this less confusing. - if xValue.Kind() == reflect.Slice && xValue.IsNil() { - xDesc = "" - } - - return fmt.Sprintf("deep equals: %s", xDesc) -} - -func (m *deepEqualsMatcher) Matches(c interface{}) error { - // Make sure the types match. - ct := reflect.TypeOf(c) - xt := reflect.TypeOf(m.x) - - if ct != xt { - return NewFatalError(fmt.Sprintf("which is of type %v", ct)) - } - - // Special case: handle byte slices more efficiently. - cValue := reflect.ValueOf(c) - xValue := reflect.ValueOf(m.x) - - if ct == byteSliceType && !cValue.IsNil() && !xValue.IsNil() { - xBytes := m.x.([]byte) - cBytes := c.([]byte) - - if bytes.Equal(cBytes, xBytes) { - return nil - } - - return errors.New("") - } - - // Defer to the reflect package. - if reflect.DeepEqual(m.x, c) { - return nil - } - - // Special case: if the comparison failed because c is the nil slice, given - // an indication of this (since its value is printed as "[]"). - if cValue.Kind() == reflect.Slice && cValue.IsNil() { - return errors.New("which is nil") - } - - return errors.New("") -} diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/equals.go b/vendor/github.com/smartystreets/assertions/internal/oglematchers/equals.go deleted file mode 100644 index a510707b3c7ee..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/oglematchers/equals.go +++ /dev/null @@ -1,541 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "errors" - "fmt" - "math" - "reflect" -) - -// Equals(x) returns a matcher that matches values v such that v and x are -// equivalent. This includes the case when the comparison v == x using Go's -// built-in comparison operator is legal (except for structs, which this -// matcher does not support), but for convenience the following rules also -// apply: -// -// * Type checking is done based on underlying types rather than actual -// types, so that e.g. two aliases for string can be compared: -// -// type stringAlias1 string -// type stringAlias2 string -// -// a := "taco" -// b := stringAlias1("taco") -// c := stringAlias2("taco") -// -// ExpectTrue(a == b) // Legal, passes -// ExpectTrue(b == c) // Illegal, doesn't compile -// -// ExpectThat(a, Equals(b)) // Passes -// ExpectThat(b, Equals(c)) // Passes -// -// * Values of numeric type are treated as if they were abstract numbers, and -// compared accordingly. Therefore Equals(17) will match int(17), -// int16(17), uint(17), float32(17), complex64(17), and so on. -// -// If you want a stricter matcher that contains no such cleverness, see -// IdenticalTo instead. -// -// Arrays are supported by this matcher, but do not participate in the -// exceptions above. Two arrays compared with this matcher must have identical -// types, and their element type must itself be comparable according to Go's == -// operator. -func Equals(x interface{}) Matcher { - v := reflect.ValueOf(x) - - // This matcher doesn't support structs. - if v.Kind() == reflect.Struct { - panic(fmt.Sprintf("oglematchers.Equals: unsupported kind %v", v.Kind())) - } - - // The == operator is not defined for non-nil slices. - if v.Kind() == reflect.Slice && v.Pointer() != uintptr(0) { - panic(fmt.Sprintf("oglematchers.Equals: non-nil slice")) - } - - return &equalsMatcher{v} -} - -type equalsMatcher struct { - expectedValue reflect.Value -} - -//////////////////////////////////////////////////////////////////////// -// Numeric types -//////////////////////////////////////////////////////////////////////// - -func isSignedInteger(v reflect.Value) bool { - k := v.Kind() - return k >= reflect.Int && k <= reflect.Int64 -} - -func isUnsignedInteger(v reflect.Value) bool { - k := v.Kind() - return k >= reflect.Uint && k <= reflect.Uintptr -} - -func isInteger(v reflect.Value) bool { - return isSignedInteger(v) || isUnsignedInteger(v) -} - -func isFloat(v reflect.Value) bool { - k := v.Kind() - return k == reflect.Float32 || k == reflect.Float64 -} - -func isComplex(v reflect.Value) bool { - k := v.Kind() - return k == reflect.Complex64 || k == reflect.Complex128 -} - -func checkAgainstInt64(e int64, c reflect.Value) (err error) { - err = errors.New("") - - switch { - case isSignedInteger(c): - if c.Int() == e { - err = nil - } - - case isUnsignedInteger(c): - u := c.Uint() - if u <= math.MaxInt64 && int64(u) == e { - err = nil - } - - // Turn around the various floating point types so that the checkAgainst* - // functions for them can deal with precision issues. - case isFloat(c), isComplex(c): - return Equals(c.Interface()).Matches(e) - - default: - err = NewFatalError("which is not numeric") - } - - return -} - -func checkAgainstUint64(e uint64, c reflect.Value) (err error) { - err = errors.New("") - - switch { - case isSignedInteger(c): - i := c.Int() - if i >= 0 && uint64(i) == e { - err = nil - } - - case isUnsignedInteger(c): - if c.Uint() == e { - err = nil - } - - // Turn around the various floating point types so that the checkAgainst* - // functions for them can deal with precision issues. - case isFloat(c), isComplex(c): - return Equals(c.Interface()).Matches(e) - - default: - err = NewFatalError("which is not numeric") - } - - return -} - -func checkAgainstFloat32(e float32, c reflect.Value) (err error) { - err = errors.New("") - - switch { - case isSignedInteger(c): - if float32(c.Int()) == e { - err = nil - } - - case isUnsignedInteger(c): - if float32(c.Uint()) == e { - err = nil - } - - case isFloat(c): - // Compare using float32 to avoid a false sense of precision; otherwise - // e.g. Equals(float32(0.1)) won't match float32(0.1). - if float32(c.Float()) == e { - err = nil - } - - case isComplex(c): - comp := c.Complex() - rl := real(comp) - im := imag(comp) - - // Compare using float32 to avoid a false sense of precision; otherwise - // e.g. Equals(float32(0.1)) won't match (0.1 + 0i). - if im == 0 && float32(rl) == e { - err = nil - } - - default: - err = NewFatalError("which is not numeric") - } - - return -} - -func checkAgainstFloat64(e float64, c reflect.Value) (err error) { - err = errors.New("") - - ck := c.Kind() - - switch { - case isSignedInteger(c): - if float64(c.Int()) == e { - err = nil - } - - case isUnsignedInteger(c): - if float64(c.Uint()) == e { - err = nil - } - - // If the actual value is lower precision, turn the comparison around so we - // apply the low-precision rules. Otherwise, e.g. Equals(0.1) may not match - // float32(0.1). - case ck == reflect.Float32 || ck == reflect.Complex64: - return Equals(c.Interface()).Matches(e) - - // Otherwise, compare with double precision. - case isFloat(c): - if c.Float() == e { - err = nil - } - - case isComplex(c): - comp := c.Complex() - rl := real(comp) - im := imag(comp) - - if im == 0 && rl == e { - err = nil - } - - default: - err = NewFatalError("which is not numeric") - } - - return -} - -func checkAgainstComplex64(e complex64, c reflect.Value) (err error) { - err = errors.New("") - realPart := real(e) - imaginaryPart := imag(e) - - switch { - case isInteger(c) || isFloat(c): - // If we have no imaginary part, then we should just compare against the - // real part. Otherwise, we can't be equal. - if imaginaryPart != 0 { - return - } - - return checkAgainstFloat32(realPart, c) - - case isComplex(c): - // Compare using complex64 to avoid a false sense of precision; otherwise - // e.g. Equals(0.1 + 0i) won't match float32(0.1). - if complex64(c.Complex()) == e { - err = nil - } - - default: - err = NewFatalError("which is not numeric") - } - - return -} - -func checkAgainstComplex128(e complex128, c reflect.Value) (err error) { - err = errors.New("") - realPart := real(e) - imaginaryPart := imag(e) - - switch { - case isInteger(c) || isFloat(c): - // If we have no imaginary part, then we should just compare against the - // real part. Otherwise, we can't be equal. - if imaginaryPart != 0 { - return - } - - return checkAgainstFloat64(realPart, c) - - case isComplex(c): - if c.Complex() == e { - err = nil - } - - default: - err = NewFatalError("which is not numeric") - } - - return -} - -//////////////////////////////////////////////////////////////////////// -// Other types -//////////////////////////////////////////////////////////////////////// - -func checkAgainstBool(e bool, c reflect.Value) (err error) { - if c.Kind() != reflect.Bool { - err = NewFatalError("which is not a bool") - return - } - - err = errors.New("") - if c.Bool() == e { - err = nil - } - return -} - -func checkAgainstChan(e reflect.Value, c reflect.Value) (err error) { - // Create a description of e's type, e.g. "chan int". - typeStr := fmt.Sprintf("%s %s", e.Type().ChanDir(), e.Type().Elem()) - - // Make sure c is a chan of the correct type. - if c.Kind() != reflect.Chan || - c.Type().ChanDir() != e.Type().ChanDir() || - c.Type().Elem() != e.Type().Elem() { - err = NewFatalError(fmt.Sprintf("which is not a %s", typeStr)) - return - } - - err = errors.New("") - if c.Pointer() == e.Pointer() { - err = nil - } - return -} - -func checkAgainstFunc(e reflect.Value, c reflect.Value) (err error) { - // Make sure c is a function. - if c.Kind() != reflect.Func { - err = NewFatalError("which is not a function") - return - } - - err = errors.New("") - if c.Pointer() == e.Pointer() { - err = nil - } - return -} - -func checkAgainstMap(e reflect.Value, c reflect.Value) (err error) { - // Make sure c is a map. - if c.Kind() != reflect.Map { - err = NewFatalError("which is not a map") - return - } - - err = errors.New("") - if c.Pointer() == e.Pointer() { - err = nil - } - return -} - -func checkAgainstPtr(e reflect.Value, c reflect.Value) (err error) { - // Create a description of e's type, e.g. "*int". - typeStr := fmt.Sprintf("*%v", e.Type().Elem()) - - // Make sure c is a pointer of the correct type. - if c.Kind() != reflect.Ptr || - c.Type().Elem() != e.Type().Elem() { - err = NewFatalError(fmt.Sprintf("which is not a %s", typeStr)) - return - } - - err = errors.New("") - if c.Pointer() == e.Pointer() { - err = nil - } - return -} - -func checkAgainstSlice(e reflect.Value, c reflect.Value) (err error) { - // Create a description of e's type, e.g. "[]int". - typeStr := fmt.Sprintf("[]%v", e.Type().Elem()) - - // Make sure c is a slice of the correct type. - if c.Kind() != reflect.Slice || - c.Type().Elem() != e.Type().Elem() { - err = NewFatalError(fmt.Sprintf("which is not a %s", typeStr)) - return - } - - err = errors.New("") - if c.Pointer() == e.Pointer() { - err = nil - } - return -} - -func checkAgainstString(e reflect.Value, c reflect.Value) (err error) { - // Make sure c is a string. - if c.Kind() != reflect.String { - err = NewFatalError("which is not a string") - return - } - - err = errors.New("") - if c.String() == e.String() { - err = nil - } - return -} - -func checkAgainstArray(e reflect.Value, c reflect.Value) (err error) { - // Create a description of e's type, e.g. "[2]int". - typeStr := fmt.Sprintf("%v", e.Type()) - - // Make sure c is the correct type. - if c.Type() != e.Type() { - err = NewFatalError(fmt.Sprintf("which is not %s", typeStr)) - return - } - - // Check for equality. - if e.Interface() != c.Interface() { - err = errors.New("") - return - } - - return -} - -func checkAgainstUnsafePointer(e reflect.Value, c reflect.Value) (err error) { - // Make sure c is a pointer. - if c.Kind() != reflect.UnsafePointer { - err = NewFatalError("which is not a unsafe.Pointer") - return - } - - err = errors.New("") - if c.Pointer() == e.Pointer() { - err = nil - } - return -} - -func checkForNil(c reflect.Value) (err error) { - err = errors.New("") - - // Make sure it is legal to call IsNil. - switch c.Kind() { - case reflect.Invalid: - case reflect.Chan: - case reflect.Func: - case reflect.Interface: - case reflect.Map: - case reflect.Ptr: - case reflect.Slice: - - default: - err = NewFatalError("which cannot be compared to nil") - return - } - - // Ask whether the value is nil. Handle a nil literal (kind Invalid) - // specially, since it's not legal to call IsNil there. - if c.Kind() == reflect.Invalid || c.IsNil() { - err = nil - } - return -} - -//////////////////////////////////////////////////////////////////////// -// Public implementation -//////////////////////////////////////////////////////////////////////// - -func (m *equalsMatcher) Matches(candidate interface{}) error { - e := m.expectedValue - c := reflect.ValueOf(candidate) - ek := e.Kind() - - switch { - case ek == reflect.Bool: - return checkAgainstBool(e.Bool(), c) - - case isSignedInteger(e): - return checkAgainstInt64(e.Int(), c) - - case isUnsignedInteger(e): - return checkAgainstUint64(e.Uint(), c) - - case ek == reflect.Float32: - return checkAgainstFloat32(float32(e.Float()), c) - - case ek == reflect.Float64: - return checkAgainstFloat64(e.Float(), c) - - case ek == reflect.Complex64: - return checkAgainstComplex64(complex64(e.Complex()), c) - - case ek == reflect.Complex128: - return checkAgainstComplex128(complex128(e.Complex()), c) - - case ek == reflect.Chan: - return checkAgainstChan(e, c) - - case ek == reflect.Func: - return checkAgainstFunc(e, c) - - case ek == reflect.Map: - return checkAgainstMap(e, c) - - case ek == reflect.Ptr: - return checkAgainstPtr(e, c) - - case ek == reflect.Slice: - return checkAgainstSlice(e, c) - - case ek == reflect.String: - return checkAgainstString(e, c) - - case ek == reflect.Array: - return checkAgainstArray(e, c) - - case ek == reflect.UnsafePointer: - return checkAgainstUnsafePointer(e, c) - - case ek == reflect.Invalid: - return checkForNil(c) - } - - panic(fmt.Sprintf("equalsMatcher.Matches: unexpected kind: %v", ek)) -} - -func (m *equalsMatcher) Description() string { - // Special case: handle nil. - if !m.expectedValue.IsValid() { - return "is nil" - } - - return fmt.Sprintf("%v", m.expectedValue.Interface()) -} diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/greater_or_equal.go b/vendor/github.com/smartystreets/assertions/internal/oglematchers/greater_or_equal.go deleted file mode 100644 index 4b9d103a38189..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/oglematchers/greater_or_equal.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "fmt" - "reflect" -) - -// GreaterOrEqual returns a matcher that matches integer, floating point, or -// strings values v such that v >= x. Comparison is not defined between numeric -// and string types, but is defined between all integer and floating point -// types. -// -// x must itself be an integer, floating point, or string type; otherwise, -// GreaterOrEqual will panic. -func GreaterOrEqual(x interface{}) Matcher { - desc := fmt.Sprintf("greater than or equal to %v", x) - - // Special case: make it clear that strings are strings. - if reflect.TypeOf(x).Kind() == reflect.String { - desc = fmt.Sprintf("greater than or equal to \"%s\"", x) - } - - return transformDescription(Not(LessThan(x)), desc) -} diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/greater_than.go b/vendor/github.com/smartystreets/assertions/internal/oglematchers/greater_than.go deleted file mode 100644 index 3eef32178f8c1..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/oglematchers/greater_than.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "fmt" - "reflect" -) - -// GreaterThan returns a matcher that matches integer, floating point, or -// strings values v such that v > x. Comparison is not defined between numeric -// and string types, but is defined between all integer and floating point -// types. -// -// x must itself be an integer, floating point, or string type; otherwise, -// GreaterThan will panic. -func GreaterThan(x interface{}) Matcher { - desc := fmt.Sprintf("greater than %v", x) - - // Special case: make it clear that strings are strings. - if reflect.TypeOf(x).Kind() == reflect.String { - desc = fmt.Sprintf("greater than \"%s\"", x) - } - - return transformDescription(Not(LessOrEqual(x)), desc) -} diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/less_or_equal.go b/vendor/github.com/smartystreets/assertions/internal/oglematchers/less_or_equal.go deleted file mode 100644 index 8402cdeaf0996..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/oglematchers/less_or_equal.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "fmt" - "reflect" -) - -// LessOrEqual returns a matcher that matches integer, floating point, or -// strings values v such that v <= x. Comparison is not defined between numeric -// and string types, but is defined between all integer and floating point -// types. -// -// x must itself be an integer, floating point, or string type; otherwise, -// LessOrEqual will panic. -func LessOrEqual(x interface{}) Matcher { - desc := fmt.Sprintf("less than or equal to %v", x) - - // Special case: make it clear that strings are strings. - if reflect.TypeOf(x).Kind() == reflect.String { - desc = fmt.Sprintf("less than or equal to \"%s\"", x) - } - - // Put LessThan last so that its error messages will be used in the event of - // failure. - return transformDescription(AnyOf(Equals(x), LessThan(x)), desc) -} diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/less_than.go b/vendor/github.com/smartystreets/assertions/internal/oglematchers/less_than.go deleted file mode 100644 index 8258e45d99d83..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/oglematchers/less_than.go +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "errors" - "fmt" - "math" - "reflect" -) - -// LessThan returns a matcher that matches integer, floating point, or strings -// values v such that v < x. Comparison is not defined between numeric and -// string types, but is defined between all integer and floating point types. -// -// x must itself be an integer, floating point, or string type; otherwise, -// LessThan will panic. -func LessThan(x interface{}) Matcher { - v := reflect.ValueOf(x) - kind := v.Kind() - - switch { - case isInteger(v): - case isFloat(v): - case kind == reflect.String: - - default: - panic(fmt.Sprintf("LessThan: unexpected kind %v", kind)) - } - - return &lessThanMatcher{v} -} - -type lessThanMatcher struct { - limit reflect.Value -} - -func (m *lessThanMatcher) Description() string { - // Special case: make it clear that strings are strings. - if m.limit.Kind() == reflect.String { - return fmt.Sprintf("less than \"%s\"", m.limit.String()) - } - - return fmt.Sprintf("less than %v", m.limit.Interface()) -} - -func compareIntegers(v1, v2 reflect.Value) (err error) { - err = errors.New("") - - switch { - case isSignedInteger(v1) && isSignedInteger(v2): - if v1.Int() < v2.Int() { - err = nil - } - return - - case isSignedInteger(v1) && isUnsignedInteger(v2): - if v1.Int() < 0 || uint64(v1.Int()) < v2.Uint() { - err = nil - } - return - - case isUnsignedInteger(v1) && isSignedInteger(v2): - if v1.Uint() <= math.MaxInt64 && int64(v1.Uint()) < v2.Int() { - err = nil - } - return - - case isUnsignedInteger(v1) && isUnsignedInteger(v2): - if v1.Uint() < v2.Uint() { - err = nil - } - return - } - - panic(fmt.Sprintf("compareIntegers: %v %v", v1, v2)) -} - -func getFloat(v reflect.Value) float64 { - switch { - case isSignedInteger(v): - return float64(v.Int()) - - case isUnsignedInteger(v): - return float64(v.Uint()) - - case isFloat(v): - return v.Float() - } - - panic(fmt.Sprintf("getFloat: %v", v)) -} - -func (m *lessThanMatcher) Matches(c interface{}) (err error) { - v1 := reflect.ValueOf(c) - v2 := m.limit - - err = errors.New("") - - // Handle strings as a special case. - if v1.Kind() == reflect.String && v2.Kind() == reflect.String { - if v1.String() < v2.String() { - err = nil - } - return - } - - // If we get here, we require that we are dealing with integers or floats. - v1Legal := isInteger(v1) || isFloat(v1) - v2Legal := isInteger(v2) || isFloat(v2) - if !v1Legal || !v2Legal { - err = NewFatalError("which is not comparable") - return - } - - // Handle the various comparison cases. - switch { - // Both integers - case isInteger(v1) && isInteger(v2): - return compareIntegers(v1, v2) - - // At least one float32 - case v1.Kind() == reflect.Float32 || v2.Kind() == reflect.Float32: - if float32(getFloat(v1)) < float32(getFloat(v2)) { - err = nil - } - return - - // At least one float64 - case v1.Kind() == reflect.Float64 || v2.Kind() == reflect.Float64: - if getFloat(v1) < getFloat(v2) { - err = nil - } - return - } - - // We shouldn't get here. - panic(fmt.Sprintf("lessThanMatcher.Matches: Shouldn't get here: %v %v", v1, v2)) -} diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/matcher.go b/vendor/github.com/smartystreets/assertions/internal/oglematchers/matcher.go deleted file mode 100644 index 78159a0727c0d..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/oglematchers/matcher.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package oglematchers provides a set of matchers useful in a testing or -// mocking framework. These matchers are inspired by and mostly compatible with -// Google Test for C++ and Google JS Test. -// -// This package is used by github.com/smartystreets/assertions/internal/ogletest and -// github.com/smartystreets/assertions/internal/oglemock, which may be more directly useful if you're not -// writing your own testing package or defining your own matchers. -package oglematchers - -// A Matcher is some predicate implicitly defining a set of values that it -// matches. For example, GreaterThan(17) matches all numeric values greater -// than 17, and HasSubstr("taco") matches all strings with the substring -// "taco". -// -// Matchers are typically exposed to tests via constructor functions like -// HasSubstr. In order to implement such a function you can either define your -// own matcher type or use NewMatcher. -type Matcher interface { - // Check whether the supplied value belongs to the the set defined by the - // matcher. Return a non-nil error if and only if it does not. - // - // The error describes why the value doesn't match. The error text is a - // relative clause that is suitable for being placed after the value. For - // example, a predicate that matches strings with a particular substring may, - // when presented with a numerical value, return the following error text: - // - // "which is not a string" - // - // Then the failure message may look like: - // - // Expected: has substring "taco" - // Actual: 17, which is not a string - // - // If the error is self-apparent based on the description of the matcher, the - // error text may be empty (but the error still non-nil). For example: - // - // Expected: 17 - // Actual: 19 - // - // If you are implementing a new matcher, see also the documentation on - // FatalError. - Matches(candidate interface{}) error - - // Description returns a string describing the property that values matching - // this matcher have, as a verb phrase where the subject is the value. For - // example, "is greather than 17" or "has substring "taco"". - Description() string -} - -// FatalError is an implementation of the error interface that may be returned -// from matchers, indicating the error should be propagated. Returning a -// *FatalError indicates that the matcher doesn't process values of the -// supplied type, or otherwise doesn't know how to handle the value. -// -// For example, if GreaterThan(17) returned false for the value "taco" without -// a fatal error, then Not(GreaterThan(17)) would return true. This is -// technically correct, but is surprising and may mask failures where the wrong -// sort of matcher is accidentally used. Instead, GreaterThan(17) can return a -// fatal error, which will be propagated by Not(). -type FatalError struct { - errorText string -} - -// NewFatalError creates a FatalError struct with the supplied error text. -func NewFatalError(s string) *FatalError { - return &FatalError{s} -} - -func (e *FatalError) Error() string { - return e.errorText -} diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/not.go b/vendor/github.com/smartystreets/assertions/internal/oglematchers/not.go deleted file mode 100644 index 623789fe28a83..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/oglematchers/not.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -import ( - "errors" - "fmt" -) - -// Not returns a matcher that inverts the set of values matched by the wrapped -// matcher. It does not transform the result for values for which the wrapped -// matcher returns a fatal error. -func Not(m Matcher) Matcher { - return ¬Matcher{m} -} - -type notMatcher struct { - wrapped Matcher -} - -func (m *notMatcher) Matches(c interface{}) (err error) { - err = m.wrapped.Matches(c) - - // Did the wrapped matcher say yes? - if err == nil { - return errors.New("") - } - - // Did the wrapped matcher return a fatal error? - if _, isFatal := err.(*FatalError); isFatal { - return err - } - - // The wrapped matcher returned a non-fatal error. - return nil -} - -func (m *notMatcher) Description() string { - return fmt.Sprintf("not(%s)", m.wrapped.Description()) -} diff --git a/vendor/github.com/smartystreets/assertions/internal/oglematchers/transform_description.go b/vendor/github.com/smartystreets/assertions/internal/oglematchers/transform_description.go deleted file mode 100644 index 8ea2807c6f4e1..0000000000000 --- a/vendor/github.com/smartystreets/assertions/internal/oglematchers/transform_description.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2011 Aaron Jacobs. All Rights Reserved. -// Author: aaronjjacobs@gmail.com (Aaron Jacobs) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oglematchers - -// transformDescription returns a matcher that is equivalent to the supplied -// one, except that it has the supplied description instead of the one attached -// to the existing matcher. -func transformDescription(m Matcher, newDesc string) Matcher { - return &transformDescriptionMatcher{newDesc, m} -} - -type transformDescriptionMatcher struct { - desc string - wrappedMatcher Matcher -} - -func (m *transformDescriptionMatcher) Description() string { - return m.desc -} - -func (m *transformDescriptionMatcher) Matches(c interface{}) error { - return m.wrappedMatcher.Matches(c) -} diff --git a/vendor/github.com/smartystreets/assertions/messages.go b/vendor/github.com/smartystreets/assertions/messages.go deleted file mode 100644 index 178d7e4042415..0000000000000 --- a/vendor/github.com/smartystreets/assertions/messages.go +++ /dev/null @@ -1,108 +0,0 @@ -package assertions - -const ( - shouldHaveBeenEqual = "Expected: '%v'\nActual: '%v'\n(Should be equal)" - shouldHaveBeenEqualNoResemblance = "Both the actual and expected values render equally ('%s') and their types are the same. Try using ShouldResemble instead." - shouldNotHaveBeenEqual = "Expected '%v'\nto NOT equal '%v'\n(but it did)!" - shouldHaveBeenEqualTypeMismatch = "Expected: '%v' (%T)\nActual: '%v' (%T)\n(Should be equal, type mismatch)" - - shouldHaveBeenAlmostEqual = "Expected '%v' to almost equal '%v' (but it didn't)!" - shouldHaveNotBeenAlmostEqual = "Expected '%v' to NOT almost equal '%v' (but it did)!" - - shouldHaveResembled = "Expected: '%s'\nActual: '%s'\n(Should resemble)!" - shouldNotHaveResembled = "Expected '%#v'\nto NOT resemble '%#v'\n(but it did)!" - - shouldBePointers = "Both arguments should be pointers " - shouldHaveBeenNonNilPointer = shouldBePointers + "(the %s was %s)!" - shouldHavePointedTo = "Expected '%+v' (address: '%v') and '%+v' (address: '%v') to be the same address (but their weren't)!" - shouldNotHavePointedTo = "Expected '%+v' and '%+v' to be different references (but they matched: '%v')!" - - shouldHaveBeenNil = "Expected: nil\nActual: '%v'" - shouldNotHaveBeenNil = "Expected '%+v' to NOT be nil (but it was)!" - - shouldHaveBeenTrue = "Expected: true\nActual: %v" - shouldHaveBeenFalse = "Expected: false\nActual: %v" - - shouldHaveBeenZeroValue = "'%+v' should have been the zero value" //"Expected: (zero value)\nActual: %v" - shouldNotHaveBeenZeroValue = "'%+v' should NOT have been the zero value" - - shouldHaveBeenGreater = "Expected '%v' to be greater than '%v' (but it wasn't)!" - shouldHaveBeenGreaterOrEqual = "Expected '%v' to be greater than or equal to '%v' (but it wasn't)!" - - shouldHaveBeenLess = "Expected '%v' to be less than '%v' (but it wasn't)!" - shouldHaveBeenLessOrEqual = "Expected '%v' to be less than or equal to '%v' (but it wasn't)!" - - shouldHaveBeenBetween = "Expected '%v' to be between '%v' and '%v' (but it wasn't)!" - shouldNotHaveBeenBetween = "Expected '%v' NOT to be between '%v' and '%v' (but it was)!" - shouldHaveDifferentUpperAndLower = "The lower and upper bounds must be different values (they were both '%v')." - - shouldHaveBeenBetweenOrEqual = "Expected '%v' to be between '%v' and '%v' or equal to one of them (but it wasn't)!" - shouldNotHaveBeenBetweenOrEqual = "Expected '%v' NOT to be between '%v' and '%v' or equal to one of them (but it was)!" - - shouldHaveContained = "Expected the container (%v) to contain: '%v' (but it didn't)!" - shouldNotHaveContained = "Expected the container (%v) NOT to contain: '%v' (but it did)!" - shouldHaveBeenAValidCollection = "You must provide a valid container (was %v)!" - - shouldHaveContainedKey = "Expected the %v to contain the key: %v (but it didn't)!" - shouldNotHaveContainedKey = "Expected the %v NOT to contain the key: %v (but it did)!" - shouldHaveBeenAValidMap = "You must provide a valid map type (was %v)!" - - shouldHaveBeenIn = "Expected '%v' to be in the container (%v), but it wasn't!" - shouldNotHaveBeenIn = "Expected '%v' NOT to be in the container (%v), but it was!" - - shouldHaveBeenEmpty = "Expected %+v to be empty (but it wasn't)!" - shouldNotHaveBeenEmpty = "Expected %+v to NOT be empty (but it was)!" - - shouldHaveBeenAValidInteger = "You must provide a valid integer (was %v)!" - shouldHaveBeenAValidLength = "You must provide a valid positive integer (was %v)!" - shouldHaveHadLength = "Expected collection to have length equal to [%v], but it's length was [%v] instead! contents: %+v" - - shouldHaveStartedWith = "Expected '%v'\nto start with '%v'\n(but it didn't)!" - shouldNotHaveStartedWith = "Expected '%v'\nNOT to start with '%v'\n(but it did)!" - - shouldHaveEndedWith = "Expected '%v'\nto end with '%v'\n(but it didn't)!" - shouldNotHaveEndedWith = "Expected '%v'\nNOT to end with '%v'\n(but it did)!" - - shouldAllBeStrings = "All arguments to this assertion must be strings (you provided: %v)." - shouldBothBeStrings = "Both arguments to this assertion must be strings (you provided %v and %v)." - - shouldHaveContainedSubstring = "Expected '%s' to contain substring '%s' (but it didn't)!" - shouldNotHaveContainedSubstring = "Expected '%s' NOT to contain substring '%s' (but it did)!" - - shouldBeString = "The argument to this assertion must be a string (you provided %v)." - shouldHaveBeenBlank = "Expected '%s' to be blank (but it wasn't)!" - shouldNotHaveBeenBlank = "Expected value to NOT be blank (but it was)!" - - shouldUseVoidNiladicFunction = "You must provide a void, niladic function as the first argument!" - shouldHavePanicked = "Expected func() to panic (but it didn't)!" - shouldNotHavePanicked = "Expected func() NOT to panic (error: '%+v')!" - - shouldHavePanickedWith = "Expected func() to panic with '%v' (but it panicked with '%v')!" - shouldNotHavePanickedWith = "Expected func() NOT to panic with '%v' (but it did)!" - - shouldHaveBeenA = "Expected '%v' to be: '%v' (but was: '%v')!" - shouldNotHaveBeenA = "Expected '%v' to NOT be: '%v' (but it was)!" - - shouldHaveImplemented = "Expected: '%v interface support'\nActual: '%v' does not implement the interface!" - shouldNotHaveImplemented = "Expected '%v'\nto NOT implement '%v'\n(but it did)!" - shouldCompareWithInterfacePointer = "The expected value must be a pointer to an interface type (eg. *fmt.Stringer)" - shouldNotBeNilActual = "The actual value was 'nil' and should be a value or a pointer to a value!" - - shouldBeError = "Expected an error value (but was '%v' instead)!" - shouldBeErrorInvalidComparisonValue = "The final argument to this assertion must be a string or an error value (you provided: '%v')." - - shouldWrapInvalidTypes = "The first and last arguments to this assertion must both be error values (you provided: '%v' and '%v')." - - shouldUseTimes = "You must provide time instances as arguments to this assertion." - shouldUseTimeSlice = "You must provide a slice of time instances as the first argument to this assertion." - shouldUseDurationAndTime = "You must provide a duration and a time as arguments to this assertion." - - shouldHaveHappenedBefore = "Expected '%v' to happen before '%v' (it happened '%v' after)!" - shouldHaveHappenedAfter = "Expected '%v' to happen after '%v' (it happened '%v' before)!" - shouldHaveHappenedBetween = "Expected '%v' to happen between '%v' and '%v' (it happened '%v' outside threshold)!" - shouldNotHaveHappenedOnOrBetween = "Expected '%v' to NOT happen on or between '%v' and '%v' (but it did)!" - - // format params: incorrect-index, previous-index, previous-time, incorrect-index, incorrect-time - shouldHaveBeenChronological = "The 'Time' at index [%d] should have happened after the previous one (but it didn't!):\n [%d]: %s\n [%d]: %s (see, it happened before!)" - shouldNotHaveBeenchronological = "The provided times should NOT be chronological, but they were." -) diff --git a/vendor/github.com/smartystreets/assertions/panic.go b/vendor/github.com/smartystreets/assertions/panic.go deleted file mode 100644 index d290d9f324e9c..0000000000000 --- a/vendor/github.com/smartystreets/assertions/panic.go +++ /dev/null @@ -1,128 +0,0 @@ -package assertions - -import ( - "errors" - "fmt" -) - -// ShouldPanic receives a void, niladic function and expects to recover a panic. -func ShouldPanic(actual interface{}, expected ...interface{}) (message string) { - if fail := need(0, expected); fail != success { - return fail - } - - action, _ := actual.(func()) - - if action == nil { - message = shouldUseVoidNiladicFunction - return - } - - defer func() { - recovered := recover() - if recovered == nil { - message = shouldHavePanicked - } else { - message = success - } - }() - action() - - return -} - -// ShouldNotPanic receives a void, niladic function and expects to execute the function without any panic. -func ShouldNotPanic(actual interface{}, expected ...interface{}) (message string) { - if fail := need(0, expected); fail != success { - return fail - } - - action, _ := actual.(func()) - - if action == nil { - message = shouldUseVoidNiladicFunction - return - } - - defer func() { - recovered := recover() - if recovered != nil { - message = fmt.Sprintf(shouldNotHavePanicked, recovered) - } else { - message = success - } - }() - action() - - return -} - -// ShouldPanicWith receives a void, niladic function and expects to recover a panic with the second argument as the content. -// If the expected value is an error and the recovered value is an error, errors.Is is used to compare them. -func ShouldPanicWith(actual interface{}, expected ...interface{}) (message string) { - if fail := need(1, expected); fail != success { - return fail - } - - action, _ := actual.(func()) - - if action == nil { - message = shouldUseVoidNiladicFunction - return - } - - defer func() { - recovered := recover() - if recovered == nil { - message = shouldHavePanicked - } else { - recoveredErr, errFound := recovered.(error) - expectedErr, expectedFound := expected[0].(error) - if errFound && expectedFound && errors.Is(recoveredErr, expectedErr) { - message = success - } else if equal := ShouldEqual(recovered, expected[0]); equal != success { - message = serializer.serialize(expected[0], recovered, fmt.Sprintf(shouldHavePanickedWith, expected[0], recovered)) - } else { - message = success - } - } - }() - action() - - return -} - -// ShouldNotPanicWith receives a void, niladic function and expects to recover a panic whose content differs from the second argument. -// If the expected value is an error and the recovered value is an error, errors.Is is used to compare them. -func ShouldNotPanicWith(actual interface{}, expected ...interface{}) (message string) { - if fail := need(1, expected); fail != success { - return fail - } - - action, _ := actual.(func()) - - if action == nil { - message = shouldUseVoidNiladicFunction - return - } - - defer func() { - recovered := recover() - if recovered == nil { - message = success - } else { - recoveredErr, errFound := recovered.(error) - expectedErr, expectedFound := expected[0].(error) - if errFound && expectedFound && errors.Is(recoveredErr, expectedErr) { - message = fmt.Sprintf(shouldNotHavePanickedWith, expected[0]) - } else if equal := ShouldEqual(recovered, expected[0]); equal == success { - message = fmt.Sprintf(shouldNotHavePanickedWith, expected[0]) - } else { - message = success - } - } - }() - action() - - return -} diff --git a/vendor/github.com/smartystreets/assertions/quantity.go b/vendor/github.com/smartystreets/assertions/quantity.go deleted file mode 100644 index f28b0a062ba5c..0000000000000 --- a/vendor/github.com/smartystreets/assertions/quantity.go +++ /dev/null @@ -1,141 +0,0 @@ -package assertions - -import ( - "fmt" - - "github.com/smartystreets/assertions/internal/oglematchers" -) - -// ShouldBeGreaterThan receives exactly two parameters and ensures that the first is greater than the second. -func ShouldBeGreaterThan(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - if matchError := oglematchers.GreaterThan(expected[0]).Matches(actual); matchError != nil { - return fmt.Sprintf(shouldHaveBeenGreater, actual, expected[0]) - } - return success -} - -// ShouldBeGreaterThanOrEqualTo receives exactly two parameters and ensures that the first is greater than or equal to the second. -func ShouldBeGreaterThanOrEqualTo(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } else if matchError := oglematchers.GreaterOrEqual(expected[0]).Matches(actual); matchError != nil { - return fmt.Sprintf(shouldHaveBeenGreaterOrEqual, actual, expected[0]) - } - return success -} - -// ShouldBeLessThan receives exactly two parameters and ensures that the first is less than the second. -func ShouldBeLessThan(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } else if matchError := oglematchers.LessThan(expected[0]).Matches(actual); matchError != nil { - return fmt.Sprintf(shouldHaveBeenLess, actual, expected[0]) - } - return success -} - -// ShouldBeLessThan receives exactly two parameters and ensures that the first is less than or equal to the second. -func ShouldBeLessThanOrEqualTo(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } else if matchError := oglematchers.LessOrEqual(expected[0]).Matches(actual); matchError != nil { - return fmt.Sprintf(shouldHaveBeenLessOrEqual, actual, expected[0]) - } - return success -} - -// ShouldBeBetween receives exactly three parameters: an actual value, a lower bound, and an upper bound. -// It ensures that the actual value is between both bounds (but not equal to either of them). -func ShouldBeBetween(actual interface{}, expected ...interface{}) string { - if fail := need(2, expected); fail != success { - return fail - } - lower, upper, fail := deriveBounds(expected) - - if fail != success { - return fail - } else if !isBetween(actual, lower, upper) { - return fmt.Sprintf(shouldHaveBeenBetween, actual, lower, upper) - } - return success -} - -// ShouldNotBeBetween receives exactly three parameters: an actual value, a lower bound, and an upper bound. -// It ensures that the actual value is NOT between both bounds. -func ShouldNotBeBetween(actual interface{}, expected ...interface{}) string { - if fail := need(2, expected); fail != success { - return fail - } - lower, upper, fail := deriveBounds(expected) - - if fail != success { - return fail - } else if isBetween(actual, lower, upper) { - return fmt.Sprintf(shouldNotHaveBeenBetween, actual, lower, upper) - } - return success -} -func deriveBounds(values []interface{}) (lower interface{}, upper interface{}, fail string) { - lower = values[0] - upper = values[1] - - if ShouldNotEqual(lower, upper) != success { - return nil, nil, fmt.Sprintf(shouldHaveDifferentUpperAndLower, lower) - } else if ShouldBeLessThan(lower, upper) != success { - lower, upper = upper, lower - } - return lower, upper, success -} -func isBetween(value, lower, upper interface{}) bool { - if ShouldBeGreaterThan(value, lower) != success { - return false - } else if ShouldBeLessThan(value, upper) != success { - return false - } - return true -} - -// ShouldBeBetweenOrEqual receives exactly three parameters: an actual value, a lower bound, and an upper bound. -// It ensures that the actual value is between both bounds or equal to one of them. -func ShouldBeBetweenOrEqual(actual interface{}, expected ...interface{}) string { - if fail := need(2, expected); fail != success { - return fail - } - lower, upper, fail := deriveBounds(expected) - - if fail != success { - return fail - } else if !isBetweenOrEqual(actual, lower, upper) { - return fmt.Sprintf(shouldHaveBeenBetweenOrEqual, actual, lower, upper) - } - return success -} - -// ShouldNotBeBetweenOrEqual receives exactly three parameters: an actual value, a lower bound, and an upper bound. -// It ensures that the actual value is nopt between the bounds nor equal to either of them. -func ShouldNotBeBetweenOrEqual(actual interface{}, expected ...interface{}) string { - if fail := need(2, expected); fail != success { - return fail - } - lower, upper, fail := deriveBounds(expected) - - if fail != success { - return fail - } else if isBetweenOrEqual(actual, lower, upper) { - return fmt.Sprintf(shouldNotHaveBeenBetweenOrEqual, actual, lower, upper) - } - return success -} - -func isBetweenOrEqual(value, lower, upper interface{}) bool { - if ShouldBeGreaterThanOrEqualTo(value, lower) != success { - return false - } else if ShouldBeLessThanOrEqualTo(value, upper) != success { - return false - } - return true -} diff --git a/vendor/github.com/smartystreets/assertions/serializer.go b/vendor/github.com/smartystreets/assertions/serializer.go deleted file mode 100644 index f1e3570edc489..0000000000000 --- a/vendor/github.com/smartystreets/assertions/serializer.go +++ /dev/null @@ -1,70 +0,0 @@ -package assertions - -import ( - "encoding/json" - "fmt" - "strings" - - "github.com/smartystreets/assertions/internal/go-render/render" -) - -type Serializer interface { - serialize(expected, actual interface{}, message string) string - serializeDetailed(expected, actual interface{}, message string) string -} - -type failureSerializer struct{} - -func (self *failureSerializer) serializeDetailed(expected, actual interface{}, message string) string { - if index := strings.Index(message, " Diff:"); index > 0 { - message = message[:index] - } - view := FailureView{ - Message: message, - Expected: render.Render(expected), - Actual: render.Render(actual), - } - serialized, _ := json.Marshal(view) - return string(serialized) -} - -func (self *failureSerializer) serialize(expected, actual interface{}, message string) string { - if index := strings.Index(message, " Diff:"); index > 0 { - message = message[:index] - } - view := FailureView{ - Message: message, - Expected: fmt.Sprintf("%+v", expected), - Actual: fmt.Sprintf("%+v", actual), - } - serialized, _ := json.Marshal(view) - return string(serialized) -} - -func newSerializer() *failureSerializer { - return &failureSerializer{} -} - -/////////////////////////////////////////////////////////////////////////////// - -// This struct is also declared in github.com/smartystreets/goconvey/convey/reporting. -// The json struct tags should be equal in both declarations. -type FailureView struct { - Message string `json:"Message"` - Expected string `json:"Expected"` - Actual string `json:"Actual"` -} - -/////////////////////////////////////////////////////// - -// noopSerializer just gives back the original message. This is useful when we are using -// the assertions from a context other than the GoConvey Web UI, that requires the JSON -// structure provided by the failureSerializer. -type noopSerializer struct{} - -func (self *noopSerializer) serialize(expected, actual interface{}, message string) string { - return message -} -func (self *noopSerializer) serializeDetailed(expected, actual interface{}, message string) string { - return message -} diff --git a/vendor/github.com/smartystreets/assertions/strings.go b/vendor/github.com/smartystreets/assertions/strings.go deleted file mode 100644 index dbc3f04790e01..0000000000000 --- a/vendor/github.com/smartystreets/assertions/strings.go +++ /dev/null @@ -1,227 +0,0 @@ -package assertions - -import ( - "fmt" - "reflect" - "strings" -) - -// ShouldStartWith receives exactly 2 string parameters and ensures that the first starts with the second. -func ShouldStartWith(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - value, valueIsString := actual.(string) - prefix, prefixIsString := expected[0].(string) - - if !valueIsString || !prefixIsString { - return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) - } - - return shouldStartWith(value, prefix) -} -func shouldStartWith(value, prefix string) string { - if !strings.HasPrefix(value, prefix) { - shortval := value - if len(shortval) > len(prefix) { - shortval = shortval[:len(prefix)] + "..." - } - return serializer.serialize(prefix, shortval, fmt.Sprintf(shouldHaveStartedWith, value, prefix)) - } - return success -} - -// ShouldNotStartWith receives exactly 2 string parameters and ensures that the first does not start with the second. -func ShouldNotStartWith(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - value, valueIsString := actual.(string) - prefix, prefixIsString := expected[0].(string) - - if !valueIsString || !prefixIsString { - return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) - } - - return shouldNotStartWith(value, prefix) -} -func shouldNotStartWith(value, prefix string) string { - if strings.HasPrefix(value, prefix) { - if value == "" { - value = "" - } - if prefix == "" { - prefix = "" - } - return fmt.Sprintf(shouldNotHaveStartedWith, value, prefix) - } - return success -} - -// ShouldEndWith receives exactly 2 string parameters and ensures that the first ends with the second. -func ShouldEndWith(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - value, valueIsString := actual.(string) - suffix, suffixIsString := expected[0].(string) - - if !valueIsString || !suffixIsString { - return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) - } - - return shouldEndWith(value, suffix) -} -func shouldEndWith(value, suffix string) string { - if !strings.HasSuffix(value, suffix) { - shortval := value - if len(shortval) > len(suffix) { - shortval = "..." + shortval[len(shortval)-len(suffix):] - } - return serializer.serialize(suffix, shortval, fmt.Sprintf(shouldHaveEndedWith, value, suffix)) - } - return success -} - -// ShouldEndWith receives exactly 2 string parameters and ensures that the first does not end with the second. -func ShouldNotEndWith(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - value, valueIsString := actual.(string) - suffix, suffixIsString := expected[0].(string) - - if !valueIsString || !suffixIsString { - return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) - } - - return shouldNotEndWith(value, suffix) -} -func shouldNotEndWith(value, suffix string) string { - if strings.HasSuffix(value, suffix) { - if value == "" { - value = "" - } - if suffix == "" { - suffix = "" - } - return fmt.Sprintf(shouldNotHaveEndedWith, value, suffix) - } - return success -} - -// ShouldContainSubstring receives exactly 2 string parameters and ensures that the first contains the second as a substring. -func ShouldContainSubstring(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - long, longOk := actual.(string) - short, shortOk := expected[0].(string) - - if !longOk || !shortOk { - return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) - } - - if !strings.Contains(long, short) { - return serializer.serialize(expected[0], actual, fmt.Sprintf(shouldHaveContainedSubstring, long, short)) - } - return success -} - -// ShouldNotContainSubstring receives exactly 2 string parameters and ensures that the first does NOT contain the second as a substring. -func ShouldNotContainSubstring(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - long, longOk := actual.(string) - short, shortOk := expected[0].(string) - - if !longOk || !shortOk { - return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) - } - - if strings.Contains(long, short) { - return fmt.Sprintf(shouldNotHaveContainedSubstring, long, short) - } - return success -} - -// ShouldBeBlank receives exactly 1 string parameter and ensures that it is equal to "". -func ShouldBeBlank(actual interface{}, expected ...interface{}) string { - if fail := need(0, expected); fail != success { - return fail - } - value, ok := actual.(string) - if !ok { - return fmt.Sprintf(shouldBeString, reflect.TypeOf(actual)) - } - if value != "" { - return serializer.serialize("", value, fmt.Sprintf(shouldHaveBeenBlank, value)) - } - return success -} - -// ShouldNotBeBlank receives exactly 1 string parameter and ensures that it is equal to "". -func ShouldNotBeBlank(actual interface{}, expected ...interface{}) string { - if fail := need(0, expected); fail != success { - return fail - } - value, ok := actual.(string) - if !ok { - return fmt.Sprintf(shouldBeString, reflect.TypeOf(actual)) - } - if value == "" { - return shouldNotHaveBeenBlank - } - return success -} - -// ShouldEqualWithout receives exactly 3 string parameters and ensures that the first is equal to the second -// after removing all instances of the third from the first using strings.Replace(first, third, "", -1). -func ShouldEqualWithout(actual interface{}, expected ...interface{}) string { - if fail := need(2, expected); fail != success { - return fail - } - actualString, ok1 := actual.(string) - expectedString, ok2 := expected[0].(string) - replace, ok3 := expected[1].(string) - - if !ok1 || !ok2 || !ok3 { - return fmt.Sprintf(shouldAllBeStrings, []reflect.Type{ - reflect.TypeOf(actual), - reflect.TypeOf(expected[0]), - reflect.TypeOf(expected[1]), - }) - } - - replaced := strings.Replace(actualString, replace, "", -1) - if replaced == expectedString { - return "" - } - - return fmt.Sprintf("Expected '%s' to equal '%s' but without any '%s' (but it didn't).", actualString, expectedString, replace) -} - -// ShouldEqualTrimSpace receives exactly 2 string parameters and ensures that the first is equal to the second -// after removing all leading and trailing whitespace using strings.TrimSpace(first). -func ShouldEqualTrimSpace(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - actualString, valueIsString := actual.(string) - _, value2IsString := expected[0].(string) - - if !valueIsString || !value2IsString { - return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) - } - - actualString = strings.TrimSpace(actualString) - return ShouldEqual(actualString, expected[0]) -} diff --git a/vendor/github.com/smartystreets/assertions/time.go b/vendor/github.com/smartystreets/assertions/time.go deleted file mode 100644 index 918ee2840e6df..0000000000000 --- a/vendor/github.com/smartystreets/assertions/time.go +++ /dev/null @@ -1,218 +0,0 @@ -package assertions - -import ( - "fmt" - "time" -) - -// ShouldHappenBefore receives exactly 2 time.Time arguments and asserts that the first happens before the second. -func ShouldHappenBefore(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - actualTime, firstOk := actual.(time.Time) - expectedTime, secondOk := expected[0].(time.Time) - - if !firstOk || !secondOk { - return shouldUseTimes - } - - if !actualTime.Before(expectedTime) { - return fmt.Sprintf(shouldHaveHappenedBefore, actualTime, expectedTime, actualTime.Sub(expectedTime)) - } - - return success -} - -// ShouldHappenOnOrBefore receives exactly 2 time.Time arguments and asserts that the first happens on or before the second. -func ShouldHappenOnOrBefore(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - actualTime, firstOk := actual.(time.Time) - expectedTime, secondOk := expected[0].(time.Time) - - if !firstOk || !secondOk { - return shouldUseTimes - } - - if actualTime.Equal(expectedTime) { - return success - } - return ShouldHappenBefore(actualTime, expectedTime) -} - -// ShouldHappenAfter receives exactly 2 time.Time arguments and asserts that the first happens after the second. -func ShouldHappenAfter(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - actualTime, firstOk := actual.(time.Time) - expectedTime, secondOk := expected[0].(time.Time) - - if !firstOk || !secondOk { - return shouldUseTimes - } - if !actualTime.After(expectedTime) { - return fmt.Sprintf(shouldHaveHappenedAfter, actualTime, expectedTime, expectedTime.Sub(actualTime)) - } - return success -} - -// ShouldHappenOnOrAfter receives exactly 2 time.Time arguments and asserts that the first happens on or after the second. -func ShouldHappenOnOrAfter(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - actualTime, firstOk := actual.(time.Time) - expectedTime, secondOk := expected[0].(time.Time) - - if !firstOk || !secondOk { - return shouldUseTimes - } - if actualTime.Equal(expectedTime) { - return success - } - return ShouldHappenAfter(actualTime, expectedTime) -} - -// ShouldHappenBetween receives exactly 3 time.Time arguments and asserts that the first happens between (not on) the second and third. -func ShouldHappenBetween(actual interface{}, expected ...interface{}) string { - if fail := need(2, expected); fail != success { - return fail - } - actualTime, firstOk := actual.(time.Time) - min, secondOk := expected[0].(time.Time) - max, thirdOk := expected[1].(time.Time) - - if !firstOk || !secondOk || !thirdOk { - return shouldUseTimes - } - - if !actualTime.After(min) { - return fmt.Sprintf(shouldHaveHappenedBetween, actualTime, min, max, min.Sub(actualTime)) - } - if !actualTime.Before(max) { - return fmt.Sprintf(shouldHaveHappenedBetween, actualTime, min, max, actualTime.Sub(max)) - } - return success -} - -// ShouldHappenOnOrBetween receives exactly 3 time.Time arguments and asserts that the first happens between or on the second and third. -func ShouldHappenOnOrBetween(actual interface{}, expected ...interface{}) string { - if fail := need(2, expected); fail != success { - return fail - } - actualTime, firstOk := actual.(time.Time) - min, secondOk := expected[0].(time.Time) - max, thirdOk := expected[1].(time.Time) - - if !firstOk || !secondOk || !thirdOk { - return shouldUseTimes - } - if actualTime.Equal(min) || actualTime.Equal(max) { - return success - } - return ShouldHappenBetween(actualTime, min, max) -} - -// ShouldNotHappenOnOrBetween receives exactly 3 time.Time arguments and asserts that the first -// does NOT happen between or on the second or third. -func ShouldNotHappenOnOrBetween(actual interface{}, expected ...interface{}) string { - if fail := need(2, expected); fail != success { - return fail - } - actualTime, firstOk := actual.(time.Time) - min, secondOk := expected[0].(time.Time) - max, thirdOk := expected[1].(time.Time) - - if !firstOk || !secondOk || !thirdOk { - return shouldUseTimes - } - if actualTime.Equal(min) || actualTime.Equal(max) { - return fmt.Sprintf(shouldNotHaveHappenedOnOrBetween, actualTime, min, max) - } - if actualTime.After(min) && actualTime.Before(max) { - return fmt.Sprintf(shouldNotHaveHappenedOnOrBetween, actualTime, min, max) - } - return success -} - -// ShouldHappenWithin receives a time.Time, a time.Duration, and a time.Time (3 arguments) -// and asserts that the first time.Time happens within or on the duration specified relative to -// the other time.Time. -func ShouldHappenWithin(actual interface{}, expected ...interface{}) string { - if fail := need(2, expected); fail != success { - return fail - } - actualTime, firstOk := actual.(time.Time) - tolerance, secondOk := expected[0].(time.Duration) - threshold, thirdOk := expected[1].(time.Time) - - if !firstOk || !secondOk || !thirdOk { - return shouldUseDurationAndTime - } - - min := threshold.Add(-tolerance) - max := threshold.Add(tolerance) - return ShouldHappenOnOrBetween(actualTime, min, max) -} - -// ShouldNotHappenWithin receives a time.Time, a time.Duration, and a time.Time (3 arguments) -// and asserts that the first time.Time does NOT happen within or on the duration specified relative to -// the other time.Time. -func ShouldNotHappenWithin(actual interface{}, expected ...interface{}) string { - if fail := need(2, expected); fail != success { - return fail - } - actualTime, firstOk := actual.(time.Time) - tolerance, secondOk := expected[0].(time.Duration) - threshold, thirdOk := expected[1].(time.Time) - - if !firstOk || !secondOk || !thirdOk { - return shouldUseDurationAndTime - } - - min := threshold.Add(-tolerance) - max := threshold.Add(tolerance) - return ShouldNotHappenOnOrBetween(actualTime, min, max) -} - -// ShouldBeChronological receives a []time.Time slice and asserts that they are -// in chronological order starting with the first time.Time as the earliest. -func ShouldBeChronological(actual interface{}, expected ...interface{}) string { - if fail := need(0, expected); fail != success { - return fail - } - - times, ok := actual.([]time.Time) - if !ok { - return shouldUseTimeSlice - } - - var previous time.Time - for i, current := range times { - if i > 0 && current.Before(previous) { - return fmt.Sprintf(shouldHaveBeenChronological, - i, i-1, previous.String(), i, current.String()) - } - previous = current - } - return "" -} - -// ShouldNotBeChronological receives a []time.Time slice and asserts that they are -// NOT in chronological order. -func ShouldNotBeChronological(actual interface{}, expected ...interface{}) string { - if fail := need(0, expected); fail != success { - return fail - } - if _, ok := actual.([]time.Time); !ok { - return shouldUseTimeSlice - } - result := ShouldBeChronological(actual, expected...) - if result != "" { - return "" - } - return shouldNotHaveBeenchronological -} diff --git a/vendor/github.com/smartystreets/assertions/type.go b/vendor/github.com/smartystreets/assertions/type.go deleted file mode 100644 index 1984fe89454fa..0000000000000 --- a/vendor/github.com/smartystreets/assertions/type.go +++ /dev/null @@ -1,154 +0,0 @@ -package assertions - -import ( - "errors" - "fmt" - "reflect" -) - -// ShouldHaveSameTypeAs receives exactly two parameters and compares their underlying types for equality. -func ShouldHaveSameTypeAs(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - first := reflect.TypeOf(actual) - second := reflect.TypeOf(expected[0]) - - if first != second { - return serializer.serialize(second, first, fmt.Sprintf(shouldHaveBeenA, actual, second, first)) - } - - return success -} - -// ShouldNotHaveSameTypeAs receives exactly two parameters and compares their underlying types for inequality. -func ShouldNotHaveSameTypeAs(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - first := reflect.TypeOf(actual) - second := reflect.TypeOf(expected[0]) - - if (actual == nil && expected[0] == nil) || first == second { - return fmt.Sprintf(shouldNotHaveBeenA, actual, second) - } - return success -} - -// ShouldImplement receives exactly two parameters and ensures -// that the first implements the interface type of the second. -func ShouldImplement(actual interface{}, expectedList ...interface{}) string { - if fail := need(1, expectedList); fail != success { - return fail - } - - expected := expectedList[0] - if fail := ShouldBeNil(expected); fail != success { - return shouldCompareWithInterfacePointer - } - - if fail := ShouldNotBeNil(actual); fail != success { - return shouldNotBeNilActual - } - - var actualType reflect.Type - if reflect.TypeOf(actual).Kind() != reflect.Ptr { - actualType = reflect.PtrTo(reflect.TypeOf(actual)) - } else { - actualType = reflect.TypeOf(actual) - } - - expectedType := reflect.TypeOf(expected) - if fail := ShouldNotBeNil(expectedType); fail != success { - return shouldCompareWithInterfacePointer - } - - expectedInterface := expectedType.Elem() - - if !actualType.Implements(expectedInterface) { - return fmt.Sprintf(shouldHaveImplemented, expectedInterface, actualType) - } - return success -} - -// ShouldNotImplement receives exactly two parameters and ensures -// that the first does NOT implement the interface type of the second. -func ShouldNotImplement(actual interface{}, expectedList ...interface{}) string { - if fail := need(1, expectedList); fail != success { - return fail - } - - expected := expectedList[0] - if fail := ShouldBeNil(expected); fail != success { - return shouldCompareWithInterfacePointer - } - - if fail := ShouldNotBeNil(actual); fail != success { - return shouldNotBeNilActual - } - - var actualType reflect.Type - if reflect.TypeOf(actual).Kind() != reflect.Ptr { - actualType = reflect.PtrTo(reflect.TypeOf(actual)) - } else { - actualType = reflect.TypeOf(actual) - } - - expectedType := reflect.TypeOf(expected) - if fail := ShouldNotBeNil(expectedType); fail != success { - return shouldCompareWithInterfacePointer - } - - expectedInterface := expectedType.Elem() - - if actualType.Implements(expectedInterface) { - return fmt.Sprintf(shouldNotHaveImplemented, actualType, expectedInterface) - } - return success -} - -// ShouldBeError asserts that the first argument implements the error interface. -// It also compares the first argument against the second argument if provided -// (which must be an error message string or another error value). -func ShouldBeError(actual interface{}, expected ...interface{}) string { - if fail := atMost(1, expected); fail != success { - return fail - } - - if !isError(actual) { - return fmt.Sprintf(shouldBeError, reflect.TypeOf(actual)) - } - - if len(expected) == 0 { - return success - } - - if expected := expected[0]; !isString(expected) && !isError(expected) { - return fmt.Sprintf(shouldBeErrorInvalidComparisonValue, reflect.TypeOf(expected)) - } - return ShouldEqual(fmt.Sprint(actual), fmt.Sprint(expected[0])) -} - -// ShouldWrap asserts that the first argument (which must be an error value) -// 'wraps' the second/final argument (which must also be an error value). -// It relies on errors.Is to make the determination (https://golang.org/pkg/errors/#Is). -func ShouldWrap(actual interface{}, expected ...interface{}) string { - if fail := need(1, expected); fail != success { - return fail - } - - if !isError(actual) || !isError(expected[0]) { - return fmt.Sprintf(shouldWrapInvalidTypes, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) - } - - if !errors.Is(actual.(error), expected[0].(error)) { - return fmt.Sprintf(`Expected error("%s") to wrap error("%s") but it didn't.`, actual, expected[0]) - } - - return success -} - -func isString(value interface{}) bool { _, ok := value.(string); return ok } -func isError(value interface{}) bool { _, ok := value.(error); return ok } diff --git a/vendor/github.com/smartystreets/goconvey/LICENSE.md b/vendor/github.com/smartystreets/goconvey/LICENSE.md deleted file mode 100644 index 3f87a40e77306..0000000000000 --- a/vendor/github.com/smartystreets/goconvey/LICENSE.md +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2016 SmartyStreets, LLC - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - -NOTE: Various optional and subordinate components carry their own licensing -requirements and restrictions. Use of those components is subject to the terms -and conditions outlined the respective license of each component. diff --git a/vendor/github.com/smartystreets/goconvey/convey/assertions.go b/vendor/github.com/smartystreets/goconvey/convey/assertions.go deleted file mode 100644 index 97e3bec82e7d6..0000000000000 --- a/vendor/github.com/smartystreets/goconvey/convey/assertions.go +++ /dev/null @@ -1,71 +0,0 @@ -package convey - -import "github.com/smartystreets/assertions" - -var ( - ShouldEqual = assertions.ShouldEqual - ShouldNotEqual = assertions.ShouldNotEqual - ShouldAlmostEqual = assertions.ShouldAlmostEqual - ShouldNotAlmostEqual = assertions.ShouldNotAlmostEqual - ShouldResemble = assertions.ShouldResemble - ShouldNotResemble = assertions.ShouldNotResemble - ShouldPointTo = assertions.ShouldPointTo - ShouldNotPointTo = assertions.ShouldNotPointTo - ShouldBeNil = assertions.ShouldBeNil - ShouldNotBeNil = assertions.ShouldNotBeNil - ShouldBeTrue = assertions.ShouldBeTrue - ShouldBeFalse = assertions.ShouldBeFalse - ShouldBeZeroValue = assertions.ShouldBeZeroValue - ShouldNotBeZeroValue = assertions.ShouldNotBeZeroValue - - ShouldBeGreaterThan = assertions.ShouldBeGreaterThan - ShouldBeGreaterThanOrEqualTo = assertions.ShouldBeGreaterThanOrEqualTo - ShouldBeLessThan = assertions.ShouldBeLessThan - ShouldBeLessThanOrEqualTo = assertions.ShouldBeLessThanOrEqualTo - ShouldBeBetween = assertions.ShouldBeBetween - ShouldNotBeBetween = assertions.ShouldNotBeBetween - ShouldBeBetweenOrEqual = assertions.ShouldBeBetweenOrEqual - ShouldNotBeBetweenOrEqual = assertions.ShouldNotBeBetweenOrEqual - - ShouldContain = assertions.ShouldContain - ShouldNotContain = assertions.ShouldNotContain - ShouldContainKey = assertions.ShouldContainKey - ShouldNotContainKey = assertions.ShouldNotContainKey - ShouldBeIn = assertions.ShouldBeIn - ShouldNotBeIn = assertions.ShouldNotBeIn - ShouldBeEmpty = assertions.ShouldBeEmpty - ShouldNotBeEmpty = assertions.ShouldNotBeEmpty - ShouldHaveLength = assertions.ShouldHaveLength - - ShouldStartWith = assertions.ShouldStartWith - ShouldNotStartWith = assertions.ShouldNotStartWith - ShouldEndWith = assertions.ShouldEndWith - ShouldNotEndWith = assertions.ShouldNotEndWith - ShouldBeBlank = assertions.ShouldBeBlank - ShouldNotBeBlank = assertions.ShouldNotBeBlank - ShouldContainSubstring = assertions.ShouldContainSubstring - ShouldNotContainSubstring = assertions.ShouldNotContainSubstring - - ShouldPanic = assertions.ShouldPanic - ShouldNotPanic = assertions.ShouldNotPanic - ShouldPanicWith = assertions.ShouldPanicWith - ShouldNotPanicWith = assertions.ShouldNotPanicWith - - ShouldHaveSameTypeAs = assertions.ShouldHaveSameTypeAs - ShouldNotHaveSameTypeAs = assertions.ShouldNotHaveSameTypeAs - ShouldImplement = assertions.ShouldImplement - ShouldNotImplement = assertions.ShouldNotImplement - - ShouldHappenBefore = assertions.ShouldHappenBefore - ShouldHappenOnOrBefore = assertions.ShouldHappenOnOrBefore - ShouldHappenAfter = assertions.ShouldHappenAfter - ShouldHappenOnOrAfter = assertions.ShouldHappenOnOrAfter - ShouldHappenBetween = assertions.ShouldHappenBetween - ShouldHappenOnOrBetween = assertions.ShouldHappenOnOrBetween - ShouldNotHappenOnOrBetween = assertions.ShouldNotHappenOnOrBetween - ShouldHappenWithin = assertions.ShouldHappenWithin - ShouldNotHappenWithin = assertions.ShouldNotHappenWithin - ShouldBeChronological = assertions.ShouldBeChronological - - ShouldBeError = assertions.ShouldBeError -) diff --git a/vendor/github.com/smartystreets/goconvey/convey/context.go b/vendor/github.com/smartystreets/goconvey/convey/context.go deleted file mode 100644 index 2c75c2d7b1b69..0000000000000 --- a/vendor/github.com/smartystreets/goconvey/convey/context.go +++ /dev/null @@ -1,272 +0,0 @@ -package convey - -import ( - "fmt" - - "github.com/jtolds/gls" - "github.com/smartystreets/goconvey/convey/reporting" -) - -type conveyErr struct { - fmt string - params []interface{} -} - -func (e *conveyErr) Error() string { - return fmt.Sprintf(e.fmt, e.params...) -} - -func conveyPanic(fmt string, params ...interface{}) { - panic(&conveyErr{fmt, params}) -} - -const ( - missingGoTest = `Top-level calls to Convey(...) need a reference to the *testing.T. - Hint: Convey("description here", t, func() { /* notice that the second argument was the *testing.T (t)! */ }) ` - extraGoTest = `Only the top-level call to Convey(...) needs a reference to the *testing.T.` - noStackContext = "Convey operation made without context on goroutine stack.\n" + - "Hint: Perhaps you meant to use `Convey(..., func(c C){...})` ?" - differentConveySituations = "Different set of Convey statements on subsequent pass!\nDid not expect %#v." - multipleIdenticalConvey = "Multiple convey suites with identical names: %#v" -) - -const ( - failureHalt = "___FAILURE_HALT___" - - nodeKey = "node" -) - -///////////////////////////////// Stack Context ///////////////////////////////// - -func getCurrentContext() *context { - ctx, ok := ctxMgr.GetValue(nodeKey) - if ok { - return ctx.(*context) - } - return nil -} - -func mustGetCurrentContext() *context { - ctx := getCurrentContext() - if ctx == nil { - conveyPanic(noStackContext) - } - return ctx -} - -//////////////////////////////////// Context //////////////////////////////////// - -// context magically handles all coordination of Convey's and So assertions. -// -// It is tracked on the stack as goroutine-local-storage with the gls package, -// or explicitly if the user decides to call convey like: -// -// Convey(..., func(c C) { -// c.So(...) -// }) -// -// This implements the `C` interface. -type context struct { - reporter reporting.Reporter - - children map[string]*context - - resets []func() - - executedOnce bool - expectChildRun *bool - complete bool - - focus bool - failureMode FailureMode -} - -// rootConvey is the main entry point to a test suite. This is called when -// there's no context in the stack already, and items must contain a `t` object, -// or this panics. -func rootConvey(items ...interface{}) { - entry := discover(items) - - if entry.Test == nil { - conveyPanic(missingGoTest) - } - - expectChildRun := true - ctx := &context{ - reporter: buildReporter(), - - children: make(map[string]*context), - - expectChildRun: &expectChildRun, - - focus: entry.Focus, - failureMode: defaultFailureMode.combine(entry.FailMode), - } - ctxMgr.SetValues(gls.Values{nodeKey: ctx}, func() { - ctx.reporter.BeginStory(reporting.NewStoryReport(entry.Test)) - defer ctx.reporter.EndStory() - - for ctx.shouldVisit() { - ctx.conveyInner(entry.Situation, entry.Func) - expectChildRun = true - } - }) -} - -//////////////////////////////////// Methods //////////////////////////////////// - -func (ctx *context) SkipConvey(items ...interface{}) { - ctx.Convey(items, skipConvey) -} - -func (ctx *context) FocusConvey(items ...interface{}) { - ctx.Convey(items, focusConvey) -} - -func (ctx *context) Convey(items ...interface{}) { - entry := discover(items) - - // we're a branch, or leaf (on the wind) - if entry.Test != nil { - conveyPanic(extraGoTest) - } - if ctx.focus && !entry.Focus { - return - } - - var inner_ctx *context - if ctx.executedOnce { - var ok bool - inner_ctx, ok = ctx.children[entry.Situation] - if !ok { - conveyPanic(differentConveySituations, entry.Situation) - } - } else { - if _, ok := ctx.children[entry.Situation]; ok { - conveyPanic(multipleIdenticalConvey, entry.Situation) - } - inner_ctx = &context{ - reporter: ctx.reporter, - - children: make(map[string]*context), - - expectChildRun: ctx.expectChildRun, - - focus: entry.Focus, - failureMode: ctx.failureMode.combine(entry.FailMode), - } - ctx.children[entry.Situation] = inner_ctx - } - - if inner_ctx.shouldVisit() { - ctxMgr.SetValues(gls.Values{nodeKey: inner_ctx}, func() { - inner_ctx.conveyInner(entry.Situation, entry.Func) - }) - } -} - -func (ctx *context) SkipSo(stuff ...interface{}) { - ctx.assertionReport(reporting.NewSkipReport()) -} - -func (ctx *context) So(actual interface{}, assert assertion, expected ...interface{}) { - if result := assert(actual, expected...); result == assertionSuccess { - ctx.assertionReport(reporting.NewSuccessReport()) - } else { - ctx.assertionReport(reporting.NewFailureReport(result)) - } -} - -func (ctx *context) Reset(action func()) { - /* TODO: Failure mode configuration */ - ctx.resets = append(ctx.resets, action) -} - -func (ctx *context) Print(items ...interface{}) (int, error) { - fmt.Fprint(ctx.reporter, items...) - return fmt.Print(items...) -} - -func (ctx *context) Println(items ...interface{}) (int, error) { - fmt.Fprintln(ctx.reporter, items...) - return fmt.Println(items...) -} - -func (ctx *context) Printf(format string, items ...interface{}) (int, error) { - fmt.Fprintf(ctx.reporter, format, items...) - return fmt.Printf(format, items...) -} - -//////////////////////////////////// Private //////////////////////////////////// - -// shouldVisit returns true iff we should traverse down into a Convey. Note -// that just because we don't traverse a Convey this time, doesn't mean that -// we may not traverse it on a subsequent pass. -func (c *context) shouldVisit() bool { - return !c.complete && *c.expectChildRun -} - -// conveyInner is the function which actually executes the user's anonymous test -// function body. At this point, Convey or RootConvey has decided that this -// function should actually run. -func (ctx *context) conveyInner(situation string, f func(C)) { - // Record/Reset state for next time. - defer func() { - ctx.executedOnce = true - - // This is only needed at the leaves, but there's no harm in also setting it - // when returning from branch Convey's - *ctx.expectChildRun = false - }() - - // Set up+tear down our scope for the reporter - ctx.reporter.Enter(reporting.NewScopeReport(situation)) - defer ctx.reporter.Exit() - - // Recover from any panics in f, and assign the `complete` status for this - // node of the tree. - defer func() { - ctx.complete = true - if problem := recover(); problem != nil { - if problem, ok := problem.(*conveyErr); ok { - panic(problem) - } - if problem != failureHalt { - ctx.reporter.Report(reporting.NewErrorReport(problem)) - } - } else { - for _, child := range ctx.children { - if !child.complete { - ctx.complete = false - return - } - } - } - }() - - // Resets are registered as the `f` function executes, so nil them here. - // All resets are run in registration order (FIFO). - ctx.resets = []func(){} - defer func() { - for _, r := range ctx.resets { - // panics handled by the previous defer - r() - } - }() - - if f == nil { - // if f is nil, this was either a Convey(..., nil), or a SkipConvey - ctx.reporter.Report(reporting.NewSkipReport()) - } else { - f(ctx) - } -} - -// assertionReport is a helper for So and SkipSo which makes the report and -// then possibly panics, depending on the current context's failureMode. -func (ctx *context) assertionReport(r *reporting.AssertionResult) { - ctx.reporter.Report(r) - if r.Failure != "" && ctx.failureMode == FailureHalts { - panic(failureHalt) - } -} diff --git a/vendor/github.com/smartystreets/goconvey/convey/convey.goconvey b/vendor/github.com/smartystreets/goconvey/convey/convey.goconvey deleted file mode 100644 index a2d9327dc9164..0000000000000 --- a/vendor/github.com/smartystreets/goconvey/convey/convey.goconvey +++ /dev/null @@ -1,4 +0,0 @@ -#ignore --timeout=1s -#-covermode=count -#-coverpkg=github.com/smartystreets/goconvey/convey,github.com/smartystreets/goconvey/convey/gotest,github.com/smartystreets/goconvey/convey/reporting \ No newline at end of file diff --git a/vendor/github.com/smartystreets/goconvey/convey/discovery.go b/vendor/github.com/smartystreets/goconvey/convey/discovery.go deleted file mode 100644 index eb8d4cb2ceebe..0000000000000 --- a/vendor/github.com/smartystreets/goconvey/convey/discovery.go +++ /dev/null @@ -1,103 +0,0 @@ -package convey - -type actionSpecifier uint8 - -const ( - noSpecifier actionSpecifier = iota - skipConvey - focusConvey -) - -type suite struct { - Situation string - Test t - Focus bool - Func func(C) // nil means skipped - FailMode FailureMode -} - -func newSuite(situation string, failureMode FailureMode, f func(C), test t, specifier actionSpecifier) *suite { - ret := &suite{ - Situation: situation, - Test: test, - Func: f, - FailMode: failureMode, - } - switch specifier { - case skipConvey: - ret.Func = nil - case focusConvey: - ret.Focus = true - } - return ret -} - -func discover(items []interface{}) *suite { - name, items := parseName(items) - test, items := parseGoTest(items) - failure, items := parseFailureMode(items) - action, items := parseAction(items) - specifier, items := parseSpecifier(items) - - if len(items) != 0 { - conveyPanic(parseError) - } - - return newSuite(name, failure, action, test, specifier) -} -func item(items []interface{}) interface{} { - if len(items) == 0 { - conveyPanic(parseError) - } - return items[0] -} -func parseName(items []interface{}) (string, []interface{}) { - if name, parsed := item(items).(string); parsed { - return name, items[1:] - } - conveyPanic(parseError) - panic("never get here") -} -func parseGoTest(items []interface{}) (t, []interface{}) { - if test, parsed := item(items).(t); parsed { - return test, items[1:] - } - return nil, items -} -func parseFailureMode(items []interface{}) (FailureMode, []interface{}) { - if mode, parsed := item(items).(FailureMode); parsed { - return mode, items[1:] - } - return FailureInherits, items -} -func parseAction(items []interface{}) (func(C), []interface{}) { - switch x := item(items).(type) { - case nil: - return nil, items[1:] - case func(C): - return x, items[1:] - case func(): - return func(C) { x() }, items[1:] - } - conveyPanic(parseError) - panic("never get here") -} -func parseSpecifier(items []interface{}) (actionSpecifier, []interface{}) { - if len(items) == 0 { - return noSpecifier, items - } - if spec, ok := items[0].(actionSpecifier); ok { - return spec, items[1:] - } - conveyPanic(parseError) - panic("never get here") -} - -// This interface allows us to pass the *testing.T struct -// throughout the internals of this package without ever -// having to import the "testing" package. -type t interface { - Fail() -} - -const parseError = "You must provide a name (string), then a *testing.T (if in outermost scope), an optional FailureMode, and then an action (func())." diff --git a/vendor/github.com/smartystreets/goconvey/convey/doc.go b/vendor/github.com/smartystreets/goconvey/convey/doc.go deleted file mode 100644 index e4f7b51a86576..0000000000000 --- a/vendor/github.com/smartystreets/goconvey/convey/doc.go +++ /dev/null @@ -1,218 +0,0 @@ -// Package convey contains all of the public-facing entry points to this project. -// This means that it should never be required of the user to import any other -// packages from this project as they serve internal purposes. -package convey - -import "github.com/smartystreets/goconvey/convey/reporting" - -////////////////////////////////// suite ////////////////////////////////// - -// C is the Convey context which you can optionally obtain in your action -// by calling Convey like: -// -// Convey(..., func(c C) { -// ... -// }) -// -// See the documentation on Convey for more details. -// -// All methods in this context behave identically to the global functions of the -// same name in this package. -type C interface { - Convey(items ...interface{}) - SkipConvey(items ...interface{}) - FocusConvey(items ...interface{}) - - So(actual interface{}, assert assertion, expected ...interface{}) - SkipSo(stuff ...interface{}) - - Reset(action func()) - - Println(items ...interface{}) (int, error) - Print(items ...interface{}) (int, error) - Printf(format string, items ...interface{}) (int, error) -} - -// Convey is the method intended for use when declaring the scopes of -// a specification. Each scope has a description and a func() which may contain -// other calls to Convey(), Reset() or Should-style assertions. Convey calls can -// be nested as far as you see fit. -// -// IMPORTANT NOTE: The top-level Convey() within a Test method -// must conform to the following signature: -// -// Convey(description string, t *testing.T, action func()) -// -// All other calls should look like this (no need to pass in *testing.T): -// -// Convey(description string, action func()) -// -// Don't worry, goconvey will panic if you get it wrong so you can fix it. -// -// Additionally, you may explicitly obtain access to the Convey context by doing: -// -// Convey(description string, action func(c C)) -// -// You may need to do this if you want to pass the context through to a -// goroutine, or to close over the context in a handler to a library which -// calls your handler in a goroutine (httptest comes to mind). -// -// All Convey()-blocks also accept an optional parameter of FailureMode which sets -// how goconvey should treat failures for So()-assertions in the block and -// nested blocks. See the constants in this file for the available options. -// -// By default it will inherit from its parent block and the top-level blocks -// default to the FailureHalts setting. -// -// This parameter is inserted before the block itself: -// -// Convey(description string, t *testing.T, mode FailureMode, action func()) -// Convey(description string, mode FailureMode, action func()) -// -// See the examples package for, well, examples. -func Convey(items ...interface{}) { - if ctx := getCurrentContext(); ctx == nil { - rootConvey(items...) - } else { - ctx.Convey(items...) - } -} - -// SkipConvey is analogous to Convey except that the scope is not executed -// (which means that child scopes defined within this scope are not run either). -// The reporter will be notified that this step was skipped. -func SkipConvey(items ...interface{}) { - Convey(append(items, skipConvey)...) -} - -// FocusConvey is has the inverse effect of SkipConvey. If the top-level -// Convey is changed to `FocusConvey`, only nested scopes that are defined -// with FocusConvey will be run. The rest will be ignored completely. This -// is handy when debugging a large suite that runs a misbehaving function -// repeatedly as you can disable all but one of that function -// without swaths of `SkipConvey` calls, just a targeted chain of calls -// to FocusConvey. -func FocusConvey(items ...interface{}) { - Convey(append(items, focusConvey)...) -} - -// Reset registers a cleanup function to be run after each Convey() -// in the same scope. See the examples package for a simple use case. -func Reset(action func()) { - mustGetCurrentContext().Reset(action) -} - -/////////////////////////////////// Assertions /////////////////////////////////// - -// assertion is an alias for a function with a signature that the convey.So() -// method can handle. Any future or custom assertions should conform to this -// method signature. The return value should be an empty string if the assertion -// passes and a well-formed failure message if not. -type assertion func(actual interface{}, expected ...interface{}) string - -const assertionSuccess = "" - -// So is the means by which assertions are made against the system under test. -// The majority of exported names in the assertions package begin with the word -// 'Should' and describe how the first argument (actual) should compare with any -// of the final (expected) arguments. How many final arguments are accepted -// depends on the particular assertion that is passed in as the assert argument. -// See the examples package for use cases and the assertions package for -// documentation on specific assertion methods. A failing assertion will -// cause t.Fail() to be invoked--you should never call this method (or other -// failure-inducing methods) in your test code. Leave that to GoConvey. -func So(actual interface{}, assert assertion, expected ...interface{}) { - mustGetCurrentContext().So(actual, assert, expected...) -} - -// SkipSo is analogous to So except that the assertion that would have been passed -// to So is not executed and the reporter is notified that the assertion was skipped. -func SkipSo(stuff ...interface{}) { - mustGetCurrentContext().SkipSo() -} - -// FailureMode is a type which determines how the So() blocks should fail -// if their assertion fails. See constants further down for acceptable values -type FailureMode string - -const ( - - // FailureContinues is a failure mode which prevents failing - // So()-assertions from halting Convey-block execution, instead - // allowing the test to continue past failing So()-assertions. - FailureContinues FailureMode = "continue" - - // FailureHalts is the default setting for a top-level Convey()-block - // and will cause all failing So()-assertions to halt further execution - // in that test-arm and continue on to the next arm. - FailureHalts FailureMode = "halt" - - // FailureInherits is the default setting for failure-mode, it will - // default to the failure-mode of the parent block. You should never - // need to specify this mode in your tests.. - FailureInherits FailureMode = "inherits" -) - -func (f FailureMode) combine(other FailureMode) FailureMode { - if other == FailureInherits { - return f - } - return other -} - -var defaultFailureMode FailureMode = FailureHalts - -// SetDefaultFailureMode allows you to specify the default failure mode -// for all Convey blocks. It is meant to be used in an init function to -// allow the default mode to be changdd across all tests for an entire packgae -// but it can be used anywhere. -func SetDefaultFailureMode(mode FailureMode) { - if mode == FailureContinues || mode == FailureHalts { - defaultFailureMode = mode - } else { - panic("You may only use the constants named 'FailureContinues' and 'FailureHalts' as default failure modes.") - } -} - -//////////////////////////////////// Print functions //////////////////////////////////// - -// Print is analogous to fmt.Print (and it even calls fmt.Print). It ensures that -// output is aligned with the corresponding scopes in the web UI. -func Print(items ...interface{}) (written int, err error) { - return mustGetCurrentContext().Print(items...) -} - -// Print is analogous to fmt.Println (and it even calls fmt.Println). It ensures that -// output is aligned with the corresponding scopes in the web UI. -func Println(items ...interface{}) (written int, err error) { - return mustGetCurrentContext().Println(items...) -} - -// Print is analogous to fmt.Printf (and it even calls fmt.Printf). It ensures that -// output is aligned with the corresponding scopes in the web UI. -func Printf(format string, items ...interface{}) (written int, err error) { - return mustGetCurrentContext().Printf(format, items...) -} - -/////////////////////////////////////////////////////////////////////////////// - -// SuppressConsoleStatistics prevents automatic printing of console statistics. -// Calling PrintConsoleStatistics explicitly will force printing of statistics. -func SuppressConsoleStatistics() { - reporting.SuppressConsoleStatistics() -} - -// PrintConsoleStatistics may be called at any time to print assertion statistics. -// Generally, the best place to do this would be in a TestMain function, -// after all tests have been run. Something like this: -// -// func TestMain(m *testing.M) { -// convey.SuppressConsoleStatistics() -// result := m.Run() -// convey.PrintConsoleStatistics() -// os.Exit(result) -// } -// -func PrintConsoleStatistics() { - reporting.PrintConsoleStatistics() -} diff --git a/vendor/github.com/smartystreets/goconvey/convey/gotest/utils.go b/vendor/github.com/smartystreets/goconvey/convey/gotest/utils.go deleted file mode 100644 index 167c8fb74a432..0000000000000 --- a/vendor/github.com/smartystreets/goconvey/convey/gotest/utils.go +++ /dev/null @@ -1,28 +0,0 @@ -// Package gotest contains internal functionality. Although this package -// contains one or more exported names it is not intended for public -// consumption. See the examples package for how to use this project. -package gotest - -import ( - "runtime" - "strings" -) - -func ResolveExternalCaller() (file string, line int, name string) { - var caller_id uintptr - callers := runtime.Callers(0, callStack) - - for x := 0; x < callers; x++ { - caller_id, file, line, _ = runtime.Caller(x) - if strings.HasSuffix(file, "_test.go") || strings.HasSuffix(file, "_tests.go") { - name = runtime.FuncForPC(caller_id).Name() - return - } - } - file, line, name = "", -1, "" - return // panic? -} - -const maxStackDepth = 100 // This had better be enough... - -var callStack []uintptr = make([]uintptr, maxStackDepth, maxStackDepth) diff --git a/vendor/github.com/smartystreets/goconvey/convey/init.go b/vendor/github.com/smartystreets/goconvey/convey/init.go deleted file mode 100644 index cb930a0db4f0d..0000000000000 --- a/vendor/github.com/smartystreets/goconvey/convey/init.go +++ /dev/null @@ -1,81 +0,0 @@ -package convey - -import ( - "flag" - "os" - - "github.com/jtolds/gls" - "github.com/smartystreets/assertions" - "github.com/smartystreets/goconvey/convey/reporting" -) - -func init() { - assertions.GoConveyMode(true) - - declareFlags() - - ctxMgr = gls.NewContextManager() -} - -func declareFlags() { - flag.BoolVar(&json, "convey-json", false, "When true, emits results in JSON blocks. Default: 'false'") - flag.BoolVar(&silent, "convey-silent", false, "When true, all output from GoConvey is suppressed.") - flag.BoolVar(&story, "convey-story", false, "When true, emits story output, otherwise emits dot output. When not provided, this flag mirrors the value of the '-test.v' flag") - - if noStoryFlagProvided() { - story = verboseEnabled - } - - // FYI: flag.Parse() is called from the testing package. -} - -func noStoryFlagProvided() bool { - return !story && !storyDisabled -} - -func buildReporter() reporting.Reporter { - selectReporter := os.Getenv("GOCONVEY_REPORTER") - - switch { - case testReporter != nil: - return testReporter - case json || selectReporter == "json": - return reporting.BuildJsonReporter() - case silent || selectReporter == "silent": - return reporting.BuildSilentReporter() - case selectReporter == "dot": - // Story is turned on when verbose is set, so we need to check for dot reporter first. - return reporting.BuildDotReporter() - case story || selectReporter == "story": - return reporting.BuildStoryReporter() - default: - return reporting.BuildDotReporter() - } -} - -var ( - ctxMgr *gls.ContextManager - - // only set by internal tests - testReporter reporting.Reporter -) - -var ( - json bool - silent bool - story bool - - verboseEnabled = flagFound("-test.v=true") - storyDisabled = flagFound("-story=false") -) - -// flagFound parses the command line args manually for flags defined in other -// packages. Like the '-v' flag from the "testing" package, for instance. -func flagFound(flagValue string) bool { - for _, arg := range os.Args { - if arg == flagValue { - return true - } - } - return false -} diff --git a/vendor/github.com/smartystreets/goconvey/convey/nilReporter.go b/vendor/github.com/smartystreets/goconvey/convey/nilReporter.go deleted file mode 100644 index 777b2a51228f3..0000000000000 --- a/vendor/github.com/smartystreets/goconvey/convey/nilReporter.go +++ /dev/null @@ -1,15 +0,0 @@ -package convey - -import ( - "github.com/smartystreets/goconvey/convey/reporting" -) - -type nilReporter struct{} - -func (self *nilReporter) BeginStory(story *reporting.StoryReport) {} -func (self *nilReporter) Enter(scope *reporting.ScopeReport) {} -func (self *nilReporter) Report(report *reporting.AssertionResult) {} -func (self *nilReporter) Exit() {} -func (self *nilReporter) EndStory() {} -func (self *nilReporter) Write(p []byte) (int, error) { return len(p), nil } -func newNilReporter() *nilReporter { return &nilReporter{} } diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/console.go b/vendor/github.com/smartystreets/goconvey/convey/reporting/console.go deleted file mode 100644 index 7bf67dbb2b14c..0000000000000 --- a/vendor/github.com/smartystreets/goconvey/convey/reporting/console.go +++ /dev/null @@ -1,16 +0,0 @@ -package reporting - -import ( - "fmt" - "io" -) - -type console struct{} - -func (self *console) Write(p []byte) (n int, err error) { - return fmt.Print(string(p)) -} - -func NewConsole() io.Writer { - return new(console) -} diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/doc.go b/vendor/github.com/smartystreets/goconvey/convey/reporting/doc.go deleted file mode 100644 index a37d001946612..0000000000000 --- a/vendor/github.com/smartystreets/goconvey/convey/reporting/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// Package reporting contains internal functionality related -// to console reporting and output. Although this package has -// exported names is not intended for public consumption. See the -// examples package for how to use this project. -package reporting diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/dot.go b/vendor/github.com/smartystreets/goconvey/convey/reporting/dot.go deleted file mode 100644 index 47d57c6b0d961..0000000000000 --- a/vendor/github.com/smartystreets/goconvey/convey/reporting/dot.go +++ /dev/null @@ -1,40 +0,0 @@ -package reporting - -import "fmt" - -type dot struct{ out *Printer } - -func (self *dot) BeginStory(story *StoryReport) {} - -func (self *dot) Enter(scope *ScopeReport) {} - -func (self *dot) Report(report *AssertionResult) { - if report.Error != nil { - fmt.Print(redColor) - self.out.Insert(dotError) - } else if report.Failure != "" { - fmt.Print(yellowColor) - self.out.Insert(dotFailure) - } else if report.Skipped { - fmt.Print(yellowColor) - self.out.Insert(dotSkip) - } else { - fmt.Print(greenColor) - self.out.Insert(dotSuccess) - } - fmt.Print(resetColor) -} - -func (self *dot) Exit() {} - -func (self *dot) EndStory() {} - -func (self *dot) Write(content []byte) (written int, err error) { - return len(content), nil // no-op -} - -func NewDotReporter(out *Printer) *dot { - self := new(dot) - self.out = out - return self -} diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/gotest.go b/vendor/github.com/smartystreets/goconvey/convey/reporting/gotest.go deleted file mode 100644 index c396e16b17a5a..0000000000000 --- a/vendor/github.com/smartystreets/goconvey/convey/reporting/gotest.go +++ /dev/null @@ -1,33 +0,0 @@ -package reporting - -type gotestReporter struct{ test T } - -func (self *gotestReporter) BeginStory(story *StoryReport) { - self.test = story.Test -} - -func (self *gotestReporter) Enter(scope *ScopeReport) {} - -func (self *gotestReporter) Report(r *AssertionResult) { - if !passed(r) { - self.test.Fail() - } -} - -func (self *gotestReporter) Exit() {} - -func (self *gotestReporter) EndStory() { - self.test = nil -} - -func (self *gotestReporter) Write(content []byte) (written int, err error) { - return len(content), nil // no-op -} - -func NewGoTestReporter() *gotestReporter { - return new(gotestReporter) -} - -func passed(r *AssertionResult) bool { - return r.Error == nil && r.Failure == "" -} diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/init.go b/vendor/github.com/smartystreets/goconvey/convey/reporting/init.go deleted file mode 100644 index 99c3bd6d615ff..0000000000000 --- a/vendor/github.com/smartystreets/goconvey/convey/reporting/init.go +++ /dev/null @@ -1,94 +0,0 @@ -package reporting - -import ( - "os" - "runtime" - "strings" -) - -func init() { - if !isColorableTerminal() { - monochrome() - } - - if runtime.GOOS == "windows" { - success, failure, error_ = dotSuccess, dotFailure, dotError - } -} - -func BuildJsonReporter() Reporter { - out := NewPrinter(NewConsole()) - return NewReporters( - NewGoTestReporter(), - NewJsonReporter(out)) -} -func BuildDotReporter() Reporter { - out := NewPrinter(NewConsole()) - return NewReporters( - NewGoTestReporter(), - NewDotReporter(out), - NewProblemReporter(out), - consoleStatistics) -} -func BuildStoryReporter() Reporter { - out := NewPrinter(NewConsole()) - return NewReporters( - NewGoTestReporter(), - NewStoryReporter(out), - NewProblemReporter(out), - consoleStatistics) -} -func BuildSilentReporter() Reporter { - out := NewPrinter(NewConsole()) - return NewReporters( - NewGoTestReporter(), - NewSilentProblemReporter(out)) -} - -var ( - newline = "\n" - success = "✔" - failure = "✘" - error_ = "🔥" - skip = "⚠" - dotSuccess = "." - dotFailure = "x" - dotError = "E" - dotSkip = "S" - errorTemplate = "* %s \nLine %d: - %v \n%s\n" - failureTemplate = "* %s \nLine %d:\n%s\n%s\n" -) - -var ( - greenColor = "\033[32m" - yellowColor = "\033[33m" - redColor = "\033[31m" - resetColor = "\033[0m" -) - -var consoleStatistics = NewStatisticsReporter(NewPrinter(NewConsole())) - -func SuppressConsoleStatistics() { consoleStatistics.Suppress() } -func PrintConsoleStatistics() { consoleStatistics.PrintSummary() } - -// QuietMode disables all console output symbols. This is only meant to be used -// for tests that are internal to goconvey where the output is distracting or -// otherwise not needed in the test output. -func QuietMode() { - success, failure, error_, skip, dotSuccess, dotFailure, dotError, dotSkip = "", "", "", "", "", "", "", "" -} - -func monochrome() { - greenColor, yellowColor, redColor, resetColor = "", "", "", "" -} - -func isColorableTerminal() bool { - return strings.Contains(os.Getenv("TERM"), "color") -} - -// This interface allows us to pass the *testing.T struct -// throughout the internals of this tool without ever -// having to import the "testing" package. -type T interface { - Fail() -} diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/json.go b/vendor/github.com/smartystreets/goconvey/convey/reporting/json.go deleted file mode 100644 index f8526979f8551..0000000000000 --- a/vendor/github.com/smartystreets/goconvey/convey/reporting/json.go +++ /dev/null @@ -1,88 +0,0 @@ -// TODO: under unit test - -package reporting - -import ( - "bytes" - "encoding/json" - "fmt" - "strings" -) - -type JsonReporter struct { - out *Printer - currentKey []string - current *ScopeResult - index map[string]*ScopeResult - scopes []*ScopeResult -} - -func (self *JsonReporter) depth() int { return len(self.currentKey) } - -func (self *JsonReporter) BeginStory(story *StoryReport) {} - -func (self *JsonReporter) Enter(scope *ScopeReport) { - self.currentKey = append(self.currentKey, scope.Title) - ID := strings.Join(self.currentKey, "|") - if _, found := self.index[ID]; !found { - next := newScopeResult(scope.Title, self.depth(), scope.File, scope.Line) - self.scopes = append(self.scopes, next) - self.index[ID] = next - } - self.current = self.index[ID] -} - -func (self *JsonReporter) Report(report *AssertionResult) { - self.current.Assertions = append(self.current.Assertions, report) -} - -func (self *JsonReporter) Exit() { - self.currentKey = self.currentKey[:len(self.currentKey)-1] -} - -func (self *JsonReporter) EndStory() { - self.report() - self.reset() -} -func (self *JsonReporter) report() { - scopes := []string{} - for _, scope := range self.scopes { - serialized, err := json.Marshal(scope) - if err != nil { - self.out.Println(jsonMarshalFailure) - panic(err) - } - var buffer bytes.Buffer - json.Indent(&buffer, serialized, "", " ") - scopes = append(scopes, buffer.String()) - } - self.out.Print(fmt.Sprintf("%s\n%s,\n%s\n", OpenJson, strings.Join(scopes, ","), CloseJson)) -} -func (self *JsonReporter) reset() { - self.scopes = []*ScopeResult{} - self.index = map[string]*ScopeResult{} - self.currentKey = nil -} - -func (self *JsonReporter) Write(content []byte) (written int, err error) { - self.current.Output += string(content) - return len(content), nil -} - -func NewJsonReporter(out *Printer) *JsonReporter { - self := new(JsonReporter) - self.out = out - self.reset() - return self -} - -const OpenJson = ">->->OPEN-JSON->->->" // "⌦" -const CloseJson = "<-<-<-CLOSE-JSON<-<-<" // "⌫" -const jsonMarshalFailure = ` - -GOCONVEY_JSON_MARSHALL_FAILURE: There was an error when attempting to convert test results to JSON. -Please file a bug report and reference the code that caused this failure if possible. - -Here's the panic: - -` diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/printer.go b/vendor/github.com/smartystreets/goconvey/convey/reporting/printer.go deleted file mode 100644 index 3dac0d4d28357..0000000000000 --- a/vendor/github.com/smartystreets/goconvey/convey/reporting/printer.go +++ /dev/null @@ -1,60 +0,0 @@ -package reporting - -import ( - "fmt" - "io" - "strings" -) - -type Printer struct { - out io.Writer - prefix string -} - -func (self *Printer) Println(message string, values ...interface{}) { - formatted := self.format(message, values...) + newline - self.out.Write([]byte(formatted)) -} - -func (self *Printer) Print(message string, values ...interface{}) { - formatted := self.format(message, values...) - self.out.Write([]byte(formatted)) -} - -func (self *Printer) Insert(text string) { - self.out.Write([]byte(text)) -} - -func (self *Printer) format(message string, values ...interface{}) string { - var formatted string - if len(values) == 0 { - formatted = self.prefix + message - } else { - formatted = self.prefix + fmt_Sprintf(message, values...) - } - indented := strings.Replace(formatted, newline, newline+self.prefix, -1) - return strings.TrimRight(indented, space) -} - -// Extracting fmt.Sprintf to a separate variable circumvents go vet, which, as of go 1.10 is run with go test. -var fmt_Sprintf = fmt.Sprintf - -func (self *Printer) Indent() { - self.prefix += pad -} - -func (self *Printer) Dedent() { - if len(self.prefix) >= padLength { - self.prefix = self.prefix[:len(self.prefix)-padLength] - } -} - -func NewPrinter(out io.Writer) *Printer { - self := new(Printer) - self.out = out - return self -} - -const space = " " -const pad = space + space -const padLength = len(pad) diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/problems.go b/vendor/github.com/smartystreets/goconvey/convey/reporting/problems.go deleted file mode 100644 index 33d5e1476714f..0000000000000 --- a/vendor/github.com/smartystreets/goconvey/convey/reporting/problems.go +++ /dev/null @@ -1,80 +0,0 @@ -package reporting - -import "fmt" - -type problem struct { - silent bool - out *Printer - errors []*AssertionResult - failures []*AssertionResult -} - -func (self *problem) BeginStory(story *StoryReport) {} - -func (self *problem) Enter(scope *ScopeReport) {} - -func (self *problem) Report(report *AssertionResult) { - if report.Error != nil { - self.errors = append(self.errors, report) - } else if report.Failure != "" { - self.failures = append(self.failures, report) - } -} - -func (self *problem) Exit() {} - -func (self *problem) EndStory() { - self.show(self.showErrors, redColor) - self.show(self.showFailures, yellowColor) - self.prepareForNextStory() -} -func (self *problem) show(display func(), color string) { - if !self.silent { - fmt.Print(color) - } - display() - if !self.silent { - fmt.Print(resetColor) - } - self.out.Dedent() -} -func (self *problem) showErrors() { - for i, e := range self.errors { - if i == 0 { - self.out.Println("\nErrors:\n") - self.out.Indent() - } - self.out.Println(errorTemplate, e.File, e.Line, e.Error, e.StackTrace) - } -} -func (self *problem) showFailures() { - for i, f := range self.failures { - if i == 0 { - self.out.Println("\nFailures:\n") - self.out.Indent() - } - self.out.Println(failureTemplate, f.File, f.Line, f.Failure, f.StackTrace) - } -} - -func (self *problem) Write(content []byte) (written int, err error) { - return len(content), nil // no-op -} - -func NewProblemReporter(out *Printer) *problem { - self := new(problem) - self.out = out - self.prepareForNextStory() - return self -} - -func NewSilentProblemReporter(out *Printer) *problem { - self := NewProblemReporter(out) - self.silent = true - return self -} - -func (self *problem) prepareForNextStory() { - self.errors = []*AssertionResult{} - self.failures = []*AssertionResult{} -} diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/reporter.go b/vendor/github.com/smartystreets/goconvey/convey/reporting/reporter.go deleted file mode 100644 index cce6c5e438850..0000000000000 --- a/vendor/github.com/smartystreets/goconvey/convey/reporting/reporter.go +++ /dev/null @@ -1,39 +0,0 @@ -package reporting - -import "io" - -type Reporter interface { - BeginStory(story *StoryReport) - Enter(scope *ScopeReport) - Report(r *AssertionResult) - Exit() - EndStory() - io.Writer -} - -type reporters struct{ collection []Reporter } - -func (self *reporters) BeginStory(s *StoryReport) { self.foreach(func(r Reporter) { r.BeginStory(s) }) } -func (self *reporters) Enter(s *ScopeReport) { self.foreach(func(r Reporter) { r.Enter(s) }) } -func (self *reporters) Report(a *AssertionResult) { self.foreach(func(r Reporter) { r.Report(a) }) } -func (self *reporters) Exit() { self.foreach(func(r Reporter) { r.Exit() }) } -func (self *reporters) EndStory() { self.foreach(func(r Reporter) { r.EndStory() }) } - -func (self *reporters) Write(contents []byte) (written int, err error) { - self.foreach(func(r Reporter) { - written, err = r.Write(contents) - }) - return written, err -} - -func (self *reporters) foreach(action func(Reporter)) { - for _, r := range self.collection { - action(r) - } -} - -func NewReporters(collection ...Reporter) *reporters { - self := new(reporters) - self.collection = collection - return self -} diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/reporting.goconvey b/vendor/github.com/smartystreets/goconvey/convey/reporting/reporting.goconvey deleted file mode 100644 index 79982854b533a..0000000000000 --- a/vendor/github.com/smartystreets/goconvey/convey/reporting/reporting.goconvey +++ /dev/null @@ -1,2 +0,0 @@ -#ignore --timeout=1s diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/reports.go b/vendor/github.com/smartystreets/goconvey/convey/reporting/reports.go deleted file mode 100644 index 712e6ade625d2..0000000000000 --- a/vendor/github.com/smartystreets/goconvey/convey/reporting/reports.go +++ /dev/null @@ -1,179 +0,0 @@ -package reporting - -import ( - "encoding/json" - "fmt" - "runtime" - "strings" - - "github.com/smartystreets/goconvey/convey/gotest" -) - -////////////////// ScopeReport //////////////////// - -type ScopeReport struct { - Title string - File string - Line int -} - -func NewScopeReport(title string) *ScopeReport { - file, line, _ := gotest.ResolveExternalCaller() - self := new(ScopeReport) - self.Title = title - self.File = file - self.Line = line - return self -} - -////////////////// ScopeResult //////////////////// - -type ScopeResult struct { - Title string - File string - Line int - Depth int - Assertions []*AssertionResult - Output string -} - -func newScopeResult(title string, depth int, file string, line int) *ScopeResult { - self := new(ScopeResult) - self.Title = title - self.Depth = depth - self.File = file - self.Line = line - self.Assertions = []*AssertionResult{} - return self -} - -/////////////////// StoryReport ///////////////////// - -type StoryReport struct { - Test T - Name string - File string - Line int -} - -func NewStoryReport(test T) *StoryReport { - file, line, name := gotest.ResolveExternalCaller() - name = removePackagePath(name) - self := new(StoryReport) - self.Test = test - self.Name = name - self.File = file - self.Line = line - return self -} - -// name comes in looking like "github.com/smartystreets/goconvey/examples.TestName". -// We only want the stuff after the last '.', which is the name of the test function. -func removePackagePath(name string) string { - parts := strings.Split(name, ".") - return parts[len(parts)-1] -} - -/////////////////// FailureView //////////////////////// - -// This struct is also declared in github.com/smartystreets/assertions. -// The json struct tags should be equal in both declarations. -type FailureView struct { - Message string `json:"Message"` - Expected string `json:"Expected"` - Actual string `json:"Actual"` -} - -////////////////////AssertionResult ////////////////////// - -type AssertionResult struct { - File string - Line int - Expected string - Actual string - Failure string - Error interface{} - StackTrace string - Skipped bool -} - -func NewFailureReport(failure string) *AssertionResult { - report := new(AssertionResult) - report.File, report.Line = caller() - report.StackTrace = stackTrace() - parseFailure(failure, report) - return report -} -func parseFailure(failure string, report *AssertionResult) { - view := new(FailureView) - err := json.Unmarshal([]byte(failure), view) - if err == nil { - report.Failure = view.Message - report.Expected = view.Expected - report.Actual = view.Actual - } else { - report.Failure = failure - } -} -func NewErrorReport(err interface{}) *AssertionResult { - report := new(AssertionResult) - report.File, report.Line = caller() - report.StackTrace = fullStackTrace() - report.Error = fmt.Sprintf("%v", err) - return report -} -func NewSuccessReport() *AssertionResult { - return new(AssertionResult) -} -func NewSkipReport() *AssertionResult { - report := new(AssertionResult) - report.File, report.Line = caller() - report.StackTrace = fullStackTrace() - report.Skipped = true - return report -} - -func caller() (file string, line int) { - file, line, _ = gotest.ResolveExternalCaller() - return -} - -func stackTrace() string { - buffer := make([]byte, 1024*64) - n := runtime.Stack(buffer, false) - return removeInternalEntries(string(buffer[:n])) -} -func fullStackTrace() string { - buffer := make([]byte, 1024*64) - n := runtime.Stack(buffer, true) - return removeInternalEntries(string(buffer[:n])) -} -func removeInternalEntries(stack string) string { - lines := strings.Split(stack, newline) - filtered := []string{} - for _, line := range lines { - if !isExternal(line) { - filtered = append(filtered, line) - } - } - return strings.Join(filtered, newline) -} -func isExternal(line string) bool { - for _, p := range internalPackages { - if strings.Contains(line, p) { - return true - } - } - return false -} - -// NOTE: any new packages that host goconvey packages will need to be added here! -// An alternative is to scan the goconvey directory and then exclude stuff like -// the examples package but that's nasty too. -var internalPackages = []string{ - "goconvey/assertions", - "goconvey/convey", - "goconvey/execution", - "goconvey/gotest", - "goconvey/reporting", -} diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/statistics.go b/vendor/github.com/smartystreets/goconvey/convey/reporting/statistics.go deleted file mode 100644 index c3ccd056a0bb0..0000000000000 --- a/vendor/github.com/smartystreets/goconvey/convey/reporting/statistics.go +++ /dev/null @@ -1,108 +0,0 @@ -package reporting - -import ( - "fmt" - "sync" -) - -func (self *statistics) BeginStory(story *StoryReport) {} - -func (self *statistics) Enter(scope *ScopeReport) {} - -func (self *statistics) Report(report *AssertionResult) { - self.Lock() - defer self.Unlock() - - if !self.failing && report.Failure != "" { - self.failing = true - } - if !self.erroring && report.Error != nil { - self.erroring = true - } - if report.Skipped { - self.skipped += 1 - } else { - self.total++ - } -} - -func (self *statistics) Exit() {} - -func (self *statistics) EndStory() { - self.Lock() - defer self.Unlock() - - if !self.suppressed { - self.printSummaryLocked() - } -} - -func (self *statistics) Suppress() { - self.Lock() - defer self.Unlock() - self.suppressed = true -} - -func (self *statistics) PrintSummary() { - self.Lock() - defer self.Unlock() - self.printSummaryLocked() -} - -func (self *statistics) printSummaryLocked() { - self.reportAssertionsLocked() - self.reportSkippedSectionsLocked() - self.completeReportLocked() -} -func (self *statistics) reportAssertionsLocked() { - self.decideColorLocked() - self.out.Print("\n%d total %s", self.total, plural("assertion", self.total)) -} -func (self *statistics) decideColorLocked() { - if self.failing && !self.erroring { - fmt.Print(yellowColor) - } else if self.erroring { - fmt.Print(redColor) - } else { - fmt.Print(greenColor) - } -} -func (self *statistics) reportSkippedSectionsLocked() { - if self.skipped > 0 { - fmt.Print(yellowColor) - self.out.Print(" (one or more sections skipped)") - } -} -func (self *statistics) completeReportLocked() { - fmt.Print(resetColor) - self.out.Print("\n") - self.out.Print("\n") -} - -func (self *statistics) Write(content []byte) (written int, err error) { - return len(content), nil // no-op -} - -func NewStatisticsReporter(out *Printer) *statistics { - self := statistics{} - self.out = out - return &self -} - -type statistics struct { - sync.Mutex - - out *Printer - total int - failing bool - erroring bool - skipped int - suppressed bool -} - -func plural(word string, count int) string { - if count == 1 { - return word - } - return word + "s" -} diff --git a/vendor/github.com/smartystreets/goconvey/convey/reporting/story.go b/vendor/github.com/smartystreets/goconvey/convey/reporting/story.go deleted file mode 100644 index 9e73c971f8fb8..0000000000000 --- a/vendor/github.com/smartystreets/goconvey/convey/reporting/story.go +++ /dev/null @@ -1,73 +0,0 @@ -// TODO: in order for this reporter to be completely honest -// we need to retrofit to be more like the json reporter such that: -// 1. it maintains ScopeResult collections, which count assertions -// 2. it reports only after EndStory(), so that all tick marks -// are placed near the appropriate title. -// 3. Under unit test - -package reporting - -import ( - "fmt" - "strings" -) - -type story struct { - out *Printer - titlesById map[string]string - currentKey []string -} - -func (self *story) BeginStory(story *StoryReport) {} - -func (self *story) Enter(scope *ScopeReport) { - self.out.Indent() - - self.currentKey = append(self.currentKey, scope.Title) - ID := strings.Join(self.currentKey, "|") - - if _, found := self.titlesById[ID]; !found { - self.out.Println("") - self.out.Print(scope.Title) - self.out.Insert(" ") - self.titlesById[ID] = scope.Title - } -} - -func (self *story) Report(report *AssertionResult) { - if report.Error != nil { - fmt.Print(redColor) - self.out.Insert(error_) - } else if report.Failure != "" { - fmt.Print(yellowColor) - self.out.Insert(failure) - } else if report.Skipped { - fmt.Print(yellowColor) - self.out.Insert(skip) - } else { - fmt.Print(greenColor) - self.out.Insert(success) - } - fmt.Print(resetColor) -} - -func (self *story) Exit() { - self.out.Dedent() - self.currentKey = self.currentKey[:len(self.currentKey)-1] -} - -func (self *story) EndStory() { - self.titlesById = make(map[string]string) - self.out.Println("\n") -} - -func (self *story) Write(content []byte) (written int, err error) { - return len(content), nil // no-op -} - -func NewStoryReporter(out *Printer) *story { - self := new(story) - self.out = out - self.titlesById = make(map[string]string) - return self -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 5b4922ebc3ceb..00247b6e7d578 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -7,6 +7,9 @@ code.gitea.io/gitea-vet/checks # code.gitea.io/sdk/gitea v0.13.1 ## explicit code.gitea.io/sdk/gitea +# gitea.com/go-chi/binding v0.0.0-20201220025549-f1056649c959 +## explicit +gitea.com/go-chi/binding # gitea.com/go-chi/session v0.0.0-20201218134809-7209fa084f27 ## explicit gitea.com/go-chi/session @@ -109,10 +112,6 @@ github.com/alecthomas/chroma/lexers/x github.com/alecthomas/chroma/lexers/y github.com/alecthomas/chroma/lexers/z github.com/alecthomas/chroma/styles -# github.com/alexedwards/scs/v2 v2.4.0 -## explicit -github.com/alexedwards/scs/v2 -github.com/alexedwards/scs/v2/memstore # github.com/andybalholm/brotli v1.0.1 ## explicit github.com/andybalholm/brotli @@ -434,8 +433,6 @@ github.com/google/go-querystring/query # github.com/google/uuid v1.1.2 ## explicit github.com/google/uuid -# github.com/gopherjs/gopherjs v0.0.0-20190910122728-9d188e94fb99 -github.com/gopherjs/gopherjs/js # github.com/gorilla/context v1.1.1 ## explicit github.com/gorilla/context @@ -490,8 +487,6 @@ github.com/jessevdk/go-flags github.com/josharian/intern # github.com/json-iterator/go v1.1.10 github.com/json-iterator/go -# github.com/jtolds/gls v4.20.0+incompatible -github.com/jtolds/gls # github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 ## explicit github.com/kballard/go-shellquote @@ -703,16 +698,6 @@ github.com/shurcooL/sanitized_anchor_name github.com/shurcooL/vfsgen # github.com/siddontang/go-snappy v0.0.0-20140704025258-d8f7bb82a96d github.com/siddontang/go-snappy/snappy -# github.com/smartystreets/assertions v1.1.1 -github.com/smartystreets/assertions -github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch -github.com/smartystreets/assertions/internal/go-render/render -github.com/smartystreets/assertions/internal/oglematchers -# github.com/smartystreets/goconvey v1.6.4 -## explicit -github.com/smartystreets/goconvey/convey -github.com/smartystreets/goconvey/convey/gotest -github.com/smartystreets/goconvey/convey/reporting # github.com/spf13/afero v1.3.2 github.com/spf13/afero github.com/spf13/afero/mem From 0e39bac7876a7da95f413fd5f22a1a37fdeba06a Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sun, 20 Dec 2020 11:17:26 +0800 Subject: [PATCH 20/23] Fix lint --- modules/context/default.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/modules/context/default.go b/modules/context/default.go index 4b35e70c3c452..1278724e91f1a 100644 --- a/modules/context/default.go +++ b/modules/context/default.go @@ -75,8 +75,7 @@ func (ctx *DefaultContext) RenderWithErr(msg string, tpl string, form interface{ // SetSession sets session key value func (ctx *DefaultContext) SetSession(key string, val interface{}) error { - ctx.Session.Set(key, val) - return nil + return ctx.Session.Set(key, val) } // GetSession gets session via key From 0ebd7751532bedc257b1c613e9e5f9ce6d5057a1 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 5 Jan 2021 21:36:57 +0800 Subject: [PATCH 21/23] Fix wrong import --- routers/routes/install.go | 3 +-- vendor/modules.txt | 3 --- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/routers/routes/install.go b/routers/routes/install.go index fa3e9ab2ff911..5d37eccbde3c2 100644 --- a/routers/routes/install.go +++ b/routers/routes/install.go @@ -26,10 +26,9 @@ import ( "code.gitea.io/gitea/modules/user" "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/routers" - "gitea.com/go-chi/session" + "gitea.com/go-chi/session" "github.com/go-chi/chi" - "github.com/unknwon/com" "github.com/unrolled/render" "gopkg.in/ini.v1" ) diff --git a/vendor/modules.txt b/vendor/modules.txt index 00247b6e7d578..f890bed843257 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -736,9 +736,6 @@ github.com/syndtr/goleveldb/leveldb/storage github.com/syndtr/goleveldb/leveldb/table github.com/syndtr/goleveldb/leveldb/util # github.com/tinylib/msgp v1.1.5 -# github.com/tecbot/gorocksdb v0.0.0-20181010114359-8752a9433481 -## explicit -# github.com/tinylib/msgp v1.1.2 ## explicit github.com/tinylib/msgp/msgp # github.com/toqueteos/webbrowser v1.2.0 From 178989d83a220638668b6a25514bf184e53e98fb Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 5 Jan 2021 23:45:22 +0800 Subject: [PATCH 22/23] Add Bind function --- modules/middlewares/cookie.go | 1 + modules/options/static.go | 2 +- routers/routes/chi.go | 16 +++++++--------- routers/routes/install.go | 14 +++++--------- 4 files changed, 14 insertions(+), 19 deletions(-) diff --git a/modules/middlewares/cookie.go b/modules/middlewares/cookie.go index 9ef03c205c03d..80d0e3b453ef6 100644 --- a/modules/middlewares/cookie.go +++ b/modules/middlewares/cookie.go @@ -26,6 +26,7 @@ func NewCookie(name, value string, maxAge int) *http.Cookie { } // SetCookie set the cookies +// TODO: Copied from gitea.com/macaron/macaron and should be improved after macaron removed. func SetCookie(resp http.ResponseWriter, name string, value string, others ...interface{}) { cookie := http.Cookie{} cookie.Name = name diff --git a/modules/options/static.go b/modules/options/static.go index ac5c749e3ce1f..5f4ffdda78e49 100644 --- a/modules/options/static.go +++ b/modules/options/static.go @@ -133,7 +133,7 @@ func AssetNames() []string { realFS := Assets.(vfsgen۰FS) var results = make([]string, 0, len(realFS)) for k := range realFS { - results = append(results, "templates/"+k[1:]) + results = append(results, k[1:]) } return results } diff --git a/routers/routes/chi.go b/routers/routes/chi.go index 7659078d23844..560c579a62bd9 100644 --- a/routers/routes/chi.go +++ b/routers/routes/chi.go @@ -188,18 +188,16 @@ func Wrap(f func(ctx *gitea_context.DefaultContext)) http.HandlerFunc { } // Bind binding an obj to a handler -func Bind(obj interface{}, handler http.HandlerFunc) http.HandlerFunc { - return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { - errs := binding.Bind(req, obj) +func Bind(obj interface{}, handler func(ctx *gitea_context.DefaultContext)) http.HandlerFunc { + return Wrap(func(ctx *gitea_context.DefaultContext) { + errs := binding.Bind(ctx.Req, obj) if errs.Len() > 0 { - ctx := gitea_context.GetDefaultContext(req) ctx.Data["HasError"] = true - auth.AssignForm(obj, ctx.Data) - // FIXME: - //ctx.Flash(ErrorFlash, msg) + ctx.Flash(gitea_context.ErrorFlash, errs[0].Error()) } - - handler(resp, req) + auth.AssignForm(obj, ctx.Data) + ctx.Data["form"] = obj + handler(ctx) }) } diff --git a/routers/routes/install.go b/routers/routes/install.go index 5d37eccbde3c2..36725997a70db 100644 --- a/routers/routes/install.go +++ b/routers/routes/install.go @@ -44,7 +44,7 @@ func InstallRoutes() http.Handler { r := chi.NewRouter() r.Use(InstallInit) r.Get("/", Wrap(Install)) - r.Post("/", Bind(&forms.InstallForm{}, Wrap(InstallPost))) + r.Post("/", Bind(&forms.InstallForm{}, InstallPost)) r.NotFound(func(w http.ResponseWriter, req *http.Request) { http.Redirect(w, req, setting.AppURL, 302) }) @@ -88,9 +88,8 @@ func InstallInit(next http.Handler) http.Handler { Session: session.GetSession(req), } - req = context.WithDefaultContext(req, &ctx) - ctx.Req = req - next.ServeHTTP(resp, req) + ctx.Req = context.WithDefaultContext(req, &ctx) + next.ServeHTTP(resp, ctx.Req) }) } @@ -170,12 +169,9 @@ func Install(ctx *context.DefaultContext) { // InstallPost response for submit install items func InstallPost(ctx *context.DefaultContext) { - var form forms.InstallForm - _ = ctx.Bind(&form) + form := ctx.Data["form"].(*forms.InstallForm) - var err error ctx.Data["CurDbOption"] = form.DbType - if ctx.HasError() { if ctx.HasValue("Err_SMTPUser") { ctx.Data["Err_SMTP"] = true @@ -190,6 +186,7 @@ func InstallPost(ctx *context.DefaultContext) { return } + var err error if _, err = exec.LookPath("git"); err != nil { ctx.RenderWithErr(ctx.Tr("install.test_git_failed", err), tplInstall, &form) return @@ -197,7 +194,6 @@ func InstallPost(ctx *context.DefaultContext) { // Pass basic check, now test configuration. // Test database setting. - setting.Database.Type = setting.GetDBTypeByName(form.DbType) setting.Database.Host = form.DbHost setting.Database.User = form.DbUser From 2495059fb5348a63758e732ebd96d7732fe0722c Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Fri, 8 Jan 2021 20:21:21 +0800 Subject: [PATCH 23/23] Fix binding --- modules/forms/forms.go | 28 ++++------------------------ modules/forms/install.go | 4 ++++ routers/routes/chi.go | 16 ++++++---------- routers/routes/install.go | 35 ++++++++++++++++++----------------- 4 files changed, 32 insertions(+), 51 deletions(-) diff --git a/modules/forms/forms.go b/modules/forms/forms.go index cd12a78c8e07a..22311688a09d2 100644 --- a/modules/forms/forms.go +++ b/modules/forms/forms.go @@ -8,6 +8,7 @@ import ( "reflect" "strings" + "code.gitea.io/gitea/modules/auth" "code.gitea.io/gitea/modules/translation" "code.gitea.io/gitea/modules/validation" @@ -20,29 +21,8 @@ type Form interface { binding.Validator } -// AssignForm assign form values back to the template data. -func AssignForm(form interface{}, data map[string]interface{}) { - typ := reflect.TypeOf(form) - val := reflect.ValueOf(form) - - if typ.Kind() == reflect.Ptr { - typ = typ.Elem() - val = val.Elem() - } - - for i := 0; i < typ.NumField(); i++ { - field := typ.Field(i) - - fieldName := field.Tag.Get("form") - // Allow ignored fields in the struct - if fieldName == "-" { - continue - } else if len(fieldName) == 0 { - fieldName = com.ToSnakeCase(field.Name) - } - - data[fieldName] = val.Field(i).Interface() - } +func init() { + binding.SetNameMapper(com.ToSnakeCase) } func getRuleBody(field reflect.StructField, prefix string) string { @@ -84,7 +64,7 @@ func validate(errs binding.Errors, data map[string]interface{}, f Form, l transl // somehow, some code later on will panic on Data["ErrorMsg"].(string). // So initialize it to some default. data["ErrorMsg"] = l.Tr("form.unknown_error") - AssignForm(f, data) + auth.AssignForm(f, data) typ := reflect.TypeOf(f) val := reflect.ValueOf(f) diff --git a/modules/forms/install.go b/modules/forms/install.go index 477734841f1b8..01d7b8c43bf77 100644 --- a/modules/forms/install.go +++ b/modules/forms/install.go @@ -13,6 +13,10 @@ import ( "gitea.com/go-chi/binding" ) +var ( + _ binding.Validator = &InstallForm{} +) + // InstallForm form for installation page type InstallForm struct { DbType string `binding:"Required"` diff --git a/routers/routes/chi.go b/routers/routes/chi.go index 560c579a62bd9..a338e6f80cb33 100644 --- a/routers/routes/chi.go +++ b/routers/routes/chi.go @@ -12,11 +12,11 @@ import ( "net/http" "os" "path" + "reflect" "strings" "text/template" "time" - "code.gitea.io/gitea/modules/auth" gitea_context "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/httpcache" "code.gitea.io/gitea/modules/log" @@ -188,16 +188,12 @@ func Wrap(f func(ctx *gitea_context.DefaultContext)) http.HandlerFunc { } // Bind binding an obj to a handler -func Bind(obj interface{}, handler func(ctx *gitea_context.DefaultContext)) http.HandlerFunc { +func Bind(obj interface{}, handler func(ctx *gitea_context.DefaultContext, form interface{})) http.HandlerFunc { + var tp = reflect.TypeOf(obj).Elem() return Wrap(func(ctx *gitea_context.DefaultContext) { - errs := binding.Bind(ctx.Req, obj) - if errs.Len() > 0 { - ctx.Data["HasError"] = true - ctx.Flash(gitea_context.ErrorFlash, errs[0].Error()) - } - auth.AssignForm(obj, ctx.Data) - ctx.Data["form"] = obj - handler(ctx) + var theObj = reflect.New(tp).Interface() // create a new form obj for every request but not use obj directly + binding.Bind(ctx.Req, theObj) + handler(ctx, theObj) }) } diff --git a/routers/routes/install.go b/routers/routes/install.go index 36725997a70db..c80889d180158 100644 --- a/routers/routes/install.go +++ b/routers/routes/install.go @@ -15,6 +15,7 @@ import ( "time" "code.gitea.io/gitea/models" + "code.gitea.io/gitea/modules/auth" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/forms" "code.gitea.io/gitea/modules/generate" @@ -163,13 +164,13 @@ func Install(ctx *context.DefaultContext) { form.DefaultEnableTimetracking = setting.Service.DefaultEnableTimetracking form.NoReplyAddress = setting.Service.NoReplyAddress - forms.AssignForm(form, ctx.Data) + auth.AssignForm(form, ctx.Data) _ = ctx.HTML(200, tplInstall) } // InstallPost response for submit install items -func InstallPost(ctx *context.DefaultContext) { - form := ctx.Data["form"].(*forms.InstallForm) +func InstallPost(ctx *context.DefaultContext, iForm interface{}) { + form := iForm.(*forms.InstallForm) ctx.Data["CurDbOption"] = form.DbType if ctx.HasError() { @@ -188,7 +189,7 @@ func InstallPost(ctx *context.DefaultContext) { var err error if _, err = exec.LookPath("git"); err != nil { - ctx.RenderWithErr(ctx.Tr("install.test_git_failed", err), tplInstall, &form) + ctx.RenderWithErr(ctx.Tr("install.test_git_failed", err), tplInstall, form) return } @@ -207,7 +208,7 @@ func InstallPost(ctx *context.DefaultContext) { if (setting.Database.Type == "sqlite3") && len(setting.Database.Path) == 0 { ctx.Data["Err_DbPath"] = true - ctx.RenderWithErr(ctx.Tr("install.err_empty_db_path"), tplInstall, &form) + ctx.RenderWithErr(ctx.Tr("install.err_empty_db_path"), tplInstall, form) return } @@ -218,7 +219,7 @@ func InstallPost(ctx *context.DefaultContext) { ctx.RenderWithErr(ctx.Tr("install.sqlite3_not_available", "https://docs.gitea.io/en-us/install-from-binary/"), tplInstall, &form) } else { ctx.Data["Err_DbSetting"] = true - ctx.RenderWithErr(ctx.Tr("install.invalid_db_setting", err), tplInstall, &form) + ctx.RenderWithErr(ctx.Tr("install.invalid_db_setting", err), tplInstall, form) } return } @@ -227,7 +228,7 @@ func InstallPost(ctx *context.DefaultContext) { form.RepoRootPath = strings.ReplaceAll(form.RepoRootPath, "\\", "/") if err = os.MkdirAll(form.RepoRootPath, os.ModePerm); err != nil { ctx.Data["Err_RepoRootPath"] = true - ctx.RenderWithErr(ctx.Tr("install.invalid_repo_path", err), tplInstall, &form) + ctx.RenderWithErr(ctx.Tr("install.invalid_repo_path", err), tplInstall, form) return } @@ -236,7 +237,7 @@ func InstallPost(ctx *context.DefaultContext) { form.LFSRootPath = strings.ReplaceAll(form.LFSRootPath, "\\", "/") if err := os.MkdirAll(form.LFSRootPath, os.ModePerm); err != nil { ctx.Data["Err_LFSRootPath"] = true - ctx.RenderWithErr(ctx.Tr("install.invalid_lfs_path", err), tplInstall, &form) + ctx.RenderWithErr(ctx.Tr("install.invalid_lfs_path", err), tplInstall, form) return } } @@ -245,14 +246,14 @@ func InstallPost(ctx *context.DefaultContext) { form.LogRootPath = strings.ReplaceAll(form.LogRootPath, "\\", "/") if err = os.MkdirAll(form.LogRootPath, os.ModePerm); err != nil { ctx.Data["Err_LogRootPath"] = true - ctx.RenderWithErr(ctx.Tr("install.invalid_log_root_path", err), tplInstall, &form) + ctx.RenderWithErr(ctx.Tr("install.invalid_log_root_path", err), tplInstall, form) return } currentUser, match := setting.IsRunUserMatchCurrentUser(form.RunUser) if !match { ctx.Data["Err_RunUser"] = true - ctx.RenderWithErr(ctx.Tr("install.run_user_not_match", form.RunUser, currentUser), tplInstall, &form) + ctx.RenderWithErr(ctx.Tr("install.run_user_not_match", form.RunUser, currentUser), tplInstall, form) return } @@ -397,19 +398,19 @@ func InstallPost(ctx *context.DefaultContext) { cfg.Section("security").Key("INSTALL_LOCK").SetValue("true") var secretKey string if secretKey, err = generate.NewSecretKey(); err != nil { - ctx.RenderWithErr(ctx.Tr("install.secret_key_failed", err), tplInstall, &form) + ctx.RenderWithErr(ctx.Tr("install.secret_key_failed", err), tplInstall, form) return } cfg.Section("security").Key("SECRET_KEY").SetValue(secretKey) err = os.MkdirAll(filepath.Dir(setting.CustomConf), os.ModePerm) if err != nil { - ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form) + ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, form) return } if err = cfg.SaveTo(setting.CustomConf); err != nil { - ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form) + ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, form) return } @@ -430,7 +431,7 @@ func InstallPost(ctx *context.DefaultContext) { setting.InstallLock = false ctx.Data["Err_AdminName"] = true ctx.Data["Err_AdminEmail"] = true - ctx.RenderWithErr(ctx.Tr("install.invalid_admin_setting", err), tplInstall, &form) + ctx.RenderWithErr(ctx.Tr("install.invalid_admin_setting", err), tplInstall, form) return } log.Info("Admin account already exist") @@ -444,16 +445,16 @@ func InstallPost(ctx *context.DefaultContext) { // Auto-login for admin if err = ctx.SetSession("uid", u.ID); err != nil { - ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form) + ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, form) return } if err = ctx.SetSession("uname", u.Name); err != nil { - ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form) + ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, form) return } if err = ctx.DestroySession(); err != nil { - ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, &form) + ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), tplInstall, form) return } }