summaryrefslogtreecommitdiffstats
path: root/Godeps/_workspace/src/github.com
diff options
context:
space:
mode:
authorChristopher Speller <crspeller@gmail.com>2015-11-26 09:02:00 -0500
committerChristopher Speller <crspeller@gmail.com>2015-11-26 09:02:00 -0500
commit006fc61ecce1ba3d5c7b7163309467c24edbbc46 (patch)
tree533f5dcd094ebd94d425e64a4261b7b21ec6f3fa /Godeps/_workspace/src/github.com
parentaaced173f8b3020fbbef236d84b070c2c67ee968 (diff)
parent2639452967e66c4840164c36817234d3e7c12ac1 (diff)
downloadchat-006fc61ecce1ba3d5c7b7163309467c24edbbc46.tar.gz
chat-006fc61ecce1ba3d5c7b7163309467c24edbbc46.tar.bz2
chat-006fc61ecce1ba3d5c7b7163309467c24edbbc46.zip
Merge pull request #1505 from mattermost/lib-upgrade
Lib upgrade
Diffstat (limited to 'Godeps/_workspace/src/github.com')
-rw-r--r--Godeps/_workspace/src/github.com/braintree/manners/README.md11
-rw-r--r--Godeps/_workspace/src/github.com/braintree/manners/helper_test.go34
-rw-r--r--Godeps/_workspace/src/github.com/braintree/manners/helpers_test.go123
-rw-r--r--Godeps/_workspace/src/github.com/braintree/manners/interfaces.go7
-rw-r--r--Godeps/_workspace/src/github.com/braintree/manners/listener.go49
-rw-r--r--Godeps/_workspace/src/github.com/braintree/manners/server.go277
-rw-r--r--Godeps/_workspace/src/github.com/braintree/manners/server_test.go273
-rw-r--r--Godeps/_workspace/src/github.com/braintree/manners/static.go35
-rw-r--r--Godeps/_workspace/src/github.com/braintree/manners/test_helpers/certs.go29
-rw-r--r--Godeps/_workspace/src/github.com/braintree/manners/test_helpers/conn.go13
-rw-r--r--Godeps/_workspace/src/github.com/braintree/manners/test_helpers/listener.go34
-rw-r--r--Godeps/_workspace/src/github.com/braintree/manners/test_helpers/temp_file.go27
-rw-r--r--Godeps/_workspace/src/github.com/braintree/manners/test_helpers/wait_group.go33
-rw-r--r--Godeps/_workspace/src/github.com/braintree/manners/transition_test.go54
-rw-r--r--Godeps/_workspace/src/github.com/davecgh/go-spew/spew/bypass.go151
-rw-r--r--Godeps/_workspace/src/github.com/davecgh/go-spew/spew/bypasssafe.go37
-rw-r--r--Godeps/_workspace/src/github.com/davecgh/go-spew/spew/common.go341
-rw-r--r--Godeps/_workspace/src/github.com/davecgh/go-spew/spew/common_test.go298
-rw-r--r--Godeps/_workspace/src/github.com/davecgh/go-spew/spew/config.go297
-rw-r--r--Godeps/_workspace/src/github.com/davecgh/go-spew/spew/doc.go202
-rw-r--r--Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dump.go509
-rw-r--r--Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dump_test.go1042
-rw-r--r--Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dumpcgo_test.go98
-rw-r--r--Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dumpnocgo_test.go26
-rw-r--r--Godeps/_workspace/src/github.com/davecgh/go-spew/spew/example_test.go226
-rw-r--r--Godeps/_workspace/src/github.com/davecgh/go-spew/spew/format.go419
-rw-r--r--Godeps/_workspace/src/github.com/davecgh/go-spew/spew/format_test.go1558
-rw-r--r--Godeps/_workspace/src/github.com/davecgh/go-spew/spew/internal_test.go87
-rw-r--r--Godeps/_workspace/src/github.com/davecgh/go-spew/spew/internalunsafe_test.go101
-rw-r--r--Godeps/_workspace/src/github.com/davecgh/go-spew/spew/spew.go148
-rw-r--r--Godeps/_workspace/src/github.com/davecgh/go-spew/spew/spew_test.go309
-rw-r--r--Godeps/_workspace/src/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go82
-rw-r--r--Godeps/_workspace/src/github.com/disintegration/imaging/README.md38
-rw-r--r--Godeps/_workspace/src/github.com/disintegration/imaging/adjust_test.go504
-rw-r--r--Godeps/_workspace/src/github.com/disintegration/imaging/effects_test.go128
-rw-r--r--Godeps/_workspace/src/github.com/disintegration/imaging/helpers.go20
-rw-r--r--Godeps/_workspace/src/github.com/disintegration/imaging/helpers_test.go361
-rw-r--r--Godeps/_workspace/src/github.com/disintegration/imaging/resize.go43
-rw-r--r--Godeps/_workspace/src/github.com/disintegration/imaging/resize_test.go455
-rw-r--r--Godeps/_workspace/src/github.com/disintegration/imaging/tools_test.go605
-rw-r--r--Godeps/_workspace/src/github.com/disintegration/imaging/transform_test.go261
-rw-r--r--Godeps/_workspace/src/github.com/disintegration/imaging/utils_test.go61
-rw-r--r--Godeps/_workspace/src/github.com/garyburd/redigo/internal/redistest/testdb.go3
-rw-r--r--Godeps/_workspace/src/github.com/garyburd/redigo/redis/conn.go182
-rw-r--r--Godeps/_workspace/src/github.com/garyburd/redigo/redis/conn_test.go161
-rw-r--r--Godeps/_workspace/src/github.com/garyburd/redigo/redis/pool.go12
-rw-r--r--Godeps/_workspace/src/github.com/garyburd/redigo/redis/pool_test.go94
-rw-r--r--Godeps/_workspace/src/github.com/garyburd/redigo/redis/pubsub_test.go20
-rw-r--r--Godeps/_workspace/src/github.com/garyburd/redigo/redis/reply.go37
-rw-r--r--Godeps/_workspace/src/github.com/garyburd/redigo/redis/reply_test.go27
-rw-r--r--Godeps/_workspace/src/github.com/garyburd/redigo/redis/scan.go92
-rw-r--r--Godeps/_workspace/src/github.com/garyburd/redigo/redis/scan_test.go64
-rw-r--r--Godeps/_workspace/src/github.com/garyburd/redigo/redis/script_test.go3
-rw-r--r--Godeps/_workspace/src/github.com/garyburd/redigo/redis/test_test.go157
-rw-r--r--Godeps/_workspace/src/github.com/go-gorp/gorp/.travis.yml35
-rw-r--r--Godeps/_workspace/src/github.com/go-gorp/gorp/Makefile6
-rw-r--r--Godeps/_workspace/src/github.com/go-gorp/gorp/README.md119
-rw-r--r--Godeps/_workspace/src/github.com/go-gorp/gorp/column.go83
-rw-r--r--Godeps/_workspace/src/github.com/go-gorp/gorp/db.go619
-rw-r--r--Godeps/_workspace/src/github.com/go-gorp/gorp/dialect.go641
-rw-r--r--Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_mysql.go171
-rw-r--r--Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_oracle.go146
-rw-r--r--Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_postgres.go147
-rw-r--r--Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_sqlite.go119
-rw-r--r--Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_sqlserver.go152
-rw-r--r--Godeps/_workspace/src/github.com/go-gorp/gorp/errors.go14
-rw-r--r--Godeps/_workspace/src/github.com/go-gorp/gorp/gorp.go1678
-rw-r--r--Godeps/_workspace/src/github.com/go-gorp/gorp/gorp_test.go239
-rw-r--r--Godeps/_workspace/src/github.com/go-gorp/gorp/hooks.go49
-rw-r--r--Godeps/_workspace/src/github.com/go-gorp/gorp/index.go56
-rw-r--r--Godeps/_workspace/src/github.com/go-gorp/gorp/lockerror.go63
-rw-r--r--Godeps/_workspace/src/github.com/go-gorp/gorp/logging.go44
-rw-r--r--Godeps/_workspace/src/github.com/go-gorp/gorp/nulltypes.go58
-rw-r--r--Godeps/_workspace/src/github.com/go-gorp/gorp/select.go351
-rw-r--r--Godeps/_workspace/src/github.com/go-gorp/gorp/table.go247
-rw-r--r--Godeps/_workspace/src/github.com/go-gorp/gorp/table_bindings.go317
-rw-r--r--Godeps/_workspace/src/github.com/go-gorp/gorp/test_all.sh28
-rw-r--r--Godeps/_workspace/src/github.com/go-gorp/gorp/transaction.go193
-rw-r--r--Godeps/_workspace/src/github.com/go-sql-driver/mysql/AUTHORS4
-rw-r--r--Godeps/_workspace/src/github.com/go-sql-driver/mysql/README.md14
-rw-r--r--Godeps/_workspace/src/github.com/go-sql-driver/mysql/connection.go33
-rw-r--r--Godeps/_workspace/src/github.com/go-sql-driver/mysql/driver.go9
-rw-r--r--Godeps/_workspace/src/github.com/go-sql-driver/mysql/driver_test.go24
-rw-r--r--Godeps/_workspace/src/github.com/go-sql-driver/mysql/errors.go20
-rw-r--r--Godeps/_workspace/src/github.com/go-sql-driver/mysql/infile.go32
-rw-r--r--Godeps/_workspace/src/github.com/go-sql-driver/mysql/packets.go56
-rw-r--r--Godeps/_workspace/src/github.com/go-sql-driver/mysql/rows.go6
-rw-r--r--Godeps/_workspace/src/github.com/go-sql-driver/mysql/statement.go7
-rw-r--r--Godeps/_workspace/src/github.com/go-sql-driver/mysql/utils.go14
-rw-r--r--Godeps/_workspace/src/github.com/go-sql-driver/mysql/utils_test.go26
-rw-r--r--Godeps/_workspace/src/github.com/goamz/goamz/aws/aws.go39
-rw-r--r--Godeps/_workspace/src/github.com/goamz/goamz/aws/regions.go11
-rw-r--r--Godeps/_workspace/src/github.com/goamz/goamz/s3/multi.go32
-rw-r--r--Godeps/_workspace/src/github.com/goamz/goamz/s3/multi_test.go4
-rw-r--r--Godeps/_workspace/src/github.com/goamz/goamz/s3/s3.go6
-rw-r--r--Godeps/_workspace/src/github.com/goamz/goamz/s3/s3test/server.go4
-rw-r--r--Godeps/_workspace/src/github.com/goamz/goamz/s3/sign.go43
-rw-r--r--Godeps/_workspace/src/github.com/golang/freetype/AUTHORS1
-rw-r--r--Godeps/_workspace/src/github.com/golang/freetype/CONTRIBUTORS1
-rw-r--r--Godeps/_workspace/src/github.com/golang/freetype/truetype/truetype.go165
-rw-r--r--Godeps/_workspace/src/github.com/golang/freetype/truetype/truetype_test.go23
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/context/.travis.yml5
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/mux/.travis.yml15
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/mux/README.md232
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/mux/doc.go19
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/mux/mux.go122
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/mux/mux_test.go322
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/mux/old_test.go6
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/mux/regexp.go79
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/mux/route.go46
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/websocket/README.md2
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/websocket/client.go246
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/websocket/client_server_test.go93
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/websocket/client_test.go1
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/websocket/conn.go48
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/websocket/conn_test.go44
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/websocket/doc.go13
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/websocket/examples/chat/README.md1
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/websocket/examples/chat/conn.go6
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/websocket/examples/command/README.md19
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/websocket/examples/command/home.html96
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/websocket/examples/command/main.go188
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/websocket/examples/echo/README.md17
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/websocket/examples/echo/client.go55
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/websocket/examples/echo/server.go132
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/websocket/json.go4
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/websocket/json_test.go4
-rw-r--r--Godeps/_workspace/src/github.com/gorilla/websocket/server.go3
-rw-r--r--Godeps/_workspace/src/github.com/lib/pq/.travis.yml1
-rw-r--r--Godeps/_workspace/src/github.com/lib/pq/buf.go1
-rw-r--r--Godeps/_workspace/src/github.com/lib/pq/conn.go12
-rw-r--r--Godeps/_workspace/src/github.com/lib/pq/copy.go9
-rw-r--r--Godeps/_workspace/src/github.com/mssola/user_agent/bot.go5
-rw-r--r--Godeps/_workspace/src/github.com/mssola/user_agent/browser.go5
-rw-r--r--Godeps/_workspace/src/github.com/pborman/uuid/CONTRIBUTORS1
-rw-r--r--Godeps/_workspace/src/github.com/pborman/uuid/LICENSE27
-rw-r--r--Godeps/_workspace/src/github.com/pborman/uuid/dce.go84
-rw-r--r--Godeps/_workspace/src/github.com/pborman/uuid/doc.go8
-rw-r--r--Godeps/_workspace/src/github.com/pborman/uuid/hash.go53
-rw-r--r--Godeps/_workspace/src/github.com/pborman/uuid/json.go30
-rw-r--r--Godeps/_workspace/src/github.com/pborman/uuid/json_test.go32
-rw-r--r--Godeps/_workspace/src/github.com/pborman/uuid/node.go101
-rw-r--r--Godeps/_workspace/src/github.com/pborman/uuid/seq_test.go66
-rw-r--r--Godeps/_workspace/src/github.com/pborman/uuid/sql.go40
-rw-r--r--Godeps/_workspace/src/github.com/pborman/uuid/sql_test.go53
-rw-r--r--Godeps/_workspace/src/github.com/pborman/uuid/time.go132
-rw-r--r--Godeps/_workspace/src/github.com/pborman/uuid/util.go43
-rw-r--r--Godeps/_workspace/src/github.com/pborman/uuid/uuid.go163
-rw-r--r--Godeps/_workspace/src/github.com/pborman/uuid/uuid_test.go390
-rw-r--r--Godeps/_workspace/src/github.com/pborman/uuid/version1.go41
-rw-r--r--Godeps/_workspace/src/github.com/pborman/uuid/version4.go25
-rw-r--r--Godeps/_workspace/src/github.com/pmezard/go-difflib/difflib/difflib.go758
-rw-r--r--Godeps/_workspace/src/github.com/pmezard/go-difflib/difflib/difflib_test.go352
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/corrupt/huge_tag_exif.jpgbin0 -> 65536 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/corrupt/infinite_loop_exif.jpgbin0 -> 3738 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/corrupt/max_uint32_exif.jpgbin0 -> 65536 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/sample1.jpgbin0 -> 80603 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2004-01-11-22-45-15-sep-2004-01-11-22-45-15a.jpgbin0 -> 4586 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2006-08-03-16-29-38-sep-2006-08-03-16-29-38a.jpgbin0 -> 9735 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2006-11-11-19-17-56-sep-2006-11-11-19-17-56a.jpgbin0 -> 35406 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2006-12-10-23-58-20-sep-2006-12-10-23-58-20a.jpgbin0 -> 8711 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2006-12-17-07-09-14-sep-2006-12-17-07-09-14a.jpgbin0 -> 38252 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2006-12-21-15-55-26-sep-2006-12-21-15-55-26a.jpgbin0 -> 16072 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-01-01-12-00-00-sep-2007-01-01-12-00-00a.jpgbin0 -> 17301 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-01-17-21-49-44-sep-2007-01-17-21-49-44a.jpgbin0 -> 7999 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-02-02-18-13-29-sep-2007-02-02-18-13-29a.jpgbin0 -> 39915 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-05-02-17-02-21-sep-2007-05-02-17-02-21a.jpgbin0 -> 11783 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-05-12-08-19-07-sep-2007-05-12-08-19-07a.jpgbin0 -> 35771 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-05-26-04-49-45-sep-2007-05-26-04-49-45a.jpgbin0 -> 35406 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-05-30-14-28-01-sep-2007-05-30-14-28-01a.jpgbin0 -> 35406 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-06-06-16-15-25-sep-2007-06-06-16-15-25a.jpgbin0 -> 35406 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-06-26-10-13-04-sep-2007-06-26-10-13-04a.jpgbin0 -> 7615 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-07-13-17-02-30-sep-2007-07-13-17-02-30a.jpgbin0 -> 21719 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-08-15-14-42-46-sep-2007-08-15-14-42-46a.jpgbin0 -> 11549 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-08-24-02-40-42-sep-2007-08-24-02-40-42a.jpgbin0 -> 7687 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-11-07-11-40-44-sep-2007-11-07-11-40-44a.jpgbin0 -> 11223 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2008-06-02-10-03-57-sep-2008-06-02-10-03-57a.jpgbin0 -> 9745 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2008-06-06-13-29-29-sep-2008-06-06-13-29-29a.jpgbin0 -> 11783 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2008-06-17-01-21-30-sep-2008-06-17-01-21-30a.jpgbin0 -> 14564 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2008-09-02-17-43-48-sep-2008-09-02-17-43-48a.jpgbin0 -> 5406 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2009-03-26-09-23-20-sep-2009-03-26-09-23-20a.jpgbin0 -> 10759 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2009-04-11-03-01-38-sep-2009-04-11-03-01-38a.jpgbin0 -> 43374 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2009-04-23-07-21-35-sep-2009-04-23-07-21-35a.jpgbin0 -> 37208 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2009-06-11-19-23-18-sep-2009-06-11-19-23-18a.jpgbin0 -> 7791 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2009-06-20-07-59-05-sep-2009-06-20-07-59-05a.jpgbin0 -> 13618 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2009-08-05-08-11-31-sep-2009-08-05-08-11-31a.jpgbin0 -> 9919 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2010-06-08-04-44-24-sep-2010-06-08-04-44-24a.jpgbin0 -> 10939 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2010-06-20-20-07-39-sep-2010-06-20-20-07-39a.jpgbin0 -> 8551 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2010-09-02-08-43-02-sep-2010-09-02-08-43-02a.jpgbin0 -> 19534 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-01-24-22-06-02-sep-2011-01-24-22-06-02a.jpgbin0 -> 29003 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-03-07-09-28-03-sep-2011-03-07-09-28-03a.jpgbin0 -> 10529 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-05-07-13-02-49-sep-2011-05-07-13-02-49a.jpgbin0 -> 23743 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-08-07-19-22-57-sep-2011-08-07-19-22-57a.jpgbin0 -> 9936 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-10-28-17-50-18-sep-2011-10-28-17-50-18a.jpgbin0 -> 7487 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-10-28-18-25-43-sep-2011-10-28-18-25-43.jpgbin0 -> 7433 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-11-18-15-38-34-sep-Photo11181538.jpgbin0 -> 12885 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2012-06-02-10-12-28-sep-2012-06-02-10-12-28.jpgbin0 -> 32165 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2012-09-21-22-07-34-sep-2012-09-21-22-07-34.jpgbin0 -> 10247 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2012-12-19-21-38-40-sep-temple_square1.jpgbin0 -> 39182 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2012-12-21-11-15-19-sep-IMG_0001.jpgbin0 -> 25269 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2013-02-05-23-12-09-sep-DSCI0001.jpgbin0 -> 10854 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2099-08-12-19-59-29-sep-2099-08-12-19-59-29a.jpgbin0 -> 37491 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2216-11-15-11-46-51-sep-2216-11-15-11-46-51a.jpgbin0 -> 23011 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/FailedHash-NoDate-sep-remembory.jpgbin0 -> 935 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f1-exif.jpgbin0 -> 992 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f2-exif.jpgbin0 -> 994 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f3-exif.jpgbin0 -> 992 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f4-exif.jpgbin0 -> 994 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f5-exif.jpgbin0 -> 980 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f6-exif.jpgbin0 -> 982 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f7-exif.jpgbin0 -> 980 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f8-exif.jpgbin0 -> 982 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/geodegrees_as_string.jpgbin0 -> 22420 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/has-lens-info.jpgbin0 -> 22493 bytes
-rw-r--r--Godeps/_workspace/src/github.com/rwcarlsen/goexif/tiff/sample1.tifbin0 -> 18382 bytes
-rw-r--r--Godeps/_workspace/src/github.com/stretchr/objx/value.go43
-rw-r--r--Godeps/_workspace/src/github.com/stretchr/objx/value_test.go65
-rw-r--r--Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions.go226
-rw-r--r--Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions_test.go302
-rw-r--r--Godeps/_workspace/src/github.com/stretchr/testify/assert/doc.go111
-rw-r--r--Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions.go27
-rw-r--r--Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions_test.go100
-rw-r--r--Godeps/_workspace/src/github.com/stretchr/testify/assert/http_assertions.go48
-rw-r--r--Godeps/_workspace/src/github.com/stretchr/testify/mock/mock.go280
-rw-r--r--Godeps/_workspace/src/github.com/stretchr/testify/mock/mock_test.go412
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/.gitignore10
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/.travis.yml10
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/LICENSE12
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/README.md80
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/common_test.go65
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/delayer.go109
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/delayer_test.go65
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/doc.go77
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/examples/README.md12
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/examples/custom/main.go90
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/examples/interval-many/main.go79
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/examples/interval-vary/main.go74
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/examples/interval-vary/siege-urls4
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/examples/interval/main.go69
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/examples/memstats/main.go97
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/examples/memstats/test-filebin65536 -> 0 bytes
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/examples/rate-limit/main.go101
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/interval.go164
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/interval_test.go114
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/memstats.go214
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/memstats_test.go64
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/misc/pre-commit38
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/rate.go116
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/rate_test.go101
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/store.go31
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/store/doc.go2
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/store/mem.go90
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/store/mem_test.go43
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/store/redis.go85
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/store/redis_test.go66
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/throttler.go86
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/varyby.go78
-rw-r--r--Godeps/_workspace/src/github.com/throttled/throttled/varyby_test.go56
258 files changed, 18793 insertions, 5780 deletions
diff --git a/Godeps/_workspace/src/github.com/braintree/manners/README.md b/Godeps/_workspace/src/github.com/braintree/manners/README.md
index 8c9a239b4..09f6f9693 100644
--- a/Godeps/_workspace/src/github.com/braintree/manners/README.md
+++ b/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.
diff --git a/Godeps/_workspace/src/github.com/braintree/manners/helper_test.go b/Godeps/_workspace/src/github.com/braintree/manners/helper_test.go
deleted file mode 100644
index ea721a180..000000000
--- a/Godeps/_workspace/src/github.com/braintree/manners/helper_test.go
+++ /dev/null
@@ -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) {}
diff --git a/Godeps/_workspace/src/github.com/braintree/manners/helpers_test.go b/Godeps/_workspace/src/github.com/braintree/manners/helpers_test.go
new file mode 100644
index 000000000..dd9a8ba18
--- /dev/null
+++ b/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)
+}
diff --git a/Godeps/_workspace/src/github.com/braintree/manners/interfaces.go b/Godeps/_workspace/src/github.com/braintree/manners/interfaces.go
new file mode 100644
index 000000000..fd0732857
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/braintree/manners/interfaces.go
@@ -0,0 +1,7 @@
+package manners
+
+type waitGroup interface {
+ Add(int)
+ Done()
+ Wait()
+}
diff --git a/Godeps/_workspace/src/github.com/braintree/manners/listener.go b/Godeps/_workspace/src/github.com/braintree/manners/listener.go
deleted file mode 100644
index dd84e4a2e..000000000
--- a/Godeps/_workspace/src/github.com/braintree/manners/listener.go
+++ /dev/null
@@ -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
-}
diff --git a/Godeps/_workspace/src/github.com/braintree/manners/server.go b/Godeps/_workspace/src/github.com/braintree/manners/server.go
index a79246668..e45f5c64b 100644
--- a/Godeps/_workspace/src/github.com/braintree/manners/server.go
+++ b/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)
+}
+
+// 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))
}
-// 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) {
+// 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
}
diff --git a/Godeps/_workspace/src/github.com/braintree/manners/server_test.go b/Godeps/_workspace/src/github.com/braintree/manners/server_test.go
index 0da015566..1ab7f19b4 100644
--- a/Godeps/_workspace/src/github.com/braintree/manners/server_test.go
+++ b/Godeps/_workspace/src/github.com/braintree/manners/server_test.go
@@ -1,71 +1,254 @@
package manners
import (
+ helpers "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()
+
+ waiting := <-wg.WaitCalled
+ if waiting < 1 {
+ t.Errorf("Expected the waitgroup to equal 1 at shutdown; actually %d", waiting)
+ }
+
+ // 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 once shutdown has begun
+func TestShutdown(t *testing.T) {
+ server := newServer()
+ wg := helpers.NewWaitGroup()
+ server.wg = wg
+ statechanged := make(chan http.ConnState)
+ listener, exitchan := startServer(t, server, statechanged)
+
+ client1 := newClient(listener.Addr(), false)
+ client1.Run()
+
+ // 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")
+
+ // 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")
+ }
+
+ 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)
- exited = true
- }()
+ client := newClient(listener.Addr(), false)
+ client.Run()
+ <-client.connected
+ client.sendrequest <- true
+ <-client.response
- go func() {
- _, err := http.Get("http://localhost:7000")
- if err != nil {
- t.Error(err)
+ 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)
}
- }()
+ }
+}
- // This will block until the server is inside the handler function.
- <-ready
+// 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)
- server.Shutdown <- true
- <-done
+ 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 exited {
- t.Fatal("The request did not complete before server exited")
- } else {
- // The handler is being allowed to run to completion; test passes.
+ 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
-func TestShutdown(t *testing.T) {
- handler := newTestHandler()
- server := NewServer()
- exited := make(chan bool)
-
- go func() {
- err := server.ListenAndServe(":7100", handler)
- if err != nil {
- t.Error(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)
}
- exited <- true
- }()
- server.Shutdown <- true
+ 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)
+ }
- <-exited
- _, err := http.Get("http://localhost:7100")
+ client.sendrequest <- true
+ waitForState(t, statechanged, http.StateActive, "Client failed to reach active state")
- if err == nil {
- t.Fatal("Did not receive an error when trying to connect to server.")
+ 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)
+ }
}
}
diff --git a/Godeps/_workspace/src/github.com/braintree/manners/static.go b/Godeps/_workspace/src/github.com/braintree/manners/static.go
new file mode 100644
index 000000000..2a74b094b
--- /dev/null
+++ b/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()
+}
diff --git a/Godeps/_workspace/src/github.com/braintree/manners/test_helpers/certs.go b/Godeps/_workspace/src/github.com/braintree/manners/test_helpers/certs.go
new file mode 100644
index 000000000..ede248b3d
--- /dev/null
+++ b/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-----`)
+)
diff --git a/Godeps/_workspace/src/github.com/braintree/manners/test_helpers/conn.go b/Godeps/_workspace/src/github.com/braintree/manners/test_helpers/conn.go
new file mode 100644
index 000000000..8c610f58e
--- /dev/null
+++ b/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
+}
diff --git a/Godeps/_workspace/src/github.com/braintree/manners/test_helpers/listener.go b/Godeps/_workspace/src/github.com/braintree/manners/test_helpers/listener.go
new file mode 100644
index 000000000..e3af35a6e
--- /dev/null
+++ b/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")
+}
diff --git a/Godeps/_workspace/src/github.com/braintree/manners/test_helpers/temp_file.go b/Godeps/_workspace/src/github.com/braintree/manners/test_helpers/temp_file.go
new file mode 100644
index 000000000..c4aa263a0
--- /dev/null
+++ b/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
+ }
+}
diff --git a/Godeps/_workspace/src/github.com/braintree/manners/test_helpers/wait_group.go b/Godeps/_workspace/src/github.com/braintree/manners/test_helpers/wait_group.go
new file mode 100644
index 000000000..1df590db7
--- /dev/null
+++ b/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()
+}
diff --git a/Godeps/_workspace/src/github.com/braintree/manners/transition_test.go b/Godeps/_workspace/src/github.com/braintree/manners/transition_test.go
new file mode 100644
index 000000000..34fe5c688
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/braintree/manners/transition_test.go
@@ -0,0 +1,54 @@
+package manners
+
+import (
+ helpers "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)
+ }
+}
diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/bypass.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/bypass.go
new file mode 100644
index 000000000..565bf5899
--- /dev/null
+++ b/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
+}
diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/bypasssafe.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/bypasssafe.go
new file mode 100644
index 000000000..457e41235
--- /dev/null
+++ b/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
+}
diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/common.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/common.go
new file mode 100644
index 000000000..14f02dc15
--- /dev/null
+++ b/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))
+}
diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/common_test.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/common_test.go
new file mode 100644
index 000000000..39b7525b3
--- /dev/null
+++ b/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/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)
+}
diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/config.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/config.go
new file mode 100644
index 000000000..ee1ab07b3
--- /dev/null
+++ b/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: " "}
+}
diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/doc.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/doc.go
new file mode 100644
index 000000000..5be0c4060
--- /dev/null
+++ b/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
diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dump.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dump.go
new file mode 100644
index 000000000..a0ff95e27
--- /dev/null
+++ b/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...)
+}
diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dump_test.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dump_test.go
new file mode 100644
index 000000000..2b320401d
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dump_test.go
@@ -0,0 +1,1042 @@
+/*
+ * 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.
+ */
+
+/*
+Test Summary:
+NOTE: For each test, a nil pointer, a single pointer and double pointer to the
+base test element are also tested to ensure proper indirection across all types.
+
+- Max int8, int16, int32, int64, int
+- Max uint8, uint16, uint32, uint64, uint
+- Boolean true and false
+- Standard complex64 and complex128
+- Array containing standard ints
+- Array containing type with custom formatter on pointer receiver only
+- Array containing interfaces
+- Array containing bytes
+- Slice containing standard float32 values
+- Slice containing type with custom formatter on pointer receiver only
+- Slice containing interfaces
+- Slice containing bytes
+- Nil slice
+- Standard string
+- Nil interface
+- Sub-interface
+- Map with string keys and int vals
+- Map with custom formatter type on pointer receiver only keys and vals
+- Map with interface keys and values
+- Map with nil interface value
+- Struct with primitives
+- Struct that contains another struct
+- Struct that contains custom type with Stringer pointer interface via both
+ exported and unexported fields
+- Struct that contains embedded struct and field to same struct
+- Uintptr to 0 (null pointer)
+- Uintptr address of real variable
+- Unsafe.Pointer to 0 (null pointer)
+- Unsafe.Pointer to address of real variable
+- Nil channel
+- Standard int channel
+- Function with no params and no returns
+- Function with param and no returns
+- Function with multiple params and multiple returns
+- Struct that is circular through self referencing
+- Structs that are circular through cross referencing
+- Structs that are indirectly circular
+- Type that panics in its Stringer interface
+*/
+
+package spew_test
+
+import (
+ "bytes"
+ "fmt"
+ "testing"
+ "unsafe"
+
+ "github.com/davecgh/go-spew/spew"
+)
+
+// dumpTest is used to describe a test to be perfomed against the Dump method.
+type dumpTest struct {
+ in interface{}
+ wants []string
+}
+
+// dumpTests houses all of the tests to be performed against the Dump method.
+var dumpTests = make([]dumpTest, 0)
+
+// addDumpTest is a helper method to append the passed input and desired result
+// to dumpTests
+func addDumpTest(in interface{}, wants ...string) {
+ test := dumpTest{in, wants}
+ dumpTests = append(dumpTests, test)
+}
+
+func addIntDumpTests() {
+ // Max int8.
+ v := int8(127)
+ nv := (*int8)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "int8"
+ vs := "127"
+ addDumpTest(v, "("+vt+") "+vs+"\n")
+ addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
+ addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
+ addDumpTest(nv, "(*"+vt+")(<nil>)\n")
+
+ // Max int16.
+ v2 := int16(32767)
+ nv2 := (*int16)(nil)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "int16"
+ v2s := "32767"
+ addDumpTest(v2, "("+v2t+") "+v2s+"\n")
+ addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
+ addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
+ addDumpTest(nv2, "(*"+v2t+")(<nil>)\n")
+
+ // Max int32.
+ v3 := int32(2147483647)
+ nv3 := (*int32)(nil)
+ pv3 := &v3
+ v3Addr := fmt.Sprintf("%p", pv3)
+ pv3Addr := fmt.Sprintf("%p", &pv3)
+ v3t := "int32"
+ v3s := "2147483647"
+ addDumpTest(v3, "("+v3t+") "+v3s+"\n")
+ addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n")
+ addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n")
+ addDumpTest(nv3, "(*"+v3t+")(<nil>)\n")
+
+ // Max int64.
+ v4 := int64(9223372036854775807)
+ nv4 := (*int64)(nil)
+ pv4 := &v4
+ v4Addr := fmt.Sprintf("%p", pv4)
+ pv4Addr := fmt.Sprintf("%p", &pv4)
+ v4t := "int64"
+ v4s := "9223372036854775807"
+ addDumpTest(v4, "("+v4t+") "+v4s+"\n")
+ addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n")
+ addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n")
+ addDumpTest(nv4, "(*"+v4t+")(<nil>)\n")
+
+ // Max int.
+ v5 := int(2147483647)
+ nv5 := (*int)(nil)
+ pv5 := &v5
+ v5Addr := fmt.Sprintf("%p", pv5)
+ pv5Addr := fmt.Sprintf("%p", &pv5)
+ v5t := "int"
+ v5s := "2147483647"
+ addDumpTest(v5, "("+v5t+") "+v5s+"\n")
+ addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n")
+ addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n")
+ addDumpTest(nv5, "(*"+v5t+")(<nil>)\n")
+}
+
+func addUintDumpTests() {
+ // Max uint8.
+ v := uint8(255)
+ nv := (*uint8)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "uint8"
+ vs := "255"
+ addDumpTest(v, "("+vt+") "+vs+"\n")
+ addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
+ addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
+ addDumpTest(nv, "(*"+vt+")(<nil>)\n")
+
+ // Max uint16.
+ v2 := uint16(65535)
+ nv2 := (*uint16)(nil)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "uint16"
+ v2s := "65535"
+ addDumpTest(v2, "("+v2t+") "+v2s+"\n")
+ addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
+ addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
+ addDumpTest(nv2, "(*"+v2t+")(<nil>)\n")
+
+ // Max uint32.
+ v3 := uint32(4294967295)
+ nv3 := (*uint32)(nil)
+ pv3 := &v3
+ v3Addr := fmt.Sprintf("%p", pv3)
+ pv3Addr := fmt.Sprintf("%p", &pv3)
+ v3t := "uint32"
+ v3s := "4294967295"
+ addDumpTest(v3, "("+v3t+") "+v3s+"\n")
+ addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n")
+ addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n")
+ addDumpTest(nv3, "(*"+v3t+")(<nil>)\n")
+
+ // Max uint64.
+ v4 := uint64(18446744073709551615)
+ nv4 := (*uint64)(nil)
+ pv4 := &v4
+ v4Addr := fmt.Sprintf("%p", pv4)
+ pv4Addr := fmt.Sprintf("%p", &pv4)
+ v4t := "uint64"
+ v4s := "18446744073709551615"
+ addDumpTest(v4, "("+v4t+") "+v4s+"\n")
+ addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n")
+ addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n")
+ addDumpTest(nv4, "(*"+v4t+")(<nil>)\n")
+
+ // Max uint.
+ v5 := uint(4294967295)
+ nv5 := (*uint)(nil)
+ pv5 := &v5
+ v5Addr := fmt.Sprintf("%p", pv5)
+ pv5Addr := fmt.Sprintf("%p", &pv5)
+ v5t := "uint"
+ v5s := "4294967295"
+ addDumpTest(v5, "("+v5t+") "+v5s+"\n")
+ addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n")
+ addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n")
+ addDumpTest(nv5, "(*"+v5t+")(<nil>)\n")
+}
+
+func addBoolDumpTests() {
+ // Boolean true.
+ v := bool(true)
+ nv := (*bool)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "bool"
+ vs := "true"
+ addDumpTest(v, "("+vt+") "+vs+"\n")
+ addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
+ addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
+ addDumpTest(nv, "(*"+vt+")(<nil>)\n")
+
+ // Boolean false.
+ v2 := bool(false)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "bool"
+ v2s := "false"
+ addDumpTest(v2, "("+v2t+") "+v2s+"\n")
+ addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
+ addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
+}
+
+func addFloatDumpTests() {
+ // Standard float32.
+ v := float32(3.1415)
+ nv := (*float32)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "float32"
+ vs := "3.1415"
+ addDumpTest(v, "("+vt+") "+vs+"\n")
+ addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
+ addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
+ addDumpTest(nv, "(*"+vt+")(<nil>)\n")
+
+ // Standard float64.
+ v2 := float64(3.1415926)
+ nv2 := (*float64)(nil)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "float64"
+ v2s := "3.1415926"
+ addDumpTest(v2, "("+v2t+") "+v2s+"\n")
+ addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
+ addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
+ addDumpTest(nv2, "(*"+v2t+")(<nil>)\n")
+}
+
+func addComplexDumpTests() {
+ // Standard complex64.
+ v := complex(float32(6), -2)
+ nv := (*complex64)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "complex64"
+ vs := "(6-2i)"
+ addDumpTest(v, "("+vt+") "+vs+"\n")
+ addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
+ addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
+ addDumpTest(nv, "(*"+vt+")(<nil>)\n")
+
+ // Standard complex128.
+ v2 := complex(float64(-6), 2)
+ nv2 := (*complex128)(nil)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "complex128"
+ v2s := "(-6+2i)"
+ addDumpTest(v2, "("+v2t+") "+v2s+"\n")
+ addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
+ addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
+ addDumpTest(nv2, "(*"+v2t+")(<nil>)\n")
+}
+
+func addArrayDumpTests() {
+ // Array containing standard ints.
+ v := [3]int{1, 2, 3}
+ vLen := fmt.Sprintf("%d", len(v))
+ vCap := fmt.Sprintf("%d", cap(v))
+ nv := (*[3]int)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "int"
+ vs := "(len=" + vLen + " cap=" + vCap + ") {\n (" + vt + ") 1,\n (" +
+ vt + ") 2,\n (" + vt + ") 3\n}"
+ addDumpTest(v, "([3]"+vt+") "+vs+"\n")
+ addDumpTest(pv, "(*[3]"+vt+")("+vAddr+")("+vs+")\n")
+ addDumpTest(&pv, "(**[3]"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
+ addDumpTest(nv, "(*[3]"+vt+")(<nil>)\n")
+
+ // Array containing type with custom formatter on pointer receiver only.
+ v2i0 := pstringer("1")
+ v2i1 := pstringer("2")
+ v2i2 := pstringer("3")
+ v2 := [3]pstringer{v2i0, v2i1, v2i2}
+ v2i0Len := fmt.Sprintf("%d", len(v2i0))
+ v2i1Len := fmt.Sprintf("%d", len(v2i1))
+ v2i2Len := fmt.Sprintf("%d", len(v2i2))
+ v2Len := fmt.Sprintf("%d", len(v2))
+ v2Cap := fmt.Sprintf("%d", cap(v2))
+ nv2 := (*[3]pstringer)(nil)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "spew_test.pstringer"
+ v2sp := "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t +
+ ") (len=" + v2i0Len + ") stringer 1,\n (" + v2t +
+ ") (len=" + v2i1Len + ") stringer 2,\n (" + v2t +
+ ") (len=" + v2i2Len + ") " + "stringer 3\n}"
+ v2s := v2sp
+ if spew.UnsafeDisabled {
+ v2s = "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t +
+ ") (len=" + v2i0Len + ") \"1\",\n (" + v2t + ") (len=" +
+ v2i1Len + ") \"2\",\n (" + v2t + ") (len=" + v2i2Len +
+ ") " + "\"3\"\n}"
+ }
+ addDumpTest(v2, "([3]"+v2t+") "+v2s+"\n")
+ addDumpTest(pv2, "(*[3]"+v2t+")("+v2Addr+")("+v2sp+")\n")
+ addDumpTest(&pv2, "(**[3]"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2sp+")\n")
+ addDumpTest(nv2, "(*[3]"+v2t+")(<nil>)\n")
+
+ // Array containing interfaces.
+ v3i0 := "one"
+ v3 := [3]interface{}{v3i0, int(2), uint(3)}
+ v3i0Len := fmt.Sprintf("%d", len(v3i0))
+ v3Len := fmt.Sprintf("%d", len(v3))
+ v3Cap := fmt.Sprintf("%d", cap(v3))
+ nv3 := (*[3]interface{})(nil)
+ pv3 := &v3
+ v3Addr := fmt.Sprintf("%p", pv3)
+ pv3Addr := fmt.Sprintf("%p", &pv3)
+ v3t := "[3]interface {}"
+ v3t2 := "string"
+ v3t3 := "int"
+ v3t4 := "uint"
+ v3s := "(len=" + v3Len + " cap=" + v3Cap + ") {\n (" + v3t2 + ") " +
+ "(len=" + v3i0Len + ") \"one\",\n (" + v3t3 + ") 2,\n (" +
+ v3t4 + ") 3\n}"
+ addDumpTest(v3, "("+v3t+") "+v3s+"\n")
+ addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n")
+ addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n")
+ addDumpTest(nv3, "(*"+v3t+")(<nil>)\n")
+
+ // Array containing bytes.
+ v4 := [34]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,
+ }
+ v4Len := fmt.Sprintf("%d", len(v4))
+ v4Cap := fmt.Sprintf("%d", cap(v4))
+ nv4 := (*[34]byte)(nil)
+ pv4 := &v4
+ v4Addr := fmt.Sprintf("%p", pv4)
+ pv4Addr := fmt.Sprintf("%p", &pv4)
+ v4t := "[34]uint8"
+ v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " +
+ "{\n 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20" +
+ " |............... |\n" +
+ " 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30" +
+ " |!\"#$%&'()*+,-./0|\n" +
+ " 00000020 31 32 " +
+ " |12|\n}"
+ addDumpTest(v4, "("+v4t+") "+v4s+"\n")
+ addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n")
+ addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n")
+ addDumpTest(nv4, "(*"+v4t+")(<nil>)\n")
+}
+
+func addSliceDumpTests() {
+ // Slice containing standard float32 values.
+ v := []float32{3.14, 6.28, 12.56}
+ vLen := fmt.Sprintf("%d", len(v))
+ vCap := fmt.Sprintf("%d", cap(v))
+ nv := (*[]float32)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "float32"
+ vs := "(len=" + vLen + " cap=" + vCap + ") {\n (" + vt + ") 3.14,\n (" +
+ vt + ") 6.28,\n (" + vt + ") 12.56\n}"
+ addDumpTest(v, "([]"+vt+") "+vs+"\n")
+ addDumpTest(pv, "(*[]"+vt+")("+vAddr+")("+vs+")\n")
+ addDumpTest(&pv, "(**[]"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
+ addDumpTest(nv, "(*[]"+vt+")(<nil>)\n")
+
+ // Slice containing type with custom formatter on pointer receiver only.
+ v2i0 := pstringer("1")
+ v2i1 := pstringer("2")
+ v2i2 := pstringer("3")
+ v2 := []pstringer{v2i0, v2i1, v2i2}
+ v2i0Len := fmt.Sprintf("%d", len(v2i0))
+ v2i1Len := fmt.Sprintf("%d", len(v2i1))
+ v2i2Len := fmt.Sprintf("%d", len(v2i2))
+ v2Len := fmt.Sprintf("%d", len(v2))
+ v2Cap := fmt.Sprintf("%d", cap(v2))
+ nv2 := (*[]pstringer)(nil)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "spew_test.pstringer"
+ v2s := "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t + ") (len=" +
+ v2i0Len + ") stringer 1,\n (" + v2t + ") (len=" + v2i1Len +
+ ") stringer 2,\n (" + v2t + ") (len=" + v2i2Len + ") " +
+ "stringer 3\n}"
+ addDumpTest(v2, "([]"+v2t+") "+v2s+"\n")
+ addDumpTest(pv2, "(*[]"+v2t+")("+v2Addr+")("+v2s+")\n")
+ addDumpTest(&pv2, "(**[]"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
+ addDumpTest(nv2, "(*[]"+v2t+")(<nil>)\n")
+
+ // Slice containing interfaces.
+ v3i0 := "one"
+ v3 := []interface{}{v3i0, int(2), uint(3), nil}
+ v3i0Len := fmt.Sprintf("%d", len(v3i0))
+ v3Len := fmt.Sprintf("%d", len(v3))
+ v3Cap := fmt.Sprintf("%d", cap(v3))
+ nv3 := (*[]interface{})(nil)
+ pv3 := &v3
+ v3Addr := fmt.Sprintf("%p", pv3)
+ pv3Addr := fmt.Sprintf("%p", &pv3)
+ v3t := "[]interface {}"
+ v3t2 := "string"
+ v3t3 := "int"
+ v3t4 := "uint"
+ v3t5 := "interface {}"
+ v3s := "(len=" + v3Len + " cap=" + v3Cap + ") {\n (" + v3t2 + ") " +
+ "(len=" + v3i0Len + ") \"one\",\n (" + v3t3 + ") 2,\n (" +
+ v3t4 + ") 3,\n (" + v3t5 + ") <nil>\n}"
+ addDumpTest(v3, "("+v3t+") "+v3s+"\n")
+ addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n")
+ addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n")
+ addDumpTest(nv3, "(*"+v3t+")(<nil>)\n")
+
+ // Slice containing bytes.
+ v4 := []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,
+ }
+ v4Len := fmt.Sprintf("%d", len(v4))
+ v4Cap := fmt.Sprintf("%d", cap(v4))
+ nv4 := (*[]byte)(nil)
+ pv4 := &v4
+ v4Addr := fmt.Sprintf("%p", pv4)
+ pv4Addr := fmt.Sprintf("%p", &pv4)
+ v4t := "[]uint8"
+ v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " +
+ "{\n 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20" +
+ " |............... |\n" +
+ " 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30" +
+ " |!\"#$%&'()*+,-./0|\n" +
+ " 00000020 31 32 " +
+ " |12|\n}"
+ addDumpTest(v4, "("+v4t+") "+v4s+"\n")
+ addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n")
+ addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n")
+ addDumpTest(nv4, "(*"+v4t+")(<nil>)\n")
+
+ // Nil slice.
+ v5 := []int(nil)
+ nv5 := (*[]int)(nil)
+ pv5 := &v5
+ v5Addr := fmt.Sprintf("%p", pv5)
+ pv5Addr := fmt.Sprintf("%p", &pv5)
+ v5t := "[]int"
+ v5s := "<nil>"
+ addDumpTest(v5, "("+v5t+") "+v5s+"\n")
+ addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n")
+ addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n")
+ addDumpTest(nv5, "(*"+v5t+")(<nil>)\n")
+}
+
+func addStringDumpTests() {
+ // Standard string.
+ v := "test"
+ vLen := fmt.Sprintf("%d", len(v))
+ nv := (*string)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "string"
+ vs := "(len=" + vLen + ") \"test\""
+ addDumpTest(v, "("+vt+") "+vs+"\n")
+ addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
+ addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
+ addDumpTest(nv, "(*"+vt+")(<nil>)\n")
+}
+
+func addInterfaceDumpTests() {
+ // Nil interface.
+ var v interface{}
+ nv := (*interface{})(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "interface {}"
+ vs := "<nil>"
+ addDumpTest(v, "("+vt+") "+vs+"\n")
+ addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
+ addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
+ addDumpTest(nv, "(*"+vt+")(<nil>)\n")
+
+ // Sub-interface.
+ v2 := interface{}(uint16(65535))
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "uint16"
+ v2s := "65535"
+ addDumpTest(v2, "("+v2t+") "+v2s+"\n")
+ addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
+ addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
+}
+
+func addMapDumpTests() {
+ // Map with string keys and int vals.
+ k := "one"
+ kk := "two"
+ m := map[string]int{k: 1, kk: 2}
+ klen := fmt.Sprintf("%d", len(k)) // not kLen to shut golint up
+ kkLen := fmt.Sprintf("%d", len(kk))
+ mLen := fmt.Sprintf("%d", len(m))
+ nilMap := map[string]int(nil)
+ nm := (*map[string]int)(nil)
+ pm := &m
+ mAddr := fmt.Sprintf("%p", pm)
+ pmAddr := fmt.Sprintf("%p", &pm)
+ mt := "map[string]int"
+ mt1 := "string"
+ mt2 := "int"
+ ms := "(len=" + mLen + ") {\n (" + mt1 + ") (len=" + klen + ") " +
+ "\"one\": (" + mt2 + ") 1,\n (" + mt1 + ") (len=" + kkLen +
+ ") \"two\": (" + mt2 + ") 2\n}"
+ ms2 := "(len=" + mLen + ") {\n (" + mt1 + ") (len=" + kkLen + ") " +
+ "\"two\": (" + mt2 + ") 2,\n (" + mt1 + ") (len=" + klen +
+ ") \"one\": (" + mt2 + ") 1\n}"
+ addDumpTest(m, "("+mt+") "+ms+"\n", "("+mt+") "+ms2+"\n")
+ addDumpTest(pm, "(*"+mt+")("+mAddr+")("+ms+")\n",
+ "(*"+mt+")("+mAddr+")("+ms2+")\n")
+ addDumpTest(&pm, "(**"+mt+")("+pmAddr+"->"+mAddr+")("+ms+")\n",
+ "(**"+mt+")("+pmAddr+"->"+mAddr+")("+ms2+")\n")
+ addDumpTest(nm, "(*"+mt+")(<nil>)\n")
+ addDumpTest(nilMap, "("+mt+") <nil>\n")
+
+ // Map with custom formatter type on pointer receiver only keys and vals.
+ k2 := pstringer("one")
+ v2 := pstringer("1")
+ m2 := map[pstringer]pstringer{k2: v2}
+ k2Len := fmt.Sprintf("%d", len(k2))
+ v2Len := fmt.Sprintf("%d", len(v2))
+ m2Len := fmt.Sprintf("%d", len(m2))
+ nilMap2 := map[pstringer]pstringer(nil)
+ nm2 := (*map[pstringer]pstringer)(nil)
+ pm2 := &m2
+ m2Addr := fmt.Sprintf("%p", pm2)
+ pm2Addr := fmt.Sprintf("%p", &pm2)
+ m2t := "map[spew_test.pstringer]spew_test.pstringer"
+ m2t1 := "spew_test.pstringer"
+ m2t2 := "spew_test.pstringer"
+ m2s := "(len=" + m2Len + ") {\n (" + m2t1 + ") (len=" + k2Len + ") " +
+ "stringer one: (" + m2t2 + ") (len=" + v2Len + ") stringer 1\n}"
+ if spew.UnsafeDisabled {
+ m2s = "(len=" + m2Len + ") {\n (" + m2t1 + ") (len=" + k2Len +
+ ") " + "\"one\": (" + m2t2 + ") (len=" + v2Len +
+ ") \"1\"\n}"
+ }
+ addDumpTest(m2, "("+m2t+") "+m2s+"\n")
+ addDumpTest(pm2, "(*"+m2t+")("+m2Addr+")("+m2s+")\n")
+ addDumpTest(&pm2, "(**"+m2t+")("+pm2Addr+"->"+m2Addr+")("+m2s+")\n")
+ addDumpTest(nm2, "(*"+m2t+")(<nil>)\n")
+ addDumpTest(nilMap2, "("+m2t+") <nil>\n")
+
+ // Map with interface keys and values.
+ k3 := "one"
+ k3Len := fmt.Sprintf("%d", len(k3))
+ m3 := map[interface{}]interface{}{k3: 1}
+ m3Len := fmt.Sprintf("%d", len(m3))
+ nilMap3 := map[interface{}]interface{}(nil)
+ nm3 := (*map[interface{}]interface{})(nil)
+ pm3 := &m3
+ m3Addr := fmt.Sprintf("%p", pm3)
+ pm3Addr := fmt.Sprintf("%p", &pm3)
+ m3t := "map[interface {}]interface {}"
+ m3t1 := "string"
+ m3t2 := "int"
+ m3s := "(len=" + m3Len + ") {\n (" + m3t1 + ") (len=" + k3Len + ") " +
+ "\"one\": (" + m3t2 + ") 1\n}"
+ addDumpTest(m3, "("+m3t+") "+m3s+"\n")
+ addDumpTest(pm3, "(*"+m3t+")("+m3Addr+")("+m3s+")\n")
+ addDumpTest(&pm3, "(**"+m3t+")("+pm3Addr+"->"+m3Addr+")("+m3s+")\n")
+ addDumpTest(nm3, "(*"+m3t+")(<nil>)\n")
+ addDumpTest(nilMap3, "("+m3t+") <nil>\n")
+
+ // Map with nil interface value.
+ k4 := "nil"
+ k4Len := fmt.Sprintf("%d", len(k4))
+ m4 := map[string]interface{}{k4: nil}
+ m4Len := fmt.Sprintf("%d", len(m4))
+ nilMap4 := map[string]interface{}(nil)
+ nm4 := (*map[string]interface{})(nil)
+ pm4 := &m4
+ m4Addr := fmt.Sprintf("%p", pm4)
+ pm4Addr := fmt.Sprintf("%p", &pm4)
+ m4t := "map[string]interface {}"
+ m4t1 := "string"
+ m4t2 := "interface {}"
+ m4s := "(len=" + m4Len + ") {\n (" + m4t1 + ") (len=" + k4Len + ")" +
+ " \"nil\": (" + m4t2 + ") <nil>\n}"
+ addDumpTest(m4, "("+m4t+") "+m4s+"\n")
+ addDumpTest(pm4, "(*"+m4t+")("+m4Addr+")("+m4s+")\n")
+ addDumpTest(&pm4, "(**"+m4t+")("+pm4Addr+"->"+m4Addr+")("+m4s+")\n")
+ addDumpTest(nm4, "(*"+m4t+")(<nil>)\n")
+ addDumpTest(nilMap4, "("+m4t+") <nil>\n")
+}
+
+func addStructDumpTests() {
+ // Struct with primitives.
+ type s1 struct {
+ a int8
+ b uint8
+ }
+ v := s1{127, 255}
+ nv := (*s1)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "spew_test.s1"
+ vt2 := "int8"
+ vt3 := "uint8"
+ vs := "{\n a: (" + vt2 + ") 127,\n b: (" + vt3 + ") 255\n}"
+ addDumpTest(v, "("+vt+") "+vs+"\n")
+ addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
+ addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
+ addDumpTest(nv, "(*"+vt+")(<nil>)\n")
+
+ // Struct that contains another struct.
+ type s2 struct {
+ s1 s1
+ b bool
+ }
+ v2 := s2{s1{127, 255}, true}
+ nv2 := (*s2)(nil)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "spew_test.s2"
+ v2t2 := "spew_test.s1"
+ v2t3 := "int8"
+ v2t4 := "uint8"
+ v2t5 := "bool"
+ v2s := "{\n s1: (" + v2t2 + ") {\n a: (" + v2t3 + ") 127,\n b: (" +
+ v2t4 + ") 255\n },\n b: (" + v2t5 + ") true\n}"
+ addDumpTest(v2, "("+v2t+") "+v2s+"\n")
+ addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
+ addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
+ addDumpTest(nv2, "(*"+v2t+")(<nil>)\n")
+
+ // Struct that contains custom type with Stringer pointer interface via both
+ // exported and unexported fields.
+ type s3 struct {
+ s pstringer
+ S pstringer
+ }
+ v3 := s3{"test", "test2"}
+ nv3 := (*s3)(nil)
+ pv3 := &v3
+ v3Addr := fmt.Sprintf("%p", pv3)
+ pv3Addr := fmt.Sprintf("%p", &pv3)
+ v3t := "spew_test.s3"
+ v3t2 := "spew_test.pstringer"
+ v3s := "{\n s: (" + v3t2 + ") (len=4) stringer test,\n S: (" + v3t2 +
+ ") (len=5) stringer test2\n}"
+ v3sp := v3s
+ if spew.UnsafeDisabled {
+ v3s = "{\n s: (" + v3t2 + ") (len=4) \"test\",\n S: (" +
+ v3t2 + ") (len=5) \"test2\"\n}"
+ v3sp = "{\n s: (" + v3t2 + ") (len=4) \"test\",\n S: (" +
+ v3t2 + ") (len=5) stringer test2\n}"
+ }
+ addDumpTest(v3, "("+v3t+") "+v3s+"\n")
+ addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3sp+")\n")
+ addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3sp+")\n")
+ addDumpTest(nv3, "(*"+v3t+")(<nil>)\n")
+
+ // Struct that contains embedded struct and field to same struct.
+ e := embed{"embedstr"}
+ eLen := fmt.Sprintf("%d", len("embedstr"))
+ v4 := embedwrap{embed: &e, e: &e}
+ nv4 := (*embedwrap)(nil)
+ pv4 := &v4
+ eAddr := fmt.Sprintf("%p", &e)
+ v4Addr := fmt.Sprintf("%p", pv4)
+ pv4Addr := fmt.Sprintf("%p", &pv4)
+ v4t := "spew_test.embedwrap"
+ v4t2 := "spew_test.embed"
+ v4t3 := "string"
+ v4s := "{\n embed: (*" + v4t2 + ")(" + eAddr + ")({\n a: (" + v4t3 +
+ ") (len=" + eLen + ") \"embedstr\"\n }),\n e: (*" + v4t2 +
+ ")(" + eAddr + ")({\n a: (" + v4t3 + ") (len=" + eLen + ")" +
+ " \"embedstr\"\n })\n}"
+ addDumpTest(v4, "("+v4t+") "+v4s+"\n")
+ addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n")
+ addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n")
+ addDumpTest(nv4, "(*"+v4t+")(<nil>)\n")
+}
+
+func addUintptrDumpTests() {
+ // Null pointer.
+ v := uintptr(0)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "uintptr"
+ vs := "<nil>"
+ addDumpTest(v, "("+vt+") "+vs+"\n")
+ addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
+ addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
+
+ // Address of real variable.
+ i := 1
+ v2 := uintptr(unsafe.Pointer(&i))
+ nv2 := (*uintptr)(nil)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "uintptr"
+ v2s := fmt.Sprintf("%p", &i)
+ addDumpTest(v2, "("+v2t+") "+v2s+"\n")
+ addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
+ addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
+ addDumpTest(nv2, "(*"+v2t+")(<nil>)\n")
+}
+
+func addUnsafePointerDumpTests() {
+ // Null pointer.
+ v := unsafe.Pointer(uintptr(0))
+ nv := (*unsafe.Pointer)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "unsafe.Pointer"
+ vs := "<nil>"
+ addDumpTest(v, "("+vt+") "+vs+"\n")
+ addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
+ addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
+ addDumpTest(nv, "(*"+vt+")(<nil>)\n")
+
+ // Address of real variable.
+ i := 1
+ v2 := unsafe.Pointer(&i)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "unsafe.Pointer"
+ v2s := fmt.Sprintf("%p", &i)
+ addDumpTest(v2, "("+v2t+") "+v2s+"\n")
+ addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
+ addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
+ addDumpTest(nv, "(*"+vt+")(<nil>)\n")
+}
+
+func addChanDumpTests() {
+ // Nil channel.
+ var v chan int
+ pv := &v
+ nv := (*chan int)(nil)
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "chan int"
+ vs := "<nil>"
+ addDumpTest(v, "("+vt+") "+vs+"\n")
+ addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
+ addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
+ addDumpTest(nv, "(*"+vt+")(<nil>)\n")
+
+ // Real channel.
+ v2 := make(chan int)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "chan int"
+ v2s := fmt.Sprintf("%p", v2)
+ addDumpTest(v2, "("+v2t+") "+v2s+"\n")
+ addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
+ addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
+}
+
+func addFuncDumpTests() {
+ // Function with no params and no returns.
+ v := addIntDumpTests
+ nv := (*func())(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "func()"
+ vs := fmt.Sprintf("%p", v)
+ addDumpTest(v, "("+vt+") "+vs+"\n")
+ addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
+ addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
+ addDumpTest(nv, "(*"+vt+")(<nil>)\n")
+
+ // Function with param and no returns.
+ v2 := TestDump
+ nv2 := (*func(*testing.T))(nil)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "func(*testing.T)"
+ v2s := fmt.Sprintf("%p", v2)
+ addDumpTest(v2, "("+v2t+") "+v2s+"\n")
+ addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
+ addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
+ addDumpTest(nv2, "(*"+v2t+")(<nil>)\n")
+
+ // Function with multiple params and multiple returns.
+ var v3 = func(i int, s string) (b bool, err error) {
+ return true, nil
+ }
+ nv3 := (*func(int, string) (bool, error))(nil)
+ pv3 := &v3
+ v3Addr := fmt.Sprintf("%p", pv3)
+ pv3Addr := fmt.Sprintf("%p", &pv3)
+ v3t := "func(int, string) (bool, error)"
+ v3s := fmt.Sprintf("%p", v3)
+ addDumpTest(v3, "("+v3t+") "+v3s+"\n")
+ addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n")
+ addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n")
+ addDumpTest(nv3, "(*"+v3t+")(<nil>)\n")
+}
+
+func addCircularDumpTests() {
+ // Struct that is circular through self referencing.
+ type circular struct {
+ c *circular
+ }
+ v := circular{nil}
+ v.c = &v
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "spew_test.circular"
+ vs := "{\n c: (*" + vt + ")(" + vAddr + ")({\n c: (*" + vt + ")(" +
+ vAddr + ")(<already shown>)\n })\n}"
+ vs2 := "{\n c: (*" + vt + ")(" + vAddr + ")(<already shown>)\n}"
+ addDumpTest(v, "("+vt+") "+vs+"\n")
+ addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs2+")\n")
+ addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs2+")\n")
+
+ // Structs that are circular through cross referencing.
+ v2 := xref1{nil}
+ ts2 := xref2{&v2}
+ v2.ps2 = &ts2
+ pv2 := &v2
+ ts2Addr := fmt.Sprintf("%p", &ts2)
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "spew_test.xref1"
+ v2t2 := "spew_test.xref2"
+ v2s := "{\n ps2: (*" + v2t2 + ")(" + ts2Addr + ")({\n ps1: (*" + v2t +
+ ")(" + v2Addr + ")({\n ps2: (*" + v2t2 + ")(" + ts2Addr +
+ ")(<already shown>)\n })\n })\n}"
+ v2s2 := "{\n ps2: (*" + v2t2 + ")(" + ts2Addr + ")({\n ps1: (*" + v2t +
+ ")(" + v2Addr + ")(<already shown>)\n })\n}"
+ addDumpTest(v2, "("+v2t+") "+v2s+"\n")
+ addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s2+")\n")
+ addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s2+")\n")
+
+ // Structs that are indirectly circular.
+ v3 := indirCir1{nil}
+ tic2 := indirCir2{nil}
+ tic3 := indirCir3{&v3}
+ tic2.ps3 = &tic3
+ v3.ps2 = &tic2
+ pv3 := &v3
+ tic2Addr := fmt.Sprintf("%p", &tic2)
+ tic3Addr := fmt.Sprintf("%p", &tic3)
+ v3Addr := fmt.Sprintf("%p", pv3)
+ pv3Addr := fmt.Sprintf("%p", &pv3)
+ v3t := "spew_test.indirCir1"
+ v3t2 := "spew_test.indirCir2"
+ v3t3 := "spew_test.indirCir3"
+ v3s := "{\n ps2: (*" + v3t2 + ")(" + tic2Addr + ")({\n ps3: (*" + v3t3 +
+ ")(" + tic3Addr + ")({\n ps1: (*" + v3t + ")(" + v3Addr +
+ ")({\n ps2: (*" + v3t2 + ")(" + tic2Addr +
+ ")(<already shown>)\n })\n })\n })\n}"
+ v3s2 := "{\n ps2: (*" + v3t2 + ")(" + tic2Addr + ")({\n ps3: (*" + v3t3 +
+ ")(" + tic3Addr + ")({\n ps1: (*" + v3t + ")(" + v3Addr +
+ ")(<already shown>)\n })\n })\n}"
+ addDumpTest(v3, "("+v3t+") "+v3s+"\n")
+ addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s2+")\n")
+ addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s2+")\n")
+}
+
+func addPanicDumpTests() {
+ // Type that panics in its Stringer interface.
+ v := panicer(127)
+ nv := (*panicer)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "spew_test.panicer"
+ vs := "(PANIC=test panic)127"
+ addDumpTest(v, "("+vt+") "+vs+"\n")
+ addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
+ addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
+ addDumpTest(nv, "(*"+vt+")(<nil>)\n")
+}
+
+func addErrorDumpTests() {
+ // Type that has a custom Error interface.
+ v := customError(127)
+ nv := (*customError)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "spew_test.customError"
+ vs := "error: 127"
+ addDumpTest(v, "("+vt+") "+vs+"\n")
+ addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
+ addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
+ addDumpTest(nv, "(*"+vt+")(<nil>)\n")
+}
+
+// TestDump executes all of the tests described by dumpTests.
+func TestDump(t *testing.T) {
+ // Setup tests.
+ addIntDumpTests()
+ addUintDumpTests()
+ addBoolDumpTests()
+ addFloatDumpTests()
+ addComplexDumpTests()
+ addArrayDumpTests()
+ addSliceDumpTests()
+ addStringDumpTests()
+ addInterfaceDumpTests()
+ addMapDumpTests()
+ addStructDumpTests()
+ addUintptrDumpTests()
+ addUnsafePointerDumpTests()
+ addChanDumpTests()
+ addFuncDumpTests()
+ addCircularDumpTests()
+ addPanicDumpTests()
+ addErrorDumpTests()
+ addCgoDumpTests()
+
+ t.Logf("Running %d tests", len(dumpTests))
+ for i, test := range dumpTests {
+ buf := new(bytes.Buffer)
+ spew.Fdump(buf, test.in)
+ s := buf.String()
+ if testFailed(s, test.wants) {
+ t.Errorf("Dump #%d\n got: %s %s", i, s, stringizeWants(test.wants))
+ continue
+ }
+ }
+}
+
+func TestDumpSortedKeys(t *testing.T) {
+ cfg := spew.ConfigState{SortKeys: true}
+ s := cfg.Sdump(map[int]string{1: "1", 3: "3", 2: "2"})
+ expected := "(map[int]string) (len=3) {\n(int) 1: (string) (len=1) " +
+ "\"1\",\n(int) 2: (string) (len=1) \"2\",\n(int) 3: (string) " +
+ "(len=1) \"3\"\n" +
+ "}\n"
+ if s != expected {
+ t.Errorf("Sorted keys mismatch:\n %v %v", s, expected)
+ }
+
+ s = cfg.Sdump(map[stringer]int{"1": 1, "3": 3, "2": 2})
+ expected = "(map[spew_test.stringer]int) (len=3) {\n" +
+ "(spew_test.stringer) (len=1) stringer 1: (int) 1,\n" +
+ "(spew_test.stringer) (len=1) stringer 2: (int) 2,\n" +
+ "(spew_test.stringer) (len=1) stringer 3: (int) 3\n" +
+ "}\n"
+ if s != expected {
+ t.Errorf("Sorted keys mismatch:\n %v %v", s, expected)
+ }
+
+ s = cfg.Sdump(map[pstringer]int{pstringer("1"): 1, pstringer("3"): 3, pstringer("2"): 2})
+ expected = "(map[spew_test.pstringer]int) (len=3) {\n" +
+ "(spew_test.pstringer) (len=1) stringer 1: (int) 1,\n" +
+ "(spew_test.pstringer) (len=1) stringer 2: (int) 2,\n" +
+ "(spew_test.pstringer) (len=1) stringer 3: (int) 3\n" +
+ "}\n"
+ if spew.UnsafeDisabled {
+ expected = "(map[spew_test.pstringer]int) (len=3) {\n" +
+ "(spew_test.pstringer) (len=1) \"1\": (int) 1,\n" +
+ "(spew_test.pstringer) (len=1) \"2\": (int) 2,\n" +
+ "(spew_test.pstringer) (len=1) \"3\": (int) 3\n" +
+ "}\n"
+ }
+ if s != expected {
+ t.Errorf("Sorted keys mismatch:\n %v %v", s, expected)
+ }
+
+ s = cfg.Sdump(map[customError]int{customError(1): 1, customError(3): 3, customError(2): 2})
+ expected = "(map[spew_test.customError]int) (len=3) {\n" +
+ "(spew_test.customError) error: 1: (int) 1,\n" +
+ "(spew_test.customError) error: 2: (int) 2,\n" +
+ "(spew_test.customError) error: 3: (int) 3\n" +
+ "}\n"
+ if s != expected {
+ t.Errorf("Sorted keys mismatch:\n %v %v", s, expected)
+ }
+
+}
diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dumpcgo_test.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dumpcgo_test.go
new file mode 100644
index 000000000..18a38358e
--- /dev/null
+++ b/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/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")
+}
diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dumpnocgo_test.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dumpnocgo_test.go
new file mode 100644
index 000000000..52a0971fb
--- /dev/null
+++ b/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.
+}
diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/example_test.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/example_test.go
new file mode 100644
index 000000000..de6c4e309
--- /dev/null
+++ b/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/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
+}
diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/format.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/format.go
new file mode 100644
index 000000000..ecf3b80e2
--- /dev/null
+++ b/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)
+}
diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/format_test.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/format_test.go
new file mode 100644
index 000000000..b664b3f13
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/format_test.go
@@ -0,0 +1,1558 @@
+/*
+ * 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.
+ */
+
+/*
+Test Summary:
+NOTE: For each test, a nil pointer, a single pointer and double pointer to the
+base test element are also tested to ensure proper indirection across all types.
+
+- Max int8, int16, int32, int64, int
+- Max uint8, uint16, uint32, uint64, uint
+- Boolean true and false
+- Standard complex64 and complex128
+- Array containing standard ints
+- Array containing type with custom formatter on pointer receiver only
+- Array containing interfaces
+- Slice containing standard float32 values
+- Slice containing type with custom formatter on pointer receiver only
+- Slice containing interfaces
+- Nil slice
+- Standard string
+- Nil interface
+- Sub-interface
+- Map with string keys and int vals
+- Map with custom formatter type on pointer receiver only keys and vals
+- Map with interface keys and values
+- Map with nil interface value
+- Struct with primitives
+- Struct that contains another struct
+- Struct that contains custom type with Stringer pointer interface via both
+ exported and unexported fields
+- Struct that contains embedded struct and field to same struct
+- Uintptr to 0 (null pointer)
+- Uintptr address of real variable
+- Unsafe.Pointer to 0 (null pointer)
+- Unsafe.Pointer to address of real variable
+- Nil channel
+- Standard int channel
+- Function with no params and no returns
+- Function with param and no returns
+- Function with multiple params and multiple returns
+- Struct that is circular through self referencing
+- Structs that are circular through cross referencing
+- Structs that are indirectly circular
+- Type that panics in its Stringer interface
+- Type that has a custom Error interface
+- %x passthrough with uint
+- %#x passthrough with uint
+- %f passthrough with precision
+- %f passthrough with width and precision
+- %d passthrough with width
+- %q passthrough with string
+*/
+
+package spew_test
+
+import (
+ "bytes"
+ "fmt"
+ "testing"
+ "unsafe"
+
+ "github.com/davecgh/go-spew/spew"
+)
+
+// formatterTest is used to describe a test to be perfomed against NewFormatter.
+type formatterTest struct {
+ format string
+ in interface{}
+ wants []string
+}
+
+// formatterTests houses all of the tests to be performed against NewFormatter.
+var formatterTests = make([]formatterTest, 0)
+
+// addFormatterTest is a helper method to append the passed input and desired
+// result to formatterTests.
+func addFormatterTest(format string, in interface{}, wants ...string) {
+ test := formatterTest{format, in, wants}
+ formatterTests = append(formatterTests, test)
+}
+
+func addIntFormatterTests() {
+ // Max int8.
+ v := int8(127)
+ nv := (*int8)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "int8"
+ vs := "127"
+ addFormatterTest("%v", v, vs)
+ addFormatterTest("%v", pv, "<*>"+vs)
+ addFormatterTest("%v", &pv, "<**>"+vs)
+ addFormatterTest("%v", nv, "<nil>")
+ addFormatterTest("%+v", v, vs)
+ addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
+ addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%#v", v, "("+vt+")"+vs)
+ addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
+ addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
+ addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
+ addFormatterTest("%#+v", v, "("+vt+")"+vs)
+ addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
+ addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
+
+ // Max int16.
+ v2 := int16(32767)
+ nv2 := (*int16)(nil)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "int16"
+ v2s := "32767"
+ addFormatterTest("%v", v2, v2s)
+ addFormatterTest("%v", pv2, "<*>"+v2s)
+ addFormatterTest("%v", &pv2, "<**>"+v2s)
+ addFormatterTest("%v", nv2, "<nil>")
+ addFormatterTest("%+v", v2, v2s)
+ addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
+ addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
+ addFormatterTest("%+v", nv2, "<nil>")
+ addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
+ addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
+ addFormatterTest("%#v", nv2, "(*"+v2t+")"+"<nil>")
+ addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
+ addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
+ addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"<nil>")
+
+ // Max int32.
+ v3 := int32(2147483647)
+ nv3 := (*int32)(nil)
+ pv3 := &v3
+ v3Addr := fmt.Sprintf("%p", pv3)
+ pv3Addr := fmt.Sprintf("%p", &pv3)
+ v3t := "int32"
+ v3s := "2147483647"
+ addFormatterTest("%v", v3, v3s)
+ addFormatterTest("%v", pv3, "<*>"+v3s)
+ addFormatterTest("%v", &pv3, "<**>"+v3s)
+ addFormatterTest("%v", nv3, "<nil>")
+ addFormatterTest("%+v", v3, v3s)
+ addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s)
+ addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s)
+ addFormatterTest("%+v", nv3, "<nil>")
+ addFormatterTest("%#v", v3, "("+v3t+")"+v3s)
+ addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s)
+ addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s)
+ addFormatterTest("%#v", nv3, "(*"+v3t+")"+"<nil>")
+ addFormatterTest("%#+v", v3, "("+v3t+")"+v3s)
+ addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s)
+ addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s)
+ addFormatterTest("%#v", nv3, "(*"+v3t+")"+"<nil>")
+
+ // Max int64.
+ v4 := int64(9223372036854775807)
+ nv4 := (*int64)(nil)
+ pv4 := &v4
+ v4Addr := fmt.Sprintf("%p", pv4)
+ pv4Addr := fmt.Sprintf("%p", &pv4)
+ v4t := "int64"
+ v4s := "9223372036854775807"
+ addFormatterTest("%v", v4, v4s)
+ addFormatterTest("%v", pv4, "<*>"+v4s)
+ addFormatterTest("%v", &pv4, "<**>"+v4s)
+ addFormatterTest("%v", nv4, "<nil>")
+ addFormatterTest("%+v", v4, v4s)
+ addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s)
+ addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s)
+ addFormatterTest("%+v", nv4, "<nil>")
+ addFormatterTest("%#v", v4, "("+v4t+")"+v4s)
+ addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s)
+ addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s)
+ addFormatterTest("%#v", nv4, "(*"+v4t+")"+"<nil>")
+ addFormatterTest("%#+v", v4, "("+v4t+")"+v4s)
+ addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s)
+ addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s)
+ addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"<nil>")
+
+ // Max int.
+ v5 := int(2147483647)
+ nv5 := (*int)(nil)
+ pv5 := &v5
+ v5Addr := fmt.Sprintf("%p", pv5)
+ pv5Addr := fmt.Sprintf("%p", &pv5)
+ v5t := "int"
+ v5s := "2147483647"
+ addFormatterTest("%v", v5, v5s)
+ addFormatterTest("%v", pv5, "<*>"+v5s)
+ addFormatterTest("%v", &pv5, "<**>"+v5s)
+ addFormatterTest("%v", nv5, "<nil>")
+ addFormatterTest("%+v", v5, v5s)
+ addFormatterTest("%+v", pv5, "<*>("+v5Addr+")"+v5s)
+ addFormatterTest("%+v", &pv5, "<**>("+pv5Addr+"->"+v5Addr+")"+v5s)
+ addFormatterTest("%+v", nv5, "<nil>")
+ addFormatterTest("%#v", v5, "("+v5t+")"+v5s)
+ addFormatterTest("%#v", pv5, "(*"+v5t+")"+v5s)
+ addFormatterTest("%#v", &pv5, "(**"+v5t+")"+v5s)
+ addFormatterTest("%#v", nv5, "(*"+v5t+")"+"<nil>")
+ addFormatterTest("%#+v", v5, "("+v5t+")"+v5s)
+ addFormatterTest("%#+v", pv5, "(*"+v5t+")("+v5Addr+")"+v5s)
+ addFormatterTest("%#+v", &pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")"+v5s)
+ addFormatterTest("%#+v", nv5, "(*"+v5t+")"+"<nil>")
+}
+
+func addUintFormatterTests() {
+ // Max uint8.
+ v := uint8(255)
+ nv := (*uint8)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "uint8"
+ vs := "255"
+ addFormatterTest("%v", v, vs)
+ addFormatterTest("%v", pv, "<*>"+vs)
+ addFormatterTest("%v", &pv, "<**>"+vs)
+ addFormatterTest("%v", nv, "<nil>")
+ addFormatterTest("%+v", v, vs)
+ addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
+ addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%#v", v, "("+vt+")"+vs)
+ addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
+ addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
+ addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
+ addFormatterTest("%#+v", v, "("+vt+")"+vs)
+ addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
+ addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
+
+ // Max uint16.
+ v2 := uint16(65535)
+ nv2 := (*uint16)(nil)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "uint16"
+ v2s := "65535"
+ addFormatterTest("%v", v2, v2s)
+ addFormatterTest("%v", pv2, "<*>"+v2s)
+ addFormatterTest("%v", &pv2, "<**>"+v2s)
+ addFormatterTest("%v", nv2, "<nil>")
+ addFormatterTest("%+v", v2, v2s)
+ addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
+ addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
+ addFormatterTest("%+v", nv2, "<nil>")
+ addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
+ addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
+ addFormatterTest("%#v", nv2, "(*"+v2t+")"+"<nil>")
+ addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
+ addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
+ addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"<nil>")
+
+ // Max uint32.
+ v3 := uint32(4294967295)
+ nv3 := (*uint32)(nil)
+ pv3 := &v3
+ v3Addr := fmt.Sprintf("%p", pv3)
+ pv3Addr := fmt.Sprintf("%p", &pv3)
+ v3t := "uint32"
+ v3s := "4294967295"
+ addFormatterTest("%v", v3, v3s)
+ addFormatterTest("%v", pv3, "<*>"+v3s)
+ addFormatterTest("%v", &pv3, "<**>"+v3s)
+ addFormatterTest("%v", nv3, "<nil>")
+ addFormatterTest("%+v", v3, v3s)
+ addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s)
+ addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s)
+ addFormatterTest("%+v", nv3, "<nil>")
+ addFormatterTest("%#v", v3, "("+v3t+")"+v3s)
+ addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s)
+ addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s)
+ addFormatterTest("%#v", nv3, "(*"+v3t+")"+"<nil>")
+ addFormatterTest("%#+v", v3, "("+v3t+")"+v3s)
+ addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s)
+ addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s)
+ addFormatterTest("%#v", nv3, "(*"+v3t+")"+"<nil>")
+
+ // Max uint64.
+ v4 := uint64(18446744073709551615)
+ nv4 := (*uint64)(nil)
+ pv4 := &v4
+ v4Addr := fmt.Sprintf("%p", pv4)
+ pv4Addr := fmt.Sprintf("%p", &pv4)
+ v4t := "uint64"
+ v4s := "18446744073709551615"
+ addFormatterTest("%v", v4, v4s)
+ addFormatterTest("%v", pv4, "<*>"+v4s)
+ addFormatterTest("%v", &pv4, "<**>"+v4s)
+ addFormatterTest("%v", nv4, "<nil>")
+ addFormatterTest("%+v", v4, v4s)
+ addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s)
+ addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s)
+ addFormatterTest("%+v", nv4, "<nil>")
+ addFormatterTest("%#v", v4, "("+v4t+")"+v4s)
+ addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s)
+ addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s)
+ addFormatterTest("%#v", nv4, "(*"+v4t+")"+"<nil>")
+ addFormatterTest("%#+v", v4, "("+v4t+")"+v4s)
+ addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s)
+ addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s)
+ addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"<nil>")
+
+ // Max uint.
+ v5 := uint(4294967295)
+ nv5 := (*uint)(nil)
+ pv5 := &v5
+ v5Addr := fmt.Sprintf("%p", pv5)
+ pv5Addr := fmt.Sprintf("%p", &pv5)
+ v5t := "uint"
+ v5s := "4294967295"
+ addFormatterTest("%v", v5, v5s)
+ addFormatterTest("%v", pv5, "<*>"+v5s)
+ addFormatterTest("%v", &pv5, "<**>"+v5s)
+ addFormatterTest("%v", nv5, "<nil>")
+ addFormatterTest("%+v", v5, v5s)
+ addFormatterTest("%+v", pv5, "<*>("+v5Addr+")"+v5s)
+ addFormatterTest("%+v", &pv5, "<**>("+pv5Addr+"->"+v5Addr+")"+v5s)
+ addFormatterTest("%+v", nv5, "<nil>")
+ addFormatterTest("%#v", v5, "("+v5t+")"+v5s)
+ addFormatterTest("%#v", pv5, "(*"+v5t+")"+v5s)
+ addFormatterTest("%#v", &pv5, "(**"+v5t+")"+v5s)
+ addFormatterTest("%#v", nv5, "(*"+v5t+")"+"<nil>")
+ addFormatterTest("%#+v", v5, "("+v5t+")"+v5s)
+ addFormatterTest("%#+v", pv5, "(*"+v5t+")("+v5Addr+")"+v5s)
+ addFormatterTest("%#+v", &pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")"+v5s)
+ addFormatterTest("%#v", nv5, "(*"+v5t+")"+"<nil>")
+}
+
+func addBoolFormatterTests() {
+ // Boolean true.
+ v := bool(true)
+ nv := (*bool)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "bool"
+ vs := "true"
+ addFormatterTest("%v", v, vs)
+ addFormatterTest("%v", pv, "<*>"+vs)
+ addFormatterTest("%v", &pv, "<**>"+vs)
+ addFormatterTest("%v", nv, "<nil>")
+ addFormatterTest("%+v", v, vs)
+ addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
+ addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%#v", v, "("+vt+")"+vs)
+ addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
+ addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
+ addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
+ addFormatterTest("%#+v", v, "("+vt+")"+vs)
+ addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
+ addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
+
+ // Boolean false.
+ v2 := bool(false)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "bool"
+ v2s := "false"
+ addFormatterTest("%v", v2, v2s)
+ addFormatterTest("%v", pv2, "<*>"+v2s)
+ addFormatterTest("%v", &pv2, "<**>"+v2s)
+ addFormatterTest("%+v", v2, v2s)
+ addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
+ addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
+ addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
+ addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
+ addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
+ addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
+}
+
+func addFloatFormatterTests() {
+ // Standard float32.
+ v := float32(3.1415)
+ nv := (*float32)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "float32"
+ vs := "3.1415"
+ addFormatterTest("%v", v, vs)
+ addFormatterTest("%v", pv, "<*>"+vs)
+ addFormatterTest("%v", &pv, "<**>"+vs)
+ addFormatterTest("%v", nv, "<nil>")
+ addFormatterTest("%+v", v, vs)
+ addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
+ addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%#v", v, "("+vt+")"+vs)
+ addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
+ addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
+ addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
+ addFormatterTest("%#+v", v, "("+vt+")"+vs)
+ addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
+ addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
+
+ // Standard float64.
+ v2 := float64(3.1415926)
+ nv2 := (*float64)(nil)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "float64"
+ v2s := "3.1415926"
+ addFormatterTest("%v", v2, v2s)
+ addFormatterTest("%v", pv2, "<*>"+v2s)
+ addFormatterTest("%v", &pv2, "<**>"+v2s)
+ addFormatterTest("%+v", nv2, "<nil>")
+ addFormatterTest("%+v", v2, v2s)
+ addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
+ addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
+ addFormatterTest("%+v", nv2, "<nil>")
+ addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
+ addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
+ addFormatterTest("%#v", nv2, "(*"+v2t+")"+"<nil>")
+ addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
+ addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
+ addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"<nil>")
+}
+
+func addComplexFormatterTests() {
+ // Standard complex64.
+ v := complex(float32(6), -2)
+ nv := (*complex64)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "complex64"
+ vs := "(6-2i)"
+ addFormatterTest("%v", v, vs)
+ addFormatterTest("%v", pv, "<*>"+vs)
+ addFormatterTest("%v", &pv, "<**>"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%+v", v, vs)
+ addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
+ addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%#v", v, "("+vt+")"+vs)
+ addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
+ addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
+ addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
+ addFormatterTest("%#+v", v, "("+vt+")"+vs)
+ addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
+ addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
+
+ // Standard complex128.
+ v2 := complex(float64(-6), 2)
+ nv2 := (*complex128)(nil)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "complex128"
+ v2s := "(-6+2i)"
+ addFormatterTest("%v", v2, v2s)
+ addFormatterTest("%v", pv2, "<*>"+v2s)
+ addFormatterTest("%v", &pv2, "<**>"+v2s)
+ addFormatterTest("%+v", nv2, "<nil>")
+ addFormatterTest("%+v", v2, v2s)
+ addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
+ addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
+ addFormatterTest("%+v", nv2, "<nil>")
+ addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
+ addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
+ addFormatterTest("%#v", nv2, "(*"+v2t+")"+"<nil>")
+ addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
+ addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
+ addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"<nil>")
+}
+
+func addArrayFormatterTests() {
+ // Array containing standard ints.
+ v := [3]int{1, 2, 3}
+ nv := (*[3]int)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "[3]int"
+ vs := "[1 2 3]"
+ addFormatterTest("%v", v, vs)
+ addFormatterTest("%v", pv, "<*>"+vs)
+ addFormatterTest("%v", &pv, "<**>"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%+v", v, vs)
+ addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
+ addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%#v", v, "("+vt+")"+vs)
+ addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
+ addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
+ addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
+ addFormatterTest("%#+v", v, "("+vt+")"+vs)
+ addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
+ addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
+
+ // Array containing type with custom formatter on pointer receiver only.
+ v2 := [3]pstringer{"1", "2", "3"}
+ nv2 := (*[3]pstringer)(nil)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "[3]spew_test.pstringer"
+ v2sp := "[stringer 1 stringer 2 stringer 3]"
+ v2s := v2sp
+ if spew.UnsafeDisabled {
+ v2s = "[1 2 3]"
+ }
+ addFormatterTest("%v", v2, v2s)
+ addFormatterTest("%v", pv2, "<*>"+v2sp)
+ addFormatterTest("%v", &pv2, "<**>"+v2sp)
+ addFormatterTest("%+v", nv2, "<nil>")
+ addFormatterTest("%+v", v2, v2s)
+ addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2sp)
+ addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2sp)
+ addFormatterTest("%+v", nv2, "<nil>")
+ addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2sp)
+ addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2sp)
+ addFormatterTest("%#v", nv2, "(*"+v2t+")"+"<nil>")
+ addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2sp)
+ addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2sp)
+ addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"<nil>")
+
+ // Array containing interfaces.
+ v3 := [3]interface{}{"one", int(2), uint(3)}
+ nv3 := (*[3]interface{})(nil)
+ pv3 := &v3
+ v3Addr := fmt.Sprintf("%p", pv3)
+ pv3Addr := fmt.Sprintf("%p", &pv3)
+ v3t := "[3]interface {}"
+ v3t2 := "string"
+ v3t3 := "int"
+ v3t4 := "uint"
+ v3s := "[one 2 3]"
+ v3s2 := "[(" + v3t2 + ")one (" + v3t3 + ")2 (" + v3t4 + ")3]"
+ addFormatterTest("%v", v3, v3s)
+ addFormatterTest("%v", pv3, "<*>"+v3s)
+ addFormatterTest("%v", &pv3, "<**>"+v3s)
+ addFormatterTest("%+v", nv3, "<nil>")
+ addFormatterTest("%+v", v3, v3s)
+ addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s)
+ addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s)
+ addFormatterTest("%+v", nv3, "<nil>")
+ addFormatterTest("%#v", v3, "("+v3t+")"+v3s2)
+ addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2)
+ addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2)
+ addFormatterTest("%#v", nv3, "(*"+v3t+")"+"<nil>")
+ addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2)
+ addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2)
+ addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2)
+ addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"<nil>")
+}
+
+func addSliceFormatterTests() {
+ // Slice containing standard float32 values.
+ v := []float32{3.14, 6.28, 12.56}
+ nv := (*[]float32)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "[]float32"
+ vs := "[3.14 6.28 12.56]"
+ addFormatterTest("%v", v, vs)
+ addFormatterTest("%v", pv, "<*>"+vs)
+ addFormatterTest("%v", &pv, "<**>"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%+v", v, vs)
+ addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
+ addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%#v", v, "("+vt+")"+vs)
+ addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
+ addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
+ addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
+ addFormatterTest("%#+v", v, "("+vt+")"+vs)
+ addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
+ addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
+
+ // Slice containing type with custom formatter on pointer receiver only.
+ v2 := []pstringer{"1", "2", "3"}
+ nv2 := (*[]pstringer)(nil)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "[]spew_test.pstringer"
+ v2s := "[stringer 1 stringer 2 stringer 3]"
+ addFormatterTest("%v", v2, v2s)
+ addFormatterTest("%v", pv2, "<*>"+v2s)
+ addFormatterTest("%v", &pv2, "<**>"+v2s)
+ addFormatterTest("%+v", nv2, "<nil>")
+ addFormatterTest("%+v", v2, v2s)
+ addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
+ addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
+ addFormatterTest("%+v", nv2, "<nil>")
+ addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
+ addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
+ addFormatterTest("%#v", nv2, "(*"+v2t+")"+"<nil>")
+ addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
+ addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
+ addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"<nil>")
+
+ // Slice containing interfaces.
+ v3 := []interface{}{"one", int(2), uint(3), nil}
+ nv3 := (*[]interface{})(nil)
+ pv3 := &v3
+ v3Addr := fmt.Sprintf("%p", pv3)
+ pv3Addr := fmt.Sprintf("%p", &pv3)
+ v3t := "[]interface {}"
+ v3t2 := "string"
+ v3t3 := "int"
+ v3t4 := "uint"
+ v3t5 := "interface {}"
+ v3s := "[one 2 3 <nil>]"
+ v3s2 := "[(" + v3t2 + ")one (" + v3t3 + ")2 (" + v3t4 + ")3 (" + v3t5 +
+ ")<nil>]"
+ addFormatterTest("%v", v3, v3s)
+ addFormatterTest("%v", pv3, "<*>"+v3s)
+ addFormatterTest("%v", &pv3, "<**>"+v3s)
+ addFormatterTest("%+v", nv3, "<nil>")
+ addFormatterTest("%+v", v3, v3s)
+ addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s)
+ addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s)
+ addFormatterTest("%+v", nv3, "<nil>")
+ addFormatterTest("%#v", v3, "("+v3t+")"+v3s2)
+ addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2)
+ addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2)
+ addFormatterTest("%#v", nv3, "(*"+v3t+")"+"<nil>")
+ addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2)
+ addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2)
+ addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2)
+ addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"<nil>")
+
+ // Nil slice.
+ var v4 []int
+ nv4 := (*[]int)(nil)
+ pv4 := &v4
+ v4Addr := fmt.Sprintf("%p", pv4)
+ pv4Addr := fmt.Sprintf("%p", &pv4)
+ v4t := "[]int"
+ v4s := "<nil>"
+ addFormatterTest("%v", v4, v4s)
+ addFormatterTest("%v", pv4, "<*>"+v4s)
+ addFormatterTest("%v", &pv4, "<**>"+v4s)
+ addFormatterTest("%+v", nv4, "<nil>")
+ addFormatterTest("%+v", v4, v4s)
+ addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s)
+ addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s)
+ addFormatterTest("%+v", nv4, "<nil>")
+ addFormatterTest("%#v", v4, "("+v4t+")"+v4s)
+ addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s)
+ addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s)
+ addFormatterTest("%#v", nv4, "(*"+v4t+")"+"<nil>")
+ addFormatterTest("%#+v", v4, "("+v4t+")"+v4s)
+ addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s)
+ addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s)
+ addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"<nil>")
+}
+
+func addStringFormatterTests() {
+ // Standard string.
+ v := "test"
+ nv := (*string)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "string"
+ vs := "test"
+ addFormatterTest("%v", v, vs)
+ addFormatterTest("%v", pv, "<*>"+vs)
+ addFormatterTest("%v", &pv, "<**>"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%+v", v, vs)
+ addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
+ addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%#v", v, "("+vt+")"+vs)
+ addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
+ addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
+ addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
+ addFormatterTest("%#+v", v, "("+vt+")"+vs)
+ addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
+ addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
+}
+
+func addInterfaceFormatterTests() {
+ // Nil interface.
+ var v interface{}
+ nv := (*interface{})(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "interface {}"
+ vs := "<nil>"
+ addFormatterTest("%v", v, vs)
+ addFormatterTest("%v", pv, "<*>"+vs)
+ addFormatterTest("%v", &pv, "<**>"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%+v", v, vs)
+ addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
+ addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%#v", v, "("+vt+")"+vs)
+ addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
+ addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
+ addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
+ addFormatterTest("%#+v", v, "("+vt+")"+vs)
+ addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
+ addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
+
+ // Sub-interface.
+ v2 := interface{}(uint16(65535))
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "uint16"
+ v2s := "65535"
+ addFormatterTest("%v", v2, v2s)
+ addFormatterTest("%v", pv2, "<*>"+v2s)
+ addFormatterTest("%v", &pv2, "<**>"+v2s)
+ addFormatterTest("%+v", v2, v2s)
+ addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
+ addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
+ addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
+ addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
+ addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
+ addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
+}
+
+func addMapFormatterTests() {
+ // Map with string keys and int vals.
+ v := map[string]int{"one": 1, "two": 2}
+ nilMap := map[string]int(nil)
+ nv := (*map[string]int)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "map[string]int"
+ vs := "map[one:1 two:2]"
+ vs2 := "map[two:2 one:1]"
+ addFormatterTest("%v", v, vs, vs2)
+ addFormatterTest("%v", pv, "<*>"+vs, "<*>"+vs2)
+ addFormatterTest("%v", &pv, "<**>"+vs, "<**>"+vs2)
+ addFormatterTest("%+v", nilMap, "<nil>")
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%+v", v, vs, vs2)
+ addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs, "<*>("+vAddr+")"+vs2)
+ addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs,
+ "<**>("+pvAddr+"->"+vAddr+")"+vs2)
+ addFormatterTest("%+v", nilMap, "<nil>")
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%#v", v, "("+vt+")"+vs, "("+vt+")"+vs2)
+ addFormatterTest("%#v", pv, "(*"+vt+")"+vs, "(*"+vt+")"+vs2)
+ addFormatterTest("%#v", &pv, "(**"+vt+")"+vs, "(**"+vt+")"+vs2)
+ addFormatterTest("%#v", nilMap, "("+vt+")"+"<nil>")
+ addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
+ addFormatterTest("%#+v", v, "("+vt+")"+vs, "("+vt+")"+vs2)
+ addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs,
+ "(*"+vt+")("+vAddr+")"+vs2)
+ addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs,
+ "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs2)
+ addFormatterTest("%#+v", nilMap, "("+vt+")"+"<nil>")
+ addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
+
+ // Map with custom formatter type on pointer receiver only keys and vals.
+ v2 := map[pstringer]pstringer{"one": "1"}
+ nv2 := (*map[pstringer]pstringer)(nil)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "map[spew_test.pstringer]spew_test.pstringer"
+ v2s := "map[stringer one:stringer 1]"
+ if spew.UnsafeDisabled {
+ v2s = "map[one:1]"
+ }
+ addFormatterTest("%v", v2, v2s)
+ addFormatterTest("%v", pv2, "<*>"+v2s)
+ addFormatterTest("%v", &pv2, "<**>"+v2s)
+ addFormatterTest("%+v", nv2, "<nil>")
+ addFormatterTest("%+v", v2, v2s)
+ addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
+ addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
+ addFormatterTest("%+v", nv2, "<nil>")
+ addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
+ addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
+ addFormatterTest("%#v", nv2, "(*"+v2t+")"+"<nil>")
+ addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
+ addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
+ addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"<nil>")
+
+ // Map with interface keys and values.
+ v3 := map[interface{}]interface{}{"one": 1}
+ nv3 := (*map[interface{}]interface{})(nil)
+ pv3 := &v3
+ v3Addr := fmt.Sprintf("%p", pv3)
+ pv3Addr := fmt.Sprintf("%p", &pv3)
+ v3t := "map[interface {}]interface {}"
+ v3t1 := "string"
+ v3t2 := "int"
+ v3s := "map[one:1]"
+ v3s2 := "map[(" + v3t1 + ")one:(" + v3t2 + ")1]"
+ addFormatterTest("%v", v3, v3s)
+ addFormatterTest("%v", pv3, "<*>"+v3s)
+ addFormatterTest("%v", &pv3, "<**>"+v3s)
+ addFormatterTest("%+v", nv3, "<nil>")
+ addFormatterTest("%+v", v3, v3s)
+ addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s)
+ addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s)
+ addFormatterTest("%+v", nv3, "<nil>")
+ addFormatterTest("%#v", v3, "("+v3t+")"+v3s2)
+ addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2)
+ addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2)
+ addFormatterTest("%#v", nv3, "(*"+v3t+")"+"<nil>")
+ addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2)
+ addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2)
+ addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2)
+ addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"<nil>")
+
+ // Map with nil interface value
+ v4 := map[string]interface{}{"nil": nil}
+ nv4 := (*map[string]interface{})(nil)
+ pv4 := &v4
+ v4Addr := fmt.Sprintf("%p", pv4)
+ pv4Addr := fmt.Sprintf("%p", &pv4)
+ v4t := "map[string]interface {}"
+ v4t1 := "interface {}"
+ v4s := "map[nil:<nil>]"
+ v4s2 := "map[nil:(" + v4t1 + ")<nil>]"
+ addFormatterTest("%v", v4, v4s)
+ addFormatterTest("%v", pv4, "<*>"+v4s)
+ addFormatterTest("%v", &pv4, "<**>"+v4s)
+ addFormatterTest("%+v", nv4, "<nil>")
+ addFormatterTest("%+v", v4, v4s)
+ addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s)
+ addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s)
+ addFormatterTest("%+v", nv4, "<nil>")
+ addFormatterTest("%#v", v4, "("+v4t+")"+v4s2)
+ addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s2)
+ addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s2)
+ addFormatterTest("%#v", nv4, "(*"+v4t+")"+"<nil>")
+ addFormatterTest("%#+v", v4, "("+v4t+")"+v4s2)
+ addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s2)
+ addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s2)
+ addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"<nil>")
+}
+
+func addStructFormatterTests() {
+ // Struct with primitives.
+ type s1 struct {
+ a int8
+ b uint8
+ }
+ v := s1{127, 255}
+ nv := (*s1)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "spew_test.s1"
+ vt2 := "int8"
+ vt3 := "uint8"
+ vs := "{127 255}"
+ vs2 := "{a:127 b:255}"
+ vs3 := "{a:(" + vt2 + ")127 b:(" + vt3 + ")255}"
+ addFormatterTest("%v", v, vs)
+ addFormatterTest("%v", pv, "<*>"+vs)
+ addFormatterTest("%v", &pv, "<**>"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%+v", v, vs2)
+ addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs2)
+ addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs2)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%#v", v, "("+vt+")"+vs3)
+ addFormatterTest("%#v", pv, "(*"+vt+")"+vs3)
+ addFormatterTest("%#v", &pv, "(**"+vt+")"+vs3)
+ addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
+ addFormatterTest("%#+v", v, "("+vt+")"+vs3)
+ addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs3)
+ addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs3)
+ addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
+
+ // Struct that contains another struct.
+ type s2 struct {
+ s1 s1
+ b bool
+ }
+ v2 := s2{s1{127, 255}, true}
+ nv2 := (*s2)(nil)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "spew_test.s2"
+ v2t2 := "spew_test.s1"
+ v2t3 := "int8"
+ v2t4 := "uint8"
+ v2t5 := "bool"
+ v2s := "{{127 255} true}"
+ v2s2 := "{s1:{a:127 b:255} b:true}"
+ v2s3 := "{s1:(" + v2t2 + "){a:(" + v2t3 + ")127 b:(" + v2t4 + ")255} b:(" +
+ v2t5 + ")true}"
+ addFormatterTest("%v", v2, v2s)
+ addFormatterTest("%v", pv2, "<*>"+v2s)
+ addFormatterTest("%v", &pv2, "<**>"+v2s)
+ addFormatterTest("%+v", nv2, "<nil>")
+ addFormatterTest("%+v", v2, v2s2)
+ addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s2)
+ addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s2)
+ addFormatterTest("%+v", nv2, "<nil>")
+ addFormatterTest("%#v", v2, "("+v2t+")"+v2s3)
+ addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s3)
+ addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s3)
+ addFormatterTest("%#v", nv2, "(*"+v2t+")"+"<nil>")
+ addFormatterTest("%#+v", v2, "("+v2t+")"+v2s3)
+ addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s3)
+ addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s3)
+ addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"<nil>")
+
+ // Struct that contains custom type with Stringer pointer interface via both
+ // exported and unexported fields.
+ type s3 struct {
+ s pstringer
+ S pstringer
+ }
+ v3 := s3{"test", "test2"}
+ nv3 := (*s3)(nil)
+ pv3 := &v3
+ v3Addr := fmt.Sprintf("%p", pv3)
+ pv3Addr := fmt.Sprintf("%p", &pv3)
+ v3t := "spew_test.s3"
+ v3t2 := "spew_test.pstringer"
+ v3s := "{stringer test stringer test2}"
+ v3sp := v3s
+ v3s2 := "{s:stringer test S:stringer test2}"
+ v3s2p := v3s2
+ v3s3 := "{s:(" + v3t2 + ")stringer test S:(" + v3t2 + ")stringer test2}"
+ v3s3p := v3s3
+ if spew.UnsafeDisabled {
+ v3s = "{test test2}"
+ v3sp = "{test stringer test2}"
+ v3s2 = "{s:test S:test2}"
+ v3s2p = "{s:test S:stringer test2}"
+ v3s3 = "{s:(" + v3t2 + ")test S:(" + v3t2 + ")test2}"
+ v3s3p = "{s:(" + v3t2 + ")test S:(" + v3t2 + ")stringer test2}"
+ }
+ addFormatterTest("%v", v3, v3s)
+ addFormatterTest("%v", pv3, "<*>"+v3sp)
+ addFormatterTest("%v", &pv3, "<**>"+v3sp)
+ addFormatterTest("%+v", nv3, "<nil>")
+ addFormatterTest("%+v", v3, v3s2)
+ addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s2p)
+ addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s2p)
+ addFormatterTest("%+v", nv3, "<nil>")
+ addFormatterTest("%#v", v3, "("+v3t+")"+v3s3)
+ addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s3p)
+ addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s3p)
+ addFormatterTest("%#v", nv3, "(*"+v3t+")"+"<nil>")
+ addFormatterTest("%#+v", v3, "("+v3t+")"+v3s3)
+ addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s3p)
+ addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s3p)
+ addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"<nil>")
+
+ // Struct that contains embedded struct and field to same struct.
+ e := embed{"embedstr"}
+ v4 := embedwrap{embed: &e, e: &e}
+ nv4 := (*embedwrap)(nil)
+ pv4 := &v4
+ eAddr := fmt.Sprintf("%p", &e)
+ v4Addr := fmt.Sprintf("%p", pv4)
+ pv4Addr := fmt.Sprintf("%p", &pv4)
+ v4t := "spew_test.embedwrap"
+ v4t2 := "spew_test.embed"
+ v4t3 := "string"
+ v4s := "{<*>{embedstr} <*>{embedstr}}"
+ v4s2 := "{embed:<*>(" + eAddr + "){a:embedstr} e:<*>(" + eAddr +
+ "){a:embedstr}}"
+ v4s3 := "{embed:(*" + v4t2 + "){a:(" + v4t3 + ")embedstr} e:(*" + v4t2 +
+ "){a:(" + v4t3 + ")embedstr}}"
+ v4s4 := "{embed:(*" + v4t2 + ")(" + eAddr + "){a:(" + v4t3 +
+ ")embedstr} e:(*" + v4t2 + ")(" + eAddr + "){a:(" + v4t3 + ")embedstr}}"
+ addFormatterTest("%v", v4, v4s)
+ addFormatterTest("%v", pv4, "<*>"+v4s)
+ addFormatterTest("%v", &pv4, "<**>"+v4s)
+ addFormatterTest("%+v", nv4, "<nil>")
+ addFormatterTest("%+v", v4, v4s2)
+ addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s2)
+ addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s2)
+ addFormatterTest("%+v", nv4, "<nil>")
+ addFormatterTest("%#v", v4, "("+v4t+")"+v4s3)
+ addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s3)
+ addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s3)
+ addFormatterTest("%#v", nv4, "(*"+v4t+")"+"<nil>")
+ addFormatterTest("%#+v", v4, "("+v4t+")"+v4s4)
+ addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s4)
+ addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s4)
+ addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"<nil>")
+}
+
+func addUintptrFormatterTests() {
+ // Null pointer.
+ v := uintptr(0)
+ nv := (*uintptr)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "uintptr"
+ vs := "<nil>"
+ addFormatterTest("%v", v, vs)
+ addFormatterTest("%v", pv, "<*>"+vs)
+ addFormatterTest("%v", &pv, "<**>"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%+v", v, vs)
+ addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
+ addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%#v", v, "("+vt+")"+vs)
+ addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
+ addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
+ addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
+ addFormatterTest("%#+v", v, "("+vt+")"+vs)
+ addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
+ addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
+
+ // Address of real variable.
+ i := 1
+ v2 := uintptr(unsafe.Pointer(&i))
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "uintptr"
+ v2s := fmt.Sprintf("%p", &i)
+ addFormatterTest("%v", v2, v2s)
+ addFormatterTest("%v", pv2, "<*>"+v2s)
+ addFormatterTest("%v", &pv2, "<**>"+v2s)
+ addFormatterTest("%+v", v2, v2s)
+ addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
+ addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
+ addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
+ addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
+ addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
+ addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
+}
+
+func addUnsafePointerFormatterTests() {
+ // Null pointer.
+ v := unsafe.Pointer(uintptr(0))
+ nv := (*unsafe.Pointer)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "unsafe.Pointer"
+ vs := "<nil>"
+ addFormatterTest("%v", v, vs)
+ addFormatterTest("%v", pv, "<*>"+vs)
+ addFormatterTest("%v", &pv, "<**>"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%+v", v, vs)
+ addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
+ addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%#v", v, "("+vt+")"+vs)
+ addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
+ addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
+ addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
+ addFormatterTest("%#+v", v, "("+vt+")"+vs)
+ addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
+ addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
+
+ // Address of real variable.
+ i := 1
+ v2 := unsafe.Pointer(&i)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "unsafe.Pointer"
+ v2s := fmt.Sprintf("%p", &i)
+ addFormatterTest("%v", v2, v2s)
+ addFormatterTest("%v", pv2, "<*>"+v2s)
+ addFormatterTest("%v", &pv2, "<**>"+v2s)
+ addFormatterTest("%+v", v2, v2s)
+ addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
+ addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
+ addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
+ addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
+ addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
+ addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
+}
+
+func addChanFormatterTests() {
+ // Nil channel.
+ var v chan int
+ pv := &v
+ nv := (*chan int)(nil)
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "chan int"
+ vs := "<nil>"
+ addFormatterTest("%v", v, vs)
+ addFormatterTest("%v", pv, "<*>"+vs)
+ addFormatterTest("%v", &pv, "<**>"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%+v", v, vs)
+ addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
+ addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%#v", v, "("+vt+")"+vs)
+ addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
+ addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
+ addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
+ addFormatterTest("%#+v", v, "("+vt+")"+vs)
+ addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
+ addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
+
+ // Real channel.
+ v2 := make(chan int)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "chan int"
+ v2s := fmt.Sprintf("%p", v2)
+ addFormatterTest("%v", v2, v2s)
+ addFormatterTest("%v", pv2, "<*>"+v2s)
+ addFormatterTest("%v", &pv2, "<**>"+v2s)
+ addFormatterTest("%+v", v2, v2s)
+ addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
+ addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
+ addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
+ addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
+ addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
+ addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
+}
+
+func addFuncFormatterTests() {
+ // Function with no params and no returns.
+ v := addIntFormatterTests
+ nv := (*func())(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "func()"
+ vs := fmt.Sprintf("%p", v)
+ addFormatterTest("%v", v, vs)
+ addFormatterTest("%v", pv, "<*>"+vs)
+ addFormatterTest("%v", &pv, "<**>"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%+v", v, vs)
+ addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
+ addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%#v", v, "("+vt+")"+vs)
+ addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
+ addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
+ addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
+ addFormatterTest("%#+v", v, "("+vt+")"+vs)
+ addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
+ addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
+
+ // Function with param and no returns.
+ v2 := TestFormatter
+ nv2 := (*func(*testing.T))(nil)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "func(*testing.T)"
+ v2s := fmt.Sprintf("%p", v2)
+ addFormatterTest("%v", v2, v2s)
+ addFormatterTest("%v", pv2, "<*>"+v2s)
+ addFormatterTest("%v", &pv2, "<**>"+v2s)
+ addFormatterTest("%+v", nv2, "<nil>")
+ addFormatterTest("%+v", v2, v2s)
+ addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
+ addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
+ addFormatterTest("%+v", nv2, "<nil>")
+ addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
+ addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
+ addFormatterTest("%#v", nv2, "(*"+v2t+")"+"<nil>")
+ addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
+ addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
+ addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
+ addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"<nil>")
+
+ // Function with multiple params and multiple returns.
+ var v3 = func(i int, s string) (b bool, err error) {
+ return true, nil
+ }
+ nv3 := (*func(int, string) (bool, error))(nil)
+ pv3 := &v3
+ v3Addr := fmt.Sprintf("%p", pv3)
+ pv3Addr := fmt.Sprintf("%p", &pv3)
+ v3t := "func(int, string) (bool, error)"
+ v3s := fmt.Sprintf("%p", v3)
+ addFormatterTest("%v", v3, v3s)
+ addFormatterTest("%v", pv3, "<*>"+v3s)
+ addFormatterTest("%v", &pv3, "<**>"+v3s)
+ addFormatterTest("%+v", nv3, "<nil>")
+ addFormatterTest("%+v", v3, v3s)
+ addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s)
+ addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s)
+ addFormatterTest("%+v", nv3, "<nil>")
+ addFormatterTest("%#v", v3, "("+v3t+")"+v3s)
+ addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s)
+ addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s)
+ addFormatterTest("%#v", nv3, "(*"+v3t+")"+"<nil>")
+ addFormatterTest("%#+v", v3, "("+v3t+")"+v3s)
+ addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s)
+ addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s)
+ addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"<nil>")
+}
+
+func addCircularFormatterTests() {
+ // Struct that is circular through self referencing.
+ type circular struct {
+ c *circular
+ }
+ v := circular{nil}
+ v.c = &v
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "spew_test.circular"
+ vs := "{<*>{<*><shown>}}"
+ vs2 := "{<*><shown>}"
+ vs3 := "{c:<*>(" + vAddr + "){c:<*>(" + vAddr + ")<shown>}}"
+ vs4 := "{c:<*>(" + vAddr + ")<shown>}"
+ vs5 := "{c:(*" + vt + "){c:(*" + vt + ")<shown>}}"
+ vs6 := "{c:(*" + vt + ")<shown>}"
+ vs7 := "{c:(*" + vt + ")(" + vAddr + "){c:(*" + vt + ")(" + vAddr +
+ ")<shown>}}"
+ vs8 := "{c:(*" + vt + ")(" + vAddr + ")<shown>}"
+ addFormatterTest("%v", v, vs)
+ addFormatterTest("%v", pv, "<*>"+vs2)
+ addFormatterTest("%v", &pv, "<**>"+vs2)
+ addFormatterTest("%+v", v, vs3)
+ addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs4)
+ addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs4)
+ addFormatterTest("%#v", v, "("+vt+")"+vs5)
+ addFormatterTest("%#v", pv, "(*"+vt+")"+vs6)
+ addFormatterTest("%#v", &pv, "(**"+vt+")"+vs6)
+ addFormatterTest("%#+v", v, "("+vt+")"+vs7)
+ addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs8)
+ addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs8)
+
+ // Structs that are circular through cross referencing.
+ v2 := xref1{nil}
+ ts2 := xref2{&v2}
+ v2.ps2 = &ts2
+ pv2 := &v2
+ ts2Addr := fmt.Sprintf("%p", &ts2)
+ v2Addr := fmt.Sprintf("%p", pv2)
+ pv2Addr := fmt.Sprintf("%p", &pv2)
+ v2t := "spew_test.xref1"
+ v2t2 := "spew_test.xref2"
+ v2s := "{<*>{<*>{<*><shown>}}}"
+ v2s2 := "{<*>{<*><shown>}}"
+ v2s3 := "{ps2:<*>(" + ts2Addr + "){ps1:<*>(" + v2Addr + "){ps2:<*>(" +
+ ts2Addr + ")<shown>}}}"
+ v2s4 := "{ps2:<*>(" + ts2Addr + "){ps1:<*>(" + v2Addr + ")<shown>}}"
+ v2s5 := "{ps2:(*" + v2t2 + "){ps1:(*" + v2t + "){ps2:(*" + v2t2 +
+ ")<shown>}}}"
+ v2s6 := "{ps2:(*" + v2t2 + "){ps1:(*" + v2t + ")<shown>}}"
+ v2s7 := "{ps2:(*" + v2t2 + ")(" + ts2Addr + "){ps1:(*" + v2t +
+ ")(" + v2Addr + "){ps2:(*" + v2t2 + ")(" + ts2Addr +
+ ")<shown>}}}"
+ v2s8 := "{ps2:(*" + v2t2 + ")(" + ts2Addr + "){ps1:(*" + v2t +
+ ")(" + v2Addr + ")<shown>}}"
+ addFormatterTest("%v", v2, v2s)
+ addFormatterTest("%v", pv2, "<*>"+v2s2)
+ addFormatterTest("%v", &pv2, "<**>"+v2s2)
+ addFormatterTest("%+v", v2, v2s3)
+ addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s4)
+ addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s4)
+ addFormatterTest("%#v", v2, "("+v2t+")"+v2s5)
+ addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s6)
+ addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s6)
+ addFormatterTest("%#+v", v2, "("+v2t+")"+v2s7)
+ addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s8)
+ addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s8)
+
+ // Structs that are indirectly circular.
+ v3 := indirCir1{nil}
+ tic2 := indirCir2{nil}
+ tic3 := indirCir3{&v3}
+ tic2.ps3 = &tic3
+ v3.ps2 = &tic2
+ pv3 := &v3
+ tic2Addr := fmt.Sprintf("%p", &tic2)
+ tic3Addr := fmt.Sprintf("%p", &tic3)
+ v3Addr := fmt.Sprintf("%p", pv3)
+ pv3Addr := fmt.Sprintf("%p", &pv3)
+ v3t := "spew_test.indirCir1"
+ v3t2 := "spew_test.indirCir2"
+ v3t3 := "spew_test.indirCir3"
+ v3s := "{<*>{<*>{<*>{<*><shown>}}}}"
+ v3s2 := "{<*>{<*>{<*><shown>}}}"
+ v3s3 := "{ps2:<*>(" + tic2Addr + "){ps3:<*>(" + tic3Addr + "){ps1:<*>(" +
+ v3Addr + "){ps2:<*>(" + tic2Addr + ")<shown>}}}}"
+ v3s4 := "{ps2:<*>(" + tic2Addr + "){ps3:<*>(" + tic3Addr + "){ps1:<*>(" +
+ v3Addr + ")<shown>}}}"
+ v3s5 := "{ps2:(*" + v3t2 + "){ps3:(*" + v3t3 + "){ps1:(*" + v3t +
+ "){ps2:(*" + v3t2 + ")<shown>}}}}"
+ v3s6 := "{ps2:(*" + v3t2 + "){ps3:(*" + v3t3 + "){ps1:(*" + v3t +
+ ")<shown>}}}"
+ v3s7 := "{ps2:(*" + v3t2 + ")(" + tic2Addr + "){ps3:(*" + v3t3 + ")(" +
+ tic3Addr + "){ps1:(*" + v3t + ")(" + v3Addr + "){ps2:(*" + v3t2 +
+ ")(" + tic2Addr + ")<shown>}}}}"
+ v3s8 := "{ps2:(*" + v3t2 + ")(" + tic2Addr + "){ps3:(*" + v3t3 + ")(" +
+ tic3Addr + "){ps1:(*" + v3t + ")(" + v3Addr + ")<shown>}}}"
+ addFormatterTest("%v", v3, v3s)
+ addFormatterTest("%v", pv3, "<*>"+v3s2)
+ addFormatterTest("%v", &pv3, "<**>"+v3s2)
+ addFormatterTest("%+v", v3, v3s3)
+ addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s4)
+ addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s4)
+ addFormatterTest("%#v", v3, "("+v3t+")"+v3s5)
+ addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s6)
+ addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s6)
+ addFormatterTest("%#+v", v3, "("+v3t+")"+v3s7)
+ addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s8)
+ addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s8)
+}
+
+func addPanicFormatterTests() {
+ // Type that panics in its Stringer interface.
+ v := panicer(127)
+ nv := (*panicer)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "spew_test.panicer"
+ vs := "(PANIC=test panic)127"
+ addFormatterTest("%v", v, vs)
+ addFormatterTest("%v", pv, "<*>"+vs)
+ addFormatterTest("%v", &pv, "<**>"+vs)
+ addFormatterTest("%v", nv, "<nil>")
+ addFormatterTest("%+v", v, vs)
+ addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
+ addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%#v", v, "("+vt+")"+vs)
+ addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
+ addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
+ addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
+ addFormatterTest("%#+v", v, "("+vt+")"+vs)
+ addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
+ addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
+}
+
+func addErrorFormatterTests() {
+ // Type that has a custom Error interface.
+ v := customError(127)
+ nv := (*customError)(nil)
+ pv := &v
+ vAddr := fmt.Sprintf("%p", pv)
+ pvAddr := fmt.Sprintf("%p", &pv)
+ vt := "spew_test.customError"
+ vs := "error: 127"
+ addFormatterTest("%v", v, vs)
+ addFormatterTest("%v", pv, "<*>"+vs)
+ addFormatterTest("%v", &pv, "<**>"+vs)
+ addFormatterTest("%v", nv, "<nil>")
+ addFormatterTest("%+v", v, vs)
+ addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
+ addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%+v", nv, "<nil>")
+ addFormatterTest("%#v", v, "("+vt+")"+vs)
+ addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
+ addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
+ addFormatterTest("%#v", nv, "(*"+vt+")"+"<nil>")
+ addFormatterTest("%#+v", v, "("+vt+")"+vs)
+ addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
+ addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
+ addFormatterTest("%#+v", nv, "(*"+vt+")"+"<nil>")
+}
+
+func addPassthroughFormatterTests() {
+ // %x passthrough with uint.
+ v := uint(4294967295)
+ pv := &v
+ vAddr := fmt.Sprintf("%x", pv)
+ pvAddr := fmt.Sprintf("%x", &pv)
+ vs := "ffffffff"
+ addFormatterTest("%x", v, vs)
+ addFormatterTest("%x", pv, vAddr)
+ addFormatterTest("%x", &pv, pvAddr)
+
+ // %#x passthrough with uint.
+ v2 := int(2147483647)
+ pv2 := &v2
+ v2Addr := fmt.Sprintf("%#x", pv2)
+ pv2Addr := fmt.Sprintf("%#x", &pv2)
+ v2s := "0x7fffffff"
+ addFormatterTest("%#x", v2, v2s)
+ addFormatterTest("%#x", pv2, v2Addr)
+ addFormatterTest("%#x", &pv2, pv2Addr)
+
+ // %f passthrough with precision.
+ addFormatterTest("%.2f", 3.1415, "3.14")
+ addFormatterTest("%.3f", 3.1415, "3.142")
+ addFormatterTest("%.4f", 3.1415, "3.1415")
+
+ // %f passthrough with width and precision.
+ addFormatterTest("%5.2f", 3.1415, " 3.14")
+ addFormatterTest("%6.3f", 3.1415, " 3.142")
+ addFormatterTest("%7.4f", 3.1415, " 3.1415")
+
+ // %d passthrough with width.
+ addFormatterTest("%3d", 127, "127")
+ addFormatterTest("%4d", 127, " 127")
+ addFormatterTest("%5d", 127, " 127")
+
+ // %q passthrough with string.
+ addFormatterTest("%q", "test", "\"test\"")
+}
+
+// TestFormatter executes all of the tests described by formatterTests.
+func TestFormatter(t *testing.T) {
+ // Setup tests.
+ addIntFormatterTests()
+ addUintFormatterTests()
+ addBoolFormatterTests()
+ addFloatFormatterTests()
+ addComplexFormatterTests()
+ addArrayFormatterTests()
+ addSliceFormatterTests()
+ addStringFormatterTests()
+ addInterfaceFormatterTests()
+ addMapFormatterTests()
+ addStructFormatterTests()
+ addUintptrFormatterTests()
+ addUnsafePointerFormatterTests()
+ addChanFormatterTests()
+ addFuncFormatterTests()
+ addCircularFormatterTests()
+ addPanicFormatterTests()
+ addErrorFormatterTests()
+ addPassthroughFormatterTests()
+
+ t.Logf("Running %d tests", len(formatterTests))
+ for i, test := range formatterTests {
+ buf := new(bytes.Buffer)
+ spew.Fprintf(buf, test.format, test.in)
+ s := buf.String()
+ if testFailed(s, test.wants) {
+ t.Errorf("Formatter #%d format: %s got: %s %s", i, test.format, s,
+ stringizeWants(test.wants))
+ continue
+ }
+ }
+}
+
+type testStruct struct {
+ x int
+}
+
+func (ts testStruct) String() string {
+ return fmt.Sprintf("ts.%d", ts.x)
+}
+
+type testStructP struct {
+ x int
+}
+
+func (ts *testStructP) String() string {
+ return fmt.Sprintf("ts.%d", ts.x)
+}
+
+func TestPrintSortedKeys(t *testing.T) {
+ cfg := spew.ConfigState{SortKeys: true}
+ s := cfg.Sprint(map[int]string{1: "1", 3: "3", 2: "2"})
+ expected := "map[1:1 2:2 3:3]"
+ if s != expected {
+ t.Errorf("Sorted keys mismatch 1:\n %v %v", s, expected)
+ }
+
+ s = cfg.Sprint(map[stringer]int{"1": 1, "3": 3, "2": 2})
+ expected = "map[stringer 1:1 stringer 2:2 stringer 3:3]"
+ if s != expected {
+ t.Errorf("Sorted keys mismatch 2:\n %v %v", s, expected)
+ }
+
+ s = cfg.Sprint(map[pstringer]int{pstringer("1"): 1, pstringer("3"): 3, pstringer("2"): 2})
+ expected = "map[stringer 1:1 stringer 2:2 stringer 3:3]"
+ if spew.UnsafeDisabled {
+ expected = "map[1:1 2:2 3:3]"
+ }
+ if s != expected {
+ t.Errorf("Sorted keys mismatch 3:\n %v %v", s, expected)
+ }
+
+ s = cfg.Sprint(map[testStruct]int{testStruct{1}: 1, testStruct{3}: 3, testStruct{2}: 2})
+ expected = "map[ts.1:1 ts.2:2 ts.3:3]"
+ if s != expected {
+ t.Errorf("Sorted keys mismatch 4:\n %v %v", s, expected)
+ }
+
+ if !spew.UnsafeDisabled {
+ s = cfg.Sprint(map[testStructP]int{testStructP{1}: 1, testStructP{3}: 3, testStructP{2}: 2})
+ expected = "map[ts.1:1 ts.2:2 ts.3:3]"
+ if s != expected {
+ t.Errorf("Sorted keys mismatch 5:\n %v %v", s, expected)
+ }
+ }
+
+ s = cfg.Sprint(map[customError]int{customError(1): 1, customError(3): 3, customError(2): 2})
+ expected = "map[error: 1:1 error: 2:2 error: 3:3]"
+ if s != expected {
+ t.Errorf("Sorted keys mismatch 6:\n %v %v", s, expected)
+ }
+}
diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/internal_test.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/internal_test.go
new file mode 100644
index 000000000..1069ee21c
--- /dev/null
+++ b/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)
+}
diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/internalunsafe_test.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/internalunsafe_test.go
new file mode 100644
index 000000000..83e070e9a
--- /dev/null
+++ b/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)
+ }
+}
diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/spew.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/spew.go
new file mode 100644
index 000000000..d8233f542
--- /dev/null
+++ b/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
+}
diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/spew_test.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/spew_test.go
new file mode 100644
index 000000000..dbbc08567
--- /dev/null
+++ b/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/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
+ }
+ }
+}
diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go
new file mode 100644
index 000000000..5c87dd456
--- /dev/null
+++ b/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)
+}
diff --git a/Godeps/_workspace/src/github.com/disintegration/imaging/README.md b/Godeps/_workspace/src/github.com/disintegration/imaging/README.md
index 16ac8cf6c..25d836cef 100644
--- a/Godeps/_workspace/src/github.com/disintegration/imaging/README.md
+++ b/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` | ![dstImage](http://disintegration.github.io/imaging/out_resize_down_gaussian.png)
`imaging.Lanczos` | ![dstImage](http://disintegration.github.io/imaging/out_resize_down_lanczos.png)
+**Resize functions comparison**
+
+Original image:
+
+![srcImage](http://disintegration.github.io/imaging/in.jpg)
+
+Resize the image to width=100px and height=100px:
+
+```go
+dstImage := imaging.Resize(srcImage, 100, 100, imaging.Lanczos)
+```
+![dstImage](http://disintegration.github.io/imaging/out-comp-resize.jpg)
+
+Resize the image to width=100px preserving the aspect ratio:
+
+```go
+dstImage := imaging.Resize(srcImage, 100, 0, imaging.Lanczos)
+```
+![dstImage](http://disintegration.github.io/imaging/out-comp-fit.jpg)
+
+Resize the image to fit the 100x100px boundng box preserving the aspect ratio:
+
+```go
+dstImage := imaging.Fit(srcImage, 100, 100, imaging.Lanczos)
+```
+![dstImage](http://disintegration.github.io/imaging/out-comp-fit.jpg)
+
+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)
+```
+![dstImage](http://disintegration.github.io/imaging/out-comp-fill.jpg)
+
### Gaussian Blur
```go
dstImage := imaging.Blur(srcImage, 0.5)
diff --git a/Godeps/_workspace/src/github.com/disintegration/imaging/adjust_test.go b/Godeps/_workspace/src/github.com/disintegration/imaging/adjust_test.go
new file mode 100644
index 000000000..99898b0dc
--- /dev/null
+++ b/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)
+ }
+ }
+}
diff --git a/Godeps/_workspace/src/github.com/disintegration/imaging/effects_test.go b/Godeps/_workspace/src/github.com/disintegration/imaging/effects_test.go
new file mode 100644
index 000000000..b7de0974c
--- /dev/null
+++ b/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)
+ }
+ }
+}
diff --git a/Godeps/_workspace/src/github.com/disintegration/imaging/helpers.go b/Godeps/_workspace/src/github.com/disintegration/imaging/helpers.go
index 983b64d71..79967ae44 100644
--- a/Godeps/_workspace/src/github.com/disintegration/imaging/helpers.go
+++ b/Godeps/_workspace/src/github.com/disintegration/imaging/helpers.go
@@ -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
diff --git a/Godeps/_workspace/src/github.com/disintegration/imaging/helpers_test.go b/Godeps/_workspace/src/github.com/disintegration/imaging/helpers_test.go
new file mode 100644
index 000000000..2d611a008
--- /dev/null
+++ b/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)
+ }
+ }
+}
diff --git a/Godeps/_workspace/src/github.com/disintegration/imaging/resize.go b/Godeps/_workspace/src/github.com/disintegration/imaging/resize.go
index d2efd5c83..3c792e904 100644
--- a/Godeps/_workspace/src/github.com/disintegration/imaging/resize.go
+++ b/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{}
}
+ if srcW == minW && srcH == minH {
+ return Clone(img)
+ }
+
srcAspectRatio := float64(srcW) / float64(srcH)
- thumbAspectRatio := float64(thumbW) / float64(thumbH)
+ minAspectRatio := float64(minW) / float64(minH)
- var tmp image.Image
- if srcAspectRatio > thumbAspectRatio {
- tmp = Resize(img, 0, thumbH, filter)
+ var tmp *image.NRGBA
+ if srcAspectRatio < minAspectRatio {
+ tmp = Resize(img, minW, 0, filter)
} else {
- tmp = Resize(img, thumbW, 0, filter)
+ tmp = Resize(img, 0, minH, filter)
}
- return CropCenter(tmp, thumbW, thumbH)
+ 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.
diff --git a/Godeps/_workspace/src/github.com/disintegration/imaging/resize_test.go b/Godeps/_workspace/src/github.com/disintegration/imaging/resize_test.go
new file mode 100644
index 000000000..bc575dcbf
--- /dev/null
+++ b/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)
+ }
+ }
+}
diff --git a/Godeps/_workspace/src/github.com/disintegration/imaging/tools_test.go b/Godeps/_workspace/src/github.com/disintegration/imaging/tools_test.go
new file mode 100644
index 000000000..2dace6299
--- /dev/null
+++ b/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)
+ }
+ }
+}
diff --git a/Godeps/_workspace/src/github.com/disintegration/imaging/transform_test.go b/Godeps/_workspace/src/github.com/disintegration/imaging/transform_test.go
new file mode 100644
index 000000000..6e64082f4
--- /dev/null
+++ b/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)
+ }
+ }
+}
diff --git a/Godeps/_workspace/src/github.com/disintegration/imaging/utils_test.go b/Godeps/_workspace/src/github.com/disintegration/imaging/utils_test.go
new file mode 100644
index 000000000..c2384586b
--- /dev/null
+++ b/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))
+ }
+ }
+}
diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/internal/redistest/testdb.go b/Godeps/_workspace/src/github.com/garyburd/redigo/internal/redistest/testdb.go
index 5f955c424..b6f205b7f 100644
--- a/Godeps/_workspace/src/github.com/garyburd/redigo/internal/redistest/testdb.go
+++ b/Godeps/_workspace/src/github.com/garyburd/redigo/internal/redistest/testdb.go
@@ -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")
}
diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/conn.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/conn.go
index ac0e971c4..6a3819f1d 100644
--- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/conn.go
+++ b/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))
+}
+
+// DialOption specifies an option for dialing a Redis server.
+type DialOption struct {
+ f func(*dialOptions)
+}
+
+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
+ }}
}
-// 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)
+// 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
+ }}
+}
- // ReadTimeout specifies the timeout for reading a single command
- // reply. If ReadTimeout is zero, then no timeout is used.
- ReadTimeout time.Duration
+// DialDatabase specifies the database to select when dialing a connection.
+func DialDatabase(db int) DialOption {
+ return DialOption{func(do *dialOptions) {
+ do.db = db
+ }}
+}
- // WriteTimeout specifies the timeout for writing a single command. If
- // WriteTimeout is zero, then no timeout is used.
- WriteTimeout time.Duration
+// 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 address on the named network.
-func (d *xDialer) Dial(network, address string) (Conn, error) {
- dial := d.NetDial
- if dial == nil {
- dial = net.Dial
+// 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 {
diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/conn_test.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/conn_test.go
index 800370136..24887cf03 100644
--- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/conn_test.go
+++ b/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"
)
+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)
}
diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/pool.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/pool.go
index 9daf2e33f..d66ef84b6 100644
--- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/pool.go
+++ b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/pool.go
@@ -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}
}
diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/pool_test.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/pool_test.go
index 1fe305f16..9419a128f 100644
--- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/pool_test.go
+++ b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/pool_test.go
@@ -22,7 +22,6 @@ import (
"testing"
"time"
- "github.com/garyburd/redigo/internal/redistest"
"github.com/garyburd/redigo/redis"
)
@@ -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) Err() error { return c.err }
-func (c *poolTestConn) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
+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)
diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/pubsub_test.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/pubsub_test.go
index 365a58821..a3ed84e68 100644
--- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/pubsub_test.go
+++ b/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"
)
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})
diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/reply.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/reply.go
index 5af29bf51..57896147f 100644
--- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/reply.go
+++ b/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
diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/reply_test.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/reply_test.go
index 92744c590..2c774866d 100644
--- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/reply_test.go
+++ b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/reply_test.go
@@ -19,7 +19,6 @@ import (
"reflect"
"testing"
- "github.com/garyburd/redigo/internal/redistest"
"github.com/garyburd/redigo/redis"
)
@@ -58,6 +57,16 @@ var replyTests = []struct {
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)),
ve([]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()
diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/scan.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/scan.go
index 8c9cfa18d..962e94bcc 100644
--- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/scan.go
+++ b/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
diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/scan_test.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/scan_test.go
index b57dd8969..d364dff42 100644
--- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/scan_test.go
+++ b/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/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)
diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/script_test.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/script_test.go
index c9635bf08..42f3c0363 100644
--- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/script_test.go
+++ b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/script_test.go
@@ -20,7 +20,6 @@ import (
"testing"
"time"
- "github.com/garyburd/redigo/internal/redistest"
"github.com/garyburd/redigo/redis"
)
@@ -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)
}
diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/test_test.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/test_test.go
index b959a11f4..7240fa1f3 100644
--- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/test_test.go
+++ b/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 }
+var (
+ ErrNegativeInt = errNegativeInt
-func (nopCloser) Close() error { return nil }
+ 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
+)
-// NewConnBufio is a hook for tests.
-func NewConnBufio(rw bufio.ReadWriter) Conn {
- return &conn{br: rw.Reader, bw: rw.Writer, conn: nopCloser{}}
+type Server struct {
+ name string
+ cmd *exec.Cmd
+ done chan struct{}
}
-var (
- ErrNegativeInt = errNegativeInt
-)
+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()
+ }())
+}
diff --git a/Godeps/_workspace/src/github.com/go-gorp/gorp/.travis.yml b/Godeps/_workspace/src/github.com/go-gorp/gorp/.travis.yml
index 6df5edf1c..ce4602884 100644
--- a/Godeps/_workspace/src/github.com/go-gorp/gorp/.travis.yml
+++ b/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
diff --git a/Godeps/_workspace/src/github.com/go-gorp/gorp/Makefile b/Godeps/_workspace/src/github.com/go-gorp/gorp/Makefile
deleted file mode 100644
index 3a27ae194..000000000
--- a/Godeps/_workspace/src/github.com/go-gorp/gorp/Makefile
+++ /dev/null
@@ -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 \ No newline at end of file
diff --git a/Godeps/_workspace/src/github.com/go-gorp/gorp/README.md b/Godeps/_workspace/src/github.com/go-gorp/gorp/README.md
index d2de8c2b6..3f0652bc7 100644
--- a/Godeps/_workspace/src/github.com/go-gorp/gorp/README.md
+++ b/Godeps/_workspace/src/github.com/go-gorp/gorp/README.md
@@ -1,19 +1,26 @@
# Go Relational Persistence
-[![build status](https://secure.travis-ci.org/go-gorp/gorp.png)](http://travis-ci.org/go-gorp/gorp)
+[![build status](https://img.shields.io/travis/go-gorp/gorp.svg)](http://travis-ci.org/go-gorp/gorp)
+[![code coverage](https://img.shields.io/coveralls/go-gorp/gorp.svg)](https://coveralls.io/r/go-gorp/gorp)
+[![issues](https://img.shields.io/github/issues/go-gorp/gorp.svg)](https://github.com/go-gorp/gorp/issues)
+[![godoc v1](https://img.shields.io/badge/godoc-v1-375EAB.svg)](https://godoc.org/gopkg.in/gorp.v1)
+[![godoc bleeding edge](https://img.shields.io/badge/godoc-bleeding--edge-375EAB.svg)](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
diff --git a/Godeps/_workspace/src/github.com/go-gorp/gorp/column.go b/Godeps/_workspace/src/github.com/go-gorp/gorp/column.go
new file mode 100644
index 000000000..99d4fd555
--- /dev/null
+++ b/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
+}
diff --git a/Godeps/_workspace/src/github.com/go-gorp/gorp/db.go b/Godeps/_workspace/src/github.com/go-gorp/gorp/db.go
new file mode 100644
index 000000000..8bba07cf6
--- /dev/null
+++ b/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)))
+ }
+}
diff --git a/Godeps/_workspace/src/github.com/go-gorp/gorp/dialect.go b/Godeps/_workspace/src/github.com/go-gorp/gorp/dialect.go
index 8277a965e..203bc62b5 100644
--- a/Godeps/_workspace/src/github.com/go-gorp/gorp/dialect.go
+++ b/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)
-}
diff --git a/Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_mysql.go b/Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_mysql.go
new file mode 100644
index 000000000..3d7d34027
--- /dev/null
+++ b/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)
+}
diff --git a/Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_oracle.go b/Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_oracle.go
new file mode 100644
index 000000000..c381380f9
--- /dev/null
+++ b/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)
+}
diff --git a/Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_postgres.go b/Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_postgres.go
new file mode 100644
index 000000000..a086381a8
--- /dev/null
+++ b/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)
+}
diff --git a/Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_sqlite.go b/Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_sqlite.go
new file mode 100644
index 000000000..7d9b29757
--- /dev/null
+++ b/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)
+}
diff --git a/Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_sqlserver.go b/Godeps/_workspace/src/github.com/go-gorp/gorp/dialect_sqlserver.go
new file mode 100644
index 000000000..8808af598
--- /dev/null
+++ b/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 "" }
diff --git a/Godeps/_workspace/src/github.com/go-gorp/gorp/errors.go b/Godeps/_workspace/src/github.com/go-gorp/gorp/errors.go
index 356d68475..d13f03fc3 100644
--- a/Godeps/_workspace/src/github.com/go-gorp/gorp/errors.go
+++ b/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)
diff --git a/Godeps/_workspace/src/github.com/go-gorp/gorp/gorp.go b/Godeps/_workspace/src/github.com/go-gorp/gorp/gorp.go
index 4c91b6f78..1f32283f5 100644
--- a/Godeps/_workspace/src/github.com/go-gorp/gorp/gorp.go
+++ b/Godeps/_workspace/src/github.com/go-gorp/gorp/gorp.go
@@ -12,10 +12,8 @@
package gorp
import (
- "bytes"
"database/sql"
"database/sql/driver"
- "errors"
"fmt"
"reflect"
"regexp"
@@ -23,7 +21,8 @@ import (
"time"
)
-// Oracle String (empty string is null)
+// OracleString (empty string is null)
+// TODO: move to dialect/oracle?, rename to String?
type OracleString struct {
sql.NullString
}
@@ -46,80 +45,25 @@ func (os OracleString) Value() (driver.Value, error) {
return os.String, nil
}
-// A nullable Time value
-type NullTime struct {
- Time time.Time
- Valid bool // Valid is true if Time is not NULL
+// SqlTyper is a type that returns its database type. Most of the
+// time, the type can just use "database/sql/driver".Valuer; but when
+// it returns nil for its empty value, it needs to implement SqlTyper
+// to have its column type detected properly during table creation.
+type SqlTyper interface {
+ SqlType() driver.Valuer
}
+// for fields that exists in DB table, but not exists in struct
+type dummyField struct{}
+
// 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
- }
- }
- }
+func (nt *dummyField) Scan(value interface{}) error {
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
-}
-
var zeroVal reflect.Value
var versFieldConst = "[gorp_ver_field]"
-// 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)
-}
-
// The TypeConverter interface provides a way to map a value of one
// type to another type when persisting to, or loading from, a database.
//
@@ -139,502 +83,6 @@ type TypeConverter interface {
FromDb(target interface{}) (CustomScanner, bool)
}
-// 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
-}
-
-// Bind is called automatically by gorp after Scan()
-func (me CustomScanner) Bind() error {
- return me.Binder(me.Holder, me.Target)
-}
-
-// 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
-}
-
-// 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
- 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
-}
-
-// 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
-}
-
-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 {
- 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++
- }
- 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) (bindInstance, error) {
- 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 {
- 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
-}
-
-// 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
-
- // Passed to Dialect.ToSqlType() to assist in informing the
- // correct column type to map to in CreateTables()
- // Not used elsewhere
- MaxSize int
-
- 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
-}
-
-// 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
-}
-
// Executor exposes the sql.DB and sql.Tx Exec function so that it can be used
// on internal functions that convert named parameters for the Exec function.
type executor interface {
@@ -670,534 +118,6 @@ type SqlExecutor interface {
// interface.
var _, _ SqlExecutor = &DbMap{}, &Transaction{}
-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 = ""
-}
-
-// 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}
- tmap.Columns = m.readStructColumns(t)
- m.tables = append(m.tables, tmap)
-
- return tmap
-}
-
-func (m *DbMap) readStructColumns(t reflect.Type) (cols []*ColumnMap) {
- 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 := 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)
- }
- }
- } else {
- columnName := f.Tag.Get("db")
- if columnName == "" {
- columnName = f.Name
- }
- gotype := f.Type
- 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.
- value := reflect.New(gotype).Interface()
- scanner, useHolder := m.TypeConverter.FromDb(value)
- if useHolder {
- gotype = reflect.TypeOf(scanner.Holder)
- }
- }
- cm := &ColumnMap{
- ColumnName: columnName,
- Transient: columnName == "-",
- fieldName: f.Name,
- gotype: gotype,
- }
- // 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]
-
- s := bytes.Buffer{}
-
- if strings.TrimSpace(table.SchemaName) != "" {
- schemaCreate := "create schema"
- if ifNotExists {
- s.WriteString(m.Dialect.IfSchemaNotExists(schemaCreate, table.SchemaName))
- } else {
- s.WriteString(schemaCreate)
- }
- s.WriteString(fmt.Sprintf(" %s;", table.SchemaName))
- }
-
- tableCreate := "create table"
- if ifNotExists {
- s.WriteString(m.Dialect.IfTableNotExists(tableCreate, table.SchemaName, table.TableName))
- } else {
- s.WriteString(tableCreate)
- }
- s.WriteString(fmt.Sprintf(" %s (", m.Dialect.QuotedTableForQuery(table.SchemaName, table.TableName)))
-
- x := 0
- for _, col := range table.Columns {
- if !col.Transient {
- if x > 0 {
- s.WriteString(", ")
- }
- stype := m.Dialect.ToSqlType(col.gotype, col.MaxSize, col.isAutoIncr)
- s.WriteString(fmt.Sprintf("%s %s", m.Dialect.QuoteField(col.ColumnName), stype))
-
- if col.isPK || col.isNotNull {
- s.WriteString(" not null")
- }
- if col.isPK && len(table.keys) == 1 {
- s.WriteString(" primary key")
- }
- if col.Unique {
- s.WriteString(" unique")
- }
- if col.isAutoIncr {
- s.WriteString(fmt.Sprintf(" %s", m.Dialect.AutoIncrStr()))
- }
-
- x++
- }
- }
- if len(table.keys) > 1 {
- s.WriteString(", primary key (")
- for x := range table.keys {
- if x > 0 {
- s.WriteString(", ")
- }
- s.WriteString(m.Dialect.QuoteField(table.keys[x].ColumnName))
- }
- s.WriteString(")")
- }
- if len(table.uniqueTogether) > 0 {
- for _, columns := range table.uniqueTogether {
- s.WriteString(", unique (")
- for i, column := range columns {
- if i > 0 {
- s.WriteString(", ")
- }
- s.WriteString(m.Dialect.QuoteField(column))
- }
- s.WriteString(")")
- }
- }
- s.WriteString(") ")
- s.WriteString(m.Dialect.CreateTableSuffix())
- s.WriteString(m.Dialect.QuerySuffix())
- _, err = m.Exec(s.String())
- if err != nil {
- break
- }
- }
- return err
-}
-
-// DropTable drops an individual table. Will throw an error
-// if the table does not exist.
-func (m *DbMap) DropTable(table interface{}) error {
- t := reflect.TypeOf(table)
- return m.dropTable(t, false)
-}
-
-// DropTable drops an individual table. Will NOT throw an error
-// if the table does not exist.
-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
- }
- }
- 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 errors.New(fmt.Sprintf("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, 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.SelectFlot 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, errors.New(fmt.Sprintf("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)))
- }
-}
-
func argsString(args ...interface{}) string {
var margs string
for i, a := range args {
@@ -1222,505 +142,6 @@ func argsString(args ...interface{}) string {
return margs
}
-///////////////
-
-// 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, 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...)
-}
-
-///////////////
-
-// 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) {
- return err
- }
- nonFatalErr = err
- }
-
- dest := reflect.ValueOf(holder)
- if isptr {
- dest = dest.Elem()
- }
-
- if list != nil && len(list) > 0 {
- // 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 {
- if colToFieldIndex, err = columnToFieldIndex(m, t, cols); 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 sql.RawBytes
- 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
-}
-
// Calls the Exec function on the executor, but attempts to expand any eligible named
// query arguments first.
func exec(e SqlExecutor, query string, args ...interface{}) (sql.Result, error) {
@@ -1818,7 +239,8 @@ func columnToFieldIndex(m *DbMap, t reflect.Type, cols []string) ([][]int, error
colName := strings.ToLower(cols[x])
field, found := t.FieldByNameFunc(func(fieldName string) bool {
field, _ := t.FieldByName(fieldName)
- fieldName = field.Tag.Get("db")
+ cArguments := strings.Split(field.Tag.Get("db"), ",")
+ fieldName = cArguments[0]
if fieldName == "-" {
return false
@@ -1881,7 +303,7 @@ func toSliceType(i interface{}) (reflect.Type, error) {
if t.Kind() != reflect.Ptr {
// If it's a slice, return a more helpful error message
if t.Kind() == reflect.Slice {
- return nil, fmt.Errorf("gorp: Cannot SELECT into a non-pointer slice: %v", t)
+ return nil, fmt.Errorf("gorp: cannot SELECT into a non-pointer slice: %v", t)
}
return nil, nil
}
@@ -1900,7 +322,7 @@ func toType(i interface{}) (reflect.Type, error) {
}
if t.Kind() != reflect.Struct {
- return nil, fmt.Errorf("gorp: Cannot SELECT into this type: %v", reflect.TypeOf(i))
+ return nil, fmt.Errorf("gorp: cannot SELECT into this type: %v", reflect.TypeOf(i))
}
return t, nil
}
@@ -2013,7 +435,7 @@ func delete(m *DbMap, exec SqlExecutor, list ...interface{}) (int64, error) {
return count, nil
}
-func update(m *DbMap, exec SqlExecutor, list ...interface{}) (int64, error) {
+func update(m *DbMap, exec SqlExecutor, colFilter ColumnFilter, list ...interface{}) (int64, error) {
count := int64(0)
for _, ptr := range list {
table, elem, err := m.tableForPointer(ptr, true)
@@ -2029,7 +451,7 @@ func update(m *DbMap, exec SqlExecutor, list ...interface{}) (int64, error) {
}
}
- bi, err := table.bindUpdate(elem)
+ bi, err := table.bindUpdate(elem, colFilter)
if err != nil {
return -1, err
}
@@ -2099,15 +521,24 @@ func insert(m *DbMap, exec SqlExecutor, list ...interface{}) error {
} else if (k == reflect.Uint) || (k == reflect.Uint16) || (k == reflect.Uint32) || (k == reflect.Uint64) {
f.SetUint(uint64(id))
} else {
- return fmt.Errorf("gorp: Cannot set autoincrement value on non-Int field. SQL=%s autoIncrIdx=%d autoIncrFieldName=%s", bi.query, bi.autoIncrIdx, bi.autoIncrFieldName)
+ return fmt.Errorf("gorp: cannot set autoincrement value on non-Int field. SQL=%s autoIncrIdx=%d autoIncrFieldName=%s", bi.query, bi.autoIncrIdx, bi.autoIncrFieldName)
}
case TargetedAutoIncrInserter:
err := inserter.InsertAutoIncrToTarget(exec, bi.query, f.Addr().Interface(), bi.args...)
if err != nil {
return err
}
+ case TargetQueryInserter:
+ var idQuery = table.ColMap(bi.autoIncrFieldName).GeneratedIdQuery
+ if idQuery == "" {
+ return fmt.Errorf("gorp: cannot set %s value if its ColumnMap.GeneratedIdQuery is empty", bi.autoIncrFieldName)
+ }
+ err := inserter.InsertQueryToTarget(exec, bi.query, idQuery, f.Addr().Interface(), bi.args...)
+ if err != nil {
+ return err
+ }
default:
- return fmt.Errorf("gorp: Cannot use autoincrement fields on dialects that do not implement an autoincrementing interface")
+ return fmt.Errorf("gorp: cannot use autoincrement fields on dialects that do not implement an autoincrementing interface")
}
} else {
_, err := exec.Exec(bi.query, bi.args...)
@@ -2125,54 +556,3 @@ func insert(m *DbMap, exec SqlExecutor, list ...interface{}) error {
}
return nil
}
-
-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
-}
-
-// 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
-}
diff --git a/Godeps/_workspace/src/github.com/go-gorp/gorp/gorp_test.go b/Godeps/_workspace/src/github.com/go-gorp/gorp/gorp_test.go
index 6e5618c1f..895ab450e 100644
--- a/Godeps/_workspace/src/github.com/go-gorp/gorp/gorp_test.go
+++ b/Godeps/_workspace/src/github.com/go-gorp/gorp/gorp_test.go
@@ -1,15 +1,29 @@
+// 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"
@@ -20,12 +34,23 @@ import (
_ "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 {
diff --git a/Godeps/_workspace/src/github.com/go-gorp/gorp/hooks.go b/Godeps/_workspace/src/github.com/go-gorp/gorp/hooks.go
new file mode 100644
index 000000000..192b51f00
--- /dev/null
+++ b/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
+}
diff --git a/Godeps/_workspace/src/github.com/go-gorp/gorp/index.go b/Godeps/_workspace/src/github.com/go-gorp/gorp/index.go
new file mode 100644
index 000000000..01ecd9eca
--- /dev/null
+++ b/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
+}
diff --git a/Godeps/_workspace/src/github.com/go-gorp/gorp/lockerror.go b/Godeps/_workspace/src/github.com/go-gorp/gorp/lockerror.go
new file mode 100644
index 000000000..07b3047ae
--- /dev/null
+++ b/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
+}
diff --git a/Godeps/_workspace/src/github.com/go-gorp/gorp/logging.go b/Godeps/_workspace/src/github.com/go-gorp/gorp/logging.go
new file mode 100644
index 000000000..89d6c0e79
--- /dev/null
+++ b/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 = ""
+}
diff --git a/Godeps/_workspace/src/github.com/go-gorp/gorp/nulltypes.go b/Godeps/_workspace/src/github.com/go-gorp/gorp/nulltypes.go
new file mode 100644
index 000000000..870770372
--- /dev/null
+++ b/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
+}
diff --git a/Godeps/_workspace/src/github.com/go-gorp/gorp/select.go b/Godeps/_workspace/src/github.com/go-gorp/gorp/select.go
new file mode 100644
index 000000000..d6ff92ee3
--- /dev/null
+++ b/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
+}
diff --git a/Godeps/_workspace/src/github.com/go-gorp/gorp/table.go b/Godeps/_workspace/src/github.com/go-gorp/gorp/table.go
new file mode 100644
index 000000000..5c513909a
--- /dev/null
+++ b/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()
+}
diff --git a/Godeps/_workspace/src/github.com/go-gorp/gorp/table_bindings.go b/Godeps/_workspace/src/github.com/go-gorp/gorp/table_bindings.go
new file mode 100644
index 000000000..1727d0d09
--- /dev/null
+++ b/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
+}
diff --git a/Godeps/_workspace/src/github.com/go-gorp/gorp/test_all.sh b/Godeps/_workspace/src/github.com/go-gorp/gorp/test_all.sh
index f870b39a3..f2d16961a 100644
--- a/Godeps/_workspace/src/github.com/go-gorp/gorp/test_all.sh
+++ b/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
diff --git a/Godeps/_workspace/src/github.com/go-gorp/gorp/transaction.go b/Godeps/_workspace/src/github.com/go-gorp/gorp/transaction.go
new file mode 100644
index 000000000..6430f24f1
--- /dev/null
+++ b/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...)
+}
diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/AUTHORS b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/AUTHORS
index 4b65bf363..6dd0167f3 100644
--- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/AUTHORS
+++ b/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
diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/README.md b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/README.md
index 9edb7628b..706b7ef2e 100644
--- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/README.md
+++ b/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.
diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/connection.go b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/connection.go
index a6d39bec9..72ed09d69 100644
--- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/connection.go
+++ b/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 {
diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/driver.go b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/driver.go
index 3cbbe6031..d310624ad 100644
--- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/driver.go
+++ b/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
diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/driver_test.go b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/driver_test.go
index cb0d5f5ec..f9da416ec 100644
--- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/driver_test.go
+++ b/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
diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/errors.go b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/errors.go
index 97d7b3996..44cf30db6 100644
--- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/errors.go
+++ b/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)
diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/infile.go b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/infile.go
index 121a04c71..84c53a99c 100644
--- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/infile.go
+++ b/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
diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/packets.go b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/packets.go
index 290a3887a..76cb7c84e 100644
--- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/packets.go
+++ b/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)
diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/rows.go b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/rows.go
index 9d97d6d4f..ba606e146 100644
--- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/rows.go
+++ b/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 {
diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/statement.go b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/statement.go
index f9dae03fa..6e869b340 100644
--- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/statement.go
+++ b/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:
diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/utils.go b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/utils.go
index 6693d2970..6a26ad129 100644
--- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/utils.go
+++ b/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&paramN=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
diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/utils_test.go b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/utils_test.go
index adb8dcbd1..79fbdd1eb 100644
--- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/utils_test.go
+++ b/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) {
diff --git a/Godeps/_workspace/src/github.com/goamz/goamz/aws/aws.go b/Godeps/_workspace/src/github.com/goamz/goamz/aws/aws.go
index cec40be7d..77bf563d6 100644
--- a/Godeps/_workspace/src/github.com/goamz/goamz/aws/aws.go
+++ b/Godeps/_workspace/src/github.com/goamz/goamz/aws/aws.go
@@ -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{
diff --git a/Godeps/_workspace/src/github.com/goamz/goamz/aws/regions.go b/Godeps/_workspace/src/github.com/goamz/goamz/aws/regions.go
index 508231e7d..5e18f023d 100644
--- a/Godeps/_workspace/src/github.com/goamz/goamz/aws/regions.go
+++ b/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",
}
diff --git a/Godeps/_workspace/src/github.com/goamz/goamz/s3/multi.go b/Godeps/_workspace/src/github.com/goamz/goamz/s3/multi.go
index 1533bda9d..348ead300 100644
--- a/Godeps/_workspace/src/github.com/goamz/goamz/s3/multi.go
+++ b/Godeps/_workspace/src/github.com/goamz/goamz/s3/multi.go
@@ -339,9 +339,23 @@ func (p completeParts) Len() int { return len(p) }
func (p completeParts) Less(i, j int) bool { return p[i].PartNumber < p[j].PartNumber }
func (p completeParts) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
+type completeResponse struct {
+ // The element name: should be either CompleteMultipartUploadResult or Error.
+ XMLName xml.Name
+ // If the element was error, then it should have the following:
+ Code string
+ Message string
+ RequestId string
+ HostId string
+}
+
// Complete assembles the given previously uploaded parts into the
// final object. This operation may take several minutes.
//
+// The complete call to AMZ may still fail after returning HTTP 200,
+// so even though it's unusued, the body of the reply must be demarshalled
+// and checked to see whether or not the complete succeeded.
+//
// See http://goo.gl/2Z7Tw for details.
func (m *Multi) Complete(parts []Part) error {
params := map[string][]string{
@@ -356,6 +370,8 @@ func (m *Multi) Complete(parts []Part) error {
if err != nil {
return err
}
+
+ // Setting Content-Length prevents breakage on DreamObjects
for attempt := m.Bucket.S3.AttemptStrategy.Start(); attempt.Next(); {
req := &request{
method: "POST",
@@ -363,11 +379,25 @@ func (m *Multi) Complete(parts []Part) error {
path: m.Key,
params: params,
payload: bytes.NewReader(data),
+ headers: map[string][]string{
+ "Content-Length": []string{strconv.Itoa(len(data))},
+ },
}
- err := m.Bucket.S3.query(req, nil)
+
+ resp := &completeResponse{}
+ err := m.Bucket.S3.query(req, resp)
if shouldRetry(err) && attempt.HasNext() {
continue
}
+ if err == nil && resp.XMLName.Local == "Error" {
+ err = &Error{
+ StatusCode: 200,
+ Code: resp.Code,
+ Message: resp.Message,
+ RequestId: resp.RequestId,
+ HostId: resp.HostId,
+ }
+ }
return err
}
panic("unreachable")
diff --git a/Godeps/_workspace/src/github.com/goamz/goamz/s3/multi_test.go b/Godeps/_workspace/src/github.com/goamz/goamz/s3/multi_test.go
index efab302d6..5c788d9cc 100644
--- a/Godeps/_workspace/src/github.com/goamz/goamz/s3/multi_test.go
+++ b/Godeps/_workspace/src/github.com/goamz/goamz/s3/multi_test.go
@@ -300,7 +300,9 @@ func (s *S) TestMultiComplete(c *C) {
c.Assert(err, IsNil)
err = multi.Complete([]s3.Part{{2, `"ETag2"`, 32}, {1, `"ETag1"`, 64}})
- c.Assert(err, IsNil)
+ // returns InternalErrorDump in the payload, which should manifest as
+ // an error.
+ c.Assert(err, NotNil)
testServer.WaitRequest()
req := testServer.WaitRequest()
diff --git a/Godeps/_workspace/src/github.com/goamz/goamz/s3/s3.go b/Godeps/_workspace/src/github.com/goamz/goamz/s3/s3.go
index 88ef975d1..9490c9b96 100644
--- a/Godeps/_workspace/src/github.com/goamz/goamz/s3/s3.go
+++ b/Godeps/_workspace/src/github.com/goamz/goamz/s3/s3.go
@@ -1101,10 +1101,14 @@ func shouldRetry(err error) bool {
}
case *Error:
switch e.Code {
- case "InternalError", "NoSuchUpload", "NoSuchBucket":
+ case "InternalError", "NoSuchUpload", "NoSuchBucket", "RequestTimeout":
return true
}
+ // let's handle tls handshake timeout issues and similar temporary errors
+ case net.Error:
+ return e.Temporary()
}
+
return false
}
diff --git a/Godeps/_workspace/src/github.com/goamz/goamz/s3/s3test/server.go b/Godeps/_workspace/src/github.com/goamz/goamz/s3/s3test/server.go
index 10d36924f..2016b5659 100644
--- a/Godeps/_workspace/src/github.com/goamz/goamz/s3/s3test/server.go
+++ b/Godeps/_workspace/src/github.com/goamz/goamz/s3/s3test/server.go
@@ -594,6 +594,10 @@ func (objr objectResource) put(a *action) interface{} {
obj.checksum = gotHash
obj.mtime = time.Now()
objr.bucket.objects[objr.name] = obj
+
+ h := a.w.Header()
+ h.Set("ETag", fmt.Sprintf(`"%s"`, hex.EncodeToString(obj.checksum)))
+
return nil
}
diff --git a/Godeps/_workspace/src/github.com/goamz/goamz/s3/sign.go b/Godeps/_workspace/src/github.com/goamz/goamz/s3/sign.go
index c8e57a2f7..722d97d29 100644
--- a/Godeps/_workspace/src/github.com/goamz/goamz/s3/sign.go
+++ b/Godeps/_workspace/src/github.com/goamz/goamz/s3/sign.go
@@ -39,10 +39,37 @@ var s3ParamsToSign = map[string]bool{
"delete": true,
}
+type keySortableTupleList []keySortableTuple
+
+type keySortableTuple struct {
+ Key string
+ TupleString string
+}
+
+func (l keySortableTupleList) StringSlice() []string {
+ slice := make([]string, len(l))
+ for i, v := range l {
+ slice[i] = v.TupleString
+ }
+ return slice
+}
+
+func (l keySortableTupleList) Len() int {
+ return len(l)
+}
+
+func (l keySortableTupleList) Less(i, j int) bool {
+ return l[i].Key < l[j].Key
+}
+
+func (l keySortableTupleList) Swap(i, j int) {
+ l[i], l[j] = l[j], l[i]
+}
+
func sign(auth aws.Auth, method, canonicalPath string, params, headers map[string][]string) {
var md5, ctype, date, xamz string
var xamzDate bool
- var sarray []string
+ var sarray keySortableTupleList
for k, v := range headers {
k = strings.ToLower(k)
switch k {
@@ -57,7 +84,7 @@ func sign(auth aws.Auth, method, canonicalPath string, params, headers map[strin
default:
if strings.HasPrefix(k, "x-amz-") {
vall := strings.Join(v, ",")
- sarray = append(sarray, k+":"+vall)
+ sarray = append(sarray, keySortableTuple{k, k + ":" + vall})
if k == "x-amz-date" {
xamzDate = true
date = ""
@@ -66,8 +93,8 @@ func sign(auth aws.Auth, method, canonicalPath string, params, headers map[strin
}
}
if len(sarray) > 0 {
- sort.StringSlice(sarray).Sort()
- xamz = strings.Join(sarray, "\n") + "\n"
+ sort.Sort(sarray)
+ xamz = strings.Join(sarray.StringSlice(), "\n") + "\n"
}
expires := false
@@ -83,17 +110,17 @@ func sign(auth aws.Auth, method, canonicalPath string, params, headers map[strin
if s3ParamsToSign[k] {
for _, vi := range v {
if vi == "" {
- sarray = append(sarray, k)
+ sarray = append(sarray, keySortableTuple{k, k})
} else {
// "When signing you do not encode these values."
- sarray = append(sarray, k+"="+vi)
+ sarray = append(sarray, keySortableTuple{k, k + "=" + vi})
}
}
}
}
if len(sarray) > 0 {
- sort.StringSlice(sarray).Sort()
- canonicalPath = canonicalPath + "?" + strings.Join(sarray, "&")
+ sort.Sort(sarray)
+ canonicalPath = canonicalPath + "?" + strings.Join(sarray.StringSlice(), "&")
}
payload := method + "\n" + md5 + "\n" + ctype + "\n" + date + "\n" + xamz + canonicalPath
diff --git a/Godeps/_workspace/src/github.com/golang/freetype/AUTHORS b/Godeps/_workspace/src/github.com/golang/freetype/AUTHORS
index 5d8b8a6b7..7b70f7768 100644
--- a/Godeps/_workspace/src/github.com/golang/freetype/AUTHORS
+++ b/Godeps/_workspace/src/github.com/golang/freetype/AUTHORS
@@ -15,3 +15,4 @@ Google Inc.
Jeff R. Allen <jra@nella.org>
Rémy Oudompheng <oudomphe@phare.normalesup.org>
Roger Peppe <rogpeppe@gmail.com>
+Steven Edwards <steven@stephenwithav.com>
diff --git a/Godeps/_workspace/src/github.com/golang/freetype/CONTRIBUTORS b/Godeps/_workspace/src/github.com/golang/freetype/CONTRIBUTORS
index 32cb6753b..7494b12c3 100644
--- a/Godeps/_workspace/src/github.com/golang/freetype/CONTRIBUTORS
+++ b/Godeps/_workspace/src/github.com/golang/freetype/CONTRIBUTORS
@@ -33,3 +33,4 @@ Rémy Oudompheng <oudomphe@phare.normalesup.org> <remyoudompheng@gmail.com>
Rob Pike <r@golang.org>
Roger Peppe <rogpeppe@gmail.com>
Russ Cox <rsc@golang.org>
+Steven Edwards <steven@stephenwithav.com>
diff --git a/Godeps/_workspace/src/github.com/golang/freetype/truetype/truetype.go b/Godeps/_workspace/src/github.com/golang/freetype/truetype/truetype.go
index 7d166ca77..692e01526 100644
--- a/Godeps/_workspace/src/github.com/golang/freetype/truetype/truetype.go
+++ b/Godeps/_workspace/src/github.com/golang/freetype/truetype/truetype.go
@@ -26,6 +26,43 @@ import (
// An Index is a Font's index of a rune.
type Index uint16
+// A NameID identifies a name table entry.
+//
+// See https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6name.html
+type NameID uint16
+
+const (
+ NameIDCopyright NameID = 0
+ NameIDFontFamily = 1
+ NameIDFontSubfamily = 2
+ NameIDUniqueSubfamilyID = 3
+ NameIDFontFullName = 4
+ NameIDNameTableVersion = 5
+ NameIDPostscriptName = 6
+ NameIDTrademarkNotice = 7
+ NameIDManufacturerName = 8
+ NameIDDesignerName = 9
+ NameIDFontDescription = 10
+ NameIDFontVendorURL = 11
+ NameIDFontDesignerURL = 12
+ NameIDFontLicense = 13
+ NameIDFontLicenseURL = 14
+ NameIDPreferredFamily = 16
+ NameIDPreferredSubfamily = 17
+ NameIDCompatibleName = 18
+ NameIDSampleText = 19
+)
+
+const (
+ // A 32-bit encoding consists of a most-significant 16-bit Platform ID and a
+ // least-significant 16-bit Platform Specific ID. The magic numbers are
+ // specified at https://www.microsoft.com/typography/otspec/name.htm
+ unicodeEncoding = 0x00000003 // PID = 0 (Unicode), PSID = 3 (Unicode 2.0)
+ microsoftSymbolEncoding = 0x00030000 // PID = 3 (Microsoft), PSID = 0 (Symbol)
+ microsoftUCS2Encoding = 0x00030001 // PID = 3 (Microsoft), PSID = 1 (UCS-2)
+ microsoftUCS4Encoding = 0x0003000a // PID = 3 (Microsoft), PSID = 10 (UCS-4)
+)
+
// An HMetric holds the horizontal metrics of a single glyph.
type HMetric struct {
AdvanceWidth, LeftSideBearing fixed.Int26_6
@@ -78,6 +115,51 @@ func readTable(ttf []byte, offsetLength []byte) ([]byte, error) {
return ttf[offset:end], nil
}
+// parseSubtables returns the offset and platformID of the best subtable in
+// table, where best favors a Unicode cmap encoding, and failing that, a
+// Microsoft cmap encoding. offset is the offset of the first subtable in
+// table, and size is the size of each subtable.
+//
+// If pred is non-nil, then only subtables that satisfy that predicate will be
+// considered.
+func parseSubtables(table []byte, name string, offset, size int, pred func([]byte) bool) (
+ bestOffset int, bestPID uint32, retErr error) {
+
+ if len(table) < 4 {
+ return 0, 0, FormatError(name + " too short")
+ }
+ nSubtables := int(u16(table, 2))
+ if len(table) < size*nSubtables+offset {
+ return 0, 0, FormatError(name + " too short")
+ }
+ ok := false
+ for i := 0; i < nSubtables; i, offset = i+1, offset+size {
+ if pred != nil && !pred(table[offset:]) {
+ continue
+ }
+ // We read the 16-bit Platform ID and 16-bit Platform Specific ID as a single uint32.
+ // All values are big-endian.
+ pidPsid := u32(table, offset)
+ // We prefer the Unicode cmap encoding. Failing to find that, we fall
+ // back onto the Microsoft cmap encoding.
+ if pidPsid == unicodeEncoding {
+ bestOffset, bestPID, ok = offset, pidPsid>>16, true
+ break
+
+ } else if pidPsid == microsoftSymbolEncoding ||
+ pidPsid == microsoftUCS2Encoding ||
+ pidPsid == microsoftUCS4Encoding {
+
+ bestOffset, bestPID, ok = offset, pidPsid>>16, true
+ // We don't break out of the for loop, so that Unicode can override Microsoft.
+ }
+ }
+ if !ok {
+ return 0, 0, UnsupportedError(name + " encoding")
+ }
+ return bestOffset, bestPID, nil
+}
+
const (
locaOffsetFormatUnknown int = iota
locaOffsetFormatShort
@@ -93,7 +175,7 @@ type cm struct {
type Font struct {
// Tables sliced from the TTF data. The different tables are documented
// at http://developer.apple.com/fonts/TTRefMan/RM06/Chap6.html
- cmap, cvt, fpgm, glyf, hdmx, head, hhea, hmtx, kern, loca, maxp, os2, prep, vmtx []byte
+ cmap, cvt, fpgm, glyf, hdmx, head, hhea, hmtx, kern, loca, maxp, name, os2, prep, vmtx []byte
cmapIndexes []byte
@@ -112,46 +194,13 @@ func (f *Font) parseCmap() error {
cmapFormat4 = 4
cmapFormat12 = 12
languageIndependent = 0
-
- // A 32-bit encoding consists of a most-significant 16-bit Platform ID and a
- // least-significant 16-bit Platform Specific ID. The magic numbers are
- // specified at https://www.microsoft.com/typography/otspec/name.htm
- unicodeEncoding = 0x00000003 // PID = 0 (Unicode), PSID = 3 (Unicode 2.0)
- microsoftSymbolEncoding = 0x00030000 // PID = 3 (Microsoft), PSID = 0 (Symbol)
- microsoftUCS2Encoding = 0x00030001 // PID = 3 (Microsoft), PSID = 1 (UCS-2)
- microsoftUCS4Encoding = 0x0003000a // PID = 3 (Microsoft), PSID = 10 (UCS-4)
)
- if len(f.cmap) < 4 {
- return FormatError("cmap too short")
- }
- nsubtab := int(u16(f.cmap, 2))
- if len(f.cmap) < 8*nsubtab+4 {
- return FormatError("cmap too short")
- }
- offset, found, x := 0, false, 4
- for i := 0; i < nsubtab; i++ {
- // We read the 16-bit Platform ID and 16-bit Platform Specific ID as a single uint32.
- // All values are big-endian.
- pidPsid, o := u32(f.cmap, x), u32(f.cmap, x+4)
- x += 8
- // We prefer the Unicode cmap encoding. Failing to find that, we fall
- // back onto the Microsoft cmap encoding.
- if pidPsid == unicodeEncoding {
- offset, found = int(o), true
- break
-
- } else if pidPsid == microsoftSymbolEncoding ||
- pidPsid == microsoftUCS2Encoding ||
- pidPsid == microsoftUCS4Encoding {
-
- offset, found = int(o), true
- // We don't break out of the for loop, so that Unicode can override Microsoft.
- }
- }
- if !found {
- return UnsupportedError("cmap encoding")
+ offset, _, err := parseSubtables(f.cmap, "cmap", 4, 8, nil)
+ if err != nil {
+ return err
}
+ offset = int(u32(f.cmap, offset+4))
if offset <= 0 || offset > len(f.cmap) {
return FormatError("bad cmap offset")
}
@@ -345,6 +394,44 @@ func (f *Font) Index(x rune) Index {
return 0
}
+// Name returns the Font's name value for the given NameID. It returns "" if
+// there was an error, or if that name was not found.
+func (f *Font) Name(id NameID) string {
+ x, platformID, err := parseSubtables(f.name, "name", 6, 12, func(b []byte) bool {
+ return NameID(u16(b, 6)) == id
+ })
+ if err != nil {
+ return ""
+ }
+ offset, length := u16(f.name, 4)+u16(f.name, x+10), u16(f.name, x+8)
+ // Return the ASCII value of the encoded string.
+ // The string is encoded as UTF-16 on non-Apple platformIDs; Apple is platformID 1.
+ src := f.name[offset : offset+length]
+ var dst []byte
+ if platformID != 1 { // UTF-16.
+ if len(src)&1 != 0 {
+ return ""
+ }
+ dst = make([]byte, len(src)/2)
+ for i := range dst {
+ dst[i] = printable(u16(src, 2*i))
+ }
+ } else { // ASCII.
+ dst = make([]byte, len(src))
+ for i, c := range src {
+ dst[i] = printable(uint16(c))
+ }
+ }
+ return string(dst)
+}
+
+func printable(r uint16) byte {
+ if 0x20 <= r && r < 0x7f {
+ return byte(r)
+ }
+ return '?'
+}
+
// unscaledHMetric returns the unscaled horizontal metrics for the glyph with
// the given index.
func (f *Font) unscaledHMetric(i Index) (h HMetric) {
@@ -518,6 +605,8 @@ func parse(ttf []byte, offset int) (font *Font, err error) {
f.loca, err = readTable(ttf, ttf[x+8:x+16])
case "maxp":
f.maxp, err = readTable(ttf, ttf[x+8:x+16])
+ case "name":
+ f.name, err = readTable(ttf, ttf[x+8:x+16])
case "OS/2":
f.os2, err = readTable(ttf, ttf[x+8:x+16])
case "prep":
diff --git a/Godeps/_workspace/src/github.com/golang/freetype/truetype/truetype_test.go b/Godeps/_workspace/src/github.com/golang/freetype/truetype/truetype_test.go
index ce7f1277a..bd62d1da1 100644
--- a/Godeps/_workspace/src/github.com/golang/freetype/truetype/truetype_test.go
+++ b/Godeps/_workspace/src/github.com/golang/freetype/truetype/truetype_test.go
@@ -211,6 +211,29 @@ func TestIndex(t *testing.T) {
}
}
+func TestName(t *testing.T) {
+ testCases := map[string]string{
+ "luximr": "Luxi Mono",
+ "luxirr": "Luxi Serif",
+ "luxisr": "Luxi Sans",
+ }
+
+ for name, want := range testCases {
+ f, testdataIsOptional, err := parseTestdataFont(name)
+ if err != nil {
+ if testdataIsOptional {
+ t.Log(err)
+ } else {
+ t.Fatal(err)
+ }
+ continue
+ }
+ if got := f.Name(NameIDFontFamily); got != want {
+ t.Errorf("%s: got %q, want %q", name, got, want)
+ }
+ }
+}
+
type scalingTestData struct {
advanceWidth fixed.Int26_6
bounds fixed.Rectangle26_6
diff --git a/Godeps/_workspace/src/github.com/gorilla/context/.travis.yml b/Godeps/_workspace/src/github.com/gorilla/context/.travis.yml
index 6796581fb..f983b60c6 100644
--- a/Godeps/_workspace/src/github.com/gorilla/context/.travis.yml
+++ b/Godeps/_workspace/src/github.com/gorilla/context/.travis.yml
@@ -1,9 +1,8 @@
language: go
+sudo: false
go:
- - 1.0
- - 1.1
- - 1.2
- 1.3
- 1.4
+ - 1.5
- tip
diff --git a/Godeps/_workspace/src/github.com/gorilla/mux/.travis.yml b/Godeps/_workspace/src/github.com/gorilla/mux/.travis.yml
index d87d46576..83ab8f59d 100644
--- a/Godeps/_workspace/src/github.com/gorilla/mux/.travis.yml
+++ b/Godeps/_workspace/src/github.com/gorilla/mux/.travis.yml
@@ -1,7 +1,14 @@
language: go
-
+sudo: false
go:
- - 1.0
- - 1.1
- - 1.2
+ - 1.3
+ - 1.4
+ - 1.5
- tip
+install:
+ - go get golang.org/x/tools/cmd/vet
+script:
+ - go get -t -v ./...
+ - diff -u <(echo -n) <(gofmt -d -s .)
+ - go tool vet .
+ - go test -v -race ./...
diff --git a/Godeps/_workspace/src/github.com/gorilla/mux/README.md b/Godeps/_workspace/src/github.com/gorilla/mux/README.md
index e60301b03..55dd4e59a 100644
--- a/Godeps/_workspace/src/github.com/gorilla/mux/README.md
+++ b/Godeps/_workspace/src/github.com/gorilla/mux/README.md
@@ -1,7 +1,235 @@
mux
===
+[![GoDoc](https://godoc.org/github.com/gorilla/mux?status.svg)](https://godoc.org/github.com/gorilla/mux)
[![Build Status](https://travis-ci.org/gorilla/mux.png?branch=master)](https://travis-ci.org/gorilla/mux)
-gorilla/mux is a powerful URL router and dispatcher.
+Package gorilla/mux implements a request router and dispatcher.
-Read the full documentation here: http://www.gorillatoolkit.org/pkg/mux
+The name mux stands for "HTTP request multiplexer". Like the standard
+http.ServeMux, mux.Router matches incoming requests against a list of
+registered routes and calls a handler for the route that matches the URL
+or other conditions. The main features are:
+
+ * Requests can be matched based on URL host, path, path prefix, schemes,
+ header and query values, HTTP methods or using custom matchers.
+ * URL hosts and paths can have variables with an optional regular
+ expression.
+ * Registered URLs can be built, or "reversed", which helps maintaining
+ references to resources.
+ * Routes can be used as subrouters: nested routes are only tested if the
+ parent route matches. This is useful to define groups of routes that
+ share common conditions like a host, a path prefix or other repeated
+ attributes. As a bonus, this optimizes request matching.
+ * It implements the http.Handler interface so it is compatible with the
+ standard http.ServeMux.
+
+Let's start registering a couple of URL paths and handlers:
+
+ func main() {
+ r := mux.NewRouter()
+ r.HandleFunc("/", HomeHandler)
+ r.HandleFunc("/products", ProductsHandler)
+ r.HandleFunc("/articles", ArticlesHandler)
+ http.Handle("/", r)
+ }
+
+Here we register three routes mapping URL paths to handlers. This is
+equivalent to how http.HandleFunc() works: if an incoming request URL matches
+one of the paths, the corresponding handler is called passing
+(http.ResponseWriter, *http.Request) as parameters.
+
+Paths can have variables. They are defined using the format {name} or
+{name:pattern}. If a regular expression pattern is not defined, the matched
+variable will be anything until the next slash. For example:
+
+ r := mux.NewRouter()
+ r.HandleFunc("/products/{key}", ProductHandler)
+ r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
+ r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
+
+The names are used to create a map of route variables which can be retrieved
+calling mux.Vars():
+
+ vars := mux.Vars(request)
+ category := vars["category"]
+
+And this is all you need to know about the basic usage. More advanced options
+are explained below.
+
+Routes can also be restricted to a domain or subdomain. Just define a host
+pattern to be matched. They can also have variables:
+
+ r := mux.NewRouter()
+ // Only matches if domain is "www.example.com".
+ r.Host("www.example.com")
+ // Matches a dynamic subdomain.
+ r.Host("{subdomain:[a-z]+}.domain.com")
+
+There are several other matchers that can be added. To match path prefixes:
+
+ r.PathPrefix("/products/")
+
+...or HTTP methods:
+
+ r.Methods("GET", "POST")
+
+...or URL schemes:
+
+ r.Schemes("https")
+
+...or header values:
+
+ r.Headers("X-Requested-With", "XMLHttpRequest")
+
+...or query values:
+
+ r.Queries("key", "value")
+
+...or to use a custom matcher function:
+
+ r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool {
+ return r.ProtoMajor == 0
+ })
+
+...and finally, it is possible to combine several matchers in a single route:
+
+ r.HandleFunc("/products", ProductsHandler).
+ Host("www.example.com").
+ Methods("GET").
+ Schemes("http")
+
+Setting the same matching conditions again and again can be boring, so we have
+a way to group several routes that share the same requirements.
+We call it "subrouting".
+
+For example, let's say we have several URLs that should only match when the
+host is `www.example.com`. Create a route for that host and get a "subrouter"
+from it:
+
+ r := mux.NewRouter()
+ s := r.Host("www.example.com").Subrouter()
+
+Then register routes in the subrouter:
+
+ s.HandleFunc("/products/", ProductsHandler)
+ s.HandleFunc("/products/{key}", ProductHandler)
+ s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)
+
+The three URL paths we registered above will only be tested if the domain is
+`www.example.com`, because the subrouter is tested first. This is not
+only convenient, but also optimizes request matching. You can create
+subrouters combining any attribute matchers accepted by a route.
+
+Subrouters can be used to create domain or path "namespaces": you define
+subrouters in a central place and then parts of the app can register its
+paths relatively to a given subrouter.
+
+There's one more thing about subroutes. When a subrouter has a path prefix,
+the inner routes use it as base for their paths:
+
+ r := mux.NewRouter()
+ s := r.PathPrefix("/products").Subrouter()
+ // "/products/"
+ s.HandleFunc("/", ProductsHandler)
+ // "/products/{key}/"
+ s.HandleFunc("/{key}/", ProductHandler)
+ // "/products/{key}/details"
+ s.HandleFunc("/{key}/details", ProductDetailsHandler)
+
+Now let's see how to build registered URLs.
+
+Routes can be named. All routes that define a name can have their URLs built,
+or "reversed". We define a name calling Name() on a route. For example:
+
+ r := mux.NewRouter()
+ r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
+ Name("article")
+
+To build a URL, get the route and call the URL() method, passing a sequence of
+key/value pairs for the route variables. For the previous route, we would do:
+
+ url, err := r.Get("article").URL("category", "technology", "id", "42")
+
+...and the result will be a url.URL with the following path:
+
+ "/articles/technology/42"
+
+This also works for host variables:
+
+ r := mux.NewRouter()
+ r.Host("{subdomain}.domain.com").
+ Path("/articles/{category}/{id:[0-9]+}").
+ HandlerFunc(ArticleHandler).
+ Name("article")
+
+ // url.String() will be "http://news.domain.com/articles/technology/42"
+ url, err := r.Get("article").URL("subdomain", "news",
+ "category", "technology",
+ "id", "42")
+
+All variables defined in the route are required, and their values must
+conform to the corresponding patterns. These requirements guarantee that a
+generated URL will always match a registered route -- the only exception is
+for explicitly defined "build-only" routes which never match.
+
+Regex support also exists for matching Headers within a route. For example, we could do:
+
+ r.HeadersRegexp("Content-Type", "application/(text|json)")
+
+...and the route will match both requests with a Content-Type of `application/json` as well as
+`application/text`
+
+There's also a way to build only the URL host or path for a route:
+use the methods URLHost() or URLPath() instead. For the previous route,
+we would do:
+
+ // "http://news.domain.com/"
+ host, err := r.Get("article").URLHost("subdomain", "news")
+
+ // "/articles/technology/42"
+ path, err := r.Get("article").URLPath("category", "technology", "id", "42")
+
+And if you use subrouters, host and path defined separately can be built
+as well:
+
+ r := mux.NewRouter()
+ s := r.Host("{subdomain}.domain.com").Subrouter()
+ s.Path("/articles/{category}/{id:[0-9]+}").
+ HandlerFunc(ArticleHandler).
+ Name("article")
+
+ // "http://news.domain.com/articles/technology/42"
+ url, err := r.Get("article").URL("subdomain", "news",
+ "category", "technology",
+ "id", "42")
+
+## Full Example
+
+Here's a complete, runnable example of a small mux based server:
+
+```go
+package main
+
+import (
+ "net/http"
+
+ "github.com/gorilla/mux"
+)
+
+func YourHandler(w http.ResponseWriter, r *http.Request) {
+ w.Write([]byte("Gorilla!\n"))
+}
+
+func main() {
+ r := mux.NewRouter()
+ // Routes consist of a path and a handler function.
+ r.HandleFunc("/", YourHandler)
+
+ // Bind to a port and pass our router in
+ http.ListenAndServe(":8000", r)
+}
+```
+
+## License
+
+BSD licensed. See the LICENSE file for details.
diff --git a/Godeps/_workspace/src/github.com/gorilla/mux/doc.go b/Godeps/_workspace/src/github.com/gorilla/mux/doc.go
index 9a5e381a2..49798cb5c 100644
--- a/Godeps/_workspace/src/github.com/gorilla/mux/doc.go
+++ b/Godeps/_workspace/src/github.com/gorilla/mux/doc.go
@@ -60,8 +60,8 @@ Routes can also be restricted to a domain or subdomain. Just define a host
pattern to be matched. They can also have variables:
r := mux.NewRouter()
- // Only matches if domain is "www.domain.com".
- r.Host("www.domain.com")
+ // Only matches if domain is "www.example.com".
+ r.Host("www.example.com")
// Matches a dynamic subdomain.
r.Host("{subdomain:[a-z]+}.domain.com")
@@ -94,7 +94,7 @@ There are several other matchers that can be added. To match path prefixes:
...and finally, it is possible to combine several matchers in a single route:
r.HandleFunc("/products", ProductsHandler).
- Host("www.domain.com").
+ Host("www.example.com").
Methods("GET").
Schemes("http")
@@ -103,11 +103,11 @@ a way to group several routes that share the same requirements.
We call it "subrouting".
For example, let's say we have several URLs that should only match when the
-host is "www.domain.com". Create a route for that host and get a "subrouter"
+host is "www.example.com". Create a route for that host and get a "subrouter"
from it:
r := mux.NewRouter()
- s := r.Host("www.domain.com").Subrouter()
+ s := r.Host("www.example.com").Subrouter()
Then register routes in the subrouter:
@@ -116,7 +116,7 @@ Then register routes in the subrouter:
s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)
The three URL paths we registered above will only be tested if the domain is
-"www.domain.com", because the subrouter is tested first. This is not
+"www.example.com", because the subrouter is tested first. This is not
only convenient, but also optimizes request matching. You can create
subrouters combining any attribute matchers accepted by a route.
@@ -172,6 +172,13 @@ conform to the corresponding patterns. These requirements guarantee that a
generated URL will always match a registered route -- the only exception is
for explicitly defined "build-only" routes which never match.
+Regex support also exists for matching Headers within a route. For example, we could do:
+
+ r.HeadersRegexp("Content-Type", "application/(text|json)")
+
+...and the route will match both requests with a Content-Type of `application/json` as well as
+`application/text`
+
There's also a way to build only the URL host or path for a route:
use the methods URLHost() or URLPath() instead. For the previous route,
we would do:
diff --git a/Godeps/_workspace/src/github.com/gorilla/mux/mux.go b/Godeps/_workspace/src/github.com/gorilla/mux/mux.go
index af31d2395..68c4ea5d8 100644
--- a/Godeps/_workspace/src/github.com/gorilla/mux/mux.go
+++ b/Godeps/_workspace/src/github.com/gorilla/mux/mux.go
@@ -5,9 +5,11 @@
package mux
import (
+ "errors"
"fmt"
"net/http"
"path"
+ "regexp"
"github.com/gorilla/context"
)
@@ -68,7 +70,7 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// Clean path to canonical form and redirect.
if p := cleanPath(req.URL.Path); p != req.URL.Path {
- // Added 3 lines (Philip Schlump) - It was droping the query string and #whatever from query.
+ // Added 3 lines (Philip Schlump) - It was dropping the query string and #whatever from query.
// This matches with fix in go 1.2 r.c. 4 for same problem. Go Issue:
// http://code.google.com/p/go/issues/detail?id=5252
url := *req.URL
@@ -237,6 +239,52 @@ func (r *Router) BuildVarsFunc(f BuildVarsFunc) *Route {
return r.NewRoute().BuildVarsFunc(f)
}
+// Walk walks the router and all its sub-routers, calling walkFn for each route
+// in the tree. The routes are walked in the order they were added. Sub-routers
+// are explored depth-first.
+func (r *Router) Walk(walkFn WalkFunc) error {
+ return r.walk(walkFn, []*Route{})
+}
+
+// SkipRouter is used as a return value from WalkFuncs to indicate that the
+// router that walk is about to descend down to should be skipped.
+var SkipRouter = errors.New("skip this router")
+
+// WalkFunc is the type of the function called for each route visited by Walk.
+// At every invocation, it is given the current route, and the current router,
+// and a list of ancestor routes that lead to the current route.
+type WalkFunc func(route *Route, router *Router, ancestors []*Route) error
+
+func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error {
+ for _, t := range r.routes {
+ if t.regexp == nil || t.regexp.path == nil || t.regexp.path.template == "" {
+ continue
+ }
+
+ err := walkFn(t, r, ancestors)
+ if err == SkipRouter {
+ continue
+ }
+ for _, sr := range t.matchers {
+ if h, ok := sr.(*Router); ok {
+ err := h.walk(walkFn, ancestors)
+ if err != nil {
+ return err
+ }
+ }
+ }
+ if h, ok := t.handler.(*Router); ok {
+ ancestors = append(ancestors, t)
+ err := h.walk(walkFn, ancestors)
+ if err != nil {
+ return err
+ }
+ ancestors = ancestors[:len(ancestors)-1]
+ }
+ }
+ return nil
+}
+
// ----------------------------------------------------------------------------
// Context
// ----------------------------------------------------------------------------
@@ -264,6 +312,10 @@ func Vars(r *http.Request) map[string]string {
}
// CurrentRoute returns the matched route for the current request, if any.
+// This only works when called inside the handler of the matched route
+// because the matched route is stored in the request context which is cleared
+// after the handler returns, unless the KeepContext option is set on the
+// Router.
func CurrentRoute(r *http.Request) *Route {
if rv := context.Get(r, routeKey); rv != nil {
return rv.(*Route)
@@ -313,13 +365,24 @@ func uniqueVars(s1, s2 []string) error {
return nil
}
-// mapFromPairs converts variadic string parameters to a string map.
-func mapFromPairs(pairs ...string) (map[string]string, error) {
+// checkPairs returns the count of strings passed in, and an error if
+// the count is not an even number.
+func checkPairs(pairs ...string) (int, error) {
length := len(pairs)
if length%2 != 0 {
- return nil, fmt.Errorf(
+ return length, fmt.Errorf(
"mux: number of parameters must be multiple of 2, got %v", pairs)
}
+ return length, nil
+}
+
+// mapFromPairsToString converts variadic string parameters to a
+// string to string map.
+func mapFromPairsToString(pairs ...string) (map[string]string, error) {
+ length, err := checkPairs(pairs...)
+ if err != nil {
+ return nil, err
+ }
m := make(map[string]string, length/2)
for i := 0; i < length; i += 2 {
m[pairs[i]] = pairs[i+1]
@@ -327,6 +390,24 @@ func mapFromPairs(pairs ...string) (map[string]string, error) {
return m, nil
}
+// mapFromPairsToRegex converts variadic string paramers to a
+// string to regex map.
+func mapFromPairsToRegex(pairs ...string) (map[string]*regexp.Regexp, error) {
+ length, err := checkPairs(pairs...)
+ if err != nil {
+ return nil, err
+ }
+ m := make(map[string]*regexp.Regexp, length/2)
+ for i := 0; i < length; i += 2 {
+ regex, err := regexp.Compile(pairs[i+1])
+ if err != nil {
+ return nil, err
+ }
+ m[pairs[i]] = regex
+ }
+ return m, nil
+}
+
// matchInArray returns true if the given string value is in the array.
func matchInArray(arr []string, value string) bool {
for _, v := range arr {
@@ -337,9 +418,8 @@ func matchInArray(arr []string, value string) bool {
return false
}
-// matchMap returns true if the given key/value pairs exist in a given map.
-func matchMap(toCheck map[string]string, toMatch map[string][]string,
- canonicalKey bool) bool {
+// matchMapWithString returns true if the given key/value pairs exist in a given map.
+func matchMapWithString(toCheck map[string]string, toMatch map[string][]string, canonicalKey bool) bool {
for k, v := range toCheck {
// Check if key exists.
if canonicalKey {
@@ -364,3 +444,31 @@ func matchMap(toCheck map[string]string, toMatch map[string][]string,
}
return true
}
+
+// matchMapWithRegex returns true if the given key/value pairs exist in a given map compiled against
+// the given regex
+func matchMapWithRegex(toCheck map[string]*regexp.Regexp, toMatch map[string][]string, canonicalKey bool) bool {
+ for k, v := range toCheck {
+ // Check if key exists.
+ if canonicalKey {
+ k = http.CanonicalHeaderKey(k)
+ }
+ if values := toMatch[k]; values == nil {
+ return false
+ } else if v != nil {
+ // If value was defined as an empty string we only check that the
+ // key exists. Otherwise we also check for equality.
+ valueExists := false
+ for _, value := range values {
+ if v.MatchString(value) {
+ valueExists = true
+ break
+ }
+ }
+ if !valueExists {
+ return false
+ }
+ }
+ }
+ return true
+}
diff --git a/Godeps/_workspace/src/github.com/gorilla/mux/mux_test.go b/Godeps/_workspace/src/github.com/gorilla/mux/mux_test.go
index 6b2c1d22f..d1eae9265 100644
--- a/Godeps/_workspace/src/github.com/gorilla/mux/mux_test.go
+++ b/Godeps/_workspace/src/github.com/gorilla/mux/mux_test.go
@@ -7,11 +7,24 @@ package mux
import (
"fmt"
"net/http"
+ "strings"
"testing"
"github.com/gorilla/context"
)
+func (r *Route) GoString() string {
+ matchers := make([]string, len(r.matchers))
+ for i, m := range r.matchers {
+ matchers[i] = fmt.Sprintf("%#v", m)
+ }
+ return fmt.Sprintf("&Route{matchers:[]matcher{%s}}", strings.Join(matchers, ", "))
+}
+
+func (r *routeRegexp) GoString() string {
+ return fmt.Sprintf("&routeRegexp{template: %q, matchHost: %t, matchQuery: %t, strictSlash: %t, regexp: regexp.MustCompile(%q), reverse: %q, varsN: %v, varsR: %v", r.template, r.matchHost, r.matchQuery, r.strictSlash, r.regexp.String(), r.reverse, r.varsN, r.varsR)
+}
+
type routeTest struct {
title string // title of the test
route *Route // the route being tested
@@ -109,6 +122,15 @@ func TestHost(t *testing.T) {
shouldMatch: true,
},
{
+ title: "Host route with pattern, additional capturing group, match",
+ route: new(Route).Host("aaa.{v1:[a-z]{2}(b|c)}.ccc"),
+ request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
+ vars: map[string]string{"v1": "bbb"},
+ host: "aaa.bbb.ccc",
+ path: "",
+ shouldMatch: true,
+ },
+ {
title: "Host route with pattern, wrong host in request URL",
route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"),
request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
@@ -136,6 +158,33 @@ func TestHost(t *testing.T) {
shouldMatch: false,
},
{
+ title: "Host route with hyphenated name and pattern, match",
+ route: new(Route).Host("aaa.{v-1:[a-z]{3}}.ccc"),
+ request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
+ vars: map[string]string{"v-1": "bbb"},
+ host: "aaa.bbb.ccc",
+ path: "",
+ shouldMatch: true,
+ },
+ {
+ title: "Host route with hyphenated name and pattern, additional capturing group, match",
+ route: new(Route).Host("aaa.{v-1:[a-z]{2}(b|c)}.ccc"),
+ request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
+ vars: map[string]string{"v-1": "bbb"},
+ host: "aaa.bbb.ccc",
+ path: "",
+ shouldMatch: true,
+ },
+ {
+ title: "Host route with multiple hyphenated names and patterns, match",
+ route: new(Route).Host("{v-1:[a-z]{3}}.{v-2:[a-z]{3}}.{v-3:[a-z]{3}}"),
+ request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
+ vars: map[string]string{"v-1": "aaa", "v-2": "bbb", "v-3": "ccc"},
+ host: "aaa.bbb.ccc",
+ path: "",
+ shouldMatch: true,
+ },
+ {
title: "Path route with single pattern with pipe, match",
route: new(Route).Path("/{category:a|b/c}"),
request: newRequest("GET", "http://localhost/a"),
@@ -260,6 +309,42 @@ func TestPath(t *testing.T) {
path: "/111/222/333",
shouldMatch: false,
},
+ {
+ title: "Path route with multiple patterns with pipe, match",
+ route: new(Route).Path("/{category:a|(b/c)}/{product}/{id:[0-9]+}"),
+ request: newRequest("GET", "http://localhost/a/product_name/1"),
+ vars: map[string]string{"category": "a", "product": "product_name", "id": "1"},
+ host: "",
+ path: "/a/product_name/1",
+ shouldMatch: true,
+ },
+ {
+ title: "Path route with hyphenated name and pattern, match",
+ route: new(Route).Path("/111/{v-1:[0-9]{3}}/333"),
+ request: newRequest("GET", "http://localhost/111/222/333"),
+ vars: map[string]string{"v-1": "222"},
+ host: "",
+ path: "/111/222/333",
+ shouldMatch: true,
+ },
+ {
+ title: "Path route with multiple hyphenated names and patterns, match",
+ route: new(Route).Path("/{v-1:[0-9]{3}}/{v-2:[0-9]{3}}/{v-3:[0-9]{3}}"),
+ request: newRequest("GET", "http://localhost/111/222/333"),
+ vars: map[string]string{"v-1": "111", "v-2": "222", "v-3": "333"},
+ host: "",
+ path: "/111/222/333",
+ shouldMatch: true,
+ },
+ {
+ title: "Path route with multiple hyphenated names and patterns with pipe, match",
+ route: new(Route).Path("/{product-category:a|(b/c)}/{product-name}/{product-id:[0-9]+}"),
+ request: newRequest("GET", "http://localhost/a/product_name/1"),
+ vars: map[string]string{"product-category": "a", "product-name": "product_name", "product-id": "1"},
+ host: "",
+ path: "/a/product_name/1",
+ shouldMatch: true,
+ },
}
for _, test := range tests {
@@ -434,6 +519,24 @@ func TestHeaders(t *testing.T) {
path: "",
shouldMatch: false,
},
+ {
+ title: "Headers route, regex header values to match",
+ route: new(Route).Headers("foo", "ba[zr]"),
+ request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar"}),
+ vars: map[string]string{},
+ host: "",
+ path: "",
+ shouldMatch: false,
+ },
+ {
+ title: "Headers route, regex header values to match",
+ route: new(Route).HeadersRegexp("foo", "ba[zr]"),
+ request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "baz"}),
+ vars: map[string]string{},
+ host: "",
+ path: "",
+ shouldMatch: true,
+ },
}
for _, test := range tests {
@@ -552,6 +655,150 @@ func TestQueries(t *testing.T) {
path: "",
shouldMatch: false,
},
+ {
+ title: "Queries route with regexp pattern with quantifier, match",
+ route: new(Route).Queries("foo", "{v1:[0-9]{1}}"),
+ request: newRequest("GET", "http://localhost?foo=1"),
+ vars: map[string]string{"v1": "1"},
+ host: "",
+ path: "",
+ shouldMatch: true,
+ },
+ {
+ title: "Queries route with regexp pattern with quantifier, additional variable in query string, match",
+ route: new(Route).Queries("foo", "{v1:[0-9]{1}}"),
+ request: newRequest("GET", "http://localhost?bar=2&foo=1"),
+ vars: map[string]string{"v1": "1"},
+ host: "",
+ path: "",
+ shouldMatch: true,
+ },
+ {
+ title: "Queries route with regexp pattern with quantifier, regexp does not match",
+ route: new(Route).Queries("foo", "{v1:[0-9]{1}}"),
+ request: newRequest("GET", "http://localhost?foo=12"),
+ vars: map[string]string{},
+ host: "",
+ path: "",
+ shouldMatch: false,
+ },
+ {
+ title: "Queries route with regexp pattern with quantifier, additional capturing group",
+ route: new(Route).Queries("foo", "{v1:[0-9]{1}(a|b)}"),
+ request: newRequest("GET", "http://localhost?foo=1a"),
+ vars: map[string]string{"v1": "1a"},
+ host: "",
+ path: "",
+ shouldMatch: true,
+ },
+ {
+ title: "Queries route with regexp pattern with quantifier, additional variable in query string, regexp does not match",
+ route: new(Route).Queries("foo", "{v1:[0-9]{1}}"),
+ request: newRequest("GET", "http://localhost?foo=12"),
+ vars: map[string]string{},
+ host: "",
+ path: "",
+ shouldMatch: false,
+ },
+ {
+ title: "Queries route with hyphenated name, match",
+ route: new(Route).Queries("foo", "{v-1}"),
+ request: newRequest("GET", "http://localhost?foo=bar"),
+ vars: map[string]string{"v-1": "bar"},
+ host: "",
+ path: "",
+ shouldMatch: true,
+ },
+ {
+ title: "Queries route with multiple hyphenated names, match",
+ route: new(Route).Queries("foo", "{v-1}", "baz", "{v-2}"),
+ request: newRequest("GET", "http://localhost?foo=bar&baz=ding"),
+ vars: map[string]string{"v-1": "bar", "v-2": "ding"},
+ host: "",
+ path: "",
+ shouldMatch: true,
+ },
+ {
+ title: "Queries route with hyphenate name and pattern, match",
+ route: new(Route).Queries("foo", "{v-1:[0-9]+}"),
+ request: newRequest("GET", "http://localhost?foo=10"),
+ vars: map[string]string{"v-1": "10"},
+ host: "",
+ path: "",
+ shouldMatch: true,
+ },
+ {
+ title: "Queries route with hyphenated name and pattern with quantifier, additional capturing group",
+ route: new(Route).Queries("foo", "{v-1:[0-9]{1}(a|b)}"),
+ request: newRequest("GET", "http://localhost?foo=1a"),
+ vars: map[string]string{"v-1": "1a"},
+ host: "",
+ path: "",
+ shouldMatch: true,
+ },
+ {
+ title: "Queries route with empty value, should match",
+ route: new(Route).Queries("foo", ""),
+ request: newRequest("GET", "http://localhost?foo=bar"),
+ vars: map[string]string{},
+ host: "",
+ path: "",
+ shouldMatch: true,
+ },
+ {
+ title: "Queries route with empty value and no parameter in request, should not match",
+ route: new(Route).Queries("foo", ""),
+ request: newRequest("GET", "http://localhost"),
+ vars: map[string]string{},
+ host: "",
+ path: "",
+ shouldMatch: false,
+ },
+ {
+ title: "Queries route with empty value and empty parameter in request, should match",
+ route: new(Route).Queries("foo", ""),
+ request: newRequest("GET", "http://localhost?foo="),
+ vars: map[string]string{},
+ host: "",
+ path: "",
+ shouldMatch: true,
+ },
+ {
+ title: "Queries route with overlapping value, should not match",
+ route: new(Route).Queries("foo", "bar"),
+ request: newRequest("GET", "http://localhost?foo=barfoo"),
+ vars: map[string]string{},
+ host: "",
+ path: "",
+ shouldMatch: false,
+ },
+ {
+ title: "Queries route with no parameter in request, should not match",
+ route: new(Route).Queries("foo", "{bar}"),
+ request: newRequest("GET", "http://localhost"),
+ vars: map[string]string{},
+ host: "",
+ path: "",
+ shouldMatch: false,
+ },
+ {
+ title: "Queries route with empty parameter in request, should match",
+ route: new(Route).Queries("foo", "{bar}"),
+ request: newRequest("GET", "http://localhost?foo="),
+ vars: map[string]string{"foo": ""},
+ host: "",
+ path: "",
+ shouldMatch: true,
+ },
+ {
+ title: "Queries route, bad submatch",
+ route: new(Route).Queries("foo", "bar", "baz", "ding"),
+ request: newRequest("GET", "http://localhost?fffoo=bar&baz=dingggg"),
+ vars: map[string]string{},
+ host: "",
+ path: "",
+ shouldMatch: false,
+ },
}
for _, test := range tests {
@@ -801,6 +1048,81 @@ func TestStrictSlash(t *testing.T) {
}
}
+func TestWalkSingleDepth(t *testing.T) {
+ r0 := NewRouter()
+ r1 := NewRouter()
+ r2 := NewRouter()
+
+ r0.Path("/g")
+ r0.Path("/o")
+ r0.Path("/d").Handler(r1)
+ r0.Path("/r").Handler(r2)
+ r0.Path("/a")
+
+ r1.Path("/z")
+ r1.Path("/i")
+ r1.Path("/l")
+ r1.Path("/l")
+
+ r2.Path("/i")
+ r2.Path("/l")
+ r2.Path("/l")
+
+ paths := []string{"g", "o", "r", "i", "l", "l", "a"}
+ depths := []int{0, 0, 0, 1, 1, 1, 0}
+ i := 0
+ err := r0.Walk(func(route *Route, router *Router, ancestors []*Route) error {
+ matcher := route.matchers[0].(*routeRegexp)
+ if matcher.template == "/d" {
+ return SkipRouter
+ }
+ if len(ancestors) != depths[i] {
+ t.Errorf(`Expected depth of %d at i = %d; got "%d"`, depths[i], i, len(ancestors))
+ }
+ if matcher.template != "/"+paths[i] {
+ t.Errorf(`Expected "/%s" at i = %d; got "%s"`, paths[i], i, matcher.template)
+ }
+ i++
+ return nil
+ })
+ if err != nil {
+ panic(err)
+ }
+ if i != len(paths) {
+ t.Errorf("Expected %d routes, found %d", len(paths), i)
+ }
+}
+
+func TestWalkNested(t *testing.T) {
+ router := NewRouter()
+
+ g := router.Path("/g").Subrouter()
+ o := g.PathPrefix("/o").Subrouter()
+ r := o.PathPrefix("/r").Subrouter()
+ i := r.PathPrefix("/i").Subrouter()
+ l1 := i.PathPrefix("/l").Subrouter()
+ l2 := l1.PathPrefix("/l").Subrouter()
+ l2.Path("/a")
+
+ paths := []string{"/g", "/g/o", "/g/o/r", "/g/o/r/i", "/g/o/r/i/l", "/g/o/r/i/l/l", "/g/o/r/i/l/l/a"}
+ idx := 0
+ err := router.Walk(func(route *Route, router *Router, ancestors []*Route) error {
+ path := paths[idx]
+ tpl := route.regexp.path.template
+ if tpl != path {
+ t.Errorf(`Expected %s got %s`, path, tpl)
+ }
+ idx++
+ return nil
+ })
+ if err != nil {
+ panic(err)
+ }
+ if idx != len(paths) {
+ t.Errorf("Expected %d routes, found %d", len(paths), idx)
+ }
+}
+
// ----------------------------------------------------------------------------
// Helpers
// ----------------------------------------------------------------------------
diff --git a/Godeps/_workspace/src/github.com/gorilla/mux/old_test.go b/Godeps/_workspace/src/github.com/gorilla/mux/old_test.go
index 1f7c190c0..755db483e 100644
--- a/Godeps/_workspace/src/github.com/gorilla/mux/old_test.go
+++ b/Godeps/_workspace/src/github.com/gorilla/mux/old_test.go
@@ -545,7 +545,7 @@ func TestMatchedRouteName(t *testing.T) {
router := NewRouter()
route := router.NewRoute().Path("/products/").Name(routeName)
- url := "http://www.domain.com/products/"
+ url := "http://www.example.com/products/"
request, _ := http.NewRequest("GET", url, nil)
var rv RouteMatch
ok := router.Match(request, &rv)
@@ -563,10 +563,10 @@ func TestMatchedRouteName(t *testing.T) {
func TestSubRouting(t *testing.T) {
// Example from docs.
router := NewRouter()
- subrouter := router.NewRoute().Host("www.domain.com").Subrouter()
+ subrouter := router.NewRoute().Host("www.example.com").Subrouter()
route := subrouter.NewRoute().Path("/products/").Name("products")
- url := "http://www.domain.com/products/"
+ url := "http://www.example.com/products/"
request, _ := http.NewRequest("GET", url, nil)
var rv RouteMatch
ok := router.Match(request, &rv)
diff --git a/Godeps/_workspace/src/github.com/gorilla/mux/regexp.go b/Godeps/_workspace/src/github.com/gorilla/mux/regexp.go
index aa3067986..06728dd54 100644
--- a/Godeps/_workspace/src/github.com/gorilla/mux/regexp.go
+++ b/Godeps/_workspace/src/github.com/gorilla/mux/regexp.go
@@ -10,6 +10,7 @@ import (
"net/http"
"net/url"
"regexp"
+ "strconv"
"strings"
)
@@ -34,8 +35,7 @@ func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash
// Now let's parse it.
defaultPattern := "[^/]+"
if matchQuery {
- defaultPattern = "[^?&]+"
- matchPrefix = true
+ defaultPattern = "[^?&]*"
} else if matchHost {
defaultPattern = "[^.]+"
matchPrefix = false
@@ -53,9 +53,7 @@ func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash
varsN := make([]string, len(idxs)/2)
varsR := make([]*regexp.Regexp, len(idxs)/2)
pattern := bytes.NewBufferString("")
- if !matchQuery {
- pattern.WriteByte('^')
- }
+ pattern.WriteByte('^')
reverse := bytes.NewBufferString("")
var end int
var err error
@@ -75,12 +73,14 @@ func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash
tpl[idxs[i]:end])
}
// Build the regexp pattern.
- fmt.Fprintf(pattern, "%s(%s)", regexp.QuoteMeta(raw), patt)
+ varIdx := i / 2
+ fmt.Fprintf(pattern, "%s(?P<%s>%s)", regexp.QuoteMeta(raw), varGroupName(varIdx), patt)
// Build the reverse template.
fmt.Fprintf(reverse, "%s%%s", raw)
+
// Append variable name and compiled pattern.
- varsN[i/2] = name
- varsR[i/2], err = regexp.Compile(fmt.Sprintf("^%s$", patt))
+ varsN[varIdx] = name
+ varsR[varIdx], err = regexp.Compile(fmt.Sprintf("^%s$", patt))
if err != nil {
return nil, err
}
@@ -91,6 +91,12 @@ func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash
if strictSlash {
pattern.WriteString("[/]?")
}
+ if matchQuery {
+ // Add the default pattern if the query value is empty
+ if queryVal := strings.SplitN(template, "=", 2)[1]; queryVal == "" {
+ pattern.WriteString(defaultPattern)
+ }
+ }
if !matchPrefix {
pattern.WriteByte('$')
}
@@ -141,7 +147,7 @@ type routeRegexp struct {
func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool {
if !r.matchHost {
if r.matchQuery {
- return r.regexp.MatchString(req.URL.RawQuery)
+ return r.matchQueryString(req)
} else {
return r.regexp.MatchString(req.URL.Path)
}
@@ -175,6 +181,26 @@ func (r *routeRegexp) url(values map[string]string) (string, error) {
return rv, nil
}
+// getUrlQuery returns a single query parameter from a request URL.
+// For a URL with foo=bar&baz=ding, we return only the relevant key
+// value pair for the routeRegexp.
+func (r *routeRegexp) getUrlQuery(req *http.Request) string {
+ if !r.matchQuery {
+ return ""
+ }
+ templateKey := strings.SplitN(r.template, "=", 2)[0]
+ for key, vals := range req.URL.Query() {
+ if key == templateKey && len(vals) > 0 {
+ return key + "=" + vals[0]
+ }
+ }
+ return ""
+}
+
+func (r *routeRegexp) matchQueryString(req *http.Request) bool {
+ return r.regexp.MatchString(r.getUrlQuery(req))
+}
+
// braceIndices returns the first level curly brace indices from a string.
// It returns an error in case of unbalanced braces.
func braceIndices(s string) ([]int, error) {
@@ -200,6 +226,11 @@ func braceIndices(s string) ([]int, error) {
return idxs, nil
}
+// varGroupName builds a capturing group name for the indexed variable.
+func varGroupName(idx int) string {
+ return "v" + strconv.Itoa(idx)
+}
+
// ----------------------------------------------------------------------------
// routeRegexpGroup
// ----------------------------------------------------------------------------
@@ -217,8 +248,13 @@ func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route)
if v.host != nil {
hostVars := v.host.regexp.FindStringSubmatch(getHost(req))
if hostVars != nil {
- for k, v := range v.host.varsN {
- m.Vars[v] = hostVars[k+1]
+ subexpNames := v.host.regexp.SubexpNames()
+ varName := 0
+ for i, name := range subexpNames[1:] {
+ if name != "" && name == varGroupName(varName) {
+ m.Vars[v.host.varsN[varName]] = hostVars[i+1]
+ varName++
+ }
}
}
}
@@ -226,8 +262,13 @@ func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route)
if v.path != nil {
pathVars := v.path.regexp.FindStringSubmatch(req.URL.Path)
if pathVars != nil {
- for k, v := range v.path.varsN {
- m.Vars[v] = pathVars[k+1]
+ subexpNames := v.path.regexp.SubexpNames()
+ varName := 0
+ for i, name := range subexpNames[1:] {
+ if name != "" && name == varGroupName(varName) {
+ m.Vars[v.path.varsN[varName]] = pathVars[i+1]
+ varName++
+ }
}
// Check if we should redirect.
if v.path.strictSlash {
@@ -246,12 +287,16 @@ func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route)
}
}
// Store query string variables.
- rawQuery := req.URL.RawQuery
for _, q := range v.queries {
- queryVars := q.regexp.FindStringSubmatch(rawQuery)
+ queryVars := q.regexp.FindStringSubmatch(q.getUrlQuery(req))
if queryVars != nil {
- for k, v := range q.varsN {
- m.Vars[v] = queryVars[k+1]
+ subexpNames := q.regexp.SubexpNames()
+ varName := 0
+ for i, name := range subexpNames[1:] {
+ if name != "" && name == varGroupName(varName) {
+ m.Vars[q.varsN[varName]] = queryVars[i+1]
+ varName++
+ }
}
}
}
diff --git a/Godeps/_workspace/src/github.com/gorilla/mux/route.go b/Godeps/_workspace/src/github.com/gorilla/mux/route.go
index d4f014688..913432c1c 100644
--- a/Godeps/_workspace/src/github.com/gorilla/mux/route.go
+++ b/Godeps/_workspace/src/github.com/gorilla/mux/route.go
@@ -9,6 +9,7 @@ import (
"fmt"
"net/http"
"net/url"
+ "regexp"
"strings"
)
@@ -188,7 +189,7 @@ func (r *Route) addRegexpMatcher(tpl string, matchHost, matchPrefix, matchQuery
type headerMatcher map[string]string
func (m headerMatcher) Match(r *http.Request, match *RouteMatch) bool {
- return matchMap(m, r.Header, true)
+ return matchMapWithString(m, r.Header, true)
}
// Headers adds a matcher for request header values.
@@ -199,22 +200,45 @@ func (m headerMatcher) Match(r *http.Request, match *RouteMatch) bool {
// "X-Requested-With", "XMLHttpRequest")
//
// The above route will only match if both request header values match.
-//
-// It the value is an empty string, it will match any value if the key is set.
+// If the value is an empty string, it will match any value if the key is set.
func (r *Route) Headers(pairs ...string) *Route {
if r.err == nil {
var headers map[string]string
- headers, r.err = mapFromPairs(pairs...)
+ headers, r.err = mapFromPairsToString(pairs...)
return r.addMatcher(headerMatcher(headers))
}
return r
}
+// headerRegexMatcher matches the request against the route given a regex for the header
+type headerRegexMatcher map[string]*regexp.Regexp
+
+func (m headerRegexMatcher) Match(r *http.Request, match *RouteMatch) bool {
+ return matchMapWithRegex(m, r.Header, true)
+}
+
+// Regular expressions can be used with headers as well.
+// It accepts a sequence of key/value pairs, where the value has regex support. For example
+// r := mux.NewRouter()
+// r.HeadersRegexp("Content-Type", "application/(text|json)",
+// "X-Requested-With", "XMLHttpRequest")
+//
+// The above route will only match if both the request header matches both regular expressions.
+// It the value is an empty string, it will match any value if the key is set.
+func (r *Route) HeadersRegexp(pairs ...string) *Route {
+ if r.err == nil {
+ var headers map[string]*regexp.Regexp
+ headers, r.err = mapFromPairsToRegex(pairs...)
+ return r.addMatcher(headerRegexMatcher(headers))
+ }
+ return r
+}
+
// Host -----------------------------------------------------------------------
// Host adds a matcher for the URL host.
// It accepts a template with zero or more URL variables enclosed by {}.
-// Variables can define an optional regexp pattern to me matched:
+// Variables can define an optional regexp pattern to be matched:
//
// - {name} matches anything until the next dot.
//
@@ -223,7 +247,7 @@ func (r *Route) Headers(pairs ...string) *Route {
// For example:
//
// r := mux.NewRouter()
-// r.Host("www.domain.com")
+// r.Host("www.example.com")
// r.Host("{subdomain}.domain.com")
// r.Host("{subdomain:[a-z]+}.domain.com")
//
@@ -272,7 +296,7 @@ func (r *Route) Methods(methods ...string) *Route {
// Path adds a matcher for the URL path.
// It accepts a template with zero or more URL variables enclosed by {}. The
// template must start with a "/".
-// Variables can define an optional regexp pattern to me matched:
+// Variables can define an optional regexp pattern to be matched:
//
// - {name} matches anything until the next slash.
//
@@ -323,7 +347,7 @@ func (r *Route) PathPrefix(tpl string) *Route {
//
// It the value is an empty string, it will match any value if the key is set.
//
-// Variables can define an optional regexp pattern to me matched:
+// Variables can define an optional regexp pattern to be matched:
//
// - {name} matches anything until the next slash.
//
@@ -336,7 +360,7 @@ func (r *Route) Queries(pairs ...string) *Route {
return nil
}
for i := 0; i < length; i += 2 {
- if r.err = r.addRegexpMatcher(pairs[i]+"="+pairs[i+1], false, true, true); r.err != nil {
+ if r.err = r.addRegexpMatcher(pairs[i]+"="+pairs[i+1], false, false, true); r.err != nil {
return r
}
}
@@ -382,7 +406,7 @@ func (r *Route) BuildVarsFunc(f BuildVarsFunc) *Route {
// It will test the inner routes only if the parent route matched. For example:
//
// r := mux.NewRouter()
-// s := r.Host("www.domain.com").Subrouter()
+// s := r.Host("www.example.com").Subrouter()
// s.HandleFunc("/products/", ProductsHandler)
// s.HandleFunc("/products/{key}", ProductHandler)
// s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)
@@ -511,7 +535,7 @@ func (r *Route) URLPath(pairs ...string) (*url.URL, error) {
// prepareVars converts the route variable pairs into a map. If the route has a
// BuildVarsFunc, it is invoked.
func (r *Route) prepareVars(pairs ...string) (map[string]string, error) {
- m, err := mapFromPairs(pairs...)
+ m, err := mapFromPairsToString(pairs...)
if err != nil {
return nil, err
}
diff --git a/Godeps/_workspace/src/github.com/gorilla/websocket/README.md b/Godeps/_workspace/src/github.com/gorilla/websocket/README.md
index 9ad75a0f5..9d71959ea 100644
--- a/Godeps/_workspace/src/github.com/gorilla/websocket/README.md
+++ b/Godeps/_workspace/src/github.com/gorilla/websocket/README.md
@@ -7,6 +7,8 @@ Gorilla WebSocket is a [Go](http://golang.org/) implementation of the
* [API Reference](http://godoc.org/github.com/gorilla/websocket)
* [Chat example](https://github.com/gorilla/websocket/tree/master/examples/chat)
+* [Command example](https://github.com/gorilla/websocket/tree/master/examples/command)
+* [Client and server example](https://github.com/gorilla/websocket/tree/master/examples/echo)
* [File watch example](https://github.com/gorilla/websocket/tree/master/examples/filewatch)
### Status
diff --git a/Godeps/_workspace/src/github.com/gorilla/websocket/client.go b/Godeps/_workspace/src/github.com/gorilla/websocket/client.go
index 5bc27e193..3bf9b2e84 100644
--- a/Godeps/_workspace/src/github.com/gorilla/websocket/client.go
+++ b/Godeps/_workspace/src/github.com/gorilla/websocket/client.go
@@ -5,6 +5,7 @@
package websocket
import (
+ "bufio"
"bytes"
"crypto/tls"
"errors"
@@ -30,50 +31,17 @@ var ErrBadHandshake = errors.New("websocket: bad handshake")
// If the WebSocket handshake fails, ErrBadHandshake is returned along with a
// non-nil *http.Response so that callers can handle redirects, authentication,
// etc.
+//
+// Deprecated: Use Dialer instead.
func NewClient(netConn net.Conn, u *url.URL, requestHeader http.Header, readBufSize, writeBufSize int) (c *Conn, response *http.Response, err error) {
- challengeKey, err := generateChallengeKey()
- if err != nil {
- return nil, nil, err
+ d := Dialer{
+ ReadBufferSize: readBufSize,
+ WriteBufferSize: writeBufSize,
+ NetDial: func(net, addr string) (net.Conn, error) {
+ return netConn, nil
+ },
}
- acceptKey := computeAcceptKey(challengeKey)
-
- c = newConn(netConn, false, readBufSize, writeBufSize)
- p := c.writeBuf[:0]
- p = append(p, "GET "...)
- p = append(p, u.RequestURI()...)
- p = append(p, " HTTP/1.1\r\nHost: "...)
- p = append(p, u.Host...)
- // "Upgrade" is capitalized for servers that do not use case insensitive
- // comparisons on header tokens.
- p = append(p, "\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: "...)
- p = append(p, challengeKey...)
- p = append(p, "\r\n"...)
- for k, vs := range requestHeader {
- for _, v := range vs {
- p = append(p, k...)
- p = append(p, ": "...)
- p = append(p, v...)
- p = append(p, "\r\n"...)
- }
- }
- p = append(p, "\r\n"...)
-
- if _, err := netConn.Write(p); err != nil {
- return nil, nil, err
- }
-
- resp, err := http.ReadResponse(c.br, &http.Request{Method: "GET", URL: u})
- if err != nil {
- return nil, nil, err
- }
- if resp.StatusCode != 101 ||
- !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
- !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
- resp.Header.Get("Sec-Websocket-Accept") != acceptKey {
- return nil, resp, ErrBadHandshake
- }
- c.subprotocol = resp.Header.Get("Sec-Websocket-Protocol")
- return c, resp, nil
+ return d.Dial(u.String(), requestHeader)
}
// A Dialer contains options for connecting to WebSocket server.
@@ -82,6 +50,12 @@ type Dialer struct {
// NetDial is nil, net.Dial is used.
NetDial func(network, addr string) (net.Conn, error)
+ // Proxy specifies a function to return a proxy for a given
+ // Request. If the function returns a non-nil error, the
+ // request is aborted with the provided error.
+ // If Proxy is nil or returns a nil *URL, no proxy is used.
+ Proxy func(*http.Request) (*url.URL, error)
+
// TLSClientConfig specifies the TLS configuration to use with tls.Client.
// If nil, the default configuration is used.
TLSClientConfig *tls.Config
@@ -99,17 +73,15 @@ type Dialer struct {
var errMalformedURL = errors.New("malformed ws or wss URL")
-// parseURL parses the URL. The url.Parse function is not used here because
-// url.Parse mangles the path.
+// parseURL parses the URL.
+//
+// This function is a replacement for the standard library url.Parse function.
+// In Go 1.4 and earlier, url.Parse loses information from the path.
func parseURL(s string) (*url.URL, error) {
// From the RFC:
//
// ws-URI = "ws:" "//" host [ ":" port ] path [ "?" query ]
// wss-URI = "wss:" "//" host [ ":" port ] path [ "?" query ]
- //
- // We don't use the net/url parser here because the dialer interface does
- // not provide a way for applications to work around percent deocding in
- // the net/url parser.
var u url.URL
switch {
@@ -130,6 +102,12 @@ func parseURL(s string) (*url.URL, error) {
u.Opaque = s[i:]
}
+ if strings.Contains(u.Host, "@") {
+ // Don't bother parsing user information because user information is
+ // not allowed in websocket URIs.
+ return nil, errMalformedURL
+ }
+
return &u, nil
}
@@ -139,9 +117,12 @@ func hostPortNoPort(u *url.URL) (hostPort, hostNoPort string) {
if i := strings.LastIndex(u.Host, ":"); i > strings.LastIndex(u.Host, "]") {
hostNoPort = hostNoPort[:i]
} else {
- if u.Scheme == "wss" {
+ switch u.Scheme {
+ case "wss":
+ hostPort += ":443"
+ case "https":
hostPort += ":443"
- } else {
+ default:
hostPort += ":80"
}
}
@@ -149,7 +130,9 @@ func hostPortNoPort(u *url.URL) (hostPort, hostNoPort string) {
}
// DefaultDialer is a dialer with all fields set to the default zero values.
-var DefaultDialer *Dialer
+var DefaultDialer = &Dialer{
+ Proxy: http.ProxyFromEnvironment,
+}
// Dial creates a new client connection. Use requestHeader to specify the
// origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies (Cookie).
@@ -161,15 +144,91 @@ var DefaultDialer *Dialer
// etcetera. The response body may not contain the entire response and does not
// need to be closed by the application.
func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) {
+
+ if d == nil {
+ d = &Dialer{
+ Proxy: http.ProxyFromEnvironment,
+ }
+ }
+
+ challengeKey, err := generateChallengeKey()
+ if err != nil {
+ return nil, nil, err
+ }
+
u, err := parseURL(urlStr)
if err != nil {
return nil, nil, err
}
+ switch u.Scheme {
+ case "ws":
+ u.Scheme = "http"
+ case "wss":
+ u.Scheme = "https"
+ default:
+ return nil, nil, errMalformedURL
+ }
+
+ if u.User != nil {
+ // User name and password are not allowed in websocket URIs.
+ return nil, nil, errMalformedURL
+ }
+
+ req := &http.Request{
+ Method: "GET",
+ URL: u,
+ Proto: "HTTP/1.1",
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ Header: make(http.Header),
+ Host: u.Host,
+ }
+
+ // Set the request headers using the capitalization for names and values in
+ // RFC examples. Although the capitalization shouldn't matter, there are
+ // servers that depend on it. The Header.Set method is not used because the
+ // method canonicalizes the header names.
+ req.Header["Upgrade"] = []string{"websocket"}
+ req.Header["Connection"] = []string{"Upgrade"}
+ req.Header["Sec-WebSocket-Key"] = []string{challengeKey}
+ req.Header["Sec-WebSocket-Version"] = []string{"13"}
+ if len(d.Subprotocols) > 0 {
+ req.Header["Sec-WebSocket-Protocol"] = []string{strings.Join(d.Subprotocols, ", ")}
+ }
+ for k, vs := range requestHeader {
+ switch {
+ case k == "Host":
+ if len(vs) > 0 {
+ req.Host = vs[0]
+ }
+ case k == "Upgrade" ||
+ k == "Connection" ||
+ k == "Sec-Websocket-Key" ||
+ k == "Sec-Websocket-Version" ||
+ (k == "Sec-Websocket-Protocol" && len(d.Subprotocols) > 0):
+ return nil, nil, errors.New("websocket: duplicate header not allowed: " + k)
+ default:
+ req.Header[k] = vs
+ }
+ }
+
hostPort, hostNoPort := hostPortNoPort(u)
- if d == nil {
- d = &Dialer{}
+ var proxyURL *url.URL
+ // Check wether the proxy method has been configured
+ if d.Proxy != nil {
+ proxyURL, err = d.Proxy(req)
+ }
+ if err != nil {
+ return nil, nil, err
+ }
+
+ var targetHostPort string
+ if proxyURL != nil {
+ targetHostPort, _ = hostPortNoPort(proxyURL)
+ } else {
+ targetHostPort = hostPort
}
var deadline time.Time
@@ -183,7 +242,7 @@ func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Re
netDial = netDialer.Dial
}
- netConn, err := netDial("tcp", hostPort)
+ netConn, err := netDial("tcp", targetHostPort)
if err != nil {
return nil, nil, err
}
@@ -198,7 +257,31 @@ func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Re
return nil, nil, err
}
- if u.Scheme == "wss" {
+ if proxyURL != nil {
+ connectReq := &http.Request{
+ Method: "CONNECT",
+ URL: &url.URL{Opaque: hostPort},
+ Host: hostPort,
+ Header: make(http.Header),
+ }
+
+ connectReq.Write(netConn)
+
+ // Read response.
+ // Okay to use and discard buffered reader here, because
+ // TLS server will not speak until spoken to.
+ br := bufio.NewReader(netConn)
+ resp, err := http.ReadResponse(br, connectReq)
+ if err != nil {
+ return nil, nil, err
+ }
+ if resp.StatusCode != 200 {
+ f := strings.SplitN(resp.Status, " ", 2)
+ return nil, nil, errors.New(f[1])
+ }
+ }
+
+ if u.Scheme == "https" {
cfg := d.TLSClientConfig
if cfg == nil {
cfg = &tls.Config{ServerName: hostNoPort}
@@ -219,45 +302,32 @@ func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Re
}
}
- if len(d.Subprotocols) > 0 {
- h := http.Header{}
- for k, v := range requestHeader {
- h[k] = v
- }
- h.Set("Sec-Websocket-Protocol", strings.Join(d.Subprotocols, ", "))
- requestHeader = h
- }
-
- if len(requestHeader["Host"]) > 0 {
- // This can be used to supply a Host: header which is different from
- // the dial address.
- u.Host = requestHeader.Get("Host")
+ conn := newConn(netConn, false, d.ReadBufferSize, d.WriteBufferSize)
- // Drop "Host" header
- h := http.Header{}
- for k, v := range requestHeader {
- if k == "Host" {
- continue
- }
- h[k] = v
- }
- requestHeader = h
+ if err := req.Write(netConn); err != nil {
+ return nil, nil, err
}
- conn, resp, err := NewClient(netConn, u, requestHeader, d.ReadBufferSize, d.WriteBufferSize)
-
+ resp, err := http.ReadResponse(conn.br, req)
if err != nil {
- if err == ErrBadHandshake {
- // Before closing the network connection on return from this
- // function, slurp up some of the response to aid application
- // debugging.
- buf := make([]byte, 1024)
- n, _ := io.ReadFull(resp.Body, buf)
- resp.Body = ioutil.NopCloser(bytes.NewReader(buf[:n]))
- }
- return nil, resp, err
+ return nil, nil, err
+ }
+ if resp.StatusCode != 101 ||
+ !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
+ !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
+ resp.Header.Get("Sec-Websocket-Accept") != computeAcceptKey(challengeKey) {
+ // Before closing the network connection on return from this
+ // function, slurp up some of the response to aid application
+ // debugging.
+ buf := make([]byte, 1024)
+ n, _ := io.ReadFull(resp.Body, buf)
+ resp.Body = ioutil.NopCloser(bytes.NewReader(buf[:n]))
+ return nil, resp, ErrBadHandshake
}
+ resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
+ conn.subprotocol = resp.Header.Get("Sec-Websocket-Protocol")
+
netConn.SetDeadline(time.Time{})
netConn = nil // to avoid close in defer.
return conn, resp, nil
diff --git a/Godeps/_workspace/src/github.com/gorilla/websocket/client_server_test.go b/Godeps/_workspace/src/github.com/gorilla/websocket/client_server_test.go
index 749ef2050..05a7888fe 100644
--- a/Godeps/_workspace/src/github.com/gorilla/websocket/client_server_test.go
+++ b/Godeps/_workspace/src/github.com/gorilla/websocket/client_server_test.go
@@ -56,11 +56,6 @@ func newTLSServer(t *testing.T) *cstServer {
}
func (t cstHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- if r.Method != "GET" {
- t.Logf("method %s not allowed", r.Method)
- http.Error(w, "method not allowed", 405)
- return
- }
subprotos := Subprotocols(r)
if !reflect.DeepEqual(subprotos, cstDialer.Subprotocols) {
t.Logf("subprotols=%v, want %v", subprotos, cstDialer.Subprotocols)
@@ -123,6 +118,45 @@ func sendRecv(t *testing.T, ws *Conn) {
}
}
+func TestProxyDial(t *testing.T) {
+
+ s := newServer(t)
+ defer s.Close()
+
+ surl, _ := url.Parse(s.URL)
+
+ cstDialer.Proxy = http.ProxyURL(surl)
+
+ connect := false
+ origHandler := s.Server.Config.Handler
+
+ // Capture the request Host header.
+ s.Server.Config.Handler = http.HandlerFunc(
+ func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == "CONNECT" {
+ connect = true
+ w.WriteHeader(200)
+ return
+ }
+
+ if !connect {
+ t.Log("connect not recieved")
+ http.Error(w, "connect not recieved", 405)
+ return
+ }
+ origHandler.ServeHTTP(w, r)
+ })
+
+ ws, _, err := cstDialer.Dial(s.URL, nil)
+ if err != nil {
+ t.Fatalf("Dial: %v", err)
+ }
+ defer ws.Close()
+ sendRecv(t, ws)
+
+ cstDialer.Proxy = http.ProxyFromEnvironment
+}
+
func TestDial(t *testing.T) {
s := newServer(t)
defer s.Close()
@@ -229,6 +263,45 @@ func TestDialBadOrigin(t *testing.T) {
}
}
+func TestDialBadHeader(t *testing.T) {
+ s := newServer(t)
+ defer s.Close()
+
+ for _, k := range []string{"Upgrade",
+ "Connection",
+ "Sec-Websocket-Key",
+ "Sec-Websocket-Version",
+ "Sec-Websocket-Protocol"} {
+ h := http.Header{}
+ h.Set(k, "bad")
+ ws, _, err := cstDialer.Dial(s.URL, http.Header{"Origin": {"bad"}})
+ if err == nil {
+ ws.Close()
+ t.Errorf("Dial with header %s returned nil", k)
+ }
+ }
+}
+
+func TestBadMethod(t *testing.T) {
+ s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ ws, err := cstUpgrader.Upgrade(w, r, nil)
+ if err == nil {
+ t.Errorf("handshake succeeded, expect fail")
+ ws.Close()
+ }
+ }))
+ defer s.Close()
+
+ resp, err := http.PostForm(s.URL, url.Values{})
+ if err != nil {
+ t.Fatalf("PostForm returned error %v", err)
+ }
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusMethodNotAllowed {
+ t.Errorf("Status = %d, want %d", resp.StatusCode, http.StatusMethodNotAllowed)
+ }
+}
+
func TestHandshake(t *testing.T) {
s := newServer(t)
defer s.Close()
@@ -289,8 +362,8 @@ func TestRespOnBadHandshake(t *testing.T) {
}
}
-// If the Host header is specified in `Dial()`, the server must receive it as
-// the `Host:` header.
+// TestHostHeader confirms that the host header provided in the call to Dial is
+// sent to the server.
func TestHostHeader(t *testing.T) {
s := newServer(t)
defer s.Close()
@@ -305,16 +378,12 @@ func TestHostHeader(t *testing.T) {
origHandler.ServeHTTP(w, r)
})
- ws, resp, err := cstDialer.Dial(s.URL, http.Header{"Host": {"testhost"}})
+ ws, _, err := cstDialer.Dial(s.URL, http.Header{"Host": {"testhost"}})
if err != nil {
t.Fatalf("Dial: %v", err)
}
defer ws.Close()
- if resp.StatusCode != http.StatusSwitchingProtocols {
- t.Fatalf("resp.StatusCode = %v, want http.StatusSwitchingProtocols", resp.StatusCode)
- }
-
if gotHost := <-specifiedHost; gotHost != "testhost" {
t.Fatalf("gotHost = %q, want \"testhost\"", gotHost)
}
diff --git a/Godeps/_workspace/src/github.com/gorilla/websocket/client_test.go b/Godeps/_workspace/src/github.com/gorilla/websocket/client_test.go
index d2f2ebd79..07a9cb453 100644
--- a/Godeps/_workspace/src/github.com/gorilla/websocket/client_test.go
+++ b/Godeps/_workspace/src/github.com/gorilla/websocket/client_test.go
@@ -20,6 +20,7 @@ var parseURLTests = []struct {
{"wss://example.com/", &url.URL{Scheme: "wss", Host: "example.com", Opaque: "/"}},
{"wss://example.com/a/b", &url.URL{Scheme: "wss", Host: "example.com", Opaque: "/a/b"}},
{"ss://example.com/a/b", nil},
+ {"ws://webmaster@example.com/", nil},
}
func TestParseURL(t *testing.T) {
diff --git a/Godeps/_workspace/src/github.com/gorilla/websocket/conn.go b/Godeps/_workspace/src/github.com/gorilla/websocket/conn.go
index e719f1ce6..e8b6b3e04 100644
--- a/Godeps/_workspace/src/github.com/gorilla/websocket/conn.go
+++ b/Godeps/_workspace/src/github.com/gorilla/websocket/conn.go
@@ -88,19 +88,23 @@ func (e *netError) Error() string { return e.msg }
func (e *netError) Temporary() bool { return e.temporary }
func (e *netError) Timeout() bool { return e.timeout }
-// closeError represents close frame.
-type closeError struct {
- code int
- text string
+// CloseError represents close frame.
+type CloseError struct {
+
+ // Code is defined in RFC 6455, section 11.7.
+ Code int
+
+ // Text is the optional text payload.
+ Text string
}
-func (e *closeError) Error() string {
- return "websocket: close " + strconv.Itoa(e.code) + " " + e.text
+func (e *CloseError) Error() string {
+ return "websocket: close " + strconv.Itoa(e.Code) + " " + e.Text
}
var (
- errWriteTimeout = &netError{msg: "websocket: write timeout", timeout: true}
- errUnexpectedEOF = &closeError{code: CloseAbnormalClosure, text: io.ErrUnexpectedEOF.Error()}
+ errWriteTimeout = &netError{msg: "websocket: write timeout", timeout: true, temporary: true}
+ errUnexpectedEOF = &CloseError{Code: CloseAbnormalClosure, Text: io.ErrUnexpectedEOF.Error()}
errBadWriteOpCode = errors.New("websocket: bad write message type")
errWriteClosed = errors.New("websocket: write closed")
errInvalidControlFrame = errors.New("websocket: invalid control frame")
@@ -296,7 +300,7 @@ func (c *Conn) WriteControl(messageType int, data []byte, deadline time.Time) er
if n != 0 && n != len(buf) {
c.conn.Close()
}
- return err
+ return hideTempErr(err)
}
// NextWriter returns a writer for the next message to send. The writer's
@@ -673,12 +677,7 @@ func (c *Conn) advanceFrame() (int, error) {
closeCode = int(binary.BigEndian.Uint16(payload))
closeText = string(payload[2:])
}
- switch closeCode {
- case CloseNormalClosure, CloseGoingAway:
- return noFrame, io.EOF
- default:
- return noFrame, &closeError{code: closeCode, text: closeText}
- }
+ return noFrame, &CloseError{Code: closeCode, Text: closeText}
}
return frameType, nil
@@ -790,20 +789,27 @@ func (c *Conn) SetReadLimit(limit int64) {
}
// SetPingHandler sets the handler for ping messages received from the peer.
-// The default ping handler sends a pong to the peer.
-func (c *Conn) SetPingHandler(h func(string) error) {
+// The appData argument to h is the PING frame application data. The default
+// ping handler sends a pong to the peer.
+func (c *Conn) SetPingHandler(h func(appData string) error) {
if h == nil {
h = func(message string) error {
- c.WriteControl(PongMessage, []byte(message), time.Now().Add(writeWait))
- return nil
+ err := c.WriteControl(PongMessage, []byte(message), time.Now().Add(writeWait))
+ if err == ErrCloseSent {
+ return nil
+ } else if e, ok := err.(net.Error); ok && e.Temporary() {
+ return nil
+ }
+ return err
}
}
c.handlePing = h
}
// SetPongHandler sets the handler for pong messages received from the peer.
-// The default pong handler does nothing.
-func (c *Conn) SetPongHandler(h func(string) error) {
+// The appData argument to h is the PONG frame application data. The default
+// pong handler does nothing.
+func (c *Conn) SetPongHandler(h func(appData string) error) {
if h == nil {
h = func(string) error { return nil }
}
diff --git a/Godeps/_workspace/src/github.com/gorilla/websocket/conn_test.go b/Godeps/_workspace/src/github.com/gorilla/websocket/conn_test.go
index 1f1197e71..02f2d4b50 100644
--- a/Godeps/_workspace/src/github.com/gorilla/websocket/conn_test.go
+++ b/Godeps/_workspace/src/github.com/gorilla/websocket/conn_test.go
@@ -5,11 +5,13 @@
package websocket
import (
+ "bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"net"
+ "reflect"
"testing"
"testing/iotest"
"time"
@@ -146,13 +148,15 @@ func TestControl(t *testing.T) {
func TestCloseBeforeFinalFrame(t *testing.T) {
const bufSize = 512
+ expectedErr := &CloseError{Code: CloseNormalClosure, Text: "hello"}
+
var b1, b2 bytes.Buffer
wc := newConn(fakeNetConn{Reader: nil, Writer: &b1}, false, 1024, bufSize)
rc := newConn(fakeNetConn{Reader: &b1, Writer: &b2}, true, 1024, 1024)
w, _ := wc.NextWriter(BinaryMessage)
w.Write(make([]byte, bufSize+bufSize/2))
- wc.WriteControl(CloseMessage, FormatCloseMessage(CloseNormalClosure, ""), time.Now().Add(10*time.Second))
+ wc.WriteControl(CloseMessage, FormatCloseMessage(expectedErr.Code, expectedErr.Text), time.Now().Add(10*time.Second))
w.Close()
op, r, err := rc.NextReader()
@@ -160,12 +164,12 @@ func TestCloseBeforeFinalFrame(t *testing.T) {
t.Fatalf("NextReader() returned %d, %v", op, err)
}
_, err = io.Copy(ioutil.Discard, r)
- if err != errUnexpectedEOF {
- t.Fatalf("io.Copy() returned %v, want %v", err, errUnexpectedEOF)
+ if !reflect.DeepEqual(err, expectedErr) {
+ t.Fatalf("io.Copy() returned %v, want %v", err, expectedErr)
}
_, _, err = rc.NextReader()
- if err != io.EOF {
- t.Fatalf("NextReader() returned %v, want %v", err, io.EOF)
+ if !reflect.DeepEqual(err, expectedErr) {
+ t.Fatalf("NextReader() returned %v, want %v", err, expectedErr)
}
}
@@ -236,3 +240,33 @@ func TestUnderlyingConn(t *testing.T) {
t.Fatalf("Underlying conn is not what it should be.")
}
}
+
+func TestBufioReadBytes(t *testing.T) {
+
+ // Test calling bufio.ReadBytes for value longer than read buffer size.
+
+ m := make([]byte, 512)
+ m[len(m)-1] = '\n'
+
+ var b1, b2 bytes.Buffer
+ wc := newConn(fakeNetConn{Reader: nil, Writer: &b1}, false, len(m)+64, len(m)+64)
+ rc := newConn(fakeNetConn{Reader: &b1, Writer: &b2}, true, len(m)-64, len(m)-64)
+
+ w, _ := wc.NextWriter(BinaryMessage)
+ w.Write(m)
+ w.Close()
+
+ op, r, err := rc.NextReader()
+ if op != BinaryMessage || err != nil {
+ t.Fatalf("NextReader() returned %d, %v", op, err)
+ }
+
+ br := bufio.NewReader(r)
+ p, err := br.ReadBytes('\n')
+ if err != nil {
+ t.Fatalf("ReadBytes() returned %v", err)
+ }
+ if len(p) != len(m) {
+ t.Fatalf("read returnd %d bytes, want %d bytes", len(p), len(m))
+ }
+}
diff --git a/Godeps/_workspace/src/github.com/gorilla/websocket/doc.go b/Godeps/_workspace/src/github.com/gorilla/websocket/doc.go
index 0d2bd912b..72286279c 100644
--- a/Godeps/_workspace/src/github.com/gorilla/websocket/doc.go
+++ b/Godeps/_workspace/src/github.com/gorilla/websocket/doc.go
@@ -24,7 +24,7 @@
// ... Use conn to send and receive messages.
// }
//
-// Call the connection WriteMessage and ReadMessages methods to send and
+// Call the connection's WriteMessage and ReadMessage methods to send and
// receive messages as a slice of bytes. This snippet of code shows how to echo
// messages using these methods:
//
@@ -97,10 +97,13 @@
//
// Concurrency
//
-// Connections do not support concurrent calls to the write methods
-// (NextWriter, SetWriteDeadline, WriteMessage) or concurrent calls to the read
-// methods methods (NextReader, SetReadDeadline, ReadMessage). Connections do
-// support a concurrent reader and writer.
+// Connections support one concurrent reader and one concurrent writer.
+//
+// Applications are responsible for ensuring that no more than one goroutine
+// calls the write methods (NextWriter, SetWriteDeadline, WriteMessage,
+// WriteJSON) concurrently and that no more than one goroutine calls the read
+// methods (NextReader, SetReadDeadline, ReadMessage, ReadJSON, SetPongHandler,
+// SetPingHandler) concurrently.
//
// The Close and WriteControl methods can be called concurrently with all other
// methods.
diff --git a/Godeps/_workspace/src/github.com/gorilla/websocket/examples/chat/README.md b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/chat/README.md
index 08fc3e65c..5df3cf1a3 100644
--- a/Godeps/_workspace/src/github.com/gorilla/websocket/examples/chat/README.md
+++ b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/chat/README.md
@@ -17,3 +17,4 @@ using the following commands.
$ cd `go list -f '{{.Dir}}' github.com/gorilla/websocket/examples/chat`
$ go run *.go
+To use the chat example, open http://localhost:8080/ in your browser.
diff --git a/Godeps/_workspace/src/github.com/gorilla/websocket/examples/chat/conn.go b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/chat/conn.go
index 7cc0496c3..22816f09f 100644
--- a/Godeps/_workspace/src/github.com/gorilla/websocket/examples/chat/conn.go
+++ b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/chat/conn.go
@@ -88,12 +88,8 @@ func (c *connection) writePump() {
}
}
-// serverWs handles websocket requests from the peer.
+// serveWs handles websocket requests from the peer.
func serveWs(w http.ResponseWriter, r *http.Request) {
- if r.Method != "GET" {
- http.Error(w, "Method not allowed", 405)
- return
- }
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
diff --git a/Godeps/_workspace/src/github.com/gorilla/websocket/examples/command/README.md b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/command/README.md
new file mode 100644
index 000000000..c30d3979a
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/command/README.md
@@ -0,0 +1,19 @@
+# Command example
+
+This example connects a websocket connection to stdin and stdout of a command.
+Received messages are written to stdin followed by a `\n`. Each line read from
+from standard out is sent as a message to the client.
+
+ $ go get github.com/gorilla/websocket
+ $ cd `go list -f '{{.Dir}}' github.com/gorilla/websocket/examples/command`
+ $ go run main.go <command and arguments to run>
+ # Open http://localhost:8080/ .
+
+Try the following commands.
+
+ # Echo sent messages to the output area.
+ $ go run main.go cat
+
+ # Run a shell.Try sending "ls" and "cat main.go".
+ $ go run main.go sh
+
diff --git a/Godeps/_workspace/src/github.com/gorilla/websocket/examples/command/home.html b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/command/home.html
new file mode 100644
index 000000000..72fd02b2a
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/command/home.html
@@ -0,0 +1,96 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<title>Command Example</title>
+<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
+<script type="text/javascript">
+ $(function() {
+
+ var conn;
+ var msg = $("#msg");
+ var log = $("#log");
+
+ function appendLog(msg) {
+ var d = log[0]
+ var doScroll = d.scrollTop == d.scrollHeight - d.clientHeight;
+ msg.appendTo(log)
+ if (doScroll) {
+ d.scrollTop = d.scrollHeight - d.clientHeight;
+ }
+ }
+
+ $("#form").submit(function() {
+ if (!conn) {
+ return false;
+ }
+ if (!msg.val()) {
+ return false;
+ }
+ conn.send(msg.val());
+ msg.val("");
+ return false
+ });
+
+ if (window["WebSocket"]) {
+ conn = new WebSocket("ws://{{$}}/ws");
+ conn.onclose = function(evt) {
+ appendLog($("<div><b>Connection closed.</b></div>"))
+ }
+ conn.onmessage = function(evt) {
+ appendLog($("<pre/>").text(evt.data))
+ }
+ } else {
+ appendLog($("<div><b>Your browser does not support WebSockets.</b></div>"))
+ }
+ });
+</script>
+<style type="text/css">
+html {
+ overflow: hidden;
+}
+
+body {
+ overflow: hidden;
+ padding: 0;
+ margin: 0;
+ width: 100%;
+ height: 100%;
+ background: gray;
+}
+
+#log {
+ background: white;
+ margin: 0;
+ padding: 0.5em 0.5em 0.5em 0.5em;
+ position: absolute;
+ top: 0.5em;
+ left: 0.5em;
+ right: 0.5em;
+ bottom: 3em;
+ overflow: auto;
+}
+
+#log pre {
+ margin: 0;
+}
+
+#form {
+ padding: 0 0.5em 0 0.5em;
+ margin: 0;
+ position: absolute;
+ bottom: 1em;
+ left: 0px;
+ width: 100%;
+ overflow: hidden;
+}
+
+</style>
+</head>
+<body>
+<div id="log"></div>
+<form id="form">
+ <input type="submit" value="Send" />
+ <input type="text" id="msg" size="64"/>
+</form>
+</body>
+</html>
diff --git a/Godeps/_workspace/src/github.com/gorilla/websocket/examples/command/main.go b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/command/main.go
new file mode 100644
index 000000000..f3f022edb
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/command/main.go
@@ -0,0 +1,188 @@
+// Copyright 2015 The Gorilla WebSocket Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package main
+
+import (
+ "bufio"
+ "flag"
+ "io"
+ "log"
+ "net/http"
+ "os"
+ "os/exec"
+ "text/template"
+ "time"
+
+ "github.com/gorilla/websocket"
+)
+
+var (
+ addr = flag.String("addr", "127.0.0.1:8080", "http service address")
+ cmdPath string
+ homeTempl = template.Must(template.ParseFiles("home.html"))
+)
+
+const (
+ // Time allowed to write a message to the peer.
+ writeWait = 10 * time.Second
+
+ // Maximum message size allowed from peer.
+ maxMessageSize = 8192
+
+ // Time allowed to read the next pong message from the peer.
+ pongWait = 60 * time.Second
+
+ // Send pings to peer with this period. Must be less than pongWait.
+ pingPeriod = (pongWait * 9) / 10
+)
+
+func pumpStdin(ws *websocket.Conn, w io.Writer) {
+ defer ws.Close()
+ ws.SetReadLimit(maxMessageSize)
+ ws.SetReadDeadline(time.Now().Add(pongWait))
+ ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })
+ for {
+ _, message, err := ws.ReadMessage()
+ if err != nil {
+ break
+ }
+ message = append(message, '\n')
+ if _, err := w.Write(message); err != nil {
+ break
+ }
+ }
+}
+
+func pumpStdout(ws *websocket.Conn, r io.Reader, done chan struct{}) {
+ defer func() {
+ ws.Close()
+ close(done)
+ }()
+ s := bufio.NewScanner(r)
+ for s.Scan() {
+ ws.SetWriteDeadline(time.Now().Add(writeWait))
+ if err := ws.WriteMessage(websocket.TextMessage, s.Bytes()); err != nil {
+ break
+ }
+ }
+ if s.Err() != nil {
+ log.Println("scan:", s.Err())
+ }
+}
+
+func ping(ws *websocket.Conn, done chan struct{}) {
+ ticker := time.NewTicker(pingPeriod)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ if err := ws.WriteControl(websocket.PingMessage, []byte{}, time.Now().Add(writeWait)); err != nil {
+ log.Println("ping:", err)
+ }
+ case <-done:
+ return
+ }
+ }
+}
+
+func internalError(ws *websocket.Conn, msg string, err error) {
+ log.Println(msg, err)
+ ws.WriteMessage(websocket.TextMessage, []byte("Internal server error."))
+}
+
+var upgrader = websocket.Upgrader{}
+
+func serveWs(w http.ResponseWriter, r *http.Request) {
+ ws, err := upgrader.Upgrade(w, r, nil)
+ if err != nil {
+ log.Println("upgrade:", err)
+ return
+ }
+
+ defer ws.Close()
+
+ outr, outw, err := os.Pipe()
+ if err != nil {
+ internalError(ws, "stdout:", err)
+ return
+ }
+ defer outr.Close()
+ defer outw.Close()
+
+ inr, inw, err := os.Pipe()
+ if err != nil {
+ internalError(ws, "stdin:", err)
+ return
+ }
+ defer inr.Close()
+ defer inw.Close()
+
+ proc, err := os.StartProcess(cmdPath, flag.Args(), &os.ProcAttr{
+ Files: []*os.File{inr, outw, outw},
+ })
+ if err != nil {
+ internalError(ws, "start:", err)
+ return
+ }
+
+ inr.Close()
+ outw.Close()
+
+ stdoutDone := make(chan struct{})
+ go pumpStdout(ws, outr, stdoutDone)
+ go ping(ws, stdoutDone)
+
+ pumpStdin(ws, inw)
+
+ // Some commands will exit when stdin is closed.
+ inw.Close()
+
+ // Other commands need a bonk on the head.
+ if err := proc.Signal(os.Interrupt); err != nil {
+ log.Println("inter:", err)
+ }
+
+ select {
+ case <-stdoutDone:
+ case <-time.After(time.Second):
+ // A bigger bonk on the head.
+ if err := proc.Signal(os.Kill); err != nil {
+ log.Println("term:", err)
+ }
+ <-stdoutDone
+ }
+
+ if _, err := proc.Wait(); err != nil {
+ log.Println("wait:", err)
+ }
+}
+
+func serveHome(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/" {
+ http.Error(w, "Not found", 404)
+ return
+ }
+ if r.Method != "GET" {
+ http.Error(w, "Method not allowed", 405)
+ return
+ }
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ homeTempl.Execute(w, r.Host)
+}
+
+func main() {
+ flag.Parse()
+ if len(flag.Args()) < 1 {
+ log.Fatal("must specify at least one argument")
+ }
+ var err error
+ cmdPath, err = exec.LookPath(flag.Args()[0])
+ if err != nil {
+ log.Fatal(err)
+ }
+ http.HandleFunc("/", serveHome)
+ http.HandleFunc("/ws", serveWs)
+ log.Fatal(http.ListenAndServe(*addr, nil))
+}
diff --git a/Godeps/_workspace/src/github.com/gorilla/websocket/examples/echo/README.md b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/echo/README.md
new file mode 100644
index 000000000..6ad79ed76
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/echo/README.md
@@ -0,0 +1,17 @@
+# Client and server example
+
+This example shows a simple client and server.
+
+The server echoes messages sent to it. The client sends a message every second
+and prints all messages received.
+
+To run the example, start the server:
+
+ $ go run server.go
+
+Next, start the client:
+
+ $ go run client.go
+
+The server includes a simple web client. To use the client, open
+http://127.0.0.1:8080 in the browser and follow the instructions on the page.
diff --git a/Godeps/_workspace/src/github.com/gorilla/websocket/examples/echo/client.go b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/echo/client.go
new file mode 100644
index 000000000..45a023175
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/echo/client.go
@@ -0,0 +1,55 @@
+// Copyright 2015 The Gorilla WebSocket Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build ignore
+
+package main
+
+import (
+ "flag"
+ "log"
+ "net/url"
+ "time"
+
+ "github.com/gorilla/websocket"
+)
+
+var addr = flag.String("addr", "localhost:8080", "http service address")
+
+func main() {
+ flag.Parse()
+ log.SetFlags(0)
+
+ u := url.URL{Scheme: "ws", Host: *addr, Path: "/echo"}
+ log.Printf("connecting to %s", u.String())
+
+ c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
+ if err != nil {
+ log.Fatal("dial:", err)
+ }
+ defer c.Close()
+
+ go func() {
+ defer c.Close()
+ for {
+ _, message, err := c.ReadMessage()
+ if err != nil {
+ log.Println("read:", err)
+ break
+ }
+ log.Printf("recv: %s", message)
+ }
+ }()
+
+ ticker := time.NewTicker(time.Second)
+ defer ticker.Stop()
+
+ for t := range ticker.C {
+ err := c.WriteMessage(websocket.TextMessage, []byte(t.String()))
+ if err != nil {
+ log.Println("write:", err)
+ break
+ }
+ }
+}
diff --git a/Godeps/_workspace/src/github.com/gorilla/websocket/examples/echo/server.go b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/echo/server.go
new file mode 100644
index 000000000..a685b0974
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/echo/server.go
@@ -0,0 +1,132 @@
+// Copyright 2015 The Gorilla WebSocket Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build ignore
+
+package main
+
+import (
+ "flag"
+ "html/template"
+ "log"
+ "net/http"
+
+ "github.com/gorilla/websocket"
+)
+
+var addr = flag.String("addr", "localhost:8080", "http service address")
+
+var upgrader = websocket.Upgrader{} // use default options
+
+func echo(w http.ResponseWriter, r *http.Request) {
+ c, err := upgrader.Upgrade(w, r, nil)
+ if err != nil {
+ log.Print("upgrade:", err)
+ return
+ }
+ defer c.Close()
+ for {
+ mt, message, err := c.ReadMessage()
+ if err != nil {
+ log.Println("read:", err)
+ break
+ }
+ log.Printf("recv: %s", message)
+ err = c.WriteMessage(mt, message)
+ if err != nil {
+ log.Println("write:", err)
+ break
+ }
+ }
+}
+
+func home(w http.ResponseWriter, r *http.Request) {
+ homeTemplate.Execute(w, "ws://"+r.Host+"/echo")
+}
+
+func main() {
+ flag.Parse()
+ log.SetFlags(0)
+ http.HandleFunc("/echo", echo)
+ http.HandleFunc("/", home)
+ log.Fatal(http.ListenAndServe(*addr, nil))
+}
+
+var homeTemplate = template.Must(template.New("").Parse(`
+<!DOCTYPE html>
+<head>
+<meta charset="utf-8">
+<script>
+window.addEventListener("load", function(evt) {
+
+ var output = document.getElementById("output");
+ var input = document.getElementById("input");
+ var ws;
+
+ var print = function(message) {
+ var d = document.createElement("div");
+ d.innerHTML = message;
+ output.appendChild(d);
+ };
+
+ document.getElementById("open").onclick = function(evt) {
+ if (ws) {
+ return false;
+ }
+ ws = new WebSocket("{{.}}");
+ ws.onopen = function(evt) {
+ print("OPEN");
+ }
+ ws.onclose = function(evt) {
+ print("CLOSE");
+ ws = null;
+ }
+ ws.onmessage = function(evt) {
+ print("RESPONSE: " + evt.data);
+ }
+ ws.onerror = function(evt) {
+ print("ERROR: " + evt.data);
+ }
+ return false;
+ };
+
+ document.getElementById("send").onclick = function(evt) {
+ if (!ws) {
+ return false;
+ }
+ print("SEND: " + input.value);
+ ws.send(input.value);
+ return false;
+ };
+
+ document.getElementById("close").onclick = function(evt) {
+ if (!ws) {
+ return false;
+ }
+ ws.close();
+ return false;
+ };
+
+});
+</script>
+</head>
+<body>
+<table>
+<tr><td valign="top" width="50%">
+<p>Click "Open" to create a connection to the server,
+"Send" to send a message to the server and "Close" to close the connection.
+You can change the message and send multiple times.
+<p>
+<form>
+<button id="open">Open</button>
+<button id="close">Close</button>
+<p><input id="input" type="text" value="Hello world!">
+<button id="send">Send</button>
+</form>
+</td><td valign="top" width="50%">
+<div id="output"></div>
+</td></tr></table>
+</body>
+</html>
+`))
diff --git a/Godeps/_workspace/src/github.com/gorilla/websocket/json.go b/Godeps/_workspace/src/github.com/gorilla/websocket/json.go
index 18e62f225..4f0e36875 100644
--- a/Godeps/_workspace/src/github.com/gorilla/websocket/json.go
+++ b/Godeps/_workspace/src/github.com/gorilla/websocket/json.go
@@ -48,9 +48,7 @@ func (c *Conn) ReadJSON(v interface{}) error {
}
err = json.NewDecoder(r).Decode(v)
if err == io.EOF {
- // Decode returns io.EOF when the message is empty or all whitespace.
- // Convert to io.ErrUnexpectedEOF so that application can distinguish
- // between an error reading the JSON value and the connection closing.
+ // One value is expected in the message.
err = io.ErrUnexpectedEOF
}
return err
diff --git a/Godeps/_workspace/src/github.com/gorilla/websocket/json_test.go b/Godeps/_workspace/src/github.com/gorilla/websocket/json_test.go
index 1b7a5ec8b..61100e481 100644
--- a/Godeps/_workspace/src/github.com/gorilla/websocket/json_test.go
+++ b/Godeps/_workspace/src/github.com/gorilla/websocket/json_test.go
@@ -38,7 +38,7 @@ func TestJSON(t *testing.T) {
}
}
-func TestPartialJsonRead(t *testing.T) {
+func TestPartialJSONRead(t *testing.T) {
var buf bytes.Buffer
c := fakeNetConn{&buf, &buf}
wc := newConn(c, true, 1024, 1024)
@@ -87,7 +87,7 @@ func TestPartialJsonRead(t *testing.T) {
}
err = rc.ReadJSON(&v)
- if err != io.EOF {
+ if _, ok := err.(*CloseError); !ok {
t.Error("final", err)
}
}
diff --git a/Godeps/_workspace/src/github.com/gorilla/websocket/server.go b/Godeps/_workspace/src/github.com/gorilla/websocket/server.go
index e56a00493..3a9805f02 100644
--- a/Godeps/_workspace/src/github.com/gorilla/websocket/server.go
+++ b/Godeps/_workspace/src/github.com/gorilla/websocket/server.go
@@ -93,6 +93,9 @@ func (u *Upgrader) selectSubprotocol(r *http.Request, responseHeader http.Header
// request. Use the responseHeader to specify cookies (Set-Cookie) and the
// application negotiated subprotocol (Sec-Websocket-Protocol).
func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) {
+ if r.Method != "GET" {
+ return u.returnError(w, r, http.StatusMethodNotAllowed, "websocket: method not GET")
+ }
if values := r.Header["Sec-Websocket-Version"]; len(values) == 0 || values[0] != "13" {
return u.returnError(w, r, http.StatusBadRequest, "websocket: version != 13")
}
diff --git a/Godeps/_workspace/src/github.com/lib/pq/.travis.yml b/Godeps/_workspace/src/github.com/lib/pq/.travis.yml
index 9bf683730..6b8eb405b 100644
--- a/Godeps/_workspace/src/github.com/lib/pq/.travis.yml
+++ b/Godeps/_workspace/src/github.com/lib/pq/.travis.yml
@@ -5,6 +5,7 @@ go:
- 1.2
- 1.3
- 1.4
+ - 1.5
- tip
before_install:
diff --git a/Godeps/_workspace/src/github.com/lib/pq/buf.go b/Godeps/_workspace/src/github.com/lib/pq/buf.go
index e7ff57771..666b0012a 100644
--- a/Godeps/_workspace/src/github.com/lib/pq/buf.go
+++ b/Godeps/_workspace/src/github.com/lib/pq/buf.go
@@ -21,6 +21,7 @@ func (b *readBuf) oid() (n oid.Oid) {
return
}
+// N.B: this is actually an unsigned 16-bit integer, unlike int32
func (b *readBuf) int16() (n int) {
n = int(binary.BigEndian.Uint16(*b))
*b = (*b)[2:]
diff --git a/Godeps/_workspace/src/github.com/lib/pq/conn.go b/Godeps/_workspace/src/github.com/lib/pq/conn.go
index 40a630d74..ce661d66e 100644
--- a/Godeps/_workspace/src/github.com/lib/pq/conn.go
+++ b/Godeps/_workspace/src/github.com/lib/pq/conn.go
@@ -1369,6 +1369,10 @@ func (rs *rows) Next(dest []driver.Value) (err error) {
return io.EOF
case 'D':
n := rs.rb.int16()
+ if err != nil {
+ conn.bad = true
+ errorf("unexpected DataRow after error %s", err)
+ }
if n < len(dest) {
dest = dest[:n]
}
@@ -1622,6 +1626,10 @@ func (cn *conn) readExecuteResponse(protocolState string) (res driver.Result, co
t, r := cn.recv1()
switch t {
case 'C':
+ if err != nil {
+ cn.bad = true
+ errorf("unexpected CommandComplete after error %s", err)
+ }
res, commandTag = cn.parseComplete(r.string())
case 'Z':
cn.processReadyForQuery(r)
@@ -1629,6 +1637,10 @@ func (cn *conn) readExecuteResponse(protocolState string) (res driver.Result, co
case 'E':
err = parseError(r)
case 'T', 'D', 'I':
+ if err != nil {
+ cn.bad = true
+ errorf("unexpected %q after error %s", t, err)
+ }
// ignore any results
default:
cn.bad = true
diff --git a/Godeps/_workspace/src/github.com/lib/pq/copy.go b/Godeps/_workspace/src/github.com/lib/pq/copy.go
index e44fa48a5..101f11133 100644
--- a/Godeps/_workspace/src/github.com/lib/pq/copy.go
+++ b/Godeps/_workspace/src/github.com/lib/pq/copy.go
@@ -215,9 +215,7 @@ func (ci *copyin) Exec(v []driver.Value) (r driver.Result, err error) {
}
if len(v) == 0 {
- err = ci.Close()
- ci.closed = true
- return nil, err
+ return nil, ci.Close()
}
numValues := len(v)
@@ -240,9 +238,10 @@ func (ci *copyin) Exec(v []driver.Value) (r driver.Result, err error) {
}
func (ci *copyin) Close() (err error) {
- if ci.closed {
- return errCopyInClosed
+ if ci.closed { // Don't do anything, we're already closed
+ return nil
}
+ ci.closed = true
if ci.cn.bad {
return driver.ErrBadConn
diff --git a/Godeps/_workspace/src/github.com/mssola/user_agent/bot.go b/Godeps/_workspace/src/github.com/mssola/user_agent/bot.go
index cc993d8fe..df0b6ccda 100644
--- a/Godeps/_workspace/src/github.com/mssola/user_agent/bot.go
+++ b/Godeps/_workspace/src/github.com/mssola/user_agent/bot.go
@@ -9,6 +9,8 @@ import (
"strings"
)
+var botFromSiteRegexp = regexp.MustCompile("http://.+\\.\\w+")
+
// Get the name of the bot from the website that may be in the given comment. If
// there is no website in the comment, then an empty string is returned.
func getFromSite(comment []string) string {
@@ -23,8 +25,7 @@ func getFromSite(comment []string) string {
}
// Pick the site.
- re := regexp.MustCompile("http://.+\\.\\w+")
- results := re.FindStringSubmatch(comment[idx])
+ results := botFromSiteRegexp.FindStringSubmatch(comment[idx])
if len(results) == 1 {
// If it's a simple comment, just return the name of the site.
if idx == 0 {
diff --git a/Godeps/_workspace/src/github.com/mssola/user_agent/browser.go b/Godeps/_workspace/src/github.com/mssola/user_agent/browser.go
index c5612db7b..a45c8ab7f 100644
--- a/Godeps/_workspace/src/github.com/mssola/user_agent/browser.go
+++ b/Godeps/_workspace/src/github.com/mssola/user_agent/browser.go
@@ -9,6 +9,8 @@ import (
"strings"
)
+var ie11Regexp = regexp.MustCompile("^rv:(.+)$")
+
// A struct containing all the information that we might be
// interested from the browser.
type Browser struct {
@@ -75,9 +77,8 @@ func (p *UserAgent) detectBrowser(sections []section) {
// This is the new user agent from Internet Explorer 11.
p.browser.Engine = "Trident"
p.browser.Name = "Internet Explorer"
- reg, _ := regexp.Compile("^rv:(.+)$")
for _, c := range sections[0].comment {
- version := reg.FindStringSubmatch(c)
+ version := ie11Regexp.FindStringSubmatch(c)
if len(version) > 0 {
p.browser.Version = version[1]
return
diff --git a/Godeps/_workspace/src/github.com/pborman/uuid/CONTRIBUTORS b/Godeps/_workspace/src/github.com/pborman/uuid/CONTRIBUTORS
new file mode 100644
index 000000000..b382a04ed
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/pborman/uuid/CONTRIBUTORS
@@ -0,0 +1 @@
+Paul Borman <borman@google.com>
diff --git a/Godeps/_workspace/src/github.com/pborman/uuid/LICENSE b/Godeps/_workspace/src/github.com/pborman/uuid/LICENSE
new file mode 100644
index 000000000..5dc68268d
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/pborman/uuid/LICENSE
@@ -0,0 +1,27 @@
+Copyright (c) 2009,2014 Google Inc. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+ * Neither the name of Google Inc. nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/Godeps/_workspace/src/github.com/pborman/uuid/dce.go b/Godeps/_workspace/src/github.com/pborman/uuid/dce.go
new file mode 100644
index 000000000..50a0f2d09
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/pborman/uuid/dce.go
@@ -0,0 +1,84 @@
+// Copyright 2011 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "encoding/binary"
+ "fmt"
+ "os"
+)
+
+// A Domain represents a Version 2 domain
+type Domain byte
+
+// Domain constants for DCE Security (Version 2) UUIDs.
+const (
+ Person = Domain(0)
+ Group = Domain(1)
+ Org = Domain(2)
+)
+
+// NewDCESecurity returns a DCE Security (Version 2) UUID.
+//
+// The domain should be one of Person, Group or Org.
+// On a POSIX system the id should be the users UID for the Person
+// domain and the users GID for the Group. The meaning of id for
+// the domain Org or on non-POSIX systems is site defined.
+//
+// For a given domain/id pair the same token may be returned for up to
+// 7 minutes and 10 seconds.
+func NewDCESecurity(domain Domain, id uint32) UUID {
+ uuid := NewUUID()
+ if uuid != nil {
+ uuid[6] = (uuid[6] & 0x0f) | 0x20 // Version 2
+ uuid[9] = byte(domain)
+ binary.BigEndian.PutUint32(uuid[0:], id)
+ }
+ return uuid
+}
+
+// NewDCEPerson returns a DCE Security (Version 2) UUID in the person
+// domain with the id returned by os.Getuid.
+//
+// NewDCEPerson(Person, uint32(os.Getuid()))
+func NewDCEPerson() UUID {
+ return NewDCESecurity(Person, uint32(os.Getuid()))
+}
+
+// NewDCEGroup returns a DCE Security (Version 2) UUID in the group
+// domain with the id returned by os.Getgid.
+//
+// NewDCEGroup(Group, uint32(os.Getgid()))
+func NewDCEGroup() UUID {
+ return NewDCESecurity(Group, uint32(os.Getgid()))
+}
+
+// Domain returns the domain for a Version 2 UUID or false.
+func (uuid UUID) Domain() (Domain, bool) {
+ if v, _ := uuid.Version(); v != 2 {
+ return 0, false
+ }
+ return Domain(uuid[9]), true
+}
+
+// Id returns the id for a Version 2 UUID or false.
+func (uuid UUID) Id() (uint32, bool) {
+ if v, _ := uuid.Version(); v != 2 {
+ return 0, false
+ }
+ return binary.BigEndian.Uint32(uuid[0:4]), true
+}
+
+func (d Domain) String() string {
+ switch d {
+ case Person:
+ return "Person"
+ case Group:
+ return "Group"
+ case Org:
+ return "Org"
+ }
+ return fmt.Sprintf("Domain%d", int(d))
+}
diff --git a/Godeps/_workspace/src/github.com/pborman/uuid/doc.go b/Godeps/_workspace/src/github.com/pborman/uuid/doc.go
new file mode 100644
index 000000000..d8bd013e6
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/pborman/uuid/doc.go
@@ -0,0 +1,8 @@
+// Copyright 2011 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// The uuid package generates and inspects UUIDs.
+//
+// UUIDs are based on RFC 4122 and DCE 1.1: Authentication and Security Services.
+package uuid
diff --git a/Godeps/_workspace/src/github.com/pborman/uuid/hash.go b/Godeps/_workspace/src/github.com/pborman/uuid/hash.go
new file mode 100644
index 000000000..cdd4192fd
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/pborman/uuid/hash.go
@@ -0,0 +1,53 @@
+// Copyright 2011 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "crypto/md5"
+ "crypto/sha1"
+ "hash"
+)
+
+// Well known Name Space IDs and UUIDs
+var (
+ NameSpace_DNS = Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
+ NameSpace_URL = Parse("6ba7b811-9dad-11d1-80b4-00c04fd430c8")
+ NameSpace_OID = Parse("6ba7b812-9dad-11d1-80b4-00c04fd430c8")
+ NameSpace_X500 = Parse("6ba7b814-9dad-11d1-80b4-00c04fd430c8")
+ NIL = Parse("00000000-0000-0000-0000-000000000000")
+)
+
+// NewHash returns a new UUID dervied from the hash of space concatenated with
+// data generated by h. The hash should be at least 16 byte in length. The
+// first 16 bytes of the hash are used to form the UUID. The version of the
+// UUID will be the lower 4 bits of version. NewHash is used to implement
+// NewMD5 and NewSHA1.
+func NewHash(h hash.Hash, space UUID, data []byte, version int) UUID {
+ h.Reset()
+ h.Write(space)
+ h.Write([]byte(data))
+ s := h.Sum(nil)
+ uuid := make([]byte, 16)
+ copy(uuid, s)
+ uuid[6] = (uuid[6] & 0x0f) | uint8((version&0xf)<<4)
+ uuid[8] = (uuid[8] & 0x3f) | 0x80 // RFC 4122 variant
+ return uuid
+}
+
+// NewMD5 returns a new MD5 (Version 3) UUID based on the
+// supplied name space and data.
+//
+// NewHash(md5.New(), space, data, 3)
+func NewMD5(space UUID, data []byte) UUID {
+ return NewHash(md5.New(), space, data, 3)
+}
+
+// NewSHA1 returns a new SHA1 (Version 5) UUID based on the
+// supplied name space and data.
+//
+// NewHash(sha1.New(), space, data, 5)
+func NewSHA1(space UUID, data []byte) UUID {
+ return NewHash(sha1.New(), space, data, 5)
+}
diff --git a/Godeps/_workspace/src/github.com/pborman/uuid/json.go b/Godeps/_workspace/src/github.com/pborman/uuid/json.go
new file mode 100644
index 000000000..760580a50
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/pborman/uuid/json.go
@@ -0,0 +1,30 @@
+// Copyright 2014 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import "errors"
+
+func (u UUID) MarshalJSON() ([]byte, error) {
+ if len(u) == 0 {
+ return []byte(`""`), nil
+ }
+ return []byte(`"` + u.String() + `"`), nil
+}
+
+func (u *UUID) UnmarshalJSON(data []byte) error {
+ if len(data) == 0 || string(data) == `""` {
+ return nil
+ }
+ if len(data) < 2 || data[0] != '"' || data[len(data)-1] != '"' {
+ return errors.New("invalid UUID format")
+ }
+ data = data[1 : len(data)-1]
+ uu := Parse(string(data))
+ if uu == nil {
+ return errors.New("invalid UUID format")
+ }
+ *u = uu
+ return nil
+}
diff --git a/Godeps/_workspace/src/github.com/pborman/uuid/json_test.go b/Godeps/_workspace/src/github.com/pborman/uuid/json_test.go
new file mode 100644
index 000000000..b5eae0924
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/pborman/uuid/json_test.go
@@ -0,0 +1,32 @@
+// Copyright 2014 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "encoding/json"
+ "reflect"
+ "testing"
+)
+
+var testUUID = Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479")
+
+func TestJSON(t *testing.T) {
+ type S struct {
+ ID1 UUID
+ ID2 UUID
+ }
+ s1 := S{ID1: testUUID}
+ data, err := json.Marshal(&s1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var s2 S
+ if err := json.Unmarshal(data, &s2); err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(&s1, &s2) {
+ t.Errorf("got %#v, want %#v", s2, s1)
+ }
+}
diff --git a/Godeps/_workspace/src/github.com/pborman/uuid/node.go b/Godeps/_workspace/src/github.com/pborman/uuid/node.go
new file mode 100644
index 000000000..dd0a8ac18
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/pborman/uuid/node.go
@@ -0,0 +1,101 @@
+// Copyright 2011 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import "net"
+
+var (
+ interfaces []net.Interface // cached list of interfaces
+ ifname string // name of interface being used
+ nodeID []byte // hardware for version 1 UUIDs
+)
+
+// NodeInterface returns the name of the interface from which the NodeID was
+// derived. The interface "user" is returned if the NodeID was set by
+// SetNodeID.
+func NodeInterface() string {
+ return ifname
+}
+
+// SetNodeInterface selects the hardware address to be used for Version 1 UUIDs.
+// If name is "" then the first usable interface found will be used or a random
+// Node ID will be generated. If a named interface cannot be found then false
+// is returned.
+//
+// SetNodeInterface never fails when name is "".
+func SetNodeInterface(name string) bool {
+ if interfaces == nil {
+ var err error
+ interfaces, err = net.Interfaces()
+ if err != nil && name != "" {
+ return false
+ }
+ }
+
+ for _, ifs := range interfaces {
+ if len(ifs.HardwareAddr) >= 6 && (name == "" || name == ifs.Name) {
+ if setNodeID(ifs.HardwareAddr) {
+ ifname = ifs.Name
+ return true
+ }
+ }
+ }
+
+ // We found no interfaces with a valid hardware address. If name
+ // does not specify a specific interface generate a random Node ID
+ // (section 4.1.6)
+ if name == "" {
+ if nodeID == nil {
+ nodeID = make([]byte, 6)
+ }
+ randomBits(nodeID)
+ return true
+ }
+ return false
+}
+
+// NodeID returns a slice of a copy of the current Node ID, setting the Node ID
+// if not already set.
+func NodeID() []byte {
+ if nodeID == nil {
+ SetNodeInterface("")
+ }
+ nid := make([]byte, 6)
+ copy(nid, nodeID)
+ return nid
+}
+
+// SetNodeID sets the Node ID to be used for Version 1 UUIDs. The first 6 bytes
+// of id are used. If id is less than 6 bytes then false is returned and the
+// Node ID is not set.
+func SetNodeID(id []byte) bool {
+ if setNodeID(id) {
+ ifname = "user"
+ return true
+ }
+ return false
+}
+
+func setNodeID(id []byte) bool {
+ if len(id) < 6 {
+ return false
+ }
+ if nodeID == nil {
+ nodeID = make([]byte, 6)
+ }
+ copy(nodeID, id)
+ return true
+}
+
+// NodeID returns the 6 byte node id encoded in uuid. It returns nil if uuid is
+// not valid. The NodeID is only well defined for version 1 and 2 UUIDs.
+func (uuid UUID) NodeID() []byte {
+ if len(uuid) != 16 {
+ return nil
+ }
+ node := make([]byte, 6)
+ copy(node, uuid[10:])
+ return node
+}
diff --git a/Godeps/_workspace/src/github.com/pborman/uuid/seq_test.go b/Godeps/_workspace/src/github.com/pborman/uuid/seq_test.go
new file mode 100644
index 000000000..3b3d1430d
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/pborman/uuid/seq_test.go
@@ -0,0 +1,66 @@
+// Copyright 2014 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "flag"
+ "runtime"
+ "testing"
+ "time"
+)
+
+// This test is only run when --regressions is passed on the go test line.
+var regressions = flag.Bool("regressions", false, "run uuid regression tests")
+
+// TestClockSeqRace tests for a particular race condition of returning two
+// identical Version1 UUIDs. The duration of 1 minute was chosen as the race
+// condition, before being fixed, nearly always occured in under 30 seconds.
+func TestClockSeqRace(t *testing.T) {
+ if !*regressions {
+ t.Skip("skipping regression tests")
+ }
+ duration := time.Minute
+
+ done := make(chan struct{})
+ defer close(done)
+
+ ch := make(chan UUID, 10000)
+ ncpu := runtime.NumCPU()
+ switch ncpu {
+ case 0, 1:
+ // We can't run the test effectively.
+ t.Skip("skipping race test, only one CPU detected")
+ return
+ default:
+ runtime.GOMAXPROCS(ncpu)
+ }
+ for i := 0; i < ncpu; i++ {
+ go func() {
+ for {
+ select {
+ case <-done:
+ return
+ case ch <- NewUUID():
+ }
+ }
+ }()
+ }
+
+ uuids := make(map[string]bool)
+ cnt := 0
+ start := time.Now()
+ for u := range ch {
+ s := u.String()
+ if uuids[s] {
+ t.Errorf("duplicate uuid after %d in %v: %s", cnt, time.Since(start), s)
+ return
+ }
+ uuids[s] = true
+ if time.Since(start) > duration {
+ return
+ }
+ cnt++
+ }
+}
diff --git a/Godeps/_workspace/src/github.com/pborman/uuid/sql.go b/Godeps/_workspace/src/github.com/pborman/uuid/sql.go
new file mode 100644
index 000000000..2d7679e2a
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/pborman/uuid/sql.go
@@ -0,0 +1,40 @@
+// Copyright 2015 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "errors"
+ "fmt"
+)
+
+// Scan implements sql.Scanner so UUIDs can be read from databases transparently
+// Currently, database types that map to string and []byte are supported. Please
+// consult database-specific driver documentation for matching types.
+func (uuid *UUID) Scan(src interface{}) error {
+ switch src.(type) {
+ case string:
+ // see uuid.Parse for required string format
+ parsed := Parse(src.(string))
+
+ if parsed == nil {
+ return errors.New("Scan: invalid UUID format")
+ }
+
+ *uuid = parsed
+ case []byte:
+ // assumes a simple slice of bytes, just check validity and store
+ u := UUID(src.([]byte))
+
+ if u.Variant() == Invalid {
+ return errors.New("Scan: invalid UUID format")
+ }
+
+ *uuid = u
+ default:
+ return fmt.Errorf("Scan: unable to scan type %T into UUID", src)
+ }
+
+ return nil
+}
diff --git a/Godeps/_workspace/src/github.com/pborman/uuid/sql_test.go b/Godeps/_workspace/src/github.com/pborman/uuid/sql_test.go
new file mode 100644
index 000000000..d643567ee
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/pborman/uuid/sql_test.go
@@ -0,0 +1,53 @@
+// Copyright 2015 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestScan(t *testing.T) {
+ var stringTest string = "f47ac10b-58cc-0372-8567-0e02b2c3d479"
+ var byteTest []byte = Parse(stringTest)
+ var badTypeTest int = 6
+ var invalidTest string = "f47ac10b-58cc-0372-8567-0e02b2c3d4"
+ var invalidByteTest []byte = Parse(invalidTest)
+
+ var uuid UUID
+ err := (&uuid).Scan(stringTest)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ err = (&uuid).Scan(byteTest)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ err = (&uuid).Scan(badTypeTest)
+ if err == nil {
+ t.Error("int correctly parsed and shouldn't have")
+ }
+ if !strings.Contains(err.Error(), "unable to scan type") {
+ t.Error("attempting to parse an int returned an incorrect error message")
+ }
+
+ err = (&uuid).Scan(invalidTest)
+ if err == nil {
+ t.Error("invalid uuid was parsed without error")
+ }
+ if !strings.Contains(err.Error(), "invalid UUID") {
+ t.Error("attempting to parse an invalid UUID returned an incorrect error message")
+ }
+
+ err = (&uuid).Scan(invalidByteTest)
+ if err == nil {
+ t.Error("invalid byte uuid was parsed without error")
+ }
+ if !strings.Contains(err.Error(), "invalid UUID") {
+ t.Error("attempting to parse an invalid byte UUID returned an incorrect error message")
+ }
+}
diff --git a/Godeps/_workspace/src/github.com/pborman/uuid/time.go b/Godeps/_workspace/src/github.com/pborman/uuid/time.go
new file mode 100644
index 000000000..7ebc9bef1
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/pborman/uuid/time.go
@@ -0,0 +1,132 @@
+// Copyright 2014 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "encoding/binary"
+ "sync"
+ "time"
+)
+
+// A Time represents a time as the number of 100's of nanoseconds since 15 Oct
+// 1582.
+type Time int64
+
+const (
+ lillian = 2299160 // Julian day of 15 Oct 1582
+ unix = 2440587 // Julian day of 1 Jan 1970
+ epoch = unix - lillian // Days between epochs
+ g1582 = epoch * 86400 // seconds between epochs
+ g1582ns100 = g1582 * 10000000 // 100s of a nanoseconds between epochs
+)
+
+var (
+ mu sync.Mutex
+ lasttime uint64 // last time we returned
+ clock_seq uint16 // clock sequence for this run
+
+ timeNow = time.Now // for testing
+)
+
+// UnixTime converts t the number of seconds and nanoseconds using the Unix
+// epoch of 1 Jan 1970.
+func (t Time) UnixTime() (sec, nsec int64) {
+ sec = int64(t - g1582ns100)
+ nsec = (sec % 10000000) * 100
+ sec /= 10000000
+ return sec, nsec
+}
+
+// GetTime returns the current Time (100s of nanoseconds since 15 Oct 1582) and
+// clock sequence as well as adjusting the clock sequence as needed. An error
+// is returned if the current time cannot be determined.
+func GetTime() (Time, uint16, error) {
+ defer mu.Unlock()
+ mu.Lock()
+ return getTime()
+}
+
+func getTime() (Time, uint16, error) {
+ t := timeNow()
+
+ // If we don't have a clock sequence already, set one.
+ if clock_seq == 0 {
+ setClockSequence(-1)
+ }
+ now := uint64(t.UnixNano()/100) + g1582ns100
+
+ // If time has gone backwards with this clock sequence then we
+ // increment the clock sequence
+ if now <= lasttime {
+ clock_seq = ((clock_seq + 1) & 0x3fff) | 0x8000
+ }
+ lasttime = now
+ return Time(now), clock_seq, nil
+}
+
+// ClockSequence returns the current clock sequence, generating one if not
+// already set. The clock sequence is only used for Version 1 UUIDs.
+//
+// The uuid package does not use global static storage for the clock sequence or
+// the last time a UUID was generated. Unless SetClockSequence a new random
+// clock sequence is generated the first time a clock sequence is requested by
+// ClockSequence, GetTime, or NewUUID. (section 4.2.1.1) sequence is generated
+// for
+func ClockSequence() int {
+ defer mu.Unlock()
+ mu.Lock()
+ return clockSequence()
+}
+
+func clockSequence() int {
+ if clock_seq == 0 {
+ setClockSequence(-1)
+ }
+ return int(clock_seq & 0x3fff)
+}
+
+// SetClockSeq sets the clock sequence to the lower 14 bits of seq. Setting to
+// -1 causes a new sequence to be generated.
+func SetClockSequence(seq int) {
+ defer mu.Unlock()
+ mu.Lock()
+ setClockSequence(seq)
+}
+
+func setClockSequence(seq int) {
+ if seq == -1 {
+ var b [2]byte
+ randomBits(b[:]) // clock sequence
+ seq = int(b[0])<<8 | int(b[1])
+ }
+ old_seq := clock_seq
+ clock_seq = uint16(seq&0x3fff) | 0x8000 // Set our variant
+ if old_seq != clock_seq {
+ lasttime = 0
+ }
+}
+
+// Time returns the time in 100s of nanoseconds since 15 Oct 1582 encoded in
+// uuid. It returns false if uuid is not valid. The time is only well defined
+// for version 1 and 2 UUIDs.
+func (uuid UUID) Time() (Time, bool) {
+ if len(uuid) != 16 {
+ return 0, false
+ }
+ time := int64(binary.BigEndian.Uint32(uuid[0:4]))
+ time |= int64(binary.BigEndian.Uint16(uuid[4:6])) << 32
+ time |= int64(binary.BigEndian.Uint16(uuid[6:8])&0xfff) << 48
+ return Time(time), true
+}
+
+// ClockSequence returns the clock sequence encoded in uuid. It returns false
+// if uuid is not valid. The clock sequence is only well defined for version 1
+// and 2 UUIDs.
+func (uuid UUID) ClockSequence() (int, bool) {
+ if len(uuid) != 16 {
+ return 0, false
+ }
+ return int(binary.BigEndian.Uint16(uuid[8:10])) & 0x3fff, true
+}
diff --git a/Godeps/_workspace/src/github.com/pborman/uuid/util.go b/Godeps/_workspace/src/github.com/pborman/uuid/util.go
new file mode 100644
index 000000000..de40b102c
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/pborman/uuid/util.go
@@ -0,0 +1,43 @@
+// Copyright 2011 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "io"
+)
+
+// randomBits completely fills slice b with random data.
+func randomBits(b []byte) {
+ if _, err := io.ReadFull(rander, b); err != nil {
+ panic(err.Error()) // rand should never fail
+ }
+}
+
+// xvalues returns the value of a byte as a hexadecimal digit or 255.
+var xvalues = []byte{
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255,
+ 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+}
+
+// xtob converts the the first two hex bytes of x into a byte.
+func xtob(x string) (byte, bool) {
+ b1 := xvalues[x[0]]
+ b2 := xvalues[x[1]]
+ return (b1 << 4) | b2, b1 != 255 && b2 != 255
+}
diff --git a/Godeps/_workspace/src/github.com/pborman/uuid/uuid.go b/Godeps/_workspace/src/github.com/pborman/uuid/uuid.go
new file mode 100644
index 000000000..2920fae63
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/pborman/uuid/uuid.go
@@ -0,0 +1,163 @@
+// Copyright 2011 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "bytes"
+ "crypto/rand"
+ "fmt"
+ "io"
+ "strings"
+)
+
+// A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC
+// 4122.
+type UUID []byte
+
+// A Version represents a UUIDs version.
+type Version byte
+
+// A Variant represents a UUIDs variant.
+type Variant byte
+
+// Constants returned by Variant.
+const (
+ Invalid = Variant(iota) // Invalid UUID
+ RFC4122 // The variant specified in RFC4122
+ Reserved // Reserved, NCS backward compatibility.
+ Microsoft // Reserved, Microsoft Corporation backward compatibility.
+ Future // Reserved for future definition.
+)
+
+var rander = rand.Reader // random function
+
+// New returns a new random (version 4) UUID as a string. It is a convenience
+// function for NewRandom().String().
+func New() string {
+ return NewRandom().String()
+}
+
+// Parse decodes s into a UUID or returns nil. Both the UUID form of
+// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and
+// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx are decoded.
+func Parse(s string) UUID {
+ if len(s) == 36+9 {
+ if strings.ToLower(s[:9]) != "urn:uuid:" {
+ return nil
+ }
+ s = s[9:]
+ } else if len(s) != 36 {
+ return nil
+ }
+ if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' {
+ return nil
+ }
+ uuid := make([]byte, 16)
+ for i, x := range []int{
+ 0, 2, 4, 6,
+ 9, 11,
+ 14, 16,
+ 19, 21,
+ 24, 26, 28, 30, 32, 34} {
+ if v, ok := xtob(s[x:]); !ok {
+ return nil
+ } else {
+ uuid[i] = v
+ }
+ }
+ return uuid
+}
+
+// Equal returns true if uuid1 and uuid2 are equal.
+func Equal(uuid1, uuid2 UUID) bool {
+ return bytes.Equal(uuid1, uuid2)
+}
+
+// String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
+// , or "" if uuid is invalid.
+func (uuid UUID) String() string {
+ if uuid == nil || len(uuid) != 16 {
+ return ""
+ }
+ b := []byte(uuid)
+ return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x",
+ b[:4], b[4:6], b[6:8], b[8:10], b[10:])
+}
+
+// URN returns the RFC 2141 URN form of uuid,
+// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, or "" if uuid is invalid.
+func (uuid UUID) URN() string {
+ if uuid == nil || len(uuid) != 16 {
+ return ""
+ }
+ b := []byte(uuid)
+ return fmt.Sprintf("urn:uuid:%08x-%04x-%04x-%04x-%012x",
+ b[:4], b[4:6], b[6:8], b[8:10], b[10:])
+}
+
+// Variant returns the variant encoded in uuid. It returns Invalid if
+// uuid is invalid.
+func (uuid UUID) Variant() Variant {
+ if len(uuid) != 16 {
+ return Invalid
+ }
+ switch {
+ case (uuid[8] & 0xc0) == 0x80:
+ return RFC4122
+ case (uuid[8] & 0xe0) == 0xc0:
+ return Microsoft
+ case (uuid[8] & 0xe0) == 0xe0:
+ return Future
+ default:
+ return Reserved
+ }
+ panic("unreachable")
+}
+
+// Version returns the verison of uuid. It returns false if uuid is not
+// valid.
+func (uuid UUID) Version() (Version, bool) {
+ if len(uuid) != 16 {
+ return 0, false
+ }
+ return Version(uuid[6] >> 4), true
+}
+
+func (v Version) String() string {
+ if v > 15 {
+ return fmt.Sprintf("BAD_VERSION_%d", v)
+ }
+ return fmt.Sprintf("VERSION_%d", v)
+}
+
+func (v Variant) String() string {
+ switch v {
+ case RFC4122:
+ return "RFC4122"
+ case Reserved:
+ return "Reserved"
+ case Microsoft:
+ return "Microsoft"
+ case Future:
+ return "Future"
+ case Invalid:
+ return "Invalid"
+ }
+ return fmt.Sprintf("BadVariant%d", int(v))
+}
+
+// SetRand sets the random number generator to r, which implents io.Reader.
+// If r.Read returns an error when the package requests random data then
+// a panic will be issued.
+//
+// Calling SetRand with nil sets the random number generator to the default
+// generator.
+func SetRand(r io.Reader) {
+ if r == nil {
+ rander = rand.Reader
+ return
+ }
+ rander = r
+}
diff --git a/Godeps/_workspace/src/github.com/pborman/uuid/uuid_test.go b/Godeps/_workspace/src/github.com/pborman/uuid/uuid_test.go
new file mode 100644
index 000000000..417ebeb26
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/pborman/uuid/uuid_test.go
@@ -0,0 +1,390 @@
+// Copyright 2011 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "bytes"
+ "fmt"
+ "os"
+ "strings"
+ "testing"
+ "time"
+)
+
+type test struct {
+ in string
+ version Version
+ variant Variant
+ isuuid bool
+}
+
+var tests = []test{
+ {"f47ac10b-58cc-0372-8567-0e02b2c3d479", 0, RFC4122, true},
+ {"f47ac10b-58cc-1372-8567-0e02b2c3d479", 1, RFC4122, true},
+ {"f47ac10b-58cc-2372-8567-0e02b2c3d479", 2, RFC4122, true},
+ {"f47ac10b-58cc-3372-8567-0e02b2c3d479", 3, RFC4122, true},
+ {"f47ac10b-58cc-4372-8567-0e02b2c3d479", 4, RFC4122, true},
+ {"f47ac10b-58cc-5372-8567-0e02b2c3d479", 5, RFC4122, true},
+ {"f47ac10b-58cc-6372-8567-0e02b2c3d479", 6, RFC4122, true},
+ {"f47ac10b-58cc-7372-8567-0e02b2c3d479", 7, RFC4122, true},
+ {"f47ac10b-58cc-8372-8567-0e02b2c3d479", 8, RFC4122, true},
+ {"f47ac10b-58cc-9372-8567-0e02b2c3d479", 9, RFC4122, true},
+ {"f47ac10b-58cc-a372-8567-0e02b2c3d479", 10, RFC4122, true},
+ {"f47ac10b-58cc-b372-8567-0e02b2c3d479", 11, RFC4122, true},
+ {"f47ac10b-58cc-c372-8567-0e02b2c3d479", 12, RFC4122, true},
+ {"f47ac10b-58cc-d372-8567-0e02b2c3d479", 13, RFC4122, true},
+ {"f47ac10b-58cc-e372-8567-0e02b2c3d479", 14, RFC4122, true},
+ {"f47ac10b-58cc-f372-8567-0e02b2c3d479", 15, RFC4122, true},
+
+ {"urn:uuid:f47ac10b-58cc-4372-0567-0e02b2c3d479", 4, Reserved, true},
+ {"URN:UUID:f47ac10b-58cc-4372-0567-0e02b2c3d479", 4, Reserved, true},
+ {"f47ac10b-58cc-4372-0567-0e02b2c3d479", 4, Reserved, true},
+ {"f47ac10b-58cc-4372-1567-0e02b2c3d479", 4, Reserved, true},
+ {"f47ac10b-58cc-4372-2567-0e02b2c3d479", 4, Reserved, true},
+ {"f47ac10b-58cc-4372-3567-0e02b2c3d479", 4, Reserved, true},
+ {"f47ac10b-58cc-4372-4567-0e02b2c3d479", 4, Reserved, true},
+ {"f47ac10b-58cc-4372-5567-0e02b2c3d479", 4, Reserved, true},
+ {"f47ac10b-58cc-4372-6567-0e02b2c3d479", 4, Reserved, true},
+ {"f47ac10b-58cc-4372-7567-0e02b2c3d479", 4, Reserved, true},
+ {"f47ac10b-58cc-4372-8567-0e02b2c3d479", 4, RFC4122, true},
+ {"f47ac10b-58cc-4372-9567-0e02b2c3d479", 4, RFC4122, true},
+ {"f47ac10b-58cc-4372-a567-0e02b2c3d479", 4, RFC4122, true},
+ {"f47ac10b-58cc-4372-b567-0e02b2c3d479", 4, RFC4122, true},
+ {"f47ac10b-58cc-4372-c567-0e02b2c3d479", 4, Microsoft, true},
+ {"f47ac10b-58cc-4372-d567-0e02b2c3d479", 4, Microsoft, true},
+ {"f47ac10b-58cc-4372-e567-0e02b2c3d479", 4, Future, true},
+ {"f47ac10b-58cc-4372-f567-0e02b2c3d479", 4, Future, true},
+
+ {"f47ac10b158cc-5372-a567-0e02b2c3d479", 0, Invalid, false},
+ {"f47ac10b-58cc25372-a567-0e02b2c3d479", 0, Invalid, false},
+ {"f47ac10b-58cc-53723a567-0e02b2c3d479", 0, Invalid, false},
+ {"f47ac10b-58cc-5372-a56740e02b2c3d479", 0, Invalid, false},
+ {"f47ac10b-58cc-5372-a567-0e02-2c3d479", 0, Invalid, false},
+ {"g47ac10b-58cc-4372-a567-0e02b2c3d479", 0, Invalid, false},
+}
+
+var constants = []struct {
+ c interface{}
+ name string
+}{
+ {Person, "Person"},
+ {Group, "Group"},
+ {Org, "Org"},
+ {Invalid, "Invalid"},
+ {RFC4122, "RFC4122"},
+ {Reserved, "Reserved"},
+ {Microsoft, "Microsoft"},
+ {Future, "Future"},
+ {Domain(17), "Domain17"},
+ {Variant(42), "BadVariant42"},
+}
+
+func testTest(t *testing.T, in string, tt test) {
+ uuid := Parse(in)
+ if ok := (uuid != nil); ok != tt.isuuid {
+ t.Errorf("Parse(%s) got %v expected %v\b", in, ok, tt.isuuid)
+ }
+ if uuid == nil {
+ return
+ }
+
+ if v := uuid.Variant(); v != tt.variant {
+ t.Errorf("Variant(%s) got %d expected %d\b", in, v, tt.variant)
+ }
+ if v, _ := uuid.Version(); v != tt.version {
+ t.Errorf("Version(%s) got %d expected %d\b", in, v, tt.version)
+ }
+}
+
+func TestUUID(t *testing.T) {
+ for _, tt := range tests {
+ testTest(t, tt.in, tt)
+ testTest(t, strings.ToUpper(tt.in), tt)
+ }
+}
+
+func TestConstants(t *testing.T) {
+ for x, tt := range constants {
+ v, ok := tt.c.(fmt.Stringer)
+ if !ok {
+ t.Errorf("%x: %v: not a stringer", x, v)
+ } else if s := v.String(); s != tt.name {
+ v, _ := tt.c.(int)
+ t.Errorf("%x: Constant %T:%d gives %q, expected %q\n", x, tt.c, v, s, tt.name)
+ }
+ }
+}
+
+func TestRandomUUID(t *testing.T) {
+ m := make(map[string]bool)
+ for x := 1; x < 32; x++ {
+ uuid := NewRandom()
+ s := uuid.String()
+ if m[s] {
+ t.Errorf("NewRandom returned duplicated UUID %s\n", s)
+ }
+ m[s] = true
+ if v, _ := uuid.Version(); v != 4 {
+ t.Errorf("Random UUID of version %s\n", v)
+ }
+ if uuid.Variant() != RFC4122 {
+ t.Errorf("Random UUID is variant %d\n", uuid.Variant())
+ }
+ }
+}
+
+func TestNew(t *testing.T) {
+ m := make(map[string]bool)
+ for x := 1; x < 32; x++ {
+ s := New()
+ if m[s] {
+ t.Errorf("New returned duplicated UUID %s\n", s)
+ }
+ m[s] = true
+ uuid := Parse(s)
+ if uuid == nil {
+ t.Errorf("New returned %q which does not decode\n", s)
+ continue
+ }
+ if v, _ := uuid.Version(); v != 4 {
+ t.Errorf("Random UUID of version %s\n", v)
+ }
+ if uuid.Variant() != RFC4122 {
+ t.Errorf("Random UUID is variant %d\n", uuid.Variant())
+ }
+ }
+}
+
+func clockSeq(t *testing.T, uuid UUID) int {
+ seq, ok := uuid.ClockSequence()
+ if !ok {
+ t.Fatalf("%s: invalid clock sequence\n", uuid)
+ }
+ return seq
+}
+
+func TestClockSeq(t *testing.T) {
+ // Fake time.Now for this test to return a monotonically advancing time; restore it at end.
+ defer func(orig func() time.Time) { timeNow = orig }(timeNow)
+ monTime := time.Now()
+ timeNow = func() time.Time {
+ monTime = monTime.Add(1 * time.Second)
+ return monTime
+ }
+
+ SetClockSequence(-1)
+ uuid1 := NewUUID()
+ uuid2 := NewUUID()
+
+ if clockSeq(t, uuid1) != clockSeq(t, uuid2) {
+ t.Errorf("clock sequence %d != %d\n", clockSeq(t, uuid1), clockSeq(t, uuid2))
+ }
+
+ SetClockSequence(-1)
+ uuid2 = NewUUID()
+
+ // Just on the very off chance we generated the same sequence
+ // two times we try again.
+ if clockSeq(t, uuid1) == clockSeq(t, uuid2) {
+ SetClockSequence(-1)
+ uuid2 = NewUUID()
+ }
+ if clockSeq(t, uuid1) == clockSeq(t, uuid2) {
+ t.Errorf("Duplicate clock sequence %d\n", clockSeq(t, uuid1))
+ }
+
+ SetClockSequence(0x1234)
+ uuid1 = NewUUID()
+ if seq := clockSeq(t, uuid1); seq != 0x1234 {
+ t.Errorf("%s: expected seq 0x1234 got 0x%04x\n", uuid1, seq)
+ }
+}
+
+func TestCoding(t *testing.T) {
+ text := "7d444840-9dc0-11d1-b245-5ffdce74fad2"
+ urn := "urn:uuid:7d444840-9dc0-11d1-b245-5ffdce74fad2"
+ data := UUID{
+ 0x7d, 0x44, 0x48, 0x40,
+ 0x9d, 0xc0,
+ 0x11, 0xd1,
+ 0xb2, 0x45,
+ 0x5f, 0xfd, 0xce, 0x74, 0xfa, 0xd2,
+ }
+ if v := data.String(); v != text {
+ t.Errorf("%x: encoded to %s, expected %s\n", data, v, text)
+ }
+ if v := data.URN(); v != urn {
+ t.Errorf("%x: urn is %s, expected %s\n", data, v, urn)
+ }
+
+ uuid := Parse(text)
+ if !Equal(uuid, data) {
+ t.Errorf("%s: decoded to %s, expected %s\n", text, uuid, data)
+ }
+}
+
+func TestVersion1(t *testing.T) {
+ uuid1 := NewUUID()
+ uuid2 := NewUUID()
+
+ if Equal(uuid1, uuid2) {
+ t.Errorf("%s:duplicate uuid\n", uuid1)
+ }
+ if v, _ := uuid1.Version(); v != 1 {
+ t.Errorf("%s: version %s expected 1\n", uuid1, v)
+ }
+ if v, _ := uuid2.Version(); v != 1 {
+ t.Errorf("%s: version %s expected 1\n", uuid2, v)
+ }
+ n1 := uuid1.NodeID()
+ n2 := uuid2.NodeID()
+ if !bytes.Equal(n1, n2) {
+ t.Errorf("Different nodes %x != %x\n", n1, n2)
+ }
+ t1, ok := uuid1.Time()
+ if !ok {
+ t.Errorf("%s: invalid time\n", uuid1)
+ }
+ t2, ok := uuid2.Time()
+ if !ok {
+ t.Errorf("%s: invalid time\n", uuid2)
+ }
+ q1, ok := uuid1.ClockSequence()
+ if !ok {
+ t.Errorf("%s: invalid clock sequence\n", uuid1)
+ }
+ q2, ok := uuid2.ClockSequence()
+ if !ok {
+ t.Errorf("%s: invalid clock sequence", uuid2)
+ }
+
+ switch {
+ case t1 == t2 && q1 == q2:
+ t.Errorf("time stopped\n")
+ case t1 > t2 && q1 == q2:
+ t.Errorf("time reversed\n")
+ case t1 < t2 && q1 != q2:
+ t.Errorf("clock sequence chaned unexpectedly\n")
+ }
+}
+
+func TestNodeAndTime(t *testing.T) {
+ // Time is February 5, 1998 12:30:23.136364800 AM GMT
+
+ uuid := Parse("7d444840-9dc0-11d1-b245-5ffdce74fad2")
+ node := []byte{0x5f, 0xfd, 0xce, 0x74, 0xfa, 0xd2}
+
+ ts, ok := uuid.Time()
+ if ok {
+ c := time.Unix(ts.UnixTime())
+ want := time.Date(1998, 2, 5, 0, 30, 23, 136364800, time.UTC)
+ if !c.Equal(want) {
+ t.Errorf("Got time %v, want %v", c, want)
+ }
+ } else {
+ t.Errorf("%s: bad time\n", uuid)
+ }
+ if !bytes.Equal(node, uuid.NodeID()) {
+ t.Errorf("Expected node %v got %v\n", node, uuid.NodeID())
+ }
+}
+
+func TestMD5(t *testing.T) {
+ uuid := NewMD5(NameSpace_DNS, []byte("python.org")).String()
+ want := "6fa459ea-ee8a-3ca4-894e-db77e160355e"
+ if uuid != want {
+ t.Errorf("MD5: got %q expected %q\n", uuid, want)
+ }
+}
+
+func TestSHA1(t *testing.T) {
+ uuid := NewSHA1(NameSpace_DNS, []byte("python.org")).String()
+ want := "886313e1-3b8a-5372-9b90-0c9aee199e5d"
+ if uuid != want {
+ t.Errorf("SHA1: got %q expected %q\n", uuid, want)
+ }
+}
+
+func TestNodeID(t *testing.T) {
+ nid := []byte{1, 2, 3, 4, 5, 6}
+ SetNodeInterface("")
+ s := NodeInterface()
+ if s == "" || s == "user" {
+ t.Errorf("NodeInterface %q after SetInteface\n", s)
+ }
+ node1 := NodeID()
+ if node1 == nil {
+ t.Errorf("NodeID nil after SetNodeInterface\n", s)
+ }
+ SetNodeID(nid)
+ s = NodeInterface()
+ if s != "user" {
+ t.Errorf("Expected NodeInterface %q got %q\n", "user", s)
+ }
+ node2 := NodeID()
+ if node2 == nil {
+ t.Errorf("NodeID nil after SetNodeID\n", s)
+ }
+ if bytes.Equal(node1, node2) {
+ t.Errorf("NodeID not changed after SetNodeID\n", s)
+ } else if !bytes.Equal(nid, node2) {
+ t.Errorf("NodeID is %x, expected %x\n", node2, nid)
+ }
+}
+
+func testDCE(t *testing.T, name string, uuid UUID, domain Domain, id uint32) {
+ if uuid == nil {
+ t.Errorf("%s failed\n", name)
+ return
+ }
+ if v, _ := uuid.Version(); v != 2 {
+ t.Errorf("%s: %s: expected version 2, got %s\n", name, uuid, v)
+ return
+ }
+ if v, ok := uuid.Domain(); !ok || v != domain {
+ if !ok {
+ t.Errorf("%s: %d: Domain failed\n", name, uuid)
+ } else {
+ t.Errorf("%s: %s: expected domain %d, got %d\n", name, uuid, domain, v)
+ }
+ }
+ if v, ok := uuid.Id(); !ok || v != id {
+ if !ok {
+ t.Errorf("%s: %d: Id failed\n", name, uuid)
+ } else {
+ t.Errorf("%s: %s: expected id %d, got %d\n", name, uuid, id, v)
+ }
+ }
+}
+
+func TestDCE(t *testing.T) {
+ testDCE(t, "NewDCESecurity", NewDCESecurity(42, 12345678), 42, 12345678)
+ testDCE(t, "NewDCEPerson", NewDCEPerson(), Person, uint32(os.Getuid()))
+ testDCE(t, "NewDCEGroup", NewDCEGroup(), Group, uint32(os.Getgid()))
+}
+
+type badRand struct{}
+
+func (r badRand) Read(buf []byte) (int, error) {
+ for i, _ := range buf {
+ buf[i] = byte(i)
+ }
+ return len(buf), nil
+}
+
+func TestBadRand(t *testing.T) {
+ SetRand(badRand{})
+ uuid1 := New()
+ uuid2 := New()
+ if uuid1 != uuid2 {
+ t.Errorf("execpted duplicates, got %q and %q\n", uuid1, uuid2)
+ }
+ SetRand(nil)
+ uuid1 = New()
+ uuid2 = New()
+ if uuid1 == uuid2 {
+ t.Errorf("unexecpted duplicates, got %q\n", uuid1)
+ }
+}
diff --git a/Godeps/_workspace/src/github.com/pborman/uuid/version1.go b/Godeps/_workspace/src/github.com/pborman/uuid/version1.go
new file mode 100644
index 000000000..0127eacfa
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/pborman/uuid/version1.go
@@ -0,0 +1,41 @@
+// Copyright 2011 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "encoding/binary"
+)
+
+// NewUUID returns a Version 1 UUID based on the current NodeID and clock
+// sequence, and the current time. If the NodeID has not been set by SetNodeID
+// or SetNodeInterface then it will be set automatically. If the NodeID cannot
+// be set NewUUID returns nil. If clock sequence has not been set by
+// SetClockSequence then it will be set automatically. If GetTime fails to
+// return the current NewUUID returns nil.
+func NewUUID() UUID {
+ if nodeID == nil {
+ SetNodeInterface("")
+ }
+
+ now, seq, err := GetTime()
+ if err != nil {
+ return nil
+ }
+
+ uuid := make([]byte, 16)
+
+ time_low := uint32(now & 0xffffffff)
+ time_mid := uint16((now >> 32) & 0xffff)
+ time_hi := uint16((now >> 48) & 0x0fff)
+ time_hi |= 0x1000 // Version 1
+
+ binary.BigEndian.PutUint32(uuid[0:], time_low)
+ binary.BigEndian.PutUint16(uuid[4:], time_mid)
+ binary.BigEndian.PutUint16(uuid[6:], time_hi)
+ binary.BigEndian.PutUint16(uuid[8:], seq)
+ copy(uuid[10:], nodeID)
+
+ return uuid
+}
diff --git a/Godeps/_workspace/src/github.com/pborman/uuid/version4.go b/Godeps/_workspace/src/github.com/pborman/uuid/version4.go
new file mode 100644
index 000000000..b3d4a368d
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/pborman/uuid/version4.go
@@ -0,0 +1,25 @@
+// Copyright 2011 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+// Random returns a Random (Version 4) UUID or panics.
+//
+// The strength of the UUIDs is based on the strength of the crypto/rand
+// package.
+//
+// A note about uniqueness derived from from the UUID Wikipedia entry:
+//
+// Randomly generated UUIDs have 122 random bits. One's annual risk of being
+// hit by a meteorite is estimated to be one chance in 17 billion, that
+// means the probability is about 0.00000000006 (6 × 10−11),
+// equivalent to the odds of creating a few tens of trillions of UUIDs in a
+// year and having one duplicate.
+func NewRandom() UUID {
+ uuid := make([]byte, 16)
+ randomBits([]byte(uuid))
+ uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4
+ uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10
+ return uuid
+}
diff --git a/Godeps/_workspace/src/github.com/pmezard/go-difflib/difflib/difflib.go b/Godeps/_workspace/src/github.com/pmezard/go-difflib/difflib/difflib.go
new file mode 100644
index 000000000..64cc40fe1
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/pmezard/go-difflib/difflib/difflib.go
@@ -0,0 +1,758 @@
+// Package difflib is a partial port of Python difflib module.
+//
+// It provides tools to compare sequences of strings and generate textual diffs.
+//
+// The following class and functions have been ported:
+//
+// - SequenceMatcher
+//
+// - unified_diff
+//
+// - context_diff
+//
+// Getting unified diffs was the main goal of the port. Keep in mind this code
+// is mostly suitable to output text differences in a human friendly way, there
+// are no guarantees generated diffs are consumable by patch(1).
+package difflib
+
+import (
+ "bufio"
+ "bytes"
+ "fmt"
+ "io"
+ "strings"
+)
+
+func min(a, b int) int {
+ if a < b {
+ return a
+ }
+ return b
+}
+
+func max(a, b int) int {
+ if a > b {
+ return a
+ }
+ return b
+}
+
+func calculateRatio(matches, length int) float64 {
+ if length > 0 {
+ return 2.0 * float64(matches) / float64(length)
+ }
+ return 1.0
+}
+
+type Match struct {
+ A int
+ B int
+ Size int
+}
+
+type OpCode struct {
+ Tag byte
+ I1 int
+ I2 int
+ J1 int
+ J2 int
+}
+
+// SequenceMatcher compares sequence of strings. The basic
+// algorithm predates, and is a little fancier than, an algorithm
+// published in the late 1980's by Ratcliff and Obershelp under the
+// hyperbolic name "gestalt pattern matching". The basic idea is to find
+// the longest contiguous matching subsequence that contains no "junk"
+// elements (R-O doesn't address junk). The same idea is then applied
+// recursively to the pieces of the sequences to the left and to the right
+// of the matching subsequence. This does not yield minimal edit
+// sequences, but does tend to yield matches that "look right" to people.
+//
+// SequenceMatcher tries to compute a "human-friendly diff" between two
+// sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the
+// longest *contiguous* & junk-free matching subsequence. That's what
+// catches peoples' eyes. The Windows(tm) windiff has another interesting
+// notion, pairing up elements that appear uniquely in each sequence.
+// That, and the method here, appear to yield more intuitive difference
+// reports than does diff. This method appears to be the least vulnerable
+// to synching up on blocks of "junk lines", though (like blank lines in
+// ordinary text files, or maybe "<P>" lines in HTML files). That may be
+// because this is the only method of the 3 that has a *concept* of
+// "junk" <wink>.
+//
+// Timing: Basic R-O is cubic time worst case and quadratic time expected
+// case. SequenceMatcher is quadratic time for the worst case and has
+// expected-case behavior dependent in a complicated way on how many
+// elements the sequences have in common; best case time is linear.
+type SequenceMatcher struct {
+ a []string
+ b []string
+ b2j map[string][]int
+ IsJunk func(string) bool
+ autoJunk bool
+ bJunk map[string]struct{}
+ matchingBlocks []Match
+ fullBCount map[string]int
+ bPopular map[string]struct{}
+ opCodes []OpCode
+}
+
+func NewMatcher(a, b []string) *SequenceMatcher {
+ m := SequenceMatcher{autoJunk: true}
+ m.SetSeqs(a, b)
+ return &m
+}
+
+func NewMatcherWithJunk(a, b []string, autoJunk bool,
+ isJunk func(string) bool) *SequenceMatcher {
+
+ m := SequenceMatcher{IsJunk: isJunk, autoJunk: autoJunk}
+ m.SetSeqs(a, b)
+ return &m
+}
+
+// Set two sequences to be compared.
+func (m *SequenceMatcher) SetSeqs(a, b []string) {
+ m.SetSeq1(a)
+ m.SetSeq2(b)
+}
+
+// Set the first sequence to be compared. The second sequence to be compared is
+// not changed.
+//
+// SequenceMatcher computes and caches detailed information about the second
+// sequence, so if you want to compare one sequence S against many sequences,
+// use .SetSeq2(s) once and call .SetSeq1(x) repeatedly for each of the other
+// sequences.
+//
+// See also SetSeqs() and SetSeq2().
+func (m *SequenceMatcher) SetSeq1(a []string) {
+ if &a == &m.a {
+ return
+ }
+ m.a = a
+ m.matchingBlocks = nil
+ m.opCodes = nil
+}
+
+// Set the second sequence to be compared. The first sequence to be compared is
+// not changed.
+func (m *SequenceMatcher) SetSeq2(b []string) {
+ if &b == &m.b {
+ return
+ }
+ m.b = b
+ m.matchingBlocks = nil
+ m.opCodes = nil
+ m.fullBCount = nil
+ m.chainB()
+}
+
+func (m *SequenceMatcher) chainB() {
+ // Populate line -> index mapping
+ b2j := map[string][]int{}
+ for i, s := range m.b {
+ indices := b2j[s]
+ indices = append(indices, i)
+ b2j[s] = indices
+ }
+
+ // Purge junk elements
+ m.bJunk = map[string]struct{}{}
+ if m.IsJunk != nil {
+ junk := m.bJunk
+ for s, _ := range b2j {
+ if m.IsJunk(s) {
+ junk[s] = struct{}{}
+ }
+ }
+ for s, _ := range junk {
+ delete(b2j, s)
+ }
+ }
+
+ // Purge remaining popular elements
+ popular := map[string]struct{}{}
+ n := len(m.b)
+ if m.autoJunk && n >= 200 {
+ ntest := n/100 + 1
+ for s, indices := range b2j {
+ if len(indices) > ntest {
+ popular[s] = struct{}{}
+ }
+ }
+ for s, _ := range popular {
+ delete(b2j, s)
+ }
+ }
+ m.bPopular = popular
+ m.b2j = b2j
+}
+
+func (m *SequenceMatcher) isBJunk(s string) bool {
+ _, ok := m.bJunk[s]
+ return ok
+}
+
+// Find longest matching block in a[alo:ahi] and b[blo:bhi].
+//
+// If IsJunk is not defined:
+//
+// Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
+// alo <= i <= i+k <= ahi
+// blo <= j <= j+k <= bhi
+// and for all (i',j',k') meeting those conditions,
+// k >= k'
+// i <= i'
+// and if i == i', j <= j'
+//
+// In other words, of all maximal matching blocks, return one that
+// starts earliest in a, and of all those maximal matching blocks that
+// start earliest in a, return the one that starts earliest in b.
+//
+// If IsJunk is defined, first the longest matching block is
+// determined as above, but with the additional restriction that no
+// junk element appears in the block. Then that block is extended as
+// far as possible by matching (only) junk elements on both sides. So
+// the resulting block never matches on junk except as identical junk
+// happens to be adjacent to an "interesting" match.
+//
+// If no blocks match, return (alo, blo, 0).
+func (m *SequenceMatcher) findLongestMatch(alo, ahi, blo, bhi int) Match {
+ // CAUTION: stripping common prefix or suffix would be incorrect.
+ // E.g.,
+ // ab
+ // acab
+ // Longest matching block is "ab", but if common prefix is
+ // stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
+ // strip, so ends up claiming that ab is changed to acab by
+ // inserting "ca" in the middle. That's minimal but unintuitive:
+ // "it's obvious" that someone inserted "ac" at the front.
+ // Windiff ends up at the same place as diff, but by pairing up
+ // the unique 'b's and then matching the first two 'a's.
+ besti, bestj, bestsize := alo, blo, 0
+
+ // find longest junk-free match
+ // during an iteration of the loop, j2len[j] = length of longest
+ // junk-free match ending with a[i-1] and b[j]
+ j2len := map[int]int{}
+ for i := alo; i != ahi; i++ {
+ // look at all instances of a[i] in b; note that because
+ // b2j has no junk keys, the loop is skipped if a[i] is junk
+ newj2len := map[int]int{}
+ for _, j := range m.b2j[m.a[i]] {
+ // a[i] matches b[j]
+ if j < blo {
+ continue
+ }
+ if j >= bhi {
+ break
+ }
+ k := j2len[j-1] + 1
+ newj2len[j] = k
+ if k > bestsize {
+ besti, bestj, bestsize = i-k+1, j-k+1, k
+ }
+ }
+ j2len = newj2len
+ }
+
+ // Extend the best by non-junk elements on each end. In particular,
+ // "popular" non-junk elements aren't in b2j, which greatly speeds
+ // the inner loop above, but also means "the best" match so far
+ // doesn't contain any junk *or* popular non-junk elements.
+ for besti > alo && bestj > blo && !m.isBJunk(m.b[bestj-1]) &&
+ m.a[besti-1] == m.b[bestj-1] {
+ besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
+ }
+ for besti+bestsize < ahi && bestj+bestsize < bhi &&
+ !m.isBJunk(m.b[bestj+bestsize]) &&
+ m.a[besti+bestsize] == m.b[bestj+bestsize] {
+ bestsize += 1
+ }
+
+ // Now that we have a wholly interesting match (albeit possibly
+ // empty!), we may as well suck up the matching junk on each
+ // side of it too. Can't think of a good reason not to, and it
+ // saves post-processing the (possibly considerable) expense of
+ // figuring out what to do with it. In the case of an empty
+ // interesting match, this is clearly the right thing to do,
+ // because no other kind of match is possible in the regions.
+ for besti > alo && bestj > blo && m.isBJunk(m.b[bestj-1]) &&
+ m.a[besti-1] == m.b[bestj-1] {
+ besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
+ }
+ for besti+bestsize < ahi && bestj+bestsize < bhi &&
+ m.isBJunk(m.b[bestj+bestsize]) &&
+ m.a[besti+bestsize] == m.b[bestj+bestsize] {
+ bestsize += 1
+ }
+
+ return Match{A: besti, B: bestj, Size: bestsize}
+}
+
+// Return list of triples describing matching subsequences.
+//
+// Each triple is of the form (i, j, n), and means that
+// a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
+// i and in j. It's also guaranteed that if (i, j, n) and (i', j', n') are
+// adjacent triples in the list, and the second is not the last triple in the
+// list, then i+n != i' or j+n != j'. IOW, adjacent triples never describe
+// adjacent equal blocks.
+//
+// The last triple is a dummy, (len(a), len(b), 0), and is the only
+// triple with n==0.
+func (m *SequenceMatcher) GetMatchingBlocks() []Match {
+ if m.matchingBlocks != nil {
+ return m.matchingBlocks
+ }
+
+ var matchBlocks func(alo, ahi, blo, bhi int, matched []Match) []Match
+ matchBlocks = func(alo, ahi, blo, bhi int, matched []Match) []Match {
+ match := m.findLongestMatch(alo, ahi, blo, bhi)
+ i, j, k := match.A, match.B, match.Size
+ if match.Size > 0 {
+ if alo < i && blo < j {
+ matched = matchBlocks(alo, i, blo, j, matched)
+ }
+ matched = append(matched, match)
+ if i+k < ahi && j+k < bhi {
+ matched = matchBlocks(i+k, ahi, j+k, bhi, matched)
+ }
+ }
+ return matched
+ }
+ matched := matchBlocks(0, len(m.a), 0, len(m.b), nil)
+
+ // It's possible that we have adjacent equal blocks in the
+ // matching_blocks list now.
+ nonAdjacent := []Match{}
+ i1, j1, k1 := 0, 0, 0
+ for _, b := range matched {
+ // Is this block adjacent to i1, j1, k1?
+ i2, j2, k2 := b.A, b.B, b.Size
+ if i1+k1 == i2 && j1+k1 == j2 {
+ // Yes, so collapse them -- this just increases the length of
+ // the first block by the length of the second, and the first
+ // block so lengthened remains the block to compare against.
+ k1 += k2
+ } else {
+ // Not adjacent. Remember the first block (k1==0 means it's
+ // the dummy we started with), and make the second block the
+ // new block to compare against.
+ if k1 > 0 {
+ nonAdjacent = append(nonAdjacent, Match{i1, j1, k1})
+ }
+ i1, j1, k1 = i2, j2, k2
+ }
+ }
+ if k1 > 0 {
+ nonAdjacent = append(nonAdjacent, Match{i1, j1, k1})
+ }
+
+ nonAdjacent = append(nonAdjacent, Match{len(m.a), len(m.b), 0})
+ m.matchingBlocks = nonAdjacent
+ return m.matchingBlocks
+}
+
+// Return list of 5-tuples describing how to turn a into b.
+//
+// Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple
+// has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
+// tuple preceding it, and likewise for j1 == the previous j2.
+//
+// The tags are characters, with these meanings:
+//
+// 'r' (replace): a[i1:i2] should be replaced by b[j1:j2]
+//
+// 'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case.
+//
+// 'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case.
+//
+// 'e' (equal): a[i1:i2] == b[j1:j2]
+func (m *SequenceMatcher) GetOpCodes() []OpCode {
+ if m.opCodes != nil {
+ return m.opCodes
+ }
+ i, j := 0, 0
+ matching := m.GetMatchingBlocks()
+ opCodes := make([]OpCode, 0, len(matching))
+ for _, m := range matching {
+ // invariant: we've pumped out correct diffs to change
+ // a[:i] into b[:j], and the next matching block is
+ // a[ai:ai+size] == b[bj:bj+size]. So we need to pump
+ // out a diff to change a[i:ai] into b[j:bj], pump out
+ // the matching block, and move (i,j) beyond the match
+ ai, bj, size := m.A, m.B, m.Size
+ tag := byte(0)
+ if i < ai && j < bj {
+ tag = 'r'
+ } else if i < ai {
+ tag = 'd'
+ } else if j < bj {
+ tag = 'i'
+ }
+ if tag > 0 {
+ opCodes = append(opCodes, OpCode{tag, i, ai, j, bj})
+ }
+ i, j = ai+size, bj+size
+ // the list of matching blocks is terminated by a
+ // sentinel with size 0
+ if size > 0 {
+ opCodes = append(opCodes, OpCode{'e', ai, i, bj, j})
+ }
+ }
+ m.opCodes = opCodes
+ return m.opCodes
+}
+
+// Isolate change clusters by eliminating ranges with no changes.
+//
+// Return a generator of groups with up to n lines of context.
+// Each group is in the same format as returned by GetOpCodes().
+func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode {
+ if n < 0 {
+ n = 3
+ }
+ codes := m.GetOpCodes()
+ if len(codes) == 0 {
+ codes = []OpCode{OpCode{'e', 0, 1, 0, 1}}
+ }
+ // Fixup leading and trailing groups if they show no changes.
+ if codes[0].Tag == 'e' {
+ c := codes[0]
+ i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
+ codes[0] = OpCode{c.Tag, max(i1, i2-n), i2, max(j1, j2-n), j2}
+ }
+ if codes[len(codes)-1].Tag == 'e' {
+ c := codes[len(codes)-1]
+ i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
+ codes[len(codes)-1] = OpCode{c.Tag, i1, min(i2, i1+n), j1, min(j2, j1+n)}
+ }
+ nn := n + n
+ groups := [][]OpCode{}
+ group := []OpCode{}
+ for _, c := range codes {
+ i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
+ // End the current group and start a new one whenever
+ // there is a large range with no changes.
+ if c.Tag == 'e' && i2-i1 > nn {
+ group = append(group, OpCode{c.Tag, i1, min(i2, i1+n),
+ j1, min(j2, j1+n)})
+ groups = append(groups, group)
+ group = []OpCode{}
+ i1, j1 = max(i1, i2-n), max(j1, j2-n)
+ }
+ group = append(group, OpCode{c.Tag, i1, i2, j1, j2})
+ }
+ if len(group) > 0 && !(len(group) == 1 && group[0].Tag == 'e') {
+ groups = append(groups, group)
+ }
+ return groups
+}
+
+// Return a measure of the sequences' similarity (float in [0,1]).
+//
+// Where T is the total number of elements in both sequences, and
+// M is the number of matches, this is 2.0*M / T.
+// Note that this is 1 if the sequences are identical, and 0 if
+// they have nothing in common.
+//
+// .Ratio() is expensive to compute if you haven't already computed
+// .GetMatchingBlocks() or .GetOpCodes(), in which case you may
+// want to try .QuickRatio() or .RealQuickRation() first to get an
+// upper bound.
+func (m *SequenceMatcher) Ratio() float64 {
+ matches := 0
+ for _, m := range m.GetMatchingBlocks() {
+ matches += m.Size
+ }
+ return calculateRatio(matches, len(m.a)+len(m.b))
+}
+
+// Return an upper bound on ratio() relatively quickly.
+//
+// This isn't defined beyond that it is an upper bound on .Ratio(), and
+// is faster to compute.
+func (m *SequenceMatcher) QuickRatio() float64 {
+ // viewing a and b as multisets, set matches to the cardinality
+ // of their intersection; this counts the number of matches
+ // without regard to order, so is clearly an upper bound
+ if m.fullBCount == nil {
+ m.fullBCount = map[string]int{}
+ for _, s := range m.b {
+ m.fullBCount[s] = m.fullBCount[s] + 1
+ }
+ }
+
+ // avail[x] is the number of times x appears in 'b' less the
+ // number of times we've seen it in 'a' so far ... kinda
+ avail := map[string]int{}
+ matches := 0
+ for _, s := range m.a {
+ n, ok := avail[s]
+ if !ok {
+ n = m.fullBCount[s]
+ }
+ avail[s] = n - 1
+ if n > 0 {
+ matches += 1
+ }
+ }
+ return calculateRatio(matches, len(m.a)+len(m.b))
+}
+
+// Return an upper bound on ratio() very quickly.
+//
+// This isn't defined beyond that it is an upper bound on .Ratio(), and
+// is faster to compute than either .Ratio() or .QuickRatio().
+func (m *SequenceMatcher) RealQuickRatio() float64 {
+ la, lb := len(m.a), len(m.b)
+ return calculateRatio(min(la, lb), la+lb)
+}
+
+// Convert range to the "ed" format
+func formatRangeUnified(start, stop int) string {
+ // Per the diff spec at http://www.unix.org/single_unix_specification/
+ beginning := start + 1 // lines start numbering with one
+ length := stop - start
+ if length == 1 {
+ return fmt.Sprintf("%d", beginning)
+ }
+ if length == 0 {
+ beginning -= 1 // empty ranges begin at line just before the range
+ }
+ return fmt.Sprintf("%d,%d", beginning, length)
+}
+
+// Unified diff parameters
+type UnifiedDiff struct {
+ A []string // First sequence lines
+ FromFile string // First file name
+ FromDate string // First file time
+ B []string // Second sequence lines
+ ToFile string // Second file name
+ ToDate string // Second file time
+ Eol string // Headers end of line, defaults to LF
+ Context int // Number of context lines
+}
+
+// Compare two sequences of lines; generate the delta as a unified diff.
+//
+// Unified diffs are a compact way of showing line changes and a few
+// lines of context. The number of context lines is set by 'n' which
+// defaults to three.
+//
+// By default, the diff control lines (those with ---, +++, or @@) are
+// created with a trailing newline. This is helpful so that inputs
+// created from file.readlines() result in diffs that are suitable for
+// file.writelines() since both the inputs and outputs have trailing
+// newlines.
+//
+// For inputs that do not have trailing newlines, set the lineterm
+// argument to "" so that the output will be uniformly newline free.
+//
+// The unidiff format normally has a header for filenames and modification
+// times. Any or all of these may be specified using strings for
+// 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
+// The modification times are normally expressed in the ISO 8601 format.
+func WriteUnifiedDiff(writer io.Writer, diff UnifiedDiff) error {
+ buf := bufio.NewWriter(writer)
+ defer buf.Flush()
+ w := func(format string, args ...interface{}) error {
+ _, err := buf.WriteString(fmt.Sprintf(format, args...))
+ return err
+ }
+
+ if len(diff.Eol) == 0 {
+ diff.Eol = "\n"
+ }
+
+ started := false
+ m := NewMatcher(diff.A, diff.B)
+ for _, g := range m.GetGroupedOpCodes(diff.Context) {
+ if !started {
+ started = true
+ fromDate := ""
+ if len(diff.FromDate) > 0 {
+ fromDate = "\t" + diff.FromDate
+ }
+ toDate := ""
+ if len(diff.ToDate) > 0 {
+ toDate = "\t" + diff.ToDate
+ }
+ err := w("--- %s%s%s", diff.FromFile, fromDate, diff.Eol)
+ if err != nil {
+ return err
+ }
+ err = w("+++ %s%s%s", diff.ToFile, toDate, diff.Eol)
+ if err != nil {
+ return err
+ }
+ }
+ first, last := g[0], g[len(g)-1]
+ range1 := formatRangeUnified(first.I1, last.I2)
+ range2 := formatRangeUnified(first.J1, last.J2)
+ if err := w("@@ -%s +%s @@%s", range1, range2, diff.Eol); err != nil {
+ return err
+ }
+ for _, c := range g {
+ i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
+ if c.Tag == 'e' {
+ for _, line := range diff.A[i1:i2] {
+ if err := w(" " + line); err != nil {
+ return err
+ }
+ }
+ continue
+ }
+ if c.Tag == 'r' || c.Tag == 'd' {
+ for _, line := range diff.A[i1:i2] {
+ if err := w("-" + line); err != nil {
+ return err
+ }
+ }
+ }
+ if c.Tag == 'r' || c.Tag == 'i' {
+ for _, line := range diff.B[j1:j2] {
+ if err := w("+" + line); err != nil {
+ return err
+ }
+ }
+ }
+ }
+ }
+ return nil
+}
+
+// Like WriteUnifiedDiff but returns the diff a string.
+func GetUnifiedDiffString(diff UnifiedDiff) (string, error) {
+ w := &bytes.Buffer{}
+ err := WriteUnifiedDiff(w, diff)
+ return string(w.Bytes()), err
+}
+
+// Convert range to the "ed" format.
+func formatRangeContext(start, stop int) string {
+ // Per the diff spec at http://www.unix.org/single_unix_specification/
+ beginning := start + 1 // lines start numbering with one
+ length := stop - start
+ if length == 0 {
+ beginning -= 1 // empty ranges begin at line just before the range
+ }
+ if length <= 1 {
+ return fmt.Sprintf("%d", beginning)
+ }
+ return fmt.Sprintf("%d,%d", beginning, beginning+length-1)
+}
+
+type ContextDiff UnifiedDiff
+
+// Compare two sequences of lines; generate the delta as a context diff.
+//
+// Context diffs are a compact way of showing line changes and a few
+// lines of context. The number of context lines is set by diff.Context
+// which defaults to three.
+//
+// By default, the diff control lines (those with *** or ---) are
+// created with a trailing newline.
+//
+// For inputs that do not have trailing newlines, set the diff.Eol
+// argument to "" so that the output will be uniformly newline free.
+//
+// The context diff format normally has a header for filenames and
+// modification times. Any or all of these may be specified using
+// strings for diff.FromFile, diff.ToFile, diff.FromDate, diff.ToDate.
+// The modification times are normally expressed in the ISO 8601 format.
+// If not specified, the strings default to blanks.
+func WriteContextDiff(writer io.Writer, diff ContextDiff) error {
+ buf := bufio.NewWriter(writer)
+ defer buf.Flush()
+ var diffErr error
+ w := func(format string, args ...interface{}) {
+ _, err := buf.WriteString(fmt.Sprintf(format, args...))
+ if diffErr == nil && err != nil {
+ diffErr = err
+ }
+ }
+
+ if len(diff.Eol) == 0 {
+ diff.Eol = "\n"
+ }
+
+ prefix := map[byte]string{
+ 'i': "+ ",
+ 'd': "- ",
+ 'r': "! ",
+ 'e': " ",
+ }
+
+ started := false
+ m := NewMatcher(diff.A, diff.B)
+ for _, g := range m.GetGroupedOpCodes(diff.Context) {
+ if !started {
+ started = true
+ fromDate := ""
+ if len(diff.FromDate) > 0 {
+ fromDate = "\t" + diff.FromDate
+ }
+ toDate := ""
+ if len(diff.ToDate) > 0 {
+ toDate = "\t" + diff.ToDate
+ }
+ w("*** %s%s%s", diff.FromFile, fromDate, diff.Eol)
+ w("--- %s%s%s", diff.ToFile, toDate, diff.Eol)
+ }
+
+ first, last := g[0], g[len(g)-1]
+ w("***************" + diff.Eol)
+
+ range1 := formatRangeContext(first.I1, last.I2)
+ w("*** %s ****%s", range1, diff.Eol)
+ for _, c := range g {
+ if c.Tag == 'r' || c.Tag == 'd' {
+ for _, cc := range g {
+ if cc.Tag == 'i' {
+ continue
+ }
+ for _, line := range diff.A[cc.I1:cc.I2] {
+ w(prefix[cc.Tag] + line)
+ }
+ }
+ break
+ }
+ }
+
+ range2 := formatRangeContext(first.J1, last.J2)
+ w("--- %s ----%s", range2, diff.Eol)
+ for _, c := range g {
+ if c.Tag == 'r' || c.Tag == 'i' {
+ for _, cc := range g {
+ if cc.Tag == 'd' {
+ continue
+ }
+ for _, line := range diff.B[cc.J1:cc.J2] {
+ w(prefix[cc.Tag] + line)
+ }
+ }
+ break
+ }
+ }
+ }
+ return diffErr
+}
+
+// Like WriteContextDiff but returns the diff a string.
+func GetContextDiffString(diff ContextDiff) (string, error) {
+ w := &bytes.Buffer{}
+ err := WriteContextDiff(w, diff)
+ return string(w.Bytes()), err
+}
+
+// Split a string on "\n" while preserving them. The output can be used
+// as input for UnifiedDiff and ContextDiff structures.
+func SplitLines(s string) []string {
+ lines := strings.SplitAfter(s, "\n")
+ lines[len(lines)-1] += "\n"
+ return lines
+}
diff --git a/Godeps/_workspace/src/github.com/pmezard/go-difflib/difflib/difflib_test.go b/Godeps/_workspace/src/github.com/pmezard/go-difflib/difflib/difflib_test.go
new file mode 100644
index 000000000..94670bea3
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/pmezard/go-difflib/difflib/difflib_test.go
@@ -0,0 +1,352 @@
+package difflib
+
+import (
+ "bytes"
+ "fmt"
+ "math"
+ "reflect"
+ "strings"
+ "testing"
+)
+
+func assertAlmostEqual(t *testing.T, a, b float64, places int) {
+ if math.Abs(a-b) > math.Pow10(-places) {
+ t.Errorf("%.7f != %.7f", a, b)
+ }
+}
+
+func assertEqual(t *testing.T, a, b interface{}) {
+ if !reflect.DeepEqual(a, b) {
+ t.Errorf("%v != %v", a, b)
+ }
+}
+
+func splitChars(s string) []string {
+ chars := make([]string, 0, len(s))
+ // Assume ASCII inputs
+ for i := 0; i != len(s); i++ {
+ chars = append(chars, string(s[i]))
+ }
+ return chars
+}
+
+func TestSequenceMatcherRatio(t *testing.T) {
+ s := NewMatcher(splitChars("abcd"), splitChars("bcde"))
+ assertEqual(t, s.Ratio(), 0.75)
+ assertEqual(t, s.QuickRatio(), 0.75)
+ assertEqual(t, s.RealQuickRatio(), 1.0)
+}
+
+func TestGetOptCodes(t *testing.T) {
+ a := "qabxcd"
+ b := "abycdf"
+ s := NewMatcher(splitChars(a), splitChars(b))
+ w := &bytes.Buffer{}
+ for _, op := range s.GetOpCodes() {
+ fmt.Fprintf(w, "%s a[%d:%d], (%s) b[%d:%d] (%s)\n", string(op.Tag),
+ op.I1, op.I2, a[op.I1:op.I2], op.J1, op.J2, b[op.J1:op.J2])
+ }
+ result := string(w.Bytes())
+ expected := `d a[0:1], (q) b[0:0] ()
+e a[1:3], (ab) b[0:2] (ab)
+r a[3:4], (x) b[2:3] (y)
+e a[4:6], (cd) b[3:5] (cd)
+i a[6:6], () b[5:6] (f)
+`
+ if expected != result {
+ t.Errorf("unexpected op codes: \n%s", result)
+ }
+}
+
+func TestGroupedOpCodes(t *testing.T) {
+ a := []string{}
+ for i := 0; i != 39; i++ {
+ a = append(a, fmt.Sprintf("%02d", i))
+ }
+ b := []string{}
+ b = append(b, a[:8]...)
+ b = append(b, " i")
+ b = append(b, a[8:19]...)
+ b = append(b, " x")
+ b = append(b, a[20:22]...)
+ b = append(b, a[27:34]...)
+ b = append(b, " y")
+ b = append(b, a[35:]...)
+ s := NewMatcher(a, b)
+ w := &bytes.Buffer{}
+ for _, g := range s.GetGroupedOpCodes(-1) {
+ fmt.Fprintf(w, "group\n")
+ for _, op := range g {
+ fmt.Fprintf(w, " %s, %d, %d, %d, %d\n", string(op.Tag),
+ op.I1, op.I2, op.J1, op.J2)
+ }
+ }
+ result := string(w.Bytes())
+ expected := `group
+ e, 5, 8, 5, 8
+ i, 8, 8, 8, 9
+ e, 8, 11, 9, 12
+group
+ e, 16, 19, 17, 20
+ r, 19, 20, 20, 21
+ e, 20, 22, 21, 23
+ d, 22, 27, 23, 23
+ e, 27, 30, 23, 26
+group
+ e, 31, 34, 27, 30
+ r, 34, 35, 30, 31
+ e, 35, 38, 31, 34
+`
+ if expected != result {
+ t.Errorf("unexpected op codes: \n%s", result)
+ }
+}
+
+func ExampleGetUnifiedDiffString() {
+ a := `one
+two
+three
+four`
+ b := `zero
+one
+three
+four`
+ diff := UnifiedDiff{
+ A: SplitLines(a),
+ B: SplitLines(b),
+ FromFile: "Original",
+ FromDate: "2005-01-26 23:30:50",
+ ToFile: "Current",
+ ToDate: "2010-04-02 10:20:52",
+ Context: 3,
+ }
+ result, _ := GetUnifiedDiffString(diff)
+ fmt.Printf(strings.Replace(result, "\t", " ", -1))
+ // Output:
+ // --- Original 2005-01-26 23:30:50
+ // +++ Current 2010-04-02 10:20:52
+ // @@ -1,4 +1,4 @@
+ // +zero
+ // one
+ // -two
+ // three
+ // four
+}
+
+func ExampleGetContextDiffString() {
+ a := `one
+two
+three
+four`
+ b := `zero
+one
+tree
+four`
+ diff := ContextDiff{
+ A: SplitLines(a),
+ B: SplitLines(b),
+ FromFile: "Original",
+ ToFile: "Current",
+ Context: 3,
+ Eol: "\n",
+ }
+ result, _ := GetContextDiffString(diff)
+ fmt.Printf(strings.Replace(result, "\t", " ", -1))
+ // Output:
+ // *** Original
+ // --- Current
+ // ***************
+ // *** 1,4 ****
+ // one
+ // ! two
+ // ! three
+ // four
+ // --- 1,4 ----
+ // + zero
+ // one
+ // ! tree
+ // four
+}
+
+func rep(s string, count int) string {
+ return strings.Repeat(s, count)
+}
+
+func TestWithAsciiOneInsert(t *testing.T) {
+ sm := NewMatcher(splitChars(rep("b", 100)),
+ splitChars("a"+rep("b", 100)))
+ assertAlmostEqual(t, sm.Ratio(), 0.995, 3)
+ assertEqual(t, sm.GetOpCodes(),
+ []OpCode{{'i', 0, 0, 0, 1}, {'e', 0, 100, 1, 101}})
+ assertEqual(t, len(sm.bPopular), 0)
+
+ sm = NewMatcher(splitChars(rep("b", 100)),
+ splitChars(rep("b", 50)+"a"+rep("b", 50)))
+ assertAlmostEqual(t, sm.Ratio(), 0.995, 3)
+ assertEqual(t, sm.GetOpCodes(),
+ []OpCode{{'e', 0, 50, 0, 50}, {'i', 50, 50, 50, 51}, {'e', 50, 100, 51, 101}})
+ assertEqual(t, len(sm.bPopular), 0)
+}
+
+func TestWithAsciiOnDelete(t *testing.T) {
+ sm := NewMatcher(splitChars(rep("a", 40)+"c"+rep("b", 40)),
+ splitChars(rep("a", 40)+rep("b", 40)))
+ assertAlmostEqual(t, sm.Ratio(), 0.994, 3)
+ assertEqual(t, sm.GetOpCodes(),
+ []OpCode{{'e', 0, 40, 0, 40}, {'d', 40, 41, 40, 40}, {'e', 41, 81, 40, 80}})
+}
+
+func TestWithAsciiBJunk(t *testing.T) {
+ isJunk := func(s string) bool {
+ return s == " "
+ }
+ sm := NewMatcherWithJunk(splitChars(rep("a", 40)+rep("b", 40)),
+ splitChars(rep("a", 44)+rep("b", 40)), true, isJunk)
+ assertEqual(t, sm.bJunk, map[string]struct{}{})
+
+ sm = NewMatcherWithJunk(splitChars(rep("a", 40)+rep("b", 40)),
+ splitChars(rep("a", 44)+rep("b", 40)+rep(" ", 20)), false, isJunk)
+ assertEqual(t, sm.bJunk, map[string]struct{}{" ": struct{}{}})
+
+ isJunk = func(s string) bool {
+ return s == " " || s == "b"
+ }
+ sm = NewMatcherWithJunk(splitChars(rep("a", 40)+rep("b", 40)),
+ splitChars(rep("a", 44)+rep("b", 40)+rep(" ", 20)), false, isJunk)
+ assertEqual(t, sm.bJunk, map[string]struct{}{" ": struct{}{}, "b": struct{}{}})
+}
+
+func TestSFBugsRatioForNullSeqn(t *testing.T) {
+ sm := NewMatcher(nil, nil)
+ assertEqual(t, sm.Ratio(), 1.0)
+ assertEqual(t, sm.QuickRatio(), 1.0)
+ assertEqual(t, sm.RealQuickRatio(), 1.0)
+}
+
+func TestSFBugsComparingEmptyLists(t *testing.T) {
+ groups := NewMatcher(nil, nil).GetGroupedOpCodes(-1)
+ assertEqual(t, len(groups), 0)
+ diff := UnifiedDiff{
+ FromFile: "Original",
+ ToFile: "Current",
+ Context: 3,
+ }
+ result, err := GetUnifiedDiffString(diff)
+ assertEqual(t, err, nil)
+ assertEqual(t, result, "")
+}
+
+func TestOutputFormatRangeFormatUnified(t *testing.T) {
+ // Per the diff spec at http://www.unix.org/single_unix_specification/
+ //
+ // Each <range> field shall be of the form:
+ // %1d", <beginning line number> if the range contains exactly one line,
+ // and:
+ // "%1d,%1d", <beginning line number>, <number of lines> otherwise.
+ // If a range is empty, its beginning line number shall be the number of
+ // the line just before the range, or 0 if the empty range starts the file.
+ fm := formatRangeUnified
+ assertEqual(t, fm(3, 3), "3,0")
+ assertEqual(t, fm(3, 4), "4")
+ assertEqual(t, fm(3, 5), "4,2")
+ assertEqual(t, fm(3, 6), "4,3")
+ assertEqual(t, fm(0, 0), "0,0")
+}
+
+func TestOutputFormatRangeFormatContext(t *testing.T) {
+ // Per the diff spec at http://www.unix.org/single_unix_specification/
+ //
+ // The range of lines in file1 shall be written in the following format
+ // if the range contains two or more lines:
+ // "*** %d,%d ****\n", <beginning line number>, <ending line number>
+ // and the following format otherwise:
+ // "*** %d ****\n", <ending line number>
+ // The ending line number of an empty range shall be the number of the preceding line,
+ // or 0 if the range is at the start of the file.
+ //
+ // Next, the range of lines in file2 shall be written in the following format
+ // if the range contains two or more lines:
+ // "--- %d,%d ----\n", <beginning line number>, <ending line number>
+ // and the following format otherwise:
+ // "--- %d ----\n", <ending line number>
+ fm := formatRangeContext
+ assertEqual(t, fm(3, 3), "3")
+ assertEqual(t, fm(3, 4), "4")
+ assertEqual(t, fm(3, 5), "4,5")
+ assertEqual(t, fm(3, 6), "4,6")
+ assertEqual(t, fm(0, 0), "0")
+}
+
+func TestOutputFormatTabDelimiter(t *testing.T) {
+ diff := UnifiedDiff{
+ A: splitChars("one"),
+ B: splitChars("two"),
+ FromFile: "Original",
+ FromDate: "2005-01-26 23:30:50",
+ ToFile: "Current",
+ ToDate: "2010-04-12 10:20:52",
+ Eol: "\n",
+ }
+ ud, err := GetUnifiedDiffString(diff)
+ assertEqual(t, err, nil)
+ assertEqual(t, SplitLines(ud)[:2], []string{
+ "--- Original\t2005-01-26 23:30:50\n",
+ "+++ Current\t2010-04-12 10:20:52\n",
+ })
+ cd, err := GetContextDiffString(ContextDiff(diff))
+ assertEqual(t, err, nil)
+ assertEqual(t, SplitLines(cd)[:2], []string{
+ "*** Original\t2005-01-26 23:30:50\n",
+ "--- Current\t2010-04-12 10:20:52\n",
+ })
+}
+
+func TestOutputFormatNoTrailingTabOnEmptyFiledate(t *testing.T) {
+ diff := UnifiedDiff{
+ A: splitChars("one"),
+ B: splitChars("two"),
+ FromFile: "Original",
+ ToFile: "Current",
+ Eol: "\n",
+ }
+ ud, err := GetUnifiedDiffString(diff)
+ assertEqual(t, err, nil)
+ assertEqual(t, SplitLines(ud)[:2], []string{"--- Original\n", "+++ Current\n"})
+
+ cd, err := GetContextDiffString(ContextDiff(diff))
+ assertEqual(t, err, nil)
+ assertEqual(t, SplitLines(cd)[:2], []string{"*** Original\n", "--- Current\n"})
+}
+
+func TestSplitLines(t *testing.T) {
+ allTests := []struct {
+ input string
+ want []string
+ }{
+ {"foo", []string{"foo\n"}},
+ {"foo\nbar", []string{"foo\n", "bar\n"}},
+ {"foo\nbar\n", []string{"foo\n", "bar\n", "\n"}},
+ }
+ for _, test := range allTests {
+ assertEqual(t, SplitLines(test.input), test.want)
+ }
+}
+
+func benchmarkSplitLines(b *testing.B, count int) {
+ str := strings.Repeat("foo\n", count)
+
+ b.ResetTimer()
+
+ n := 0
+ for i := 0; i < b.N; i++ {
+ n += len(SplitLines(str))
+ }
+}
+
+func BenchmarkSplitLines100(b *testing.B) {
+ benchmarkSplitLines(b, 100)
+}
+
+func BenchmarkSplitLines10000(b *testing.B) {
+ benchmarkSplitLines(b, 10000)
+}
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/corrupt/huge_tag_exif.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/corrupt/huge_tag_exif.jpg
new file mode 100644
index 000000000..ffb31743d
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/corrupt/huge_tag_exif.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/corrupt/infinite_loop_exif.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/corrupt/infinite_loop_exif.jpg
new file mode 100644
index 000000000..6b0994713
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/corrupt/infinite_loop_exif.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/corrupt/max_uint32_exif.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/corrupt/max_uint32_exif.jpg
new file mode 100644
index 000000000..2a51b0ba0
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/corrupt/max_uint32_exif.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/sample1.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/sample1.jpg
new file mode 100644
index 000000000..87bcf8e33
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/sample1.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2004-01-11-22-45-15-sep-2004-01-11-22-45-15a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2004-01-11-22-45-15-sep-2004-01-11-22-45-15a.jpg
new file mode 100644
index 000000000..6f3be2480
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2004-01-11-22-45-15-sep-2004-01-11-22-45-15a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2006-08-03-16-29-38-sep-2006-08-03-16-29-38a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2006-08-03-16-29-38-sep-2006-08-03-16-29-38a.jpg
new file mode 100644
index 000000000..39891df84
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2006-08-03-16-29-38-sep-2006-08-03-16-29-38a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2006-11-11-19-17-56-sep-2006-11-11-19-17-56a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2006-11-11-19-17-56-sep-2006-11-11-19-17-56a.jpg
new file mode 100644
index 000000000..4721e7542
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2006-11-11-19-17-56-sep-2006-11-11-19-17-56a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2006-12-10-23-58-20-sep-2006-12-10-23-58-20a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2006-12-10-23-58-20-sep-2006-12-10-23-58-20a.jpg
new file mode 100644
index 000000000..8c0997ea0
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2006-12-10-23-58-20-sep-2006-12-10-23-58-20a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2006-12-17-07-09-14-sep-2006-12-17-07-09-14a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2006-12-17-07-09-14-sep-2006-12-17-07-09-14a.jpg
new file mode 100644
index 000000000..1c6e7601d
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2006-12-17-07-09-14-sep-2006-12-17-07-09-14a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2006-12-21-15-55-26-sep-2006-12-21-15-55-26a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2006-12-21-15-55-26-sep-2006-12-21-15-55-26a.jpg
new file mode 100644
index 000000000..8aaf632be
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2006-12-21-15-55-26-sep-2006-12-21-15-55-26a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-01-01-12-00-00-sep-2007-01-01-12-00-00a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-01-01-12-00-00-sep-2007-01-01-12-00-00a.jpg
new file mode 100644
index 000000000..c44db32c1
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-01-01-12-00-00-sep-2007-01-01-12-00-00a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-01-17-21-49-44-sep-2007-01-17-21-49-44a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-01-17-21-49-44-sep-2007-01-17-21-49-44a.jpg
new file mode 100644
index 000000000..f025460d6
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-01-17-21-49-44-sep-2007-01-17-21-49-44a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-02-02-18-13-29-sep-2007-02-02-18-13-29a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-02-02-18-13-29-sep-2007-02-02-18-13-29a.jpg
new file mode 100644
index 000000000..3f1fbfbdf
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-02-02-18-13-29-sep-2007-02-02-18-13-29a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-05-02-17-02-21-sep-2007-05-02-17-02-21a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-05-02-17-02-21-sep-2007-05-02-17-02-21a.jpg
new file mode 100644
index 000000000..351935778
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-05-02-17-02-21-sep-2007-05-02-17-02-21a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-05-12-08-19-07-sep-2007-05-12-08-19-07a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-05-12-08-19-07-sep-2007-05-12-08-19-07a.jpg
new file mode 100644
index 000000000..175b60663
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-05-12-08-19-07-sep-2007-05-12-08-19-07a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-05-26-04-49-45-sep-2007-05-26-04-49-45a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-05-26-04-49-45-sep-2007-05-26-04-49-45a.jpg
new file mode 100644
index 000000000..90a6c92b0
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-05-26-04-49-45-sep-2007-05-26-04-49-45a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-05-30-14-28-01-sep-2007-05-30-14-28-01a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-05-30-14-28-01-sep-2007-05-30-14-28-01a.jpg
new file mode 100644
index 000000000..74f30c351
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-05-30-14-28-01-sep-2007-05-30-14-28-01a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-06-06-16-15-25-sep-2007-06-06-16-15-25a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-06-06-16-15-25-sep-2007-06-06-16-15-25a.jpg
new file mode 100644
index 000000000..0a025a0b8
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-06-06-16-15-25-sep-2007-06-06-16-15-25a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-06-26-10-13-04-sep-2007-06-26-10-13-04a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-06-26-10-13-04-sep-2007-06-26-10-13-04a.jpg
new file mode 100644
index 000000000..526cefafd
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-06-26-10-13-04-sep-2007-06-26-10-13-04a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-07-13-17-02-30-sep-2007-07-13-17-02-30a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-07-13-17-02-30-sep-2007-07-13-17-02-30a.jpg
new file mode 100644
index 000000000..c39e90fca
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-07-13-17-02-30-sep-2007-07-13-17-02-30a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-08-15-14-42-46-sep-2007-08-15-14-42-46a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-08-15-14-42-46-sep-2007-08-15-14-42-46a.jpg
new file mode 100644
index 000000000..81be2a200
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-08-15-14-42-46-sep-2007-08-15-14-42-46a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-08-24-02-40-42-sep-2007-08-24-02-40-42a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-08-24-02-40-42-sep-2007-08-24-02-40-42a.jpg
new file mode 100644
index 000000000..aa457643d
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-08-24-02-40-42-sep-2007-08-24-02-40-42a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-11-07-11-40-44-sep-2007-11-07-11-40-44a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-11-07-11-40-44-sep-2007-11-07-11-40-44a.jpg
new file mode 100644
index 000000000..916a2b6c3
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2007-11-07-11-40-44-sep-2007-11-07-11-40-44a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2008-06-02-10-03-57-sep-2008-06-02-10-03-57a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2008-06-02-10-03-57-sep-2008-06-02-10-03-57a.jpg
new file mode 100644
index 000000000..0aedf3003
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2008-06-02-10-03-57-sep-2008-06-02-10-03-57a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2008-06-06-13-29-29-sep-2008-06-06-13-29-29a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2008-06-06-13-29-29-sep-2008-06-06-13-29-29a.jpg
new file mode 100644
index 000000000..a291900e3
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2008-06-06-13-29-29-sep-2008-06-06-13-29-29a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2008-06-17-01-21-30-sep-2008-06-17-01-21-30a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2008-06-17-01-21-30-sep-2008-06-17-01-21-30a.jpg
new file mode 100644
index 000000000..805d1d0f0
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2008-06-17-01-21-30-sep-2008-06-17-01-21-30a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2008-09-02-17-43-48-sep-2008-09-02-17-43-48a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2008-09-02-17-43-48-sep-2008-09-02-17-43-48a.jpg
new file mode 100644
index 000000000..c866423c7
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2008-09-02-17-43-48-sep-2008-09-02-17-43-48a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2009-03-26-09-23-20-sep-2009-03-26-09-23-20a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2009-03-26-09-23-20-sep-2009-03-26-09-23-20a.jpg
new file mode 100644
index 000000000..761bf6488
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2009-03-26-09-23-20-sep-2009-03-26-09-23-20a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2009-04-11-03-01-38-sep-2009-04-11-03-01-38a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2009-04-11-03-01-38-sep-2009-04-11-03-01-38a.jpg
new file mode 100644
index 000000000..484fe3759
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2009-04-11-03-01-38-sep-2009-04-11-03-01-38a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2009-04-23-07-21-35-sep-2009-04-23-07-21-35a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2009-04-23-07-21-35-sep-2009-04-23-07-21-35a.jpg
new file mode 100644
index 000000000..f39db7d9a
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2009-04-23-07-21-35-sep-2009-04-23-07-21-35a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2009-06-11-19-23-18-sep-2009-06-11-19-23-18a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2009-06-11-19-23-18-sep-2009-06-11-19-23-18a.jpg
new file mode 100644
index 000000000..599764bf8
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2009-06-11-19-23-18-sep-2009-06-11-19-23-18a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2009-06-20-07-59-05-sep-2009-06-20-07-59-05a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2009-06-20-07-59-05-sep-2009-06-20-07-59-05a.jpg
new file mode 100644
index 000000000..8718269e9
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2009-06-20-07-59-05-sep-2009-06-20-07-59-05a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2009-08-05-08-11-31-sep-2009-08-05-08-11-31a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2009-08-05-08-11-31-sep-2009-08-05-08-11-31a.jpg
new file mode 100644
index 000000000..9598b2136
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2009-08-05-08-11-31-sep-2009-08-05-08-11-31a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2010-06-08-04-44-24-sep-2010-06-08-04-44-24a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2010-06-08-04-44-24-sep-2010-06-08-04-44-24a.jpg
new file mode 100644
index 000000000..33f7d9b20
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2010-06-08-04-44-24-sep-2010-06-08-04-44-24a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2010-06-20-20-07-39-sep-2010-06-20-20-07-39a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2010-06-20-20-07-39-sep-2010-06-20-20-07-39a.jpg
new file mode 100644
index 000000000..ec2faa1a9
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2010-06-20-20-07-39-sep-2010-06-20-20-07-39a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2010-09-02-08-43-02-sep-2010-09-02-08-43-02a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2010-09-02-08-43-02-sep-2010-09-02-08-43-02a.jpg
new file mode 100644
index 000000000..3b7f906db
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2010-09-02-08-43-02-sep-2010-09-02-08-43-02a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-01-24-22-06-02-sep-2011-01-24-22-06-02a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-01-24-22-06-02-sep-2011-01-24-22-06-02a.jpg
new file mode 100644
index 000000000..1a4af42d3
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-01-24-22-06-02-sep-2011-01-24-22-06-02a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-03-07-09-28-03-sep-2011-03-07-09-28-03a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-03-07-09-28-03-sep-2011-03-07-09-28-03a.jpg
new file mode 100644
index 000000000..42d347656
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-03-07-09-28-03-sep-2011-03-07-09-28-03a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-05-07-13-02-49-sep-2011-05-07-13-02-49a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-05-07-13-02-49-sep-2011-05-07-13-02-49a.jpg
new file mode 100644
index 000000000..7e84ec481
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-05-07-13-02-49-sep-2011-05-07-13-02-49a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-08-07-19-22-57-sep-2011-08-07-19-22-57a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-08-07-19-22-57-sep-2011-08-07-19-22-57a.jpg
new file mode 100644
index 000000000..16fad2ecb
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-08-07-19-22-57-sep-2011-08-07-19-22-57a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-10-28-17-50-18-sep-2011-10-28-17-50-18a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-10-28-17-50-18-sep-2011-10-28-17-50-18a.jpg
new file mode 100644
index 000000000..f6020a8c9
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-10-28-17-50-18-sep-2011-10-28-17-50-18a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-10-28-18-25-43-sep-2011-10-28-18-25-43.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-10-28-18-25-43-sep-2011-10-28-18-25-43.jpg
new file mode 100644
index 000000000..3aa541878
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-10-28-18-25-43-sep-2011-10-28-18-25-43.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-11-18-15-38-34-sep-Photo11181538.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-11-18-15-38-34-sep-Photo11181538.jpg
new file mode 100644
index 000000000..48ef933a2
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2011-11-18-15-38-34-sep-Photo11181538.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2012-06-02-10-12-28-sep-2012-06-02-10-12-28.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2012-06-02-10-12-28-sep-2012-06-02-10-12-28.jpg
new file mode 100644
index 000000000..f83270eee
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2012-06-02-10-12-28-sep-2012-06-02-10-12-28.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2012-09-21-22-07-34-sep-2012-09-21-22-07-34.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2012-09-21-22-07-34-sep-2012-09-21-22-07-34.jpg
new file mode 100644
index 000000000..5cdb55aac
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2012-09-21-22-07-34-sep-2012-09-21-22-07-34.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2012-12-19-21-38-40-sep-temple_square1.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2012-12-19-21-38-40-sep-temple_square1.jpg
new file mode 100644
index 000000000..4cc074f8e
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2012-12-19-21-38-40-sep-temple_square1.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2012-12-21-11-15-19-sep-IMG_0001.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2012-12-21-11-15-19-sep-IMG_0001.jpg
new file mode 100644
index 000000000..ba23c3c42
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2012-12-21-11-15-19-sep-IMG_0001.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2013-02-05-23-12-09-sep-DSCI0001.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2013-02-05-23-12-09-sep-DSCI0001.jpg
new file mode 100644
index 000000000..0396148af
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2013-02-05-23-12-09-sep-DSCI0001.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2099-08-12-19-59-29-sep-2099-08-12-19-59-29a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2099-08-12-19-59-29-sep-2099-08-12-19-59-29a.jpg
new file mode 100644
index 000000000..9729182b3
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2099-08-12-19-59-29-sep-2099-08-12-19-59-29a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2216-11-15-11-46-51-sep-2216-11-15-11-46-51a.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2216-11-15-11-46-51-sep-2216-11-15-11-46-51a.jpg
new file mode 100644
index 000000000..ae53a397a
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/2216-11-15-11-46-51-sep-2216-11-15-11-46-51a.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/FailedHash-NoDate-sep-remembory.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/FailedHash-NoDate-sep-remembory.jpg
new file mode 100644
index 000000000..9fb415124
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/FailedHash-NoDate-sep-remembory.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f1-exif.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f1-exif.jpg
new file mode 100644
index 000000000..ff003e394
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f1-exif.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f2-exif.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f2-exif.jpg
new file mode 100644
index 000000000..7e0f170e3
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f2-exif.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f3-exif.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f3-exif.jpg
new file mode 100644
index 000000000..3ed7b16a7
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f3-exif.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f4-exif.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f4-exif.jpg
new file mode 100644
index 000000000..0e081f919
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f4-exif.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f5-exif.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f5-exif.jpg
new file mode 100644
index 000000000..e8d875479
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f5-exif.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f6-exif.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f6-exif.jpg
new file mode 100644
index 000000000..4e2c86415
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f6-exif.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f7-exif.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f7-exif.jpg
new file mode 100644
index 000000000..b5dddea44
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f7-exif.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f8-exif.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f8-exif.jpg
new file mode 100644
index 000000000..fb050fc6d
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/f8-exif.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/geodegrees_as_string.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/geodegrees_as_string.jpg
new file mode 100644
index 000000000..280a70ec4
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/geodegrees_as_string.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/has-lens-info.jpg b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/has-lens-info.jpg
new file mode 100644
index 000000000..57757da33
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/exif/samples/has-lens-info.jpg
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/rwcarlsen/goexif/tiff/sample1.tif b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/tiff/sample1.tif
new file mode 100644
index 000000000..fe51399c5
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/rwcarlsen/goexif/tiff/sample1.tif
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/value.go b/Godeps/_workspace/src/github.com/stretchr/objx/value.go
index 7aaef06b1..956a2211d 100644
--- a/Godeps/_workspace/src/github.com/stretchr/objx/value.go
+++ b/Godeps/_workspace/src/github.com/stretchr/objx/value.go
@@ -1,5 +1,10 @@
package objx
+import (
+ "fmt"
+ "strconv"
+)
+
// Value provides methods for extracting interface{} data in various
// types.
type Value struct {
@@ -11,3 +16,41 @@ type Value struct {
func (v *Value) Data() interface{} {
return v.data
}
+
+// String returns the value always as a string
+func (v *Value) String() string {
+ switch {
+ case v.IsStr():
+ return v.Str()
+ case v.IsBool():
+ return strconv.FormatBool(v.Bool())
+ case v.IsFloat32():
+ return strconv.FormatFloat(float64(v.Float32()), 'f', -1, 32)
+ case v.IsFloat64():
+ return strconv.FormatFloat(v.Float64(), 'f', -1, 64)
+ case v.IsInt():
+ return strconv.FormatInt(int64(v.Int()), 10)
+ case v.IsInt():
+ return strconv.FormatInt(int64(v.Int()), 10)
+ case v.IsInt8():
+ return strconv.FormatInt(int64(v.Int8()), 10)
+ case v.IsInt16():
+ return strconv.FormatInt(int64(v.Int16()), 10)
+ case v.IsInt32():
+ return strconv.FormatInt(int64(v.Int32()), 10)
+ case v.IsInt64():
+ return strconv.FormatInt(v.Int64(), 10)
+ case v.IsUint():
+ return strconv.FormatUint(uint64(v.Uint()), 10)
+ case v.IsUint8():
+ return strconv.FormatUint(uint64(v.Uint8()), 10)
+ case v.IsUint16():
+ return strconv.FormatUint(uint64(v.Uint16()), 10)
+ case v.IsUint32():
+ return strconv.FormatUint(uint64(v.Uint32()), 10)
+ case v.IsUint64():
+ return strconv.FormatUint(v.Uint64(), 10)
+ }
+
+ return fmt.Sprintf("%#v", v.Data())
+}
diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/value_test.go b/Godeps/_workspace/src/github.com/stretchr/objx/value_test.go
index 0bc65d92c..521405801 100644
--- a/Godeps/_workspace/src/github.com/stretchr/objx/value_test.go
+++ b/Godeps/_workspace/src/github.com/stretchr/objx/value_test.go
@@ -1 +1,66 @@
package objx
+
+import (
+ "github.com/stretchr/testify/assert"
+ "testing"
+)
+
+func TestStringTypeString(t *testing.T) {
+ m := New(map[string]interface{}{"string": "foo"})
+ assert.Equal(t, "foo", m.Get("string").String())
+}
+
+func TestStringTypeBool(t *testing.T) {
+ m := New(map[string]interface{}{"bool": true})
+ assert.Equal(t, "true", m.Get("bool").String())
+}
+
+func TestStringTypeInt(t *testing.T) {
+ m := New(map[string]interface{}{
+ "int": int(1),
+ "int8": int8(8),
+ "int16": int16(16),
+ "int32": int32(32),
+ "int64": int64(64),
+ })
+
+ assert.Equal(t, "1", m.Get("int").String())
+ assert.Equal(t, "8", m.Get("int8").String())
+ assert.Equal(t, "16", m.Get("int16").String())
+ assert.Equal(t, "32", m.Get("int32").String())
+ assert.Equal(t, "64", m.Get("int64").String())
+}
+
+func TestStringTypeUint(t *testing.T) {
+ m := New(map[string]interface{}{
+ "uint": uint(1),
+ "uint8": uint8(8),
+ "uint16": uint16(16),
+ "uint32": uint32(32),
+ "uint64": uint64(64),
+ })
+
+ assert.Equal(t, "1", m.Get("uint").String())
+ assert.Equal(t, "8", m.Get("uint8").String())
+ assert.Equal(t, "16", m.Get("uint16").String())
+ assert.Equal(t, "32", m.Get("uint32").String())
+ assert.Equal(t, "64", m.Get("uint64").String())
+}
+
+func TestStringTypeFloat(t *testing.T) {
+ m := New(map[string]interface{}{
+ "float32": float32(32.32),
+ "float64": float64(64.64),
+ })
+
+ assert.Equal(t, "32.32", m.Get("float32").String())
+ assert.Equal(t, "64.64", m.Get("float64").String())
+}
+
+func TestStringTypeOther(t *testing.T) {
+ m := New(map[string]interface{}{
+ "other": []string{"foo", "bar"},
+ })
+
+ assert.Equal(t, "[]string{\"foo\", \"bar\"}", m.Get("other").String())
+}
diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions.go b/Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions.go
index 818cd7b0e..1935d18da 100644
--- a/Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions.go
+++ b/Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions.go
@@ -3,6 +3,7 @@ package assert
import (
"bufio"
"bytes"
+ "encoding/json"
"fmt"
"math"
"reflect"
@@ -10,6 +11,11 @@ import (
"runtime"
"strings"
"time"
+ "unicode"
+ "unicode/utf8"
+
+ "github.com/davecgh/go-spew/spew"
+ "github.com/pmezard/go-difflib/difflib"
)
// TestingT is an interface wrapper around *testing.T
@@ -33,11 +39,7 @@ func ObjectsAreEqual(expected, actual interface{}) bool {
return expected == actual
}
- if reflect.DeepEqual(expected, actual) {
- return true
- }
-
- return false
+ return reflect.DeepEqual(expected, actual)
}
@@ -49,12 +51,13 @@ func ObjectsAreEqualValues(expected, actual interface{}) bool {
}
actualType := reflect.TypeOf(actual)
+ if actualType == nil {
+ return false
+ }
expectedValue := reflect.ValueOf(expected)
- if expectedValue.Type().ConvertibleTo(actualType) {
+ if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) {
// Attempt comparison after type conversion
- if reflect.DeepEqual(actual, expectedValue.Convert(actualType).Interface()) {
- return true
- }
+ return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual)
}
return false
@@ -64,28 +67,67 @@ func ObjectsAreEqualValues(expected, actual interface{}) bool {
internally, causing it to print the file:line of the assert method, rather than where
the problem actually occured in calling code.*/
-// CallerInfo returns a string containing the file and line number of the assert call
-// that failed.
-func CallerInfo() string {
+// CallerInfo returns an array of strings containing the file and line number
+// of each stack frame leading from the current test to the assert call that
+// failed.
+func CallerInfo() []string {
+ pc := uintptr(0)
file := ""
line := 0
ok := false
+ name := ""
+ callers := []string{}
for i := 0; ; i++ {
- _, file, line, ok = runtime.Caller(i)
+ pc, file, line, ok = runtime.Caller(i)
if !ok {
- return ""
+ return nil
}
+
+ // This is a huge edge case, but it will panic if this is the case, see #180
+ if file == "<autogenerated>" {
+ break
+ }
+
parts := strings.Split(file, "/")
dir := parts[len(parts)-2]
file = parts[len(parts)-1]
if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" {
+ callers = append(callers, fmt.Sprintf("%s:%d", file, line))
+ }
+
+ f := runtime.FuncForPC(pc)
+ if f == nil {
+ break
+ }
+ name = f.Name()
+ // Drop the package
+ segments := strings.Split(name, ".")
+ name = segments[len(segments)-1]
+ if isTest(name, "Test") ||
+ isTest(name, "Benchmark") ||
+ isTest(name, "Example") {
break
}
}
- return fmt.Sprintf("%s:%d", file, line)
+ return callers
+}
+
+// Stolen from the `go test` tool.
+// isTest tells whether name looks like a test (or benchmark, according to prefix).
+// It is a Test (say) if there is a character after Test that is not a lower-case letter.
+// We don't want TesticularCancer.
+func isTest(name, prefix string) bool {
+ if !strings.HasPrefix(name, prefix) {
+ return false
+ }
+ if len(name) == len(prefix) { // "Test" is ok
+ return true
+ }
+ rune, _ := utf8.DecodeRuneInString(name[len(prefix):])
+ return !unicode.IsLower(rune)
}
// getWhitespaceString returns a string that is long enough to overwrite the default
@@ -144,19 +186,20 @@ func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
message := messageFromMsgAndArgs(msgAndArgs...)
+ errorTrace := strings.Join(CallerInfo(), "\n\r\t\t\t")
if len(message) > 0 {
- t.Errorf("\r%s\r\tLocation:\t%s\n"+
+ t.Errorf("\r%s\r\tError Trace:\t%s\n"+
"\r\tError:%s\n"+
"\r\tMessages:\t%s\n\r",
getWhitespaceString(),
- CallerInfo(),
+ errorTrace,
indentMessageLines(failureMessage, 2),
message)
} else {
- t.Errorf("\r%s\r\tLocation:\t%s\n"+
+ t.Errorf("\r%s\r\tError Trace:\t%s\n"+
"\r\tError:%s\n\r",
getWhitespaceString(),
- CallerInfo(),
+ errorTrace,
indentMessageLines(failureMessage, 2))
}
@@ -171,7 +214,7 @@ func Implements(t TestingT, interfaceObject interface{}, object interface{}, msg
interfaceType := reflect.TypeOf(interfaceObject).Elem()
if !reflect.TypeOf(object).Implements(interfaceType) {
- return Fail(t, fmt.Sprintf("Object must implement %v", interfaceType), msgAndArgs...)
+ return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...)
}
return true
@@ -196,8 +239,9 @@ func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs
func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
if !ObjectsAreEqual(expected, actual) {
+ diff := diff(expected, actual)
return Fail(t, fmt.Sprintf("Not equal: %#v (expected)\n"+
- " != %#v (actual)", expected, actual), msgAndArgs...)
+ " != %#v (actual)%s", expected, actual, diff), msgAndArgs...)
}
return true
@@ -232,7 +276,7 @@ func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}
bType := reflect.TypeOf(actual)
if aType != bType {
- return Fail(t, "Types expected to match exactly", "%v != %v", aType, bType)
+ return Fail(t, fmt.Sprintf("Types expected to match exactly\n\r\t%v != %v", aType, bType), msgAndArgs...)
}
return Equal(t, expected, actual, msgAndArgs...)
@@ -245,24 +289,10 @@ func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}
//
// Returns whether the assertion was successful (true) or not (false).
func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
-
- success := true
-
- if object == nil {
- success = false
- } else {
- value := reflect.ValueOf(object)
- kind := value.Kind()
- if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() {
- success = false
- }
- }
-
- if !success {
- Fail(t, "Expected not to be nil.", msgAndArgs...)
+ if !isNil(object) {
+ return true
}
-
- return success
+ return Fail(t, "Expected value not to be nil.", msgAndArgs...)
}
// isNil checks if a specified object is nil or not, without Failing.
@@ -292,7 +322,7 @@ func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...)
}
-var zeros = []interface{}{
+var numericZeros = []interface{}{
int(0),
int8(0),
int16(0),
@@ -318,7 +348,7 @@ func isEmpty(object interface{}) bool {
return true
}
- for _, v := range zeros {
+ for _, v := range numericZeros {
if object == v {
return true
}
@@ -335,6 +365,9 @@ func isEmpty(object interface{}) bool {
}
case reflect.Ptr:
{
+ if objValue.IsNil() {
+ return true
+ }
switch object.(type) {
case *time.Time:
return object.(*time.Time).IsZero()
@@ -349,7 +382,7 @@ func isEmpty(object interface{}) bool {
// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either
// a slice or a channel with len == 0.
//
-// assert.Empty(t, obj)
+// assert.Empty(t, obj)
//
// Returns whether the assertion was successful (true) or not (false).
func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
@@ -366,9 +399,9 @@ func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
// a slice or a channel with len == 0.
//
-// if assert.NotEmpty(t, obj) {
-// assert.Equal(t, "two", obj[1])
-// }
+// if assert.NotEmpty(t, obj) {
+// assert.Equal(t, "two", obj[1])
+// }
//
// Returns whether the assertion was successful (true) or not (false).
func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
@@ -450,7 +483,7 @@ func False(t TestingT, value bool, msgAndArgs ...interface{}) bool {
func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
if ObjectsAreEqual(expected, actual) {
- return Fail(t, "Should not be equal", msgAndArgs...)
+ return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
}
return true
@@ -476,6 +509,16 @@ func includeElement(list interface{}, element interface{}) (ok, found bool) {
return true, strings.Contains(listValue.String(), elementValue.String())
}
+ if reflect.TypeOf(list).Kind() == reflect.Map {
+ mapKeys := listValue.MapKeys()
+ for i := 0; i < len(mapKeys); i++ {
+ if ObjectsAreEqual(mapKeys[i].Interface(), element) {
+ return true, true
+ }
+ }
+ return true, false
+ }
+
for i := 0; i < listValue.Len(); i++ {
if ObjectsAreEqual(listValue.Index(i).Interface(), element) {
return true, true
@@ -485,11 +528,12 @@ func includeElement(list interface{}, element interface{}) (ok, found bool) {
}
-// Contains asserts that the specified string or list(array, slice...) contains the
+// Contains asserts that the specified string, list(array, slice...) or map contains the
// specified substring or element.
//
// assert.Contains(t, "Hello World", "World", "But 'Hello World' does contain 'World'")
// assert.Contains(t, ["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'")
+// assert.Contains(t, {"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'")
//
// Returns whether the assertion was successful (true) or not (false).
func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
@@ -506,11 +550,12 @@ func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bo
}
-// NotContains asserts that the specified string or list(array, slice...) does NOT contain the
+// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the
// specified substring or element.
//
// assert.NotContains(t, "Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'")
// assert.NotContains(t, ["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'")
+// assert.NotContains(t, {"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'")
//
// Returns whether the assertion was successful (true) or not (false).
func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
@@ -766,7 +811,7 @@ func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool {
return true
}
- return Fail(t, fmt.Sprintf("No error is expected but got %v", err), msgAndArgs...)
+ return Fail(t, fmt.Sprintf("Received unexpected error %q", err), msgAndArgs...)
}
// Error asserts that a function returned an error (i.e. not `nil`).
@@ -800,7 +845,7 @@ func EqualError(t TestingT, theError error, errString string, msgAndArgs ...inte
return false
}
s := "An error with value \"%s\" is expected but got \"%s\". %s"
- return Equal(t, theError.Error(), errString,
+ return Equal(t, errString, theError.Error(),
s, errString, theError.Error(), message)
}
@@ -851,3 +896,84 @@ func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interf
return !match
}
+
+// Zero asserts that i is the zero value for its type and returns the truth.
+func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
+ if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
+ return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...)
+ }
+ return true
+}
+
+// NotZero asserts that i is not the zero value for its type and returns the truth.
+func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
+ if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
+ return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...)
+ }
+ return true
+}
+
+// JSONEq asserts that two JSON strings are equivalent.
+//
+// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
+//
+// Returns whether the assertion was successful (true) or not (false).
+func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
+ var expectedJSONAsInterface, actualJSONAsInterface interface{}
+
+ if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil {
+ return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...)
+ }
+
+ if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil {
+ return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...)
+ }
+
+ return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...)
+}
+
+func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) {
+ t := reflect.TypeOf(v)
+ k := t.Kind()
+
+ if k == reflect.Ptr {
+ t = t.Elem()
+ k = t.Kind()
+ }
+ return t, k
+}
+
+// diff returns a diff of both values as long as both are of the same type and
+// are a struct, map, slice or array. Otherwise it returns an empty string.
+func diff(expected interface{}, actual interface{}) string {
+ if expected == nil || actual == nil {
+ return ""
+ }
+
+ et, ek := typeAndKind(expected)
+ at, _ := typeAndKind(actual)
+
+ if et != at {
+ return ""
+ }
+
+ if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array {
+ return ""
+ }
+
+ spew.Config.SortKeys = true
+ e := spew.Sdump(expected)
+ a := spew.Sdump(actual)
+
+ diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
+ A: difflib.SplitLines(e),
+ B: difflib.SplitLines(a),
+ FromFile: "Expected",
+ FromDate: "",
+ ToFile: "Actual",
+ ToDate: "",
+ Context: 1,
+ })
+
+ return "\n\nDiff:\n" + diff
+}
diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions_test.go b/Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions_test.go
index d859c77b9..a12352e4c 100644
--- a/Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions_test.go
+++ b/Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions_test.go
@@ -2,12 +2,82 @@ package assert
import (
"errors"
+ "io"
"math"
+ "os"
+ "reflect"
"regexp"
"testing"
"time"
)
+var (
+ i interface{}
+ zeros = []interface{}{
+ false,
+ byte(0),
+ complex64(0),
+ complex128(0),
+ float32(0),
+ float64(0),
+ int(0),
+ int8(0),
+ int16(0),
+ int32(0),
+ int64(0),
+ rune(0),
+ uint(0),
+ uint8(0),
+ uint16(0),
+ uint32(0),
+ uint64(0),
+ uintptr(0),
+ "",
+ [0]interface{}{},
+ []interface{}(nil),
+ struct{ x int }{},
+ (*interface{})(nil),
+ (func())(nil),
+ nil,
+ interface{}(nil),
+ map[interface{}]interface{}(nil),
+ (chan interface{})(nil),
+ (<-chan interface{})(nil),
+ (chan<- interface{})(nil),
+ }
+ nonZeros = []interface{}{
+ true,
+ byte(1),
+ complex64(1),
+ complex128(1),
+ float32(1),
+ float64(1),
+ int(1),
+ int8(1),
+ int16(1),
+ int32(1),
+ int64(1),
+ rune(1),
+ uint(1),
+ uint8(1),
+ uint16(1),
+ uint32(1),
+ uint64(1),
+ uintptr(1),
+ "s",
+ [1]interface{}{1},
+ []interface{}{},
+ struct{ x int }{1},
+ (*interface{})(&i),
+ (func())(func() {}),
+ interface{}(1),
+ map[interface{}]interface{}{},
+ (chan interface{})(make(chan interface{})),
+ (<-chan interface{})(make(chan interface{})),
+ (chan<- interface{})(make(chan interface{})),
+ }
+)
+
// AssertionTesterInterface defines an interface to be used for testing assertion methods
type AssertionTesterInterface interface {
TestMethod()
@@ -62,6 +132,12 @@ func TestObjectsAreEqual(t *testing.T) {
if !ObjectsAreEqualValues(uint32(10), int32(10)) {
t.Error("ObjectsAreEqualValues should return true")
}
+ if ObjectsAreEqualValues(0, nil) {
+ t.Fail()
+ }
+ if ObjectsAreEqualValues(nil, 0) {
+ t.Fail()
+ }
}
@@ -129,6 +205,9 @@ func TestNotNil(t *testing.T) {
if NotNil(mockT, nil) {
t.Error("NotNil should return false: object is nil")
}
+ if NotNil(mockT, (*struct{})(nil)) {
+ t.Error("NotNil should return false: object is (*struct{})(nil)")
+ }
}
@@ -139,6 +218,9 @@ func TestNil(t *testing.T) {
if !Nil(mockT, nil) {
t.Error("Nil should return true: object is nil")
}
+ if !Nil(mockT, (*struct{})(nil)) {
+ t.Error("Nil should return true: object is (*struct{})(nil)")
+ }
if Nil(mockT, new(AssertionTesterConformingObject)) {
t.Error("Nil should return false: object is not nil")
}
@@ -255,6 +337,7 @@ func TestContains(t *testing.T) {
{"g", "h"},
{"j", "k"},
}
+ simpleMap := map[interface{}]interface{}{"Foo": "Bar"}
if !Contains(mockT, "Hello World", "Hello") {
t.Error("Contains should return true: \"Hello World\" contains \"Hello\"")
@@ -275,12 +358,22 @@ func TestContains(t *testing.T) {
if Contains(mockT, complexList, &A{"g", "e"}) {
t.Error("Contains should return false: complexList contains {\"g\", \"e\"}")
}
+ if Contains(mockT, complexList, &A{"g", "e"}) {
+ t.Error("Contains should return false: complexList contains {\"g\", \"e\"}")
+ }
+ if !Contains(mockT, simpleMap, "Foo") {
+ t.Error("Contains should return true: \"{\"Foo\": \"Bar\"}\" contains \"Foo\"")
+ }
+ if Contains(mockT, simpleMap, "Bar") {
+ t.Error("Contains should return false: \"{\"Foo\": \"Bar\"}\" does not contains \"Bar\"")
+ }
}
func TestNotContains(t *testing.T) {
mockT := new(testing.T)
list := []string{"Foo", "Bar"}
+ simpleMap := map[interface{}]interface{}{"Foo": "Bar"}
if !NotContains(mockT, "Hello World", "Hello!") {
t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"")
@@ -295,13 +388,19 @@ func TestNotContains(t *testing.T) {
if NotContains(mockT, list, "Foo") {
t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"")
}
-
+ if NotContains(mockT, simpleMap, "Foo") {
+ t.Error("Contains should return true: \"{\"Foo\": \"Bar\"}\" contains \"Foo\"")
+ }
+ if !NotContains(mockT, simpleMap, "Bar") {
+ t.Error("Contains should return false: \"{\"Foo\": \"Bar\"}\" does not contains \"Bar\"")
+ }
}
func Test_includeElement(t *testing.T) {
list1 := []string{"Foo", "Bar"}
list2 := []int{1, 2}
+ simpleMap := map[interface{}]interface{}{"Foo": "Bar"}
ok, found := includeElement("Hello World", "World")
True(t, ok)
@@ -335,10 +434,17 @@ func Test_includeElement(t *testing.T) {
True(t, ok)
False(t, found)
+ ok, found = includeElement(simpleMap, "Foo")
+ True(t, ok)
+ True(t, found)
+
+ ok, found = includeElement(simpleMap, "Bar")
+ True(t, ok)
+ False(t, found)
+
ok, found = includeElement(1433, "1")
False(t, ok)
False(t, found)
-
}
func TestCondition(t *testing.T) {
@@ -481,6 +587,9 @@ func TestEmpty(t *testing.T) {
mockT := new(testing.T)
chWithValue := make(chan struct{}, 1)
chWithValue <- struct{}{}
+ var ti *time.Time
+ var s *string
+ var f *os.File
True(t, Empty(mockT, ""), "Empty string is empty")
True(t, Empty(mockT, nil), "Nil is empty")
@@ -488,6 +597,9 @@ func TestEmpty(t *testing.T) {
True(t, Empty(mockT, 0), "Zero int value is empty")
True(t, Empty(mockT, false), "False value is empty")
True(t, Empty(mockT, make(chan struct{})), "Channel without values is empty")
+ True(t, Empty(mockT, s), "Nil string pointer is empty")
+ True(t, Empty(mockT, f), "Nil os.File pointer is empty")
+ True(t, Empty(mockT, ti), "Nil time.Time pointer is empty")
False(t, Empty(mockT, "something"), "Non Empty string is not empty")
False(t, Empty(mockT, errors.New("something")), "Non nil object is not empty")
@@ -789,3 +901,189 @@ func TestRegexp(t *testing.T) {
True(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str))
}
}
+
+func testAutogeneratedFunction() {
+ defer func() {
+ if err := recover(); err == nil {
+ panic("did not panic")
+ }
+ CallerInfo()
+ }()
+ t := struct {
+ io.Closer
+ }{}
+ var c io.Closer
+ c = t
+ c.Close()
+}
+
+func TestCallerInfoWithAutogeneratedFunctions(t *testing.T) {
+ NotPanics(t, func() {
+ testAutogeneratedFunction()
+ })
+}
+
+func TestZero(t *testing.T) {
+ mockT := new(testing.T)
+
+ for _, test := range zeros {
+ True(t, Zero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
+ }
+
+ for _, test := range nonZeros {
+ False(t, Zero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
+ }
+}
+
+func TestNotZero(t *testing.T) {
+ mockT := new(testing.T)
+
+ for _, test := range zeros {
+ False(t, NotZero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
+ }
+
+ for _, test := range nonZeros {
+ True(t, NotZero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
+ }
+}
+
+func TestJSONEq_EqualSONString(t *testing.T) {
+ mockT := new(testing.T)
+ True(t, JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`))
+}
+
+func TestJSONEq_EquivalentButNotEqual(t *testing.T) {
+ mockT := new(testing.T)
+ True(t, JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`))
+}
+
+func TestJSONEq_HashOfArraysAndHashes(t *testing.T) {
+ mockT := new(testing.T)
+ True(t, JSONEq(mockT, "{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}",
+ "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}"))
+}
+
+func TestJSONEq_Array(t *testing.T) {
+ mockT := new(testing.T)
+ True(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`))
+}
+
+func TestJSONEq_HashAndArrayNotEquivalent(t *testing.T) {
+ mockT := new(testing.T)
+ False(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`))
+}
+
+func TestJSONEq_HashesNotEquivalent(t *testing.T) {
+ mockT := new(testing.T)
+ False(t, JSONEq(mockT, `{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`))
+}
+
+func TestJSONEq_ActualIsNotJSON(t *testing.T) {
+ mockT := new(testing.T)
+ False(t, JSONEq(mockT, `{"foo": "bar"}`, "Not JSON"))
+}
+
+func TestJSONEq_ExpectedIsNotJSON(t *testing.T) {
+ mockT := new(testing.T)
+ False(t, JSONEq(mockT, "Not JSON", `{"foo": "bar", "hello": "world"}`))
+}
+
+func TestJSONEq_ExpectedAndActualNotJSON(t *testing.T) {
+ mockT := new(testing.T)
+ False(t, JSONEq(mockT, "Not JSON", "Not JSON"))
+}
+
+func TestJSONEq_ArraysOfDifferentOrder(t *testing.T) {
+ mockT := new(testing.T)
+ False(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`))
+}
+
+func TestDiff(t *testing.T) {
+ expected := `
+
+Diff:
+--- Expected
++++ Actual
+@@ -1,3 +1,3 @@
+ (struct { foo string }) {
+- foo: (string) (len=5) "hello"
++ foo: (string) (len=3) "bar"
+ }
+`
+ actual := diff(
+ struct{ foo string }{"hello"},
+ struct{ foo string }{"bar"},
+ )
+ Equal(t, expected, actual)
+
+ expected = `
+
+Diff:
+--- Expected
++++ Actual
+@@ -2,5 +2,5 @@
+ (int) 1,
+- (int) 2,
+ (int) 3,
+- (int) 4
++ (int) 5,
++ (int) 7
+ }
+`
+ actual = diff(
+ []int{1, 2, 3, 4},
+ []int{1, 3, 5, 7},
+ )
+ Equal(t, expected, actual)
+
+ expected = `
+
+Diff:
+--- Expected
++++ Actual
+@@ -2,4 +2,4 @@
+ (int) 1,
+- (int) 2,
+- (int) 3
++ (int) 3,
++ (int) 5
+ }
+`
+ actual = diff(
+ []int{1, 2, 3, 4}[0:3],
+ []int{1, 3, 5, 7}[0:3],
+ )
+ Equal(t, expected, actual)
+
+ expected = `
+
+Diff:
+--- Expected
++++ Actual
+@@ -1,6 +1,6 @@
+ (map[string]int) (len=4) {
+- (string) (len=4) "four": (int) 4,
++ (string) (len=4) "five": (int) 5,
+ (string) (len=3) "one": (int) 1,
+- (string) (len=5) "three": (int) 3,
+- (string) (len=3) "two": (int) 2
++ (string) (len=5) "seven": (int) 7,
++ (string) (len=5) "three": (int) 3
+ }
+`
+
+ actual = diff(
+ map[string]int{"one": 1, "two": 2, "three": 3, "four": 4},
+ map[string]int{"one": 1, "three": 3, "five": 5, "seven": 7},
+ )
+ Equal(t, expected, actual)
+}
+
+func TestDiffEmptyCases(t *testing.T) {
+ Equal(t, "", diff(nil, nil))
+ Equal(t, "", diff(struct{ foo string }{}, nil))
+ Equal(t, "", diff(nil, struct{ foo string }{}))
+ Equal(t, "", diff(1, 2))
+ Equal(t, "", diff(1, 2))
+ Equal(t, "", diff([]int{1}, []bool{true}))
+}
diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/assert/doc.go b/Godeps/_workspace/src/github.com/stretchr/testify/assert/doc.go
index f67810628..c9dccc4d6 100644
--- a/Godeps/_workspace/src/github.com/stretchr/testify/assert/doc.go
+++ b/Godeps/_workspace/src/github.com/stretchr/testify/assert/doc.go
@@ -17,7 +17,7 @@
//
// }
//
-// if you assert many times, use the below:
+// if you assert many times, use the format below:
//
// import (
// "testing"
@@ -42,113 +42,4 @@
//
// Every assertion function also takes an optional string message as the final argument,
// allowing custom error messages to be appended to the message the assertion method outputs.
-//
-// Here is an overview of the assert functions:
-//
-// assert.Equal(t, expected, actual [, message [, format-args]])
-//
-// assert.EqualValues(t, expected, actual [, message [, format-args]])
-//
-// assert.NotEqual(t, notExpected, actual [, message [, format-args]])
-//
-// assert.True(t, actualBool [, message [, format-args]])
-//
-// assert.False(t, actualBool [, message [, format-args]])
-//
-// assert.Nil(t, actualObject [, message [, format-args]])
-//
-// assert.NotNil(t, actualObject [, message [, format-args]])
-//
-// assert.Empty(t, actualObject [, message [, format-args]])
-//
-// assert.NotEmpty(t, actualObject [, message [, format-args]])
-//
-// assert.Len(t, actualObject, expectedLength, [, message [, format-args]])
-//
-// assert.Error(t, errorObject [, message [, format-args]])
-//
-// assert.NoError(t, errorObject [, message [, format-args]])
-//
-// assert.EqualError(t, theError, errString [, message [, format-args]])
-//
-// assert.Implements(t, (*MyInterface)(nil), new(MyObject) [,message [, format-args]])
-//
-// assert.IsType(t, expectedObject, actualObject [, message [, format-args]])
-//
-// assert.Contains(t, stringOrSlice, substringOrElement [, message [, format-args]])
-//
-// assert.NotContains(t, stringOrSlice, substringOrElement [, message [, format-args]])
-//
-// assert.Panics(t, func(){
-//
-// // call code that should panic
-//
-// } [, message [, format-args]])
-//
-// assert.NotPanics(t, func(){
-//
-// // call code that should not panic
-//
-// } [, message [, format-args]])
-//
-// assert.WithinDuration(t, timeA, timeB, deltaTime, [, message [, format-args]])
-//
-// assert.InDelta(t, numA, numB, delta, [, message [, format-args]])
-//
-// assert.InEpsilon(t, numA, numB, epsilon, [, message [, format-args]])
-//
-// assert package contains Assertions object. it has assertion methods.
-//
-// Here is an overview of the assert functions:
-// assert.Equal(expected, actual [, message [, format-args]])
-//
-// assert.EqualValues(expected, actual [, message [, format-args]])
-//
-// assert.NotEqual(notExpected, actual [, message [, format-args]])
-//
-// assert.True(actualBool [, message [, format-args]])
-//
-// assert.False(actualBool [, message [, format-args]])
-//
-// assert.Nil(actualObject [, message [, format-args]])
-//
-// assert.NotNil(actualObject [, message [, format-args]])
-//
-// assert.Empty(actualObject [, message [, format-args]])
-//
-// assert.NotEmpty(actualObject [, message [, format-args]])
-//
-// assert.Len(actualObject, expectedLength, [, message [, format-args]])
-//
-// assert.Error(errorObject [, message [, format-args]])
-//
-// assert.NoError(errorObject [, message [, format-args]])
-//
-// assert.EqualError(theError, errString [, message [, format-args]])
-//
-// assert.Implements((*MyInterface)(nil), new(MyObject) [,message [, format-args]])
-//
-// assert.IsType(expectedObject, actualObject [, message [, format-args]])
-//
-// assert.Contains(stringOrSlice, substringOrElement [, message [, format-args]])
-//
-// assert.NotContains(stringOrSlice, substringOrElement [, message [, format-args]])
-//
-// assert.Panics(func(){
-//
-// // call code that should panic
-//
-// } [, message [, format-args]])
-//
-// assert.NotPanics(func(){
-//
-// // call code that should not panic
-//
-// } [, message [, format-args]])
-//
-// assert.WithinDuration(timeA, timeB, deltaTime, [, message [, format-args]])
-//
-// assert.InDelta(numA, numB, delta, [, message [, format-args]])
-//
-// assert.InEpsilon(numA, numB, epsilon, [, message [, format-args]])
package assert
diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions.go b/Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions.go
index d8d3f531e..cab3aa2ac 100644
--- a/Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions.go
+++ b/Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions.go
@@ -81,7 +81,7 @@ func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) bool {
// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or a
// slice with len == 0.
//
-// assert.Empty(obj)
+// assert.Empty(obj)
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) bool {
@@ -91,9 +91,9 @@ func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) bool {
// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or a
// slice with len == 0.
//
-// if assert.NotEmpty(obj) {
-// assert.Equal("two", obj[1])
-// }
+// if assert.NotEmpty(obj) {
+// assert.Equal("two", obj[1])
+// }
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) bool {
@@ -263,3 +263,22 @@ func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...inter
func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
return NotRegexp(a.t, rx, str, msgAndArgs...)
}
+
+// Zero asserts that i is the zero value for its type and returns the truth.
+func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) bool {
+ return Zero(a.t, i, msgAndArgs...)
+}
+
+// NotZero asserts that i is not the zero value for its type and returns the truth.
+func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) bool {
+ return NotZero(a.t, i, msgAndArgs...)
+}
+
+// JSONEq asserts that two JSON strings are equivalent.
+//
+// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) bool {
+ return JSONEq(a.t, expected, actual, msgAndArgs...)
+}
diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions_test.go b/Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions_test.go
index 3df3f3917..22e1df1d9 100644
--- a/Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions_test.go
+++ b/Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions_test.go
@@ -509,3 +509,103 @@ func TestRegexpWrapper(t *testing.T) {
True(t, assert.NotRegexp(regexp.MustCompile(tc.rx), tc.str))
}
}
+
+func TestZeroWrapper(t *testing.T) {
+ assert := New(t)
+ mockAssert := New(new(testing.T))
+
+ for _, test := range zeros {
+ assert.True(mockAssert.Zero(test), "Zero should return true for %v", test)
+ }
+
+ for _, test := range nonZeros {
+ assert.False(mockAssert.Zero(test), "Zero should return false for %v", test)
+ }
+}
+
+func TestNotZeroWrapper(t *testing.T) {
+ assert := New(t)
+ mockAssert := New(new(testing.T))
+
+ for _, test := range zeros {
+ assert.False(mockAssert.NotZero(test), "Zero should return true for %v", test)
+ }
+
+ for _, test := range nonZeros {
+ assert.True(mockAssert.NotZero(test), "Zero should return false for %v", test)
+ }
+}
+
+func TestJSONEqWrapper_EqualSONString(t *testing.T) {
+ assert := New(new(testing.T))
+ if !assert.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`) {
+ t.Error("JSONEq should return true")
+ }
+
+}
+
+func TestJSONEqWrapper_EquivalentButNotEqual(t *testing.T) {
+ assert := New(new(testing.T))
+ if !assert.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) {
+ t.Error("JSONEq should return true")
+ }
+
+}
+
+func TestJSONEqWrapper_HashOfArraysAndHashes(t *testing.T) {
+ assert := New(new(testing.T))
+ if !assert.JSONEq("{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}",
+ "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}") {
+ t.Error("JSONEq should return true")
+ }
+}
+
+func TestJSONEqWrapper_Array(t *testing.T) {
+ assert := New(new(testing.T))
+ if !assert.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`) {
+ t.Error("JSONEq should return true")
+ }
+
+}
+
+func TestJSONEqWrapper_HashAndArrayNotEquivalent(t *testing.T) {
+ assert := New(new(testing.T))
+ if assert.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`) {
+ t.Error("JSONEq should return false")
+ }
+}
+
+func TestJSONEqWrapper_HashesNotEquivalent(t *testing.T) {
+ assert := New(new(testing.T))
+ if assert.JSONEq(`{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) {
+ t.Error("JSONEq should return false")
+ }
+}
+
+func TestJSONEqWrapper_ActualIsNotJSON(t *testing.T) {
+ assert := New(new(testing.T))
+ if assert.JSONEq(`{"foo": "bar"}`, "Not JSON") {
+ t.Error("JSONEq should return false")
+ }
+}
+
+func TestJSONEqWrapper_ExpectedIsNotJSON(t *testing.T) {
+ assert := New(new(testing.T))
+ if assert.JSONEq("Not JSON", `{"foo": "bar", "hello": "world"}`) {
+ t.Error("JSONEq should return false")
+ }
+}
+
+func TestJSONEqWrapper_ExpectedAndActualNotJSON(t *testing.T) {
+ assert := New(new(testing.T))
+ if assert.JSONEq("Not JSON", "Not JSON") {
+ t.Error("JSONEq should return false")
+ }
+}
+
+func TestJSONEqWrapper_ArraysOfDifferentOrder(t *testing.T) {
+ assert := New(new(testing.T))
+ if assert.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`) {
+ t.Error("JSONEq should return false")
+ }
+}
diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/assert/http_assertions.go b/Godeps/_workspace/src/github.com/stretchr/testify/assert/http_assertions.go
index 1246e58e0..437a86ce4 100644
--- a/Godeps/_workspace/src/github.com/stretchr/testify/assert/http_assertions.go
+++ b/Godeps/_workspace/src/github.com/stretchr/testify/assert/http_assertions.go
@@ -10,9 +10,9 @@ import (
// httpCode is a helper that returns HTTP code of the response. It returns -1
// if building a new request fails.
-func httpCode(handler http.HandlerFunc, mode, url string, values url.Values) int {
+func httpCode(handler http.HandlerFunc, method, url string, values url.Values) int {
w := httptest.NewRecorder()
- req, err := http.NewRequest(mode, url+"?"+values.Encode(), nil)
+ req, err := http.NewRequest(method, url+"?"+values.Encode(), nil)
if err != nil {
return -1
}
@@ -25,8 +25,8 @@ func httpCode(handler http.HandlerFunc, mode, url string, values url.Values) int
// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil)
//
// Returns whether the assertion was successful (true) or not (false).
-func HTTPSuccess(t TestingT, handler http.HandlerFunc, mode, url string, values url.Values) bool {
- code := httpCode(handler, mode, url, values)
+func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool {
+ code := httpCode(handler, method, url, values)
if code == -1 {
return false
}
@@ -38,8 +38,8 @@ func HTTPSuccess(t TestingT, handler http.HandlerFunc, mode, url string, values
// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
//
// Returns whether the assertion was successful (true) or not (false).
-func HTTPRedirect(t TestingT, handler http.HandlerFunc, mode, url string, values url.Values) bool {
- code := httpCode(handler, mode, url, values)
+func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool {
+ code := httpCode(handler, method, url, values)
if code == -1 {
return false
}
@@ -51,8 +51,8 @@ func HTTPRedirect(t TestingT, handler http.HandlerFunc, mode, url string, values
// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
//
// Returns whether the assertion was successful (true) or not (false).
-func HTTPError(t TestingT, handler http.HandlerFunc, mode, url string, values url.Values) bool {
- code := httpCode(handler, mode, url, values)
+func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool {
+ code := httpCode(handler, method, url, values)
if code == -1 {
return false
}
@@ -61,9 +61,9 @@ func HTTPError(t TestingT, handler http.HandlerFunc, mode, url string, values ur
// HTTPBody is a helper that returns HTTP body of the response. It returns
// empty string if building a new request fails.
-func HTTPBody(handler http.HandlerFunc, mode, url string, values url.Values) string {
+func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string {
w := httptest.NewRecorder()
- req, err := http.NewRequest(mode, url+"?"+values.Encode(), nil)
+ req, err := http.NewRequest(method, url+"?"+values.Encode(), nil)
if err != nil {
return ""
}
@@ -77,8 +77,8 @@ func HTTPBody(handler http.HandlerFunc, mode, url string, values url.Values) str
// assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky")
//
// Returns whether the assertion was successful (true) or not (false).
-func HTTPBodyContains(t TestingT, handler http.HandlerFunc, mode, url string, values url.Values, str interface{}) bool {
- body := HTTPBody(handler, mode, url, values)
+func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}) bool {
+ body := HTTPBody(handler, method, url, values)
contains := strings.Contains(body, fmt.Sprint(str))
if !contains {
@@ -94,8 +94,8 @@ func HTTPBodyContains(t TestingT, handler http.HandlerFunc, mode, url string, va
// assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky")
//
// Returns whether the assertion was successful (true) or not (false).
-func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, mode, url string, values url.Values, str interface{}) bool {
- body := HTTPBody(handler, mode, url, values)
+func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}) bool {
+ body := HTTPBody(handler, method, url, values)
contains := strings.Contains(body, fmt.Sprint(str))
if contains {
@@ -114,8 +114,8 @@ func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, mode, url string,
// assert.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil)
//
// Returns whether the assertion was successful (true) or not (false).
-func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, mode, url string, values url.Values) bool {
- return HTTPSuccess(a.t, handler, mode, url, values)
+func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method, url string, values url.Values) bool {
+ return HTTPSuccess(a.t, handler, method, url, values)
}
// HTTPRedirect asserts that a specified handler returns a redirect status code.
@@ -123,8 +123,8 @@ func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, mode, url string, val
// assert.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
//
// Returns whether the assertion was successful (true) or not (false).
-func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, mode, url string, values url.Values) bool {
- return HTTPRedirect(a.t, handler, mode, url, values)
+func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method, url string, values url.Values) bool {
+ return HTTPRedirect(a.t, handler, method, url, values)
}
// HTTPError asserts that a specified handler returns an error status code.
@@ -132,8 +132,8 @@ func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, mode, url string, va
// assert.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
//
// Returns whether the assertion was successful (true) or not (false).
-func (a *Assertions) HTTPError(handler http.HandlerFunc, mode, url string, values url.Values) bool {
- return HTTPError(a.t, handler, mode, url, values)
+func (a *Assertions) HTTPError(handler http.HandlerFunc, method, url string, values url.Values) bool {
+ return HTTPError(a.t, handler, method, url, values)
}
// HTTPBodyContains asserts that a specified handler returns a
@@ -142,8 +142,8 @@ func (a *Assertions) HTTPError(handler http.HandlerFunc, mode, url string, value
// assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky")
//
// Returns whether the assertion was successful (true) or not (false).
-func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, mode, url string, values url.Values, str interface{}) bool {
- return HTTPBodyContains(a.t, handler, mode, url, values, str)
+func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method, url string, values url.Values, str interface{}) bool {
+ return HTTPBodyContains(a.t, handler, method, url, values, str)
}
// HTTPBodyNotContains asserts that a specified handler returns a
@@ -152,6 +152,6 @@ func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, mode, url string
// assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky")
//
// Returns whether the assertion was successful (true) or not (false).
-func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, mode, url string, values url.Values, str interface{}) bool {
- return HTTPBodyNotContains(a.t, handler, mode, url, values, str)
+func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method, url string, values url.Values, str interface{}) bool {
+ return HTTPBodyNotContains(a.t, handler, method, url, values, str)
}
diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/mock/mock.go b/Godeps/_workspace/src/github.com/stretchr/testify/mock/mock.go
index fa8747e29..111a281b4 100644
--- a/Godeps/_workspace/src/github.com/stretchr/testify/mock/mock.go
+++ b/Godeps/_workspace/src/github.com/stretchr/testify/mock/mock.go
@@ -2,13 +2,15 @@ package mock
import (
"fmt"
- "github.com/stretchr/objx"
- "github.com/stretchr/testify/assert"
"reflect"
+ "regexp"
"runtime"
"strings"
"sync"
"time"
+
+ "github.com/stretchr/objx"
+ "github.com/stretchr/testify/assert"
)
// TestingT is an interface wrapper around *testing.T
@@ -24,6 +26,7 @@ type TestingT interface {
// Call represents a method call and is used for setting expectations,
// as well as recording activity.
type Call struct {
+ Parent *Mock
// The name of the method that was or will be called.
Method string
@@ -46,112 +49,79 @@ type Call struct {
// Holds a handler used to manipulate arguments content that are passed by
// reference. It's useful when mocking methods such as unmarshalers or
// decoders.
- Run func(Arguments)
-}
-
-// Mock is the workhorse used to track activity on another object.
-// For an example of its usage, refer to the "Example Usage" section at the top of this document.
-type Mock struct {
-
- // The method name that is currently
- // being referred to by the On method.
- onMethodName string
-
- // An array of the arguments that are
- // currently being referred to by the On method.
- onMethodArguments Arguments
-
- // Represents the calls that are expected of
- // an object.
- ExpectedCalls []Call
-
- // Holds the calls that were made to this mocked object.
- Calls []Call
-
- // TestData holds any data that might be useful for testing. Testify ignores
- // this data completely allowing you to do whatever you like with it.
- testData objx.Map
-
- mutex sync.Mutex
+ RunFn func(Arguments)
}
-// TestData holds any data that might be useful for testing. Testify ignores
-// this data completely allowing you to do whatever you like with it.
-func (m *Mock) TestData() objx.Map {
-
- if m.testData == nil {
- m.testData = make(objx.Map)
+func newCall(parent *Mock, methodName string, methodArguments ...interface{}) *Call {
+ return &Call{
+ Parent: parent,
+ Method: methodName,
+ Arguments: methodArguments,
+ ReturnArguments: make([]interface{}, 0),
+ Repeatability: 0,
+ WaitFor: nil,
+ RunFn: nil,
}
-
- return m.testData
}
-/*
- Setting expectations
-*/
+func (self *Call) lock() {
+ self.Parent.mutex.Lock()
+}
-// On starts a description of an expectation of the specified method
-// being called.
-//
-// Mock.On("MyMethod", arg1, arg2)
-func (m *Mock) On(methodName string, arguments ...interface{}) *Mock {
- m.onMethodName = methodName
- m.onMethodArguments = arguments
+func (self *Call) unlock() {
+ self.Parent.mutex.Unlock()
+}
- for _, arg := range arguments {
- if v := reflect.ValueOf(arg); v.Kind() == reflect.Func {
- panic(fmt.Sprintf("cannot use Func in expectations. Use mock.AnythingOfType(\"%T\")", arg))
- }
- }
+func (self *Call) Return(returnArguments ...interface{}) *Call {
+ self.lock()
+ defer self.unlock()
- return m
-}
+ self.ReturnArguments = returnArguments
-// Return finishes a description of an expectation of the method (and arguments)
-// specified in the most recent On method call.
-//
-// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2)
-func (m *Mock) Return(returnArguments ...interface{}) *Mock {
- m.ExpectedCalls = append(m.ExpectedCalls, Call{m.onMethodName, m.onMethodArguments, returnArguments, 0, nil, nil})
- return m
+ return self
}
// Once indicates that that the mock should only return the value once.
//
// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Once()
-func (m *Mock) Once() {
- m.ExpectedCalls[len(m.ExpectedCalls)-1].Repeatability = 1
+func (self *Call) Once() *Call {
+ return self.Times(1)
}
// Twice indicates that that the mock should only return the value twice.
//
// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Twice()
-func (m *Mock) Twice() {
- m.ExpectedCalls[len(m.ExpectedCalls)-1].Repeatability = 2
+func (self *Call) Twice() *Call {
+ return self.Times(2)
}
// Times indicates that that the mock should only return the indicated number
// of times.
//
// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Times(5)
-func (m *Mock) Times(i int) {
- m.ExpectedCalls[len(m.ExpectedCalls)-1].Repeatability = i
+func (self *Call) Times(i int) *Call {
+ self.lock()
+ defer self.unlock()
+ self.Repeatability = i
+ return self
}
// WaitUntil sets the channel that will block the mock's return until its closed
// or a message is received.
//
// Mock.On("MyMethod", arg1, arg2).WaitUntil(time.After(time.Second))
-func (m *Mock) WaitUntil(w <-chan time.Time) *Mock {
- m.ExpectedCalls[len(m.ExpectedCalls)-1].WaitFor = w
- return m
+func (self *Call) WaitUntil(w <-chan time.Time) *Call {
+ self.lock()
+ defer self.unlock()
+ self.WaitFor = w
+ return self
}
// After sets how long to block until the call returns
//
// Mock.On("MyMethod", arg1, arg2).After(time.Second)
-func (m *Mock) After(d time.Duration) *Mock {
- return m.WaitUntil(time.After(d))
+func (self *Call) After(d time.Duration) *Call {
+ return self.WaitUntil(time.After(d))
}
// Run sets a handler to be called before returning. It can be used when
@@ -162,22 +132,87 @@ func (m *Mock) After(d time.Duration) *Mock {
// arg := args.Get(0).(*map[string]interface{})
// arg["foo"] = "bar"
// })
-func (m *Mock) Run(fn func(Arguments)) *Mock {
- m.ExpectedCalls[len(m.ExpectedCalls)-1].Run = fn
- return m
+func (self *Call) Run(fn func(Arguments)) *Call {
+ self.lock()
+ defer self.unlock()
+ self.RunFn = fn
+ return self
+}
+
+// On chains a new expectation description onto the mocked interface. This
+// allows syntax like.
+//
+// Mock.
+// On("MyMethod", 1).Return(nil).
+// On("MyOtherMethod", 'a', 'b', 'c').Return(errors.New("Some Error"))
+func (self *Call) On(methodName string, arguments ...interface{}) *Call {
+ return self.Parent.On(methodName, arguments...)
+}
+
+// Mock is the workhorse used to track activity on another object.
+// For an example of its usage, refer to the "Example Usage" section at the top
+// of this document.
+type Mock struct {
+ // Represents the calls that are expected of
+ // an object.
+ ExpectedCalls []*Call
+
+ // Holds the calls that were made to this mocked object.
+ Calls []Call
+
+ // TestData holds any data that might be useful for testing. Testify ignores
+ // this data completely allowing you to do whatever you like with it.
+ testData objx.Map
+
+ mutex sync.Mutex
+}
+
+// TestData holds any data that might be useful for testing. Testify ignores
+// this data completely allowing you to do whatever you like with it.
+func (m *Mock) TestData() objx.Map {
+
+ if m.testData == nil {
+ m.testData = make(objx.Map)
+ }
+
+ return m.testData
}
/*
- Recording and responding to activity
+ Setting expectations
*/
+// On starts a description of an expectation of the specified method
+// being called.
+//
+// Mock.On("MyMethod", arg1, arg2)
+func (self *Mock) On(methodName string, arguments ...interface{}) *Call {
+ for _, arg := range arguments {
+ if v := reflect.ValueOf(arg); v.Kind() == reflect.Func {
+ panic(fmt.Sprintf("cannot use Func in expectations. Use mock.AnythingOfType(\"%T\")", arg))
+ }
+ }
+
+ self.mutex.Lock()
+ defer self.mutex.Unlock()
+ c := newCall(self, methodName, arguments...)
+ self.ExpectedCalls = append(self.ExpectedCalls, c)
+ return c
+}
+
+// /*
+// Recording and responding to activity
+// */
+
func (m *Mock) findExpectedCall(method string, arguments ...interface{}) (int, *Call) {
+ m.mutex.Lock()
+ defer m.mutex.Unlock()
for i, call := range m.ExpectedCalls {
if call.Method == method && call.Repeatability > -1 {
_, diffCount := call.Arguments.Diff(arguments)
if diffCount == 0 {
- return i, &call
+ return i, call
}
}
@@ -186,17 +221,16 @@ func (m *Mock) findExpectedCall(method string, arguments ...interface{}) (int, *
}
func (m *Mock) findClosestCall(method string, arguments ...interface{}) (bool, *Call) {
-
diffCount := 0
var closestCall *Call = nil
- for _, call := range m.ExpectedCalls {
+ for _, call := range m.expectedCalls() {
if call.Method == method {
_, tempDiffCount := call.Arguments.Diff(arguments)
if tempDiffCount < diffCount || diffCount == 0 {
diffCount = tempDiffCount
- closestCall = &call
+ closestCall = call
}
}
@@ -215,7 +249,7 @@ func callString(method string, arguments Arguments, includeArgumentValues bool)
if includeArgumentValues {
var argVals []string
for argIndex, arg := range arguments {
- argVals = append(argVals, fmt.Sprintf("%d: %v", argIndex, arg))
+ argVals = append(argVals, fmt.Sprintf("%d: %#v", argIndex, arg))
}
argValsString = fmt.Sprintf("\n\t\t%s", strings.Join(argVals, "\n\t\t"))
}
@@ -228,22 +262,26 @@ func callString(method string, arguments Arguments, includeArgumentValues bool)
// appropriate .On .Return() calls)
// If Call.WaitFor is set, blocks until the channel is closed or receives a message.
func (m *Mock) Called(arguments ...interface{}) Arguments {
- defer m.mutex.Unlock()
- m.mutex.Lock()
-
// get the calling function's name
pc, _, _, ok := runtime.Caller(1)
if !ok {
panic("Couldn't get the caller information")
}
functionPath := runtime.FuncForPC(pc).Name()
+ //Next four lines are required to use GCCGO function naming conventions.
+ //For Ex: github_com_docker_libkv_store_mock.WatchTree.pN39_github_com_docker_libkv_store_mock.Mock
+ //uses inteface information unlike golang github.com/docker/libkv/store/mock.(*Mock).WatchTree
+ //With GCCGO we need to remove interface information starting from pN<dd>.
+ re := regexp.MustCompile("\\.pN\\d+_")
+ if re.MatchString(functionPath) {
+ functionPath = re.Split(functionPath, -1)[0]
+ }
parts := strings.Split(functionPath, ".")
functionName := parts[len(parts)-1]
found, call := m.findExpectedCall(functionName, arguments...)
- switch {
- case found < 0:
+ if found < 0 {
// we have to fail here - because we don't know what to do
// as the return arguments. This is because:
//
@@ -258,28 +296,33 @@ func (m *Mock) Called(arguments ...interface{}) Arguments {
} else {
panic(fmt.Sprintf("\nassert: mock: I don't know what to return because the method call was unexpected.\n\tEither do Mock.On(\"%s\").Return(...) first, or remove the %s() call.\n\tThis method was unexpected:\n\t\t%s\n\tat: %s", functionName, functionName, callString(functionName, arguments, true), assert.CallerInfo()))
}
- case call.Repeatability == 1:
- call.Repeatability = -1
- m.ExpectedCalls[found] = *call
- case call.Repeatability > 1:
- call.Repeatability -= 1
- m.ExpectedCalls[found] = *call
+ } else {
+ m.mutex.Lock()
+ switch {
+ case call.Repeatability == 1:
+ call.Repeatability = -1
+
+ case call.Repeatability > 1:
+ call.Repeatability -= 1
+ }
+ m.mutex.Unlock()
}
// add the call
- m.Calls = append(m.Calls, Call{functionName, arguments, make([]interface{}, 0), 0, nil, nil})
+ m.mutex.Lock()
+ m.Calls = append(m.Calls, *newCall(m, functionName, arguments...))
+ m.mutex.Unlock()
// block if specified
if call.WaitFor != nil {
<-call.WaitFor
}
- if call.Run != nil {
- call.Run(arguments)
+ if call.RunFn != nil {
+ call.RunFn(arguments)
}
return call.ReturnArguments
-
}
/*
@@ -302,27 +345,30 @@ func AssertExpectationsForObjects(t TestingT, testObjects ...interface{}) bool {
// AssertExpectations asserts that everything specified with On and Return was
// in fact called as expected. Calls may have occurred in any order.
func (m *Mock) AssertExpectations(t TestingT) bool {
-
var somethingMissing bool = false
var failedExpectations int = 0
// iterate through each expectation
- for _, expectedCall := range m.ExpectedCalls {
- switch {
- case !m.methodWasCalled(expectedCall.Method, expectedCall.Arguments):
+ expectedCalls := m.expectedCalls()
+ for _, expectedCall := range expectedCalls {
+ if !m.methodWasCalled(expectedCall.Method, expectedCall.Arguments) {
somethingMissing = true
failedExpectations++
t.Logf("\u274C\t%s(%s)", expectedCall.Method, expectedCall.Arguments.String())
- case expectedCall.Repeatability > 0:
- somethingMissing = true
- failedExpectations++
- default:
- t.Logf("\u2705\t%s(%s)", expectedCall.Method, expectedCall.Arguments.String())
+ } else {
+ m.mutex.Lock()
+ if expectedCall.Repeatability > 0 {
+ somethingMissing = true
+ failedExpectations++
+ } else {
+ t.Logf("\u2705\t%s(%s)", expectedCall.Method, expectedCall.Arguments.String())
+ }
+ m.mutex.Unlock()
}
}
if somethingMissing {
- t.Errorf("FAIL: %d out of %d expectation(s) were met.\n\tThe code you are testing needs to make %d more call(s).\n\tat: %s", len(m.ExpectedCalls)-failedExpectations, len(m.ExpectedCalls), failedExpectations, assert.CallerInfo())
+ t.Errorf("FAIL: %d out of %d expectation(s) were met.\n\tThe code you are testing needs to make %d more call(s).\n\tat: %s", len(expectedCalls)-failedExpectations, len(expectedCalls), failedExpectations, assert.CallerInfo())
}
return !somethingMissing
@@ -331,18 +377,18 @@ func (m *Mock) AssertExpectations(t TestingT) bool {
// AssertNumberOfCalls asserts that the method was called expectedCalls times.
func (m *Mock) AssertNumberOfCalls(t TestingT, methodName string, expectedCalls int) bool {
var actualCalls int = 0
- for _, call := range m.Calls {
+ for _, call := range m.calls() {
if call.Method == methodName {
actualCalls++
}
}
- return assert.Equal(t, actualCalls, expectedCalls, fmt.Sprintf("Expected number of calls (%d) does not match the actual number of calls (%d).", expectedCalls, actualCalls))
+ return assert.Equal(t, expectedCalls, actualCalls, fmt.Sprintf("Expected number of calls (%d) does not match the actual number of calls (%d).", expectedCalls, actualCalls))
}
// AssertCalled asserts that the method was called.
func (m *Mock) AssertCalled(t TestingT, methodName string, arguments ...interface{}) bool {
if !assert.True(t, m.methodWasCalled(methodName, arguments), fmt.Sprintf("The \"%s\" method should have been called with %d argument(s), but was not.", methodName, len(arguments))) {
- t.Logf("%v", m.ExpectedCalls)
+ t.Logf("%v", m.expectedCalls())
return false
}
return true
@@ -351,14 +397,14 @@ func (m *Mock) AssertCalled(t TestingT, methodName string, arguments ...interfac
// AssertNotCalled asserts that the method was not called.
func (m *Mock) AssertNotCalled(t TestingT, methodName string, arguments ...interface{}) bool {
if !assert.False(t, m.methodWasCalled(methodName, arguments), fmt.Sprintf("The \"%s\" method was called with %d argument(s), but should NOT have been.", methodName, len(arguments))) {
- t.Logf("%v", m.ExpectedCalls)
+ t.Logf("%v", m.expectedCalls())
return false
}
return true
}
func (m *Mock) methodWasCalled(methodName string, expected []interface{}) bool {
- for _, call := range m.Calls {
+ for _, call := range m.calls() {
if call.Method == methodName {
_, differences := Arguments(expected).Diff(call.Arguments)
@@ -374,6 +420,18 @@ func (m *Mock) methodWasCalled(methodName string, expected []interface{}) bool {
return false
}
+func (m *Mock) expectedCalls() []*Call {
+ m.mutex.Lock()
+ defer m.mutex.Unlock()
+ return append([]*Call{}, m.ExpectedCalls...)
+}
+
+func (m *Mock) calls() []Call {
+ m.mutex.Lock()
+ defer m.mutex.Unlock()
+ return append([]Call{}, m.Calls...)
+}
+
/*
Arguments
*/
diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/mock/mock_test.go b/Godeps/_workspace/src/github.com/stretchr/testify/mock/mock_test.go
index b7446accb..1315ceccb 100644
--- a/Godeps/_workspace/src/github.com/stretchr/testify/mock/mock_test.go
+++ b/Godeps/_workspace/src/github.com/stretchr/testify/mock/mock_test.go
@@ -3,6 +3,7 @@ package mock
import (
"errors"
"github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
"testing"
"time"
)
@@ -44,6 +45,16 @@ func (i *TestExampleImplementation) TheExampleMethodFunc(fn func(string) error)
return args.Error(0)
}
+func (i *TestExampleImplementation) TheExampleMethodVariadic(a ...int) error {
+ args := i.Called(a)
+ return args.Error(0)
+}
+
+func (i *TestExampleImplementation) TheExampleMethodVariadicInterface(a ...interface{}) error {
+ args := i.Called(a)
+ return args.Error(0)
+}
+
type ExampleFuncType func(string) error
func (i *TestExampleImplementation) TheExampleMethodFuncType(fn ExampleFuncType) error {
@@ -63,9 +74,7 @@ func Test_Mock_TestData(t *testing.T) {
mockedService.TestData().Set("something", 123)
assert.Equal(t, 123, mockedService.TestData().Get("something").Data())
-
}
-
}
func Test_Mock_On(t *testing.T) {
@@ -73,9 +82,36 @@ func Test_Mock_On(t *testing.T) {
// make a test impl object
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
- assert.Equal(t, mockedService.On("TheExampleMethod"), &mockedService.Mock)
- assert.Equal(t, "TheExampleMethod", mockedService.onMethodName)
+ c := mockedService.On("TheExampleMethod")
+ assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
+ assert.Equal(t, "TheExampleMethod", c.Method)
+}
+
+func Test_Mock_Chained_On(t *testing.T) {
+ // make a test impl object
+ var mockedService *TestExampleImplementation = new(TestExampleImplementation)
+ mockedService.
+ On("TheExampleMethod", 1, 2, 3).
+ Return(0).
+ On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")).
+ Return(nil)
+
+ expectedCalls := []*Call{
+ &Call{
+ Parent: &mockedService.Mock,
+ Method: "TheExampleMethod",
+ Arguments: []interface{}{1, 2, 3},
+ ReturnArguments: []interface{}{0},
+ },
+ &Call{
+ Parent: &mockedService.Mock,
+ Method: "TheExampleMethod3",
+ Arguments: []interface{}{AnythingOfType("*mock.ExampleType")},
+ ReturnArguments: []interface{}{nil},
+ },
+ }
+ assert.Equal(t, expectedCalls, mockedService.ExpectedCalls)
}
func Test_Mock_On_WithArgs(t *testing.T) {
@@ -83,12 +119,11 @@ func Test_Mock_On_WithArgs(t *testing.T) {
// make a test impl object
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
- assert.Equal(t, mockedService.On("TheExampleMethod", 1, 2, 3), &mockedService.Mock)
- assert.Equal(t, "TheExampleMethod", mockedService.onMethodName)
- assert.Equal(t, 1, mockedService.onMethodArguments[0])
- assert.Equal(t, 2, mockedService.onMethodArguments[1])
- assert.Equal(t, 3, mockedService.onMethodArguments[2])
+ c := mockedService.On("TheExampleMethod", 1, 2, 3, 4)
+ assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
+ assert.Equal(t, "TheExampleMethod", c.Method)
+ assert.Equal(t, Arguments{1, 2, 3, 4}, c.Arguments)
}
func Test_Mock_On_WithFuncArg(t *testing.T) {
@@ -96,12 +131,85 @@ func Test_Mock_On_WithFuncArg(t *testing.T) {
// make a test impl object
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
- assert.Equal(t, mockedService.On("TheExampleMethodFunc", AnythingOfType("func(string) error")).Return(nil), &mockedService.Mock)
- assert.Equal(t, "TheExampleMethodFunc", mockedService.onMethodName)
- assert.Equal(t, AnythingOfType("func(string) error"), mockedService.onMethodArguments[0])
+ c := mockedService.
+ On("TheExampleMethodFunc", AnythingOfType("func(string) error")).
+ Return(nil)
+
+ assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
+ assert.Equal(t, "TheExampleMethodFunc", c.Method)
+ assert.Equal(t, 1, len(c.Arguments))
+ assert.Equal(t, AnythingOfType("func(string) error"), c.Arguments[0])
fn := func(string) error { return nil }
- mockedService.TheExampleMethodFunc(fn)
+
+ assert.NotPanics(t, func() {
+ mockedService.TheExampleMethodFunc(fn)
+ })
+}
+
+func Test_Mock_On_WithVariadicFunc(t *testing.T) {
+
+ // make a test impl object
+ var mockedService *TestExampleImplementation = new(TestExampleImplementation)
+
+ c := mockedService.
+ On("TheExampleMethodVariadic", []int{1, 2, 3}).
+ Return(nil)
+
+ assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
+ assert.Equal(t, 1, len(c.Arguments))
+ assert.Equal(t, []int{1, 2, 3}, c.Arguments[0])
+
+ assert.NotPanics(t, func() {
+ mockedService.TheExampleMethodVariadic(1, 2, 3)
+ })
+ assert.Panics(t, func() {
+ mockedService.TheExampleMethodVariadic(1, 2)
+ })
+
+}
+
+func Test_Mock_On_WithVariadicFuncWithInterface(t *testing.T) {
+
+ // make a test impl object
+ var mockedService *TestExampleImplementation = new(TestExampleImplementation)
+
+ c := mockedService.On("TheExampleMethodVariadicInterface", []interface{}{1, 2, 3}).
+ Return(nil)
+
+ assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
+ assert.Equal(t, 1, len(c.Arguments))
+ assert.Equal(t, []interface{}{1, 2, 3}, c.Arguments[0])
+
+ assert.NotPanics(t, func() {
+ mockedService.TheExampleMethodVariadicInterface(1, 2, 3)
+ })
+ assert.Panics(t, func() {
+ mockedService.TheExampleMethodVariadicInterface(1, 2)
+ })
+
+}
+
+func Test_Mock_On_WithVariadicFuncWithEmptyInterfaceArray(t *testing.T) {
+
+ // make a test impl object
+ var mockedService *TestExampleImplementation = new(TestExampleImplementation)
+
+ var expected []interface{}
+ c := mockedService.
+ On("TheExampleMethodVariadicInterface", expected).
+ Return(nil)
+
+ assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
+ assert.Equal(t, 1, len(c.Arguments))
+ assert.Equal(t, expected, c.Arguments[0])
+
+ assert.NotPanics(t, func() {
+ mockedService.TheExampleMethodVariadicInterface()
+ })
+ assert.Panics(t, func() {
+ mockedService.TheExampleMethodVariadicInterface(1, 2)
+ })
}
@@ -119,13 +227,18 @@ func Test_Mock_On_WithFuncTypeArg(t *testing.T) {
// make a test impl object
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
- assert.Equal(t, mockedService.On("TheExampleMethodFuncType", AnythingOfType("mock.ExampleFuncType")).Return(nil), &mockedService.Mock)
- assert.Equal(t, "TheExampleMethodFuncType", mockedService.onMethodName)
- assert.Equal(t, AnythingOfType("mock.ExampleFuncType"), mockedService.onMethodArguments[0])
+ c := mockedService.
+ On("TheExampleMethodFuncType", AnythingOfType("mock.ExampleFuncType")).
+ Return(nil)
- fn := func(string) error { return nil }
- mockedService.TheExampleMethodFuncType(fn)
+ assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
+ assert.Equal(t, 1, len(c.Arguments))
+ assert.Equal(t, AnythingOfType("mock.ExampleFuncType"), c.Arguments[0])
+ fn := func(string) error { return nil }
+ assert.NotPanics(t, func() {
+ mockedService.TheExampleMethodFuncType(fn)
+ })
}
func Test_Mock_Return(t *testing.T) {
@@ -133,24 +246,23 @@ func Test_Mock_Return(t *testing.T) {
// make a test impl object
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
- assert.Equal(t, mockedService.On("TheExampleMethod", "A", "B", true).Return(1, "two", true), &mockedService.Mock)
-
- // ensure the call was created
- if assert.Equal(t, 1, len(mockedService.ExpectedCalls)) {
- call := mockedService.ExpectedCalls[0]
+ c := mockedService.
+ On("TheExampleMethod", "A", "B", true).
+ Return(1, "two", true)
- assert.Equal(t, "TheExampleMethod", call.Method)
- assert.Equal(t, "A", call.Arguments[0])
- assert.Equal(t, "B", call.Arguments[1])
- assert.Equal(t, true, call.Arguments[2])
- assert.Equal(t, 1, call.ReturnArguments[0])
- assert.Equal(t, "two", call.ReturnArguments[1])
- assert.Equal(t, true, call.ReturnArguments[2])
- assert.Equal(t, 0, call.Repeatability)
- assert.Nil(t, call.WaitFor)
+ require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
- }
+ call := mockedService.ExpectedCalls[0]
+ assert.Equal(t, "TheExampleMethod", call.Method)
+ assert.Equal(t, "A", call.Arguments[0])
+ assert.Equal(t, "B", call.Arguments[1])
+ assert.Equal(t, true, call.Arguments[2])
+ assert.Equal(t, 1, call.ReturnArguments[0])
+ assert.Equal(t, "two", call.ReturnArguments[1])
+ assert.Equal(t, true, call.ReturnArguments[2])
+ assert.Equal(t, 0, call.Repeatability)
+ assert.Nil(t, call.WaitFor)
}
func Test_Mock_Return_WaitUntil(t *testing.T) {
@@ -159,24 +271,25 @@ func Test_Mock_Return_WaitUntil(t *testing.T) {
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
ch := time.After(time.Second)
- assert.Equal(t, mockedService.Mock.On("TheExampleMethod", "A", "B", true).Return(1, "two", true).WaitUntil(ch), &mockedService.Mock)
-
- // ensure the call was created
- if assert.Equal(t, 1, len(mockedService.Mock.ExpectedCalls)) {
- call := mockedService.Mock.ExpectedCalls[0]
+ c := mockedService.Mock.
+ On("TheExampleMethod", "A", "B", true).
+ WaitUntil(ch).
+ Return(1, "two", true)
- assert.Equal(t, "TheExampleMethod", call.Method)
- assert.Equal(t, "A", call.Arguments[0])
- assert.Equal(t, "B", call.Arguments[1])
- assert.Equal(t, true, call.Arguments[2])
- assert.Equal(t, 1, call.ReturnArguments[0])
- assert.Equal(t, "two", call.ReturnArguments[1])
- assert.Equal(t, true, call.ReturnArguments[2])
- assert.Equal(t, 0, call.Repeatability)
- assert.Equal(t, ch, call.WaitFor)
+ // assert that the call was created
+ require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
- }
+ call := mockedService.ExpectedCalls[0]
+ assert.Equal(t, "TheExampleMethod", call.Method)
+ assert.Equal(t, "A", call.Arguments[0])
+ assert.Equal(t, "B", call.Arguments[1])
+ assert.Equal(t, true, call.Arguments[2])
+ assert.Equal(t, 1, call.ReturnArguments[0])
+ assert.Equal(t, "two", call.ReturnArguments[1])
+ assert.Equal(t, true, call.ReturnArguments[2])
+ assert.Equal(t, 0, call.Repeatability)
+ assert.Equal(t, ch, call.WaitFor)
}
func Test_Mock_Return_After(t *testing.T) {
@@ -184,23 +297,24 @@ func Test_Mock_Return_After(t *testing.T) {
// make a test impl object
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
- assert.Equal(t, mockedService.Mock.On("TheExampleMethod", "A", "B", true).Return(1, "two", true).After(time.Second), &mockedService.Mock)
+ c := mockedService.Mock.
+ On("TheExampleMethod", "A", "B", true).
+ Return(1, "two", true).
+ After(time.Second)
- // ensure the call was created
- if assert.Equal(t, 1, len(mockedService.Mock.ExpectedCalls)) {
- call := mockedService.Mock.ExpectedCalls[0]
+ require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
- assert.Equal(t, "TheExampleMethod", call.Method)
- assert.Equal(t, "A", call.Arguments[0])
- assert.Equal(t, "B", call.Arguments[1])
- assert.Equal(t, true, call.Arguments[2])
- assert.Equal(t, 1, call.ReturnArguments[0])
- assert.Equal(t, "two", call.ReturnArguments[1])
- assert.Equal(t, true, call.ReturnArguments[2])
- assert.Equal(t, 0, call.Repeatability)
- assert.NotEqual(t, nil, call.WaitFor)
+ call := mockedService.Mock.ExpectedCalls[0]
- }
+ assert.Equal(t, "TheExampleMethod", call.Method)
+ assert.Equal(t, "A", call.Arguments[0])
+ assert.Equal(t, "B", call.Arguments[1])
+ assert.Equal(t, true, call.Arguments[2])
+ assert.Equal(t, 1, call.ReturnArguments[0])
+ assert.Equal(t, "two", call.ReturnArguments[1])
+ assert.Equal(t, true, call.ReturnArguments[2])
+ assert.Equal(t, 0, call.Repeatability)
+ assert.NotEqual(t, nil, call.WaitFor)
}
@@ -209,29 +323,56 @@ func Test_Mock_Return_Run(t *testing.T) {
// make a test impl object
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
- assert.Equal(t, mockedService.Mock.On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")).Return(nil).Run(func(args Arguments) {
+ fn := func(args Arguments) {
arg := args.Get(0).(*ExampleType)
arg.ran = true
- }), &mockedService.Mock)
+ }
- // ensure the call was created
- if assert.Equal(t, 1, len(mockedService.Mock.ExpectedCalls)) {
- call := mockedService.Mock.ExpectedCalls[0]
+ c := mockedService.Mock.
+ On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")).
+ Return(nil).
+ Run(fn)
- assert.Equal(t, "TheExampleMethod3", call.Method)
- assert.Equal(t, AnythingOfType("*mock.ExampleType"), call.Arguments[0])
- assert.Equal(t, nil, call.ReturnArguments[0])
- assert.Equal(t, 0, call.Repeatability)
- assert.NotEqual(t, nil, call.WaitFor)
- assert.NotNil(t, call.Run)
+ require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
- }
+ call := mockedService.Mock.ExpectedCalls[0]
+
+ assert.Equal(t, "TheExampleMethod3", call.Method)
+ assert.Equal(t, AnythingOfType("*mock.ExampleType"), call.Arguments[0])
+ assert.Equal(t, nil, call.ReturnArguments[0])
+ assert.Equal(t, 0, call.Repeatability)
+ assert.NotEqual(t, nil, call.WaitFor)
+ assert.NotNil(t, call.Run)
et := ExampleType{}
assert.Equal(t, false, et.ran)
mockedService.TheExampleMethod3(&et)
assert.Equal(t, true, et.ran)
+}
+
+func Test_Mock_Return_Run_Out_Of_Order(t *testing.T) {
+ // make a test impl object
+ var mockedService *TestExampleImplementation = new(TestExampleImplementation)
+ f := func(args Arguments) {
+ arg := args.Get(0).(*ExampleType)
+ arg.ran = true
+ }
+
+ c := mockedService.Mock.
+ On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")).
+ Run(f).
+ Return(nil)
+ require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
+
+ call := mockedService.Mock.ExpectedCalls[0]
+
+ assert.Equal(t, "TheExampleMethod3", call.Method)
+ assert.Equal(t, AnythingOfType("*mock.ExampleType"), call.Arguments[0])
+ assert.Equal(t, nil, call.ReturnArguments[0])
+ assert.Equal(t, 0, call.Repeatability)
+ assert.NotEqual(t, nil, call.WaitFor)
+ assert.NotNil(t, call.Run)
}
func Test_Mock_Return_Once(t *testing.T) {
@@ -239,24 +380,23 @@ func Test_Mock_Return_Once(t *testing.T) {
// make a test impl object
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
- mockedService.On("TheExampleMethod", "A", "B", true).Return(1, "two", true).Once()
+ c := mockedService.On("TheExampleMethod", "A", "B", true).
+ Return(1, "two", true).
+ Once()
- // ensure the call was created
- if assert.Equal(t, 1, len(mockedService.ExpectedCalls)) {
- call := mockedService.ExpectedCalls[0]
+ require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
- assert.Equal(t, "TheExampleMethod", call.Method)
- assert.Equal(t, "A", call.Arguments[0])
- assert.Equal(t, "B", call.Arguments[1])
- assert.Equal(t, true, call.Arguments[2])
- assert.Equal(t, 1, call.ReturnArguments[0])
- assert.Equal(t, "two", call.ReturnArguments[1])
- assert.Equal(t, true, call.ReturnArguments[2])
- assert.Equal(t, 1, call.Repeatability)
- assert.Nil(t, call.WaitFor)
-
- }
+ call := mockedService.ExpectedCalls[0]
+ assert.Equal(t, "TheExampleMethod", call.Method)
+ assert.Equal(t, "A", call.Arguments[0])
+ assert.Equal(t, "B", call.Arguments[1])
+ assert.Equal(t, true, call.Arguments[2])
+ assert.Equal(t, 1, call.ReturnArguments[0])
+ assert.Equal(t, "two", call.ReturnArguments[1])
+ assert.Equal(t, true, call.ReturnArguments[2])
+ assert.Equal(t, 1, call.Repeatability)
+ assert.Nil(t, call.WaitFor)
}
func Test_Mock_Return_Twice(t *testing.T) {
@@ -264,24 +404,24 @@ func Test_Mock_Return_Twice(t *testing.T) {
// make a test impl object
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
- mockedService.On("TheExampleMethod", "A", "B", true).Return(1, "two", true).Twice()
-
- // ensure the call was created
- if assert.Equal(t, 1, len(mockedService.ExpectedCalls)) {
- call := mockedService.ExpectedCalls[0]
+ c := mockedService.
+ On("TheExampleMethod", "A", "B", true).
+ Return(1, "two", true).
+ Twice()
- assert.Equal(t, "TheExampleMethod", call.Method)
- assert.Equal(t, "A", call.Arguments[0])
- assert.Equal(t, "B", call.Arguments[1])
- assert.Equal(t, true, call.Arguments[2])
- assert.Equal(t, 1, call.ReturnArguments[0])
- assert.Equal(t, "two", call.ReturnArguments[1])
- assert.Equal(t, true, call.ReturnArguments[2])
- assert.Equal(t, 2, call.Repeatability)
- assert.Nil(t, call.WaitFor)
+ require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
- }
+ call := mockedService.ExpectedCalls[0]
+ assert.Equal(t, "TheExampleMethod", call.Method)
+ assert.Equal(t, "A", call.Arguments[0])
+ assert.Equal(t, "B", call.Arguments[1])
+ assert.Equal(t, true, call.Arguments[2])
+ assert.Equal(t, 1, call.ReturnArguments[0])
+ assert.Equal(t, "two", call.ReturnArguments[1])
+ assert.Equal(t, true, call.ReturnArguments[2])
+ assert.Equal(t, 2, call.Repeatability)
+ assert.Nil(t, call.WaitFor)
}
func Test_Mock_Return_Times(t *testing.T) {
@@ -289,24 +429,24 @@ func Test_Mock_Return_Times(t *testing.T) {
// make a test impl object
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
- mockedService.On("TheExampleMethod", "A", "B", true).Return(1, "two", true).Times(5)
-
- // ensure the call was created
- if assert.Equal(t, 1, len(mockedService.ExpectedCalls)) {
- call := mockedService.ExpectedCalls[0]
+ c := mockedService.
+ On("TheExampleMethod", "A", "B", true).
+ Return(1, "two", true).
+ Times(5)
- assert.Equal(t, "TheExampleMethod", call.Method)
- assert.Equal(t, "A", call.Arguments[0])
- assert.Equal(t, "B", call.Arguments[1])
- assert.Equal(t, true, call.Arguments[2])
- assert.Equal(t, 1, call.ReturnArguments[0])
- assert.Equal(t, "two", call.ReturnArguments[1])
- assert.Equal(t, true, call.ReturnArguments[2])
- assert.Equal(t, 5, call.Repeatability)
- assert.Nil(t, call.WaitFor)
+ require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
- }
+ call := mockedService.ExpectedCalls[0]
+ assert.Equal(t, "TheExampleMethod", call.Method)
+ assert.Equal(t, "A", call.Arguments[0])
+ assert.Equal(t, "B", call.Arguments[1])
+ assert.Equal(t, true, call.Arguments[2])
+ assert.Equal(t, 1, call.ReturnArguments[0])
+ assert.Equal(t, "two", call.ReturnArguments[1])
+ assert.Equal(t, true, call.ReturnArguments[2])
+ assert.Equal(t, 5, call.Repeatability)
+ assert.Nil(t, call.WaitFor)
}
func Test_Mock_Return_Nothing(t *testing.T) {
@@ -314,20 +454,19 @@ func Test_Mock_Return_Nothing(t *testing.T) {
// make a test impl object
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
- assert.Equal(t, mockedService.On("TheExampleMethod", "A", "B", true).Return(), &mockedService.Mock)
+ c := mockedService.
+ On("TheExampleMethod", "A", "B", true).
+ Return()
- // ensure the call was created
- if assert.Equal(t, 1, len(mockedService.ExpectedCalls)) {
- call := mockedService.ExpectedCalls[0]
+ require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
- assert.Equal(t, "TheExampleMethod", call.Method)
- assert.Equal(t, "A", call.Arguments[0])
- assert.Equal(t, "B", call.Arguments[1])
- assert.Equal(t, true, call.Arguments[2])
- assert.Equal(t, 0, len(call.ReturnArguments))
-
- }
+ call := mockedService.ExpectedCalls[0]
+ assert.Equal(t, "TheExampleMethod", call.Method)
+ assert.Equal(t, "A", call.Arguments[0])
+ assert.Equal(t, "B", call.Arguments[1])
+ assert.Equal(t, true, call.Arguments[2])
+ assert.Equal(t, 0, len(call.ReturnArguments))
}
func Test_Mock_findExpectedCall(t *testing.T) {
@@ -452,8 +591,13 @@ func Test_Mock_Called_For_Bounded_Repeatability(t *testing.T) {
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
- mockedService.On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3).Return(5, "6", true).Once()
- mockedService.On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3).Return(-1, "hi", false)
+ mockedService.
+ On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3).
+ Return(5, "6", true).
+ Once()
+ mockedService.
+ On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3).
+ Return(-1, "hi", false)
returnArguments1 := mockedService.Called(1, 2, 3)
returnArguments2 := mockedService.Called(1, 2, 3)
@@ -651,7 +795,9 @@ func Test_Mock_AssertCalled_WithAnythingOfTypeArgument(t *testing.T) {
var mockedService *TestExampleImplementation = new(TestExampleImplementation)
- mockedService.On("Test_Mock_AssertCalled_WithAnythingOfTypeArgument", Anything, Anything, Anything).Return()
+ mockedService.
+ On("Test_Mock_AssertCalled_WithAnythingOfTypeArgument", Anything, Anything, Anything).
+ Return()
mockedService.Called(1, "two", []uint8("three"))
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/.gitignore b/Godeps/_workspace/src/github.com/throttled/throttled/.gitignore
deleted file mode 100644
index c2a6499b4..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/.gitignore
+++ /dev/null
@@ -1,10 +0,0 @@
-.DS_Store
-*.swp
-*.swo
-*.test
-examples/interval/interval
-examples/interval-vary/interval-vary
-examples/interval-many/interval-many
-examples/memstats/memstats
-examples/rate-limit/rate-limit
-examples/custom/custom
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/.travis.yml b/Godeps/_workspace/src/github.com/throttled/throttled/.travis.yml
deleted file mode 100644
index 1b2427202..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/.travis.yml
+++ /dev/null
@@ -1,10 +0,0 @@
-sudo: false
-language: go
-
-go:
- - 1.2
- - tip
-
-install: go get -t ./...
-
-script: go test -v -short ./...
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/LICENSE b/Godeps/_workspace/src/github.com/throttled/throttled/LICENSE
deleted file mode 100644
index f9616483e..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/LICENSE
+++ /dev/null
@@ -1,12 +0,0 @@
-Copyright (c) 2014, Martin Angers and Contributors.
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
-
-* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
-
-* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
-
-* Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/README.md b/Godeps/_workspace/src/github.com/throttled/throttled/README.md
deleted file mode 100644
index 0954c808a..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/README.md
+++ /dev/null
@@ -1,80 +0,0 @@
-# Throttled [![build status](https://secure.travis-ci.org/throttled/throttled.png)](http://travis-ci.org/throttled/throttled) [![GoDoc](https://godoc.org/github.com/throttled/throttled?status.png)](http://godoc.org/github.com/throttled/throttled)
-
-Package throttled implements different throttling strategies for controlling
-access to HTTP handlers.
-
-*As of July 27, 2015, the package is now located under its own GitHub organization, please adjust your imports to `github.com/throttled/throttled`.*
-
-## Installation
-
-`go get github.com/throttled/throttled/...`
-
-## Interval
-
-The Interval function creates a throttler that allows requests to go through at
-a controlled, constant interval. The interval may be applied to all requests
-(vary argument == nil) or independently based on vary-by criteria.
-
-For example:
-
- th := throttled.Interval(throttled.PerSec(10), 100, &throttled.VaryBy{Path: true}, 50)
- h := th.Throttle(myHandler)
- http.ListenAndServe(":9000", h)
-
-Creates a throttler that will allow a request each 100ms (10 requests per second), with
-a buffer of 100 exceeding requests before dropping requests with a status code 429 (by
-default, configurable using th.DeniedHandler or the package-global DefaultDeniedHandler
-variable). Different paths will be throttled independently, so that /path_a and /path_b
-both can serve 10 requests per second. The last argument, 50, indicates the maximum number
-of keys that the throttler will keep in memory.
-
-## MemStats
-
-The MemStats function creates a throttler that allows requests to go through only if
-the memory statistics of the current process are below specified thresholds.
-
-For example:
-
- th := throttled.MemStats(throttled.MemThresholds(&runtime.MemStats{NumGC: 10}, 10*time.Millisecond)
- h := th.Throttle(myHandler)
- http.ListenAndServe(":9000", h)
-
-Creates a throttler that will allow requests to go through until the number of garbage
-collections reaches the initial number + 10 (the MemThresholds function creates absolute
-memory stats thresholds from offsets). The second argument, 10ms, indicates the refresh
-rate of the memory stats.
-
-## RateLimit
-
-The RateLimit function creates a throttler that allows a certain number of requests in
-a given time window, as is often implemented in public RESTful APIs.
-
-For example:
-
- th := throttled.RateLimit(throttled.PerMin(30), &throttled.VaryBy{RemoteAddr: true}, store.NewMemStore(1000))
- h := th.Throttle(myHandler)
- http.ListenAndServe(":9000", h)
-
-Creates a throttler that will limit requests to 30 per minute, based on the remote address
-of the client, and will store the counter and remaining time of the current window in the
-provided memory store, limiting the number of keys to keep in memory to 1000. The store
-sub-package also provides a Redis-based Store implementations.
-
-The RateLimit throttler sets the expected X-RateLimit-* headers on the response, and
-also sets a Retry-After header when the limit is exceeded.
-
-## Documentation
-
-The API documentation is available as usual on [godoc.org][doc].
-
-There is also a [blog post explaining the package's usage on 0value.com][blog].
-
-Finally, many examples are provided in the /examples sub-folder of the repository.
-
-## License
-
-The [BSD 3-clause license][bsd]. Copyright (c) 2014 Martin Angers and Contributors.
-
-[doc]: http://godoc.org/github.com/throttled/throttled
-[blog]: http://0value.com/throttled--guardian-of-the-web-server
-[bsd]: http://opensource.org/licenses/BSD-3-Clause
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/common_test.go b/Godeps/_workspace/src/github.com/throttled/throttled/common_test.go
deleted file mode 100644
index ddb57fb1c..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/common_test.go
+++ /dev/null
@@ -1,65 +0,0 @@
-package throttled
-
-import (
- "fmt"
- "net/http"
- "net/http/httptest"
- "sync"
- "time"
-
- "github.com/PuerkitoBio/boom/commands"
-)
-
-type stats struct {
- sync.Mutex
- ok int
- dropped int
- ts []time.Time
-
- body func()
-}
-
-func (s *stats) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- if s.body != nil {
- s.body()
- }
- s.Lock()
- defer s.Unlock()
- s.ts = append(s.ts, time.Now())
- s.ok++
- w.WriteHeader(200)
-}
-
-func (s *stats) DeniedHTTP(w http.ResponseWriter, r *http.Request) {
- s.Lock()
- defer s.Unlock()
- s.dropped++
- w.WriteHeader(deniedStatus)
-}
-
-func (s *stats) Stats() (int, int, []time.Time) {
- s.Lock()
- defer s.Unlock()
- return s.ok, s.dropped, s.ts
-}
-
-func runTest(h http.Handler, b ...commands.Boom) []*commands.Report {
- srv := httptest.NewServer(h)
- defer srv.Close()
-
- var rpts []*commands.Report
- var wg sync.WaitGroup
- var mu sync.Mutex
- wg.Add(len(b))
- for i, bo := range b {
- bo.Req.Url = srv.URL + fmt.Sprintf("/%d", i)
- go func(bo commands.Boom) {
- mu.Lock()
- defer mu.Unlock()
- rpts = append(rpts, bo.Run())
- wg.Done()
- }(bo)
- }
- wg.Wait()
- return rpts
-}
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/delayer.go b/Godeps/_workspace/src/github.com/throttled/throttled/delayer.go
deleted file mode 100644
index e62ec9e86..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/delayer.go
+++ /dev/null
@@ -1,109 +0,0 @@
-package throttled
-
-import "time"
-
-// The Quota interface defines the method to implement to describe
-// a time-window quota, as required by the RateLimit throttler.
-type Quota interface {
- // Quota returns a number of requests allowed, and a duration.
- Quota() (int, time.Duration)
-}
-
-// The Delayer interface defines the method to implement to describe
-// a delay as required by the Interval throttler.
-type Delayer interface {
- // Delay returns a duration.
- Delay() time.Duration
-}
-
-// PerSec represents a number of requests per second.
-type PerSec int
-
-// Delay returns the duration to wait before the next request can go through,
-// so that PerSec(n) == n requests per second at regular intervals.
-func (ps PerSec) Delay() time.Duration {
- if ps <= 0 {
- return 0
- }
- return time.Duration(1.0 / float64(ps) * float64(time.Second))
-}
-
-// Quota returns the number of requests allowed in a 1 second time window,
-// so that PerSec(n) == n requests allowed per second.
-func (ps PerSec) Quota() (int, time.Duration) {
- return int(ps), time.Second
-}
-
-// PerMin represents a number of requests per minute.
-type PerMin int
-
-// Delay returns the duration to wait before the next request can go through,
-// so that PerMin(n) == n requests per minute at regular intervals.
-func (pm PerMin) Delay() time.Duration {
- if pm <= 0 {
- return 0
- }
- return time.Duration(1.0 / float64(pm) * float64(time.Minute))
-}
-
-// Quota returns the number of requests allowed in a 1 minute time window,
-// so that PerMin(n) == n requests allowed per minute.
-func (pm PerMin) Quota() (int, time.Duration) {
- return int(pm), time.Minute
-}
-
-// PerHour represents a number of requests per hour.
-type PerHour int
-
-// Delay returns the duration to wait before the next request can go through,
-// so that PerHour(n) == n requests per hour at regular intervals.
-func (ph PerHour) Delay() time.Duration {
- if ph <= 0 {
- return 0
- }
- return time.Duration(1.0 / float64(ph) * float64(time.Hour))
-}
-
-// Quota returns the number of requests allowed in a 1 hour time window,
-// so that PerHour(n) == n requests allowed per hour.
-func (ph PerHour) Quota() (int, time.Duration) {
- return int(ph), time.Hour
-}
-
-// PerDay represents a number of requests per day.
-type PerDay int
-
-// Delay returns the duration to wait before the next request can go through,
-// so that PerDay(n) == n requests per day at regular intervals.
-func (pd PerDay) Delay() time.Duration {
- if pd <= 0 {
- return 0
- }
- return time.Duration(1.0 / float64(pd) * float64(24*time.Hour))
-}
-
-// Quota returns the number of requests allowed in a 1 day time window,
-// so that PerDay(n) == n requests allowed per day.
-func (pd PerDay) Quota() (int, time.Duration) {
- return int(pd), 24 * time.Hour
-}
-
-// D represents a custom delay.
-type D time.Duration
-
-// Delay returns the duration to wait before the next request can go through,
-// which is the custom duration represented by the D value.
-func (d D) Delay() time.Duration {
- return time.Duration(d)
-}
-
-// Q represents a custom quota.
-type Q struct {
- Requests int
- Window time.Duration
-}
-
-// Quota returns the number of requests allowed and the custom time window.
-func (q Q) Quota() (int, time.Duration) {
- return q.Requests, q.Window
-}
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/delayer_test.go b/Godeps/_workspace/src/github.com/throttled/throttled/delayer_test.go
deleted file mode 100644
index 822978e5d..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/delayer_test.go
+++ /dev/null
@@ -1,65 +0,0 @@
-package throttled
-
-import (
- "testing"
- "time"
-)
-
-func TestDelayer(t *testing.T) {
- cases := []struct {
- in Delayer
- out time.Duration
- }{
- 0: {PerSec(1), time.Second},
- 1: {PerSec(2), 500 * time.Millisecond},
- 2: {PerSec(4), 250 * time.Millisecond},
- 3: {PerSec(5), 200 * time.Millisecond},
- 4: {PerSec(10), 100 * time.Millisecond},
- 5: {PerSec(100), 10 * time.Millisecond},
- 6: {PerSec(3), 333333333 * time.Nanosecond},
- 7: {PerMin(1), time.Minute},
- 8: {PerMin(2), 30 * time.Second},
- 9: {PerMin(4), 15 * time.Second},
- 10: {PerMin(5), 12 * time.Second},
- 11: {PerMin(10), 6 * time.Second},
- 12: {PerMin(60), time.Second},
- 13: {PerHour(1), time.Hour},
- 14: {PerHour(2), 30 * time.Minute},
- 15: {PerHour(4), 15 * time.Minute},
- 16: {PerHour(60), time.Minute},
- 17: {PerHour(120), 30 * time.Second},
- 18: {D(time.Second), time.Second},
- 19: {D(5 * time.Minute), 5 * time.Minute},
- 20: {PerSec(200), 5 * time.Millisecond},
- 21: {PerDay(24), time.Hour},
- }
- for i, c := range cases {
- got := c.in.Delay()
- if got != c.out {
- t.Errorf("%d: expected %s, got %s", i, c.out, got)
- }
- }
-}
-
-func TestQuota(t *testing.T) {
- cases := []struct {
- q Quota
- reqs int
- win time.Duration
- }{
- 0: {PerSec(10), 10, time.Second},
- 1: {PerMin(30), 30, time.Minute},
- 2: {PerHour(124), 124, time.Hour},
- 3: {PerDay(1), 1, 24 * time.Hour},
- 4: {Q{148, 17 * time.Second}, 148, 17 * time.Second},
- }
- for i, c := range cases {
- r, w := c.q.Quota()
- if r != c.reqs {
- t.Errorf("%d: expected %d requests, got %d", i, c.reqs, r)
- }
- if w != c.win {
- t.Errorf("%d: expected %s window, got %s", i, c.win, w)
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/doc.go b/Godeps/_workspace/src/github.com/throttled/throttled/doc.go
deleted file mode 100644
index a83b0aca4..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/doc.go
+++ /dev/null
@@ -1,77 +0,0 @@
-// Package throttled implements different throttling strategies for controlling
-// access to HTTP handlers.
-//
-// Installation
-//
-// go get github.com/throttled/throttled/...
-//
-// Inverval
-//
-// The Interval function creates a throttler that allows requests to go through at
-// a controlled, constant interval. The interval may be applied to all requests
-// (vary argument == nil) or independently based on vary-by criteria.
-//
-// For example:
-//
-// th := throttled.Interval(throttled.PerSec(10), 100, &throttled.VaryBy{Path: true}, 50)
-// h := th.Throttle(myHandler)
-// http.ListenAndServe(":9000", h)
-//
-// Creates a throttler that will allow a request each 100ms (10 requests per second), with
-// a buffer of 100 exceeding requests before dropping requests with a status code 429 (by
-// default, configurable using th.DeniedHandler or the package-global DefaultDeniedHandler
-// variable). Different paths will be throttled independently, so that /path_a and /path_b
-// both can serve 10 requests per second. The last argument, 50, indicates the maximum number
-// of keys that the throttler will keep in memory.
-//
-// MemStats
-//
-// The MemStats function creates a throttler that allows requests to go through only if
-// the memory statistics of the current process are below specified thresholds.
-//
-// For example:
-//
-// th := throttled.MemStats(throttled.MemThresholds(&runtime.MemStats{NumGC: 10}, 10*time.Millisecond)
-// h := th.Throttle(myHandler)
-// http.ListenAndServe(":9000", h)
-//
-// Creates a throttler that will allow requests to go through until the number of garbage
-// collections reaches the initial number + 10 (the MemThresholds function creates absolute
-// memory stats thresholds from offsets). The second argument, 10ms, indicates the refresh
-// rate of the memory stats.
-//
-// RateLimit
-//
-// The RateLimit function creates a throttler that allows a certain number of requests in
-// a given time window, as is often implemented in public RESTful APIs.
-//
-// For example:
-//
-// th := throttled.RateLimit(throttled.PerMin(30), &throttled.VaryBy{RemoteAddr: true}, store.NewMemStore(1000))
-// h := th.Throttle(myHandler)
-// http.ListenAndServe(":9000", h)
-//
-// Creates a throttler that will limit requests to 30 per minute, based on the remote address
-// of the client, and will store the counter and remaining time of the current window in the
-// provided memory store, limiting the number of keys to keep in memory to 1000. The store
-// sub-package also provides a Redis-based Store implementations.
-//
-// The RateLimit throttler sets the expected X-RateLimit-* headers on the response, and
-// also sets a Retry-After header when the limit is exceeded.
-//
-// Documentation
-//
-// The API documentation is available as usual on godoc.org:
-// http://godoc.org/github.com/throttled/throttled
-//
-// There is also a blog post explaining the package's usage on 0value.com:
-// http://0value.com/throttled--guardian-of-the-web-server
-//
-// Finally, many examples are provided in the /examples sub-folder of the repository.
-//
-// License
-//
-// The BSD 3-clause license. Copyright (c) 2014 Martin Angers and Contributors.
-// http://opensource.org/licenses/BSD-3-Clause
-//
-package throttled
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/examples/README.md b/Godeps/_workspace/src/github.com/throttled/throttled/examples/README.md
deleted file mode 100644
index 6b12dad20..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/examples/README.md
+++ /dev/null
@@ -1,12 +0,0 @@
-# Examples
-
-This directory contains examples for all the throttlers implemented by the throttled package, as well as an example of a custom limiter.
-
-* custom/ : implements a custom limiter that allows requests to path /a on even seconds, and on path /b on odd seconds.
-* interval-many/ : implements a common interval throttler to control two different handlers, one for path /a and another for path /b, so that requests to any one of the handlers go through at the specified interval.
-* interval-vary/ : implements an interval throttler that varies by path, so that requests to each different path goes through at the specified interval.
-* interval/ : implements an interval throttler so that any request goes through at the specified interval, regardless of path or any other criteria.
-* memstats/ : implements a memory-usage throttler that limits access based on current memory statistics.
-* rate-limit/ : implements a rate-limiter throttler that varies by path, so that the number of requests allowed are counted based on the requested path.
-
-Each example app supports a number of command-line flags. Run the example with the -h flag to display usage and defaults.
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/examples/custom/main.go b/Godeps/_workspace/src/github.com/throttled/throttled/examples/custom/main.go
deleted file mode 100644
index 4a3fe119c..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/examples/custom/main.go
+++ /dev/null
@@ -1,90 +0,0 @@
-package main
-
-import (
- "flag"
- "fmt"
- "log"
- "math/rand"
- "net/http"
- "sync"
- "time"
-
- "github.com/throttled/throttled"
-)
-
-var (
- delayRes = flag.Duration("delay-response", 0, "delay the response by a random duration between 0 and this value")
- output = flag.String("output", "v", "type of output, one of `v`erbose, `q`uiet, `ok`-only, `ko`-only")
-)
-
-// Custom limiter: allow requests to the /a path on even seconds only, and
-// allow access to the /b path on odd seconds only.
-//
-// Yes this is absurd. A more realistic case could be to allow requests to some
-// contest page only during a limited time window.
-type customLimiter struct {
-}
-
-func (c *customLimiter) Start() {
- // No-op
-}
-
-func (c *customLimiter) Limit(w http.ResponseWriter, r *http.Request) (<-chan bool, error) {
- s := time.Now().Second()
- ch := make(chan bool, 1)
- ok := (r.URL.Path == "/a" && s%2 == 0) || (r.URL.Path == "/b" && s%2 != 0)
- ch <- ok
- if *output == "v" {
- log.Printf("Custom Limiter: Path=%s, Second=%d; ok? %v", r.URL.Path, s, ok)
- }
- return ch, nil
-}
-
-func main() {
- flag.Parse()
-
- var h http.Handler
- var ok, ko int
- var mu sync.Mutex
-
- // Keep the start time to print since-time
- start := time.Now()
- // Create the custom throttler using our custom limiter
- t := throttled.Custom(&customLimiter{})
- // Set its denied handler
- t.DeniedHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if *output == "v" || *output == "ko" {
- log.Printf("KO: %s", time.Since(start))
- }
- throttled.DefaultDeniedHandler.ServeHTTP(w, r)
- mu.Lock()
- defer mu.Unlock()
- ko++
- })
- // Throttle the OK handler
- rand.Seed(time.Now().Unix())
- h = t.Throttle(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if *output == "v" || *output == "ok" {
- log.Printf("ok: %s", time.Since(start))
- }
- if *delayRes > 0 {
- wait := time.Duration(rand.Intn(int(*delayRes)))
- time.Sleep(wait)
- }
- w.WriteHeader(200)
- mu.Lock()
- defer mu.Unlock()
- ok++
- }))
-
- // Print stats once in a while
- go func() {
- for _ = range time.Tick(10 * time.Second) {
- mu.Lock()
- log.Printf("ok: %d, ko: %d", ok, ko)
- mu.Unlock()
- }
- }()
- fmt.Println("server listening on port 9000")
- http.ListenAndServe(":9000", h)
-}
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/examples/interval-many/main.go b/Godeps/_workspace/src/github.com/throttled/throttled/examples/interval-many/main.go
deleted file mode 100644
index d0add9fb2..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/examples/interval-many/main.go
+++ /dev/null
@@ -1,79 +0,0 @@
-package main
-
-import (
- "flag"
- "fmt"
- "log"
- "math/rand"
- "net/http"
- "sync"
- "time"
-
- "github.com/throttled/throttled"
-)
-
-var (
- delay = flag.Duration("delay", 200*time.Millisecond, "delay between calls")
- bursts = flag.Int("bursts", 10, "number of bursts allowed")
- delayRes = flag.Duration("delay-response", 0, "delay the response by a random duration between 0 and this value")
- output = flag.String("output", "v", "type of output, one of `v`erbose, `q`uiet, `ok`-only, `ko`-only")
-)
-
-func main() {
- flag.Parse()
-
- var ok, ko int
- var mu sync.Mutex
-
- // Keep start time to log since-time
- start := time.Now()
-
- // Create the interval throttle
- t := throttled.Interval(throttled.D(*delay), *bursts, nil, 0)
- // Set its denied handler
- t.DeniedHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if *output == "v" || *output == "ko" {
- log.Printf("%s: KO: %s", r.URL.Path, time.Since(start))
- }
- throttled.DefaultDeniedHandler.ServeHTTP(w, r)
- mu.Lock()
- defer mu.Unlock()
- ko++
- })
- // Create OK handlers
- rand.Seed(time.Now().Unix())
- makeHandler := func(ix int) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if *output == "v" || *output == "ok" {
- log.Printf("handler %d: %s: ok: %s", ix, r.URL.Path, time.Since(start))
- }
- if *delayRes > 0 {
- wait := time.Duration(rand.Intn(int(*delayRes)))
- time.Sleep(wait)
- }
- w.WriteHeader(200)
- mu.Lock()
- defer mu.Unlock()
- ok++
- })
- }
- // Throttle them using the same interval throttler
- h1 := t.Throttle(makeHandler(1))
- h2 := t.Throttle(makeHandler(2))
-
- // Handle two paths
- mux := http.NewServeMux()
- mux.Handle("/a", h1)
- mux.Handle("/b", h2)
-
- // Print stats once in a while
- go func() {
- for _ = range time.Tick(10 * time.Second) {
- mu.Lock()
- log.Printf("ok: %d, ko: %d", ok, ko)
- mu.Unlock()
- }
- }()
- fmt.Println("server listening on port 9000")
- http.ListenAndServe(":9000", mux)
-}
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/examples/interval-vary/main.go b/Godeps/_workspace/src/github.com/throttled/throttled/examples/interval-vary/main.go
deleted file mode 100644
index 439d4ad8b..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/examples/interval-vary/main.go
+++ /dev/null
@@ -1,74 +0,0 @@
-package main
-
-import (
- "flag"
- "fmt"
- "log"
- "math/rand"
- "net/http"
- "sync"
- "time"
-
- "github.com/throttled/throttled"
-)
-
-var (
- delay = flag.Duration("delay", 200*time.Millisecond, "delay between calls")
- bursts = flag.Int("bursts", 10, "number of bursts allowed")
- maxkeys = flag.Int("max-keys", 1000, "maximum number of keys")
- delayRes = flag.Duration("delay-response", 0, "delay the response by a random duration between 0 and this value")
- output = flag.String("output", "v", "type of output, one of `v`erbose, `q`uiet, `ok`-only, `ko`-only")
-)
-
-func main() {
- flag.Parse()
-
- var h http.Handler
- var ok, ko int
- var mu sync.Mutex
-
- // Keep the start time to print since-time
- start := time.Now()
-
- // Create the interval throttler
- t := throttled.Interval(throttled.D(*delay), *bursts, &throttled.VaryBy{
- Path: true,
- }, *maxkeys)
- // Set the denied handler
- t.DeniedHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if *output == "v" || *output == "ko" {
- log.Printf("KO: %s", time.Since(start))
- }
- throttled.DefaultDeniedHandler.ServeHTTP(w, r)
- mu.Lock()
- defer mu.Unlock()
- ko++
- })
-
- // Throttle the OK handler
- rand.Seed(time.Now().Unix())
- h = t.Throttle(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if *output == "v" || *output == "ok" {
- log.Printf("%s: ok: %s", r.URL.Path, time.Since(start))
- }
- if *delayRes > 0 {
- wait := time.Duration(rand.Intn(int(*delayRes)))
- time.Sleep(wait)
- }
- w.WriteHeader(200)
- mu.Lock()
- defer mu.Unlock()
- ok++
- }))
-
- // Print stats once in a while
- go func() {
- for _ = range time.Tick(10 * time.Second) {
- mu.Lock()
- log.Printf("ok: %d, ko: %d", ok, ko)
- mu.Unlock()
- }
- }()
- fmt.Println("server listening on port 9000")
- http.ListenAndServe(":9000", h)
-}
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/examples/interval-vary/siege-urls b/Godeps/_workspace/src/github.com/throttled/throttled/examples/interval-vary/siege-urls
deleted file mode 100644
index 9a2d0d312..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/examples/interval-vary/siege-urls
+++ /dev/null
@@ -1,4 +0,0 @@
-http://localhost:9000/a
-http://localhost:9000/b
-http://localhost:9000/c
-
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/examples/interval/main.go b/Godeps/_workspace/src/github.com/throttled/throttled/examples/interval/main.go
deleted file mode 100644
index 7c6473346..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/examples/interval/main.go
+++ /dev/null
@@ -1,69 +0,0 @@
-package main
-
-import (
- "flag"
- "fmt"
- "log"
- "math/rand"
- "net/http"
- "sync"
- "time"
-
- "github.com/throttled/throttled"
-)
-
-var (
- delay = flag.Duration("delay", 200*time.Millisecond, "delay between calls")
- bursts = flag.Int("bursts", 10, "number of bursts allowed")
- delayRes = flag.Duration("delay-response", 0, "delay the response by a random duration between 0 and this value")
- output = flag.String("output", "v", "type of output, one of `v`erbose, `q`uiet, `ok`-only, `ko`-only")
-)
-
-func main() {
- flag.Parse()
-
- var h http.Handler
- var ok, ko int
- var mu sync.Mutex
-
- // Keep the start time to print since-time
- start := time.Now()
- // Create the interval throttler
- t := throttled.Interval(throttled.D(*delay), *bursts, nil, 0)
- // Set its denied handler
- t.DeniedHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if *output == "v" || *output == "ko" {
- log.Printf("KO: %s", time.Since(start))
- }
- throttled.DefaultDeniedHandler.ServeHTTP(w, r)
- mu.Lock()
- defer mu.Unlock()
- ko++
- })
- // Throttle the OK handler
- rand.Seed(time.Now().Unix())
- h = t.Throttle(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if *output == "v" || *output == "ok" {
- log.Printf("ok: %s", time.Since(start))
- }
- if *delayRes > 0 {
- wait := time.Duration(rand.Intn(int(*delayRes)))
- time.Sleep(wait)
- }
- w.WriteHeader(200)
- mu.Lock()
- defer mu.Unlock()
- ok++
- }))
-
- // Print stats once in a while
- go func() {
- for _ = range time.Tick(10 * time.Second) {
- mu.Lock()
- log.Printf("ok: %d, ko: %d", ok, ko)
- mu.Unlock()
- }
- }()
- fmt.Println("server listening on port 9000")
- http.ListenAndServe(":9000", h)
-}
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/examples/memstats/main.go b/Godeps/_workspace/src/github.com/throttled/throttled/examples/memstats/main.go
deleted file mode 100644
index 719fea01b..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/examples/memstats/main.go
+++ /dev/null
@@ -1,97 +0,0 @@
-package main
-
-import (
- "flag"
- "fmt"
- "io/ioutil"
- "log"
- "math/rand"
- "net/http"
- "runtime"
- "sync"
- "time"
-
- "github.com/throttled/throttled"
-)
-
-var (
- numgc = flag.Int("gc", 0, "number of GC runs")
- mallocs = flag.Int("mallocs", 0, "number of mallocs")
- total = flag.Int("total", 0, "total number of bytes allocated")
- allocs = flag.Int("allocs", 0, "number of bytes allocated")
- refrate = flag.Duration("refresh", 0, "refresh rate of the memory stats")
- delayRes = flag.Duration("delay-response", 0, "delay the response by a random duration between 0 and this value")
- output = flag.String("output", "v", "type of output, one of `v`erbose, `q`uiet, `ok`-only, `ko`-only")
-)
-
-func main() {
- flag.Parse()
-
- var h http.Handler
- var ok, ko int
- var mu sync.Mutex
-
- // Keep the start time to print since-time
- start := time.Now()
- // Create the thresholds struct
- thresh := throttled.MemThresholds(&runtime.MemStats{
- NumGC: uint32(*numgc),
- Mallocs: uint64(*mallocs),
- TotalAlloc: uint64(*total),
- Alloc: uint64(*allocs),
- })
- if *output != "q" {
- log.Printf("thresholds: NumGC: %d, Mallocs: %d, Alloc: %dKb, Total: %dKb", thresh.NumGC, thresh.Mallocs, thresh.Alloc/1024, thresh.TotalAlloc/1024)
- }
- // Create the MemStats throttler
- t := throttled.MemStats(thresh, *refrate)
- // Set its denied handler
- t.DeniedHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if *output == "v" || *output == "ko" {
- log.Printf("KO: %s", time.Since(start))
- }
- throttled.DefaultDeniedHandler.ServeHTTP(w, r)
- mu.Lock()
- defer mu.Unlock()
- ko++
- })
-
- // Throttle the OK handler
- rand.Seed(time.Now().Unix())
- h = t.Throttle(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if *output == "v" || *output == "ok" {
- log.Printf("ok: %s", time.Since(start))
- }
- if *delayRes > 0 {
- wait := time.Duration(rand.Intn(int(*delayRes)))
- time.Sleep(wait)
- }
- // Read the whole file in memory, to actually use 64Kb (instead of streaming to w)
- b, err := ioutil.ReadFile("test-file")
- if err != nil {
- throttled.Error(w, r, err)
- return
- }
- _, err = w.Write(b)
- if err != nil {
- throttled.Error(w, r, err)
- }
- mu.Lock()
- defer mu.Unlock()
- ok++
- }))
-
- // Print stats once in a while
- go func() {
- var mem runtime.MemStats
- for _ = range time.Tick(10 * time.Second) {
- mu.Lock()
- runtime.ReadMemStats(&mem)
- log.Printf("ok: %d, ko: %d", ok, ko)
- log.Printf("TotalAllocs: %d Kb, Allocs: %d Kb, Mallocs: %d, NumGC: %d", mem.TotalAlloc/1024, mem.Alloc/1024, mem.Mallocs, mem.NumGC)
- mu.Unlock()
- }
- }()
- fmt.Println("server listening on port 9000")
- http.ListenAndServe(":9000", h)
-}
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/examples/memstats/test-file b/Godeps/_workspace/src/github.com/throttled/throttled/examples/memstats/test-file
deleted file mode 100644
index c97c12f9b..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/examples/memstats/test-file
+++ /dev/null
Binary files differ
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/examples/rate-limit/main.go b/Godeps/_workspace/src/github.com/throttled/throttled/examples/rate-limit/main.go
deleted file mode 100644
index b7b31529a..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/examples/rate-limit/main.go
+++ /dev/null
@@ -1,101 +0,0 @@
-package main
-
-import (
- "flag"
- "fmt"
- "log"
- "math/rand"
- "net/http"
- "sync"
- "time"
-
- "github.com/garyburd/redigo/redis"
- "github.com/throttled/throttled"
- "github.com/throttled/throttled/store"
-)
-
-var (
- requests = flag.Int("requests", 10, "number of requests allowed in the time window")
- window = flag.Duration("window", time.Minute, "time window for the limit of requests")
- storeType = flag.String("store", "mem", "store to use, one of `mem` or `redis` (on default localhost port)")
- delayRes = flag.Duration("delay-response", 0, "delay the response by a random duration between 0 and this value")
- output = flag.String("output", "v", "type of output, one of `v`erbose, `q`uiet, `ok`-only, `ko`-only")
-)
-
-func main() {
- flag.Parse()
-
- var h http.Handler
- var ok, ko int
- var mu sync.Mutex
- var st throttled.Store
-
- // Keep the start time to print since-time
- start := time.Now()
- // Create the rate-limit store
- switch *storeType {
- case "mem":
- st = store.NewMemStore(0)
- case "redis":
- st = store.NewRedisStore(setupRedis(), "throttled:", 0)
- default:
- log.Fatalf("unsupported store: %s", *storeType)
- }
- // Create the rate-limit throttler, varying on path
- t := throttled.RateLimit(throttled.Q{Requests: *requests, Window: *window}, &throttled.VaryBy{
- Path: true,
- }, st)
-
- // Set its denied handler
- t.DeniedHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if *output == "v" || *output == "ko" {
- log.Printf("KO: %s", time.Since(start))
- }
- throttled.DefaultDeniedHandler.ServeHTTP(w, r)
- mu.Lock()
- defer mu.Unlock()
- ko++
- })
-
- // Throttle the OK handler
- rand.Seed(time.Now().Unix())
- h = t.Throttle(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if *output == "v" || *output == "ok" {
- log.Printf("ok: %s", time.Since(start))
- }
- if *delayRes > 0 {
- wait := time.Duration(rand.Intn(int(*delayRes)))
- time.Sleep(wait)
- }
- w.WriteHeader(200)
- mu.Lock()
- defer mu.Unlock()
- ok++
- }))
-
- // Print stats once in a while
- go func() {
- for _ = range time.Tick(10 * time.Second) {
- mu.Lock()
- log.Printf("ok: %d, ko: %d", ok, ko)
- mu.Unlock()
- }
- }()
- fmt.Println("server listening on port 9000")
- http.ListenAndServe(":9000", h)
-}
-
-func setupRedis() *redis.Pool {
- pool := &redis.Pool{
- MaxIdle: 3,
- IdleTimeout: 30 * time.Second,
- Dial: func() (redis.Conn, error) {
- return redis.Dial("tcp", ":6379")
- },
- TestOnBorrow: func(c redis.Conn, t time.Time) error {
- _, err := c.Do("PING")
- return err
- },
- }
- return pool
-}
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/interval.go b/Godeps/_workspace/src/github.com/throttled/throttled/interval.go
deleted file mode 100644
index 628a5593e..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/interval.go
+++ /dev/null
@@ -1,164 +0,0 @@
-package throttled
-
-import (
- "net/http"
- "sync"
- "time"
-
- "github.com/golang/groupcache/lru"
-)
-
-// Static check to ensure that the interval limiters implement the Limiter interface.
-var _ Limiter = (*intervalVaryByLimiter)(nil)
-var _ Limiter = (*intervalLimiter)(nil)
-
-// Interval creates a throttler that controls the requests so that they
-// go through at a constant interval. The interval is specified by the
-// delay argument, and convenience types such as PerSec can be used to
-// express the interval in a more expressive way, i.e. PerSec(10) means
-// 10 requests per second or one request each 100ms, PerMin(30) means
-// 30 requests per minute or on request each 2s, etc.
-//
-// The bursts argument indicates the number of exceeding requests that may
-// be queued up waiting to be processed. Requests that overflow the queue
-// are dropped and go through the denied handler, which may be specified
-// on the Throttler and that defaults to the package-global variable
-// DefaultDeniedHandler.
-//
-// The vary argument indicates the criteria to use to group the requests,
-// so that the interval applies to the requests in the same group (e.g. based on
-// the path, or the remote IP address, etc.). If this argument is nil, the
-// interval applies to all requests going through this throttler.
-//
-// The maxKeys indicates the maximum number of keys to keep in memory to apply the interval,
-// when a vary argument is specified. A LRU algorithm is used to remove older keys.
-//
-func Interval(delay Delayer, bursts int, vary *VaryBy, maxKeys int) *Throttler {
- var l Limiter
- if vary != nil {
- if maxKeys < 1 {
- maxKeys = 1
- }
- l = &intervalVaryByLimiter{
- delay: delay.Delay(),
- bursts: bursts,
- vary: vary,
- maxKeys: maxKeys,
- }
- } else {
- l = &intervalLimiter{
- delay: delay.Delay(),
- bursts: bursts,
- }
- }
- return &Throttler{
- limiter: l,
- }
-}
-
-// The intervalLimiter struct implements an interval limiter with no vary-by
-// criteria.
-type intervalLimiter struct {
- delay time.Duration
- bursts int
-
- bucket chan chan bool
-}
-
-// Start initializes the limiter for execution.
-func (il *intervalLimiter) Start() {
- if il.bursts < 0 {
- il.bursts = 0
- }
- il.bucket = make(chan chan bool, il.bursts)
- go process(il.bucket, il.delay)
-}
-
-// Limit is called for each request to the throttled handler. It tries to
-// queue the request to allow it to run at the given interval, but if the
-// queue is full, the request is denied access.
-func (il *intervalLimiter) Limit(w http.ResponseWriter, r *http.Request) (<-chan bool, error) {
- ch := make(chan bool, 1)
- select {
- case il.bucket <- ch:
- return ch, nil
- default:
- ch <- false
- return ch, nil
- }
-}
-
-// The intervalVaryByLimiter struct implements an interval limiter with a vary-by
-// criteria.
-type intervalVaryByLimiter struct {
- delay time.Duration
- bursts int
- vary *VaryBy
-
- lock sync.RWMutex
- keys *lru.Cache
- maxKeys int
-}
-
-// Start initializes the limiter for execution.
-func (il *intervalVaryByLimiter) Start() {
- if il.bursts < 0 {
- il.bursts = 0
- }
- il.keys = lru.New(il.maxKeys)
- il.keys.OnEvicted = il.stopProcess
-}
-
-// Limit is called for each request to the throttled handler. It tries to
-// queue the request for the vary-by key to allow it to run at the given interval,
-// but if the queue is full, the request is denied access.
-func (il *intervalVaryByLimiter) Limit(w http.ResponseWriter, r *http.Request) (<-chan bool, error) {
- ch := make(chan bool, 1)
- key := il.vary.Key(r)
-
- il.lock.RLock()
- item, ok := il.keys.Get(key)
- if !ok {
- // Create the key, bucket, start goroutine
- // First release the read lock and acquire a write lock
- il.lock.RUnlock()
- il.lock.Lock()
- // Create the bucket, add the key
- bucket := make(chan chan bool, il.bursts)
- il.keys.Add(key, bucket)
- // Start the goroutine to process this bucket
- go process(bucket, il.delay)
- item = bucket
- // Release the write lock, acquire the read lock
- il.lock.Unlock()
- il.lock.RLock()
- }
- defer il.lock.RUnlock()
- bucket := item.(chan chan bool)
- select {
- case bucket <- ch:
- return ch, nil
- default:
- ch <- false
- return ch, nil
- }
-}
-
-// process loops through the queued requests for a key's bucket, and sends
-// requests through at the given interval.
-func process(bucket chan chan bool, delay time.Duration) {
- after := time.After(0)
- for v := range bucket {
- <-after
- // Let the request go through
- v <- true
- // Wait the required duration
- after = time.After(delay)
- }
-}
-
-// stopProcess is called when a key is removed from the LRU cache so that its
-// accompanying goroutine is correctly released.
-func (il *intervalVaryByLimiter) stopProcess(key lru.Key, value interface{}) {
- close(value.(chan chan bool))
-}
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/interval_test.go b/Godeps/_workspace/src/github.com/throttled/throttled/interval_test.go
deleted file mode 100644
index bc584e134..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/interval_test.go
+++ /dev/null
@@ -1,114 +0,0 @@
-package throttled
-
-import (
- "net/http"
- "testing"
-
- "github.com/PuerkitoBio/boom/commands"
-)
-
-func TestInterval(t *testing.T) {
- if testing.Short() {
- t.Skip()
- }
- cases := []struct {
- n int
- c int
- rps int
- bursts int
- }{
- 0: {60, 10, 20, 100},
- 1: {300, 20, 100, 100},
- 2: {10, 10, 1, 10},
- 3: {1000, 100, 1000, 100},
- }
- for i, c := range cases {
- // Setup the stats handler
- st := &stats{}
- // Create the throttler
- th := Interval(PerSec(c.rps), c.bursts, nil, 0)
- th.DeniedHandler = http.HandlerFunc(st.DeniedHTTP)
- b := commands.Boom{
- Req: &commands.ReqOpts{},
- N: c.n,
- C: c.c,
- Output: "quiet",
- }
- // Run the test
- rpts := runTest(th.Throttle(st), b)
- // Assert results
- for _, rpt := range rpts {
- assertRPS(t, i, c.rps, rpt)
- }
- assertStats(t, i, st, rpts)
- }
-}
-
-func TestIntervalVary(t *testing.T) {
- if testing.Short() {
- t.Skip()
- }
- cases := []struct {
- n int
- c int
- urls int
- rps int
- bursts int
- }{
- 0: {60, 10, 3, 20, 100},
- 1: {300, 20, 3, 100, 100},
- 2: {10, 10, 3, 1, 10},
- 3: {500, 10, 2, 1000, 100},
- }
- for i, c := range cases {
- // Setup the stats handler
- st := &stats{}
- // Create the throttler
- th := Interval(PerSec(c.rps), c.bursts, nil, 0)
- th.DeniedHandler = http.HandlerFunc(st.DeniedHTTP)
- var booms []commands.Boom
- for j := 0; j < c.urls; j++ {
- booms = append(booms, commands.Boom{
- Req: &commands.ReqOpts{},
- N: c.n,
- C: c.c,
- Output: "quiet",
- })
- }
- // Run the test
- rpts := runTest(th.Throttle(st), booms...)
- // Assert results
- for _, rpt := range rpts {
- assertRPS(t, i, c.rps, rpt)
- }
- assertStats(t, i, st, rpts)
- }
-}
-
-func assertRPS(t *testing.T, ix int, exp int, rpt *commands.Report) {
- wigglef := 0.2 * float64(exp)
- if rpt.SuccessRPS < float64(exp)-wigglef || rpt.SuccessRPS > float64(exp)+wigglef {
- t.Errorf("%d: expected RPS to be around %d, got %f", ix, exp, rpt.SuccessRPS)
- }
-}
-
-func assertStats(t *testing.T, ix int, st *stats, rpts []*commands.Report) {
- ok, ko, _ := st.Stats()
- var twos, fives, max int
- for _, rpt := range rpts {
- twos += rpt.StatusCodeDist[200]
- fives += rpt.StatusCodeDist[deniedStatus]
- if len(rpt.StatusCodeDist) > max {
- max = len(rpt.StatusCodeDist)
- }
- }
- if ok != twos {
- t.Errorf("%d: expected %d status 200, got %d", ix, twos, ok)
- }
- if ko != fives {
- t.Errorf("%d: expected %d status 429, got %d", ix, fives, ok)
- }
- if max > 2 {
- t.Errorf("%d: expected at most 2 different status codes, got %d", ix, max)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/memstats.go b/Godeps/_workspace/src/github.com/throttled/throttled/memstats.go
deleted file mode 100644
index bd2765630..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/memstats.go
+++ /dev/null
@@ -1,214 +0,0 @@
-package throttled
-
-import (
- "net/http"
- "runtime"
- "sync"
- "time"
-)
-
-// Static check to ensure that memStatsLimiter implements Limiter.
-var _ Limiter = (*memStatsLimiter)(nil)
-
-// The memStatsLimiter struct implements a limiter based on the memory statistics
-// of the current process.
-type memStatsLimiter struct {
- thresholds *runtime.MemStats
- refreshRate time.Duration
-
- lockStats sync.RWMutex
- stats runtime.MemStats
-}
-
-// MemStats creates a Throttler based on the memory statistics of the current process.
-// Any combination of any (non-array) integer field of Go's runtime.MemStats structure
-// can be used as thresholds to deny a request.
-//
-// As soon as one threshold value is reached, the access is denied. If the value can
-// decrease, access will be allowed again once it gets back under the threshold value.
-// Denied requests go through the denied handler, which may be specified on the Throttler
-// and that defaults to the package-global variable DefaultDeniedHandler.
-//
-// Thresholds must be specified in absolute numbers (i.e. NumGC = 10 means stop once the
-// NumGC reaches 10, not when the current value increments by 10), and zero values are
-// ignored.
-//
-// The refreshRate indicates the frequency at which the process' memory stats are refreshed,
-// and 0 means on each request.
-//
-func MemStats(thresholds *runtime.MemStats, refreshRate time.Duration) *Throttler {
- return &Throttler{
- limiter: &memStatsLimiter{
- thresholds: thresholds,
- refreshRate: refreshRate,
- },
- }
-}
-
-// Start initialized the limiter for execution.
-func (m *memStatsLimiter) Start() {
- // Make sure there is an initial MemStats reading
- runtime.ReadMemStats(&m.stats)
- if m.refreshRate > 0 {
- go m.refresh()
- }
-}
-
-// refresh runs in a separate goroutine and refreshes the memory statistics
-// at regular intervals.
-func (m *memStatsLimiter) refresh() {
- c := time.Tick(m.refreshRate)
- for _ = range c {
- m.lockStats.Lock()
- runtime.ReadMemStats(&m.stats)
- m.lockStats.Unlock()
- }
-}
-
-// Limit is called for each request to the throttled handler. It checks if
-// the request can go through by checking the memory thresholds, and signals it
-// via the returned channel.
-func (m *memStatsLimiter) Limit(w http.ResponseWriter, r *http.Request) (<-chan bool, error) {
- ch := make(chan bool, 1)
- // Check if memory thresholds are reached
- ch <- m.allow()
- return ch, nil
-}
-
-// allow compares the current memory stats with the thresholds, and returns
-// false if any threshold is reached.
-func (m *memStatsLimiter) allow() bool {
- m.lockStats.RLock()
- mem := m.stats
- m.lockStats.RUnlock()
- // If refreshRate == 0, then read on every request.
- if m.refreshRate == 0 {
- runtime.ReadMemStats(&mem)
- }
- ok := true
- checkStat(m.thresholds.Alloc, mem.Alloc, &ok)
- checkStat(m.thresholds.BuckHashSys, mem.BuckHashSys, &ok)
- checkStat(m.thresholds.Frees, mem.Frees, &ok)
- checkStat(m.thresholds.GCSys, mem.GCSys, &ok)
- checkStat(m.thresholds.HeapAlloc, mem.HeapAlloc, &ok)
- checkStat(m.thresholds.HeapIdle, mem.HeapIdle, &ok)
- checkStat(m.thresholds.HeapInuse, mem.HeapInuse, &ok)
- checkStat(m.thresholds.HeapObjects, mem.HeapObjects, &ok)
- checkStat(m.thresholds.HeapReleased, mem.HeapReleased, &ok)
- checkStat(m.thresholds.HeapSys, mem.HeapSys, &ok)
- checkStat(m.thresholds.LastGC, mem.LastGC, &ok)
- checkStat(m.thresholds.Lookups, mem.Lookups, &ok)
- checkStat(m.thresholds.MCacheInuse, mem.MCacheInuse, &ok)
- checkStat(m.thresholds.MCacheSys, mem.MCacheSys, &ok)
- checkStat(m.thresholds.MSpanInuse, mem.MSpanInuse, &ok)
- checkStat(m.thresholds.MSpanSys, mem.MSpanSys, &ok)
- checkStat(m.thresholds.Mallocs, mem.Mallocs, &ok)
- checkStat(m.thresholds.NextGC, mem.NextGC, &ok)
- checkStat(uint64(m.thresholds.NumGC), uint64(mem.NumGC), &ok)
- checkStat(m.thresholds.OtherSys, mem.OtherSys, &ok)
- checkStat(m.thresholds.PauseTotalNs, mem.PauseTotalNs, &ok)
- checkStat(m.thresholds.StackInuse, mem.StackInuse, &ok)
- checkStat(m.thresholds.StackSys, mem.StackSys, &ok)
- checkStat(m.thresholds.Sys, mem.Sys, &ok)
- checkStat(m.thresholds.TotalAlloc, mem.TotalAlloc, &ok)
- return ok
-}
-
-// Checks the threshold value against the actual value, and assigns false
-// to the boolean pointer if the threshold is reached.
-func checkStat(threshold, actual uint64, ok *bool) {
- if !*ok {
- return
- }
- if threshold > 0 {
- if actual >= threshold {
- *ok = false
- }
- }
-}
-
-// MemThresholds is a convenience function to create a thresholds memory stats from
-// offsets to apply to the current memory stats. Zero values in the offset stats
-// are left to 0 in the resulting thresholds memory stats value.
-//
-// The return value may be used as thresholds argument to the MemStats function.
-func MemThresholds(offset *runtime.MemStats) *runtime.MemStats {
- var mem, thr runtime.MemStats
- runtime.ReadMemStats(&mem)
- if offset.Alloc > 0 {
- thr.Alloc = mem.Alloc + offset.Alloc
- }
- if offset.BuckHashSys > 0 {
- thr.BuckHashSys = mem.BuckHashSys + offset.BuckHashSys
- }
- if offset.Frees > 0 {
- thr.Frees = mem.Frees + offset.Frees
- }
- if offset.GCSys > 0 {
- thr.GCSys = mem.GCSys + offset.GCSys
- }
- if offset.HeapAlloc > 0 {
- thr.HeapAlloc = mem.HeapAlloc + offset.HeapAlloc
- }
- if offset.HeapIdle > 0 {
- thr.HeapIdle = mem.HeapIdle + offset.HeapIdle
- }
- if offset.HeapInuse > 0 {
- thr.HeapInuse = mem.HeapInuse + offset.HeapInuse
- }
- if offset.HeapObjects > 0 {
- thr.HeapObjects = mem.HeapObjects + offset.HeapObjects
- }
- if offset.HeapReleased > 0 {
- thr.HeapReleased = mem.HeapReleased + offset.HeapReleased
- }
- if offset.HeapSys > 0 {
- thr.HeapSys = mem.HeapSys + offset.HeapSys
- }
- if offset.LastGC > 0 {
- thr.LastGC = mem.LastGC + offset.LastGC
- }
- if offset.Lookups > 0 {
- thr.Lookups = mem.Lookups + offset.Lookups
- }
- if offset.MCacheInuse > 0 {
- thr.MCacheInuse = mem.MCacheInuse + offset.MCacheInuse
- }
- if offset.MCacheSys > 0 {
- thr.MCacheSys = mem.MCacheSys + offset.MCacheSys
- }
- if offset.MSpanInuse > 0 {
- thr.MSpanInuse = mem.MSpanInuse + offset.MSpanInuse
- }
- if offset.MSpanSys > 0 {
- thr.MSpanSys = mem.MSpanSys + offset.MSpanSys
- }
- if offset.Mallocs > 0 {
- thr.Mallocs = mem.Mallocs + offset.Mallocs
- }
- if offset.NextGC > 0 {
- thr.NextGC = mem.NextGC + offset.NextGC
- }
- if offset.NumGC > 0 {
- thr.NumGC = mem.NumGC + offset.NumGC
- }
- if offset.OtherSys > 0 {
- thr.OtherSys = mem.OtherSys + offset.OtherSys
- }
- if offset.PauseTotalNs > 0 {
- thr.PauseTotalNs = mem.PauseTotalNs + offset.PauseTotalNs
- }
- if offset.StackInuse > 0 {
- thr.StackInuse = mem.StackInuse + offset.StackInuse
- }
- if offset.StackSys > 0 {
- thr.StackSys = mem.StackSys + offset.StackSys
- }
- if offset.Sys > 0 {
- thr.Sys = mem.Sys + offset.Sys
- }
- if offset.TotalAlloc > 0 {
- thr.TotalAlloc = mem.TotalAlloc + offset.TotalAlloc
- }
- return &thr
-}
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/memstats_test.go b/Godeps/_workspace/src/github.com/throttled/throttled/memstats_test.go
deleted file mode 100644
index 2b8faa721..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/memstats_test.go
+++ /dev/null
@@ -1,64 +0,0 @@
-package throttled
-
-import (
- "net/http"
- "runtime"
- "testing"
- "time"
-
- "github.com/PuerkitoBio/boom/commands"
-)
-
-func TestMemStats(t *testing.T) {
- if testing.Short() {
- t.Skip()
- }
- cases := []struct {
- n int
- c int
- gc uint32
- total uint64
- rate time.Duration
- }{
- 0: {1000, 10, 3, 0, 0},
- 1: {200, 10, 0, 600000, 0},
- 2: {500, 10, 2, 555555, 10 * time.Millisecond},
- }
- for i, c := range cases {
- // Setup the stats handler
- st := &stats{}
- // Create the throttler
- limit := MemThresholds(&runtime.MemStats{NumGC: c.gc, TotalAlloc: c.total})
- th := MemStats(limit, c.rate)
- th.DeniedHandler = http.HandlerFunc(st.DeniedHTTP)
- // Run the test
- b := commands.Boom{
- Req: &commands.ReqOpts{},
- N: c.n,
- C: c.c,
- Output: "quiet",
- }
- rpts := runTest(th.Throttle(st), b)
- // Assert results
- assertStats(t, i, st, rpts)
- assertMem(t, i, limit)
- }
-}
-
-func assertMem(t *testing.T, ix int, limit *runtime.MemStats) {
- var mem runtime.MemStats
- runtime.ReadMemStats(&mem)
- if mem.NumGC < limit.NumGC {
- t.Errorf("%d: expected gc to be at least %d, got %d", ix, limit.NumGC, mem.NumGC)
- }
- if mem.TotalAlloc < limit.TotalAlloc {
- t.Errorf("%d: expected total alloc to be at least %dKb, got %dKb", ix, limit.TotalAlloc/1024, mem.TotalAlloc/1024)
- }
-}
-
-func BenchmarkReadMemStats(b *testing.B) {
- var mem runtime.MemStats
- for i := 0; i < b.N; i++ {
- runtime.ReadMemStats(&mem)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/misc/pre-commit b/Godeps/_workspace/src/github.com/throttled/throttled/misc/pre-commit
deleted file mode 100644
index 88b61bfde..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/misc/pre-commit
+++ /dev/null
@@ -1,38 +0,0 @@
-#!/bin/sh
-# Copyright 2012 The Go Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style
-# license that can be found in the LICENSE file.
-
-# git gofmt pre-commit hook
-#
-# To use, store as .git/hooks/pre-commit inside your repository and make sure
-# it has execute permissions.
-#
-# This script does not handle file names that contain spaces.
-
-# golint is purely informational, it doesn't fail with exit code != 0 if it finds something,
-# because it may find a lot of false positives. Just print out its result for information.
-echo "lint result (informational only):"
-echo
-golint .
-
-# go vet returns 1 if an error was found. Exit the hook with this exit code.
-go vet ./...
-vetres=$?
-
-# Check for gofmt problems and report if any.
-gofiles=$(git diff --cached --name-only --diff-filter=ACM | grep '.go$')
-[ -z "$gofiles" ] && echo "EXIT $vetres" && exit $vetres
-
-unformatted=$(gofmt -l $gofiles)
-[ -z "$unformatted" ] && echo "EXIT $vetres" && exit $vetres
-
-# Some files are not gofmt'd. Print message and fail.
-
-echo >&2 "Go files must be formatted with gofmt. Please run:"
-for fn in $unformatted; do
- echo >&2 " gofmt -w $PWD/$fn"
-done
-
-echo "EXIT 1"
-exit 1
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/rate.go b/Godeps/_workspace/src/github.com/throttled/throttled/rate.go
deleted file mode 100644
index d7a7de6d7..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/rate.go
+++ /dev/null
@@ -1,116 +0,0 @@
-package throttled
-
-import (
- "math"
- "net/http"
- "strconv"
- "time"
-)
-
-// Static check to ensure that rateLimiter implements Limiter.
-var _ Limiter = (*rateLimiter)(nil)
-
-// RateLimit creates a throttler that limits the number of requests allowed
-// in a certain time window defined by the Quota q. The q parameter specifies
-// the requests per time window, and it is silently set to at least 1 request
-// and at least a 1 second window if it is less than that. The time window
-// starts when the first request is made outside an existing window. Fractions
-// of seconds are not supported, they are truncated.
-//
-// The vary parameter indicates what criteria should be used to group requests
-// for which the limit must be applied (ex.: rate limit based on the remote address).
-// See varyby.go for the various options.
-//
-// The specified store is used to keep track of the request count and the
-// time remaining in the window. The throttled package comes with some stores
-// in the throttled/store package. Custom stores can be created too, by implementing
-// the Store interface.
-//
-// Requests that bust the rate limit are denied access and go through the denied handler,
-// which may be specified on the Throttler and that defaults to the package-global
-// variable DefaultDeniedHandler.
-//
-// The rate limit throttler sets the following headers on the response:
-//
-// X-RateLimit-Limit : quota
-// X-RateLimit-Remaining : number of requests remaining in the current window
-// X-RateLimit-Reset : seconds before a new window
-//
-// Additionally, if the request was denied access, the following header is added:
-//
-// Retry-After : seconds before the caller should retry
-//
-func RateLimit(q Quota, vary *VaryBy, store Store) *Throttler {
- // Extract requests and window
- reqs, win := q.Quota()
-
- // Create and return the throttler
- return &Throttler{
- limiter: &rateLimiter{
- reqs: reqs,
- window: win,
- vary: vary,
- store: store,
- },
- }
-}
-
-// The rate limiter implements limiting the request to a certain quota
-// based on the vary-by criteria. State is saved in the store.
-type rateLimiter struct {
- reqs int
- window time.Duration
- vary *VaryBy
- store Store
-}
-
-// Start initializes the limiter for execution.
-func (r *rateLimiter) Start() {
- if r.reqs < 1 {
- r.reqs = 1
- }
- if r.window < time.Second {
- r.window = time.Second
- }
-}
-
-// Limit is called for each request to the throttled handler. It checks if
-// the request can go through and signals it via the returned channel.
-// It returns an error if the operation fails.
-func (r *rateLimiter) Limit(w http.ResponseWriter, req *http.Request) (<-chan bool, error) {
- // Create return channel and initialize
- ch := make(chan bool, 1)
- ok := true
- key := r.vary.Key(req)
-
- // Get the current count and remaining seconds
- cnt, secs, err := r.store.Incr(key, r.window)
- // Handle the possible situations: error, begin new window, or increment current window.
- switch {
- case err != nil && err != ErrNoSuchKey:
- // An unexpected error occurred
- return nil, err
- case err == ErrNoSuchKey || secs <= 0:
- // Reset counter
- if err := r.store.Reset(key, r.window); err != nil {
- return nil, err
- }
- cnt = 1
- secs = int(r.window.Seconds())
- default:
- // If the limit is reached, deny access
- if cnt > r.reqs {
- ok = false
- }
- }
- // Set rate-limit headers
- w.Header().Add("X-RateLimit-Limit", strconv.Itoa(r.reqs))
- w.Header().Add("X-RateLimit-Remaining", strconv.Itoa(int(math.Max(float64(r.reqs-cnt), 0))))
- w.Header().Add("X-RateLimit-Reset", strconv.Itoa(secs))
- if !ok {
- w.Header().Add("Retry-After", strconv.Itoa(secs))
- }
- // Send response via the return channel
- ch <- ok
- return ch, nil
-}
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/rate_test.go b/Godeps/_workspace/src/github.com/throttled/throttled/rate_test.go
deleted file mode 100644
index 67dea74b1..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/rate_test.go
+++ /dev/null
@@ -1,101 +0,0 @@
-package throttled
-
-import (
- "net/http"
- "net/http/httptest"
- "strconv"
- "testing"
- "time"
-)
-
-const deniedStatus = 429
-
-// Simple memory store for tests, unsafe for concurrent access
-type mapStore struct {
- cnt map[string]int
- ts map[string]time.Time
-}
-
-func newMapStore() *mapStore {
- return &mapStore{
- make(map[string]int),
- make(map[string]time.Time),
- }
-}
-func (ms *mapStore) Incr(key string, window time.Duration) (int, int, error) {
- if _, ok := ms.cnt[key]; !ok {
- return 0, 0, ErrNoSuchKey
- }
- ms.cnt[key]++
- ts := ms.ts[key]
- return ms.cnt[key], RemainingSeconds(ts, window), nil
-}
-func (ms *mapStore) Reset(key string, win time.Duration) error {
- ms.cnt[key] = 1
- ms.ts[key] = time.Now().UTC()
- return nil
-}
-
-func TestRateLimit(t *testing.T) {
- quota := Q{5, 5 * time.Second}
- cases := []struct {
- limit, remain, reset, status int
- }{
- 0: {5, 4, 5, 200},
- 1: {5, 3, 4, 200},
- 2: {5, 2, 4, 200},
- 3: {5, 1, 3, 200},
- 4: {5, 0, 3, 200},
- 5: {5, 0, 2, deniedStatus},
- }
- // Limit the requests to 2 per second
- th := Interval(PerSec(2), 0, nil, 0)
- // Rate limit
- rl := RateLimit(quota, nil, newMapStore())
- // Create the stats
- st := &stats{}
- // Create the handler
- h := th.Throttle(rl.Throttle(st))
-
- // Start the server
- srv := httptest.NewServer(h)
- defer srv.Close()
- for i, c := range cases {
- callRateLimited(t, i, c.limit, c.remain, c.reset, c.status, srv.URL)
- }
- // Wait 3 seconds and call again, should start a new window
- time.Sleep(3 * time.Second)
- callRateLimited(t, len(cases), 5, 4, 5, 200, srv.URL)
-}
-
-func callRateLimited(t *testing.T, i, limit, remain, reset, status int, url string) {
- res, err := http.Get(url)
- if err != nil {
- t.Fatal(err)
- }
- defer res.Body.Close()
- // Assert status code
- if status != res.StatusCode {
- t.Errorf("%d: expected status %d, got %d", i, status, res.StatusCode)
- }
- // Assert headers
- if v := res.Header.Get("X-RateLimit-Limit"); v != strconv.Itoa(limit) {
- t.Errorf("%d: expected limit header to be %d, got %s", i, limit, v)
- }
- if v := res.Header.Get("X-RateLimit-Remaining"); v != strconv.Itoa(remain) {
- t.Errorf("%d: expected remain header to be %d, got %s", i, remain, v)
- }
- // Allow 1 second wiggle room
- v := res.Header.Get("X-RateLimit-Reset")
- vi, _ := strconv.Atoi(v)
- if vi < reset-1 || vi > reset+1 {
- t.Errorf("%d: expected reset header to be close to %d, got %d", i, reset, vi)
- }
- if status == deniedStatus {
- v := res.Header.Get("Retry-After")
- vi, _ := strconv.Atoi(v)
- if vi < reset-1 || vi > reset+1 {
- t.Errorf("%d: expected retry after header to be close to %d, got %d", i, reset, vi)
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/store.go b/Godeps/_workspace/src/github.com/throttled/throttled/store.go
deleted file mode 100644
index 760fe2b69..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/store.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package throttled
-
-import (
- "errors"
- "time"
-)
-
-// The error returned if the key does not exist in the Store.
-var ErrNoSuchKey = errors.New("throttled: no such key")
-
-// Store is the interface to implement to store the RateLimit state (number
-// of requests per key, time-to-live or creation timestamp).
-type Store interface {
- // Incr increments the count for the specified key and returns the new value along
- // with the number of seconds remaining. It may return an error
- // if the operation fails.
- //
- // The method may return ErrNoSuchKey if the key to increment does not exist,
- // in which case Reset will be called to initialize the value.
- Incr(string, time.Duration) (int, int, error)
-
- // Reset resets the key to 1 with the specified window duration. It must create the
- // key if it doesn't exist. It returns an error if it fails.
- Reset(string, time.Duration) error
-}
-
-// RemainingSeconds is a helper function that returns the number of seconds
-// remaining from an absolute timestamp in UTC.
-func RemainingSeconds(ts time.Time, window time.Duration) int {
- return int((window - time.Now().UTC().Sub(ts)).Seconds())
-}
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/store/doc.go b/Godeps/_workspace/src/github.com/throttled/throttled/store/doc.go
deleted file mode 100644
index adb4618d3..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/store/doc.go
+++ /dev/null
@@ -1,2 +0,0 @@
-// Package store offers a memory-based and a Redis-based throttled.Store implementation.
-package store
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/store/mem.go b/Godeps/_workspace/src/github.com/throttled/throttled/store/mem.go
deleted file mode 100644
index e220dfe81..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/store/mem.go
+++ /dev/null
@@ -1,90 +0,0 @@
-package store
-
-import (
- "sync"
- "time"
-
- "github.com/golang/groupcache/lru"
- "github.com/throttled/throttled"
-)
-
-// memStore implements an in-memory Store.
-type memStore struct {
- sync.Mutex
- keys *lru.Cache
- m map[string]*counter
-}
-
-// NewMemStore creates a new MemStore. If maxKeys > 0, the number of different keys
-// is restricted to the specified amount. In this case, it uses an LRU algorithm to
-// evict older keys to make room for newer ones. If a request is made for a key that
-// has been evicted, it will be processed as if its count was 0, possibly allowing requests
-// that should be denied.
-//
-// If maxKeys <= 0, there is no limit on the number of keys, which may use an unbounded amount of
-// memory depending on the server's load.
-//
-// The MemStore is only for single-process rate-limiting. To share the rate limit state
-// among multiple instances of the web server, use a database- or key-value-based
-// store.
-//
-func NewMemStore(maxKeys int) throttled.Store {
- var m *memStore
- if maxKeys > 0 {
- m = &memStore{
- keys: lru.New(maxKeys),
- }
- } else {
- m = &memStore{
- m: make(map[string]*counter),
- }
- }
- return m
-}
-
-// A counter represents a single entry in the MemStore.
-type counter struct {
- n int
- ts time.Time
-}
-
-// Incr increments the counter for the specified key. It returns the new
-// count value and the remaining number of seconds, or an error.
-func (ms *memStore) Incr(key string, window time.Duration) (int, int, error) {
- ms.Lock()
- defer ms.Unlock()
- var c *counter
- if ms.keys != nil {
- v, _ := ms.keys.Get(key)
- if v != nil {
- c = v.(*counter)
- }
- } else {
- c = ms.m[key]
- }
- if c == nil {
- c = &counter{0, time.Now().UTC()}
- }
- c.n++
- if ms.keys != nil {
- ms.keys.Add(key, c)
- } else {
- ms.m[key] = c
- }
- return c.n, throttled.RemainingSeconds(c.ts, window), nil
-}
-
-// Reset resets the counter for the specified key. It sets the count
-// to 1 and initializes the timestamp with the current time, in UTC.
-// It returns an error if the operation fails.
-func (ms *memStore) Reset(key string, win time.Duration) error {
- ms.Lock()
- defer ms.Unlock()
- c := &counter{1, time.Now().UTC()}
- if ms.keys != nil {
- ms.keys.Add(key, c)
- } else {
- ms.m[key] = c
- }
- return nil
-}
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/store/mem_test.go b/Godeps/_workspace/src/github.com/throttled/throttled/store/mem_test.go
deleted file mode 100644
index e8ef8d0da..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/store/mem_test.go
+++ /dev/null
@@ -1,43 +0,0 @@
-package store
-
-import (
- "testing"
- "time"
-)
-
-func TestMemStore(t *testing.T) {
- st := NewMemStore(0)
- win := time.Second
-
- // Reset stores a key with count of 1, current timestamp
- err := st.Reset("k", time.Second)
- if err != nil {
- t.Errorf("expected reset to return nil, got %s", err)
- }
- cnt, sec1, _ := st.Incr("k", win)
- if cnt != 2 {
- t.Errorf("expected reset+incr to set count to 2, got %d", cnt)
- }
-
- // Incr increments the key, keeps same timestamp
- cnt, sec2, err := st.Incr("k", win)
- if err != nil {
- t.Errorf("expected 2nd incr to return nil error, got %s", err)
- }
- if cnt != 3 {
- t.Errorf("expected 2nd incr to return 3, got %d", cnt)
- }
- if sec1 != sec2 {
- t.Errorf("expected 2nd incr to return %d secs, got %d", sec1, sec2)
- }
-
- // Reset on existing key brings it back to 1, new timestamp
- err = st.Reset("k", win)
- if err != nil {
- t.Errorf("expected reset on existing key to return nil, got %s", err)
- }
- cnt, _, _ = st.Incr("k", win)
- if cnt != 2 {
- t.Errorf("expected last reset+incr to return 2, got %d", cnt)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/store/redis.go b/Godeps/_workspace/src/github.com/throttled/throttled/store/redis.go
deleted file mode 100644
index 6347eb6fc..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/store/redis.go
+++ /dev/null
@@ -1,85 +0,0 @@
-package store
-
-import (
- "time"
-
- "github.com/garyburd/redigo/redis"
- "github.com/throttled/throttled"
-)
-
-// redisStore implements a Redis-based store.
-type redisStore struct {
- pool *redis.Pool
- prefix string
- db int
-}
-
-// NewRedisStore creates a new Redis-based store, using the provided pool to get its
-// connections. The keys will have the specified keyPrefix, which may be an empty string,
-// and the database index specified by db will be selected to store the keys.
-//
-func NewRedisStore(pool *redis.Pool, keyPrefix string, db int) throttled.Store {
- return &redisStore{
- pool: pool,
- prefix: keyPrefix,
- db: db,
- }
-}
-
-// Incr increments the specified key. If the key did not exist, it sets it to 1
-// and sets it to expire after the number of seconds specified by window.
-//
-// It returns the new count value and the number of remaining seconds, or an error
-// if the operation fails.
-func (r *redisStore) Incr(key string, window time.Duration) (int, int, error) {
- conn := r.pool.Get()
- defer conn.Close()
- if err := selectDB(r.db, conn); err != nil {
- return 0, 0, err
- }
- // Atomically increment and read the TTL.
- conn.Send("MULTI")
- conn.Send("INCR", r.prefix+key)
- conn.Send("TTL", r.prefix+key)
- vals, err := redis.Values(conn.Do("EXEC"))
- if err != nil {
- conn.Do("DISCARD")
- return 0, 0, err
- }
- var cnt, ttl int
- if _, err = redis.Scan(vals, &cnt, &ttl); err != nil {
- return 0, 0, err
- }
- // If there was no TTL set, then this is a newly created key (INCR creates the key
- // if it didn't exist), so set it to expire.
- if ttl == -1 {
- ttl = int(window.Seconds())
- _, err = conn.Do("EXPIRE", r.prefix+key, ttl)
- if err != nil {
- return 0, 0, err
- }
- }
- return cnt, ttl, nil
-}
-
-// Reset sets the value of the key to 1, and resets its time window.
-func (r *redisStore) Reset(key string, window time.Duration) error {
- conn := r.pool.Get()
- defer conn.Close()
- if err := selectDB(r.db, conn); err != nil {
- return err
- }
- _, err := redis.String(conn.Do("SET", r.prefix+key, "1", "EX", int(window.Seconds()), "NX"))
- return err
-}
-
-// Select the specified database index.
-func selectDB(db int, conn redis.Conn) error {
- // Select the specified database
- if db > 0 {
- if _, err := redis.String(conn.Do("SELECT", db)); err != nil {
- return err
- }
- }
- return nil
-}
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/store/redis_test.go b/Godeps/_workspace/src/github.com/throttled/throttled/store/redis_test.go
deleted file mode 100644
index a282d6d25..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/store/redis_test.go
+++ /dev/null
@@ -1,66 +0,0 @@
-package store
-
-import (
- "testing"
- "time"
-
- "github.com/garyburd/redigo/redis"
-)
-
-func getPool() *redis.Pool {
- pool := &redis.Pool{
- MaxIdle: 3,
- IdleTimeout: 30 * time.Second,
- Dial: func() (redis.Conn, error) {
- return redis.Dial("tcp", ":6379")
- },
- TestOnBorrow: func(c redis.Conn, t time.Time) error {
- _, err := c.Do("PING")
- return err
- },
- }
- return pool
-}
-
-func TestRedisStore(t *testing.T) {
- pool := getPool()
- c := pool.Get()
- if _, err := redis.String(c.Do("PING")); err != nil {
- c.Close()
- t.Skip("redis server not available on localhost port 6379")
- }
- st := NewRedisStore(pool, "throttled:", 1)
- win := 2 * time.Second
-
- // Incr increments the key, even if it does not exist
- cnt, secs, err := st.Incr("k", win)
- if err != nil {
- t.Errorf("expected initial incr to return nil error, got %s", err)
- }
- if cnt != 1 {
- t.Errorf("expected initial incr to return 1, got %d", cnt)
- }
- if secs != int(win.Seconds()) {
- t.Errorf("expected initial incr to return %d secs, got %d", int(win.Seconds()), secs)
- }
-
- // Waiting a second diminishes the remaining seconds
- time.Sleep(time.Second)
- _, sec2, _ := st.Incr("k", win)
- if sec2 != secs-1 {
- t.Errorf("expected 2nd incr after a 1s sleep to return %d secs, got %d", secs-1, sec2)
- }
-
- // Waiting a second so the key expires, Incr should set back to 1, initial secs
- time.Sleep(1100 * time.Millisecond)
- cnt, sec3, err := st.Incr("k", win)
- if err != nil {
- t.Errorf("expected last incr to return nil error, got %s", err)
- }
- if cnt != 1 {
- t.Errorf("expected last incr to return 1, got %d", cnt)
- }
- if sec3 != int(win.Seconds()) {
- t.Errorf("expected last incr to return %d secs, got %d", int(win.Seconds()), sec3)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/throttler.go b/Godeps/_workspace/src/github.com/throttled/throttled/throttler.go
deleted file mode 100644
index 06da13051..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/throttler.go
+++ /dev/null
@@ -1,86 +0,0 @@
-package throttled
-
-import (
- "net/http"
- "sync"
-)
-
-var (
- // DefaultDeniedHandler handles the requests that were denied access because
- // of a throttler. By default, returns a 429 status code with a
- // generic message.
- DefaultDeniedHandler = http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- http.Error(w, "limit exceeded", 429)
- }))
-
- // Error is the function to call when an error occurs on a throttled handler.
- // By default, returns a 500 status code with a generic message.
- Error = ErrorFunc(func(w http.ResponseWriter, r *http.Request, err error) {
- http.Error(w, "internal error", http.StatusInternalServerError)
- })
-)
-
-// ErrorFunc defines the function type for the Error variable.
-type ErrorFunc func(w http.ResponseWriter, r *http.Request, err error)
-
-// The Limiter interface defines the methods required to control access to a
-// throttled handler.
-type Limiter interface {
- Start()
- Limit(http.ResponseWriter, *http.Request) (<-chan bool, error)
-}
-
-// Custom creates a Throttler using the provided Limiter implementation.
-func Custom(l Limiter) *Throttler {
- return &Throttler{
- limiter: l,
- }
-}
-
-// A Throttler controls access to HTTP handlers using a Limiter.
-type Throttler struct {
- // DeniedHandler is called if the request is disallowed. If it is nil,
- // the DefaultDeniedHandler variable is used.
- DeniedHandler http.Handler
-
- limiter Limiter
- // The mutex protects the started flag
- mu sync.Mutex
- started bool
-}
-
-// Throttle wraps a HTTP handler so that its access is controlled by
-// the Throttler. It returns the Handler with the throttling logic.
-func (t *Throttler) Throttle(h http.Handler) http.Handler {
- dh := t.start()
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- ch, err := t.limiter.Limit(w, r)
- if err != nil {
- Error(w, r, err)
- return
- }
- ok := <-ch
- if ok {
- h.ServeHTTP(w, r)
- } else {
- dh.ServeHTTP(w, r)
- }
- })
-}
-
-// start starts the throttling and returns the effective denied handler to
-// use for requests that were denied access.
-func (t *Throttler) start() http.Handler {
- t.mu.Lock()
- defer t.mu.Unlock()
- // Get the effective denied handler
- dh := t.DeniedHandler
- if dh == nil {
- dh = DefaultDeniedHandler
- }
- if !t.started {
- t.limiter.Start()
- t.started = true
- }
- return dh
-}
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/varyby.go b/Godeps/_workspace/src/github.com/throttled/throttled/varyby.go
deleted file mode 100644
index 3b2cdb011..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/varyby.go
+++ /dev/null
@@ -1,78 +0,0 @@
-package throttled
-
-import (
- "bytes"
- "net/http"
- "strings"
-)
-
-// VaryBy defines the criteria to use to group requests.
-type VaryBy struct {
- // Vary by the RemoteAddr as specified by the net/http.Request field.
- RemoteAddr bool
-
- // Vary by the HTTP Method as specified by the net/http.Request field.
- Method bool
-
- // Vary by the URL's Path as specified by the Path field of the net/http.Request
- // URL field.
- Path bool
-
- // Vary by this list of header names, read from the net/http.Request Header field.
- Headers []string
-
- // Vary by this list of parameters, read from the net/http.Request FormValue method.
- Params []string
-
- // Vary by this list of cookie names, read from the net/http.Request Cookie method.
- Cookies []string
-
- // Use this separator string to concatenate the various criteria of the VaryBy struct.
- // Defaults to a newline character if empty (\n).
- Separator string
-
- // Custom specifies the custom-generated key to use for this request.
- // If not nil, the value returned by this function is used instead of any
- // VaryBy criteria.
- Custom func(r *http.Request) string
-}
-
-// Key returns the key for this request based on the criteria defined by the VaryBy struct.
-func (vb *VaryBy) Key(r *http.Request) string {
- var buf bytes.Buffer
-
- if vb == nil {
- return "" // Special case for no vary-by option
- }
- if vb.Custom != nil {
- // A custom key generator is specified
- return vb.Custom(r)
- }
- sep := vb.Separator
- if sep == "" {
- sep = "\n" // Separator defaults to newline
- }
- if vb.RemoteAddr {
- buf.WriteString(strings.ToLower(r.RemoteAddr) + sep)
- }
- if vb.Method {
- buf.WriteString(strings.ToLower(r.Method) + sep)
- }
- for _, h := range vb.Headers {
- buf.WriteString(strings.ToLower(r.Header.Get(h)) + sep)
- }
- if vb.Path {
- buf.WriteString(r.URL.Path + sep)
- }
- for _, p := range vb.Params {
- buf.WriteString(r.FormValue(p) + sep)
- }
- for _, c := range vb.Cookies {
- ck, err := r.Cookie(c)
- if err == nil {
- buf.WriteString(ck.Value)
- }
- buf.WriteString(sep) // Write the separator anyway, whether or not the cookie exists
- }
- return buf.String()
-}
diff --git a/Godeps/_workspace/src/github.com/throttled/throttled/varyby_test.go b/Godeps/_workspace/src/github.com/throttled/throttled/varyby_test.go
deleted file mode 100644
index 91b7ae0ae..000000000
--- a/Godeps/_workspace/src/github.com/throttled/throttled/varyby_test.go
+++ /dev/null
@@ -1,56 +0,0 @@
-package throttled
-
-import (
- "net/http"
- "net/url"
- "testing"
-)
-
-func TestVaryBy(t *testing.T) {
- u, err := url.Parse("http://localhost/test/path?q=s")
- if err != nil {
- panic(err)
- }
- ck := &http.Cookie{Name: "ssn", Value: "test"}
- cases := []struct {
- vb *VaryBy
- r *http.Request
- k string
- }{
- 0: {nil, &http.Request{}, ""},
- 1: {&VaryBy{RemoteAddr: true}, &http.Request{RemoteAddr: "::"}, "::\n"},
- 2: {
- &VaryBy{Method: true, Path: true},
- &http.Request{Method: "POST", URL: u},
- "post\n/test/path\n",
- },
- 3: {
- &VaryBy{Headers: []string{"Content-length"}},
- &http.Request{Header: http.Header{"Content-Type": []string{"text/plain"}, "Content-Length": []string{"123"}}},
- "123\n",
- },
- 4: {
- &VaryBy{Separator: ",", Method: true, Headers: []string{"Content-length"}, Params: []string{"q", "user"}},
- &http.Request{Method: "GET", Header: http.Header{"Content-Type": []string{"text/plain"}, "Content-Length": []string{"123"}}, Form: url.Values{"q": []string{"s"}, "pwd": []string{"secret"}, "user": []string{"test"}}},
- "get,123,s,test,",
- },
- 5: {
- &VaryBy{Cookies: []string{"ssn"}},
- &http.Request{Header: http.Header{"Cookie": []string{ck.String()}}},
- "test\n",
- },
- 6: {
- &VaryBy{Cookies: []string{"ssn"}, RemoteAddr: true, Custom: func(r *http.Request) string {
- return "blah"
- }},
- &http.Request{Header: http.Header{"Cookie": []string{ck.String()}}},
- "blah",
- },
- }
- for i, c := range cases {
- got := c.vb.Key(c.r)
- if got != c.k {
- t.Errorf("%d: expected '%s' (%d), got '%s' (%d)", i, c.k, len(c.k), got, len(got))
- }
- }
-}