upgrading libs
Этот коммит содержится в:
2
Godeps/_workspace/src/github.com/anachronistic/apns/client_mock.go
сгенерированный
поставляемый
2
Godeps/_workspace/src/github.com/anachronistic/apns/client_mock.go
сгенерированный
поставляемый
@@ -1,6 +1,6 @@
|
||||
package apns
|
||||
|
||||
import "github.com/stretchr/testify/mock"
|
||||
import "github.com/mattermost/platform/Godeps/_workspace/src/github.com/stretchr/testify/mock"
|
||||
|
||||
type MockClient struct {
|
||||
mock.Mock
|
||||
|
||||
2
Godeps/_workspace/src/github.com/anachronistic/apns/client_mock_test.go
сгенерированный
поставляемый
2
Godeps/_workspace/src/github.com/anachronistic/apns/client_mock_test.go
сгенерированный
поставляемый
@@ -4,7 +4,7 @@ import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/mattermost/platform/Godeps/_workspace/src/github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestMockClientConnectAndWrite(t *testing.T) {
|
||||
|
||||
11
Godeps/_workspace/src/github.com/braintree/manners/README.md
сгенерированный
поставляемый
11
Godeps/_workspace/src/github.com/braintree/manners/README.md
сгенерированный
поставляемый
@@ -7,23 +7,26 @@ Manners allows you to shut your Go webserver down gracefully, without dropping a
|
||||
```go
|
||||
func main() {
|
||||
handler := MyHTTPHandler()
|
||||
server := manners.NewServer()
|
||||
server.ListenAndServe(":7000", handler)
|
||||
manners.ListenAndServe(":7000", handler)
|
||||
}
|
||||
```
|
||||
|
||||
Then, when you want to shut the server down:
|
||||
|
||||
```go
|
||||
server.Shutdown <- true
|
||||
manners.Close()
|
||||
```
|
||||
|
||||
(Note that this does not block until all the requests are finished. Rather, the call to server.ListenAndServe will stop blocking when all the requests are finished.)
|
||||
(Note that this does not block until all the requests are finished. Rather, the call to manners.ListenAndServe will stop blocking when all the requests are finished.)
|
||||
|
||||
Manners ensures that all requests are served by incrementing a WaitGroup when a request comes in and decrementing it when the request finishes.
|
||||
|
||||
If your request handler spawns Goroutines that are not guaranteed to finish with the request, you can ensure they are also completed with the `StartRoutine` and `FinishRoutine` functions on the server.
|
||||
|
||||
### Known Issues
|
||||
|
||||
Manners does not correctly shut down long-lived keepalive connections when issued a shutdown command. Clients on an idle keepalive connection may see a connection reset error rather than a close. See https://github.com/braintree/manners/issues/13 for details.
|
||||
|
||||
### Compatability
|
||||
|
||||
Manners 0.3.0 and above uses standard library functionality introduced in Go 1.3.
|
||||
|
||||
34
Godeps/_workspace/src/github.com/braintree/manners/helper_test.go
сгенерированный
поставляемый
34
Godeps/_workspace/src/github.com/braintree/manners/helper_test.go
сгенерированный
поставляемый
@@ -1,34 +0,0 @@
|
||||
package manners
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A response handler that blocks until it receives a signal; simulates an
|
||||
// arbitrarily long web request. The "ready" channel is to prevent a race
|
||||
// condition in the test where the test moves on before the server is ready
|
||||
// to handle the request.
|
||||
func newBlockingHandler(ready, done chan bool) *blockingHandler {
|
||||
return &blockingHandler{ready, done}
|
||||
}
|
||||
|
||||
type blockingHandler struct {
|
||||
ready chan bool
|
||||
done chan bool
|
||||
}
|
||||
|
||||
func (h *blockingHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
|
||||
h.ready <- true
|
||||
time.Sleep(1e2)
|
||||
h.done <- true
|
||||
}
|
||||
|
||||
// A response handler that does nothing.
|
||||
func newTestHandler() testHandler {
|
||||
return testHandler{}
|
||||
}
|
||||
|
||||
type testHandler struct{}
|
||||
|
||||
func (h testHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {}
|
||||
123
Godeps/_workspace/src/github.com/braintree/manners/helpers_test.go
сгенерированный
поставляемый
Обычный файл
123
Godeps/_workspace/src/github.com/braintree/manners/helpers_test.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,123 @@
|
||||
package manners
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/tls"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func newServer() *GracefulServer {
|
||||
return NewWithServer(new(http.Server))
|
||||
}
|
||||
|
||||
// a simple step-controllable http client
|
||||
type client struct {
|
||||
tls bool
|
||||
addr net.Addr
|
||||
connected chan error
|
||||
sendrequest chan bool
|
||||
response chan *rawResponse
|
||||
closed chan bool
|
||||
}
|
||||
|
||||
type rawResponse struct {
|
||||
body []string
|
||||
err error
|
||||
}
|
||||
|
||||
func (c *client) Run() {
|
||||
go func() {
|
||||
var err error
|
||||
conn, err := net.Dial(c.addr.Network(), c.addr.String())
|
||||
if err != nil {
|
||||
c.connected <- err
|
||||
return
|
||||
}
|
||||
if c.tls {
|
||||
conn = tls.Client(conn, &tls.Config{InsecureSkipVerify: true})
|
||||
}
|
||||
c.connected <- nil
|
||||
for <-c.sendrequest {
|
||||
_, err = conn.Write([]byte("GET / HTTP/1.1\nHost: localhost:8000\n\n"))
|
||||
if err != nil {
|
||||
c.response <- &rawResponse{err: err}
|
||||
}
|
||||
// Read response; no content
|
||||
scanner := bufio.NewScanner(conn)
|
||||
var lines []string
|
||||
for scanner.Scan() {
|
||||
// our null handler doesn't send a body, so we know the request is
|
||||
// done when we reach the blank line after the headers
|
||||
line := scanner.Text()
|
||||
if line == "" {
|
||||
break
|
||||
}
|
||||
lines = append(lines, line)
|
||||
}
|
||||
c.response <- &rawResponse{lines, scanner.Err()}
|
||||
}
|
||||
conn.Close()
|
||||
ioutil.ReadAll(conn)
|
||||
c.closed <- true
|
||||
}()
|
||||
}
|
||||
|
||||
func newClient(addr net.Addr, tls bool) *client {
|
||||
return &client{
|
||||
addr: addr,
|
||||
tls: tls,
|
||||
connected: make(chan error),
|
||||
sendrequest: make(chan bool),
|
||||
response: make(chan *rawResponse),
|
||||
closed: make(chan bool),
|
||||
}
|
||||
}
|
||||
|
||||
// a handler that returns 200 ok with no body
|
||||
var nullHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
|
||||
|
||||
func startGenericServer(t *testing.T, server *GracefulServer, statechanged chan http.ConnState, runner func() error) (l net.Listener, errc chan error) {
|
||||
server.Addr = "localhost:0"
|
||||
server.Handler = nullHandler
|
||||
if statechanged != nil {
|
||||
// Wrap the ConnState handler with something that will notify
|
||||
// the statechanged channel when a state change happens
|
||||
server.ConnState = func(conn net.Conn, newState http.ConnState) {
|
||||
statechanged <- newState
|
||||
}
|
||||
}
|
||||
|
||||
server.up = make(chan net.Listener)
|
||||
exitchan := make(chan error)
|
||||
|
||||
go func() {
|
||||
exitchan <- runner()
|
||||
}()
|
||||
|
||||
// wait for server socket to be bound
|
||||
select {
|
||||
case l = <-server.up:
|
||||
// all good
|
||||
|
||||
case err := <-exitchan:
|
||||
// all bad
|
||||
t.Fatal("Server failed to start", err)
|
||||
}
|
||||
return l, exitchan
|
||||
}
|
||||
|
||||
func startServer(t *testing.T, server *GracefulServer, statechanged chan http.ConnState) (
|
||||
l net.Listener, errc chan error) {
|
||||
return startGenericServer(t, server, statechanged, server.ListenAndServe)
|
||||
}
|
||||
|
||||
func startTLSServer(t *testing.T, server *GracefulServer, certFile, keyFile string, statechanged chan http.ConnState) (l net.Listener, errc chan error) {
|
||||
runner := func() error {
|
||||
return server.ListenAndServeTLS(certFile, keyFile)
|
||||
}
|
||||
|
||||
return startGenericServer(t, server, statechanged, runner)
|
||||
}
|
||||
7
Godeps/_workspace/src/github.com/braintree/manners/interfaces.go
сгенерированный
поставляемый
Обычный файл
7
Godeps/_workspace/src/github.com/braintree/manners/interfaces.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,7 @@
|
||||
package manners
|
||||
|
||||
type waitGroup interface {
|
||||
Add(int)
|
||||
Done()
|
||||
Wait()
|
||||
}
|
||||
49
Godeps/_workspace/src/github.com/braintree/manners/listener.go
сгенерированный
поставляемый
49
Godeps/_workspace/src/github.com/braintree/manners/listener.go
сгенерированный
поставляемый
@@ -1,49 +0,0 @@
|
||||
package manners
|
||||
|
||||
import (
|
||||
"net"
|
||||
"sync"
|
||||
)
|
||||
|
||||
func NewListener(l net.Listener, s *GracefulServer) *GracefulListener {
|
||||
return &GracefulListener{l, true, s, sync.RWMutex{}}
|
||||
}
|
||||
|
||||
// A GracefulListener differs from a standard net.Listener in one way: if
|
||||
// Accept() is called after it is gracefully closed, it returns a
|
||||
// listenerAlreadyClosed error. The GracefulServer will ignore this
|
||||
// error.
|
||||
type GracefulListener struct {
|
||||
net.Listener
|
||||
open bool
|
||||
server *GracefulServer
|
||||
rw sync.RWMutex
|
||||
}
|
||||
|
||||
func (l *GracefulListener) Accept() (net.Conn, error) {
|
||||
conn, err := l.Listener.Accept()
|
||||
if err != nil {
|
||||
l.rw.RLock()
|
||||
defer l.rw.RUnlock()
|
||||
if !l.open {
|
||||
err = listenerAlreadyClosed{err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func (l *GracefulListener) Close() error {
|
||||
l.rw.Lock()
|
||||
defer l.rw.Unlock()
|
||||
if !l.open {
|
||||
return nil
|
||||
}
|
||||
l.open = false
|
||||
err := l.Listener.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
type listenerAlreadyClosed struct {
|
||||
error
|
||||
}
|
||||
275
Godeps/_workspace/src/github.com/braintree/manners/server.go
сгенерированный
поставляемый
275
Godeps/_workspace/src/github.com/braintree/manners/server.go
сгенерированный
поставляемый
@@ -1,83 +1,272 @@
|
||||
/*
|
||||
Package manners provides a wrapper for a standard net/http server that
|
||||
ensures all active HTTP client have completed their current request
|
||||
before the server shuts down.
|
||||
|
||||
It can be used a drop-in replacement for the standard http package,
|
||||
or can wrap a pre-configured Server.
|
||||
|
||||
eg.
|
||||
|
||||
http.Handle("/hello", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte("Hello\n"))
|
||||
})
|
||||
|
||||
log.Fatal(manners.ListenAndServe(":8080", nil))
|
||||
|
||||
or for a customized server:
|
||||
|
||||
s := manners.NewWithServer(&http.Server{
|
||||
Addr: ":8080",
|
||||
Handler: myHandler,
|
||||
ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: 10 * time.Second,
|
||||
MaxHeaderBytes: 1 << 20,
|
||||
})
|
||||
log.Fatal(s.ListenAndServe())
|
||||
|
||||
The server will shut down cleanly when the Close() method is called:
|
||||
|
||||
go func() {
|
||||
sigchan := make(chan os.Signal, 1)
|
||||
signal.Notify(sigchan, os.Interrupt, os.Kill)
|
||||
<-sigchan
|
||||
log.Info("Shutting down...")
|
||||
manners.Close()
|
||||
}()
|
||||
|
||||
http.Handle("/hello", myHandler)
|
||||
log.Fatal(manners.ListenAndServe(":8080", nil))
|
||||
*/
|
||||
package manners
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
// Creates a new GracefulServer. The server will begin shutting down when
|
||||
// a value is passed to the Shutdown channel.
|
||||
func NewServer() *GracefulServer {
|
||||
return &GracefulServer{
|
||||
Shutdown: make(chan bool),
|
||||
}
|
||||
}
|
||||
|
||||
// A GracefulServer maintains a WaitGroup that counts how many in-flight
|
||||
// requests the server is handling. When it receives a shutdown signal,
|
||||
// it stops accepting new requests but does not actually shut down until
|
||||
// all in-flight requests terminate.
|
||||
//
|
||||
// GracefulServer embeds the underlying net/http.Server making its non-override
|
||||
// methods and properties avaiable.
|
||||
//
|
||||
// It must be initialized by calling NewWithServer.
|
||||
type GracefulServer struct {
|
||||
Shutdown chan bool
|
||||
wg sync.WaitGroup
|
||||
shutdownHandler func()
|
||||
InnerServer http.Server
|
||||
*http.Server
|
||||
|
||||
shutdown chan bool
|
||||
shutdownFinished chan bool
|
||||
wg waitGroup
|
||||
|
||||
lcsmu sync.RWMutex
|
||||
connections map[net.Conn]bool
|
||||
|
||||
up chan net.Listener // Only used by test code.
|
||||
}
|
||||
|
||||
// A helper function that emulates the functionality of http.ListenAndServe.
|
||||
func (s *GracefulServer) ListenAndServe(addr string, handler http.Handler) error {
|
||||
oldListener, err := net.Listen("tcp", addr)
|
||||
// NewWithServer wraps an existing http.Server object and returns a
|
||||
// GracefulServer that supports all of the original Server operations.
|
||||
func NewWithServer(s *http.Server) *GracefulServer {
|
||||
return &GracefulServer{
|
||||
Server: s,
|
||||
shutdown: make(chan bool),
|
||||
shutdownFinished: make(chan bool, 1),
|
||||
wg: new(sync.WaitGroup),
|
||||
connections: make(map[net.Conn]bool),
|
||||
}
|
||||
}
|
||||
|
||||
// Close stops the server from accepting new requets and begins shutting down.
|
||||
// It returns true if it's the first time Close is called.
|
||||
func (s *GracefulServer) Close() bool {
|
||||
return <-s.shutdown
|
||||
}
|
||||
|
||||
// BlockingClose is similar to Close, except that it blocks until the last
|
||||
// connection has been closed.
|
||||
func (s *GracefulServer) BlockingClose() bool {
|
||||
result := s.Close()
|
||||
<-s.shutdownFinished
|
||||
return result
|
||||
}
|
||||
|
||||
// ListenAndServe provides a graceful equivalent of net/http.Serve.ListenAndServe.
|
||||
func (s *GracefulServer) ListenAndServe() error {
|
||||
addr := s.Addr
|
||||
if addr == "" {
|
||||
addr = ":http"
|
||||
}
|
||||
listener, err := net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
listener := NewListener(oldListener, s)
|
||||
err = s.Serve(listener, handler)
|
||||
return err
|
||||
return s.Serve(listener)
|
||||
}
|
||||
|
||||
// Similar to http.Serve. The listener passed must wrap a GracefulListener.
|
||||
func (s *GracefulServer) Serve(listener net.Listener, handler http.Handler) error {
|
||||
s.shutdownHandler = func() { listener.Close() }
|
||||
s.listenForShutdown()
|
||||
s.InnerServer.Handler = handler
|
||||
s.InnerServer.ConnState = func(conn net.Conn, newState http.ConnState) {
|
||||
// ListenAndServeTLS provides a graceful equivalent of net/http.Serve.ListenAndServeTLS.
|
||||
func (s *GracefulServer) ListenAndServeTLS(certFile, keyFile string) error {
|
||||
// direct lift from net/http/server.go
|
||||
addr := s.Addr
|
||||
if addr == "" {
|
||||
addr = ":https"
|
||||
}
|
||||
config := &tls.Config{}
|
||||
if s.TLSConfig != nil {
|
||||
*config = *s.TLSConfig
|
||||
}
|
||||
if config.NextProtos == nil {
|
||||
config.NextProtos = []string{"http/1.1"}
|
||||
}
|
||||
|
||||
var err error
|
||||
config.Certificates = make([]tls.Certificate, 1)
|
||||
config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ln, err := net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.Serve(tls.NewListener(ln, config))
|
||||
}
|
||||
|
||||
// Serve provides a graceful equivalent net/http.Server.Serve.
|
||||
func (s *GracefulServer) Serve(listener net.Listener) error {
|
||||
// Wrap the server HTTP handler into graceful one, that will close kept
|
||||
// alive connections if a new request is received after shutdown.
|
||||
gracefulHandler := newGracefulHandler(s.Server.Handler)
|
||||
s.Server.Handler = gracefulHandler
|
||||
|
||||
// Start a goroutine that waits for a shutdown signal and will stop the
|
||||
// listener when it receives the signal. That in turn will result in
|
||||
// unblocking of the http.Serve call.
|
||||
go func() {
|
||||
s.shutdown <- true
|
||||
close(s.shutdown)
|
||||
gracefulHandler.Close()
|
||||
s.Server.SetKeepAlivesEnabled(false)
|
||||
listener.Close()
|
||||
}()
|
||||
|
||||
originalConnState := s.Server.ConnState
|
||||
|
||||
// s.ConnState is invoked by the net/http.Server every time a connection
|
||||
// changes state. It keeps track of each connection's state over time,
|
||||
// enabling manners to handle persisted connections correctly.
|
||||
s.ConnState = func(conn net.Conn, newState http.ConnState) {
|
||||
s.lcsmu.RLock()
|
||||
protected := s.connections[conn]
|
||||
s.lcsmu.RUnlock()
|
||||
|
||||
switch newState {
|
||||
|
||||
case http.StateNew:
|
||||
// New connection -> StateNew
|
||||
protected = true
|
||||
s.StartRoutine()
|
||||
case http.StateClosed, http.StateHijacked:
|
||||
s.FinishRoutine()
|
||||
|
||||
case http.StateActive:
|
||||
// (StateNew, StateIdle) -> StateActive
|
||||
if gracefulHandler.IsClosed() {
|
||||
conn.Close()
|
||||
break
|
||||
}
|
||||
|
||||
if !protected {
|
||||
protected = true
|
||||
s.StartRoutine()
|
||||
}
|
||||
|
||||
default:
|
||||
// (StateNew, StateActive) -> (StateIdle, StateClosed, StateHiJacked)
|
||||
if protected {
|
||||
s.FinishRoutine()
|
||||
protected = false
|
||||
}
|
||||
}
|
||||
|
||||
s.lcsmu.Lock()
|
||||
if newState == http.StateClosed || newState == http.StateHijacked {
|
||||
delete(s.connections, conn)
|
||||
} else {
|
||||
s.connections[conn] = protected
|
||||
}
|
||||
s.lcsmu.Unlock()
|
||||
|
||||
if originalConnState != nil {
|
||||
originalConnState(conn, newState)
|
||||
}
|
||||
}
|
||||
err := s.InnerServer.Serve(listener)
|
||||
|
||||
// This block is reached when the server has received a shut down command.
|
||||
if err == nil {
|
||||
s.wg.Wait()
|
||||
return nil
|
||||
} else if _, ok := err.(listenerAlreadyClosed); ok {
|
||||
s.wg.Wait()
|
||||
return nil
|
||||
// A hook to allow the server to notify others when it is ready to receive
|
||||
// requests; only used by tests.
|
||||
if s.up != nil {
|
||||
s.up <- listener
|
||||
}
|
||||
|
||||
err := s.Server.Serve(listener)
|
||||
// An error returned on shutdown is not worth reporting.
|
||||
if err != nil && gracefulHandler.IsClosed() {
|
||||
err = nil
|
||||
}
|
||||
|
||||
// Wait for pending requests to complete regardless the Serve result.
|
||||
s.wg.Wait()
|
||||
s.shutdownFinished <- true
|
||||
return err
|
||||
}
|
||||
|
||||
// Increments the server's WaitGroup. Use this if a web request starts more
|
||||
// goroutines and these goroutines are not guaranteed to finish before the
|
||||
// request.
|
||||
// StartRoutine increments the server's WaitGroup. Use this if a web request
|
||||
// starts more goroutines and these goroutines are not guaranteed to finish
|
||||
// before the request.
|
||||
func (s *GracefulServer) StartRoutine() {
|
||||
s.wg.Add(1)
|
||||
}
|
||||
|
||||
// Decrement the server's WaitGroup. Used this to complement StartRoutine().
|
||||
// FinishRoutine decrements the server's WaitGroup. Use this to complement
|
||||
// StartRoutine().
|
||||
func (s *GracefulServer) FinishRoutine() {
|
||||
s.wg.Done()
|
||||
}
|
||||
|
||||
func (s *GracefulServer) listenForShutdown() {
|
||||
go func() {
|
||||
<-s.Shutdown
|
||||
s.shutdownHandler()
|
||||
}()
|
||||
// gracefulHandler is used by GracefulServer to prevent calling ServeHTTP on
|
||||
// to be closed kept-alive connections during the server shutdown.
|
||||
type gracefulHandler struct {
|
||||
closed int32 // accessed atomically.
|
||||
wrapped http.Handler
|
||||
}
|
||||
|
||||
func newGracefulHandler(wrapped http.Handler) *gracefulHandler {
|
||||
return &gracefulHandler{
|
||||
wrapped: wrapped,
|
||||
}
|
||||
}
|
||||
|
||||
func (gh *gracefulHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if atomic.LoadInt32(&gh.closed) == 0 {
|
||||
gh.wrapped.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
r.Body.Close()
|
||||
// Server is shutting down at this moment, and the connection that this
|
||||
// handler is being called on is about to be closed. So we do not need to
|
||||
// actually execute the handler logic.
|
||||
}
|
||||
|
||||
func (gh *gracefulHandler) Close() {
|
||||
atomic.StoreInt32(&gh.closed, 1)
|
||||
}
|
||||
|
||||
func (gh *gracefulHandler) IsClosed() bool {
|
||||
return atomic.LoadInt32(&gh.closed) == 1
|
||||
}
|
||||
|
||||
277
Godeps/_workspace/src/github.com/braintree/manners/server_test.go
сгенерированный
поставляемый
277
Godeps/_workspace/src/github.com/braintree/manners/server_test.go
сгенерированный
поставляемый
@@ -1,71 +1,254 @@
|
||||
package manners
|
||||
|
||||
import (
|
||||
helpers "github.com/mattermost/platform/Godeps/_workspace/src/github.com/braintree/manners/test_helpers"
|
||||
"net"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Tests that the server allows in-flight requests to complete before shutting
|
||||
// down.
|
||||
type httpInterface interface {
|
||||
ListenAndServe() error
|
||||
ListenAndServeTLS(certFile, keyFile string) error
|
||||
Serve(listener net.Listener) error
|
||||
}
|
||||
|
||||
// Test that the method signatures of the methods we override from net/http/Server match those of the original.
|
||||
func TestInterface(t *testing.T) {
|
||||
var original, ours interface{}
|
||||
original = &http.Server{}
|
||||
ours = &GracefulServer{}
|
||||
if _, ok := original.(httpInterface); !ok {
|
||||
t.Errorf("httpInterface definition does not match the canonical server!")
|
||||
}
|
||||
if _, ok := ours.(httpInterface); !ok {
|
||||
t.Errorf("GracefulServer does not implement httpInterface")
|
||||
}
|
||||
}
|
||||
|
||||
// Tests that the server allows in-flight requests to complete
|
||||
// before shutting down.
|
||||
func TestGracefulness(t *testing.T) {
|
||||
ready := make(chan bool)
|
||||
done := make(chan bool)
|
||||
server := newServer()
|
||||
wg := helpers.NewWaitGroup()
|
||||
server.wg = wg
|
||||
statechanged := make(chan http.ConnState)
|
||||
listener, exitchan := startServer(t, server, statechanged)
|
||||
|
||||
exited := false
|
||||
client := newClient(listener.Addr(), false)
|
||||
client.Run()
|
||||
|
||||
handler := newBlockingHandler(ready, done)
|
||||
server := NewServer()
|
||||
// wait for client to connect, but don't let it send the request yet
|
||||
if err := <-client.connected; err != nil {
|
||||
t.Fatal("Client failed to connect to server", err)
|
||||
}
|
||||
// Even though the client is connected, the server ConnState handler may
|
||||
// not know about that yet. So wait until it is called.
|
||||
waitForState(t, statechanged, http.StateNew, "Request not received")
|
||||
|
||||
go func() {
|
||||
err := server.ListenAndServe(":7000", handler)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
server.Close()
|
||||
|
||||
exited = true
|
||||
}()
|
||||
waiting := <-wg.WaitCalled
|
||||
if waiting < 1 {
|
||||
t.Errorf("Expected the waitgroup to equal 1 at shutdown; actually %d", waiting)
|
||||
}
|
||||
|
||||
go func() {
|
||||
_, err := http.Get("http://localhost:7000")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}()
|
||||
|
||||
// This will block until the server is inside the handler function.
|
||||
<-ready
|
||||
|
||||
server.Shutdown <- true
|
||||
<-done
|
||||
|
||||
if exited {
|
||||
t.Fatal("The request did not complete before server exited")
|
||||
} else {
|
||||
// The handler is being allowed to run to completion; test passes.
|
||||
// allow the client to finish sending the request and make sure the server exits after
|
||||
// (client will be in connected but idle state at that point)
|
||||
client.sendrequest <- true
|
||||
close(client.sendrequest)
|
||||
if err := <-exitchan; err != nil {
|
||||
t.Error("Unexpected error during shutdown", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Tests that the server begins to shut down when told to and does not accept
|
||||
// new requests
|
||||
// new requests once shutdown has begun
|
||||
func TestShutdown(t *testing.T) {
|
||||
handler := newTestHandler()
|
||||
server := NewServer()
|
||||
exited := make(chan bool)
|
||||
server := newServer()
|
||||
wg := helpers.NewWaitGroup()
|
||||
server.wg = wg
|
||||
statechanged := make(chan http.ConnState)
|
||||
listener, exitchan := startServer(t, server, statechanged)
|
||||
|
||||
go func() {
|
||||
err := server.ListenAndServe(":7100", handler)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
exited <- true
|
||||
}()
|
||||
client1 := newClient(listener.Addr(), false)
|
||||
client1.Run()
|
||||
|
||||
server.Shutdown <- true
|
||||
// wait for client1 to connect
|
||||
if err := <-client1.connected; err != nil {
|
||||
t.Fatal("Client failed to connect to server", err)
|
||||
}
|
||||
// Even though the client is connected, the server ConnState handler may
|
||||
// not know about that yet. So wait until it is called.
|
||||
waitForState(t, statechanged, http.StateNew, "Request not received")
|
||||
|
||||
<-exited
|
||||
_, err := http.Get("http://localhost:7100")
|
||||
// start the shutdown; once it hits waitgroup.Wait()
|
||||
// the listener should of been closed, though client1 is still connected
|
||||
if server.Close() != true {
|
||||
t.Fatal("first call to Close returned false")
|
||||
}
|
||||
if server.Close() != false {
|
||||
t.Fatal("second call to Close returned true")
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("Did not receive an error when trying to connect to server.")
|
||||
waiting := <-wg.WaitCalled
|
||||
if waiting != 1 {
|
||||
t.Errorf("Waitcount should be one, got %d", waiting)
|
||||
}
|
||||
|
||||
// should get connection refused at this point
|
||||
client2 := newClient(listener.Addr(), false)
|
||||
client2.Run()
|
||||
|
||||
if err := <-client2.connected; err == nil {
|
||||
t.Fatal("client2 connected when it should of received connection refused")
|
||||
}
|
||||
|
||||
// let client1 finish so the server can exit
|
||||
close(client1.sendrequest) // don't bother sending an actual request
|
||||
|
||||
<-exitchan
|
||||
}
|
||||
|
||||
// If a request is sent to a closed server via a kept alive connection then
|
||||
// the server closes the connection upon receiving the request.
|
||||
func TestRequestAfterClose(t *testing.T) {
|
||||
// Given
|
||||
server := newServer()
|
||||
srvStateChangedCh := make(chan http.ConnState, 100)
|
||||
listener, srvClosedCh := startServer(t, server, srvStateChangedCh)
|
||||
|
||||
client := newClient(listener.Addr(), false)
|
||||
client.Run()
|
||||
<-client.connected
|
||||
client.sendrequest <- true
|
||||
<-client.response
|
||||
|
||||
server.Close()
|
||||
if err := <-srvClosedCh; err != nil {
|
||||
t.Error("Unexpected error during shutdown", err)
|
||||
}
|
||||
|
||||
// When
|
||||
client.sendrequest <- true
|
||||
rr := <-client.response
|
||||
|
||||
// Then
|
||||
if rr.body != nil || rr.err != nil {
|
||||
t.Errorf("Request should be rejected, body=%v, err=%v", rr.body, rr.err)
|
||||
}
|
||||
}
|
||||
|
||||
func waitForState(t *testing.T, waiter chan http.ConnState, state http.ConnState, errmsg string) {
|
||||
for {
|
||||
select {
|
||||
case ns := <-waiter:
|
||||
if ns == state {
|
||||
return
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal(errmsg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Test that a request moving from active->idle->active using an actual
|
||||
// network connection still results in a corect shutdown
|
||||
func TestStateTransitionActiveIdleActive(t *testing.T) {
|
||||
server := newServer()
|
||||
wg := helpers.NewWaitGroup()
|
||||
statechanged := make(chan http.ConnState)
|
||||
server.wg = wg
|
||||
listener, exitchan := startServer(t, server, statechanged)
|
||||
|
||||
client := newClient(listener.Addr(), false)
|
||||
client.Run()
|
||||
|
||||
// wait for client to connect, but don't let it send the request
|
||||
if err := <-client.connected; err != nil {
|
||||
t.Fatal("Client failed to connect to server", err)
|
||||
}
|
||||
|
||||
for i := 0; i < 2; i++ {
|
||||
client.sendrequest <- true
|
||||
waitForState(t, statechanged, http.StateActive, "Client failed to reach active state")
|
||||
<-client.response
|
||||
waitForState(t, statechanged, http.StateIdle, "Client failed to reach idle state")
|
||||
}
|
||||
|
||||
// client is now in an idle state
|
||||
|
||||
server.Close()
|
||||
waiting := <-wg.WaitCalled
|
||||
if waiting != 0 {
|
||||
t.Errorf("Waitcount should be zero, got %d", waiting)
|
||||
}
|
||||
|
||||
if err := <-exitchan; err != nil {
|
||||
t.Error("Unexpected error during shutdown", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Test state transitions from new->active->-idle->closed using an actual
|
||||
// network connection and make sure the waitgroup count is correct at the end.
|
||||
func TestStateTransitionActiveIdleClosed(t *testing.T) {
|
||||
var (
|
||||
listener net.Listener
|
||||
exitchan chan error
|
||||
)
|
||||
|
||||
keyFile, err1 := helpers.NewTempFile(helpers.Key)
|
||||
certFile, err2 := helpers.NewTempFile(helpers.Cert)
|
||||
defer keyFile.Unlink()
|
||||
defer certFile.Unlink()
|
||||
|
||||
if err1 != nil || err2 != nil {
|
||||
t.Fatal("Failed to create temporary files", err1, err2)
|
||||
}
|
||||
|
||||
for _, withTLS := range []bool{false, true} {
|
||||
server := newServer()
|
||||
wg := helpers.NewWaitGroup()
|
||||
statechanged := make(chan http.ConnState)
|
||||
server.wg = wg
|
||||
if withTLS {
|
||||
listener, exitchan = startTLSServer(t, server, certFile.Name(), keyFile.Name(), statechanged)
|
||||
} else {
|
||||
listener, exitchan = startServer(t, server, statechanged)
|
||||
}
|
||||
|
||||
client := newClient(listener.Addr(), withTLS)
|
||||
client.Run()
|
||||
|
||||
// wait for client to connect, but don't let it send the request
|
||||
if err := <-client.connected; err != nil {
|
||||
t.Fatal("Client failed to connect to server", err)
|
||||
}
|
||||
|
||||
client.sendrequest <- true
|
||||
waitForState(t, statechanged, http.StateActive, "Client failed to reach active state")
|
||||
|
||||
rr := <-client.response
|
||||
if rr.err != nil {
|
||||
t.Fatalf("tls=%t unexpected error from client %s", withTLS, rr.err)
|
||||
}
|
||||
|
||||
waitForState(t, statechanged, http.StateIdle, "Client failed to reach idle state")
|
||||
|
||||
// client is now in an idle state
|
||||
close(client.sendrequest)
|
||||
<-client.closed
|
||||
waitForState(t, statechanged, http.StateClosed, "Client failed to reach closed state")
|
||||
|
||||
server.Close()
|
||||
waiting := <-wg.WaitCalled
|
||||
if waiting != 0 {
|
||||
t.Errorf("Waitcount should be zero, got %d", waiting)
|
||||
}
|
||||
|
||||
if err := <-exitchan; err != nil {
|
||||
t.Error("Unexpected error during shutdown", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
35
Godeps/_workspace/src/github.com/braintree/manners/static.go
сгенерированный
поставляемый
Обычный файл
35
Godeps/_workspace/src/github.com/braintree/manners/static.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,35 @@
|
||||
package manners
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
var defaultServer *GracefulServer
|
||||
|
||||
// ListenAndServe provides a graceful version of the function provided by the
|
||||
// net/http package. Call Close() to stop the server.
|
||||
func ListenAndServe(addr string, handler http.Handler) error {
|
||||
defaultServer = NewWithServer(&http.Server{Addr: addr, Handler: handler})
|
||||
return defaultServer.ListenAndServe()
|
||||
}
|
||||
|
||||
// ListenAndServeTLS provides a graceful version of the function provided by the
|
||||
// net/http package. Call Close() to stop the server.
|
||||
func ListenAndServeTLS(addr string, certFile string, keyFile string, handler http.Handler) error {
|
||||
defaultServer = NewWithServer(&http.Server{Addr: addr, Handler: handler})
|
||||
return defaultServer.ListenAndServeTLS(certFile, keyFile)
|
||||
}
|
||||
|
||||
// Serve provides a graceful version of the function provided by the net/http
|
||||
// package. Call Close() to stop the server.
|
||||
func Serve(l net.Listener, handler http.Handler) error {
|
||||
defaultServer = NewWithServer(&http.Server{Handler: handler})
|
||||
return defaultServer.Serve(l)
|
||||
}
|
||||
|
||||
// Shuts down the default server used by ListenAndServe, ListenAndServeTLS and
|
||||
// Serve. It returns true if it's the first time Close is called.
|
||||
func Close() bool {
|
||||
return defaultServer.Close()
|
||||
}
|
||||
29
Godeps/_workspace/src/github.com/braintree/manners/test_helpers/certs.go
сгенерированный
поставляемый
Обычный файл
29
Godeps/_workspace/src/github.com/braintree/manners/test_helpers/certs.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,29 @@
|
||||
package test_helpers
|
||||
|
||||
// A PEM-encoded TLS cert with SAN IPs "127.0.0.1" and "[::1]", expiring at the
|
||||
// last second of 2049 (the end of ASN.1 time).
|
||||
|
||||
// generated from src/pkg/crypto/tls:
|
||||
// go run generate_cert.go --rsa-bits 512 --host 127.0.0.1,::1,example.com --ca --start-date "Jan 1 00:00:00 1970" --duration=1000000h
|
||||
var (
|
||||
Cert = []byte(`-----BEGIN CERTIFICATE-----
|
||||
MIIBdzCCASOgAwIBAgIBADALBgkqhkiG9w0BAQUwEjEQMA4GA1UEChMHQWNtZSBD
|
||||
bzAeFw03MDAxMDEwMDAwMDBaFw00OTEyMzEyMzU5NTlaMBIxEDAOBgNVBAoTB0Fj
|
||||
bWUgQ28wWjALBgkqhkiG9w0BAQEDSwAwSAJBAN55NcYKZeInyTuhcCwFMhDHCmwa
|
||||
IUSdtXdcbItRB/yfXGBhiex00IaLXQnSU+QZPRZWYqeTEbFSgihqi1PUDy8CAwEA
|
||||
AaNoMGYwDgYDVR0PAQH/BAQDAgCkMBMGA1UdJQQMMAoGCCsGAQUFBwMBMA8GA1Ud
|
||||
EwEB/wQFMAMBAf8wLgYDVR0RBCcwJYILZXhhbXBsZS5jb22HBH8AAAGHEAAAAAAA
|
||||
AAAAAAAAAAAAAAEwCwYJKoZIhvcNAQEFA0EAAoQn/ytgqpiLcZu9XKbCJsJcvkgk
|
||||
Se6AbGXgSlq+ZCEVo0qIwSgeBqmsJxUu7NCSOwVJLYNEBO2DtIxoYVk+MA==
|
||||
-----END CERTIFICATE-----`)
|
||||
|
||||
Key = []byte(`-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIBPAIBAAJBAN55NcYKZeInyTuhcCwFMhDHCmwaIUSdtXdcbItRB/yfXGBhiex0
|
||||
0IaLXQnSU+QZPRZWYqeTEbFSgihqi1PUDy8CAwEAAQJBAQdUx66rfh8sYsgfdcvV
|
||||
NoafYpnEcB5s4m/vSVe6SU7dCK6eYec9f9wpT353ljhDUHq3EbmE4foNzJngh35d
|
||||
AekCIQDhRQG5Li0Wj8TM4obOnnXUXf1jRv0UkzE9AHWLG5q3AwIhAPzSjpYUDjVW
|
||||
MCUXgckTpKCuGwbJk7424Nb8bLzf3kllAiA5mUBgjfr/WtFSJdWcPQ4Zt9KTMNKD
|
||||
EUO0ukpTwEIl6wIhAMbGqZK3zAAFdq8DD2jPx+UJXnh0rnOkZBzDtJ6/iN69AiEA
|
||||
1Aq8MJgTaYsDQWyU/hDq5YkDJc9e9DSCvUIzqxQWMQE=
|
||||
-----END RSA PRIVATE KEY-----`)
|
||||
)
|
||||
13
Godeps/_workspace/src/github.com/braintree/manners/test_helpers/conn.go
сгенерированный
поставляемый
Обычный файл
13
Godeps/_workspace/src/github.com/braintree/manners/test_helpers/conn.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,13 @@
|
||||
package test_helpers
|
||||
|
||||
import "net"
|
||||
|
||||
type Conn struct {
|
||||
net.Conn
|
||||
CloseCalled bool
|
||||
}
|
||||
|
||||
func (c *Conn) Close() error {
|
||||
c.CloseCalled = true
|
||||
return nil
|
||||
}
|
||||
34
Godeps/_workspace/src/github.com/braintree/manners/test_helpers/listener.go
сгенерированный
поставляемый
Обычный файл
34
Godeps/_workspace/src/github.com/braintree/manners/test_helpers/listener.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,34 @@
|
||||
package test_helpers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
)
|
||||
|
||||
type Listener struct {
|
||||
AcceptRelease chan bool
|
||||
CloseCalled chan bool
|
||||
}
|
||||
|
||||
func NewListener() *Listener {
|
||||
return &Listener{
|
||||
make(chan bool, 1),
|
||||
make(chan bool, 1),
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Listener) Addr() net.Addr {
|
||||
addr, _ := net.ResolveTCPAddr("tcp", "127.0.0.1:8080")
|
||||
return addr
|
||||
}
|
||||
|
||||
func (l *Listener) Close() error {
|
||||
l.CloseCalled <- true
|
||||
l.AcceptRelease <- true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *Listener) Accept() (net.Conn, error) {
|
||||
<-l.AcceptRelease
|
||||
return nil, errors.New("connection closed")
|
||||
}
|
||||
27
Godeps/_workspace/src/github.com/braintree/manners/test_helpers/temp_file.go
сгенерированный
поставляемый
Обычный файл
27
Godeps/_workspace/src/github.com/braintree/manners/test_helpers/temp_file.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,27 @@
|
||||
package test_helpers
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
)
|
||||
|
||||
type TempFile struct {
|
||||
*os.File
|
||||
}
|
||||
|
||||
func NewTempFile(content []byte) (*TempFile, error) {
|
||||
f, err := ioutil.TempFile("", "graceful-test")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
f.Write(content)
|
||||
return &TempFile{f}, nil
|
||||
}
|
||||
|
||||
func (tf *TempFile) Unlink() {
|
||||
if tf.File != nil {
|
||||
os.Remove(tf.Name())
|
||||
tf.File = nil
|
||||
}
|
||||
}
|
||||
33
Godeps/_workspace/src/github.com/braintree/manners/test_helpers/wait_group.go
сгенерированный
поставляемый
Обычный файл
33
Godeps/_workspace/src/github.com/braintree/manners/test_helpers/wait_group.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,33 @@
|
||||
package test_helpers
|
||||
|
||||
import "sync"
|
||||
|
||||
type WaitGroup struct {
|
||||
sync.Mutex
|
||||
Count int
|
||||
WaitCalled chan int
|
||||
}
|
||||
|
||||
func NewWaitGroup() *WaitGroup {
|
||||
return &WaitGroup{
|
||||
WaitCalled: make(chan int, 1),
|
||||
}
|
||||
}
|
||||
|
||||
func (wg *WaitGroup) Add(delta int) {
|
||||
wg.Lock()
|
||||
wg.Count++
|
||||
wg.Unlock()
|
||||
}
|
||||
|
||||
func (wg *WaitGroup) Done() {
|
||||
wg.Lock()
|
||||
wg.Count--
|
||||
wg.Unlock()
|
||||
}
|
||||
|
||||
func (wg *WaitGroup) Wait() {
|
||||
wg.Lock()
|
||||
wg.WaitCalled <- wg.Count
|
||||
wg.Unlock()
|
||||
}
|
||||
54
Godeps/_workspace/src/github.com/braintree/manners/transition_test.go
сгенерированный
поставляемый
Обычный файл
54
Godeps/_workspace/src/github.com/braintree/manners/transition_test.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,54 @@
|
||||
package manners
|
||||
|
||||
import (
|
||||
helpers "github.com/mattermost/platform/Godeps/_workspace/src/github.com/braintree/manners/test_helpers"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestStateTransitions(t *testing.T) {
|
||||
tests := []transitionTest{
|
||||
transitionTest{[]http.ConnState{http.StateNew, http.StateActive}, 1},
|
||||
transitionTest{[]http.ConnState{http.StateNew, http.StateClosed}, 0},
|
||||
transitionTest{[]http.ConnState{http.StateNew, http.StateActive, http.StateClosed}, 0},
|
||||
transitionTest{[]http.ConnState{http.StateNew, http.StateActive, http.StateHijacked}, 0},
|
||||
transitionTest{[]http.ConnState{http.StateNew, http.StateActive, http.StateIdle}, 0},
|
||||
transitionTest{[]http.ConnState{http.StateNew, http.StateActive, http.StateIdle, http.StateActive}, 1},
|
||||
transitionTest{[]http.ConnState{http.StateNew, http.StateActive, http.StateIdle, http.StateActive, http.StateIdle}, 0},
|
||||
transitionTest{[]http.ConnState{http.StateNew, http.StateActive, http.StateIdle, http.StateActive, http.StateClosed}, 0},
|
||||
transitionTest{[]http.ConnState{http.StateNew, http.StateActive, http.StateIdle, http.StateActive, http.StateIdle, http.StateClosed}, 0},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
testStateTransition(t, test)
|
||||
}
|
||||
}
|
||||
|
||||
type transitionTest struct {
|
||||
states []http.ConnState
|
||||
expectedWgCount int
|
||||
}
|
||||
|
||||
func testStateTransition(t *testing.T, test transitionTest) {
|
||||
server := newServer()
|
||||
wg := helpers.NewWaitGroup()
|
||||
server.wg = wg
|
||||
startServer(t, server, nil)
|
||||
|
||||
conn := &helpers.Conn{}
|
||||
for _, newState := range test.states {
|
||||
server.ConnState(conn, newState)
|
||||
}
|
||||
|
||||
server.Close()
|
||||
waiting := <-wg.WaitCalled
|
||||
if waiting != test.expectedWgCount {
|
||||
names := make([]string, len(test.states))
|
||||
for i, s := range test.states {
|
||||
names[i] = s.String()
|
||||
}
|
||||
transitions := strings.Join(names, " -> ")
|
||||
t.Errorf("%s - Waitcount should be %d, got %d", transitions, test.expectedWgCount, waiting)
|
||||
}
|
||||
}
|
||||
151
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/bypass.go
сгенерированный
поставляемый
Обычный файл
151
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/bypass.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,151 @@
|
||||
// Copyright (c) 2015 Dave Collins <dave@davec.name>
|
||||
//
|
||||
// Permission to use, copy, modify, and distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
// NOTE: Due to the following build constraints, this file will only be compiled
|
||||
// when the code is not running on Google App Engine and "-tags disableunsafe"
|
||||
// is not added to the go build command line.
|
||||
// +build !appengine,!disableunsafe
|
||||
|
||||
package spew
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
// UnsafeDisabled is a build-time constant which specifies whether or
|
||||
// not access to the unsafe package is available.
|
||||
UnsafeDisabled = false
|
||||
|
||||
// ptrSize is the size of a pointer on the current arch.
|
||||
ptrSize = unsafe.Sizeof((*byte)(nil))
|
||||
)
|
||||
|
||||
var (
|
||||
// offsetPtr, offsetScalar, and offsetFlag are the offsets for the
|
||||
// internal reflect.Value fields. These values are valid before golang
|
||||
// commit ecccf07e7f9d which changed the format. The are also valid
|
||||
// after commit 82f48826c6c7 which changed the format again to mirror
|
||||
// the original format. Code in the init function updates these offsets
|
||||
// as necessary.
|
||||
offsetPtr = uintptr(ptrSize)
|
||||
offsetScalar = uintptr(0)
|
||||
offsetFlag = uintptr(ptrSize * 2)
|
||||
|
||||
// flagKindWidth and flagKindShift indicate various bits that the
|
||||
// reflect package uses internally to track kind information.
|
||||
//
|
||||
// flagRO indicates whether or not the value field of a reflect.Value is
|
||||
// read-only.
|
||||
//
|
||||
// flagIndir indicates whether the value field of a reflect.Value is
|
||||
// the actual data or a pointer to the data.
|
||||
//
|
||||
// These values are valid before golang commit 90a7c3c86944 which
|
||||
// changed their positions. Code in the init function updates these
|
||||
// flags as necessary.
|
||||
flagKindWidth = uintptr(5)
|
||||
flagKindShift = uintptr(flagKindWidth - 1)
|
||||
flagRO = uintptr(1 << 0)
|
||||
flagIndir = uintptr(1 << 1)
|
||||
)
|
||||
|
||||
func init() {
|
||||
// Older versions of reflect.Value stored small integers directly in the
|
||||
// ptr field (which is named val in the older versions). Versions
|
||||
// between commits ecccf07e7f9d and 82f48826c6c7 added a new field named
|
||||
// scalar for this purpose which unfortunately came before the flag
|
||||
// field, so the offset of the flag field is different for those
|
||||
// versions.
|
||||
//
|
||||
// This code constructs a new reflect.Value from a known small integer
|
||||
// and checks if the size of the reflect.Value struct indicates it has
|
||||
// the scalar field. When it does, the offsets are updated accordingly.
|
||||
vv := reflect.ValueOf(0xf00)
|
||||
if unsafe.Sizeof(vv) == (ptrSize * 4) {
|
||||
offsetScalar = ptrSize * 2
|
||||
offsetFlag = ptrSize * 3
|
||||
}
|
||||
|
||||
// Commit 90a7c3c86944 changed the flag positions such that the low
|
||||
// order bits are the kind. This code extracts the kind from the flags
|
||||
// field and ensures it's the correct type. When it's not, the flag
|
||||
// order has been changed to the newer format, so the flags are updated
|
||||
// accordingly.
|
||||
upf := unsafe.Pointer(uintptr(unsafe.Pointer(&vv)) + offsetFlag)
|
||||
upfv := *(*uintptr)(upf)
|
||||
flagKindMask := uintptr((1<<flagKindWidth - 1) << flagKindShift)
|
||||
if (upfv&flagKindMask)>>flagKindShift != uintptr(reflect.Int) {
|
||||
flagKindShift = 0
|
||||
flagRO = 1 << 5
|
||||
flagIndir = 1 << 6
|
||||
|
||||
// Commit adf9b30e5594 modified the flags to separate the
|
||||
// flagRO flag into two bits which specifies whether or not the
|
||||
// field is embedded. This causes flagIndir to move over a bit
|
||||
// and means that flagRO is the combination of either of the
|
||||
// original flagRO bit and the new bit.
|
||||
//
|
||||
// This code detects the change by extracting what used to be
|
||||
// the indirect bit to ensure it's set. When it's not, the flag
|
||||
// order has been changed to the newer format, so the flags are
|
||||
// updated accordingly.
|
||||
if upfv&flagIndir == 0 {
|
||||
flagRO = 3 << 5
|
||||
flagIndir = 1 << 7
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// unsafeReflectValue converts the passed reflect.Value into a one that bypasses
|
||||
// the typical safety restrictions preventing access to unaddressable and
|
||||
// unexported data. It works by digging the raw pointer to the underlying
|
||||
// value out of the protected value and generating a new unprotected (unsafe)
|
||||
// reflect.Value to it.
|
||||
//
|
||||
// This allows us to check for implementations of the Stringer and error
|
||||
// interfaces to be used for pretty printing ordinarily unaddressable and
|
||||
// inaccessible values such as unexported struct fields.
|
||||
func unsafeReflectValue(v reflect.Value) (rv reflect.Value) {
|
||||
indirects := 1
|
||||
vt := v.Type()
|
||||
upv := unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetPtr)
|
||||
rvf := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetFlag))
|
||||
if rvf&flagIndir != 0 {
|
||||
vt = reflect.PtrTo(v.Type())
|
||||
indirects++
|
||||
} else if offsetScalar != 0 {
|
||||
// The value is in the scalar field when it's not one of the
|
||||
// reference types.
|
||||
switch vt.Kind() {
|
||||
case reflect.Uintptr:
|
||||
case reflect.Chan:
|
||||
case reflect.Func:
|
||||
case reflect.Map:
|
||||
case reflect.Ptr:
|
||||
case reflect.UnsafePointer:
|
||||
default:
|
||||
upv = unsafe.Pointer(uintptr(unsafe.Pointer(&v)) +
|
||||
offsetScalar)
|
||||
}
|
||||
}
|
||||
|
||||
pv := reflect.NewAt(vt, upv)
|
||||
rv = pv
|
||||
for i := 0; i < indirects; i++ {
|
||||
rv = rv.Elem()
|
||||
}
|
||||
return rv
|
||||
}
|
||||
37
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/bypasssafe.go
сгенерированный
поставляемый
Обычный файл
37
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/bypasssafe.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,37 @@
|
||||
// Copyright (c) 2015 Dave Collins <dave@davec.name>
|
||||
//
|
||||
// Permission to use, copy, modify, and distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
// NOTE: Due to the following build constraints, this file will only be compiled
|
||||
// when either the code is running on Google App Engine or "-tags disableunsafe"
|
||||
// is added to the go build command line.
|
||||
// +build appengine disableunsafe
|
||||
|
||||
package spew
|
||||
|
||||
import "reflect"
|
||||
|
||||
const (
|
||||
// UnsafeDisabled is a build-time constant which specifies whether or
|
||||
// not access to the unsafe package is available.
|
||||
UnsafeDisabled = true
|
||||
)
|
||||
|
||||
// unsafeReflectValue typically converts the passed reflect.Value into a one
|
||||
// that bypasses the typical safety restrictions preventing access to
|
||||
// unaddressable and unexported data. However, doing this relies on access to
|
||||
// the unsafe package. This is a stub version which simply returns the passed
|
||||
// reflect.Value when the unsafe package is not available.
|
||||
func unsafeReflectValue(v reflect.Value) reflect.Value {
|
||||
return v
|
||||
}
|
||||
341
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/common.go
сгенерированный
поставляемый
Обычный файл
341
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/common.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,341 @@
|
||||
/*
|
||||
* Copyright (c) 2013 Dave Collins <dave@davec.name>
|
||||
*
|
||||
* Permission to use, copy, modify, and distribute this software for any
|
||||
* purpose with or without fee is hereby granted, provided that the above
|
||||
* copyright notice and this permission notice appear in all copies.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
package spew
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// Some constants in the form of bytes to avoid string overhead. This mirrors
|
||||
// the technique used in the fmt package.
|
||||
var (
|
||||
panicBytes = []byte("(PANIC=")
|
||||
plusBytes = []byte("+")
|
||||
iBytes = []byte("i")
|
||||
trueBytes = []byte("true")
|
||||
falseBytes = []byte("false")
|
||||
interfaceBytes = []byte("(interface {})")
|
||||
commaNewlineBytes = []byte(",\n")
|
||||
newlineBytes = []byte("\n")
|
||||
openBraceBytes = []byte("{")
|
||||
openBraceNewlineBytes = []byte("{\n")
|
||||
closeBraceBytes = []byte("}")
|
||||
asteriskBytes = []byte("*")
|
||||
colonBytes = []byte(":")
|
||||
colonSpaceBytes = []byte(": ")
|
||||
openParenBytes = []byte("(")
|
||||
closeParenBytes = []byte(")")
|
||||
spaceBytes = []byte(" ")
|
||||
pointerChainBytes = []byte("->")
|
||||
nilAngleBytes = []byte("<nil>")
|
||||
maxNewlineBytes = []byte("<max depth reached>\n")
|
||||
maxShortBytes = []byte("<max>")
|
||||
circularBytes = []byte("<already shown>")
|
||||
circularShortBytes = []byte("<shown>")
|
||||
invalidAngleBytes = []byte("<invalid>")
|
||||
openBracketBytes = []byte("[")
|
||||
closeBracketBytes = []byte("]")
|
||||
percentBytes = []byte("%")
|
||||
precisionBytes = []byte(".")
|
||||
openAngleBytes = []byte("<")
|
||||
closeAngleBytes = []byte(">")
|
||||
openMapBytes = []byte("map[")
|
||||
closeMapBytes = []byte("]")
|
||||
lenEqualsBytes = []byte("len=")
|
||||
capEqualsBytes = []byte("cap=")
|
||||
)
|
||||
|
||||
// hexDigits is used to map a decimal value to a hex digit.
|
||||
var hexDigits = "0123456789abcdef"
|
||||
|
||||
// catchPanic handles any panics that might occur during the handleMethods
|
||||
// calls.
|
||||
func catchPanic(w io.Writer, v reflect.Value) {
|
||||
if err := recover(); err != nil {
|
||||
w.Write(panicBytes)
|
||||
fmt.Fprintf(w, "%v", err)
|
||||
w.Write(closeParenBytes)
|
||||
}
|
||||
}
|
||||
|
||||
// handleMethods attempts to call the Error and String methods on the underlying
|
||||
// type the passed reflect.Value represents and outputes the result to Writer w.
|
||||
//
|
||||
// It handles panics in any called methods by catching and displaying the error
|
||||
// as the formatted value.
|
||||
func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) {
|
||||
// We need an interface to check if the type implements the error or
|
||||
// Stringer interface. However, the reflect package won't give us an
|
||||
// interface on certain things like unexported struct fields in order
|
||||
// to enforce visibility rules. We use unsafe, when it's available,
|
||||
// to bypass these restrictions since this package does not mutate the
|
||||
// values.
|
||||
if !v.CanInterface() {
|
||||
if UnsafeDisabled {
|
||||
return false
|
||||
}
|
||||
|
||||
v = unsafeReflectValue(v)
|
||||
}
|
||||
|
||||
// Choose whether or not to do error and Stringer interface lookups against
|
||||
// the base type or a pointer to the base type depending on settings.
|
||||
// Technically calling one of these methods with a pointer receiver can
|
||||
// mutate the value, however, types which choose to satisify an error or
|
||||
// Stringer interface with a pointer receiver should not be mutating their
|
||||
// state inside these interface methods.
|
||||
if !cs.DisablePointerMethods && !UnsafeDisabled && !v.CanAddr() {
|
||||
v = unsafeReflectValue(v)
|
||||
}
|
||||
if v.CanAddr() {
|
||||
v = v.Addr()
|
||||
}
|
||||
|
||||
// Is it an error or Stringer?
|
||||
switch iface := v.Interface().(type) {
|
||||
case error:
|
||||
defer catchPanic(w, v)
|
||||
if cs.ContinueOnMethod {
|
||||
w.Write(openParenBytes)
|
||||
w.Write([]byte(iface.Error()))
|
||||
w.Write(closeParenBytes)
|
||||
w.Write(spaceBytes)
|
||||
return false
|
||||
}
|
||||
|
||||
w.Write([]byte(iface.Error()))
|
||||
return true
|
||||
|
||||
case fmt.Stringer:
|
||||
defer catchPanic(w, v)
|
||||
if cs.ContinueOnMethod {
|
||||
w.Write(openParenBytes)
|
||||
w.Write([]byte(iface.String()))
|
||||
w.Write(closeParenBytes)
|
||||
w.Write(spaceBytes)
|
||||
return false
|
||||
}
|
||||
w.Write([]byte(iface.String()))
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// printBool outputs a boolean value as true or false to Writer w.
|
||||
func printBool(w io.Writer, val bool) {
|
||||
if val {
|
||||
w.Write(trueBytes)
|
||||
} else {
|
||||
w.Write(falseBytes)
|
||||
}
|
||||
}
|
||||
|
||||
// printInt outputs a signed integer value to Writer w.
|
||||
func printInt(w io.Writer, val int64, base int) {
|
||||
w.Write([]byte(strconv.FormatInt(val, base)))
|
||||
}
|
||||
|
||||
// printUint outputs an unsigned integer value to Writer w.
|
||||
func printUint(w io.Writer, val uint64, base int) {
|
||||
w.Write([]byte(strconv.FormatUint(val, base)))
|
||||
}
|
||||
|
||||
// printFloat outputs a floating point value using the specified precision,
|
||||
// which is expected to be 32 or 64bit, to Writer w.
|
||||
func printFloat(w io.Writer, val float64, precision int) {
|
||||
w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision)))
|
||||
}
|
||||
|
||||
// printComplex outputs a complex value using the specified float precision
|
||||
// for the real and imaginary parts to Writer w.
|
||||
func printComplex(w io.Writer, c complex128, floatPrecision int) {
|
||||
r := real(c)
|
||||
w.Write(openParenBytes)
|
||||
w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision)))
|
||||
i := imag(c)
|
||||
if i >= 0 {
|
||||
w.Write(plusBytes)
|
||||
}
|
||||
w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision)))
|
||||
w.Write(iBytes)
|
||||
w.Write(closeParenBytes)
|
||||
}
|
||||
|
||||
// printHexPtr outputs a uintptr formatted as hexidecimal with a leading '0x'
|
||||
// prefix to Writer w.
|
||||
func printHexPtr(w io.Writer, p uintptr) {
|
||||
// Null pointer.
|
||||
num := uint64(p)
|
||||
if num == 0 {
|
||||
w.Write(nilAngleBytes)
|
||||
return
|
||||
}
|
||||
|
||||
// Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix
|
||||
buf := make([]byte, 18)
|
||||
|
||||
// It's simpler to construct the hex string right to left.
|
||||
base := uint64(16)
|
||||
i := len(buf) - 1
|
||||
for num >= base {
|
||||
buf[i] = hexDigits[num%base]
|
||||
num /= base
|
||||
i--
|
||||
}
|
||||
buf[i] = hexDigits[num]
|
||||
|
||||
// Add '0x' prefix.
|
||||
i--
|
||||
buf[i] = 'x'
|
||||
i--
|
||||
buf[i] = '0'
|
||||
|
||||
// Strip unused leading bytes.
|
||||
buf = buf[i:]
|
||||
w.Write(buf)
|
||||
}
|
||||
|
||||
// valuesSorter implements sort.Interface to allow a slice of reflect.Value
|
||||
// elements to be sorted.
|
||||
type valuesSorter struct {
|
||||
values []reflect.Value
|
||||
strings []string // either nil or same len and values
|
||||
cs *ConfigState
|
||||
}
|
||||
|
||||
// newValuesSorter initializes a valuesSorter instance, which holds a set of
|
||||
// surrogate keys on which the data should be sorted. It uses flags in
|
||||
// ConfigState to decide if and how to populate those surrogate keys.
|
||||
func newValuesSorter(values []reflect.Value, cs *ConfigState) sort.Interface {
|
||||
vs := &valuesSorter{values: values, cs: cs}
|
||||
if canSortSimply(vs.values[0].Kind()) {
|
||||
return vs
|
||||
}
|
||||
if !cs.DisableMethods {
|
||||
vs.strings = make([]string, len(values))
|
||||
for i := range vs.values {
|
||||
b := bytes.Buffer{}
|
||||
if !handleMethods(cs, &b, vs.values[i]) {
|
||||
vs.strings = nil
|
||||
break
|
||||
}
|
||||
vs.strings[i] = b.String()
|
||||
}
|
||||
}
|
||||
if vs.strings == nil && cs.SpewKeys {
|
||||
vs.strings = make([]string, len(values))
|
||||
for i := range vs.values {
|
||||
vs.strings[i] = Sprintf("%#v", vs.values[i].Interface())
|
||||
}
|
||||
}
|
||||
return vs
|
||||
}
|
||||
|
||||
// canSortSimply tests whether a reflect.Kind is a primitive that can be sorted
|
||||
// directly, or whether it should be considered for sorting by surrogate keys
|
||||
// (if the ConfigState allows it).
|
||||
func canSortSimply(kind reflect.Kind) bool {
|
||||
// This switch parallels valueSortLess, except for the default case.
|
||||
switch kind {
|
||||
case reflect.Bool:
|
||||
return true
|
||||
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
|
||||
return true
|
||||
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
|
||||
return true
|
||||
case reflect.Float32, reflect.Float64:
|
||||
return true
|
||||
case reflect.String:
|
||||
return true
|
||||
case reflect.Uintptr:
|
||||
return true
|
||||
case reflect.Array:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Len returns the number of values in the slice. It is part of the
|
||||
// sort.Interface implementation.
|
||||
func (s *valuesSorter) Len() int {
|
||||
return len(s.values)
|
||||
}
|
||||
|
||||
// Swap swaps the values at the passed indices. It is part of the
|
||||
// sort.Interface implementation.
|
||||
func (s *valuesSorter) Swap(i, j int) {
|
||||
s.values[i], s.values[j] = s.values[j], s.values[i]
|
||||
if s.strings != nil {
|
||||
s.strings[i], s.strings[j] = s.strings[j], s.strings[i]
|
||||
}
|
||||
}
|
||||
|
||||
// valueSortLess returns whether the first value should sort before the second
|
||||
// value. It is used by valueSorter.Less as part of the sort.Interface
|
||||
// implementation.
|
||||
func valueSortLess(a, b reflect.Value) bool {
|
||||
switch a.Kind() {
|
||||
case reflect.Bool:
|
||||
return !a.Bool() && b.Bool()
|
||||
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
|
||||
return a.Int() < b.Int()
|
||||
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
|
||||
return a.Uint() < b.Uint()
|
||||
case reflect.Float32, reflect.Float64:
|
||||
return a.Float() < b.Float()
|
||||
case reflect.String:
|
||||
return a.String() < b.String()
|
||||
case reflect.Uintptr:
|
||||
return a.Uint() < b.Uint()
|
||||
case reflect.Array:
|
||||
// Compare the contents of both arrays.
|
||||
l := a.Len()
|
||||
for i := 0; i < l; i++ {
|
||||
av := a.Index(i)
|
||||
bv := b.Index(i)
|
||||
if av.Interface() == bv.Interface() {
|
||||
continue
|
||||
}
|
||||
return valueSortLess(av, bv)
|
||||
}
|
||||
}
|
||||
return a.String() < b.String()
|
||||
}
|
||||
|
||||
// Less returns whether the value at index i should sort before the
|
||||
// value at index j. It is part of the sort.Interface implementation.
|
||||
func (s *valuesSorter) Less(i, j int) bool {
|
||||
if s.strings == nil {
|
||||
return valueSortLess(s.values[i], s.values[j])
|
||||
}
|
||||
return s.strings[i] < s.strings[j]
|
||||
}
|
||||
|
||||
// sortValues is a sort function that handles both native types and any type that
|
||||
// can be converted to error or Stringer. Other inputs are sorted according to
|
||||
// their Value.String() value to ensure display stability.
|
||||
func sortValues(values []reflect.Value, cs *ConfigState) {
|
||||
if len(values) == 0 {
|
||||
return
|
||||
}
|
||||
sort.Sort(newValuesSorter(values, cs))
|
||||
}
|
||||
298
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/common_test.go
сгенерированный
поставляемый
Обычный файл
298
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/common_test.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,298 @@
|
||||
/*
|
||||
* Copyright (c) 2013 Dave Collins <dave@davec.name>
|
||||
*
|
||||
* Permission to use, copy, modify, and distribute this software for any
|
||||
* purpose with or without fee is hereby granted, provided that the above
|
||||
* copyright notice and this permission notice appear in all copies.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
package spew_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/mattermost/platform/Godeps/_workspace/src/github.com/davecgh/go-spew/spew"
|
||||
)
|
||||
|
||||
// custom type to test Stinger interface on non-pointer receiver.
|
||||
type stringer string
|
||||
|
||||
// String implements the Stringer interface for testing invocation of custom
|
||||
// stringers on types with non-pointer receivers.
|
||||
func (s stringer) String() string {
|
||||
return "stringer " + string(s)
|
||||
}
|
||||
|
||||
// custom type to test Stinger interface on pointer receiver.
|
||||
type pstringer string
|
||||
|
||||
// String implements the Stringer interface for testing invocation of custom
|
||||
// stringers on types with only pointer receivers.
|
||||
func (s *pstringer) String() string {
|
||||
return "stringer " + string(*s)
|
||||
}
|
||||
|
||||
// xref1 and xref2 are cross referencing structs for testing circular reference
|
||||
// detection.
|
||||
type xref1 struct {
|
||||
ps2 *xref2
|
||||
}
|
||||
type xref2 struct {
|
||||
ps1 *xref1
|
||||
}
|
||||
|
||||
// indirCir1, indirCir2, and indirCir3 are used to generate an indirect circular
|
||||
// reference for testing detection.
|
||||
type indirCir1 struct {
|
||||
ps2 *indirCir2
|
||||
}
|
||||
type indirCir2 struct {
|
||||
ps3 *indirCir3
|
||||
}
|
||||
type indirCir3 struct {
|
||||
ps1 *indirCir1
|
||||
}
|
||||
|
||||
// embed is used to test embedded structures.
|
||||
type embed struct {
|
||||
a string
|
||||
}
|
||||
|
||||
// embedwrap is used to test embedded structures.
|
||||
type embedwrap struct {
|
||||
*embed
|
||||
e *embed
|
||||
}
|
||||
|
||||
// panicer is used to intentionally cause a panic for testing spew properly
|
||||
// handles them
|
||||
type panicer int
|
||||
|
||||
func (p panicer) String() string {
|
||||
panic("test panic")
|
||||
}
|
||||
|
||||
// customError is used to test custom error interface invocation.
|
||||
type customError int
|
||||
|
||||
func (e customError) Error() string {
|
||||
return fmt.Sprintf("error: %d", int(e))
|
||||
}
|
||||
|
||||
// stringizeWants converts a slice of wanted test output into a format suitable
|
||||
// for a test error message.
|
||||
func stringizeWants(wants []string) string {
|
||||
s := ""
|
||||
for i, want := range wants {
|
||||
if i > 0 {
|
||||
s += fmt.Sprintf("want%d: %s", i+1, want)
|
||||
} else {
|
||||
s += "want: " + want
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// testFailed returns whether or not a test failed by checking if the result
|
||||
// of the test is in the slice of wanted strings.
|
||||
func testFailed(result string, wants []string) bool {
|
||||
for _, want := range wants {
|
||||
if result == want {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type sortableStruct struct {
|
||||
x int
|
||||
}
|
||||
|
||||
func (ss sortableStruct) String() string {
|
||||
return fmt.Sprintf("ss.%d", ss.x)
|
||||
}
|
||||
|
||||
type unsortableStruct struct {
|
||||
x int
|
||||
}
|
||||
|
||||
type sortTestCase struct {
|
||||
input []reflect.Value
|
||||
expected []reflect.Value
|
||||
}
|
||||
|
||||
func helpTestSortValues(tests []sortTestCase, cs *spew.ConfigState, t *testing.T) {
|
||||
getInterfaces := func(values []reflect.Value) []interface{} {
|
||||
interfaces := []interface{}{}
|
||||
for _, v := range values {
|
||||
interfaces = append(interfaces, v.Interface())
|
||||
}
|
||||
return interfaces
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
spew.SortValues(test.input, cs)
|
||||
// reflect.DeepEqual cannot really make sense of reflect.Value,
|
||||
// probably because of all the pointer tricks. For instance,
|
||||
// v(2.0) != v(2.0) on a 32-bits system. Turn them into interface{}
|
||||
// instead.
|
||||
input := getInterfaces(test.input)
|
||||
expected := getInterfaces(test.expected)
|
||||
if !reflect.DeepEqual(input, expected) {
|
||||
t.Errorf("Sort mismatch:\n %v != %v", input, expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestSortValues ensures the sort functionality for relect.Value based sorting
|
||||
// works as intended.
|
||||
func TestSortValues(t *testing.T) {
|
||||
v := reflect.ValueOf
|
||||
|
||||
a := v("a")
|
||||
b := v("b")
|
||||
c := v("c")
|
||||
embedA := v(embed{"a"})
|
||||
embedB := v(embed{"b"})
|
||||
embedC := v(embed{"c"})
|
||||
tests := []sortTestCase{
|
||||
// No values.
|
||||
{
|
||||
[]reflect.Value{},
|
||||
[]reflect.Value{},
|
||||
},
|
||||
// Bools.
|
||||
{
|
||||
[]reflect.Value{v(false), v(true), v(false)},
|
||||
[]reflect.Value{v(false), v(false), v(true)},
|
||||
},
|
||||
// Ints.
|
||||
{
|
||||
[]reflect.Value{v(2), v(1), v(3)},
|
||||
[]reflect.Value{v(1), v(2), v(3)},
|
||||
},
|
||||
// Uints.
|
||||
{
|
||||
[]reflect.Value{v(uint8(2)), v(uint8(1)), v(uint8(3))},
|
||||
[]reflect.Value{v(uint8(1)), v(uint8(2)), v(uint8(3))},
|
||||
},
|
||||
// Floats.
|
||||
{
|
||||
[]reflect.Value{v(2.0), v(1.0), v(3.0)},
|
||||
[]reflect.Value{v(1.0), v(2.0), v(3.0)},
|
||||
},
|
||||
// Strings.
|
||||
{
|
||||
[]reflect.Value{b, a, c},
|
||||
[]reflect.Value{a, b, c},
|
||||
},
|
||||
// Array
|
||||
{
|
||||
[]reflect.Value{v([3]int{3, 2, 1}), v([3]int{1, 3, 2}), v([3]int{1, 2, 3})},
|
||||
[]reflect.Value{v([3]int{1, 2, 3}), v([3]int{1, 3, 2}), v([3]int{3, 2, 1})},
|
||||
},
|
||||
// Uintptrs.
|
||||
{
|
||||
[]reflect.Value{v(uintptr(2)), v(uintptr(1)), v(uintptr(3))},
|
||||
[]reflect.Value{v(uintptr(1)), v(uintptr(2)), v(uintptr(3))},
|
||||
},
|
||||
// SortableStructs.
|
||||
{
|
||||
// Note: not sorted - DisableMethods is set.
|
||||
[]reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})},
|
||||
[]reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})},
|
||||
},
|
||||
// UnsortableStructs.
|
||||
{
|
||||
// Note: not sorted - SpewKeys is false.
|
||||
[]reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})},
|
||||
[]reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})},
|
||||
},
|
||||
// Invalid.
|
||||
{
|
||||
[]reflect.Value{embedB, embedA, embedC},
|
||||
[]reflect.Value{embedB, embedA, embedC},
|
||||
},
|
||||
}
|
||||
cs := spew.ConfigState{DisableMethods: true, SpewKeys: false}
|
||||
helpTestSortValues(tests, &cs, t)
|
||||
}
|
||||
|
||||
// TestSortValuesWithMethods ensures the sort functionality for relect.Value
|
||||
// based sorting works as intended when using string methods.
|
||||
func TestSortValuesWithMethods(t *testing.T) {
|
||||
v := reflect.ValueOf
|
||||
|
||||
a := v("a")
|
||||
b := v("b")
|
||||
c := v("c")
|
||||
tests := []sortTestCase{
|
||||
// Ints.
|
||||
{
|
||||
[]reflect.Value{v(2), v(1), v(3)},
|
||||
[]reflect.Value{v(1), v(2), v(3)},
|
||||
},
|
||||
// Strings.
|
||||
{
|
||||
[]reflect.Value{b, a, c},
|
||||
[]reflect.Value{a, b, c},
|
||||
},
|
||||
// SortableStructs.
|
||||
{
|
||||
[]reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})},
|
||||
[]reflect.Value{v(sortableStruct{1}), v(sortableStruct{2}), v(sortableStruct{3})},
|
||||
},
|
||||
// UnsortableStructs.
|
||||
{
|
||||
// Note: not sorted - SpewKeys is false.
|
||||
[]reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})},
|
||||
[]reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})},
|
||||
},
|
||||
}
|
||||
cs := spew.ConfigState{DisableMethods: false, SpewKeys: false}
|
||||
helpTestSortValues(tests, &cs, t)
|
||||
}
|
||||
|
||||
// TestSortValuesWithSpew ensures the sort functionality for relect.Value
|
||||
// based sorting works as intended when using spew to stringify keys.
|
||||
func TestSortValuesWithSpew(t *testing.T) {
|
||||
v := reflect.ValueOf
|
||||
|
||||
a := v("a")
|
||||
b := v("b")
|
||||
c := v("c")
|
||||
tests := []sortTestCase{
|
||||
// Ints.
|
||||
{
|
||||
[]reflect.Value{v(2), v(1), v(3)},
|
||||
[]reflect.Value{v(1), v(2), v(3)},
|
||||
},
|
||||
// Strings.
|
||||
{
|
||||
[]reflect.Value{b, a, c},
|
||||
[]reflect.Value{a, b, c},
|
||||
},
|
||||
// SortableStructs.
|
||||
{
|
||||
[]reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})},
|
||||
[]reflect.Value{v(sortableStruct{1}), v(sortableStruct{2}), v(sortableStruct{3})},
|
||||
},
|
||||
// UnsortableStructs.
|
||||
{
|
||||
[]reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})},
|
||||
[]reflect.Value{v(unsortableStruct{1}), v(unsortableStruct{2}), v(unsortableStruct{3})},
|
||||
},
|
||||
}
|
||||
cs := spew.ConfigState{DisableMethods: true, SpewKeys: true}
|
||||
helpTestSortValues(tests, &cs, t)
|
||||
}
|
||||
297
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/config.go
сгенерированный
поставляемый
Обычный файл
297
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/config.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,297 @@
|
||||
/*
|
||||
* Copyright (c) 2013 Dave Collins <dave@davec.name>
|
||||
*
|
||||
* Permission to use, copy, modify, and distribute this software for any
|
||||
* purpose with or without fee is hereby granted, provided that the above
|
||||
* copyright notice and this permission notice appear in all copies.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
package spew
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
// ConfigState houses the configuration options used by spew to format and
|
||||
// display values. There is a global instance, Config, that is used to control
|
||||
// all top-level Formatter and Dump functionality. Each ConfigState instance
|
||||
// provides methods equivalent to the top-level functions.
|
||||
//
|
||||
// The zero value for ConfigState provides no indentation. You would typically
|
||||
// want to set it to a space or a tab.
|
||||
//
|
||||
// Alternatively, you can use NewDefaultConfig to get a ConfigState instance
|
||||
// with default settings. See the documentation of NewDefaultConfig for default
|
||||
// values.
|
||||
type ConfigState struct {
|
||||
// Indent specifies the string to use for each indentation level. The
|
||||
// global config instance that all top-level functions use set this to a
|
||||
// single space by default. If you would like more indentation, you might
|
||||
// set this to a tab with "\t" or perhaps two spaces with " ".
|
||||
Indent string
|
||||
|
||||
// MaxDepth controls the maximum number of levels to descend into nested
|
||||
// data structures. The default, 0, means there is no limit.
|
||||
//
|
||||
// NOTE: Circular data structures are properly detected, so it is not
|
||||
// necessary to set this value unless you specifically want to limit deeply
|
||||
// nested data structures.
|
||||
MaxDepth int
|
||||
|
||||
// DisableMethods specifies whether or not error and Stringer interfaces are
|
||||
// invoked for types that implement them.
|
||||
DisableMethods bool
|
||||
|
||||
// DisablePointerMethods specifies whether or not to check for and invoke
|
||||
// error and Stringer interfaces on types which only accept a pointer
|
||||
// receiver when the current type is not a pointer.
|
||||
//
|
||||
// NOTE: This might be an unsafe action since calling one of these methods
|
||||
// with a pointer receiver could technically mutate the value, however,
|
||||
// in practice, types which choose to satisify an error or Stringer
|
||||
// interface with a pointer receiver should not be mutating their state
|
||||
// inside these interface methods. As a result, this option relies on
|
||||
// access to the unsafe package, so it will not have any effect when
|
||||
// running in environments without access to the unsafe package such as
|
||||
// Google App Engine or with the "disableunsafe" build tag specified.
|
||||
DisablePointerMethods bool
|
||||
|
||||
// ContinueOnMethod specifies whether or not recursion should continue once
|
||||
// a custom error or Stringer interface is invoked. The default, false,
|
||||
// means it will print the results of invoking the custom error or Stringer
|
||||
// interface and return immediately instead of continuing to recurse into
|
||||
// the internals of the data type.
|
||||
//
|
||||
// NOTE: This flag does not have any effect if method invocation is disabled
|
||||
// via the DisableMethods or DisablePointerMethods options.
|
||||
ContinueOnMethod bool
|
||||
|
||||
// SortKeys specifies map keys should be sorted before being printed. Use
|
||||
// this to have a more deterministic, diffable output. Note that only
|
||||
// native types (bool, int, uint, floats, uintptr and string) and types
|
||||
// that support the error or Stringer interfaces (if methods are
|
||||
// enabled) are supported, with other types sorted according to the
|
||||
// reflect.Value.String() output which guarantees display stability.
|
||||
SortKeys bool
|
||||
|
||||
// SpewKeys specifies that, as a last resort attempt, map keys should
|
||||
// be spewed to strings and sorted by those strings. This is only
|
||||
// considered if SortKeys is true.
|
||||
SpewKeys bool
|
||||
}
|
||||
|
||||
// Config is the active configuration of the top-level functions.
|
||||
// The configuration can be changed by modifying the contents of spew.Config.
|
||||
var Config = ConfigState{Indent: " "}
|
||||
|
||||
// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were
|
||||
// passed with a Formatter interface returned by c.NewFormatter. It returns
|
||||
// the formatted string as a value that satisfies error. See NewFormatter
|
||||
// for formatting details.
|
||||
//
|
||||
// This function is shorthand for the following syntax:
|
||||
//
|
||||
// fmt.Errorf(format, c.NewFormatter(a), c.NewFormatter(b))
|
||||
func (c *ConfigState) Errorf(format string, a ...interface{}) (err error) {
|
||||
return fmt.Errorf(format, c.convertArgs(a)...)
|
||||
}
|
||||
|
||||
// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were
|
||||
// passed with a Formatter interface returned by c.NewFormatter. It returns
|
||||
// the number of bytes written and any write error encountered. See
|
||||
// NewFormatter for formatting details.
|
||||
//
|
||||
// This function is shorthand for the following syntax:
|
||||
//
|
||||
// fmt.Fprint(w, c.NewFormatter(a), c.NewFormatter(b))
|
||||
func (c *ConfigState) Fprint(w io.Writer, a ...interface{}) (n int, err error) {
|
||||
return fmt.Fprint(w, c.convertArgs(a)...)
|
||||
}
|
||||
|
||||
// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were
|
||||
// passed with a Formatter interface returned by c.NewFormatter. It returns
|
||||
// the number of bytes written and any write error encountered. See
|
||||
// NewFormatter for formatting details.
|
||||
//
|
||||
// This function is shorthand for the following syntax:
|
||||
//
|
||||
// fmt.Fprintf(w, format, c.NewFormatter(a), c.NewFormatter(b))
|
||||
func (c *ConfigState) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
|
||||
return fmt.Fprintf(w, format, c.convertArgs(a)...)
|
||||
}
|
||||
|
||||
// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it
|
||||
// passed with a Formatter interface returned by c.NewFormatter. See
|
||||
// NewFormatter for formatting details.
|
||||
//
|
||||
// This function is shorthand for the following syntax:
|
||||
//
|
||||
// fmt.Fprintln(w, c.NewFormatter(a), c.NewFormatter(b))
|
||||
func (c *ConfigState) Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
|
||||
return fmt.Fprintln(w, c.convertArgs(a)...)
|
||||
}
|
||||
|
||||
// Print is a wrapper for fmt.Print that treats each argument as if it were
|
||||
// passed with a Formatter interface returned by c.NewFormatter. It returns
|
||||
// the number of bytes written and any write error encountered. See
|
||||
// NewFormatter for formatting details.
|
||||
//
|
||||
// This function is shorthand for the following syntax:
|
||||
//
|
||||
// fmt.Print(c.NewFormatter(a), c.NewFormatter(b))
|
||||
func (c *ConfigState) Print(a ...interface{}) (n int, err error) {
|
||||
return fmt.Print(c.convertArgs(a)...)
|
||||
}
|
||||
|
||||
// Printf is a wrapper for fmt.Printf that treats each argument as if it were
|
||||
// passed with a Formatter interface returned by c.NewFormatter. It returns
|
||||
// the number of bytes written and any write error encountered. See
|
||||
// NewFormatter for formatting details.
|
||||
//
|
||||
// This function is shorthand for the following syntax:
|
||||
//
|
||||
// fmt.Printf(format, c.NewFormatter(a), c.NewFormatter(b))
|
||||
func (c *ConfigState) Printf(format string, a ...interface{}) (n int, err error) {
|
||||
return fmt.Printf(format, c.convertArgs(a)...)
|
||||
}
|
||||
|
||||
// Println is a wrapper for fmt.Println that treats each argument as if it were
|
||||
// passed with a Formatter interface returned by c.NewFormatter. It returns
|
||||
// the number of bytes written and any write error encountered. See
|
||||
// NewFormatter for formatting details.
|
||||
//
|
||||
// This function is shorthand for the following syntax:
|
||||
//
|
||||
// fmt.Println(c.NewFormatter(a), c.NewFormatter(b))
|
||||
func (c *ConfigState) Println(a ...interface{}) (n int, err error) {
|
||||
return fmt.Println(c.convertArgs(a)...)
|
||||
}
|
||||
|
||||
// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were
|
||||
// passed with a Formatter interface returned by c.NewFormatter. It returns
|
||||
// the resulting string. See NewFormatter for formatting details.
|
||||
//
|
||||
// This function is shorthand for the following syntax:
|
||||
//
|
||||
// fmt.Sprint(c.NewFormatter(a), c.NewFormatter(b))
|
||||
func (c *ConfigState) Sprint(a ...interface{}) string {
|
||||
return fmt.Sprint(c.convertArgs(a)...)
|
||||
}
|
||||
|
||||
// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were
|
||||
// passed with a Formatter interface returned by c.NewFormatter. It returns
|
||||
// the resulting string. See NewFormatter for formatting details.
|
||||
//
|
||||
// This function is shorthand for the following syntax:
|
||||
//
|
||||
// fmt.Sprintf(format, c.NewFormatter(a), c.NewFormatter(b))
|
||||
func (c *ConfigState) Sprintf(format string, a ...interface{}) string {
|
||||
return fmt.Sprintf(format, c.convertArgs(a)...)
|
||||
}
|
||||
|
||||
// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it
|
||||
// were passed with a Formatter interface returned by c.NewFormatter. It
|
||||
// returns the resulting string. See NewFormatter for formatting details.
|
||||
//
|
||||
// This function is shorthand for the following syntax:
|
||||
//
|
||||
// fmt.Sprintln(c.NewFormatter(a), c.NewFormatter(b))
|
||||
func (c *ConfigState) Sprintln(a ...interface{}) string {
|
||||
return fmt.Sprintln(c.convertArgs(a)...)
|
||||
}
|
||||
|
||||
/*
|
||||
NewFormatter returns a custom formatter that satisfies the fmt.Formatter
|
||||
interface. As a result, it integrates cleanly with standard fmt package
|
||||
printing functions. The formatter is useful for inline printing of smaller data
|
||||
types similar to the standard %v format specifier.
|
||||
|
||||
The custom formatter only responds to the %v (most compact), %+v (adds pointer
|
||||
addresses), %#v (adds types), and %#+v (adds types and pointer addresses) verb
|
||||
combinations. Any other verbs such as %x and %q will be sent to the the
|
||||
standard fmt package for formatting. In addition, the custom formatter ignores
|
||||
the width and precision arguments (however they will still work on the format
|
||||
specifiers not handled by the custom formatter).
|
||||
|
||||
Typically this function shouldn't be called directly. It is much easier to make
|
||||
use of the custom formatter by calling one of the convenience functions such as
|
||||
c.Printf, c.Println, or c.Printf.
|
||||
*/
|
||||
func (c *ConfigState) NewFormatter(v interface{}) fmt.Formatter {
|
||||
return newFormatter(c, v)
|
||||
}
|
||||
|
||||
// Fdump formats and displays the passed arguments to io.Writer w. It formats
|
||||
// exactly the same as Dump.
|
||||
func (c *ConfigState) Fdump(w io.Writer, a ...interface{}) {
|
||||
fdump(c, w, a...)
|
||||
}
|
||||
|
||||
/*
|
||||
Dump displays the passed parameters to standard out with newlines, customizable
|
||||
indentation, and additional debug information such as complete types and all
|
||||
pointer addresses used to indirect to the final value. It provides the
|
||||
following features over the built-in printing facilities provided by the fmt
|
||||
package:
|
||||
|
||||
* Pointers are dereferenced and followed
|
||||
* Circular data structures are detected and handled properly
|
||||
* Custom Stringer/error interfaces are optionally invoked, including
|
||||
on unexported types
|
||||
* Custom types which only implement the Stringer/error interfaces via
|
||||
a pointer receiver are optionally invoked when passing non-pointer
|
||||
variables
|
||||
* Byte arrays and slices are dumped like the hexdump -C command which
|
||||
includes offsets, byte values in hex, and ASCII output
|
||||
|
||||
The configuration options are controlled by modifying the public members
|
||||
of c. See ConfigState for options documentation.
|
||||
|
||||
See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to
|
||||
get the formatted result as a string.
|
||||
*/
|
||||
func (c *ConfigState) Dump(a ...interface{}) {
|
||||
fdump(c, os.Stdout, a...)
|
||||
}
|
||||
|
||||
// Sdump returns a string with the passed arguments formatted exactly the same
|
||||
// as Dump.
|
||||
func (c *ConfigState) Sdump(a ...interface{}) string {
|
||||
var buf bytes.Buffer
|
||||
fdump(c, &buf, a...)
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// convertArgs accepts a slice of arguments and returns a slice of the same
|
||||
// length with each argument converted to a spew Formatter interface using
|
||||
// the ConfigState associated with s.
|
||||
func (c *ConfigState) convertArgs(args []interface{}) (formatters []interface{}) {
|
||||
formatters = make([]interface{}, len(args))
|
||||
for index, arg := range args {
|
||||
formatters[index] = newFormatter(c, arg)
|
||||
}
|
||||
return formatters
|
||||
}
|
||||
|
||||
// NewDefaultConfig returns a ConfigState with the following default settings.
|
||||
//
|
||||
// Indent: " "
|
||||
// MaxDepth: 0
|
||||
// DisableMethods: false
|
||||
// DisablePointerMethods: false
|
||||
// ContinueOnMethod: false
|
||||
// SortKeys: false
|
||||
func NewDefaultConfig() *ConfigState {
|
||||
return &ConfigState{Indent: " "}
|
||||
}
|
||||
202
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/doc.go
сгенерированный
поставляемый
Обычный файл
202
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/doc.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,202 @@
|
||||
/*
|
||||
* Copyright (c) 2013 Dave Collins <dave@davec.name>
|
||||
*
|
||||
* Permission to use, copy, modify, and distribute this software for any
|
||||
* purpose with or without fee is hereby granted, provided that the above
|
||||
* copyright notice and this permission notice appear in all copies.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
/*
|
||||
Package spew implements a deep pretty printer for Go data structures to aid in
|
||||
debugging.
|
||||
|
||||
A quick overview of the additional features spew provides over the built-in
|
||||
printing facilities for Go data types are as follows:
|
||||
|
||||
* Pointers are dereferenced and followed
|
||||
* Circular data structures are detected and handled properly
|
||||
* Custom Stringer/error interfaces are optionally invoked, including
|
||||
on unexported types
|
||||
* Custom types which only implement the Stringer/error interfaces via
|
||||
a pointer receiver are optionally invoked when passing non-pointer
|
||||
variables
|
||||
* Byte arrays and slices are dumped like the hexdump -C command which
|
||||
includes offsets, byte values in hex, and ASCII output (only when using
|
||||
Dump style)
|
||||
|
||||
There are two different approaches spew allows for dumping Go data structures:
|
||||
|
||||
* Dump style which prints with newlines, customizable indentation,
|
||||
and additional debug information such as types and all pointer addresses
|
||||
used to indirect to the final value
|
||||
* A custom Formatter interface that integrates cleanly with the standard fmt
|
||||
package and replaces %v, %+v, %#v, and %#+v to provide inline printing
|
||||
similar to the default %v while providing the additional functionality
|
||||
outlined above and passing unsupported format verbs such as %x and %q
|
||||
along to fmt
|
||||
|
||||
Quick Start
|
||||
|
||||
This section demonstrates how to quickly get started with spew. See the
|
||||
sections below for further details on formatting and configuration options.
|
||||
|
||||
To dump a variable with full newlines, indentation, type, and pointer
|
||||
information use Dump, Fdump, or Sdump:
|
||||
spew.Dump(myVar1, myVar2, ...)
|
||||
spew.Fdump(someWriter, myVar1, myVar2, ...)
|
||||
str := spew.Sdump(myVar1, myVar2, ...)
|
||||
|
||||
Alternatively, if you would prefer to use format strings with a compacted inline
|
||||
printing style, use the convenience wrappers Printf, Fprintf, etc with
|
||||
%v (most compact), %+v (adds pointer addresses), %#v (adds types), or
|
||||
%#+v (adds types and pointer addresses):
|
||||
spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2)
|
||||
spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
|
||||
spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2)
|
||||
spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
|
||||
|
||||
Configuration Options
|
||||
|
||||
Configuration of spew is handled by fields in the ConfigState type. For
|
||||
convenience, all of the top-level functions use a global state available
|
||||
via the spew.Config global.
|
||||
|
||||
It is also possible to create a ConfigState instance that provides methods
|
||||
equivalent to the top-level functions. This allows concurrent configuration
|
||||
options. See the ConfigState documentation for more details.
|
||||
|
||||
The following configuration options are available:
|
||||
* Indent
|
||||
String to use for each indentation level for Dump functions.
|
||||
It is a single space by default. A popular alternative is "\t".
|
||||
|
||||
* MaxDepth
|
||||
Maximum number of levels to descend into nested data structures.
|
||||
There is no limit by default.
|
||||
|
||||
* DisableMethods
|
||||
Disables invocation of error and Stringer interface methods.
|
||||
Method invocation is enabled by default.
|
||||
|
||||
* DisablePointerMethods
|
||||
Disables invocation of error and Stringer interface methods on types
|
||||
which only accept pointer receivers from non-pointer variables.
|
||||
Pointer method invocation is enabled by default.
|
||||
|
||||
* ContinueOnMethod
|
||||
Enables recursion into types after invoking error and Stringer interface
|
||||
methods. Recursion after method invocation is disabled by default.
|
||||
|
||||
* SortKeys
|
||||
Specifies map keys should be sorted before being printed. Use
|
||||
this to have a more deterministic, diffable output. Note that
|
||||
only native types (bool, int, uint, floats, uintptr and string)
|
||||
and types which implement error or Stringer interfaces are
|
||||
supported with other types sorted according to the
|
||||
reflect.Value.String() output which guarantees display
|
||||
stability. Natural map order is used by default.
|
||||
|
||||
* SpewKeys
|
||||
Specifies that, as a last resort attempt, map keys should be
|
||||
spewed to strings and sorted by those strings. This is only
|
||||
considered if SortKeys is true.
|
||||
|
||||
Dump Usage
|
||||
|
||||
Simply call spew.Dump with a list of variables you want to dump:
|
||||
|
||||
spew.Dump(myVar1, myVar2, ...)
|
||||
|
||||
You may also call spew.Fdump if you would prefer to output to an arbitrary
|
||||
io.Writer. For example, to dump to standard error:
|
||||
|
||||
spew.Fdump(os.Stderr, myVar1, myVar2, ...)
|
||||
|
||||
A third option is to call spew.Sdump to get the formatted output as a string:
|
||||
|
||||
str := spew.Sdump(myVar1, myVar2, ...)
|
||||
|
||||
Sample Dump Output
|
||||
|
||||
See the Dump example for details on the setup of the types and variables being
|
||||
shown here.
|
||||
|
||||
(main.Foo) {
|
||||
unexportedField: (*main.Bar)(0xf84002e210)({
|
||||
flag: (main.Flag) flagTwo,
|
||||
data: (uintptr) <nil>
|
||||
}),
|
||||
ExportedField: (map[interface {}]interface {}) (len=1) {
|
||||
(string) (len=3) "one": (bool) true
|
||||
}
|
||||
}
|
||||
|
||||
Byte (and uint8) arrays and slices are displayed uniquely like the hexdump -C
|
||||
command as shown.
|
||||
([]uint8) (len=32 cap=32) {
|
||||
00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... |
|
||||
00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0|
|
||||
00000020 31 32 |12|
|
||||
}
|
||||
|
||||
Custom Formatter
|
||||
|
||||
Spew provides a custom formatter that implements the fmt.Formatter interface
|
||||
so that it integrates cleanly with standard fmt package printing functions. The
|
||||
formatter is useful for inline printing of smaller data types similar to the
|
||||
standard %v format specifier.
|
||||
|
||||
The custom formatter only responds to the %v (most compact), %+v (adds pointer
|
||||
addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb
|
||||
combinations. Any other verbs such as %x and %q will be sent to the the
|
||||
standard fmt package for formatting. In addition, the custom formatter ignores
|
||||
the width and precision arguments (however they will still work on the format
|
||||
specifiers not handled by the custom formatter).
|
||||
|
||||
Custom Formatter Usage
|
||||
|
||||
The simplest way to make use of the spew custom formatter is to call one of the
|
||||
convenience functions such as spew.Printf, spew.Println, or spew.Printf. The
|
||||
functions have syntax you are most likely already familiar with:
|
||||
|
||||
spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2)
|
||||
spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
|
||||
spew.Println(myVar, myVar2)
|
||||
spew.Fprintf(os.Stderr, "myVar1: %v -- myVar2: %+v", myVar1, myVar2)
|
||||
spew.Fprintf(os.Stderr, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
|
||||
|
||||
See the Index for the full list convenience functions.
|
||||
|
||||
Sample Formatter Output
|
||||
|
||||
Double pointer to a uint8:
|
||||
%v: <**>5
|
||||
%+v: <**>(0xf8400420d0->0xf8400420c8)5
|
||||
%#v: (**uint8)5
|
||||
%#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5
|
||||
|
||||
Pointer to circular struct with a uint8 field and a pointer to itself:
|
||||
%v: <*>{1 <*><shown>}
|
||||
%+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)<shown>}
|
||||
%#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)<shown>}
|
||||
%#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)<shown>}
|
||||
|
||||
See the Printf example for details on the setup of variables being shown
|
||||
here.
|
||||
|
||||
Errors
|
||||
|
||||
Since it is possible for custom Stringer/error interfaces to panic, spew
|
||||
detects them and handles them internally by printing the panic information
|
||||
inline with the output. Since spew is intended to provide deep pretty printing
|
||||
capabilities on structures, it intentionally does not return any errors.
|
||||
*/
|
||||
package spew
|
||||
509
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dump.go
сгенерированный
поставляемый
Обычный файл
509
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dump.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,509 @@
|
||||
/*
|
||||
* Copyright (c) 2013 Dave Collins <dave@davec.name>
|
||||
*
|
||||
* Permission to use, copy, modify, and distribute this software for any
|
||||
* purpose with or without fee is hereby granted, provided that the above
|
||||
* copyright notice and this permission notice appear in all copies.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
package spew
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
// uint8Type is a reflect.Type representing a uint8. It is used to
|
||||
// convert cgo types to uint8 slices for hexdumping.
|
||||
uint8Type = reflect.TypeOf(uint8(0))
|
||||
|
||||
// cCharRE is a regular expression that matches a cgo char.
|
||||
// It is used to detect character arrays to hexdump them.
|
||||
cCharRE = regexp.MustCompile("^.*\\._Ctype_char$")
|
||||
|
||||
// cUnsignedCharRE is a regular expression that matches a cgo unsigned
|
||||
// char. It is used to detect unsigned character arrays to hexdump
|
||||
// them.
|
||||
cUnsignedCharRE = regexp.MustCompile("^.*\\._Ctype_unsignedchar$")
|
||||
|
||||
// cUint8tCharRE is a regular expression that matches a cgo uint8_t.
|
||||
// It is used to detect uint8_t arrays to hexdump them.
|
||||
cUint8tCharRE = regexp.MustCompile("^.*\\._Ctype_uint8_t$")
|
||||
)
|
||||
|
||||
// dumpState contains information about the state of a dump operation.
|
||||
type dumpState struct {
|
||||
w io.Writer
|
||||
depth int
|
||||
pointers map[uintptr]int
|
||||
ignoreNextType bool
|
||||
ignoreNextIndent bool
|
||||
cs *ConfigState
|
||||
}
|
||||
|
||||
// indent performs indentation according to the depth level and cs.Indent
|
||||
// option.
|
||||
func (d *dumpState) indent() {
|
||||
if d.ignoreNextIndent {
|
||||
d.ignoreNextIndent = false
|
||||
return
|
||||
}
|
||||
d.w.Write(bytes.Repeat([]byte(d.cs.Indent), d.depth))
|
||||
}
|
||||
|
||||
// unpackValue returns values inside of non-nil interfaces when possible.
|
||||
// This is useful for data types like structs, arrays, slices, and maps which
|
||||
// can contain varying types packed inside an interface.
|
||||
func (d *dumpState) unpackValue(v reflect.Value) reflect.Value {
|
||||
if v.Kind() == reflect.Interface && !v.IsNil() {
|
||||
v = v.Elem()
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// dumpPtr handles formatting of pointers by indirecting them as necessary.
|
||||
func (d *dumpState) dumpPtr(v reflect.Value) {
|
||||
// Remove pointers at or below the current depth from map used to detect
|
||||
// circular refs.
|
||||
for k, depth := range d.pointers {
|
||||
if depth >= d.depth {
|
||||
delete(d.pointers, k)
|
||||
}
|
||||
}
|
||||
|
||||
// Keep list of all dereferenced pointers to show later.
|
||||
pointerChain := make([]uintptr, 0)
|
||||
|
||||
// Figure out how many levels of indirection there are by dereferencing
|
||||
// pointers and unpacking interfaces down the chain while detecting circular
|
||||
// references.
|
||||
nilFound := false
|
||||
cycleFound := false
|
||||
indirects := 0
|
||||
ve := v
|
||||
for ve.Kind() == reflect.Ptr {
|
||||
if ve.IsNil() {
|
||||
nilFound = true
|
||||
break
|
||||
}
|
||||
indirects++
|
||||
addr := ve.Pointer()
|
||||
pointerChain = append(pointerChain, addr)
|
||||
if pd, ok := d.pointers[addr]; ok && pd < d.depth {
|
||||
cycleFound = true
|
||||
indirects--
|
||||
break
|
||||
}
|
||||
d.pointers[addr] = d.depth
|
||||
|
||||
ve = ve.Elem()
|
||||
if ve.Kind() == reflect.Interface {
|
||||
if ve.IsNil() {
|
||||
nilFound = true
|
||||
break
|
||||
}
|
||||
ve = ve.Elem()
|
||||
}
|
||||
}
|
||||
|
||||
// Display type information.
|
||||
d.w.Write(openParenBytes)
|
||||
d.w.Write(bytes.Repeat(asteriskBytes, indirects))
|
||||
d.w.Write([]byte(ve.Type().String()))
|
||||
d.w.Write(closeParenBytes)
|
||||
|
||||
// Display pointer information.
|
||||
if len(pointerChain) > 0 {
|
||||
d.w.Write(openParenBytes)
|
||||
for i, addr := range pointerChain {
|
||||
if i > 0 {
|
||||
d.w.Write(pointerChainBytes)
|
||||
}
|
||||
printHexPtr(d.w, addr)
|
||||
}
|
||||
d.w.Write(closeParenBytes)
|
||||
}
|
||||
|
||||
// Display dereferenced value.
|
||||
d.w.Write(openParenBytes)
|
||||
switch {
|
||||
case nilFound == true:
|
||||
d.w.Write(nilAngleBytes)
|
||||
|
||||
case cycleFound == true:
|
||||
d.w.Write(circularBytes)
|
||||
|
||||
default:
|
||||
d.ignoreNextType = true
|
||||
d.dump(ve)
|
||||
}
|
||||
d.w.Write(closeParenBytes)
|
||||
}
|
||||
|
||||
// dumpSlice handles formatting of arrays and slices. Byte (uint8 under
|
||||
// reflection) arrays and slices are dumped in hexdump -C fashion.
|
||||
func (d *dumpState) dumpSlice(v reflect.Value) {
|
||||
// Determine whether this type should be hex dumped or not. Also,
|
||||
// for types which should be hexdumped, try to use the underlying data
|
||||
// first, then fall back to trying to convert them to a uint8 slice.
|
||||
var buf []uint8
|
||||
doConvert := false
|
||||
doHexDump := false
|
||||
numEntries := v.Len()
|
||||
if numEntries > 0 {
|
||||
vt := v.Index(0).Type()
|
||||
vts := vt.String()
|
||||
switch {
|
||||
// C types that need to be converted.
|
||||
case cCharRE.MatchString(vts):
|
||||
fallthrough
|
||||
case cUnsignedCharRE.MatchString(vts):
|
||||
fallthrough
|
||||
case cUint8tCharRE.MatchString(vts):
|
||||
doConvert = true
|
||||
|
||||
// Try to use existing uint8 slices and fall back to converting
|
||||
// and copying if that fails.
|
||||
case vt.Kind() == reflect.Uint8:
|
||||
// We need an addressable interface to convert the type
|
||||
// to a byte slice. However, the reflect package won't
|
||||
// give us an interface on certain things like
|
||||
// unexported struct fields in order to enforce
|
||||
// visibility rules. We use unsafe, when available, to
|
||||
// bypass these restrictions since this package does not
|
||||
// mutate the values.
|
||||
vs := v
|
||||
if !vs.CanInterface() || !vs.CanAddr() {
|
||||
vs = unsafeReflectValue(vs)
|
||||
}
|
||||
if !UnsafeDisabled {
|
||||
vs = vs.Slice(0, numEntries)
|
||||
|
||||
// Use the existing uint8 slice if it can be
|
||||
// type asserted.
|
||||
iface := vs.Interface()
|
||||
if slice, ok := iface.([]uint8); ok {
|
||||
buf = slice
|
||||
doHexDump = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// The underlying data needs to be converted if it can't
|
||||
// be type asserted to a uint8 slice.
|
||||
doConvert = true
|
||||
}
|
||||
|
||||
// Copy and convert the underlying type if needed.
|
||||
if doConvert && vt.ConvertibleTo(uint8Type) {
|
||||
// Convert and copy each element into a uint8 byte
|
||||
// slice.
|
||||
buf = make([]uint8, numEntries)
|
||||
for i := 0; i < numEntries; i++ {
|
||||
vv := v.Index(i)
|
||||
buf[i] = uint8(vv.Convert(uint8Type).Uint())
|
||||
}
|
||||
doHexDump = true
|
||||
}
|
||||
}
|
||||
|
||||
// Hexdump the entire slice as needed.
|
||||
if doHexDump {
|
||||
indent := strings.Repeat(d.cs.Indent, d.depth)
|
||||
str := indent + hex.Dump(buf)
|
||||
str = strings.Replace(str, "\n", "\n"+indent, -1)
|
||||
str = strings.TrimRight(str, d.cs.Indent)
|
||||
d.w.Write([]byte(str))
|
||||
return
|
||||
}
|
||||
|
||||
// Recursively call dump for each item.
|
||||
for i := 0; i < numEntries; i++ {
|
||||
d.dump(d.unpackValue(v.Index(i)))
|
||||
if i < (numEntries - 1) {
|
||||
d.w.Write(commaNewlineBytes)
|
||||
} else {
|
||||
d.w.Write(newlineBytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// dump is the main workhorse for dumping a value. It uses the passed reflect
|
||||
// value to figure out what kind of object we are dealing with and formats it
|
||||
// appropriately. It is a recursive function, however circular data structures
|
||||
// are detected and handled properly.
|
||||
func (d *dumpState) dump(v reflect.Value) {
|
||||
// Handle invalid reflect values immediately.
|
||||
kind := v.Kind()
|
||||
if kind == reflect.Invalid {
|
||||
d.w.Write(invalidAngleBytes)
|
||||
return
|
||||
}
|
||||
|
||||
// Handle pointers specially.
|
||||
if kind == reflect.Ptr {
|
||||
d.indent()
|
||||
d.dumpPtr(v)
|
||||
return
|
||||
}
|
||||
|
||||
// Print type information unless already handled elsewhere.
|
||||
if !d.ignoreNextType {
|
||||
d.indent()
|
||||
d.w.Write(openParenBytes)
|
||||
d.w.Write([]byte(v.Type().String()))
|
||||
d.w.Write(closeParenBytes)
|
||||
d.w.Write(spaceBytes)
|
||||
}
|
||||
d.ignoreNextType = false
|
||||
|
||||
// Display length and capacity if the built-in len and cap functions
|
||||
// work with the value's kind and the len/cap itself is non-zero.
|
||||
valueLen, valueCap := 0, 0
|
||||
switch v.Kind() {
|
||||
case reflect.Array, reflect.Slice, reflect.Chan:
|
||||
valueLen, valueCap = v.Len(), v.Cap()
|
||||
case reflect.Map, reflect.String:
|
||||
valueLen = v.Len()
|
||||
}
|
||||
if valueLen != 0 || valueCap != 0 {
|
||||
d.w.Write(openParenBytes)
|
||||
if valueLen != 0 {
|
||||
d.w.Write(lenEqualsBytes)
|
||||
printInt(d.w, int64(valueLen), 10)
|
||||
}
|
||||
if valueCap != 0 {
|
||||
if valueLen != 0 {
|
||||
d.w.Write(spaceBytes)
|
||||
}
|
||||
d.w.Write(capEqualsBytes)
|
||||
printInt(d.w, int64(valueCap), 10)
|
||||
}
|
||||
d.w.Write(closeParenBytes)
|
||||
d.w.Write(spaceBytes)
|
||||
}
|
||||
|
||||
// Call Stringer/error interfaces if they exist and the handle methods flag
|
||||
// is enabled
|
||||
if !d.cs.DisableMethods {
|
||||
if (kind != reflect.Invalid) && (kind != reflect.Interface) {
|
||||
if handled := handleMethods(d.cs, d.w, v); handled {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
switch kind {
|
||||
case reflect.Invalid:
|
||||
// Do nothing. We should never get here since invalid has already
|
||||
// been handled above.
|
||||
|
||||
case reflect.Bool:
|
||||
printBool(d.w, v.Bool())
|
||||
|
||||
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
|
||||
printInt(d.w, v.Int(), 10)
|
||||
|
||||
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
|
||||
printUint(d.w, v.Uint(), 10)
|
||||
|
||||
case reflect.Float32:
|
||||
printFloat(d.w, v.Float(), 32)
|
||||
|
||||
case reflect.Float64:
|
||||
printFloat(d.w, v.Float(), 64)
|
||||
|
||||
case reflect.Complex64:
|
||||
printComplex(d.w, v.Complex(), 32)
|
||||
|
||||
case reflect.Complex128:
|
||||
printComplex(d.w, v.Complex(), 64)
|
||||
|
||||
case reflect.Slice:
|
||||
if v.IsNil() {
|
||||
d.w.Write(nilAngleBytes)
|
||||
break
|
||||
}
|
||||
fallthrough
|
||||
|
||||
case reflect.Array:
|
||||
d.w.Write(openBraceNewlineBytes)
|
||||
d.depth++
|
||||
if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) {
|
||||
d.indent()
|
||||
d.w.Write(maxNewlineBytes)
|
||||
} else {
|
||||
d.dumpSlice(v)
|
||||
}
|
||||
d.depth--
|
||||
d.indent()
|
||||
d.w.Write(closeBraceBytes)
|
||||
|
||||
case reflect.String:
|
||||
d.w.Write([]byte(strconv.Quote(v.String())))
|
||||
|
||||
case reflect.Interface:
|
||||
// The only time we should get here is for nil interfaces due to
|
||||
// unpackValue calls.
|
||||
if v.IsNil() {
|
||||
d.w.Write(nilAngleBytes)
|
||||
}
|
||||
|
||||
case reflect.Ptr:
|
||||
// Do nothing. We should never get here since pointers have already
|
||||
// been handled above.
|
||||
|
||||
case reflect.Map:
|
||||
// nil maps should be indicated as different than empty maps
|
||||
if v.IsNil() {
|
||||
d.w.Write(nilAngleBytes)
|
||||
break
|
||||
}
|
||||
|
||||
d.w.Write(openBraceNewlineBytes)
|
||||
d.depth++
|
||||
if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) {
|
||||
d.indent()
|
||||
d.w.Write(maxNewlineBytes)
|
||||
} else {
|
||||
numEntries := v.Len()
|
||||
keys := v.MapKeys()
|
||||
if d.cs.SortKeys {
|
||||
sortValues(keys, d.cs)
|
||||
}
|
||||
for i, key := range keys {
|
||||
d.dump(d.unpackValue(key))
|
||||
d.w.Write(colonSpaceBytes)
|
||||
d.ignoreNextIndent = true
|
||||
d.dump(d.unpackValue(v.MapIndex(key)))
|
||||
if i < (numEntries - 1) {
|
||||
d.w.Write(commaNewlineBytes)
|
||||
} else {
|
||||
d.w.Write(newlineBytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
d.depth--
|
||||
d.indent()
|
||||
d.w.Write(closeBraceBytes)
|
||||
|
||||
case reflect.Struct:
|
||||
d.w.Write(openBraceNewlineBytes)
|
||||
d.depth++
|
||||
if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) {
|
||||
d.indent()
|
||||
d.w.Write(maxNewlineBytes)
|
||||
} else {
|
||||
vt := v.Type()
|
||||
numFields := v.NumField()
|
||||
for i := 0; i < numFields; i++ {
|
||||
d.indent()
|
||||
vtf := vt.Field(i)
|
||||
d.w.Write([]byte(vtf.Name))
|
||||
d.w.Write(colonSpaceBytes)
|
||||
d.ignoreNextIndent = true
|
||||
d.dump(d.unpackValue(v.Field(i)))
|
||||
if i < (numFields - 1) {
|
||||
d.w.Write(commaNewlineBytes)
|
||||
} else {
|
||||
d.w.Write(newlineBytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
d.depth--
|
||||
d.indent()
|
||||
d.w.Write(closeBraceBytes)
|
||||
|
||||
case reflect.Uintptr:
|
||||
printHexPtr(d.w, uintptr(v.Uint()))
|
||||
|
||||
case reflect.UnsafePointer, reflect.Chan, reflect.Func:
|
||||
printHexPtr(d.w, v.Pointer())
|
||||
|
||||
// There were not any other types at the time this code was written, but
|
||||
// fall back to letting the default fmt package handle it in case any new
|
||||
// types are added.
|
||||
default:
|
||||
if v.CanInterface() {
|
||||
fmt.Fprintf(d.w, "%v", v.Interface())
|
||||
} else {
|
||||
fmt.Fprintf(d.w, "%v", v.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// fdump is a helper function to consolidate the logic from the various public
|
||||
// methods which take varying writers and config states.
|
||||
func fdump(cs *ConfigState, w io.Writer, a ...interface{}) {
|
||||
for _, arg := range a {
|
||||
if arg == nil {
|
||||
w.Write(interfaceBytes)
|
||||
w.Write(spaceBytes)
|
||||
w.Write(nilAngleBytes)
|
||||
w.Write(newlineBytes)
|
||||
continue
|
||||
}
|
||||
|
||||
d := dumpState{w: w, cs: cs}
|
||||
d.pointers = make(map[uintptr]int)
|
||||
d.dump(reflect.ValueOf(arg))
|
||||
d.w.Write(newlineBytes)
|
||||
}
|
||||
}
|
||||
|
||||
// Fdump formats and displays the passed arguments to io.Writer w. It formats
|
||||
// exactly the same as Dump.
|
||||
func Fdump(w io.Writer, a ...interface{}) {
|
||||
fdump(&Config, w, a...)
|
||||
}
|
||||
|
||||
// Sdump returns a string with the passed arguments formatted exactly the same
|
||||
// as Dump.
|
||||
func Sdump(a ...interface{}) string {
|
||||
var buf bytes.Buffer
|
||||
fdump(&Config, &buf, a...)
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
/*
|
||||
Dump displays the passed parameters to standard out with newlines, customizable
|
||||
indentation, and additional debug information such as complete types and all
|
||||
pointer addresses used to indirect to the final value. It provides the
|
||||
following features over the built-in printing facilities provided by the fmt
|
||||
package:
|
||||
|
||||
* Pointers are dereferenced and followed
|
||||
* Circular data structures are detected and handled properly
|
||||
* Custom Stringer/error interfaces are optionally invoked, including
|
||||
on unexported types
|
||||
* Custom types which only implement the Stringer/error interfaces via
|
||||
a pointer receiver are optionally invoked when passing non-pointer
|
||||
variables
|
||||
* Byte arrays and slices are dumped like the hexdump -C command which
|
||||
includes offsets, byte values in hex, and ASCII output
|
||||
|
||||
The configuration options are controlled by an exported package global,
|
||||
spew.Config. See ConfigState for options documentation.
|
||||
|
||||
See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to
|
||||
get the formatted result as a string.
|
||||
*/
|
||||
func Dump(a ...interface{}) {
|
||||
fdump(&Config, os.Stdout, a...)
|
||||
}
|
||||
1042
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dump_test.go
сгенерированный
поставляемый
Обычный файл
1042
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dump_test.go
сгенерированный
поставляемый
Обычный файл
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
98
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dumpcgo_test.go
сгенерированный
поставляемый
Обычный файл
98
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dumpcgo_test.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,98 @@
|
||||
// Copyright (c) 2013 Dave Collins <dave@davec.name>
|
||||
//
|
||||
// Permission to use, copy, modify, and distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
// NOTE: Due to the following build constraints, this file will only be compiled
|
||||
// when both cgo is supported and "-tags testcgo" is added to the go test
|
||||
// command line. This means the cgo tests are only added (and hence run) when
|
||||
// specifially requested. This configuration is used because spew itself
|
||||
// does not require cgo to run even though it does handle certain cgo types
|
||||
// specially. Rather than forcing all clients to require cgo and an external
|
||||
// C compiler just to run the tests, this scheme makes them optional.
|
||||
// +build cgo,testcgo
|
||||
|
||||
package spew_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/mattermost/platform/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/testdata"
|
||||
)
|
||||
|
||||
func addCgoDumpTests() {
|
||||
// C char pointer.
|
||||
v := testdata.GetCgoCharPointer()
|
||||
nv := testdata.GetCgoNullCharPointer()
|
||||
pv := &v
|
||||
vcAddr := fmt.Sprintf("%p", v)
|
||||
vAddr := fmt.Sprintf("%p", pv)
|
||||
pvAddr := fmt.Sprintf("%p", &pv)
|
||||
vt := "*testdata._Ctype_char"
|
||||
vs := "116"
|
||||
addDumpTest(v, "("+vt+")("+vcAddr+")("+vs+")\n")
|
||||
addDumpTest(pv, "(*"+vt+")("+vAddr+"->"+vcAddr+")("+vs+")\n")
|
||||
addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+"->"+vcAddr+")("+vs+")\n")
|
||||
addDumpTest(nv, "("+vt+")(<nil>)\n")
|
||||
|
||||
// C char array.
|
||||
v2, v2l, v2c := testdata.GetCgoCharArray()
|
||||
v2Len := fmt.Sprintf("%d", v2l)
|
||||
v2Cap := fmt.Sprintf("%d", v2c)
|
||||
v2t := "[6]testdata._Ctype_char"
|
||||
v2s := "(len=" + v2Len + " cap=" + v2Cap + ") " +
|
||||
"{\n 00000000 74 65 73 74 32 00 " +
|
||||
" |test2.|\n}"
|
||||
addDumpTest(v2, "("+v2t+") "+v2s+"\n")
|
||||
|
||||
// C unsigned char array.
|
||||
v3, v3l, v3c := testdata.GetCgoUnsignedCharArray()
|
||||
v3Len := fmt.Sprintf("%d", v3l)
|
||||
v3Cap := fmt.Sprintf("%d", v3c)
|
||||
v3t := "[6]testdata._Ctype_unsignedchar"
|
||||
v3s := "(len=" + v3Len + " cap=" + v3Cap + ") " +
|
||||
"{\n 00000000 74 65 73 74 33 00 " +
|
||||
" |test3.|\n}"
|
||||
addDumpTest(v3, "("+v3t+") "+v3s+"\n")
|
||||
|
||||
// C signed char array.
|
||||
v4, v4l, v4c := testdata.GetCgoSignedCharArray()
|
||||
v4Len := fmt.Sprintf("%d", v4l)
|
||||
v4Cap := fmt.Sprintf("%d", v4c)
|
||||
v4t := "[6]testdata._Ctype_schar"
|
||||
v4t2 := "testdata._Ctype_schar"
|
||||
v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " +
|
||||
"{\n (" + v4t2 + ") 116,\n (" + v4t2 + ") 101,\n (" + v4t2 +
|
||||
") 115,\n (" + v4t2 + ") 116,\n (" + v4t2 + ") 52,\n (" + v4t2 +
|
||||
") 0\n}"
|
||||
addDumpTest(v4, "("+v4t+") "+v4s+"\n")
|
||||
|
||||
// C uint8_t array.
|
||||
v5, v5l, v5c := testdata.GetCgoUint8tArray()
|
||||
v5Len := fmt.Sprintf("%d", v5l)
|
||||
v5Cap := fmt.Sprintf("%d", v5c)
|
||||
v5t := "[6]testdata._Ctype_uint8_t"
|
||||
v5s := "(len=" + v5Len + " cap=" + v5Cap + ") " +
|
||||
"{\n 00000000 74 65 73 74 35 00 " +
|
||||
" |test5.|\n}"
|
||||
addDumpTest(v5, "("+v5t+") "+v5s+"\n")
|
||||
|
||||
// C typedefed unsigned char array.
|
||||
v6, v6l, v6c := testdata.GetCgoTypdefedUnsignedCharArray()
|
||||
v6Len := fmt.Sprintf("%d", v6l)
|
||||
v6Cap := fmt.Sprintf("%d", v6c)
|
||||
v6t := "[6]testdata._Ctype_custom_uchar_t"
|
||||
v6s := "(len=" + v6Len + " cap=" + v6Cap + ") " +
|
||||
"{\n 00000000 74 65 73 74 36 00 " +
|
||||
" |test6.|\n}"
|
||||
addDumpTest(v6, "("+v6t+") "+v6s+"\n")
|
||||
}
|
||||
26
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dumpnocgo_test.go
сгенерированный
поставляемый
Обычный файл
26
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dumpnocgo_test.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,26 @@
|
||||
// Copyright (c) 2013 Dave Collins <dave@davec.name>
|
||||
//
|
||||
// Permission to use, copy, modify, and distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
// NOTE: Due to the following build constraints, this file will only be compiled
|
||||
// when either cgo is not supported or "-tags testcgo" is not added to the go
|
||||
// test command line. This file intentionally does not setup any cgo tests in
|
||||
// this scenario.
|
||||
// +build !cgo !testcgo
|
||||
|
||||
package spew_test
|
||||
|
||||
func addCgoDumpTests() {
|
||||
// Don't add any tests for cgo since this file is only compiled when
|
||||
// there should not be any cgo tests.
|
||||
}
|
||||
226
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/example_test.go
сгенерированный
поставляемый
Обычный файл
226
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/example_test.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,226 @@
|
||||
/*
|
||||
* Copyright (c) 2013 Dave Collins <dave@davec.name>
|
||||
*
|
||||
* Permission to use, copy, modify, and distribute this software for any
|
||||
* purpose with or without fee is hereby granted, provided that the above
|
||||
* copyright notice and this permission notice appear in all copies.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
package spew_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/mattermost/platform/Godeps/_workspace/src/github.com/davecgh/go-spew/spew"
|
||||
)
|
||||
|
||||
type Flag int
|
||||
|
||||
const (
|
||||
flagOne Flag = iota
|
||||
flagTwo
|
||||
)
|
||||
|
||||
var flagStrings = map[Flag]string{
|
||||
flagOne: "flagOne",
|
||||
flagTwo: "flagTwo",
|
||||
}
|
||||
|
||||
func (f Flag) String() string {
|
||||
if s, ok := flagStrings[f]; ok {
|
||||
return s
|
||||
}
|
||||
return fmt.Sprintf("Unknown flag (%d)", int(f))
|
||||
}
|
||||
|
||||
type Bar struct {
|
||||
data uintptr
|
||||
}
|
||||
|
||||
type Foo struct {
|
||||
unexportedField Bar
|
||||
ExportedField map[interface{}]interface{}
|
||||
}
|
||||
|
||||
// This example demonstrates how to use Dump to dump variables to stdout.
|
||||
func ExampleDump() {
|
||||
// The following package level declarations are assumed for this example:
|
||||
/*
|
||||
type Flag int
|
||||
|
||||
const (
|
||||
flagOne Flag = iota
|
||||
flagTwo
|
||||
)
|
||||
|
||||
var flagStrings = map[Flag]string{
|
||||
flagOne: "flagOne",
|
||||
flagTwo: "flagTwo",
|
||||
}
|
||||
|
||||
func (f Flag) String() string {
|
||||
if s, ok := flagStrings[f]; ok {
|
||||
return s
|
||||
}
|
||||
return fmt.Sprintf("Unknown flag (%d)", int(f))
|
||||
}
|
||||
|
||||
type Bar struct {
|
||||
data uintptr
|
||||
}
|
||||
|
||||
type Foo struct {
|
||||
unexportedField Bar
|
||||
ExportedField map[interface{}]interface{}
|
||||
}
|
||||
*/
|
||||
|
||||
// Setup some sample data structures for the example.
|
||||
bar := Bar{uintptr(0)}
|
||||
s1 := Foo{bar, map[interface{}]interface{}{"one": true}}
|
||||
f := Flag(5)
|
||||
b := []byte{
|
||||
0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
|
||||
0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
|
||||
0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
|
||||
0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
|
||||
0x31, 0x32,
|
||||
}
|
||||
|
||||
// Dump!
|
||||
spew.Dump(s1, f, b)
|
||||
|
||||
// Output:
|
||||
// (spew_test.Foo) {
|
||||
// unexportedField: (spew_test.Bar) {
|
||||
// data: (uintptr) <nil>
|
||||
// },
|
||||
// ExportedField: (map[interface {}]interface {}) (len=1) {
|
||||
// (string) (len=3) "one": (bool) true
|
||||
// }
|
||||
// }
|
||||
// (spew_test.Flag) Unknown flag (5)
|
||||
// ([]uint8) (len=34 cap=34) {
|
||||
// 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... |
|
||||
// 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0|
|
||||
// 00000020 31 32 |12|
|
||||
// }
|
||||
//
|
||||
}
|
||||
|
||||
// This example demonstrates how to use Printf to display a variable with a
|
||||
// format string and inline formatting.
|
||||
func ExamplePrintf() {
|
||||
// Create a double pointer to a uint 8.
|
||||
ui8 := uint8(5)
|
||||
pui8 := &ui8
|
||||
ppui8 := &pui8
|
||||
|
||||
// Create a circular data type.
|
||||
type circular struct {
|
||||
ui8 uint8
|
||||
c *circular
|
||||
}
|
||||
c := circular{ui8: 1}
|
||||
c.c = &c
|
||||
|
||||
// Print!
|
||||
spew.Printf("ppui8: %v\n", ppui8)
|
||||
spew.Printf("circular: %v\n", c)
|
||||
|
||||
// Output:
|
||||
// ppui8: <**>5
|
||||
// circular: {1 <*>{1 <*><shown>}}
|
||||
}
|
||||
|
||||
// This example demonstrates how to use a ConfigState.
|
||||
func ExampleConfigState() {
|
||||
// Modify the indent level of the ConfigState only. The global
|
||||
// configuration is not modified.
|
||||
scs := spew.ConfigState{Indent: "\t"}
|
||||
|
||||
// Output using the ConfigState instance.
|
||||
v := map[string]int{"one": 1}
|
||||
scs.Printf("v: %v\n", v)
|
||||
scs.Dump(v)
|
||||
|
||||
// Output:
|
||||
// v: map[one:1]
|
||||
// (map[string]int) (len=1) {
|
||||
// (string) (len=3) "one": (int) 1
|
||||
// }
|
||||
}
|
||||
|
||||
// This example demonstrates how to use ConfigState.Dump to dump variables to
|
||||
// stdout
|
||||
func ExampleConfigState_Dump() {
|
||||
// See the top-level Dump example for details on the types used in this
|
||||
// example.
|
||||
|
||||
// Create two ConfigState instances with different indentation.
|
||||
scs := spew.ConfigState{Indent: "\t"}
|
||||
scs2 := spew.ConfigState{Indent: " "}
|
||||
|
||||
// Setup some sample data structures for the example.
|
||||
bar := Bar{uintptr(0)}
|
||||
s1 := Foo{bar, map[interface{}]interface{}{"one": true}}
|
||||
|
||||
// Dump using the ConfigState instances.
|
||||
scs.Dump(s1)
|
||||
scs2.Dump(s1)
|
||||
|
||||
// Output:
|
||||
// (spew_test.Foo) {
|
||||
// unexportedField: (spew_test.Bar) {
|
||||
// data: (uintptr) <nil>
|
||||
// },
|
||||
// ExportedField: (map[interface {}]interface {}) (len=1) {
|
||||
// (string) (len=3) "one": (bool) true
|
||||
// }
|
||||
// }
|
||||
// (spew_test.Foo) {
|
||||
// unexportedField: (spew_test.Bar) {
|
||||
// data: (uintptr) <nil>
|
||||
// },
|
||||
// ExportedField: (map[interface {}]interface {}) (len=1) {
|
||||
// (string) (len=3) "one": (bool) true
|
||||
// }
|
||||
// }
|
||||
//
|
||||
}
|
||||
|
||||
// This example demonstrates how to use ConfigState.Printf to display a variable
|
||||
// with a format string and inline formatting.
|
||||
func ExampleConfigState_Printf() {
|
||||
// See the top-level Dump example for details on the types used in this
|
||||
// example.
|
||||
|
||||
// Create two ConfigState instances and modify the method handling of the
|
||||
// first ConfigState only.
|
||||
scs := spew.NewDefaultConfig()
|
||||
scs2 := spew.NewDefaultConfig()
|
||||
scs.DisableMethods = true
|
||||
|
||||
// Alternatively
|
||||
// scs := spew.ConfigState{Indent: " ", DisableMethods: true}
|
||||
// scs2 := spew.ConfigState{Indent: " "}
|
||||
|
||||
// This is of type Flag which implements a Stringer and has raw value 1.
|
||||
f := flagTwo
|
||||
|
||||
// Dump using the ConfigState instances.
|
||||
scs.Printf("f: %v\n", f)
|
||||
scs2.Printf("f: %v\n", f)
|
||||
|
||||
// Output:
|
||||
// f: 1
|
||||
// f: flagTwo
|
||||
}
|
||||
419
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/format.go
сгенерированный
поставляемый
Обычный файл
419
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/format.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,419 @@
|
||||
/*
|
||||
* Copyright (c) 2013 Dave Collins <dave@davec.name>
|
||||
*
|
||||
* Permission to use, copy, modify, and distribute this software for any
|
||||
* purpose with or without fee is hereby granted, provided that the above
|
||||
* copyright notice and this permission notice appear in all copies.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
package spew
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// supportedFlags is a list of all the character flags supported by fmt package.
|
||||
const supportedFlags = "0-+# "
|
||||
|
||||
// formatState implements the fmt.Formatter interface and contains information
|
||||
// about the state of a formatting operation. The NewFormatter function can
|
||||
// be used to get a new Formatter which can be used directly as arguments
|
||||
// in standard fmt package printing calls.
|
||||
type formatState struct {
|
||||
value interface{}
|
||||
fs fmt.State
|
||||
depth int
|
||||
pointers map[uintptr]int
|
||||
ignoreNextType bool
|
||||
cs *ConfigState
|
||||
}
|
||||
|
||||
// buildDefaultFormat recreates the original format string without precision
|
||||
// and width information to pass in to fmt.Sprintf in the case of an
|
||||
// unrecognized type. Unless new types are added to the language, this
|
||||
// function won't ever be called.
|
||||
func (f *formatState) buildDefaultFormat() (format string) {
|
||||
buf := bytes.NewBuffer(percentBytes)
|
||||
|
||||
for _, flag := range supportedFlags {
|
||||
if f.fs.Flag(int(flag)) {
|
||||
buf.WriteRune(flag)
|
||||
}
|
||||
}
|
||||
|
||||
buf.WriteRune('v')
|
||||
|
||||
format = buf.String()
|
||||
return format
|
||||
}
|
||||
|
||||
// constructOrigFormat recreates the original format string including precision
|
||||
// and width information to pass along to the standard fmt package. This allows
|
||||
// automatic deferral of all format strings this package doesn't support.
|
||||
func (f *formatState) constructOrigFormat(verb rune) (format string) {
|
||||
buf := bytes.NewBuffer(percentBytes)
|
||||
|
||||
for _, flag := range supportedFlags {
|
||||
if f.fs.Flag(int(flag)) {
|
||||
buf.WriteRune(flag)
|
||||
}
|
||||
}
|
||||
|
||||
if width, ok := f.fs.Width(); ok {
|
||||
buf.WriteString(strconv.Itoa(width))
|
||||
}
|
||||
|
||||
if precision, ok := f.fs.Precision(); ok {
|
||||
buf.Write(precisionBytes)
|
||||
buf.WriteString(strconv.Itoa(precision))
|
||||
}
|
||||
|
||||
buf.WriteRune(verb)
|
||||
|
||||
format = buf.String()
|
||||
return format
|
||||
}
|
||||
|
||||
// unpackValue returns values inside of non-nil interfaces when possible and
|
||||
// ensures that types for values which have been unpacked from an interface
|
||||
// are displayed when the show types flag is also set.
|
||||
// This is useful for data types like structs, arrays, slices, and maps which
|
||||
// can contain varying types packed inside an interface.
|
||||
func (f *formatState) unpackValue(v reflect.Value) reflect.Value {
|
||||
if v.Kind() == reflect.Interface {
|
||||
f.ignoreNextType = false
|
||||
if !v.IsNil() {
|
||||
v = v.Elem()
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// formatPtr handles formatting of pointers by indirecting them as necessary.
|
||||
func (f *formatState) formatPtr(v reflect.Value) {
|
||||
// Display nil if top level pointer is nil.
|
||||
showTypes := f.fs.Flag('#')
|
||||
if v.IsNil() && (!showTypes || f.ignoreNextType) {
|
||||
f.fs.Write(nilAngleBytes)
|
||||
return
|
||||
}
|
||||
|
||||
// Remove pointers at or below the current depth from map used to detect
|
||||
// circular refs.
|
||||
for k, depth := range f.pointers {
|
||||
if depth >= f.depth {
|
||||
delete(f.pointers, k)
|
||||
}
|
||||
}
|
||||
|
||||
// Keep list of all dereferenced pointers to possibly show later.
|
||||
pointerChain := make([]uintptr, 0)
|
||||
|
||||
// Figure out how many levels of indirection there are by derferencing
|
||||
// pointers and unpacking interfaces down the chain while detecting circular
|
||||
// references.
|
||||
nilFound := false
|
||||
cycleFound := false
|
||||
indirects := 0
|
||||
ve := v
|
||||
for ve.Kind() == reflect.Ptr {
|
||||
if ve.IsNil() {
|
||||
nilFound = true
|
||||
break
|
||||
}
|
||||
indirects++
|
||||
addr := ve.Pointer()
|
||||
pointerChain = append(pointerChain, addr)
|
||||
if pd, ok := f.pointers[addr]; ok && pd < f.depth {
|
||||
cycleFound = true
|
||||
indirects--
|
||||
break
|
||||
}
|
||||
f.pointers[addr] = f.depth
|
||||
|
||||
ve = ve.Elem()
|
||||
if ve.Kind() == reflect.Interface {
|
||||
if ve.IsNil() {
|
||||
nilFound = true
|
||||
break
|
||||
}
|
||||
ve = ve.Elem()
|
||||
}
|
||||
}
|
||||
|
||||
// Display type or indirection level depending on flags.
|
||||
if showTypes && !f.ignoreNextType {
|
||||
f.fs.Write(openParenBytes)
|
||||
f.fs.Write(bytes.Repeat(asteriskBytes, indirects))
|
||||
f.fs.Write([]byte(ve.Type().String()))
|
||||
f.fs.Write(closeParenBytes)
|
||||
} else {
|
||||
if nilFound || cycleFound {
|
||||
indirects += strings.Count(ve.Type().String(), "*")
|
||||
}
|
||||
f.fs.Write(openAngleBytes)
|
||||
f.fs.Write([]byte(strings.Repeat("*", indirects)))
|
||||
f.fs.Write(closeAngleBytes)
|
||||
}
|
||||
|
||||
// Display pointer information depending on flags.
|
||||
if f.fs.Flag('+') && (len(pointerChain) > 0) {
|
||||
f.fs.Write(openParenBytes)
|
||||
for i, addr := range pointerChain {
|
||||
if i > 0 {
|
||||
f.fs.Write(pointerChainBytes)
|
||||
}
|
||||
printHexPtr(f.fs, addr)
|
||||
}
|
||||
f.fs.Write(closeParenBytes)
|
||||
}
|
||||
|
||||
// Display dereferenced value.
|
||||
switch {
|
||||
case nilFound == true:
|
||||
f.fs.Write(nilAngleBytes)
|
||||
|
||||
case cycleFound == true:
|
||||
f.fs.Write(circularShortBytes)
|
||||
|
||||
default:
|
||||
f.ignoreNextType = true
|
||||
f.format(ve)
|
||||
}
|
||||
}
|
||||
|
||||
// format is the main workhorse for providing the Formatter interface. It
|
||||
// uses the passed reflect value to figure out what kind of object we are
|
||||
// dealing with and formats it appropriately. It is a recursive function,
|
||||
// however circular data structures are detected and handled properly.
|
||||
func (f *formatState) format(v reflect.Value) {
|
||||
// Handle invalid reflect values immediately.
|
||||
kind := v.Kind()
|
||||
if kind == reflect.Invalid {
|
||||
f.fs.Write(invalidAngleBytes)
|
||||
return
|
||||
}
|
||||
|
||||
// Handle pointers specially.
|
||||
if kind == reflect.Ptr {
|
||||
f.formatPtr(v)
|
||||
return
|
||||
}
|
||||
|
||||
// Print type information unless already handled elsewhere.
|
||||
if !f.ignoreNextType && f.fs.Flag('#') {
|
||||
f.fs.Write(openParenBytes)
|
||||
f.fs.Write([]byte(v.Type().String()))
|
||||
f.fs.Write(closeParenBytes)
|
||||
}
|
||||
f.ignoreNextType = false
|
||||
|
||||
// Call Stringer/error interfaces if they exist and the handle methods
|
||||
// flag is enabled.
|
||||
if !f.cs.DisableMethods {
|
||||
if (kind != reflect.Invalid) && (kind != reflect.Interface) {
|
||||
if handled := handleMethods(f.cs, f.fs, v); handled {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
switch kind {
|
||||
case reflect.Invalid:
|
||||
// Do nothing. We should never get here since invalid has already
|
||||
// been handled above.
|
||||
|
||||
case reflect.Bool:
|
||||
printBool(f.fs, v.Bool())
|
||||
|
||||
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
|
||||
printInt(f.fs, v.Int(), 10)
|
||||
|
||||
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
|
||||
printUint(f.fs, v.Uint(), 10)
|
||||
|
||||
case reflect.Float32:
|
||||
printFloat(f.fs, v.Float(), 32)
|
||||
|
||||
case reflect.Float64:
|
||||
printFloat(f.fs, v.Float(), 64)
|
||||
|
||||
case reflect.Complex64:
|
||||
printComplex(f.fs, v.Complex(), 32)
|
||||
|
||||
case reflect.Complex128:
|
||||
printComplex(f.fs, v.Complex(), 64)
|
||||
|
||||
case reflect.Slice:
|
||||
if v.IsNil() {
|
||||
f.fs.Write(nilAngleBytes)
|
||||
break
|
||||
}
|
||||
fallthrough
|
||||
|
||||
case reflect.Array:
|
||||
f.fs.Write(openBracketBytes)
|
||||
f.depth++
|
||||
if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) {
|
||||
f.fs.Write(maxShortBytes)
|
||||
} else {
|
||||
numEntries := v.Len()
|
||||
for i := 0; i < numEntries; i++ {
|
||||
if i > 0 {
|
||||
f.fs.Write(spaceBytes)
|
||||
}
|
||||
f.ignoreNextType = true
|
||||
f.format(f.unpackValue(v.Index(i)))
|
||||
}
|
||||
}
|
||||
f.depth--
|
||||
f.fs.Write(closeBracketBytes)
|
||||
|
||||
case reflect.String:
|
||||
f.fs.Write([]byte(v.String()))
|
||||
|
||||
case reflect.Interface:
|
||||
// The only time we should get here is for nil interfaces due to
|
||||
// unpackValue calls.
|
||||
if v.IsNil() {
|
||||
f.fs.Write(nilAngleBytes)
|
||||
}
|
||||
|
||||
case reflect.Ptr:
|
||||
// Do nothing. We should never get here since pointers have already
|
||||
// been handled above.
|
||||
|
||||
case reflect.Map:
|
||||
// nil maps should be indicated as different than empty maps
|
||||
if v.IsNil() {
|
||||
f.fs.Write(nilAngleBytes)
|
||||
break
|
||||
}
|
||||
|
||||
f.fs.Write(openMapBytes)
|
||||
f.depth++
|
||||
if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) {
|
||||
f.fs.Write(maxShortBytes)
|
||||
} else {
|
||||
keys := v.MapKeys()
|
||||
if f.cs.SortKeys {
|
||||
sortValues(keys, f.cs)
|
||||
}
|
||||
for i, key := range keys {
|
||||
if i > 0 {
|
||||
f.fs.Write(spaceBytes)
|
||||
}
|
||||
f.ignoreNextType = true
|
||||
f.format(f.unpackValue(key))
|
||||
f.fs.Write(colonBytes)
|
||||
f.ignoreNextType = true
|
||||
f.format(f.unpackValue(v.MapIndex(key)))
|
||||
}
|
||||
}
|
||||
f.depth--
|
||||
f.fs.Write(closeMapBytes)
|
||||
|
||||
case reflect.Struct:
|
||||
numFields := v.NumField()
|
||||
f.fs.Write(openBraceBytes)
|
||||
f.depth++
|
||||
if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) {
|
||||
f.fs.Write(maxShortBytes)
|
||||
} else {
|
||||
vt := v.Type()
|
||||
for i := 0; i < numFields; i++ {
|
||||
if i > 0 {
|
||||
f.fs.Write(spaceBytes)
|
||||
}
|
||||
vtf := vt.Field(i)
|
||||
if f.fs.Flag('+') || f.fs.Flag('#') {
|
||||
f.fs.Write([]byte(vtf.Name))
|
||||
f.fs.Write(colonBytes)
|
||||
}
|
||||
f.format(f.unpackValue(v.Field(i)))
|
||||
}
|
||||
}
|
||||
f.depth--
|
||||
f.fs.Write(closeBraceBytes)
|
||||
|
||||
case reflect.Uintptr:
|
||||
printHexPtr(f.fs, uintptr(v.Uint()))
|
||||
|
||||
case reflect.UnsafePointer, reflect.Chan, reflect.Func:
|
||||
printHexPtr(f.fs, v.Pointer())
|
||||
|
||||
// There were not any other types at the time this code was written, but
|
||||
// fall back to letting the default fmt package handle it if any get added.
|
||||
default:
|
||||
format := f.buildDefaultFormat()
|
||||
if v.CanInterface() {
|
||||
fmt.Fprintf(f.fs, format, v.Interface())
|
||||
} else {
|
||||
fmt.Fprintf(f.fs, format, v.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Format satisfies the fmt.Formatter interface. See NewFormatter for usage
|
||||
// details.
|
||||
func (f *formatState) Format(fs fmt.State, verb rune) {
|
||||
f.fs = fs
|
||||
|
||||
// Use standard formatting for verbs that are not v.
|
||||
if verb != 'v' {
|
||||
format := f.constructOrigFormat(verb)
|
||||
fmt.Fprintf(fs, format, f.value)
|
||||
return
|
||||
}
|
||||
|
||||
if f.value == nil {
|
||||
if fs.Flag('#') {
|
||||
fs.Write(interfaceBytes)
|
||||
}
|
||||
fs.Write(nilAngleBytes)
|
||||
return
|
||||
}
|
||||
|
||||
f.format(reflect.ValueOf(f.value))
|
||||
}
|
||||
|
||||
// newFormatter is a helper function to consolidate the logic from the various
|
||||
// public methods which take varying config states.
|
||||
func newFormatter(cs *ConfigState, v interface{}) fmt.Formatter {
|
||||
fs := &formatState{value: v, cs: cs}
|
||||
fs.pointers = make(map[uintptr]int)
|
||||
return fs
|
||||
}
|
||||
|
||||
/*
|
||||
NewFormatter returns a custom formatter that satisfies the fmt.Formatter
|
||||
interface. As a result, it integrates cleanly with standard fmt package
|
||||
printing functions. The formatter is useful for inline printing of smaller data
|
||||
types similar to the standard %v format specifier.
|
||||
|
||||
The custom formatter only responds to the %v (most compact), %+v (adds pointer
|
||||
addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb
|
||||
combinations. Any other verbs such as %x and %q will be sent to the the
|
||||
standard fmt package for formatting. In addition, the custom formatter ignores
|
||||
the width and precision arguments (however they will still work on the format
|
||||
specifiers not handled by the custom formatter).
|
||||
|
||||
Typically this function shouldn't be called directly. It is much easier to make
|
||||
use of the custom formatter by calling one of the convenience functions such as
|
||||
Printf, Println, or Fprintf.
|
||||
*/
|
||||
func NewFormatter(v interface{}) fmt.Formatter {
|
||||
return newFormatter(&Config, v)
|
||||
}
|
||||
1558
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/format_test.go
сгенерированный
поставляемый
Обычный файл
1558
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/format_test.go
сгенерированный
поставляемый
Обычный файл
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
87
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/internal_test.go
сгенерированный
поставляемый
Обычный файл
87
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/internal_test.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
* Copyright (c) 2013 Dave Collins <dave@davec.name>
|
||||
*
|
||||
* Permission to use, copy, modify, and distribute this software for any
|
||||
* purpose with or without fee is hereby granted, provided that the above
|
||||
* copyright notice and this permission notice appear in all copies.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
/*
|
||||
This test file is part of the spew package rather than than the spew_test
|
||||
package because it needs access to internals to properly test certain cases
|
||||
which are not possible via the public interface since they should never happen.
|
||||
*/
|
||||
|
||||
package spew
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// dummyFmtState implements a fake fmt.State to use for testing invalid
|
||||
// reflect.Value handling. This is necessary because the fmt package catches
|
||||
// invalid values before invoking the formatter on them.
|
||||
type dummyFmtState struct {
|
||||
bytes.Buffer
|
||||
}
|
||||
|
||||
func (dfs *dummyFmtState) Flag(f int) bool {
|
||||
if f == int('+') {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (dfs *dummyFmtState) Precision() (int, bool) {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func (dfs *dummyFmtState) Width() (int, bool) {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// TestInvalidReflectValue ensures the dump and formatter code handles an
|
||||
// invalid reflect value properly. This needs access to internal state since it
|
||||
// should never happen in real code and therefore can't be tested via the public
|
||||
// API.
|
||||
func TestInvalidReflectValue(t *testing.T) {
|
||||
i := 1
|
||||
|
||||
// Dump invalid reflect value.
|
||||
v := new(reflect.Value)
|
||||
buf := new(bytes.Buffer)
|
||||
d := dumpState{w: buf, cs: &Config}
|
||||
d.dump(*v)
|
||||
s := buf.String()
|
||||
want := "<invalid>"
|
||||
if s != want {
|
||||
t.Errorf("InvalidReflectValue #%d\n got: %s want: %s", i, s, want)
|
||||
}
|
||||
i++
|
||||
|
||||
// Formatter invalid reflect value.
|
||||
buf2 := new(dummyFmtState)
|
||||
f := formatState{value: *v, cs: &Config, fs: buf2}
|
||||
f.format(*v)
|
||||
s = buf2.String()
|
||||
want = "<invalid>"
|
||||
if s != want {
|
||||
t.Errorf("InvalidReflectValue #%d got: %s want: %s", i, s, want)
|
||||
}
|
||||
}
|
||||
|
||||
// SortValues makes the internal sortValues function available to the test
|
||||
// package.
|
||||
func SortValues(values []reflect.Value, cs *ConfigState) {
|
||||
sortValues(values, cs)
|
||||
}
|
||||
101
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/internalunsafe_test.go
сгенерированный
поставляемый
Обычный файл
101
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/internalunsafe_test.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,101 @@
|
||||
// Copyright (c) 2013-2015 Dave Collins <dave@davec.name>
|
||||
|
||||
// Permission to use, copy, modify, and distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
// NOTE: Due to the following build constraints, this file will only be compiled
|
||||
// when the code is not running on Google App Engine and "-tags disableunsafe"
|
||||
// is not added to the go build command line.
|
||||
// +build !appengine,!disableunsafe
|
||||
|
||||
/*
|
||||
This test file is part of the spew package rather than than the spew_test
|
||||
package because it needs access to internals to properly test certain cases
|
||||
which are not possible via the public interface since they should never happen.
|
||||
*/
|
||||
|
||||
package spew
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"reflect"
|
||||
"testing"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// changeKind uses unsafe to intentionally change the kind of a reflect.Value to
|
||||
// the maximum kind value which does not exist. This is needed to test the
|
||||
// fallback code which punts to the standard fmt library for new types that
|
||||
// might get added to the language.
|
||||
func changeKind(v *reflect.Value, readOnly bool) {
|
||||
rvf := (*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + offsetFlag))
|
||||
*rvf = *rvf | ((1<<flagKindWidth - 1) << flagKindShift)
|
||||
if readOnly {
|
||||
*rvf |= flagRO
|
||||
} else {
|
||||
*rvf &= ^uintptr(flagRO)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAddedReflectValue tests functionaly of the dump and formatter code which
|
||||
// falls back to the standard fmt library for new types that might get added to
|
||||
// the language.
|
||||
func TestAddedReflectValue(t *testing.T) {
|
||||
i := 1
|
||||
|
||||
// Dump using a reflect.Value that is exported.
|
||||
v := reflect.ValueOf(int8(5))
|
||||
changeKind(&v, false)
|
||||
buf := new(bytes.Buffer)
|
||||
d := dumpState{w: buf, cs: &Config}
|
||||
d.dump(v)
|
||||
s := buf.String()
|
||||
want := "(int8) 5"
|
||||
if s != want {
|
||||
t.Errorf("TestAddedReflectValue #%d\n got: %s want: %s", i, s, want)
|
||||
}
|
||||
i++
|
||||
|
||||
// Dump using a reflect.Value that is not exported.
|
||||
changeKind(&v, true)
|
||||
buf.Reset()
|
||||
d.dump(v)
|
||||
s = buf.String()
|
||||
want = "(int8) <int8 Value>"
|
||||
if s != want {
|
||||
t.Errorf("TestAddedReflectValue #%d\n got: %s want: %s", i, s, want)
|
||||
}
|
||||
i++
|
||||
|
||||
// Formatter using a reflect.Value that is exported.
|
||||
changeKind(&v, false)
|
||||
buf2 := new(dummyFmtState)
|
||||
f := formatState{value: v, cs: &Config, fs: buf2}
|
||||
f.format(v)
|
||||
s = buf2.String()
|
||||
want = "5"
|
||||
if s != want {
|
||||
t.Errorf("TestAddedReflectValue #%d got: %s want: %s", i, s, want)
|
||||
}
|
||||
i++
|
||||
|
||||
// Formatter using a reflect.Value that is not exported.
|
||||
changeKind(&v, true)
|
||||
buf2.Reset()
|
||||
f = formatState{value: v, cs: &Config, fs: buf2}
|
||||
f.format(v)
|
||||
s = buf2.String()
|
||||
want = "<int8 Value>"
|
||||
if s != want {
|
||||
t.Errorf("TestAddedReflectValue #%d got: %s want: %s", i, s, want)
|
||||
}
|
||||
}
|
||||
148
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/spew.go
сгенерированный
поставляемый
Обычный файл
148
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/spew.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,148 @@
|
||||
/*
|
||||
* Copyright (c) 2013 Dave Collins <dave@davec.name>
|
||||
*
|
||||
* Permission to use, copy, modify, and distribute this software for any
|
||||
* purpose with or without fee is hereby granted, provided that the above
|
||||
* copyright notice and this permission notice appear in all copies.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
package spew
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were
|
||||
// passed with a default Formatter interface returned by NewFormatter. It
|
||||
// returns the formatted string as a value that satisfies error. See
|
||||
// NewFormatter for formatting details.
|
||||
//
|
||||
// This function is shorthand for the following syntax:
|
||||
//
|
||||
// fmt.Errorf(format, spew.NewFormatter(a), spew.NewFormatter(b))
|
||||
func Errorf(format string, a ...interface{}) (err error) {
|
||||
return fmt.Errorf(format, convertArgs(a)...)
|
||||
}
|
||||
|
||||
// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were
|
||||
// passed with a default Formatter interface returned by NewFormatter. It
|
||||
// returns the number of bytes written and any write error encountered. See
|
||||
// NewFormatter for formatting details.
|
||||
//
|
||||
// This function is shorthand for the following syntax:
|
||||
//
|
||||
// fmt.Fprint(w, spew.NewFormatter(a), spew.NewFormatter(b))
|
||||
func Fprint(w io.Writer, a ...interface{}) (n int, err error) {
|
||||
return fmt.Fprint(w, convertArgs(a)...)
|
||||
}
|
||||
|
||||
// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were
|
||||
// passed with a default Formatter interface returned by NewFormatter. It
|
||||
// returns the number of bytes written and any write error encountered. See
|
||||
// NewFormatter for formatting details.
|
||||
//
|
||||
// This function is shorthand for the following syntax:
|
||||
//
|
||||
// fmt.Fprintf(w, format, spew.NewFormatter(a), spew.NewFormatter(b))
|
||||
func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
|
||||
return fmt.Fprintf(w, format, convertArgs(a)...)
|
||||
}
|
||||
|
||||
// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it
|
||||
// passed with a default Formatter interface returned by NewFormatter. See
|
||||
// NewFormatter for formatting details.
|
||||
//
|
||||
// This function is shorthand for the following syntax:
|
||||
//
|
||||
// fmt.Fprintln(w, spew.NewFormatter(a), spew.NewFormatter(b))
|
||||
func Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
|
||||
return fmt.Fprintln(w, convertArgs(a)...)
|
||||
}
|
||||
|
||||
// Print is a wrapper for fmt.Print that treats each argument as if it were
|
||||
// passed with a default Formatter interface returned by NewFormatter. It
|
||||
// returns the number of bytes written and any write error encountered. See
|
||||
// NewFormatter for formatting details.
|
||||
//
|
||||
// This function is shorthand for the following syntax:
|
||||
//
|
||||
// fmt.Print(spew.NewFormatter(a), spew.NewFormatter(b))
|
||||
func Print(a ...interface{}) (n int, err error) {
|
||||
return fmt.Print(convertArgs(a)...)
|
||||
}
|
||||
|
||||
// Printf is a wrapper for fmt.Printf that treats each argument as if it were
|
||||
// passed with a default Formatter interface returned by NewFormatter. It
|
||||
// returns the number of bytes written and any write error encountered. See
|
||||
// NewFormatter for formatting details.
|
||||
//
|
||||
// This function is shorthand for the following syntax:
|
||||
//
|
||||
// fmt.Printf(format, spew.NewFormatter(a), spew.NewFormatter(b))
|
||||
func Printf(format string, a ...interface{}) (n int, err error) {
|
||||
return fmt.Printf(format, convertArgs(a)...)
|
||||
}
|
||||
|
||||
// Println is a wrapper for fmt.Println that treats each argument as if it were
|
||||
// passed with a default Formatter interface returned by NewFormatter. It
|
||||
// returns the number of bytes written and any write error encountered. See
|
||||
// NewFormatter for formatting details.
|
||||
//
|
||||
// This function is shorthand for the following syntax:
|
||||
//
|
||||
// fmt.Println(spew.NewFormatter(a), spew.NewFormatter(b))
|
||||
func Println(a ...interface{}) (n int, err error) {
|
||||
return fmt.Println(convertArgs(a)...)
|
||||
}
|
||||
|
||||
// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were
|
||||
// passed with a default Formatter interface returned by NewFormatter. It
|
||||
// returns the resulting string. See NewFormatter for formatting details.
|
||||
//
|
||||
// This function is shorthand for the following syntax:
|
||||
//
|
||||
// fmt.Sprint(spew.NewFormatter(a), spew.NewFormatter(b))
|
||||
func Sprint(a ...interface{}) string {
|
||||
return fmt.Sprint(convertArgs(a)...)
|
||||
}
|
||||
|
||||
// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were
|
||||
// passed with a default Formatter interface returned by NewFormatter. It
|
||||
// returns the resulting string. See NewFormatter for formatting details.
|
||||
//
|
||||
// This function is shorthand for the following syntax:
|
||||
//
|
||||
// fmt.Sprintf(format, spew.NewFormatter(a), spew.NewFormatter(b))
|
||||
func Sprintf(format string, a ...interface{}) string {
|
||||
return fmt.Sprintf(format, convertArgs(a)...)
|
||||
}
|
||||
|
||||
// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it
|
||||
// were passed with a default Formatter interface returned by NewFormatter. It
|
||||
// returns the resulting string. See NewFormatter for formatting details.
|
||||
//
|
||||
// This function is shorthand for the following syntax:
|
||||
//
|
||||
// fmt.Sprintln(spew.NewFormatter(a), spew.NewFormatter(b))
|
||||
func Sprintln(a ...interface{}) string {
|
||||
return fmt.Sprintln(convertArgs(a)...)
|
||||
}
|
||||
|
||||
// convertArgs accepts a slice of arguments and returns a slice of the same
|
||||
// length with each argument converted to a default spew Formatter interface.
|
||||
func convertArgs(args []interface{}) (formatters []interface{}) {
|
||||
formatters = make([]interface{}, len(args))
|
||||
for index, arg := range args {
|
||||
formatters[index] = NewFormatter(arg)
|
||||
}
|
||||
return formatters
|
||||
}
|
||||
309
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/spew_test.go
сгенерированный
поставляемый
Обычный файл
309
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/spew_test.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,309 @@
|
||||
/*
|
||||
* Copyright (c) 2013 Dave Collins <dave@davec.name>
|
||||
*
|
||||
* Permission to use, copy, modify, and distribute this software for any
|
||||
* purpose with or without fee is hereby granted, provided that the above
|
||||
* copyright notice and this permission notice appear in all copies.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
package spew_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/mattermost/platform/Godeps/_workspace/src/github.com/davecgh/go-spew/spew"
|
||||
)
|
||||
|
||||
// spewFunc is used to identify which public function of the spew package or
|
||||
// ConfigState a test applies to.
|
||||
type spewFunc int
|
||||
|
||||
const (
|
||||
fCSFdump spewFunc = iota
|
||||
fCSFprint
|
||||
fCSFprintf
|
||||
fCSFprintln
|
||||
fCSPrint
|
||||
fCSPrintln
|
||||
fCSSdump
|
||||
fCSSprint
|
||||
fCSSprintf
|
||||
fCSSprintln
|
||||
fCSErrorf
|
||||
fCSNewFormatter
|
||||
fErrorf
|
||||
fFprint
|
||||
fFprintln
|
||||
fPrint
|
||||
fPrintln
|
||||
fSdump
|
||||
fSprint
|
||||
fSprintf
|
||||
fSprintln
|
||||
)
|
||||
|
||||
// Map of spewFunc values to names for pretty printing.
|
||||
var spewFuncStrings = map[spewFunc]string{
|
||||
fCSFdump: "ConfigState.Fdump",
|
||||
fCSFprint: "ConfigState.Fprint",
|
||||
fCSFprintf: "ConfigState.Fprintf",
|
||||
fCSFprintln: "ConfigState.Fprintln",
|
||||
fCSSdump: "ConfigState.Sdump",
|
||||
fCSPrint: "ConfigState.Print",
|
||||
fCSPrintln: "ConfigState.Println",
|
||||
fCSSprint: "ConfigState.Sprint",
|
||||
fCSSprintf: "ConfigState.Sprintf",
|
||||
fCSSprintln: "ConfigState.Sprintln",
|
||||
fCSErrorf: "ConfigState.Errorf",
|
||||
fCSNewFormatter: "ConfigState.NewFormatter",
|
||||
fErrorf: "spew.Errorf",
|
||||
fFprint: "spew.Fprint",
|
||||
fFprintln: "spew.Fprintln",
|
||||
fPrint: "spew.Print",
|
||||
fPrintln: "spew.Println",
|
||||
fSdump: "spew.Sdump",
|
||||
fSprint: "spew.Sprint",
|
||||
fSprintf: "spew.Sprintf",
|
||||
fSprintln: "spew.Sprintln",
|
||||
}
|
||||
|
||||
func (f spewFunc) String() string {
|
||||
if s, ok := spewFuncStrings[f]; ok {
|
||||
return s
|
||||
}
|
||||
return fmt.Sprintf("Unknown spewFunc (%d)", int(f))
|
||||
}
|
||||
|
||||
// spewTest is used to describe a test to be performed against the public
|
||||
// functions of the spew package or ConfigState.
|
||||
type spewTest struct {
|
||||
cs *spew.ConfigState
|
||||
f spewFunc
|
||||
format string
|
||||
in interface{}
|
||||
want string
|
||||
}
|
||||
|
||||
// spewTests houses the tests to be performed against the public functions of
|
||||
// the spew package and ConfigState.
|
||||
//
|
||||
// These tests are only intended to ensure the public functions are exercised
|
||||
// and are intentionally not exhaustive of types. The exhaustive type
|
||||
// tests are handled in the dump and format tests.
|
||||
var spewTests []spewTest
|
||||
|
||||
// redirStdout is a helper function to return the standard output from f as a
|
||||
// byte slice.
|
||||
func redirStdout(f func()) ([]byte, error) {
|
||||
tempFile, err := ioutil.TempFile("", "ss-test")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fileName := tempFile.Name()
|
||||
defer os.Remove(fileName) // Ignore error
|
||||
|
||||
origStdout := os.Stdout
|
||||
os.Stdout = tempFile
|
||||
f()
|
||||
os.Stdout = origStdout
|
||||
tempFile.Close()
|
||||
|
||||
return ioutil.ReadFile(fileName)
|
||||
}
|
||||
|
||||
func initSpewTests() {
|
||||
// Config states with various settings.
|
||||
scsDefault := spew.NewDefaultConfig()
|
||||
scsNoMethods := &spew.ConfigState{Indent: " ", DisableMethods: true}
|
||||
scsNoPmethods := &spew.ConfigState{Indent: " ", DisablePointerMethods: true}
|
||||
scsMaxDepth := &spew.ConfigState{Indent: " ", MaxDepth: 1}
|
||||
scsContinue := &spew.ConfigState{Indent: " ", ContinueOnMethod: true}
|
||||
|
||||
// Variables for tests on types which implement Stringer interface with and
|
||||
// without a pointer receiver.
|
||||
ts := stringer("test")
|
||||
tps := pstringer("test")
|
||||
|
||||
// depthTester is used to test max depth handling for structs, array, slices
|
||||
// and maps.
|
||||
type depthTester struct {
|
||||
ic indirCir1
|
||||
arr [1]string
|
||||
slice []string
|
||||
m map[string]int
|
||||
}
|
||||
dt := depthTester{indirCir1{nil}, [1]string{"arr"}, []string{"slice"},
|
||||
map[string]int{"one": 1}}
|
||||
|
||||
// Variable for tests on types which implement error interface.
|
||||
te := customError(10)
|
||||
|
||||
spewTests = []spewTest{
|
||||
{scsDefault, fCSFdump, "", int8(127), "(int8) 127\n"},
|
||||
{scsDefault, fCSFprint, "", int16(32767), "32767"},
|
||||
{scsDefault, fCSFprintf, "%v", int32(2147483647), "2147483647"},
|
||||
{scsDefault, fCSFprintln, "", int(2147483647), "2147483647\n"},
|
||||
{scsDefault, fCSPrint, "", int64(9223372036854775807), "9223372036854775807"},
|
||||
{scsDefault, fCSPrintln, "", uint8(255), "255\n"},
|
||||
{scsDefault, fCSSdump, "", uint8(64), "(uint8) 64\n"},
|
||||
{scsDefault, fCSSprint, "", complex(1, 2), "(1+2i)"},
|
||||
{scsDefault, fCSSprintf, "%v", complex(float32(3), 4), "(3+4i)"},
|
||||
{scsDefault, fCSSprintln, "", complex(float64(5), 6), "(5+6i)\n"},
|
||||
{scsDefault, fCSErrorf, "%#v", uint16(65535), "(uint16)65535"},
|
||||
{scsDefault, fCSNewFormatter, "%v", uint32(4294967295), "4294967295"},
|
||||
{scsDefault, fErrorf, "%v", uint64(18446744073709551615), "18446744073709551615"},
|
||||
{scsDefault, fFprint, "", float32(3.14), "3.14"},
|
||||
{scsDefault, fFprintln, "", float64(6.28), "6.28\n"},
|
||||
{scsDefault, fPrint, "", true, "true"},
|
||||
{scsDefault, fPrintln, "", false, "false\n"},
|
||||
{scsDefault, fSdump, "", complex(-10, -20), "(complex128) (-10-20i)\n"},
|
||||
{scsDefault, fSprint, "", complex(-1, -2), "(-1-2i)"},
|
||||
{scsDefault, fSprintf, "%v", complex(float32(-3), -4), "(-3-4i)"},
|
||||
{scsDefault, fSprintln, "", complex(float64(-5), -6), "(-5-6i)\n"},
|
||||
{scsNoMethods, fCSFprint, "", ts, "test"},
|
||||
{scsNoMethods, fCSFprint, "", &ts, "<*>test"},
|
||||
{scsNoMethods, fCSFprint, "", tps, "test"},
|
||||
{scsNoMethods, fCSFprint, "", &tps, "<*>test"},
|
||||
{scsNoPmethods, fCSFprint, "", ts, "stringer test"},
|
||||
{scsNoPmethods, fCSFprint, "", &ts, "<*>stringer test"},
|
||||
{scsNoPmethods, fCSFprint, "", tps, "test"},
|
||||
{scsNoPmethods, fCSFprint, "", &tps, "<*>stringer test"},
|
||||
{scsMaxDepth, fCSFprint, "", dt, "{{<max>} [<max>] [<max>] map[<max>]}"},
|
||||
{scsMaxDepth, fCSFdump, "", dt, "(spew_test.depthTester) {\n" +
|
||||
" ic: (spew_test.indirCir1) {\n <max depth reached>\n },\n" +
|
||||
" arr: ([1]string) (len=1 cap=1) {\n <max depth reached>\n },\n" +
|
||||
" slice: ([]string) (len=1 cap=1) {\n <max depth reached>\n },\n" +
|
||||
" m: (map[string]int) (len=1) {\n <max depth reached>\n }\n}\n"},
|
||||
{scsContinue, fCSFprint, "", ts, "(stringer test) test"},
|
||||
{scsContinue, fCSFdump, "", ts, "(spew_test.stringer) " +
|
||||
"(len=4) (stringer test) \"test\"\n"},
|
||||
{scsContinue, fCSFprint, "", te, "(error: 10) 10"},
|
||||
{scsContinue, fCSFdump, "", te, "(spew_test.customError) " +
|
||||
"(error: 10) 10\n"},
|
||||
}
|
||||
}
|
||||
|
||||
// TestSpew executes all of the tests described by spewTests.
|
||||
func TestSpew(t *testing.T) {
|
||||
initSpewTests()
|
||||
|
||||
t.Logf("Running %d tests", len(spewTests))
|
||||
for i, test := range spewTests {
|
||||
buf := new(bytes.Buffer)
|
||||
switch test.f {
|
||||
case fCSFdump:
|
||||
test.cs.Fdump(buf, test.in)
|
||||
|
||||
case fCSFprint:
|
||||
test.cs.Fprint(buf, test.in)
|
||||
|
||||
case fCSFprintf:
|
||||
test.cs.Fprintf(buf, test.format, test.in)
|
||||
|
||||
case fCSFprintln:
|
||||
test.cs.Fprintln(buf, test.in)
|
||||
|
||||
case fCSPrint:
|
||||
b, err := redirStdout(func() { test.cs.Print(test.in) })
|
||||
if err != nil {
|
||||
t.Errorf("%v #%d %v", test.f, i, err)
|
||||
continue
|
||||
}
|
||||
buf.Write(b)
|
||||
|
||||
case fCSPrintln:
|
||||
b, err := redirStdout(func() { test.cs.Println(test.in) })
|
||||
if err != nil {
|
||||
t.Errorf("%v #%d %v", test.f, i, err)
|
||||
continue
|
||||
}
|
||||
buf.Write(b)
|
||||
|
||||
case fCSSdump:
|
||||
str := test.cs.Sdump(test.in)
|
||||
buf.WriteString(str)
|
||||
|
||||
case fCSSprint:
|
||||
str := test.cs.Sprint(test.in)
|
||||
buf.WriteString(str)
|
||||
|
||||
case fCSSprintf:
|
||||
str := test.cs.Sprintf(test.format, test.in)
|
||||
buf.WriteString(str)
|
||||
|
||||
case fCSSprintln:
|
||||
str := test.cs.Sprintln(test.in)
|
||||
buf.WriteString(str)
|
||||
|
||||
case fCSErrorf:
|
||||
err := test.cs.Errorf(test.format, test.in)
|
||||
buf.WriteString(err.Error())
|
||||
|
||||
case fCSNewFormatter:
|
||||
fmt.Fprintf(buf, test.format, test.cs.NewFormatter(test.in))
|
||||
|
||||
case fErrorf:
|
||||
err := spew.Errorf(test.format, test.in)
|
||||
buf.WriteString(err.Error())
|
||||
|
||||
case fFprint:
|
||||
spew.Fprint(buf, test.in)
|
||||
|
||||
case fFprintln:
|
||||
spew.Fprintln(buf, test.in)
|
||||
|
||||
case fPrint:
|
||||
b, err := redirStdout(func() { spew.Print(test.in) })
|
||||
if err != nil {
|
||||
t.Errorf("%v #%d %v", test.f, i, err)
|
||||
continue
|
||||
}
|
||||
buf.Write(b)
|
||||
|
||||
case fPrintln:
|
||||
b, err := redirStdout(func() { spew.Println(test.in) })
|
||||
if err != nil {
|
||||
t.Errorf("%v #%d %v", test.f, i, err)
|
||||
continue
|
||||
}
|
||||
buf.Write(b)
|
||||
|
||||
case fSdump:
|
||||
str := spew.Sdump(test.in)
|
||||
buf.WriteString(str)
|
||||
|
||||
case fSprint:
|
||||
str := spew.Sprint(test.in)
|
||||
buf.WriteString(str)
|
||||
|
||||
case fSprintf:
|
||||
str := spew.Sprintf(test.format, test.in)
|
||||
buf.WriteString(str)
|
||||
|
||||
case fSprintln:
|
||||
str := spew.Sprintln(test.in)
|
||||
buf.WriteString(str)
|
||||
|
||||
default:
|
||||
t.Errorf("%v #%d unrecognized function", test.f, i)
|
||||
continue
|
||||
}
|
||||
s := buf.String()
|
||||
if test.want != s {
|
||||
t.Errorf("ConfigState #%d\n got: %s want: %s", i, s, test.want)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
82
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go
сгенерированный
поставляемый
Обычный файл
82
Godeps/_workspace/src/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,82 @@
|
||||
// Copyright (c) 2013 Dave Collins <dave@davec.name>
|
||||
//
|
||||
// Permission to use, copy, modify, and distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
// NOTE: Due to the following build constraints, this file will only be compiled
|
||||
// when both cgo is supported and "-tags testcgo" is added to the go test
|
||||
// command line. This code should really only be in the dumpcgo_test.go file,
|
||||
// but unfortunately Go will not allow cgo in test files, so this is a
|
||||
// workaround to allow cgo types to be tested. This configuration is used
|
||||
// because spew itself does not require cgo to run even though it does handle
|
||||
// certain cgo types specially. Rather than forcing all clients to require cgo
|
||||
// and an external C compiler just to run the tests, this scheme makes them
|
||||
// optional.
|
||||
// +build cgo,testcgo
|
||||
|
||||
package testdata
|
||||
|
||||
/*
|
||||
#include <stdint.h>
|
||||
typedef unsigned char custom_uchar_t;
|
||||
|
||||
char *ncp = 0;
|
||||
char *cp = "test";
|
||||
char ca[6] = {'t', 'e', 's', 't', '2', '\0'};
|
||||
unsigned char uca[6] = {'t', 'e', 's', 't', '3', '\0'};
|
||||
signed char sca[6] = {'t', 'e', 's', 't', '4', '\0'};
|
||||
uint8_t ui8ta[6] = {'t', 'e', 's', 't', '5', '\0'};
|
||||
custom_uchar_t tuca[6] = {'t', 'e', 's', 't', '6', '\0'};
|
||||
*/
|
||||
import "C"
|
||||
|
||||
// GetCgoNullCharPointer returns a null char pointer via cgo. This is only
|
||||
// used for tests.
|
||||
func GetCgoNullCharPointer() interface{} {
|
||||
return C.ncp
|
||||
}
|
||||
|
||||
// GetCgoCharPointer returns a char pointer via cgo. This is only used for
|
||||
// tests.
|
||||
func GetCgoCharPointer() interface{} {
|
||||
return C.cp
|
||||
}
|
||||
|
||||
// GetCgoCharArray returns a char array via cgo and the array's len and cap.
|
||||
// This is only used for tests.
|
||||
func GetCgoCharArray() (interface{}, int, int) {
|
||||
return C.ca, len(C.ca), cap(C.ca)
|
||||
}
|
||||
|
||||
// GetCgoUnsignedCharArray returns an unsigned char array via cgo and the
|
||||
// array's len and cap. This is only used for tests.
|
||||
func GetCgoUnsignedCharArray() (interface{}, int, int) {
|
||||
return C.uca, len(C.uca), cap(C.uca)
|
||||
}
|
||||
|
||||
// GetCgoSignedCharArray returns a signed char array via cgo and the array's len
|
||||
// and cap. This is only used for tests.
|
||||
func GetCgoSignedCharArray() (interface{}, int, int) {
|
||||
return C.sca, len(C.sca), cap(C.sca)
|
||||
}
|
||||
|
||||
// GetCgoUint8tArray returns a uint8_t array via cgo and the array's len and
|
||||
// cap. This is only used for tests.
|
||||
func GetCgoUint8tArray() (interface{}, int, int) {
|
||||
return C.ui8ta, len(C.ui8ta), cap(C.ui8ta)
|
||||
}
|
||||
|
||||
// GetCgoTypdefedUnsignedCharArray returns a typedefed unsigned char array via
|
||||
// cgo and the array's len and cap. This is only used for tests.
|
||||
func GetCgoTypdefedUnsignedCharArray() (interface{}, int, int) {
|
||||
return C.tuca, len(C.tuca), cap(C.tuca)
|
||||
}
|
||||
38
Godeps/_workspace/src/github.com/disintegration/imaging/README.md
сгенерированный
поставляемый
38
Godeps/_workspace/src/github.com/disintegration/imaging/README.md
сгенерированный
поставляемый
@@ -32,8 +32,8 @@ dstImage800 := imaging.Resize(srcImage, 800, 0, imaging.Lanczos)
|
||||
// scale down srcImage to fit the 800x600px bounding box
|
||||
dstImageFit := imaging.Fit(srcImage, 800, 600, imaging.Lanczos)
|
||||
|
||||
// resize and crop the srcImage to make a 100x100px thumbnail
|
||||
dstImageThumb := imaging.Thumbnail(srcImage, 100, 100, imaging.Lanczos)
|
||||
// resize and crop the srcImage to fill the 100x100px area
|
||||
dstImageFill := imaging.Fill(srcImage, 100, 100, imaging.Center, imaging.Lanczos)
|
||||
```
|
||||
|
||||
Imaging supports image resizing using various resampling filters. The most notable ones:
|
||||
@@ -63,6 +63,40 @@ Filter | Resize result
|
||||
`imaging.Gaussian` | 
|
||||
`imaging.Lanczos` | 
|
||||
|
||||
**Resize functions comparison**
|
||||
|
||||
Original image:
|
||||
|
||||

|
||||
|
||||
Resize the image to width=100px and height=100px:
|
||||
|
||||
```go
|
||||
dstImage := imaging.Resize(srcImage, 100, 100, imaging.Lanczos)
|
||||
```
|
||||

|
||||
|
||||
Resize the image to width=100px preserving the aspect ratio:
|
||||
|
||||
```go
|
||||
dstImage := imaging.Resize(srcImage, 100, 0, imaging.Lanczos)
|
||||
```
|
||||

|
||||
|
||||
Resize the image to fit the 100x100px boundng box preserving the aspect ratio:
|
||||
|
||||
```go
|
||||
dstImage := imaging.Fit(srcImage, 100, 100, imaging.Lanczos)
|
||||
```
|
||||

|
||||
|
||||
Resize and crop the image with a center anchor point to fill the 100x100px area:
|
||||
|
||||
```go
|
||||
dstImage := imaging.Fill(srcImage, 100, 100, imaging.Center, imaging.Lanczos)
|
||||
```
|
||||

|
||||
|
||||
### Gaussian Blur
|
||||
```go
|
||||
dstImage := imaging.Blur(srcImage, 0.5)
|
||||
|
||||
504
Godeps/_workspace/src/github.com/disintegration/imaging/adjust_test.go
сгенерированный
поставляемый
Обычный файл
504
Godeps/_workspace/src/github.com/disintegration/imaging/adjust_test.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,504 @@
|
||||
package imaging
|
||||
|
||||
import (
|
||||
"image"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGrayscale(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Grayscale 3x3",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x3d, 0x3d, 0x3d, 0x01, 0x78, 0x78, 0x78, 0x02, 0x17, 0x17, 0x17, 0x03,
|
||||
0x1f, 0x1f, 0x1f, 0xff, 0x25, 0x25, 0x25, 0xff, 0x66, 0x66, 0x66, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := Grayscale(d.src)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvert(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Invert 3x3",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x33, 0xff, 0xff, 0x01, 0xff, 0x33, 0xff, 0x02, 0xff, 0xff, 0x33, 0x03,
|
||||
0xee, 0xdd, 0xcc, 0xff, 0xcc, 0xdd, 0xee, 0xff, 0x55, 0xcc, 0x44, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xcc, 0xcc, 0xcc, 0xff, 0x00, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := Invert(d.src)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdjustContrast(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
p float64
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"AdjustContrast 3x3 10",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
10,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xd5, 0x00, 0x00, 0x01, 0x00, 0xd5, 0x00, 0x02, 0x00, 0x00, 0xd5, 0x03,
|
||||
0x05, 0x18, 0x2b, 0xff, 0x2b, 0x18, 0x05, 0xff, 0xaf, 0x2b, 0xc2, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x2b, 0x2b, 0x2b, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"AdjustContrast 3x3 100",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
100,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xff, 0x00, 0x00, 0x01, 0x00, 0xff, 0x00, 0x02, 0x00, 0x00, 0xff, 0x03,
|
||||
0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0xff, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"AdjustContrast 3x3 -10",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
-10,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xc4, 0x0d, 0x0d, 0x01, 0x0d, 0xc4, 0x0d, 0x02, 0x0d, 0x0d, 0xc4, 0x03,
|
||||
0x1c, 0x2b, 0x3b, 0xff, 0x3b, 0x2b, 0x1c, 0xff, 0xa6, 0x3b, 0xb5, 0xff,
|
||||
0x0d, 0x0d, 0x0d, 0xff, 0x3b, 0x3b, 0x3b, 0xff, 0xf2, 0xf2, 0xf2, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"AdjustContrast 3x3 -100",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
-100,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x80, 0x80, 0x80, 0x01, 0x80, 0x80, 0x80, 0x02, 0x80, 0x80, 0x80, 0x03,
|
||||
0x80, 0x80, 0x80, 0xff, 0x80, 0x80, 0x80, 0xff, 0x80, 0x80, 0x80, 0xff,
|
||||
0x80, 0x80, 0x80, 0xff, 0x80, 0x80, 0x80, 0xff, 0x80, 0x80, 0x80, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"AdjustContrast 3x3 0",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
0,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := AdjustContrast(d.src, d.p)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdjustBrightness(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
p float64
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"AdjustBrightness 3x3 10",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
10,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xe6, 0x1a, 0x1a, 0x01, 0x1a, 0xe6, 0x1a, 0x02, 0x1a, 0x1a, 0xe6, 0x03,
|
||||
0x2b, 0x3c, 0x4d, 0xff, 0x4d, 0x3c, 0x2b, 0xff, 0xc4, 0x4d, 0xd5, 0xff,
|
||||
0x1a, 0x1a, 0x1a, 0xff, 0x4d, 0x4d, 0x4d, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"AdjustBrightness 3x3 100",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
100,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xff, 0xff, 0xff, 0x01, 0xff, 0xff, 0xff, 0x02, 0xff, 0xff, 0xff, 0x03,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"AdjustBrightness 3x3 -10",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
-10,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xb3, 0x00, 0x00, 0x01, 0x00, 0xb3, 0x00, 0x02, 0x00, 0x00, 0xb3, 0x03,
|
||||
0x00, 0x09, 0x1a, 0xff, 0x1a, 0x09, 0x00, 0xff, 0x91, 0x1a, 0xa2, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x1a, 0x1a, 0x1a, 0xff, 0xe6, 0xe6, 0xe6, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"AdjustBrightness 3x3 -100",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
-100,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03,
|
||||
0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"AdjustBrightness 3x3 0",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
0,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := AdjustBrightness(d.src, d.p)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdjustGamma(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
p float64
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"AdjustGamma 3x3 0.75",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
0.75,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xbd, 0x00, 0x00, 0x01, 0x00, 0xbd, 0x00, 0x02, 0x00, 0x00, 0xbd, 0x03,
|
||||
0x07, 0x11, 0x1e, 0xff, 0x1e, 0x11, 0x07, 0xff, 0x95, 0x1e, 0xa9, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x1e, 0x1e, 0x1e, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"AdjustGamma 3x3 1.5",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
1.5,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xdc, 0x00, 0x00, 0x01, 0x00, 0xdc, 0x00, 0x02, 0x00, 0x00, 0xdc, 0x03,
|
||||
0x2a, 0x43, 0x57, 0xff, 0x57, 0x43, 0x2a, 0xff, 0xc3, 0x57, 0xcf, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x57, 0x57, 0x57, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"AdjustGamma 3x3 1.0",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
1.0,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := AdjustGamma(d.src, d.p)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdjustSigmoid(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
m float64
|
||||
p float64
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"AdjustSigmoid 3x3 0.5 3.0",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
0.5,
|
||||
3.0,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xd4, 0x00, 0x00, 0x01, 0x00, 0xd4, 0x00, 0x02, 0x00, 0x00, 0xd4, 0x03,
|
||||
0x0d, 0x1b, 0x2b, 0xff, 0x2b, 0x1b, 0x0d, 0xff, 0xb1, 0x2b, 0xc3, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x2b, 0x2b, 0x2b, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"AdjustSigmoid 3x3 0.5 -3.0",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
0.5,
|
||||
-3.0,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xc4, 0x00, 0x00, 0x01, 0x00, 0xc4, 0x00, 0x02, 0x00, 0x00, 0xc4, 0x03,
|
||||
0x16, 0x2a, 0x3b, 0xff, 0x3b, 0x2a, 0x16, 0xff, 0xa4, 0x3b, 0xb3, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x3b, 0x3b, 0x3b, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"AdjustSigmoid 3x3 0.5 0.0",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
0.5,
|
||||
0.0,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0x00, 0x00, 0x01, 0x00, 0xcc, 0x00, 0x02, 0x00, 0x00, 0xcc, 0x03,
|
||||
0x11, 0x22, 0x33, 0xff, 0x33, 0x22, 0x11, 0xff, 0xaa, 0x33, 0xbb, 0xff,
|
||||
0x00, 0x00, 0x00, 0xff, 0x33, 0x33, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := AdjustSigmoid(d.src, d.m, d.p)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
128
Godeps/_workspace/src/github.com/disintegration/imaging/effects_test.go
сгенерированный
поставляемый
Обычный файл
128
Godeps/_workspace/src/github.com/disintegration/imaging/effects_test.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,128 @@
|
||||
package imaging
|
||||
|
||||
import (
|
||||
"image"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBlur(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
sigma float64
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Blur 3x3 0.5",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x66, 0xaa, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
},
|
||||
},
|
||||
0.5,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x01, 0x02, 0x04, 0x04, 0x0a, 0x10, 0x18, 0x18, 0x01, 0x02, 0x04, 0x04,
|
||||
0x09, 0x10, 0x18, 0x18, 0x3f, 0x69, 0x9e, 0x9e, 0x09, 0x10, 0x18, 0x18,
|
||||
0x01, 0x02, 0x04, 0x04, 0x0a, 0x10, 0x18, 0x18, 0x01, 0x02, 0x04, 0x04,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
"Blur 3x3 10",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x66, 0xaa, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
},
|
||||
},
|
||||
10,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x0b, 0x13, 0x1c, 0x1c, 0x0b, 0x13, 0x1c, 0x1c, 0x0b, 0x13, 0x1c, 0x1c,
|
||||
0x0b, 0x13, 0x1c, 0x1c, 0x0b, 0x13, 0x1c, 0x1c, 0x0b, 0x13, 0x1c, 0x1c,
|
||||
0x0b, 0x13, 0x1c, 0x1c, 0x0b, 0x13, 0x1c, 0x1c, 0x0b, 0x13, 0x1c, 0x1c,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := Blur(d.src, d.sigma)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSharpen(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
sigma float64
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Sharpen 3x3 0.5",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
|
||||
0x66, 0x66, 0x66, 0x66, 0x77, 0x77, 0x77, 0x77, 0x66, 0x66, 0x66, 0x66,
|
||||
0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
|
||||
},
|
||||
},
|
||||
0.5,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x66, 0x66, 0x66, 0x66, 0x64, 0x64, 0x64, 0x64, 0x66, 0x66, 0x66, 0x66,
|
||||
0x64, 0x64, 0x64, 0x64, 0x7e, 0x7e, 0x7e, 0x7e, 0x64, 0x64, 0x64, 0x64,
|
||||
0x66, 0x66, 0x66, 0x66, 0x64, 0x64, 0x64, 0x64, 0x66, 0x66, 0x66, 0x66},
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
"Sharpen 3x3 10",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
|
||||
0x66, 0x66, 0x66, 0x66, 0x77, 0x77, 0x77, 0x77, 0x66, 0x66, 0x66, 0x66,
|
||||
0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66},
|
||||
},
|
||||
100,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 3),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64,
|
||||
0x64, 0x64, 0x64, 0x64, 0x86, 0x86, 0x86, 0x86, 0x64, 0x64, 0x64, 0x64,
|
||||
0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := Sharpen(d.src, d.sigma)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
24
Godeps/_workspace/src/github.com/disintegration/imaging/helpers.go
сгенерированный
поставляемый
24
Godeps/_workspace/src/github.com/disintegration/imaging/helpers.go
сгенерированный
поставляемый
@@ -20,8 +20,8 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/image/bmp"
|
||||
"golang.org/x/image/tiff"
|
||||
"github.com/mattermost/platform/Godeps/_workspace/src/golang.org/x/image/bmp"
|
||||
"github.com/mattermost/platform/Godeps/_workspace/src/golang.org/x/image/tiff"
|
||||
)
|
||||
|
||||
type Format int
|
||||
@@ -226,9 +226,13 @@ func Clone(img image.Image) *image.NRGBA {
|
||||
dst.Pix[di+1] = src.Pix[si+1]
|
||||
dst.Pix[di+2] = src.Pix[si+2]
|
||||
default:
|
||||
dst.Pix[di+0] = uint8(uint16(src.Pix[si+0]) * 0xff / uint16(a))
|
||||
dst.Pix[di+1] = uint8(uint16(src.Pix[si+1]) * 0xff / uint16(a))
|
||||
dst.Pix[di+2] = uint8(uint16(src.Pix[si+2]) * 0xff / uint16(a))
|
||||
var tmp uint16
|
||||
tmp = uint16(src.Pix[si+0]) * 0xff / uint16(a)
|
||||
dst.Pix[di+0] = uint8(tmp)
|
||||
tmp = uint16(src.Pix[si+1]) * 0xff / uint16(a)
|
||||
dst.Pix[di+1] = uint8(tmp)
|
||||
tmp = uint16(src.Pix[si+2]) * 0xff / uint16(a)
|
||||
dst.Pix[di+2] = uint8(tmp)
|
||||
}
|
||||
|
||||
di += 4
|
||||
@@ -257,9 +261,13 @@ func Clone(img image.Image) *image.NRGBA {
|
||||
dst.Pix[di+1] = src.Pix[si+2]
|
||||
dst.Pix[di+2] = src.Pix[si+4]
|
||||
default:
|
||||
dst.Pix[di+0] = uint8(uint16(src.Pix[si+0]) * 0xff / uint16(a))
|
||||
dst.Pix[di+1] = uint8(uint16(src.Pix[si+2]) * 0xff / uint16(a))
|
||||
dst.Pix[di+2] = uint8(uint16(src.Pix[si+4]) * 0xff / uint16(a))
|
||||
var tmp uint16
|
||||
tmp = uint16(src.Pix[si+0]) * 0xff / uint16(a)
|
||||
dst.Pix[di+0] = uint8(tmp)
|
||||
tmp = uint16(src.Pix[si+2]) * 0xff / uint16(a)
|
||||
dst.Pix[di+1] = uint8(tmp)
|
||||
tmp = uint16(src.Pix[si+4]) * 0xff / uint16(a)
|
||||
dst.Pix[di+2] = uint8(tmp)
|
||||
}
|
||||
|
||||
di += 4
|
||||
|
||||
361
Godeps/_workspace/src/github.com/disintegration/imaging/helpers_test.go
сгенерированный
поставляемый
Обычный файл
361
Godeps/_workspace/src/github.com/disintegration/imaging/helpers_test.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,361 @@
|
||||
package imaging
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
"image/color"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func compareNRGBA(img1, img2 *image.NRGBA, delta int) bool {
|
||||
if !img1.Rect.Eq(img2.Rect) {
|
||||
return false
|
||||
}
|
||||
|
||||
if len(img1.Pix) != len(img2.Pix) {
|
||||
return false
|
||||
}
|
||||
|
||||
for i := 0; i < len(img1.Pix); i++ {
|
||||
if absint(int(img1.Pix[i])-int(img2.Pix[i])) > delta {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func TestEncodeDecode(t *testing.T) {
|
||||
imgWithAlpha := image.NewNRGBA(image.Rect(0, 0, 3, 3))
|
||||
imgWithAlpha.Pix = []uint8{
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
|
||||
127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138,
|
||||
244, 245, 246, 247, 248, 249, 250, 252, 252, 253, 254, 255,
|
||||
}
|
||||
|
||||
imgWithoutAlpha := image.NewNRGBA(image.Rect(0, 0, 3, 3))
|
||||
imgWithoutAlpha.Pix = []uint8{
|
||||
0, 1, 2, 255, 4, 5, 6, 255, 8, 9, 10, 255,
|
||||
127, 128, 129, 255, 131, 132, 133, 255, 135, 136, 137, 255,
|
||||
244, 245, 246, 255, 248, 249, 250, 255, 252, 253, 254, 255,
|
||||
}
|
||||
|
||||
for _, format := range []Format{JPEG, PNG, GIF, BMP, TIFF} {
|
||||
img := imgWithoutAlpha
|
||||
if format == PNG {
|
||||
img = imgWithAlpha
|
||||
}
|
||||
|
||||
buf := &bytes.Buffer{}
|
||||
err := Encode(buf, img, format)
|
||||
if err != nil {
|
||||
t.Errorf("fail encoding format %s", format)
|
||||
continue
|
||||
}
|
||||
|
||||
img2, err := Decode(buf)
|
||||
if err != nil {
|
||||
t.Errorf("fail decoding format %s", format)
|
||||
continue
|
||||
}
|
||||
img2cloned := Clone(img2)
|
||||
|
||||
delta := 0
|
||||
if format == JPEG {
|
||||
delta = 3
|
||||
} else if format == GIF {
|
||||
delta = 16
|
||||
}
|
||||
|
||||
if !compareNRGBA(img, img2cloned, delta) {
|
||||
t.Errorf("test [DecodeEncode %s] failed: %#v %#v", format, img, img2cloned)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
buf := &bytes.Buffer{}
|
||||
err := Encode(buf, imgWithAlpha, Format(100))
|
||||
if err != ErrUnsupportedFormat {
|
||||
t.Errorf("expected ErrUnsupportedFormat")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNew(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
w, h int
|
||||
c color.Color
|
||||
dstBounds image.Rectangle
|
||||
dstPix []uint8
|
||||
}{
|
||||
{
|
||||
"New 1x1 black",
|
||||
1, 1,
|
||||
color.NRGBA{0, 0, 0, 0},
|
||||
image.Rect(0, 0, 1, 1),
|
||||
[]uint8{0x00, 0x00, 0x00, 0x00},
|
||||
},
|
||||
{
|
||||
"New 1x2 red",
|
||||
1, 2,
|
||||
color.NRGBA{255, 0, 0, 255},
|
||||
image.Rect(0, 0, 1, 2),
|
||||
[]uint8{0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff},
|
||||
},
|
||||
{
|
||||
"New 2x1 white",
|
||||
2, 1,
|
||||
color.NRGBA{255, 255, 255, 255},
|
||||
image.Rect(0, 0, 2, 1),
|
||||
[]uint8{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
|
||||
},
|
||||
}
|
||||
|
||||
for _, d := range td {
|
||||
got := New(d.w, d.h, d.c)
|
||||
want := image.NewNRGBA(d.dstBounds)
|
||||
want.Pix = d.dstPix
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClone(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Clone NRGBA",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 0, 1),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 2),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Clone NRGBA64",
|
||||
&image.NRGBA64{
|
||||
Rect: image.Rect(-1, -1, 0, 1),
|
||||
Stride: 1 * 8,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x11, 0x11, 0x22, 0x22, 0x33, 0x33,
|
||||
0xcc, 0xcc, 0xdd, 0xdd, 0xee, 0xee, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 2),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Clone RGBA",
|
||||
&image.RGBA{
|
||||
Rect: image.Rect(-1, -1, 0, 1),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 2),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x00, 0x55, 0xaa, 0x33, 0xcc, 0xdd, 0xee, 0xff},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Clone RGBA64",
|
||||
&image.RGBA64{
|
||||
Rect: image.Rect(-1, -1, 0, 1),
|
||||
Stride: 1 * 8,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x11, 0x11, 0x22, 0x22, 0x33, 0x33,
|
||||
0xcc, 0xcc, 0xdd, 0xdd, 0xee, 0xee, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 2),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x00, 0x55, 0xaa, 0x33, 0xcc, 0xdd, 0xee, 0xff},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Clone Gray",
|
||||
&image.Gray{
|
||||
Rect: image.Rect(-1, -1, 0, 1),
|
||||
Stride: 1 * 1,
|
||||
Pix: []uint8{0x11, 0xee},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 2),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x11, 0x11, 0x11, 0xff, 0xee, 0xee, 0xee, 0xff},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Clone Gray16",
|
||||
&image.Gray16{
|
||||
Rect: image.Rect(-1, -1, 0, 1),
|
||||
Stride: 1 * 2,
|
||||
Pix: []uint8{0x11, 0x11, 0xee, 0xee},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 2),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x11, 0x11, 0x11, 0xff, 0xee, 0xee, 0xee, 0xff},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Clone Alpha",
|
||||
&image.Alpha{
|
||||
Rect: image.Rect(-1, -1, 0, 1),
|
||||
Stride: 1 * 1,
|
||||
Pix: []uint8{0x11, 0xee},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 2),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0xff, 0xff, 0xff, 0x11, 0xff, 0xff, 0xff, 0xee},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Clone YCbCr",
|
||||
&image.YCbCr{
|
||||
Rect: image.Rect(-1, -1, 5, 0),
|
||||
SubsampleRatio: image.YCbCrSubsampleRatio444,
|
||||
YStride: 6,
|
||||
CStride: 6,
|
||||
Y: []uint8{0x00, 0xff, 0x7f, 0x26, 0x4b, 0x0e},
|
||||
Cb: []uint8{0x80, 0x80, 0x80, 0x6b, 0x56, 0xc0},
|
||||
Cr: []uint8{0x80, 0x80, 0x80, 0xc0, 0x4b, 0x76},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 6, 1),
|
||||
Stride: 6 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff,
|
||||
0x7f, 0x7f, 0x7f, 0xff,
|
||||
0x7f, 0x00, 0x00, 0xff,
|
||||
0x00, 0x7f, 0x00, 0xff,
|
||||
0x00, 0x00, 0x7f, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Clone YCbCr 444",
|
||||
&image.YCbCr{
|
||||
Y: []uint8{0x4c, 0x69, 0x1d, 0xb1, 0x96, 0xe2, 0x26, 0x34, 0xe, 0x59, 0x4b, 0x71, 0x0, 0x4c, 0x99, 0xff},
|
||||
Cb: []uint8{0x55, 0xd4, 0xff, 0x8e, 0x2c, 0x01, 0x6b, 0xaa, 0xc0, 0x95, 0x56, 0x40, 0x80, 0x80, 0x80, 0x80},
|
||||
Cr: []uint8{0xff, 0xeb, 0x6b, 0x36, 0x15, 0x95, 0xc0, 0xb5, 0x76, 0x41, 0x4b, 0x8c, 0x80, 0x80, 0x80, 0x80},
|
||||
YStride: 4,
|
||||
CStride: 4,
|
||||
SubsampleRatio: image.YCbCrSubsampleRatio444,
|
||||
Rect: image.Rectangle{Min: image.Point{X: 0, Y: 0}, Max: image.Point{X: 4, Y: 4}},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Pix: []uint8{0xff, 0x0, 0x0, 0xff, 0xff, 0x0, 0xff, 0xff, 0x0, 0x0, 0xff, 0xff, 0x49, 0xe1, 0xca, 0xff, 0x0, 0xff, 0x0, 0xff, 0xff, 0xff, 0x0, 0xff, 0x7f, 0x0, 0x0, 0xff, 0x7f, 0x0, 0x7f, 0xff, 0x0, 0x0, 0x7f, 0xff, 0x0, 0x7f, 0x7f, 0xff, 0x0, 0x7f, 0x0, 0xff, 0x82, 0x7f, 0x0, 0xff, 0x0, 0x0, 0x0, 0xff, 0x4c, 0x4c, 0x4c, 0xff, 0x99, 0x99, 0x99, 0xff, 0xff, 0xff, 0xff, 0xff},
|
||||
Stride: 16,
|
||||
Rect: image.Rectangle{Min: image.Point{X: 0, Y: 0}, Max: image.Point{X: 4, Y: 4}},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Clone YCbCr 440",
|
||||
&image.YCbCr{
|
||||
Y: []uint8{0x4c, 0x69, 0x1d, 0xb1, 0x96, 0xe2, 0x26, 0x34, 0xe, 0x59, 0x4b, 0x71, 0x0, 0x4c, 0x99, 0xff},
|
||||
Cb: []uint8{0x2c, 0x01, 0x6b, 0xaa, 0x80, 0x80, 0x80, 0x80},
|
||||
Cr: []uint8{0x15, 0x95, 0xc0, 0xb5, 0x80, 0x80, 0x80, 0x80},
|
||||
YStride: 4,
|
||||
CStride: 4,
|
||||
SubsampleRatio: image.YCbCrSubsampleRatio440,
|
||||
Rect: image.Rectangle{Min: image.Point{X: 0, Y: 0}, Max: image.Point{X: 4, Y: 4}},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Pix: []uint8{0x0, 0xb5, 0x0, 0xff, 0x86, 0x86, 0x0, 0xff, 0x77, 0x0, 0x0, 0xff, 0xfb, 0x7d, 0xfb, 0xff, 0x0, 0xff, 0x1, 0xff, 0xff, 0xff, 0x1, 0xff, 0x80, 0x0, 0x1, 0xff, 0x7e, 0x0, 0x7e, 0xff, 0xe, 0xe, 0xe, 0xff, 0x59, 0x59, 0x59, 0xff, 0x4b, 0x4b, 0x4b, 0xff, 0x71, 0x71, 0x71, 0xff, 0x0, 0x0, 0x0, 0xff, 0x4c, 0x4c, 0x4c, 0xff, 0x99, 0x99, 0x99, 0xff, 0xff, 0xff, 0xff, 0xff},
|
||||
Stride: 16,
|
||||
Rect: image.Rectangle{Min: image.Point{X: 0, Y: 0}, Max: image.Point{X: 4, Y: 4}},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Clone YCbCr 422",
|
||||
&image.YCbCr{
|
||||
Y: []uint8{0x4c, 0x69, 0x1d, 0xb1, 0x96, 0xe2, 0x26, 0x34, 0xe, 0x59, 0x4b, 0x71, 0x0, 0x4c, 0x99, 0xff},
|
||||
Cb: []uint8{0xd4, 0x8e, 0x01, 0xaa, 0x95, 0x40, 0x80, 0x80},
|
||||
Cr: []uint8{0xeb, 0x36, 0x95, 0xb5, 0x41, 0x8c, 0x80, 0x80},
|
||||
YStride: 4,
|
||||
CStride: 2,
|
||||
SubsampleRatio: image.YCbCrSubsampleRatio422,
|
||||
Rect: image.Rectangle{Min: image.Point{X: 0, Y: 0}, Max: image.Point{X: 4, Y: 4}},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Pix: []uint8{0xe2, 0x0, 0xe1, 0xff, 0xff, 0x0, 0xfe, 0xff, 0x0, 0x4d, 0x36, 0xff, 0x49, 0xe1, 0xca, 0xff, 0xb3, 0xb3, 0x0, 0xff, 0xff, 0xff, 0x1, 0xff, 0x70, 0x0, 0x70, 0xff, 0x7e, 0x0, 0x7e, 0xff, 0x0, 0x34, 0x33, 0xff, 0x1, 0x7f, 0x7e, 0xff, 0x5c, 0x58, 0x0, 0xff, 0x82, 0x7e, 0x0, 0xff, 0x0, 0x0, 0x0, 0xff, 0x4c, 0x4c, 0x4c, 0xff, 0x99, 0x99, 0x99, 0xff, 0xff, 0xff, 0xff, 0xff},
|
||||
Stride: 16,
|
||||
Rect: image.Rectangle{Min: image.Point{X: 0, Y: 0}, Max: image.Point{X: 4, Y: 4}},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Clone YCbCr 420",
|
||||
&image.YCbCr{
|
||||
Y: []uint8{0x4c, 0x69, 0x1d, 0xb1, 0x96, 0xe2, 0x26, 0x34, 0xe, 0x59, 0x4b, 0x71, 0x0, 0x4c, 0x99, 0xff},
|
||||
Cb: []uint8{0x01, 0xaa, 0x80, 0x80},
|
||||
Cr: []uint8{0x95, 0xb5, 0x80, 0x80},
|
||||
YStride: 4, CStride: 2,
|
||||
SubsampleRatio: image.YCbCrSubsampleRatio420,
|
||||
Rect: image.Rectangle{Min: image.Point{X: 0, Y: 0}, Max: image.Point{X: 4, Y: 4}},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Pix: []uint8{0x69, 0x69, 0x0, 0xff, 0x86, 0x86, 0x0, 0xff, 0x67, 0x0, 0x67, 0xff, 0xfb, 0x7d, 0xfb, 0xff, 0xb3, 0xb3, 0x0, 0xff, 0xff, 0xff, 0x1, 0xff, 0x70, 0x0, 0x70, 0xff, 0x7e, 0x0, 0x7e, 0xff, 0xe, 0xe, 0xe, 0xff, 0x59, 0x59, 0x59, 0xff, 0x4b, 0x4b, 0x4b, 0xff, 0x71, 0x71, 0x71, 0xff, 0x0, 0x0, 0x0, 0xff, 0x4c, 0x4c, 0x4c, 0xff, 0x99, 0x99, 0x99, 0xff, 0xff, 0xff, 0xff, 0xff},
|
||||
Stride: 16,
|
||||
Rect: image.Rectangle{Min: image.Point{X: 0, Y: 0}, Max: image.Point{X: 4, Y: 4}},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Clone Paletted",
|
||||
&image.Paletted{
|
||||
Rect: image.Rect(-1, -1, 5, 0),
|
||||
Stride: 6 * 1,
|
||||
Palette: color.Palette{
|
||||
color.NRGBA{R: 0x00, G: 0x00, B: 0x00, A: 0xff},
|
||||
color.NRGBA{R: 0xff, G: 0xff, B: 0xff, A: 0xff},
|
||||
color.NRGBA{R: 0x7f, G: 0x7f, B: 0x7f, A: 0xff},
|
||||
color.NRGBA{R: 0x7f, G: 0x00, B: 0x00, A: 0xff},
|
||||
color.NRGBA{R: 0x00, G: 0x7f, B: 0x00, A: 0xff},
|
||||
color.NRGBA{R: 0x00, G: 0x00, B: 0x7f, A: 0xff},
|
||||
},
|
||||
Pix: []uint8{0x0, 0x1, 0x2, 0x3, 0x4, 0x5},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 6, 1),
|
||||
Stride: 6 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff,
|
||||
0x7f, 0x7f, 0x7f, 0xff,
|
||||
0x7f, 0x00, 0x00, 0xff,
|
||||
0x00, 0x7f, 0x00, 0xff,
|
||||
0x00, 0x00, 0x7f, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, d := range td {
|
||||
got := Clone(d.src)
|
||||
want := d.want
|
||||
|
||||
delta := 0
|
||||
if _, ok := d.src.(*image.YCbCr); ok {
|
||||
delta = 1
|
||||
}
|
||||
|
||||
if !compareNRGBA(got, want, delta) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
49
Godeps/_workspace/src/github.com/disintegration/imaging/resize.go
сгенерированный
поставляемый
49
Godeps/_workspace/src/github.com/disintegration/imaging/resize.go
сгенерированный
поставляемый
@@ -267,20 +267,21 @@ func Fit(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA
|
||||
return Resize(img, newW, newH, filter)
|
||||
}
|
||||
|
||||
// Thumbnail scales the image up or down using the specified resample filter, crops it
|
||||
// to the specified width and hight and returns the transformed image.
|
||||
// Fill scales the image to the smallest possible size that will cover the specified dimensions,
|
||||
// crops the resized image to the specified dimensions using the given anchor point and returns
|
||||
// the transformed image.
|
||||
//
|
||||
// Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali,
|
||||
// CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.
|
||||
//
|
||||
// Usage example:
|
||||
//
|
||||
// dstImage := imaging.Thumbnail(srcImage, 100, 100, imaging.Lanczos)
|
||||
// dstImage := imaging.Fill(srcImage, 800, 600, imaging.Center, imaging.Lanczos)
|
||||
//
|
||||
func Thumbnail(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA {
|
||||
thumbW, thumbH := width, height
|
||||
func Fill(img image.Image, width, height int, anchor Anchor, filter ResampleFilter) *image.NRGBA {
|
||||
minW, minH := width, height
|
||||
|
||||
if thumbW <= 0 || thumbH <= 0 {
|
||||
if minW <= 0 || minH <= 0 {
|
||||
return &image.NRGBA{}
|
||||
}
|
||||
|
||||
@@ -292,17 +293,35 @@ func Thumbnail(img image.Image, width, height int, filter ResampleFilter) *image
|
||||
return &image.NRGBA{}
|
||||
}
|
||||
|
||||
srcAspectRatio := float64(srcW) / float64(srcH)
|
||||
thumbAspectRatio := float64(thumbW) / float64(thumbH)
|
||||
|
||||
var tmp image.Image
|
||||
if srcAspectRatio > thumbAspectRatio {
|
||||
tmp = Resize(img, 0, thumbH, filter)
|
||||
} else {
|
||||
tmp = Resize(img, thumbW, 0, filter)
|
||||
if srcW == minW && srcH == minH {
|
||||
return Clone(img)
|
||||
}
|
||||
|
||||
return CropCenter(tmp, thumbW, thumbH)
|
||||
srcAspectRatio := float64(srcW) / float64(srcH)
|
||||
minAspectRatio := float64(minW) / float64(minH)
|
||||
|
||||
var tmp *image.NRGBA
|
||||
if srcAspectRatio < minAspectRatio {
|
||||
tmp = Resize(img, minW, 0, filter)
|
||||
} else {
|
||||
tmp = Resize(img, 0, minH, filter)
|
||||
}
|
||||
|
||||
return CropAnchor(tmp, minW, minH, anchor)
|
||||
}
|
||||
|
||||
// Thumbnail scales the image up or down using the specified resample filter, crops it
|
||||
// to the specified width and hight and returns the transformed image.
|
||||
//
|
||||
// Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali,
|
||||
// CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.
|
||||
//
|
||||
// Usage example:
|
||||
//
|
||||
// dstImage := imaging.Thumbnail(srcImage, 100, 100, imaging.Lanczos)
|
||||
//
|
||||
func Thumbnail(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA {
|
||||
return Fill(img, width, height, Center, filter)
|
||||
}
|
||||
|
||||
// Resample filter struct. It can be used to make custom filters.
|
||||
|
||||
455
Godeps/_workspace/src/github.com/disintegration/imaging/resize_test.go
сгенерированный
поставляемый
Обычный файл
455
Godeps/_workspace/src/github.com/disintegration/imaging/resize_test.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,455 @@
|
||||
package imaging
|
||||
|
||||
import (
|
||||
"image"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestResize(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
w, h int
|
||||
f ResampleFilter
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Resize 2x2 1x1 box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 1),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
1, 1,
|
||||
Box,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 1),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x40, 0x40, 0x40, 0xc0},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Resize 2x2 2x2 box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 1),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
2, 2,
|
||||
Box,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Resize 3x1 1x1 nearest",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 2, 0),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xff, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
1, 1,
|
||||
NearestNeighbor,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 1),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x00, 0xff, 0x00, 0xff},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Resize 2x2 0x4 box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 1),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
0, 4,
|
||||
Box,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 4, 4),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Resize 2x2 4x0 linear",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 1),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
4, 0,
|
||||
Linear,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 4, 4),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x40, 0xbf, 0x00, 0x00, 0xbf, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0x40, 0x00, 0x40, 0x30, 0x30, 0x10, 0x70, 0x8f, 0x10, 0x30, 0xcf, 0xbf, 0x00, 0x40, 0xff,
|
||||
0x00, 0xbf, 0x00, 0xbf, 0x10, 0x8f, 0x30, 0xcf, 0x30, 0x30, 0x8f, 0xef, 0x40, 0x00, 0xbf, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0xbf, 0x40, 0xff, 0x00, 0x40, 0xbf, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := Resize(d.src, d.w, d.h, d.f)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 1) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFit(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
w, h int
|
||||
f ResampleFilter
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Fit 2x2 1x10 box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 1),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
1, 10,
|
||||
Box,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 1),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x40, 0x40, 0x40, 0xc0},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Fit 2x2 10x1 box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 1),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
10, 1,
|
||||
Box,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 1),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x40, 0x40, 0x40, 0xc0},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Fit 2x2 10x10 box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 1),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
10, 10,
|
||||
Box,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := Fit(d.src, d.w, d.h, d.f)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFill(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
w, h int
|
||||
a Anchor
|
||||
f ResampleFilter
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Fill 4x4 2x2 Center Nearest",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
2, 2,
|
||||
Center,
|
||||
NearestNeighbor,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x14, 0x15, 0x16, 0x17, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x34, 0x35, 0x36, 0x37, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Fill 4x4 1x4 TopLeft Nearest",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
1, 4,
|
||||
TopLeft,
|
||||
NearestNeighbor,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 4),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03,
|
||||
0x10, 0x11, 0x12, 0x13,
|
||||
0x20, 0x21, 0x22, 0x23,
|
||||
0x30, 0x31, 0x32, 0x33,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Fill 4x4 8x2 Bottom Nearest",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
8, 2,
|
||||
Bottom,
|
||||
NearestNeighbor,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 8, 2),
|
||||
Stride: 8 * 4,
|
||||
Pix: []uint8{
|
||||
0x30, 0x31, 0x32, 0x33, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Fill 4x4 2x8 Top Nearest",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
2, 8,
|
||||
Top,
|
||||
NearestNeighbor,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 8),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
|
||||
0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
|
||||
0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b,
|
||||
0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b,
|
||||
0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
|
||||
0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
|
||||
0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b,
|
||||
0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Fill 4x4 4x4 TopRight Box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
4, 4,
|
||||
TopRight,
|
||||
Box,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 4, 4),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Fill 4x4 0x4 Left Box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
0, 4,
|
||||
Left,
|
||||
Box,
|
||||
&image.NRGBA{},
|
||||
},
|
||||
{
|
||||
"Fill 0x0 4x4 Right Box",
|
||||
&image.NRGBA{},
|
||||
4, 4,
|
||||
Right,
|
||||
Box,
|
||||
&image.NRGBA{},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := Fill(d.src, d.w, d.h, d.a, d.f)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestThumbnail(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
w, h int
|
||||
f ResampleFilter
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Thumbnail 6x2 1x1 box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 5, 1),
|
||||
Stride: 6 * 4,
|
||||
Pix: []uint8{
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
1, 1,
|
||||
Box,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 1),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x40, 0x40, 0x40, 0xc0},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Thumbnail 2x6 1x1 box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 5),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
|
||||
0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
1, 1,
|
||||
Box,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 1),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{0x40, 0x40, 0x40, 0xc0},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Thumbnail 1x3 2x2 box",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 0, 2),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0x00,
|
||||
0xff, 0x00, 0x00, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff,
|
||||
},
|
||||
},
|
||||
2, 2,
|
||||
Box,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff,
|
||||
0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := Thumbnail(d.src, d.w, d.h, d.f)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
605
Godeps/_workspace/src/github.com/disintegration/imaging/tools_test.go
сгенерированный
поставляемый
Обычный файл
605
Godeps/_workspace/src/github.com/disintegration/imaging/tools_test.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,605 @@
|
||||
package imaging
|
||||
|
||||
import (
|
||||
"image"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCrop(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
r image.Rectangle
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Crop 2x3 2x1",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff,
|
||||
0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00,
|
||||
0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
image.Rect(-1, 0, 1, 1),
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 1),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := Crop(d.src, d.r)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCropCenter(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
w, h int
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"CropCenter 2x3 2x1",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff,
|
||||
0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00,
|
||||
0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
2, 1,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 1),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"CropCenter 2x3 0x1",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff,
|
||||
0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00,
|
||||
0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
0, 1,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 0, 0),
|
||||
Stride: 0,
|
||||
Pix: []uint8{},
|
||||
},
|
||||
},
|
||||
{
|
||||
"CropCenter 2x3 5x5",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff,
|
||||
0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00,
|
||||
0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
5, 5,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 3),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff,
|
||||
0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00,
|
||||
0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := CropCenter(d.src, d.w, d.h)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCropAnchor(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
w, h int
|
||||
anchor Anchor
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"CropAnchor 4x4 2x2 TopLeft",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
2, 2,
|
||||
TopLeft,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"CropAnchor 4x4 2x2 Top",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
2, 2,
|
||||
Top,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
|
||||
0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"CropAnchor 4x4 2x2 TopRight",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
2, 2,
|
||||
TopRight,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"CropAnchor 4x4 2x2 Left",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
2, 2,
|
||||
Left,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"CropAnchor 4x4 2x2 Center",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
2, 2,
|
||||
Center,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b,
|
||||
0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"CropAnchor 4x4 2x2 Right",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
2, 2,
|
||||
Right,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"CropAnchor 4x4 2x2 BottomLeft",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
2, 2,
|
||||
BottomLeft,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"CropAnchor 4x4 2x2 Bottom",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
2, 2,
|
||||
Bottom,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
|
||||
0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"CropAnchor 4x4 2x2 BottomRight",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
2, 2,
|
||||
BottomRight,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"CropAnchor 4x4 0x0 BottomRight",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
0, 0,
|
||||
BottomRight,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 0, 0),
|
||||
Stride: 0,
|
||||
Pix: []uint8{},
|
||||
},
|
||||
},
|
||||
{
|
||||
"CropAnchor 4x4 100x100 BottomRight",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
100, 100,
|
||||
BottomRight,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 4, 4),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"CropAnchor 4x4 1x100 BottomRight",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
1, 100,
|
||||
BottomRight,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 1, 4),
|
||||
Stride: 1 * 4,
|
||||
Pix: []uint8{
|
||||
0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"CropAnchor 4x4 0x100 BottomRight",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 3, 3),
|
||||
Stride: 4 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
},
|
||||
},
|
||||
0, 100,
|
||||
BottomRight,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 0, 0),
|
||||
Stride: 0,
|
||||
Pix: []uint8{},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := CropAnchor(d.src, d.w, d.h, d.anchor)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaste(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src1 image.Image
|
||||
src2 image.Image
|
||||
p image.Point
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Paste 2x3 2x1",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff,
|
||||
0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00,
|
||||
0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(1, 1, 3, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
|
||||
},
|
||||
},
|
||||
image.Pt(-1, 0),
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 3),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff,
|
||||
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
|
||||
0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := Paste(d.src1, d.src2, d.p)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasteCenter(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src1 image.Image
|
||||
src2 image.Image
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"PasteCenter 2x3 2x1",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff,
|
||||
0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00,
|
||||
0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(1, 1, 3, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
|
||||
},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 3),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff,
|
||||
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
|
||||
0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := PasteCenter(d.src1, d.src2)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOverlay(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src1 image.Image
|
||||
src2 image.Image
|
||||
p image.Point
|
||||
a float64
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Overlay 2x3 2x1 1.0",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff,
|
||||
0x60, 0x00, 0x90, 0xff, 0xff, 0x00, 0x99, 0x7f,
|
||||
0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(1, 1, 3, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x20, 0x40, 0x80, 0x7f, 0xaa, 0xbb, 0xcc, 0xff,
|
||||
},
|
||||
},
|
||||
image.Pt(-1, 0),
|
||||
1.0,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 3),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff,
|
||||
0x40, 0x1f, 0x88, 0xff, 0xaa, 0xbb, 0xcc, 0xff,
|
||||
0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"Overlay 2x2 2x2 0.5",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 1),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0xff, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff,
|
||||
0x00, 0x00, 0xff, 0xff, 0x20, 0x20, 0x20, 0x00,
|
||||
},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 1),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,
|
||||
0xff, 0xff, 0x00, 0xff, 0x20, 0x20, 0x20, 0xff,
|
||||
},
|
||||
},
|
||||
image.Pt(-1, -1),
|
||||
0.5,
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0xff, 0x7f, 0x7f, 0xff, 0x00, 0xff, 0x00, 0xff,
|
||||
0x7f, 0x7f, 0x7f, 0xff, 0x20, 0x20, 0x20, 0x7f,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := Overlay(d.src1, d.src2, d.p, d.a)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 1) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
261
Godeps/_workspace/src/github.com/disintegration/imaging/transform_test.go
сгенерированный
поставляемый
Обычный файл
261
Godeps/_workspace/src/github.com/disintegration/imaging/transform_test.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,261 @@
|
||||
package imaging
|
||||
|
||||
import (
|
||||
"image"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRotate90(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Rotate90 2x3",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff,
|
||||
0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00,
|
||||
0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0xdd, 0xee, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff,
|
||||
0x00, 0x11, 0x22, 0x33, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := Rotate90(d.src)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRotate180(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Rotate180 2x3",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff,
|
||||
0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00,
|
||||
0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 3),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00,
|
||||
0x00, 0xff, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00,
|
||||
0xcc, 0xdd, 0xee, 0xff, 0x00, 0x11, 0x22, 0x33,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := Rotate180(d.src)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRotate270(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Rotate270 2x3",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff,
|
||||
0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00,
|
||||
0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x11, 0x22, 0x33,
|
||||
0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xcc, 0xdd, 0xee, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := Rotate270(d.src)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlipV(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"FlipV 2x3",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff,
|
||||
0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00,
|
||||
0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 3),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff,
|
||||
0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00,
|
||||
0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := FlipV(d.src)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlipH(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"FlipH 2x3",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff,
|
||||
0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00,
|
||||
0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 2, 3),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0xcc, 0xdd, 0xee, 0xff, 0x00, 0x11, 0x22, 0x33,
|
||||
0x00, 0xff, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := FlipH(d.src)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTranspose(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Transpose 2x3",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff,
|
||||
0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00,
|
||||
0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x11, 0x22, 0x33, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00,
|
||||
0xcc, 0xdd, 0xee, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := Transpose(d.src)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTransverse(t *testing.T) {
|
||||
td := []struct {
|
||||
desc string
|
||||
src image.Image
|
||||
want *image.NRGBA
|
||||
}{
|
||||
{
|
||||
"Transverse 2x3",
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(-1, -1, 1, 2),
|
||||
Stride: 2 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff,
|
||||
0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00,
|
||||
0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff,
|
||||
},
|
||||
},
|
||||
&image.NRGBA{
|
||||
Rect: image.Rect(0, 0, 3, 2),
|
||||
Stride: 3 * 4,
|
||||
Pix: []uint8{
|
||||
0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xcc, 0xdd, 0xee, 0xff,
|
||||
0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x11, 0x22, 0x33,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, d := range td {
|
||||
got := Transverse(d.src)
|
||||
want := d.want
|
||||
if !compareNRGBA(got, want, 0) {
|
||||
t.Errorf("test [%s] failed: %#v", d.desc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
61
Godeps/_workspace/src/github.com/disintegration/imaging/utils_test.go
сгенерированный
поставляемый
Обычный файл
61
Godeps/_workspace/src/github.com/disintegration/imaging/utils_test.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,61 @@
|
||||
package imaging
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func testParallelN(enabled bool, n, procs int) bool {
|
||||
data := make([]bool, n)
|
||||
before := runtime.GOMAXPROCS(0)
|
||||
runtime.GOMAXPROCS(procs)
|
||||
parallel(n, func(start, end int) {
|
||||
for i := start; i < end; i++ {
|
||||
data[i] = true
|
||||
}
|
||||
})
|
||||
for i := 0; i < n; i++ {
|
||||
if data[i] != true {
|
||||
return false
|
||||
}
|
||||
}
|
||||
runtime.GOMAXPROCS(before)
|
||||
return true
|
||||
}
|
||||
|
||||
func TestParallel(t *testing.T) {
|
||||
for _, e := range []bool{true, false} {
|
||||
for _, n := range []int{1, 10, 100, 1000} {
|
||||
for _, p := range []int{1, 2, 4, 8, 16, 100} {
|
||||
if testParallelN(e, n, p) != true {
|
||||
t.Errorf("test [parallel %v %d %d] failed", e, n, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClamp(t *testing.T) {
|
||||
td := []struct {
|
||||
f float64
|
||||
u uint8
|
||||
}{
|
||||
{0, 0},
|
||||
{255, 255},
|
||||
{128, 128},
|
||||
{0.49, 0},
|
||||
{0.50, 1},
|
||||
{254.9, 255},
|
||||
{254.0, 254},
|
||||
{256, 255},
|
||||
{2500, 255},
|
||||
{-10, 0},
|
||||
{127.6, 128},
|
||||
}
|
||||
|
||||
for _, d := range td {
|
||||
if clamp(d.f) != d.u {
|
||||
t.Errorf("test [clamp %v %v] failed: %v", d.f, d.u, clamp(d.f))
|
||||
}
|
||||
}
|
||||
}
|
||||
5
Godeps/_workspace/src/github.com/garyburd/redigo/internal/redistest/testdb.go
сгенерированный
поставляемый
5
Godeps/_workspace/src/github.com/garyburd/redigo/internal/redistest/testdb.go
сгенерированный
поставляемый
@@ -19,7 +19,7 @@ import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/garyburd/redigo/redis"
|
||||
"github.com/mattermost/platform/Godeps/_workspace/src/github.com/garyburd/redigo/redis"
|
||||
)
|
||||
|
||||
type testConn struct {
|
||||
@@ -49,15 +49,18 @@ func Dial() (redis.Conn, error) {
|
||||
|
||||
_, err = c.Do("SELECT", "9")
|
||||
if err != nil {
|
||||
c.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
n, err := redis.Int(c.Do("DBSIZE"))
|
||||
if err != nil {
|
||||
c.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if n != 0 {
|
||||
c.Close()
|
||||
return nil, errors.New("database #9 is not empty, test can not continue")
|
||||
}
|
||||
|
||||
|
||||
186
Godeps/_workspace/src/github.com/garyburd/redigo/redis/conn.go
сгенерированный
поставляемый
186
Godeps/_workspace/src/github.com/garyburd/redigo/redis/conn.go
сгенерированный
поставляемый
@@ -21,6 +21,8 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -51,56 +53,164 @@ type conn struct {
|
||||
numScratch [40]byte
|
||||
}
|
||||
|
||||
// Dial connects to the Redis server at the given network and address.
|
||||
func Dial(network, address string) (Conn, error) {
|
||||
dialer := xDialer{}
|
||||
return dialer.Dial(network, address)
|
||||
}
|
||||
|
||||
// DialTimeout acts like Dial but takes timeouts for establishing the
|
||||
// connection to the server, writing a command and reading a reply.
|
||||
//
|
||||
// Deprecated: Use Dial with options instead.
|
||||
func DialTimeout(network, address string, connectTimeout, readTimeout, writeTimeout time.Duration) (Conn, error) {
|
||||
netDialer := net.Dialer{Timeout: connectTimeout}
|
||||
dialer := xDialer{
|
||||
NetDial: netDialer.Dial,
|
||||
ReadTimeout: readTimeout,
|
||||
WriteTimeout: writeTimeout,
|
||||
}
|
||||
return dialer.Dial(network, address)
|
||||
return Dial(network, address,
|
||||
DialConnectTimeout(connectTimeout),
|
||||
DialReadTimeout(readTimeout),
|
||||
DialWriteTimeout(writeTimeout))
|
||||
}
|
||||
|
||||
// A Dialer specifies options for connecting to a Redis server.
|
||||
type xDialer struct {
|
||||
// NetDial specifies the dial function for creating TCP connections. If
|
||||
// NetDial is nil, then net.Dial is used.
|
||||
NetDial func(network, addr string) (net.Conn, error)
|
||||
|
||||
// ReadTimeout specifies the timeout for reading a single command
|
||||
// reply. If ReadTimeout is zero, then no timeout is used.
|
||||
ReadTimeout time.Duration
|
||||
|
||||
// WriteTimeout specifies the timeout for writing a single command. If
|
||||
// WriteTimeout is zero, then no timeout is used.
|
||||
WriteTimeout time.Duration
|
||||
// DialOption specifies an option for dialing a Redis server.
|
||||
type DialOption struct {
|
||||
f func(*dialOptions)
|
||||
}
|
||||
|
||||
// Dial connects to the Redis server at address on the named network.
|
||||
func (d *xDialer) Dial(network, address string) (Conn, error) {
|
||||
dial := d.NetDial
|
||||
if dial == nil {
|
||||
dial = net.Dial
|
||||
type dialOptions struct {
|
||||
readTimeout time.Duration
|
||||
writeTimeout time.Duration
|
||||
dial func(network, addr string) (net.Conn, error)
|
||||
db int
|
||||
password string
|
||||
}
|
||||
|
||||
// DialReadTimeout specifies the timeout for reading a single command reply.
|
||||
func DialReadTimeout(d time.Duration) DialOption {
|
||||
return DialOption{func(do *dialOptions) {
|
||||
do.readTimeout = d
|
||||
}}
|
||||
}
|
||||
|
||||
// DialWriteTimeout specifies the timeout for writing a single command.
|
||||
func DialWriteTimeout(d time.Duration) DialOption {
|
||||
return DialOption{func(do *dialOptions) {
|
||||
do.writeTimeout = d
|
||||
}}
|
||||
}
|
||||
|
||||
// DialConnectTimeout specifies the timeout for connecting to the Redis server.
|
||||
func DialConnectTimeout(d time.Duration) DialOption {
|
||||
return DialOption{func(do *dialOptions) {
|
||||
dialer := net.Dialer{Timeout: d}
|
||||
do.dial = dialer.Dial
|
||||
}}
|
||||
}
|
||||
|
||||
// DialNetDial specifies a custom dial function for creating TCP
|
||||
// connections. If this option is left out, then net.Dial is
|
||||
// used. DialNetDial overrides DialConnectTimeout.
|
||||
func DialNetDial(dial func(network, addr string) (net.Conn, error)) DialOption {
|
||||
return DialOption{func(do *dialOptions) {
|
||||
do.dial = dial
|
||||
}}
|
||||
}
|
||||
|
||||
// DialDatabase specifies the database to select when dialing a connection.
|
||||
func DialDatabase(db int) DialOption {
|
||||
return DialOption{func(do *dialOptions) {
|
||||
do.db = db
|
||||
}}
|
||||
}
|
||||
|
||||
// DialPassword specifies the password to use when connecting to
|
||||
// the Redis server.
|
||||
func DialPassword(password string) DialOption {
|
||||
return DialOption{func(do *dialOptions) {
|
||||
do.password = password
|
||||
}}
|
||||
}
|
||||
|
||||
// Dial connects to the Redis server at the given network and
|
||||
// address using the specified options.
|
||||
func Dial(network, address string, options ...DialOption) (Conn, error) {
|
||||
do := dialOptions{
|
||||
dial: net.Dial,
|
||||
}
|
||||
netConn, err := dial(network, address)
|
||||
for _, option := range options {
|
||||
option.f(&do)
|
||||
}
|
||||
|
||||
netConn, err := do.dial(network, address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &conn{
|
||||
c := &conn{
|
||||
conn: netConn,
|
||||
bw: bufio.NewWriter(netConn),
|
||||
br: bufio.NewReader(netConn),
|
||||
readTimeout: d.ReadTimeout,
|
||||
writeTimeout: d.WriteTimeout,
|
||||
}, nil
|
||||
readTimeout: do.readTimeout,
|
||||
writeTimeout: do.writeTimeout,
|
||||
}
|
||||
|
||||
if do.password != "" {
|
||||
if _, err := c.Do("AUTH", do.password); err != nil {
|
||||
netConn.Close()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if do.db != 0 {
|
||||
if _, err := c.Do("SELECT", do.db); err != nil {
|
||||
netConn.Close()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
var pathDBRegexp = regexp.MustCompile(`/(\d+)\z`)
|
||||
|
||||
// DialURL connects to a Redis server at the given URL using the Redis
|
||||
// URI scheme. URLs should follow the draft IANA specification for the
|
||||
// scheme (https://www.iana.org/assignments/uri-schemes/prov/redis).
|
||||
func DialURL(rawurl string, options ...DialOption) (Conn, error) {
|
||||
u, err := url.Parse(rawurl)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if u.Scheme != "redis" {
|
||||
return nil, fmt.Errorf("invalid redis URL scheme: %s", u.Scheme)
|
||||
}
|
||||
|
||||
// As per the IANA draft spec, the host defaults to localhost and
|
||||
// the port defaults to 6379.
|
||||
host, port, err := net.SplitHostPort(u.Host)
|
||||
if err != nil {
|
||||
// assume port is missing
|
||||
host = u.Host
|
||||
port = "6379"
|
||||
}
|
||||
if host == "" {
|
||||
host = "localhost"
|
||||
}
|
||||
address := net.JoinHostPort(host, port)
|
||||
|
||||
if u.User != nil {
|
||||
password, isSet := u.User.Password()
|
||||
if isSet {
|
||||
options = append(options, DialPassword(password))
|
||||
}
|
||||
}
|
||||
|
||||
match := pathDBRegexp.FindStringSubmatch(u.Path)
|
||||
if len(match) == 2 {
|
||||
db, err := strconv.Atoi(match[1])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid database: %s", u.Path[1:])
|
||||
}
|
||||
if db != 0 {
|
||||
options = append(options, DialDatabase(db))
|
||||
}
|
||||
} else if u.Path != "" {
|
||||
return nil, fmt.Errorf("invalid database: %s", u.Path[1:])
|
||||
}
|
||||
|
||||
return Dial("tcp", address, options...)
|
||||
}
|
||||
|
||||
// NewConn returns a new Redigo connection for the given net connection.
|
||||
@@ -417,7 +527,9 @@ func (c *conn) Do(cmd string, args ...interface{}) (interface{}, error) {
|
||||
}
|
||||
|
||||
if cmd != "" {
|
||||
c.writeCommand(cmd, args)
|
||||
if err := c.writeCommand(cmd, args); err != nil {
|
||||
return nil, c.fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := c.bw.Flush(); err != nil {
|
||||
|
||||
163
Godeps/_workspace/src/github.com/garyburd/redigo/redis/conn_test.go
сгенерированный
поставляемый
163
Godeps/_workspace/src/github.com/garyburd/redigo/redis/conn_test.go
сгенерированный
поставляемый
@@ -15,19 +15,37 @@
|
||||
package redis_test
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/garyburd/redigo/internal/redistest"
|
||||
"github.com/garyburd/redigo/redis"
|
||||
"github.com/mattermost/platform/Godeps/_workspace/src/github.com/garyburd/redigo/redis"
|
||||
)
|
||||
|
||||
type testConn struct {
|
||||
io.Reader
|
||||
io.Writer
|
||||
}
|
||||
|
||||
func (*testConn) Close() error { return nil }
|
||||
func (*testConn) LocalAddr() net.Addr { return nil }
|
||||
func (*testConn) RemoteAddr() net.Addr { return nil }
|
||||
func (*testConn) SetDeadline(t time.Time) error { return nil }
|
||||
func (*testConn) SetReadDeadline(t time.Time) error { return nil }
|
||||
func (*testConn) SetWriteDeadline(t time.Time) error { return nil }
|
||||
|
||||
func dialTestConn(r io.Reader, w io.Writer) redis.DialOption {
|
||||
return redis.DialNetDial(func(net, addr string) (net.Conn, error) {
|
||||
return &testConn{Reader: r, Writer: w}, nil
|
||||
})
|
||||
}
|
||||
|
||||
var writeTests = []struct {
|
||||
args []interface{}
|
||||
expected string
|
||||
@@ -73,14 +91,13 @@ var writeTests = []struct {
|
||||
func TestWrite(t *testing.T) {
|
||||
for _, tt := range writeTests {
|
||||
var buf bytes.Buffer
|
||||
rw := bufio.ReadWriter{Writer: bufio.NewWriter(&buf)}
|
||||
c := redis.NewConnBufio(rw)
|
||||
c, _ := redis.Dial("", "", dialTestConn(nil, &buf))
|
||||
err := c.Send(tt.args[0].(string), tt.args[1:]...)
|
||||
if err != nil {
|
||||
t.Errorf("Send(%v) returned error %v", tt.args, err)
|
||||
continue
|
||||
}
|
||||
rw.Flush()
|
||||
c.Flush()
|
||||
actual := buf.String()
|
||||
if actual != tt.expected {
|
||||
t.Errorf("Send(%v) = %q, want %q", tt.args, actual, tt.expected)
|
||||
@@ -173,11 +190,7 @@ var readTests = []struct {
|
||||
|
||||
func TestRead(t *testing.T) {
|
||||
for _, tt := range readTests {
|
||||
rw := bufio.ReadWriter{
|
||||
Reader: bufio.NewReader(strings.NewReader(tt.reply)),
|
||||
Writer: bufio.NewWriter(nil), // writer need to support Flush
|
||||
}
|
||||
c := redis.NewConnBufio(rw)
|
||||
c, _ := redis.Dial("", "", dialTestConn(strings.NewReader(tt.reply), nil))
|
||||
actual, err := c.Receive()
|
||||
if tt.expected == errorSentinel {
|
||||
if err == nil {
|
||||
@@ -257,7 +270,7 @@ var testCommands = []struct {
|
||||
}
|
||||
|
||||
func TestDoCommands(t *testing.T) {
|
||||
c, err := redistest.Dial()
|
||||
c, err := redis.DialDefaultServer()
|
||||
if err != nil {
|
||||
t.Fatalf("error connection to database, %v", err)
|
||||
}
|
||||
@@ -276,7 +289,7 @@ func TestDoCommands(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestPipelineCommands(t *testing.T) {
|
||||
c, err := redistest.Dial()
|
||||
c, err := redis.DialDefaultServer()
|
||||
if err != nil {
|
||||
t.Fatalf("error connection to database, %v", err)
|
||||
}
|
||||
@@ -302,7 +315,7 @@ func TestPipelineCommands(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestBlankCommmand(t *testing.T) {
|
||||
c, err := redistest.Dial()
|
||||
c, err := redis.DialDefaultServer()
|
||||
if err != nil {
|
||||
t.Fatalf("error connection to database, %v", err)
|
||||
}
|
||||
@@ -329,7 +342,7 @@ func TestBlankCommmand(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRecvBeforeSend(t *testing.T) {
|
||||
c, err := redistest.Dial()
|
||||
c, err := redis.DialDefaultServer()
|
||||
if err != nil {
|
||||
t.Fatalf("error connection to database, %v", err)
|
||||
}
|
||||
@@ -350,7 +363,7 @@ func TestRecvBeforeSend(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestError(t *testing.T) {
|
||||
c, err := redistest.Dial()
|
||||
c, err := redis.DialDefaultServer()
|
||||
if err != nil {
|
||||
t.Fatalf("error connection to database, %v", err)
|
||||
}
|
||||
@@ -370,7 +383,7 @@ func TestError(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadDeadline(t *testing.T) {
|
||||
func TestReadTimeout(t *testing.T) {
|
||||
l, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("net.Listen returned %v", err)
|
||||
@@ -391,7 +404,9 @@ func TestReadDeadline(t *testing.T) {
|
||||
}
|
||||
}()
|
||||
|
||||
c1, err := redis.DialTimeout(l.Addr().Network(), l.Addr().String(), 0, time.Millisecond, 0)
|
||||
// Do
|
||||
|
||||
c1, err := redis.Dial(l.Addr().Network(), l.Addr().String(), redis.DialReadTimeout(time.Millisecond))
|
||||
if err != nil {
|
||||
t.Fatalf("redis.Dial returned %v", err)
|
||||
}
|
||||
@@ -405,7 +420,9 @@ func TestReadDeadline(t *testing.T) {
|
||||
t.Fatalf("c1.Err() = nil, expect error")
|
||||
}
|
||||
|
||||
c2, err := redis.DialTimeout(l.Addr().Network(), l.Addr().String(), 0, time.Millisecond, 0)
|
||||
// Send/Flush/Receive
|
||||
|
||||
c2, err := redis.Dial(l.Addr().Network(), l.Addr().String(), redis.DialReadTimeout(time.Millisecond))
|
||||
if err != nil {
|
||||
t.Fatalf("redis.Dial returned %v", err)
|
||||
}
|
||||
@@ -422,6 +439,95 @@ func TestReadDeadline(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
var dialErrors = []struct {
|
||||
rawurl string
|
||||
expectedError string
|
||||
}{
|
||||
{
|
||||
"localhost",
|
||||
"invalid redis URL scheme",
|
||||
},
|
||||
// The error message for invalid hosts is diffferent in different
|
||||
// versions of Go, so just check that there is an error message.
|
||||
{
|
||||
"redis://weird url",
|
||||
"",
|
||||
},
|
||||
{
|
||||
"redis://foo:bar:baz",
|
||||
"",
|
||||
},
|
||||
{
|
||||
"http://www.google.com",
|
||||
"invalid redis URL scheme: http",
|
||||
},
|
||||
{
|
||||
"redis://localhost:6379/abc123",
|
||||
"invalid database: abc123",
|
||||
},
|
||||
}
|
||||
|
||||
func TestDialURLErrors(t *testing.T) {
|
||||
for _, d := range dialErrors {
|
||||
_, err := redis.DialURL(d.rawurl)
|
||||
if err == nil || !strings.Contains(err.Error(), d.expectedError) {
|
||||
t.Errorf("DialURL did not return expected error (expected %v to contain %s)", err, d.expectedError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDialURLPort(t *testing.T) {
|
||||
checkPort := func(network, address string) (net.Conn, error) {
|
||||
if address != "localhost:6379" {
|
||||
t.Errorf("DialURL did not set port to 6379 by default (got %v)", address)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
_, err := redis.DialURL("redis://localhost", redis.DialNetDial(checkPort))
|
||||
if err != nil {
|
||||
t.Error("dial error:", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDialURLHost(t *testing.T) {
|
||||
checkHost := func(network, address string) (net.Conn, error) {
|
||||
if address != "localhost:6379" {
|
||||
t.Errorf("DialURL did not set host to localhost by default (got %v)", address)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
_, err := redis.DialURL("redis://:6379", redis.DialNetDial(checkHost))
|
||||
if err != nil {
|
||||
t.Error("dial error:", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDialURLPassword(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
_, err := redis.DialURL("redis://x:abc123@localhost", dialTestConn(strings.NewReader("+OK\r\n"), &buf))
|
||||
if err != nil {
|
||||
t.Error("dial error:", err)
|
||||
}
|
||||
expected := "*2\r\n$4\r\nAUTH\r\n$6\r\nabc123\r\n"
|
||||
actual := buf.String()
|
||||
if actual != expected {
|
||||
t.Errorf("commands = %q, want %q", actual, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDialURLDatabase(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
_, err := redis.DialURL("redis://localhost/3", dialTestConn(strings.NewReader("+OK\r\n"), &buf))
|
||||
if err != nil {
|
||||
t.Error("dial error:", err)
|
||||
}
|
||||
expected := "*2\r\n$6\r\nSELECT\r\n$1\r\n3\r\n"
|
||||
actual := buf.String()
|
||||
if actual != expected {
|
||||
t.Errorf("commands = %q, want %q", actual, expected)
|
||||
}
|
||||
}
|
||||
|
||||
// Connect to local instance of Redis running on the default port.
|
||||
func ExampleDial(x int) {
|
||||
c, err := redis.Dial("tcp", ":6379")
|
||||
@@ -431,11 +537,20 @@ func ExampleDial(x int) {
|
||||
defer c.Close()
|
||||
}
|
||||
|
||||
// Connect to remote instance of Redis using a URL.
|
||||
func ExampleDialURL() {
|
||||
c, err := redis.DialURL(os.Getenv("REDIS_URL"))
|
||||
if err != nil {
|
||||
// handle connection error
|
||||
}
|
||||
defer c.Close()
|
||||
}
|
||||
|
||||
// TextExecError tests handling of errors in a transaction. See
|
||||
// http://redis.io/topics/transactions for information on how Redis handles
|
||||
// errors in a transaction.
|
||||
func TestExecError(t *testing.T) {
|
||||
c, err := redistest.Dial()
|
||||
c, err := redis.DialDefaultServer()
|
||||
if err != nil {
|
||||
t.Fatalf("error connection to database, %v", err)
|
||||
}
|
||||
@@ -443,6 +558,7 @@ func TestExecError(t *testing.T) {
|
||||
|
||||
// Execute commands that fail before EXEC is called.
|
||||
|
||||
c.Do("DEL", "k0")
|
||||
c.Do("ZADD", "k0", 0, 0)
|
||||
c.Send("MULTI")
|
||||
c.Send("NOTACOMMAND", "k0", 0, 0)
|
||||
@@ -455,6 +571,7 @@ func TestExecError(t *testing.T) {
|
||||
// Execute commands that fail after EXEC is called. The first command
|
||||
// returns an error.
|
||||
|
||||
c.Do("DEL", "k1")
|
||||
c.Do("ZADD", "k1", 0, 0)
|
||||
c.Send("MULTI")
|
||||
c.Send("HSET", "k1", 0, 0)
|
||||
@@ -478,7 +595,7 @@ func TestExecError(t *testing.T) {
|
||||
}
|
||||
|
||||
if _, ok := vs[1].([]byte); !ok {
|
||||
t.Fatalf("second result is type %T, expected []byte", vs[2])
|
||||
t.Fatalf("second result is type %T, expected []byte", vs[1])
|
||||
}
|
||||
|
||||
// Execute commands that fail after EXEC is called. The second command
|
||||
@@ -513,7 +630,7 @@ func TestExecError(t *testing.T) {
|
||||
|
||||
func BenchmarkDoEmpty(b *testing.B) {
|
||||
b.StopTimer()
|
||||
c, err := redistest.Dial()
|
||||
c, err := redis.DialDefaultServer()
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
@@ -528,7 +645,7 @@ func BenchmarkDoEmpty(b *testing.B) {
|
||||
|
||||
func BenchmarkDoPing(b *testing.B) {
|
||||
b.StopTimer()
|
||||
c, err := redistest.Dial()
|
||||
c, err := redis.DialDefaultServer()
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
||||
14
Godeps/_workspace/src/github.com/garyburd/redigo/redis/pool.go
сгенерированный
поставляемый
14
Godeps/_workspace/src/github.com/garyburd/redigo/redis/pool.go
сгенерированный
поставляемый
@@ -25,7 +25,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/garyburd/redigo/internal"
|
||||
"github.com/mattermost/platform/Godeps/_workspace/src/github.com/garyburd/redigo/internal"
|
||||
)
|
||||
|
||||
var nowFunc = time.Now // for testing
|
||||
@@ -94,7 +94,10 @@ var (
|
||||
type Pool struct {
|
||||
|
||||
// Dial is an application supplied function for creating and configuring a
|
||||
// connection
|
||||
// connection.
|
||||
//
|
||||
// The connection returned from Dial must not be in a special state
|
||||
// (subscribed to pubsub channel, transaction started, ...).
|
||||
Dial func() (Conn, error)
|
||||
|
||||
// TestOnBorrow is an optional application supplied function for checking
|
||||
@@ -116,7 +119,7 @@ type Pool struct {
|
||||
// the timeout to a value less than the server's timeout.
|
||||
IdleTimeout time.Duration
|
||||
|
||||
// If Wait is true and the pool is at the MaxIdle limit, then Get() waits
|
||||
// If Wait is true and the pool is at the MaxActive limit, then Get() waits
|
||||
// for a connection to be returned to the pool before returning.
|
||||
Wait bool
|
||||
|
||||
@@ -135,8 +138,9 @@ type idleConn struct {
|
||||
t time.Time
|
||||
}
|
||||
|
||||
// NewPool creates a new pool. This function is deprecated. Applications should
|
||||
// initialize the Pool fields directly as shown in example.
|
||||
// NewPool creates a new pool.
|
||||
//
|
||||
// Deprecated: Initialize the Pool directory as shown in the example.
|
||||
func NewPool(newFn func() (Conn, error), maxIdle int) *Pool {
|
||||
return &Pool{Dial: newFn, MaxIdle: maxIdle}
|
||||
}
|
||||
|
||||
96
Godeps/_workspace/src/github.com/garyburd/redigo/redis/pool_test.go
сгенерированный
поставляемый
96
Godeps/_workspace/src/github.com/garyburd/redigo/redis/pool_test.go
сгенерированный
поставляемый
@@ -22,8 +22,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/garyburd/redigo/internal/redistest"
|
||||
"github.com/garyburd/redigo/redis"
|
||||
"github.com/mattermost/platform/Godeps/_workspace/src/github.com/garyburd/redigo/redis"
|
||||
)
|
||||
|
||||
type poolTestConn struct {
|
||||
@@ -32,10 +31,16 @@ type poolTestConn struct {
|
||||
redis.Conn
|
||||
}
|
||||
|
||||
func (c *poolTestConn) Close() error { c.d.open -= 1; return nil }
|
||||
func (c *poolTestConn) Err() error { return c.err }
|
||||
func (c *poolTestConn) Close() error {
|
||||
c.d.mu.Lock()
|
||||
c.d.open -= 1
|
||||
c.d.mu.Unlock()
|
||||
return c.Conn.Close()
|
||||
}
|
||||
|
||||
func (c *poolTestConn) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
|
||||
func (c *poolTestConn) Err() error { return c.err }
|
||||
|
||||
func (c *poolTestConn) Do(commandName string, args ...interface{}) (interface{}, error) {
|
||||
if commandName == "ERR" {
|
||||
c.err = args[0].(error)
|
||||
commandName = "PING"
|
||||
@@ -52,6 +57,7 @@ func (c *poolTestConn) Send(commandName string, args ...interface{}) error {
|
||||
}
|
||||
|
||||
type poolDialer struct {
|
||||
mu sync.Mutex
|
||||
t *testing.T
|
||||
dialed int
|
||||
open int
|
||||
@@ -60,19 +66,25 @@ type poolDialer struct {
|
||||
}
|
||||
|
||||
func (d *poolDialer) dial() (redis.Conn, error) {
|
||||
d.mu.Lock()
|
||||
d.dialed += 1
|
||||
if d.dialErr != nil {
|
||||
dialErr := d.dialErr
|
||||
d.mu.Unlock()
|
||||
if dialErr != nil {
|
||||
return nil, d.dialErr
|
||||
}
|
||||
c, err := redistest.Dial()
|
||||
c, err := redis.DialDefaultServer()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d.mu.Lock()
|
||||
d.open += 1
|
||||
d.mu.Unlock()
|
||||
return &poolTestConn{d: d, Conn: c}, nil
|
||||
}
|
||||
|
||||
func (d *poolDialer) check(message string, p *redis.Pool, dialed, open int) {
|
||||
d.mu.Lock()
|
||||
if d.dialed != dialed {
|
||||
d.t.Errorf("%s: dialed=%d, want %d", message, d.dialed, dialed)
|
||||
}
|
||||
@@ -82,6 +94,7 @@ func (d *poolDialer) check(message string, p *redis.Pool, dialed, open int) {
|
||||
if active := p.ActiveCount(); active != open {
|
||||
d.t.Errorf("%s: active=%d, want %d", message, active, open)
|
||||
}
|
||||
d.mu.Unlock()
|
||||
}
|
||||
|
||||
func TestPoolReuse(t *testing.T) {
|
||||
@@ -111,6 +124,8 @@ func TestPoolMaxIdle(t *testing.T) {
|
||||
MaxIdle: 2,
|
||||
Dial: d.dial,
|
||||
}
|
||||
defer p.Close()
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
c1 := p.Get()
|
||||
c1.Do("PING")
|
||||
@@ -133,6 +148,7 @@ func TestPoolError(t *testing.T) {
|
||||
MaxIdle: 2,
|
||||
Dial: d.dial,
|
||||
}
|
||||
defer p.Close()
|
||||
|
||||
c := p.Get()
|
||||
c.Do("ERR", io.EOF)
|
||||
@@ -154,6 +170,7 @@ func TestPoolClose(t *testing.T) {
|
||||
MaxIdle: 2,
|
||||
Dial: d.dial,
|
||||
}
|
||||
defer p.Close()
|
||||
|
||||
c1 := p.Get()
|
||||
c1.Do("PING")
|
||||
@@ -195,6 +212,7 @@ func TestPoolTimeout(t *testing.T) {
|
||||
IdleTimeout: 300 * time.Second,
|
||||
Dial: d.dial,
|
||||
}
|
||||
defer p.Close()
|
||||
|
||||
now := time.Now()
|
||||
redis.SetNowFunc(func() time.Time { return now })
|
||||
@@ -213,14 +231,14 @@ func TestPoolTimeout(t *testing.T) {
|
||||
c.Close()
|
||||
|
||||
d.check("2", p, 2, 1)
|
||||
|
||||
p.Close()
|
||||
}
|
||||
|
||||
func TestPoolConcurrenSendReceive(t *testing.T) {
|
||||
p := &redis.Pool{
|
||||
Dial: redistest.Dial,
|
||||
Dial: redis.DialDefaultServer,
|
||||
}
|
||||
defer p.Close()
|
||||
|
||||
c := p.Get()
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
@@ -238,7 +256,6 @@ func TestPoolConcurrenSendReceive(t *testing.T) {
|
||||
t.Fatalf("Do() returned error %v", err)
|
||||
}
|
||||
c.Close()
|
||||
p.Close()
|
||||
}
|
||||
|
||||
func TestPoolBorrowCheck(t *testing.T) {
|
||||
@@ -248,6 +265,7 @@ func TestPoolBorrowCheck(t *testing.T) {
|
||||
Dial: d.dial,
|
||||
TestOnBorrow: func(redis.Conn, time.Time) error { return redis.Error("BLAH") },
|
||||
}
|
||||
defer p.Close()
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
c := p.Get()
|
||||
@@ -255,7 +273,6 @@ func TestPoolBorrowCheck(t *testing.T) {
|
||||
c.Close()
|
||||
}
|
||||
d.check("1", p, 10, 1)
|
||||
p.Close()
|
||||
}
|
||||
|
||||
func TestPoolMaxActive(t *testing.T) {
|
||||
@@ -265,6 +282,8 @@ func TestPoolMaxActive(t *testing.T) {
|
||||
MaxActive: 2,
|
||||
Dial: d.dial,
|
||||
}
|
||||
defer p.Close()
|
||||
|
||||
c1 := p.Get()
|
||||
c1.Do("PING")
|
||||
c2 := p.Get()
|
||||
@@ -289,7 +308,6 @@ func TestPoolMaxActive(t *testing.T) {
|
||||
c3.Close()
|
||||
|
||||
d.check("4", p, 2, 2)
|
||||
p.Close()
|
||||
}
|
||||
|
||||
func TestPoolMonitorCleanup(t *testing.T) {
|
||||
@@ -299,12 +317,13 @@ func TestPoolMonitorCleanup(t *testing.T) {
|
||||
MaxActive: 2,
|
||||
Dial: d.dial,
|
||||
}
|
||||
defer p.Close()
|
||||
|
||||
c := p.Get()
|
||||
c.Send("MONITOR")
|
||||
c.Close()
|
||||
|
||||
d.check("", p, 1, 0)
|
||||
p.Close()
|
||||
}
|
||||
|
||||
func TestPoolPubSubCleanup(t *testing.T) {
|
||||
@@ -314,6 +333,7 @@ func TestPoolPubSubCleanup(t *testing.T) {
|
||||
MaxActive: 2,
|
||||
Dial: d.dial,
|
||||
}
|
||||
defer p.Close()
|
||||
|
||||
c := p.Get()
|
||||
c.Send("SUBSCRIBE", "x")
|
||||
@@ -334,8 +354,6 @@ func TestPoolPubSubCleanup(t *testing.T) {
|
||||
t.Errorf("got commands %v, want %v", d.commands, want)
|
||||
}
|
||||
d.commands = nil
|
||||
|
||||
p.Close()
|
||||
}
|
||||
|
||||
func TestPoolTransactionCleanup(t *testing.T) {
|
||||
@@ -345,6 +363,7 @@ func TestPoolTransactionCleanup(t *testing.T) {
|
||||
MaxActive: 2,
|
||||
Dial: d.dial,
|
||||
}
|
||||
defer p.Close()
|
||||
|
||||
c := p.Get()
|
||||
c.Do("WATCH", "key")
|
||||
@@ -406,8 +425,6 @@ func TestPoolTransactionCleanup(t *testing.T) {
|
||||
t.Errorf("got commands %v, want %v", d.commands, want)
|
||||
}
|
||||
d.commands = nil
|
||||
|
||||
p.Close()
|
||||
}
|
||||
|
||||
func startGoroutines(p *redis.Pool, cmd string, args ...interface{}) chan error {
|
||||
@@ -436,6 +453,7 @@ func TestWaitPool(t *testing.T) {
|
||||
Wait: true,
|
||||
}
|
||||
defer p.Close()
|
||||
|
||||
c := p.Get()
|
||||
errs := startGoroutines(p, "PING")
|
||||
d.check("before close", p, 1, 1)
|
||||
@@ -462,6 +480,8 @@ func TestWaitPoolClose(t *testing.T) {
|
||||
Dial: d.dial,
|
||||
Wait: true,
|
||||
}
|
||||
defer p.Close()
|
||||
|
||||
c := p.Get()
|
||||
if _, err := c.Do("PING"); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -497,6 +517,7 @@ func TestWaitPoolCommandError(t *testing.T) {
|
||||
Wait: true,
|
||||
}
|
||||
defer p.Close()
|
||||
|
||||
c := p.Get()
|
||||
errs := startGoroutines(p, "ERR", testErr)
|
||||
d.check("before close", p, 1, 1)
|
||||
@@ -525,6 +546,7 @@ func TestWaitPoolDialError(t *testing.T) {
|
||||
Wait: true,
|
||||
}
|
||||
defer p.Close()
|
||||
|
||||
c := p.Get()
|
||||
errs := startGoroutines(p, "ERR", testErr)
|
||||
d.check("before close", p, 1, 1)
|
||||
@@ -565,7 +587,7 @@ func TestWaitPoolDialError(t *testing.T) {
|
||||
// test ensures that iteration will work correctly if multiple threads are
|
||||
// iterating simultaneously.
|
||||
func TestLocking_TestOnBorrowFails_PoolDoesntCrash(t *testing.T) {
|
||||
count := 100
|
||||
const count = 100
|
||||
|
||||
// First we'll Create a pool where the pilfering of idle connections fails.
|
||||
d := poolDialer{t: t}
|
||||
@@ -580,29 +602,17 @@ func TestLocking_TestOnBorrowFails_PoolDoesntCrash(t *testing.T) {
|
||||
defer p.Close()
|
||||
|
||||
// Fill the pool with idle connections.
|
||||
b1 := sync.WaitGroup{}
|
||||
b1.Add(count)
|
||||
b2 := sync.WaitGroup{}
|
||||
b2.Add(count)
|
||||
for i := 0; i < count; i++ {
|
||||
go func() {
|
||||
c := p.Get()
|
||||
if c.Err() != nil {
|
||||
t.Errorf("pool get failed: %v", c.Err())
|
||||
}
|
||||
b1.Done()
|
||||
b1.Wait()
|
||||
c.Close()
|
||||
b2.Done()
|
||||
}()
|
||||
conns := make([]redis.Conn, count)
|
||||
for i := range conns {
|
||||
conns[i] = p.Get()
|
||||
}
|
||||
b2.Wait()
|
||||
if d.dialed != count {
|
||||
t.Errorf("Expected %d dials, got %d", count, d.dialed)
|
||||
for i := range conns {
|
||||
conns[i].Close()
|
||||
}
|
||||
|
||||
// Spawn a bunch of goroutines to thrash the pool.
|
||||
b2.Add(count)
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(count)
|
||||
for i := 0; i < count; i++ {
|
||||
go func() {
|
||||
c := p.Get()
|
||||
@@ -610,10 +620,10 @@ func TestLocking_TestOnBorrowFails_PoolDoesntCrash(t *testing.T) {
|
||||
t.Errorf("pool get failed: %v", c.Err())
|
||||
}
|
||||
c.Close()
|
||||
b2.Done()
|
||||
wg.Done()
|
||||
}()
|
||||
}
|
||||
b2.Wait()
|
||||
wg.Wait()
|
||||
if d.dialed != count*2 {
|
||||
t.Errorf("Expected %d dials, got %d", count*2, d.dialed)
|
||||
}
|
||||
@@ -621,7 +631,7 @@ func TestLocking_TestOnBorrowFails_PoolDoesntCrash(t *testing.T) {
|
||||
|
||||
func BenchmarkPoolGet(b *testing.B) {
|
||||
b.StopTimer()
|
||||
p := redis.Pool{Dial: redistest.Dial, MaxIdle: 2}
|
||||
p := redis.Pool{Dial: redis.DialDefaultServer, MaxIdle: 2}
|
||||
c := p.Get()
|
||||
if err := c.Err(); err != nil {
|
||||
b.Fatal(err)
|
||||
@@ -637,7 +647,7 @@ func BenchmarkPoolGet(b *testing.B) {
|
||||
|
||||
func BenchmarkPoolGetErr(b *testing.B) {
|
||||
b.StopTimer()
|
||||
p := redis.Pool{Dial: redistest.Dial, MaxIdle: 2}
|
||||
p := redis.Pool{Dial: redis.DialDefaultServer, MaxIdle: 2}
|
||||
c := p.Get()
|
||||
if err := c.Err(); err != nil {
|
||||
b.Fatal(err)
|
||||
@@ -656,7 +666,7 @@ func BenchmarkPoolGetErr(b *testing.B) {
|
||||
|
||||
func BenchmarkPoolGetPing(b *testing.B) {
|
||||
b.StopTimer()
|
||||
p := redis.Pool{Dial: redistest.Dial, MaxIdle: 2}
|
||||
p := redis.Pool{Dial: redis.DialDefaultServer, MaxIdle: 2}
|
||||
c := p.Get()
|
||||
if err := c.Err(); err != nil {
|
||||
b.Fatal(err)
|
||||
|
||||
22
Godeps/_workspace/src/github.com/garyburd/redigo/redis/pubsub_test.go
сгенерированный
поставляемый
22
Godeps/_workspace/src/github.com/garyburd/redigo/redis/pubsub_test.go
сгенерированный
поставляемый
@@ -16,20 +16,18 @@ package redis_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"reflect"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/garyburd/redigo/internal/redistest"
|
||||
"github.com/garyburd/redigo/redis"
|
||||
"github.com/mattermost/platform/Godeps/_workspace/src/github.com/garyburd/redigo/redis"
|
||||
)
|
||||
|
||||
func publish(channel, value interface{}) {
|
||||
c, err := dial()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
c.Do("PUBLISH", channel, value)
|
||||
@@ -39,7 +37,8 @@ func publish(channel, value interface{}) {
|
||||
func ExamplePubSubConn() {
|
||||
c, err := dial()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
var wg sync.WaitGroup
|
||||
@@ -111,20 +110,19 @@ func expectPushed(t *testing.T, c redis.PubSubConn, message string, expected int
|
||||
}
|
||||
|
||||
func TestPushed(t *testing.T) {
|
||||
pc, err := redistest.Dial()
|
||||
pc, err := redis.DialDefaultServer()
|
||||
if err != nil {
|
||||
t.Fatalf("error connection to database, %v", err)
|
||||
}
|
||||
defer pc.Close()
|
||||
|
||||
nc, err := net.Dial("tcp", ":6379")
|
||||
sc, err := redis.DialDefaultServer()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
t.Fatalf("error connection to database, %v", err)
|
||||
}
|
||||
defer nc.Close()
|
||||
nc.SetReadDeadline(time.Now().Add(4 * time.Second))
|
||||
defer sc.Close()
|
||||
|
||||
c := redis.PubSubConn{Conn: redis.NewConn(nc, 0, 0)}
|
||||
c := redis.PubSubConn{Conn: sc}
|
||||
|
||||
c.Subscribe("c1")
|
||||
expectPushed(t, c, "Subscribe(c1)", redis.Subscription{Kind: "subscribe", Channel: "c1", Count: 1})
|
||||
|
||||
37
Godeps/_workspace/src/github.com/garyburd/redigo/redis/reply.go
сгенерированный
поставляемый
37
Godeps/_workspace/src/github.com/garyburd/redigo/redis/reply.go
сгенерированный
поставляемый
@@ -215,7 +215,9 @@ func Bool(reply interface{}, err error) (bool, error) {
|
||||
return false, fmt.Errorf("redigo: unexpected type for Bool, got type %T", reply)
|
||||
}
|
||||
|
||||
// MultiBulk is deprecated. Use Values.
|
||||
// MultiBulk is a helper that converts an array command reply to a []interface{}.
|
||||
//
|
||||
// Deprecated: Use Values instead.
|
||||
func MultiBulk(reply interface{}, err error) ([]interface{}, error) { return Values(reply, err) }
|
||||
|
||||
// Values is a helper that converts an array command reply to a []interface{}.
|
||||
@@ -271,13 +273,40 @@ func Strings(reply interface{}, err error) ([]string, error) {
|
||||
return nil, fmt.Errorf("redigo: unexpected type for Strings, got type %T", reply)
|
||||
}
|
||||
|
||||
// ByteSlices is a helper that converts an array command reply to a [][]byte.
|
||||
// If err is not equal to nil, then ByteSlices returns nil, err. Nil array
|
||||
// items are stay nil. ByteSlices returns an error if an array item is not a
|
||||
// bulk string or nil.
|
||||
func ByteSlices(reply interface{}, err error) ([][]byte, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch reply := reply.(type) {
|
||||
case []interface{}:
|
||||
result := make([][]byte, len(reply))
|
||||
for i := range reply {
|
||||
if reply[i] == nil {
|
||||
continue
|
||||
}
|
||||
p, ok := reply[i].([]byte)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("redigo: unexpected element type for ByteSlices, got type %T", reply[i])
|
||||
}
|
||||
result[i] = p
|
||||
}
|
||||
return result, nil
|
||||
case nil:
|
||||
return nil, ErrNil
|
||||
case Error:
|
||||
return nil, reply
|
||||
}
|
||||
return nil, fmt.Errorf("redigo: unexpected type for ByteSlices, got type %T", reply)
|
||||
}
|
||||
|
||||
// Ints is a helper that converts an array command reply to a []int. If
|
||||
// err is not equal to nil, then Ints returns nil, err.
|
||||
func Ints(reply interface{}, err error) ([]int, error) {
|
||||
var ints []int
|
||||
if reply == nil {
|
||||
return ints, ErrNil
|
||||
}
|
||||
values, err := Values(reply, err)
|
||||
if err != nil {
|
||||
return ints, err
|
||||
|
||||
29
Godeps/_workspace/src/github.com/garyburd/redigo/redis/reply_test.go
сгенерированный
поставляемый
29
Godeps/_workspace/src/github.com/garyburd/redigo/redis/reply_test.go
сгенерированный
поставляемый
@@ -19,8 +19,7 @@ import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/garyburd/redigo/internal/redistest"
|
||||
"github.com/garyburd/redigo/redis"
|
||||
"github.com/mattermost/platform/Godeps/_workspace/src/github.com/garyburd/redigo/redis"
|
||||
)
|
||||
|
||||
type valueError struct {
|
||||
@@ -57,6 +56,16 @@ var replyTests = []struct {
|
||||
ve(redis.Strings(nil, nil)),
|
||||
ve([]string(nil), redis.ErrNil),
|
||||
},
|
||||
{
|
||||
"byteslices([v1, v2])",
|
||||
ve(redis.ByteSlices([]interface{}{[]byte("v1"), []byte("v2")}, nil)),
|
||||
ve([][]byte{[]byte("v1"), []byte("v2")}, nil),
|
||||
},
|
||||
{
|
||||
"byteslices(nil)",
|
||||
ve(redis.ByteSlices(nil, nil)),
|
||||
ve([][]byte(nil), redis.ErrNil),
|
||||
},
|
||||
{
|
||||
"values([v1, v2])",
|
||||
ve(redis.Values([]interface{}{[]byte("v1"), []byte("v2")}, nil)),
|
||||
@@ -101,15 +110,16 @@ func TestReply(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// dial wraps DialTestDB() with a more suitable function name for examples.
|
||||
// dial wraps DialDefaultServer() with a more suitable function name for examples.
|
||||
func dial() (redis.Conn, error) {
|
||||
return redistest.Dial()
|
||||
return redis.DialDefaultServer()
|
||||
}
|
||||
|
||||
func ExampleBool() {
|
||||
c, err := dial()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
@@ -123,7 +133,8 @@ func ExampleBool() {
|
||||
func ExampleInt() {
|
||||
c, err := dial()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
@@ -140,7 +151,8 @@ func ExampleInt() {
|
||||
func ExampleInts() {
|
||||
c, err := dial()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
@@ -154,7 +166,8 @@ func ExampleInts() {
|
||||
func ExampleString() {
|
||||
c, err := dial()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
|
||||
92
Godeps/_workspace/src/github.com/garyburd/redigo/redis/scan.go
сгенерированный
поставляемый
92
Godeps/_workspace/src/github.com/garyburd/redigo/redis/scan.go
сгенерированный
поставляемый
@@ -32,11 +32,25 @@ func ensureLen(d reflect.Value, n int) {
|
||||
}
|
||||
|
||||
func cannotConvert(d reflect.Value, s interface{}) error {
|
||||
return fmt.Errorf("redigo: Scan cannot convert from %s to %s",
|
||||
reflect.TypeOf(s), d.Type())
|
||||
var sname string
|
||||
switch s.(type) {
|
||||
case string:
|
||||
sname = "Redis simple string"
|
||||
case Error:
|
||||
sname = "Redis error"
|
||||
case int64:
|
||||
sname = "Redis integer"
|
||||
case []byte:
|
||||
sname = "Redis bulk string"
|
||||
case []interface{}:
|
||||
sname = "Redis array"
|
||||
default:
|
||||
sname = reflect.TypeOf(s).String()
|
||||
}
|
||||
return fmt.Errorf("cannot convert from %s to %s", sname, d.Type())
|
||||
}
|
||||
|
||||
func convertAssignBytes(d reflect.Value, s []byte) (err error) {
|
||||
func convertAssignBulkString(d reflect.Value, s []byte) (err error) {
|
||||
switch d.Type().Kind() {
|
||||
case reflect.Float32, reflect.Float64:
|
||||
var x float64
|
||||
@@ -98,7 +112,7 @@ func convertAssignInt(d reflect.Value, s int64) (err error) {
|
||||
func convertAssignValue(d reflect.Value, s interface{}) (err error) {
|
||||
switch s := s.(type) {
|
||||
case []byte:
|
||||
err = convertAssignBytes(d, s)
|
||||
err = convertAssignBulkString(d, s)
|
||||
case int64:
|
||||
err = convertAssignInt(d, s)
|
||||
default:
|
||||
@@ -107,7 +121,7 @@ func convertAssignValue(d reflect.Value, s interface{}) (err error) {
|
||||
return err
|
||||
}
|
||||
|
||||
func convertAssignValues(d reflect.Value, s []interface{}) error {
|
||||
func convertAssignArray(d reflect.Value, s []interface{}) error {
|
||||
if d.Type().Kind() != reflect.Slice {
|
||||
return cannotConvert(d, s)
|
||||
}
|
||||
@@ -144,7 +158,7 @@ func convertAssign(d interface{}, s interface{}) (err error) {
|
||||
if d := reflect.ValueOf(d); d.Type().Kind() != reflect.Ptr {
|
||||
err = cannotConvert(d, s)
|
||||
} else {
|
||||
err = convertAssignBytes(d.Elem(), s)
|
||||
err = convertAssignBulkString(d.Elem(), s)
|
||||
}
|
||||
}
|
||||
case int64:
|
||||
@@ -169,6 +183,13 @@ func convertAssign(d interface{}, s interface{}) (err error) {
|
||||
err = convertAssignInt(d.Elem(), s)
|
||||
}
|
||||
}
|
||||
case string:
|
||||
switch d := d.(type) {
|
||||
case *string:
|
||||
*d = string(s)
|
||||
default:
|
||||
err = cannotConvert(reflect.ValueOf(d), s)
|
||||
}
|
||||
case []interface{}:
|
||||
switch d := d.(type) {
|
||||
case *[]interface{}:
|
||||
@@ -181,7 +202,7 @@ func convertAssign(d interface{}, s interface{}) (err error) {
|
||||
if d := reflect.ValueOf(d); d.Type().Kind() != reflect.Ptr {
|
||||
err = cannotConvert(d, s)
|
||||
} else {
|
||||
err = convertAssignValues(d.Elem(), s)
|
||||
err = convertAssignArray(d.Elem(), s)
|
||||
}
|
||||
}
|
||||
case Error:
|
||||
@@ -206,12 +227,13 @@ func convertAssign(d interface{}, s interface{}) (err error) {
|
||||
// following the copied values.
|
||||
func Scan(src []interface{}, dest ...interface{}) ([]interface{}, error) {
|
||||
if len(src) < len(dest) {
|
||||
return nil, errors.New("redigo: Scan array short")
|
||||
return nil, errors.New("redigo.Scan: array short")
|
||||
}
|
||||
var err error
|
||||
for i, d := range dest {
|
||||
err = convertAssign(d, src[i])
|
||||
if err != nil {
|
||||
err = fmt.Errorf("redigo.Scan: cannot assign to dest %d: %v", i, err)
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -219,9 +241,9 @@ func Scan(src []interface{}, dest ...interface{}) ([]interface{}, error) {
|
||||
}
|
||||
|
||||
type fieldSpec struct {
|
||||
name string
|
||||
index []int
|
||||
//omitEmpty bool
|
||||
name string
|
||||
index []int
|
||||
omitEmpty bool
|
||||
}
|
||||
|
||||
type structSpec struct {
|
||||
@@ -237,7 +259,7 @@ func compileStructSpec(t reflect.Type, depth map[string]int, index []int, ss *st
|
||||
for i := 0; i < t.NumField(); i++ {
|
||||
f := t.Field(i)
|
||||
switch {
|
||||
case f.PkgPath != "":
|
||||
case f.PkgPath != "" && !f.Anonymous:
|
||||
// Ignore unexported fields.
|
||||
case f.Anonymous:
|
||||
// TODO: Handle pointers. Requires change to decoder and
|
||||
@@ -258,10 +280,10 @@ func compileStructSpec(t reflect.Type, depth map[string]int, index []int, ss *st
|
||||
}
|
||||
for _, s := range p[1:] {
|
||||
switch s {
|
||||
//case "omitempty":
|
||||
// fs.omitempty = true
|
||||
case "omitempty":
|
||||
fs.omitEmpty = true
|
||||
default:
|
||||
panic(errors.New("redigo: unknown field flag " + s + " for type " + t.Name()))
|
||||
panic(fmt.Errorf("redigo: unknown field tag %s for type %s", s, t.Name()))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -321,7 +343,7 @@ func structSpecForType(t reflect.Type) *structSpec {
|
||||
return ss
|
||||
}
|
||||
|
||||
var errScanStructValue = errors.New("redigo: ScanStruct value must be non-nil pointer to a struct")
|
||||
var errScanStructValue = errors.New("redigo.ScanStruct: value must be non-nil pointer to a struct")
|
||||
|
||||
// ScanStruct scans alternating names and values from src to a struct. The
|
||||
// HGETALL and CONFIG GET commands return replies in this format.
|
||||
@@ -350,7 +372,7 @@ func ScanStruct(src []interface{}, dest interface{}) error {
|
||||
ss := structSpecForType(d.Type())
|
||||
|
||||
if len(src)%2 != 0 {
|
||||
return errors.New("redigo: ScanStruct expects even number of values in values")
|
||||
return errors.New("redigo.ScanStruct: number of values not a multiple of 2")
|
||||
}
|
||||
|
||||
for i := 0; i < len(src); i += 2 {
|
||||
@@ -360,21 +382,21 @@ func ScanStruct(src []interface{}, dest interface{}) error {
|
||||
}
|
||||
name, ok := src[i].([]byte)
|
||||
if !ok {
|
||||
return errors.New("redigo: ScanStruct key not a bulk string value")
|
||||
return fmt.Errorf("redigo.ScanStruct: key %d not a bulk string value", i)
|
||||
}
|
||||
fs := ss.fieldSpec(name)
|
||||
if fs == nil {
|
||||
continue
|
||||
}
|
||||
if err := convertAssignValue(d.FieldByIndex(fs.index), s); err != nil {
|
||||
return err
|
||||
return fmt.Errorf("redigo.ScanStruct: cannot assign field %s: %v", fs.name, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var (
|
||||
errScanSliceValue = errors.New("redigo: ScanSlice dest must be non-nil pointer to a struct")
|
||||
errScanSliceValue = errors.New("redigo.ScanSlice: dest must be non-nil pointer to a struct")
|
||||
)
|
||||
|
||||
// ScanSlice scans src to the slice pointed to by dest. The elements the dest
|
||||
@@ -407,7 +429,7 @@ func ScanSlice(src []interface{}, dest interface{}, fieldNames ...string) error
|
||||
continue
|
||||
}
|
||||
if err := convertAssignValue(d.Index(i), s); err != nil {
|
||||
return err
|
||||
return fmt.Errorf("redigo.ScanSlice: cannot assign element %d: %v", i, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -420,18 +442,18 @@ func ScanSlice(src []interface{}, dest interface{}, fieldNames ...string) error
|
||||
for i, name := range fieldNames {
|
||||
fss[i] = ss.m[name]
|
||||
if fss[i] == nil {
|
||||
return errors.New("redigo: ScanSlice bad field name " + name)
|
||||
return fmt.Errorf("redigo.ScanSlice: ScanSlice bad field name %s", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(fss) == 0 {
|
||||
return errors.New("redigo: ScanSlice no struct fields")
|
||||
return errors.New("redigo.ScanSlice: no struct fields")
|
||||
}
|
||||
|
||||
n := len(src) / len(fss)
|
||||
if n*len(fss) != len(src) {
|
||||
return errors.New("redigo: ScanSlice length not a multiple of struct field count")
|
||||
return errors.New("redigo.ScanSlice: length not a multiple of struct field count")
|
||||
}
|
||||
|
||||
ensureLen(d, n)
|
||||
@@ -449,7 +471,7 @@ func ScanSlice(src []interface{}, dest interface{}, fieldNames ...string) error
|
||||
continue
|
||||
}
|
||||
if err := convertAssignValue(d.FieldByIndex(fs.index), s); err != nil {
|
||||
return err
|
||||
return fmt.Errorf("redigo.ScanSlice: cannot assign element %d to field %s: %v", i*len(fss)+j, fs.name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -507,6 +529,26 @@ func flattenStruct(args Args, v reflect.Value) Args {
|
||||
ss := structSpecForType(v.Type())
|
||||
for _, fs := range ss.l {
|
||||
fv := v.FieldByIndex(fs.index)
|
||||
if fs.omitEmpty {
|
||||
var empty = false
|
||||
switch fv.Kind() {
|
||||
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
|
||||
empty = fv.Len() == 0
|
||||
case reflect.Bool:
|
||||
empty = !fv.Bool()
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
empty = fv.Int() == 0
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
|
||||
empty = fv.Uint() == 0
|
||||
case reflect.Float32, reflect.Float64:
|
||||
empty = fv.Float() == 0
|
||||
case reflect.Interface, reflect.Ptr:
|
||||
empty = fv.IsNil()
|
||||
}
|
||||
if empty {
|
||||
continue
|
||||
}
|
||||
}
|
||||
args = append(args, fs.name, fv.Interface())
|
||||
}
|
||||
return args
|
||||
|
||||
64
Godeps/_workspace/src/github.com/garyburd/redigo/redis/scan_test.go
сгенерированный
поставляемый
64
Godeps/_workspace/src/github.com/garyburd/redigo/redis/scan_test.go
сгенерированный
поставляемый
@@ -16,10 +16,11 @@ package redis_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/garyburd/redigo/redis"
|
||||
"math"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/mattermost/platform/Godeps/_workspace/src/github.com/garyburd/redigo/redis"
|
||||
)
|
||||
|
||||
var scanConversionTests = []struct {
|
||||
@@ -46,6 +47,7 @@ var scanConversionTests = []struct {
|
||||
{[]byte("1"), true},
|
||||
{int64(1), true},
|
||||
{[]byte("t"), true},
|
||||
{"hello", "hello"},
|
||||
{[]byte("hello"), "hello"},
|
||||
{[]byte("world"), []byte("world")},
|
||||
{[]interface{}{[]byte("foo")}, []interface{}{[]byte("foo")}},
|
||||
@@ -100,7 +102,8 @@ func TestScanConversionError(t *testing.T) {
|
||||
func ExampleScan() {
|
||||
c, err := dial()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
@@ -115,7 +118,8 @@ func ExampleScan() {
|
||||
"GET", "album:*->title",
|
||||
"GET", "album:*->rating"))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
for len(values) > 0 {
|
||||
@@ -123,7 +127,8 @@ func ExampleScan() {
|
||||
rating := -1 // initialize to illegal value to detect nil.
|
||||
values, err = redis.Scan(values, &title, &rating)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
if rating == -1 {
|
||||
fmt.Println(title, "not-rated")
|
||||
@@ -295,7 +300,8 @@ func TestScanSlice(t *testing.T) {
|
||||
func ExampleScanSlice() {
|
||||
c, err := dial()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
@@ -310,7 +316,8 @@ func ExampleScanSlice() {
|
||||
"GET", "album:*->title",
|
||||
"GET", "album:*->rating"))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
var albums []struct {
|
||||
@@ -318,7 +325,8 @@ func ExampleScanSlice() {
|
||||
Rating int
|
||||
}
|
||||
if err := redis.ScanSlice(values, &albums); err != nil {
|
||||
panic(err)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
fmt.Printf("%v\n", albums)
|
||||
// Output:
|
||||
@@ -332,16 +340,17 @@ var argsTests = []struct {
|
||||
}{
|
||||
{"struct ptr",
|
||||
redis.Args{}.AddFlat(&struct {
|
||||
I int `redis:"i"`
|
||||
U uint `redis:"u"`
|
||||
S string `redis:"s"`
|
||||
P []byte `redis:"p"`
|
||||
I int `redis:"i"`
|
||||
U uint `redis:"u"`
|
||||
S string `redis:"s"`
|
||||
P []byte `redis:"p"`
|
||||
M map[string]string `redis:"m"`
|
||||
Bt bool
|
||||
Bf bool
|
||||
}{
|
||||
-1234, 5678, "hello", []byte("world"), true, false,
|
||||
-1234, 5678, "hello", []byte("world"), map[string]string{"hello": "world"}, true, false,
|
||||
}),
|
||||
redis.Args{"i", int(-1234), "u", uint(5678), "s", "hello", "p", []byte("world"), "Bt", true, "Bf", false},
|
||||
redis.Args{"i", int(-1234), "u", uint(5678), "s", "hello", "p", []byte("world"), "m", map[string]string{"hello": "world"}, "Bt", true, "Bf", false},
|
||||
},
|
||||
{"struct",
|
||||
redis.Args{}.AddFlat(struct{ I int }{123}),
|
||||
@@ -351,6 +360,20 @@ var argsTests = []struct {
|
||||
redis.Args{}.Add(1).AddFlat([]string{"a", "b", "c"}).Add(2),
|
||||
redis.Args{1, "a", "b", "c", 2},
|
||||
},
|
||||
{"struct omitempty",
|
||||
redis.Args{}.AddFlat(&struct {
|
||||
I int `redis:"i,omitempty"`
|
||||
U uint `redis:"u,omitempty"`
|
||||
S string `redis:"s,omitempty"`
|
||||
P []byte `redis:"p,omitempty"`
|
||||
M map[string]string `redis:"m,omitempty"`
|
||||
Bt bool `redis:"Bt,omitempty"`
|
||||
Bf bool `redis:"Bf,omitempty"`
|
||||
}{
|
||||
0, 0, "", []byte{}, map[string]string{}, true, false,
|
||||
}),
|
||||
redis.Args{"Bt", true},
|
||||
},
|
||||
}
|
||||
|
||||
func TestArgs(t *testing.T) {
|
||||
@@ -364,7 +387,8 @@ func TestArgs(t *testing.T) {
|
||||
func ExampleArgs() {
|
||||
c, err := dial()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
@@ -379,7 +403,8 @@ func ExampleArgs() {
|
||||
p1.Body = "Hello"
|
||||
|
||||
if _, err := c.Do("HMSET", redis.Args{}.Add("id1").AddFlat(&p1)...); err != nil {
|
||||
panic(err)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
m := map[string]string{
|
||||
@@ -389,18 +414,21 @@ func ExampleArgs() {
|
||||
}
|
||||
|
||||
if _, err := c.Do("HMSET", redis.Args{}.Add("id2").AddFlat(m)...); err != nil {
|
||||
panic(err)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
for _, id := range []string{"id1", "id2"} {
|
||||
|
||||
v, err := redis.Values(c.Do("HGETALL", id))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := redis.ScanStruct(v, &p2); err != nil {
|
||||
panic(err)
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("%+v\n", p2)
|
||||
|
||||
5
Godeps/_workspace/src/github.com/garyburd/redigo/redis/script_test.go
сгенерированный
поставляемый
5
Godeps/_workspace/src/github.com/garyburd/redigo/redis/script_test.go
сгенерированный
поставляемый
@@ -20,8 +20,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/garyburd/redigo/internal/redistest"
|
||||
"github.com/garyburd/redigo/redis"
|
||||
"github.com/mattermost/platform/Godeps/_workspace/src/github.com/garyburd/redigo/redis"
|
||||
)
|
||||
|
||||
func ExampleScript(c redis.Conn, reply interface{}, err error) {
|
||||
@@ -35,7 +34,7 @@ func ExampleScript(c redis.Conn, reply interface{}, err error) {
|
||||
}
|
||||
|
||||
func TestScript(t *testing.T) {
|
||||
c, err := redistest.Dial()
|
||||
c, err := redis.DialDefaultServer()
|
||||
if err != nil {
|
||||
t.Fatalf("error connection to database, %v", err)
|
||||
}
|
||||
|
||||
159
Godeps/_workspace/src/github.com/garyburd/redigo/redis/test_test.go
сгенерированный
поставляемый
159
Godeps/_workspace/src/github.com/garyburd/redigo/redis/test_test.go
сгенерированный
поставляемый
@@ -16,7 +16,17 @@ package redis
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"net"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -24,15 +34,144 @@ func SetNowFunc(f func() time.Time) {
|
||||
nowFunc = f
|
||||
}
|
||||
|
||||
type nopCloser struct{ net.Conn }
|
||||
|
||||
func (nopCloser) Close() error { return nil }
|
||||
|
||||
// NewConnBufio is a hook for tests.
|
||||
func NewConnBufio(rw bufio.ReadWriter) Conn {
|
||||
return &conn{br: rw.Reader, bw: rw.Writer, conn: nopCloser{}}
|
||||
}
|
||||
|
||||
var (
|
||||
ErrNegativeInt = errNegativeInt
|
||||
|
||||
serverPath = flag.String("redis-server", "redis-server", "Path to redis server binary")
|
||||
serverBasePort = flag.Int("redis-port", 16379, "Beginning of port range for test servers")
|
||||
serverLogName = flag.String("redis-log", "", "Write Redis server logs to `filename`")
|
||||
serverLog = ioutil.Discard
|
||||
|
||||
defaultServerMu sync.Mutex
|
||||
defaultServer *Server
|
||||
defaultServerErr error
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
name string
|
||||
cmd *exec.Cmd
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
func NewServer(name string, args ...string) (*Server, error) {
|
||||
s := &Server{
|
||||
name: name,
|
||||
cmd: exec.Command(*serverPath, args...),
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
|
||||
r, err := s.cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = s.cmd.Start()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ready := make(chan error, 1)
|
||||
go s.watch(r, ready)
|
||||
|
||||
select {
|
||||
case err = <-ready:
|
||||
case <-time.After(time.Second * 10):
|
||||
err = errors.New("timeout waiting for server to start")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
s.Stop()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *Server) watch(r io.Reader, ready chan error) {
|
||||
fmt.Fprintf(serverLog, "%d START %s \n", s.cmd.Process.Pid, s.name)
|
||||
var listening bool
|
||||
var text string
|
||||
scn := bufio.NewScanner(r)
|
||||
for scn.Scan() {
|
||||
text = scn.Text()
|
||||
fmt.Fprintf(serverLog, "%s\n", text)
|
||||
if !listening {
|
||||
if strings.Contains(text, "The server is now ready to accept connections on port") {
|
||||
listening = true
|
||||
ready <- nil
|
||||
}
|
||||
}
|
||||
}
|
||||
if !listening {
|
||||
ready <- fmt.Errorf("server exited: %s", text)
|
||||
}
|
||||
s.cmd.Wait()
|
||||
fmt.Fprintf(serverLog, "%d STOP %s \n", s.cmd.Process.Pid, s.name)
|
||||
close(s.done)
|
||||
}
|
||||
|
||||
func (s *Server) Stop() {
|
||||
s.cmd.Process.Signal(os.Interrupt)
|
||||
<-s.done
|
||||
}
|
||||
|
||||
// stopDefaultServer stops the server created by DialDefaultServer.
|
||||
func stopDefaultServer() {
|
||||
defaultServerMu.Lock()
|
||||
defer defaultServerMu.Unlock()
|
||||
if defaultServer != nil {
|
||||
defaultServer.Stop()
|
||||
defaultServer = nil
|
||||
}
|
||||
}
|
||||
|
||||
// startDefaultServer starts the default server if not already running.
|
||||
func startDefaultServer() error {
|
||||
defaultServerMu.Lock()
|
||||
defer defaultServerMu.Unlock()
|
||||
if defaultServer != nil || defaultServerErr != nil {
|
||||
return defaultServerErr
|
||||
}
|
||||
defaultServer, defaultServerErr = NewServer(
|
||||
"default",
|
||||
"--port", strconv.Itoa(*serverBasePort),
|
||||
"--save", "",
|
||||
"--appendonly", "no")
|
||||
return defaultServerErr
|
||||
}
|
||||
|
||||
// DialDefaultServer starts the test server if not already started and dials a
|
||||
// connection to the server.
|
||||
func DialDefaultServer() (Conn, error) {
|
||||
if err := startDefaultServer(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c, err := Dial("tcp", fmt.Sprintf(":%d", *serverBasePort), DialReadTimeout(1*time.Second), DialWriteTimeout(1*time.Second))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.Do("FLUSHDB")
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
os.Exit(func() int {
|
||||
flag.Parse()
|
||||
|
||||
var f *os.File
|
||||
if *serverLogName != "" {
|
||||
var err error
|
||||
f, err = os.OpenFile(*serverLogName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error opening redis-log: %v\n", err)
|
||||
return 1
|
||||
}
|
||||
defer f.Close()
|
||||
serverLog = f
|
||||
}
|
||||
|
||||
defer stopDefaultServer()
|
||||
|
||||
return m.Run()
|
||||
}())
|
||||
}
|
||||
|
||||
2
Godeps/_workspace/src/github.com/garyburd/redigo/redis/zpop_example_test.go
сгенерированный
поставляемый
2
Godeps/_workspace/src/github.com/garyburd/redigo/redis/zpop_example_test.go
сгенерированный
поставляемый
@@ -16,7 +16,7 @@ package redis_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/garyburd/redigo/redis"
|
||||
"github.com/mattermost/platform/Godeps/_workspace/src/github.com/garyburd/redigo/redis"
|
||||
)
|
||||
|
||||
// zpop pops a value from the ZSET key using WATCH/MULTI/EXEC commands.
|
||||
|
||||
35
Godeps/_workspace/src/github.com/go-gorp/gorp/.travis.yml
сгенерированный
поставляемый
35
Godeps/_workspace/src/github.com/go-gorp/gorp/.travis.yml
сгенерированный
поставляемый
@@ -1,23 +1,28 @@
|
||||
language: go
|
||||
go:
|
||||
- 1.2
|
||||
- 1.3
|
||||
- 1.4
|
||||
- tip
|
||||
- 1.3
|
||||
- 1.4
|
||||
- tip
|
||||
|
||||
services:
|
||||
- mysql
|
||||
- postgres
|
||||
- sqlite3
|
||||
- mysql
|
||||
- postgres
|
||||
- sqlite3
|
||||
|
||||
env:
|
||||
global:
|
||||
- secure: RriLxF6+2yMl67hdVv8ImXlu0h62mhcpqjaOgYNU+IEbUQ7hx96CKY6gkpYubW3BgApvF5RH6j3+HKvh2kGp0XhDOYOQCODfBSaSipZ5Aa5RKjsEYLtuVIobvJ80awR9hUeql69+WXs0/s72WThG0qTbOUY4pqHWfteeY235hWM=
|
||||
|
||||
before_script:
|
||||
- mysql -e "CREATE DATABASE gorptest;"
|
||||
- mysql -u root -e "GRANT ALL ON gorptest.* TO gorptest@localhost IDENTIFIED BY 'gorptest'"
|
||||
- psql -c "CREATE DATABASE gorptest;" -U postgres
|
||||
- psql -c "CREATE USER "gorptest" WITH SUPERUSER PASSWORD 'gorptest';" -U postgres
|
||||
- go get github.com/lib/pq
|
||||
- go get github.com/mattn/go-sqlite3
|
||||
- go get github.com/ziutek/mymysql/godrv
|
||||
- go get github.com/go-sql-driver/mysql
|
||||
- mysql -e "CREATE DATABASE gorptest;"
|
||||
- mysql -u root -e "GRANT ALL ON gorptest.* TO gorptest@localhost IDENTIFIED BY 'gorptest'"
|
||||
- psql -c "CREATE DATABASE gorptest;" -U postgres
|
||||
- psql -c "CREATE USER "gorptest" WITH SUPERUSER PASSWORD 'gorptest';" -U postgres
|
||||
- go get github.com/lib/pq
|
||||
- go get github.com/mattn/go-sqlite3
|
||||
- go get github.com/ziutek/mymysql/godrv
|
||||
- go get github.com/go-sql-driver/mysql
|
||||
- go get golang.org/x/tools/cmd/cover
|
||||
- go get github.com/mattn/goveralls
|
||||
|
||||
script: ./test_all.sh
|
||||
|
||||
6
Godeps/_workspace/src/github.com/go-gorp/gorp/Makefile
сгенерированный
поставляемый
6
Godeps/_workspace/src/github.com/go-gorp/gorp/Makefile
сгенерированный
поставляемый
@@ -1,6 +0,0 @@
|
||||
include $(GOROOT)/src/Make.inc
|
||||
|
||||
TARG = github.com/go-gorp/gorp
|
||||
GOFILES = gorp.go dialect.go
|
||||
|
||||
include $(GOROOT)/src/Make.pkg
|
||||
119
Godeps/_workspace/src/github.com/go-gorp/gorp/README.md
сгенерированный
поставляемый
119
Godeps/_workspace/src/github.com/go-gorp/gorp/README.md
сгенерированный
поставляемый
@@ -1,19 +1,26 @@
|
||||
# Go Relational Persistence
|
||||
|
||||
[](http://travis-ci.org/go-gorp/gorp)
|
||||
[](http://travis-ci.org/go-gorp/gorp)
|
||||
[](https://coveralls.io/r/go-gorp/gorp)
|
||||
[](https://github.com/go-gorp/gorp/issues)
|
||||
[](https://godoc.org/gopkg.in/gorp.v1)
|
||||
[](https://godoc.org/github.com/go-gorp/gorp)
|
||||
|
||||
I hesitate to call gorp an ORM. Go doesn't really have objects, at least
|
||||
not in the classic Smalltalk/Java sense. There goes the "O". gorp doesn't
|
||||
know anything about the relationships between your structs (at least not
|
||||
yet). So the "R" is questionable too (but I use it in the name because,
|
||||
well, it seemed more clever).
|
||||
### Update 2015-07-01 Cleanup & feature freeze ([#270](https://github.com/go-gorp/gorp/issues/270))
|
||||
|
||||
The "M" is alive and well. Given some Go structs and a database, gorp
|
||||
should remove a fair amount of boilerplate busy-work from your code.
|
||||
We are currently cleaning up the backlog of issues and PR's. When this is done the codebase will be split into separate files and there will be breaking changes to the API's. We're also adding better tests and documentation. As a result of these changes the `master` branch will be unstable. Please use `gopkg.in/gorp.v1`. When the cleanup and changes are done, we will release `v2.0`.
|
||||
|
||||
I hope that gorp saves you time, minimizes the drudgery of getting data
|
||||
in and out of your database, and helps your code focus on algorithms,
|
||||
not infrastructure.
|
||||
At this time we won't accept new feature-related pull-requests because of changes to the codebase. Please create an issue for your feature and wait until `v2.0` has been released.
|
||||
|
||||
For more information, please read [#270](https://github.com/go-gorp/gorp/issues/270).
|
||||
|
||||
## Introduction
|
||||
|
||||
I hesitate to call gorp an ORM. Go doesn't really have objects, at least not in the classic Smalltalk/Java sense. There goes the "O". gorp doesn't know anything about the relationships between your structs (at least not yet). So the "R" is questionable too (but I use it in the name because, well, it seemed more clever).
|
||||
|
||||
The "M" is alive and well. Given some Go structs and a database, gorp should remove a fair amount of boilerplate busy-work from your code.
|
||||
|
||||
I hope that gorp saves you time, minimizes the drudgery of getting data in and out of your database, and helps your code focus on algorithms, not infrastructure.
|
||||
|
||||
* Bind struct fields to table columns via API or tag
|
||||
* Support for embedded structs
|
||||
@@ -34,7 +41,7 @@ not infrastructure.
|
||||
|
||||
# install the library:
|
||||
go get gopkg.in/gorp.v1
|
||||
|
||||
|
||||
// use in your .go code:
|
||||
import (
|
||||
"gopkg.in/gorp.v1"
|
||||
@@ -143,10 +150,10 @@ func main() {
|
||||
|
||||
type Post struct {
|
||||
// db tag lets you specify the column name if it differs from the struct field
|
||||
Id int64 `db:"post_id"`
|
||||
Id int64 `db:"post_id"`
|
||||
Created int64
|
||||
Title string
|
||||
Body string
|
||||
Title string `db:",size:50"` // Column size set to 50
|
||||
Body string `db:"article_body,size:1024"` // Set both column name and size
|
||||
}
|
||||
|
||||
func newPost(title, body string) Post {
|
||||
@@ -201,7 +208,7 @@ type Invoice struct {
|
||||
}
|
||||
|
||||
type Person struct {
|
||||
Id int64
|
||||
Id int64
|
||||
Created int64
|
||||
Updated int64
|
||||
FName string
|
||||
@@ -221,8 +228,10 @@ type Person struct {
|
||||
// table.ColMap("Price").Rename("unit_price")
|
||||
// table.ColMap("IgnoreMe").SetTransient(true)
|
||||
//
|
||||
// You can optionally declare the field to be a primary key and/or autoincrement
|
||||
//
|
||||
type Product struct {
|
||||
Id int64 `db:"product_id"`
|
||||
Id int64 `db:"product_id, primarykey, autoincrement"`
|
||||
Price int64 `db:"unit_price"`
|
||||
IgnoreMe string `db:"-"`
|
||||
}
|
||||
@@ -239,7 +248,7 @@ db, err := sql.Open("mymysql", "tcp:localhost:3306*mydb/myuser/mypassword")
|
||||
dbmap := &gorp.DbMap{Db: db, Dialect: gorp.MySQLDialect{"InnoDB", "UTF8"}}
|
||||
|
||||
// register the structs you wish to use with gorp
|
||||
// you can also use the shorter dbmap.AddTable() if you
|
||||
// you can also use the shorter dbmap.AddTable() if you
|
||||
// don't want to override the table name
|
||||
//
|
||||
// SetKeys(true) means we have a auto increment primary key, which
|
||||
@@ -296,13 +305,13 @@ I recommend enabling this initially while you're getting the feel for what
|
||||
gorp is doing on your behalf.
|
||||
|
||||
Gorp defines a `GorpLogger` interface that Go's built in `log.Logger` satisfies.
|
||||
However, you can write your own `GorpLogger` implementation, or use a package such
|
||||
However, you can write your own `GorpLogger` implementation, or use a package such
|
||||
as `glog` if you want more control over how statements are logged.
|
||||
|
||||
```go
|
||||
// Will log all SQL statements + args as they are run
|
||||
// The first arg is a string prefix to prepend to all log messages
|
||||
dbmap.TraceOn("[gorp]", log.New(os.Stdout, "myapp:", log.Lmicroseconds))
|
||||
dbmap.TraceOn("[gorp]", log.New(os.Stdout, "myapp:", log.Lmicroseconds))
|
||||
|
||||
// Turn off tracing
|
||||
dbmap.TraceOff()
|
||||
@@ -435,7 +444,7 @@ only supported in SELECT queries.
|
||||
|
||||
```go
|
||||
_, err := dbm.Select(&dest, "select * from Foo where name = :name and age = :age", map[string]interface{}{
|
||||
"name": "Rob",
|
||||
"name": "Rob",
|
||||
"age": 31,
|
||||
})
|
||||
```
|
||||
@@ -509,11 +518,11 @@ Full list of hooks that you can implement:
|
||||
PostUpdate
|
||||
PreDelete
|
||||
PostDelete
|
||||
|
||||
|
||||
All have the same signature. for example:
|
||||
|
||||
|
||||
func (p *MyStruct) PostUpdate(s gorp.SqlExecutor) error
|
||||
|
||||
|
||||
### Optimistic Locking
|
||||
|
||||
#### Note that this behaviour has changed in v2. See [Migration Guide](#migration-guide).
|
||||
@@ -536,7 +545,7 @@ type Person struct {
|
||||
Updated int64
|
||||
FName string
|
||||
LName string
|
||||
|
||||
|
||||
// automatically used as the Version col
|
||||
// use table.SetVersionCol("columnName") to map a different
|
||||
// struct field as the version field
|
||||
@@ -558,7 +567,7 @@ count, err := dbmap.Update(p1)
|
||||
_, ok := err.(gorp.OptimisticLockError)
|
||||
if ok {
|
||||
// should reach this statement
|
||||
|
||||
|
||||
// in a real app you might reload the row and retry, or
|
||||
// you might propegate this to the user, depending on the desired
|
||||
// semantics
|
||||
@@ -568,6 +577,49 @@ if ok {
|
||||
fmt.Printf("Unknown db err: %v\n", err)
|
||||
}
|
||||
```
|
||||
### Adding INDEX(es) on column(s) beyond the primary key ###
|
||||
|
||||
Indexes are frequently critical for performance. Here is how to add them to your tables.
|
||||
|
||||
NB: SqlServer and Oracle need testing and possible adjustment to the
|
||||
CreateIndexSuffix() and DropIndexSuffix() methods to make AddIndex()
|
||||
work for them.
|
||||
|
||||
In the example below we put an index both on the Id field, and on the AcctId field.
|
||||
|
||||
```
|
||||
type Account struct {
|
||||
Id int64
|
||||
AcctId string // e.g. this might be a long uuid for portability
|
||||
}
|
||||
|
||||
// indexType (the 2nd param to AddIndex call) is "Btree" or "Hash" for MySQL.
|
||||
// demonstrate adding a second index on AcctId, and constrain that field to have unique values.
|
||||
dbm.AddTable(iptab.Account{}).SetKeys(true, "Id").AddIndex("AcctIdIndex", "Btree", []string{"AcctId"}).SetUnique(true)
|
||||
|
||||
err = dbm.CreateTablesIfNotExists()
|
||||
checkErr(err, "CreateTablesIfNotExists failed")
|
||||
|
||||
err = dbm.CreateIndex()
|
||||
checkErr(err, "CreateIndex failed")
|
||||
|
||||
```
|
||||
Check the effect of the CreateIndex() call in mysql:
|
||||
```
|
||||
$ mysql
|
||||
|
||||
MariaDB [test]> show create table Account;
|
||||
+---------+--------------------------+
|
||||
| Account | CREATE TABLE `Account` (
|
||||
`Id` bigint(20) NOT NULL AUTO_INCREMENT,
|
||||
`AcctId` varchar(255) DEFAULT NULL,
|
||||
PRIMARY KEY (`Id`),
|
||||
UNIQUE KEY `AcctIdIndex` (`AcctId`) USING BTREE <<<--- yes! index added.
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8
|
||||
+---------+--------------------------+
|
||||
|
||||
```
|
||||
|
||||
|
||||
## Database Drivers
|
||||
|
||||
@@ -582,13 +634,13 @@ implemented per database vendor. Dialects are provided for:
|
||||
* PostgreSQL
|
||||
* sqlite3
|
||||
|
||||
Each of these three databases pass the test suite. See `gorp_test.go` for example
|
||||
Each of these three databases pass the test suite. See `gorp_test.go` for example
|
||||
DSNs for these three databases.
|
||||
|
||||
Support is also provided for:
|
||||
|
||||
* Oracle (contributed by @klaidliadon)
|
||||
* SQL Server (contributed by @qrawl) - use driver: github.com/denisenkom/go-mssqldb
|
||||
* SQL Server (contributed by @qrawl) - use driver: github.com/denisenkom/go-mssqldb
|
||||
|
||||
Note that these databases are not covered by CI and I (@coopernurse) have no good way to
|
||||
test them locally. So please try them and send patches as needed, but expect a bit more
|
||||
@@ -598,7 +650,7 @@ unpredicability.
|
||||
|
||||
### SQL placeholder portability
|
||||
|
||||
Different databases use different strings to indicate variable placeholders in
|
||||
Different databases use different strings to indicate variable placeholders in
|
||||
prepared SQL statements. Unlike some database abstraction layers (such as JDBC),
|
||||
Go's `database/sql` does not standardize this.
|
||||
|
||||
@@ -617,13 +669,18 @@ In `Select` and `SelectOne` you can use named parameters to work around this.
|
||||
The following is portable:
|
||||
|
||||
```go
|
||||
err := dbmap.SelectOne(&val, "select * from foo where id = :id",
|
||||
err := dbmap.SelectOne(&val, "select * from foo where id = :id",
|
||||
map[string]interface{} { "id": 30})
|
||||
```
|
||||
|
||||
Additionally, when using Postgres as your database, you should utilize `$1` instead
|
||||
of `?` placeholders as utilizing `?` placeholders when querying Postgres will result
|
||||
in `pq: operator does not exist` errors. Alternatively, use
|
||||
`dbMap.Dialect.BindVar(varIdx)` to get the proper variable binding for your dialect.
|
||||
|
||||
### time.Time and time zones
|
||||
|
||||
gorp will pass `time.Time` fields through to the `database/sql` driver, but note that
|
||||
gorp will pass `time.Time` fields through to the `database/sql` driver, but note that
|
||||
the behavior of this type varies across database drivers.
|
||||
|
||||
MySQL users should be especially cautious. See: https://github.com/ziutek/mymysql/pull/77
|
||||
|
||||
83
Godeps/_workspace/src/github.com/go-gorp/gorp/column.go
сгенерированный
поставляемый
Обычный файл
83
Godeps/_workspace/src/github.com/go-gorp/gorp/column.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,83 @@
|
||||
// Copyright 2012 James Cooper. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package gorp provides a simple way to marshal Go structs to and from
|
||||
// SQL databases. It uses the database/sql package, and should work with any
|
||||
// compliant database/sql driver.
|
||||
//
|
||||
// Source code and project home:
|
||||
// https://github.com/go-gorp/gorp
|
||||
|
||||
package gorp
|
||||
|
||||
import "reflect"
|
||||
|
||||
// ColumnMap represents a mapping between a Go struct field and a single
|
||||
// column in a table.
|
||||
// Unique and MaxSize only inform the
|
||||
// CreateTables() function and are not used by Insert/Update/Delete/Get.
|
||||
type ColumnMap struct {
|
||||
// Column name in db table
|
||||
ColumnName string
|
||||
|
||||
// If true, this column is skipped in generated SQL statements
|
||||
Transient bool
|
||||
|
||||
// If true, " unique" is added to create table statements.
|
||||
// Not used elsewhere
|
||||
Unique bool
|
||||
|
||||
// Query used for getting generated id after insert
|
||||
GeneratedIdQuery string
|
||||
|
||||
// Passed to Dialect.ToSqlType() to assist in informing the
|
||||
// correct column type to map to in CreateTables()
|
||||
MaxSize int
|
||||
|
||||
DefaultValue string
|
||||
|
||||
fieldName string
|
||||
gotype reflect.Type
|
||||
isPK bool
|
||||
isAutoIncr bool
|
||||
isNotNull bool
|
||||
}
|
||||
|
||||
// Rename allows you to specify the column name in the table
|
||||
//
|
||||
// Example: table.ColMap("Updated").Rename("date_updated")
|
||||
//
|
||||
func (c *ColumnMap) Rename(colname string) *ColumnMap {
|
||||
c.ColumnName = colname
|
||||
return c
|
||||
}
|
||||
|
||||
// SetTransient allows you to mark the column as transient. If true
|
||||
// this column will be skipped when SQL statements are generated
|
||||
func (c *ColumnMap) SetTransient(b bool) *ColumnMap {
|
||||
c.Transient = b
|
||||
return c
|
||||
}
|
||||
|
||||
// SetUnique adds "unique" to the create table statements for this
|
||||
// column, if b is true.
|
||||
func (c *ColumnMap) SetUnique(b bool) *ColumnMap {
|
||||
c.Unique = b
|
||||
return c
|
||||
}
|
||||
|
||||
// SetNotNull adds "not null" to the create table statements for this
|
||||
// column, if nn is true.
|
||||
func (c *ColumnMap) SetNotNull(nn bool) *ColumnMap {
|
||||
c.isNotNull = nn
|
||||
return c
|
||||
}
|
||||
|
||||
// SetMaxSize specifies the max length of values of this column. This is
|
||||
// passed to the dialect.ToSqlType() function, which can use the value
|
||||
// to alter the generated type for "create table" statements
|
||||
func (c *ColumnMap) SetMaxSize(size int) *ColumnMap {
|
||||
c.MaxSize = size
|
||||
return c
|
||||
}
|
||||
619
Godeps/_workspace/src/github.com/go-gorp/gorp/db.go
сгенерированный
поставляемый
Обычный файл
619
Godeps/_workspace/src/github.com/go-gorp/gorp/db.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,619 @@
|
||||
// Copyright 2012 James Cooper. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package gorp provides a simple way to marshal Go structs to and from
|
||||
// SQL databases. It uses the database/sql package, and should work with any
|
||||
// compliant database/sql driver.
|
||||
//
|
||||
// Source code and project home:
|
||||
// https://github.com/go-gorp/gorp
|
||||
|
||||
package gorp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// DbMap is the root gorp mapping object. Create one of these for each
|
||||
// database schema you wish to map. Each DbMap contains a list of
|
||||
// mapped tables.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// dialect := gorp.MySQLDialect{"InnoDB", "UTF8"}
|
||||
// dbmap := &gorp.DbMap{Db: db, Dialect: dialect}
|
||||
//
|
||||
type DbMap struct {
|
||||
// Db handle to use with this map
|
||||
Db *sql.DB
|
||||
|
||||
// Dialect implementation to use with this map
|
||||
Dialect Dialect
|
||||
|
||||
TypeConverter TypeConverter
|
||||
|
||||
tables []*TableMap
|
||||
logger GorpLogger
|
||||
logPrefix string
|
||||
}
|
||||
|
||||
func (m *DbMap) CreateIndex() error {
|
||||
|
||||
var err error
|
||||
dialect := reflect.TypeOf(m.Dialect)
|
||||
for _, table := range m.tables {
|
||||
for _, index := range table.indexes {
|
||||
|
||||
s := bytes.Buffer{}
|
||||
s.WriteString("create")
|
||||
if index.Unique {
|
||||
s.WriteString(" unique")
|
||||
}
|
||||
s.WriteString(" index")
|
||||
s.WriteString(fmt.Sprintf(" %s on %s", index.IndexName, table.TableName))
|
||||
if dname := dialect.Name(); dname == "PostgresDialect" && index.IndexType != "" {
|
||||
s.WriteString(fmt.Sprintf(" %s %s", m.Dialect.CreateIndexSuffix(), index.IndexType))
|
||||
}
|
||||
s.WriteString(" (")
|
||||
for x, col := range index.columns {
|
||||
if x > 0 {
|
||||
s.WriteString(", ")
|
||||
}
|
||||
s.WriteString(m.Dialect.QuoteField(col))
|
||||
}
|
||||
s.WriteString(")")
|
||||
|
||||
if dname := dialect.Name(); dname == "MySQLDialect" && index.IndexType != "" {
|
||||
s.WriteString(fmt.Sprintf(" %s %s", m.Dialect.CreateIndexSuffix(), index.IndexType))
|
||||
}
|
||||
s.WriteString(";")
|
||||
_, err = m.Exec(s.String())
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (t *TableMap) DropIndex(name string) error {
|
||||
|
||||
var err error
|
||||
dialect := reflect.TypeOf(t.dbmap.Dialect)
|
||||
for _, idx := range t.indexes {
|
||||
if idx.IndexName == name {
|
||||
s := bytes.Buffer{}
|
||||
s.WriteString(fmt.Sprintf("DROP INDEX %s", idx.IndexName))
|
||||
|
||||
if dname := dialect.Name(); dname == "MySQLDialect" {
|
||||
s.WriteString(fmt.Sprintf(" %s %s", t.dbmap.Dialect.DropIndexSuffix(), t.TableName))
|
||||
}
|
||||
s.WriteString(";")
|
||||
_, e := t.dbmap.Exec(s.String())
|
||||
if e != nil {
|
||||
err = e
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
t.ResetSql()
|
||||
return err
|
||||
}
|
||||
|
||||
// AddTable registers the given interface type with gorp. The table name
|
||||
// will be given the name of the TypeOf(i). You must call this function,
|
||||
// or AddTableWithName, for any struct type you wish to persist with
|
||||
// the given DbMap.
|
||||
//
|
||||
// This operation is idempotent. If i's type is already mapped, the
|
||||
// existing *TableMap is returned
|
||||
func (m *DbMap) AddTable(i interface{}) *TableMap {
|
||||
return m.AddTableWithName(i, "")
|
||||
}
|
||||
|
||||
// AddTableWithName has the same behavior as AddTable, but sets
|
||||
// table.TableName to name.
|
||||
func (m *DbMap) AddTableWithName(i interface{}, name string) *TableMap {
|
||||
return m.AddTableWithNameAndSchema(i, "", name)
|
||||
}
|
||||
|
||||
// AddTableWithNameAndSchema has the same behavior as AddTable, but sets
|
||||
// table.TableName to name.
|
||||
func (m *DbMap) AddTableWithNameAndSchema(i interface{}, schema string, name string) *TableMap {
|
||||
t := reflect.TypeOf(i)
|
||||
if name == "" {
|
||||
name = t.Name()
|
||||
}
|
||||
|
||||
// check if we have a table for this type already
|
||||
// if so, update the name and return the existing pointer
|
||||
for i := range m.tables {
|
||||
table := m.tables[i]
|
||||
if table.gotype == t {
|
||||
table.TableName = name
|
||||
return table
|
||||
}
|
||||
}
|
||||
|
||||
tmap := &TableMap{gotype: t, TableName: name, SchemaName: schema, dbmap: m}
|
||||
var primaryKey []*ColumnMap
|
||||
tmap.Columns, primaryKey = m.readStructColumns(t)
|
||||
m.tables = append(m.tables, tmap)
|
||||
if len(primaryKey) > 0 {
|
||||
tmap.keys = append(tmap.keys, primaryKey...)
|
||||
}
|
||||
|
||||
return tmap
|
||||
}
|
||||
|
||||
func (m *DbMap) readStructColumns(t reflect.Type) (cols []*ColumnMap, primaryKey []*ColumnMap) {
|
||||
primaryKey = make([]*ColumnMap, 0)
|
||||
n := t.NumField()
|
||||
for i := 0; i < n; i++ {
|
||||
f := t.Field(i)
|
||||
if f.Anonymous && f.Type.Kind() == reflect.Struct {
|
||||
// Recursively add nested fields in embedded structs.
|
||||
subcols, subpk := m.readStructColumns(f.Type)
|
||||
// Don't append nested fields that have the same field
|
||||
// name as an already-mapped field.
|
||||
for _, subcol := range subcols {
|
||||
shouldAppend := true
|
||||
for _, col := range cols {
|
||||
if !subcol.Transient && subcol.fieldName == col.fieldName {
|
||||
shouldAppend = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if shouldAppend {
|
||||
cols = append(cols, subcol)
|
||||
}
|
||||
}
|
||||
if subpk != nil {
|
||||
primaryKey = append(primaryKey, subpk...)
|
||||
}
|
||||
} else {
|
||||
// Tag = Name { ',' Option }
|
||||
// Option = OptionKey [ ':' OptionValue ]
|
||||
cArguments := strings.Split(f.Tag.Get("db"), ",")
|
||||
columnName := cArguments[0]
|
||||
var maxSize int
|
||||
var defaultValue string
|
||||
var isAuto bool
|
||||
var isPK bool
|
||||
for _, argString := range cArguments[1:] {
|
||||
argString = strings.TrimSpace(argString)
|
||||
arg := strings.SplitN(argString, ":", 2)
|
||||
|
||||
// check mandatory/unexpected option values
|
||||
switch arg[0] {
|
||||
case "size", "default":
|
||||
// options requiring value
|
||||
if len(arg) == 1 {
|
||||
panic(fmt.Sprintf("missing option value for option %v on field %v", arg[0], f.Name))
|
||||
}
|
||||
default:
|
||||
// options where value is invalid (currently all other options)
|
||||
if len(arg) == 2 {
|
||||
panic(fmt.Sprintf("unexpected option value for option %v on field %v", arg[0], f.Name))
|
||||
}
|
||||
}
|
||||
|
||||
switch arg[0] {
|
||||
case "size":
|
||||
maxSize, _ = strconv.Atoi(arg[1])
|
||||
case "default":
|
||||
defaultValue = arg[1]
|
||||
case "primarykey":
|
||||
isPK = true
|
||||
case "autoincrement":
|
||||
isAuto = true
|
||||
default:
|
||||
panic(fmt.Sprintf("Unrecognized tag option for field %v: %v", f.Name, arg))
|
||||
}
|
||||
}
|
||||
if columnName == "" {
|
||||
columnName = f.Name
|
||||
}
|
||||
|
||||
gotype := f.Type
|
||||
value := reflect.New(gotype).Interface()
|
||||
if m.TypeConverter != nil {
|
||||
// Make a new pointer to a value of type gotype and
|
||||
// pass it to the TypeConverter's FromDb method to see
|
||||
// if a different type should be used for the column
|
||||
// type during table creation.
|
||||
scanner, useHolder := m.TypeConverter.FromDb(value)
|
||||
if useHolder {
|
||||
value = scanner.Holder
|
||||
gotype = reflect.TypeOf(value)
|
||||
}
|
||||
}
|
||||
if typer, ok := value.(SqlTyper); ok {
|
||||
gotype = reflect.TypeOf(typer.SqlType())
|
||||
} else if valuer, ok := value.(driver.Valuer); ok {
|
||||
// Only check for driver.Valuer if SqlTyper wasn't
|
||||
// found.
|
||||
v, err := valuer.Value()
|
||||
if err == nil && v != nil {
|
||||
gotype = reflect.TypeOf(v)
|
||||
}
|
||||
}
|
||||
cm := &ColumnMap{
|
||||
ColumnName: columnName,
|
||||
DefaultValue: defaultValue,
|
||||
Transient: columnName == "-",
|
||||
fieldName: f.Name,
|
||||
gotype: gotype,
|
||||
isPK: isPK,
|
||||
isAutoIncr: isAuto,
|
||||
MaxSize: maxSize,
|
||||
}
|
||||
if isPK {
|
||||
primaryKey = append(primaryKey, cm)
|
||||
}
|
||||
// Check for nested fields of the same field name and
|
||||
// override them.
|
||||
shouldAppend := true
|
||||
for index, col := range cols {
|
||||
if !col.Transient && col.fieldName == cm.fieldName {
|
||||
cols[index] = cm
|
||||
shouldAppend = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if shouldAppend {
|
||||
cols = append(cols, cm)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// CreateTables iterates through TableMaps registered to this DbMap and
|
||||
// executes "create table" statements against the database for each.
|
||||
//
|
||||
// This is particularly useful in unit tests where you want to create
|
||||
// and destroy the schema automatically.
|
||||
func (m *DbMap) CreateTables() error {
|
||||
return m.createTables(false)
|
||||
}
|
||||
|
||||
// CreateTablesIfNotExists is similar to CreateTables, but starts
|
||||
// each statement with "create table if not exists" so that existing
|
||||
// tables do not raise errors
|
||||
func (m *DbMap) CreateTablesIfNotExists() error {
|
||||
return m.createTables(true)
|
||||
}
|
||||
|
||||
func (m *DbMap) createTables(ifNotExists bool) error {
|
||||
var err error
|
||||
for i := range m.tables {
|
||||
table := m.tables[i]
|
||||
sql := table.SqlForCreate(ifNotExists)
|
||||
_, err = m.Exec(sql)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// DropTable drops an individual table.
|
||||
// Returns an error when the table does not exist.
|
||||
func (m *DbMap) DropTable(table interface{}) error {
|
||||
t := reflect.TypeOf(table)
|
||||
return m.dropTable(t, false)
|
||||
}
|
||||
|
||||
// DropTableIfExists drops an individual table when the table exists.
|
||||
func (m *DbMap) DropTableIfExists(table interface{}) error {
|
||||
t := reflect.TypeOf(table)
|
||||
return m.dropTable(t, true)
|
||||
}
|
||||
|
||||
// DropTables iterates through TableMaps registered to this DbMap and
|
||||
// executes "drop table" statements against the database for each.
|
||||
func (m *DbMap) DropTables() error {
|
||||
return m.dropTables(false)
|
||||
}
|
||||
|
||||
// DropTablesIfExists is the same as DropTables, but uses the "if exists" clause to
|
||||
// avoid errors for tables that do not exist.
|
||||
func (m *DbMap) DropTablesIfExists() error {
|
||||
return m.dropTables(true)
|
||||
}
|
||||
|
||||
// Goes through all the registered tables, dropping them one by one.
|
||||
// If an error is encountered, then it is returned and the rest of
|
||||
// the tables are not dropped.
|
||||
func (m *DbMap) dropTables(addIfExists bool) (err error) {
|
||||
for _, table := range m.tables {
|
||||
err = m.dropTableImpl(table, addIfExists)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Implementation of dropping a single table.
|
||||
func (m *DbMap) dropTable(t reflect.Type, addIfExists bool) error {
|
||||
table := tableOrNil(m, t)
|
||||
if table == nil {
|
||||
return fmt.Errorf("table %s was not registered", table.TableName)
|
||||
}
|
||||
|
||||
return m.dropTableImpl(table, addIfExists)
|
||||
}
|
||||
|
||||
func (m *DbMap) dropTableImpl(table *TableMap, ifExists bool) (err error) {
|
||||
tableDrop := "drop table"
|
||||
if ifExists {
|
||||
tableDrop = m.Dialect.IfTableExists(tableDrop, table.SchemaName, table.TableName)
|
||||
}
|
||||
_, err = m.Exec(fmt.Sprintf("%s %s;", tableDrop, m.Dialect.QuotedTableForQuery(table.SchemaName, table.TableName)))
|
||||
return err
|
||||
}
|
||||
|
||||
// TruncateTables iterates through TableMaps registered to this DbMap and
|
||||
// executes "truncate table" statements against the database for each, or in the case of
|
||||
// sqlite, a "delete from" with no "where" clause, which uses the truncate optimization
|
||||
// (http://www.sqlite.org/lang_delete.html)
|
||||
func (m *DbMap) TruncateTables() error {
|
||||
var err error
|
||||
for i := range m.tables {
|
||||
table := m.tables[i]
|
||||
_, e := m.Exec(fmt.Sprintf("%s %s;", m.Dialect.TruncateClause(), m.Dialect.QuotedTableForQuery(table.SchemaName, table.TableName)))
|
||||
if e != nil {
|
||||
err = e
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Insert runs a SQL INSERT statement for each element in list. List
|
||||
// items must be pointers.
|
||||
//
|
||||
// Any interface whose TableMap has an auto-increment primary key will
|
||||
// have its last insert id bound to the PK field on the struct.
|
||||
//
|
||||
// The hook functions PreInsert() and/or PostInsert() will be executed
|
||||
// before/after the INSERT statement if the interface defines them.
|
||||
//
|
||||
// Panics if any interface in the list has not been registered with AddTable
|
||||
func (m *DbMap) Insert(list ...interface{}) error {
|
||||
return insert(m, m, list...)
|
||||
}
|
||||
|
||||
// Update runs a SQL UPDATE statement for each element in list. List
|
||||
// items must be pointers.
|
||||
//
|
||||
// The hook functions PreUpdate() and/or PostUpdate() will be executed
|
||||
// before/after the UPDATE statement if the interface defines them.
|
||||
//
|
||||
// Returns the number of rows updated.
|
||||
//
|
||||
// Returns an error if SetKeys has not been called on the TableMap
|
||||
// Panics if any interface in the list has not been registered with AddTable
|
||||
func (m *DbMap) Update(list ...interface{}) (int64, error) {
|
||||
return update(m, m, nil, list...)
|
||||
}
|
||||
|
||||
// UpdateColumns runs a SQL UPDATE statement for each element in list. List
|
||||
// items must be pointers.
|
||||
//
|
||||
// Only the columns accepted by filter are included in the UPDATE.
|
||||
//
|
||||
// The hook functions PreUpdate() and/or PostUpdate() will be executed
|
||||
// before/after the UPDATE statement if the interface defines them.
|
||||
//
|
||||
// Returns the number of rows updated.
|
||||
//
|
||||
// Returns an error if SetKeys has not been called on the TableMap
|
||||
// Panics if any interface in the list has not been registered with AddTable
|
||||
func (m *DbMap) UpdateColumns(filter ColumnFilter, list ...interface{}) (int64, error) {
|
||||
return update(m, m, filter, list...)
|
||||
}
|
||||
|
||||
// Delete runs a SQL DELETE statement for each element in list. List
|
||||
// items must be pointers.
|
||||
//
|
||||
// The hook functions PreDelete() and/or PostDelete() will be executed
|
||||
// before/after the DELETE statement if the interface defines them.
|
||||
//
|
||||
// Returns the number of rows deleted.
|
||||
//
|
||||
// Returns an error if SetKeys has not been called on the TableMap
|
||||
// Panics if any interface in the list has not been registered with AddTable
|
||||
func (m *DbMap) Delete(list ...interface{}) (int64, error) {
|
||||
return delete(m, m, list...)
|
||||
}
|
||||
|
||||
// Get runs a SQL SELECT to fetch a single row from the table based on the
|
||||
// primary key(s)
|
||||
//
|
||||
// i should be an empty value for the struct to load. keys should be
|
||||
// the primary key value(s) for the row to load. If multiple keys
|
||||
// exist on the table, the order should match the column order
|
||||
// specified in SetKeys() when the table mapping was defined.
|
||||
//
|
||||
// The hook function PostGet() will be executed after the SELECT
|
||||
// statement if the interface defines them.
|
||||
//
|
||||
// Returns a pointer to a struct that matches or nil if no row is found.
|
||||
//
|
||||
// Returns an error if SetKeys has not been called on the TableMap
|
||||
// Panics if any interface in the list has not been registered with AddTable
|
||||
func (m *DbMap) Get(i interface{}, keys ...interface{}) (interface{}, error) {
|
||||
return get(m, m, i, keys...)
|
||||
}
|
||||
|
||||
// Select runs an arbitrary SQL query, binding the columns in the result
|
||||
// to fields on the struct specified by i. args represent the bind
|
||||
// parameters for the SQL statement.
|
||||
//
|
||||
// Column names on the SELECT statement should be aliased to the field names
|
||||
// on the struct i. Returns an error if one or more columns in the result
|
||||
// do not match. It is OK if fields on i are not part of the SQL
|
||||
// statement.
|
||||
//
|
||||
// The hook function PostGet() will be executed after the SELECT
|
||||
// statement if the interface defines them.
|
||||
//
|
||||
// Values are returned in one of two ways:
|
||||
// 1. If i is a struct or a pointer to a struct, returns a slice of pointers to
|
||||
// matching rows of type i.
|
||||
// 2. If i is a pointer to a slice, the results will be appended to that slice
|
||||
// and nil returned.
|
||||
//
|
||||
// i does NOT need to be registered with AddTable()
|
||||
func (m *DbMap) Select(i interface{}, query string, args ...interface{}) ([]interface{}, error) {
|
||||
return hookedselect(m, m, i, query, args...)
|
||||
}
|
||||
|
||||
// Exec runs an arbitrary SQL statement. args represent the bind parameters.
|
||||
// This is equivalent to running: Exec() using database/sql
|
||||
func (m *DbMap) Exec(query string, args ...interface{}) (sql.Result, error) {
|
||||
if m.logger != nil {
|
||||
now := time.Now()
|
||||
defer m.trace(now, query, args...)
|
||||
}
|
||||
return exec(m, query, args...)
|
||||
}
|
||||
|
||||
// SelectInt is a convenience wrapper around the gorp.SelectInt function
|
||||
func (m *DbMap) SelectInt(query string, args ...interface{}) (int64, error) {
|
||||
return SelectInt(m, query, args...)
|
||||
}
|
||||
|
||||
// SelectNullInt is a convenience wrapper around the gorp.SelectNullInt function
|
||||
func (m *DbMap) SelectNullInt(query string, args ...interface{}) (sql.NullInt64, error) {
|
||||
return SelectNullInt(m, query, args...)
|
||||
}
|
||||
|
||||
// SelectFloat is a convenience wrapper around the gorp.SelectFloat function
|
||||
func (m *DbMap) SelectFloat(query string, args ...interface{}) (float64, error) {
|
||||
return SelectFloat(m, query, args...)
|
||||
}
|
||||
|
||||
// SelectNullFloat is a convenience wrapper around the gorp.SelectNullFloat function
|
||||
func (m *DbMap) SelectNullFloat(query string, args ...interface{}) (sql.NullFloat64, error) {
|
||||
return SelectNullFloat(m, query, args...)
|
||||
}
|
||||
|
||||
// SelectStr is a convenience wrapper around the gorp.SelectStr function
|
||||
func (m *DbMap) SelectStr(query string, args ...interface{}) (string, error) {
|
||||
return SelectStr(m, query, args...)
|
||||
}
|
||||
|
||||
// SelectNullStr is a convenience wrapper around the gorp.SelectNullStr function
|
||||
func (m *DbMap) SelectNullStr(query string, args ...interface{}) (sql.NullString, error) {
|
||||
return SelectNullStr(m, query, args...)
|
||||
}
|
||||
|
||||
// SelectOne is a convenience wrapper around the gorp.SelectOne function
|
||||
func (m *DbMap) SelectOne(holder interface{}, query string, args ...interface{}) error {
|
||||
return SelectOne(m, m, holder, query, args...)
|
||||
}
|
||||
|
||||
// Begin starts a gorp Transaction
|
||||
func (m *DbMap) Begin() (*Transaction, error) {
|
||||
if m.logger != nil {
|
||||
now := time.Now()
|
||||
defer m.trace(now, "begin;")
|
||||
}
|
||||
tx, err := m.Db.Begin()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Transaction{m, tx, false}, nil
|
||||
}
|
||||
|
||||
// TableFor returns the *TableMap corresponding to the given Go Type
|
||||
// If no table is mapped to that type an error is returned.
|
||||
// If checkPK is true and the mapped table has no registered PKs, an error is returned.
|
||||
func (m *DbMap) TableFor(t reflect.Type, checkPK bool) (*TableMap, error) {
|
||||
table := tableOrNil(m, t)
|
||||
if table == nil {
|
||||
return nil, fmt.Errorf("no table found for type: %v", t.Name())
|
||||
}
|
||||
|
||||
if checkPK && len(table.keys) < 1 {
|
||||
e := fmt.Sprintf("gorp: no keys defined for table: %s",
|
||||
table.TableName)
|
||||
return nil, errors.New(e)
|
||||
}
|
||||
|
||||
return table, nil
|
||||
}
|
||||
|
||||
// Prepare creates a prepared statement for later queries or executions.
|
||||
// Multiple queries or executions may be run concurrently from the returned statement.
|
||||
// This is equivalent to running: Prepare() using database/sql
|
||||
func (m *DbMap) Prepare(query string) (*sql.Stmt, error) {
|
||||
if m.logger != nil {
|
||||
now := time.Now()
|
||||
defer m.trace(now, query, nil)
|
||||
}
|
||||
return m.Db.Prepare(query)
|
||||
}
|
||||
|
||||
func tableOrNil(m *DbMap, t reflect.Type) *TableMap {
|
||||
for i := range m.tables {
|
||||
table := m.tables[i]
|
||||
if table.gotype == t {
|
||||
return table
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *DbMap) tableForPointer(ptr interface{}, checkPK bool) (*TableMap, reflect.Value, error) {
|
||||
ptrv := reflect.ValueOf(ptr)
|
||||
if ptrv.Kind() != reflect.Ptr {
|
||||
e := fmt.Sprintf("gorp: passed non-pointer: %v (kind=%v)", ptr,
|
||||
ptrv.Kind())
|
||||
return nil, reflect.Value{}, errors.New(e)
|
||||
}
|
||||
elem := ptrv.Elem()
|
||||
etype := reflect.TypeOf(elem.Interface())
|
||||
t, err := m.TableFor(etype, checkPK)
|
||||
if err != nil {
|
||||
return nil, reflect.Value{}, err
|
||||
}
|
||||
|
||||
return t, elem, nil
|
||||
}
|
||||
|
||||
func (m *DbMap) queryRow(query string, args ...interface{}) *sql.Row {
|
||||
if m.logger != nil {
|
||||
now := time.Now()
|
||||
defer m.trace(now, query, args...)
|
||||
}
|
||||
return m.Db.QueryRow(query, args...)
|
||||
}
|
||||
|
||||
func (m *DbMap) query(query string, args ...interface{}) (*sql.Rows, error) {
|
||||
if m.logger != nil {
|
||||
now := time.Now()
|
||||
defer m.trace(now, query, args...)
|
||||
}
|
||||
return m.Db.Query(query, args...)
|
||||
}
|
||||
|
||||
func (m *DbMap) trace(started time.Time, query string, args ...interface{}) {
|
||||
if m.logger != nil {
|
||||
var margs = argsString(args...)
|
||||
m.logger.Printf("%s%s [%s] (%v)", m.logPrefix, query, margs, (time.Now().Sub(started)))
|
||||
}
|
||||
}
|
||||
641
Godeps/_workspace/src/github.com/go-gorp/gorp/dialect.go
сгенерированный
поставляемый
641
Godeps/_workspace/src/github.com/go-gorp/gorp/dialect.go
сгенерированный
поставляемый
@@ -1,11 +1,17 @@
|
||||
// Copyright 2012 James Cooper. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package gorp provides a simple way to marshal Go structs to and from
|
||||
// SQL databases. It uses the database/sql package, and should work with any
|
||||
// compliant database/sql driver.
|
||||
//
|
||||
// Source code and project home:
|
||||
// https://github.com/go-gorp/gorp
|
||||
|
||||
package gorp
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
import "reflect"
|
||||
|
||||
// The Dialect interface encapsulates behaviors that differ across
|
||||
// SQL databases. At present the Dialect is only used by CreateTables()
|
||||
@@ -34,6 +40,12 @@ type Dialect interface {
|
||||
// table attributes
|
||||
CreateTableSuffix() string
|
||||
|
||||
// string to append to "create index" statement
|
||||
CreateIndexSuffix() string
|
||||
|
||||
// string to append to "drop index" statement
|
||||
DropIndexSuffix() string
|
||||
|
||||
// string to truncate tables
|
||||
TruncateClause() string
|
||||
|
||||
@@ -80,6 +92,16 @@ type TargetedAutoIncrInserter interface {
|
||||
InsertAutoIncrToTarget(exec SqlExecutor, insertSql string, target interface{}, params ...interface{}) error
|
||||
}
|
||||
|
||||
// TargetQueryInserter is implemented by dialects that can perform
|
||||
// assignment of integer primary key type by executing a query
|
||||
// like "select sequence.currval from dual".
|
||||
type TargetQueryInserter interface {
|
||||
// TargetQueryInserter runs an insert operation and assigns the
|
||||
// automatically generated primary key retrived by the query
|
||||
// extracted from the GeneratedIdQuery field of the id column.
|
||||
InsertQueryToTarget(exec SqlExecutor, insertSql, idSql string, target interface{}, params ...interface{}) error
|
||||
}
|
||||
|
||||
func standardInsertAutoIncr(exec SqlExecutor, insertSql string, params ...interface{}) (int64, error) {
|
||||
res, err := exec.Exec(insertSql, params...)
|
||||
if err != nil {
|
||||
@@ -87,610 +109,3 @@ func standardInsertAutoIncr(exec SqlExecutor, insertSql string, params ...interf
|
||||
}
|
||||
return res.LastInsertId()
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////
|
||||
// sqlite3 //
|
||||
/////////////
|
||||
|
||||
type SqliteDialect struct {
|
||||
suffix string
|
||||
}
|
||||
|
||||
func (d SqliteDialect) QuerySuffix() string { return ";" }
|
||||
|
||||
func (d SqliteDialect) ToSqlType(val reflect.Type, maxsize int, isAutoIncr bool) string {
|
||||
switch val.Kind() {
|
||||
case reflect.Ptr:
|
||||
return d.ToSqlType(val.Elem(), maxsize, isAutoIncr)
|
||||
case reflect.Bool:
|
||||
return "integer"
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
return "integer"
|
||||
case reflect.Float64, reflect.Float32:
|
||||
return "real"
|
||||
case reflect.Slice:
|
||||
if val.Elem().Kind() == reflect.Uint8 {
|
||||
return "blob"
|
||||
}
|
||||
}
|
||||
|
||||
switch val.Name() {
|
||||
case "NullInt64":
|
||||
return "integer"
|
||||
case "NullFloat64":
|
||||
return "real"
|
||||
case "NullBool":
|
||||
return "integer"
|
||||
case "Time":
|
||||
return "datetime"
|
||||
}
|
||||
|
||||
if maxsize < 1 {
|
||||
maxsize = 255
|
||||
}
|
||||
return fmt.Sprintf("varchar(%d)", maxsize)
|
||||
}
|
||||
|
||||
// Returns autoincrement
|
||||
func (d SqliteDialect) AutoIncrStr() string {
|
||||
return "autoincrement"
|
||||
}
|
||||
|
||||
func (d SqliteDialect) AutoIncrBindValue() string {
|
||||
return "null"
|
||||
}
|
||||
|
||||
func (d SqliteDialect) AutoIncrInsertSuffix(col *ColumnMap) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Returns suffix
|
||||
func (d SqliteDialect) CreateTableSuffix() string {
|
||||
return d.suffix
|
||||
}
|
||||
|
||||
// With sqlite, there technically isn't a TRUNCATE statement,
|
||||
// but a DELETE FROM uses a truncate optimization:
|
||||
// http://www.sqlite.org/lang_delete.html
|
||||
func (d SqliteDialect) TruncateClause() string {
|
||||
return "delete from"
|
||||
}
|
||||
|
||||
// Returns "?"
|
||||
func (d SqliteDialect) BindVar(i int) string {
|
||||
return "?"
|
||||
}
|
||||
|
||||
func (d SqliteDialect) InsertAutoIncr(exec SqlExecutor, insertSql string, params ...interface{}) (int64, error) {
|
||||
return standardInsertAutoIncr(exec, insertSql, params...)
|
||||
}
|
||||
|
||||
func (d SqliteDialect) QuoteField(f string) string {
|
||||
return `"` + f + `"`
|
||||
}
|
||||
|
||||
// sqlite does not have schemas like PostgreSQL does, so just escape it like normal
|
||||
func (d SqliteDialect) QuotedTableForQuery(schema string, table string) string {
|
||||
return d.QuoteField(table)
|
||||
}
|
||||
|
||||
func (d SqliteDialect) IfSchemaNotExists(command, schema string) string {
|
||||
return fmt.Sprintf("%s if not exists", command)
|
||||
}
|
||||
|
||||
func (d SqliteDialect) IfTableExists(command, schema, table string) string {
|
||||
return fmt.Sprintf("%s if exists", command)
|
||||
}
|
||||
|
||||
func (d SqliteDialect) IfTableNotExists(command, schema, table string) string {
|
||||
return fmt.Sprintf("%s if not exists", command)
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////
|
||||
// PostgreSQL //
|
||||
////////////////
|
||||
|
||||
type PostgresDialect struct {
|
||||
suffix string
|
||||
}
|
||||
|
||||
func (d PostgresDialect) QuerySuffix() string { return ";" }
|
||||
|
||||
func (d PostgresDialect) ToSqlType(val reflect.Type, maxsize int, isAutoIncr bool) string {
|
||||
switch val.Kind() {
|
||||
case reflect.Ptr:
|
||||
return d.ToSqlType(val.Elem(), maxsize, isAutoIncr)
|
||||
case reflect.Bool:
|
||||
return "boolean"
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint8, reflect.Uint16, reflect.Uint32:
|
||||
if isAutoIncr {
|
||||
return "serial"
|
||||
}
|
||||
return "integer"
|
||||
case reflect.Int64, reflect.Uint64:
|
||||
if isAutoIncr {
|
||||
return "bigserial"
|
||||
}
|
||||
return "bigint"
|
||||
case reflect.Float64:
|
||||
return "double precision"
|
||||
case reflect.Float32:
|
||||
return "real"
|
||||
case reflect.Slice:
|
||||
if val.Elem().Kind() == reflect.Uint8 {
|
||||
return "bytea"
|
||||
}
|
||||
}
|
||||
|
||||
switch val.Name() {
|
||||
case "NullInt64":
|
||||
return "bigint"
|
||||
case "NullFloat64":
|
||||
return "double precision"
|
||||
case "NullBool":
|
||||
return "boolean"
|
||||
case "Time", "NullTime":
|
||||
return "timestamp with time zone"
|
||||
}
|
||||
|
||||
if maxsize > 0 {
|
||||
return fmt.Sprintf("varchar(%d)", maxsize)
|
||||
} else {
|
||||
return "text"
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Returns empty string
|
||||
func (d PostgresDialect) AutoIncrStr() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (d PostgresDialect) AutoIncrBindValue() string {
|
||||
return "default"
|
||||
}
|
||||
|
||||
func (d PostgresDialect) AutoIncrInsertSuffix(col *ColumnMap) string {
|
||||
return " returning " + col.ColumnName
|
||||
}
|
||||
|
||||
// Returns suffix
|
||||
func (d PostgresDialect) CreateTableSuffix() string {
|
||||
return d.suffix
|
||||
}
|
||||
|
||||
func (d PostgresDialect) TruncateClause() string {
|
||||
return "truncate"
|
||||
}
|
||||
|
||||
// Returns "$(i+1)"
|
||||
func (d PostgresDialect) BindVar(i int) string {
|
||||
return fmt.Sprintf("$%d", i+1)
|
||||
}
|
||||
|
||||
func (d PostgresDialect) InsertAutoIncrToTarget(exec SqlExecutor, insertSql string, target interface{}, params ...interface{}) error {
|
||||
rows, err := exec.query(insertSql, params...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
if !rows.Next() {
|
||||
return fmt.Errorf("No serial value returned for insert: %s Encountered error: %s", insertSql, rows.Err())
|
||||
}
|
||||
if err := rows.Scan(target); err != nil {
|
||||
return err
|
||||
}
|
||||
if rows.Next() {
|
||||
return fmt.Errorf("more than two serial value returned for insert: %s", insertSql)
|
||||
}
|
||||
return rows.Err()
|
||||
}
|
||||
|
||||
func (d PostgresDialect) QuoteField(f string) string {
|
||||
return `"` + strings.ToLower(f) + `"`
|
||||
}
|
||||
|
||||
func (d PostgresDialect) QuotedTableForQuery(schema string, table string) string {
|
||||
if strings.TrimSpace(schema) == "" {
|
||||
return d.QuoteField(table)
|
||||
}
|
||||
|
||||
return schema + "." + d.QuoteField(table)
|
||||
}
|
||||
|
||||
func (d PostgresDialect) IfSchemaNotExists(command, schema string) string {
|
||||
return fmt.Sprintf("%s if not exists", command)
|
||||
}
|
||||
|
||||
func (d PostgresDialect) IfTableExists(command, schema, table string) string {
|
||||
return fmt.Sprintf("%s if exists", command)
|
||||
}
|
||||
|
||||
func (d PostgresDialect) IfTableNotExists(command, schema, table string) string {
|
||||
return fmt.Sprintf("%s if not exists", command)
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////
|
||||
// MySQL //
|
||||
///////////
|
||||
|
||||
// Implementation of Dialect for MySQL databases.
|
||||
type MySQLDialect struct {
|
||||
|
||||
// Engine is the storage engine to use "InnoDB" vs "MyISAM" for example
|
||||
Engine string
|
||||
|
||||
// Encoding is the character encoding to use for created tables
|
||||
Encoding string
|
||||
}
|
||||
|
||||
func (d MySQLDialect) QuerySuffix() string { return ";" }
|
||||
|
||||
func (d MySQLDialect) ToSqlType(val reflect.Type, maxsize int, isAutoIncr bool) string {
|
||||
switch val.Kind() {
|
||||
case reflect.Ptr:
|
||||
return d.ToSqlType(val.Elem(), maxsize, isAutoIncr)
|
||||
case reflect.Bool:
|
||||
return "boolean"
|
||||
case reflect.Int8:
|
||||
return "tinyint"
|
||||
case reflect.Uint8:
|
||||
return "tinyint unsigned"
|
||||
case reflect.Int16:
|
||||
return "smallint"
|
||||
case reflect.Uint16:
|
||||
return "smallint unsigned"
|
||||
case reflect.Int, reflect.Int32:
|
||||
return "int"
|
||||
case reflect.Uint, reflect.Uint32:
|
||||
return "int unsigned"
|
||||
case reflect.Int64:
|
||||
return "bigint"
|
||||
case reflect.Uint64:
|
||||
return "bigint unsigned"
|
||||
case reflect.Float64, reflect.Float32:
|
||||
return "double"
|
||||
case reflect.Slice:
|
||||
if val.Elem().Kind() == reflect.Uint8 {
|
||||
return "mediumblob"
|
||||
}
|
||||
}
|
||||
|
||||
switch val.Name() {
|
||||
case "NullInt64":
|
||||
return "bigint"
|
||||
case "NullFloat64":
|
||||
return "double"
|
||||
case "NullBool":
|
||||
return "tinyint"
|
||||
case "Time":
|
||||
return "datetime"
|
||||
}
|
||||
|
||||
if maxsize < 1 {
|
||||
maxsize = 255
|
||||
}
|
||||
return fmt.Sprintf("varchar(%d)", maxsize)
|
||||
}
|
||||
|
||||
// Returns auto_increment
|
||||
func (d MySQLDialect) AutoIncrStr() string {
|
||||
return "auto_increment"
|
||||
}
|
||||
|
||||
func (d MySQLDialect) AutoIncrBindValue() string {
|
||||
return "null"
|
||||
}
|
||||
|
||||
func (d MySQLDialect) AutoIncrInsertSuffix(col *ColumnMap) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Returns engine=%s charset=%s based on values stored on struct
|
||||
func (d MySQLDialect) CreateTableSuffix() string {
|
||||
if d.Engine == "" || d.Encoding == "" {
|
||||
msg := "gorp - undefined"
|
||||
|
||||
if d.Engine == "" {
|
||||
msg += " MySQLDialect.Engine"
|
||||
}
|
||||
if d.Engine == "" && d.Encoding == "" {
|
||||
msg += ","
|
||||
}
|
||||
if d.Encoding == "" {
|
||||
msg += " MySQLDialect.Encoding"
|
||||
}
|
||||
msg += ". Check that your MySQLDialect was correctly initialized when declared."
|
||||
panic(msg)
|
||||
}
|
||||
|
||||
return fmt.Sprintf(" engine=%s charset=%s", d.Engine, d.Encoding)
|
||||
}
|
||||
|
||||
func (d MySQLDialect) TruncateClause() string {
|
||||
return "truncate"
|
||||
}
|
||||
|
||||
// Returns "?"
|
||||
func (d MySQLDialect) BindVar(i int) string {
|
||||
return "?"
|
||||
}
|
||||
|
||||
func (d MySQLDialect) InsertAutoIncr(exec SqlExecutor, insertSql string, params ...interface{}) (int64, error) {
|
||||
return standardInsertAutoIncr(exec, insertSql, params...)
|
||||
}
|
||||
|
||||
func (d MySQLDialect) QuoteField(f string) string {
|
||||
return "`" + f + "`"
|
||||
}
|
||||
|
||||
func (d MySQLDialect) QuotedTableForQuery(schema string, table string) string {
|
||||
if strings.TrimSpace(schema) == "" {
|
||||
return d.QuoteField(table)
|
||||
}
|
||||
|
||||
return schema + "." + d.QuoteField(table)
|
||||
}
|
||||
|
||||
func (d MySQLDialect) IfSchemaNotExists(command, schema string) string {
|
||||
return fmt.Sprintf("%s if not exists", command)
|
||||
}
|
||||
|
||||
func (d MySQLDialect) IfTableExists(command, schema, table string) string {
|
||||
return fmt.Sprintf("%s if exists", command)
|
||||
}
|
||||
|
||||
func (d MySQLDialect) IfTableNotExists(command, schema, table string) string {
|
||||
return fmt.Sprintf("%s if not exists", command)
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////
|
||||
// Sql Server //
|
||||
////////////////
|
||||
|
||||
// Implementation of Dialect for Microsoft SQL Server databases.
|
||||
// Tested on SQL Server 2008 with driver: github.com/denisenkom/go-mssqldb
|
||||
|
||||
type SqlServerDialect struct {
|
||||
suffix string
|
||||
}
|
||||
|
||||
func (d SqlServerDialect) ToSqlType(val reflect.Type, maxsize int, isAutoIncr bool) string {
|
||||
switch val.Kind() {
|
||||
case reflect.Ptr:
|
||||
return d.ToSqlType(val.Elem(), maxsize, isAutoIncr)
|
||||
case reflect.Bool:
|
||||
return "bit"
|
||||
case reflect.Int8:
|
||||
return "tinyint"
|
||||
case reflect.Uint8:
|
||||
return "smallint"
|
||||
case reflect.Int16:
|
||||
return "smallint"
|
||||
case reflect.Uint16:
|
||||
return "int"
|
||||
case reflect.Int, reflect.Int32:
|
||||
return "int"
|
||||
case reflect.Uint, reflect.Uint32:
|
||||
return "bigint"
|
||||
case reflect.Int64:
|
||||
return "bigint"
|
||||
case reflect.Uint64:
|
||||
return "bigint"
|
||||
case reflect.Float32:
|
||||
return "real"
|
||||
case reflect.Float64:
|
||||
return "float(53)"
|
||||
case reflect.Slice:
|
||||
if val.Elem().Kind() == reflect.Uint8 {
|
||||
return "varbinary"
|
||||
}
|
||||
}
|
||||
|
||||
switch val.Name() {
|
||||
case "NullInt64":
|
||||
return "bigint"
|
||||
case "NullFloat64":
|
||||
return "float(53)"
|
||||
case "NullBool":
|
||||
return "tinyint"
|
||||
case "Time":
|
||||
return "datetime"
|
||||
}
|
||||
|
||||
if maxsize < 1 {
|
||||
maxsize = 255
|
||||
}
|
||||
return fmt.Sprintf("varchar(%d)", maxsize)
|
||||
}
|
||||
|
||||
// Returns auto_increment
|
||||
func (d SqlServerDialect) AutoIncrStr() string {
|
||||
return "identity(0,1)"
|
||||
}
|
||||
|
||||
// Empty string removes autoincrement columns from the INSERT statements.
|
||||
func (d SqlServerDialect) AutoIncrBindValue() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (d SqlServerDialect) AutoIncrInsertSuffix(col *ColumnMap) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Returns suffix
|
||||
func (d SqlServerDialect) CreateTableSuffix() string {
|
||||
|
||||
return d.suffix
|
||||
}
|
||||
|
||||
func (d SqlServerDialect) TruncateClause() string {
|
||||
return "delete from"
|
||||
}
|
||||
|
||||
// Returns "?"
|
||||
func (d SqlServerDialect) BindVar(i int) string {
|
||||
return "?"
|
||||
}
|
||||
|
||||
func (d SqlServerDialect) InsertAutoIncr(exec SqlExecutor, insertSql string, params ...interface{}) (int64, error) {
|
||||
return standardInsertAutoIncr(exec, insertSql, params...)
|
||||
}
|
||||
|
||||
func (d SqlServerDialect) QuoteField(f string) string {
|
||||
return `"` + f + `"`
|
||||
}
|
||||
|
||||
func (d SqlServerDialect) QuotedTableForQuery(schema string, table string) string {
|
||||
if strings.TrimSpace(schema) == "" {
|
||||
return table
|
||||
}
|
||||
return schema + "." + table
|
||||
}
|
||||
|
||||
func (d SqlServerDialect) QuerySuffix() string { return ";" }
|
||||
|
||||
func (d SqlServerDialect) IfSchemaNotExists(command, schema string) string {
|
||||
s := fmt.Sprintf("if not exists (select name from sys.schemas where name = '%s') %s", schema, command)
|
||||
return s
|
||||
}
|
||||
|
||||
func (d SqlServerDialect) IfTableExists(command, schema, table string) string {
|
||||
var schema_clause string
|
||||
if strings.TrimSpace(schema) != "" {
|
||||
schema_clause = fmt.Sprintf("table_schema = '%s' and ", schema)
|
||||
}
|
||||
s := fmt.Sprintf("if exists (select * from information_schema.tables where %stable_name = '%s') %s", schema_clause, table, command)
|
||||
return s
|
||||
}
|
||||
|
||||
func (d SqlServerDialect) IfTableNotExists(command, schema, table string) string {
|
||||
var schema_clause string
|
||||
if strings.TrimSpace(schema) != "" {
|
||||
schema_clause = fmt.Sprintf("table_schema = '%s' and ", schema)
|
||||
}
|
||||
s := fmt.Sprintf("if not exists (select * from information_schema.tables where %stable_name = '%s') %s", schema_clause, table, command)
|
||||
return s
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////
|
||||
// Oracle //
|
||||
///////////
|
||||
|
||||
// Implementation of Dialect for Oracle databases.
|
||||
type OracleDialect struct{}
|
||||
|
||||
func (d OracleDialect) QuerySuffix() string { return "" }
|
||||
|
||||
func (d OracleDialect) ToSqlType(val reflect.Type, maxsize int, isAutoIncr bool) string {
|
||||
switch val.Kind() {
|
||||
case reflect.Ptr:
|
||||
return d.ToSqlType(val.Elem(), maxsize, isAutoIncr)
|
||||
case reflect.Bool:
|
||||
return "boolean"
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint8, reflect.Uint16, reflect.Uint32:
|
||||
if isAutoIncr {
|
||||
return "serial"
|
||||
}
|
||||
return "integer"
|
||||
case reflect.Int64, reflect.Uint64:
|
||||
if isAutoIncr {
|
||||
return "bigserial"
|
||||
}
|
||||
return "bigint"
|
||||
case reflect.Float64:
|
||||
return "double precision"
|
||||
case reflect.Float32:
|
||||
return "real"
|
||||
case reflect.Slice:
|
||||
if val.Elem().Kind() == reflect.Uint8 {
|
||||
return "bytea"
|
||||
}
|
||||
}
|
||||
|
||||
switch val.Name() {
|
||||
case "NullInt64":
|
||||
return "bigint"
|
||||
case "NullFloat64":
|
||||
return "double precision"
|
||||
case "NullBool":
|
||||
return "boolean"
|
||||
case "NullTime", "Time":
|
||||
return "timestamp with time zone"
|
||||
}
|
||||
|
||||
if maxsize > 0 {
|
||||
return fmt.Sprintf("varchar(%d)", maxsize)
|
||||
} else {
|
||||
return "text"
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Returns empty string
|
||||
func (d OracleDialect) AutoIncrStr() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (d OracleDialect) AutoIncrBindValue() string {
|
||||
return "default"
|
||||
}
|
||||
|
||||
func (d OracleDialect) AutoIncrInsertSuffix(col *ColumnMap) string {
|
||||
return " returning " + col.ColumnName
|
||||
}
|
||||
|
||||
// Returns suffix
|
||||
func (d OracleDialect) CreateTableSuffix() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (d OracleDialect) TruncateClause() string {
|
||||
return "truncate"
|
||||
}
|
||||
|
||||
// Returns "$(i+1)"
|
||||
func (d OracleDialect) BindVar(i int) string {
|
||||
return fmt.Sprintf(":%d", i+1)
|
||||
}
|
||||
|
||||
func (d OracleDialect) InsertAutoIncr(exec SqlExecutor, insertSql string, params ...interface{}) (int64, error) {
|
||||
rows, err := exec.query(insertSql, params...)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
if rows.Next() {
|
||||
var id int64
|
||||
err := rows.Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
return 0, errors.New("No serial value returned for insert: " + insertSql + " Encountered error: " + rows.Err().Error())
|
||||
}
|
||||
|
||||
func (d OracleDialect) QuoteField(f string) string {
|
||||
return `"` + strings.ToUpper(f) + `"`
|
||||
}
|
||||
|
||||
func (d OracleDialect) QuotedTableForQuery(schema string, table string) string {
|
||||
if strings.TrimSpace(schema) == "" {
|
||||
return d.QuoteField(table)
|
||||
}
|
||||
|
||||
return schema + "." + d.QuoteField(table)
|
||||
}
|
||||
|
||||
func (d OracleDialect) IfSchemaNotExists(command, schema string) string {
|
||||
return fmt.Sprintf("%s if not exists", command)
|
||||
}
|
||||
|
||||
func (d OracleDialect) IfTableExists(command, schema, table string) string {
|
||||
return fmt.Sprintf("%s if exists", command)
|
||||
}
|
||||
|
||||
func (d OracleDialect) IfTableNotExists(command, schema, table string) string {
|
||||
return fmt.Sprintf("%s if not exists", command)
|
||||
}
|
||||
|
||||
171
Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_mysql.go
сгенерированный
поставляемый
Обычный файл
171
Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_mysql.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,171 @@
|
||||
// Copyright 2012 James Cooper. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package gorp provides a simple way to marshal Go structs to and from
|
||||
// SQL databases. It uses the database/sql package, and should work with any
|
||||
// compliant database/sql driver.
|
||||
//
|
||||
// Source code and project home:
|
||||
// https://github.com/go-gorp/gorp
|
||||
|
||||
package gorp
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Implementation of Dialect for MySQL databases.
|
||||
type MySQLDialect struct {
|
||||
|
||||
// Engine is the storage engine to use "InnoDB" vs "MyISAM" for example
|
||||
Engine string
|
||||
|
||||
// Encoding is the character encoding to use for created tables
|
||||
Encoding string
|
||||
}
|
||||
|
||||
func (d MySQLDialect) QuerySuffix() string { return ";" }
|
||||
|
||||
func (d MySQLDialect) ToSqlType(val reflect.Type, maxsize int, isAutoIncr bool) string {
|
||||
switch val.Kind() {
|
||||
case reflect.Ptr:
|
||||
return d.ToSqlType(val.Elem(), maxsize, isAutoIncr)
|
||||
case reflect.Bool:
|
||||
return "boolean"
|
||||
case reflect.Int8:
|
||||
return "tinyint"
|
||||
case reflect.Uint8:
|
||||
return "tinyint unsigned"
|
||||
case reflect.Int16:
|
||||
return "smallint"
|
||||
case reflect.Uint16:
|
||||
return "smallint unsigned"
|
||||
case reflect.Int, reflect.Int32:
|
||||
return "int"
|
||||
case reflect.Uint, reflect.Uint32:
|
||||
return "int unsigned"
|
||||
case reflect.Int64:
|
||||
return "bigint"
|
||||
case reflect.Uint64:
|
||||
return "bigint unsigned"
|
||||
case reflect.Float64, reflect.Float32:
|
||||
return "double"
|
||||
case reflect.Slice:
|
||||
if val.Elem().Kind() == reflect.Uint8 {
|
||||
return "mediumblob"
|
||||
}
|
||||
}
|
||||
|
||||
switch val.Name() {
|
||||
case "NullInt64":
|
||||
return "bigint"
|
||||
case "NullFloat64":
|
||||
return "double"
|
||||
case "NullBool":
|
||||
return "tinyint"
|
||||
case "Time":
|
||||
return "datetime"
|
||||
}
|
||||
|
||||
if maxsize < 1 {
|
||||
maxsize = 255
|
||||
}
|
||||
|
||||
/* == About varchar(N) ==
|
||||
* N is number of characters.
|
||||
* A varchar column can store up to 65535 bytes.
|
||||
* Remember that 1 character is 3 bytes in utf-8 charset.
|
||||
* Also remember that each row can store up to 65535 bytes,
|
||||
* and you have some overheads, so it's not possible for a
|
||||
* varchar column to have 65535/3 characters really.
|
||||
* So it would be better to use 'text' type in stead of
|
||||
* large varchar type.
|
||||
*/
|
||||
if maxsize < 256 {
|
||||
return fmt.Sprintf("varchar(%d)", maxsize)
|
||||
} else {
|
||||
return "text"
|
||||
}
|
||||
}
|
||||
|
||||
// Returns auto_increment
|
||||
func (d MySQLDialect) AutoIncrStr() string {
|
||||
return "auto_increment"
|
||||
}
|
||||
|
||||
func (d MySQLDialect) AutoIncrBindValue() string {
|
||||
return "null"
|
||||
}
|
||||
|
||||
func (d MySQLDialect) AutoIncrInsertSuffix(col *ColumnMap) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Returns engine=%s charset=%s based on values stored on struct
|
||||
func (d MySQLDialect) CreateTableSuffix() string {
|
||||
if d.Engine == "" || d.Encoding == "" {
|
||||
msg := "gorp - undefined"
|
||||
|
||||
if d.Engine == "" {
|
||||
msg += " MySQLDialect.Engine"
|
||||
}
|
||||
if d.Engine == "" && d.Encoding == "" {
|
||||
msg += ","
|
||||
}
|
||||
if d.Encoding == "" {
|
||||
msg += " MySQLDialect.Encoding"
|
||||
}
|
||||
msg += ". Check that your MySQLDialect was correctly initialized when declared."
|
||||
panic(msg)
|
||||
}
|
||||
|
||||
return fmt.Sprintf(" engine=%s charset=%s", d.Engine, d.Encoding)
|
||||
}
|
||||
|
||||
func (m MySQLDialect) CreateIndexSuffix() string {
|
||||
return "using"
|
||||
}
|
||||
|
||||
func (m MySQLDialect) DropIndexSuffix() string {
|
||||
return "on"
|
||||
}
|
||||
|
||||
func (m MySQLDialect) TruncateClause() string {
|
||||
return "truncate"
|
||||
}
|
||||
|
||||
// Returns "?"
|
||||
func (d MySQLDialect) BindVar(i int) string {
|
||||
return "?"
|
||||
}
|
||||
|
||||
func (d MySQLDialect) InsertAutoIncr(exec SqlExecutor, insertSql string, params ...interface{}) (int64, error) {
|
||||
return standardInsertAutoIncr(exec, insertSql, params...)
|
||||
}
|
||||
|
||||
func (d MySQLDialect) QuoteField(f string) string {
|
||||
return "`" + f + "`"
|
||||
}
|
||||
|
||||
func (d MySQLDialect) QuotedTableForQuery(schema string, table string) string {
|
||||
if strings.TrimSpace(schema) == "" {
|
||||
return d.QuoteField(table)
|
||||
}
|
||||
|
||||
return schema + "." + d.QuoteField(table)
|
||||
}
|
||||
|
||||
func (d MySQLDialect) IfSchemaNotExists(command, schema string) string {
|
||||
return fmt.Sprintf("%s if not exists", command)
|
||||
}
|
||||
|
||||
func (d MySQLDialect) IfTableExists(command, schema, table string) string {
|
||||
return fmt.Sprintf("%s if exists", command)
|
||||
}
|
||||
|
||||
func (d MySQLDialect) IfTableNotExists(command, schema, table string) string {
|
||||
return fmt.Sprintf("%s if not exists", command)
|
||||
}
|
||||
146
Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_oracle.go
сгенерированный
поставляемый
Обычный файл
146
Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_oracle.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,146 @@
|
||||
// Copyright 2012 James Cooper. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package gorp provides a simple way to marshal Go structs to and from
|
||||
// SQL databases. It uses the database/sql package, and should work with any
|
||||
// compliant database/sql driver.
|
||||
//
|
||||
// Source code and project home:
|
||||
// https://github.com/go-gorp/gorp
|
||||
|
||||
package gorp
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Implementation of Dialect for Oracle databases.
|
||||
type OracleDialect struct{}
|
||||
|
||||
func (d OracleDialect) QuerySuffix() string { return "" }
|
||||
|
||||
func (d OracleDialect) CreateIndexSuffix() string { return "" }
|
||||
|
||||
func (d OracleDialect) DropIndexSuffix() string { return "" }
|
||||
|
||||
func (d OracleDialect) ToSqlType(val reflect.Type, maxsize int, isAutoIncr bool) string {
|
||||
switch val.Kind() {
|
||||
case reflect.Ptr:
|
||||
return d.ToSqlType(val.Elem(), maxsize, isAutoIncr)
|
||||
case reflect.Bool:
|
||||
return "boolean"
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32:
|
||||
if isAutoIncr {
|
||||
return "serial"
|
||||
}
|
||||
return "integer"
|
||||
case reflect.Int64, reflect.Uint64:
|
||||
if isAutoIncr {
|
||||
return "bigserial"
|
||||
}
|
||||
return "bigint"
|
||||
case reflect.Float64:
|
||||
return "double precision"
|
||||
case reflect.Float32:
|
||||
return "real"
|
||||
case reflect.Slice:
|
||||
if val.Elem().Kind() == reflect.Uint8 {
|
||||
return "bytea"
|
||||
}
|
||||
}
|
||||
|
||||
switch val.Name() {
|
||||
case "NullInt64":
|
||||
return "bigint"
|
||||
case "NullFloat64":
|
||||
return "double precision"
|
||||
case "NullBool":
|
||||
return "boolean"
|
||||
case "NullTime", "Time":
|
||||
return "timestamp with time zone"
|
||||
}
|
||||
|
||||
if maxsize > 0 {
|
||||
return fmt.Sprintf("varchar(%d)", maxsize)
|
||||
} else {
|
||||
return "text"
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Returns empty string
|
||||
func (d OracleDialect) AutoIncrStr() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (d OracleDialect) AutoIncrBindValue() string {
|
||||
return "NULL"
|
||||
}
|
||||
|
||||
func (d OracleDialect) AutoIncrInsertSuffix(col *ColumnMap) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Returns suffix
|
||||
func (d OracleDialect) CreateTableSuffix() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (d OracleDialect) TruncateClause() string {
|
||||
return "truncate"
|
||||
}
|
||||
|
||||
// Returns "$(i+1)"
|
||||
func (d OracleDialect) BindVar(i int) string {
|
||||
return fmt.Sprintf(":%d", i+1)
|
||||
}
|
||||
|
||||
// After executing the insert uses the ColMap IdQuery to get the generated id
|
||||
func (d OracleDialect) InsertQueryToTarget(exec SqlExecutor, insertSql, idSql string, target interface{}, params ...interface{}) error {
|
||||
_, err := exec.Exec(insertSql, params...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
id, err := exec.SelectInt(idSql)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch target.(type) {
|
||||
case *int64:
|
||||
*(target.(*int64)) = id
|
||||
case *int32:
|
||||
*(target.(*int32)) = int32(id)
|
||||
case int:
|
||||
*(target.(*int)) = int(id)
|
||||
default:
|
||||
return fmt.Errorf("Id field can be int, int32 or int64")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d OracleDialect) QuoteField(f string) string {
|
||||
return `"` + strings.ToUpper(f) + `"`
|
||||
}
|
||||
|
||||
func (d OracleDialect) QuotedTableForQuery(schema string, table string) string {
|
||||
if strings.TrimSpace(schema) == "" {
|
||||
return d.QuoteField(table)
|
||||
}
|
||||
|
||||
return schema + "." + d.QuoteField(table)
|
||||
}
|
||||
|
||||
func (d OracleDialect) IfSchemaNotExists(command, schema string) string {
|
||||
return fmt.Sprintf("%s if not exists", command)
|
||||
}
|
||||
|
||||
func (d OracleDialect) IfTableExists(command, schema, table string) string {
|
||||
return fmt.Sprintf("%s if exists", command)
|
||||
}
|
||||
|
||||
func (d OracleDialect) IfTableNotExists(command, schema, table string) string {
|
||||
return fmt.Sprintf("%s if not exists", command)
|
||||
}
|
||||
147
Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_postgres.go
сгенерированный
поставляемый
Обычный файл
147
Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_postgres.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,147 @@
|
||||
// Copyright 2012 James Cooper. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package gorp provides a simple way to marshal Go structs to and from
|
||||
// SQL databases. It uses the database/sql package, and should work with any
|
||||
// compliant database/sql driver.
|
||||
//
|
||||
// Source code and project home:
|
||||
// https://github.com/go-gorp/gorp
|
||||
|
||||
package gorp
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type PostgresDialect struct {
|
||||
suffix string
|
||||
}
|
||||
|
||||
func (d PostgresDialect) QuerySuffix() string { return ";" }
|
||||
|
||||
func (d PostgresDialect) ToSqlType(val reflect.Type, maxsize int, isAutoIncr bool) string {
|
||||
switch val.Kind() {
|
||||
case reflect.Ptr:
|
||||
return d.ToSqlType(val.Elem(), maxsize, isAutoIncr)
|
||||
case reflect.Bool:
|
||||
return "boolean"
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32:
|
||||
if isAutoIncr {
|
||||
return "serial"
|
||||
}
|
||||
return "integer"
|
||||
case reflect.Int64, reflect.Uint64:
|
||||
if isAutoIncr {
|
||||
return "bigserial"
|
||||
}
|
||||
return "bigint"
|
||||
case reflect.Float64:
|
||||
return "double precision"
|
||||
case reflect.Float32:
|
||||
return "real"
|
||||
case reflect.Slice:
|
||||
if val.Elem().Kind() == reflect.Uint8 {
|
||||
return "bytea"
|
||||
}
|
||||
}
|
||||
|
||||
switch val.Name() {
|
||||
case "NullInt64":
|
||||
return "bigint"
|
||||
case "NullFloat64":
|
||||
return "double precision"
|
||||
case "NullBool":
|
||||
return "boolean"
|
||||
case "Time", "NullTime":
|
||||
return "timestamp with time zone"
|
||||
}
|
||||
|
||||
if maxsize > 0 {
|
||||
return fmt.Sprintf("varchar(%d)", maxsize)
|
||||
} else {
|
||||
return "text"
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Returns empty string
|
||||
func (d PostgresDialect) AutoIncrStr() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (d PostgresDialect) AutoIncrBindValue() string {
|
||||
return "default"
|
||||
}
|
||||
|
||||
func (d PostgresDialect) AutoIncrInsertSuffix(col *ColumnMap) string {
|
||||
return " returning " + col.ColumnName
|
||||
}
|
||||
|
||||
// Returns suffix
|
||||
func (d PostgresDialect) CreateTableSuffix() string {
|
||||
return d.suffix
|
||||
}
|
||||
|
||||
func (d PostgresDialect) CreateIndexSuffix() string {
|
||||
return "using"
|
||||
}
|
||||
|
||||
func (d PostgresDialect) DropIndexSuffix() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (d PostgresDialect) TruncateClause() string {
|
||||
return "truncate"
|
||||
}
|
||||
|
||||
// Returns "$(i+1)"
|
||||
func (d PostgresDialect) BindVar(i int) string {
|
||||
return fmt.Sprintf("$%d", i+1)
|
||||
}
|
||||
|
||||
func (d PostgresDialect) InsertAutoIncrToTarget(exec SqlExecutor, insertSql string, target interface{}, params ...interface{}) error {
|
||||
rows, err := exec.query(insertSql, params...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
if !rows.Next() {
|
||||
return fmt.Errorf("No serial value returned for insert: %s Encountered error: %s", insertSql, rows.Err())
|
||||
}
|
||||
if err := rows.Scan(target); err != nil {
|
||||
return err
|
||||
}
|
||||
if rows.Next() {
|
||||
return fmt.Errorf("more than two serial value returned for insert: %s", insertSql)
|
||||
}
|
||||
return rows.Err()
|
||||
}
|
||||
|
||||
func (d PostgresDialect) QuoteField(f string) string {
|
||||
return `"` + strings.ToLower(f) + `"`
|
||||
}
|
||||
|
||||
func (d PostgresDialect) QuotedTableForQuery(schema string, table string) string {
|
||||
if strings.TrimSpace(schema) == "" {
|
||||
return d.QuoteField(table)
|
||||
}
|
||||
|
||||
return schema + "." + d.QuoteField(table)
|
||||
}
|
||||
|
||||
func (d PostgresDialect) IfSchemaNotExists(command, schema string) string {
|
||||
return fmt.Sprintf("%s if not exists", command)
|
||||
}
|
||||
|
||||
func (d PostgresDialect) IfTableExists(command, schema, table string) string {
|
||||
return fmt.Sprintf("%s if exists", command)
|
||||
}
|
||||
|
||||
func (d PostgresDialect) IfTableNotExists(command, schema, table string) string {
|
||||
return fmt.Sprintf("%s if not exists", command)
|
||||
}
|
||||
119
Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_sqlite.go
сгенерированный
поставляемый
Обычный файл
119
Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_sqlite.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,119 @@
|
||||
// Copyright 2012 James Cooper. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package gorp provides a simple way to marshal Go structs to and from
|
||||
// SQL databases. It uses the database/sql package, and should work with any
|
||||
// compliant database/sql driver.
|
||||
//
|
||||
// Source code and project home:
|
||||
// https://github.com/go-gorp/gorp
|
||||
|
||||
package gorp
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
type SqliteDialect struct {
|
||||
suffix string
|
||||
}
|
||||
|
||||
func (d SqliteDialect) QuerySuffix() string { return ";" }
|
||||
|
||||
func (d SqliteDialect) ToSqlType(val reflect.Type, maxsize int, isAutoIncr bool) string {
|
||||
switch val.Kind() {
|
||||
case reflect.Ptr:
|
||||
return d.ToSqlType(val.Elem(), maxsize, isAutoIncr)
|
||||
case reflect.Bool:
|
||||
return "integer"
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
return "integer"
|
||||
case reflect.Float64, reflect.Float32:
|
||||
return "real"
|
||||
case reflect.Slice:
|
||||
if val.Elem().Kind() == reflect.Uint8 {
|
||||
return "blob"
|
||||
}
|
||||
}
|
||||
|
||||
switch val.Name() {
|
||||
case "NullInt64":
|
||||
return "integer"
|
||||
case "NullFloat64":
|
||||
return "real"
|
||||
case "NullBool":
|
||||
return "integer"
|
||||
case "Time":
|
||||
return "datetime"
|
||||
}
|
||||
|
||||
if maxsize < 1 {
|
||||
maxsize = 255
|
||||
}
|
||||
return fmt.Sprintf("varchar(%d)", maxsize)
|
||||
}
|
||||
|
||||
// Returns autoincrement
|
||||
func (d SqliteDialect) AutoIncrStr() string {
|
||||
return "autoincrement"
|
||||
}
|
||||
|
||||
func (d SqliteDialect) AutoIncrBindValue() string {
|
||||
return "null"
|
||||
}
|
||||
|
||||
func (d SqliteDialect) AutoIncrInsertSuffix(col *ColumnMap) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Returns suffix
|
||||
func (d SqliteDialect) CreateTableSuffix() string {
|
||||
return d.suffix
|
||||
}
|
||||
|
||||
func (d SqliteDialect) CreateIndexSuffix() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (d SqliteDialect) DropIndexSuffix() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// With sqlite, there technically isn't a TRUNCATE statement,
|
||||
// but a DELETE FROM uses a truncate optimization:
|
||||
// http://www.sqlite.org/lang_delete.html
|
||||
func (d SqliteDialect) TruncateClause() string {
|
||||
return "delete from"
|
||||
}
|
||||
|
||||
// Returns "?"
|
||||
func (d SqliteDialect) BindVar(i int) string {
|
||||
return "?"
|
||||
}
|
||||
|
||||
func (d SqliteDialect) InsertAutoIncr(exec SqlExecutor, insertSql string, params ...interface{}) (int64, error) {
|
||||
return standardInsertAutoIncr(exec, insertSql, params...)
|
||||
}
|
||||
|
||||
func (d SqliteDialect) QuoteField(f string) string {
|
||||
return `"` + f + `"`
|
||||
}
|
||||
|
||||
// sqlite does not have schemas like PostgreSQL does, so just escape it like normal
|
||||
func (d SqliteDialect) QuotedTableForQuery(schema string, table string) string {
|
||||
return d.QuoteField(table)
|
||||
}
|
||||
|
||||
func (d SqliteDialect) IfSchemaNotExists(command, schema string) string {
|
||||
return fmt.Sprintf("%s if not exists", command)
|
||||
}
|
||||
|
||||
func (d SqliteDialect) IfTableExists(command, schema, table string) string {
|
||||
return fmt.Sprintf("%s if exists", command)
|
||||
}
|
||||
|
||||
func (d SqliteDialect) IfTableNotExists(command, schema, table string) string {
|
||||
return fmt.Sprintf("%s if not exists", command)
|
||||
}
|
||||
152
Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_sqlserver.go
сгенерированный
поставляемый
Обычный файл
152
Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_sqlserver.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,152 @@
|
||||
// Copyright 2012 James Cooper. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package gorp provides a simple way to marshal Go structs to and from
|
||||
// SQL databases. It uses the database/sql package, and should work with any
|
||||
// compliant database/sql driver.
|
||||
//
|
||||
// Source code and project home:
|
||||
// https://github.com/go-gorp/gorp
|
||||
|
||||
package gorp
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Implementation of Dialect for Microsoft SQL Server databases.
|
||||
// Use gorp.SqlServerDialect{"2005"} for legacy datatypes.
|
||||
// Tested with driver: github.com/denisenkom/go-mssqldb
|
||||
|
||||
type SqlServerDialect struct {
|
||||
|
||||
// If set to "2005" legacy datatypes will be used
|
||||
Version string
|
||||
}
|
||||
|
||||
func (d SqlServerDialect) ToSqlType(val reflect.Type, maxsize int, isAutoIncr bool) string {
|
||||
switch val.Kind() {
|
||||
case reflect.Ptr:
|
||||
return d.ToSqlType(val.Elem(), maxsize, isAutoIncr)
|
||||
case reflect.Bool:
|
||||
return "bit"
|
||||
case reflect.Int8:
|
||||
return "tinyint"
|
||||
case reflect.Uint8:
|
||||
return "smallint"
|
||||
case reflect.Int16:
|
||||
return "smallint"
|
||||
case reflect.Uint16:
|
||||
return "int"
|
||||
case reflect.Int, reflect.Int32:
|
||||
return "int"
|
||||
case reflect.Uint, reflect.Uint32:
|
||||
return "bigint"
|
||||
case reflect.Int64:
|
||||
return "bigint"
|
||||
case reflect.Uint64:
|
||||
return "numeric(20,0)"
|
||||
case reflect.Float32:
|
||||
return "float(24)"
|
||||
case reflect.Float64:
|
||||
return "float(53)"
|
||||
case reflect.Slice:
|
||||
if val.Elem().Kind() == reflect.Uint8 {
|
||||
return "varbinary"
|
||||
}
|
||||
}
|
||||
|
||||
switch val.Name() {
|
||||
case "NullInt64":
|
||||
return "bigint"
|
||||
case "NullFloat64":
|
||||
return "float(53)"
|
||||
case "NullBool":
|
||||
return "bit"
|
||||
case "NullTime", "Time":
|
||||
if d.Version == "2005" {
|
||||
return "datetime"
|
||||
}
|
||||
return "datetime2"
|
||||
}
|
||||
|
||||
if maxsize < 1 {
|
||||
if d.Version == "2005" {
|
||||
maxsize = 255
|
||||
} else {
|
||||
return fmt.Sprintf("nvarchar(max)")
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf("nvarchar(%d)", maxsize)
|
||||
}
|
||||
|
||||
// Returns auto_increment
|
||||
func (d SqlServerDialect) AutoIncrStr() string {
|
||||
return "identity(0,1)"
|
||||
}
|
||||
|
||||
// Empty string removes autoincrement columns from the INSERT statements.
|
||||
func (d SqlServerDialect) AutoIncrBindValue() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (d SqlServerDialect) AutoIncrInsertSuffix(col *ColumnMap) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (d SqlServerDialect) CreateTableSuffix() string { return ";" }
|
||||
|
||||
func (d SqlServerDialect) TruncateClause() string {
|
||||
return "truncate table"
|
||||
}
|
||||
|
||||
// Returns "?"
|
||||
func (d SqlServerDialect) BindVar(i int) string {
|
||||
return "?"
|
||||
}
|
||||
|
||||
func (d SqlServerDialect) InsertAutoIncr(exec SqlExecutor, insertSql string, params ...interface{}) (int64, error) {
|
||||
return standardInsertAutoIncr(exec, insertSql, params...)
|
||||
}
|
||||
|
||||
func (d SqlServerDialect) QuoteField(f string) string {
|
||||
return "[" + strings.Replace(f, "]", "]]", -1) + "]"
|
||||
}
|
||||
|
||||
func (d SqlServerDialect) QuotedTableForQuery(schema string, table string) string {
|
||||
if strings.TrimSpace(schema) == "" {
|
||||
return d.QuoteField(table)
|
||||
}
|
||||
return d.QuoteField(schema) + "." + d.QuoteField(table)
|
||||
}
|
||||
|
||||
func (d SqlServerDialect) QuerySuffix() string { return ";" }
|
||||
|
||||
func (d SqlServerDialect) IfSchemaNotExists(command, schema string) string {
|
||||
s := fmt.Sprintf("if schema_id(N'%s') is null %s", schema, command)
|
||||
return s
|
||||
}
|
||||
|
||||
func (d SqlServerDialect) IfTableExists(command, schema, table string) string {
|
||||
var schema_clause string
|
||||
if strings.TrimSpace(schema) != "" {
|
||||
schema_clause = fmt.Sprintf("%s.", d.QuoteField(schema))
|
||||
}
|
||||
s := fmt.Sprintf("if object_id('%s%s') is not null %s", schema_clause, d.QuoteField(table), command)
|
||||
return s
|
||||
}
|
||||
|
||||
func (d SqlServerDialect) IfTableNotExists(command, schema, table string) string {
|
||||
var schema_clause string
|
||||
if strings.TrimSpace(schema) != "" {
|
||||
schema_clause = fmt.Sprintf("%s.", schema)
|
||||
}
|
||||
s := fmt.Sprintf("if object_id('%s%s') is null %s", schema_clause, table, command)
|
||||
return s
|
||||
}
|
||||
|
||||
func (d SqlServerDialect) CreateIndexSuffix() string { return "" }
|
||||
func (d SqlServerDialect) DropIndexSuffix() string { return "" }
|
||||
14
Godeps/_workspace/src/github.com/go-gorp/gorp/errors.go
сгенерированный
поставляемый
14
Godeps/_workspace/src/github.com/go-gorp/gorp/errors.go
сгенерированный
поставляемый
@@ -1,3 +1,14 @@
|
||||
// Copyright 2012 James Cooper. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package gorp provides a simple way to marshal Go structs to and from
|
||||
// SQL databases. It uses the database/sql package, and should work with any
|
||||
// compliant database/sql driver.
|
||||
//
|
||||
// Source code and project home:
|
||||
// https://github.com/go-gorp/gorp
|
||||
|
||||
package gorp
|
||||
|
||||
import (
|
||||
@@ -6,13 +17,14 @@ import (
|
||||
|
||||
// A non-fatal error, when a select query returns columns that do not exist
|
||||
// as fields in the struct it is being mapped to
|
||||
// TODO: discuss wether this needs an error. encoding/json silently ignores missing fields
|
||||
type NoFieldInTypeError struct {
|
||||
TypeName string
|
||||
MissingColNames []string
|
||||
}
|
||||
|
||||
func (err *NoFieldInTypeError) Error() string {
|
||||
return fmt.Sprintf("gorp: No fields %+v in type %s", err.MissingColNames, err.TypeName)
|
||||
return fmt.Sprintf("gorp: no fields %+v in type %s", err.MissingColNames, err.TypeName)
|
||||
}
|
||||
|
||||
// returns true if the error is non-fatal (ie, we shouldn't immediately return)
|
||||
|
||||
1678
Godeps/_workspace/src/github.com/go-gorp/gorp/gorp.go
сгенерированный
поставляемый
1678
Godeps/_workspace/src/github.com/go-gorp/gorp/gorp.go
сгенерированный
поставляемый
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
243
Godeps/_workspace/src/github.com/go-gorp/gorp/gorp_test.go
сгенерированный
поставляемый
243
Godeps/_workspace/src/github.com/go-gorp/gorp/gorp_test.go
сгенерированный
поставляемый
@@ -1,31 +1,56 @@
|
||||
// Copyright 2012 James Cooper. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package gorp provides a simple way to marshal Go structs to and from
|
||||
// SQL databases. It uses the database/sql package, and should work with any
|
||||
// compliant database/sql driver.
|
||||
//
|
||||
// Source code and project home:
|
||||
// https://github.com/go-gorp/gorp
|
||||
|
||||
package gorp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"math/rand"
|
||||
"os"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
_ "github.com/lib/pq"
|
||||
_ "github.com/mattermost/platform/Godeps/_workspace/src/github.com/go-sql-driver/mysql"
|
||||
_ "github.com/mattermost/platform/Godeps/_workspace/src/github.com/lib/pq"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
_ "github.com/ziutek/mymysql/godrv"
|
||||
)
|
||||
|
||||
// verify interface compliance
|
||||
var _ Dialect = SqliteDialect{}
|
||||
var _ Dialect = PostgresDialect{}
|
||||
var _ Dialect = MySQLDialect{}
|
||||
var _ Dialect = SqlServerDialect{}
|
||||
var _ Dialect = OracleDialect{}
|
||||
var (
|
||||
// verify interface compliance
|
||||
_ = []Dialect{
|
||||
SqliteDialect{},
|
||||
PostgresDialect{},
|
||||
MySQLDialect{},
|
||||
SqlServerDialect{},
|
||||
OracleDialect{},
|
||||
}
|
||||
|
||||
debug bool
|
||||
)
|
||||
|
||||
func init() {
|
||||
flag.BoolVar(&debug, "trace", true, "Turn on or off database tracing (DbMap.TraceOn)")
|
||||
flag.Parse()
|
||||
}
|
||||
|
||||
type testable interface {
|
||||
GetId() int64
|
||||
@@ -41,6 +66,15 @@ type Invoice struct {
|
||||
IsPaid bool
|
||||
}
|
||||
|
||||
type InvoiceWithValuer struct {
|
||||
Id int64
|
||||
Created int64
|
||||
Updated int64
|
||||
Memo string
|
||||
Person PersonValuerScanner `db:"personid"`
|
||||
IsPaid bool
|
||||
}
|
||||
|
||||
func (me *Invoice) GetId() int64 { return me.Id }
|
||||
func (me *Invoice) Rand() {
|
||||
me.Memo = fmt.Sprintf("random %d", rand.Int63())
|
||||
@@ -49,7 +83,7 @@ func (me *Invoice) Rand() {
|
||||
}
|
||||
|
||||
type InvoiceTag struct {
|
||||
Id int64 `db:"myid"`
|
||||
Id int64 `db:"myid, primarykey, autoincrement"`
|
||||
Created int64 `db:"myCreated"`
|
||||
Updated int64 `db:"date_updated"`
|
||||
Memo string
|
||||
@@ -90,6 +124,34 @@ type Person struct {
|
||||
Version int64
|
||||
}
|
||||
|
||||
type PersonValuerScanner struct {
|
||||
Person
|
||||
}
|
||||
|
||||
func (p PersonValuerScanner) Value() (driver.Value, error) {
|
||||
return p.Id, nil
|
||||
}
|
||||
|
||||
// FIXME: this Scan is never actually used in the tests?
|
||||
// Also: if the comments below on the mysql driver are true, then that should be fixed by the dialect when scanning values into structs.
|
||||
func (p *PersonValuerScanner) Scan(value interface{}) (err error) {
|
||||
switch src := value.(type) {
|
||||
case []byte:
|
||||
// The mysql driver seems to return a []byte, even though the
|
||||
// type in the database is bigint. Note that this case is
|
||||
// *only* used by the mysql driver.
|
||||
p.Id, err = strconv.ParseInt(string(src), 10, 64)
|
||||
case int64:
|
||||
// postgres, gomysql, and sqlite drivers all return an int64,
|
||||
// as you'd expect.
|
||||
p.Id = src
|
||||
default:
|
||||
typ := reflect.TypeOf(value)
|
||||
return fmt.Errorf("Expected person value to be convertible to int64, got %v (type %s)", value, typ)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type FNameOnly struct {
|
||||
FName string
|
||||
}
|
||||
@@ -160,6 +222,17 @@ type WithEmbeddedStruct struct {
|
||||
Names
|
||||
}
|
||||
|
||||
type WithEmbeddedStructConflictingEmbeddedMemberNames struct {
|
||||
Id int64
|
||||
Names
|
||||
NamesConflict
|
||||
}
|
||||
|
||||
type WithEmbeddedStructSameMemberName struct {
|
||||
Id int64
|
||||
SameName
|
||||
}
|
||||
|
||||
type WithEmbeddedStructBeforeAutoincrField struct {
|
||||
Names
|
||||
Id int64
|
||||
@@ -175,6 +248,15 @@ type Names struct {
|
||||
LastName string
|
||||
}
|
||||
|
||||
type NamesConflict struct {
|
||||
FirstName string
|
||||
Surname string
|
||||
}
|
||||
|
||||
type SameName struct {
|
||||
SameName string
|
||||
}
|
||||
|
||||
type UniqueColumns struct {
|
||||
FirstName string
|
||||
LastName string
|
||||
@@ -353,7 +435,6 @@ func TestTruncateTables(t *testing.T) {
|
||||
func TestCustomDateType(t *testing.T) {
|
||||
dbmap := newDbMap()
|
||||
dbmap.TypeConverter = testTypeConverter{}
|
||||
dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
|
||||
dbmap.AddTable(WithCustomDate{}).SetKeys(true, "Id")
|
||||
err := dbmap.CreateTables()
|
||||
if err != nil {
|
||||
@@ -389,7 +470,6 @@ func TestCustomDateType(t *testing.T) {
|
||||
|
||||
func TestUIntPrimaryKey(t *testing.T) {
|
||||
dbmap := newDbMap()
|
||||
dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
|
||||
dbmap.AddTable(PersonUInt64{}).SetKeys(true, "Id")
|
||||
dbmap.AddTable(PersonUInt32{}).SetKeys(true, "Id")
|
||||
dbmap.AddTable(PersonUInt16{}).SetKeys(true, "Id")
|
||||
@@ -419,7 +499,6 @@ func TestUIntPrimaryKey(t *testing.T) {
|
||||
|
||||
func TestSetUniqueTogether(t *testing.T) {
|
||||
dbmap := newDbMap()
|
||||
dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
|
||||
dbmap.AddTable(UniqueColumns{}).SetUniqueTogether("FirstName", "LastName").SetUniqueTogether("City", "ZipCode")
|
||||
err := dbmap.CreateTablesIfNotExists()
|
||||
if err != nil {
|
||||
@@ -468,7 +547,6 @@ func TestSetUniqueTogether(t *testing.T) {
|
||||
func TestPersistentUser(t *testing.T) {
|
||||
dbmap := newDbMap()
|
||||
dbmap.Exec("drop table if exists PersistentUser")
|
||||
dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
|
||||
table := dbmap.AddTable(PersistentUser{}).SetKeys(false, "Key")
|
||||
table.ColMap("Key").Rename("mykey")
|
||||
err := dbmap.CreateTablesIfNotExists()
|
||||
@@ -581,7 +659,6 @@ func TestPersistentUser(t *testing.T) {
|
||||
func TestNamedQueryMap(t *testing.T) {
|
||||
dbmap := newDbMap()
|
||||
dbmap.Exec("drop table if exists PersistentUser")
|
||||
dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
|
||||
table := dbmap.AddTable(PersistentUser{}).SetKeys(false, "Key")
|
||||
table.ColMap("Key").Rename("mykey")
|
||||
err := dbmap.CreateTablesIfNotExists()
|
||||
@@ -679,7 +756,6 @@ select * from PersistentUser
|
||||
func TestNamedQueryStruct(t *testing.T) {
|
||||
dbmap := newDbMap()
|
||||
dbmap.Exec("drop table if exists PersistentUser")
|
||||
dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
|
||||
table := dbmap.AddTable(PersistentUser{}).SetKeys(false, "Key")
|
||||
table.ColMap("Key").Rename("mykey")
|
||||
err := dbmap.CreateTablesIfNotExists()
|
||||
@@ -859,9 +935,48 @@ func TestNullValues(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestScannerValuer(t *testing.T) {
|
||||
dbmap := newDbMap()
|
||||
dbmap.AddTableWithName(PersonValuerScanner{}, "person_test").SetKeys(true, "Id")
|
||||
dbmap.AddTableWithName(InvoiceWithValuer{}, "invoice_test").SetKeys(true, "Id")
|
||||
err := dbmap.CreateTables()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer dropAndClose(dbmap)
|
||||
|
||||
pv := PersonValuerScanner{}
|
||||
pv.FName = "foo"
|
||||
pv.LName = "bar"
|
||||
err = dbmap.Insert(&pv)
|
||||
if err != nil {
|
||||
t.Errorf("Could not insert PersonValuerScanner using Person table: %v", err)
|
||||
t.FailNow()
|
||||
}
|
||||
|
||||
inv := InvoiceWithValuer{}
|
||||
inv.Memo = "foo"
|
||||
inv.Person = pv
|
||||
err = dbmap.Insert(&inv)
|
||||
if err != nil {
|
||||
t.Errorf("Could not insert InvoiceWithValuer using Invoice table: %v", err)
|
||||
t.FailNow()
|
||||
}
|
||||
|
||||
res, err := dbmap.Get(InvoiceWithValuer{}, inv.Id)
|
||||
if err != nil {
|
||||
t.Errorf("Could not get InvoiceWithValuer: %v", err)
|
||||
t.FailNow()
|
||||
}
|
||||
dbInv := res.(*InvoiceWithValuer)
|
||||
|
||||
if dbInv.Person.Id != pv.Id {
|
||||
t.Errorf("InvoiceWithValuer got wrong person ID: %d (expected) != %d (actual)", pv.Id, dbInv.Person.Id)
|
||||
}
|
||||
}
|
||||
|
||||
func TestColumnProps(t *testing.T) {
|
||||
dbmap := newDbMap()
|
||||
dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
|
||||
t1 := dbmap.AddTable(Invoice{}).SetKeys(true, "Id")
|
||||
t1.ColMap("Created").Rename("date_created")
|
||||
t1.ColMap("Updated").SetTransient(true)
|
||||
@@ -1161,6 +1276,29 @@ func TestWithIgnoredColumn(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestColumnFilter(t *testing.T) {
|
||||
dbmap := initDbMap()
|
||||
defer dropAndClose(dbmap)
|
||||
|
||||
inv1 := &Invoice{0, 100, 200, "a", 0, false}
|
||||
_insert(dbmap, inv1)
|
||||
|
||||
inv1.Memo = "c"
|
||||
inv1.IsPaid = true
|
||||
_updateColumns(dbmap, func(col *ColumnMap) bool {
|
||||
return col.ColumnName == "Memo"
|
||||
}, inv1)
|
||||
|
||||
inv2 := &Invoice{}
|
||||
inv2 = _get(dbmap, inv2, inv1.Id).(*Invoice)
|
||||
if inv2.Memo != "c" {
|
||||
t.Errorf("Expected column to be updated (%#v)", inv2)
|
||||
}
|
||||
if inv2.IsPaid {
|
||||
t.Error("IsPaid shouldn't have been updated")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTypeConversionExample(t *testing.T) {
|
||||
dbmap := initDbMap()
|
||||
defer dropAndClose(dbmap)
|
||||
@@ -1217,6 +1355,60 @@ func TestWithEmbeddedStruct(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
func TestWithEmbeddedStructConflictingEmbeddedMemberNames(t *testing.T) {
|
||||
dbmap := initDbMap()
|
||||
defer dropAndClose(dbmap)
|
||||
|
||||
es := &WithEmbeddedStructConflictingEmbeddedMemberNames{-1, Names{FirstName: "Alice", LastName: "Smith"}, NamesConflict{FirstName: "Andrew", Surname: "Wiggin"}}
|
||||
_insert(dbmap, es)
|
||||
expected := &WithEmbeddedStructConflictingEmbeddedMemberNames{-1, Names{FirstName: "Alice", LastName: "Smith"}, NamesConflict{FirstName: "Andrew", Surname: "Wiggin"}}
|
||||
es2 := _get(dbmap, WithEmbeddedStructConflictingEmbeddedMemberNames{}, es.Id).(*WithEmbeddedStructConflictingEmbeddedMemberNames)
|
||||
if !reflect.DeepEqual(expected, es2) {
|
||||
t.Errorf("%v != %v", expected, es2)
|
||||
}
|
||||
|
||||
es2.Names.FirstName = "Bob"
|
||||
expected.Names.FirstName = "Bob"
|
||||
_update(dbmap, es2)
|
||||
es2 = _get(dbmap, WithEmbeddedStructConflictingEmbeddedMemberNames{}, es.Id).(*WithEmbeddedStructConflictingEmbeddedMemberNames)
|
||||
if !reflect.DeepEqual(expected, es2) {
|
||||
t.Errorf("%v != %v", expected, es2)
|
||||
}
|
||||
|
||||
ess := _rawselect(dbmap, WithEmbeddedStructConflictingEmbeddedMemberNames{}, "select * from embedded_struct_conflict_name_test")
|
||||
if !reflect.DeepEqual(es2, ess[0]) {
|
||||
t.Errorf("%v != %v", es2, ess[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithEmbeddedStructSameMemberName(t *testing.T) {
|
||||
dbmap := initDbMap()
|
||||
defer dropAndClose(dbmap)
|
||||
|
||||
es := &WithEmbeddedStructSameMemberName{-1, SameName{SameName: "Alice"}}
|
||||
_insert(dbmap, es)
|
||||
expected := &WithEmbeddedStructSameMemberName{-1, SameName{SameName: "Alice"}}
|
||||
es2 := _get(dbmap, WithEmbeddedStructSameMemberName{}, es.Id).(*WithEmbeddedStructSameMemberName)
|
||||
if !reflect.DeepEqual(expected, es2) {
|
||||
t.Errorf("%v != %v", expected, es2)
|
||||
}
|
||||
|
||||
es2.SameName = SameName{"Bob"}
|
||||
expected.SameName = SameName{"Bob"}
|
||||
_update(dbmap, es2)
|
||||
es2 = _get(dbmap, WithEmbeddedStructSameMemberName{}, es.Id).(*WithEmbeddedStructSameMemberName)
|
||||
if !reflect.DeepEqual(expected, es2) {
|
||||
t.Errorf("%v != %v", expected, es2)
|
||||
}
|
||||
|
||||
ess := _rawselect(dbmap, WithEmbeddedStructSameMemberName{}, "select * from embedded_struct_same_member_name_test")
|
||||
if !reflect.DeepEqual(es2, ess[0]) {
|
||||
t.Errorf("%v != %v", es2, ess[0])
|
||||
}
|
||||
}
|
||||
//*/
|
||||
|
||||
func TestWithEmbeddedStructBeforeAutoincr(t *testing.T) {
|
||||
dbmap := initDbMap()
|
||||
defer dropAndClose(dbmap)
|
||||
@@ -1359,7 +1551,6 @@ func TestVersionMultipleRows(t *testing.T) {
|
||||
|
||||
func TestWithStringPk(t *testing.T) {
|
||||
dbmap := newDbMap()
|
||||
dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
|
||||
dbmap.AddTableWithName(WithStringPk{}, "string_pk_test").SetKeys(true, "Id")
|
||||
_, err := dbmap.Exec("create table string_pk_test (Id varchar(255), Name varchar(255));")
|
||||
if err != nil {
|
||||
@@ -1491,7 +1682,6 @@ func testWithTime(t *testing.T) {
|
||||
// See: https://github.com/go-gorp/gorp/issues/86
|
||||
func testEmbeddedTime(t *testing.T) {
|
||||
dbmap := newDbMap()
|
||||
dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
|
||||
dbmap.AddTable(EmbeddedTime{}).SetKeys(false, "Id")
|
||||
defer dropAndClose(dbmap)
|
||||
err := dbmap.CreateTables()
|
||||
@@ -1987,7 +2177,7 @@ func initDbMapBench() *DbMap {
|
||||
func initDbMap() *DbMap {
|
||||
dbmap := newDbMap()
|
||||
dbmap.AddTableWithName(Invoice{}, "invoice_test").SetKeys(true, "Id")
|
||||
dbmap.AddTableWithName(InvoiceTag{}, "invoice_tag_test").SetKeys(true, "myid")
|
||||
dbmap.AddTableWithName(InvoiceTag{}, "invoice_tag_test") //key is set via primarykey attribute
|
||||
dbmap.AddTableWithName(AliasTransientField{}, "alias_trans_field_test").SetKeys(true, "id")
|
||||
dbmap.AddTableWithName(OverriddenInvoice{}, "invoice_override_test").SetKeys(false, "Id")
|
||||
dbmap.AddTableWithName(Person{}, "person_test").SetKeys(true, "Id").SetVersionCol("Version")
|
||||
@@ -1995,6 +2185,8 @@ func initDbMap() *DbMap {
|
||||
dbmap.AddTableWithName(IdCreated{}, "id_created_test").SetKeys(true, "Id")
|
||||
dbmap.AddTableWithName(TypeConversionExample{}, "type_conv_test").SetKeys(true, "Id")
|
||||
dbmap.AddTableWithName(WithEmbeddedStruct{}, "embedded_struct_test").SetKeys(true, "Id")
|
||||
//dbmap.AddTableWithName(WithEmbeddedStructConflictingEmbeddedMemberNames{}, "embedded_struct_conflict_name_test").SetKeys(true, "Id")
|
||||
//dbmap.AddTableWithName(WithEmbeddedStructSameMemberName{}, "embedded_struct_same_member_name_test").SetKeys(true, "Id")
|
||||
dbmap.AddTableWithName(WithEmbeddedStructBeforeAutoincrField{}, "embedded_struct_before_autoincr_test").SetKeys(true, "Id")
|
||||
dbmap.AddTableWithName(WithEmbeddedAutoincr{}, "embedded_autoincr_test").SetKeys(true, "Id")
|
||||
dbmap.AddTableWithName(WithTime{}, "time_test").SetKeys(true, "Id")
|
||||
@@ -2018,7 +2210,6 @@ func initDbMap() *DbMap {
|
||||
|
||||
func initDbMapNulls() *DbMap {
|
||||
dbmap := newDbMap()
|
||||
dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
|
||||
dbmap.AddTable(TableWithNull{}).SetKeys(false, "Id")
|
||||
err := dbmap.CreateTables()
|
||||
if err != nil {
|
||||
@@ -2030,7 +2221,9 @@ func initDbMapNulls() *DbMap {
|
||||
func newDbMap() *DbMap {
|
||||
dialect, driver := dialectAndDriver()
|
||||
dbmap := &DbMap{Db: connect(driver), Dialect: dialect}
|
||||
dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
|
||||
if debug {
|
||||
dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
|
||||
}
|
||||
return dbmap
|
||||
}
|
||||
|
||||
@@ -2081,6 +2274,14 @@ func _update(dbmap *DbMap, list ...interface{}) int64 {
|
||||
return count
|
||||
}
|
||||
|
||||
func _updateColumns(dbmap *DbMap, filter ColumnFilter, list ...interface{}) int64 {
|
||||
count, err := dbmap.UpdateColumns(filter, list...)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
func _del(dbmap *DbMap, list ...interface{}) int64 {
|
||||
count, err := dbmap.Delete(list...)
|
||||
if err != nil {
|
||||
|
||||
49
Godeps/_workspace/src/github.com/go-gorp/gorp/hooks.go
сгенерированный
поставляемый
Обычный файл
49
Godeps/_workspace/src/github.com/go-gorp/gorp/hooks.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,49 @@
|
||||
// Copyright 2012 James Cooper. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package gorp provides a simple way to marshal Go structs to and from
|
||||
// SQL databases. It uses the database/sql package, and should work with any
|
||||
// compliant database/sql driver.
|
||||
//
|
||||
// Source code and project home:
|
||||
// https://github.com/go-gorp/gorp
|
||||
|
||||
package gorp
|
||||
|
||||
//++ TODO v2-phase3: HasPostGet => PostGetter, HasPostDelete => PostDeleter, etc.
|
||||
|
||||
// PostUpdate() will be executed after the GET statement.
|
||||
type HasPostGet interface {
|
||||
PostGet(SqlExecutor) error
|
||||
}
|
||||
|
||||
// PostUpdate() will be executed after the DELETE statement
|
||||
type HasPostDelete interface {
|
||||
PostDelete(SqlExecutor) error
|
||||
}
|
||||
|
||||
// PostUpdate() will be executed after the UPDATE statement
|
||||
type HasPostUpdate interface {
|
||||
PostUpdate(SqlExecutor) error
|
||||
}
|
||||
|
||||
// PostInsert() will be executed after the INSERT statement
|
||||
type HasPostInsert interface {
|
||||
PostInsert(SqlExecutor) error
|
||||
}
|
||||
|
||||
// PreDelete() will be executed before the DELETE statement.
|
||||
type HasPreDelete interface {
|
||||
PreDelete(SqlExecutor) error
|
||||
}
|
||||
|
||||
// PreUpdate() will be executed before UPDATE statement.
|
||||
type HasPreUpdate interface {
|
||||
PreUpdate(SqlExecutor) error
|
||||
}
|
||||
|
||||
// PreInsert() will be executed before INSERT statement.
|
||||
type HasPreInsert interface {
|
||||
PreInsert(SqlExecutor) error
|
||||
}
|
||||
56
Godeps/_workspace/src/github.com/go-gorp/gorp/index.go
сгенерированный
поставляемый
Обычный файл
56
Godeps/_workspace/src/github.com/go-gorp/gorp/index.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,56 @@
|
||||
// Copyright 2012 James Cooper. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package gorp provides a simple way to marshal Go structs to and from
|
||||
// SQL databases. It uses the database/sql package, and should work with any
|
||||
// compliant database/sql driver.
|
||||
//
|
||||
// Source code and project home:
|
||||
// https://github.com/go-gorp/gorp
|
||||
|
||||
package gorp
|
||||
|
||||
// IndexMap represents a mapping between a Go struct field and a single
|
||||
// index in a table.
|
||||
// Unique and MaxSize only inform the
|
||||
// CreateTables() function and are not used by Insert/Update/Delete/Get.
|
||||
type IndexMap struct {
|
||||
// Index name in db table
|
||||
IndexName string
|
||||
|
||||
// If true, " unique" is added to create index statements.
|
||||
// Not used elsewhere
|
||||
Unique bool
|
||||
|
||||
// Index type supported by Dialect
|
||||
// Postgres: B-tree, Hash, GiST and GIN.
|
||||
// Mysql: Btree, Hash.
|
||||
// Sqlite: nil.
|
||||
IndexType string
|
||||
|
||||
// Columns name for single and multiple indexes
|
||||
columns []string
|
||||
}
|
||||
|
||||
// Rename allows you to specify the index name in the table
|
||||
//
|
||||
// Example: table.IndMap("customer_test_idx").Rename("customer_idx")
|
||||
//
|
||||
func (idx *IndexMap) Rename(indname string) *IndexMap {
|
||||
idx.IndexName = indname
|
||||
return idx
|
||||
}
|
||||
|
||||
// SetUnique adds "unique" to the create index statements for this
|
||||
// index, if b is true.
|
||||
func (idx *IndexMap) SetUnique(b bool) *IndexMap {
|
||||
idx.Unique = b
|
||||
return idx
|
||||
}
|
||||
|
||||
// SetIndexType specifies the index type supported by chousen SQL Dialect
|
||||
func (idx *IndexMap) SetIndexType(indtype string) *IndexMap {
|
||||
idx.IndexType = indtype
|
||||
return idx
|
||||
}
|
||||
63
Godeps/_workspace/src/github.com/go-gorp/gorp/lockerror.go
сгенерированный
поставляемый
Обычный файл
63
Godeps/_workspace/src/github.com/go-gorp/gorp/lockerror.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,63 @@
|
||||
// Copyright 2012 James Cooper. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package gorp provides a simple way to marshal Go structs to and from
|
||||
// SQL databases. It uses the database/sql package, and should work with any
|
||||
// compliant database/sql driver.
|
||||
//
|
||||
// Source code and project home:
|
||||
// https://github.com/go-gorp/gorp
|
||||
|
||||
package gorp
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
// OptimisticLockError is returned by Update() or Delete() if the
|
||||
// struct being modified has a Version field and the value is not equal to
|
||||
// the current value in the database
|
||||
type OptimisticLockError struct {
|
||||
// Table name where the lock error occurred
|
||||
TableName string
|
||||
|
||||
// Primary key values of the row being updated/deleted
|
||||
Keys []interface{}
|
||||
|
||||
// true if a row was found with those keys, indicating the
|
||||
// LocalVersion is stale. false if no value was found with those
|
||||
// keys, suggesting the row has been deleted since loaded, or
|
||||
// was never inserted to begin with
|
||||
RowExists bool
|
||||
|
||||
// Version value on the struct passed to Update/Delete. This value is
|
||||
// out of sync with the database.
|
||||
LocalVersion int64
|
||||
}
|
||||
|
||||
// Error returns a description of the cause of the lock error
|
||||
func (e OptimisticLockError) Error() string {
|
||||
if e.RowExists {
|
||||
return fmt.Sprintf("gorp: OptimisticLockError table=%s keys=%v out of date version=%d", e.TableName, e.Keys, e.LocalVersion)
|
||||
}
|
||||
|
||||
return fmt.Sprintf("gorp: OptimisticLockError no row found for table=%s keys=%v", e.TableName, e.Keys)
|
||||
}
|
||||
|
||||
func lockError(m *DbMap, exec SqlExecutor, tableName string,
|
||||
existingVer int64, elem reflect.Value,
|
||||
keys ...interface{}) (int64, error) {
|
||||
|
||||
existing, err := get(m, exec, elem.Interface(), keys...)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
|
||||
ole := OptimisticLockError{tableName, keys, true, existingVer}
|
||||
if existing == nil {
|
||||
ole.RowExists = false
|
||||
}
|
||||
return -1, ole
|
||||
}
|
||||
44
Godeps/_workspace/src/github.com/go-gorp/gorp/logging.go
сгенерированный
поставляемый
Обычный файл
44
Godeps/_workspace/src/github.com/go-gorp/gorp/logging.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,44 @@
|
||||
// Copyright 2012 James Cooper. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package gorp provides a simple way to marshal Go structs to and from
|
||||
// SQL databases. It uses the database/sql package, and should work with any
|
||||
// compliant database/sql driver.
|
||||
//
|
||||
// Source code and project home:
|
||||
// https://github.com/go-gorp/gorp
|
||||
|
||||
package gorp
|
||||
|
||||
import "fmt"
|
||||
|
||||
type GorpLogger interface {
|
||||
Printf(format string, v ...interface{})
|
||||
}
|
||||
|
||||
// TraceOn turns on SQL statement logging for this DbMap. After this is
|
||||
// called, all SQL statements will be sent to the logger. If prefix is
|
||||
// a non-empty string, it will be written to the front of all logged
|
||||
// strings, which can aid in filtering log lines.
|
||||
//
|
||||
// Use TraceOn if you want to spy on the SQL statements that gorp
|
||||
// generates.
|
||||
//
|
||||
// Note that the base log.Logger type satisfies GorpLogger, but adapters can
|
||||
// easily be written for other logging packages (e.g., the golang-sanctioned
|
||||
// glog framework).
|
||||
func (m *DbMap) TraceOn(prefix string, logger GorpLogger) {
|
||||
m.logger = logger
|
||||
if prefix == "" {
|
||||
m.logPrefix = prefix
|
||||
} else {
|
||||
m.logPrefix = fmt.Sprintf("%s ", prefix)
|
||||
}
|
||||
}
|
||||
|
||||
// TraceOff turns off tracing. It is idempotent.
|
||||
func (m *DbMap) TraceOff() {
|
||||
m.logger = nil
|
||||
m.logPrefix = ""
|
||||
}
|
||||
58
Godeps/_workspace/src/github.com/go-gorp/gorp/nulltypes.go
сгенерированный
поставляемый
Обычный файл
58
Godeps/_workspace/src/github.com/go-gorp/gorp/nulltypes.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,58 @@
|
||||
// Copyright 2012 James Cooper. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package gorp provides a simple way to marshal Go structs to and from
|
||||
// SQL databases. It uses the database/sql package, and should work with any
|
||||
// compliant database/sql driver.
|
||||
//
|
||||
// Source code and project home:
|
||||
// https://github.com/go-gorp/gorp
|
||||
|
||||
package gorp
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A nullable Time value
|
||||
type NullTime struct {
|
||||
Time time.Time
|
||||
Valid bool // Valid is true if Time is not NULL
|
||||
}
|
||||
|
||||
// Scan implements the Scanner interface.
|
||||
func (nt *NullTime) Scan(value interface{}) error {
|
||||
switch t := value.(type) {
|
||||
case time.Time:
|
||||
nt.Time, nt.Valid = t, true
|
||||
case []byte:
|
||||
nt.Valid = false
|
||||
for _, dtfmt := range []string{
|
||||
"2006-01-02 15:04:05.999999999",
|
||||
"2006-01-02T15:04:05.999999999",
|
||||
"2006-01-02 15:04:05",
|
||||
"2006-01-02T15:04:05",
|
||||
"2006-01-02 15:04",
|
||||
"2006-01-02T15:04",
|
||||
"2006-01-02",
|
||||
"2006-01-02 15:04:05-07:00",
|
||||
} {
|
||||
var err error
|
||||
if nt.Time, err = time.Parse(dtfmt, string(t)); err == nil {
|
||||
nt.Valid = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Value implements the driver Valuer interface.
|
||||
func (nt NullTime) Value() (driver.Value, error) {
|
||||
if !nt.Valid {
|
||||
return nil, nil
|
||||
}
|
||||
return nt.Time, nil
|
||||
}
|
||||
351
Godeps/_workspace/src/github.com/go-gorp/gorp/select.go
сгенерированный
поставляемый
Обычный файл
351
Godeps/_workspace/src/github.com/go-gorp/gorp/select.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,351 @@
|
||||
// Copyright 2012 James Cooper. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package gorp provides a simple way to marshal Go structs to and from
|
||||
// SQL databases. It uses the database/sql package, and should work with any
|
||||
// compliant database/sql driver.
|
||||
//
|
||||
// Source code and project home:
|
||||
// https://github.com/go-gorp/gorp
|
||||
|
||||
package gorp
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
// SelectInt executes the given query, which should be a SELECT statement for a single
|
||||
// integer column, and returns the value of the first row returned. If no rows are
|
||||
// found, zero is returned.
|
||||
func SelectInt(e SqlExecutor, query string, args ...interface{}) (int64, error) {
|
||||
var h int64
|
||||
err := selectVal(e, &h, query, args...)
|
||||
if err != nil && err != sql.ErrNoRows {
|
||||
return 0, err
|
||||
}
|
||||
return h, nil
|
||||
}
|
||||
|
||||
// SelectNullInt executes the given query, which should be a SELECT statement for a single
|
||||
// integer column, and returns the value of the first row returned. If no rows are
|
||||
// found, the empty sql.NullInt64 value is returned.
|
||||
func SelectNullInt(e SqlExecutor, query string, args ...interface{}) (sql.NullInt64, error) {
|
||||
var h sql.NullInt64
|
||||
err := selectVal(e, &h, query, args...)
|
||||
if err != nil && err != sql.ErrNoRows {
|
||||
return h, err
|
||||
}
|
||||
return h, nil
|
||||
}
|
||||
|
||||
// SelectFloat executes the given query, which should be a SELECT statement for a single
|
||||
// float column, and returns the value of the first row returned. If no rows are
|
||||
// found, zero is returned.
|
||||
func SelectFloat(e SqlExecutor, query string, args ...interface{}) (float64, error) {
|
||||
var h float64
|
||||
err := selectVal(e, &h, query, args...)
|
||||
if err != nil && err != sql.ErrNoRows {
|
||||
return 0, err
|
||||
}
|
||||
return h, nil
|
||||
}
|
||||
|
||||
// SelectNullFloat executes the given query, which should be a SELECT statement for a single
|
||||
// float column, and returns the value of the first row returned. If no rows are
|
||||
// found, the empty sql.NullInt64 value is returned.
|
||||
func SelectNullFloat(e SqlExecutor, query string, args ...interface{}) (sql.NullFloat64, error) {
|
||||
var h sql.NullFloat64
|
||||
err := selectVal(e, &h, query, args...)
|
||||
if err != nil && err != sql.ErrNoRows {
|
||||
return h, err
|
||||
}
|
||||
return h, nil
|
||||
}
|
||||
|
||||
// SelectStr executes the given query, which should be a SELECT statement for a single
|
||||
// char/varchar column, and returns the value of the first row returned. If no rows are
|
||||
// found, an empty string is returned.
|
||||
func SelectStr(e SqlExecutor, query string, args ...interface{}) (string, error) {
|
||||
var h string
|
||||
err := selectVal(e, &h, query, args...)
|
||||
if err != nil && err != sql.ErrNoRows {
|
||||
return "", err
|
||||
}
|
||||
return h, nil
|
||||
}
|
||||
|
||||
// SelectNullStr executes the given query, which should be a SELECT
|
||||
// statement for a single char/varchar column, and returns the value
|
||||
// of the first row returned. If no rows are found, the empty
|
||||
// sql.NullString is returned.
|
||||
func SelectNullStr(e SqlExecutor, query string, args ...interface{}) (sql.NullString, error) {
|
||||
var h sql.NullString
|
||||
err := selectVal(e, &h, query, args...)
|
||||
if err != nil && err != sql.ErrNoRows {
|
||||
return h, err
|
||||
}
|
||||
return h, nil
|
||||
}
|
||||
|
||||
// SelectOne executes the given query (which should be a SELECT statement)
|
||||
// and binds the result to holder, which must be a pointer.
|
||||
//
|
||||
// If no row is found, an error (sql.ErrNoRows specifically) will be returned
|
||||
//
|
||||
// If more than one row is found, an error will be returned.
|
||||
//
|
||||
func SelectOne(m *DbMap, e SqlExecutor, holder interface{}, query string, args ...interface{}) error {
|
||||
t := reflect.TypeOf(holder)
|
||||
if t.Kind() == reflect.Ptr {
|
||||
t = t.Elem()
|
||||
} else {
|
||||
return fmt.Errorf("gorp: SelectOne holder must be a pointer, but got: %t", holder)
|
||||
}
|
||||
|
||||
// Handle pointer to pointer
|
||||
isptr := false
|
||||
if t.Kind() == reflect.Ptr {
|
||||
isptr = true
|
||||
t = t.Elem()
|
||||
}
|
||||
|
||||
if t.Kind() == reflect.Struct {
|
||||
var nonFatalErr error
|
||||
|
||||
list, err := hookedselect(m, e, holder, query, args...)
|
||||
if err != nil {
|
||||
if !NonFatalError(err) { // FIXME: double negative, rename NonFatalError to FatalError
|
||||
return err
|
||||
}
|
||||
nonFatalErr = err
|
||||
}
|
||||
|
||||
dest := reflect.ValueOf(holder)
|
||||
if isptr {
|
||||
dest = dest.Elem()
|
||||
}
|
||||
|
||||
if list != nil && len(list) > 0 { // FIXME: invert if/else
|
||||
// check for multiple rows
|
||||
if len(list) > 1 {
|
||||
return fmt.Errorf("gorp: multiple rows returned for: %s - %v", query, args)
|
||||
}
|
||||
|
||||
// Initialize if nil
|
||||
if dest.IsNil() {
|
||||
dest.Set(reflect.New(t))
|
||||
}
|
||||
|
||||
// only one row found
|
||||
src := reflect.ValueOf(list[0])
|
||||
dest.Elem().Set(src.Elem())
|
||||
} else {
|
||||
// No rows found, return a proper error.
|
||||
return sql.ErrNoRows
|
||||
}
|
||||
|
||||
return nonFatalErr
|
||||
}
|
||||
|
||||
return selectVal(e, holder, query, args...)
|
||||
}
|
||||
|
||||
func selectVal(e SqlExecutor, holder interface{}, query string, args ...interface{}) error {
|
||||
if len(args) == 1 {
|
||||
switch m := e.(type) {
|
||||
case *DbMap:
|
||||
query, args = maybeExpandNamedQuery(m, query, args)
|
||||
case *Transaction:
|
||||
query, args = maybeExpandNamedQuery(m.dbmap, query, args)
|
||||
}
|
||||
}
|
||||
rows, err := e.query(query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
if !rows.Next() {
|
||||
return sql.ErrNoRows
|
||||
}
|
||||
|
||||
return rows.Scan(holder)
|
||||
}
|
||||
|
||||
func hookedselect(m *DbMap, exec SqlExecutor, i interface{}, query string,
|
||||
args ...interface{}) ([]interface{}, error) {
|
||||
|
||||
var nonFatalErr error
|
||||
|
||||
list, err := rawselect(m, exec, i, query, args...)
|
||||
if err != nil {
|
||||
if !NonFatalError(err) {
|
||||
return nil, err
|
||||
}
|
||||
nonFatalErr = err
|
||||
}
|
||||
|
||||
// Determine where the results are: written to i, or returned in list
|
||||
if t, _ := toSliceType(i); t == nil {
|
||||
for _, v := range list {
|
||||
if v, ok := v.(HasPostGet); ok {
|
||||
err := v.PostGet(exec)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
resultsValue := reflect.Indirect(reflect.ValueOf(i))
|
||||
for i := 0; i < resultsValue.Len(); i++ {
|
||||
if v, ok := resultsValue.Index(i).Interface().(HasPostGet); ok {
|
||||
err := v.PostGet(exec)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return list, nonFatalErr
|
||||
}
|
||||
|
||||
func rawselect(m *DbMap, exec SqlExecutor, i interface{}, query string,
|
||||
args ...interface{}) ([]interface{}, error) {
|
||||
var (
|
||||
appendToSlice = false // Write results to i directly?
|
||||
intoStruct = true // Selecting into a struct?
|
||||
pointerElements = true // Are the slice elements pointers (vs values)?
|
||||
)
|
||||
|
||||
var nonFatalErr error
|
||||
|
||||
// get type for i, verifying it's a supported destination
|
||||
t, err := toType(i)
|
||||
if err != nil {
|
||||
var err2 error
|
||||
if t, err2 = toSliceType(i); t == nil {
|
||||
if err2 != nil {
|
||||
return nil, err2
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
pointerElements = t.Kind() == reflect.Ptr
|
||||
if pointerElements {
|
||||
t = t.Elem()
|
||||
}
|
||||
appendToSlice = true
|
||||
intoStruct = t.Kind() == reflect.Struct
|
||||
}
|
||||
|
||||
// If the caller supplied a single struct/map argument, assume a "named
|
||||
// parameter" query. Extract the named arguments from the struct/map, create
|
||||
// the flat arg slice, and rewrite the query to use the dialect's placeholder.
|
||||
if len(args) == 1 {
|
||||
query, args = maybeExpandNamedQuery(m, query, args)
|
||||
}
|
||||
|
||||
// Run the query
|
||||
rows, err := exec.query(query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
// Fetch the column names as returned from db
|
||||
cols, err := rows.Columns()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !intoStruct && len(cols) > 1 {
|
||||
return nil, fmt.Errorf("gorp: select into non-struct slice requires 1 column, got %d", len(cols))
|
||||
}
|
||||
|
||||
var colToFieldIndex [][]int
|
||||
if intoStruct {
|
||||
colToFieldIndex, err = columnToFieldIndex(m, t, cols)
|
||||
if err != nil {
|
||||
if !NonFatalError(err) {
|
||||
return nil, err
|
||||
}
|
||||
nonFatalErr = err
|
||||
}
|
||||
}
|
||||
|
||||
conv := m.TypeConverter
|
||||
|
||||
// Add results to one of these two slices.
|
||||
var (
|
||||
list = make([]interface{}, 0)
|
||||
sliceValue = reflect.Indirect(reflect.ValueOf(i))
|
||||
)
|
||||
|
||||
for {
|
||||
if !rows.Next() {
|
||||
// if error occured return rawselect
|
||||
if rows.Err() != nil {
|
||||
return nil, rows.Err()
|
||||
}
|
||||
// time to exit from outer "for" loop
|
||||
break
|
||||
}
|
||||
v := reflect.New(t)
|
||||
dest := make([]interface{}, len(cols))
|
||||
|
||||
custScan := make([]CustomScanner, 0)
|
||||
|
||||
for x := range cols {
|
||||
f := v.Elem()
|
||||
if intoStruct {
|
||||
index := colToFieldIndex[x]
|
||||
if index == nil {
|
||||
// this field is not present in the struct, so create a dummy
|
||||
// value for rows.Scan to scan into
|
||||
var dummy dummyField
|
||||
dest[x] = &dummy
|
||||
continue
|
||||
}
|
||||
f = f.FieldByIndex(index)
|
||||
}
|
||||
target := f.Addr().Interface()
|
||||
if conv != nil {
|
||||
scanner, ok := conv.FromDb(target)
|
||||
if ok {
|
||||
target = scanner.Holder
|
||||
custScan = append(custScan, scanner)
|
||||
}
|
||||
}
|
||||
dest[x] = target
|
||||
}
|
||||
|
||||
err = rows.Scan(dest...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, c := range custScan {
|
||||
err = c.Bind()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if appendToSlice {
|
||||
if !pointerElements {
|
||||
v = v.Elem()
|
||||
}
|
||||
sliceValue.Set(reflect.Append(sliceValue, v))
|
||||
} else {
|
||||
list = append(list, v.Interface())
|
||||
}
|
||||
}
|
||||
|
||||
if appendToSlice && sliceValue.IsNil() {
|
||||
sliceValue.Set(reflect.MakeSlice(sliceValue.Type(), 0, 0))
|
||||
}
|
||||
|
||||
return list, nonFatalErr
|
||||
}
|
||||
247
Godeps/_workspace/src/github.com/go-gorp/gorp/table.go
сгенерированный
поставляемый
Обычный файл
247
Godeps/_workspace/src/github.com/go-gorp/gorp/table.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,247 @@
|
||||
// Copyright 2012 James Cooper. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package gorp provides a simple way to marshal Go structs to and from
|
||||
// SQL databases. It uses the database/sql package, and should work with any
|
||||
// compliant database/sql driver.
|
||||
//
|
||||
// Source code and project home:
|
||||
// https://github.com/go-gorp/gorp
|
||||
|
||||
package gorp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// TableMap represents a mapping between a Go struct and a database table
|
||||
// Use dbmap.AddTable() or dbmap.AddTableWithName() to create these
|
||||
type TableMap struct {
|
||||
// Name of database table.
|
||||
TableName string
|
||||
SchemaName string
|
||||
gotype reflect.Type
|
||||
Columns []*ColumnMap
|
||||
keys []*ColumnMap
|
||||
indexes []*IndexMap
|
||||
uniqueTogether [][]string
|
||||
version *ColumnMap
|
||||
insertPlan bindPlan
|
||||
updatePlan bindPlan
|
||||
deletePlan bindPlan
|
||||
getPlan bindPlan
|
||||
dbmap *DbMap
|
||||
}
|
||||
|
||||
// ResetSql removes cached insert/update/select/delete SQL strings
|
||||
// associated with this TableMap. Call this if you've modified
|
||||
// any column names or the table name itself.
|
||||
func (t *TableMap) ResetSql() {
|
||||
t.insertPlan = bindPlan{}
|
||||
t.updatePlan = bindPlan{}
|
||||
t.deletePlan = bindPlan{}
|
||||
t.getPlan = bindPlan{}
|
||||
}
|
||||
|
||||
// SetKeys lets you specify the fields on a struct that map to primary
|
||||
// key columns on the table. If isAutoIncr is set, result.LastInsertId()
|
||||
// will be used after INSERT to bind the generated id to the Go struct.
|
||||
//
|
||||
// Automatically calls ResetSql() to ensure SQL statements are regenerated.
|
||||
//
|
||||
// Panics if isAutoIncr is true, and fieldNames length != 1
|
||||
//
|
||||
func (t *TableMap) SetKeys(isAutoIncr bool, fieldNames ...string) *TableMap {
|
||||
if isAutoIncr && len(fieldNames) != 1 {
|
||||
panic(fmt.Sprintf(
|
||||
"gorp: SetKeys: fieldNames length must be 1 if key is auto-increment. (Saw %v fieldNames)",
|
||||
len(fieldNames)))
|
||||
}
|
||||
t.keys = make([]*ColumnMap, 0)
|
||||
for _, name := range fieldNames {
|
||||
colmap := t.ColMap(name)
|
||||
colmap.isPK = true
|
||||
colmap.isAutoIncr = isAutoIncr
|
||||
t.keys = append(t.keys, colmap)
|
||||
}
|
||||
t.ResetSql()
|
||||
|
||||
return t
|
||||
}
|
||||
|
||||
// SetUniqueTogether lets you specify uniqueness constraints across multiple
|
||||
// columns on the table. Each call adds an additional constraint for the
|
||||
// specified columns.
|
||||
//
|
||||
// Automatically calls ResetSql() to ensure SQL statements are regenerated.
|
||||
//
|
||||
// Panics if fieldNames length < 2.
|
||||
//
|
||||
func (t *TableMap) SetUniqueTogether(fieldNames ...string) *TableMap {
|
||||
if len(fieldNames) < 2 {
|
||||
panic(fmt.Sprintf(
|
||||
"gorp: SetUniqueTogether: must provide at least two fieldNames to set uniqueness constraint."))
|
||||
}
|
||||
|
||||
columns := make([]string, 0)
|
||||
for _, name := range fieldNames {
|
||||
columns = append(columns, name)
|
||||
}
|
||||
t.uniqueTogether = append(t.uniqueTogether, columns)
|
||||
t.ResetSql()
|
||||
|
||||
return t
|
||||
}
|
||||
|
||||
// ColMap returns the ColumnMap pointer matching the given struct field
|
||||
// name. It panics if the struct does not contain a field matching this
|
||||
// name.
|
||||
func (t *TableMap) ColMap(field string) *ColumnMap {
|
||||
col := colMapOrNil(t, field)
|
||||
if col == nil {
|
||||
e := fmt.Sprintf("No ColumnMap in table %s type %s with field %s",
|
||||
t.TableName, t.gotype.Name(), field)
|
||||
|
||||
panic(e)
|
||||
}
|
||||
return col
|
||||
}
|
||||
|
||||
func colMapOrNil(t *TableMap, field string) *ColumnMap {
|
||||
for _, col := range t.Columns {
|
||||
if col.fieldName == field || col.ColumnName == field {
|
||||
return col
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// IdxMap returns the IndexMap pointer matching the given index name.
|
||||
func (t *TableMap) IdxMap(field string) *IndexMap {
|
||||
for _, idx := range t.indexes {
|
||||
if idx.IndexName == field {
|
||||
return idx
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AddIndex registers the index with gorp for specified table with given parameters.
|
||||
// This operation is idempotent. If index is already mapped, the
|
||||
// existing *IndexMap is returned
|
||||
// Function will panic if one of the given for index columns does not exists
|
||||
//
|
||||
// Automatically calls ResetSql() to ensure SQL statements are regenerated.
|
||||
//
|
||||
func (t *TableMap) AddIndex(name string, idxtype string, columns []string) *IndexMap {
|
||||
// check if we have a index with this name already
|
||||
for _, idx := range t.indexes {
|
||||
if idx.IndexName == name {
|
||||
return idx
|
||||
}
|
||||
}
|
||||
for _, icol := range columns {
|
||||
if res := t.ColMap(icol); res == nil {
|
||||
e := fmt.Sprintf("No ColumnName in table %s to create index on", t.TableName)
|
||||
panic(e)
|
||||
}
|
||||
}
|
||||
|
||||
idx := &IndexMap{IndexName: name, Unique: false, IndexType: idxtype, columns: columns}
|
||||
t.indexes = append(t.indexes, idx)
|
||||
t.ResetSql()
|
||||
return idx
|
||||
}
|
||||
|
||||
// SetVersionCol sets the column to use as the Version field. By default
|
||||
// the "Version" field is used. Returns the column found, or panics
|
||||
// if the struct does not contain a field matching this name.
|
||||
//
|
||||
// Automatically calls ResetSql() to ensure SQL statements are regenerated.
|
||||
func (t *TableMap) SetVersionCol(field string) *ColumnMap {
|
||||
c := t.ColMap(field)
|
||||
t.version = c
|
||||
t.ResetSql()
|
||||
return c
|
||||
}
|
||||
|
||||
// SqlForCreateTable gets a sequence of SQL commands that will create
|
||||
// the specified table and any associated schema
|
||||
func (t *TableMap) SqlForCreate(ifNotExists bool) string {
|
||||
s := bytes.Buffer{}
|
||||
dialect := t.dbmap.Dialect
|
||||
|
||||
if strings.TrimSpace(t.SchemaName) != "" {
|
||||
schemaCreate := "create schema"
|
||||
if ifNotExists {
|
||||
s.WriteString(dialect.IfSchemaNotExists(schemaCreate, t.SchemaName))
|
||||
} else {
|
||||
s.WriteString(schemaCreate)
|
||||
}
|
||||
s.WriteString(fmt.Sprintf(" %s;", t.SchemaName))
|
||||
}
|
||||
|
||||
tableCreate := "create table"
|
||||
if ifNotExists {
|
||||
s.WriteString(dialect.IfTableNotExists(tableCreate, t.SchemaName, t.TableName))
|
||||
} else {
|
||||
s.WriteString(tableCreate)
|
||||
}
|
||||
s.WriteString(fmt.Sprintf(" %s (", dialect.QuotedTableForQuery(t.SchemaName, t.TableName)))
|
||||
|
||||
x := 0
|
||||
for _, col := range t.Columns {
|
||||
if !col.Transient {
|
||||
if x > 0 {
|
||||
s.WriteString(", ")
|
||||
}
|
||||
stype := dialect.ToSqlType(col.gotype, col.MaxSize, col.isAutoIncr)
|
||||
s.WriteString(fmt.Sprintf("%s %s", dialect.QuoteField(col.ColumnName), stype))
|
||||
|
||||
if col.isPK || col.isNotNull {
|
||||
s.WriteString(" not null")
|
||||
}
|
||||
if col.isPK && len(t.keys) == 1 {
|
||||
s.WriteString(" primary key")
|
||||
}
|
||||
if col.Unique {
|
||||
s.WriteString(" unique")
|
||||
}
|
||||
if col.isAutoIncr {
|
||||
s.WriteString(fmt.Sprintf(" %s", dialect.AutoIncrStr()))
|
||||
}
|
||||
|
||||
x++
|
||||
}
|
||||
}
|
||||
if len(t.keys) > 1 {
|
||||
s.WriteString(", primary key (")
|
||||
for x := range t.keys {
|
||||
if x > 0 {
|
||||
s.WriteString(", ")
|
||||
}
|
||||
s.WriteString(dialect.QuoteField(t.keys[x].ColumnName))
|
||||
}
|
||||
s.WriteString(")")
|
||||
}
|
||||
if len(t.uniqueTogether) > 0 {
|
||||
for _, columns := range t.uniqueTogether {
|
||||
s.WriteString(", unique (")
|
||||
for i, column := range columns {
|
||||
if i > 0 {
|
||||
s.WriteString(", ")
|
||||
}
|
||||
s.WriteString(dialect.QuoteField(column))
|
||||
}
|
||||
s.WriteString(")")
|
||||
}
|
||||
}
|
||||
s.WriteString(") ")
|
||||
s.WriteString(dialect.CreateTableSuffix())
|
||||
s.WriteString(dialect.QuerySuffix())
|
||||
return s.String()
|
||||
}
|
||||
317
Godeps/_workspace/src/github.com/go-gorp/gorp/table_bindings.go
сгенерированный
поставляемый
Обычный файл
317
Godeps/_workspace/src/github.com/go-gorp/gorp/table_bindings.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,317 @@
|
||||
// Copyright 2012 James Cooper. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package gorp provides a simple way to marshal Go structs to and from
|
||||
// SQL databases. It uses the database/sql package, and should work with any
|
||||
// compliant database/sql driver.
|
||||
//
|
||||
// Source code and project home:
|
||||
// https://github.com/go-gorp/gorp
|
||||
|
||||
package gorp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
// CustomScanner binds a database column value to a Go type
|
||||
type CustomScanner struct {
|
||||
// After a row is scanned, Holder will contain the value from the database column.
|
||||
// Initialize the CustomScanner with the concrete Go type you wish the database
|
||||
// driver to scan the raw column into.
|
||||
Holder interface{}
|
||||
// Target typically holds a pointer to the target struct field to bind the Holder
|
||||
// value to.
|
||||
Target interface{}
|
||||
// Binder is a custom function that converts the holder value to the target type
|
||||
// and sets target accordingly. This function should return error if a problem
|
||||
// occurs converting the holder to the target.
|
||||
Binder func(holder interface{}, target interface{}) error
|
||||
}
|
||||
|
||||
// Used to filter columns when selectively updating
|
||||
type ColumnFilter func(*ColumnMap) bool
|
||||
|
||||
func acceptAllFilter(col *ColumnMap) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// Bind is called automatically by gorp after Scan()
|
||||
func (me CustomScanner) Bind() error {
|
||||
return me.Binder(me.Holder, me.Target)
|
||||
}
|
||||
|
||||
type bindPlan struct {
|
||||
query string
|
||||
argFields []string
|
||||
keyFields []string
|
||||
versField string
|
||||
autoIncrIdx int
|
||||
autoIncrFieldName string
|
||||
}
|
||||
|
||||
func (plan bindPlan) createBindInstance(elem reflect.Value, conv TypeConverter) (bindInstance, error) {
|
||||
bi := bindInstance{query: plan.query, autoIncrIdx: plan.autoIncrIdx, autoIncrFieldName: plan.autoIncrFieldName, versField: plan.versField}
|
||||
if plan.versField != "" {
|
||||
bi.existingVersion = elem.FieldByName(plan.versField).Int()
|
||||
}
|
||||
|
||||
var err error
|
||||
|
||||
for i := 0; i < len(plan.argFields); i++ {
|
||||
k := plan.argFields[i]
|
||||
if k == versFieldConst {
|
||||
newVer := bi.existingVersion + 1
|
||||
bi.args = append(bi.args, newVer)
|
||||
if bi.existingVersion == 0 {
|
||||
elem.FieldByName(plan.versField).SetInt(int64(newVer))
|
||||
}
|
||||
} else {
|
||||
val := elem.FieldByName(k).Interface()
|
||||
if conv != nil {
|
||||
val, err = conv.ToDb(val)
|
||||
if err != nil {
|
||||
return bindInstance{}, err
|
||||
}
|
||||
}
|
||||
bi.args = append(bi.args, val)
|
||||
}
|
||||
}
|
||||
|
||||
for i := 0; i < len(plan.keyFields); i++ {
|
||||
k := plan.keyFields[i]
|
||||
val := elem.FieldByName(k).Interface()
|
||||
if conv != nil {
|
||||
val, err = conv.ToDb(val)
|
||||
if err != nil {
|
||||
return bindInstance{}, err
|
||||
}
|
||||
}
|
||||
bi.keys = append(bi.keys, val)
|
||||
}
|
||||
|
||||
return bi, nil
|
||||
}
|
||||
|
||||
type bindInstance struct {
|
||||
query string
|
||||
args []interface{}
|
||||
keys []interface{}
|
||||
existingVersion int64
|
||||
versField string
|
||||
autoIncrIdx int
|
||||
autoIncrFieldName string
|
||||
}
|
||||
|
||||
func (t *TableMap) bindInsert(elem reflect.Value) (bindInstance, error) {
|
||||
plan := t.insertPlan
|
||||
if plan.query == "" {
|
||||
plan.autoIncrIdx = -1
|
||||
|
||||
s := bytes.Buffer{}
|
||||
s2 := bytes.Buffer{}
|
||||
s.WriteString(fmt.Sprintf("insert into %s (", t.dbmap.Dialect.QuotedTableForQuery(t.SchemaName, t.TableName)))
|
||||
|
||||
x := 0
|
||||
first := true
|
||||
for y := range t.Columns {
|
||||
col := t.Columns[y]
|
||||
if !(col.isAutoIncr && t.dbmap.Dialect.AutoIncrBindValue() == "") {
|
||||
if !col.Transient {
|
||||
if !first {
|
||||
s.WriteString(",")
|
||||
s2.WriteString(",")
|
||||
}
|
||||
s.WriteString(t.dbmap.Dialect.QuoteField(col.ColumnName))
|
||||
|
||||
if col.isAutoIncr {
|
||||
s2.WriteString(t.dbmap.Dialect.AutoIncrBindValue())
|
||||
plan.autoIncrIdx = y
|
||||
plan.autoIncrFieldName = col.fieldName
|
||||
} else {
|
||||
if col.DefaultValue == "" {
|
||||
s2.WriteString(t.dbmap.Dialect.BindVar(x))
|
||||
if col == t.version {
|
||||
plan.versField = col.fieldName
|
||||
plan.argFields = append(plan.argFields, versFieldConst)
|
||||
} else {
|
||||
plan.argFields = append(plan.argFields, col.fieldName)
|
||||
}
|
||||
x++
|
||||
} else {
|
||||
s2.WriteString(col.DefaultValue)
|
||||
}
|
||||
}
|
||||
first = false
|
||||
}
|
||||
} else {
|
||||
plan.autoIncrIdx = y
|
||||
plan.autoIncrFieldName = col.fieldName
|
||||
}
|
||||
}
|
||||
s.WriteString(") values (")
|
||||
s.WriteString(s2.String())
|
||||
s.WriteString(")")
|
||||
if plan.autoIncrIdx > -1 {
|
||||
s.WriteString(t.dbmap.Dialect.AutoIncrInsertSuffix(t.Columns[plan.autoIncrIdx]))
|
||||
}
|
||||
s.WriteString(t.dbmap.Dialect.QuerySuffix())
|
||||
|
||||
plan.query = s.String()
|
||||
t.insertPlan = plan
|
||||
}
|
||||
|
||||
return plan.createBindInstance(elem, t.dbmap.TypeConverter)
|
||||
}
|
||||
|
||||
func (t *TableMap) bindUpdate(elem reflect.Value, colFilter ColumnFilter) (bindInstance, error) {
|
||||
if colFilter == nil {
|
||||
colFilter = acceptAllFilter
|
||||
}
|
||||
|
||||
plan := t.updatePlan
|
||||
if plan.query == "" {
|
||||
|
||||
s := bytes.Buffer{}
|
||||
s.WriteString(fmt.Sprintf("update %s set ", t.dbmap.Dialect.QuotedTableForQuery(t.SchemaName, t.TableName)))
|
||||
x := 0
|
||||
|
||||
for y := range t.Columns {
|
||||
col := t.Columns[y]
|
||||
if !col.isAutoIncr && !col.Transient && colFilter(col) {
|
||||
if x > 0 {
|
||||
s.WriteString(", ")
|
||||
}
|
||||
s.WriteString(t.dbmap.Dialect.QuoteField(col.ColumnName))
|
||||
s.WriteString("=")
|
||||
s.WriteString(t.dbmap.Dialect.BindVar(x))
|
||||
|
||||
if col == t.version {
|
||||
plan.versField = col.fieldName
|
||||
plan.argFields = append(plan.argFields, versFieldConst)
|
||||
} else {
|
||||
plan.argFields = append(plan.argFields, col.fieldName)
|
||||
}
|
||||
x++
|
||||
}
|
||||
}
|
||||
|
||||
s.WriteString(" where ")
|
||||
for y := range t.keys {
|
||||
col := t.keys[y]
|
||||
if y > 0 {
|
||||
s.WriteString(" and ")
|
||||
}
|
||||
s.WriteString(t.dbmap.Dialect.QuoteField(col.ColumnName))
|
||||
s.WriteString("=")
|
||||
s.WriteString(t.dbmap.Dialect.BindVar(x))
|
||||
|
||||
plan.argFields = append(plan.argFields, col.fieldName)
|
||||
plan.keyFields = append(plan.keyFields, col.fieldName)
|
||||
x++
|
||||
}
|
||||
if plan.versField != "" {
|
||||
s.WriteString(" and ")
|
||||
s.WriteString(t.dbmap.Dialect.QuoteField(t.version.ColumnName))
|
||||
s.WriteString("=")
|
||||
s.WriteString(t.dbmap.Dialect.BindVar(x))
|
||||
plan.argFields = append(plan.argFields, plan.versField)
|
||||
}
|
||||
s.WriteString(t.dbmap.Dialect.QuerySuffix())
|
||||
|
||||
plan.query = s.String()
|
||||
t.updatePlan = plan
|
||||
}
|
||||
|
||||
return plan.createBindInstance(elem, t.dbmap.TypeConverter)
|
||||
}
|
||||
|
||||
func (t *TableMap) bindDelete(elem reflect.Value) (bindInstance, error) {
|
||||
plan := t.deletePlan
|
||||
if plan.query == "" {
|
||||
|
||||
s := bytes.Buffer{}
|
||||
s.WriteString(fmt.Sprintf("delete from %s", t.dbmap.Dialect.QuotedTableForQuery(t.SchemaName, t.TableName)))
|
||||
|
||||
for y := range t.Columns {
|
||||
col := t.Columns[y]
|
||||
if !col.Transient {
|
||||
if col == t.version {
|
||||
plan.versField = col.fieldName
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
s.WriteString(" where ")
|
||||
for x := range t.keys {
|
||||
k := t.keys[x]
|
||||
if x > 0 {
|
||||
s.WriteString(" and ")
|
||||
}
|
||||
s.WriteString(t.dbmap.Dialect.QuoteField(k.ColumnName))
|
||||
s.WriteString("=")
|
||||
s.WriteString(t.dbmap.Dialect.BindVar(x))
|
||||
|
||||
plan.keyFields = append(plan.keyFields, k.fieldName)
|
||||
plan.argFields = append(plan.argFields, k.fieldName)
|
||||
}
|
||||
if plan.versField != "" {
|
||||
s.WriteString(" and ")
|
||||
s.WriteString(t.dbmap.Dialect.QuoteField(t.version.ColumnName))
|
||||
s.WriteString("=")
|
||||
s.WriteString(t.dbmap.Dialect.BindVar(len(plan.argFields)))
|
||||
|
||||
plan.argFields = append(plan.argFields, plan.versField)
|
||||
}
|
||||
s.WriteString(t.dbmap.Dialect.QuerySuffix())
|
||||
|
||||
plan.query = s.String()
|
||||
t.deletePlan = plan
|
||||
}
|
||||
|
||||
return plan.createBindInstance(elem, t.dbmap.TypeConverter)
|
||||
}
|
||||
|
||||
func (t *TableMap) bindGet() bindPlan {
|
||||
plan := t.getPlan
|
||||
if plan.query == "" {
|
||||
|
||||
s := bytes.Buffer{}
|
||||
s.WriteString("select ")
|
||||
|
||||
x := 0
|
||||
for _, col := range t.Columns {
|
||||
if !col.Transient {
|
||||
if x > 0 {
|
||||
s.WriteString(",")
|
||||
}
|
||||
s.WriteString(t.dbmap.Dialect.QuoteField(col.ColumnName))
|
||||
plan.argFields = append(plan.argFields, col.fieldName)
|
||||
x++
|
||||
}
|
||||
}
|
||||
s.WriteString(" from ")
|
||||
s.WriteString(t.dbmap.Dialect.QuotedTableForQuery(t.SchemaName, t.TableName))
|
||||
s.WriteString(" where ")
|
||||
for x := range t.keys {
|
||||
col := t.keys[x]
|
||||
if x > 0 {
|
||||
s.WriteString(" and ")
|
||||
}
|
||||
s.WriteString(t.dbmap.Dialect.QuoteField(col.ColumnName))
|
||||
s.WriteString("=")
|
||||
s.WriteString(t.dbmap.Dialect.BindVar(x))
|
||||
|
||||
plan.keyFields = append(plan.keyFields, col.fieldName)
|
||||
}
|
||||
s.WriteString(t.dbmap.Dialect.QuerySuffix())
|
||||
|
||||
plan.query = s.String()
|
||||
t.getPlan = plan
|
||||
}
|
||||
|
||||
return plan
|
||||
}
|
||||
28
Godeps/_workspace/src/github.com/go-gorp/gorp/test_all.sh
сгенерированный
поставляемый
28
Godeps/_workspace/src/github.com/go-gorp/gorp/test_all.sh
сгенерированный
поставляемый
@@ -1,22 +1,38 @@
|
||||
#!/bin/sh
|
||||
#!/bin/bash -e
|
||||
|
||||
# on macs, you may need to:
|
||||
# export GOBUILDFLAG=-ldflags -linkmode=external
|
||||
|
||||
set -e
|
||||
coveralls_testflags="-v -covermode=count -coverprofile=coverage.out"
|
||||
|
||||
echo "Testing against mysql"
|
||||
export GORP_TEST_DSN=gorptest/gorptest/gorptest
|
||||
export GORP_TEST_DIALECT=mysql
|
||||
go test $GOBUILDFLAG .
|
||||
go test $coveralls_testflags $GOBUILDFLAG $@ .
|
||||
|
||||
echo "Testing against gomysql"
|
||||
export GORP_TEST_DSN=gorptest:gorptest@/gorptest
|
||||
export GORP_TEST_DIALECT=gomysql
|
||||
go test $GOBUILDFLAG .
|
||||
go test $coveralls_testflags $GOBUILDFLAG $@ .
|
||||
|
||||
echo "Testing against postgres"
|
||||
export GORP_TEST_DSN="user=gorptest password=gorptest dbname=gorptest sslmode=disable"
|
||||
export GORP_TEST_DIALECT=postgres
|
||||
go test $GOBUILDFLAG .
|
||||
go test $coveralls_testflags $GOBUILDFLAG $@ .
|
||||
|
||||
echo "Testing against sqlite"
|
||||
export GORP_TEST_DSN=/tmp/gorptest.bin
|
||||
export GORP_TEST_DIALECT=sqlite
|
||||
go test $GOBUILDFLAG .
|
||||
go test $coveralls_testflags $GOBUILDFLAG $@ .
|
||||
rm -f /tmp/gorptest.bin
|
||||
|
||||
case $(go version) in
|
||||
*go1.4*)
|
||||
if [ "$(type -p goveralls)" != "" ]; then
|
||||
goveralls -covermode=count -coverprofile=coverage.out -service=travis-ci
|
||||
elif [ -x $HOME/gopath/bin/goveralls ]; then
|
||||
$HOME/gopath/bin/goveralls -covermode=count -coverprofile=coverage.out -service=travis-ci
|
||||
fi
|
||||
;;
|
||||
*) ;;
|
||||
esac
|
||||
|
||||
193
Godeps/_workspace/src/github.com/go-gorp/gorp/transaction.go
сгенерированный
поставляемый
Обычный файл
193
Godeps/_workspace/src/github.com/go-gorp/gorp/transaction.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,193 @@
|
||||
// Copyright 2012 James Cooper. All rights reserved.
|
||||
// Use of this source code is governed by a MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package gorp provides a simple way to marshal Go structs to and from
|
||||
// SQL databases. It uses the database/sql package, and should work with any
|
||||
// compliant database/sql driver.
|
||||
//
|
||||
// Source code and project home:
|
||||
// https://github.com/go-gorp/gorp
|
||||
|
||||
package gorp
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Transaction represents a database transaction.
|
||||
// Insert/Update/Delete/Get/Exec operations will be run in the context
|
||||
// of that transaction. Transactions should be terminated with
|
||||
// a call to Commit() or Rollback()
|
||||
type Transaction struct {
|
||||
dbmap *DbMap
|
||||
tx *sql.Tx
|
||||
closed bool
|
||||
}
|
||||
|
||||
// Insert has the same behavior as DbMap.Insert(), but runs in a transaction.
|
||||
func (t *Transaction) Insert(list ...interface{}) error {
|
||||
return insert(t.dbmap, t, list...)
|
||||
}
|
||||
|
||||
// Update had the same behavior as DbMap.Update(), but runs in a transaction.
|
||||
func (t *Transaction) Update(list ...interface{}) (int64, error) {
|
||||
return update(t.dbmap, t, nil, list...)
|
||||
}
|
||||
|
||||
// UpdateColumns had the same behavior as DbMap.UpdateColumns(), but runs in a transaction.
|
||||
func (t *Transaction) UpdateColumns(filter ColumnFilter, list ...interface{}) (int64, error) {
|
||||
return update(t.dbmap, t, filter, list...)
|
||||
}
|
||||
|
||||
// Delete has the same behavior as DbMap.Delete(), but runs in a transaction.
|
||||
func (t *Transaction) Delete(list ...interface{}) (int64, error) {
|
||||
return delete(t.dbmap, t, list...)
|
||||
}
|
||||
|
||||
// Get has the same behavior as DbMap.Get(), but runs in a transaction.
|
||||
func (t *Transaction) Get(i interface{}, keys ...interface{}) (interface{}, error) {
|
||||
return get(t.dbmap, t, i, keys...)
|
||||
}
|
||||
|
||||
// Select has the same behavior as DbMap.Select(), but runs in a transaction.
|
||||
func (t *Transaction) Select(i interface{}, query string, args ...interface{}) ([]interface{}, error) {
|
||||
return hookedselect(t.dbmap, t, i, query, args...)
|
||||
}
|
||||
|
||||
// Exec has the same behavior as DbMap.Exec(), but runs in a transaction.
|
||||
func (t *Transaction) Exec(query string, args ...interface{}) (sql.Result, error) {
|
||||
if t.dbmap.logger != nil {
|
||||
now := time.Now()
|
||||
defer t.dbmap.trace(now, query, args...)
|
||||
}
|
||||
return exec(t, query, args...)
|
||||
}
|
||||
|
||||
// SelectInt is a convenience wrapper around the gorp.SelectInt function.
|
||||
func (t *Transaction) SelectInt(query string, args ...interface{}) (int64, error) {
|
||||
return SelectInt(t, query, args...)
|
||||
}
|
||||
|
||||
// SelectNullInt is a convenience wrapper around the gorp.SelectNullInt function.
|
||||
func (t *Transaction) SelectNullInt(query string, args ...interface{}) (sql.NullInt64, error) {
|
||||
return SelectNullInt(t, query, args...)
|
||||
}
|
||||
|
||||
// SelectFloat is a convenience wrapper around the gorp.SelectFloat function.
|
||||
func (t *Transaction) SelectFloat(query string, args ...interface{}) (float64, error) {
|
||||
return SelectFloat(t, query, args...)
|
||||
}
|
||||
|
||||
// SelectNullFloat is a convenience wrapper around the gorp.SelectNullFloat function.
|
||||
func (t *Transaction) SelectNullFloat(query string, args ...interface{}) (sql.NullFloat64, error) {
|
||||
return SelectNullFloat(t, query, args...)
|
||||
}
|
||||
|
||||
// SelectStr is a convenience wrapper around the gorp.SelectStr function.
|
||||
func (t *Transaction) SelectStr(query string, args ...interface{}) (string, error) {
|
||||
return SelectStr(t, query, args...)
|
||||
}
|
||||
|
||||
// SelectNullStr is a convenience wrapper around the gorp.SelectNullStr function.
|
||||
func (t *Transaction) SelectNullStr(query string, args ...interface{}) (sql.NullString, error) {
|
||||
return SelectNullStr(t, query, args...)
|
||||
}
|
||||
|
||||
// SelectOne is a convenience wrapper around the gorp.SelectOne function.
|
||||
func (t *Transaction) SelectOne(holder interface{}, query string, args ...interface{}) error {
|
||||
return SelectOne(t.dbmap, t, holder, query, args...)
|
||||
}
|
||||
|
||||
// Commit commits the underlying database transaction.
|
||||
func (t *Transaction) Commit() error {
|
||||
if !t.closed {
|
||||
t.closed = true
|
||||
if t.dbmap.logger != nil {
|
||||
now := time.Now()
|
||||
defer t.dbmap.trace(now, "commit;")
|
||||
}
|
||||
return t.tx.Commit()
|
||||
}
|
||||
|
||||
return sql.ErrTxDone
|
||||
}
|
||||
|
||||
// Rollback rolls back the underlying database transaction.
|
||||
func (t *Transaction) Rollback() error {
|
||||
if !t.closed {
|
||||
t.closed = true
|
||||
if t.dbmap.logger != nil {
|
||||
now := time.Now()
|
||||
defer t.dbmap.trace(now, "rollback;")
|
||||
}
|
||||
return t.tx.Rollback()
|
||||
}
|
||||
|
||||
return sql.ErrTxDone
|
||||
}
|
||||
|
||||
// Savepoint creates a savepoint with the given name. The name is interpolated
|
||||
// directly into the SQL SAVEPOINT statement, so you must sanitize it if it is
|
||||
// derived from user input.
|
||||
func (t *Transaction) Savepoint(name string) error {
|
||||
query := "savepoint " + t.dbmap.Dialect.QuoteField(name)
|
||||
if t.dbmap.logger != nil {
|
||||
now := time.Now()
|
||||
defer t.dbmap.trace(now, query, nil)
|
||||
}
|
||||
_, err := t.tx.Exec(query)
|
||||
return err
|
||||
}
|
||||
|
||||
// RollbackToSavepoint rolls back to the savepoint with the given name. The
|
||||
// name is interpolated directly into the SQL SAVEPOINT statement, so you must
|
||||
// sanitize it if it is derived from user input.
|
||||
func (t *Transaction) RollbackToSavepoint(savepoint string) error {
|
||||
query := "rollback to savepoint " + t.dbmap.Dialect.QuoteField(savepoint)
|
||||
if t.dbmap.logger != nil {
|
||||
now := time.Now()
|
||||
defer t.dbmap.trace(now, query, nil)
|
||||
}
|
||||
_, err := t.tx.Exec(query)
|
||||
return err
|
||||
}
|
||||
|
||||
// ReleaseSavepint releases the savepoint with the given name. The name is
|
||||
// interpolated directly into the SQL SAVEPOINT statement, so you must sanitize
|
||||
// it if it is derived from user input.
|
||||
func (t *Transaction) ReleaseSavepoint(savepoint string) error {
|
||||
query := "release savepoint " + t.dbmap.Dialect.QuoteField(savepoint)
|
||||
if t.dbmap.logger != nil {
|
||||
now := time.Now()
|
||||
defer t.dbmap.trace(now, query, nil)
|
||||
}
|
||||
_, err := t.tx.Exec(query)
|
||||
return err
|
||||
}
|
||||
|
||||
// Prepare has the same behavior as DbMap.Prepare(), but runs in a transaction.
|
||||
func (t *Transaction) Prepare(query string) (*sql.Stmt, error) {
|
||||
if t.dbmap.logger != nil {
|
||||
now := time.Now()
|
||||
defer t.dbmap.trace(now, query, nil)
|
||||
}
|
||||
return t.tx.Prepare(query)
|
||||
}
|
||||
|
||||
func (t *Transaction) queryRow(query string, args ...interface{}) *sql.Row {
|
||||
if t.dbmap.logger != nil {
|
||||
now := time.Now()
|
||||
defer t.dbmap.trace(now, query, args...)
|
||||
}
|
||||
return t.tx.QueryRow(query, args...)
|
||||
}
|
||||
|
||||
func (t *Transaction) query(query string, args ...interface{}) (*sql.Rows, error) {
|
||||
if t.dbmap.logger != nil {
|
||||
now := time.Now()
|
||||
defer t.dbmap.trace(now, query, args...)
|
||||
}
|
||||
return t.tx.Query(query, args...)
|
||||
}
|
||||
4
Godeps/_workspace/src/github.com/go-sql-driver/mysql/AUTHORS
сгенерированный
поставляемый
4
Godeps/_workspace/src/github.com/go-sql-driver/mysql/AUTHORS
сгенерированный
поставляемый
@@ -20,9 +20,11 @@ Frederick Mayle <frederickmayle at gmail.com>
|
||||
Gustavo Kristic <gkristic at gmail.com>
|
||||
Hanno Braun <mail at hannobraun.com>
|
||||
Henri Yandell <flamefew at gmail.com>
|
||||
Hirotaka Yamamoto <ymmt2005 at gmail.com>
|
||||
INADA Naoki <songofacandy at gmail.com>
|
||||
James Harr <james.harr at gmail.com>
|
||||
Jian Zhen <zhenjl at gmail.com>
|
||||
Joshua Prunier <joshua.prunier at gmail.com>
|
||||
Julien Schmidt <go-sql-driver at julienschmidt.com>
|
||||
Kamil Dziedzic <kamil at klecza.pl>
|
||||
Leonardo YongUk Kim <dalinaum at gmail.com>
|
||||
@@ -32,8 +34,10 @@ Michael Woolnough <michael.woolnough at gmail.com>
|
||||
Nicola Peduzzi <thenikso at gmail.com>
|
||||
Runrioter Wung <runrioter at gmail.com>
|
||||
Soroush Pour <me at soroushjp.com>
|
||||
Stan Putrya <root.vagner at gmail.com>
|
||||
Xiaobing Jiang <s7v7nislands at gmail.com>
|
||||
Xiuming Chen <cc at cxm.cc>
|
||||
Julien Lefevre <julien.lefevr at gmail.com>
|
||||
|
||||
# Organizations
|
||||
|
||||
|
||||
14
Godeps/_workspace/src/github.com/go-sql-driver/mysql/README.md
сгенерированный
поставляемый
14
Godeps/_workspace/src/github.com/go-sql-driver/mysql/README.md
сгенерированный
поставляемый
@@ -30,7 +30,7 @@ A MySQL-Driver for Go's [database/sql](http://golang.org/pkg/database/sql) packa
|
||||
## Features
|
||||
* Lightweight and [fast](https://github.com/go-sql-driver/sql-benchmark "golang MySQL-Driver performance")
|
||||
* Native Go implementation. No C-bindings, just pure Go
|
||||
* Connections over TCP/IPv4, TCP/IPv6 or Unix domain sockets
|
||||
* Connections over TCP/IPv4, TCP/IPv6, Unix domain sockets or [custom protocols](http://godoc.org/github.com/go-sql-driver/mysql#DialFunc)
|
||||
* Automatic handling of broken connections
|
||||
* Automatic Connection Pooling *(by database/sql package)*
|
||||
* Supports queries larger than 16MB
|
||||
@@ -123,6 +123,16 @@ Default: false
|
||||
`allowAllFiles=true` disables the file Whitelist for `LOAD DATA LOCAL INFILE` and allows *all* files.
|
||||
[*Might be insecure!*](http://dev.mysql.com/doc/refman/5.7/en/load-data-local.html)
|
||||
|
||||
##### `allowCleartextPasswords`
|
||||
|
||||
```
|
||||
Type: bool
|
||||
Valid Values: true, false
|
||||
Default: false
|
||||
```
|
||||
|
||||
`allowCleartextPasswords=true` allows using the [cleartext client side plugin](http://dev.mysql.com/doc/en/cleartext-authentication-plugin.html) if required by an account, such as one defined with the [PAM authentication plugin](http://dev.mysql.com/doc/en/pam-authentication-plugin.html). Sending passwords in clear text may be a security problem in some configurations. To avoid problems if there is any possibility that the password would be intercepted, clients should connect to MySQL Server using a method that protects the password. Possibilities include [TLS / SSL](#tls), IPsec, or a private network.
|
||||
|
||||
##### `allowOldPasswords`
|
||||
|
||||
```
|
||||
@@ -321,7 +331,7 @@ import "github.com/go-sql-driver/mysql"
|
||||
|
||||
Files must be whitelisted by registering them with `mysql.RegisterLocalFile(filepath)` (recommended) or the Whitelist check must be deactivated by using the DSN parameter `allowAllFiles=true` ([*Might be insecure!*](http://dev.mysql.com/doc/refman/5.7/en/load-data-local.html)).
|
||||
|
||||
To use a `io.Reader` a handler function must be registered with `mysql.RegisterReaderHandler(name, handler)` which returns a `io.Reader` or `io.ReadCloser`. The Reader is available with the filepath `Reader::<name>` then.
|
||||
To use a `io.Reader` a handler function must be registered with `mysql.RegisterReaderHandler(name, handler)` which returns a `io.Reader` or `io.ReadCloser`. The Reader is available with the filepath `Reader::<name>` then. Choose different names for different handlers and `DeregisterReaderHandler` when you don't need it anymore.
|
||||
|
||||
See the [godoc of Go-MySQL-Driver](http://godoc.org/github.com/go-sql-driver/mysql "golang mysql driver documentation") for details.
|
||||
|
||||
|
||||
33
Godeps/_workspace/src/github.com/go-sql-driver/mysql/connection.go
сгенерированный
поставляемый
33
Godeps/_workspace/src/github.com/go-sql-driver/mysql/connection.go
сгенерированный
поставляемый
@@ -34,21 +34,22 @@ type mysqlConn struct {
|
||||
}
|
||||
|
||||
type config struct {
|
||||
user string
|
||||
passwd string
|
||||
net string
|
||||
addr string
|
||||
dbname string
|
||||
params map[string]string
|
||||
loc *time.Location
|
||||
tls *tls.Config
|
||||
timeout time.Duration
|
||||
collation uint8
|
||||
allowAllFiles bool
|
||||
allowOldPasswords bool
|
||||
clientFoundRows bool
|
||||
columnsWithAlias bool
|
||||
interpolateParams bool
|
||||
user string
|
||||
passwd string
|
||||
net string
|
||||
addr string
|
||||
dbname string
|
||||
params map[string]string
|
||||
loc *time.Location
|
||||
tls *tls.Config
|
||||
timeout time.Duration
|
||||
collation uint8
|
||||
allowAllFiles bool
|
||||
allowOldPasswords bool
|
||||
allowCleartextPasswords bool
|
||||
clientFoundRows bool
|
||||
columnsWithAlias bool
|
||||
interpolateParams bool
|
||||
}
|
||||
|
||||
// Handles parameters set in DSN after the connection is established
|
||||
@@ -252,7 +253,7 @@ func (mc *mysqlConn) interpolateParams(query string, args []driver.Value) (strin
|
||||
if v == nil {
|
||||
buf = append(buf, "NULL"...)
|
||||
} else {
|
||||
buf = append(buf, '\'')
|
||||
buf = append(buf, "_binary'"...)
|
||||
if mc.status&statusNoBackslashEscapes == 0 {
|
||||
buf = escapeBytesBackslash(buf, v)
|
||||
} else {
|
||||
|
||||
9
Godeps/_workspace/src/github.com/go-sql-driver/mysql/driver.go
сгенерированный
поставляемый
9
Godeps/_workspace/src/github.com/go-sql-driver/mysql/driver.go
сгенерированный
поставляемый
@@ -107,6 +107,15 @@ func (d MySQLDriver) Open(dsn string) (driver.Conn, error) {
|
||||
mc.Close()
|
||||
return nil, err
|
||||
}
|
||||
} else if mc.cfg != nil && mc.cfg.allowCleartextPasswords && err == ErrCleartextPassword {
|
||||
if err = mc.writeClearAuthPacket(); err != nil {
|
||||
mc.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err = mc.readResultOK(); err != nil {
|
||||
mc.Close()
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
mc.Close()
|
||||
return nil, err
|
||||
|
||||
24
Godeps/_workspace/src/github.com/go-sql-driver/mysql/driver_test.go
сгенерированный
поставляемый
24
Godeps/_workspace/src/github.com/go-sql-driver/mysql/driver_test.go
сгенерированный
поставляемый
@@ -1246,6 +1246,30 @@ func TestCollation(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestColumnsWithAlias(t *testing.T) {
|
||||
runTests(t, dsn+"&columnsWithAlias=true", func(dbt *DBTest) {
|
||||
rows := dbt.mustQuery("SELECT 1 AS A")
|
||||
defer rows.Close()
|
||||
cols, _ := rows.Columns()
|
||||
if len(cols) != 1 {
|
||||
t.Fatalf("expected 1 column, got %d", len(cols))
|
||||
}
|
||||
if cols[0] != "A" {
|
||||
t.Fatalf("expected column name \"A\", got \"%s\"", cols[0])
|
||||
}
|
||||
rows.Close()
|
||||
|
||||
rows = dbt.mustQuery("SELECT * FROM (SELECT 1 AS one) AS A")
|
||||
cols, _ = rows.Columns()
|
||||
if len(cols) != 1 {
|
||||
t.Fatalf("expected 1 column, got %d", len(cols))
|
||||
}
|
||||
if cols[0] != "A.one" {
|
||||
t.Fatalf("expected column name \"A.one\", got \"%s\"", cols[0])
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRawBytesResultExceedsBuffer(t *testing.T) {
|
||||
runTests(t, dsn, func(dbt *DBTest) {
|
||||
// defaultBufSize from buffer.go
|
||||
|
||||
20
Godeps/_workspace/src/github.com/go-sql-driver/mysql/errors.go
сгенерированный
поставляемый
20
Godeps/_workspace/src/github.com/go-sql-driver/mysql/errors.go
сгенерированный
поставляемый
@@ -19,15 +19,17 @@ import (
|
||||
|
||||
// Various errors the driver might return. Can change between driver versions.
|
||||
var (
|
||||
ErrInvalidConn = errors.New("Invalid Connection")
|
||||
ErrMalformPkt = errors.New("Malformed Packet")
|
||||
ErrNoTLS = errors.New("TLS encryption requested but server does not support TLS")
|
||||
ErrOldPassword = errors.New("This server only supports the insecure old password authentication. If you still want to use it, please add 'allowOldPasswords=1' to your DSN. See also https://github.com/go-sql-driver/mysql/wiki/old_passwords")
|
||||
ErrOldProtocol = errors.New("MySQL-Server does not support required Protocol 41+")
|
||||
ErrPktSync = errors.New("Commands out of sync. You can't run this command now")
|
||||
ErrPktSyncMul = errors.New("Commands out of sync. Did you run multiple statements at once?")
|
||||
ErrPktTooLarge = errors.New("Packet for query is too large. You can change this value on the server by adjusting the 'max_allowed_packet' variable.")
|
||||
ErrBusyBuffer = errors.New("Busy buffer")
|
||||
ErrInvalidConn = errors.New("Invalid Connection")
|
||||
ErrMalformPkt = errors.New("Malformed Packet")
|
||||
ErrNoTLS = errors.New("TLS encryption requested but server does not support TLS")
|
||||
ErrOldPassword = errors.New("This user requires old password authentication. If you still want to use it, please add 'allowOldPasswords=1' to your DSN. See also https://github.com/go-sql-driver/mysql/wiki/old_passwords")
|
||||
ErrCleartextPassword = errors.New("This user requires clear text authentication. If you still want to use it, please add 'allowCleartextPasswords=1' to your DSN.")
|
||||
ErrUnknownPlugin = errors.New("The authentication plugin is not supported.")
|
||||
ErrOldProtocol = errors.New("MySQL-Server does not support required Protocol 41+")
|
||||
ErrPktSync = errors.New("Commands out of sync. You can't run this command now")
|
||||
ErrPktSyncMul = errors.New("Commands out of sync. Did you run multiple statements at once?")
|
||||
ErrPktTooLarge = errors.New("Packet for query is too large. You can change this value on the server by adjusting the 'max_allowed_packet' variable.")
|
||||
ErrBusyBuffer = errors.New("Busy buffer")
|
||||
)
|
||||
|
||||
var errLog Logger = log.New(os.Stderr, "[MySQL] ", log.Ldate|log.Ltime|log.Lshortfile)
|
||||
|
||||
32
Godeps/_workspace/src/github.com/go-sql-driver/mysql/infile.go
сгенерированный
поставляемый
32
Godeps/_workspace/src/github.com/go-sql-driver/mysql/infile.go
сгенерированный
поставляемый
@@ -13,11 +13,14 @@ import (
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var (
|
||||
fileRegister map[string]bool
|
||||
readerRegister map[string]func() io.Reader
|
||||
fileRegister map[string]bool
|
||||
fileRegisterLock sync.RWMutex
|
||||
readerRegister map[string]func() io.Reader
|
||||
readerRegisterLock sync.RWMutex
|
||||
)
|
||||
|
||||
// RegisterLocalFile adds the given file to the file whitelist,
|
||||
@@ -32,17 +35,21 @@ var (
|
||||
// ...
|
||||
//
|
||||
func RegisterLocalFile(filePath string) {
|
||||
fileRegisterLock.Lock()
|
||||
// lazy map init
|
||||
if fileRegister == nil {
|
||||
fileRegister = make(map[string]bool)
|
||||
}
|
||||
|
||||
fileRegister[strings.Trim(filePath, `"`)] = true
|
||||
fileRegisterLock.Unlock()
|
||||
}
|
||||
|
||||
// DeregisterLocalFile removes the given filepath from the whitelist.
|
||||
func DeregisterLocalFile(filePath string) {
|
||||
fileRegisterLock.Lock()
|
||||
delete(fileRegister, strings.Trim(filePath, `"`))
|
||||
fileRegisterLock.Unlock()
|
||||
}
|
||||
|
||||
// RegisterReaderHandler registers a handler function which is used
|
||||
@@ -61,18 +68,22 @@ func DeregisterLocalFile(filePath string) {
|
||||
// ...
|
||||
//
|
||||
func RegisterReaderHandler(name string, handler func() io.Reader) {
|
||||
readerRegisterLock.Lock()
|
||||
// lazy map init
|
||||
if readerRegister == nil {
|
||||
readerRegister = make(map[string]func() io.Reader)
|
||||
}
|
||||
|
||||
readerRegister[name] = handler
|
||||
readerRegisterLock.Unlock()
|
||||
}
|
||||
|
||||
// DeregisterReaderHandler removes the ReaderHandler function with
|
||||
// the given name from the registry.
|
||||
func DeregisterReaderHandler(name string) {
|
||||
readerRegisterLock.Lock()
|
||||
delete(readerRegister, name)
|
||||
readerRegisterLock.Unlock()
|
||||
}
|
||||
|
||||
func deferredClose(err *error, closer io.Closer) {
|
||||
@@ -86,9 +97,15 @@ func (mc *mysqlConn) handleInFileRequest(name string) (err error) {
|
||||
var rdr io.Reader
|
||||
var data []byte
|
||||
|
||||
if strings.HasPrefix(name, "Reader::") { // io.Reader
|
||||
name = name[8:]
|
||||
if handler, inMap := readerRegister[name]; inMap {
|
||||
if idx := strings.Index(name, "Reader::"); idx == 0 || (idx > 0 && name[idx-1] == '/') { // io.Reader
|
||||
// The server might return an an absolute path. See issue #355.
|
||||
name = name[idx+8:]
|
||||
|
||||
readerRegisterLock.RLock()
|
||||
handler, inMap := readerRegister[name]
|
||||
readerRegisterLock.RUnlock()
|
||||
|
||||
if inMap {
|
||||
rdr = handler()
|
||||
if rdr != nil {
|
||||
data = make([]byte, 4+mc.maxWriteSize)
|
||||
@@ -104,7 +121,10 @@ func (mc *mysqlConn) handleInFileRequest(name string) (err error) {
|
||||
}
|
||||
} else { // File
|
||||
name = strings.Trim(name, `"`)
|
||||
if mc.cfg.allowAllFiles || fileRegister[name] {
|
||||
fileRegisterLock.RLock()
|
||||
fr := fileRegister[name]
|
||||
fileRegisterLock.RUnlock()
|
||||
if mc.cfg.allowAllFiles || fr {
|
||||
var file *os.File
|
||||
var fi os.FileInfo
|
||||
|
||||
|
||||
56
Godeps/_workspace/src/github.com/go-sql-driver/mysql/packets.go
сгенерированный
поставляемый
56
Godeps/_workspace/src/github.com/go-sql-driver/mysql/packets.go
сгенерированный
поставляемый
@@ -196,7 +196,11 @@ func (mc *mysqlConn) readInitPacket() ([]byte, error) {
|
||||
// return
|
||||
//}
|
||||
//return ErrMalformPkt
|
||||
return cipher, nil
|
||||
|
||||
// make a memory safe copy of the cipher slice
|
||||
var b [20]byte
|
||||
copy(b[:], cipher)
|
||||
return b[:], nil
|
||||
}
|
||||
|
||||
// make a memory safe copy of the cipher slice
|
||||
@@ -214,6 +218,7 @@ func (mc *mysqlConn) writeAuthPacket(cipher []byte) error {
|
||||
clientLongPassword |
|
||||
clientTransactions |
|
||||
clientLocalFiles |
|
||||
clientPluginAuth |
|
||||
mc.flags&clientLongFlag
|
||||
|
||||
if mc.cfg.clientFoundRows {
|
||||
@@ -228,7 +233,7 @@ func (mc *mysqlConn) writeAuthPacket(cipher []byte) error {
|
||||
// User Password
|
||||
scrambleBuff := scramblePassword(cipher, []byte(mc.cfg.passwd))
|
||||
|
||||
pktLen := 4 + 4 + 1 + 23 + len(mc.cfg.user) + 1 + 1 + len(scrambleBuff)
|
||||
pktLen := 4 + 4 + 1 + 23 + len(mc.cfg.user) + 1 + 1 + len(scrambleBuff) + 21 + 1
|
||||
|
||||
// To specify a db name
|
||||
if n := len(mc.cfg.dbname); n > 0 {
|
||||
@@ -277,7 +282,10 @@ func (mc *mysqlConn) writeAuthPacket(cipher []byte) error {
|
||||
}
|
||||
|
||||
// Filler [23 bytes] (all 0x00)
|
||||
pos := 13 + 23
|
||||
pos := 13
|
||||
for ; pos < 13+23; pos++ {
|
||||
data[pos] = 0
|
||||
}
|
||||
|
||||
// User [null terminated string]
|
||||
if len(mc.cfg.user) > 0 {
|
||||
@@ -294,8 +302,13 @@ func (mc *mysqlConn) writeAuthPacket(cipher []byte) error {
|
||||
if len(mc.cfg.dbname) > 0 {
|
||||
pos += copy(data[pos:], mc.cfg.dbname)
|
||||
data[pos] = 0x00
|
||||
pos++
|
||||
}
|
||||
|
||||
// Assume native client during response
|
||||
pos += copy(data[pos:], "mysql_native_password")
|
||||
data[pos] = 0x00
|
||||
|
||||
// Send Auth packet
|
||||
return mc.writePacket(data)
|
||||
}
|
||||
@@ -306,7 +319,7 @@ func (mc *mysqlConn) writeOldAuthPacket(cipher []byte) error {
|
||||
// User password
|
||||
scrambleBuff := scrambleOldPassword(cipher, []byte(mc.cfg.passwd))
|
||||
|
||||
// Calculate the packet lenght and add a tailing 0
|
||||
// Calculate the packet length and add a tailing 0
|
||||
pktLen := len(scrambleBuff) + 1
|
||||
data := mc.buf.takeSmallBuffer(4 + pktLen)
|
||||
if data == nil {
|
||||
@@ -322,6 +335,25 @@ func (mc *mysqlConn) writeOldAuthPacket(cipher []byte) error {
|
||||
return mc.writePacket(data)
|
||||
}
|
||||
|
||||
// Client clear text authentication packet
|
||||
// http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::AuthSwitchResponse
|
||||
func (mc *mysqlConn) writeClearAuthPacket() error {
|
||||
// Calculate the packet length and add a tailing 0
|
||||
pktLen := len(mc.cfg.passwd) + 1
|
||||
data := mc.buf.takeSmallBuffer(4 + pktLen)
|
||||
if data == nil {
|
||||
// can not take the buffer. Something must be wrong with the connection
|
||||
errLog.Print(ErrBusyBuffer)
|
||||
return driver.ErrBadConn
|
||||
}
|
||||
|
||||
// Add the clear password [null terminated string]
|
||||
copy(data[4:], mc.cfg.passwd)
|
||||
data[4+pktLen-1] = 0x00
|
||||
|
||||
return mc.writePacket(data)
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
* Command Packets *
|
||||
******************************************************************************/
|
||||
@@ -405,8 +437,20 @@ func (mc *mysqlConn) readResultOK() error {
|
||||
return mc.handleOkPacket(data)
|
||||
|
||||
case iEOF:
|
||||
// someone is using old_passwords
|
||||
return ErrOldPassword
|
||||
if len(data) > 1 {
|
||||
plugin := string(data[1:bytes.IndexByte(data, 0x00)])
|
||||
if plugin == "mysql_old_password" {
|
||||
// using old_passwords
|
||||
return ErrOldPassword
|
||||
} else if plugin == "mysql_clear_password" {
|
||||
// using clear text password
|
||||
return ErrCleartextPassword
|
||||
} else {
|
||||
return ErrUnknownPlugin
|
||||
}
|
||||
} else {
|
||||
return ErrOldPassword
|
||||
}
|
||||
|
||||
default: // Error otherwise
|
||||
return mc.handleErrorPacket(data)
|
||||
|
||||
6
Godeps/_workspace/src/github.com/go-sql-driver/mysql/rows.go
сгенерированный
поставляемый
6
Godeps/_workspace/src/github.com/go-sql-driver/mysql/rows.go
сгенерированный
поставляемый
@@ -40,7 +40,11 @@ func (rows *mysqlRows) Columns() []string {
|
||||
columns := make([]string, len(rows.columns))
|
||||
if rows.mc.cfg.columnsWithAlias {
|
||||
for i := range columns {
|
||||
columns[i] = rows.columns[i].tableName + "." + rows.columns[i].name
|
||||
if tableName := rows.columns[i].tableName; len(tableName) > 0 {
|
||||
columns[i] = tableName + "." + rows.columns[i].name
|
||||
} else {
|
||||
columns[i] = rows.columns[i].name
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for i := range columns {
|
||||
|
||||
7
Godeps/_workspace/src/github.com/go-sql-driver/mysql/statement.go
сгенерированный
поставляемый
7
Godeps/_workspace/src/github.com/go-sql-driver/mysql/statement.go
сгенерированный
поставляемый
@@ -12,6 +12,7 @@ import (
|
||||
"database/sql/driver"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type mysqlStmt struct {
|
||||
@@ -119,7 +120,7 @@ func (stmt *mysqlStmt) Query(args []driver.Value) (driver.Rows, error) {
|
||||
|
||||
type converter struct{}
|
||||
|
||||
func (converter) ConvertValue(v interface{}) (driver.Value, error) {
|
||||
func (c converter) ConvertValue(v interface{}) (driver.Value, error) {
|
||||
if driver.IsValue(v) {
|
||||
return v, nil
|
||||
}
|
||||
@@ -131,7 +132,7 @@ func (converter) ConvertValue(v interface{}) (driver.Value, error) {
|
||||
if rv.IsNil() {
|
||||
return nil, nil
|
||||
}
|
||||
return driver.DefaultParameterConverter.ConvertValue(rv.Elem().Interface())
|
||||
return c.ConvertValue(rv.Elem().Interface())
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
return rv.Int(), nil
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32:
|
||||
@@ -139,7 +140,7 @@ func (converter) ConvertValue(v interface{}) (driver.Value, error) {
|
||||
case reflect.Uint64:
|
||||
u64 := rv.Uint()
|
||||
if u64 >= 1<<63 {
|
||||
return fmt.Sprintf("%d", u64), nil
|
||||
return strconv.FormatUint(u64, 10), nil
|
||||
}
|
||||
return int64(u64), nil
|
||||
case reflect.Float32, reflect.Float64:
|
||||
|
||||
14
Godeps/_workspace/src/github.com/go-sql-driver/mysql/utils.go
сгенерированный
поставляемый
14
Godeps/_workspace/src/github.com/go-sql-driver/mysql/utils.go
сгенерированный
поставляемый
@@ -80,8 +80,6 @@ func parseDSN(dsn string) (cfg *config, err error) {
|
||||
collation: defaultCollation,
|
||||
}
|
||||
|
||||
// TODO: use strings.IndexByte when we can depend on Go 1.2
|
||||
|
||||
// [user[:password]@][net[(addr)]]/dbname[?param1=value1¶mN=valueN]
|
||||
// Find the last '/' (since the password or the net addr might contain a '/')
|
||||
foundSlash := false
|
||||
@@ -201,6 +199,14 @@ func parseDSNParams(cfg *config, params string) (err error) {
|
||||
return fmt.Errorf("Invalid Bool value: %s", value)
|
||||
}
|
||||
|
||||
// Use cleartext authentication mode (MySQL 5.5.10+)
|
||||
case "allowCleartextPasswords":
|
||||
var isBool bool
|
||||
cfg.allowCleartextPasswords, isBool = readBool(value)
|
||||
if !isBool {
|
||||
return fmt.Errorf("Invalid Bool value: %s", value)
|
||||
}
|
||||
|
||||
// Use old authentication mode (pre MySQL 4.1)
|
||||
case "allowOldPasswords":
|
||||
var isBool bool
|
||||
@@ -771,6 +777,10 @@ func skipLengthEncodedString(b []byte) (int, error) {
|
||||
|
||||
// returns the number read, whether the value is NULL and the number of bytes read
|
||||
func readLengthEncodedInteger(b []byte) (uint64, bool, int) {
|
||||
// See issue #349
|
||||
if len(b) == 0 {
|
||||
return 0, true, 1
|
||||
}
|
||||
switch b[0] {
|
||||
|
||||
// 251: NULL
|
||||
|
||||
26
Godeps/_workspace/src/github.com/go-sql-driver/mysql/utils_test.go
сгенерированный
поставляемый
26
Godeps/_workspace/src/github.com/go-sql-driver/mysql/utils_test.go
сгенерированный
поставляемый
@@ -22,19 +22,19 @@ var testDSNs = []struct {
|
||||
out string
|
||||
loc *time.Location
|
||||
}{
|
||||
{"username:password@protocol(address)/dbname?param=value", "&{user:username passwd:password net:protocol addr:address dbname:dbname params:map[param:value] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
|
||||
{"username:password@protocol(address)/dbname?param=value&columnsWithAlias=true", "&{user:username passwd:password net:protocol addr:address dbname:dbname params:map[param:value] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:true interpolateParams:false}", time.UTC},
|
||||
{"user@unix(/path/to/socket)/dbname?charset=utf8", "&{user:user passwd: net:unix addr:/path/to/socket dbname:dbname params:map[charset:utf8] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
|
||||
{"user:password@tcp(localhost:5555)/dbname?charset=utf8&tls=true", "&{user:user passwd:password net:tcp addr:localhost:5555 dbname:dbname params:map[charset:utf8] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
|
||||
{"user:password@tcp(localhost:5555)/dbname?charset=utf8mb4,utf8&tls=skip-verify", "&{user:user passwd:password net:tcp addr:localhost:5555 dbname:dbname params:map[charset:utf8mb4,utf8] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
|
||||
{"user:password@/dbname?loc=UTC&timeout=30s&allowAllFiles=1&clientFoundRows=true&allowOldPasswords=TRUE&collation=utf8mb4_unicode_ci", "&{user:user passwd:password net:tcp addr:127.0.0.1:3306 dbname:dbname params:map[] loc:%p tls:<nil> timeout:30000000000 collation:224 allowAllFiles:true allowOldPasswords:true clientFoundRows:true columnsWithAlias:false interpolateParams:false}", time.UTC},
|
||||
{"user:p@ss(word)@tcp([de:ad:be:ef::ca:fe]:80)/dbname?loc=Local", "&{user:user passwd:p@ss(word) net:tcp addr:[de:ad:be:ef::ca:fe]:80 dbname:dbname params:map[] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.Local},
|
||||
{"/dbname", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname:dbname params:map[] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
|
||||
{"@/", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
|
||||
{"/", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
|
||||
{"", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
|
||||
{"user:p@/ssword@/", "&{user:user passwd:p@/ssword net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
|
||||
{"unix/?arg=%2Fsome%2Fpath.ext", "&{user: passwd: net:unix addr:/tmp/mysql.sock dbname: params:map[arg:/some/path.ext] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
|
||||
{"username:password@protocol(address)/dbname?param=value", "&{user:username passwd:password net:protocol addr:address dbname:dbname params:map[param:value] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
|
||||
{"username:password@protocol(address)/dbname?param=value&columnsWithAlias=true", "&{user:username passwd:password net:protocol addr:address dbname:dbname params:map[param:value] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:true interpolateParams:false}", time.UTC},
|
||||
{"user@unix(/path/to/socket)/dbname?charset=utf8", "&{user:user passwd: net:unix addr:/path/to/socket dbname:dbname params:map[charset:utf8] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
|
||||
{"user:password@tcp(localhost:5555)/dbname?charset=utf8&tls=true", "&{user:user passwd:password net:tcp addr:localhost:5555 dbname:dbname params:map[charset:utf8] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
|
||||
{"user:password@tcp(localhost:5555)/dbname?charset=utf8mb4,utf8&tls=skip-verify", "&{user:user passwd:password net:tcp addr:localhost:5555 dbname:dbname params:map[charset:utf8mb4,utf8] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
|
||||
{"user:password@/dbname?loc=UTC&timeout=30s&allowAllFiles=1&clientFoundRows=true&allowOldPasswords=TRUE&collation=utf8mb4_unicode_ci", "&{user:user passwd:password net:tcp addr:127.0.0.1:3306 dbname:dbname params:map[] loc:%p tls:<nil> timeout:30000000000 collation:224 allowAllFiles:true allowOldPasswords:true allowCleartextPasswords:false clientFoundRows:true columnsWithAlias:false interpolateParams:false}", time.UTC},
|
||||
{"user:p@ss(word)@tcp([de:ad:be:ef::ca:fe]:80)/dbname?loc=Local", "&{user:user passwd:p@ss(word) net:tcp addr:[de:ad:be:ef::ca:fe]:80 dbname:dbname params:map[] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.Local},
|
||||
{"/dbname", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname:dbname params:map[] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
|
||||
{"@/", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
|
||||
{"/", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
|
||||
{"", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
|
||||
{"user:p@/ssword@/", "&{user:user passwd:p@/ssword net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
|
||||
{"unix/?arg=%2Fsome%2Fpath.ext", "&{user: passwd: net:unix addr:/tmp/mysql.sock dbname: params:map[arg:/some/path.ext] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC},
|
||||
}
|
||||
|
||||
func TestDSNParser(t *testing.T) {
|
||||
|
||||
2
Godeps/_workspace/src/github.com/goamz/goamz/aws/attempt_test.go
сгенерированный
поставляемый
2
Godeps/_workspace/src/github.com/goamz/goamz/aws/attempt_test.go
сгенерированный
поставляемый
@@ -3,7 +3,7 @@ package aws_test
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/goamz/goamz/aws"
|
||||
"github.com/mattermost/platform/Godeps/_workspace/src/github.com/goamz/goamz/aws"
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
|
||||
41
Godeps/_workspace/src/github.com/goamz/goamz/aws/aws.go
сгенерированный
поставляемый
41
Godeps/_workspace/src/github.com/goamz/goamz/aws/aws.go
сгенерированный
поставляемый
@@ -20,7 +20,7 @@ import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/vaughan0/go-ini"
|
||||
"github.com/mattermost/platform/Godeps/_workspace/src/github.com/vaughan0/go-ini"
|
||||
)
|
||||
|
||||
// Defines the valid signers
|
||||
@@ -41,25 +41,26 @@ type ServiceInfo struct {
|
||||
//
|
||||
// See http://goo.gl/d8BP1 for more details.
|
||||
type Region struct {
|
||||
Name string // the canonical name of this region.
|
||||
EC2Endpoint string
|
||||
S3Endpoint string
|
||||
S3BucketEndpoint string // Not needed by AWS S3. Use ${bucket} for bucket name.
|
||||
S3LocationConstraint bool // true if this region requires a LocationConstraint declaration.
|
||||
S3LowercaseBucket bool // true if the region requires bucket names to be lower case.
|
||||
SDBEndpoint string
|
||||
SESEndpoint string
|
||||
SNSEndpoint string
|
||||
SQSEndpoint string
|
||||
IAMEndpoint string
|
||||
ELBEndpoint string
|
||||
DynamoDBEndpoint string
|
||||
CloudWatchServicepoint ServiceInfo
|
||||
AutoScalingEndpoint string
|
||||
RDSEndpoint ServiceInfo
|
||||
STSEndpoint string
|
||||
CloudFormationEndpoint string
|
||||
ECSEndpoint string
|
||||
Name string // the canonical name of this region.
|
||||
EC2Endpoint string
|
||||
S3Endpoint string
|
||||
S3BucketEndpoint string // Not needed by AWS S3. Use ${bucket} for bucket name.
|
||||
S3LocationConstraint bool // true if this region requires a LocationConstraint declaration.
|
||||
S3LowercaseBucket bool // true if the region requires bucket names to be lower case.
|
||||
SDBEndpoint string
|
||||
SESEndpoint string
|
||||
SNSEndpoint string
|
||||
SQSEndpoint string
|
||||
IAMEndpoint string
|
||||
ELBEndpoint string
|
||||
DynamoDBEndpoint string
|
||||
CloudWatchServicepoint ServiceInfo
|
||||
AutoScalingEndpoint string
|
||||
RDSEndpoint ServiceInfo
|
||||
STSEndpoint string
|
||||
CloudFormationEndpoint string
|
||||
ECSEndpoint string
|
||||
DynamoDBStreamsEndpoint string
|
||||
}
|
||||
|
||||
var Regions = map[string]Region{
|
||||
|
||||
2
Godeps/_workspace/src/github.com/goamz/goamz/aws/aws_test.go
сгенерированный
поставляемый
2
Godeps/_workspace/src/github.com/goamz/goamz/aws/aws_test.go
сгенерированный
поставляемый
@@ -7,7 +7,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/goamz/goamz/aws"
|
||||
"github.com/mattermost/platform/Godeps/_workspace/src/github.com/goamz/goamz/aws"
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
|
||||
2
Godeps/_workspace/src/github.com/goamz/goamz/aws/client_test.go
сгенерированный
поставляемый
2
Godeps/_workspace/src/github.com/goamz/goamz/aws/client_test.go
сгенерированный
поставляемый
@@ -2,7 +2,7 @@ package aws_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/goamz/goamz/aws"
|
||||
"github.com/mattermost/platform/Godeps/_workspace/src/github.com/goamz/goamz/aws"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
|
||||
11
Godeps/_workspace/src/github.com/goamz/goamz/aws/regions.go
сгенерированный
поставляемый
11
Godeps/_workspace/src/github.com/goamz/goamz/aws/regions.go
сгенерированный
поставляемый
@@ -20,6 +20,7 @@ var USGovWest = Region{
|
||||
"https://sts.amazonaws.com",
|
||||
"https://cloudformation.us-gov-west-1.amazonaws.com",
|
||||
"https://ecs.us-gov-west-1.amazonaws.com",
|
||||
"https://streams.dynamodb.us-gov-west-1.amazonaws.com",
|
||||
}
|
||||
|
||||
var USEast = Region{
|
||||
@@ -42,6 +43,7 @@ var USEast = Region{
|
||||
"https://sts.amazonaws.com",
|
||||
"https://cloudformation.us-east-1.amazonaws.com",
|
||||
"https://ecs.us-east-1.amazonaws.com",
|
||||
"https://streams.dynamodb.us-east-1.amazonaws.com",
|
||||
}
|
||||
|
||||
var USWest = Region{
|
||||
@@ -64,6 +66,7 @@ var USWest = Region{
|
||||
"https://sts.amazonaws.com",
|
||||
"https://cloudformation.us-west-1.amazonaws.com",
|
||||
"https://ecs.us-west-1.amazonaws.com",
|
||||
"https://streams.dynamodb.us-west-1.amazonaws.com",
|
||||
}
|
||||
|
||||
var USWest2 = Region{
|
||||
@@ -86,6 +89,7 @@ var USWest2 = Region{
|
||||
"https://sts.amazonaws.com",
|
||||
"https://cloudformation.us-west-2.amazonaws.com",
|
||||
"https://ecs.us-west-2.amazonaws.com",
|
||||
"https://streams.dynamodb.us-west-2.amazonaws.com",
|
||||
}
|
||||
|
||||
var EUWest = Region{
|
||||
@@ -108,6 +112,7 @@ var EUWest = Region{
|
||||
"https://sts.amazonaws.com",
|
||||
"https://cloudformation.eu-west-1.amazonaws.com",
|
||||
"https://ecs.eu-west-1.amazonaws.com",
|
||||
"https://streams.dynamodb.eu-west-1.amazonaws.com",
|
||||
}
|
||||
|
||||
var EUCentral = Region{
|
||||
@@ -130,6 +135,7 @@ var EUCentral = Region{
|
||||
"https://sts.amazonaws.com",
|
||||
"https://cloudformation.eu-central-1.amazonaws.com",
|
||||
"https://ecs.eu-central-1.amazonaws.com",
|
||||
"https://streams.dynamodb.eu-central-1.amazonaws.com",
|
||||
}
|
||||
|
||||
var APSoutheast = Region{
|
||||
@@ -152,6 +158,7 @@ var APSoutheast = Region{
|
||||
"https://sts.amazonaws.com",
|
||||
"https://cloudformation.ap-southeast-1.amazonaws.com",
|
||||
"https://ecs.ap-southeast-1.amazonaws.com",
|
||||
"https://streams.dynamodb.ap-southeast-1.amazonaws.com",
|
||||
}
|
||||
|
||||
var APSoutheast2 = Region{
|
||||
@@ -174,6 +181,7 @@ var APSoutheast2 = Region{
|
||||
"https://sts.amazonaws.com",
|
||||
"https://cloudformation.ap-southeast-2.amazonaws.com",
|
||||
"https://ecs.ap-southeast-2.amazonaws.com",
|
||||
"https://streams.dynamodb.ap-southeast-2.amazonaws.com",
|
||||
}
|
||||
|
||||
var APNortheast = Region{
|
||||
@@ -196,6 +204,7 @@ var APNortheast = Region{
|
||||
"https://sts.amazonaws.com",
|
||||
"https://cloudformation.ap-northeast-1.amazonaws.com",
|
||||
"https://ecs.ap-northeast-1.amazonaws.com",
|
||||
"https://streams.dynamodb.ap-northeast-1.amazonaws.com",
|
||||
}
|
||||
|
||||
var SAEast = Region{
|
||||
@@ -218,6 +227,7 @@ var SAEast = Region{
|
||||
"https://sts.amazonaws.com",
|
||||
"https://cloudformation.sa-east-1.amazonaws.com",
|
||||
"https://ecs.sa-east-1.amazonaws.com",
|
||||
"https://streams.dynamodb.sa-east-1.amazonaws.com",
|
||||
}
|
||||
|
||||
var CNNorth = Region{
|
||||
@@ -240,4 +250,5 @@ var CNNorth = Region{
|
||||
"https://sts.cn-north-1.amazonaws.com.cn",
|
||||
"https://cloudformation.cn-north-1.amazonaws.com.cn",
|
||||
"https://ecs.cn-north-1.amazonaws.com.cn",
|
||||
"https://streams.dynamodb.cn-north-1.amazonaws.com.cn",
|
||||
}
|
||||
|
||||
2
Godeps/_workspace/src/github.com/goamz/goamz/aws/sign_test.go
сгенерированный
поставляемый
2
Godeps/_workspace/src/github.com/goamz/goamz/aws/sign_test.go
сгенерированный
поставляемый
@@ -6,7 +6,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/goamz/goamz/aws"
|
||||
"github.com/mattermost/platform/Godeps/_workspace/src/github.com/goamz/goamz/aws"
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
|
||||
2
Godeps/_workspace/src/github.com/goamz/goamz/s3/export_test.go
сгенерированный
поставляемый
2
Godeps/_workspace/src/github.com/goamz/goamz/s3/export_test.go
сгенерированный
поставляемый
@@ -1,7 +1,7 @@
|
||||
package s3
|
||||
|
||||
import (
|
||||
"github.com/goamz/goamz/aws"
|
||||
"github.com/mattermost/platform/Godeps/_workspace/src/github.com/goamz/goamz/aws"
|
||||
)
|
||||
|
||||
func Sign(auth aws.Auth, method, path string, params, headers map[string][]string) {
|
||||
|
||||
Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше
Ссылка в новой задаче
Block a user