From 0aee10e7d450d8d0b697f35fdf4cea49867e279f Mon Sep 17 00:00:00 2001 From: sam boyer Date: Tue, 23 Jan 2018 23:22:34 -0500 Subject: [PATCH 1/4] dep: Fix broken test from prune init --- .../testdata/harness_tests/init/glide/case4/final/Gopkg.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/cmd/dep/testdata/harness_tests/init/glide/case4/final/Gopkg.toml b/cmd/dep/testdata/harness_tests/init/glide/case4/final/Gopkg.toml index aaf78303..e3e66aac 100644 --- a/cmd/dep/testdata/harness_tests/init/glide/case4/final/Gopkg.toml +++ b/cmd/dep/testdata/harness_tests/init/glide/case4/final/Gopkg.toml @@ -2,3 +2,7 @@ [[constraint]] name = "github.com/sdboyer/deptestdos" version = "2.0.0" + +[prune] + go-tests = true + unused-packages = true From bd4a7ec7c5832d7c6386e7877a226d1385830f51 Mon Sep 17 00:00:00 2001 From: sam boyer Date: Tue, 23 Jan 2018 23:22:53 -0500 Subject: [PATCH 2/4] docs: Fix links in announce blog && intro --- docs/introduction.md | 2 +- website/blog/2018-01-23-announce-v0.4.0.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/introduction.md b/docs/introduction.md index c52d9347..0367ebd5 100644 --- a/docs/introduction.md +++ b/docs/introduction.md @@ -6,6 +6,6 @@ title: Getting Started Welcome! This is documentation for dep, the "official experiment" dependency management tool for the Go language. Dep is a tool intended primarily for use by developers, to support the work of actually writing and shipping code. It is _not_ intended for end users who are installing Go software - that's what `go get` does. -This site has both guides and reference documents. The guides are practical explanations of how to actually do things with dep, whereas the reference material provides deeper dives on specific topics. Of particular note is the [glossary](#glossary.md) - if you're unfamiliar with terminology used in this documentation, make sure to check there! +This site has both guides and reference documents. The guides are practical explanations of how to actually do things with dep, whereas the reference material provides deeper dives on specific topics. Of particular note is the [glossary](glossary.md) - if you're unfamiliar with terminology used in this documentation, make sure to check there! After [installing dep](installation.md), if you're using it for the first time, check out [Creating a New Project](new-project.md). Or, if you have an existing Go project that you want to convert to dep, [Migrating to Dep](migrating.md) is probably the place to start. \ No newline at end of file diff --git a/website/blog/2018-01-23-announce-v0.4.0.md b/website/blog/2018-01-23-announce-v0.4.0.md index ad94a092..14b86584 100644 --- a/website/blog/2018-01-23-announce-v0.4.0.md +++ b/website/blog/2018-01-23-announce-v0.4.0.md @@ -23,12 +23,12 @@ This site, which is automatically generated from the [docs directory](https://gi * New user guides - reference documentation is not what folks need when starting with a new tool. Step-by-step instructions are. Now [we have that](https://golang.github.io/dep/docs/introduction.html), and it caters to users who are not only new to dep, but also to Go in general. * Thematic organization of content - up until now, we were somewhat haphazardly flinging information into the FAQ. The body of documentation here is organized from the ground up, which will hopefully make it both more useful and easier to maintain. -* Versioning - all of the docs are snapshotted on each release, and users can [select the version of the docs](https://golang.github.io/dep/versions.html) they want to view. Ideally, everyone should always be able to use the latest version, but this at least means you're not penalized if that's not feasible for you/your organization. +* Versioning - docusaurus is capable of snapshotting doc versions on each release, and users will be able to select the version of the docs they want to view (though we've not enabled this just quite yet). Ideally, everyone should always be able to use the latest version, but this at least means you're not penalized if that's not feasible for you/your organization. * A blog - you're reading it! This is great, as it provides us a canonical place to circulate information about what's happening with the project. At the same time, the docs aren't quite comprehensive _yet_. There's more reference material and guides to be written. For example, we're still missing a guide for project maintainers on how to make releases that align well with dep's happy path. -Also, now that we have this whole docs apparatus, it would be particularly awesome if someone were to step up to help as a [docs maintainer](https://github.com/golang/dep/issues/629#issuecomment-359922251)! Also also, the CSS on this site is terrible, and +Also, now that we have this whole docs apparatus, it would be particularly awesome if someone were to step up to help as a [docs maintainer](https://github.com/golang/dep/issues/629#issuecomment-359922251)! (Also also, the CSS on this site is terrible, [please halp](https://github.com/golang/dep/issues/1558)!) ### The future From 7297a48ece4df1df5e88440fe70fd441de73e01e Mon Sep 17 00:00:00 2001 From: sam boyer Date: Tue, 23 Jan 2018 23:24:47 -0500 Subject: [PATCH 3/4] dep: Update CHANGELOG for release --- CHANGELOG.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dac5a2f5..3ae52753 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,12 @@ -# v0.4.0 (Unreleased) +# (next version) + +NEW FEATURES: + +BUG FIXES: + +IMPROVEMENTS: + +# v0.4.0 NEW FEATURES: * Add support for importing from [glock](https://github.com/robfig/glock) based projects. ([#1422](https://github.com/golang/dep/pull/1422) From 916906bed1151d03f38760936aba919cd85cb9b3 Mon Sep 17 00:00:00 2001 From: sam boyer Date: Tue, 23 Jan 2018 23:42:44 -0500 Subject: [PATCH 4/4] dep: Prune vendor using new pruning powers Also remove the now-superfluous `dep prune` call from vendor validation checks. --- hack/validate-vendor.bash | 3 +- .../github.com/Masterminds/semver/.travis.yml | 24 - .../Masterminds/semver/CHANGELOG.md | 17 - vendor/github.com/Masterminds/semver/Makefile | 36 - .../github.com/Masterminds/semver/README.md | 146 -- .../Masterminds/semver/appveyor.yml | 44 - .../Masterminds/semver/benchmark_test.go | 259 -- .../Masterminds/semver/collection_test.go | 46 - .../Masterminds/semver/constraints_test.go | 712 ------ .../Masterminds/semver/set_ops_test.go | 932 ------- .../Masterminds/semver/version_test.go | 310 --- vendor/github.com/Masterminds/vcs/.gitignore | 24 - vendor/github.com/Masterminds/vcs/.travis.yml | 29 - .../github.com/Masterminds/vcs/CHANGELOG.md | 148 -- vendor/github.com/Masterminds/vcs/Makefile | 41 - vendor/github.com/Masterminds/vcs/README.md | 48 - .../github.com/Masterminds/vcs/appveyor.yml | 26 - vendor/github.com/Masterminds/vcs/bzr_test.go | 328 --- .../github.com/Masterminds/vcs/errors_test.go | 36 - vendor/github.com/Masterminds/vcs/git_test.go | 599 ----- vendor/github.com/Masterminds/vcs/glide.yaml | 8 - vendor/github.com/Masterminds/vcs/hg_test.go | 332 --- .../github.com/Masterminds/vcs/repo_test.go | 74 - vendor/github.com/Masterminds/vcs/svn_test.go | 337 --- .../Masterminds/vcs/vcs_remote_lookup_test.go | 137 - vendor/github.com/armon/go-radix/.gitignore | 22 - vendor/github.com/armon/go-radix/.travis.yml | 3 - vendor/github.com/armon/go-radix/README.md | 38 - .../github.com/armon/go-radix/radix_test.go | 319 --- vendor/github.com/boltdb/bolt/.gitignore | 4 - vendor/github.com/boltdb/bolt/Makefile | 18 - vendor/github.com/boltdb/bolt/README.md | 916 ------- vendor/github.com/boltdb/bolt/appveyor.yml | 18 - vendor/github.com/boltdb/bolt/bucket_test.go | 1909 -------------- vendor/github.com/boltdb/bolt/cursor_test.go | 817 ------ vendor/github.com/boltdb/bolt/db_test.go | 1545 ----------- .../github.com/boltdb/bolt/freelist_test.go | 158 -- vendor/github.com/boltdb/bolt/node_test.go | 156 -- vendor/github.com/boltdb/bolt/page_test.go | 72 - vendor/github.com/boltdb/bolt/quick_test.go | 87 - .../github.com/boltdb/bolt/simulation_test.go | 329 --- vendor/github.com/boltdb/bolt/tx_test.go | 716 ------ vendor/github.com/go-yaml/yaml/.travis.yml | 9 - vendor/github.com/go-yaml/yaml/README.md | 131 - vendor/github.com/go-yaml/yaml/decode_test.go | 998 -------- vendor/github.com/go-yaml/yaml/encode_test.go | 501 ---- vendor/github.com/go-yaml/yaml/suite_test.go | 12 - vendor/github.com/golang/protobuf/.gitignore | 16 - vendor/github.com/golang/protobuf/.travis.yml | 18 - .../github.com/golang/protobuf/Make.protobuf | 40 - vendor/github.com/golang/protobuf/Makefile | 55 - vendor/github.com/golang/protobuf/README.md | 242 -- .../github.com/golang/protobuf/proto/Makefile | 43 - .../golang/protobuf/proto/all_test.go | 2278 ----------------- .../golang/protobuf/proto/any_test.go | 300 --- .../golang/protobuf/proto/clone_test.go | 300 --- .../golang/protobuf/proto/decode_test.go | 258 -- .../golang/protobuf/proto/encode_test.go | 85 - .../golang/protobuf/proto/equal_test.go | 224 -- .../golang/protobuf/proto/extensions_test.go | 536 ---- .../golang/protobuf/proto/map_test.go | 46 - .../golang/protobuf/proto/message_set_test.go | 66 - .../golang/protobuf/proto/proto3_test.go | 135 - .../golang/protobuf/proto/size2_test.go | 63 - .../golang/protobuf/proto/size_test.go | 164 -- .../golang/protobuf/proto/text_parser_test.go | 673 ----- .../golang/protobuf/proto/text_test.go | 474 ---- vendor/github.com/jmank88/nuts/.gitignore | 3 - vendor/github.com/jmank88/nuts/.travis.yml | 9 - vendor/github.com/jmank88/nuts/Gopkg.lock | 21 - vendor/github.com/jmank88/nuts/Gopkg.toml | 3 - vendor/github.com/jmank88/nuts/README.md | 53 - .../github.com/jmank88/nuts/example_test.go | 22 - vendor/github.com/jmank88/nuts/key_test.go | 114 - vendor/github.com/jmank88/nuts/paths_test.go | 338 --- .../github.com/nightlyone/lockfile/.gitignore | 27 - .../nightlyone/lockfile/.gitmodules | 3 - .../nightlyone/lockfile/.travis.yml | 14 - .../github.com/nightlyone/lockfile/README.md | 52 - .../nightlyone/lockfile/appveyor.yml | 12 - .../nightlyone/lockfile/lockfile_test.go | 308 --- .../github.com/pelletier/go-toml/.gitignore | 2 - .../github.com/pelletier/go-toml/.travis.yml | 22 - vendor/github.com/pelletier/go-toml/README.md | 131 - .../pelletier/go-toml/benchmark.json | 164 -- .../github.com/pelletier/go-toml/benchmark.sh | 32 - .../pelletier/go-toml/benchmark.toml | 244 -- .../pelletier/go-toml/benchmark.yml | 121 - .../pelletier/go-toml/benchmark_test.go | 192 -- .../github.com/pelletier/go-toml/doc_test.go | 105 - .../pelletier/go-toml/example-crlf.toml | 29 - .../github.com/pelletier/go-toml/example.toml | 29 - vendor/github.com/pelletier/go-toml/fuzz.sh | 15 - .../pelletier/go-toml/keysparsing_test.go | 70 - .../pelletier/go-toml/lexer_test.go | 750 ------ .../pelletier/go-toml/marshal_test.go | 806 ------ .../pelletier/go-toml/marshal_test.toml | 38 - .../pelletier/go-toml/parser_test.go | 785 ------ .../pelletier/go-toml/position_test.go | 29 - vendor/github.com/pelletier/go-toml/test.sh | 90 - .../pelletier/go-toml/token_test.go | 67 - .../github.com/pelletier/go-toml/toml_test.go | 106 - .../pelletier/go-toml/tomltree_create_test.go | 126 - .../pelletier/go-toml/tomltree_write_test.go | 358 --- vendor/github.com/pkg/errors/.gitignore | 24 - vendor/github.com/pkg/errors/.travis.yml | 11 - vendor/github.com/pkg/errors/README.md | 52 - vendor/github.com/pkg/errors/appveyor.yml | 32 - vendor/github.com/pkg/errors/bench_test.go | 59 - vendor/github.com/pkg/errors/errors_test.go | 226 -- vendor/github.com/pkg/errors/example_test.go | 205 -- vendor/github.com/pkg/errors/format_test.go | 535 ---- vendor/github.com/pkg/errors/stack_test.go | 292 --- vendor/github.com/sdboyer/constext/README.md | 78 - .../sdboyer/constext/constext_test.go | 156 -- vendor/golang.org/x/net/.gitattributes | 10 - vendor/golang.org/x/net/.gitignore | 2 - vendor/golang.org/x/net/CONTRIBUTING.md | 31 - vendor/golang.org/x/net/README | 3 - vendor/golang.org/x/net/codereview.cfg | 1 - .../golang.org/x/net/context/context_test.go | 583 ----- .../x/net/context/withtimeout_test.go | 31 - vendor/golang.org/x/sync/CONTRIBUTING.md | 31 - vendor/golang.org/x/sync/README | 2 - vendor/golang.org/x/sync/codereview.cfg | 1 - .../errgroup/errgroup_example_md5all_test.go | 101 - .../x/sync/errgroup/errgroup_test.go | 176 -- vendor/golang.org/x/sys/.gitattributes | 10 - vendor/golang.org/x/sys/.gitignore | 2 - vendor/golang.org/x/sys/CONTRIBUTING.md | 31 - vendor/golang.org/x/sys/README | 3 - vendor/golang.org/x/sys/codereview.cfg | 1 - vendor/golang.org/x/sys/unix/.gitignore | 1 - vendor/golang.org/x/sys/unix/README.md | 173 -- vendor/golang.org/x/sys/unix/creds_test.go | 136 - .../golang.org/x/sys/unix/dev_linux_test.go | 51 - vendor/golang.org/x/sys/unix/export_test.go | 9 - vendor/golang.org/x/sys/unix/mkall.sh | 197 -- vendor/golang.org/x/sys/unix/mkerrors.sh | 563 ---- vendor/golang.org/x/sys/unix/mksyscall.pl | 328 --- .../x/sys/unix/mksyscall_solaris.pl | 289 --- .../golang.org/x/sys/unix/mksysctl_openbsd.pl | 264 -- .../golang.org/x/sys/unix/mksysnum_darwin.pl | 39 - .../x/sys/unix/mksysnum_dragonfly.pl | 50 - .../golang.org/x/sys/unix/mksysnum_freebsd.pl | 50 - .../golang.org/x/sys/unix/mksysnum_netbsd.pl | 58 - .../golang.org/x/sys/unix/mksysnum_openbsd.pl | 50 - .../golang.org/x/sys/unix/mmap_unix_test.go | 35 - vendor/golang.org/x/sys/unix/openbsd_test.go | 113 - .../golang.org/x/sys/unix/syscall_bsd_test.go | 62 - .../x/sys/unix/syscall_freebsd_test.go | 297 --- .../x/sys/unix/syscall_linux_test.go | 227 -- .../x/sys/unix/syscall_solaris_test.go | 34 - vendor/golang.org/x/sys/unix/syscall_test.go | 50 - .../x/sys/unix/syscall_unix_test.go | 345 --- 155 files changed, 1 insertion(+), 30889 deletions(-) delete mode 100644 vendor/github.com/Masterminds/semver/.travis.yml delete mode 100644 vendor/github.com/Masterminds/semver/CHANGELOG.md delete mode 100644 vendor/github.com/Masterminds/semver/Makefile delete mode 100644 vendor/github.com/Masterminds/semver/README.md delete mode 100644 vendor/github.com/Masterminds/semver/appveyor.yml delete mode 100644 vendor/github.com/Masterminds/semver/benchmark_test.go delete mode 100644 vendor/github.com/Masterminds/semver/collection_test.go delete mode 100644 vendor/github.com/Masterminds/semver/constraints_test.go delete mode 100644 vendor/github.com/Masterminds/semver/set_ops_test.go delete mode 100644 vendor/github.com/Masterminds/semver/version_test.go delete mode 100644 vendor/github.com/Masterminds/vcs/.gitignore delete mode 100644 vendor/github.com/Masterminds/vcs/.travis.yml delete mode 100644 vendor/github.com/Masterminds/vcs/CHANGELOG.md delete mode 100644 vendor/github.com/Masterminds/vcs/Makefile delete mode 100644 vendor/github.com/Masterminds/vcs/README.md delete mode 100644 vendor/github.com/Masterminds/vcs/appveyor.yml delete mode 100644 vendor/github.com/Masterminds/vcs/bzr_test.go delete mode 100644 vendor/github.com/Masterminds/vcs/errors_test.go delete mode 100644 vendor/github.com/Masterminds/vcs/git_test.go delete mode 100644 vendor/github.com/Masterminds/vcs/glide.yaml delete mode 100644 vendor/github.com/Masterminds/vcs/hg_test.go delete mode 100644 vendor/github.com/Masterminds/vcs/repo_test.go delete mode 100644 vendor/github.com/Masterminds/vcs/svn_test.go delete mode 100644 vendor/github.com/Masterminds/vcs/vcs_remote_lookup_test.go delete mode 100644 vendor/github.com/armon/go-radix/.gitignore delete mode 100644 vendor/github.com/armon/go-radix/.travis.yml delete mode 100644 vendor/github.com/armon/go-radix/README.md delete mode 100644 vendor/github.com/armon/go-radix/radix_test.go delete mode 100644 vendor/github.com/boltdb/bolt/.gitignore delete mode 100644 vendor/github.com/boltdb/bolt/Makefile delete mode 100644 vendor/github.com/boltdb/bolt/README.md delete mode 100644 vendor/github.com/boltdb/bolt/appveyor.yml delete mode 100644 vendor/github.com/boltdb/bolt/bucket_test.go delete mode 100644 vendor/github.com/boltdb/bolt/cursor_test.go delete mode 100644 vendor/github.com/boltdb/bolt/db_test.go delete mode 100644 vendor/github.com/boltdb/bolt/freelist_test.go delete mode 100644 vendor/github.com/boltdb/bolt/node_test.go delete mode 100644 vendor/github.com/boltdb/bolt/page_test.go delete mode 100644 vendor/github.com/boltdb/bolt/quick_test.go delete mode 100644 vendor/github.com/boltdb/bolt/simulation_test.go delete mode 100644 vendor/github.com/boltdb/bolt/tx_test.go delete mode 100644 vendor/github.com/go-yaml/yaml/.travis.yml delete mode 100644 vendor/github.com/go-yaml/yaml/README.md delete mode 100644 vendor/github.com/go-yaml/yaml/decode_test.go delete mode 100644 vendor/github.com/go-yaml/yaml/encode_test.go delete mode 100644 vendor/github.com/go-yaml/yaml/suite_test.go delete mode 100644 vendor/github.com/golang/protobuf/.gitignore delete mode 100644 vendor/github.com/golang/protobuf/.travis.yml delete mode 100644 vendor/github.com/golang/protobuf/Make.protobuf delete mode 100644 vendor/github.com/golang/protobuf/Makefile delete mode 100644 vendor/github.com/golang/protobuf/README.md delete mode 100644 vendor/github.com/golang/protobuf/proto/Makefile delete mode 100644 vendor/github.com/golang/protobuf/proto/all_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/any_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/clone_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/decode_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/encode_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/equal_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/extensions_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/map_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/message_set_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/proto3_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/size2_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/size_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/text_parser_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/text_test.go delete mode 100644 vendor/github.com/jmank88/nuts/.gitignore delete mode 100644 vendor/github.com/jmank88/nuts/.travis.yml delete mode 100644 vendor/github.com/jmank88/nuts/Gopkg.lock delete mode 100644 vendor/github.com/jmank88/nuts/Gopkg.toml delete mode 100644 vendor/github.com/jmank88/nuts/README.md delete mode 100644 vendor/github.com/jmank88/nuts/example_test.go delete mode 100644 vendor/github.com/jmank88/nuts/key_test.go delete mode 100644 vendor/github.com/jmank88/nuts/paths_test.go delete mode 100644 vendor/github.com/nightlyone/lockfile/.gitignore delete mode 100644 vendor/github.com/nightlyone/lockfile/.gitmodules delete mode 100644 vendor/github.com/nightlyone/lockfile/.travis.yml delete mode 100644 vendor/github.com/nightlyone/lockfile/README.md delete mode 100644 vendor/github.com/nightlyone/lockfile/appveyor.yml delete mode 100644 vendor/github.com/nightlyone/lockfile/lockfile_test.go delete mode 100644 vendor/github.com/pelletier/go-toml/.gitignore delete mode 100644 vendor/github.com/pelletier/go-toml/.travis.yml delete mode 100644 vendor/github.com/pelletier/go-toml/README.md delete mode 100644 vendor/github.com/pelletier/go-toml/benchmark.json delete mode 100755 vendor/github.com/pelletier/go-toml/benchmark.sh delete mode 100644 vendor/github.com/pelletier/go-toml/benchmark.toml delete mode 100644 vendor/github.com/pelletier/go-toml/benchmark.yml delete mode 100644 vendor/github.com/pelletier/go-toml/benchmark_test.go delete mode 100644 vendor/github.com/pelletier/go-toml/doc_test.go delete mode 100644 vendor/github.com/pelletier/go-toml/example-crlf.toml delete mode 100644 vendor/github.com/pelletier/go-toml/example.toml delete mode 100755 vendor/github.com/pelletier/go-toml/fuzz.sh delete mode 100644 vendor/github.com/pelletier/go-toml/keysparsing_test.go delete mode 100644 vendor/github.com/pelletier/go-toml/lexer_test.go delete mode 100644 vendor/github.com/pelletier/go-toml/marshal_test.go delete mode 100644 vendor/github.com/pelletier/go-toml/marshal_test.toml delete mode 100644 vendor/github.com/pelletier/go-toml/parser_test.go delete mode 100644 vendor/github.com/pelletier/go-toml/position_test.go delete mode 100755 vendor/github.com/pelletier/go-toml/test.sh delete mode 100644 vendor/github.com/pelletier/go-toml/token_test.go delete mode 100644 vendor/github.com/pelletier/go-toml/toml_test.go delete mode 100644 vendor/github.com/pelletier/go-toml/tomltree_create_test.go delete mode 100644 vendor/github.com/pelletier/go-toml/tomltree_write_test.go delete mode 100644 vendor/github.com/pkg/errors/.gitignore delete mode 100644 vendor/github.com/pkg/errors/.travis.yml delete mode 100644 vendor/github.com/pkg/errors/README.md delete mode 100644 vendor/github.com/pkg/errors/appveyor.yml delete mode 100644 vendor/github.com/pkg/errors/bench_test.go delete mode 100644 vendor/github.com/pkg/errors/errors_test.go delete mode 100644 vendor/github.com/pkg/errors/example_test.go delete mode 100644 vendor/github.com/pkg/errors/format_test.go delete mode 100644 vendor/github.com/pkg/errors/stack_test.go delete mode 100644 vendor/github.com/sdboyer/constext/README.md delete mode 100644 vendor/github.com/sdboyer/constext/constext_test.go delete mode 100644 vendor/golang.org/x/net/.gitattributes delete mode 100644 vendor/golang.org/x/net/.gitignore delete mode 100644 vendor/golang.org/x/net/CONTRIBUTING.md delete mode 100644 vendor/golang.org/x/net/README delete mode 100644 vendor/golang.org/x/net/codereview.cfg delete mode 100644 vendor/golang.org/x/net/context/context_test.go delete mode 100644 vendor/golang.org/x/net/context/withtimeout_test.go delete mode 100644 vendor/golang.org/x/sync/CONTRIBUTING.md delete mode 100644 vendor/golang.org/x/sync/README delete mode 100644 vendor/golang.org/x/sync/codereview.cfg delete mode 100644 vendor/golang.org/x/sync/errgroup/errgroup_example_md5all_test.go delete mode 100644 vendor/golang.org/x/sync/errgroup/errgroup_test.go delete mode 100644 vendor/golang.org/x/sys/.gitattributes delete mode 100644 vendor/golang.org/x/sys/.gitignore delete mode 100644 vendor/golang.org/x/sys/CONTRIBUTING.md delete mode 100644 vendor/golang.org/x/sys/README delete mode 100644 vendor/golang.org/x/sys/codereview.cfg delete mode 100644 vendor/golang.org/x/sys/unix/.gitignore delete mode 100644 vendor/golang.org/x/sys/unix/README.md delete mode 100644 vendor/golang.org/x/sys/unix/creds_test.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_linux_test.go delete mode 100644 vendor/golang.org/x/sys/unix/export_test.go delete mode 100755 vendor/golang.org/x/sys/unix/mkall.sh delete mode 100755 vendor/golang.org/x/sys/unix/mkerrors.sh delete mode 100755 vendor/golang.org/x/sys/unix/mksyscall.pl delete mode 100755 vendor/golang.org/x/sys/unix/mksyscall_solaris.pl delete mode 100755 vendor/golang.org/x/sys/unix/mksysctl_openbsd.pl delete mode 100755 vendor/golang.org/x/sys/unix/mksysnum_darwin.pl delete mode 100755 vendor/golang.org/x/sys/unix/mksysnum_dragonfly.pl delete mode 100755 vendor/golang.org/x/sys/unix/mksysnum_freebsd.pl delete mode 100755 vendor/golang.org/x/sys/unix/mksysnum_netbsd.pl delete mode 100755 vendor/golang.org/x/sys/unix/mksysnum_openbsd.pl delete mode 100644 vendor/golang.org/x/sys/unix/mmap_unix_test.go delete mode 100644 vendor/golang.org/x/sys/unix/openbsd_test.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_bsd_test.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd_test.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_test.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_solaris_test.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_test.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_unix_test.go diff --git a/hack/validate-vendor.bash b/hack/validate-vendor.bash index fd395f02..d6fb2bf5 100755 --- a/hack/validate-vendor.bash +++ b/hack/validate-vendor.bash @@ -33,12 +33,11 @@ unset IFS if [ ${#files[@]} -gt 0 ]; then go build ./cmd/dep ./dep ensure -vendor-only - ./dep prune # Let see if the working directory is clean diffs="$(git status --porcelain -- vendor Gopkg.toml Gopkg.lock 2>/dev/null)" if [ "$diffs" ]; then { - echo 'The contents of vendor differ after "dep ensure && dep prune":' + echo 'The contents of vendor differ after "dep ensure":' echo echo "$diffs" echo diff --git a/vendor/github.com/Masterminds/semver/.travis.yml b/vendor/github.com/Masterminds/semver/.travis.yml deleted file mode 100644 index fa92a5a3..00000000 --- a/vendor/github.com/Masterminds/semver/.travis.yml +++ /dev/null @@ -1,24 +0,0 @@ -language: go - -go: - - 1.6 - - 1.7 - - tip - -# Setting sudo access to false will let Travis CI use containers rather than -# VMs to run the tests. For more details see: -# - http://docs.travis-ci.com/user/workers/container-based-infrastructure/ -# - http://docs.travis-ci.com/user/workers/standard-infrastructure/ -sudo: false - -script: - - make setup - - make test - -notifications: - webhooks: - urls: - - https://webhooks.gitter.im/e/06e3328629952dabe3e0 - on_success: change # options: [always|never|change] default: always - on_failure: always # options: [always|never|change] default: always - on_start: never # options: [always|never|change] default: always diff --git a/vendor/github.com/Masterminds/semver/CHANGELOG.md b/vendor/github.com/Masterminds/semver/CHANGELOG.md deleted file mode 100644 index 25550675..00000000 --- a/vendor/github.com/Masterminds/semver/CHANGELOG.md +++ /dev/null @@ -1,17 +0,0 @@ -# Release 1.x.x (xxxx-xx-xx) - -- Issue #9: Speed up version comparison performance (thanks @sdboyer) -- Issue #8: Added benchmarks (thanks @sdboyer) - -# Release 1.1.0 (2015-03-11) - -- Issue #2: Implemented validation to provide reasons a versions failed a - constraint. - -# Release 1.0.1 (2015-12-31) - -- Fixed #1: * constraint failing on valid versions. - -# Release 1.0.0 (2015-10-20) - -- Initial release diff --git a/vendor/github.com/Masterminds/semver/Makefile b/vendor/github.com/Masterminds/semver/Makefile deleted file mode 100644 index a7a1b4e3..00000000 --- a/vendor/github.com/Masterminds/semver/Makefile +++ /dev/null @@ -1,36 +0,0 @@ -.PHONY: setup -setup: - go get -u gopkg.in/alecthomas/gometalinter.v1 - gometalinter.v1 --install - -.PHONY: test -test: validate lint - @echo "==> Running tests" - go test -v - -.PHONY: validate -validate: - @echo "==> Running static validations" - @gometalinter.v1 \ - --disable-all \ - --enable deadcode \ - --severity deadcode:error \ - --enable gofmt \ - --enable gosimple \ - --enable ineffassign \ - --enable misspell \ - --enable vet \ - --tests \ - --vendor \ - --deadline 60s \ - ./... || exit_code=1 - -.PHONY: lint -lint: - @echo "==> Running linters" - @gometalinter.v1 \ - --disable-all \ - --enable golint \ - --vendor \ - --deadline 60s \ - ./... || : diff --git a/vendor/github.com/Masterminds/semver/README.md b/vendor/github.com/Masterminds/semver/README.md deleted file mode 100644 index aa133eac..00000000 --- a/vendor/github.com/Masterminds/semver/README.md +++ /dev/null @@ -1,146 +0,0 @@ -# SemVer - -The `semver` package provides the ability to work with [Semantic Versions](http://semver.org) in Go. Specifically it provides the ability to: - -* Parse semantic versions -* Sort semantic versions -* Check if a semantic version fits within a set of constraints -* Optionally work with a `v` prefix - -[![Build Status](https://travis-ci.org/Masterminds/semver.svg)](https://travis-ci.org/Masterminds/semver) [![Build status](https://ci.appveyor.com/api/projects/status/jfk66lib7hb985k8/branch/master?svg=true&passingText=windows%20build%20passing&failingText=windows%20build%20failing)](https://ci.appveyor.com/project/mattfarina/semver/branch/master) [![GoDoc](https://godoc.org/github.com/Masterminds/semver?status.png)](https://godoc.org/github.com/Masterminds/semver) [![Go Report Card](http://goreportcard.com/badge/Masterminds/semver)](http://goreportcard.com/report/Masterminds/semver) - -## Parsing Semantic Versions - -To parse a semantic version use the `NewVersion` function. For example, - - v, err := semver.NewVersion("1.2.3-beta.1+build345") - -If there is an error the version wasn't parseable. The version object has methods -to get the parts of the version, compare it to other versions, convert the -version back into a string, and get the original string. For more details -please see the [documentation](https://godoc.org/github.com/Masterminds/semver). - -## Sorting Semantic Versions - -A set of versions can be sorted using the [`sort`](https://golang.org/pkg/sort/) -package from the standard library. For example, - - raw := []string{"1.2.3", "1.0", "1.3", "2", "0.4.2",} - vs := make([]*semver.Version, len(raw)) - for i, r := range raw { - v, err := semver.NewVersion(r) - if err != nil { - t.Errorf("Error parsing version: %s", err) - } - - vs[i] = v - } - - sort.Sort(semver.Collection(vs)) - -## Checking Version Constraints - -Checking a version against version constraints is one of the most featureful -parts of the package. - - c, err := semver.NewConstraint(">= 1.2.3") - if err != nil { - // Handle constraint not being parseable. - } - - v, _ := semver.NewVersion("1.3") - if err != nil { - // Handle version not being parseable. - } - // Check if the version meets the constraints. The a variable will be true. - a := c.Check(v) - -## Basic Comparisons - -There are two elements to the comparisons. First, a comparison string is a list -of comma separated and comparisons. These are then separated by || separated or -comparisons. For example, `">= 1.2, < 3.0.0 || >= 4.2.3"` is looking for a -comparison that's greater than or equal to 1.2 and less than 3.0.0 or is -greater than or equal to 4.2.3. - -The basic comparisons are: - -* `=`: equal (aliased to no operator) -* `!=`: not equal -* `>`: greater than -* `<`: less than -* `>=`: greater than or equal to -* `<=`: less than or equal to - -## Hyphen Range Comparisons - -There are multiple methods to handle ranges and the first is hyphens ranges. -These look like: - -* `1.2 - 1.4.5` which is equivalent to `>= 1.2, <= 1.4.5` -* `2.3.4 - 4.5` which is equivalent to `>= 2.3.4, <= 4.5` - -## Wildcards In Comparisons - -The `x`, `X`, and `*` characters can be used as a wildcard character. This works -for all comparison operators. When used on the `=` operator it falls -back to the pack level comparison (see tilde below). For example, - -* `1.2.x` is equivalent to `>= 1.2.0, < 1.3.0` -* `>= 1.2.x` is equivalent to `>= 1.2.0` -* `<= 2.x` is equivalent to `<= 3` -* `*` is equivalent to `>= 0.0.0` - -## Tilde Range Comparisons (Patch) - -The tilde (`~`) comparison operator is for patch level ranges when a minor -version is specified and major level changes when the minor number is missing. -For example, - -* `~1.2.3` is equivalent to `>= 1.2.3, < 1.3.0` -* `~1` is equivalent to `>= 1, < 2` -* `~2.3` is equivalent to `>= 2.3, < 2.4` -* `~1.2.x` is equivalent to `>= 1.2.0, < 1.3.0` -* `~1.x` is equivalent to `>= 1, < 2` - -## Caret Range Comparisons (Major) - -The caret (`^`) comparison operator is for major level changes. This is useful -when comparisons of API versions as a major change is API breaking. For example, - -* `^1.2.3` is equivalent to `>= 1.2.3, < 2.0.0` -* `^1.2.x` is equivalent to `>= 1.2.0, < 2.0.0` -* `^2.3` is equivalent to `>= 2.3, < 3` -* `^2.x` is equivalent to `>= 2.0.0, < 3` - -# Validation - -In addition to testing a version against a constraint, a version can be validated -against a constraint. When validation fails a slice of errors containing why a -version didn't meet the constraint is returned. For example, - - c, err := semver.NewConstraint("<= 1.2.3, >= 1.4") - if err != nil { - // Handle constraint not being parseable. - } - - v, _ := semver.NewVersion("1.3") - if err != nil { - // Handle version not being parseable. - } - - // Validate a version against a constraint. - a, msgs := c.Validate(v) - // a is false - for _, m := range msgs { - fmt.Println(m) - - // Loops over the errors which would read - // "1.3 is greater than 1.2.3" - // "1.3 is less than 1.4" - } - -# Contribute - -If you find an issue or want to contribute please file an [issue](https://github.com/Masterminds/semver/issues) -or [create a pull request](https://github.com/Masterminds/semver/pulls). diff --git a/vendor/github.com/Masterminds/semver/appveyor.yml b/vendor/github.com/Masterminds/semver/appveyor.yml deleted file mode 100644 index 08d60708..00000000 --- a/vendor/github.com/Masterminds/semver/appveyor.yml +++ /dev/null @@ -1,44 +0,0 @@ -version: build-{build}.{branch} - -clone_folder: C:\gopath\src\github.com\Masterminds\semver -shallow_clone: true - -environment: - GOPATH: C:\gopath - -platform: - - x64 - -install: - - go version - - go env - - go get -u gopkg.in/alecthomas/gometalinter.v1 - - set PATH=%PATH%;%GOPATH%\bin - - gometalinter.v1.exe --install - -build_script: - - go install -v ./... - -test_script: - - "gometalinter.v1 \ - --disable-all \ - --enable deadcode \ - --severity deadcode:error \ - --enable gofmt \ - --enable gosimple \ - --enable ineffassign \ - --enable misspell \ - --enable vet \ - --tests \ - --vendor \ - --deadline 60s \ - ./... || cmd /C EXIT 0" - - "gometalinter.v1 \ - --disable-all \ - --enable golint \ - --vendor \ - --deadline 60s \ - ./... || cmd /C EXIT 0" - - go test -v - -deploy: off diff --git a/vendor/github.com/Masterminds/semver/benchmark_test.go b/vendor/github.com/Masterminds/semver/benchmark_test.go deleted file mode 100644 index 5a76f6a9..00000000 --- a/vendor/github.com/Masterminds/semver/benchmark_test.go +++ /dev/null @@ -1,259 +0,0 @@ -package semver - -import "testing" - -func init() { - // disable constraint and version creation caching - CacheConstraints = false - CacheVersions = false -} - -var ( - rc1 = rangeConstraint{ - min: newV(1, 5, 0), - max: newV(2, 0, 0), - includeMax: true, - } - rc2 = rangeConstraint{ - min: newV(2, 0, 0), - max: newV(3, 0, 0), - } - rc3 = rangeConstraint{ - min: newV(1, 5, 0), - max: newV(2, 0, 0), - } - rc4 = rangeConstraint{ - min: newV(1, 7, 0), - max: newV(4, 0, 0), - } - rc5 = rangeConstraint{ - min: newV(2, 7, 0), - max: newV(3, 0, 0), - } - rc6 = rangeConstraint{ - min: newV(3, 0, 1), - max: newV(3, 0, 4), - } - rc7 = rangeConstraint{ - min: newV(1, 0, 0), - max: newV(1, 2, 0), - } - // Two fully non-overlapping unions - u1 = rc1.Union(rc7) - u2 = rc5.Union(rc6) -) - -/* Constraint creation benchmarks */ - -func benchNewConstraint(c string, b *testing.B) { - for i := 0; i < b.N; i++ { - NewConstraint(c) - } -} - -func BenchmarkNewConstraintUnary(b *testing.B) { - benchNewConstraint("=2.0", b) -} - -func BenchmarkNewConstraintTilde(b *testing.B) { - benchNewConstraint("~2.0.0", b) -} - -func BenchmarkNewConstraintCaret(b *testing.B) { - benchNewConstraint("^2.0.0", b) -} - -func BenchmarkNewConstraintWildcard(b *testing.B) { - benchNewConstraint("1.x", b) -} - -func BenchmarkNewConstraintRange(b *testing.B) { - benchNewConstraint(">=2.1.x, <3.1.0", b) -} - -func BenchmarkNewConstraintUnion(b *testing.B) { - benchNewConstraint("~2.0.0 || =3.1.0", b) -} - -/* Validate benchmarks, including fails */ - -func benchValidateVersion(c, v string, b *testing.B) { - version, _ := NewVersion(v) - constraint, _ := NewConstraint(c) - - for i := 0; i < b.N; i++ { - constraint.Matches(version) - } -} - -func BenchmarkValidateVersionUnary(b *testing.B) { - benchValidateVersion("=2.0", "2.0.0", b) -} - -func BenchmarkValidateVersionUnaryFail(b *testing.B) { - benchValidateVersion("=2.0", "2.0.1", b) -} - -func BenchmarkValidateVersionTilde(b *testing.B) { - benchValidateVersion("~2.0.0", "2.0.5", b) -} - -func BenchmarkValidateVersionTildeFail(b *testing.B) { - benchValidateVersion("~2.0.0", "1.0.5", b) -} - -func BenchmarkValidateVersionCaret(b *testing.B) { - benchValidateVersion("^2.0.0", "2.1.0", b) -} - -func BenchmarkValidateVersionCaretFail(b *testing.B) { - benchValidateVersion("^2.0.0", "4.1.0", b) -} - -func BenchmarkValidateVersionWildcard(b *testing.B) { - benchValidateVersion("1.x", "1.4.0", b) -} - -func BenchmarkValidateVersionWildcardFail(b *testing.B) { - benchValidateVersion("1.x", "2.4.0", b) -} - -func BenchmarkValidateVersionRange(b *testing.B) { - benchValidateVersion(">=2.1.x, <3.1.0", "2.4.5", b) -} - -func BenchmarkValidateVersionRangeFail(b *testing.B) { - benchValidateVersion(">=2.1.x, <3.1.0", "1.4.5", b) -} - -func BenchmarkValidateVersionUnion(b *testing.B) { - benchValidateVersion("~2.0.0 || =3.1.0", "3.1.0", b) -} - -func BenchmarkValidateVersionUnionFail(b *testing.B) { - benchValidateVersion("~2.0.0 || =3.1.0", "3.1.1", b) -} - -/* Version creation benchmarks */ - -func benchNewVersion(v string, b *testing.B) { - for i := 0; i < b.N; i++ { - NewVersion(v) - } -} - -func BenchmarkNewVersionSimple(b *testing.B) { - benchNewVersion("1.0.0", b) -} - -func BenchmarkNewVersionPre(b *testing.B) { - benchNewVersion("1.0.0-alpha", b) -} - -func BenchmarkNewVersionMeta(b *testing.B) { - benchNewVersion("1.0.0+metadata", b) -} - -func BenchmarkNewVersionMetaDash(b *testing.B) { - benchNewVersion("1.0.0+metadata-dash", b) -} - -/* Union benchmarks */ - -func BenchmarkAdjacentRangeUnion(b *testing.B) { - for i := 0; i < b.N; i++ { - Union(rc1, rc2) - } -} - -func BenchmarkAdjacentRangeUnionMethod(b *testing.B) { - for i := 0; i < b.N; i++ { - rc1.Union(rc2) - } -} - -func BenchmarkDisjointRangeUnion(b *testing.B) { - for i := 0; i < b.N; i++ { - Union(rc2, rc3) - } -} - -func BenchmarkDisjointRangeUnionMethod(b *testing.B) { - for i := 0; i < b.N; i++ { - rc2.Union(rc3) - } -} - -func BenchmarkOverlappingRangeUnion(b *testing.B) { - for i := 0; i < b.N; i++ { - Union(rc1, rc4) - } -} - -func BenchmarkOverlappingRangeUnionMethod(b *testing.B) { - for i := 0; i < b.N; i++ { - rc1.Union(rc4) - } -} - -func BenchmarkUnionUnion(b *testing.B) { - for i := 0; i < b.N; i++ { - Union(u1, u2) - } -} - -func BenchmarkUnionUnionMethod(b *testing.B) { - for i := 0; i < b.N; i++ { - u1.Union(u2) - } -} - -/* Intersection benchmarks */ - -func BenchmarkSubsetRangeIntersection(b *testing.B) { - for i := 0; i < b.N; i++ { - Intersection(rc2, rc4) - } -} - -func BenchmarkSubsetRangeIntersectionMethod(b *testing.B) { - for i := 0; i < b.N; i++ { - rc2.Intersect(rc4) - } -} - -func BenchmarkDisjointRangeIntersection(b *testing.B) { - for i := 0; i < b.N; i++ { - Intersection(rc2, rc3) - } -} - -func BenchmarkDisjointRangeIntersectionMethod(b *testing.B) { - for i := 0; i < b.N; i++ { - rc2.Intersect(rc3) - } -} - -func BenchmarkOverlappingRangeIntersection(b *testing.B) { - for i := 0; i < b.N; i++ { - Intersection(rc1, rc4) - } -} - -func BenchmarkOverlappingRangeIntersectionMethod(b *testing.B) { - for i := 0; i < b.N; i++ { - rc1.Intersect(rc4) - } -} - -func BenchmarkUnionIntersection(b *testing.B) { - for i := 0; i < b.N; i++ { - Intersection(u1, u2) - } -} - -func BenchmarkUnionIntersectionMethod(b *testing.B) { - for i := 0; i < b.N; i++ { - u1.Intersect(u2) - } -} diff --git a/vendor/github.com/Masterminds/semver/collection_test.go b/vendor/github.com/Masterminds/semver/collection_test.go deleted file mode 100644 index a1d745f4..00000000 --- a/vendor/github.com/Masterminds/semver/collection_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package semver - -import ( - "reflect" - "sort" - "testing" -) - -func TestCollection(t *testing.T) { - raw := []string{ - "1.2.3", - "1.0", - "1.3", - "2", - "0.4.2", - } - - vs := make([]Version, len(raw)) - for i, r := range raw { - v, err := NewVersion(r) - if err != nil { - t.Errorf("Error parsing version: %s", err) - } - - vs[i] = v - } - - sort.Sort(Collection(vs)) - - e := []string{ - "0.4.2", - "1.0.0", - "1.2.3", - "1.3.0", - "2.0.0", - } - - a := make([]string, len(vs)) - for i, v := range vs { - a[i] = v.String() - } - - if !reflect.DeepEqual(a, e) { - t.Error("Sorting Collection failed") - } -} diff --git a/vendor/github.com/Masterminds/semver/constraints_test.go b/vendor/github.com/Masterminds/semver/constraints_test.go deleted file mode 100644 index cb77c89d..00000000 --- a/vendor/github.com/Masterminds/semver/constraints_test.go +++ /dev/null @@ -1,712 +0,0 @@ -package semver - -import "testing" - -func TestParseConstraint(t *testing.T) { - tests := []struct { - in string - c Constraint - err bool - }{ - {"*", Any(), false}, - {">= 1.2", rangeConstraint{ - min: newV(1, 2, 0), - max: Version{special: infiniteVersion}, - includeMin: true, - }, false}, - {"1.0", newV(1, 0, 0), false}, - {"foo", nil, true}, - {"<= 1.2", rangeConstraint{ - min: Version{special: zeroVersion}, - max: newV(1, 2, 0), - includeMax: true, - }, false}, - {"=< 1.2", rangeConstraint{ - min: Version{special: zeroVersion}, - max: newV(1, 2, 0), - includeMax: true, - }, false}, - {"=> 1.2", rangeConstraint{ - min: newV(1, 2, 0), - max: Version{special: infiniteVersion}, - includeMin: true, - }, false}, - {"v1.2", newV(1, 2, 0), false}, - {"=1.5", newV(1, 5, 0), false}, - {"> 1.3", rangeConstraint{ - min: newV(1, 3, 0), - max: Version{special: infiniteVersion}, - }, false}, - {"< 1.4.1", rangeConstraint{ - min: Version{special: zeroVersion}, - max: newV(1, 4, 1), - }, false}, - {"~1.1.0", rangeConstraint{ - min: newV(1, 1, 0), - max: newV(1, 2, 0), - includeMin: true, - includeMax: false, - }, false}, - {"^1.1.0", rangeConstraint{ - min: newV(1, 1, 0), - max: newV(2, 0, 0), - includeMin: true, - includeMax: false, - }, false}, - {"^1.1.0-12-abc123", rangeConstraint{ - min: Version{major: 1, minor: 1, patch: 0, pre: "12-abc123"}, - max: newV(2, 0, 0), - includeMin: true, - includeMax: false, - }, false}, - } - - for _, tc := range tests { - c, err := parseConstraint(tc.in, false) - if tc.err && err == nil { - t.Errorf("Expected error for %s didn't occur", tc.in) - } else if !tc.err && err != nil { - t.Errorf("Unexpected error %q for %s", err, tc.in) - } - - // If an error was expected continue the loop and don't try the other - // tests as they will cause errors. - if tc.err { - continue - } - - if !constraintEq(tc.c, c) { - t.Errorf("%q produced constraint %q, but expected %q", tc.in, c, tc.c) - } - } -} - -func constraintEq(c1, c2 Constraint) bool { - switch tc1 := c1.(type) { - case any: - if _, ok := c2.(any); !ok { - return false - } - return true - case none: - if _, ok := c2.(none); !ok { - return false - } - return true - case Version: - if tc2, ok := c2.(Version); ok { - return tc1.Equal(tc2) - } - return false - case rangeConstraint: - if tc2, ok := c2.(rangeConstraint); ok { - if len(tc1.excl) != len(tc2.excl) { - return false - } - - if !tc1.minIsZero() { - if !(tc1.includeMin == tc2.includeMin && tc1.min.Equal(tc2.min)) { - return false - } - } else if !tc2.minIsZero() { - return false - } - - if !tc1.maxIsInf() { - if !(tc1.includeMax == tc2.includeMax && tc1.max.Equal(tc2.max)) { - return false - } - } else if !tc2.maxIsInf() { - return false - } - - for k, e := range tc1.excl { - if !e.Equal(tc2.excl[k]) { - return false - } - } - return true - } - return false - case unionConstraint: - if tc2, ok := c2.(unionConstraint); ok { - if len(tc1) != len(tc2) { - return false - } - - for k, c := range tc1 { - if !constraintEq(c, tc2[k]) { - return false - } - } - return true - } - return false - } - - panic("unknown type") -} - -// newV is a helper to create a new Version object. -func newV(major, minor, patch uint64) Version { - return Version{ - major: major, - minor: minor, - patch: patch, - } -} - -func TestConstraintCheck(t *testing.T) { - tests := []struct { - constraint string - version string - check bool - }{ - {"= 2.0", "1.2.3", false}, - {"= 2.0", "2.0.0", true}, - {"4.1", "4.1.0", true}, - {"!=4.1", "4.1.0", false}, - {"!=4.1", "5.1.0", true}, - {">1.1", "4.1.0", true}, - {">1.1", "1.1.0", false}, - {"<1.1", "0.1.0", true}, - {"<1.1", "1.1.0", false}, - {"<1.1", "1.1.1", false}, - {">=1.1", "4.1.0", true}, - {">=1.1", "1.1.0", true}, - {">=1.1", "0.0.9", false}, - {"<=1.1", "0.1.0", true}, - {"<=1.1", "1.1.0", true}, - {"<=1.1", "1.1.1", false}, - {"<=1.1-alpha1", "1.1", false}, - {"<=2.x", "3.0.0", false}, - {"<=2.x", "2.9.9", true}, - {"<2.x", "2.0.0", false}, - {"<2.x", "1.9.9", true}, - {">=2.x", "3.0.0", true}, - {">=2.x", "2.9.9", true}, - {">=2.x", "1.9.9", false}, - {">2.x", "3.0.0", true}, - {">2.x", "2.9.9", false}, - {">2.x", "1.9.9", false}, - {"<=2.x-alpha2", "3.0.0-alpha3", false}, - {"<=2.0.0", "2.0.0-alpha1", false}, - {">2.x-beta1", "3.0.0-alpha2", false}, - {"^2.0.0", "3.0.0-alpha2", false}, - {"^2.0.0", "2.0.0-alpha1", false}, - {"^2.1.0-alpha1", "2.1.0-alpha2", true}, // allow prerelease match within same major/minor/patch - {"^2.1.0-alpha1", "2.1.1-alpha2", false}, // but ONLY within same major/minor/patch - {"^2.1.0-alpha3", "2.1.0-alpha2", false}, // still respect prerelease ordering - {"^2.0.0", "2.0.0-alpha2", false}, // and only if the min has a prerelease - } - - for _, tc := range tests { - if testing.Verbose() { - t.Logf("Testing if %q allows %q", tc.constraint, tc.version) - } - c, err := parseConstraint(tc.constraint, false) - if err != nil { - t.Errorf("err: %s", err) - continue - } - - v, err := NewVersion(tc.version) - if err != nil { - t.Errorf("err: %s", err) - continue - } - - a := c.Matches(v) == nil - if a != tc.check { - if tc.check { - t.Errorf("%q should have matched %q", tc.constraint, tc.version) - } else { - t.Errorf("%q should not have matched %q", tc.constraint, tc.version) - } - } - } -} - -func TestNewConstraint(t *testing.T) { - tests := []struct { - input string - c Constraint - err bool - }{ - {">= 1.1", rangeConstraint{ - min: newV(1, 1, 0), - max: Version{special: infiniteVersion}, - includeMin: true, - }, false}, - {"2.0", newV(2, 0, 0), false}, - {">= bar", nil, true}, - {"^1.1.0", rangeConstraint{ - min: newV(1, 1, 0), - max: newV(2, 0, 0), - includeMin: true, - }, false}, - {">= 1.2.3, < 2.0 || => 3.0, < 4", unionConstraint{ - rangeConstraint{ - min: newV(1, 2, 3), - max: newV(2, 0, 0), - includeMin: true, - }, - rangeConstraint{ - min: newV(3, 0, 0), - max: newV(4, 0, 0), - includeMin: true, - }, - }, false}, - {"3-4 || => 1.0, < 2", Union( - rangeConstraint{ - min: newV(3, 0, 0), - max: newV(4, 0, 0), - includeMin: true, - includeMax: true, - }, - rangeConstraint{ - min: newV(1, 0, 0), - max: newV(2, 0, 0), - includeMin: true, - }, - ), false}, - // demonstrates union compression - {"3-4 || => 3.0, < 4", rangeConstraint{ - min: newV(3, 0, 0), - max: newV(4, 0, 0), - includeMin: true, - includeMax: true, - }, false}, - {">=1.1.0, <2.0.0", rangeConstraint{ - min: newV(1, 1, 0), - max: newV(2, 0, 0), - includeMin: true, - includeMax: false, - }, false}, - {"!=1.4.0", rangeConstraint{ - min: Version{special: zeroVersion}, - max: Version{special: infiniteVersion}, - excl: []Version{ - newV(1, 4, 0), - }, - }, false}, - {">=1.1.0, !=1.4.0", rangeConstraint{ - min: newV(1, 1, 0), - max: Version{special: infiniteVersion}, - includeMin: true, - excl: []Version{ - newV(1, 4, 0), - }, - }, false}, - } - - for _, tc := range tests { - c, err := NewConstraint(tc.input) - if tc.err && err == nil { - t.Errorf("expected but did not get error for: %s", tc.input) - continue - } else if !tc.err && err != nil { - t.Errorf("unexpectederror for input %s: %s", tc.input, err) - continue - } - if tc.err { - continue - } - - if !constraintEq(tc.c, c) { - t.Errorf("%q produced constraint %q, but expected %q", tc.input, c, tc.c) - } - } -} - -func TestNewConstraintIC(t *testing.T) { - tests := []struct { - input string - c Constraint - err bool - }{ - {"=2.0", newV(2, 0, 0), false}, - {"= 2.0", newV(2, 0, 0), false}, - {"1.1.0", rangeConstraint{ - min: newV(1, 1, 0), - max: newV(2, 0, 0), - includeMin: true, - }, false}, - {"1.1", rangeConstraint{ - min: newV(1, 1, 0), - max: newV(2, 0, 0), - includeMin: true, - }, false}, - {"v1.1.0-12-abc123", rangeConstraint{ - min: Version{major: 1, minor: 1, patch: 0, pre: "12-abc123"}, - max: newV(2, 0, 0), - includeMin: true, - includeMax: false, - }, false}, - } - - for _, tc := range tests { - c, err := NewConstraintIC(tc.input) - if tc.err && err == nil { - t.Errorf("expected but did not get error for: %s", tc.input) - continue - } else if !tc.err && err != nil { - t.Errorf("unexpectederror for input %s: %s", tc.input, err) - continue - } - if tc.err { - continue - } - - if !constraintEq(tc.c, c) { - t.Errorf("%q produced constraint %q, but expected %q", tc.input, c, tc.c) - } - } -} - -func TestConstraintsCheck(t *testing.T) { - tests := []struct { - constraint string - version string - check bool - }{ - {"*", "1.2.3", true}, - {"~0.0.0", "1.2.3", false}, - {"0.x.x", "1.2.3", false}, - {"0.0.x", "1.2.3", false}, - {"~0.0.0", "0.1.9", false}, - {"~0.0.0", "0.0.9", true}, - {"^0.0.0", "0.0.9", true}, - {"^0.0.0", "0.1.9", false}, // caret behaves like tilde below 1.0.0 - {"= 2.0", "1.2.3", false}, - {"= 2.0", "2.0.0", true}, - {"4.1", "4.1.0", true}, - {"4.1.x", "4.1.3", true}, - {"1.x", "1.4", true}, - {"!=4.1", "4.1.0", false}, - {"!=4.1", "5.1.0", true}, - {"!=4.x", "5.1.0", true}, - {"!=4.x", "4.1.0", false}, - {"!=4.1.x", "4.2.0", true}, - {"!=4.2.x", "4.2.3", false}, - {">1.1", "4.1.0", true}, - {">1.1", "1.1.0", false}, - {"<1.1", "0.1.0", true}, - {"<1.1", "1.1.0", false}, - {"<1.1", "1.1.1", false}, - {"<1.x", "1.1.1", false}, - {"<1.x", "0.9.1", true}, - {"<1.x", "2.1.1", false}, - {"<1.1.x", "1.2.1", false}, - {"<1.1.x", "1.1.500", false}, - {"<1.1.x", "1.0.500", true}, - {"<1.2.x", "1.1.1", true}, - {">=1.1", "4.1.0", true}, - {">=1.1", "1.1.0", true}, - {">=1.1", "0.0.9", false}, - {"<=1.1", "0.1.0", true}, - {"<=1.1", "1.1.0", true}, - {"<=1.x", "1.1.0", true}, - {"<=2.x", "3.1.0", false}, - {"<=1.1", "1.1.1", false}, - {"<=1.1.x", "1.2.500", false}, - {">1.1, <2", "1.1.1", true}, - {">1.1, <3", "4.3.2", false}, - {">=1.1, <2, !=1.2.3", "1.2.3", false}, - {">=1.1, <2, !=1.2.3 || > 3", "3.1.2", true}, - {">=1.1, <2, !=1.2.3 || >= 3", "3.0.0", true}, - {">=1.1, <2, !=1.2.3 || > 3", "3.0.0", false}, - {">=1.1, <2, !=1.2.3 || > 3", "1.2.3", false}, - {"1.1 - 2", "1.1.1", true}, - {"1.1-3", "4.3.2", false}, - {"^1.1", "1.1.1", true}, - {"^1.1", "4.3.2", false}, - {"^1.x", "1.1.1", true}, - {"^2.x", "1.1.1", false}, - {"^1.x", "2.1.1", false}, - {"~*", "2.1.1", true}, - {"~1.x", "2.1.1", false}, - {"~1.x", "1.3.5", true}, - {"~1.x", "1.4", true}, - {"~1.1", "1.1.1", true}, - {"~1.2.3", "1.2.5", true}, - {"~1.2.3", "1.2.2", false}, - {"~1.2.3", "1.3.2", false}, - {"~1.1", "1.2.3", false}, - {"~1.3", "2.4.5", false}, - } - - for _, tc := range tests { - c, err := NewConstraint(tc.constraint) - if err != nil { - t.Errorf("err: %s", err) - continue - } - - v, err := NewVersion(tc.version) - if err != nil { - t.Errorf("err: %s", err) - continue - } - - a := c.Matches(v) == nil - if a != tc.check { - if a { - t.Errorf("Input %q produced constraint %q; should not have admitted %q, but did", tc.constraint, c, tc.version) - } else { - t.Errorf("Input %q produced constraint %q; should have admitted %q, but did not", tc.constraint, c, tc.version) - } - } - } -} - -func TestBidirectionalSerialization(t *testing.T) { - tests := []struct { - io string - eq bool - }{ - {"*", true}, // any - {"~0.0.0", false}, // tildes expand into ranges - {"=2.0", false}, // abbreviated versions print as full - {"4.1.x", false}, // wildcards expand into ranges - {">= 1.1.0", false}, // does not produce spaces on ranges - {"4.1.0", true}, - {"!=4.1.0", true}, - {">=1.1.0", true}, - {">1.0.0, <=1.1.0", true}, - {"<=1.1.0", true}, - {">=1.1.7, <1.3.0", true}, // tilde width - {">=1.1.0, <=2.0.0", true}, // no unary op on lte max - {">1.1.3, <2.0.0", true}, // no unary op on gt min - {">1.1.0, <=2.0.0", true}, // no unary op on gt min and lte max - {">=1.1.0, <=1.2.0", true}, // no unary op on lte max - {">1.1.1, <1.2.0", true}, // no unary op on gt min - {">1.1.7, <=2.0.0", true}, // no unary op on gt min and lte max - {">1.1.7, <=2.0.0", true}, // no unary op on gt min and lte max - {">=0.1.7, <1.0.0", true}, // caret shifting below 1.0.0 - {">=0.1.7, <0.3.0", true}, // caret shifting width below 1.0.0 - } - - for _, fix := range tests { - c, err := NewConstraint(fix.io) - if err != nil { - t.Errorf("Valid constraint string produced unexpected error: %s", err) - } - - eq := fix.io == c.String() - if eq != fix.eq { - if eq { - t.Errorf("Constraint %q should not have reproduced input string %q, but did", c, fix.io) - } else { - t.Errorf("Constraint should have reproduced input string %q, but instead produced %q", fix.io, c) - } - } - } -} - -func TestBidirectionalSerializationIC(t *testing.T) { - tests := []struct { - io string - eq bool - }{ - {"*", true}, // any - {"=2.0.0", true}, // versions retain leading = - {"2.0.0", true}, // (no) caret in, (no) caret out - } - - for _, fix := range tests { - c, err := NewConstraintIC(fix.io) - if err != nil { - t.Errorf("Valid constraint string produced unexpected error: %s", err) - } - - eq := fix.io == c.ImpliedCaretString() - if eq != fix.eq { - if eq { - t.Errorf("Constraint %q should not have reproduced input string %q, but did", c, fix.io) - } else { - t.Errorf("Constraint should have reproduced input string %q, but instead produced %q", fix.io, c) - } - } - } -} - -func TestPreferUnaryOpForm(t *testing.T) { - tests := []struct { - in, out string - }{ - {">=0.1.7, <0.2.0", "^0.1.7"}, // caret shifting below 1.0.0 - {">=1.1.0, <2.0.0", "^1.1.0"}, - {">=1.1.0, <2.0.0, !=1.2.3", "^1.1.0, !=1.2.3"}, - } - - for _, fix := range tests { - c, err := NewConstraint(fix.in) - if err != nil { - t.Errorf("Valid constraint string produced unexpected error: %s", err) - } - - if fix.out != c.String() { - t.Errorf("Constraint %q was not transformed into expected output string %q", fix.in, fix.out) - } - } -} - -func TestRewriteRange(t *testing.T) { - tests := []struct { - c string - nc string - }{ - {"2-3", ">= 2, <= 3"}, - {"2-3, 2-3", ">= 2, <= 3,>= 2, <= 3"}, - {"2-3, 4.0.0-5.1", ">= 2, <= 3,>= 4.0.0, <= 5.1"}, - {"v2-3, 2-3", "v2-3,>= 2, <= 3"}, - } - - for _, tc := range tests { - o := rewriteRange(tc.c) - - if o != tc.nc { - t.Errorf("Range %s rewritten incorrectly as '%s'", tc.c, o) - } - } -} - -func TestIsX(t *testing.T) { - tests := []struct { - t string - c bool - }{ - {"A", false}, - {"%", false}, - {"X", true}, - {"x", true}, - {"*", true}, - } - - for _, tc := range tests { - a := isX(tc.t) - if a != tc.c { - t.Errorf("Function isX error on %s", tc.t) - } - } -} - -func TestUnionErr(t *testing.T) { - u1 := Union( - rangeConstraint{ - min: newV(3, 0, 0), - max: newV(4, 0, 0), - includeMin: true, - includeMax: true, - }, - rangeConstraint{ - min: newV(1, 0, 0), - max: newV(2, 0, 0), - includeMin: true, - }, - ) - fail := u1.Matches(newV(2, 5, 0)) - failstr := `2.5.0 is greater than or equal to the maximum of ^1.0.0 -2.5.0 is less than the minimum of >=3.0.0, <=4.0.0` - if fail.Error() != failstr { - t.Errorf("Did not get expected failure message from union, got %q", fail) - } -} - -func TestIsSuperset(t *testing.T) { - rc := []rangeConstraint{ - { - min: newV(1, 2, 0), - max: newV(2, 0, 0), - includeMin: true, - }, - { - min: newV(1, 2, 0), - max: newV(2, 1, 0), - }, - { - min: Version{special: zeroVersion}, - max: newV(1, 10, 0), - }, - { - min: newV(2, 0, 0), - max: Version{special: infiniteVersion}, - }, - { - min: newV(1, 2, 0), - max: newV(2, 0, 0), - includeMax: true, - }, - } - - for _, c := range rc { - - // Superset comparison is not strict, so a range should always be a superset - // of itself. - if !c.isSupersetOf(c) { - t.Errorf("Ranges should be supersets of themselves; %s indicated it was not", c) - } - } - - pairs := []struct{ l, r rangeConstraint }{ - { - // ensures lte is handled correctly (min side) - l: rc[0], - r: rc[1], - }, - { - // ensures nil on min side works well - l: rc[0], - r: rc[2], - }, - { - // ensures nil on max side works well - l: rc[0], - r: rc[3], - }, - { - // ensures nils on both sides work well - l: rc[2], - r: rc[3], - }, - { - // ensures gte is handled correctly (max side) - l: rc[2], - r: rc[4], - }, - } - - for _, p := range pairs { - if p.l.isSupersetOf(p.r) { - t.Errorf("%s is not a superset of %s", p.l, p.r) - } - if p.r.isSupersetOf(p.l) { - t.Errorf("%s is not a superset of %s", p.r, p.l) - } - } - - rc[1].max.minor = 0 - - if !rc[0].isSupersetOf(rc[1]) { - t.Errorf("%s is a superset of %s", rc[0], rc[1]) - } - rc[1].includeMax = true - if rc[1].isSupersetOf(rc[0]) { - t.Errorf("%s is not a superset of %s", rc[1], rc[0]) - } - rc[0].includeMin = false - if !rc[1].isSupersetOf(rc[0]) { - t.Errorf("%s is a superset of %s", rc[1], rc[0]) - } - - // isSupersetOf ignores excludes, so even though this would make rc[1] not a - // superset of rc[0] anymore, it should still say it is. - rc[1].excl = []Version{ - newV(1, 5, 0), - } - - if !rc[1].isSupersetOf(rc[0]) { - t.Errorf("%s is still a superset of %s, because isSupersetOf is supposed to ignore excluded versions", rc[1], rc[0]) - } -} diff --git a/vendor/github.com/Masterminds/semver/set_ops_test.go b/vendor/github.com/Masterminds/semver/set_ops_test.go deleted file mode 100644 index c08f2761..00000000 --- a/vendor/github.com/Masterminds/semver/set_ops_test.go +++ /dev/null @@ -1,932 +0,0 @@ -package semver - -import "testing" - -func TestIntersection(t *testing.T) { - var actual Constraint - rc1 := rangeConstraint{ - min: newV(1, 0, 0), - max: newV(2, 0, 0), - } - - if actual = Intersection(); !IsNone(actual) { - t.Errorf("Intersection of nothing should always produce None; got %q", actual) - } - - if actual = Intersection(rc1); !constraintEq(actual, rc1) { - t.Errorf("Intersection of one item should always return that item; got %q", actual) - } - - if actual = Intersection(rc1, None()); !IsNone(actual) { - t.Errorf("Intersection of anything with None should always produce None; got %q", actual) - } - - if actual = Intersection(rc1, Any()); !constraintEq(actual, rc1) { - t.Errorf("Intersection of anything with Any should return self; got %q", actual) - } - - v1 := newV(1, 5, 0) - if actual = Intersection(rc1, v1); !constraintEq(actual, v1) { - t.Errorf("Got constraint %q, but expected %q", actual, v1) - } - - rc2 := rangeConstraint{ - min: newV(1, 2, 0), - max: newV(2, 2, 0), - } - result := rangeConstraint{ - min: newV(1, 2, 0), - max: newV(2, 0, 0), - } - - if actual = Intersection(rc1, rc2); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - - u1 := unionConstraint{ - rangeConstraint{ - min: newV(1, 2, 0), - max: newV(3, 0, 0), - }, - newV(3, 1, 0), - } - - if actual = Intersection(u1, rc1); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - if actual = Intersection(rc1, newV(2, 0, 5), u1); !IsNone(actual) { - t.Errorf("First two are disjoint, should have gotten None but got %q", actual) - } -} - -func TestRangeIntersection(t *testing.T) { - var actual Constraint - // Test magic cases - rc1 := rangeConstraint{ - min: newV(1, 0, 0), - max: newV(2, 0, 0), - } - if actual = rc1.Intersect(Any()); !constraintEq(actual, rc1) { - t.Errorf("Intersection of anything with Any should return self; got %q", actual) - } - if actual = rc1.Intersect(None()); !IsNone(actual) { - t.Errorf("Intersection of anything with None should always produce None; got %q", actual) - } - - // Test single version cases - - // single v, in range - v1 := newV(1, 5, 0) - - if actual = rc1.Intersect(v1); !constraintEq(actual, v1) { - t.Errorf("Intersection of version with matching range should return the version; got %q", actual) - } - - // now exclude just that version - rc1.excl = []Version{v1} - if actual = rc1.Intersect(v1); !IsNone(actual) { - t.Errorf("Intersection of version with range having specific exclude for that version should produce None; got %q", actual) - } - - // and, of course, none if the version is out of range - v2 := newV(0, 5, 0) - if actual = rc1.Intersect(v2); !IsNone(actual) { - t.Errorf("Intersection of version with non-matching range should produce None; got %q", actual) - } - - // Test basic overlap case - rc1 = rangeConstraint{ - min: newV(1, 0, 0), - max: newV(2, 0, 0), - } - rc2 := rangeConstraint{ - min: newV(1, 2, 0), - max: newV(2, 2, 0), - } - result := rangeConstraint{ - min: newV(1, 2, 0), - max: newV(2, 0, 0), - } - - if actual = rc1.Intersect(rc2); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - if actual = rc2.Intersect(rc1); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - - // And with includes - rc1.includeMin = true - rc1.includeMax = true - rc2.includeMin = true - rc2.includeMax = true - result.includeMin = true - result.includeMax = true - - if actual = rc1.Intersect(rc2); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - if actual = rc2.Intersect(rc1); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - - // Overlaps with nils - rc1 = rangeConstraint{ - min: newV(1, 0, 0), - max: Version{special: infiniteVersion}, - } - rc2 = rangeConstraint{ - min: Version{special: zeroVersion}, - max: newV(2, 2, 0), - } - result = rangeConstraint{ - min: newV(1, 0, 0), - max: newV(2, 2, 0), - } - - if actual = rc1.Intersect(rc2); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - if actual = rc2.Intersect(rc1); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - - // And with includes - rc1.includeMin = true - rc2.includeMax = true - result.includeMin = true - result.includeMax = true - - if actual = rc1.Intersect(rc2); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - if actual = rc2.Intersect(rc1); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - - // Test superset overlap case - rc1 = rangeConstraint{ - min: newV(1, 5, 0), - max: newV(2, 0, 0), - } - rc2 = rangeConstraint{ - min: newV(1, 0, 0), - max: newV(3, 0, 0), - } - result = rangeConstraint{ - min: newV(1, 5, 0), - max: newV(2, 0, 0), - } - - if actual = rc1.Intersect(rc2); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - if actual = rc2.Intersect(rc1); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - - // Make sure irrelevant includes don't leak in - rc2.includeMin = true - rc2.includeMax = true - - if actual = rc1.Intersect(rc2); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - if actual = rc2.Intersect(rc1); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - - // But relevant includes get used - rc1.includeMin = true - rc1.includeMax = true - result.includeMin = true - result.includeMax = true - - if actual = rc1.Intersect(rc2); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - if actual = rc2.Intersect(rc1); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - - // Test disjoint case - rc1 = rangeConstraint{ - min: newV(1, 5, 0), - max: newV(1, 6, 0), - } - rc2 = rangeConstraint{ - min: newV(2, 0, 0), - max: newV(3, 0, 0), - } - - if actual = rc1.Intersect(rc2); !constraintEq(actual, None()) { - t.Errorf("Got constraint %q, but expected %q", actual, None()) - } - if actual = rc2.Intersect(rc1); !constraintEq(actual, None()) { - t.Errorf("Got constraint %q, but expected %q", actual, None()) - } - - // Test disjoint at gt/lt boundary (non-adjacent) - rc1 = rangeConstraint{ - min: newV(1, 5, 0), - max: newV(2, 0, 0), - } - rc2 = rangeConstraint{ - min: newV(2, 0, 0), - max: newV(3, 0, 0), - } - - if actual = rc1.Intersect(rc2); !constraintEq(actual, None()) { - t.Errorf("Got constraint %q, but expected %q", actual, None()) - } - if actual = rc2.Intersect(rc1); !constraintEq(actual, None()) { - t.Errorf("Got constraint %q, but expected %q", actual, None()) - } - - // Now, just have them touch at a single version - rc1.includeMax = true - rc2.includeMin = true - - vresult := newV(2, 0, 0) - if actual = rc1.Intersect(rc2); !constraintEq(actual, vresult) { - t.Errorf("Got constraint %q, but expected %q", actual, vresult) - } - if actual = rc2.Intersect(rc1); !constraintEq(actual, vresult) { - t.Errorf("Got constraint %q, but expected %q", actual, vresult) - } - - // Test excludes in intersection range - rc1 = rangeConstraint{ - min: newV(1, 5, 0), - max: newV(2, 0, 0), - excl: []Version{ - newV(1, 6, 0), - }, - } - rc2 = rangeConstraint{ - min: newV(1, 0, 0), - max: newV(3, 0, 0), - } - - if actual = rc1.Intersect(rc2); !constraintEq(actual, rc1) { - t.Errorf("Got constraint %q, but expected %q", actual, rc1) - } - if actual = rc2.Intersect(rc1); !constraintEq(actual, rc1) { - t.Errorf("Got constraint %q, but expected %q", actual, rc1) - } - - // Test excludes not in intersection range - rc1 = rangeConstraint{ - min: newV(1, 5, 0), - max: newV(2, 0, 0), - } - rc2 = rangeConstraint{ - min: newV(1, 0, 0), - max: newV(3, 0, 0), - excl: []Version{ - newV(1, 1, 0), - }, - } - - if actual = rc1.Intersect(rc2); !constraintEq(actual, rc1) { - t.Errorf("Got constraint %q, but expected %q", actual, rc1) - } - if actual = rc2.Intersect(rc1); !constraintEq(actual, rc1) { - t.Errorf("Got constraint %q, but expected %q", actual, rc1) - } - - // Test min, and greater min - rc1 = rangeConstraint{ - min: newV(1, 0, 0), - max: Version{special: infiniteVersion}, - } - rc2 = rangeConstraint{ - min: newV(1, 5, 0), - max: Version{special: infiniteVersion}, - includeMin: true, - } - - if actual = rc1.Intersect(rc2); !constraintEq(actual, rc2) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - if actual = rc2.Intersect(rc1); !constraintEq(actual, rc2) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - - // Test max, and lesser max - rc1 = rangeConstraint{ - max: newV(1, 0, 0), - } - rc2 = rangeConstraint{ - max: newV(1, 5, 0), - } - result = rangeConstraint{ - max: newV(1, 0, 0), - } - - if actual = rc1.Intersect(rc2); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - if actual = rc2.Intersect(rc1); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - - // Ensure pure excludes come through as they should - rc1 = rangeConstraint{ - min: Version{special: zeroVersion}, - max: Version{special: infiniteVersion}, - excl: []Version{ - newV(1, 6, 0), - }, - } - - rc2 = rangeConstraint{ - min: Version{special: zeroVersion}, - max: Version{special: infiniteVersion}, - excl: []Version{ - newV(1, 6, 0), - newV(1, 7, 0), - }, - } - - if actual = Any().Intersect(rc1); !constraintEq(actual, rc1) { - t.Errorf("Got constraint %q, but expected %q", actual, rc1) - } - if actual = rc1.Intersect(Any()); !constraintEq(actual, rc1) { - t.Errorf("Got constraint %q, but expected %q", actual, rc1) - } - if actual = rc1.Intersect(rc2); !constraintEq(actual, rc2) { - t.Errorf("Got constraint %q, but expected %q", actual, rc2) - } - - // TODO test the pre-release special range stuff -} - -func TestRangeUnion(t *testing.T) { - var actual Constraint - // Test magic cases - rc1 := rangeConstraint{ - min: newV(1, 0, 0), - max: newV(2, 0, 0), - } - if actual = rc1.Union(Any()); !IsAny(actual) { - t.Errorf("Union of anything with Any should always produce Any; got %q", actual) - } - if actual = rc1.Union(None()); !constraintEq(actual, rc1) { - t.Errorf("Union of anything with None should return self; got %q", actual) - } - - // Test single version cases - - // single v, in range - v1 := newV(1, 5, 0) - - if actual = rc1.Union(v1); !constraintEq(actual, rc1) { - t.Errorf("Union of version with matching range should return the range; got %q", actual) - } - - // now exclude just that version - rc2 := rc1.dup() - rc2.excl = []Version{v1} - if actual = rc2.Union(v1); !constraintEq(actual, rc1) { - t.Errorf("Union of version with range having specific exclude for that version should produce the range without that exclude; got %q", actual) - } - - // and a union if the version is not within the range - v2 := newV(0, 5, 0) - uresult := unionConstraint{v2, rc1} - if actual = rc1.Union(v2); !constraintEq(actual, uresult) { - t.Errorf("Union of version with non-matching range should produce a unionConstraint with those two; got %q", actual) - } - - // union with version at the min should ensure "oreq" - v2 = newV(1, 0, 0) - rc3 := rc1 - rc3.includeMin = true - - if actual = rc1.Union(v2); !constraintEq(actual, rc3) { - t.Errorf("Union of range with version at min end should add includeMin (%q), but got %q", rc3, actual) - } - if actual = v2.Union(rc1); !constraintEq(actual, rc3) { - t.Errorf("Union of range with version at min end should add includeMin (%q), but got %q", rc3, actual) - } - - // same at max end - v2 = newV(2, 0, 0) - rc3.includeMin = false - rc3.includeMax = true - - if actual = rc1.Union(v2); !constraintEq(actual, rc3) { - t.Errorf("Union of range with version at max end should add includeMax (%q), but got %q", rc3, actual) - } - if actual = v2.Union(rc1); !constraintEq(actual, rc3) { - t.Errorf("Union of range with version at max end should add includeMax (%q), but got %q", rc3, actual) - } - - // Test basic overlap case - rc1 = rangeConstraint{ - min: newV(1, 0, 0), - max: newV(2, 0, 0), - } - rc2 = rangeConstraint{ - min: newV(1, 2, 0), - max: newV(2, 2, 0), - } - result := rangeConstraint{ - min: newV(1, 0, 0), - max: newV(2, 2, 0), - } - - if actual = rc1.Union(rc2); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - if actual = rc2.Union(rc1); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - - // And with includes - rc1.includeMin = true - rc1.includeMax = true - rc2.includeMin = true - rc2.includeMax = true - result.includeMin = true - result.includeMax = true - - if actual = rc1.Union(rc2); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - if actual = rc2.Union(rc1); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - - // Overlaps with nils - rc1 = rangeConstraint{ - min: newV(1, 0, 0), - max: Version{special: infiniteVersion}, - } - rc2 = rangeConstraint{ - min: Version{special: zeroVersion}, - max: newV(2, 2, 0), - } - - if actual = rc1.Union(rc2); !constraintEq(actual, Any()) { - t.Errorf("Got constraint %q, but expected %q", actual, Any()) - } - if actual = rc2.Union(rc1); !constraintEq(actual, Any()) { - t.Errorf("Got constraint %q, but expected %q", actual, Any()) - } - - // Just one nil in overlap - rc1.max = newV(2, 0, 0) - result = rangeConstraint{ - min: Version{special: zeroVersion}, - max: newV(2, 2, 0), - } - - if actual = rc1.Union(rc2); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - if actual = rc2.Union(rc1); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - - rc1.max = Version{special: infiniteVersion} - rc2.min = newV(1, 5, 0) - result = rangeConstraint{ - min: newV(1, 0, 0), - max: Version{special: infiniteVersion}, - } - - if actual = rc1.Union(rc2); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - if actual = rc2.Union(rc1); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - - // Test superset overlap case - rc1 = rangeConstraint{ - min: newV(1, 5, 0), - max: newV(2, 0, 0), - } - rc2 = rangeConstraint{ - min: newV(1, 0, 0), - max: newV(3, 0, 0), - } - - if actual = rc1.Union(rc2); !constraintEq(actual, rc2) { - t.Errorf("Got constraint %q, but expected %q", actual, rc2) - } - if actual = rc2.Union(rc1); !constraintEq(actual, rc2) { - t.Errorf("Got constraint %q, but expected %q", actual, rc2) - } - - // Test disjoint case - rc1 = rangeConstraint{ - min: newV(1, 5, 0), - max: newV(1, 6, 0), - } - rc2 = rangeConstraint{ - min: newV(2, 0, 0), - max: newV(3, 0, 0), - } - uresult = unionConstraint{rc1, rc2} - - if actual = rc1.Union(rc2); !constraintEq(actual, uresult) { - t.Errorf("Got constraint %q, but expected %q", actual, uresult) - } - if actual = rc2.Union(rc1); !constraintEq(actual, uresult) { - t.Errorf("Got constraint %q, but expected %q", actual, uresult) - } - - // Test disjoint at gt/lt boundary (non-adjacent) - rc1 = rangeConstraint{ - min: newV(1, 5, 0), - max: newV(2, 0, 0), - } - rc2 = rangeConstraint{ - min: newV(2, 0, 0), - max: newV(3, 0, 0), - } - uresult = unionConstraint{rc1, rc2} - - if actual = rc1.Union(rc2); !constraintEq(actual, uresult) { - t.Errorf("Got constraint %q, but expected %q", actual, uresult) - } - if actual = rc2.Union(rc1); !constraintEq(actual, uresult) { - t.Errorf("Got constraint %q, but expected %q", actual, uresult) - } - - // Now, just have them touch at a single version - rc1.includeMax = true - rc2.includeMin = true - result = rangeConstraint{ - min: newV(1, 5, 0), - max: newV(3, 0, 0), - } - - if actual = rc1.Union(rc2); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - if actual = rc2.Union(rc1); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - - // And top-adjacent at that version - rc2.includeMin = false - if actual = rc1.Union(rc2); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - if actual = rc2.Union(rc1); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - // And bottom-adjacent at that version - rc1.includeMax = false - rc2.includeMin = true - if actual = rc1.Union(rc2); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - if actual = rc2.Union(rc1); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - - // Test excludes in overlapping range - rc1 = rangeConstraint{ - min: newV(1, 5, 0), - max: newV(2, 0, 0), - excl: []Version{ - newV(1, 6, 0), - }, - } - rc2 = rangeConstraint{ - min: newV(1, 0, 0), - max: newV(3, 0, 0), - } - - if actual = rc1.Union(rc2); !constraintEq(actual, rc2) { - t.Errorf("Got constraint %q, but expected %q", actual, rc2) - } - if actual = rc2.Union(rc1); !constraintEq(actual, rc2) { - t.Errorf("Got constraint %q, but expected %q", actual, rc2) - } - - // Test excludes not in non-overlapping range - rc1 = rangeConstraint{ - min: newV(1, 5, 0), - max: newV(2, 0, 0), - } - rc2 = rangeConstraint{ - min: newV(1, 0, 0), - max: newV(3, 0, 0), - excl: []Version{ - newV(1, 1, 0), - }, - } - - if actual = rc1.Union(rc2); !constraintEq(actual, rc2) { - t.Errorf("Got constraint %q, but expected %q", actual, rc2) - } - if actual = rc2.Union(rc1); !constraintEq(actual, rc2) { - t.Errorf("Got constraint %q, but expected %q", actual, rc2) - } - - // Ensure pure excludes come through as they should - rc1 = rangeConstraint{ - min: Version{special: zeroVersion}, - max: Version{special: infiniteVersion}, - excl: []Version{ - newV(1, 6, 0), - }, - } - - rc2 = rangeConstraint{ - min: Version{special: zeroVersion}, - max: Version{special: infiniteVersion}, - excl: []Version{ - newV(1, 6, 0), - newV(1, 7, 0), - }, - } - - if actual = rc1.Union(rc2); !constraintEq(actual, rc1) { - t.Errorf("Got constraint %q, but expected %q", actual, rc1) - } - if actual = rc2.Union(rc1); !constraintEq(actual, rc1) { - t.Errorf("Got constraint %q, but expected %q", actual, rc1) - } - - rc1 = rangeConstraint{ - min: Version{special: zeroVersion}, - max: Version{special: infiniteVersion}, - excl: []Version{ - newV(1, 5, 0), - }, - } - - if actual = rc1.Union(rc2); !constraintEq(actual, Any()) { - t.Errorf("Got constraint %q, but expected %q", actual, Any()) - } - if actual = rc2.Union(rc1); !constraintEq(actual, Any()) { - t.Errorf("Got constraint %q, but expected %q", actual, Any()) - } - - // TODO test the pre-release special range stuff -} - -func TestUnionIntersection(t *testing.T) { - var actual Constraint - // magic first - u1 := unionConstraint{ - newV(1, 1, 0), - newV(1, 2, 0), - newV(1, 3, 0), - } - if actual = u1.Intersect(Any()); !constraintEq(actual, u1) { - t.Errorf("Intersection of anything with Any should return self; got %s", actual) - } - if actual = u1.Intersect(None()); !IsNone(actual) { - t.Errorf("Intersection of anything with None should always produce None; got %s", actual) - } - if u1.MatchesAny(None()) { - t.Errorf("Can't match any when intersected with None") - } - - // intersect of unions with single versions - v1 := newV(1, 1, 0) - if actual = u1.Intersect(v1); !constraintEq(actual, v1) { - t.Errorf("Got constraint %q, but expected %q", actual, v1) - } - if actual = v1.Intersect(u1); !constraintEq(actual, v1) { - t.Errorf("Got constraint %q, but expected %q", actual, v1) - } - - // intersect of range with union of versions - u1 = unionConstraint{ - newV(1, 1, 0), - newV(1, 2, 0), - newV(1, 3, 0), - } - rc1 := rangeConstraint{ - min: newV(1, 0, 0), - max: newV(2, 0, 0), - } - - if actual = u1.Intersect(rc1); !constraintEq(actual, u1) { - t.Errorf("Got constraint %q, but expected %q", actual, u1) - } - if actual = rc1.Intersect(u1); !constraintEq(actual, u1) { - t.Errorf("Got constraint %q, but expected %q", actual, u1) - } - - u2 := unionConstraint{ - newV(1, 1, 0), - newV(1, 2, 0), - } - - if actual = u1.Intersect(u2); !constraintEq(actual, u2) { - t.Errorf("Got constraint %q, but expected %q", actual, u2) - } - - // Overlapping sub/supersets - rc1 = rangeConstraint{ - min: newV(1, 5, 0), - max: newV(1, 6, 0), - } - rc2 := rangeConstraint{ - min: newV(2, 0, 0), - max: newV(3, 0, 0), - } - rc3 = rangeConstraint{ - min: newV(1, 0, 0), - max: newV(2, 0, 0), - } - rc4 := rangeConstraint{ - min: newV(2, 5, 0), - max: newV(2, 6, 0), - } - u1 = unionConstraint{rc1, rc2} - u2 = unionConstraint{rc3, rc4} - ur := unionConstraint{rc1, rc4} - - if actual = u1.Intersect(u2); !constraintEq(actual, ur) { - t.Errorf("Got constraint %q, but expected %q", actual, ur) - } - if actual = u2.Intersect(u1); !constraintEq(actual, ur) { - t.Errorf("Got constraint %q, but expected %q", actual, ur) - } - - // Ensure excludes carry as they should - rc1.excl = []Version{newV(1, 5, 5)} - u1 = unionConstraint{rc1, rc2} - ur = unionConstraint{rc1, rc4} - - if actual = u1.Intersect(u2); !constraintEq(actual, ur) { - t.Errorf("Got constraint %q, but expected %q", actual, ur) - } - if actual = u2.Intersect(u1); !constraintEq(actual, ur) { - t.Errorf("Got constraint %q, but expected %q", actual, ur) - } -} - -func TestUnionUnion(t *testing.T) { - var actual Constraint - // magic first - u1 := unionConstraint{ - newV(1, 1, 0), - newV(1, 2, 0), - newV(1, 3, 0), - } - if actual = u1.Union(Any()); !IsAny(actual) { - t.Errorf("Union of anything with Any should always return Any; got %s", actual) - } - if actual = u1.Union(None()); !constraintEq(actual, u1) { - t.Errorf("Union of anything with None should always return self; got %s", actual) - } - - // union of uc with single versions - // already present - v1 := newV(1, 2, 0) - if actual = u1.Union(v1); !constraintEq(actual, u1) { - t.Errorf("Got constraint %q, but expected %q", actual, u1) - } - if actual = v1.Union(u1); !constraintEq(actual, u1) { - t.Errorf("Got constraint %q, but expected %q", actual, u1) - } - - // not present - v2 := newV(1, 4, 0) - ur := append(u1, v2) - if actual = u1.Union(v2); !constraintEq(actual, ur) { - t.Errorf("Got constraint %q, but expected %q", actual, ur) - } - if actual = v2.Union(u1); !constraintEq(actual, ur) { - t.Errorf("Got constraint %q, but expected %q", actual, ur) - } - - // union of uc with uc, all versions - u2 := unionConstraint{ - newV(1, 3, 0), - newV(1, 4, 0), - newV(1, 5, 0), - } - ur = unionConstraint{ - newV(1, 1, 0), - newV(1, 2, 0), - newV(1, 3, 0), - newV(1, 4, 0), - newV(1, 5, 0), - } - - if actual = u1.Union(u2); !constraintEq(actual, ur) { - t.Errorf("Got constraint %q, but expected %q", actual, ur) - } - if actual = u2.Union(u1); !constraintEq(actual, ur) { - t.Errorf("Got constraint %q, but expected %q", actual, ur) - } - - // union that should compress versions into range - rc1 := rangeConstraint{ - min: newV(1, 0, 0), - max: newV(2, 0, 0), - } - - if actual = u1.Union(rc1); !constraintEq(actual, rc1) { - t.Errorf("Got constraint %q, but expected %q", actual, rc1) - } - if actual = rc1.Union(u1); !constraintEq(actual, rc1) { - t.Errorf("Got constraint %q, but expected %q", actual, rc1) - } - - rc1.max = newV(1, 4, 5) - u3 := append(u2, newV(1, 7, 0)) - ur = unionConstraint{ - rc1, - newV(1, 5, 0), - newV(1, 7, 0), - } - - if actual = u3.Union(rc1); !constraintEq(actual, ur) { - t.Errorf("Got constraint %q, but expected %q", actual, ur) - } - if actual = rc1.Union(u3); !constraintEq(actual, ur) { - t.Errorf("Got constraint %q, but expected %q", actual, ur) - } -} - -// Most version stuff got tested by range and/or union b/c most tests were -// repeated bidirectionally (set operations are commutative; testing in pairs -// helps us catch any situation where we fail to maintain that invariant) -func TestVersionSetOps(t *testing.T) { - var actual Constraint - - v1 := newV(1, 0, 0) - - if actual = v1.Intersect(v1); !constraintEq(actual, v1) { - t.Errorf("Version intersected with itself should be itself, got %q", actual) - } - if !v1.MatchesAny(v1) { - t.Errorf("MatchesAny should work with a version against itself") - } - - v2 := newV(2, 0, 0) - if actual = v1.Intersect(v2); !IsNone(actual) { - t.Errorf("Versions should only intersect with themselves, got %q", actual) - } - if v1.MatchesAny(v2) { - t.Errorf("MatchesAny should not work when combined with anything other than itself") - } - - result := unionConstraint{v1, v2} - - if actual = v1.Union(v1); !constraintEq(actual, v1) { - t.Errorf("Version union with itself should return self, got %q", actual) - } - - if actual = v1.Union(v2); !constraintEq(actual, result) { - t.Errorf("Got constraint %q, but expected %q", actual, result) - } - if actual = v1.Union(v2); !constraintEq(actual, result) { - // Duplicate just to make sure ordering works right - t.Errorf("Got constraint %q, but expected %q", actual, result) - } -} - -func TestAreAdjacent(t *testing.T) { - rc1 := rangeConstraint{ - min: newV(1, 0, 0), - max: newV(2, 0, 0), - } - rc2 := rangeConstraint{ - min: newV(1, 2, 0), - max: newV(2, 2, 0), - } - - if areAdjacent(rc1, rc2) { - t.Errorf("Ranges overlap, should not indicate as adjacent") - } - - rc2 = rangeConstraint{ - min: newV(2, 0, 0), - } - - if areAdjacent(rc1, rc2) { - t.Errorf("Ranges are non-overlapping and non-adjacent, but reported as adjacent") - } - - rc2.includeMin = true - - if !areAdjacent(rc1, rc2) { - t.Errorf("Ranges are non-overlapping and adjacent, but reported as non-adjacent") - } - - rc1.includeMax = true - - if areAdjacent(rc1, rc2) { - t.Errorf("Ranges are overlapping at a single version, but reported as adjacent") - } - - rc2.includeMin = false - if !areAdjacent(rc1, rc2) { - t.Errorf("Ranges are non-overlapping and adjacent, but reported as non-adjacent") - } -} diff --git a/vendor/github.com/Masterminds/semver/version_test.go b/vendor/github.com/Masterminds/semver/version_test.go deleted file mode 100644 index 1fae87f5..00000000 --- a/vendor/github.com/Masterminds/semver/version_test.go +++ /dev/null @@ -1,310 +0,0 @@ -package semver - -import ( - "testing" -) - -func TestNewVersion(t *testing.T) { - tests := []struct { - version string - err bool - }{ - {"1.2.3", false}, - {"v1.2.3", false}, - {"1.0", false}, - {"v1.0", false}, - {"1", false}, - {"v1", false}, - {"1.2.beta", true}, - {"v1.2.beta", true}, - {"foo", true}, - {"1.2-5", false}, - {"v1.2-5", false}, - {"1.2-beta.5", false}, - {"v1.2-beta.5", false}, - {"\n1.2", true}, - {"\nv1.2", true}, - {"1.2.0-x.Y.0+metadata", false}, - {"v1.2.0-x.Y.0+metadata", false}, - {"1.2.0-x.Y.0+metadata-width-hypen", false}, - {"v1.2.0-x.Y.0+metadata-width-hypen", false}, - {"1.2.3-rc1-with-hypen", false}, - {"v1.2.3-rc1-with-hypen", false}, - {"1.2.3.4", true}, - {"v1.2.3.4", true}, - } - - for _, tc := range tests { - _, err := NewVersion(tc.version) - if tc.err && err == nil { - t.Fatalf("expected error for version: %s", tc.version) - } else if !tc.err && err != nil { - t.Fatalf("error for version %s: %s", tc.version, err) - } - } -} - -func TestOriginal(t *testing.T) { - tests := []string{ - "1.2.3", - "v1.2.3", - "1.0", - "v1.0", - "1", - "v1", - "1.2-5", - "v1.2-5", - "1.2-beta.5", - "v1.2-beta.5", - "1.2.0-x.Y.0+metadata", - "v1.2.0-x.Y.0+metadata", - "1.2.0-x.Y.0+metadata-width-hypen", - "v1.2.0-x.Y.0+metadata-width-hypen", - "1.2.3-rc1-with-hypen", - "v1.2.3-rc1-with-hypen", - } - - for _, tc := range tests { - v, err := NewVersion(tc) - if err != nil { - t.Errorf("Error parsing version %s", tc) - } - - o := v.Original() - if o != tc { - t.Errorf("Error retrieving originl. Expected '%s' but got '%s'", tc, v) - } - } -} - -func TestParts(t *testing.T) { - v, err := NewVersion("1.2.3-beta.1+build.123") - if err != nil { - t.Error("Error parsing version 1.2.3-beta.1+build.123") - } - - if v.Major() != 1 { - t.Error("Major() returning wrong value") - } - if v.Minor() != 2 { - t.Error("Minor() returning wrong value") - } - if v.Patch() != 3 { - t.Error("Patch() returning wrong value") - } - if v.Prerelease() != "beta.1" { - t.Error("Prerelease() returning wrong value") - } - if v.Metadata() != "build.123" { - t.Error("Metadata() returning wrong value") - } -} - -func TestString(t *testing.T) { - tests := []struct { - version string - expected string - }{ - {"1.2.3", "1.2.3"}, - {"v1.2.3", "1.2.3"}, - {"1.0", "1.0.0"}, - {"v1.0", "1.0.0"}, - {"1", "1.0.0"}, - {"v1", "1.0.0"}, - {"1.2-5", "1.2.0-5"}, - {"v1.2-5", "1.2.0-5"}, - {"1.2-beta.5", "1.2.0-beta.5"}, - {"v1.2-beta.5", "1.2.0-beta.5"}, - {"1.2.0-x.Y.0+metadata", "1.2.0-x.Y.0+metadata"}, - {"v1.2.0-x.Y.0+metadata", "1.2.0-x.Y.0+metadata"}, - {"1.2.0-x.Y.0+metadata-width-hypen", "1.2.0-x.Y.0+metadata-width-hypen"}, - {"v1.2.0-x.Y.0+metadata-width-hypen", "1.2.0-x.Y.0+metadata-width-hypen"}, - {"1.2.3-rc1-with-hypen", "1.2.3-rc1-with-hypen"}, - {"v1.2.3-rc1-with-hypen", "1.2.3-rc1-with-hypen"}, - } - - for _, tc := range tests { - v, err := NewVersion(tc.version) - if err != nil { - t.Errorf("Error parsing version %s", tc) - } - - s := v.String() - if s != tc.expected { - t.Errorf("Error generating string. Expected '%s' but got '%s'", tc.expected, s) - } - } -} - -func TestCompare(t *testing.T) { - tests := []struct { - v1 string - v2 string - expected int - }{ - {"1.2.3", "1.5.1", -1}, - {"2.2.3", "1.5.1", 1}, - {"2.2.3", "2.2.2", 1}, - {"3.2-beta", "3.2-beta", 0}, - {"1.3", "1.1.4", 1}, - {"4.2", "4.2-beta", 1}, - {"4.2-beta", "4.2", -1}, - {"4.2-alpha", "4.2-beta", -1}, - {"4.2-alpha", "4.2-alpha", 0}, - {"4.2-beta.2", "4.2-beta.1", 1}, - {"4.2-beta2", "4.2-beta1", 1}, - {"4.2-beta", "4.2-beta.2", -1}, - {"4.2-beta", "4.2-beta.foo", 1}, - {"4.2-beta.2", "4.2-beta", 1}, - {"4.2-beta.foo", "4.2-beta", -1}, - {"1.2+bar", "1.2+baz", 0}, - } - - for _, tc := range tests { - v1, err := NewVersion(tc.v1) - if err != nil { - t.Errorf("Error parsing version: %s", err) - } - - v2, err := NewVersion(tc.v2) - if err != nil { - t.Errorf("Error parsing version: %s", err) - } - - a := v1.Compare(v2) - e := tc.expected - if a != e { - t.Errorf( - "Comparison of '%s' and '%s' failed. Expected '%d', got '%d'", - tc.v1, tc.v2, e, a, - ) - } - } - - // One-off tests for special version comparisons - zero := Version{special: zeroVersion} - inf := Version{special: infiniteVersion} - - if zero.Compare(inf) != -1 { - t.Error("Zero version should always be less than infinite version") - } - if zero.Compare(zero) != 0 { - t.Error("Zero version should equal itself") - } - if inf.Compare(zero) != 1 { - t.Error("Infinite version should always be greater than zero version") - } - if inf.Compare(inf) != 0 { - t.Error("Infinite version should equal itself") - } - - // Need to work vs. a normal version, too. - v := Version{} - - if zero.Compare(v) != -1 { - t.Error("Zero version should always be less than any normal version") - } - if inf.Compare(v) != 1 { - t.Error("Infinite version should always be greater than any normal version") - } -} - -func TestLessThan(t *testing.T) { - tests := []struct { - v1 string - v2 string - expected bool - }{ - {"1.2.3", "1.5.1", true}, - {"2.2.3", "1.5.1", false}, - {"3.2-beta", "3.2-beta", false}, - } - - for _, tc := range tests { - v1, err := NewVersion(tc.v1) - if err != nil { - t.Errorf("Error parsing version: %s", err) - } - - v2, err := NewVersion(tc.v2) - if err != nil { - t.Errorf("Error parsing version: %s", err) - } - - a := v1.LessThan(v2) - e := tc.expected - if a != e { - t.Errorf( - "Comparison of '%s' and '%s' failed. Expected '%t', got '%t'", - tc.v1, tc.v2, e, a, - ) - } - } -} - -func TestGreaterThan(t *testing.T) { - tests := []struct { - v1 string - v2 string - expected bool - }{ - {"1.2.3", "1.5.1", false}, - {"2.2.3", "1.5.1", true}, - {"3.2-beta", "3.2-beta", false}, - } - - for _, tc := range tests { - v1, err := NewVersion(tc.v1) - if err != nil { - t.Errorf("Error parsing version: %s", err) - } - - v2, err := NewVersion(tc.v2) - if err != nil { - t.Errorf("Error parsing version: %s", err) - } - - a := v1.GreaterThan(v2) - e := tc.expected - if a != e { - t.Errorf( - "Comparison of '%s' and '%s' failed. Expected '%t', got '%t'", - tc.v1, tc.v2, e, a, - ) - } - } -} - -func TestEqual(t *testing.T) { - tests := []struct { - v1 string - v2 string - expected bool - }{ - {"1.2.3", "1.5.1", false}, - {"2.2.3", "1.5.1", false}, - {"3.2-beta", "3.2-beta", true}, - {"3.2-beta+foo", "3.2-beta+bar", true}, - } - - for _, tc := range tests { - v1, err := NewVersion(tc.v1) - if err != nil { - t.Errorf("Error parsing version: %s", err) - } - - v2, err := NewVersion(tc.v2) - if err != nil { - t.Errorf("Error parsing version: %s", err) - } - - a := v1.Equal(v2) - e := tc.expected - if a != e { - t.Errorf( - "Comparison of '%s' and '%s' failed. Expected '%t', got '%t'", - tc.v1, tc.v2, e, a, - ) - } - } -} diff --git a/vendor/github.com/Masterminds/vcs/.gitignore b/vendor/github.com/Masterminds/vcs/.gitignore deleted file mode 100644 index daf913b1..00000000 --- a/vendor/github.com/Masterminds/vcs/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof diff --git a/vendor/github.com/Masterminds/vcs/.travis.yml b/vendor/github.com/Masterminds/vcs/.travis.yml deleted file mode 100644 index 47bd9491..00000000 --- a/vendor/github.com/Masterminds/vcs/.travis.yml +++ /dev/null @@ -1,29 +0,0 @@ -language: go - -go: - - 1.6 - - 1.7 - - 1.8 - - tip - -before_script: - - git version - - svn --version - -# Setting sudo access to false will let Travis CI use containers rather than -# VMs to run the tests. For more details see: -# - http://docs.travis-ci.com/user/workers/container-based-infrastructure/ -# - http://docs.travis-ci.com/user/workers/standard-infrastructure/ -sudo: false - -script: - - make setup - - make test - -notifications: - webhooks: - urls: - - https://webhooks.gitter.im/e/06e3328629952dabe3e0 - on_success: change # options: [always|never|change] default: always - on_failure: always # options: [always|never|change] default: always - on_start: never # options: [always|never|change] default: always diff --git a/vendor/github.com/Masterminds/vcs/CHANGELOG.md b/vendor/github.com/Masterminds/vcs/CHANGELOG.md deleted file mode 100644 index bdc6d1f2..00000000 --- a/vendor/github.com/Masterminds/vcs/CHANGELOG.md +++ /dev/null @@ -1,148 +0,0 @@ -# 1.11.1 (2017-04-28) - -## Fixed -- #76: Fix submodule handling for Windows (thanks @m0j0hn) - -# 1.11.0 (2017-03-23) - -## Added -- #65: Exposed CmdFromDir function (thanks @erizocosmico) - -## Changed -- #69: Updated testing for Go 1.8 - -## Fixed -- #64: Testing fatal error if bzr not installed (thanks @kevinburke) - -# 1.10.2 (2017-01-24) - -## Fixed -- #63: Remove extra quotes in submodule export (thanks @dt) - -# 1.10.1 (2017-01-18) - -## Fixed -- #62: Added windows testing via appveyor and fixed issues under windows. - -# 1.10.0 (2017-01-09) - -## Added -- #60: Handle Git submodules (thanks @sdboyer) -- #61: Add gometalinter to testing - -# 1.9.0 (2016-11-18) - -## Added -- #50: Auto-detect remotes with file:// prefix. -- #59: Testing against Go 1.7 - -## Changed -- Removed auto-detection for Google Code as the service is deprecated -- Added auto-detection of git.openstack.org - -## Fixed -- #53: Git not fetching tags off branch - -# 1.8.0 (2016-06-29) - -## Added -- #43: Detect when tool (e.g., git, svn, etc) not installed -- #49: Detect access denied and not found situations - -## Changed -- #48: Updated Go Report Gard url to new format -- Refactored SVN handling to detect when not in a top level directory -- Updating tagging to v[SemVer] structure for compatibility with other tools. - -## Fixed -- #45: Fixed hg's update method so that it pulls from remote before updates - -# 1.7.0 (2016-05-05) - -- Adds a glide.yaml file with some limited information. -- Implements #37: Ability to export source as a directory. -- Implements #36: Get current version-ish with Current method. This returns - a branch (if on tip) or equivalent tip, a tag if on a tag, or a revision if - on an individual revision. Note, the tip of branch is VCS specific so usage - may require detecting VCS type. - -# 1.6.1 (2016-04-27) - -- Fixed #30: tags from commit should not have ^{} appended (seen in git) -- Fixed #29: isDetachedHead fails with non-english locales (git) -- Fixed #33: Access denied and not found http errors causing xml parsing errors - -# 1.6.0 (2016-04-18) - -- Issue #26: Added Init method to initialize a repo at the local location - (thanks tony). -- Issue #19: Added method to retrieve tags for a commit. -- Issue #24: Reworked errors returned from common methods. Now differing - VCS implementations return the same errors. The original VCS specific error - is available on the error. See the docs for more details. -- Issue #25: Export the function RunFromDir which runs VCS commands from the - root of the local directory. This is useful for those that want to build and - extend on top of the vcs package (thanks tony). -- Issue #22: Added Ping command to test if remote location is present and - accessible. - -# 1.5.1 (2016-03-23) - -- Fixing bug parsing some Git commit dates. - -# 1.5.0 (2016-03-22) - -- Add Travis CI testing for Go 1.6. -- Issue #17: Add CommitInfo method allowing for a common way to get commit - metadata from all VCS. -- Autodetect types that have git@ or hg@ users. -- Autodetect git+ssh, bzr+ssh, git, and svn+ssh scheme urls. -- On Bitbucket for ssh style URLs retrieve the type from the URL. This allows - for private repo type detection. -- Issue #14: Autodetect ssh/scp style urls (thanks chonthu). - -# 1.4.1 (2016-03-07) - -- Fixes #16: some windows situations are unable to create parent directory. - -# 1.4.0 (2016-02-15) - -- Adding support for IBM JazzHub. - -# 1.3.1 (2016-01-27) - -- Issue #12: Failed to checkout Bzr repo when parent directory didn't - exist (thanks cyrilleverrier). - -# 1.3.0 (2015-11-09) - -- Issue #9: Added Date method to get the date/time of latest commit (thanks kamilchm). - -# 1.2.0 (2015-10-29) - -- Adding IsDirty method to detect a checkout with uncommitted changes. - -# 1.1.4 (2015-10-28) - -- Fixed #8: Git IsReference not detecting branches that have not been checked - out yet. - -# 1.1.3 (2015-10-21) - -- Fixing issue where there are multiple go-import statements for go redirects - -# 1.1.2 (2015-10-20) - -- Fixes #7: hg not checking out code when Get is called - -# 1.1.1 (2015-10-20) - -- Issue #6: Allow VCS commands to be run concurrently. - -# 1.1.0 (2015-10-19) - -- #5: Added output of failed command to returned errors. - -# 1.0.0 (2015-10-06) - -- Initial release. diff --git a/vendor/github.com/Masterminds/vcs/Makefile b/vendor/github.com/Masterminds/vcs/Makefile deleted file mode 100644 index 5d722c2f..00000000 --- a/vendor/github.com/Masterminds/vcs/Makefile +++ /dev/null @@ -1,41 +0,0 @@ -.PHONY: setup -setup: - go get -u gopkg.in/alecthomas/gometalinter.v1 - gometalinter.v1 --install - -.PHONY: test -test: validate lint - @echo "==> Running tests" - go test -v - -.PHONY: validate -validate: -# misspell finds the work adresář (used in bzr.go) as a mispelling of -# address. It finds adres. An issue has been filed at -# https://github.com/client9/misspell/issues/99. In the meantime adding -# adres to the ignore list. - @echo "==> Running static validations" - @gometalinter.v1 \ - --disable-all \ - --linter "misspell:misspell -i adres -j 1 {path}/*.go:PATH:LINE:COL:MESSAGE" \ - --enable deadcode \ - --severity deadcode:error \ - --enable gofmt \ - --enable gosimple \ - --enable ineffassign \ - --enable misspell \ - --enable vet \ - --tests \ - --vendor \ - --deadline 60s \ - ./... || exit_code=1 - -.PHONY: lint -lint: - @echo "==> Running linters" - @gometalinter.v1 \ - --disable-all \ - --enable golint \ - --vendor \ - --deadline 60s \ - ./... || : diff --git a/vendor/github.com/Masterminds/vcs/README.md b/vendor/github.com/Masterminds/vcs/README.md deleted file mode 100644 index a1126851..00000000 --- a/vendor/github.com/Masterminds/vcs/README.md +++ /dev/null @@ -1,48 +0,0 @@ -# VCS Repository Management for Go - -Manage repos in varying version control systems with ease through a common -interface. - -[![Build Status](https://travis-ci.org/Masterminds/vcs.svg)](https://travis-ci.org/Masterminds/vcs) [![GoDoc](https://godoc.org/github.com/Masterminds/vcs?status.png)](https://godoc.org/github.com/Masterminds/vcs) [![Go Report Card](https://goreportcard.com/badge/github.com/Masterminds/vcs)](https://goreportcard.com/report/github.com/Masterminds/vcs) -[![Build status](https://ci.appveyor.com/api/projects/status/vg3cjc561q2trobm?svg=true&passingText=windows%20build%20passing&failingText=windows%20build%20failing)](https://ci.appveyor.com/project/mattfarina/vcs) - - -## Quick Usage - -Quick usage: - - remote := "https://github.com/Masterminds/vcs" - local, _ := ioutil.TempDir("", "go-vcs") - repo, err := NewRepo(remote, local) - -In this case `NewRepo` will detect the VCS is Git and return a `GitRepo`. All of -the repos implement the `Repo` interface with a common set of features between -them. - -## Supported VCS - -Git, SVN, Bazaar (Bzr), and Mercurial (Hg) are currently supported. They each -have their own type (e.g., `GitRepo`) that follow a simple naming pattern. Each -type implements the `Repo` interface and has a constructor (e.g., `NewGitRepo`). -The constructors have the same signature as `NewRepo`. - -## Features - -- Clone or checkout a repository depending on the version control system. -- Pull updates to a repository. -- Get the currently checked out commit id. -- Checkout a commit id, branch, or tag (depending on the availability in the VCS). -- Get a list of tags and branches in the VCS. -- Check if a string value is a valid reference within the VCS. -- More... - -For more details see [the documentation](https://godoc.org/github.com/Masterminds/vcs). - -## Motivation - -The package `golang.org/x/tools/go/vcs` provides some valuable functionality -for working with packages in repositories in varying source control management -systems. That package, while useful and well tested, is designed with a specific -purpose in mind. Our uses went beyond the scope of that package. To implement -our scope we built a package that went beyond the functionality and scope -of `golang.org/x/tools/go/vcs`. diff --git a/vendor/github.com/Masterminds/vcs/appveyor.yml b/vendor/github.com/Masterminds/vcs/appveyor.yml deleted file mode 100644 index c0c9170f..00000000 --- a/vendor/github.com/Masterminds/vcs/appveyor.yml +++ /dev/null @@ -1,26 +0,0 @@ - -version: build-{build}.{branch} - -clone_folder: C:\gopath\src\github.com\Masterminds\vcs -shallow_clone: true - -environment: - GOPATH: C:\gopath - -platform: - - x64 - -install: - - go version - - go env - - choco install -y bzr - - set PATH=C:\Program Files (x86)\Bazaar;%PATH% - - bzr --version - -build_script: - - go install -v ./... - -test_script: - - go test -v - -deploy: off diff --git a/vendor/github.com/Masterminds/vcs/bzr_test.go b/vendor/github.com/Masterminds/vcs/bzr_test.go deleted file mode 100644 index 4b2e50ec..00000000 --- a/vendor/github.com/Masterminds/vcs/bzr_test.go +++ /dev/null @@ -1,328 +0,0 @@ -package vcs - -import ( - "io/ioutil" - "path/filepath" - "time" - //"log" - "os" - "testing" -) - -// Canary test to ensure BzrRepo implements the Repo interface. -var _ Repo = &BzrRepo{} - -// To verify bzr is working we perform integration testing -// with a known bzr service. Due to the long time of repeatedly checking out -// repos these tests are structured to work together. - -func TestBzr(t *testing.T) { - - tempDir, err := ioutil.TempDir("", "go-vcs-bzr-tests") - if err != nil { - t.Error(err) - } - defer func() { - err = os.RemoveAll(tempDir) - if err != nil { - t.Error(err) - } - }() - - repo, err := NewBzrRepo("https://launchpad.net/govcstestbzrrepo", tempDir+"/govcstestbzrrepo") - if err != nil { - t.Fatal(err) - } - - if repo.Vcs() != Bzr { - t.Error("Bzr is detecting the wrong type") - } - - // Check the basic getters. - if repo.Remote() != "https://launchpad.net/govcstestbzrrepo" { - t.Error("Remote not set properly") - } - if repo.LocalPath() != tempDir+"/govcstestbzrrepo" { - t.Error("Local disk location not set properly") - } - - //Logger = log.New(os.Stdout, "", log.LstdFlags) - - // Do an initial clone. - err = repo.Get() - if err != nil { - t.Errorf("Unable to clone Bzr repo. Err was %s", err) - } - - // Verify Bzr repo is a Bzr repo - if !repo.CheckLocal() { - t.Error("Problem checking out repo or Bzr CheckLocal is not working") - } - - // Test internal lookup mechanism used outside of Bzr specific functionality. - ltype, err := DetectVcsFromFS(tempDir + "/govcstestbzrrepo") - if err != nil { - t.Error("detectVcsFromFS unable to Bzr repo") - } - if ltype != Bzr { - t.Errorf("detectVcsFromFS detected %s instead of Bzr type", ltype) - } - - // Test NewRepo on existing checkout. This should simply provide a working - // instance without error based on looking at the local directory. - nrepo, nrerr := NewRepo("https://launchpad.net/govcstestbzrrepo", tempDir+"/govcstestbzrrepo") - if nrerr != nil { - t.Error(nrerr) - } - // Verify the right oject is returned. It will check the local repo type. - if !nrepo.CheckLocal() { - t.Error("Wrong version returned from NewRepo") - } - - v, err := repo.Current() - if err != nil { - t.Errorf("Error trying Bzr Current: %s", err) - } - if v != "-1" { - t.Errorf("Current failed to detect Bzr on tip of branch. Got version: %s", v) - } - - err = repo.UpdateVersion("2") - if err != nil { - t.Errorf("Unable to update Bzr repo version. Err was %s", err) - } - - // Use Version to verify we are on the right version. - v, err = repo.Version() - if v != "2" { - t.Error("Error checking checked out Bzr version") - } - if err != nil { - t.Error(err) - } - - v, err = repo.Current() - if err != nil { - t.Errorf("Error trying Bzr Current: %s", err) - } - if v != "2" { - t.Errorf("Current failed to detect Bzr on rev 2 of branch. Got version: %s", v) - } - - // Use Date to verify we are on the right commit. - d, err := repo.Date() - if d.Format(longForm) != "2015-07-31 09:50:42 -0400" { - t.Error("Error checking checked out Bzr commit date") - } - if err != nil { - t.Error(err) - } - - // Perform an update. - err = repo.Update() - if err != nil { - t.Error(err) - } - - v, err = repo.Version() - if v != "3" { - t.Error("Error checking checked out Bzr version") - } - if err != nil { - t.Error(err) - } - - tags, err := repo.Tags() - if err != nil { - t.Error(err) - } - if tags[0] != "1.0.0" { - t.Error("Bzr tags is not reporting the correct version") - } - - tags, err = repo.TagsFromCommit("2") - if err != nil { - t.Error(err) - } - if len(tags) != 0 { - t.Error("Bzr is incorrectly returning tags for a commit") - } - - tags, err = repo.TagsFromCommit("3") - if err != nil { - t.Error(err) - } - if len(tags) != 1 || tags[0] != "1.0.0" { - t.Error("Bzr is incorrectly returning tags for a commit") - } - - branches, err := repo.Branches() - if err != nil { - t.Error(err) - } - if len(branches) != 0 { - t.Error("Bzr is incorrectly returning branches") - } - - if !repo.IsReference("1.0.0") { - t.Error("Bzr is reporting a reference is not one") - } - - if repo.IsReference("foo") { - t.Error("Bzr is reporting a non-existent reference is one") - } - - if repo.IsDirty() { - t.Error("Bzr incorrectly reporting dirty") - } - - ci, err := repo.CommitInfo("3") - if err != nil { - t.Error(err) - } - if ci.Commit != "3" { - t.Error("Bzr.CommitInfo wrong commit id") - } - if ci.Author != "Matt Farina " { - t.Error("Bzr.CommitInfo wrong author") - } - if ci.Message != "Updated Readme with pointer." { - t.Error("Bzr.CommitInfo wrong message") - } - ti, err := time.Parse(time.RFC1123Z, "Fri, 31 Jul 2015 09:51:37 -0400") - if err != nil { - t.Error(err) - } - if !ti.Equal(ci.Date) { - t.Error("Bzr.CommitInfo wrong date") - } - - _, err = repo.CommitInfo("asdfasdfasdf") - if err != ErrRevisionUnavailable { - t.Error("Bzr didn't return expected ErrRevisionUnavailable") - } - - tempDir2, err := ioutil.TempDir("", "go-vcs-bzr-tests-export") - if err != nil { - t.Fatalf("Error creating temp directory: %s", err) - } - defer func() { - err = os.RemoveAll(tempDir2) - if err != nil { - t.Error(err) - } - }() - - exportDir := filepath.Join(tempDir2, "src") - - err = repo.ExportDir(exportDir) - if err != nil { - t.Errorf("Unable to export Bzr repo. Err was %s", err) - } - - _, err = os.Stat(filepath.Join(exportDir, "Readme.md")) - if err != nil { - t.Errorf("Error checking exported file in Bzr: %s", err) - } - - _, err = os.Stat(filepath.Join(exportDir, string(repo.Vcs()))) - if err != nil { - if found := os.IsNotExist(err); !found { - t.Errorf("Error checking exported metadata in Bzr: %s", err) - } - } else { - t.Error("Error checking Bzr metadata. It exists.") - } -} - -func TestBzrCheckLocal(t *testing.T) { - // Verify repo.CheckLocal fails for non-Bzr directories. - // TestBzr is already checking on a valid repo - tempDir, err := ioutil.TempDir("", "go-vcs-bzr-tests") - if err != nil { - t.Error(err) - } - defer func() { - err = os.RemoveAll(tempDir) - if err != nil { - t.Error(err) - } - }() - - repo, _ := NewBzrRepo("", tempDir) - if repo.CheckLocal() { - t.Error("Bzr CheckLocal does not identify non-Bzr location") - } - - // Test NewRepo when there's no local. This should simply provide a working - // instance without error based on looking at the remote localtion. - _, nrerr := NewRepo("https://launchpad.net/govcstestbzrrepo", tempDir+"/govcstestbzrrepo") - if nrerr != nil { - t.Error(nrerr) - } -} - -func TestBzrPing(t *testing.T) { - tempDir, err := ioutil.TempDir("", "go-vcs-bzr-tests") - if err != nil { - t.Error(err) - } - defer func() { - err = os.RemoveAll(tempDir) - if err != nil { - t.Error(err) - } - }() - - repo, err := NewBzrRepo("https://launchpad.net/govcstestbzrrepo", tempDir) - if err != nil { - t.Error(err) - } - - ping := repo.Ping() - if !ping { - t.Error("Bzr unable to ping working repo") - } - - repo, err = NewBzrRepo("https://launchpad.net/ihopethisneverexistsbecauseitshouldnt", tempDir) - if err != nil { - t.Error(err) - } - - ping = repo.Ping() - if ping { - t.Error("Bzr got a ping response from when it should not have") - } -} - -func TestBzrInit(t *testing.T) { - tempDir, err := ioutil.TempDir("", "go-vcs-bzr-tests") - repoDir := tempDir + "/repo" - if err != nil { - t.Error(err) - } - defer func() { - err = os.RemoveAll(tempDir) - if err != nil { - t.Error(err) - } - }() - - repo, err := NewBzrRepo(repoDir, repoDir) - if err != nil { - t.Error(err) - } - - err = repo.Init() - if err != nil { - t.Error(err) - } - - v, err := repo.Version() - if err != nil { - t.Error(err) - } - if v != "0" { - t.Errorf("Bzr Init returns wrong version: %s", v) - } -} diff --git a/vendor/github.com/Masterminds/vcs/errors_test.go b/vendor/github.com/Masterminds/vcs/errors_test.go deleted file mode 100644 index 2effd7cc..00000000 --- a/vendor/github.com/Masterminds/vcs/errors_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package vcs - -import ( - "errors" - "testing" -) - -func TestNewRemoteError(t *testing.T) { - base := errors.New("Foo error") - out := "This is a test" - msg := "remote error msg" - - e := NewRemoteError(msg, base, out) - - switch e.(type) { - case *RemoteError: - // This is the right error type - default: - t.Error("Wrong error type returned from NewRemoteError") - } -} - -func TestNewLocalError(t *testing.T) { - base := errors.New("Foo error") - out := "This is a test" - msg := "local error msg" - - e := NewLocalError(msg, base, out) - - switch e.(type) { - case *LocalError: - // This is the right error type - default: - t.Error("Wrong error type returned from NewLocalError") - } -} diff --git a/vendor/github.com/Masterminds/vcs/git_test.go b/vendor/github.com/Masterminds/vcs/git_test.go deleted file mode 100644 index b58c2c2e..00000000 --- a/vendor/github.com/Masterminds/vcs/git_test.go +++ /dev/null @@ -1,599 +0,0 @@ -package vcs - -import ( - "fmt" - "io/ioutil" - "path/filepath" - "time" - //"log" - "os" - "testing" -) - -// Canary test to ensure GitRepo implements the Repo interface. -var _ Repo = &GitRepo{} - -// To verify git is working we perform integration testing -// with a known git service. - -func TestGit(t *testing.T) { - tempDir, err := ioutil.TempDir("", "go-vcs-git-tests") - if err != nil { - t.Error(err) - } - defer func() { - err = os.RemoveAll(tempDir) - if err != nil { - t.Error(err) - } - }() - - repo, err := NewGitRepo("https://github.com/Masterminds/VCSTestRepo", tempDir+"/VCSTestRepo") - if err != nil { - t.Error(err) - } - - if repo.Vcs() != Git { - t.Error("Git is detecting the wrong type") - } - - // Check the basic getters. - if repo.Remote() != "https://github.com/Masterminds/VCSTestRepo" { - t.Error("Remote not set properly") - } - if repo.LocalPath() != tempDir+"/VCSTestRepo" { - t.Error("Local disk location not set properly") - } - - //Logger = log.New(os.Stdout, "", log.LstdFlags) - - // Do an initial clone. - err = repo.Get() - if err != nil { - t.Errorf("Unable to clone Git repo. Err was %s", err) - } - - // Verify Git repo is a Git repo - if !repo.CheckLocal() { - t.Error("Problem checking out repo or Git CheckLocal is not working") - } - - // Test internal lookup mechanism used outside of Git specific functionality. - ltype, err := DetectVcsFromFS(tempDir + "/VCSTestRepo") - if err != nil { - t.Error("detectVcsFromFS unable to Git repo") - } - if ltype != Git { - t.Errorf("detectVcsFromFS detected %s instead of Git type", ltype) - } - - // Test NewRepo on existing checkout. This should simply provide a working - // instance without error based on looking at the local directory. - nrepo, nrerr := NewRepo("https://github.com/Masterminds/VCSTestRepo", tempDir+"/VCSTestRepo") - if nrerr != nil { - t.Error(nrerr) - } - // Verify the right oject is returned. It will check the local repo type. - if !nrepo.CheckLocal() { - t.Error("Wrong version returned from NewRepo") - } - - // Perform an update. - err = repo.Update() - if err != nil { - t.Error(err) - } - - v, err := repo.Current() - if err != nil { - t.Errorf("Error trying Git Current: %s", err) - } - if v != "master" { - t.Errorf("Current failed to detect Git on tip of master. Got version: %s", v) - } - - // Set the version using the short hash. - err = repo.UpdateVersion("806b07b") - if err != nil { - t.Errorf("Unable to update Git repo version. Err was %s", err) - } - - // Once a ref has been checked out the repo is in a detached head state. - // Trying to pull in an update in this state will cause an error. Update - // should cleanly handle this. Pulling on a branch (tested elsewhere) and - // skipping that here. - err = repo.Update() - if err != nil { - t.Error(err) - } - - // Use Version to verify we are on the right version. - v, err = repo.Version() - if v != "806b07b08faa21cfbdae93027904f80174679402" { - t.Error("Error checking checked out Git version") - } - if err != nil { - t.Error(err) - } - - v, err = repo.Current() - if err != nil { - t.Errorf("Error trying Git Current for ref: %s", err) - } - if v != "806b07b08faa21cfbdae93027904f80174679402" { - t.Errorf("Current failed to detect Git on ref of branch. Got version: %s", v) - } - - // Use Date to verify we are on the right commit. - d, err := repo.Date() - if d.Format(longForm) != "2015-07-29 09:46:39 -0400" { - t.Error("Error checking checked out Git commit date") - } - if err != nil { - t.Error(err) - } - - // Verify that we can set the version something other than short hash - err = repo.UpdateVersion("master") - if err != nil { - t.Errorf("Unable to update Git repo version. Err was %s", err) - } - err = repo.UpdateVersion("806b07b08faa21cfbdae93027904f80174679402") - if err != nil { - t.Errorf("Unable to update Git repo version. Err was %s", err) - } - v, err = repo.Version() - if v != "806b07b08faa21cfbdae93027904f80174679402" { - t.Error("Error checking checked out Git version") - } - if err != nil { - t.Error(err) - } - - tags, err := repo.Tags() - if err != nil { - t.Error(err) - } - - var hasRelTag bool - var hasOffMasterTag bool - - for _, tv := range tags { - if tv == "1.0.0" { - hasRelTag = true - } else if tv == "off-master-tag" { - hasOffMasterTag = true - } - } - - if !hasRelTag { - t.Error("Git tags unable to find release tag on master") - } - if !hasOffMasterTag { - t.Error("Git tags did not fetch tags not on master") - } - - tags, err = repo.TagsFromCommit("74dd547545b7df4aa285bcec1b54e2b76f726395") - if err != nil { - t.Error(err) - } - if len(tags) != 0 { - t.Error("Git is incorrectly returning tags for a commit") - } - - tags, err = repo.TagsFromCommit("30605f6ac35fcb075ad0bfa9296f90a7d891523e") - if err != nil { - t.Error(err) - } - if len(tags) != 1 || tags[0] != "1.0.0" { - t.Error("Git is incorrectly returning tags for a commit") - } - - branches, err := repo.Branches() - if err != nil { - t.Error(err) - } - // The branches should be HEAD, master, other, and test. - if branches[3] != "test" { - t.Error("Git is incorrectly returning branches") - } - - if !repo.IsReference("1.0.0") { - t.Error("Git is reporting a reference is not one") - } - - if repo.IsReference("foo") { - t.Error("Git is reporting a non-existent reference is one") - } - - if repo.IsDirty() { - t.Error("Git incorrectly reporting dirty") - } - - ci, err := repo.CommitInfo("806b07b08faa21cfbdae93027904f80174679402") - if err != nil { - t.Error(err) - } - if ci.Commit != "806b07b08faa21cfbdae93027904f80174679402" { - t.Error("Git.CommitInfo wrong commit id") - } - if ci.Author != "Matt Farina " { - t.Error("Git.CommitInfo wrong author") - } - if ci.Message != "Update README.md" { - t.Error("Git.CommitInfo wrong message") - } - ti, err := time.Parse(time.RFC1123Z, "Wed, 29 Jul 2015 09:46:39 -0400") - if err != nil { - t.Error(err) - } - if !ti.Equal(ci.Date) { - t.Error("Git.CommitInfo wrong date") - } - - _, err = repo.CommitInfo("asdfasdfasdf") - if err != ErrRevisionUnavailable { - t.Error("Git didn't return expected ErrRevisionUnavailable") - } - - tempDir2, err := ioutil.TempDir("", "go-vcs-git-tests-export") - if err != nil { - t.Fatalf("Error creating temp directory: %s", err) - } - defer func() { - err = os.RemoveAll(tempDir2) - if err != nil { - t.Error(err) - } - }() - - exportDir := filepath.Join(tempDir2, "src") - - err = repo.ExportDir(exportDir) - if err != nil { - t.Errorf("Unable to export Git repo. Err was %s", err) - } - - _, err = os.Stat(filepath.Join(exportDir, "README.md")) - if err != nil { - t.Errorf("Error checking exported file in Git: %s", err) - } - - _, err = os.Stat(filepath.Join(exportDir, string(repo.Vcs()))) - if err != nil { - if found := os.IsNotExist(err); !found { - t.Errorf("Error checking exported metadata in Git: %s", err) - } - } else { - t.Error("Error checking Git metadata. It exists.") - } -} - -func TestGitCheckLocal(t *testing.T) { - // Verify repo.CheckLocal fails for non-Git directories. - // TestGit is already checking on a valid repo - tempDir, err := ioutil.TempDir("", "go-vcs-git-tests") - if err != nil { - t.Error(err) - } - defer func() { - err = os.RemoveAll(tempDir) - if err != nil { - t.Error(err) - } - }() - - repo, _ := NewGitRepo("", tempDir) - if repo.CheckLocal() { - t.Error("Git CheckLocal does not identify non-Git location") - } - - // Test NewRepo when there's no local. This should simply provide a working - // instance without error based on looking at the remote localtion. - _, nrerr := NewRepo("https://github.com/Masterminds/VCSTestRepo", tempDir+"/VCSTestRepo") - if nrerr != nil { - t.Error(nrerr) - } -} - -func TestGitPing(t *testing.T) { - tempDir, err := ioutil.TempDir("", "go-vcs-git-tests") - if err != nil { - t.Error(err) - } - defer func() { - err = os.RemoveAll(tempDir) - if err != nil { - t.Error(err) - } - }() - - repo, err := NewGitRepo("https://github.com/Masterminds/VCSTestRepo", tempDir) - if err != nil { - t.Error(err) - } - - ping := repo.Ping() - if !ping { - t.Error("Git unable to ping working repo") - } - - repo, err = NewGitRepo("https://github.com/Masterminds/ihopethisneverexistsbecauseitshouldnt", tempDir) - if err != nil { - t.Error(err) - } - - ping = repo.Ping() - if ping { - t.Error("Git got a ping response from when it should not have") - } -} - -func TestGitInit(t *testing.T) { - tempDir, err := ioutil.TempDir("", "go-vcs-git-tests") - repoDir := tempDir + "/repo" - if err != nil { - t.Error(err) - } - defer func() { - err = os.RemoveAll(tempDir) - if err != nil { - t.Error(err) - } - }() - - repo, err := NewGitRepo(repoDir, repoDir) - if err != nil { - t.Error(err) - } - - err = repo.Init() - if err != nil { - t.Error(err) - } - - _, err = repo.RunFromDir("git", "status") - if err != nil { - t.Error(err) - } -} - -func TestGitSubmoduleHandling(t *testing.T) { - tempDir, err := ioutil.TempDir("", "go-vcs-git-submodule-tests") - if err != nil { - t.Fatal(err) - } - defer func() { - err = os.RemoveAll(tempDir) - if err != nil { - t.Error(err) - } - }() - - dumplocal := func(err error) string { - if terr, ok := err.(*LocalError); ok { - return fmt.Sprintf("msg: %s\norig: %s\nout: %s", terr.Error(), terr.Original(), terr.Out()) - } - return err.Error() - } - - subdirExists := func(dir ...string) bool { - _, err := os.Stat(filepath.Join(append([]string{tempDir}, dir...)...)) - return err == nil - } - - // Initial clone should get version with two submodules, each of which have - // their own submodule - repo, err := NewGitRepo("https://github.com/sdboyer/subm", tempDir) - if err != nil { - t.Fatal(dumplocal(err)) - } - err = repo.Get() - if err != nil { - t.Fatalf("unable to clone Git repo. Err was %s", dumplocal(err)) - } - - // Verify we are on the right version. - v, err := repo.Version() - if v != "18e3a5f6fc7f6d577e732e7a5ab2caf990efbf8f" { - t.Fatalf("did not start from expected rev, tests could fail - bailing out (got %s)", v) - } - if err != nil { - t.Fatal(dumplocal(err)) - } - - if !subdirExists("subm1", ".git") { - t.Fatal("subm1 submodule does not exist on initial clone/checkout") - } - if !subdirExists("subm1", "dep-test", ".git") { - t.Fatal("dep-test submodule nested under subm1 does not exist on initial clone/checkout") - } - - if !subdirExists("subm-again", ".git") { - t.Fatal("subm-again submodule does not exist on initial clone/checkout") - } - if !subdirExists("subm-again", "dep-test", ".git") { - t.Fatal("dep-test submodule nested under subm-again does not exist on initial clone/checkout") - } - - // Now switch to version with no submodules, make sure they all go away - err = repo.UpdateVersion("e677f82015f72ac1c8fafa66b5463163b3597af2") - if err != nil { - t.Fatalf("checking out needed version failed with err: %s", dumplocal(err)) - } - - if subdirExists("subm1") { - t.Fatal("checking out version without submodule did not clean up immediate submodules") - } - if subdirExists("subm1", "dep-test") { - t.Fatal("checking out version without submodule did not clean up nested submodules") - } - if subdirExists("subm-again") { - t.Fatal("checking out version without submodule did not clean up immediate submodules") - } - if subdirExists("subm-again", "dep-test") { - t.Fatal("checking out version without submodule did not clean up nested submodules") - } - - err = repo.UpdateVersion("aaf7aa1bc4c3c682cc530eca8f80417088ee8540") - if err != nil { - t.Fatalf("checking out needed version failed with err: %s", dumplocal(err)) - } - - if !subdirExists("subm1", ".git") { - t.Fatal("checking out version with immediate submodule did not set up git subrepo") - } - - err = repo.UpdateVersion("6cc4669af468f3b4f16e7e96275ad01ade5b522f") - if err != nil { - t.Fatalf("checking out needed version failed with err: %s", dumplocal(err)) - } - - if !subdirExists("subm1", "dep-test", ".git") { - t.Fatal("checking out version with nested submodule did not set up nested git subrepo") - } - - err = repo.UpdateVersion("aaf7aa1bc4c3c682cc530eca8f80417088ee8540") - if err != nil { - t.Fatalf("checking out needed version failed with err: %s", dumplocal(err)) - } - - if subdirExists("subm1", "dep-test") { - t.Fatal("rolling back to version without nested submodule did not clean up the nested submodule") - } - - err = repo.UpdateVersion("18e3a5f6fc7f6d577e732e7a5ab2caf990efbf8f") - if err != nil { - t.Fatalf("checking out needed version failed with err: %s", dumplocal(err)) - } - - if !subdirExists("subm1", ".git") { - t.Fatal("subm1 submodule does not exist after switch from other commit") - } - if !subdirExists("subm1", "dep-test", ".git") { - t.Fatal("dep-test submodule nested under subm1 does not exist after switch from other commit") - } - - if !subdirExists("subm-again", ".git") { - t.Fatal("subm-again submodule does not exist after switch from other commit") - } - if !subdirExists("subm-again", "dep-test", ".git") { - t.Fatal("dep-test submodule nested under subm-again does not exist after switch from other commit") - } - -} - -func TestGitSubmoduleHandling2(t *testing.T) { - tempDir, err := ioutil.TempDir("", "go-vcs-git-submodule-tests2") - if err != nil { - t.Error(err) - } - defer func() { - err = os.RemoveAll(tempDir) - if err != nil { - t.Error(err) - } - }() - - repo, err := NewGitRepo("https://github.com/cloudfoundry/sonde-go", tempDir+"/VCSTestRepo2") - if err != nil { - t.Error(err) - } - - if repo.Vcs() != Git { - t.Error("Git is detecting the wrong type") - } - - // Check the basic getters. - if repo.Remote() != "https://github.com/cloudfoundry/sonde-go" { - t.Error("Remote not set properly") - } - if repo.LocalPath() != tempDir+"/VCSTestRepo2" { - t.Error("Local disk location not set properly") - } - - //Logger = log.New(os.Stdout, "", log.LstdFlags) - - // Do an initial clone. - err = repo.Get() - if err != nil { - t.Errorf("Unable to clone Git repo. Err was %s", err) - } - - // Verify Git repo is a Git repo - if !repo.CheckLocal() { - t.Error("Problem checking out repo or Git CheckLocal is not working") - } - - // Test internal lookup mechanism used outside of Git specific functionality. - ltype, err := DetectVcsFromFS(tempDir + "/VCSTestRepo2") - if err != nil { - t.Error("detectVcsFromFS unable to Git repo") - } - if ltype != Git { - t.Errorf("detectVcsFromFS detected %s instead of Git type", ltype) - } - - // Test NewRepo on existing checkout. This should simply provide a working - // instance without error based on looking at the local directory. - nrepo, nrerr := NewRepo("https://github.com/cloudfoundry/sonde-go", tempDir+"/VCSTestRepo2") - if nrerr != nil { - t.Error(nrerr) - } - // Verify the right oject is returned. It will check the local repo type. - if !nrepo.CheckLocal() { - t.Error("Wrong version returned from NewRepo") - } - - // Perform an update. - err = repo.Update() - if err != nil { - t.Error(err) - } - - v, err := repo.Current() - if err != nil { - t.Errorf("Error trying Git Current: %s", err) - } - if v != "master" { - t.Errorf("Current failed to detect Git on tip of master. Got version: %s", v) - } - - - tempDir2, err := ioutil.TempDir("", "go-vcs-git-tests-export") - if err != nil { - t.Fatalf("Error creating temp directory: %s", err) - } - defer func() { - err = os.RemoveAll(tempDir2) - if err != nil { - t.Error(err) - } - }() - - exportDir := filepath.Join(tempDir2, "src") - - err = repo.ExportDir(exportDir) - if err != nil { - t.Errorf("Unable to export Git repo. Err was %s", err) - } - - _, err = os.Stat(filepath.Join(exportDir, "README.md")) - if err != nil { - t.Errorf("Error checking exported file in Git: %s", err) - } - - _, err = os.Stat(filepath.Join( filepath.Join(exportDir, "definitions"), "README.md")) - if err != nil { - t.Errorf("Error checking exported file in Git: %s", err) - } - - _, err = os.Stat(filepath.Join(exportDir, string(repo.Vcs()))) - if err != nil { - if found := os.IsNotExist(err); !found { - t.Errorf("Error checking exported metadata in Git: %s", err) - } - } else { - t.Error("Error checking Git metadata. It exists.") - } -} diff --git a/vendor/github.com/Masterminds/vcs/glide.yaml b/vendor/github.com/Masterminds/vcs/glide.yaml deleted file mode 100644 index b96e0bd3..00000000 --- a/vendor/github.com/Masterminds/vcs/glide.yaml +++ /dev/null @@ -1,8 +0,0 @@ -package: github.com/Masterminds/vcs -homepage: https://github.com/Masterminds/vcs -license: MIT -owners: -- name: Matt Farina - email: matt@mattfarina.com - homepage: https://www.mattfarina.com/ -import: [] diff --git a/vendor/github.com/Masterminds/vcs/hg_test.go b/vendor/github.com/Masterminds/vcs/hg_test.go deleted file mode 100644 index 6b19f728..00000000 --- a/vendor/github.com/Masterminds/vcs/hg_test.go +++ /dev/null @@ -1,332 +0,0 @@ -package vcs - -import ( - "io/ioutil" - "path/filepath" - "strings" - "time" - //"log" - "os" - "testing" -) - -// Canary test to ensure HgRepo implements the Repo interface. -var _ Repo = &HgRepo{} - -// To verify hg is working we perform integration testing -// with a known hg service. - -func TestHg(t *testing.T) { - - tempDir, err := ioutil.TempDir("", "go-vcs-hg-tests") - if err != nil { - t.Error(err) - } - defer func() { - err = os.RemoveAll(tempDir) - if err != nil { - t.Error(err) - } - }() - - repo, err := NewHgRepo("https://bitbucket.org/mattfarina/testhgrepo", tempDir+"/testhgrepo") - if err != nil { - t.Error(err) - } - - if repo.Vcs() != Hg { - t.Error("Hg is detecting the wrong type") - } - - // Check the basic getters. - if repo.Remote() != "https://bitbucket.org/mattfarina/testhgrepo" { - t.Error("Remote not set properly") - } - if repo.LocalPath() != tempDir+"/testhgrepo" { - t.Error("Local disk location not set properly") - } - - //Logger = log.New(os.Stdout, "", log.LstdFlags) - - // Do an initial clone. - err = repo.Get() - if err != nil { - t.Errorf("Unable to clone Hg repo. Err was %s", err) - } - - // Verify Hg repo is a Hg repo - if !repo.CheckLocal() { - t.Error("Problem checking out repo or Hg CheckLocal is not working") - } - - // Test internal lookup mechanism used outside of Hg specific functionality. - ltype, err := DetectVcsFromFS(tempDir + "/testhgrepo") - if err != nil { - t.Error("detectVcsFromFS unable to Hg repo") - } - if ltype != Hg { - t.Errorf("detectVcsFromFS detected %s instead of Hg type", ltype) - } - - // Test NewRepo on existing checkout. This should simply provide a working - // instance without error based on looking at the local directory. - nrepo, nrerr := NewRepo("https://bitbucket.org/mattfarina/testhgrepo", tempDir+"/testhgrepo") - if nrerr != nil { - t.Error(nrerr) - } - // Verify the right oject is returned. It will check the local repo type. - if !nrepo.CheckLocal() { - t.Error("Wrong version returned from NewRepo") - } - - v, err := repo.Current() - if err != nil { - t.Errorf("Error trying Hg Current: %s", err) - } - if v != "default" { - t.Errorf("Current failed to detect Hg on tip of default. Got version: %s", v) - } - - // Set the version using the short hash. - err = repo.UpdateVersion("a5494ba2177f") - if err != nil { - t.Errorf("Unable to update Hg repo version. Err was %s", err) - } - - // Use Version to verify we are on the right version. - v, err = repo.Version() - if v != "a5494ba2177ff9ef26feb3c155dfecc350b1a8ef" { - t.Errorf("Error checking checked out Hg version: %s", v) - } - if err != nil { - t.Error(err) - } - - v, err = repo.Current() - if err != nil { - t.Errorf("Error trying Hg Current for ref: %s", err) - } - if v != "a5494ba2177ff9ef26feb3c155dfecc350b1a8ef" { - t.Errorf("Current failed to detect Hg on ref of branch. Got version: %s", v) - } - - // Use Date to verify we are on the right commit. - d, err := repo.Date() - if err != nil { - t.Error(err) - } - if d.Format(longForm) != "2015-07-30 16:14:08 -0400" { - t.Error("Error checking checked out Hg commit date. Got wrong date:", d) - } - - // Perform an update. - err = repo.Update() - if err != nil { - t.Error(err) - } - - v, err = repo.Version() - if v != "9c6ccbca73e8a1351c834f33f57f1f7a0329ad35" { - t.Errorf("Error checking checked out Hg version: %s", v) - } - if err != nil { - t.Error(err) - } - - tags, err := repo.Tags() - if err != nil { - t.Error(err) - } - if tags[1] != "1.0.0" { - t.Error("Hg tags is not reporting the correct version") - } - - tags, err = repo.TagsFromCommit("a5494ba2177f") - if err != nil { - t.Error(err) - } - if len(tags) != 0 { - t.Error("Hg is incorrectly returning tags for a commit") - } - - tags, err = repo.TagsFromCommit("d680e82228d2") - if err != nil { - t.Error(err) - } - if len(tags) != 1 || tags[0] != "1.0.0" { - t.Error("Hg is incorrectly returning tags for a commit") - } - - branches, err := repo.Branches() - if err != nil { - t.Error(err) - } - // The branches should be HEAD, master, and test. - if branches[0] != "test" { - t.Error("Hg is incorrectly returning branches") - } - - if !repo.IsReference("1.0.0") { - t.Error("Hg is reporting a reference is not one") - } - - if !repo.IsReference("test") { - t.Error("Hg is reporting a reference is not one") - } - - if repo.IsReference("foo") { - t.Error("Hg is reporting a non-existent reference is one") - } - - if repo.IsDirty() { - t.Error("Hg incorrectly reporting dirty") - } - - ci, err := repo.CommitInfo("a5494ba2177f") - if err != nil { - t.Error(err) - } - if ci.Commit != "a5494ba2177ff9ef26feb3c155dfecc350b1a8ef" { - t.Error("Hg.CommitInfo wrong commit id") - } - if ci.Author != "Matt Farina " { - t.Error("Hg.CommitInfo wrong author") - } - if ci.Message != "A commit" { - t.Error("Hg.CommitInfo wrong message") - } - - ti := time.Unix(1438287248, 0) - if !ti.Equal(ci.Date) { - t.Error("Hg.CommitInfo wrong date") - } - - _, err = repo.CommitInfo("asdfasdfasdf") - if err != ErrRevisionUnavailable { - t.Error("Hg didn't return expected ErrRevisionUnavailable") - } - - tempDir2, err := ioutil.TempDir("", "go-vcs-hg-tests-export") - if err != nil { - t.Fatalf("Error creating temp directory: %s", err) - } - defer func() { - err = os.RemoveAll(tempDir2) - if err != nil { - t.Error(err) - } - }() - - exportDir := filepath.Join(tempDir2, "src") - - err = repo.ExportDir(exportDir) - if err != nil { - t.Errorf("Unable to export Hg repo. Err was %s", err) - } - - _, err = os.Stat(filepath.Join(exportDir, "Readme.md")) - if err != nil { - t.Errorf("Error checking exported file in Hg: %s", err) - } - - _, err = os.Stat(filepath.Join(exportDir, string(repo.Vcs()))) - if err != nil { - if found := os.IsNotExist(err); !found { - t.Errorf("Error checking exported metadata in Hg: %s", err) - } - } else { - t.Error("Error checking Hg metadata. It exists.") - } -} - -func TestHgCheckLocal(t *testing.T) { - // Verify repo.CheckLocal fails for non-Hg directories. - // TestHg is already checking on a valid repo - tempDir, err := ioutil.TempDir("", "go-vcs-hg-tests") - if err != nil { - t.Error(err) - } - defer func() { - err = os.RemoveAll(tempDir) - if err != nil { - t.Error(err) - } - }() - - repo, _ := NewHgRepo("", tempDir) - if repo.CheckLocal() { - t.Error("Hg CheckLocal does not identify non-Hg location") - } - - // Test NewRepo when there's no local. This should simply provide a working - // instance without error based on looking at the remote localtion. - _, nrerr := NewRepo("https://bitbucket.org/mattfarina/testhgrepo", tempDir+"/testhgrepo") - if nrerr != nil { - t.Error(nrerr) - } -} - -func TestHgPing(t *testing.T) { - tempDir, err := ioutil.TempDir("", "go-vcs-hg-tests") - if err != nil { - t.Error(err) - } - defer func() { - err = os.RemoveAll(tempDir) - if err != nil { - t.Error(err) - } - }() - - repo, err := NewHgRepo("https://bitbucket.org/mattfarina/testhgrepo", tempDir) - if err != nil { - t.Error(err) - } - - ping := repo.Ping() - if !ping { - t.Error("Hg unable to ping working repo") - } - - repo, err = NewHgRepo("https://bitbucket.org/mattfarina/ihopethisneverexistsbecauseitshouldnt", tempDir) - if err != nil { - t.Error(err) - } - - ping = repo.Ping() - if ping { - t.Error("Hg got a ping response from when it should not have") - } -} - -func TestHgInit(t *testing.T) { - tempDir, err := ioutil.TempDir("", "go-vcs-hg-tests") - repoDir := tempDir + "/repo" - if err != nil { - t.Error(err) - } - defer func() { - err = os.RemoveAll(tempDir) - if err != nil { - t.Error(err) - } - }() - - repo, err := NewHgRepo(repoDir, repoDir) - if err != nil { - t.Error(err) - } - - err = repo.Init() - if err != nil { - t.Error(err) - } - - v, err := repo.Version() - if err != nil { - t.Error(err) - } - if !strings.HasPrefix(v, "000000") { - t.Errorf("Hg Init reporting wrong initial version: %s", v) - } -} diff --git a/vendor/github.com/Masterminds/vcs/repo_test.go b/vendor/github.com/Masterminds/vcs/repo_test.go deleted file mode 100644 index 8c083b3f..00000000 --- a/vendor/github.com/Masterminds/vcs/repo_test.go +++ /dev/null @@ -1,74 +0,0 @@ -package vcs - -import ( - "fmt" - "io/ioutil" - "os" - "testing" -) - -func ExampleNewRepo() { - remote := "https://github.com/Masterminds/vcs" - local, _ := ioutil.TempDir("", "go-vcs") - repo, _ := NewRepo(remote, local) - // Returns: instance of GitRepo - - repo.Vcs() - // Returns Git as this is a Git repo - - err := repo.Get() - // Pulls down a repo, or a checkout in the case of SVN, and returns an - // error if that didn't happen successfully. - if err != nil { - fmt.Println(err) - } - - err = repo.UpdateVersion("master") - // Checkouts out a specific version. In most cases this can be a commit id, - // branch, or tag. - if err != nil { - fmt.Println(err) - } -} - -func TestTypeSwitch(t *testing.T) { - - // To test repo type switching we checkout as SVN and then try to get it as - // a git repo afterwards. - tempDir, err := ioutil.TempDir("", "go-vcs-svn-tests") - if err != nil { - t.Error(err) - } - defer func() { - err = os.RemoveAll(tempDir) - if err != nil { - t.Error(err) - } - }() - - repo, err := NewSvnRepo("https://github.com/Masterminds/VCSTestRepo/trunk", tempDir+string(os.PathSeparator)+"VCSTestRepo") - if err != nil { - t.Error(err) - } - err = repo.Get() - if err != nil { - t.Errorf("Unable to checkout SVN repo for repo switching tests. Err was %s", err) - } - - _, err = NewRepo("https://github.com/Masterminds/VCSTestRepo", tempDir+string(os.PathSeparator)+"VCSTestRepo") - if err != ErrWrongVCS { - t.Errorf("Not detecting repo switch from SVN to Git") - } -} - -func TestDepInstalled(t *testing.T) { - i := depInstalled("git") - if !i { - t.Error("depInstalled not finding installed dep.") - } - - i = depInstalled("thisreallyisntinstalled") - if i { - t.Error("depInstalled finding not installed dep.") - } -} diff --git a/vendor/github.com/Masterminds/vcs/svn_test.go b/vendor/github.com/Masterminds/vcs/svn_test.go deleted file mode 100644 index 93fc139a..00000000 --- a/vendor/github.com/Masterminds/vcs/svn_test.go +++ /dev/null @@ -1,337 +0,0 @@ -package vcs - -import ( - "io/ioutil" - "path/filepath" - "time" - //"log" - "os" - "testing" -) - -// To verify svn is working we perform integration testing -// with a known svn service. - -// Canary test to ensure SvnRepo implements the Repo interface. -var _ Repo = &SvnRepo{} - -func TestSvn(t *testing.T) { - - tempDir, err := ioutil.TempDir("", "go-vcs-svn-tests") - if err != nil { - t.Error(err) - } - defer func() { - err = os.RemoveAll(tempDir) - if err != nil { - t.Error(err) - } - }() - - repo, err := NewSvnRepo("https://github.com/Masterminds/VCSTestRepo/trunk", tempDir+string(os.PathSeparator)+"VCSTestRepo") - if err != nil { - t.Error(err) - } - - if repo.Vcs() != Svn { - t.Error("Svn is detecting the wrong type") - } - - // Check the basic getters. - if repo.Remote() != "https://github.com/Masterminds/VCSTestRepo/trunk" { - t.Error("Remote not set properly") - } - if repo.LocalPath() != tempDir+string(os.PathSeparator)+"VCSTestRepo" { - t.Error("Local disk location not set properly") - } - - //Logger = log.New(os.Stdout, "", log.LstdFlags) - - // Do an initial checkout. - err = repo.Get() - if err != nil { - t.Errorf("Unable to checkout SVN repo. Err was %s", err) - } - - // Verify SVN repo is a SVN repo - if !repo.CheckLocal() { - t.Error("Problem checking out repo or SVN CheckLocal is not working") - } - - // Verify an incorrect remote is caught when NewSvnRepo is used on an existing location - _, nrerr := NewSvnRepo("https://github.com/Masterminds/VCSTestRepo/unknownbranch", tempDir+"/VCSTestRepo") - if nrerr != ErrWrongRemote { - t.Error("ErrWrongRemote was not triggered for SVN") - } - - // Test internal lookup mechanism used outside of Hg specific functionality. - ltype, err := DetectVcsFromFS(tempDir + "/VCSTestRepo") - if err != nil { - t.Error("detectVcsFromFS unable to Svn repo") - } - if ltype != Svn { - t.Errorf("detectVcsFromFS detected %s instead of Svn type", ltype) - } - - // Commenting out auto-detection tests for SVN. NewRepo automatically detects - // GitHub to be a Git repo and that's an issue for this test. Need an - // SVN host that can autodetect from before using this test again. - // - // Test NewRepo on existing checkout. This should simply provide a working - // instance without error based on looking at the local directory. - // nrepo, nrerr := NewRepo("https://github.com/Masterminds/VCSTestRepo/trunk", tempDir+"/VCSTestRepo") - // if nrerr != nil { - // t.Error(nrerr) - // } - // // Verify the right oject is returned. It will check the local repo type. - // if nrepo.CheckLocal() == false { - // t.Error("Wrong version returned from NewRepo") - // } - - v, err := repo.Current() - if err != nil { - t.Errorf("Error trying Svn Current: %s", err) - } - if v != "HEAD" { - t.Errorf("Current failed to detect Svn on HEAD. Got version: %s", v) - } - - // Update the version to a previous version. - err = repo.UpdateVersion("r2") - if err != nil { - t.Errorf("Unable to update SVN repo version. Err was %s", err) - } - - // Use Version to verify we are on the right version. - v, err = repo.Version() - if v != "2" { - t.Error("Error checking checked SVN out version") - } - if err != nil { - t.Error(err) - } - - v, err = repo.Current() - if err != nil { - t.Errorf("Error trying Svn Current for ref: %s", err) - } - if v != "2" { - t.Errorf("Current failed to detect Svn on HEAD. Got version: %s", v) - } - - // Perform an update which should take up back to the latest version. - err = repo.Update() - if err != nil { - t.Error(err) - } - - // Make sure we are on a newer version because of the update. - v, err = repo.Version() - if v == "2" { - t.Error("Error with version. Still on old version. Update failed") - } - if err != nil { - t.Error(err) - } - - // Use Date to verify we are on the right commit. - d, err := repo.Date() - if d.Format(longForm) != "2015-07-29 13:47:03 +0000" { - t.Error("Error checking checked out Svn commit date") - } - if err != nil { - t.Error(err) - } - - tags, err := repo.Tags() - if err != nil { - t.Error(err) - } - if len(tags) != 0 { - t.Error("Svn is incorrectly returning tags") - } - - tags, err = repo.TagsFromCommit("2") - if err != nil { - t.Error(err) - } - if len(tags) != 0 { - t.Error("Svn is incorrectly returning tags for a commit") - } - - branches, err := repo.Branches() - if err != nil { - t.Error(err) - } - if len(branches) != 0 { - t.Error("Svn is incorrectly returning branches") - } - - if !repo.IsReference("r4") { - t.Error("Svn is reporting a reference is not one") - } - - if repo.IsReference("55") { - t.Error("Svn is reporting a non-existent reference is one") - } - - if repo.IsDirty() { - t.Error("Svn incorrectly reporting dirty") - } - - ci, err := repo.CommitInfo("2") - if err != nil { - t.Error(err) - } - if ci.Commit != "2" { - t.Error("Svn.CommitInfo wrong commit id") - } - if ci.Author != "matt.farina" { - t.Error("Svn.CommitInfo wrong author") - } - if ci.Message != "Update README.md" { - t.Error("Svn.CommitInfo wrong message") - } - ti, err := time.Parse(time.RFC3339Nano, "2015-07-29T13:46:20.000000Z") - if err != nil { - t.Error(err) - } - if !ti.Equal(ci.Date) { - t.Error("Svn.CommitInfo wrong date") - } - - _, err = repo.CommitInfo("555555555") - if err != ErrRevisionUnavailable { - t.Error("Svn didn't return expected ErrRevisionUnavailable") - } - - tempDir2, err := ioutil.TempDir("", "go-vcs-svn-tests-export") - if err != nil { - t.Fatalf("Error creating temp directory: %s", err) - } - defer func() { - err = os.RemoveAll(tempDir2) - if err != nil { - t.Error(err) - } - }() - - exportDir := filepath.Join(tempDir2, "src") - - err = repo.ExportDir(exportDir) - if err != nil { - t.Errorf("Unable to export Svn repo. Err was %s", err) - } - - _, err = os.Stat(filepath.Join(exportDir, "README.md")) - if err != nil { - t.Errorf("Error checking exported file in Svn: %s", err) - } - - _, err = os.Stat(filepath.Join(exportDir, string(repo.Vcs()))) - if err != nil { - if found := os.IsNotExist(err); !found { - t.Errorf("Error checking exported metadata in Svn: %s", err) - } - } else { - t.Error("Error checking Svn metadata. It exists.") - } -} - -func TestSvnCheckLocal(t *testing.T) { - // Verify repo.CheckLocal fails for non-SVN directories. - // TestSvn is already checking on a valid repo - tempDir, err := ioutil.TempDir("", "go-vcs-svn-tests") - if err != nil { - t.Error(err) - } - defer func() { - err = os.RemoveAll(tempDir) - if err != nil { - t.Error(err) - } - }() - - repo, _ := NewSvnRepo("", tempDir) - if repo.CheckLocal() { - t.Error("SVN CheckLocal does not identify non-SVN location") - } - - // Test NewRepo when there's no local. This should simply provide a working - // instance without error based on looking at the remote localtion. - _, nrerr := NewRepo("https://github.com/Masterminds/VCSTestRepo/trunk", tempDir+"/VCSTestRepo") - if nrerr != nil { - t.Error(nrerr) - } -} - -func TestSvnPing(t *testing.T) { - tempDir, err := ioutil.TempDir("", "go-vcs-svn-tests") - if err != nil { - t.Error(err) - } - defer func() { - err = os.RemoveAll(tempDir) - if err != nil { - t.Error(err) - } - }() - - repo, err := NewSvnRepo("https://github.com/Masterminds/VCSTestRepo/trunk", tempDir) - if err != nil { - t.Error(err) - } - - ping := repo.Ping() - if !ping { - t.Error("Svn unable to ping working repo") - } - - repo, err = NewSvnRepo("https://github.com/Masterminds/ihopethisneverexistsbecauseitshouldnt", tempDir) - if err != nil { - t.Error(err) - } - - ping = repo.Ping() - if ping { - t.Error("Svn got a ping response from when it should not have") - } -} - -func TestSvnInit(t *testing.T) { - tempDir, err := ioutil.TempDir("", "go-vcs-svn-tests") - remoteDir := tempDir + string(os.PathSeparator) + "remoteDir" - localDir := tempDir + string(os.PathSeparator) + "localDir" - if err != nil { - t.Error(err) - } - defer func() { - err = os.RemoveAll(tempDir) - if err != nil { - t.Error(err) - } - }() - - repo, err := NewSvnRepo(remoteDir, localDir) - if err != nil { - t.Error(err) - } - - err = repo.Init() - if err != nil { - t.Error(err) - } - - err = repo.Get() - if err != nil { - t.Error(err) - } - - v, err := repo.Version() - if err != nil { - t.Error(err) - } - if v != "0" { - t.Errorf("Svn Init returns wrong version: %s", v) - } -} diff --git a/vendor/github.com/Masterminds/vcs/vcs_remote_lookup_test.go b/vendor/github.com/Masterminds/vcs/vcs_remote_lookup_test.go deleted file mode 100644 index 938cb0eb..00000000 --- a/vendor/github.com/Masterminds/vcs/vcs_remote_lookup_test.go +++ /dev/null @@ -1,137 +0,0 @@ -package vcs - -import ( - "io/ioutil" - "os" - "os/exec" - "runtime" - "strings" - "testing" -) - -func TestVCSLookup(t *testing.T) { - // TODO: Expand to make sure it detected the right vcs. - urlList := map[string]struct { - work bool - t Type - }{ - "https://github.com/masterminds": {work: false, t: Git}, - "https://github.com/Masterminds/VCSTestRepo": {work: true, t: Git}, - "https://bitbucket.org/mattfarina/testhgrepo": {work: true, t: Hg}, - "https://bitbucket.org/mattfarina/repo-does-not-exist": {work: false, t: Hg}, - "https://bitbucket.org/mattfarina/private-repo-for-vcs-testing": {work: false, t: Hg}, - "https://launchpad.net/govcstestbzrrepo/trunk": {work: true, t: Bzr}, - "https://launchpad.net/~mattfarina/+junk/mygovcstestbzrrepo": {work: true, t: Bzr}, - "https://launchpad.net/~mattfarina/+junk/mygovcstestbzrrepo/trunk": {work: true, t: Bzr}, - "https://git.launchpad.net/govcstestgitrepo": {work: true, t: Git}, - "https://git.launchpad.net/~mattfarina/+git/mygovcstestgitrepo": {work: true, t: Git}, - "https://hub.jazz.net/git/user1/pkgname": {work: true, t: Git}, - "https://hub.jazz.net/git/user1/pkgname/subpkg/subpkg/subpkg": {work: true, t: Git}, - "https://hubs.jazz.net/git/user1/pkgname": {work: false, t: Git}, - "https://example.com/foo/bar.git": {work: true, t: Git}, - "https://example.com/foo/bar.svn": {work: true, t: Svn}, - "https://example.com/foo/bar/baz.bzr": {work: true, t: Bzr}, - "https://example.com/foo/bar/baz.hg": {work: true, t: Hg}, - "https://gopkg.in/tomb.v1": {work: true, t: Git}, - "https://golang.org/x/net": {work: true, t: Git}, - "https://speter.net/go/exp/math/dec/inf": {work: true, t: Git}, - "https://git.openstack.org/foo/bar": {work: true, t: Git}, - "git@github.com:Masterminds/vcs.git": {work: true, t: Git}, - "git@example.com:foo.git": {work: true, t: Git}, - "ssh://hg@bitbucket.org/mattfarina/testhgrepo": {work: true, t: Hg}, - "git@bitbucket.org:mattfarina/glide-bitbucket-example.git": {work: true, t: Git}, - "git+ssh://example.com/foo/bar": {work: true, t: Git}, - "git://example.com/foo/bar": {work: true, t: Git}, - "bzr+ssh://example.com/foo/bar": {work: true, t: Bzr}, - "svn+ssh://example.com/foo/bar": {work: true, t: Svn}, - "git@example.com:foo/bar": {work: true, t: Git}, - "hg@example.com:foo/bar": {work: true, t: Hg}, - } - - for u, c := range urlList { - ty, _, err := detectVcsFromRemote(u) - if err == nil && !c.work { - t.Errorf("Error detecting VCS from URL(%s)", u) - } - - if err == ErrCannotDetectVCS && c.work { - t.Errorf("Error detecting VCS from URL(%s)", u) - } - - if err != nil && c.work { - t.Errorf("Error detecting VCS from URL(%s): %s", u, err) - } - - if err != nil && - err != ErrCannotDetectVCS && - !strings.HasSuffix(err.Error(), "Not Found") && - !strings.HasSuffix(err.Error(), "Access Denied") && - !c.work { - t.Errorf("Unexpected error returned (%s): %s", u, err) - } - - if c.work && ty != c.t { - t.Errorf("Incorrect VCS type returned(%s)", u) - } - } -} - -func TestVCSFileLookup(t *testing.T) { - tempDir, err := ioutil.TempDir("", "go-vcs-file-lookup-tests") - if err != nil { - t.Error(err) - } - defer func() { - err = os.RemoveAll(tempDir) - if err != nil { - t.Error(err) - } - }() - - _, err = exec.Command("git", "init", tempDir).CombinedOutput() - if err != nil { - t.Error(err) - } - - // On Windows it should be file:// followed by /C:\for\bar. That / before - // the drive needs to be included in testing. - var pth string - if runtime.GOOS == "windows" { - pth = "file:///" + tempDir - } else { - pth = "file://" + tempDir - } - ty, _, err := detectVcsFromRemote(pth) - - if err != nil { - t.Errorf("Unable to detect file:// path: %s", err) - } - - if ty != Git { - t.Errorf("Detected wrong type from file:// path. Found type %v", ty) - } -} - -func TestNotFound(t *testing.T) { - _, _, err := detectVcsFromRemote("https://mattfarina.com/notfound") - if err == nil || !strings.HasSuffix(err.Error(), " Not Found") { - t.Errorf("Failed to find not found repo") - } - - _, err = NewRepo("https://mattfarina.com/notfound", "") - if err == nil || !strings.HasSuffix(err.Error(), " Not Found") { - t.Errorf("Failed to find not found repo") - } -} - -func TestAccessDenied(t *testing.T) { - _, _, err := detectVcsFromRemote("https://bitbucket.org/mattfarina/private-repo-for-vcs-testing") - if err == nil || err.Error() != "Access Denied" { - t.Errorf("Failed to detect access denied") - } - - _, err = NewRepo("https://bitbucket.org/mattfarina/private-repo-for-vcs-testing", "") - if err == nil || err.Error() != "Access Denied" { - t.Errorf("Failed to detect access denied") - } -} diff --git a/vendor/github.com/armon/go-radix/.gitignore b/vendor/github.com/armon/go-radix/.gitignore deleted file mode 100644 index 00268614..00000000 --- a/vendor/github.com/armon/go-radix/.gitignore +++ /dev/null @@ -1,22 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe diff --git a/vendor/github.com/armon/go-radix/.travis.yml b/vendor/github.com/armon/go-radix/.travis.yml deleted file mode 100644 index 1a0bbea6..00000000 --- a/vendor/github.com/armon/go-radix/.travis.yml +++ /dev/null @@ -1,3 +0,0 @@ -language: go -go: - - tip diff --git a/vendor/github.com/armon/go-radix/README.md b/vendor/github.com/armon/go-radix/README.md deleted file mode 100644 index 26f42a28..00000000 --- a/vendor/github.com/armon/go-radix/README.md +++ /dev/null @@ -1,38 +0,0 @@ -go-radix [![Build Status](https://travis-ci.org/armon/go-radix.png)](https://travis-ci.org/armon/go-radix) -========= - -Provides the `radix` package that implements a [radix tree](http://en.wikipedia.org/wiki/Radix_tree). -The package only provides a single `Tree` implementation, optimized for sparse nodes. - -As a radix tree, it provides the following: - * O(k) operations. In many cases, this can be faster than a hash table since - the hash function is an O(k) operation, and hash tables have very poor cache locality. - * Minimum / Maximum value lookups - * Ordered iteration - -For an immutable variant, see [go-immutable-radix](https://github.com/hashicorp/go-immutable-radix). - -Documentation -============= - -The full documentation is available on [Godoc](http://godoc.org/github.com/armon/go-radix). - -Example -======= - -Below is a simple example of usage - -```go -// Create a tree -r := radix.New() -r.Insert("foo", 1) -r.Insert("bar", 2) -r.Insert("foobar", 2) - -// Find the longest prefix match -m, _, _ := r.LongestPrefix("foozip") -if m != "foo" { - panic("should be foo") -} -``` - diff --git a/vendor/github.com/armon/go-radix/radix_test.go b/vendor/github.com/armon/go-radix/radix_test.go deleted file mode 100644 index 300f0d47..00000000 --- a/vendor/github.com/armon/go-radix/radix_test.go +++ /dev/null @@ -1,319 +0,0 @@ -package radix - -import ( - crand "crypto/rand" - "fmt" - "reflect" - "sort" - "testing" -) - -func TestRadix(t *testing.T) { - var min, max string - inp := make(map[string]interface{}) - for i := 0; i < 1000; i++ { - gen := generateUUID() - inp[gen] = i - if gen < min || i == 0 { - min = gen - } - if gen > max || i == 0 { - max = gen - } - } - - r := NewFromMap(inp) - if r.Len() != len(inp) { - t.Fatalf("bad length: %v %v", r.Len(), len(inp)) - } - - r.Walk(func(k string, v interface{}) bool { - println(k) - return false - }) - - for k, v := range inp { - out, ok := r.Get(k) - if !ok { - t.Fatalf("missing key: %v", k) - } - if out != v { - t.Fatalf("value mis-match: %v %v", out, v) - } - } - - // Check min and max - outMin, _, _ := r.Minimum() - if outMin != min { - t.Fatalf("bad minimum: %v %v", outMin, min) - } - outMax, _, _ := r.Maximum() - if outMax != max { - t.Fatalf("bad maximum: %v %v", outMax, max) - } - - for k, v := range inp { - out, ok := r.Delete(k) - if !ok { - t.Fatalf("missing key: %v", k) - } - if out != v { - t.Fatalf("value mis-match: %v %v", out, v) - } - } - if r.Len() != 0 { - t.Fatalf("bad length: %v", r.Len()) - } -} - -func TestRoot(t *testing.T) { - r := New() - _, ok := r.Delete("") - if ok { - t.Fatalf("bad") - } - _, ok = r.Insert("", true) - if ok { - t.Fatalf("bad") - } - val, ok := r.Get("") - if !ok || val != true { - t.Fatalf("bad: %v", val) - } - val, ok = r.Delete("") - if !ok || val != true { - t.Fatalf("bad: %v", val) - } -} - -func TestDelete(t *testing.T) { - - r := New() - - s := []string{"", "A", "AB"} - - for _, ss := range s { - r.Insert(ss, true) - } - - for _, ss := range s { - _, ok := r.Delete(ss) - if !ok { - t.Fatalf("bad %q", ss) - } - } -} - -func TestLongestPrefix(t *testing.T) { - r := New() - - keys := []string{ - "", - "foo", - "foobar", - "foobarbaz", - "foobarbazzip", - "foozip", - } - for _, k := range keys { - r.Insert(k, nil) - } - if r.Len() != len(keys) { - t.Fatalf("bad len: %v %v", r.Len(), len(keys)) - } - - type exp struct { - inp string - out string - } - cases := []exp{ - {"a", ""}, - {"abc", ""}, - {"fo", ""}, - {"foo", "foo"}, - {"foob", "foo"}, - {"foobar", "foobar"}, - {"foobarba", "foobar"}, - {"foobarbaz", "foobarbaz"}, - {"foobarbazzi", "foobarbaz"}, - {"foobarbazzip", "foobarbazzip"}, - {"foozi", "foo"}, - {"foozip", "foozip"}, - {"foozipzap", "foozip"}, - } - for _, test := range cases { - m, _, ok := r.LongestPrefix(test.inp) - if !ok { - t.Fatalf("no match: %v", test) - } - if m != test.out { - t.Fatalf("mis-match: %v %v", m, test) - } - } -} - -func TestWalkPrefix(t *testing.T) { - r := New() - - keys := []string{ - "foobar", - "foo/bar/baz", - "foo/baz/bar", - "foo/zip/zap", - "zipzap", - } - for _, k := range keys { - r.Insert(k, nil) - } - if r.Len() != len(keys) { - t.Fatalf("bad len: %v %v", r.Len(), len(keys)) - } - - type exp struct { - inp string - out []string - } - cases := []exp{ - { - "f", - []string{"foobar", "foo/bar/baz", "foo/baz/bar", "foo/zip/zap"}, - }, - { - "foo", - []string{"foobar", "foo/bar/baz", "foo/baz/bar", "foo/zip/zap"}, - }, - { - "foob", - []string{"foobar"}, - }, - { - "foo/", - []string{"foo/bar/baz", "foo/baz/bar", "foo/zip/zap"}, - }, - { - "foo/b", - []string{"foo/bar/baz", "foo/baz/bar"}, - }, - { - "foo/ba", - []string{"foo/bar/baz", "foo/baz/bar"}, - }, - { - "foo/bar", - []string{"foo/bar/baz"}, - }, - { - "foo/bar/baz", - []string{"foo/bar/baz"}, - }, - { - "foo/bar/bazoo", - []string{}, - }, - { - "z", - []string{"zipzap"}, - }, - } - - for _, test := range cases { - out := []string{} - fn := func(s string, v interface{}) bool { - out = append(out, s) - return false - } - r.WalkPrefix(test.inp, fn) - sort.Strings(out) - sort.Strings(test.out) - if !reflect.DeepEqual(out, test.out) { - t.Fatalf("mis-match: %v %v", out, test.out) - } - } -} - -func TestWalkPath(t *testing.T) { - r := New() - - keys := []string{ - "foo", - "foo/bar", - "foo/bar/baz", - "foo/baz/bar", - "foo/zip/zap", - "zipzap", - } - for _, k := range keys { - r.Insert(k, nil) - } - if r.Len() != len(keys) { - t.Fatalf("bad len: %v %v", r.Len(), len(keys)) - } - - type exp struct { - inp string - out []string - } - cases := []exp{ - { - "f", - []string{}, - }, - { - "foo", - []string{"foo"}, - }, - { - "foo/", - []string{"foo"}, - }, - { - "foo/ba", - []string{"foo"}, - }, - { - "foo/bar", - []string{"foo", "foo/bar"}, - }, - { - "foo/bar/baz", - []string{"foo", "foo/bar", "foo/bar/baz"}, - }, - { - "foo/bar/bazoo", - []string{"foo", "foo/bar", "foo/bar/baz"}, - }, - { - "z", - []string{}, - }, - } - - for _, test := range cases { - out := []string{} - fn := func(s string, v interface{}) bool { - out = append(out, s) - return false - } - r.WalkPath(test.inp, fn) - sort.Strings(out) - sort.Strings(test.out) - if !reflect.DeepEqual(out, test.out) { - t.Fatalf("mis-match: %v %v", out, test.out) - } - } -} - -// generateUUID is used to generate a random UUID -func generateUUID() string { - buf := make([]byte, 16) - if _, err := crand.Read(buf); err != nil { - panic(fmt.Errorf("failed to read random bytes: %v", err)) - } - - return fmt.Sprintf("%08x-%04x-%04x-%04x-%12x", - buf[0:4], - buf[4:6], - buf[6:8], - buf[8:10], - buf[10:16]) -} diff --git a/vendor/github.com/boltdb/bolt/.gitignore b/vendor/github.com/boltdb/bolt/.gitignore deleted file mode 100644 index c7bd2b7a..00000000 --- a/vendor/github.com/boltdb/bolt/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -*.prof -*.test -*.swp -/bin/ diff --git a/vendor/github.com/boltdb/bolt/Makefile b/vendor/github.com/boltdb/bolt/Makefile deleted file mode 100644 index e035e63a..00000000 --- a/vendor/github.com/boltdb/bolt/Makefile +++ /dev/null @@ -1,18 +0,0 @@ -BRANCH=`git rev-parse --abbrev-ref HEAD` -COMMIT=`git rev-parse --short HEAD` -GOLDFLAGS="-X main.branch $(BRANCH) -X main.commit $(COMMIT)" - -default: build - -race: - @go test -v -race -test.run="TestSimulate_(100op|1000op)" - -# go get github.com/kisielk/errcheck -errcheck: - @errcheck -ignorepkg=bytes -ignore=os:Remove github.com/boltdb/bolt - -test: - @go test -v -cover . - @go test -v ./cmd/bolt - -.PHONY: fmt test diff --git a/vendor/github.com/boltdb/bolt/README.md b/vendor/github.com/boltdb/bolt/README.md deleted file mode 100644 index 7d43a15b..00000000 --- a/vendor/github.com/boltdb/bolt/README.md +++ /dev/null @@ -1,916 +0,0 @@ -Bolt [![Coverage Status](https://coveralls.io/repos/boltdb/bolt/badge.svg?branch=master)](https://coveralls.io/r/boltdb/bolt?branch=master) [![GoDoc](https://godoc.org/github.com/boltdb/bolt?status.svg)](https://godoc.org/github.com/boltdb/bolt) ![Version](https://img.shields.io/badge/version-1.2.1-green.svg) -==== - -Bolt is a pure Go key/value store inspired by [Howard Chu's][hyc_symas] -[LMDB project][lmdb]. The goal of the project is to provide a simple, -fast, and reliable database for projects that don't require a full database -server such as Postgres or MySQL. - -Since Bolt is meant to be used as such a low-level piece of functionality, -simplicity is key. The API will be small and only focus on getting values -and setting values. That's it. - -[hyc_symas]: https://twitter.com/hyc_symas -[lmdb]: http://symas.com/mdb/ - -## Project Status - -Bolt is stable, the API is fixed, and the file format is fixed. Full unit -test coverage and randomized black box testing are used to ensure database -consistency and thread safety. Bolt is currently used in high-load production -environments serving databases as large as 1TB. Many companies such as -Shopify and Heroku use Bolt-backed services every day. - -## Table of Contents - -- [Getting Started](#getting-started) - - [Installing](#installing) - - [Opening a database](#opening-a-database) - - [Transactions](#transactions) - - [Read-write transactions](#read-write-transactions) - - [Read-only transactions](#read-only-transactions) - - [Batch read-write transactions](#batch-read-write-transactions) - - [Managing transactions manually](#managing-transactions-manually) - - [Using buckets](#using-buckets) - - [Using key/value pairs](#using-keyvalue-pairs) - - [Autoincrementing integer for the bucket](#autoincrementing-integer-for-the-bucket) - - [Iterating over keys](#iterating-over-keys) - - [Prefix scans](#prefix-scans) - - [Range scans](#range-scans) - - [ForEach()](#foreach) - - [Nested buckets](#nested-buckets) - - [Database backups](#database-backups) - - [Statistics](#statistics) - - [Read-Only Mode](#read-only-mode) - - [Mobile Use (iOS/Android)](#mobile-use-iosandroid) -- [Resources](#resources) -- [Comparison with other databases](#comparison-with-other-databases) - - [Postgres, MySQL, & other relational databases](#postgres-mysql--other-relational-databases) - - [LevelDB, RocksDB](#leveldb-rocksdb) - - [LMDB](#lmdb) -- [Caveats & Limitations](#caveats--limitations) -- [Reading the Source](#reading-the-source) -- [Other Projects Using Bolt](#other-projects-using-bolt) - -## Getting Started - -### Installing - -To start using Bolt, install Go and run `go get`: - -```sh -$ go get github.com/boltdb/bolt/... -``` - -This will retrieve the library and install the `bolt` command line utility into -your `$GOBIN` path. - - -### Opening a database - -The top-level object in Bolt is a `DB`. It is represented as a single file on -your disk and represents a consistent snapshot of your data. - -To open your database, simply use the `bolt.Open()` function: - -```go -package main - -import ( - "log" - - "github.com/boltdb/bolt" -) - -func main() { - // Open the my.db data file in your current directory. - // It will be created if it doesn't exist. - db, err := bolt.Open("my.db", 0600, nil) - if err != nil { - log.Fatal(err) - } - defer db.Close() - - ... -} -``` - -Please note that Bolt obtains a file lock on the data file so multiple processes -cannot open the same database at the same time. Opening an already open Bolt -database will cause it to hang until the other process closes it. To prevent -an indefinite wait you can pass a timeout option to the `Open()` function: - -```go -db, err := bolt.Open("my.db", 0600, &bolt.Options{Timeout: 1 * time.Second}) -``` - - -### Transactions - -Bolt allows only one read-write transaction at a time but allows as many -read-only transactions as you want at a time. Each transaction has a consistent -view of the data as it existed when the transaction started. - -Individual transactions and all objects created from them (e.g. buckets, keys) -are not thread safe. To work with data in multiple goroutines you must start -a transaction for each one or use locking to ensure only one goroutine accesses -a transaction at a time. Creating transaction from the `DB` is thread safe. - -Read-only transactions and read-write transactions should not depend on one -another and generally shouldn't be opened simultaneously in the same goroutine. -This can cause a deadlock as the read-write transaction needs to periodically -re-map the data file but it cannot do so while a read-only transaction is open. - - -#### Read-write transactions - -To start a read-write transaction, you can use the `DB.Update()` function: - -```go -err := db.Update(func(tx *bolt.Tx) error { - ... - return nil -}) -``` - -Inside the closure, you have a consistent view of the database. You commit the -transaction by returning `nil` at the end. You can also rollback the transaction -at any point by returning an error. All database operations are allowed inside -a read-write transaction. - -Always check the return error as it will report any disk failures that can cause -your transaction to not complete. If you return an error within your closure -it will be passed through. - - -#### Read-only transactions - -To start a read-only transaction, you can use the `DB.View()` function: - -```go -err := db.View(func(tx *bolt.Tx) error { - ... - return nil -}) -``` - -You also get a consistent view of the database within this closure, however, -no mutating operations are allowed within a read-only transaction. You can only -retrieve buckets, retrieve values, and copy the database within a read-only -transaction. - - -#### Batch read-write transactions - -Each `DB.Update()` waits for disk to commit the writes. This overhead -can be minimized by combining multiple updates with the `DB.Batch()` -function: - -```go -err := db.Batch(func(tx *bolt.Tx) error { - ... - return nil -}) -``` - -Concurrent Batch calls are opportunistically combined into larger -transactions. Batch is only useful when there are multiple goroutines -calling it. - -The trade-off is that `Batch` can call the given -function multiple times, if parts of the transaction fail. The -function must be idempotent and side effects must take effect only -after a successful return from `DB.Batch()`. - -For example: don't display messages from inside the function, instead -set variables in the enclosing scope: - -```go -var id uint64 -err := db.Batch(func(tx *bolt.Tx) error { - // Find last key in bucket, decode as bigendian uint64, increment - // by one, encode back to []byte, and add new key. - ... - id = newValue - return nil -}) -if err != nil { - return ... -} -fmt.Println("Allocated ID %d", id) -``` - - -#### Managing transactions manually - -The `DB.View()` and `DB.Update()` functions are wrappers around the `DB.Begin()` -function. These helper functions will start the transaction, execute a function, -and then safely close your transaction if an error is returned. This is the -recommended way to use Bolt transactions. - -However, sometimes you may want to manually start and end your transactions. -You can use the `DB.Begin()` function directly but **please** be sure to close -the transaction. - -```go -// Start a writable transaction. -tx, err := db.Begin(true) -if err != nil { - return err -} -defer tx.Rollback() - -// Use the transaction... -_, err := tx.CreateBucket([]byte("MyBucket")) -if err != nil { - return err -} - -// Commit the transaction and check for error. -if err := tx.Commit(); err != nil { - return err -} -``` - -The first argument to `DB.Begin()` is a boolean stating if the transaction -should be writable. - - -### Using buckets - -Buckets are collections of key/value pairs within the database. All keys in a -bucket must be unique. You can create a bucket using the `DB.CreateBucket()` -function: - -```go -db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("MyBucket")) - if err != nil { - return fmt.Errorf("create bucket: %s", err) - } - return nil -}) -``` - -You can also create a bucket only if it doesn't exist by using the -`Tx.CreateBucketIfNotExists()` function. It's a common pattern to call this -function for all your top-level buckets after you open your database so you can -guarantee that they exist for future transactions. - -To delete a bucket, simply call the `Tx.DeleteBucket()` function. - - -### Using key/value pairs - -To save a key/value pair to a bucket, use the `Bucket.Put()` function: - -```go -db.Update(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("MyBucket")) - err := b.Put([]byte("answer"), []byte("42")) - return err -}) -``` - -This will set the value of the `"answer"` key to `"42"` in the `MyBucket` -bucket. To retrieve this value, we can use the `Bucket.Get()` function: - -```go -db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("MyBucket")) - v := b.Get([]byte("answer")) - fmt.Printf("The answer is: %s\n", v) - return nil -}) -``` - -The `Get()` function does not return an error because its operation is -guaranteed to work (unless there is some kind of system failure). If the key -exists then it will return its byte slice value. If it doesn't exist then it -will return `nil`. It's important to note that you can have a zero-length value -set to a key which is different than the key not existing. - -Use the `Bucket.Delete()` function to delete a key from the bucket. - -Please note that values returned from `Get()` are only valid while the -transaction is open. If you need to use a value outside of the transaction -then you must use `copy()` to copy it to another byte slice. - - -### Autoincrementing integer for the bucket -By using the `NextSequence()` function, you can let Bolt determine a sequence -which can be used as the unique identifier for your key/value pairs. See the -example below. - -```go -// CreateUser saves u to the store. The new user ID is set on u once the data is persisted. -func (s *Store) CreateUser(u *User) error { - return s.db.Update(func(tx *bolt.Tx) error { - // Retrieve the users bucket. - // This should be created when the DB is first opened. - b := tx.Bucket([]byte("users")) - - // Generate ID for the user. - // This returns an error only if the Tx is closed or not writeable. - // That can't happen in an Update() call so I ignore the error check. - id, _ := b.NextSequence() - u.ID = int(id) - - // Marshal user data into bytes. - buf, err := json.Marshal(u) - if err != nil { - return err - } - - // Persist bytes to users bucket. - return b.Put(itob(u.ID), buf) - }) -} - -// itob returns an 8-byte big endian representation of v. -func itob(v int) []byte { - b := make([]byte, 8) - binary.BigEndian.PutUint64(b, uint64(v)) - return b -} - -type User struct { - ID int - ... -} -``` - -### Iterating over keys - -Bolt stores its keys in byte-sorted order within a bucket. This makes sequential -iteration over these keys extremely fast. To iterate over keys we'll use a -`Cursor`: - -```go -db.View(func(tx *bolt.Tx) error { - // Assume bucket exists and has keys - b := tx.Bucket([]byte("MyBucket")) - - c := b.Cursor() - - for k, v := c.First(); k != nil; k, v = c.Next() { - fmt.Printf("key=%s, value=%s\n", k, v) - } - - return nil -}) -``` - -The cursor allows you to move to a specific point in the list of keys and move -forward or backward through the keys one at a time. - -The following functions are available on the cursor: - -``` -First() Move to the first key. -Last() Move to the last key. -Seek() Move to a specific key. -Next() Move to the next key. -Prev() Move to the previous key. -``` - -Each of those functions has a return signature of `(key []byte, value []byte)`. -When you have iterated to the end of the cursor then `Next()` will return a -`nil` key. You must seek to a position using `First()`, `Last()`, or `Seek()` -before calling `Next()` or `Prev()`. If you do not seek to a position then -these functions will return a `nil` key. - -During iteration, if the key is non-`nil` but the value is `nil`, that means -the key refers to a bucket rather than a value. Use `Bucket.Bucket()` to -access the sub-bucket. - - -#### Prefix scans - -To iterate over a key prefix, you can combine `Seek()` and `bytes.HasPrefix()`: - -```go -db.View(func(tx *bolt.Tx) error { - // Assume bucket exists and has keys - c := tx.Bucket([]byte("MyBucket")).Cursor() - - prefix := []byte("1234") - for k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() { - fmt.Printf("key=%s, value=%s\n", k, v) - } - - return nil -}) -``` - -#### Range scans - -Another common use case is scanning over a range such as a time range. If you -use a sortable time encoding such as RFC3339 then you can query a specific -date range like this: - -```go -db.View(func(tx *bolt.Tx) error { - // Assume our events bucket exists and has RFC3339 encoded time keys. - c := tx.Bucket([]byte("Events")).Cursor() - - // Our time range spans the 90's decade. - min := []byte("1990-01-01T00:00:00Z") - max := []byte("2000-01-01T00:00:00Z") - - // Iterate over the 90's. - for k, v := c.Seek(min); k != nil && bytes.Compare(k, max) <= 0; k, v = c.Next() { - fmt.Printf("%s: %s\n", k, v) - } - - return nil -}) -``` - -Note that, while RFC3339 is sortable, the Golang implementation of RFC3339Nano does not use a fixed number of digits after the decimal point and is therefore not sortable. - - -#### ForEach() - -You can also use the function `ForEach()` if you know you'll be iterating over -all the keys in a bucket: - -```go -db.View(func(tx *bolt.Tx) error { - // Assume bucket exists and has keys - b := tx.Bucket([]byte("MyBucket")) - - b.ForEach(func(k, v []byte) error { - fmt.Printf("key=%s, value=%s\n", k, v) - return nil - }) - return nil -}) -``` - -Please note that keys and values in `ForEach()` are only valid while -the transaction is open. If you need to use a key or value outside of -the transaction, you must use `copy()` to copy it to another byte -slice. - -### Nested buckets - -You can also store a bucket in a key to create nested buckets. The API is the -same as the bucket management API on the `DB` object: - -```go -func (*Bucket) CreateBucket(key []byte) (*Bucket, error) -func (*Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error) -func (*Bucket) DeleteBucket(key []byte) error -``` - -Say you had a multi-tenant application where the root level bucket was the account bucket. Inside of this bucket was a sequence of accounts which themselves are buckets. And inside the sequence bucket you could have many buckets pertaining to the Account itself (Users, Notes, etc) isolating the information into logical groupings. - -```go - -// createUser creates a new user in the given account. -func createUser(accountID int, u *User) error { - // Start the transaction. - tx, err := db.Begin(true) - if err != nil { - return err - } - defer tx.Rollback() - - // Retrieve the root bucket for the account. - // Assume this has already been created when the account was set up. - root := tx.Bucket([]byte(strconv.FormatUint(accountID, 10))) - - // Setup the users bucket. - bkt, err := root.CreateBucketIfNotExists([]byte("USERS")) - if err != nil { - return err - } - - // Generate an ID for the new user. - userID, err := bkt.NextSequence() - if err != nil { - return err - } - u.ID = userID - - // Marshal and save the encoded user. - if buf, err := json.Marshal(u); err != nil { - return err - } else if err := bkt.Put([]byte(strconv.FormatUint(u.ID, 10)), buf); err != nil { - return err - } - - // Commit the transaction. - if err := tx.Commit(); err != nil { - return err - } - - return nil -} - -``` - - - - -### Database backups - -Bolt is a single file so it's easy to backup. You can use the `Tx.WriteTo()` -function to write a consistent view of the database to a writer. If you call -this from a read-only transaction, it will perform a hot backup and not block -your other database reads and writes. - -By default, it will use a regular file handle which will utilize the operating -system's page cache. See the [`Tx`](https://godoc.org/github.com/boltdb/bolt#Tx) -documentation for information about optimizing for larger-than-RAM datasets. - -One common use case is to backup over HTTP so you can use tools like `cURL` to -do database backups: - -```go -func BackupHandleFunc(w http.ResponseWriter, req *http.Request) { - err := db.View(func(tx *bolt.Tx) error { - w.Header().Set("Content-Type", "application/octet-stream") - w.Header().Set("Content-Disposition", `attachment; filename="my.db"`) - w.Header().Set("Content-Length", strconv.Itoa(int(tx.Size()))) - _, err := tx.WriteTo(w) - return err - }) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } -} -``` - -Then you can backup using this command: - -```sh -$ curl http://localhost/backup > my.db -``` - -Or you can open your browser to `http://localhost/backup` and it will download -automatically. - -If you want to backup to another file you can use the `Tx.CopyFile()` helper -function. - - -### Statistics - -The database keeps a running count of many of the internal operations it -performs so you can better understand what's going on. By grabbing a snapshot -of these stats at two points in time we can see what operations were performed -in that time range. - -For example, we could start a goroutine to log stats every 10 seconds: - -```go -go func() { - // Grab the initial stats. - prev := db.Stats() - - for { - // Wait for 10s. - time.Sleep(10 * time.Second) - - // Grab the current stats and diff them. - stats := db.Stats() - diff := stats.Sub(&prev) - - // Encode stats to JSON and print to STDERR. - json.NewEncoder(os.Stderr).Encode(diff) - - // Save stats for the next loop. - prev = stats - } -}() -``` - -It's also useful to pipe these stats to a service such as statsd for monitoring -or to provide an HTTP endpoint that will perform a fixed-length sample. - - -### Read-Only Mode - -Sometimes it is useful to create a shared, read-only Bolt database. To this, -set the `Options.ReadOnly` flag when opening your database. Read-only mode -uses a shared lock to allow multiple processes to read from the database but -it will block any processes from opening the database in read-write mode. - -```go -db, err := bolt.Open("my.db", 0666, &bolt.Options{ReadOnly: true}) -if err != nil { - log.Fatal(err) -} -``` - -### Mobile Use (iOS/Android) - -Bolt is able to run on mobile devices by leveraging the binding feature of the -[gomobile](https://github.com/golang/mobile) tool. Create a struct that will -contain your database logic and a reference to a `*bolt.DB` with a initializing -constructor that takes in a filepath where the database file will be stored. -Neither Android nor iOS require extra permissions or cleanup from using this method. - -```go -func NewBoltDB(filepath string) *BoltDB { - db, err := bolt.Open(filepath+"/demo.db", 0600, nil) - if err != nil { - log.Fatal(err) - } - - return &BoltDB{db} -} - -type BoltDB struct { - db *bolt.DB - ... -} - -func (b *BoltDB) Path() string { - return b.db.Path() -} - -func (b *BoltDB) Close() { - b.db.Close() -} -``` - -Database logic should be defined as methods on this wrapper struct. - -To initialize this struct from the native language (both platforms now sync -their local storage to the cloud. These snippets disable that functionality for the -database file): - -#### Android - -```java -String path; -if (android.os.Build.VERSION.SDK_INT >=android.os.Build.VERSION_CODES.LOLLIPOP){ - path = getNoBackupFilesDir().getAbsolutePath(); -} else{ - path = getFilesDir().getAbsolutePath(); -} -Boltmobiledemo.BoltDB boltDB = Boltmobiledemo.NewBoltDB(path) -``` - -#### iOS - -```objc -- (void)demo { - NSString* path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, - NSUserDomainMask, - YES) objectAtIndex:0]; - GoBoltmobiledemoBoltDB * demo = GoBoltmobiledemoNewBoltDB(path); - [self addSkipBackupAttributeToItemAtPath:demo.path]; - //Some DB Logic would go here - [demo close]; -} - -- (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *) filePathString -{ - NSURL* URL= [NSURL fileURLWithPath: filePathString]; - assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]); - - NSError *error = nil; - BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES] - forKey: NSURLIsExcludedFromBackupKey error: &error]; - if(!success){ - NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error); - } - return success; -} - -``` - -## Resources - -For more information on getting started with Bolt, check out the following articles: - -* [Intro to BoltDB: Painless Performant Persistence](http://npf.io/2014/07/intro-to-boltdb-painless-performant-persistence/) by [Nate Finch](https://github.com/natefinch). -* [Bolt -- an embedded key/value database for Go](https://www.progville.com/go/bolt-embedded-db-golang/) by Progville - - -## Comparison with other databases - -### Postgres, MySQL, & other relational databases - -Relational databases structure data into rows and are only accessible through -the use of SQL. This approach provides flexibility in how you store and query -your data but also incurs overhead in parsing and planning SQL statements. Bolt -accesses all data by a byte slice key. This makes Bolt fast to read and write -data by key but provides no built-in support for joining values together. - -Most relational databases (with the exception of SQLite) are standalone servers -that run separately from your application. This gives your systems -flexibility to connect multiple application servers to a single database -server but also adds overhead in serializing and transporting data over the -network. Bolt runs as a library included in your application so all data access -has to go through your application's process. This brings data closer to your -application but limits multi-process access to the data. - - -### LevelDB, RocksDB - -LevelDB and its derivatives (RocksDB, HyperLevelDB) are similar to Bolt in that -they are libraries bundled into the application, however, their underlying -structure is a log-structured merge-tree (LSM tree). An LSM tree optimizes -random writes by using a write ahead log and multi-tiered, sorted files called -SSTables. Bolt uses a B+tree internally and only a single file. Both approaches -have trade-offs. - -If you require a high random write throughput (>10,000 w/sec) or you need to use -spinning disks then LevelDB could be a good choice. If your application is -read-heavy or does a lot of range scans then Bolt could be a good choice. - -One other important consideration is that LevelDB does not have transactions. -It supports batch writing of key/values pairs and it supports read snapshots -but it will not give you the ability to do a compare-and-swap operation safely. -Bolt supports fully serializable ACID transactions. - - -### LMDB - -Bolt was originally a port of LMDB so it is architecturally similar. Both use -a B+tree, have ACID semantics with fully serializable transactions, and support -lock-free MVCC using a single writer and multiple readers. - -The two projects have somewhat diverged. LMDB heavily focuses on raw performance -while Bolt has focused on simplicity and ease of use. For example, LMDB allows -several unsafe actions such as direct writes for the sake of performance. Bolt -opts to disallow actions which can leave the database in a corrupted state. The -only exception to this in Bolt is `DB.NoSync`. - -There are also a few differences in API. LMDB requires a maximum mmap size when -opening an `mdb_env` whereas Bolt will handle incremental mmap resizing -automatically. LMDB overloads the getter and setter functions with multiple -flags whereas Bolt splits these specialized cases into their own functions. - - -## Caveats & Limitations - -It's important to pick the right tool for the job and Bolt is no exception. -Here are a few things to note when evaluating and using Bolt: - -* Bolt is good for read intensive workloads. Sequential write performance is - also fast but random writes can be slow. You can use `DB.Batch()` or add a - write-ahead log to help mitigate this issue. - -* Bolt uses a B+tree internally so there can be a lot of random page access. - SSDs provide a significant performance boost over spinning disks. - -* Try to avoid long running read transactions. Bolt uses copy-on-write so - old pages cannot be reclaimed while an old transaction is using them. - -* Byte slices returned from Bolt are only valid during a transaction. Once the - transaction has been committed or rolled back then the memory they point to - can be reused by a new page or can be unmapped from virtual memory and you'll - see an `unexpected fault address` panic when accessing it. - -* Bolt uses an exclusive write lock on the database file so it cannot be - shared by multiple processes. - -* Be careful when using `Bucket.FillPercent`. Setting a high fill percent for - buckets that have random inserts will cause your database to have very poor - page utilization. - -* Use larger buckets in general. Smaller buckets causes poor page utilization - once they become larger than the page size (typically 4KB). - -* Bulk loading a lot of random writes into a new bucket can be slow as the - page will not split until the transaction is committed. Randomly inserting - more than 100,000 key/value pairs into a single new bucket in a single - transaction is not advised. - -* Bolt uses a memory-mapped file so the underlying operating system handles the - caching of the data. Typically, the OS will cache as much of the file as it - can in memory and will release memory as needed to other processes. This means - that Bolt can show very high memory usage when working with large databases. - However, this is expected and the OS will release memory as needed. Bolt can - handle databases much larger than the available physical RAM, provided its - memory-map fits in the process virtual address space. It may be problematic - on 32-bits systems. - -* The data structures in the Bolt database are memory mapped so the data file - will be endian specific. This means that you cannot copy a Bolt file from a - little endian machine to a big endian machine and have it work. For most - users this is not a concern since most modern CPUs are little endian. - -* Because of the way pages are laid out on disk, Bolt cannot truncate data files - and return free pages back to the disk. Instead, Bolt maintains a free list - of unused pages within its data file. These free pages can be reused by later - transactions. This works well for many use cases as databases generally tend - to grow. However, it's important to note that deleting large chunks of data - will not allow you to reclaim that space on disk. - - For more information on page allocation, [see this comment][page-allocation]. - -[page-allocation]: https://github.com/boltdb/bolt/issues/308#issuecomment-74811638 - - -## Reading the Source - -Bolt is a relatively small code base (<3KLOC) for an embedded, serializable, -transactional key/value database so it can be a good starting point for people -interested in how databases work. - -The best places to start are the main entry points into Bolt: - -- `Open()` - Initializes the reference to the database. It's responsible for - creating the database if it doesn't exist, obtaining an exclusive lock on the - file, reading the meta pages, & memory-mapping the file. - -- `DB.Begin()` - Starts a read-only or read-write transaction depending on the - value of the `writable` argument. This requires briefly obtaining the "meta" - lock to keep track of open transactions. Only one read-write transaction can - exist at a time so the "rwlock" is acquired during the life of a read-write - transaction. - -- `Bucket.Put()` - Writes a key/value pair into a bucket. After validating the - arguments, a cursor is used to traverse the B+tree to the page and position - where they key & value will be written. Once the position is found, the bucket - materializes the underlying page and the page's parent pages into memory as - "nodes". These nodes are where mutations occur during read-write transactions. - These changes get flushed to disk during commit. - -- `Bucket.Get()` - Retrieves a key/value pair from a bucket. This uses a cursor - to move to the page & position of a key/value pair. During a read-only - transaction, the key and value data is returned as a direct reference to the - underlying mmap file so there's no allocation overhead. For read-write - transactions, this data may reference the mmap file or one of the in-memory - node values. - -- `Cursor` - This object is simply for traversing the B+tree of on-disk pages - or in-memory nodes. It can seek to a specific key, move to the first or last - value, or it can move forward or backward. The cursor handles the movement up - and down the B+tree transparently to the end user. - -- `Tx.Commit()` - Converts the in-memory dirty nodes and the list of free pages - into pages to be written to disk. Writing to disk then occurs in two phases. - First, the dirty pages are written to disk and an `fsync()` occurs. Second, a - new meta page with an incremented transaction ID is written and another - `fsync()` occurs. This two phase write ensures that partially written data - pages are ignored in the event of a crash since the meta page pointing to them - is never written. Partially written meta pages are invalidated because they - are written with a checksum. - -If you have additional notes that could be helpful for others, please submit -them via pull request. - - -## Other Projects Using Bolt - -Below is a list of public, open source projects that use Bolt: - -* [BoltDbWeb](https://github.com/evnix/boltdbweb) - A web based GUI for BoltDB files. -* [Operation Go: A Routine Mission](http://gocode.io) - An online programming game for Golang using Bolt for user accounts and a leaderboard. -* [Bazil](https://bazil.org/) - A file system that lets your data reside where it is most convenient for it to reside. -* [DVID](https://github.com/janelia-flyem/dvid) - Added Bolt as optional storage engine and testing it against Basho-tuned leveldb. -* [Skybox Analytics](https://github.com/skybox/skybox) - A standalone funnel analysis tool for web analytics. -* [Scuttlebutt](https://github.com/benbjohnson/scuttlebutt) - Uses Bolt to store and process all Twitter mentions of GitHub projects. -* [Wiki](https://github.com/peterhellberg/wiki) - A tiny wiki using Goji, BoltDB and Blackfriday. -* [ChainStore](https://github.com/pressly/chainstore) - Simple key-value interface to a variety of storage engines organized as a chain of operations. -* [MetricBase](https://github.com/msiebuhr/MetricBase) - Single-binary version of Graphite. -* [Gitchain](https://github.com/gitchain/gitchain) - Decentralized, peer-to-peer Git repositories aka "Git meets Bitcoin". -* [event-shuttle](https://github.com/sclasen/event-shuttle) - A Unix system service to collect and reliably deliver messages to Kafka. -* [ipxed](https://github.com/kelseyhightower/ipxed) - Web interface and api for ipxed. -* [BoltStore](https://github.com/yosssi/boltstore) - Session store using Bolt. -* [photosite/session](https://godoc.org/bitbucket.org/kardianos/photosite/session) - Sessions for a photo viewing site. -* [LedisDB](https://github.com/siddontang/ledisdb) - A high performance NoSQL, using Bolt as optional storage. -* [ipLocator](https://github.com/AndreasBriese/ipLocator) - A fast ip-geo-location-server using bolt with bloom filters. -* [cayley](https://github.com/google/cayley) - Cayley is an open-source graph database using Bolt as optional backend. -* [bleve](http://www.blevesearch.com/) - A pure Go search engine similar to ElasticSearch that uses Bolt as the default storage backend. -* [tentacool](https://github.com/optiflows/tentacool) - REST api server to manage system stuff (IP, DNS, Gateway...) on a linux server. -* [Seaweed File System](https://github.com/chrislusf/seaweedfs) - Highly scalable distributed key~file system with O(1) disk read. -* [InfluxDB](https://influxdata.com) - Scalable datastore for metrics, events, and real-time analytics. -* [Freehold](http://tshannon.bitbucket.org/freehold/) - An open, secure, and lightweight platform for your files and data. -* [Prometheus Annotation Server](https://github.com/oliver006/prom_annotation_server) - Annotation server for PromDash & Prometheus service monitoring system. -* [Consul](https://github.com/hashicorp/consul) - Consul is service discovery and configuration made easy. Distributed, highly available, and datacenter-aware. -* [Kala](https://github.com/ajvb/kala) - Kala is a modern job scheduler optimized to run on a single node. It is persistent, JSON over HTTP API, ISO 8601 duration notation, and dependent jobs. -* [drive](https://github.com/odeke-em/drive) - drive is an unofficial Google Drive command line client for \*NIX operating systems. -* [stow](https://github.com/djherbis/stow) - a persistence manager for objects - backed by boltdb. -* [buckets](https://github.com/joyrexus/buckets) - a bolt wrapper streamlining - simple tx and key scans. -* [mbuckets](https://github.com/abhigupta912/mbuckets) - A Bolt wrapper that allows easy operations on multi level (nested) buckets. -* [Request Baskets](https://github.com/darklynx/request-baskets) - A web service to collect arbitrary HTTP requests and inspect them via REST API or simple web UI, similar to [RequestBin](http://requestb.in/) service -* [Go Report Card](https://goreportcard.com/) - Go code quality report cards as a (free and open source) service. -* [Boltdb Boilerplate](https://github.com/bobintornado/boltdb-boilerplate) - Boilerplate wrapper around bolt aiming to make simple calls one-liners. -* [lru](https://github.com/crowdriff/lru) - Easy to use Bolt-backed Least-Recently-Used (LRU) read-through cache with chainable remote stores. -* [Storm](https://github.com/asdine/storm) - Simple and powerful ORM for BoltDB. -* [GoWebApp](https://github.com/josephspurrier/gowebapp) - A basic MVC web application in Go using BoltDB. -* [SimpleBolt](https://github.com/xyproto/simplebolt) - A simple way to use BoltDB. Deals mainly with strings. -* [Algernon](https://github.com/xyproto/algernon) - A HTTP/2 web server with built-in support for Lua. Uses BoltDB as the default database backend. -* [MuLiFS](https://github.com/dankomiocevic/mulifs) - Music Library Filesystem creates a filesystem to organise your music files. -* [GoShort](https://github.com/pankajkhairnar/goShort) - GoShort is a URL shortener written in Golang and BoltDB for persistent key/value storage and for routing it's using high performent HTTPRouter. -* [torrent](https://github.com/anacrolix/torrent) - Full-featured BitTorrent client package and utilities in Go. BoltDB is a storage backend in development. -* [gopherpit](https://github.com/gopherpit/gopherpit) - A web service to manage Go remote import paths with custom domains -* [bolter](https://github.com/hasit/bolter) - Command-line app for viewing BoltDB file in your terminal. -* [btcwallet](https://github.com/btcsuite/btcwallet) - A bitcoin wallet. -* [dcrwallet](https://github.com/decred/dcrwallet) - A wallet for the Decred cryptocurrency. -* [Ironsmith](https://github.com/timshannon/ironsmith) - A simple, script-driven continuous integration (build - > test -> release) tool, with no external dependencies -* [BoltHold](https://github.com/timshannon/bolthold) - An embeddable NoSQL store for Go types built on BoltDB -* [Ponzu CMS](https://ponzu-cms.org) - Headless CMS + automatic JSON API with auto-HTTPS, HTTP/2 Server Push, and flexible server framework. - -If you are using Bolt in a project please send a pull request to add it to the list. diff --git a/vendor/github.com/boltdb/bolt/appveyor.yml b/vendor/github.com/boltdb/bolt/appveyor.yml deleted file mode 100644 index 6e26e941..00000000 --- a/vendor/github.com/boltdb/bolt/appveyor.yml +++ /dev/null @@ -1,18 +0,0 @@ -version: "{build}" - -os: Windows Server 2012 R2 - -clone_folder: c:\gopath\src\github.com\boltdb\bolt - -environment: - GOPATH: c:\gopath - -install: - - echo %PATH% - - echo %GOPATH% - - go version - - go env - - go get -v -t ./... - -build_script: - - go test -v ./... diff --git a/vendor/github.com/boltdb/bolt/bucket_test.go b/vendor/github.com/boltdb/bolt/bucket_test.go deleted file mode 100644 index cddbe271..00000000 --- a/vendor/github.com/boltdb/bolt/bucket_test.go +++ /dev/null @@ -1,1909 +0,0 @@ -package bolt_test - -import ( - "bytes" - "encoding/binary" - "errors" - "fmt" - "log" - "math/rand" - "os" - "strconv" - "strings" - "testing" - "testing/quick" - - "github.com/boltdb/bolt" -) - -// Ensure that a bucket that gets a non-existent key returns nil. -func TestBucket_Get_NonExistent(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if v := b.Get([]byte("foo")); v != nil { - t.Fatal("expected nil value") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket can read a value that is not flushed yet. -func TestBucket_Get_FromNode(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - if v := b.Get([]byte("foo")); !bytes.Equal(v, []byte("bar")) { - t.Fatalf("unexpected value: %v", v) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket retrieved via Get() returns a nil. -func TestBucket_Get_IncompatibleValue(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - if _, err := tx.Bucket([]byte("widgets")).CreateBucket([]byte("foo")); err != nil { - t.Fatal(err) - } - - if tx.Bucket([]byte("widgets")).Get([]byte("foo")) != nil { - t.Fatal("expected nil value") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a slice returned from a bucket has a capacity equal to its length. -// This also allows slices to be appended to since it will require a realloc by Go. -// -// https://github.com/boltdb/bolt/issues/544 -func TestBucket_Get_Capacity(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - // Write key to a bucket. - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("bucket")) - if err != nil { - return err - } - return b.Put([]byte("key"), []byte("val")) - }); err != nil { - t.Fatal(err) - } - - // Retrieve value and attempt to append to it. - if err := db.Update(func(tx *bolt.Tx) error { - k, v := tx.Bucket([]byte("bucket")).Cursor().First() - - // Verify capacity. - if len(k) != cap(k) { - t.Fatalf("unexpected key slice capacity: %d", cap(k)) - } else if len(v) != cap(v) { - t.Fatalf("unexpected value slice capacity: %d", cap(v)) - } - - // Ensure slice can be appended to without a segfault. - k = append(k, []byte("123")...) - v = append(v, []byte("123")...) - - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket can write a key/value. -func TestBucket_Put(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - - v := tx.Bucket([]byte("widgets")).Get([]byte("foo")) - if !bytes.Equal([]byte("bar"), v) { - t.Fatalf("unexpected value: %v", v) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket can rewrite a key in the same transaction. -func TestBucket_Put_Repeat(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("baz")); err != nil { - t.Fatal(err) - } - - value := tx.Bucket([]byte("widgets")).Get([]byte("foo")) - if !bytes.Equal([]byte("baz"), value) { - t.Fatalf("unexpected value: %v", value) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket can write a bunch of large values. -func TestBucket_Put_Large(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - count, factor := 100, 200 - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - for i := 1; i < count; i++ { - if err := b.Put([]byte(strings.Repeat("0", i*factor)), []byte(strings.Repeat("X", (count-i)*factor))); err != nil { - t.Fatal(err) - } - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - for i := 1; i < count; i++ { - value := b.Get([]byte(strings.Repeat("0", i*factor))) - if !bytes.Equal(value, []byte(strings.Repeat("X", (count-i)*factor))) { - t.Fatalf("unexpected value: %v", value) - } - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a database can perform multiple large appends safely. -func TestDB_Put_VeryLarge(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - - n, batchN := 400000, 200000 - ksize, vsize := 8, 500 - - db := MustOpenDB() - defer db.MustClose() - - for i := 0; i < n; i += batchN { - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucketIfNotExists([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - for j := 0; j < batchN; j++ { - k, v := make([]byte, ksize), make([]byte, vsize) - binary.BigEndian.PutUint32(k, uint32(i+j)) - if err := b.Put(k, v); err != nil { - t.Fatal(err) - } - } - return nil - }); err != nil { - t.Fatal(err) - } - } -} - -// Ensure that a setting a value on a key with a bucket value returns an error. -func TestBucket_Put_IncompatibleValue(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b0, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - if _, err := tx.Bucket([]byte("widgets")).CreateBucket([]byte("foo")); err != nil { - t.Fatal(err) - } - if err := b0.Put([]byte("foo"), []byte("bar")); err != bolt.ErrIncompatibleValue { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a setting a value while the transaction is closed returns an error. -func TestBucket_Put_Closed(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - if err := tx.Rollback(); err != nil { - t.Fatal(err) - } - - if err := b.Put([]byte("foo"), []byte("bar")); err != bolt.ErrTxClosed { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure that setting a value on a read-only bucket returns an error. -func TestBucket_Put_ReadOnly(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - if err := b.Put([]byte("foo"), []byte("bar")); err != bolt.ErrTxNotWritable { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket can delete an existing key. -func TestBucket_Delete(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - if err := b.Delete([]byte("foo")); err != nil { - t.Fatal(err) - } - if v := b.Get([]byte("foo")); v != nil { - t.Fatalf("unexpected value: %v", v) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that deleting a large set of keys will work correctly. -func TestBucket_Delete_Large(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - for i := 0; i < 100; i++ { - if err := b.Put([]byte(strconv.Itoa(i)), []byte(strings.Repeat("*", 1024))); err != nil { - t.Fatal(err) - } - } - - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.Update(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - for i := 0; i < 100; i++ { - if err := b.Delete([]byte(strconv.Itoa(i))); err != nil { - t.Fatal(err) - } - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - for i := 0; i < 100; i++ { - if v := b.Get([]byte(strconv.Itoa(i))); v != nil { - t.Fatalf("unexpected value: %v, i=%d", v, i) - } - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Deleting a very large list of keys will cause the freelist to use overflow. -func TestBucket_Delete_FreelistOverflow(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - - db := MustOpenDB() - defer db.MustClose() - - k := make([]byte, 16) - for i := uint64(0); i < 10000; i++ { - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucketIfNotExists([]byte("0")) - if err != nil { - t.Fatalf("bucket error: %s", err) - } - - for j := uint64(0); j < 1000; j++ { - binary.BigEndian.PutUint64(k[:8], i) - binary.BigEndian.PutUint64(k[8:], j) - if err := b.Put(k, nil); err != nil { - t.Fatalf("put error: %s", err) - } - } - - return nil - }); err != nil { - t.Fatal(err) - } - } - - // Delete all of them in one large transaction - if err := db.Update(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("0")) - c := b.Cursor() - for k, _ := c.First(); k != nil; k, _ = c.Next() { - if err := c.Delete(); err != nil { - t.Fatal(err) - } - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that accessing and updating nested buckets is ok across transactions. -func TestBucket_Nested(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - // Create a widgets bucket. - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - // Create a widgets/foo bucket. - _, err = b.CreateBucket([]byte("foo")) - if err != nil { - t.Fatal(err) - } - - // Create a widgets/bar key. - if err := b.Put([]byte("bar"), []byte("0000")); err != nil { - t.Fatal(err) - } - - return nil - }); err != nil { - t.Fatal(err) - } - db.MustCheck() - - // Update widgets/bar. - if err := db.Update(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - if err := b.Put([]byte("bar"), []byte("xxxx")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - db.MustCheck() - - // Cause a split. - if err := db.Update(func(tx *bolt.Tx) error { - var b = tx.Bucket([]byte("widgets")) - for i := 0; i < 10000; i++ { - if err := b.Put([]byte(strconv.Itoa(i)), []byte(strconv.Itoa(i))); err != nil { - t.Fatal(err) - } - } - return nil - }); err != nil { - t.Fatal(err) - } - db.MustCheck() - - // Insert into widgets/foo/baz. - if err := db.Update(func(tx *bolt.Tx) error { - var b = tx.Bucket([]byte("widgets")) - if err := b.Bucket([]byte("foo")).Put([]byte("baz"), []byte("yyyy")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - db.MustCheck() - - // Verify. - if err := db.View(func(tx *bolt.Tx) error { - var b = tx.Bucket([]byte("widgets")) - if v := b.Bucket([]byte("foo")).Get([]byte("baz")); !bytes.Equal(v, []byte("yyyy")) { - t.Fatalf("unexpected value: %v", v) - } - if v := b.Get([]byte("bar")); !bytes.Equal(v, []byte("xxxx")) { - t.Fatalf("unexpected value: %v", v) - } - for i := 0; i < 10000; i++ { - if v := b.Get([]byte(strconv.Itoa(i))); !bytes.Equal(v, []byte(strconv.Itoa(i))) { - t.Fatalf("unexpected value: %v", v) - } - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that deleting a bucket using Delete() returns an error. -func TestBucket_Delete_Bucket(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if _, err := b.CreateBucket([]byte("foo")); err != nil { - t.Fatal(err) - } - if err := b.Delete([]byte("foo")); err != bolt.ErrIncompatibleValue { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that deleting a key on a read-only bucket returns an error. -func TestBucket_Delete_ReadOnly(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - if err := tx.Bucket([]byte("widgets")).Delete([]byte("foo")); err != bolt.ErrTxNotWritable { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a deleting value while the transaction is closed returns an error. -func TestBucket_Delete_Closed(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - if err := tx.Rollback(); err != nil { - t.Fatal(err) - } - if err := b.Delete([]byte("foo")); err != bolt.ErrTxClosed { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure that deleting a bucket causes nested buckets to be deleted. -func TestBucket_DeleteBucket_Nested(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - widgets, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - foo, err := widgets.CreateBucket([]byte("foo")) - if err != nil { - t.Fatal(err) - } - - bar, err := foo.CreateBucket([]byte("bar")) - if err != nil { - t.Fatal(err) - } - if err := bar.Put([]byte("baz"), []byte("bat")); err != nil { - t.Fatal(err) - } - if err := tx.Bucket([]byte("widgets")).DeleteBucket([]byte("foo")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that deleting a bucket causes nested buckets to be deleted after they have been committed. -func TestBucket_DeleteBucket_Nested2(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - widgets, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - foo, err := widgets.CreateBucket([]byte("foo")) - if err != nil { - t.Fatal(err) - } - - bar, err := foo.CreateBucket([]byte("bar")) - if err != nil { - t.Fatal(err) - } - - if err := bar.Put([]byte("baz"), []byte("bat")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.Update(func(tx *bolt.Tx) error { - widgets := tx.Bucket([]byte("widgets")) - if widgets == nil { - t.Fatal("expected widgets bucket") - } - - foo := widgets.Bucket([]byte("foo")) - if foo == nil { - t.Fatal("expected foo bucket") - } - - bar := foo.Bucket([]byte("bar")) - if bar == nil { - t.Fatal("expected bar bucket") - } - - if v := bar.Get([]byte("baz")); !bytes.Equal(v, []byte("bat")) { - t.Fatalf("unexpected value: %v", v) - } - if err := tx.DeleteBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - if tx.Bucket([]byte("widgets")) != nil { - t.Fatal("expected bucket to be deleted") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that deleting a child bucket with multiple pages causes all pages to get collected. -// NOTE: Consistency check in bolt_test.DB.Close() will panic if pages not freed properly. -func TestBucket_DeleteBucket_Large(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - widgets, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - foo, err := widgets.CreateBucket([]byte("foo")) - if err != nil { - t.Fatal(err) - } - - for i := 0; i < 1000; i++ { - if err := foo.Put([]byte(fmt.Sprintf("%d", i)), []byte(fmt.Sprintf("%0100d", i))); err != nil { - t.Fatal(err) - } - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.Update(func(tx *bolt.Tx) error { - if err := tx.DeleteBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a simple value retrieved via Bucket() returns a nil. -func TestBucket_Bucket_IncompatibleValue(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - widgets, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - if err := widgets.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - if b := tx.Bucket([]byte("widgets")).Bucket([]byte("foo")); b != nil { - t.Fatal("expected nil bucket") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that creating a bucket on an existing non-bucket key returns an error. -func TestBucket_CreateBucket_IncompatibleValue(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - widgets, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - if err := widgets.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - if _, err := widgets.CreateBucket([]byte("foo")); err != bolt.ErrIncompatibleValue { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that deleting a bucket on an existing non-bucket key returns an error. -func TestBucket_DeleteBucket_IncompatibleValue(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - widgets, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := widgets.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - if err := tx.Bucket([]byte("widgets")).DeleteBucket([]byte("foo")); err != bolt.ErrIncompatibleValue { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure bucket can set and update its sequence number. -func TestBucket_Sequence(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - bkt, err := tx.CreateBucket([]byte("0")) - if err != nil { - t.Fatal(err) - } - - // Retrieve sequence. - if v := bkt.Sequence(); v != 0 { - t.Fatalf("unexpected sequence: %d", v) - } - - // Update sequence. - if err := bkt.SetSequence(1000); err != nil { - t.Fatal(err) - } - - // Read sequence again. - if v := bkt.Sequence(); v != 1000 { - t.Fatalf("unexpected sequence: %d", v) - } - - return nil - }); err != nil { - t.Fatal(err) - } - - // Verify sequence in separate transaction. - if err := db.View(func(tx *bolt.Tx) error { - if v := tx.Bucket([]byte("0")).Sequence(); v != 1000 { - t.Fatalf("unexpected sequence: %d", v) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket can return an autoincrementing sequence. -func TestBucket_NextSequence(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - widgets, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - woojits, err := tx.CreateBucket([]byte("woojits")) - if err != nil { - t.Fatal(err) - } - - // Make sure sequence increments. - if seq, err := widgets.NextSequence(); err != nil { - t.Fatal(err) - } else if seq != 1 { - t.Fatalf("unexpecte sequence: %d", seq) - } - - if seq, err := widgets.NextSequence(); err != nil { - t.Fatal(err) - } else if seq != 2 { - t.Fatalf("unexpected sequence: %d", seq) - } - - // Buckets should be separate. - if seq, err := woojits.NextSequence(); err != nil { - t.Fatal(err) - } else if seq != 1 { - t.Fatalf("unexpected sequence: %d", 1) - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket will persist an autoincrementing sequence even if its -// the only thing updated on the bucket. -// https://github.com/boltdb/bolt/issues/296 -func TestBucket_NextSequence_Persist(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.Bucket([]byte("widgets")).NextSequence(); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.Update(func(tx *bolt.Tx) error { - seq, err := tx.Bucket([]byte("widgets")).NextSequence() - if err != nil { - t.Fatalf("unexpected error: %s", err) - } else if seq != 2 { - t.Fatalf("unexpected sequence: %d", seq) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that retrieving the next sequence on a read-only bucket returns an error. -func TestBucket_NextSequence_ReadOnly(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - _, err := tx.Bucket([]byte("widgets")).NextSequence() - if err != bolt.ErrTxNotWritable { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that retrieving the next sequence for a bucket on a closed database return an error. -func TestBucket_NextSequence_Closed(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := tx.Rollback(); err != nil { - t.Fatal(err) - } - if _, err := b.NextSequence(); err != bolt.ErrTxClosed { - t.Fatal(err) - } -} - -// Ensure a user can loop over all key/value pairs in a bucket. -func TestBucket_ForEach(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("0000")); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("baz"), []byte("0001")); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("bar"), []byte("0002")); err != nil { - t.Fatal(err) - } - - var index int - if err := b.ForEach(func(k, v []byte) error { - switch index { - case 0: - if !bytes.Equal(k, []byte("bar")) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, []byte("0002")) { - t.Fatalf("unexpected value: %v", v) - } - case 1: - if !bytes.Equal(k, []byte("baz")) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, []byte("0001")) { - t.Fatalf("unexpected value: %v", v) - } - case 2: - if !bytes.Equal(k, []byte("foo")) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, []byte("0000")) { - t.Fatalf("unexpected value: %v", v) - } - } - index++ - return nil - }); err != nil { - t.Fatal(err) - } - - if index != 3 { - t.Fatalf("unexpected index: %d", index) - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure a database can stop iteration early. -func TestBucket_ForEach_ShortCircuit(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("bar"), []byte("0000")); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("baz"), []byte("0000")); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("0000")); err != nil { - t.Fatal(err) - } - - var index int - if err := tx.Bucket([]byte("widgets")).ForEach(func(k, v []byte) error { - index++ - if bytes.Equal(k, []byte("baz")) { - return errors.New("marker") - } - return nil - }); err == nil || err.Error() != "marker" { - t.Fatalf("unexpected error: %s", err) - } - if index != 2 { - t.Fatalf("unexpected index: %d", index) - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that looping over a bucket on a closed database returns an error. -func TestBucket_ForEach_Closed(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - if err := tx.Rollback(); err != nil { - t.Fatal(err) - } - - if err := b.ForEach(func(k, v []byte) error { return nil }); err != bolt.ErrTxClosed { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure that an error is returned when inserting with an empty key. -func TestBucket_Put_EmptyKey(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte(""), []byte("bar")); err != bolt.ErrKeyRequired { - t.Fatalf("unexpected error: %s", err) - } - if err := b.Put(nil, []byte("bar")); err != bolt.ErrKeyRequired { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that an error is returned when inserting with a key that's too large. -func TestBucket_Put_KeyTooLarge(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put(make([]byte, 32769), []byte("bar")); err != bolt.ErrKeyTooLarge { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that an error is returned when inserting a value that's too large. -func TestBucket_Put_ValueTooLarge(t *testing.T) { - // Skip this test on DroneCI because the machine is resource constrained. - if os.Getenv("DRONE") == "true" { - t.Skip("not enough RAM for test") - } - - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), make([]byte, bolt.MaxValueSize+1)); err != bolt.ErrValueTooLarge { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure a bucket can calculate stats. -func TestBucket_Stats(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - // Add bucket with fewer keys but one big value. - bigKey := []byte("really-big-value") - for i := 0; i < 500; i++ { - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucketIfNotExists([]byte("woojits")) - if err != nil { - t.Fatal(err) - } - - if err := b.Put([]byte(fmt.Sprintf("%03d", i)), []byte(strconv.Itoa(i))); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - } - if err := db.Update(func(tx *bolt.Tx) error { - if err := tx.Bucket([]byte("woojits")).Put(bigKey, []byte(strings.Repeat("*", 10000))); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - db.MustCheck() - - if err := db.View(func(tx *bolt.Tx) error { - stats := tx.Bucket([]byte("woojits")).Stats() - if stats.BranchPageN != 1 { - t.Fatalf("unexpected BranchPageN: %d", stats.BranchPageN) - } else if stats.BranchOverflowN != 0 { - t.Fatalf("unexpected BranchOverflowN: %d", stats.BranchOverflowN) - } else if stats.LeafPageN != 7 { - t.Fatalf("unexpected LeafPageN: %d", stats.LeafPageN) - } else if stats.LeafOverflowN != 2 { - t.Fatalf("unexpected LeafOverflowN: %d", stats.LeafOverflowN) - } else if stats.KeyN != 501 { - t.Fatalf("unexpected KeyN: %d", stats.KeyN) - } else if stats.Depth != 2 { - t.Fatalf("unexpected Depth: %d", stats.Depth) - } - - branchInuse := 16 // branch page header - branchInuse += 7 * 16 // branch elements - branchInuse += 7 * 3 // branch keys (6 3-byte keys) - if stats.BranchInuse != branchInuse { - t.Fatalf("unexpected BranchInuse: %d", stats.BranchInuse) - } - - leafInuse := 7 * 16 // leaf page header - leafInuse += 501 * 16 // leaf elements - leafInuse += 500*3 + len(bigKey) // leaf keys - leafInuse += 1*10 + 2*90 + 3*400 + 10000 // leaf values - if stats.LeafInuse != leafInuse { - t.Fatalf("unexpected LeafInuse: %d", stats.LeafInuse) - } - - // Only check allocations for 4KB pages. - if os.Getpagesize() == 4096 { - if stats.BranchAlloc != 4096 { - t.Fatalf("unexpected BranchAlloc: %d", stats.BranchAlloc) - } else if stats.LeafAlloc != 36864 { - t.Fatalf("unexpected LeafAlloc: %d", stats.LeafAlloc) - } - } - - if stats.BucketN != 1 { - t.Fatalf("unexpected BucketN: %d", stats.BucketN) - } else if stats.InlineBucketN != 0 { - t.Fatalf("unexpected InlineBucketN: %d", stats.InlineBucketN) - } else if stats.InlineBucketInuse != 0 { - t.Fatalf("unexpected InlineBucketInuse: %d", stats.InlineBucketInuse) - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure a bucket with random insertion utilizes fill percentage correctly. -func TestBucket_Stats_RandomFill(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } else if os.Getpagesize() != 4096 { - t.Skip("invalid page size for test") - } - - db := MustOpenDB() - defer db.MustClose() - - // Add a set of values in random order. It will be the same random - // order so we can maintain consistency between test runs. - var count int - rand := rand.New(rand.NewSource(42)) - for _, i := range rand.Perm(1000) { - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucketIfNotExists([]byte("woojits")) - if err != nil { - t.Fatal(err) - } - b.FillPercent = 0.9 - for _, j := range rand.Perm(100) { - index := (j * 10000) + i - if err := b.Put([]byte(fmt.Sprintf("%d000000000000000", index)), []byte("0000000000")); err != nil { - t.Fatal(err) - } - count++ - } - return nil - }); err != nil { - t.Fatal(err) - } - } - - db.MustCheck() - - if err := db.View(func(tx *bolt.Tx) error { - stats := tx.Bucket([]byte("woojits")).Stats() - if stats.KeyN != 100000 { - t.Fatalf("unexpected KeyN: %d", stats.KeyN) - } - - if stats.BranchPageN != 98 { - t.Fatalf("unexpected BranchPageN: %d", stats.BranchPageN) - } else if stats.BranchOverflowN != 0 { - t.Fatalf("unexpected BranchOverflowN: %d", stats.BranchOverflowN) - } else if stats.BranchInuse != 130984 { - t.Fatalf("unexpected BranchInuse: %d", stats.BranchInuse) - } else if stats.BranchAlloc != 401408 { - t.Fatalf("unexpected BranchAlloc: %d", stats.BranchAlloc) - } - - if stats.LeafPageN != 3412 { - t.Fatalf("unexpected LeafPageN: %d", stats.LeafPageN) - } else if stats.LeafOverflowN != 0 { - t.Fatalf("unexpected LeafOverflowN: %d", stats.LeafOverflowN) - } else if stats.LeafInuse != 4742482 { - t.Fatalf("unexpected LeafInuse: %d", stats.LeafInuse) - } else if stats.LeafAlloc != 13975552 { - t.Fatalf("unexpected LeafAlloc: %d", stats.LeafAlloc) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure a bucket can calculate stats. -func TestBucket_Stats_Small(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - // Add a bucket that fits on a single root leaf. - b, err := tx.CreateBucket([]byte("whozawhats")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - - return nil - }); err != nil { - t.Fatal(err) - } - - db.MustCheck() - - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("whozawhats")) - stats := b.Stats() - if stats.BranchPageN != 0 { - t.Fatalf("unexpected BranchPageN: %d", stats.BranchPageN) - } else if stats.BranchOverflowN != 0 { - t.Fatalf("unexpected BranchOverflowN: %d", stats.BranchOverflowN) - } else if stats.LeafPageN != 0 { - t.Fatalf("unexpected LeafPageN: %d", stats.LeafPageN) - } else if stats.LeafOverflowN != 0 { - t.Fatalf("unexpected LeafOverflowN: %d", stats.LeafOverflowN) - } else if stats.KeyN != 1 { - t.Fatalf("unexpected KeyN: %d", stats.KeyN) - } else if stats.Depth != 1 { - t.Fatalf("unexpected Depth: %d", stats.Depth) - } else if stats.BranchInuse != 0 { - t.Fatalf("unexpected BranchInuse: %d", stats.BranchInuse) - } else if stats.LeafInuse != 0 { - t.Fatalf("unexpected LeafInuse: %d", stats.LeafInuse) - } - - if os.Getpagesize() == 4096 { - if stats.BranchAlloc != 0 { - t.Fatalf("unexpected BranchAlloc: %d", stats.BranchAlloc) - } else if stats.LeafAlloc != 0 { - t.Fatalf("unexpected LeafAlloc: %d", stats.LeafAlloc) - } - } - - if stats.BucketN != 1 { - t.Fatalf("unexpected BucketN: %d", stats.BucketN) - } else if stats.InlineBucketN != 1 { - t.Fatalf("unexpected InlineBucketN: %d", stats.InlineBucketN) - } else if stats.InlineBucketInuse != 16+16+6 { - t.Fatalf("unexpected InlineBucketInuse: %d", stats.InlineBucketInuse) - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -func TestBucket_Stats_EmptyBucket(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - // Add a bucket that fits on a single root leaf. - if _, err := tx.CreateBucket([]byte("whozawhats")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - db.MustCheck() - - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("whozawhats")) - stats := b.Stats() - if stats.BranchPageN != 0 { - t.Fatalf("unexpected BranchPageN: %d", stats.BranchPageN) - } else if stats.BranchOverflowN != 0 { - t.Fatalf("unexpected BranchOverflowN: %d", stats.BranchOverflowN) - } else if stats.LeafPageN != 0 { - t.Fatalf("unexpected LeafPageN: %d", stats.LeafPageN) - } else if stats.LeafOverflowN != 0 { - t.Fatalf("unexpected LeafOverflowN: %d", stats.LeafOverflowN) - } else if stats.KeyN != 0 { - t.Fatalf("unexpected KeyN: %d", stats.KeyN) - } else if stats.Depth != 1 { - t.Fatalf("unexpected Depth: %d", stats.Depth) - } else if stats.BranchInuse != 0 { - t.Fatalf("unexpected BranchInuse: %d", stats.BranchInuse) - } else if stats.LeafInuse != 0 { - t.Fatalf("unexpected LeafInuse: %d", stats.LeafInuse) - } - - if os.Getpagesize() == 4096 { - if stats.BranchAlloc != 0 { - t.Fatalf("unexpected BranchAlloc: %d", stats.BranchAlloc) - } else if stats.LeafAlloc != 0 { - t.Fatalf("unexpected LeafAlloc: %d", stats.LeafAlloc) - } - } - - if stats.BucketN != 1 { - t.Fatalf("unexpected BucketN: %d", stats.BucketN) - } else if stats.InlineBucketN != 1 { - t.Fatalf("unexpected InlineBucketN: %d", stats.InlineBucketN) - } else if stats.InlineBucketInuse != 16 { - t.Fatalf("unexpected InlineBucketInuse: %d", stats.InlineBucketInuse) - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure a bucket can calculate stats. -func TestBucket_Stats_Nested(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("foo")) - if err != nil { - t.Fatal(err) - } - for i := 0; i < 100; i++ { - if err := b.Put([]byte(fmt.Sprintf("%02d", i)), []byte(fmt.Sprintf("%02d", i))); err != nil { - t.Fatal(err) - } - } - - bar, err := b.CreateBucket([]byte("bar")) - if err != nil { - t.Fatal(err) - } - for i := 0; i < 10; i++ { - if err := bar.Put([]byte(strconv.Itoa(i)), []byte(strconv.Itoa(i))); err != nil { - t.Fatal(err) - } - } - - baz, err := bar.CreateBucket([]byte("baz")) - if err != nil { - t.Fatal(err) - } - for i := 0; i < 10; i++ { - if err := baz.Put([]byte(strconv.Itoa(i)), []byte(strconv.Itoa(i))); err != nil { - t.Fatal(err) - } - } - - return nil - }); err != nil { - t.Fatal(err) - } - - db.MustCheck() - - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("foo")) - stats := b.Stats() - if stats.BranchPageN != 0 { - t.Fatalf("unexpected BranchPageN: %d", stats.BranchPageN) - } else if stats.BranchOverflowN != 0 { - t.Fatalf("unexpected BranchOverflowN: %d", stats.BranchOverflowN) - } else if stats.LeafPageN != 2 { - t.Fatalf("unexpected LeafPageN: %d", stats.LeafPageN) - } else if stats.LeafOverflowN != 0 { - t.Fatalf("unexpected LeafOverflowN: %d", stats.LeafOverflowN) - } else if stats.KeyN != 122 { - t.Fatalf("unexpected KeyN: %d", stats.KeyN) - } else if stats.Depth != 3 { - t.Fatalf("unexpected Depth: %d", stats.Depth) - } else if stats.BranchInuse != 0 { - t.Fatalf("unexpected BranchInuse: %d", stats.BranchInuse) - } - - foo := 16 // foo (pghdr) - foo += 101 * 16 // foo leaf elements - foo += 100*2 + 100*2 // foo leaf key/values - foo += 3 + 16 // foo -> bar key/value - - bar := 16 // bar (pghdr) - bar += 11 * 16 // bar leaf elements - bar += 10 + 10 // bar leaf key/values - bar += 3 + 16 // bar -> baz key/value - - baz := 16 // baz (inline) (pghdr) - baz += 10 * 16 // baz leaf elements - baz += 10 + 10 // baz leaf key/values - - if stats.LeafInuse != foo+bar+baz { - t.Fatalf("unexpected LeafInuse: %d", stats.LeafInuse) - } - - if os.Getpagesize() == 4096 { - if stats.BranchAlloc != 0 { - t.Fatalf("unexpected BranchAlloc: %d", stats.BranchAlloc) - } else if stats.LeafAlloc != 8192 { - t.Fatalf("unexpected LeafAlloc: %d", stats.LeafAlloc) - } - } - - if stats.BucketN != 3 { - t.Fatalf("unexpected BucketN: %d", stats.BucketN) - } else if stats.InlineBucketN != 1 { - t.Fatalf("unexpected InlineBucketN: %d", stats.InlineBucketN) - } else if stats.InlineBucketInuse != baz { - t.Fatalf("unexpected InlineBucketInuse: %d", stats.InlineBucketInuse) - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure a large bucket can calculate stats. -func TestBucket_Stats_Large(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - - db := MustOpenDB() - defer db.MustClose() - - var index int - for i := 0; i < 100; i++ { - // Add bucket with lots of keys. - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucketIfNotExists([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - for i := 0; i < 1000; i++ { - if err := b.Put([]byte(strconv.Itoa(index)), []byte(strconv.Itoa(index))); err != nil { - t.Fatal(err) - } - index++ - } - return nil - }); err != nil { - t.Fatal(err) - } - } - - db.MustCheck() - - if err := db.View(func(tx *bolt.Tx) error { - stats := tx.Bucket([]byte("widgets")).Stats() - if stats.BranchPageN != 13 { - t.Fatalf("unexpected BranchPageN: %d", stats.BranchPageN) - } else if stats.BranchOverflowN != 0 { - t.Fatalf("unexpected BranchOverflowN: %d", stats.BranchOverflowN) - } else if stats.LeafPageN != 1196 { - t.Fatalf("unexpected LeafPageN: %d", stats.LeafPageN) - } else if stats.LeafOverflowN != 0 { - t.Fatalf("unexpected LeafOverflowN: %d", stats.LeafOverflowN) - } else if stats.KeyN != 100000 { - t.Fatalf("unexpected KeyN: %d", stats.KeyN) - } else if stats.Depth != 3 { - t.Fatalf("unexpected Depth: %d", stats.Depth) - } else if stats.BranchInuse != 25257 { - t.Fatalf("unexpected BranchInuse: %d", stats.BranchInuse) - } else if stats.LeafInuse != 2596916 { - t.Fatalf("unexpected LeafInuse: %d", stats.LeafInuse) - } - - if os.Getpagesize() == 4096 { - if stats.BranchAlloc != 53248 { - t.Fatalf("unexpected BranchAlloc: %d", stats.BranchAlloc) - } else if stats.LeafAlloc != 4898816 { - t.Fatalf("unexpected LeafAlloc: %d", stats.LeafAlloc) - } - } - - if stats.BucketN != 1 { - t.Fatalf("unexpected BucketN: %d", stats.BucketN) - } else if stats.InlineBucketN != 0 { - t.Fatalf("unexpected InlineBucketN: %d", stats.InlineBucketN) - } else if stats.InlineBucketInuse != 0 { - t.Fatalf("unexpected InlineBucketInuse: %d", stats.InlineBucketInuse) - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket can write random keys and values across multiple transactions. -func TestBucket_Put_Single(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - - index := 0 - if err := quick.Check(func(items testdata) bool { - db := MustOpenDB() - defer db.MustClose() - - m := make(map[string][]byte) - - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - for _, item := range items { - if err := db.Update(func(tx *bolt.Tx) error { - if err := tx.Bucket([]byte("widgets")).Put(item.Key, item.Value); err != nil { - panic("put error: " + err.Error()) - } - m[string(item.Key)] = item.Value - return nil - }); err != nil { - t.Fatal(err) - } - - // Verify all key/values so far. - if err := db.View(func(tx *bolt.Tx) error { - i := 0 - for k, v := range m { - value := tx.Bucket([]byte("widgets")).Get([]byte(k)) - if !bytes.Equal(value, v) { - t.Logf("value mismatch [run %d] (%d of %d):\nkey: %x\ngot: %x\nexp: %x", index, i, len(m), []byte(k), value, v) - db.CopyTempFile() - t.FailNow() - } - i++ - } - return nil - }); err != nil { - t.Fatal(err) - } - } - - index++ - return true - }, nil); err != nil { - t.Error(err) - } -} - -// Ensure that a transaction can insert multiple key/value pairs at once. -func TestBucket_Put_Multiple(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - - if err := quick.Check(func(items testdata) bool { - db := MustOpenDB() - defer db.MustClose() - - // Bulk insert all values. - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.Update(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - for _, item := range items { - if err := b.Put(item.Key, item.Value); err != nil { - t.Fatal(err) - } - } - return nil - }); err != nil { - t.Fatal(err) - } - - // Verify all items exist. - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - for _, item := range items { - value := b.Get(item.Key) - if !bytes.Equal(item.Value, value) { - db.CopyTempFile() - t.Fatalf("exp=%x; got=%x", item.Value, value) - } - } - return nil - }); err != nil { - t.Fatal(err) - } - - return true - }, qconfig()); err != nil { - t.Error(err) - } -} - -// Ensure that a transaction can delete all key/value pairs and return to a single leaf page. -func TestBucket_Delete_Quick(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - - if err := quick.Check(func(items testdata) bool { - db := MustOpenDB() - defer db.MustClose() - - // Bulk insert all values. - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.Update(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - for _, item := range items { - if err := b.Put(item.Key, item.Value); err != nil { - t.Fatal(err) - } - } - return nil - }); err != nil { - t.Fatal(err) - } - - // Remove items one at a time and check consistency. - for _, item := range items { - if err := db.Update(func(tx *bolt.Tx) error { - return tx.Bucket([]byte("widgets")).Delete(item.Key) - }); err != nil { - t.Fatal(err) - } - } - - // Anything before our deletion index should be nil. - if err := db.View(func(tx *bolt.Tx) error { - if err := tx.Bucket([]byte("widgets")).ForEach(func(k, v []byte) error { - t.Fatalf("bucket should be empty; found: %06x", trunc(k, 3)) - return nil - }); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - return true - }, qconfig()); err != nil { - t.Error(err) - } -} - -func ExampleBucket_Put() { - // Open the database. - db, err := bolt.Open(tempfile(), 0666, nil) - if err != nil { - log.Fatal(err) - } - defer os.Remove(db.Path()) - - // Start a write transaction. - if err := db.Update(func(tx *bolt.Tx) error { - // Create a bucket. - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - return err - } - - // Set the value "bar" for the key "foo". - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - return err - } - return nil - }); err != nil { - log.Fatal(err) - } - - // Read value back in a different read-only transaction. - if err := db.View(func(tx *bolt.Tx) error { - value := tx.Bucket([]byte("widgets")).Get([]byte("foo")) - fmt.Printf("The value of 'foo' is: %s\n", value) - return nil - }); err != nil { - log.Fatal(err) - } - - // Close database to release file lock. - if err := db.Close(); err != nil { - log.Fatal(err) - } - - // Output: - // The value of 'foo' is: bar -} - -func ExampleBucket_Delete() { - // Open the database. - db, err := bolt.Open(tempfile(), 0666, nil) - if err != nil { - log.Fatal(err) - } - defer os.Remove(db.Path()) - - // Start a write transaction. - if err := db.Update(func(tx *bolt.Tx) error { - // Create a bucket. - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - return err - } - - // Set the value "bar" for the key "foo". - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - return err - } - - // Retrieve the key back from the database and verify it. - value := b.Get([]byte("foo")) - fmt.Printf("The value of 'foo' was: %s\n", value) - - return nil - }); err != nil { - log.Fatal(err) - } - - // Delete the key in a different write transaction. - if err := db.Update(func(tx *bolt.Tx) error { - return tx.Bucket([]byte("widgets")).Delete([]byte("foo")) - }); err != nil { - log.Fatal(err) - } - - // Retrieve the key again. - if err := db.View(func(tx *bolt.Tx) error { - value := tx.Bucket([]byte("widgets")).Get([]byte("foo")) - if value == nil { - fmt.Printf("The value of 'foo' is now: nil\n") - } - return nil - }); err != nil { - log.Fatal(err) - } - - // Close database to release file lock. - if err := db.Close(); err != nil { - log.Fatal(err) - } - - // Output: - // The value of 'foo' was: bar - // The value of 'foo' is now: nil -} - -func ExampleBucket_ForEach() { - // Open the database. - db, err := bolt.Open(tempfile(), 0666, nil) - if err != nil { - log.Fatal(err) - } - defer os.Remove(db.Path()) - - // Insert data into a bucket. - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("animals")) - if err != nil { - return err - } - - if err := b.Put([]byte("dog"), []byte("fun")); err != nil { - return err - } - if err := b.Put([]byte("cat"), []byte("lame")); err != nil { - return err - } - if err := b.Put([]byte("liger"), []byte("awesome")); err != nil { - return err - } - - // Iterate over items in sorted key order. - if err := b.ForEach(func(k, v []byte) error { - fmt.Printf("A %s is %s.\n", k, v) - return nil - }); err != nil { - return err - } - - return nil - }); err != nil { - log.Fatal(err) - } - - // Close database to release file lock. - if err := db.Close(); err != nil { - log.Fatal(err) - } - - // Output: - // A cat is lame. - // A dog is fun. - // A liger is awesome. -} diff --git a/vendor/github.com/boltdb/bolt/cursor_test.go b/vendor/github.com/boltdb/bolt/cursor_test.go deleted file mode 100644 index 562d60f9..00000000 --- a/vendor/github.com/boltdb/bolt/cursor_test.go +++ /dev/null @@ -1,817 +0,0 @@ -package bolt_test - -import ( - "bytes" - "encoding/binary" - "fmt" - "log" - "os" - "reflect" - "sort" - "testing" - "testing/quick" - - "github.com/boltdb/bolt" -) - -// Ensure that a cursor can return a reference to the bucket that created it. -func TestCursor_Bucket(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if cb := b.Cursor().Bucket(); !reflect.DeepEqual(cb, b) { - t.Fatal("cursor bucket mismatch") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a Tx cursor can seek to the appropriate keys. -func TestCursor_Seek(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("0001")); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("bar"), []byte("0002")); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("baz"), []byte("0003")); err != nil { - t.Fatal(err) - } - - if _, err := b.CreateBucket([]byte("bkt")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - c := tx.Bucket([]byte("widgets")).Cursor() - - // Exact match should go to the key. - if k, v := c.Seek([]byte("bar")); !bytes.Equal(k, []byte("bar")) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, []byte("0002")) { - t.Fatalf("unexpected value: %v", v) - } - - // Inexact match should go to the next key. - if k, v := c.Seek([]byte("bas")); !bytes.Equal(k, []byte("baz")) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, []byte("0003")) { - t.Fatalf("unexpected value: %v", v) - } - - // Low key should go to the first key. - if k, v := c.Seek([]byte("")); !bytes.Equal(k, []byte("bar")) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, []byte("0002")) { - t.Fatalf("unexpected value: %v", v) - } - - // High key should return no key. - if k, v := c.Seek([]byte("zzz")); k != nil { - t.Fatalf("expected nil key: %v", k) - } else if v != nil { - t.Fatalf("expected nil value: %v", v) - } - - // Buckets should return their key but no value. - if k, v := c.Seek([]byte("bkt")); !bytes.Equal(k, []byte("bkt")) { - t.Fatalf("unexpected key: %v", k) - } else if v != nil { - t.Fatalf("expected nil value: %v", v) - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -func TestCursor_Delete(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - const count = 1000 - - // Insert every other key between 0 and $count. - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - for i := 0; i < count; i += 1 { - k := make([]byte, 8) - binary.BigEndian.PutUint64(k, uint64(i)) - if err := b.Put(k, make([]byte, 100)); err != nil { - t.Fatal(err) - } - } - if _, err := b.CreateBucket([]byte("sub")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.Update(func(tx *bolt.Tx) error { - c := tx.Bucket([]byte("widgets")).Cursor() - bound := make([]byte, 8) - binary.BigEndian.PutUint64(bound, uint64(count/2)) - for key, _ := c.First(); bytes.Compare(key, bound) < 0; key, _ = c.Next() { - if err := c.Delete(); err != nil { - t.Fatal(err) - } - } - - c.Seek([]byte("sub")) - if err := c.Delete(); err != bolt.ErrIncompatibleValue { - t.Fatalf("unexpected error: %s", err) - } - - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - stats := tx.Bucket([]byte("widgets")).Stats() - if stats.KeyN != count/2+1 { - t.Fatalf("unexpected KeyN: %d", stats.KeyN) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a Tx cursor can seek to the appropriate keys when there are a -// large number of keys. This test also checks that seek will always move -// forward to the next key. -// -// Related: https://github.com/boltdb/bolt/pull/187 -func TestCursor_Seek_Large(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - var count = 10000 - - // Insert every other key between 0 and $count. - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - for i := 0; i < count; i += 100 { - for j := i; j < i+100; j += 2 { - k := make([]byte, 8) - binary.BigEndian.PutUint64(k, uint64(j)) - if err := b.Put(k, make([]byte, 100)); err != nil { - t.Fatal(err) - } - } - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - c := tx.Bucket([]byte("widgets")).Cursor() - for i := 0; i < count; i++ { - seek := make([]byte, 8) - binary.BigEndian.PutUint64(seek, uint64(i)) - - k, _ := c.Seek(seek) - - // The last seek is beyond the end of the the range so - // it should return nil. - if i == count-1 { - if k != nil { - t.Fatal("expected nil key") - } - continue - } - - // Otherwise we should seek to the exact key or the next key. - num := binary.BigEndian.Uint64(k) - if i%2 == 0 { - if num != uint64(i) { - t.Fatalf("unexpected num: %d", num) - } - } else { - if num != uint64(i+1) { - t.Fatalf("unexpected num: %d", num) - } - } - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a cursor can iterate over an empty bucket without error. -func TestCursor_EmptyBucket(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("widgets")) - return err - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - c := tx.Bucket([]byte("widgets")).Cursor() - k, v := c.First() - if k != nil { - t.Fatalf("unexpected key: %v", k) - } else if v != nil { - t.Fatalf("unexpected value: %v", v) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a Tx cursor can reverse iterate over an empty bucket without error. -func TestCursor_EmptyBucketReverse(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("widgets")) - return err - }); err != nil { - t.Fatal(err) - } - if err := db.View(func(tx *bolt.Tx) error { - c := tx.Bucket([]byte("widgets")).Cursor() - k, v := c.Last() - if k != nil { - t.Fatalf("unexpected key: %v", k) - } else if v != nil { - t.Fatalf("unexpected value: %v", v) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a Tx cursor can iterate over a single root with a couple elements. -func TestCursor_Iterate_Leaf(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("baz"), []byte{}); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte{0}); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("bar"), []byte{1}); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - tx, err := db.Begin(false) - if err != nil { - t.Fatal(err) - } - defer func() { _ = tx.Rollback() }() - - c := tx.Bucket([]byte("widgets")).Cursor() - - k, v := c.First() - if !bytes.Equal(k, []byte("bar")) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, []byte{1}) { - t.Fatalf("unexpected value: %v", v) - } - - k, v = c.Next() - if !bytes.Equal(k, []byte("baz")) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, []byte{}) { - t.Fatalf("unexpected value: %v", v) - } - - k, v = c.Next() - if !bytes.Equal(k, []byte("foo")) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, []byte{0}) { - t.Fatalf("unexpected value: %v", v) - } - - k, v = c.Next() - if k != nil { - t.Fatalf("expected nil key: %v", k) - } else if v != nil { - t.Fatalf("expected nil value: %v", v) - } - - k, v = c.Next() - if k != nil { - t.Fatalf("expected nil key: %v", k) - } else if v != nil { - t.Fatalf("expected nil value: %v", v) - } - - if err := tx.Rollback(); err != nil { - t.Fatal(err) - } -} - -// Ensure that a Tx cursor can iterate in reverse over a single root with a couple elements. -func TestCursor_LeafRootReverse(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("baz"), []byte{}); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte{0}); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("bar"), []byte{1}); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - tx, err := db.Begin(false) - if err != nil { - t.Fatal(err) - } - c := tx.Bucket([]byte("widgets")).Cursor() - - if k, v := c.Last(); !bytes.Equal(k, []byte("foo")) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, []byte{0}) { - t.Fatalf("unexpected value: %v", v) - } - - if k, v := c.Prev(); !bytes.Equal(k, []byte("baz")) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, []byte{}) { - t.Fatalf("unexpected value: %v", v) - } - - if k, v := c.Prev(); !bytes.Equal(k, []byte("bar")) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, []byte{1}) { - t.Fatalf("unexpected value: %v", v) - } - - if k, v := c.Prev(); k != nil { - t.Fatalf("expected nil key: %v", k) - } else if v != nil { - t.Fatalf("expected nil value: %v", v) - } - - if k, v := c.Prev(); k != nil { - t.Fatalf("expected nil key: %v", k) - } else if v != nil { - t.Fatalf("expected nil value: %v", v) - } - - if err := tx.Rollback(); err != nil { - t.Fatal(err) - } -} - -// Ensure that a Tx cursor can restart from the beginning. -func TestCursor_Restart(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("bar"), []byte{}); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte{}); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - tx, err := db.Begin(false) - if err != nil { - t.Fatal(err) - } - c := tx.Bucket([]byte("widgets")).Cursor() - - if k, _ := c.First(); !bytes.Equal(k, []byte("bar")) { - t.Fatalf("unexpected key: %v", k) - } - if k, _ := c.Next(); !bytes.Equal(k, []byte("foo")) { - t.Fatalf("unexpected key: %v", k) - } - - if k, _ := c.First(); !bytes.Equal(k, []byte("bar")) { - t.Fatalf("unexpected key: %v", k) - } - if k, _ := c.Next(); !bytes.Equal(k, []byte("foo")) { - t.Fatalf("unexpected key: %v", k) - } - - if err := tx.Rollback(); err != nil { - t.Fatal(err) - } -} - -// Ensure that a cursor can skip over empty pages that have been deleted. -func TestCursor_First_EmptyPages(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - // Create 1000 keys in the "widgets" bucket. - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - for i := 0; i < 1000; i++ { - if err := b.Put(u64tob(uint64(i)), []byte{}); err != nil { - t.Fatal(err) - } - } - - return nil - }); err != nil { - t.Fatal(err) - } - - // Delete half the keys and then try to iterate. - if err := db.Update(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - for i := 0; i < 600; i++ { - if err := b.Delete(u64tob(uint64(i))); err != nil { - t.Fatal(err) - } - } - - c := b.Cursor() - var n int - for k, _ := c.First(); k != nil; k, _ = c.Next() { - n++ - } - if n != 400 { - t.Fatalf("unexpected key count: %d", n) - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a Tx can iterate over all elements in a bucket. -func TestCursor_QuickCheck(t *testing.T) { - f := func(items testdata) bool { - db := MustOpenDB() - defer db.MustClose() - - // Bulk insert all values. - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - for _, item := range items { - if err := b.Put(item.Key, item.Value); err != nil { - t.Fatal(err) - } - } - if err := tx.Commit(); err != nil { - t.Fatal(err) - } - - // Sort test data. - sort.Sort(items) - - // Iterate over all items and check consistency. - var index = 0 - tx, err = db.Begin(false) - if err != nil { - t.Fatal(err) - } - - c := tx.Bucket([]byte("widgets")).Cursor() - for k, v := c.First(); k != nil && index < len(items); k, v = c.Next() { - if !bytes.Equal(k, items[index].Key) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, items[index].Value) { - t.Fatalf("unexpected value: %v", v) - } - index++ - } - if len(items) != index { - t.Fatalf("unexpected item count: %v, expected %v", len(items), index) - } - - if err := tx.Rollback(); err != nil { - t.Fatal(err) - } - - return true - } - if err := quick.Check(f, qconfig()); err != nil { - t.Error(err) - } -} - -// Ensure that a transaction can iterate over all elements in a bucket in reverse. -func TestCursor_QuickCheck_Reverse(t *testing.T) { - f := func(items testdata) bool { - db := MustOpenDB() - defer db.MustClose() - - // Bulk insert all values. - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - for _, item := range items { - if err := b.Put(item.Key, item.Value); err != nil { - t.Fatal(err) - } - } - if err := tx.Commit(); err != nil { - t.Fatal(err) - } - - // Sort test data. - sort.Sort(revtestdata(items)) - - // Iterate over all items and check consistency. - var index = 0 - tx, err = db.Begin(false) - if err != nil { - t.Fatal(err) - } - c := tx.Bucket([]byte("widgets")).Cursor() - for k, v := c.Last(); k != nil && index < len(items); k, v = c.Prev() { - if !bytes.Equal(k, items[index].Key) { - t.Fatalf("unexpected key: %v", k) - } else if !bytes.Equal(v, items[index].Value) { - t.Fatalf("unexpected value: %v", v) - } - index++ - } - if len(items) != index { - t.Fatalf("unexpected item count: %v, expected %v", len(items), index) - } - - if err := tx.Rollback(); err != nil { - t.Fatal(err) - } - - return true - } - if err := quick.Check(f, qconfig()); err != nil { - t.Error(err) - } -} - -// Ensure that a Tx cursor can iterate over subbuckets. -func TestCursor_QuickCheck_BucketsOnly(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if _, err := b.CreateBucket([]byte("foo")); err != nil { - t.Fatal(err) - } - if _, err := b.CreateBucket([]byte("bar")); err != nil { - t.Fatal(err) - } - if _, err := b.CreateBucket([]byte("baz")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - var names []string - c := tx.Bucket([]byte("widgets")).Cursor() - for k, v := c.First(); k != nil; k, v = c.Next() { - names = append(names, string(k)) - if v != nil { - t.Fatalf("unexpected value: %v", v) - } - } - if !reflect.DeepEqual(names, []string{"bar", "baz", "foo"}) { - t.Fatalf("unexpected names: %+v", names) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a Tx cursor can reverse iterate over subbuckets. -func TestCursor_QuickCheck_BucketsOnly_Reverse(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if _, err := b.CreateBucket([]byte("foo")); err != nil { - t.Fatal(err) - } - if _, err := b.CreateBucket([]byte("bar")); err != nil { - t.Fatal(err) - } - if _, err := b.CreateBucket([]byte("baz")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - var names []string - c := tx.Bucket([]byte("widgets")).Cursor() - for k, v := c.Last(); k != nil; k, v = c.Prev() { - names = append(names, string(k)) - if v != nil { - t.Fatalf("unexpected value: %v", v) - } - } - if !reflect.DeepEqual(names, []string{"foo", "baz", "bar"}) { - t.Fatalf("unexpected names: %+v", names) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -func ExampleCursor() { - // Open the database. - db, err := bolt.Open(tempfile(), 0666, nil) - if err != nil { - log.Fatal(err) - } - defer os.Remove(db.Path()) - - // Start a read-write transaction. - if err := db.Update(func(tx *bolt.Tx) error { - // Create a new bucket. - b, err := tx.CreateBucket([]byte("animals")) - if err != nil { - return err - } - - // Insert data into a bucket. - if err := b.Put([]byte("dog"), []byte("fun")); err != nil { - log.Fatal(err) - } - if err := b.Put([]byte("cat"), []byte("lame")); err != nil { - log.Fatal(err) - } - if err := b.Put([]byte("liger"), []byte("awesome")); err != nil { - log.Fatal(err) - } - - // Create a cursor for iteration. - c := b.Cursor() - - // Iterate over items in sorted key order. This starts from the - // first key/value pair and updates the k/v variables to the - // next key/value on each iteration. - // - // The loop finishes at the end of the cursor when a nil key is returned. - for k, v := c.First(); k != nil; k, v = c.Next() { - fmt.Printf("A %s is %s.\n", k, v) - } - - return nil - }); err != nil { - log.Fatal(err) - } - - if err := db.Close(); err != nil { - log.Fatal(err) - } - - // Output: - // A cat is lame. - // A dog is fun. - // A liger is awesome. -} - -func ExampleCursor_reverse() { - // Open the database. - db, err := bolt.Open(tempfile(), 0666, nil) - if err != nil { - log.Fatal(err) - } - defer os.Remove(db.Path()) - - // Start a read-write transaction. - if err := db.Update(func(tx *bolt.Tx) error { - // Create a new bucket. - b, err := tx.CreateBucket([]byte("animals")) - if err != nil { - return err - } - - // Insert data into a bucket. - if err := b.Put([]byte("dog"), []byte("fun")); err != nil { - log.Fatal(err) - } - if err := b.Put([]byte("cat"), []byte("lame")); err != nil { - log.Fatal(err) - } - if err := b.Put([]byte("liger"), []byte("awesome")); err != nil { - log.Fatal(err) - } - - // Create a cursor for iteration. - c := b.Cursor() - - // Iterate over items in reverse sorted key order. This starts - // from the last key/value pair and updates the k/v variables to - // the previous key/value on each iteration. - // - // The loop finishes at the beginning of the cursor when a nil key - // is returned. - for k, v := c.Last(); k != nil; k, v = c.Prev() { - fmt.Printf("A %s is %s.\n", k, v) - } - - return nil - }); err != nil { - log.Fatal(err) - } - - // Close the database to release the file lock. - if err := db.Close(); err != nil { - log.Fatal(err) - } - - // Output: - // A liger is awesome. - // A dog is fun. - // A cat is lame. -} diff --git a/vendor/github.com/boltdb/bolt/db_test.go b/vendor/github.com/boltdb/bolt/db_test.go deleted file mode 100644 index 3034d4f4..00000000 --- a/vendor/github.com/boltdb/bolt/db_test.go +++ /dev/null @@ -1,1545 +0,0 @@ -package bolt_test - -import ( - "bytes" - "encoding/binary" - "errors" - "flag" - "fmt" - "hash/fnv" - "io/ioutil" - "log" - "os" - "path/filepath" - "regexp" - "sort" - "strings" - "sync" - "testing" - "time" - "unsafe" - - "github.com/boltdb/bolt" -) - -var statsFlag = flag.Bool("stats", false, "show performance stats") - -// version is the data file format version. -const version = 2 - -// magic is the marker value to indicate that a file is a Bolt DB. -const magic uint32 = 0xED0CDAED - -// pageSize is the size of one page in the data file. -const pageSize = 4096 - -// pageHeaderSize is the size of a page header. -const pageHeaderSize = 16 - -// meta represents a simplified version of a database meta page for testing. -type meta struct { - magic uint32 - version uint32 - _ uint32 - _ uint32 - _ [16]byte - _ uint64 - pgid uint64 - _ uint64 - checksum uint64 -} - -// Ensure that a database can be opened without error. -func TestOpen(t *testing.T) { - path := tempfile() - db, err := bolt.Open(path, 0666, nil) - if err != nil { - t.Fatal(err) - } else if db == nil { - t.Fatal("expected db") - } - - if s := db.Path(); s != path { - t.Fatalf("unexpected path: %s", s) - } - - if err := db.Close(); err != nil { - t.Fatal(err) - } -} - -// Ensure that opening a database with a blank path returns an error. -func TestOpen_ErrPathRequired(t *testing.T) { - _, err := bolt.Open("", 0666, nil) - if err == nil { - t.Fatalf("expected error") - } -} - -// Ensure that opening a database with a bad path returns an error. -func TestOpen_ErrNotExists(t *testing.T) { - _, err := bolt.Open(filepath.Join(tempfile(), "bad-path"), 0666, nil) - if err == nil { - t.Fatal("expected error") - } -} - -// Ensure that opening a file that is not a Bolt database returns ErrInvalid. -func TestOpen_ErrInvalid(t *testing.T) { - path := tempfile() - - f, err := os.Create(path) - if err != nil { - t.Fatal(err) - } - if _, err := fmt.Fprintln(f, "this is not a bolt database"); err != nil { - t.Fatal(err) - } - if err := f.Close(); err != nil { - t.Fatal(err) - } - defer os.Remove(path) - - if _, err := bolt.Open(path, 0666, nil); err != bolt.ErrInvalid { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure that opening a file with two invalid versions returns ErrVersionMismatch. -func TestOpen_ErrVersionMismatch(t *testing.T) { - if pageSize != os.Getpagesize() { - t.Skip("page size mismatch") - } - - // Create empty database. - db := MustOpenDB() - path := db.Path() - defer db.MustClose() - - // Close database. - if err := db.DB.Close(); err != nil { - t.Fatal(err) - } - - // Read data file. - buf, err := ioutil.ReadFile(path) - if err != nil { - t.Fatal(err) - } - - // Rewrite meta pages. - meta0 := (*meta)(unsafe.Pointer(&buf[pageHeaderSize])) - meta0.version++ - meta1 := (*meta)(unsafe.Pointer(&buf[pageSize+pageHeaderSize])) - meta1.version++ - if err := ioutil.WriteFile(path, buf, 0666); err != nil { - t.Fatal(err) - } - - // Reopen data file. - if _, err := bolt.Open(path, 0666, nil); err != bolt.ErrVersionMismatch { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure that opening a file with two invalid checksums returns ErrChecksum. -func TestOpen_ErrChecksum(t *testing.T) { - if pageSize != os.Getpagesize() { - t.Skip("page size mismatch") - } - - // Create empty database. - db := MustOpenDB() - path := db.Path() - defer db.MustClose() - - // Close database. - if err := db.DB.Close(); err != nil { - t.Fatal(err) - } - - // Read data file. - buf, err := ioutil.ReadFile(path) - if err != nil { - t.Fatal(err) - } - - // Rewrite meta pages. - meta0 := (*meta)(unsafe.Pointer(&buf[pageHeaderSize])) - meta0.pgid++ - meta1 := (*meta)(unsafe.Pointer(&buf[pageSize+pageHeaderSize])) - meta1.pgid++ - if err := ioutil.WriteFile(path, buf, 0666); err != nil { - t.Fatal(err) - } - - // Reopen data file. - if _, err := bolt.Open(path, 0666, nil); err != bolt.ErrChecksum { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure that opening a database does not increase its size. -// https://github.com/boltdb/bolt/issues/291 -func TestOpen_Size(t *testing.T) { - // Open a data file. - db := MustOpenDB() - path := db.Path() - defer db.MustClose() - - pagesize := db.Info().PageSize - - // Insert until we get above the minimum 4MB size. - if err := db.Update(func(tx *bolt.Tx) error { - b, _ := tx.CreateBucketIfNotExists([]byte("data")) - for i := 0; i < 10000; i++ { - if err := b.Put([]byte(fmt.Sprintf("%04d", i)), make([]byte, 1000)); err != nil { - t.Fatal(err) - } - } - return nil - }); err != nil { - t.Fatal(err) - } - - // Close database and grab the size. - if err := db.DB.Close(); err != nil { - t.Fatal(err) - } - sz := fileSize(path) - if sz == 0 { - t.Fatalf("unexpected new file size: %d", sz) - } - - // Reopen database, update, and check size again. - db0, err := bolt.Open(path, 0666, nil) - if err != nil { - t.Fatal(err) - } - if err := db0.Update(func(tx *bolt.Tx) error { - if err := tx.Bucket([]byte("data")).Put([]byte{0}, []byte{0}); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - if err := db0.Close(); err != nil { - t.Fatal(err) - } - newSz := fileSize(path) - if newSz == 0 { - t.Fatalf("unexpected new file size: %d", newSz) - } - - // Compare the original size with the new size. - // db size might increase by a few page sizes due to the new small update. - if sz < newSz-5*int64(pagesize) { - t.Fatalf("unexpected file growth: %d => %d", sz, newSz) - } -} - -// Ensure that opening a database beyond the max step size does not increase its size. -// https://github.com/boltdb/bolt/issues/303 -func TestOpen_Size_Large(t *testing.T) { - if testing.Short() { - t.Skip("short mode") - } - - // Open a data file. - db := MustOpenDB() - path := db.Path() - defer db.MustClose() - - pagesize := db.Info().PageSize - - // Insert until we get above the minimum 4MB size. - var index uint64 - for i := 0; i < 10000; i++ { - if err := db.Update(func(tx *bolt.Tx) error { - b, _ := tx.CreateBucketIfNotExists([]byte("data")) - for j := 0; j < 1000; j++ { - if err := b.Put(u64tob(index), make([]byte, 50)); err != nil { - t.Fatal(err) - } - index++ - } - return nil - }); err != nil { - t.Fatal(err) - } - } - - // Close database and grab the size. - if err := db.DB.Close(); err != nil { - t.Fatal(err) - } - sz := fileSize(path) - if sz == 0 { - t.Fatalf("unexpected new file size: %d", sz) - } else if sz < (1 << 30) { - t.Fatalf("expected larger initial size: %d", sz) - } - - // Reopen database, update, and check size again. - db0, err := bolt.Open(path, 0666, nil) - if err != nil { - t.Fatal(err) - } - if err := db0.Update(func(tx *bolt.Tx) error { - return tx.Bucket([]byte("data")).Put([]byte{0}, []byte{0}) - }); err != nil { - t.Fatal(err) - } - if err := db0.Close(); err != nil { - t.Fatal(err) - } - - newSz := fileSize(path) - if newSz == 0 { - t.Fatalf("unexpected new file size: %d", newSz) - } - - // Compare the original size with the new size. - // db size might increase by a few page sizes due to the new small update. - if sz < newSz-5*int64(pagesize) { - t.Fatalf("unexpected file growth: %d => %d", sz, newSz) - } -} - -// Ensure that a re-opened database is consistent. -func TestOpen_Check(t *testing.T) { - path := tempfile() - - db, err := bolt.Open(path, 0666, nil) - if err != nil { - t.Fatal(err) - } - if err := db.View(func(tx *bolt.Tx) error { return <-tx.Check() }); err != nil { - t.Fatal(err) - } - if err := db.Close(); err != nil { - t.Fatal(err) - } - - db, err = bolt.Open(path, 0666, nil) - if err != nil { - t.Fatal(err) - } - if err := db.View(func(tx *bolt.Tx) error { return <-tx.Check() }); err != nil { - t.Fatal(err) - } - if err := db.Close(); err != nil { - t.Fatal(err) - } -} - -// Ensure that write errors to the meta file handler during initialization are returned. -func TestOpen_MetaInitWriteError(t *testing.T) { - t.Skip("pending") -} - -// Ensure that a database that is too small returns an error. -func TestOpen_FileTooSmall(t *testing.T) { - path := tempfile() - - db, err := bolt.Open(path, 0666, nil) - if err != nil { - t.Fatal(err) - } - if err := db.Close(); err != nil { - t.Fatal(err) - } - - // corrupt the database - if err := os.Truncate(path, int64(os.Getpagesize())); err != nil { - t.Fatal(err) - } - - db, err = bolt.Open(path, 0666, nil) - if err == nil || err.Error() != "file size too small" { - t.Fatalf("unexpected error: %s", err) - } -} - -// TestDB_Open_InitialMmapSize tests if having InitialMmapSize large enough -// to hold data from concurrent write transaction resolves the issue that -// read transaction blocks the write transaction and causes deadlock. -// This is a very hacky test since the mmap size is not exposed. -func TestDB_Open_InitialMmapSize(t *testing.T) { - path := tempfile() - defer os.Remove(path) - - initMmapSize := 1 << 31 // 2GB - testWriteSize := 1 << 27 // 134MB - - db, err := bolt.Open(path, 0666, &bolt.Options{InitialMmapSize: initMmapSize}) - if err != nil { - t.Fatal(err) - } - - // create a long-running read transaction - // that never gets closed while writing - rtx, err := db.Begin(false) - if err != nil { - t.Fatal(err) - } - - // create a write transaction - wtx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - - b, err := wtx.CreateBucket([]byte("test")) - if err != nil { - t.Fatal(err) - } - - // and commit a large write - err = b.Put([]byte("foo"), make([]byte, testWriteSize)) - if err != nil { - t.Fatal(err) - } - - done := make(chan struct{}) - - go func() { - if err := wtx.Commit(); err != nil { - t.Fatal(err) - } - done <- struct{}{} - }() - - select { - case <-time.After(5 * time.Second): - t.Errorf("unexpected that the reader blocks writer") - case <-done: - } - - if err := rtx.Rollback(); err != nil { - t.Fatal(err) - } -} - -// Ensure that a database cannot open a transaction when it's not open. -func TestDB_Begin_ErrDatabaseNotOpen(t *testing.T) { - var db bolt.DB - if _, err := db.Begin(false); err != bolt.ErrDatabaseNotOpen { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure that a read-write transaction can be retrieved. -func TestDB_BeginRW(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } else if tx == nil { - t.Fatal("expected tx") - } - - if tx.DB() != db.DB { - t.Fatal("unexpected tx database") - } else if !tx.Writable() { - t.Fatal("expected writable tx") - } - - if err := tx.Commit(); err != nil { - t.Fatal(err) - } -} - -// Ensure that opening a transaction while the DB is closed returns an error. -func TestDB_BeginRW_Closed(t *testing.T) { - var db bolt.DB - if _, err := db.Begin(true); err != bolt.ErrDatabaseNotOpen { - t.Fatalf("unexpected error: %s", err) - } -} - -func TestDB_Close_PendingTx_RW(t *testing.T) { testDB_Close_PendingTx(t, true) } -func TestDB_Close_PendingTx_RO(t *testing.T) { testDB_Close_PendingTx(t, false) } - -// Ensure that a database cannot close while transactions are open. -func testDB_Close_PendingTx(t *testing.T, writable bool) { - db := MustOpenDB() - defer db.MustClose() - - // Start transaction. - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - - // Open update in separate goroutine. - done := make(chan struct{}) - go func() { - if err := db.Close(); err != nil { - t.Fatal(err) - } - close(done) - }() - - // Ensure database hasn't closed. - time.Sleep(100 * time.Millisecond) - select { - case <-done: - t.Fatal("database closed too early") - default: - } - - // Commit transaction. - if err := tx.Commit(); err != nil { - t.Fatal(err) - } - - // Ensure database closed now. - time.Sleep(100 * time.Millisecond) - select { - case <-done: - default: - t.Fatal("database did not close") - } -} - -// Ensure a database can provide a transactional block. -func TestDB_Update(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("baz"), []byte("bat")); err != nil { - t.Fatal(err) - } - if err := b.Delete([]byte("foo")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - if v := b.Get([]byte("foo")); v != nil { - t.Fatalf("expected nil value, got: %v", v) - } - if v := b.Get([]byte("baz")); !bytes.Equal(v, []byte("bat")) { - t.Fatalf("unexpected value: %v", v) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure a closed database returns an error while running a transaction block -func TestDB_Update_Closed(t *testing.T) { - var db bolt.DB - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != bolt.ErrDatabaseNotOpen { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure a panic occurs while trying to commit a managed transaction. -func TestDB_Update_ManualCommit(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - var panicked bool - if err := db.Update(func(tx *bolt.Tx) error { - func() { - defer func() { - if r := recover(); r != nil { - panicked = true - } - }() - - if err := tx.Commit(); err != nil { - t.Fatal(err) - } - }() - return nil - }); err != nil { - t.Fatal(err) - } else if !panicked { - t.Fatal("expected panic") - } -} - -// Ensure a panic occurs while trying to rollback a managed transaction. -func TestDB_Update_ManualRollback(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - var panicked bool - if err := db.Update(func(tx *bolt.Tx) error { - func() { - defer func() { - if r := recover(); r != nil { - panicked = true - } - }() - - if err := tx.Rollback(); err != nil { - t.Fatal(err) - } - }() - return nil - }); err != nil { - t.Fatal(err) - } else if !panicked { - t.Fatal("expected panic") - } -} - -// Ensure a panic occurs while trying to commit a managed transaction. -func TestDB_View_ManualCommit(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - var panicked bool - if err := db.View(func(tx *bolt.Tx) error { - func() { - defer func() { - if r := recover(); r != nil { - panicked = true - } - }() - - if err := tx.Commit(); err != nil { - t.Fatal(err) - } - }() - return nil - }); err != nil { - t.Fatal(err) - } else if !panicked { - t.Fatal("expected panic") - } -} - -// Ensure a panic occurs while trying to rollback a managed transaction. -func TestDB_View_ManualRollback(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - var panicked bool - if err := db.View(func(tx *bolt.Tx) error { - func() { - defer func() { - if r := recover(); r != nil { - panicked = true - } - }() - - if err := tx.Rollback(); err != nil { - t.Fatal(err) - } - }() - return nil - }); err != nil { - t.Fatal(err) - } else if !panicked { - t.Fatal("expected panic") - } -} - -// Ensure a write transaction that panics does not hold open locks. -func TestDB_Update_Panic(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - // Panic during update but recover. - func() { - defer func() { - if r := recover(); r != nil { - t.Log("recover: update", r) - } - }() - - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - panic("omg") - }); err != nil { - t.Fatal(err) - } - }() - - // Verify we can update again. - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - // Verify that our change persisted. - if err := db.Update(func(tx *bolt.Tx) error { - if tx.Bucket([]byte("widgets")) == nil { - t.Fatal("expected bucket") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure a database can return an error through a read-only transactional block. -func TestDB_View_Error(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.View(func(tx *bolt.Tx) error { - return errors.New("xxx") - }); err == nil || err.Error() != "xxx" { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure a read transaction that panics does not hold open locks. -func TestDB_View_Panic(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - // Panic during view transaction but recover. - func() { - defer func() { - if r := recover(); r != nil { - t.Log("recover: view", r) - } - }() - - if err := db.View(func(tx *bolt.Tx) error { - if tx.Bucket([]byte("widgets")) == nil { - t.Fatal("expected bucket") - } - panic("omg") - }); err != nil { - t.Fatal(err) - } - }() - - // Verify that we can still use read transactions. - if err := db.View(func(tx *bolt.Tx) error { - if tx.Bucket([]byte("widgets")) == nil { - t.Fatal("expected bucket") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that DB stats can be returned. -func TestDB_Stats(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("widgets")) - return err - }); err != nil { - t.Fatal(err) - } - - stats := db.Stats() - if stats.TxStats.PageCount != 2 { - t.Fatalf("unexpected TxStats.PageCount: %d", stats.TxStats.PageCount) - } else if stats.FreePageN != 0 { - t.Fatalf("unexpected FreePageN != 0: %d", stats.FreePageN) - } else if stats.PendingPageN != 2 { - t.Fatalf("unexpected PendingPageN != 2: %d", stats.PendingPageN) - } -} - -// Ensure that database pages are in expected order and type. -func TestDB_Consistency(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("widgets")) - return err - }); err != nil { - t.Fatal(err) - } - - for i := 0; i < 10; i++ { - if err := db.Update(func(tx *bolt.Tx) error { - if err := tx.Bucket([]byte("widgets")).Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - } - - if err := db.Update(func(tx *bolt.Tx) error { - if p, _ := tx.Page(0); p == nil { - t.Fatal("expected page") - } else if p.Type != "meta" { - t.Fatalf("unexpected page type: %s", p.Type) - } - - if p, _ := tx.Page(1); p == nil { - t.Fatal("expected page") - } else if p.Type != "meta" { - t.Fatalf("unexpected page type: %s", p.Type) - } - - if p, _ := tx.Page(2); p == nil { - t.Fatal("expected page") - } else if p.Type != "free" { - t.Fatalf("unexpected page type: %s", p.Type) - } - - if p, _ := tx.Page(3); p == nil { - t.Fatal("expected page") - } else if p.Type != "free" { - t.Fatalf("unexpected page type: %s", p.Type) - } - - if p, _ := tx.Page(4); p == nil { - t.Fatal("expected page") - } else if p.Type != "leaf" { - t.Fatalf("unexpected page type: %s", p.Type) - } - - if p, _ := tx.Page(5); p == nil { - t.Fatal("expected page") - } else if p.Type != "freelist" { - t.Fatalf("unexpected page type: %s", p.Type) - } - - if p, _ := tx.Page(6); p != nil { - t.Fatal("unexpected page") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that DB stats can be subtracted from one another. -func TestDBStats_Sub(t *testing.T) { - var a, b bolt.Stats - a.TxStats.PageCount = 3 - a.FreePageN = 4 - b.TxStats.PageCount = 10 - b.FreePageN = 14 - diff := b.Sub(&a) - if diff.TxStats.PageCount != 7 { - t.Fatalf("unexpected TxStats.PageCount: %d", diff.TxStats.PageCount) - } - - // free page stats are copied from the receiver and not subtracted - if diff.FreePageN != 14 { - t.Fatalf("unexpected FreePageN: %d", diff.FreePageN) - } -} - -// Ensure two functions can perform updates in a single batch. -func TestDB_Batch(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - // Iterate over multiple updates in separate goroutines. - n := 2 - ch := make(chan error) - for i := 0; i < n; i++ { - go func(i int) { - ch <- db.Batch(func(tx *bolt.Tx) error { - return tx.Bucket([]byte("widgets")).Put(u64tob(uint64(i)), []byte{}) - }) - }(i) - } - - // Check all responses to make sure there's no error. - for i := 0; i < n; i++ { - if err := <-ch; err != nil { - t.Fatal(err) - } - } - - // Ensure data is correct. - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - for i := 0; i < n; i++ { - if v := b.Get(u64tob(uint64(i))); v == nil { - t.Errorf("key not found: %d", i) - } - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -func TestDB_Batch_Panic(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - var sentinel int - var bork = &sentinel - var problem interface{} - var err error - - // Execute a function inside a batch that panics. - func() { - defer func() { - if p := recover(); p != nil { - problem = p - } - }() - err = db.Batch(func(tx *bolt.Tx) error { - panic(bork) - }) - }() - - // Verify there is no error. - if g, e := err, error(nil); g != e { - t.Fatalf("wrong error: %v != %v", g, e) - } - // Verify the panic was captured. - if g, e := problem, bork; g != e { - t.Fatalf("wrong error: %v != %v", g, e) - } -} - -func TestDB_BatchFull(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("widgets")) - return err - }); err != nil { - t.Fatal(err) - } - - const size = 3 - // buffered so we never leak goroutines - ch := make(chan error, size) - put := func(i int) { - ch <- db.Batch(func(tx *bolt.Tx) error { - return tx.Bucket([]byte("widgets")).Put(u64tob(uint64(i)), []byte{}) - }) - } - - db.MaxBatchSize = size - // high enough to never trigger here - db.MaxBatchDelay = 1 * time.Hour - - go put(1) - go put(2) - - // Give the batch a chance to exhibit bugs. - time.Sleep(10 * time.Millisecond) - - // not triggered yet - select { - case <-ch: - t.Fatalf("batch triggered too early") - default: - } - - go put(3) - - // Check all responses to make sure there's no error. - for i := 0; i < size; i++ { - if err := <-ch; err != nil { - t.Fatal(err) - } - } - - // Ensure data is correct. - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - for i := 1; i <= size; i++ { - if v := b.Get(u64tob(uint64(i))); v == nil { - t.Errorf("key not found: %d", i) - } - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -func TestDB_BatchTime(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("widgets")) - return err - }); err != nil { - t.Fatal(err) - } - - const size = 1 - // buffered so we never leak goroutines - ch := make(chan error, size) - put := func(i int) { - ch <- db.Batch(func(tx *bolt.Tx) error { - return tx.Bucket([]byte("widgets")).Put(u64tob(uint64(i)), []byte{}) - }) - } - - db.MaxBatchSize = 1000 - db.MaxBatchDelay = 0 - - go put(1) - - // Batch must trigger by time alone. - - // Check all responses to make sure there's no error. - for i := 0; i < size; i++ { - if err := <-ch; err != nil { - t.Fatal(err) - } - } - - // Ensure data is correct. - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("widgets")) - for i := 1; i <= size; i++ { - if v := b.Get(u64tob(uint64(i))); v == nil { - t.Errorf("key not found: %d", i) - } - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -func ExampleDB_Update() { - // Open the database. - db, err := bolt.Open(tempfile(), 0666, nil) - if err != nil { - log.Fatal(err) - } - defer os.Remove(db.Path()) - - // Execute several commands within a read-write transaction. - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - return err - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - return err - } - return nil - }); err != nil { - log.Fatal(err) - } - - // Read the value back from a separate read-only transaction. - if err := db.View(func(tx *bolt.Tx) error { - value := tx.Bucket([]byte("widgets")).Get([]byte("foo")) - fmt.Printf("The value of 'foo' is: %s\n", value) - return nil - }); err != nil { - log.Fatal(err) - } - - // Close database to release the file lock. - if err := db.Close(); err != nil { - log.Fatal(err) - } - - // Output: - // The value of 'foo' is: bar -} - -func ExampleDB_View() { - // Open the database. - db, err := bolt.Open(tempfile(), 0666, nil) - if err != nil { - log.Fatal(err) - } - defer os.Remove(db.Path()) - - // Insert data into a bucket. - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("people")) - if err != nil { - return err - } - if err := b.Put([]byte("john"), []byte("doe")); err != nil { - return err - } - if err := b.Put([]byte("susy"), []byte("que")); err != nil { - return err - } - return nil - }); err != nil { - log.Fatal(err) - } - - // Access data from within a read-only transactional block. - if err := db.View(func(tx *bolt.Tx) error { - v := tx.Bucket([]byte("people")).Get([]byte("john")) - fmt.Printf("John's last name is %s.\n", v) - return nil - }); err != nil { - log.Fatal(err) - } - - // Close database to release the file lock. - if err := db.Close(); err != nil { - log.Fatal(err) - } - - // Output: - // John's last name is doe. -} - -func ExampleDB_Begin_ReadOnly() { - // Open the database. - db, err := bolt.Open(tempfile(), 0666, nil) - if err != nil { - log.Fatal(err) - } - defer os.Remove(db.Path()) - - // Create a bucket using a read-write transaction. - if err := db.Update(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("widgets")) - return err - }); err != nil { - log.Fatal(err) - } - - // Create several keys in a transaction. - tx, err := db.Begin(true) - if err != nil { - log.Fatal(err) - } - b := tx.Bucket([]byte("widgets")) - if err := b.Put([]byte("john"), []byte("blue")); err != nil { - log.Fatal(err) - } - if err := b.Put([]byte("abby"), []byte("red")); err != nil { - log.Fatal(err) - } - if err := b.Put([]byte("zephyr"), []byte("purple")); err != nil { - log.Fatal(err) - } - if err := tx.Commit(); err != nil { - log.Fatal(err) - } - - // Iterate over the values in sorted key order. - tx, err = db.Begin(false) - if err != nil { - log.Fatal(err) - } - c := tx.Bucket([]byte("widgets")).Cursor() - for k, v := c.First(); k != nil; k, v = c.Next() { - fmt.Printf("%s likes %s\n", k, v) - } - - if err := tx.Rollback(); err != nil { - log.Fatal(err) - } - - if err := db.Close(); err != nil { - log.Fatal(err) - } - - // Output: - // abby likes red - // john likes blue - // zephyr likes purple -} - -func BenchmarkDBBatchAutomatic(b *testing.B) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("bench")) - return err - }); err != nil { - b.Fatal(err) - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - start := make(chan struct{}) - var wg sync.WaitGroup - - for round := 0; round < 1000; round++ { - wg.Add(1) - - go func(id uint32) { - defer wg.Done() - <-start - - h := fnv.New32a() - buf := make([]byte, 4) - binary.LittleEndian.PutUint32(buf, id) - _, _ = h.Write(buf[:]) - k := h.Sum(nil) - insert := func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("bench")) - return b.Put(k, []byte("filler")) - } - if err := db.Batch(insert); err != nil { - b.Error(err) - return - } - }(uint32(round)) - } - close(start) - wg.Wait() - } - - b.StopTimer() - validateBatchBench(b, db) -} - -func BenchmarkDBBatchSingle(b *testing.B) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("bench")) - return err - }); err != nil { - b.Fatal(err) - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - start := make(chan struct{}) - var wg sync.WaitGroup - - for round := 0; round < 1000; round++ { - wg.Add(1) - go func(id uint32) { - defer wg.Done() - <-start - - h := fnv.New32a() - buf := make([]byte, 4) - binary.LittleEndian.PutUint32(buf, id) - _, _ = h.Write(buf[:]) - k := h.Sum(nil) - insert := func(tx *bolt.Tx) error { - b := tx.Bucket([]byte("bench")) - return b.Put(k, []byte("filler")) - } - if err := db.Update(insert); err != nil { - b.Error(err) - return - } - }(uint32(round)) - } - close(start) - wg.Wait() - } - - b.StopTimer() - validateBatchBench(b, db) -} - -func BenchmarkDBBatchManual10x100(b *testing.B) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("bench")) - return err - }); err != nil { - b.Fatal(err) - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - start := make(chan struct{}) - var wg sync.WaitGroup - - for major := 0; major < 10; major++ { - wg.Add(1) - go func(id uint32) { - defer wg.Done() - <-start - - insert100 := func(tx *bolt.Tx) error { - h := fnv.New32a() - buf := make([]byte, 4) - for minor := uint32(0); minor < 100; minor++ { - binary.LittleEndian.PutUint32(buf, uint32(id*100+minor)) - h.Reset() - _, _ = h.Write(buf[:]) - k := h.Sum(nil) - b := tx.Bucket([]byte("bench")) - if err := b.Put(k, []byte("filler")); err != nil { - return err - } - } - return nil - } - if err := db.Update(insert100); err != nil { - b.Fatal(err) - } - }(uint32(major)) - } - close(start) - wg.Wait() - } - - b.StopTimer() - validateBatchBench(b, db) -} - -func validateBatchBench(b *testing.B, db *DB) { - var rollback = errors.New("sentinel error to cause rollback") - validate := func(tx *bolt.Tx) error { - bucket := tx.Bucket([]byte("bench")) - h := fnv.New32a() - buf := make([]byte, 4) - for id := uint32(0); id < 1000; id++ { - binary.LittleEndian.PutUint32(buf, id) - h.Reset() - _, _ = h.Write(buf[:]) - k := h.Sum(nil) - v := bucket.Get(k) - if v == nil { - b.Errorf("not found id=%d key=%x", id, k) - continue - } - if g, e := v, []byte("filler"); !bytes.Equal(g, e) { - b.Errorf("bad value for id=%d key=%x: %s != %q", id, k, g, e) - } - if err := bucket.Delete(k); err != nil { - return err - } - } - // should be empty now - c := bucket.Cursor() - for k, v := c.First(); k != nil; k, v = c.Next() { - b.Errorf("unexpected key: %x = %q", k, v) - } - return rollback - } - if err := db.Update(validate); err != nil && err != rollback { - b.Error(err) - } -} - -// DB is a test wrapper for bolt.DB. -type DB struct { - *bolt.DB -} - -// MustOpenDB returns a new, open DB at a temporary location. -func MustOpenDB() *DB { - db, err := bolt.Open(tempfile(), 0666, nil) - if err != nil { - panic(err) - } - return &DB{db} -} - -// Close closes the database and deletes the underlying file. -func (db *DB) Close() error { - // Log statistics. - if *statsFlag { - db.PrintStats() - } - - // Check database consistency after every test. - db.MustCheck() - - // Close database and remove file. - defer os.Remove(db.Path()) - return db.DB.Close() -} - -// MustClose closes the database and deletes the underlying file. Panic on error. -func (db *DB) MustClose() { - if err := db.Close(); err != nil { - panic(err) - } -} - -// PrintStats prints the database stats -func (db *DB) PrintStats() { - var stats = db.Stats() - fmt.Printf("[db] %-20s %-20s %-20s\n", - fmt.Sprintf("pg(%d/%d)", stats.TxStats.PageCount, stats.TxStats.PageAlloc), - fmt.Sprintf("cur(%d)", stats.TxStats.CursorCount), - fmt.Sprintf("node(%d/%d)", stats.TxStats.NodeCount, stats.TxStats.NodeDeref), - ) - fmt.Printf(" %-20s %-20s %-20s\n", - fmt.Sprintf("rebal(%d/%v)", stats.TxStats.Rebalance, truncDuration(stats.TxStats.RebalanceTime)), - fmt.Sprintf("spill(%d/%v)", stats.TxStats.Spill, truncDuration(stats.TxStats.SpillTime)), - fmt.Sprintf("w(%d/%v)", stats.TxStats.Write, truncDuration(stats.TxStats.WriteTime)), - ) -} - -// MustCheck runs a consistency check on the database and panics if any errors are found. -func (db *DB) MustCheck() { - if err := db.Update(func(tx *bolt.Tx) error { - // Collect all the errors. - var errors []error - for err := range tx.Check() { - errors = append(errors, err) - if len(errors) > 10 { - break - } - } - - // If errors occurred, copy the DB and print the errors. - if len(errors) > 0 { - var path = tempfile() - if err := tx.CopyFile(path, 0600); err != nil { - panic(err) - } - - // Print errors. - fmt.Print("\n\n") - fmt.Printf("consistency check failed (%d errors)\n", len(errors)) - for _, err := range errors { - fmt.Println(err) - } - fmt.Println("") - fmt.Println("db saved to:") - fmt.Println(path) - fmt.Print("\n\n") - os.Exit(-1) - } - - return nil - }); err != nil && err != bolt.ErrDatabaseNotOpen { - panic(err) - } -} - -// CopyTempFile copies a database to a temporary file. -func (db *DB) CopyTempFile() { - path := tempfile() - if err := db.View(func(tx *bolt.Tx) error { - return tx.CopyFile(path, 0600) - }); err != nil { - panic(err) - } - fmt.Println("db copied to: ", path) -} - -// tempfile returns a temporary file path. -func tempfile() string { - f, err := ioutil.TempFile("", "bolt-") - if err != nil { - panic(err) - } - if err := f.Close(); err != nil { - panic(err) - } - if err := os.Remove(f.Name()); err != nil { - panic(err) - } - return f.Name() -} - -// mustContainKeys checks that a bucket contains a given set of keys. -func mustContainKeys(b *bolt.Bucket, m map[string]string) { - found := make(map[string]string) - if err := b.ForEach(func(k, _ []byte) error { - found[string(k)] = "" - return nil - }); err != nil { - panic(err) - } - - // Check for keys found in bucket that shouldn't be there. - var keys []string - for k, _ := range found { - if _, ok := m[string(k)]; !ok { - keys = append(keys, k) - } - } - if len(keys) > 0 { - sort.Strings(keys) - panic(fmt.Sprintf("keys found(%d): %s", len(keys), strings.Join(keys, ","))) - } - - // Check for keys not found in bucket that should be there. - for k, _ := range m { - if _, ok := found[string(k)]; !ok { - keys = append(keys, k) - } - } - if len(keys) > 0 { - sort.Strings(keys) - panic(fmt.Sprintf("keys not found(%d): %s", len(keys), strings.Join(keys, ","))) - } -} - -func trunc(b []byte, length int) []byte { - if length < len(b) { - return b[:length] - } - return b -} - -func truncDuration(d time.Duration) string { - return regexp.MustCompile(`^(\d+)(\.\d+)`).ReplaceAllString(d.String(), "$1") -} - -func fileSize(path string) int64 { - fi, err := os.Stat(path) - if err != nil { - return 0 - } - return fi.Size() -} - -func warn(v ...interface{}) { fmt.Fprintln(os.Stderr, v...) } -func warnf(msg string, v ...interface{}) { fmt.Fprintf(os.Stderr, msg+"\n", v...) } - -// u64tob converts a uint64 into an 8-byte slice. -func u64tob(v uint64) []byte { - b := make([]byte, 8) - binary.BigEndian.PutUint64(b, v) - return b -} - -// btou64 converts an 8-byte slice into an uint64. -func btou64(b []byte) uint64 { return binary.BigEndian.Uint64(b) } diff --git a/vendor/github.com/boltdb/bolt/freelist_test.go b/vendor/github.com/boltdb/bolt/freelist_test.go deleted file mode 100644 index 4e9b3a8d..00000000 --- a/vendor/github.com/boltdb/bolt/freelist_test.go +++ /dev/null @@ -1,158 +0,0 @@ -package bolt - -import ( - "math/rand" - "reflect" - "sort" - "testing" - "unsafe" -) - -// Ensure that a page is added to a transaction's freelist. -func TestFreelist_free(t *testing.T) { - f := newFreelist() - f.free(100, &page{id: 12}) - if !reflect.DeepEqual([]pgid{12}, f.pending[100]) { - t.Fatalf("exp=%v; got=%v", []pgid{12}, f.pending[100]) - } -} - -// Ensure that a page and its overflow is added to a transaction's freelist. -func TestFreelist_free_overflow(t *testing.T) { - f := newFreelist() - f.free(100, &page{id: 12, overflow: 3}) - if exp := []pgid{12, 13, 14, 15}; !reflect.DeepEqual(exp, f.pending[100]) { - t.Fatalf("exp=%v; got=%v", exp, f.pending[100]) - } -} - -// Ensure that a transaction's free pages can be released. -func TestFreelist_release(t *testing.T) { - f := newFreelist() - f.free(100, &page{id: 12, overflow: 1}) - f.free(100, &page{id: 9}) - f.free(102, &page{id: 39}) - f.release(100) - f.release(101) - if exp := []pgid{9, 12, 13}; !reflect.DeepEqual(exp, f.ids) { - t.Fatalf("exp=%v; got=%v", exp, f.ids) - } - - f.release(102) - if exp := []pgid{9, 12, 13, 39}; !reflect.DeepEqual(exp, f.ids) { - t.Fatalf("exp=%v; got=%v", exp, f.ids) - } -} - -// Ensure that a freelist can find contiguous blocks of pages. -func TestFreelist_allocate(t *testing.T) { - f := &freelist{ids: []pgid{3, 4, 5, 6, 7, 9, 12, 13, 18}} - if id := int(f.allocate(3)); id != 3 { - t.Fatalf("exp=3; got=%v", id) - } - if id := int(f.allocate(1)); id != 6 { - t.Fatalf("exp=6; got=%v", id) - } - if id := int(f.allocate(3)); id != 0 { - t.Fatalf("exp=0; got=%v", id) - } - if id := int(f.allocate(2)); id != 12 { - t.Fatalf("exp=12; got=%v", id) - } - if id := int(f.allocate(1)); id != 7 { - t.Fatalf("exp=7; got=%v", id) - } - if id := int(f.allocate(0)); id != 0 { - t.Fatalf("exp=0; got=%v", id) - } - if id := int(f.allocate(0)); id != 0 { - t.Fatalf("exp=0; got=%v", id) - } - if exp := []pgid{9, 18}; !reflect.DeepEqual(exp, f.ids) { - t.Fatalf("exp=%v; got=%v", exp, f.ids) - } - - if id := int(f.allocate(1)); id != 9 { - t.Fatalf("exp=9; got=%v", id) - } - if id := int(f.allocate(1)); id != 18 { - t.Fatalf("exp=18; got=%v", id) - } - if id := int(f.allocate(1)); id != 0 { - t.Fatalf("exp=0; got=%v", id) - } - if exp := []pgid{}; !reflect.DeepEqual(exp, f.ids) { - t.Fatalf("exp=%v; got=%v", exp, f.ids) - } -} - -// Ensure that a freelist can deserialize from a freelist page. -func TestFreelist_read(t *testing.T) { - // Create a page. - var buf [4096]byte - page := (*page)(unsafe.Pointer(&buf[0])) - page.flags = freelistPageFlag - page.count = 2 - - // Insert 2 page ids. - ids := (*[3]pgid)(unsafe.Pointer(&page.ptr)) - ids[0] = 23 - ids[1] = 50 - - // Deserialize page into a freelist. - f := newFreelist() - f.read(page) - - // Ensure that there are two page ids in the freelist. - if exp := []pgid{23, 50}; !reflect.DeepEqual(exp, f.ids) { - t.Fatalf("exp=%v; got=%v", exp, f.ids) - } -} - -// Ensure that a freelist can serialize into a freelist page. -func TestFreelist_write(t *testing.T) { - // Create a freelist and write it to a page. - var buf [4096]byte - f := &freelist{ids: []pgid{12, 39}, pending: make(map[txid][]pgid)} - f.pending[100] = []pgid{28, 11} - f.pending[101] = []pgid{3} - p := (*page)(unsafe.Pointer(&buf[0])) - if err := f.write(p); err != nil { - t.Fatal(err) - } - - // Read the page back out. - f2 := newFreelist() - f2.read(p) - - // Ensure that the freelist is correct. - // All pages should be present and in reverse order. - if exp := []pgid{3, 11, 12, 28, 39}; !reflect.DeepEqual(exp, f2.ids) { - t.Fatalf("exp=%v; got=%v", exp, f2.ids) - } -} - -func Benchmark_FreelistRelease10K(b *testing.B) { benchmark_FreelistRelease(b, 10000) } -func Benchmark_FreelistRelease100K(b *testing.B) { benchmark_FreelistRelease(b, 100000) } -func Benchmark_FreelistRelease1000K(b *testing.B) { benchmark_FreelistRelease(b, 1000000) } -func Benchmark_FreelistRelease10000K(b *testing.B) { benchmark_FreelistRelease(b, 10000000) } - -func benchmark_FreelistRelease(b *testing.B, size int) { - ids := randomPgids(size) - pending := randomPgids(len(ids) / 400) - b.ResetTimer() - for i := 0; i < b.N; i++ { - f := &freelist{ids: ids, pending: map[txid][]pgid{1: pending}} - f.release(1) - } -} - -func randomPgids(n int) []pgid { - rand.Seed(42) - pgids := make(pgids, n) - for i := range pgids { - pgids[i] = pgid(rand.Int63()) - } - sort.Sort(pgids) - return pgids -} diff --git a/vendor/github.com/boltdb/bolt/node_test.go b/vendor/github.com/boltdb/bolt/node_test.go deleted file mode 100644 index fa5d10f9..00000000 --- a/vendor/github.com/boltdb/bolt/node_test.go +++ /dev/null @@ -1,156 +0,0 @@ -package bolt - -import ( - "testing" - "unsafe" -) - -// Ensure that a node can insert a key/value. -func TestNode_put(t *testing.T) { - n := &node{inodes: make(inodes, 0), bucket: &Bucket{tx: &Tx{meta: &meta{pgid: 1}}}} - n.put([]byte("baz"), []byte("baz"), []byte("2"), 0, 0) - n.put([]byte("foo"), []byte("foo"), []byte("0"), 0, 0) - n.put([]byte("bar"), []byte("bar"), []byte("1"), 0, 0) - n.put([]byte("foo"), []byte("foo"), []byte("3"), 0, leafPageFlag) - - if len(n.inodes) != 3 { - t.Fatalf("exp=3; got=%d", len(n.inodes)) - } - if k, v := n.inodes[0].key, n.inodes[0].value; string(k) != "bar" || string(v) != "1" { - t.Fatalf("exp=; got=<%s,%s>", k, v) - } - if k, v := n.inodes[1].key, n.inodes[1].value; string(k) != "baz" || string(v) != "2" { - t.Fatalf("exp=; got=<%s,%s>", k, v) - } - if k, v := n.inodes[2].key, n.inodes[2].value; string(k) != "foo" || string(v) != "3" { - t.Fatalf("exp=; got=<%s,%s>", k, v) - } - if n.inodes[2].flags != uint32(leafPageFlag) { - t.Fatalf("not a leaf: %d", n.inodes[2].flags) - } -} - -// Ensure that a node can deserialize from a leaf page. -func TestNode_read_LeafPage(t *testing.T) { - // Create a page. - var buf [4096]byte - page := (*page)(unsafe.Pointer(&buf[0])) - page.flags = leafPageFlag - page.count = 2 - - // Insert 2 elements at the beginning. sizeof(leafPageElement) == 16 - nodes := (*[3]leafPageElement)(unsafe.Pointer(&page.ptr)) - nodes[0] = leafPageElement{flags: 0, pos: 32, ksize: 3, vsize: 4} // pos = sizeof(leafPageElement) * 2 - nodes[1] = leafPageElement{flags: 0, pos: 23, ksize: 10, vsize: 3} // pos = sizeof(leafPageElement) + 3 + 4 - - // Write data for the nodes at the end. - data := (*[4096]byte)(unsafe.Pointer(&nodes[2])) - copy(data[:], []byte("barfooz")) - copy(data[7:], []byte("helloworldbye")) - - // Deserialize page into a leaf. - n := &node{} - n.read(page) - - // Check that there are two inodes with correct data. - if !n.isLeaf { - t.Fatal("expected leaf") - } - if len(n.inodes) != 2 { - t.Fatalf("exp=2; got=%d", len(n.inodes)) - } - if k, v := n.inodes[0].key, n.inodes[0].value; string(k) != "bar" || string(v) != "fooz" { - t.Fatalf("exp=; got=<%s,%s>", k, v) - } - if k, v := n.inodes[1].key, n.inodes[1].value; string(k) != "helloworld" || string(v) != "bye" { - t.Fatalf("exp=; got=<%s,%s>", k, v) - } -} - -// Ensure that a node can serialize into a leaf page. -func TestNode_write_LeafPage(t *testing.T) { - // Create a node. - n := &node{isLeaf: true, inodes: make(inodes, 0), bucket: &Bucket{tx: &Tx{db: &DB{}, meta: &meta{pgid: 1}}}} - n.put([]byte("susy"), []byte("susy"), []byte("que"), 0, 0) - n.put([]byte("ricki"), []byte("ricki"), []byte("lake"), 0, 0) - n.put([]byte("john"), []byte("john"), []byte("johnson"), 0, 0) - - // Write it to a page. - var buf [4096]byte - p := (*page)(unsafe.Pointer(&buf[0])) - n.write(p) - - // Read the page back in. - n2 := &node{} - n2.read(p) - - // Check that the two pages are the same. - if len(n2.inodes) != 3 { - t.Fatalf("exp=3; got=%d", len(n2.inodes)) - } - if k, v := n2.inodes[0].key, n2.inodes[0].value; string(k) != "john" || string(v) != "johnson" { - t.Fatalf("exp=; got=<%s,%s>", k, v) - } - if k, v := n2.inodes[1].key, n2.inodes[1].value; string(k) != "ricki" || string(v) != "lake" { - t.Fatalf("exp=; got=<%s,%s>", k, v) - } - if k, v := n2.inodes[2].key, n2.inodes[2].value; string(k) != "susy" || string(v) != "que" { - t.Fatalf("exp=; got=<%s,%s>", k, v) - } -} - -// Ensure that a node can split into appropriate subgroups. -func TestNode_split(t *testing.T) { - // Create a node. - n := &node{inodes: make(inodes, 0), bucket: &Bucket{tx: &Tx{db: &DB{}, meta: &meta{pgid: 1}}}} - n.put([]byte("00000001"), []byte("00000001"), []byte("0123456701234567"), 0, 0) - n.put([]byte("00000002"), []byte("00000002"), []byte("0123456701234567"), 0, 0) - n.put([]byte("00000003"), []byte("00000003"), []byte("0123456701234567"), 0, 0) - n.put([]byte("00000004"), []byte("00000004"), []byte("0123456701234567"), 0, 0) - n.put([]byte("00000005"), []byte("00000005"), []byte("0123456701234567"), 0, 0) - - // Split between 2 & 3. - n.split(100) - - var parent = n.parent - if len(parent.children) != 2 { - t.Fatalf("exp=2; got=%d", len(parent.children)) - } - if len(parent.children[0].inodes) != 2 { - t.Fatalf("exp=2; got=%d", len(parent.children[0].inodes)) - } - if len(parent.children[1].inodes) != 3 { - t.Fatalf("exp=3; got=%d", len(parent.children[1].inodes)) - } -} - -// Ensure that a page with the minimum number of inodes just returns a single node. -func TestNode_split_MinKeys(t *testing.T) { - // Create a node. - n := &node{inodes: make(inodes, 0), bucket: &Bucket{tx: &Tx{db: &DB{}, meta: &meta{pgid: 1}}}} - n.put([]byte("00000001"), []byte("00000001"), []byte("0123456701234567"), 0, 0) - n.put([]byte("00000002"), []byte("00000002"), []byte("0123456701234567"), 0, 0) - - // Split. - n.split(20) - if n.parent != nil { - t.Fatalf("expected nil parent") - } -} - -// Ensure that a node that has keys that all fit on a page just returns one leaf. -func TestNode_split_SinglePage(t *testing.T) { - // Create a node. - n := &node{inodes: make(inodes, 0), bucket: &Bucket{tx: &Tx{db: &DB{}, meta: &meta{pgid: 1}}}} - n.put([]byte("00000001"), []byte("00000001"), []byte("0123456701234567"), 0, 0) - n.put([]byte("00000002"), []byte("00000002"), []byte("0123456701234567"), 0, 0) - n.put([]byte("00000003"), []byte("00000003"), []byte("0123456701234567"), 0, 0) - n.put([]byte("00000004"), []byte("00000004"), []byte("0123456701234567"), 0, 0) - n.put([]byte("00000005"), []byte("00000005"), []byte("0123456701234567"), 0, 0) - - // Split. - n.split(4096) - if n.parent != nil { - t.Fatalf("expected nil parent") - } -} diff --git a/vendor/github.com/boltdb/bolt/page_test.go b/vendor/github.com/boltdb/bolt/page_test.go deleted file mode 100644 index 59f4a30e..00000000 --- a/vendor/github.com/boltdb/bolt/page_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package bolt - -import ( - "reflect" - "sort" - "testing" - "testing/quick" -) - -// Ensure that the page type can be returned in human readable format. -func TestPage_typ(t *testing.T) { - if typ := (&page{flags: branchPageFlag}).typ(); typ != "branch" { - t.Fatalf("exp=branch; got=%v", typ) - } - if typ := (&page{flags: leafPageFlag}).typ(); typ != "leaf" { - t.Fatalf("exp=leaf; got=%v", typ) - } - if typ := (&page{flags: metaPageFlag}).typ(); typ != "meta" { - t.Fatalf("exp=meta; got=%v", typ) - } - if typ := (&page{flags: freelistPageFlag}).typ(); typ != "freelist" { - t.Fatalf("exp=freelist; got=%v", typ) - } - if typ := (&page{flags: 20000}).typ(); typ != "unknown<4e20>" { - t.Fatalf("exp=unknown<4e20>; got=%v", typ) - } -} - -// Ensure that the hexdump debugging function doesn't blow up. -func TestPage_dump(t *testing.T) { - (&page{id: 256}).hexdump(16) -} - -func TestPgids_merge(t *testing.T) { - a := pgids{4, 5, 6, 10, 11, 12, 13, 27} - b := pgids{1, 3, 8, 9, 25, 30} - c := a.merge(b) - if !reflect.DeepEqual(c, pgids{1, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 25, 27, 30}) { - t.Errorf("mismatch: %v", c) - } - - a = pgids{4, 5, 6, 10, 11, 12, 13, 27, 35, 36} - b = pgids{8, 9, 25, 30} - c = a.merge(b) - if !reflect.DeepEqual(c, pgids{4, 5, 6, 8, 9, 10, 11, 12, 13, 25, 27, 30, 35, 36}) { - t.Errorf("mismatch: %v", c) - } -} - -func TestPgids_merge_quick(t *testing.T) { - if err := quick.Check(func(a, b pgids) bool { - // Sort incoming lists. - sort.Sort(a) - sort.Sort(b) - - // Merge the two lists together. - got := a.merge(b) - - // The expected value should be the two lists combined and sorted. - exp := append(a, b...) - sort.Sort(exp) - - if !reflect.DeepEqual(exp, got) { - t.Errorf("\nexp=%+v\ngot=%+v\n", exp, got) - return false - } - - return true - }, nil); err != nil { - t.Fatal(err) - } -} diff --git a/vendor/github.com/boltdb/bolt/quick_test.go b/vendor/github.com/boltdb/bolt/quick_test.go deleted file mode 100644 index 9e27792e..00000000 --- a/vendor/github.com/boltdb/bolt/quick_test.go +++ /dev/null @@ -1,87 +0,0 @@ -package bolt_test - -import ( - "bytes" - "flag" - "fmt" - "math/rand" - "os" - "reflect" - "testing/quick" - "time" -) - -// testing/quick defaults to 5 iterations and a random seed. -// You can override these settings from the command line: -// -// -quick.count The number of iterations to perform. -// -quick.seed The seed to use for randomizing. -// -quick.maxitems The maximum number of items to insert into a DB. -// -quick.maxksize The maximum size of a key. -// -quick.maxvsize The maximum size of a value. -// - -var qcount, qseed, qmaxitems, qmaxksize, qmaxvsize int - -func init() { - flag.IntVar(&qcount, "quick.count", 5, "") - flag.IntVar(&qseed, "quick.seed", int(time.Now().UnixNano())%100000, "") - flag.IntVar(&qmaxitems, "quick.maxitems", 1000, "") - flag.IntVar(&qmaxksize, "quick.maxksize", 1024, "") - flag.IntVar(&qmaxvsize, "quick.maxvsize", 1024, "") - flag.Parse() - fmt.Fprintln(os.Stderr, "seed:", qseed) - fmt.Fprintf(os.Stderr, "quick settings: count=%v, items=%v, ksize=%v, vsize=%v\n", qcount, qmaxitems, qmaxksize, qmaxvsize) -} - -func qconfig() *quick.Config { - return &quick.Config{ - MaxCount: qcount, - Rand: rand.New(rand.NewSource(int64(qseed))), - } -} - -type testdata []testdataitem - -func (t testdata) Len() int { return len(t) } -func (t testdata) Swap(i, j int) { t[i], t[j] = t[j], t[i] } -func (t testdata) Less(i, j int) bool { return bytes.Compare(t[i].Key, t[j].Key) == -1 } - -func (t testdata) Generate(rand *rand.Rand, size int) reflect.Value { - n := rand.Intn(qmaxitems-1) + 1 - items := make(testdata, n) - used := make(map[string]bool) - for i := 0; i < n; i++ { - item := &items[i] - // Ensure that keys are unique by looping until we find one that we have not already used. - for { - item.Key = randByteSlice(rand, 1, qmaxksize) - if !used[string(item.Key)] { - used[string(item.Key)] = true - break - } - } - item.Value = randByteSlice(rand, 0, qmaxvsize) - } - return reflect.ValueOf(items) -} - -type revtestdata []testdataitem - -func (t revtestdata) Len() int { return len(t) } -func (t revtestdata) Swap(i, j int) { t[i], t[j] = t[j], t[i] } -func (t revtestdata) Less(i, j int) bool { return bytes.Compare(t[i].Key, t[j].Key) == 1 } - -type testdataitem struct { - Key []byte - Value []byte -} - -func randByteSlice(rand *rand.Rand, minSize, maxSize int) []byte { - n := rand.Intn(maxSize-minSize) + minSize - b := make([]byte, n) - for i := 0; i < n; i++ { - b[i] = byte(rand.Intn(255)) - } - return b -} diff --git a/vendor/github.com/boltdb/bolt/simulation_test.go b/vendor/github.com/boltdb/bolt/simulation_test.go deleted file mode 100644 index 38310165..00000000 --- a/vendor/github.com/boltdb/bolt/simulation_test.go +++ /dev/null @@ -1,329 +0,0 @@ -package bolt_test - -import ( - "bytes" - "fmt" - "math/rand" - "sync" - "testing" - - "github.com/boltdb/bolt" -) - -func TestSimulate_1op_1p(t *testing.T) { testSimulate(t, 1, 1) } -func TestSimulate_10op_1p(t *testing.T) { testSimulate(t, 10, 1) } -func TestSimulate_100op_1p(t *testing.T) { testSimulate(t, 100, 1) } -func TestSimulate_1000op_1p(t *testing.T) { testSimulate(t, 1000, 1) } -func TestSimulate_10000op_1p(t *testing.T) { testSimulate(t, 10000, 1) } - -func TestSimulate_10op_10p(t *testing.T) { testSimulate(t, 10, 10) } -func TestSimulate_100op_10p(t *testing.T) { testSimulate(t, 100, 10) } -func TestSimulate_1000op_10p(t *testing.T) { testSimulate(t, 1000, 10) } -func TestSimulate_10000op_10p(t *testing.T) { testSimulate(t, 10000, 10) } - -func TestSimulate_100op_100p(t *testing.T) { testSimulate(t, 100, 100) } -func TestSimulate_1000op_100p(t *testing.T) { testSimulate(t, 1000, 100) } -func TestSimulate_10000op_100p(t *testing.T) { testSimulate(t, 10000, 100) } - -func TestSimulate_10000op_1000p(t *testing.T) { testSimulate(t, 10000, 1000) } - -// Randomly generate operations on a given database with multiple clients to ensure consistency and thread safety. -func testSimulate(t *testing.T, threadCount, parallelism int) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - - rand.Seed(int64(qseed)) - - // A list of operations that readers and writers can perform. - var readerHandlers = []simulateHandler{simulateGetHandler} - var writerHandlers = []simulateHandler{simulateGetHandler, simulatePutHandler} - - var versions = make(map[int]*QuickDB) - versions[1] = NewQuickDB() - - db := MustOpenDB() - defer db.MustClose() - - var mutex sync.Mutex - - // Run n threads in parallel, each with their own operation. - var wg sync.WaitGroup - var threads = make(chan bool, parallelism) - var i int - for { - threads <- true - wg.Add(1) - writable := ((rand.Int() % 100) < 20) // 20% writers - - // Choose an operation to execute. - var handler simulateHandler - if writable { - handler = writerHandlers[rand.Intn(len(writerHandlers))] - } else { - handler = readerHandlers[rand.Intn(len(readerHandlers))] - } - - // Execute a thread for the given operation. - go func(writable bool, handler simulateHandler) { - defer wg.Done() - - // Start transaction. - tx, err := db.Begin(writable) - if err != nil { - t.Fatal("tx begin: ", err) - } - - // Obtain current state of the dataset. - mutex.Lock() - var qdb = versions[tx.ID()] - if writable { - qdb = versions[tx.ID()-1].Copy() - } - mutex.Unlock() - - // Make sure we commit/rollback the tx at the end and update the state. - if writable { - defer func() { - mutex.Lock() - versions[tx.ID()] = qdb - mutex.Unlock() - - if err := tx.Commit(); err != nil { - t.Fatal(err) - } - }() - } else { - defer func() { _ = tx.Rollback() }() - } - - // Ignore operation if we don't have data yet. - if qdb == nil { - return - } - - // Execute handler. - handler(tx, qdb) - - // Release a thread back to the scheduling loop. - <-threads - }(writable, handler) - - i++ - if i > threadCount { - break - } - } - - // Wait until all threads are done. - wg.Wait() -} - -type simulateHandler func(tx *bolt.Tx, qdb *QuickDB) - -// Retrieves a key from the database and verifies that it is what is expected. -func simulateGetHandler(tx *bolt.Tx, qdb *QuickDB) { - // Randomly retrieve an existing exist. - keys := qdb.Rand() - if len(keys) == 0 { - return - } - - // Retrieve root bucket. - b := tx.Bucket(keys[0]) - if b == nil { - panic(fmt.Sprintf("bucket[0] expected: %08x\n", trunc(keys[0], 4))) - } - - // Drill into nested buckets. - for _, key := range keys[1 : len(keys)-1] { - b = b.Bucket(key) - if b == nil { - panic(fmt.Sprintf("bucket[n] expected: %v -> %v\n", keys, key)) - } - } - - // Verify key/value on the final bucket. - expected := qdb.Get(keys) - actual := b.Get(keys[len(keys)-1]) - if !bytes.Equal(actual, expected) { - fmt.Println("=== EXPECTED ===") - fmt.Println(expected) - fmt.Println("=== ACTUAL ===") - fmt.Println(actual) - fmt.Println("=== END ===") - panic("value mismatch") - } -} - -// Inserts a key into the database. -func simulatePutHandler(tx *bolt.Tx, qdb *QuickDB) { - var err error - keys, value := randKeys(), randValue() - - // Retrieve root bucket. - b := tx.Bucket(keys[0]) - if b == nil { - b, err = tx.CreateBucket(keys[0]) - if err != nil { - panic("create bucket: " + err.Error()) - } - } - - // Create nested buckets, if necessary. - for _, key := range keys[1 : len(keys)-1] { - child := b.Bucket(key) - if child != nil { - b = child - } else { - b, err = b.CreateBucket(key) - if err != nil { - panic("create bucket: " + err.Error()) - } - } - } - - // Insert into database. - if err := b.Put(keys[len(keys)-1], value); err != nil { - panic("put: " + err.Error()) - } - - // Insert into in-memory database. - qdb.Put(keys, value) -} - -// QuickDB is an in-memory database that replicates the functionality of the -// Bolt DB type except that it is entirely in-memory. It is meant for testing -// that the Bolt database is consistent. -type QuickDB struct { - sync.RWMutex - m map[string]interface{} -} - -// NewQuickDB returns an instance of QuickDB. -func NewQuickDB() *QuickDB { - return &QuickDB{m: make(map[string]interface{})} -} - -// Get retrieves the value at a key path. -func (db *QuickDB) Get(keys [][]byte) []byte { - db.RLock() - defer db.RUnlock() - - m := db.m - for _, key := range keys[:len(keys)-1] { - value := m[string(key)] - if value == nil { - return nil - } - switch value := value.(type) { - case map[string]interface{}: - m = value - case []byte: - return nil - } - } - - // Only return if it's a simple value. - if value, ok := m[string(keys[len(keys)-1])].([]byte); ok { - return value - } - return nil -} - -// Put inserts a value into a key path. -func (db *QuickDB) Put(keys [][]byte, value []byte) { - db.Lock() - defer db.Unlock() - - // Build buckets all the way down the key path. - m := db.m - for _, key := range keys[:len(keys)-1] { - if _, ok := m[string(key)].([]byte); ok { - return // Keypath intersects with a simple value. Do nothing. - } - - if m[string(key)] == nil { - m[string(key)] = make(map[string]interface{}) - } - m = m[string(key)].(map[string]interface{}) - } - - // Insert value into the last key. - m[string(keys[len(keys)-1])] = value -} - -// Rand returns a random key path that points to a simple value. -func (db *QuickDB) Rand() [][]byte { - db.RLock() - defer db.RUnlock() - if len(db.m) == 0 { - return nil - } - var keys [][]byte - db.rand(db.m, &keys) - return keys -} - -func (db *QuickDB) rand(m map[string]interface{}, keys *[][]byte) { - i, index := 0, rand.Intn(len(m)) - for k, v := range m { - if i == index { - *keys = append(*keys, []byte(k)) - if v, ok := v.(map[string]interface{}); ok { - db.rand(v, keys) - } - return - } - i++ - } - panic("quickdb rand: out-of-range") -} - -// Copy copies the entire database. -func (db *QuickDB) Copy() *QuickDB { - db.RLock() - defer db.RUnlock() - return &QuickDB{m: db.copy(db.m)} -} - -func (db *QuickDB) copy(m map[string]interface{}) map[string]interface{} { - clone := make(map[string]interface{}, len(m)) - for k, v := range m { - switch v := v.(type) { - case map[string]interface{}: - clone[k] = db.copy(v) - default: - clone[k] = v - } - } - return clone -} - -func randKey() []byte { - var min, max = 1, 1024 - n := rand.Intn(max-min) + min - b := make([]byte, n) - for i := 0; i < n; i++ { - b[i] = byte(rand.Intn(255)) - } - return b -} - -func randKeys() [][]byte { - var keys [][]byte - var count = rand.Intn(2) + 2 - for i := 0; i < count; i++ { - keys = append(keys, randKey()) - } - return keys -} - -func randValue() []byte { - n := rand.Intn(8192) - b := make([]byte, n) - for i := 0; i < n; i++ { - b[i] = byte(rand.Intn(255)) - } - return b -} diff --git a/vendor/github.com/boltdb/bolt/tx_test.go b/vendor/github.com/boltdb/bolt/tx_test.go deleted file mode 100644 index 2201e792..00000000 --- a/vendor/github.com/boltdb/bolt/tx_test.go +++ /dev/null @@ -1,716 +0,0 @@ -package bolt_test - -import ( - "bytes" - "errors" - "fmt" - "log" - "os" - "testing" - - "github.com/boltdb/bolt" -) - -// Ensure that committing a closed transaction returns an error. -func TestTx_Commit_ErrTxClosed(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - - if _, err := tx.CreateBucket([]byte("foo")); err != nil { - t.Fatal(err) - } - - if err := tx.Commit(); err != nil { - t.Fatal(err) - } - - if err := tx.Commit(); err != bolt.ErrTxClosed { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure that rolling back a closed transaction returns an error. -func TestTx_Rollback_ErrTxClosed(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - - if err := tx.Rollback(); err != nil { - t.Fatal(err) - } - if err := tx.Rollback(); err != bolt.ErrTxClosed { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure that committing a read-only transaction returns an error. -func TestTx_Commit_ErrTxNotWritable(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - tx, err := db.Begin(false) - if err != nil { - t.Fatal(err) - } - if err := tx.Commit(); err != bolt.ErrTxNotWritable { - t.Fatal(err) - } -} - -// Ensure that a transaction can retrieve a cursor on the root bucket. -func TestTx_Cursor(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - - if _, err := tx.CreateBucket([]byte("woojits")); err != nil { - t.Fatal(err) - } - - c := tx.Cursor() - if k, v := c.First(); !bytes.Equal(k, []byte("widgets")) { - t.Fatalf("unexpected key: %v", k) - } else if v != nil { - t.Fatalf("unexpected value: %v", v) - } - - if k, v := c.Next(); !bytes.Equal(k, []byte("woojits")) { - t.Fatalf("unexpected key: %v", k) - } else if v != nil { - t.Fatalf("unexpected value: %v", v) - } - - if k, v := c.Next(); k != nil { - t.Fatalf("unexpected key: %v", k) - } else if v != nil { - t.Fatalf("unexpected value: %v", k) - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that creating a bucket with a read-only transaction returns an error. -func TestTx_CreateBucket_ErrTxNotWritable(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.View(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("foo")) - if err != bolt.ErrTxNotWritable { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that creating a bucket on a closed transaction returns an error. -func TestTx_CreateBucket_ErrTxClosed(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - if err := tx.Commit(); err != nil { - t.Fatal(err) - } - - if _, err := tx.CreateBucket([]byte("foo")); err != bolt.ErrTxClosed { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure that a Tx can retrieve a bucket. -func TestTx_Bucket(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - if tx.Bucket([]byte("widgets")) == nil { - t.Fatal("expected bucket") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a Tx retrieving a non-existent key returns nil. -func TestTx_Get_NotFound(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - if b.Get([]byte("no_such_key")) != nil { - t.Fatal("expected nil value") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket can be created and retrieved. -func TestTx_CreateBucket(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - // Create a bucket. - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } else if b == nil { - t.Fatal("expected bucket") - } - return nil - }); err != nil { - t.Fatal(err) - } - - // Read the bucket through a separate transaction. - if err := db.View(func(tx *bolt.Tx) error { - if tx.Bucket([]byte("widgets")) == nil { - t.Fatal("expected bucket") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket can be created if it doesn't already exist. -func TestTx_CreateBucketIfNotExists(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - // Create bucket. - if b, err := tx.CreateBucketIfNotExists([]byte("widgets")); err != nil { - t.Fatal(err) - } else if b == nil { - t.Fatal("expected bucket") - } - - // Create bucket again. - if b, err := tx.CreateBucketIfNotExists([]byte("widgets")); err != nil { - t.Fatal(err) - } else if b == nil { - t.Fatal("expected bucket") - } - - return nil - }); err != nil { - t.Fatal(err) - } - - // Read the bucket through a separate transaction. - if err := db.View(func(tx *bolt.Tx) error { - if tx.Bucket([]byte("widgets")) == nil { - t.Fatal("expected bucket") - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure transaction returns an error if creating an unnamed bucket. -func TestTx_CreateBucketIfNotExists_ErrBucketNameRequired(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucketIfNotExists([]byte{}); err != bolt.ErrBucketNameRequired { - t.Fatalf("unexpected error: %s", err) - } - - if _, err := tx.CreateBucketIfNotExists(nil); err != bolt.ErrBucketNameRequired { - t.Fatalf("unexpected error: %s", err) - } - - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket cannot be created twice. -func TestTx_CreateBucket_ErrBucketExists(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - // Create a bucket. - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - // Create the same bucket again. - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket([]byte("widgets")); err != bolt.ErrBucketExists { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket is created with a non-blank name. -func TestTx_CreateBucket_ErrBucketNameRequired(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - if _, err := tx.CreateBucket(nil); err != bolt.ErrBucketNameRequired { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that a bucket can be deleted. -func TestTx_DeleteBucket(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - // Create a bucket and add a value. - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - // Delete the bucket and make sure we can't get the value. - if err := db.Update(func(tx *bolt.Tx) error { - if err := tx.DeleteBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - if tx.Bucket([]byte("widgets")) != nil { - t.Fatal("unexpected bucket") - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.Update(func(tx *bolt.Tx) error { - // Create the bucket again and make sure there's not a phantom value. - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if v := b.Get([]byte("foo")); v != nil { - t.Fatalf("unexpected phantom value: %v", v) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that deleting a bucket on a closed transaction returns an error. -func TestTx_DeleteBucket_ErrTxClosed(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - tx, err := db.Begin(true) - if err != nil { - t.Fatal(err) - } - if err := tx.Commit(); err != nil { - t.Fatal(err) - } - if err := tx.DeleteBucket([]byte("foo")); err != bolt.ErrTxClosed { - t.Fatalf("unexpected error: %s", err) - } -} - -// Ensure that deleting a bucket with a read-only transaction returns an error. -func TestTx_DeleteBucket_ReadOnly(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.View(func(tx *bolt.Tx) error { - if err := tx.DeleteBucket([]byte("foo")); err != bolt.ErrTxNotWritable { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that nothing happens when deleting a bucket that doesn't exist. -func TestTx_DeleteBucket_NotFound(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - if err := tx.DeleteBucket([]byte("widgets")); err != bolt.ErrBucketNotFound { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that no error is returned when a tx.ForEach function does not return -// an error. -func TestTx_ForEach_NoError(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - - if err := tx.ForEach(func(name []byte, b *bolt.Bucket) error { - return nil - }); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that an error is returned when a tx.ForEach function returns an error. -func TestTx_ForEach_WithError(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - - marker := errors.New("marker") - if err := tx.ForEach(func(name []byte, b *bolt.Bucket) error { - return marker - }); err != marker { - t.Fatalf("unexpected error: %s", err) - } - return nil - }); err != nil { - t.Fatal(err) - } -} - -// Ensure that Tx commit handlers are called after a transaction successfully commits. -func TestTx_OnCommit(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - var x int - if err := db.Update(func(tx *bolt.Tx) error { - tx.OnCommit(func() { x += 1 }) - tx.OnCommit(func() { x += 2 }) - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } else if x != 3 { - t.Fatalf("unexpected x: %d", x) - } -} - -// Ensure that Tx commit handlers are NOT called after a transaction rolls back. -func TestTx_OnCommit_Rollback(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - var x int - if err := db.Update(func(tx *bolt.Tx) error { - tx.OnCommit(func() { x += 1 }) - tx.OnCommit(func() { x += 2 }) - if _, err := tx.CreateBucket([]byte("widgets")); err != nil { - t.Fatal(err) - } - return errors.New("rollback this commit") - }); err == nil || err.Error() != "rollback this commit" { - t.Fatalf("unexpected error: %s", err) - } else if x != 0 { - t.Fatalf("unexpected x: %d", x) - } -} - -// Ensure that the database can be copied to a file path. -func TestTx_CopyFile(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - - path := tempfile() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("baz"), []byte("bat")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - return tx.CopyFile(path, 0600) - }); err != nil { - t.Fatal(err) - } - - db2, err := bolt.Open(path, 0600, nil) - if err != nil { - t.Fatal(err) - } - - if err := db2.View(func(tx *bolt.Tx) error { - if v := tx.Bucket([]byte("widgets")).Get([]byte("foo")); !bytes.Equal(v, []byte("bar")) { - t.Fatalf("unexpected value: %v", v) - } - if v := tx.Bucket([]byte("widgets")).Get([]byte("baz")); !bytes.Equal(v, []byte("bat")) { - t.Fatalf("unexpected value: %v", v) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db2.Close(); err != nil { - t.Fatal(err) - } -} - -type failWriterError struct{} - -func (failWriterError) Error() string { - return "error injected for tests" -} - -type failWriter struct { - // fail after this many bytes - After int -} - -func (f *failWriter) Write(p []byte) (n int, err error) { - n = len(p) - if n > f.After { - n = f.After - err = failWriterError{} - } - f.After -= n - return n, err -} - -// Ensure that Copy handles write errors right. -func TestTx_CopyFile_Error_Meta(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("baz"), []byte("bat")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - return tx.Copy(&failWriter{}) - }); err == nil || err.Error() != "meta 0 copy: error injected for tests" { - t.Fatalf("unexpected error: %v", err) - } -} - -// Ensure that Copy handles write errors right. -func TestTx_CopyFile_Error_Normal(t *testing.T) { - db := MustOpenDB() - defer db.MustClose() - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - t.Fatal(err) - } - if err := b.Put([]byte("baz"), []byte("bat")); err != nil { - t.Fatal(err) - } - return nil - }); err != nil { - t.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - return tx.Copy(&failWriter{3 * db.Info().PageSize}) - }); err == nil || err.Error() != "error injected for tests" { - t.Fatalf("unexpected error: %v", err) - } -} - -func ExampleTx_Rollback() { - // Open the database. - db, err := bolt.Open(tempfile(), 0666, nil) - if err != nil { - log.Fatal(err) - } - defer os.Remove(db.Path()) - - // Create a bucket. - if err := db.Update(func(tx *bolt.Tx) error { - _, err := tx.CreateBucket([]byte("widgets")) - return err - }); err != nil { - log.Fatal(err) - } - - // Set a value for a key. - if err := db.Update(func(tx *bolt.Tx) error { - return tx.Bucket([]byte("widgets")).Put([]byte("foo"), []byte("bar")) - }); err != nil { - log.Fatal(err) - } - - // Update the key but rollback the transaction so it never saves. - tx, err := db.Begin(true) - if err != nil { - log.Fatal(err) - } - b := tx.Bucket([]byte("widgets")) - if err := b.Put([]byte("foo"), []byte("baz")); err != nil { - log.Fatal(err) - } - if err := tx.Rollback(); err != nil { - log.Fatal(err) - } - - // Ensure that our original value is still set. - if err := db.View(func(tx *bolt.Tx) error { - value := tx.Bucket([]byte("widgets")).Get([]byte("foo")) - fmt.Printf("The value for 'foo' is still: %s\n", value) - return nil - }); err != nil { - log.Fatal(err) - } - - // Close database to release file lock. - if err := db.Close(); err != nil { - log.Fatal(err) - } - - // Output: - // The value for 'foo' is still: bar -} - -func ExampleTx_CopyFile() { - // Open the database. - db, err := bolt.Open(tempfile(), 0666, nil) - if err != nil { - log.Fatal(err) - } - defer os.Remove(db.Path()) - - // Create a bucket and a key. - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket([]byte("widgets")) - if err != nil { - return err - } - if err := b.Put([]byte("foo"), []byte("bar")); err != nil { - return err - } - return nil - }); err != nil { - log.Fatal(err) - } - - // Copy the database to another file. - toFile := tempfile() - if err := db.View(func(tx *bolt.Tx) error { - return tx.CopyFile(toFile, 0666) - }); err != nil { - log.Fatal(err) - } - defer os.Remove(toFile) - - // Open the cloned database. - db2, err := bolt.Open(toFile, 0666, nil) - if err != nil { - log.Fatal(err) - } - - // Ensure that the key exists in the copy. - if err := db2.View(func(tx *bolt.Tx) error { - value := tx.Bucket([]byte("widgets")).Get([]byte("foo")) - fmt.Printf("The value for 'foo' in the clone is: %s\n", value) - return nil - }); err != nil { - log.Fatal(err) - } - - // Close database to release file lock. - if err := db.Close(); err != nil { - log.Fatal(err) - } - - if err := db2.Close(); err != nil { - log.Fatal(err) - } - - // Output: - // The value for 'foo' in the clone is: bar -} diff --git a/vendor/github.com/go-yaml/yaml/.travis.yml b/vendor/github.com/go-yaml/yaml/.travis.yml deleted file mode 100644 index 004172a2..00000000 --- a/vendor/github.com/go-yaml/yaml/.travis.yml +++ /dev/null @@ -1,9 +0,0 @@ -language: go - -go: - - 1.4 - - 1.5 - - 1.6 - - tip - -go_import_path: gopkg.in/yaml.v2 diff --git a/vendor/github.com/go-yaml/yaml/README.md b/vendor/github.com/go-yaml/yaml/README.md deleted file mode 100644 index 1884de6a..00000000 --- a/vendor/github.com/go-yaml/yaml/README.md +++ /dev/null @@ -1,131 +0,0 @@ -# YAML support for the Go language - -Introduction ------------- - -The yaml package enables Go programs to comfortably encode and decode YAML -values. It was developed within [Canonical](https://www.canonical.com) as -part of the [juju](https://juju.ubuntu.com) project, and is based on a -pure Go port of the well-known [libyaml](http://pyyaml.org/wiki/LibYAML) -C library to parse and generate YAML data quickly and reliably. - -Compatibility -------------- - -The yaml package supports most of YAML 1.1 and 1.2, including support for -anchors, tags, map merging, etc. Multi-document unmarshalling is not yet -implemented, and base-60 floats from YAML 1.1 are purposefully not -supported since they're a poor design and are gone in YAML 1.2. - -Installation and usage ----------------------- - -The import path for the package is *gopkg.in/yaml.v2*. - -To install it, run: - - go get gopkg.in/yaml.v2 - -API documentation ------------------ - -If opened in a browser, the import path itself leads to the API documentation: - - * [https://gopkg.in/yaml.v2](https://gopkg.in/yaml.v2) - -API stability -------------- - -The package API for yaml v2 will remain stable as described in [gopkg.in](https://gopkg.in). - - -License -------- - -The yaml package is licensed under the Apache License 2.0. Please see the LICENSE file for details. - - -Example -------- - -```Go -package main - -import ( - "fmt" - "log" - - "gopkg.in/yaml.v2" -) - -var data = ` -a: Easy! -b: - c: 2 - d: [3, 4] -` - -type T struct { - A string - B struct { - RenamedC int `yaml:"c"` - D []int `yaml:",flow"` - } -} - -func main() { - t := T{} - - err := yaml.Unmarshal([]byte(data), &t) - if err != nil { - log.Fatalf("error: %v", err) - } - fmt.Printf("--- t:\n%v\n\n", t) - - d, err := yaml.Marshal(&t) - if err != nil { - log.Fatalf("error: %v", err) - } - fmt.Printf("--- t dump:\n%s\n\n", string(d)) - - m := make(map[interface{}]interface{}) - - err = yaml.Unmarshal([]byte(data), &m) - if err != nil { - log.Fatalf("error: %v", err) - } - fmt.Printf("--- m:\n%v\n\n", m) - - d, err = yaml.Marshal(&m) - if err != nil { - log.Fatalf("error: %v", err) - } - fmt.Printf("--- m dump:\n%s\n\n", string(d)) -} -``` - -This example will generate the following output: - -``` ---- t: -{Easy! {2 [3 4]}} - ---- t dump: -a: Easy! -b: - c: 2 - d: [3, 4] - - ---- m: -map[a:Easy! b:map[c:2 d:[3 4]]] - ---- m dump: -a: Easy! -b: - c: 2 - d: - - 3 - - 4 -``` - diff --git a/vendor/github.com/go-yaml/yaml/decode_test.go b/vendor/github.com/go-yaml/yaml/decode_test.go deleted file mode 100644 index a6fea0f2..00000000 --- a/vendor/github.com/go-yaml/yaml/decode_test.go +++ /dev/null @@ -1,998 +0,0 @@ -package yaml_test - -import ( - "errors" - . "gopkg.in/check.v1" - "gopkg.in/yaml.v2" - "math" - "net" - "reflect" - "strings" - "time" -) - -var unmarshalIntTest = 123 - -var unmarshalTests = []struct { - data string - value interface{} -}{ - { - "", - &struct{}{}, - }, { - "{}", &struct{}{}, - }, { - "v: hi", - map[string]string{"v": "hi"}, - }, { - "v: hi", map[string]interface{}{"v": "hi"}, - }, { - "v: true", - map[string]string{"v": "true"}, - }, { - "v: true", - map[string]interface{}{"v": true}, - }, { - "v: 10", - map[string]interface{}{"v": 10}, - }, { - "v: 0b10", - map[string]interface{}{"v": 2}, - }, { - "v: 0xA", - map[string]interface{}{"v": 10}, - }, { - "v: 4294967296", - map[string]int64{"v": 4294967296}, - }, { - "v: 0.1", - map[string]interface{}{"v": 0.1}, - }, { - "v: .1", - map[string]interface{}{"v": 0.1}, - }, { - "v: .Inf", - map[string]interface{}{"v": math.Inf(+1)}, - }, { - "v: -.Inf", - map[string]interface{}{"v": math.Inf(-1)}, - }, { - "v: -10", - map[string]interface{}{"v": -10}, - }, { - "v: -.1", - map[string]interface{}{"v": -0.1}, - }, - - // Simple values. - { - "123", - &unmarshalIntTest, - }, - - // Floats from spec - { - "canonical: 6.8523e+5", - map[string]interface{}{"canonical": 6.8523e+5}, - }, { - "expo: 685.230_15e+03", - map[string]interface{}{"expo": 685.23015e+03}, - }, { - "fixed: 685_230.15", - map[string]interface{}{"fixed": 685230.15}, - }, { - "neginf: -.inf", - map[string]interface{}{"neginf": math.Inf(-1)}, - }, { - "fixed: 685_230.15", - map[string]float64{"fixed": 685230.15}, - }, - //{"sexa: 190:20:30.15", map[string]interface{}{"sexa": 0}}, // Unsupported - //{"notanum: .NaN", map[string]interface{}{"notanum": math.NaN()}}, // Equality of NaN fails. - - // Bools from spec - { - "canonical: y", - map[string]interface{}{"canonical": true}, - }, { - "answer: NO", - map[string]interface{}{"answer": false}, - }, { - "logical: True", - map[string]interface{}{"logical": true}, - }, { - "option: on", - map[string]interface{}{"option": true}, - }, { - "option: on", - map[string]bool{"option": true}, - }, - // Ints from spec - { - "canonical: 685230", - map[string]interface{}{"canonical": 685230}, - }, { - "decimal: +685_230", - map[string]interface{}{"decimal": 685230}, - }, { - "octal: 02472256", - map[string]interface{}{"octal": 685230}, - }, { - "hexa: 0x_0A_74_AE", - map[string]interface{}{"hexa": 685230}, - }, { - "bin: 0b1010_0111_0100_1010_1110", - map[string]interface{}{"bin": 685230}, - }, { - "bin: -0b101010", - map[string]interface{}{"bin": -42}, - }, { - "decimal: +685_230", - map[string]int{"decimal": 685230}, - }, - - //{"sexa: 190:20:30", map[string]interface{}{"sexa": 0}}, // Unsupported - - // Nulls from spec - { - "empty:", - map[string]interface{}{"empty": nil}, - }, { - "canonical: ~", - map[string]interface{}{"canonical": nil}, - }, { - "english: null", - map[string]interface{}{"english": nil}, - }, { - "~: null key", - map[interface{}]string{nil: "null key"}, - }, { - "empty:", - map[string]*bool{"empty": nil}, - }, - - // Flow sequence - { - "seq: [A,B]", - map[string]interface{}{"seq": []interface{}{"A", "B"}}, - }, { - "seq: [A,B,C,]", - map[string][]string{"seq": []string{"A", "B", "C"}}, - }, { - "seq: [A,1,C]", - map[string][]string{"seq": []string{"A", "1", "C"}}, - }, { - "seq: [A,1,C]", - map[string][]int{"seq": []int{1}}, - }, { - "seq: [A,1,C]", - map[string]interface{}{"seq": []interface{}{"A", 1, "C"}}, - }, - // Block sequence - { - "seq:\n - A\n - B", - map[string]interface{}{"seq": []interface{}{"A", "B"}}, - }, { - "seq:\n - A\n - B\n - C", - map[string][]string{"seq": []string{"A", "B", "C"}}, - }, { - "seq:\n - A\n - 1\n - C", - map[string][]string{"seq": []string{"A", "1", "C"}}, - }, { - "seq:\n - A\n - 1\n - C", - map[string][]int{"seq": []int{1}}, - }, { - "seq:\n - A\n - 1\n - C", - map[string]interface{}{"seq": []interface{}{"A", 1, "C"}}, - }, - - // Literal block scalar - { - "scalar: | # Comment\n\n literal\n\n \ttext\n\n", - map[string]string{"scalar": "\nliteral\n\n\ttext\n"}, - }, - - // Folded block scalar - { - "scalar: > # Comment\n\n folded\n line\n \n next\n line\n * one\n * two\n\n last\n line\n\n", - map[string]string{"scalar": "\nfolded line\nnext line\n * one\n * two\n\nlast line\n"}, - }, - - // Map inside interface with no type hints. - { - "a: {b: c}", - map[interface{}]interface{}{"a": map[interface{}]interface{}{"b": "c"}}, - }, - - // Structs and type conversions. - { - "hello: world", - &struct{ Hello string }{"world"}, - }, { - "a: {b: c}", - &struct{ A struct{ B string } }{struct{ B string }{"c"}}, - }, { - "a: {b: c}", - &struct{ A *struct{ B string } }{&struct{ B string }{"c"}}, - }, { - "a: {b: c}", - &struct{ A map[string]string }{map[string]string{"b": "c"}}, - }, { - "a: {b: c}", - &struct{ A *map[string]string }{&map[string]string{"b": "c"}}, - }, { - "a:", - &struct{ A map[string]string }{}, - }, { - "a: 1", - &struct{ A int }{1}, - }, { - "a: 1", - &struct{ A float64 }{1}, - }, { - "a: 1.0", - &struct{ A int }{1}, - }, { - "a: 1.0", - &struct{ A uint }{1}, - }, { - "a: [1, 2]", - &struct{ A []int }{[]int{1, 2}}, - }, { - "a: 1", - &struct{ B int }{0}, - }, { - "a: 1", - &struct { - B int "a" - }{1}, - }, { - "a: y", - &struct{ A bool }{true}, - }, - - // Some cross type conversions - { - "v: 42", - map[string]uint{"v": 42}, - }, { - "v: -42", - map[string]uint{}, - }, { - "v: 4294967296", - map[string]uint64{"v": 4294967296}, - }, { - "v: -4294967296", - map[string]uint64{}, - }, - - // int - { - "int_max: 2147483647", - map[string]int{"int_max": math.MaxInt32}, - }, - { - "int_min: -2147483648", - map[string]int{"int_min": math.MinInt32}, - }, - { - "int_overflow: 9223372036854775808", // math.MaxInt64 + 1 - map[string]int{}, - }, - - // int64 - { - "int64_max: 9223372036854775807", - map[string]int64{"int64_max": math.MaxInt64}, - }, - { - "int64_max_base2: 0b111111111111111111111111111111111111111111111111111111111111111", - map[string]int64{"int64_max_base2": math.MaxInt64}, - }, - { - "int64_min: -9223372036854775808", - map[string]int64{"int64_min": math.MinInt64}, - }, - { - "int64_neg_base2: -0b111111111111111111111111111111111111111111111111111111111111111", - map[string]int64{"int64_neg_base2": -math.MaxInt64}, - }, - { - "int64_overflow: 9223372036854775808", // math.MaxInt64 + 1 - map[string]int64{}, - }, - - // uint - { - "uint_min: 0", - map[string]uint{"uint_min": 0}, - }, - { - "uint_max: 4294967295", - map[string]uint{"uint_max": math.MaxUint32}, - }, - { - "uint_underflow: -1", - map[string]uint{}, - }, - - // uint64 - { - "uint64_min: 0", - map[string]uint{"uint64_min": 0}, - }, - { - "uint64_max: 18446744073709551615", - map[string]uint64{"uint64_max": math.MaxUint64}, - }, - { - "uint64_max_base2: 0b1111111111111111111111111111111111111111111111111111111111111111", - map[string]uint64{"uint64_max_base2": math.MaxUint64}, - }, - { - "uint64_maxint64: 9223372036854775807", - map[string]uint64{"uint64_maxint64": math.MaxInt64}, - }, - { - "uint64_underflow: -1", - map[string]uint64{}, - }, - - // float32 - { - "float32_max: 3.40282346638528859811704183484516925440e+38", - map[string]float32{"float32_max": math.MaxFloat32}, - }, - { - "float32_nonzero: 1.401298464324817070923729583289916131280e-45", - map[string]float32{"float32_nonzero": math.SmallestNonzeroFloat32}, - }, - { - "float32_maxuint64: 18446744073709551615", - map[string]float32{"float32_maxuint64": float32(math.MaxUint64)}, - }, - { - "float32_maxuint64+1: 18446744073709551616", - map[string]float32{"float32_maxuint64+1": float32(math.MaxUint64 + 1)}, - }, - - // float64 - { - "float64_max: 1.797693134862315708145274237317043567981e+308", - map[string]float64{"float64_max": math.MaxFloat64}, - }, - { - "float64_nonzero: 4.940656458412465441765687928682213723651e-324", - map[string]float64{"float64_nonzero": math.SmallestNonzeroFloat64}, - }, - { - "float64_maxuint64: 18446744073709551615", - map[string]float64{"float64_maxuint64": float64(math.MaxUint64)}, - }, - { - "float64_maxuint64+1: 18446744073709551616", - map[string]float64{"float64_maxuint64+1": float64(math.MaxUint64 + 1)}, - }, - - // Overflow cases. - { - "v: 4294967297", - map[string]int32{}, - }, { - "v: 128", - map[string]int8{}, - }, - - // Quoted values. - { - "'1': '\"2\"'", - map[interface{}]interface{}{"1": "\"2\""}, - }, { - "v:\n- A\n- 'B\n\n C'\n", - map[string][]string{"v": []string{"A", "B\nC"}}, - }, - - // Explicit tags. - { - "v: !!float '1.1'", - map[string]interface{}{"v": 1.1}, - }, { - "v: !!null ''", - map[string]interface{}{"v": nil}, - }, { - "%TAG !y! tag:yaml.org,2002:\n---\nv: !y!int '1'", - map[string]interface{}{"v": 1}, - }, - - // Anchors and aliases. - { - "a: &x 1\nb: &y 2\nc: *x\nd: *y\n", - &struct{ A, B, C, D int }{1, 2, 1, 2}, - }, { - "a: &a {c: 1}\nb: *a", - &struct { - A, B struct { - C int - } - }{struct{ C int }{1}, struct{ C int }{1}}, - }, { - "a: &a [1, 2]\nb: *a", - &struct{ B []int }{[]int{1, 2}}, - }, { - "b: *a\na: &a {c: 1}", - &struct { - A, B struct { - C int - } - }{struct{ C int }{1}, struct{ C int }{1}}, - }, - - // Bug #1133337 - { - "foo: ''", - map[string]*string{"foo": new(string)}, - }, { - "foo: null", - map[string]string{"foo": ""}, - }, { - "foo: null", - map[string]interface{}{"foo": nil}, - }, - - // Ignored field - { - "a: 1\nb: 2\n", - &struct { - A int - B int "-" - }{1, 0}, - }, - - // Bug #1191981 - { - "" + - "%YAML 1.1\n" + - "--- !!str\n" + - `"Generic line break (no glyph)\n\` + "\n" + - ` Generic line break (glyphed)\n\` + "\n" + - ` Line separator\u2028\` + "\n" + - ` Paragraph separator\u2029"` + "\n", - "" + - "Generic line break (no glyph)\n" + - "Generic line break (glyphed)\n" + - "Line separator\u2028Paragraph separator\u2029", - }, - - // Struct inlining - { - "a: 1\nb: 2\nc: 3\n", - &struct { - A int - C inlineB `yaml:",inline"` - }{1, inlineB{2, inlineC{3}}}, - }, - - // Map inlining - { - "a: 1\nb: 2\nc: 3\n", - &struct { - A int - C map[string]int `yaml:",inline"` - }{1, map[string]int{"b": 2, "c": 3}}, - }, - - // bug 1243827 - { - "a: -b_c", - map[string]interface{}{"a": "-b_c"}, - }, - { - "a: +b_c", - map[string]interface{}{"a": "+b_c"}, - }, - { - "a: 50cent_of_dollar", - map[string]interface{}{"a": "50cent_of_dollar"}, - }, - - // Duration - { - "a: 3s", - map[string]time.Duration{"a": 3 * time.Second}, - }, - - // Issue #24. - { - "a: ", - map[string]string{"a": ""}, - }, - - // Base 60 floats are obsolete and unsupported. - { - "a: 1:1\n", - map[string]string{"a": "1:1"}, - }, - - // Binary data. - { - "a: !!binary gIGC\n", - map[string]string{"a": "\x80\x81\x82"}, - }, { - "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n", - map[string]string{"a": strings.Repeat("\x90", 54)}, - }, { - "a: !!binary |\n " + strings.Repeat("A", 70) + "\n ==\n", - map[string]string{"a": strings.Repeat("\x00", 52)}, - }, - - // Ordered maps. - { - "{b: 2, a: 1, d: 4, c: 3, sub: {e: 5}}", - &yaml.MapSlice{{"b", 2}, {"a", 1}, {"d", 4}, {"c", 3}, {"sub", yaml.MapSlice{{"e", 5}}}}, - }, - - // Issue #39. - { - "a:\n b:\n c: d\n", - map[string]struct{ B interface{} }{"a": {map[interface{}]interface{}{"c": "d"}}}, - }, - - // Custom map type. - { - "a: {b: c}", - M{"a": M{"b": "c"}}, - }, - - // Support encoding.TextUnmarshaler. - { - "a: 1.2.3.4\n", - map[string]net.IP{"a": net.IPv4(1, 2, 3, 4)}, - }, - { - "a: 2015-02-24T18:19:39Z\n", - map[string]time.Time{"a": time.Unix(1424801979, 0).In(time.UTC)}, - }, - - // Encode empty lists as zero-length slices. - { - "a: []", - &struct{ A []int }{[]int{}}, - }, - - // UTF-16-LE - { - "\xff\xfe\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00\n\x00", - M{"ñoño": "very yes"}, - }, - // UTF-16-LE with surrogate. - { - "\xff\xfe\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00 \x00=\xd8\xd4\xdf\n\x00", - M{"ñoño": "very yes 🟔"}, - }, - - // UTF-16-BE - { - "\xfe\xff\x00\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00\n", - M{"ñoño": "very yes"}, - }, - // UTF-16-BE with surrogate. - { - "\xfe\xff\x00\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00 \xd8=\xdf\xd4\x00\n", - M{"ñoño": "very yes 🟔"}, - }, - - // YAML Float regex shouldn't match this - { - "a: 123456e1\n", - M{"a": "123456e1"}, - }, { - "a: 123456E1\n", - M{"a": "123456E1"}, - }, -} - -type M map[interface{}]interface{} - -type inlineB struct { - B int - inlineC `yaml:",inline"` -} - -type inlineC struct { - C int -} - -func (s *S) TestUnmarshal(c *C) { - for _, item := range unmarshalTests { - t := reflect.ValueOf(item.value).Type() - var value interface{} - switch t.Kind() { - case reflect.Map: - value = reflect.MakeMap(t).Interface() - case reflect.String: - value = reflect.New(t).Interface() - case reflect.Ptr: - value = reflect.New(t.Elem()).Interface() - default: - c.Fatalf("missing case for %s", t) - } - err := yaml.Unmarshal([]byte(item.data), value) - if _, ok := err.(*yaml.TypeError); !ok { - c.Assert(err, IsNil) - } - if t.Kind() == reflect.String { - c.Assert(*value.(*string), Equals, item.value) - } else { - c.Assert(value, DeepEquals, item.value) - } - } -} - -func (s *S) TestUnmarshalNaN(c *C) { - value := map[string]interface{}{} - err := yaml.Unmarshal([]byte("notanum: .NaN"), &value) - c.Assert(err, IsNil) - c.Assert(math.IsNaN(value["notanum"].(float64)), Equals, true) -} - -var unmarshalErrorTests = []struct { - data, error string -}{ - {"v: !!float 'error'", "yaml: cannot decode !!str `error` as a !!float"}, - {"v: [A,", "yaml: line 1: did not find expected node content"}, - {"v:\n- [A,", "yaml: line 2: did not find expected node content"}, - {"a: *b\n", "yaml: unknown anchor 'b' referenced"}, - {"a: &a\n b: *a\n", "yaml: anchor 'a' value contains itself"}, - {"value: -", "yaml: block sequence entries are not allowed in this context"}, - {"a: !!binary ==", "yaml: !!binary value contains invalid base64 data"}, - {"{[.]}", `yaml: invalid map key: \[\]interface \{\}\{"\."\}`}, - {"{{.}}", `yaml: invalid map key: map\[interface\ \{\}\]interface \{\}\{".":interface \{\}\(nil\)\}`}, -} - -func (s *S) TestUnmarshalErrors(c *C) { - for _, item := range unmarshalErrorTests { - var value interface{} - err := yaml.Unmarshal([]byte(item.data), &value) - c.Assert(err, ErrorMatches, item.error, Commentf("Partial unmarshal: %#v", value)) - } -} - -var unmarshalerTests = []struct { - data, tag string - value interface{} -}{ - {"_: {hi: there}", "!!map", map[interface{}]interface{}{"hi": "there"}}, - {"_: [1,A]", "!!seq", []interface{}{1, "A"}}, - {"_: 10", "!!int", 10}, - {"_: null", "!!null", nil}, - {`_: BAR!`, "!!str", "BAR!"}, - {`_: "BAR!"`, "!!str", "BAR!"}, - {"_: !!foo 'BAR!'", "!!foo", "BAR!"}, - {`_: ""`, "!!str", ""}, -} - -var unmarshalerResult = map[int]error{} - -type unmarshalerType struct { - value interface{} -} - -func (o *unmarshalerType) UnmarshalYAML(unmarshal func(v interface{}) error) error { - if err := unmarshal(&o.value); err != nil { - return err - } - if i, ok := o.value.(int); ok { - if result, ok := unmarshalerResult[i]; ok { - return result - } - } - return nil -} - -type unmarshalerPointer struct { - Field *unmarshalerType "_" -} - -type unmarshalerValue struct { - Field unmarshalerType "_" -} - -func (s *S) TestUnmarshalerPointerField(c *C) { - for _, item := range unmarshalerTests { - obj := &unmarshalerPointer{} - err := yaml.Unmarshal([]byte(item.data), obj) - c.Assert(err, IsNil) - if item.value == nil { - c.Assert(obj.Field, IsNil) - } else { - c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value)) - c.Assert(obj.Field.value, DeepEquals, item.value) - } - } -} - -func (s *S) TestUnmarshalerValueField(c *C) { - for _, item := range unmarshalerTests { - obj := &unmarshalerValue{} - err := yaml.Unmarshal([]byte(item.data), obj) - c.Assert(err, IsNil) - c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value)) - c.Assert(obj.Field.value, DeepEquals, item.value) - } -} - -func (s *S) TestUnmarshalerWholeDocument(c *C) { - obj := &unmarshalerType{} - err := yaml.Unmarshal([]byte(unmarshalerTests[0].data), obj) - c.Assert(err, IsNil) - value, ok := obj.value.(map[interface{}]interface{}) - c.Assert(ok, Equals, true, Commentf("value: %#v", obj.value)) - c.Assert(value["_"], DeepEquals, unmarshalerTests[0].value) -} - -func (s *S) TestUnmarshalerTypeError(c *C) { - unmarshalerResult[2] = &yaml.TypeError{[]string{"foo"}} - unmarshalerResult[4] = &yaml.TypeError{[]string{"bar"}} - defer func() { - delete(unmarshalerResult, 2) - delete(unmarshalerResult, 4) - }() - - type T struct { - Before int - After int - M map[string]*unmarshalerType - } - var v T - data := `{before: A, m: {abc: 1, def: 2, ghi: 3, jkl: 4}, after: B}` - err := yaml.Unmarshal([]byte(data), &v) - c.Assert(err, ErrorMatches, ""+ - "yaml: unmarshal errors:\n"+ - " line 1: cannot unmarshal !!str `A` into int\n"+ - " foo\n"+ - " bar\n"+ - " line 1: cannot unmarshal !!str `B` into int") - c.Assert(v.M["abc"], NotNil) - c.Assert(v.M["def"], IsNil) - c.Assert(v.M["ghi"], NotNil) - c.Assert(v.M["jkl"], IsNil) - - c.Assert(v.M["abc"].value, Equals, 1) - c.Assert(v.M["ghi"].value, Equals, 3) -} - -type proxyTypeError struct{} - -func (v *proxyTypeError) UnmarshalYAML(unmarshal func(interface{}) error) error { - var s string - var a int32 - var b int64 - if err := unmarshal(&s); err != nil { - panic(err) - } - if s == "a" { - if err := unmarshal(&b); err == nil { - panic("should have failed") - } - return unmarshal(&a) - } - if err := unmarshal(&a); err == nil { - panic("should have failed") - } - return unmarshal(&b) -} - -func (s *S) TestUnmarshalerTypeErrorProxying(c *C) { - type T struct { - Before int - After int - M map[string]*proxyTypeError - } - var v T - data := `{before: A, m: {abc: a, def: b}, after: B}` - err := yaml.Unmarshal([]byte(data), &v) - c.Assert(err, ErrorMatches, ""+ - "yaml: unmarshal errors:\n"+ - " line 1: cannot unmarshal !!str `A` into int\n"+ - " line 1: cannot unmarshal !!str `a` into int32\n"+ - " line 1: cannot unmarshal !!str `b` into int64\n"+ - " line 1: cannot unmarshal !!str `B` into int") -} - -type failingUnmarshaler struct{} - -var failingErr = errors.New("failingErr") - -func (ft *failingUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error { - return failingErr -} - -func (s *S) TestUnmarshalerError(c *C) { - err := yaml.Unmarshal([]byte("a: b"), &failingUnmarshaler{}) - c.Assert(err, Equals, failingErr) -} - -type sliceUnmarshaler []int - -func (su *sliceUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error { - var slice []int - err := unmarshal(&slice) - if err == nil { - *su = slice - return nil - } - - var intVal int - err = unmarshal(&intVal) - if err == nil { - *su = []int{intVal} - return nil - } - - return err -} - -func (s *S) TestUnmarshalerRetry(c *C) { - var su sliceUnmarshaler - err := yaml.Unmarshal([]byte("[1, 2, 3]"), &su) - c.Assert(err, IsNil) - c.Assert(su, DeepEquals, sliceUnmarshaler([]int{1, 2, 3})) - - err = yaml.Unmarshal([]byte("1"), &su) - c.Assert(err, IsNil) - c.Assert(su, DeepEquals, sliceUnmarshaler([]int{1})) -} - -// From http://yaml.org/type/merge.html -var mergeTests = ` -anchors: - list: - - &CENTER { "x": 1, "y": 2 } - - &LEFT { "x": 0, "y": 2 } - - &BIG { "r": 10 } - - &SMALL { "r": 1 } - -# All the following maps are equal: - -plain: - # Explicit keys - "x": 1 - "y": 2 - "r": 10 - label: center/big - -mergeOne: - # Merge one map - << : *CENTER - "r": 10 - label: center/big - -mergeMultiple: - # Merge multiple maps - << : [ *CENTER, *BIG ] - label: center/big - -override: - # Override - << : [ *BIG, *LEFT, *SMALL ] - "x": 1 - label: center/big - -shortTag: - # Explicit short merge tag - !!merge "<<" : [ *CENTER, *BIG ] - label: center/big - -longTag: - # Explicit merge long tag - ! "<<" : [ *CENTER, *BIG ] - label: center/big - -inlineMap: - # Inlined map - << : {"x": 1, "y": 2, "r": 10} - label: center/big - -inlineSequenceMap: - # Inlined map in sequence - << : [ *CENTER, {"r": 10} ] - label: center/big -` - -func (s *S) TestMerge(c *C) { - var want = map[interface{}]interface{}{ - "x": 1, - "y": 2, - "r": 10, - "label": "center/big", - } - - var m map[interface{}]interface{} - err := yaml.Unmarshal([]byte(mergeTests), &m) - c.Assert(err, IsNil) - for name, test := range m { - if name == "anchors" { - continue - } - c.Assert(test, DeepEquals, want, Commentf("test %q failed", name)) - } -} - -func (s *S) TestMergeStruct(c *C) { - type Data struct { - X, Y, R int - Label string - } - want := Data{1, 2, 10, "center/big"} - - var m map[string]Data - err := yaml.Unmarshal([]byte(mergeTests), &m) - c.Assert(err, IsNil) - for name, test := range m { - if name == "anchors" { - continue - } - c.Assert(test, Equals, want, Commentf("test %q failed", name)) - } -} - -var unmarshalNullTests = []func() interface{}{ - func() interface{} { var v interface{}; v = "v"; return &v }, - func() interface{} { var s = "s"; return &s }, - func() interface{} { var s = "s"; sptr := &s; return &sptr }, - func() interface{} { var i = 1; return &i }, - func() interface{} { var i = 1; iptr := &i; return &iptr }, - func() interface{} { m := map[string]int{"s": 1}; return &m }, - func() interface{} { m := map[string]int{"s": 1}; return m }, -} - -func (s *S) TestUnmarshalNull(c *C) { - for _, test := range unmarshalNullTests { - item := test() - zero := reflect.Zero(reflect.TypeOf(item).Elem()).Interface() - err := yaml.Unmarshal([]byte("null"), item) - c.Assert(err, IsNil) - if reflect.TypeOf(item).Kind() == reflect.Map { - c.Assert(reflect.ValueOf(item).Interface(), DeepEquals, reflect.MakeMap(reflect.TypeOf(item)).Interface()) - } else { - c.Assert(reflect.ValueOf(item).Elem().Interface(), DeepEquals, zero) - } - } -} - -func (s *S) TestUnmarshalSliceOnPreset(c *C) { - // Issue #48. - v := struct{ A []int }{[]int{1}} - yaml.Unmarshal([]byte("a: [2]"), &v) - c.Assert(v.A, DeepEquals, []int{2}) -} - -//var data []byte -//func init() { -// var err error -// data, err = ioutil.ReadFile("/tmp/file.yaml") -// if err != nil { -// panic(err) -// } -//} -// -//func (s *S) BenchmarkUnmarshal(c *C) { -// var err error -// for i := 0; i < c.N; i++ { -// var v map[string]interface{} -// err = yaml.Unmarshal(data, &v) -// } -// if err != nil { -// panic(err) -// } -//} -// -//func (s *S) BenchmarkMarshal(c *C) { -// var v map[string]interface{} -// yaml.Unmarshal(data, &v) -// c.ResetTimer() -// for i := 0; i < c.N; i++ { -// yaml.Marshal(&v) -// } -//} diff --git a/vendor/github.com/go-yaml/yaml/encode_test.go b/vendor/github.com/go-yaml/yaml/encode_test.go deleted file mode 100644 index 84099bd3..00000000 --- a/vendor/github.com/go-yaml/yaml/encode_test.go +++ /dev/null @@ -1,501 +0,0 @@ -package yaml_test - -import ( - "fmt" - "math" - "strconv" - "strings" - "time" - - . "gopkg.in/check.v1" - "gopkg.in/yaml.v2" - "net" - "os" -) - -var marshalIntTest = 123 - -var marshalTests = []struct { - value interface{} - data string -}{ - { - nil, - "null\n", - }, { - &struct{}{}, - "{}\n", - }, { - map[string]string{"v": "hi"}, - "v: hi\n", - }, { - map[string]interface{}{"v": "hi"}, - "v: hi\n", - }, { - map[string]string{"v": "true"}, - "v: \"true\"\n", - }, { - map[string]string{"v": "false"}, - "v: \"false\"\n", - }, { - map[string]interface{}{"v": true}, - "v: true\n", - }, { - map[string]interface{}{"v": false}, - "v: false\n", - }, { - map[string]interface{}{"v": 10}, - "v: 10\n", - }, { - map[string]interface{}{"v": -10}, - "v: -10\n", - }, { - map[string]uint{"v": 42}, - "v: 42\n", - }, { - map[string]interface{}{"v": int64(4294967296)}, - "v: 4294967296\n", - }, { - map[string]int64{"v": int64(4294967296)}, - "v: 4294967296\n", - }, { - map[string]uint64{"v": 4294967296}, - "v: 4294967296\n", - }, { - map[string]interface{}{"v": "10"}, - "v: \"10\"\n", - }, { - map[string]interface{}{"v": 0.1}, - "v: 0.1\n", - }, { - map[string]interface{}{"v": float64(0.1)}, - "v: 0.1\n", - }, { - map[string]interface{}{"v": -0.1}, - "v: -0.1\n", - }, { - map[string]interface{}{"v": math.Inf(+1)}, - "v: .inf\n", - }, { - map[string]interface{}{"v": math.Inf(-1)}, - "v: -.inf\n", - }, { - map[string]interface{}{"v": math.NaN()}, - "v: .nan\n", - }, { - map[string]interface{}{"v": nil}, - "v: null\n", - }, { - map[string]interface{}{"v": ""}, - "v: \"\"\n", - }, { - map[string][]string{"v": []string{"A", "B"}}, - "v:\n- A\n- B\n", - }, { - map[string][]string{"v": []string{"A", "B\nC"}}, - "v:\n- A\n- |-\n B\n C\n", - }, { - map[string][]interface{}{"v": []interface{}{"A", 1, map[string][]int{"B": []int{2, 3}}}}, - "v:\n- A\n- 1\n- B:\n - 2\n - 3\n", - }, { - map[string]interface{}{"a": map[interface{}]interface{}{"b": "c"}}, - "a:\n b: c\n", - }, { - map[string]interface{}{"a": "-"}, - "a: '-'\n", - }, - - // Simple values. - { - &marshalIntTest, - "123\n", - }, - - // Structures - { - &struct{ Hello string }{"world"}, - "hello: world\n", - }, { - &struct { - A struct { - B string - } - }{struct{ B string }{"c"}}, - "a:\n b: c\n", - }, { - &struct { - A *struct { - B string - } - }{&struct{ B string }{"c"}}, - "a:\n b: c\n", - }, { - &struct { - A *struct { - B string - } - }{}, - "a: null\n", - }, { - &struct{ A int }{1}, - "a: 1\n", - }, { - &struct{ A []int }{[]int{1, 2}}, - "a:\n- 1\n- 2\n", - }, { - &struct { - B int "a" - }{1}, - "a: 1\n", - }, { - &struct{ A bool }{true}, - "a: true\n", - }, - - // Conditional flag - { - &struct { - A int "a,omitempty" - B int "b,omitempty" - }{1, 0}, - "a: 1\n", - }, { - &struct { - A int "a,omitempty" - B int "b,omitempty" - }{0, 0}, - "{}\n", - }, { - &struct { - A *struct{ X, y int } "a,omitempty,flow" - }{&struct{ X, y int }{1, 2}}, - "a: {x: 1}\n", - }, { - &struct { - A *struct{ X, y int } "a,omitempty,flow" - }{nil}, - "{}\n", - }, { - &struct { - A *struct{ X, y int } "a,omitempty,flow" - }{&struct{ X, y int }{}}, - "a: {x: 0}\n", - }, { - &struct { - A struct{ X, y int } "a,omitempty,flow" - }{struct{ X, y int }{1, 2}}, - "a: {x: 1}\n", - }, { - &struct { - A struct{ X, y int } "a,omitempty,flow" - }{struct{ X, y int }{0, 1}}, - "{}\n", - }, { - &struct { - A float64 "a,omitempty" - B float64 "b,omitempty" - }{1, 0}, - "a: 1\n", - }, - - // Flow flag - { - &struct { - A []int "a,flow" - }{[]int{1, 2}}, - "a: [1, 2]\n", - }, { - &struct { - A map[string]string "a,flow" - }{map[string]string{"b": "c", "d": "e"}}, - "a: {b: c, d: e}\n", - }, { - &struct { - A struct { - B, D string - } "a,flow" - }{struct{ B, D string }{"c", "e"}}, - "a: {b: c, d: e}\n", - }, - - // Unexported field - { - &struct { - u int - A int - }{0, 1}, - "a: 1\n", - }, - - // Ignored field - { - &struct { - A int - B int "-" - }{1, 2}, - "a: 1\n", - }, - - // Struct inlining - { - &struct { - A int - C inlineB `yaml:",inline"` - }{1, inlineB{2, inlineC{3}}}, - "a: 1\nb: 2\nc: 3\n", - }, - - // Map inlining - { - &struct { - A int - C map[string]int `yaml:",inline"` - }{1, map[string]int{"b": 2, "c": 3}}, - "a: 1\nb: 2\nc: 3\n", - }, - - // Duration - { - map[string]time.Duration{"a": 3 * time.Second}, - "a: 3s\n", - }, - - // Issue #24: bug in map merging logic. - { - map[string]string{"a": ""}, - "a: \n", - }, - - // Issue #34: marshal unsupported base 60 floats quoted for compatibility - // with old YAML 1.1 parsers. - { - map[string]string{"a": "1:1"}, - "a: \"1:1\"\n", - }, - - // Binary data. - { - map[string]string{"a": "\x00"}, - "a: \"\\0\"\n", - }, { - map[string]string{"a": "\x80\x81\x82"}, - "a: !!binary gIGC\n", - }, { - map[string]string{"a": strings.Repeat("\x90", 54)}, - "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n", - }, - - // Ordered maps. - { - &yaml.MapSlice{{"b", 2}, {"a", 1}, {"d", 4}, {"c", 3}, {"sub", yaml.MapSlice{{"e", 5}}}}, - "b: 2\na: 1\nd: 4\nc: 3\nsub:\n e: 5\n", - }, - - // Encode unicode as utf-8 rather than in escaped form. - { - map[string]string{"a": "你好"}, - "a: 你好\n", - }, - - // Support encoding.TextMarshaler. - { - map[string]net.IP{"a": net.IPv4(1, 2, 3, 4)}, - "a: 1.2.3.4\n", - }, - { - map[string]time.Time{"a": time.Unix(1424801979, 0)}, - "a: 2015-02-24T18:19:39Z\n", - }, - - // Ensure strings containing ": " are quoted (reported as PR #43, but not reproducible). - { - map[string]string{"a": "b: c"}, - "a: 'b: c'\n", - }, - - // Containing hash mark ('#') in string should be quoted - { - map[string]string{"a": "Hello #comment"}, - "a: 'Hello #comment'\n", - }, - { - map[string]string{"a": "你好 #comment"}, - "a: '你好 #comment'\n", - }, -} - -func (s *S) TestMarshal(c *C) { - defer os.Setenv("TZ", os.Getenv("TZ")) - os.Setenv("TZ", "UTC") - for _, item := range marshalTests { - data, err := yaml.Marshal(item.value) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, item.data) - } -} - -var marshalErrorTests = []struct { - value interface{} - error string - panic string -}{{ - value: &struct { - B int - inlineB ",inline" - }{1, inlineB{2, inlineC{3}}}, - panic: `Duplicated key 'b' in struct struct \{ B int; .*`, -}, { - value: &struct { - A int - B map[string]int ",inline" - }{1, map[string]int{"a": 2}}, - panic: `Can't have key "a" in inlined map; conflicts with struct field`, -}} - -func (s *S) TestMarshalErrors(c *C) { - for _, item := range marshalErrorTests { - if item.panic != "" { - c.Assert(func() { yaml.Marshal(item.value) }, PanicMatches, item.panic) - } else { - _, err := yaml.Marshal(item.value) - c.Assert(err, ErrorMatches, item.error) - } - } -} - -func (s *S) TestMarshalTypeCache(c *C) { - var data []byte - var err error - func() { - type T struct{ A int } - data, err = yaml.Marshal(&T{}) - c.Assert(err, IsNil) - }() - func() { - type T struct{ B int } - data, err = yaml.Marshal(&T{}) - c.Assert(err, IsNil) - }() - c.Assert(string(data), Equals, "b: 0\n") -} - -var marshalerTests = []struct { - data string - value interface{} -}{ - {"_:\n hi: there\n", map[interface{}]interface{}{"hi": "there"}}, - {"_:\n- 1\n- A\n", []interface{}{1, "A"}}, - {"_: 10\n", 10}, - {"_: null\n", nil}, - {"_: BAR!\n", "BAR!"}, -} - -type marshalerType struct { - value interface{} -} - -func (o marshalerType) MarshalText() ([]byte, error) { - panic("MarshalText called on type with MarshalYAML") -} - -func (o marshalerType) MarshalYAML() (interface{}, error) { - return o.value, nil -} - -type marshalerValue struct { - Field marshalerType "_" -} - -func (s *S) TestMarshaler(c *C) { - for _, item := range marshalerTests { - obj := &marshalerValue{} - obj.Field.value = item.value - data, err := yaml.Marshal(obj) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, string(item.data)) - } -} - -func (s *S) TestMarshalerWholeDocument(c *C) { - obj := &marshalerType{} - obj.value = map[string]string{"hello": "world!"} - data, err := yaml.Marshal(obj) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, "hello: world!\n") -} - -type failingMarshaler struct{} - -func (ft *failingMarshaler) MarshalYAML() (interface{}, error) { - return nil, failingErr -} - -func (s *S) TestMarshalerError(c *C) { - _, err := yaml.Marshal(&failingMarshaler{}) - c.Assert(err, Equals, failingErr) -} - -func (s *S) TestSortedOutput(c *C) { - order := []interface{}{ - false, - true, - 1, - uint(1), - 1.0, - 1.1, - 1.2, - 2, - uint(2), - 2.0, - 2.1, - "", - ".1", - ".2", - ".a", - "1", - "2", - "a!10", - "a/2", - "a/10", - "a~10", - "ab/1", - "b/1", - "b/01", - "b/2", - "b/02", - "b/3", - "b/03", - "b1", - "b01", - "b3", - "c2.10", - "c10.2", - "d1", - "d12", - "d12a", - } - m := make(map[interface{}]int) - for _, k := range order { - m[k] = 1 - } - data, err := yaml.Marshal(m) - c.Assert(err, IsNil) - out := "\n" + string(data) - last := 0 - for i, k := range order { - repr := fmt.Sprint(k) - if s, ok := k.(string); ok { - if _, err = strconv.ParseFloat(repr, 32); s == "" || err == nil { - repr = `"` + repr + `"` - } - } - index := strings.Index(out, "\n"+repr+":") - if index == -1 { - c.Fatalf("%#v is not in the output: %#v", k, out) - } - if index < last { - c.Fatalf("%#v was generated before %#v: %q", k, order[i-1], out) - } - last = index - } -} diff --git a/vendor/github.com/go-yaml/yaml/suite_test.go b/vendor/github.com/go-yaml/yaml/suite_test.go deleted file mode 100644 index c5cf1ed4..00000000 --- a/vendor/github.com/go-yaml/yaml/suite_test.go +++ /dev/null @@ -1,12 +0,0 @@ -package yaml_test - -import ( - . "gopkg.in/check.v1" - "testing" -) - -func Test(t *testing.T) { TestingT(t) } - -type S struct{} - -var _ = Suite(&S{}) diff --git a/vendor/github.com/golang/protobuf/.gitignore b/vendor/github.com/golang/protobuf/.gitignore deleted file mode 100644 index 8f5b596b..00000000 --- a/vendor/github.com/golang/protobuf/.gitignore +++ /dev/null @@ -1,16 +0,0 @@ -.DS_Store -*.[568ao] -*.ao -*.so -*.pyc -._* -.nfs.* -[568a].out -*~ -*.orig -core -_obj -_test -_testmain.go -protoc-gen-go/testdata/multi/*.pb.go -_conformance/_conformance diff --git a/vendor/github.com/golang/protobuf/.travis.yml b/vendor/github.com/golang/protobuf/.travis.yml deleted file mode 100644 index 93c67805..00000000 --- a/vendor/github.com/golang/protobuf/.travis.yml +++ /dev/null @@ -1,18 +0,0 @@ -sudo: false -language: go -go: -- 1.6.x -- 1.7.x -- 1.8.x -- 1.9.x - -install: - - go get -v -d -t github.com/golang/protobuf/... - - curl -L https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip -o /tmp/protoc.zip - - unzip /tmp/protoc.zip -d $HOME/protoc - -env: - - PATH=$HOME/protoc/bin:$PATH - -script: - - make all test diff --git a/vendor/github.com/golang/protobuf/Make.protobuf b/vendor/github.com/golang/protobuf/Make.protobuf deleted file mode 100644 index 15071de1..00000000 --- a/vendor/github.com/golang/protobuf/Make.protobuf +++ /dev/null @@ -1,40 +0,0 @@ -# Go support for Protocol Buffers - Google's data interchange format -# -# Copyright 2010 The Go Authors. All rights reserved. -# https://github.com/golang/protobuf -# -# 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. - -# Includable Makefile to add a rule for generating .pb.go files from .proto files -# (Google protocol buffer descriptions). -# Typical use if myproto.proto is a file in package mypackage in this directory: -# -# include $(GOROOT)/src/pkg/github.com/golang/protobuf/Make.protobuf - -%.pb.go: %.proto - protoc --go_out=. $< - diff --git a/vendor/github.com/golang/protobuf/Makefile b/vendor/github.com/golang/protobuf/Makefile deleted file mode 100644 index a1421d8b..00000000 --- a/vendor/github.com/golang/protobuf/Makefile +++ /dev/null @@ -1,55 +0,0 @@ -# Go support for Protocol Buffers - Google's data interchange format -# -# Copyright 2010 The Go Authors. All rights reserved. -# https://github.com/golang/protobuf -# -# 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. - - -all: install - -install: - go install ./proto ./jsonpb ./ptypes - go install ./protoc-gen-go - -test: - go test ./proto ./jsonpb ./ptypes - make -C protoc-gen-go/testdata test - -clean: - go clean ./... - -nuke: - go clean -i ./... - -regenerate: - make -C protoc-gen-go/descriptor regenerate - make -C protoc-gen-go/plugin regenerate - make -C protoc-gen-go/testdata regenerate - make -C proto/testdata regenerate - make -C jsonpb/jsonpb_test_proto regenerate - make -C _conformance regenerate diff --git a/vendor/github.com/golang/protobuf/README.md b/vendor/github.com/golang/protobuf/README.md deleted file mode 100644 index 795f53f6..00000000 --- a/vendor/github.com/golang/protobuf/README.md +++ /dev/null @@ -1,242 +0,0 @@ -# Go support for Protocol Buffers - -[![Build Status](https://travis-ci.org/golang/protobuf.svg?branch=master)](https://travis-ci.org/golang/protobuf) - -Google's data interchange format. -Copyright 2010 The Go Authors. -https://github.com/golang/protobuf - -This package and the code it generates requires at least Go 1.4. - -This software implements Go bindings for protocol buffers. For -information about protocol buffers themselves, see - https://developers.google.com/protocol-buffers/ - -## Installation ## - -To use this software, you must: -- Install the standard C++ implementation of protocol buffers from - https://developers.google.com/protocol-buffers/ -- Of course, install the Go compiler and tools from - https://golang.org/ - See - https://golang.org/doc/install - for details or, if you are using gccgo, follow the instructions at - https://golang.org/doc/install/gccgo -- Grab the code from the repository and install the proto package. - The simplest way is to run `go get -u github.com/golang/protobuf/protoc-gen-go`. - The compiler plugin, protoc-gen-go, will be installed in $GOBIN, - defaulting to $GOPATH/bin. It must be in your $PATH for the protocol - compiler, protoc, to find it. - -This software has two parts: a 'protocol compiler plugin' that -generates Go source files that, once compiled, can access and manage -protocol buffers; and a library that implements run-time support for -encoding (marshaling), decoding (unmarshaling), and accessing protocol -buffers. - -There is support for gRPC in Go using protocol buffers. -See the note at the bottom of this file for details. - -There are no insertion points in the plugin. - - -## Using protocol buffers with Go ## - -Once the software is installed, there are two steps to using it. -First you must compile the protocol buffer definitions and then import -them, with the support library, into your program. - -To compile the protocol buffer definition, run protoc with the --go_out -parameter set to the directory you want to output the Go code to. - - protoc --go_out=. *.proto - -The generated files will be suffixed .pb.go. See the Test code below -for an example using such a file. - - -The package comment for the proto library contains text describing -the interface provided in Go for protocol buffers. Here is an edited -version. - -========== - -The proto package converts data structures to and from the -wire format of protocol buffers. It works in concert with the -Go source code generated for .proto files by the protocol compiler. - -A summary of the properties of the protocol buffer interface -for a protocol buffer variable v: - - - Names are turned from camel_case to CamelCase for export. - - There are no methods on v to set fields; just treat - them as structure fields. - - There are getters that return a field's value if set, - and return the field's default value if unset. - The getters work even if the receiver is a nil message. - - The zero value for a struct is its correct initialization state. - All desired fields must be set before marshaling. - - A Reset() method will restore a protobuf struct to its zero state. - - Non-repeated fields are pointers to the values; nil means unset. - That is, optional or required field int32 f becomes F *int32. - - Repeated fields are slices. - - Helper functions are available to aid the setting of fields. - Helpers for getting values are superseded by the - GetFoo methods and their use is deprecated. - msg.Foo = proto.String("hello") // set field - - Constants are defined to hold the default values of all fields that - have them. They have the form Default_StructName_FieldName. - Because the getter methods handle defaulted values, - direct use of these constants should be rare. - - Enums are given type names and maps from names to values. - Enum values are prefixed with the enum's type name. Enum types have - a String method, and a Enum method to assist in message construction. - - Nested groups and enums have type names prefixed with the name of - the surrounding message type. - - Extensions are given descriptor names that start with E_, - followed by an underscore-delimited list of the nested messages - that contain it (if any) followed by the CamelCased name of the - extension field itself. HasExtension, ClearExtension, GetExtension - and SetExtension are functions for manipulating extensions. - - Oneof field sets are given a single field in their message, - with distinguished wrapper types for each possible field value. - - Marshal and Unmarshal are functions to encode and decode the wire format. - -When the .proto file specifies `syntax="proto3"`, there are some differences: - - - Non-repeated fields of non-message type are values instead of pointers. - - Enum types do not get an Enum method. - -Consider file test.proto, containing - -```proto - package example; - - enum FOO { X = 17; }; - - message Test { - required string label = 1; - optional int32 type = 2 [default=77]; - repeated int64 reps = 3; - optional group OptionalGroup = 4 { - required string RequiredField = 5; - } - } -``` - -To create and play with a Test object from the example package, - -```go - package main - - import ( - "log" - - "github.com/golang/protobuf/proto" - "path/to/example" - ) - - func main() { - test := &example.Test { - Label: proto.String("hello"), - Type: proto.Int32(17), - Reps: []int64{1, 2, 3}, - Optionalgroup: &example.Test_OptionalGroup { - RequiredField: proto.String("good bye"), - }, - } - data, err := proto.Marshal(test) - if err != nil { - log.Fatal("marshaling error: ", err) - } - newTest := &example.Test{} - err = proto.Unmarshal(data, newTest) - if err != nil { - log.Fatal("unmarshaling error: ", err) - } - // Now test and newTest contain the same data. - if test.GetLabel() != newTest.GetLabel() { - log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) - } - // etc. - } -``` - -## Parameters ## - -To pass extra parameters to the plugin, use a comma-separated -parameter list separated from the output directory by a colon: - - - protoc --go_out=plugins=grpc,import_path=mypackage:. *.proto - - -- `import_prefix=xxx` - a prefix that is added onto the beginning of - all imports. Useful for things like generating protos in a - subdirectory, or regenerating vendored protobufs in-place. -- `import_path=foo/bar` - used as the package if no input files - declare `go_package`. If it contains slashes, everything up to the - rightmost slash is ignored. -- `plugins=plugin1+plugin2` - specifies the list of sub-plugins to - load. The only plugin in this repo is `grpc`. -- `Mfoo/bar.proto=quux/shme` - declares that foo/bar.proto is - associated with Go package quux/shme. This is subject to the - import_prefix parameter. - -## gRPC Support ## - -If a proto file specifies RPC services, protoc-gen-go can be instructed to -generate code compatible with gRPC (http://www.grpc.io/). To do this, pass -the `plugins` parameter to protoc-gen-go; the usual way is to insert it into -the --go_out argument to protoc: - - protoc --go_out=plugins=grpc:. *.proto - -## Compatibility ## - -The library and the generated code are expected to be stable over time. -However, we reserve the right to make breaking changes without notice for the -following reasons: - -- Security. A security issue in the specification or implementation may come to - light whose resolution requires breaking compatibility. We reserve the right - to address such security issues. -- Unspecified behavior. There are some aspects of the Protocol Buffers - specification that are undefined. Programs that depend on such unspecified - behavior may break in future releases. -- Specification errors or changes. If it becomes necessary to address an - inconsistency, incompleteness, or change in the Protocol Buffers - specification, resolving the issue could affect the meaning or legality of - existing programs. We reserve the right to address such issues, including - updating the implementations. -- Bugs. If the library has a bug that violates the specification, a program - that depends on the buggy behavior may break if the bug is fixed. We reserve - the right to fix such bugs. -- Adding methods or fields to generated structs. These may conflict with field - names that already exist in a schema, causing applications to break. When the - code generator encounters a field in the schema that would collide with a - generated field or method name, the code generator will append an underscore - to the generated field or method name. -- Adding, removing, or changing methods or fields in generated structs that - start with `XXX`. These parts of the generated code are exported out of - necessity, but should not be considered part of the public API. -- Adding, removing, or changing unexported symbols in generated code. - -Any breaking changes outside of these will be announced 6 months in advance to -protobuf@googlegroups.com. - -You should, whenever possible, use generated code created by the `protoc-gen-go` -tool built at the same commit as the `proto` package. The `proto` package -declares package-level constants in the form `ProtoPackageIsVersionX`. -Application code and generated code may depend on one of these constants to -ensure that compilation will fail if the available version of the proto library -is too old. Whenever we make a change to the generated code that requires newer -library support, in the same commit we will increment the version number of the -generated code and declare a new package-level constant whose name incorporates -the latest version number. Removing a compatibility constant is considered a -breaking change and would be subject to the announcement policy stated above. - -The `protoc-gen-go/generator` package exposes a plugin interface, -which is used by the gRPC code generation. This interface is not -supported and is subject to incompatible changes without notice. diff --git a/vendor/github.com/golang/protobuf/proto/Makefile b/vendor/github.com/golang/protobuf/proto/Makefile deleted file mode 100644 index e2e0651a..00000000 --- a/vendor/github.com/golang/protobuf/proto/Makefile +++ /dev/null @@ -1,43 +0,0 @@ -# Go support for Protocol Buffers - Google's data interchange format -# -# Copyright 2010 The Go Authors. All rights reserved. -# https://github.com/golang/protobuf -# -# 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. - -install: - go install - -test: install generate-test-pbs - go test - - -generate-test-pbs: - make install - make -C testdata - protoc --go_out=Mtestdata/test.proto=github.com/golang/protobuf/proto/testdata,Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. proto3_proto/proto3.proto - make diff --git a/vendor/github.com/golang/protobuf/proto/all_test.go b/vendor/github.com/golang/protobuf/proto/all_test.go deleted file mode 100644 index 41451a40..00000000 --- a/vendor/github.com/golang/protobuf/proto/all_test.go +++ /dev/null @@ -1,2278 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto_test - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "math" - "math/rand" - "reflect" - "runtime/debug" - "strings" - "testing" - "time" - - . "github.com/golang/protobuf/proto" - . "github.com/golang/protobuf/proto/testdata" -) - -var globalO *Buffer - -func old() *Buffer { - if globalO == nil { - globalO = NewBuffer(nil) - } - globalO.Reset() - return globalO -} - -func equalbytes(b1, b2 []byte, t *testing.T) { - if len(b1) != len(b2) { - t.Errorf("wrong lengths: 2*%d != %d", len(b1), len(b2)) - return - } - for i := 0; i < len(b1); i++ { - if b1[i] != b2[i] { - t.Errorf("bad byte[%d]:%x %x: %s %s", i, b1[i], b2[i], b1, b2) - } - } -} - -func initGoTestField() *GoTestField { - f := new(GoTestField) - f.Label = String("label") - f.Type = String("type") - return f -} - -// These are all structurally equivalent but the tag numbers differ. -// (It's remarkable that required, optional, and repeated all have -// 8 letters.) -func initGoTest_RequiredGroup() *GoTest_RequiredGroup { - return &GoTest_RequiredGroup{ - RequiredField: String("required"), - } -} - -func initGoTest_OptionalGroup() *GoTest_OptionalGroup { - return &GoTest_OptionalGroup{ - RequiredField: String("optional"), - } -} - -func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup { - return &GoTest_RepeatedGroup{ - RequiredField: String("repeated"), - } -} - -func initGoTest(setdefaults bool) *GoTest { - pb := new(GoTest) - if setdefaults { - pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted) - pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted) - pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted) - pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted) - pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted) - pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted) - pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted) - pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted) - pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted) - pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted) - pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted - pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted) - pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted) - } - - pb.Kind = GoTest_TIME.Enum() - pb.RequiredField = initGoTestField() - pb.F_BoolRequired = Bool(true) - pb.F_Int32Required = Int32(3) - pb.F_Int64Required = Int64(6) - pb.F_Fixed32Required = Uint32(32) - pb.F_Fixed64Required = Uint64(64) - pb.F_Uint32Required = Uint32(3232) - pb.F_Uint64Required = Uint64(6464) - pb.F_FloatRequired = Float32(3232) - pb.F_DoubleRequired = Float64(6464) - pb.F_StringRequired = String("string") - pb.F_BytesRequired = []byte("bytes") - pb.F_Sint32Required = Int32(-32) - pb.F_Sint64Required = Int64(-64) - pb.Requiredgroup = initGoTest_RequiredGroup() - - return pb -} - -func fail(msg string, b *bytes.Buffer, s string, t *testing.T) { - data := b.Bytes() - ld := len(data) - ls := len(s) / 2 - - fmt.Printf("fail %s ld=%d ls=%d\n", msg, ld, ls) - - // find the interesting spot - n - n := ls - if ld < ls { - n = ld - } - j := 0 - for i := 0; i < n; i++ { - bs := hex(s[j])*16 + hex(s[j+1]) - j += 2 - if data[i] == bs { - continue - } - n = i - break - } - l := n - 10 - if l < 0 { - l = 0 - } - h := n + 10 - - // find the interesting spot - n - fmt.Printf("is[%d]:", l) - for i := l; i < h; i++ { - if i >= ld { - fmt.Printf(" --") - continue - } - fmt.Printf(" %.2x", data[i]) - } - fmt.Printf("\n") - - fmt.Printf("sb[%d]:", l) - for i := l; i < h; i++ { - if i >= ls { - fmt.Printf(" --") - continue - } - bs := hex(s[j])*16 + hex(s[j+1]) - j += 2 - fmt.Printf(" %.2x", bs) - } - fmt.Printf("\n") - - t.Fail() - - // t.Errorf("%s: \ngood: %s\nbad: %x", msg, s, b.Bytes()) - // Print the output in a partially-decoded format; can - // be helpful when updating the test. It produces the output - // that is pasted, with minor edits, into the argument to verify(). - // data := b.Bytes() - // nesting := 0 - // for b.Len() > 0 { - // start := len(data) - b.Len() - // var u uint64 - // u, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on varint:", err) - // return - // } - // wire := u & 0x7 - // tag := u >> 3 - // switch wire { - // case WireVarint: - // v, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on varint:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireFixed32: - // v, err := DecodeFixed32(b) - // if err != nil { - // fmt.Printf("decode error on fixed32:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireFixed64: - // v, err := DecodeFixed64(b) - // if err != nil { - // fmt.Printf("decode error on fixed64:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireBytes: - // nb, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on bytes:", err) - // return - // } - // after_tag := len(data) - b.Len() - // str := make([]byte, nb) - // _, err = b.Read(str) - // if err != nil { - // fmt.Printf("decode error on bytes:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" \"%x\" // field %d, encoding %d (FIELD)\n", - // data[start:after_tag], str, tag, wire) - // case WireStartGroup: - // nesting++ - // fmt.Printf("\t\t\"%x\"\t\t// start group field %d level %d\n", - // data[start:len(data)-b.Len()], tag, nesting) - // case WireEndGroup: - // fmt.Printf("\t\t\"%x\"\t\t// end group field %d level %d\n", - // data[start:len(data)-b.Len()], tag, nesting) - // nesting-- - // default: - // fmt.Printf("unrecognized wire type %d\n", wire) - // return - // } - // } -} - -func hex(c uint8) uint8 { - if '0' <= c && c <= '9' { - return c - '0' - } - if 'a' <= c && c <= 'f' { - return 10 + c - 'a' - } - if 'A' <= c && c <= 'F' { - return 10 + c - 'A' - } - return 0 -} - -func equal(b []byte, s string, t *testing.T) bool { - if 2*len(b) != len(s) { - // fail(fmt.Sprintf("wrong lengths: 2*%d != %d", len(b), len(s)), b, s, t) - fmt.Printf("wrong lengths: 2*%d != %d\n", len(b), len(s)) - return false - } - for i, j := 0, 0; i < len(b); i, j = i+1, j+2 { - x := hex(s[j])*16 + hex(s[j+1]) - if b[i] != x { - // fail(fmt.Sprintf("bad byte[%d]:%x %x", i, b[i], x), b, s, t) - fmt.Printf("bad byte[%d]:%x %x", i, b[i], x) - return false - } - } - return true -} - -func overify(t *testing.T, pb *GoTest, expected string) { - o := old() - err := o.Marshal(pb) - if err != nil { - fmt.Printf("overify marshal-1 err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("expected = %s", expected) - } - if !equal(o.Bytes(), expected, t) { - o.DebugPrint("overify neq 1", o.Bytes()) - t.Fatalf("expected = %s", expected) - } - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - err = o.Unmarshal(pbd) - if err != nil { - t.Fatalf("overify unmarshal err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("string = %s", expected) - } - o.Reset() - err = o.Marshal(pbd) - if err != nil { - t.Errorf("overify marshal-2 err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("string = %s", expected) - } - if !equal(o.Bytes(), expected, t) { - o.DebugPrint("overify neq 2", o.Bytes()) - t.Fatalf("string = %s", expected) - } -} - -// Simple tests for numeric encode/decode primitives (varint, etc.) -func TestNumericPrimitives(t *testing.T) { - for i := uint64(0); i < 1e6; i += 111 { - o := old() - if o.EncodeVarint(i) != nil { - t.Error("EncodeVarint") - break - } - x, e := o.DecodeVarint() - if e != nil { - t.Fatal("DecodeVarint") - } - if x != i { - t.Fatal("varint decode fail:", i, x) - } - - o = old() - if o.EncodeFixed32(i) != nil { - t.Fatal("encFixed32") - } - x, e = o.DecodeFixed32() - if e != nil { - t.Fatal("decFixed32") - } - if x != i { - t.Fatal("fixed32 decode fail:", i, x) - } - - o = old() - if o.EncodeFixed64(i*1234567) != nil { - t.Error("encFixed64") - break - } - x, e = o.DecodeFixed64() - if e != nil { - t.Error("decFixed64") - break - } - if x != i*1234567 { - t.Error("fixed64 decode fail:", i*1234567, x) - break - } - - o = old() - i32 := int32(i - 12345) - if o.EncodeZigzag32(uint64(i32)) != nil { - t.Fatal("EncodeZigzag32") - } - x, e = o.DecodeZigzag32() - if e != nil { - t.Fatal("DecodeZigzag32") - } - if x != uint64(uint32(i32)) { - t.Fatal("zigzag32 decode fail:", i32, x) - } - - o = old() - i64 := int64(i - 12345) - if o.EncodeZigzag64(uint64(i64)) != nil { - t.Fatal("EncodeZigzag64") - } - x, e = o.DecodeZigzag64() - if e != nil { - t.Fatal("DecodeZigzag64") - } - if x != uint64(i64) { - t.Fatal("zigzag64 decode fail:", i64, x) - } - } -} - -// fakeMarshaler is a simple struct implementing Marshaler and Message interfaces. -type fakeMarshaler struct { - b []byte - err error -} - -func (f *fakeMarshaler) Marshal() ([]byte, error) { return f.b, f.err } -func (f *fakeMarshaler) String() string { return fmt.Sprintf("Bytes: %v Error: %v", f.b, f.err) } -func (f *fakeMarshaler) ProtoMessage() {} -func (f *fakeMarshaler) Reset() {} - -type msgWithFakeMarshaler struct { - M *fakeMarshaler `protobuf:"bytes,1,opt,name=fake"` -} - -func (m *msgWithFakeMarshaler) String() string { return CompactTextString(m) } -func (m *msgWithFakeMarshaler) ProtoMessage() {} -func (m *msgWithFakeMarshaler) Reset() {} - -// Simple tests for proto messages that implement the Marshaler interface. -func TestMarshalerEncoding(t *testing.T) { - tests := []struct { - name string - m Message - want []byte - errType reflect.Type - }{ - { - name: "Marshaler that fails", - m: &fakeMarshaler{ - err: errors.New("some marshal err"), - b: []byte{5, 6, 7}, - }, - // Since the Marshal method returned bytes, they should be written to the - // buffer. (For efficiency, we assume that Marshal implementations are - // always correct w.r.t. RequiredNotSetError and output.) - want: []byte{5, 6, 7}, - errType: reflect.TypeOf(errors.New("some marshal err")), - }, - { - name: "Marshaler that fails with RequiredNotSetError", - m: &msgWithFakeMarshaler{ - M: &fakeMarshaler{ - err: &RequiredNotSetError{}, - b: []byte{5, 6, 7}, - }, - }, - // Since there's an error that can be continued after, - // the buffer should be written. - want: []byte{ - 10, 3, // for &msgWithFakeMarshaler - 5, 6, 7, // for &fakeMarshaler - }, - errType: reflect.TypeOf(&RequiredNotSetError{}), - }, - { - name: "Marshaler that succeeds", - m: &fakeMarshaler{ - b: []byte{0, 1, 2, 3, 4, 127, 255}, - }, - want: []byte{0, 1, 2, 3, 4, 127, 255}, - }, - } - for _, test := range tests { - b := NewBuffer(nil) - err := b.Marshal(test.m) - if reflect.TypeOf(err) != test.errType { - t.Errorf("%s: got err %T(%v) wanted %T", test.name, err, err, test.errType) - } - if !reflect.DeepEqual(test.want, b.Bytes()) { - t.Errorf("%s: got bytes %v wanted %v", test.name, b.Bytes(), test.want) - } - if size := Size(test.m); size != len(b.Bytes()) { - t.Errorf("%s: Size(_) = %v, but marshaled to %v bytes", test.name, size, len(b.Bytes())) - } - - m, mErr := Marshal(test.m) - if !bytes.Equal(b.Bytes(), m) { - t.Errorf("%s: Marshal returned %v, but (*Buffer).Marshal wrote %v", test.name, m, b.Bytes()) - } - if !reflect.DeepEqual(err, mErr) { - t.Errorf("%s: Marshal err = %q, but (*Buffer).Marshal returned %q", - test.name, fmt.Sprint(mErr), fmt.Sprint(err)) - } - } -} - -// Simple tests for bytes -func TestBytesPrimitives(t *testing.T) { - o := old() - bytes := []byte{'n', 'o', 'w', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 't', 'i', 'm', 'e'} - if o.EncodeRawBytes(bytes) != nil { - t.Error("EncodeRawBytes") - } - decb, e := o.DecodeRawBytes(false) - if e != nil { - t.Error("DecodeRawBytes") - } - equalbytes(bytes, decb, t) -} - -// Simple tests for strings -func TestStringPrimitives(t *testing.T) { - o := old() - s := "now is the time" - if o.EncodeStringBytes(s) != nil { - t.Error("enc_string") - } - decs, e := o.DecodeStringBytes() - if e != nil { - t.Error("dec_string") - } - if s != decs { - t.Error("string encode/decode fail:", s, decs) - } -} - -// Do we catch the "required bit not set" case? -func TestRequiredBit(t *testing.T) { - o := old() - pb := new(GoTest) - err := o.Marshal(pb) - if err == nil { - t.Error("did not catch missing required fields") - } else if strings.Index(err.Error(), "Kind") < 0 { - t.Error("wrong error type:", err) - } -} - -// Check that all fields are nil. -// Clearly silly, and a residue from a more interesting test with an earlier, -// different initialization property, but it once caught a compiler bug so -// it lives. -func checkInitialized(pb *GoTest, t *testing.T) { - if pb.F_BoolDefaulted != nil { - t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted) - } - if pb.F_Int32Defaulted != nil { - t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted) - } - if pb.F_Int64Defaulted != nil { - t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted) - } - if pb.F_Fixed32Defaulted != nil { - t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted) - } - if pb.F_Fixed64Defaulted != nil { - t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted) - } - if pb.F_Uint32Defaulted != nil { - t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted) - } - if pb.F_Uint64Defaulted != nil { - t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted) - } - if pb.F_FloatDefaulted != nil { - t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted) - } - if pb.F_DoubleDefaulted != nil { - t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted) - } - if pb.F_StringDefaulted != nil { - t.Error("New or Reset did not set string:", *pb.F_StringDefaulted) - } - if pb.F_BytesDefaulted != nil { - t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted)) - } - if pb.F_Sint32Defaulted != nil { - t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted) - } - if pb.F_Sint64Defaulted != nil { - t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted) - } -} - -// Does Reset() reset? -func TestReset(t *testing.T) { - pb := initGoTest(true) - // muck with some values - pb.F_BoolDefaulted = Bool(false) - pb.F_Int32Defaulted = Int32(237) - pb.F_Int64Defaulted = Int64(12346) - pb.F_Fixed32Defaulted = Uint32(32000) - pb.F_Fixed64Defaulted = Uint64(666) - pb.F_Uint32Defaulted = Uint32(323232) - pb.F_Uint64Defaulted = nil - pb.F_FloatDefaulted = nil - pb.F_DoubleDefaulted = Float64(0) - pb.F_StringDefaulted = String("gotcha") - pb.F_BytesDefaulted = []byte("asdfasdf") - pb.F_Sint32Defaulted = Int32(123) - pb.F_Sint64Defaulted = Int64(789) - pb.Reset() - checkInitialized(pb, t) -} - -// All required fields set, no defaults provided. -func TestEncodeDecode1(t *testing.T) { - pb := initGoTest(false) - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 0x20 - "714000000000000000"+ // field 14, encoding 1, value 0x40 - "78a019"+ // field 15, encoding 0, value 0xca0 = 3232 - "8001c032"+ // field 16, encoding 0, value 0x1940 = 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2, string "string" - "b304"+ // field 70, encoding 3, start group - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // field 70, encoding 4, end group - "aa0605"+"6279746573"+ // field 101, encoding 2, string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f") // field 103, encoding 0, 0x7f zigzag64 -} - -// All required fields set, defaults provided. -func TestEncodeDecode2(t *testing.T) { - pb := initGoTest(true) - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All default fields set to their default value by hand -func TestEncodeDecode3(t *testing.T) { - pb := initGoTest(false) - pb.F_BoolDefaulted = Bool(true) - pb.F_Int32Defaulted = Int32(32) - pb.F_Int64Defaulted = Int64(64) - pb.F_Fixed32Defaulted = Uint32(320) - pb.F_Fixed64Defaulted = Uint64(640) - pb.F_Uint32Defaulted = Uint32(3200) - pb.F_Uint64Defaulted = Uint64(6400) - pb.F_FloatDefaulted = Float32(314159) - pb.F_DoubleDefaulted = Float64(271828) - pb.F_StringDefaulted = String("hello, \"world!\"\n") - pb.F_BytesDefaulted = []byte("Bignose") - pb.F_Sint32Defaulted = Int32(-32) - pb.F_Sint64Defaulted = Int64(-64) - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, defaults provided, all non-defaulted optional fields have values. -func TestEncodeDecode4(t *testing.T) { - pb := initGoTest(true) - pb.Table = String("hello") - pb.Param = Int32(7) - pb.OptionalField = initGoTestField() - pb.F_BoolOptional = Bool(true) - pb.F_Int32Optional = Int32(32) - pb.F_Int64Optional = Int64(64) - pb.F_Fixed32Optional = Uint32(3232) - pb.F_Fixed64Optional = Uint64(6464) - pb.F_Uint32Optional = Uint32(323232) - pb.F_Uint64Optional = Uint64(646464) - pb.F_FloatOptional = Float32(32.) - pb.F_DoubleOptional = Float64(64.) - pb.F_StringOptional = String("hello") - pb.F_BytesOptional = []byte("Bignose") - pb.F_Sint32Optional = Int32(-32) - pb.F_Sint64Optional = Int64(-64) - pb.Optionalgroup = initGoTest_OptionalGroup() - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "1205"+"68656c6c6f"+ // field 2, encoding 2, string "hello" - "1807"+ // field 3, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "320d"+"0a056c6162656c120474797065"+ // field 6, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "f00101"+ // field 30, encoding 0, value 1 - "f80120"+ // field 31, encoding 0, value 32 - "800240"+ // field 32, encoding 0, value 64 - "8d02a00c0000"+ // field 33, encoding 5, value 3232 - "91024019000000000000"+ // field 34, encoding 1, value 6464 - "9802a0dd13"+ // field 35, encoding 0, value 323232 - "a002c0ba27"+ // field 36, encoding 0, value 646464 - "ad0200000042"+ // field 37, encoding 5, value 32.0 - "b1020000000000005040"+ // field 38, encoding 1, value 64.0 - "ba0205"+"68656c6c6f"+ // field 39, encoding 2, string "hello" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "d305"+ // start group field 90 level 1 - "da0508"+"6f7074696f6e616c"+ // field 91, encoding 2, string "optional" - "d405"+ // end group field 90 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "ea1207"+"4269676e6f7365"+ // field 301, encoding 2, string "Bignose" - "f0123f"+ // field 302, encoding 0, value 63 - "f8127f"+ // field 303, encoding 0, value 127 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, defaults provided, all repeated fields given two values. -func TestEncodeDecode5(t *testing.T) { - pb := initGoTest(true) - pb.RepeatedField = []*GoTestField{initGoTestField(), initGoTestField()} - pb.F_BoolRepeated = []bool{false, true} - pb.F_Int32Repeated = []int32{32, 33} - pb.F_Int64Repeated = []int64{64, 65} - pb.F_Fixed32Repeated = []uint32{3232, 3333} - pb.F_Fixed64Repeated = []uint64{6464, 6565} - pb.F_Uint32Repeated = []uint32{323232, 333333} - pb.F_Uint64Repeated = []uint64{646464, 656565} - pb.F_FloatRepeated = []float32{32., 33.} - pb.F_DoubleRepeated = []float64{64., 65.} - pb.F_StringRepeated = []string{"hello", "sailor"} - pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")} - pb.F_Sint32Repeated = []int32{32, -32} - pb.F_Sint64Repeated = []int64{64, -64} - pb.Repeatedgroup = []*GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()} - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) - "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "a00100"+ // field 20, encoding 0, value 0 - "a00101"+ // field 20, encoding 0, value 1 - "a80120"+ // field 21, encoding 0, value 32 - "a80121"+ // field 21, encoding 0, value 33 - "b00140"+ // field 22, encoding 0, value 64 - "b00141"+ // field 22, encoding 0, value 65 - "bd01a00c0000"+ // field 23, encoding 5, value 3232 - "bd01050d0000"+ // field 23, encoding 5, value 3333 - "c1014019000000000000"+ // field 24, encoding 1, value 6464 - "c101a519000000000000"+ // field 24, encoding 1, value 6565 - "c801a0dd13"+ // field 25, encoding 0, value 323232 - "c80195ac14"+ // field 25, encoding 0, value 333333 - "d001c0ba27"+ // field 26, encoding 0, value 646464 - "d001b58928"+ // field 26, encoding 0, value 656565 - "dd0100000042"+ // field 27, encoding 5, value 32.0 - "dd0100000442"+ // field 27, encoding 5, value 33.0 - "e1010000000000005040"+ // field 28, encoding 1, value 64.0 - "e1010000000000405040"+ // field 28, encoding 1, value 65.0 - "ea0105"+"68656c6c6f"+ // field 29, encoding 2, string "hello" - "ea0106"+"7361696c6f72"+ // field 29, encoding 2, string "sailor" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "8305"+ // start group field 80 level 1 - "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" - "8405"+ // end group field 80 level 1 - "8305"+ // start group field 80 level 1 - "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" - "8405"+ // end group field 80 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "ca0c03"+"626967"+ // field 201, encoding 2, string "big" - "ca0c04"+"6e6f7365"+ // field 201, encoding 2, string "nose" - "d00c40"+ // field 202, encoding 0, value 32 - "d00c3f"+ // field 202, encoding 0, value -32 - "d80c8001"+ // field 203, encoding 0, value 64 - "d80c7f"+ // field 203, encoding 0, value -64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, all packed repeated fields given two values. -func TestEncodeDecode6(t *testing.T) { - pb := initGoTest(false) - pb.F_BoolRepeatedPacked = []bool{false, true} - pb.F_Int32RepeatedPacked = []int32{32, 33} - pb.F_Int64RepeatedPacked = []int64{64, 65} - pb.F_Fixed32RepeatedPacked = []uint32{3232, 3333} - pb.F_Fixed64RepeatedPacked = []uint64{6464, 6565} - pb.F_Uint32RepeatedPacked = []uint32{323232, 333333} - pb.F_Uint64RepeatedPacked = []uint64{646464, 656565} - pb.F_FloatRepeatedPacked = []float32{32., 33.} - pb.F_DoubleRepeatedPacked = []float64{64., 65.} - pb.F_Sint32RepeatedPacked = []int32{32, -32} - pb.F_Sint64RepeatedPacked = []int64{64, -64} - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "9203020001"+ // field 50, encoding 2, 2 bytes, value 0, value 1 - "9a03022021"+ // field 51, encoding 2, 2 bytes, value 32, value 33 - "a203024041"+ // field 52, encoding 2, 2 bytes, value 64, value 65 - "aa0308"+ // field 53, encoding 2, 8 bytes - "a00c0000050d0000"+ // value 3232, value 3333 - "b20310"+ // field 54, encoding 2, 16 bytes - "4019000000000000a519000000000000"+ // value 6464, value 6565 - "ba0306"+ // field 55, encoding 2, 6 bytes - "a0dd1395ac14"+ // value 323232, value 333333 - "c20306"+ // field 56, encoding 2, 6 bytes - "c0ba27b58928"+ // value 646464, value 656565 - "ca0308"+ // field 57, encoding 2, 8 bytes - "0000004200000442"+ // value 32.0, value 33.0 - "d20310"+ // field 58, encoding 2, 16 bytes - "00000000000050400000000000405040"+ // value 64.0, value 65.0 - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "b21f02"+ // field 502, encoding 2, 2 bytes - "403f"+ // value 32, value -32 - "ba1f03"+ // field 503, encoding 2, 3 bytes - "80017f") // value 64, value -64 -} - -// Test that we can encode empty bytes fields. -func TestEncodeDecodeBytes1(t *testing.T) { - pb := initGoTest(false) - - // Create our bytes - pb.F_BytesRequired = []byte{} - pb.F_BytesRepeated = [][]byte{{}} - pb.F_BytesOptional = []byte{} - - d, err := Marshal(pb) - if err != nil { - t.Error(err) - } - - pbd := new(GoTest) - if err := Unmarshal(d, pbd); err != nil { - t.Error(err) - } - - if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 { - t.Error("required empty bytes field is incorrect") - } - if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil { - t.Error("repeated empty bytes field is incorrect") - } - if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 { - t.Error("optional empty bytes field is incorrect") - } -} - -// Test that we encode nil-valued fields of a repeated bytes field correctly. -// Since entries in a repeated field cannot be nil, nil must mean empty value. -func TestEncodeDecodeBytes2(t *testing.T) { - pb := initGoTest(false) - - // Create our bytes - pb.F_BytesRepeated = [][]byte{nil} - - d, err := Marshal(pb) - if err != nil { - t.Error(err) - } - - pbd := new(GoTest) - if err := Unmarshal(d, pbd); err != nil { - t.Error(err) - } - - if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil { - t.Error("Unexpected value for repeated bytes field") - } -} - -// All required fields set, defaults provided, all repeated fields given two values. -func TestSkippingUnrecognizedFields(t *testing.T) { - o := old() - pb := initGoTestField() - - // Marshal it normally. - o.Marshal(pb) - - // Now new a GoSkipTest record. - skip := &GoSkipTest{ - SkipInt32: Int32(32), - SkipFixed32: Uint32(3232), - SkipFixed64: Uint64(6464), - SkipString: String("skipper"), - Skipgroup: &GoSkipTest_SkipGroup{ - GroupInt32: Int32(75), - GroupString: String("wxyz"), - }, - } - - // Marshal it into same buffer. - o.Marshal(skip) - - pbd := new(GoTestField) - o.Unmarshal(pbd) - - // The __unrecognized field should be a marshaling of GoSkipTest - skipd := new(GoSkipTest) - - o.SetBuf(pbd.XXX_unrecognized) - o.Unmarshal(skipd) - - if *skipd.SkipInt32 != *skip.SkipInt32 { - t.Error("skip int32", skipd.SkipInt32) - } - if *skipd.SkipFixed32 != *skip.SkipFixed32 { - t.Error("skip fixed32", skipd.SkipFixed32) - } - if *skipd.SkipFixed64 != *skip.SkipFixed64 { - t.Error("skip fixed64", skipd.SkipFixed64) - } - if *skipd.SkipString != *skip.SkipString { - t.Error("skip string", *skipd.SkipString) - } - if *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32 { - t.Error("skip group int32", skipd.Skipgroup.GroupInt32) - } - if *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString { - t.Error("skip group string", *skipd.Skipgroup.GroupString) - } -} - -// Check that unrecognized fields of a submessage are preserved. -func TestSubmessageUnrecognizedFields(t *testing.T) { - nm := &NewMessage{ - Nested: &NewMessage_Nested{ - Name: String("Nigel"), - FoodGroup: String("carbs"), - }, - } - b, err := Marshal(nm) - if err != nil { - t.Fatalf("Marshal of NewMessage: %v", err) - } - - // Unmarshal into an OldMessage. - om := new(OldMessage) - if err := Unmarshal(b, om); err != nil { - t.Fatalf("Unmarshal to OldMessage: %v", err) - } - exp := &OldMessage{ - Nested: &OldMessage_Nested{ - Name: String("Nigel"), - // normal protocol buffer users should not do this - XXX_unrecognized: []byte("\x12\x05carbs"), - }, - } - if !Equal(om, exp) { - t.Errorf("om = %v, want %v", om, exp) - } - - // Clone the OldMessage. - om = Clone(om).(*OldMessage) - if !Equal(om, exp) { - t.Errorf("Clone(om) = %v, want %v", om, exp) - } - - // Marshal the OldMessage, then unmarshal it into an empty NewMessage. - if b, err = Marshal(om); err != nil { - t.Fatalf("Marshal of OldMessage: %v", err) - } - t.Logf("Marshal(%v) -> %q", om, b) - nm2 := new(NewMessage) - if err := Unmarshal(b, nm2); err != nil { - t.Fatalf("Unmarshal to NewMessage: %v", err) - } - if !Equal(nm, nm2) { - t.Errorf("NewMessage round-trip: %v => %v", nm, nm2) - } -} - -// Check that an int32 field can be upgraded to an int64 field. -func TestNegativeInt32(t *testing.T) { - om := &OldMessage{ - Num: Int32(-1), - } - b, err := Marshal(om) - if err != nil { - t.Fatalf("Marshal of OldMessage: %v", err) - } - - // Check the size. It should be 11 bytes; - // 1 for the field/wire type, and 10 for the negative number. - if len(b) != 11 { - t.Errorf("%v marshaled as %q, wanted 11 bytes", om, b) - } - - // Unmarshal into a NewMessage. - nm := new(NewMessage) - if err := Unmarshal(b, nm); err != nil { - t.Fatalf("Unmarshal to NewMessage: %v", err) - } - want := &NewMessage{ - Num: Int64(-1), - } - if !Equal(nm, want) { - t.Errorf("nm = %v, want %v", nm, want) - } -} - -// Check that we can grow an array (repeated field) to have many elements. -// This test doesn't depend only on our encoding; for variety, it makes sure -// we create, encode, and decode the correct contents explicitly. It's therefore -// a bit messier. -// This test also uses (and hence tests) the Marshal/Unmarshal functions -// instead of the methods. -func TestBigRepeated(t *testing.T) { - pb := initGoTest(true) - - // Create the arrays - const N = 50 // Internally the library starts much smaller. - pb.Repeatedgroup = make([]*GoTest_RepeatedGroup, N) - pb.F_Sint64Repeated = make([]int64, N) - pb.F_Sint32Repeated = make([]int32, N) - pb.F_BytesRepeated = make([][]byte, N) - pb.F_StringRepeated = make([]string, N) - pb.F_DoubleRepeated = make([]float64, N) - pb.F_FloatRepeated = make([]float32, N) - pb.F_Uint64Repeated = make([]uint64, N) - pb.F_Uint32Repeated = make([]uint32, N) - pb.F_Fixed64Repeated = make([]uint64, N) - pb.F_Fixed32Repeated = make([]uint32, N) - pb.F_Int64Repeated = make([]int64, N) - pb.F_Int32Repeated = make([]int32, N) - pb.F_BoolRepeated = make([]bool, N) - pb.RepeatedField = make([]*GoTestField, N) - - // Fill in the arrays with checkable values. - igtf := initGoTestField() - igtrg := initGoTest_RepeatedGroup() - for i := 0; i < N; i++ { - pb.Repeatedgroup[i] = igtrg - pb.F_Sint64Repeated[i] = int64(i) - pb.F_Sint32Repeated[i] = int32(i) - s := fmt.Sprint(i) - pb.F_BytesRepeated[i] = []byte(s) - pb.F_StringRepeated[i] = s - pb.F_DoubleRepeated[i] = float64(i) - pb.F_FloatRepeated[i] = float32(i) - pb.F_Uint64Repeated[i] = uint64(i) - pb.F_Uint32Repeated[i] = uint32(i) - pb.F_Fixed64Repeated[i] = uint64(i) - pb.F_Fixed32Repeated[i] = uint32(i) - pb.F_Int64Repeated[i] = int64(i) - pb.F_Int32Repeated[i] = int32(i) - pb.F_BoolRepeated[i] = i%2 == 0 - pb.RepeatedField[i] = igtf - } - - // Marshal. - buf, _ := Marshal(pb) - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - Unmarshal(buf, pbd) - - // Check the checkable values - for i := uint64(0); i < N; i++ { - if pbd.Repeatedgroup[i] == nil { // TODO: more checking? - t.Error("pbd.Repeatedgroup bad") - } - var x uint64 - x = uint64(pbd.F_Sint64Repeated[i]) - if x != i { - t.Error("pbd.F_Sint64Repeated bad", x, i) - } - x = uint64(pbd.F_Sint32Repeated[i]) - if x != i { - t.Error("pbd.F_Sint32Repeated bad", x, i) - } - s := fmt.Sprint(i) - equalbytes(pbd.F_BytesRepeated[i], []byte(s), t) - if pbd.F_StringRepeated[i] != s { - t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i) - } - x = uint64(pbd.F_DoubleRepeated[i]) - if x != i { - t.Error("pbd.F_DoubleRepeated bad", x, i) - } - x = uint64(pbd.F_FloatRepeated[i]) - if x != i { - t.Error("pbd.F_FloatRepeated bad", x, i) - } - x = pbd.F_Uint64Repeated[i] - if x != i { - t.Error("pbd.F_Uint64Repeated bad", x, i) - } - x = uint64(pbd.F_Uint32Repeated[i]) - if x != i { - t.Error("pbd.F_Uint32Repeated bad", x, i) - } - x = pbd.F_Fixed64Repeated[i] - if x != i { - t.Error("pbd.F_Fixed64Repeated bad", x, i) - } - x = uint64(pbd.F_Fixed32Repeated[i]) - if x != i { - t.Error("pbd.F_Fixed32Repeated bad", x, i) - } - x = uint64(pbd.F_Int64Repeated[i]) - if x != i { - t.Error("pbd.F_Int64Repeated bad", x, i) - } - x = uint64(pbd.F_Int32Repeated[i]) - if x != i { - t.Error("pbd.F_Int32Repeated bad", x, i) - } - if pbd.F_BoolRepeated[i] != (i%2 == 0) { - t.Error("pbd.F_BoolRepeated bad", x, i) - } - if pbd.RepeatedField[i] == nil { // TODO: more checking? - t.Error("pbd.RepeatedField bad") - } - } -} - -// Verify we give a useful message when decoding to the wrong structure type. -func TestTypeMismatch(t *testing.T) { - pb1 := initGoTest(true) - - // Marshal - o := old() - o.Marshal(pb1) - - // Now Unmarshal it to the wrong type. - pb2 := initGoTestField() - err := o.Unmarshal(pb2) - if err == nil { - t.Error("expected error, got no error") - } else if !strings.Contains(err.Error(), "bad wiretype") { - t.Error("expected bad wiretype error, got", err) - } -} - -func encodeDecode(t *testing.T, in, out Message, msg string) { - buf, err := Marshal(in) - if err != nil { - t.Fatalf("failed marshaling %v: %v", msg, err) - } - if err := Unmarshal(buf, out); err != nil { - t.Fatalf("failed unmarshaling %v: %v", msg, err) - } -} - -func TestPackedNonPackedDecoderSwitching(t *testing.T) { - np, p := new(NonPackedTest), new(PackedTest) - - // non-packed -> packed - np.A = []int32{0, 1, 1, 2, 3, 5} - encodeDecode(t, np, p, "non-packed -> packed") - if !reflect.DeepEqual(np.A, p.B) { - t.Errorf("failed non-packed -> packed; np.A=%+v, p.B=%+v", np.A, p.B) - } - - // packed -> non-packed - np.Reset() - p.B = []int32{3, 1, 4, 1, 5, 9} - encodeDecode(t, p, np, "packed -> non-packed") - if !reflect.DeepEqual(p.B, np.A) { - t.Errorf("failed packed -> non-packed; p.B=%+v, np.A=%+v", p.B, np.A) - } -} - -func TestProto1RepeatedGroup(t *testing.T) { - pb := &MessageList{ - Message: []*MessageList_Message{ - { - Name: String("blah"), - Count: Int32(7), - }, - // NOTE: pb.Message[1] is a nil - nil, - }, - } - - o := old() - err := o.Marshal(pb) - if err == nil || !strings.Contains(err.Error(), "repeated field Message has nil") { - t.Fatalf("unexpected or no error when marshaling: %v", err) - } -} - -// Test that enums work. Checks for a bug introduced by making enums -// named types instead of int32: newInt32FromUint64 would crash with -// a type mismatch in reflect.PointTo. -func TestEnum(t *testing.T) { - pb := new(GoEnum) - pb.Foo = FOO_FOO1.Enum() - o := old() - if err := o.Marshal(pb); err != nil { - t.Fatal("error encoding enum:", err) - } - pb1 := new(GoEnum) - if err := o.Unmarshal(pb1); err != nil { - t.Fatal("error decoding enum:", err) - } - if *pb1.Foo != FOO_FOO1 { - t.Error("expected 7 but got ", *pb1.Foo) - } -} - -// Enum types have String methods. Check that enum fields can be printed. -// We don't care what the value actually is, just as long as it doesn't crash. -func TestPrintingNilEnumFields(t *testing.T) { - pb := new(GoEnum) - _ = fmt.Sprintf("%+v", pb) -} - -// Verify that absent required fields cause Marshal/Unmarshal to return errors. -func TestRequiredFieldEnforcement(t *testing.T) { - pb := new(GoTestField) - _, err := Marshal(pb) - if err == nil { - t.Error("marshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Label") { - t.Errorf("marshal: bad error type: %v", err) - } - - // A slightly sneaky, yet valid, proto. It encodes the same required field twice, - // so simply counting the required fields is insufficient. - // field 1, encoding 2, value "hi" - buf := []byte("\x0A\x02hi\x0A\x02hi") - err = Unmarshal(buf, pb) - if err == nil { - t.Error("unmarshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "{Unknown}") { - t.Errorf("unmarshal: bad error type: %v", err) - } -} - -// Verify that absent required fields in groups cause Marshal/Unmarshal to return errors. -func TestRequiredFieldEnforcementGroups(t *testing.T) { - pb := &GoTestRequiredGroupField{Group: &GoTestRequiredGroupField_Group{}} - if _, err := Marshal(pb); err == nil { - t.Error("marshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.Field") { - t.Errorf("marshal: bad error type: %v", err) - } - - buf := []byte{11, 12} - if err := Unmarshal(buf, pb); err == nil { - t.Error("unmarshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.{Unknown}") { - t.Errorf("unmarshal: bad error type: %v", err) - } -} - -func TestTypedNilMarshal(t *testing.T) { - // A typed nil should return ErrNil and not crash. - { - var m *GoEnum - if _, err := Marshal(m); err != ErrNil { - t.Errorf("Marshal(%#v): got %v, want ErrNil", m, err) - } - } - - { - m := &Communique{Union: &Communique_Msg{nil}} - if _, err := Marshal(m); err == nil || err == ErrNil { - t.Errorf("Marshal(%#v): got %v, want errOneofHasNil", m, err) - } - } -} - -// A type that implements the Marshaler interface, but is not nillable. -type nonNillableInt uint64 - -func (nni nonNillableInt) Marshal() ([]byte, error) { - return EncodeVarint(uint64(nni)), nil -} - -type NNIMessage struct { - nni nonNillableInt -} - -func (*NNIMessage) Reset() {} -func (*NNIMessage) String() string { return "" } -func (*NNIMessage) ProtoMessage() {} - -// A type that implements the Marshaler interface and is nillable. -type nillableMessage struct { - x uint64 -} - -func (nm *nillableMessage) Marshal() ([]byte, error) { - return EncodeVarint(nm.x), nil -} - -type NMMessage struct { - nm *nillableMessage -} - -func (*NMMessage) Reset() {} -func (*NMMessage) String() string { return "" } -func (*NMMessage) ProtoMessage() {} - -// Verify a type that uses the Marshaler interface, but has a nil pointer. -func TestNilMarshaler(t *testing.T) { - // Try a struct with a Marshaler field that is nil. - // It should be directly marshable. - nmm := new(NMMessage) - if _, err := Marshal(nmm); err != nil { - t.Error("unexpected error marshaling nmm: ", err) - } - - // Try a struct with a Marshaler field that is not nillable. - nnim := new(NNIMessage) - nnim.nni = 7 - var _ Marshaler = nnim.nni // verify it is truly a Marshaler - if _, err := Marshal(nnim); err != nil { - t.Error("unexpected error marshaling nnim: ", err) - } -} - -func TestAllSetDefaults(t *testing.T) { - // Exercise SetDefaults with all scalar field types. - m := &Defaults{ - // NaN != NaN, so override that here. - F_Nan: Float32(1.7), - } - expected := &Defaults{ - F_Bool: Bool(true), - F_Int32: Int32(32), - F_Int64: Int64(64), - F_Fixed32: Uint32(320), - F_Fixed64: Uint64(640), - F_Uint32: Uint32(3200), - F_Uint64: Uint64(6400), - F_Float: Float32(314159), - F_Double: Float64(271828), - F_String: String(`hello, "world!"` + "\n"), - F_Bytes: []byte("Bignose"), - F_Sint32: Int32(-32), - F_Sint64: Int64(-64), - F_Enum: Defaults_GREEN.Enum(), - F_Pinf: Float32(float32(math.Inf(1))), - F_Ninf: Float32(float32(math.Inf(-1))), - F_Nan: Float32(1.7), - StrZero: String(""), - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("SetDefaults failed\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultsWithSetField(t *testing.T) { - // Check that a set value is not overridden. - m := &Defaults{ - F_Int32: Int32(12), - } - SetDefaults(m) - if v := m.GetF_Int32(); v != 12 { - t.Errorf("m.FInt32 = %v, want 12", v) - } -} - -func TestSetDefaultsWithSubMessage(t *testing.T) { - m := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("gopher"), - }, - } - expected := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("gopher"), - Port: Int32(4000), - }, - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultsWithRepeatedSubMessage(t *testing.T) { - m := &MyMessage{ - RepInner: []*InnerMessage{{}}, - } - expected := &MyMessage{ - RepInner: []*InnerMessage{{ - Port: Int32(4000), - }}, - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultWithRepeatedNonMessage(t *testing.T) { - m := &MyMessage{ - Pet: []string{"turtle", "wombat"}, - } - expected := Clone(m) - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestMaximumTagNumber(t *testing.T) { - m := &MaxTag{ - LastField: String("natural goat essence"), - } - buf, err := Marshal(m) - if err != nil { - t.Fatalf("proto.Marshal failed: %v", err) - } - m2 := new(MaxTag) - if err := Unmarshal(buf, m2); err != nil { - t.Fatalf("proto.Unmarshal failed: %v", err) - } - if got, want := m2.GetLastField(), *m.LastField; got != want { - t.Errorf("got %q, want %q", got, want) - } -} - -func TestJSON(t *testing.T) { - m := &MyMessage{ - Count: Int32(4), - Pet: []string{"bunny", "kitty"}, - Inner: &InnerMessage{ - Host: String("cauchy"), - }, - Bikeshed: MyMessage_GREEN.Enum(), - } - const expected = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":1}` - - b, err := json.Marshal(m) - if err != nil { - t.Fatalf("json.Marshal failed: %v", err) - } - s := string(b) - if s != expected { - t.Errorf("got %s\nwant %s", s, expected) - } - - received := new(MyMessage) - if err := json.Unmarshal(b, received); err != nil { - t.Fatalf("json.Unmarshal failed: %v", err) - } - if !Equal(received, m) { - t.Fatalf("got %s, want %s", received, m) - } - - // Test unmarshalling of JSON with symbolic enum name. - const old = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":"GREEN"}` - received.Reset() - if err := json.Unmarshal([]byte(old), received); err != nil { - t.Fatalf("json.Unmarshal failed: %v", err) - } - if !Equal(received, m) { - t.Fatalf("got %s, want %s", received, m) - } -} - -func TestBadWireType(t *testing.T) { - b := []byte{7<<3 | 6} // field 7, wire type 6 - pb := new(OtherMessage) - if err := Unmarshal(b, pb); err == nil { - t.Errorf("Unmarshal did not fail") - } else if !strings.Contains(err.Error(), "unknown wire type") { - t.Errorf("wrong error: %v", err) - } -} - -func TestBytesWithInvalidLength(t *testing.T) { - // If a byte sequence has an invalid (negative) length, Unmarshal should not panic. - b := []byte{2<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0} - Unmarshal(b, new(MyMessage)) -} - -func TestLengthOverflow(t *testing.T) { - // Overflowing a length should not panic. - b := []byte{2<<3 | WireBytes, 1, 1, 3<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01} - Unmarshal(b, new(MyMessage)) -} - -func TestVarintOverflow(t *testing.T) { - // Overflowing a 64-bit length should not be allowed. - b := []byte{1<<3 | WireVarint, 0x01, 3<<3 | WireBytes, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01} - if err := Unmarshal(b, new(MyMessage)); err == nil { - t.Fatalf("Overflowed uint64 length without error") - } -} - -func TestUnmarshalFuzz(t *testing.T) { - const N = 1000 - seed := time.Now().UnixNano() - t.Logf("RNG seed is %d", seed) - rng := rand.New(rand.NewSource(seed)) - buf := make([]byte, 20) - for i := 0; i < N; i++ { - for j := range buf { - buf[j] = byte(rng.Intn(256)) - } - fuzzUnmarshal(t, buf) - } -} - -func TestMergeMessages(t *testing.T) { - pb := &MessageList{Message: []*MessageList_Message{{Name: String("x"), Count: Int32(1)}}} - data, err := Marshal(pb) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - pb1 := new(MessageList) - if err := Unmarshal(data, pb1); err != nil { - t.Fatalf("first Unmarshal: %v", err) - } - if err := Unmarshal(data, pb1); err != nil { - t.Fatalf("second Unmarshal: %v", err) - } - if len(pb1.Message) != 1 { - t.Errorf("two Unmarshals produced %d Messages, want 1", len(pb1.Message)) - } - - pb2 := new(MessageList) - if err := UnmarshalMerge(data, pb2); err != nil { - t.Fatalf("first UnmarshalMerge: %v", err) - } - if err := UnmarshalMerge(data, pb2); err != nil { - t.Fatalf("second UnmarshalMerge: %v", err) - } - if len(pb2.Message) != 2 { - t.Errorf("two UnmarshalMerges produced %d Messages, want 2", len(pb2.Message)) - } -} - -func TestExtensionMarshalOrder(t *testing.T) { - m := &MyMessage{Count: Int(123)} - if err := SetExtension(m, E_Ext_More, &Ext{Data: String("alpha")}); err != nil { - t.Fatalf("SetExtension: %v", err) - } - if err := SetExtension(m, E_Ext_Text, String("aleph")); err != nil { - t.Fatalf("SetExtension: %v", err) - } - if err := SetExtension(m, E_Ext_Number, Int32(1)); err != nil { - t.Fatalf("SetExtension: %v", err) - } - - // Serialize m several times, and check we get the same bytes each time. - var orig []byte - for i := 0; i < 100; i++ { - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if i == 0 { - orig = b - continue - } - if !bytes.Equal(b, orig) { - t.Errorf("Bytes differ on attempt #%d", i) - } - } -} - -// Many extensions, because small maps might not iterate differently on each iteration. -var exts = []*ExtensionDesc{ - E_X201, - E_X202, - E_X203, - E_X204, - E_X205, - E_X206, - E_X207, - E_X208, - E_X209, - E_X210, - E_X211, - E_X212, - E_X213, - E_X214, - E_X215, - E_X216, - E_X217, - E_X218, - E_X219, - E_X220, - E_X221, - E_X222, - E_X223, - E_X224, - E_X225, - E_X226, - E_X227, - E_X228, - E_X229, - E_X230, - E_X231, - E_X232, - E_X233, - E_X234, - E_X235, - E_X236, - E_X237, - E_X238, - E_X239, - E_X240, - E_X241, - E_X242, - E_X243, - E_X244, - E_X245, - E_X246, - E_X247, - E_X248, - E_X249, - E_X250, -} - -func TestMessageSetMarshalOrder(t *testing.T) { - m := &MyMessageSet{} - for _, x := range exts { - if err := SetExtension(m, x, &Empty{}); err != nil { - t.Fatalf("SetExtension: %v", err) - } - } - - buf, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - // Serialize m several times, and check we get the same bytes each time. - for i := 0; i < 10; i++ { - b1, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if !bytes.Equal(b1, buf) { - t.Errorf("Bytes differ on re-Marshal #%d", i) - } - - m2 := &MyMessageSet{} - if err := Unmarshal(buf, m2); err != nil { - t.Errorf("Unmarshal: %v", err) - } - b2, err := Marshal(m2) - if err != nil { - t.Errorf("re-Marshal: %v", err) - } - if !bytes.Equal(b2, buf) { - t.Errorf("Bytes differ on round-trip #%d", i) - } - } -} - -func TestUnmarshalMergesMessages(t *testing.T) { - // If a nested message occurs twice in the input, - // the fields should be merged when decoding. - a := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("polhode"), - Port: Int32(1234), - }, - } - aData, err := Marshal(a) - if err != nil { - t.Fatalf("Marshal(a): %v", err) - } - b := &OtherMessage{ - Weight: Float32(1.2), - Inner: &InnerMessage{ - Host: String("herpolhode"), - Connected: Bool(true), - }, - } - bData, err := Marshal(b) - if err != nil { - t.Fatalf("Marshal(b): %v", err) - } - want := &OtherMessage{ - Key: Int64(123), - Weight: Float32(1.2), - Inner: &InnerMessage{ - Host: String("herpolhode"), - Port: Int32(1234), - Connected: Bool(true), - }, - } - got := new(OtherMessage) - if err := Unmarshal(append(aData, bData...), got); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if !Equal(got, want) { - t.Errorf("\n got %v\nwant %v", got, want) - } -} - -func TestEncodingSizes(t *testing.T) { - tests := []struct { - m Message - n int - }{ - {&Defaults{F_Int32: Int32(math.MaxInt32)}, 6}, - {&Defaults{F_Int32: Int32(math.MinInt32)}, 11}, - {&Defaults{F_Uint32: Uint32(uint32(math.MaxInt32) + 1)}, 6}, - {&Defaults{F_Uint32: Uint32(math.MaxUint32)}, 6}, - } - for _, test := range tests { - b, err := Marshal(test.m) - if err != nil { - t.Errorf("Marshal(%v): %v", test.m, err) - continue - } - if len(b) != test.n { - t.Errorf("Marshal(%v) yielded %d bytes, want %d bytes", test.m, len(b), test.n) - } - } -} - -func TestRequiredNotSetError(t *testing.T) { - pb := initGoTest(false) - pb.RequiredField.Label = nil - pb.F_Int32Required = nil - pb.F_Int64Required = nil - - expected := "0807" + // field 1, encoding 0, value 7 - "2206" + "120474797065" + // field 4, encoding 2 (GoTestField) - "5001" + // field 10, encoding 0, value 1 - "6d20000000" + // field 13, encoding 5, value 0x20 - "714000000000000000" + // field 14, encoding 1, value 0x40 - "78a019" + // field 15, encoding 0, value 0xca0 = 3232 - "8001c032" + // field 16, encoding 0, value 0x1940 = 6464 - "8d0100004a45" + // field 17, encoding 5, value 3232.0 - "9101000000000040b940" + // field 18, encoding 1, value 6464.0 - "9a0106" + "737472696e67" + // field 19, encoding 2, string "string" - "b304" + // field 70, encoding 3, start group - "ba0408" + "7265717569726564" + // field 71, encoding 2, string "required" - "b404" + // field 70, encoding 4, end group - "aa0605" + "6279746573" + // field 101, encoding 2, string "bytes" - "b0063f" + // field 102, encoding 0, 0x3f zigzag32 - "b8067f" // field 103, encoding 0, 0x7f zigzag64 - - o := old() - bytes, err := Marshal(pb) - if _, ok := err.(*RequiredNotSetError); !ok { - fmt.Printf("marshal-1 err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("expected = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.Label") < 0 { - t.Errorf("marshal-1 wrong err msg: %v", err) - } - if !equal(bytes, expected, t) { - o.DebugPrint("neq 1", bytes) - t.Fatalf("expected = %s", expected) - } - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - err = Unmarshal(bytes, pbd) - if _, ok := err.(*RequiredNotSetError); !ok { - t.Fatalf("unmarshal err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("string = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.{Unknown}") < 0 { - t.Errorf("unmarshal wrong err msg: %v", err) - } - bytes, err = Marshal(pbd) - if _, ok := err.(*RequiredNotSetError); !ok { - t.Errorf("marshal-2 err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("string = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.Label") < 0 { - t.Errorf("marshal-2 wrong err msg: %v", err) - } - if !equal(bytes, expected, t) { - o.DebugPrint("neq 2", bytes) - t.Fatalf("string = %s", expected) - } -} - -func fuzzUnmarshal(t *testing.T, data []byte) { - defer func() { - if e := recover(); e != nil { - t.Errorf("These bytes caused a panic: %+v", data) - t.Logf("Stack:\n%s", debug.Stack()) - t.FailNow() - } - }() - - pb := new(MyMessage) - Unmarshal(data, pb) -} - -func TestMapFieldMarshal(t *testing.T) { - m := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Rob", - 4: "Ian", - 8: "Dave", - }, - } - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - // b should be the concatenation of these three byte sequences in some order. - parts := []string{ - "\n\a\b\x01\x12\x03Rob", - "\n\a\b\x04\x12\x03Ian", - "\n\b\b\x08\x12\x04Dave", - } - ok := false - for i := range parts { - for j := range parts { - if j == i { - continue - } - for k := range parts { - if k == i || k == j { - continue - } - try := parts[i] + parts[j] + parts[k] - if bytes.Equal(b, []byte(try)) { - ok = true - break - } - } - } - } - if !ok { - t.Fatalf("Incorrect Marshal output.\n got %q\nwant %q (or a permutation of that)", b, parts[0]+parts[1]+parts[2]) - } - t.Logf("FYI b: %q", b) - - (new(Buffer)).DebugPrint("Dump of b", b) -} - -func TestMapFieldRoundTrips(t *testing.T) { - m := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Rob", - 4: "Ian", - 8: "Dave", - }, - MsgMapping: map[int64]*FloatingPoint{ - 0x7001: &FloatingPoint{F: Float64(2.0)}, - }, - ByteMapping: map[bool][]byte{ - false: []byte("that's not right!"), - true: []byte("aye, 'tis true!"), - }, - } - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - t.Logf("FYI b: %q", b) - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - for _, pair := range [][2]interface{}{ - {m.NameMapping, m2.NameMapping}, - {m.MsgMapping, m2.MsgMapping}, - {m.ByteMapping, m2.ByteMapping}, - } { - if !reflect.DeepEqual(pair[0], pair[1]) { - t.Errorf("Map did not survive a round trip.\ninitial: %v\n final: %v", pair[0], pair[1]) - } - } -} - -func TestMapFieldWithNil(t *testing.T) { - m1 := &MessageWithMap{ - MsgMapping: map[int64]*FloatingPoint{ - 1: nil, - }, - } - b, err := Marshal(m1) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b) - } - if v, ok := m2.MsgMapping[1]; !ok { - t.Error("msg_mapping[1] not present") - } else if v != nil { - t.Errorf("msg_mapping[1] not nil: %v", v) - } -} - -func TestMapFieldWithNilBytes(t *testing.T) { - m1 := &MessageWithMap{ - ByteMapping: map[bool][]byte{ - false: []byte{}, - true: nil, - }, - } - n := Size(m1) - b, err := Marshal(m1) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if n != len(b) { - t.Errorf("Size(m1) = %d; want len(Marshal(m1)) = %d", n, len(b)) - } - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b) - } - if v, ok := m2.ByteMapping[false]; !ok { - t.Error("byte_mapping[false] not present") - } else if len(v) != 0 { - t.Errorf("byte_mapping[false] not empty: %#v", v) - } - if v, ok := m2.ByteMapping[true]; !ok { - t.Error("byte_mapping[true] not present") - } else if len(v) != 0 { - t.Errorf("byte_mapping[true] not empty: %#v", v) - } -} - -func TestDecodeMapFieldMissingKey(t *testing.T) { - b := []byte{ - 0x0A, 0x03, // message, tag 1 (name_mapping), of length 3 bytes - // no key - 0x12, 0x01, 0x6D, // string value of length 1 byte, value "m" - } - got := &MessageWithMap{} - err := Unmarshal(b, got) - if err != nil { - t.Fatalf("failed to marshal map with missing key: %v", err) - } - want := &MessageWithMap{NameMapping: map[int32]string{0: "m"}} - if !Equal(got, want) { - t.Errorf("Unmarshaled map with no key was not as expected. got: %v, want %v", got, want) - } -} - -func TestDecodeMapFieldMissingValue(t *testing.T) { - b := []byte{ - 0x0A, 0x02, // message, tag 1 (name_mapping), of length 2 bytes - 0x08, 0x01, // varint key, value 1 - // no value - } - got := &MessageWithMap{} - err := Unmarshal(b, got) - if err != nil { - t.Fatalf("failed to marshal map with missing value: %v", err) - } - want := &MessageWithMap{NameMapping: map[int32]string{1: ""}} - if !Equal(got, want) { - t.Errorf("Unmarshaled map with no value was not as expected. got: %v, want %v", got, want) - } -} - -func TestOneof(t *testing.T) { - m := &Communique{} - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal of empty message with oneof: %v", err) - } - if len(b) != 0 { - t.Errorf("Marshal of empty message yielded too many bytes: %v", b) - } - - m = &Communique{ - Union: &Communique_Name{"Barry"}, - } - - // Round-trip. - b, err = Marshal(m) - if err != nil { - t.Fatalf("Marshal of message with oneof: %v", err) - } - if len(b) != 7 { // name tag/wire (1) + name len (1) + name (5) - t.Errorf("Incorrect marshal of message with oneof: %v", b) - } - m.Reset() - if err := Unmarshal(b, m); err != nil { - t.Fatalf("Unmarshal of message with oneof: %v", err) - } - if x, ok := m.Union.(*Communique_Name); !ok || x.Name != "Barry" { - t.Errorf("After round trip, Union = %+v", m.Union) - } - if name := m.GetName(); name != "Barry" { - t.Errorf("After round trip, GetName = %q, want %q", name, "Barry") - } - - // Let's try with a message in the oneof. - m.Union = &Communique_Msg{&Strings{StringField: String("deep deep string")}} - b, err = Marshal(m) - if err != nil { - t.Fatalf("Marshal of message with oneof set to message: %v", err) - } - if len(b) != 20 { // msg tag/wire (1) + msg len (1) + msg (1 + 1 + 16) - t.Errorf("Incorrect marshal of message with oneof set to message: %v", b) - } - m.Reset() - if err := Unmarshal(b, m); err != nil { - t.Fatalf("Unmarshal of message with oneof set to message: %v", err) - } - ss, ok := m.Union.(*Communique_Msg) - if !ok || ss.Msg.GetStringField() != "deep deep string" { - t.Errorf("After round trip with oneof set to message, Union = %+v", m.Union) - } -} - -func TestInefficientPackedBool(t *testing.T) { - // https://github.com/golang/protobuf/issues/76 - inp := []byte{ - 0x12, 0x02, // 0x12 = 2<<3|2; 2 bytes - // Usually a bool should take a single byte, - // but it is permitted to be any varint. - 0xb9, 0x30, - } - if err := Unmarshal(inp, new(MoreRepeated)); err != nil { - t.Error(err) - } -} - -// Benchmarks - -func testMsg() *GoTest { - pb := initGoTest(true) - const N = 1000 // Internally the library starts much smaller. - pb.F_Int32Repeated = make([]int32, N) - pb.F_DoubleRepeated = make([]float64, N) - for i := 0; i < N; i++ { - pb.F_Int32Repeated[i] = int32(i) - pb.F_DoubleRepeated[i] = float64(i) - } - return pb -} - -func bytesMsg() *GoTest { - pb := initGoTest(true) - buf := make([]byte, 4000) - for i := range buf { - buf[i] = byte(i) - } - pb.F_BytesDefaulted = buf - return pb -} - -func benchmarkMarshal(b *testing.B, pb Message, marshal func(Message) ([]byte, error)) { - d, _ := marshal(pb) - b.SetBytes(int64(len(d))) - b.ResetTimer() - for i := 0; i < b.N; i++ { - marshal(pb) - } -} - -func benchmarkBufferMarshal(b *testing.B, pb Message) { - p := NewBuffer(nil) - benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { - p.Reset() - err := p.Marshal(pb0) - return p.Bytes(), err - }) -} - -func benchmarkSize(b *testing.B, pb Message) { - benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { - Size(pb) - return nil, nil - }) -} - -func newOf(pb Message) Message { - in := reflect.ValueOf(pb) - if in.IsNil() { - return pb - } - return reflect.New(in.Type().Elem()).Interface().(Message) -} - -func benchmarkUnmarshal(b *testing.B, pb Message, unmarshal func([]byte, Message) error) { - d, _ := Marshal(pb) - b.SetBytes(int64(len(d))) - pbd := newOf(pb) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - unmarshal(d, pbd) - } -} - -func benchmarkBufferUnmarshal(b *testing.B, pb Message) { - p := NewBuffer(nil) - benchmarkUnmarshal(b, pb, func(d []byte, pb0 Message) error { - p.SetBuf(d) - return p.Unmarshal(pb0) - }) -} - -// Benchmark{Marshal,BufferMarshal,Size,Unmarshal,BufferUnmarshal}{,Bytes} - -func BenchmarkMarshal(b *testing.B) { - benchmarkMarshal(b, testMsg(), Marshal) -} - -func BenchmarkBufferMarshal(b *testing.B) { - benchmarkBufferMarshal(b, testMsg()) -} - -func BenchmarkSize(b *testing.B) { - benchmarkSize(b, testMsg()) -} - -func BenchmarkUnmarshal(b *testing.B) { - benchmarkUnmarshal(b, testMsg(), Unmarshal) -} - -func BenchmarkBufferUnmarshal(b *testing.B) { - benchmarkBufferUnmarshal(b, testMsg()) -} - -func BenchmarkMarshalBytes(b *testing.B) { - benchmarkMarshal(b, bytesMsg(), Marshal) -} - -func BenchmarkBufferMarshalBytes(b *testing.B) { - benchmarkBufferMarshal(b, bytesMsg()) -} - -func BenchmarkSizeBytes(b *testing.B) { - benchmarkSize(b, bytesMsg()) -} - -func BenchmarkUnmarshalBytes(b *testing.B) { - benchmarkUnmarshal(b, bytesMsg(), Unmarshal) -} - -func BenchmarkBufferUnmarshalBytes(b *testing.B) { - benchmarkBufferUnmarshal(b, bytesMsg()) -} - -func BenchmarkUnmarshalUnrecognizedFields(b *testing.B) { - b.StopTimer() - pb := initGoTestField() - skip := &GoSkipTest{ - SkipInt32: Int32(32), - SkipFixed32: Uint32(3232), - SkipFixed64: Uint64(6464), - SkipString: String("skipper"), - Skipgroup: &GoSkipTest_SkipGroup{ - GroupInt32: Int32(75), - GroupString: String("wxyz"), - }, - } - - pbd := new(GoTestField) - p := NewBuffer(nil) - p.Marshal(pb) - p.Marshal(skip) - p2 := NewBuffer(nil) - - b.StartTimer() - for i := 0; i < b.N; i++ { - p2.SetBuf(p.Bytes()) - p2.Unmarshal(pbd) - } -} diff --git a/vendor/github.com/golang/protobuf/proto/any_test.go b/vendor/github.com/golang/protobuf/proto/any_test.go deleted file mode 100644 index 1a3c22ed..00000000 --- a/vendor/github.com/golang/protobuf/proto/any_test.go +++ /dev/null @@ -1,300 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto_test - -import ( - "strings" - "testing" - - "github.com/golang/protobuf/proto" - - pb "github.com/golang/protobuf/proto/proto3_proto" - testpb "github.com/golang/protobuf/proto/testdata" - anypb "github.com/golang/protobuf/ptypes/any" -) - -var ( - expandedMarshaler = proto.TextMarshaler{ExpandAny: true} - expandedCompactMarshaler = proto.TextMarshaler{Compact: true, ExpandAny: true} -) - -// anyEqual reports whether two messages which may be google.protobuf.Any or may -// contain google.protobuf.Any fields are equal. We can't use proto.Equal for -// comparison, because semantically equivalent messages may be marshaled to -// binary in different tag order. Instead, trust that TextMarshaler with -// ExpandAny option works and compare the text marshaling results. -func anyEqual(got, want proto.Message) bool { - // if messages are proto.Equal, no need to marshal. - if proto.Equal(got, want) { - return true - } - g := expandedMarshaler.Text(got) - w := expandedMarshaler.Text(want) - return g == w -} - -type golden struct { - m proto.Message - t, c string -} - -var goldenMessages = makeGolden() - -func makeGolden() []golden { - nested := &pb.Nested{Bunny: "Monty"} - nb, err := proto.Marshal(nested) - if err != nil { - panic(err) - } - m1 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb}, - } - m2 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: "http://[::1]/type.googleapis.com/" + proto.MessageName(nested), Value: nb}, - } - m3 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: `type.googleapis.com/"/` + proto.MessageName(nested), Value: nb}, - } - m4 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: "type.googleapis.com/a/path/" + proto.MessageName(nested), Value: nb}, - } - m5 := &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb} - - any1 := &testpb.MyMessage{Count: proto.Int32(47), Name: proto.String("David")} - proto.SetExtension(any1, testpb.E_Ext_More, &testpb.Ext{Data: proto.String("foo")}) - proto.SetExtension(any1, testpb.E_Ext_Text, proto.String("bar")) - any1b, err := proto.Marshal(any1) - if err != nil { - panic(err) - } - any2 := &testpb.MyMessage{Count: proto.Int32(42), Bikeshed: testpb.MyMessage_GREEN.Enum(), RepBytes: [][]byte{[]byte("roboto")}} - proto.SetExtension(any2, testpb.E_Ext_More, &testpb.Ext{Data: proto.String("baz")}) - any2b, err := proto.Marshal(any2) - if err != nil { - panic(err) - } - m6 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b}, - ManyThings: []*anypb.Any{ - &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any2), Value: any2b}, - &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b}, - }, - } - - const ( - m1Golden = ` -name: "David" -result_count: 47 -anything: < - [type.googleapis.com/proto3_proto.Nested]: < - bunny: "Monty" - > -> -` - m2Golden = ` -name: "David" -result_count: 47 -anything: < - ["http://[::1]/type.googleapis.com/proto3_proto.Nested"]: < - bunny: "Monty" - > -> -` - m3Golden = ` -name: "David" -result_count: 47 -anything: < - ["type.googleapis.com/\"/proto3_proto.Nested"]: < - bunny: "Monty" - > -> -` - m4Golden = ` -name: "David" -result_count: 47 -anything: < - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Monty" - > -> -` - m5Golden = ` -[type.googleapis.com/proto3_proto.Nested]: < - bunny: "Monty" -> -` - m6Golden = ` -name: "David" -result_count: 47 -anything: < - [type.googleapis.com/testdata.MyMessage]: < - count: 47 - name: "David" - [testdata.Ext.more]: < - data: "foo" - > - [testdata.Ext.text]: "bar" - > -> -many_things: < - [type.googleapis.com/testdata.MyMessage]: < - count: 42 - bikeshed: GREEN - rep_bytes: "roboto" - [testdata.Ext.more]: < - data: "baz" - > - > -> -many_things: < - [type.googleapis.com/testdata.MyMessage]: < - count: 47 - name: "David" - [testdata.Ext.more]: < - data: "foo" - > - [testdata.Ext.text]: "bar" - > -> -` - ) - return []golden{ - {m1, strings.TrimSpace(m1Golden) + "\n", strings.TrimSpace(compact(m1Golden)) + " "}, - {m2, strings.TrimSpace(m2Golden) + "\n", strings.TrimSpace(compact(m2Golden)) + " "}, - {m3, strings.TrimSpace(m3Golden) + "\n", strings.TrimSpace(compact(m3Golden)) + " "}, - {m4, strings.TrimSpace(m4Golden) + "\n", strings.TrimSpace(compact(m4Golden)) + " "}, - {m5, strings.TrimSpace(m5Golden) + "\n", strings.TrimSpace(compact(m5Golden)) + " "}, - {m6, strings.TrimSpace(m6Golden) + "\n", strings.TrimSpace(compact(m6Golden)) + " "}, - } -} - -func TestMarshalGolden(t *testing.T) { - for _, tt := range goldenMessages { - if got, want := expandedMarshaler.Text(tt.m), tt.t; got != want { - t.Errorf("message %v: got:\n%s\nwant:\n%s", tt.m, got, want) - } - if got, want := expandedCompactMarshaler.Text(tt.m), tt.c; got != want { - t.Errorf("message %v: got:\n`%s`\nwant:\n`%s`", tt.m, got, want) - } - } -} - -func TestUnmarshalGolden(t *testing.T) { - for _, tt := range goldenMessages { - want := tt.m - got := proto.Clone(tt.m) - got.Reset() - if err := proto.UnmarshalText(tt.t, got); err != nil { - t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.t, err) - } - if !anyEqual(got, want) { - t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.t, got, want) - } - got.Reset() - if err := proto.UnmarshalText(tt.c, got); err != nil { - t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.c, err) - } - if !anyEqual(got, want) { - t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.c, got, want) - } - } -} - -func TestMarshalUnknownAny(t *testing.T) { - m := &pb.Message{ - Anything: &anypb.Any{ - TypeUrl: "foo", - Value: []byte("bar"), - }, - } - want := `anything: < - type_url: "foo" - value: "bar" -> -` - got := expandedMarshaler.Text(m) - if got != want { - t.Errorf("got\n`%s`\nwant\n`%s`", got, want) - } -} - -func TestAmbiguousAny(t *testing.T) { - pb := &anypb.Any{} - err := proto.UnmarshalText(` - type_url: "ttt/proto3_proto.Nested" - value: "\n\x05Monty" - `, pb) - t.Logf("result: %v (error: %v)", expandedMarshaler.Text(pb), err) - if err != nil { - t.Errorf("failed to parse ambiguous Any message: %v", err) - } -} - -func TestUnmarshalOverwriteAny(t *testing.T) { - pb := &anypb.Any{} - err := proto.UnmarshalText(` - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Monty" - > - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Rabbit of Caerbannog" - > - `, pb) - want := `line 7: Any message unpacked multiple times, or "type_url" already set` - if err.Error() != want { - t.Errorf("incorrect error.\nHave: %v\nWant: %v", err.Error(), want) - } -} - -func TestUnmarshalAnyMixAndMatch(t *testing.T) { - pb := &anypb.Any{} - err := proto.UnmarshalText(` - value: "\n\x05Monty" - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Rabbit of Caerbannog" - > - `, pb) - want := `line 5: Any message unpacked multiple times, or "value" already set` - if err.Error() != want { - t.Errorf("incorrect error.\nHave: %v\nWant: %v", err.Error(), want) - } -} diff --git a/vendor/github.com/golang/protobuf/proto/clone_test.go b/vendor/github.com/golang/protobuf/proto/clone_test.go deleted file mode 100644 index f607ff49..00000000 --- a/vendor/github.com/golang/protobuf/proto/clone_test.go +++ /dev/null @@ -1,300 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto_test - -import ( - "testing" - - "github.com/golang/protobuf/proto" - - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - pb "github.com/golang/protobuf/proto/testdata" -) - -var cloneTestMessage = &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &pb.InnerMessage{ - Host: proto.String("niles"), - Port: proto.Int32(9099), - Connected: proto.Bool(true), - }, - Others: []*pb.OtherMessage{ - { - Value: []byte("some bytes"), - }, - }, - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, -} - -func init() { - ext := &pb.Ext{ - Data: proto.String("extension"), - } - if err := proto.SetExtension(cloneTestMessage, pb.E_Ext_More, ext); err != nil { - panic("SetExtension: " + err.Error()) - } -} - -func TestClone(t *testing.T) { - m := proto.Clone(cloneTestMessage).(*pb.MyMessage) - if !proto.Equal(m, cloneTestMessage) { - t.Errorf("Clone(%v) = %v", cloneTestMessage, m) - } - - // Verify it was a deep copy. - *m.Inner.Port++ - if proto.Equal(m, cloneTestMessage) { - t.Error("Mutating clone changed the original") - } - // Byte fields and repeated fields should be copied. - if &m.Pet[0] == &cloneTestMessage.Pet[0] { - t.Error("Pet: repeated field not copied") - } - if &m.Others[0] == &cloneTestMessage.Others[0] { - t.Error("Others: repeated field not copied") - } - if &m.Others[0].Value[0] == &cloneTestMessage.Others[0].Value[0] { - t.Error("Others[0].Value: bytes field not copied") - } - if &m.RepBytes[0] == &cloneTestMessage.RepBytes[0] { - t.Error("RepBytes: repeated field not copied") - } - if &m.RepBytes[0][0] == &cloneTestMessage.RepBytes[0][0] { - t.Error("RepBytes[0]: bytes field not copied") - } -} - -func TestCloneNil(t *testing.T) { - var m *pb.MyMessage - if c := proto.Clone(m); !proto.Equal(m, c) { - t.Errorf("Clone(%v) = %v", m, c) - } -} - -var mergeTests = []struct { - src, dst, want proto.Message -}{ - { - src: &pb.MyMessage{ - Count: proto.Int32(42), - }, - dst: &pb.MyMessage{ - Name: proto.String("Dave"), - }, - want: &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - }, - }, - { - src: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("hey"), - Connected: proto.Bool(true), - }, - Pet: []string{"horsey"}, - Others: []*pb.OtherMessage{ - { - Value: []byte("some bytes"), - }, - }, - }, - dst: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("niles"), - Port: proto.Int32(9099), - }, - Pet: []string{"bunny", "kitty"}, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(31415926535), - }, - { - // Explicitly test a src=nil field - Inner: nil, - }, - }, - }, - want: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("hey"), - Connected: proto.Bool(true), - Port: proto.Int32(9099), - }, - Pet: []string{"bunny", "kitty", "horsey"}, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(31415926535), - }, - {}, - { - Value: []byte("some bytes"), - }, - }, - }, - }, - { - src: &pb.MyMessage{ - RepBytes: [][]byte{[]byte("wow")}, - }, - dst: &pb.MyMessage{ - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham")}, - }, - want: &pb.MyMessage{ - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, - }, - }, - // Check that a scalar bytes field replaces rather than appends. - { - src: &pb.OtherMessage{Value: []byte("foo")}, - dst: &pb.OtherMessage{Value: []byte("bar")}, - want: &pb.OtherMessage{Value: []byte("foo")}, - }, - { - src: &pb.MessageWithMap{ - NameMapping: map[int32]string{6: "Nigel"}, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)}, - 0x4002: &pb.FloatingPoint{ - F: proto.Float64(2.0), - }, - }, - ByteMapping: map[bool][]byte{true: []byte("wowsa")}, - }, - dst: &pb.MessageWithMap{ - NameMapping: map[int32]string{ - 6: "Bruce", // should be overwritten - 7: "Andrew", - }, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4002: &pb.FloatingPoint{ - F: proto.Float64(3.0), - Exact: proto.Bool(true), - }, // the entire message should be overwritten - }, - }, - want: &pb.MessageWithMap{ - NameMapping: map[int32]string{ - 6: "Nigel", - 7: "Andrew", - }, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)}, - 0x4002: &pb.FloatingPoint{ - F: proto.Float64(2.0), - }, - }, - ByteMapping: map[bool][]byte{true: []byte("wowsa")}, - }, - }, - // proto3 shouldn't merge zero values, - // in the same way that proto2 shouldn't merge nils. - { - src: &proto3pb.Message{ - Name: "Aaron", - Data: []byte(""), // zero value, but not nil - }, - dst: &proto3pb.Message{ - HeightInCm: 176, - Data: []byte("texas!"), - }, - want: &proto3pb.Message{ - Name: "Aaron", - HeightInCm: 176, - Data: []byte("texas!"), - }, - }, - // Oneof fields should merge by assignment. - { - src: &pb.Communique{ - Union: &pb.Communique_Number{41}, - }, - dst: &pb.Communique{ - Union: &pb.Communique_Name{"Bobby Tables"}, - }, - want: &pb.Communique{ - Union: &pb.Communique_Number{41}, - }, - }, - // Oneof nil is the same as not set. - { - src: &pb.Communique{}, - dst: &pb.Communique{ - Union: &pb.Communique_Name{"Bobby Tables"}, - }, - want: &pb.Communique{ - Union: &pb.Communique_Name{"Bobby Tables"}, - }, - }, - { - src: &proto3pb.Message{ - Terrain: map[string]*proto3pb.Nested{ - "kay_a": &proto3pb.Nested{Cute: true}, // replace - "kay_b": &proto3pb.Nested{Bunny: "rabbit"}, // insert - }, - }, - dst: &proto3pb.Message{ - Terrain: map[string]*proto3pb.Nested{ - "kay_a": &proto3pb.Nested{Bunny: "lost"}, // replaced - "kay_c": &proto3pb.Nested{Bunny: "bunny"}, // keep - }, - }, - want: &proto3pb.Message{ - Terrain: map[string]*proto3pb.Nested{ - "kay_a": &proto3pb.Nested{Cute: true}, - "kay_b": &proto3pb.Nested{Bunny: "rabbit"}, - "kay_c": &proto3pb.Nested{Bunny: "bunny"}, - }, - }, - }, -} - -func TestMerge(t *testing.T) { - for _, m := range mergeTests { - got := proto.Clone(m.dst) - proto.Merge(got, m.src) - if !proto.Equal(got, m.want) { - t.Errorf("Merge(%v, %v)\n got %v\nwant %v\n", m.dst, m.src, got, m.want) - } - } -} diff --git a/vendor/github.com/golang/protobuf/proto/decode_test.go b/vendor/github.com/golang/protobuf/proto/decode_test.go deleted file mode 100644 index 2c4c31d1..00000000 --- a/vendor/github.com/golang/protobuf/proto/decode_test.go +++ /dev/null @@ -1,258 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -// +build go1.7 - -package proto_test - -import ( - "fmt" - "testing" - - "github.com/golang/protobuf/proto" - tpb "github.com/golang/protobuf/proto/proto3_proto" -) - -var ( - bytesBlackhole []byte - msgBlackhole = new(tpb.Message) -) - -// BenchmarkVarint32ArraySmall shows the performance on an array of small int32 fields (1 and -// 2 bytes long). -func BenchmarkVarint32ArraySmall(b *testing.B) { - for i := uint(1); i <= 10; i++ { - dist := genInt32Dist([7]int{0, 3, 1}, 1<unmarshal. -} - -func TestMarshalUnmarshalRepeatedExtension(t *testing.T) { - // Add a repeated extension to the result. - tests := []struct { - name string - ext []*pb.ComplexExtension - }{ - { - "two fields", - []*pb.ComplexExtension{ - {First: proto.Int32(7)}, - {Second: proto.Int32(11)}, - }, - }, - { - "repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {Third: []int32{2000}}, - }, - }, - { - "two fields and repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {First: proto.Int32(9)}, - {Second: proto.Int32(21)}, - {Third: []int32{2000}}, - }, - }, - } - for _, test := range tests { - // Marshal message with a repeated extension. - msg1 := new(pb.OtherMessage) - err := proto.SetExtension(msg1, pb.E_RComplex, test.ext) - if err != nil { - t.Fatalf("[%s] Error setting extension: %v", test.name, err) - } - b, err := proto.Marshal(msg1) - if err != nil { - t.Fatalf("[%s] Error marshaling message: %v", test.name, err) - } - - // Unmarshal and read the merged proto. - msg2 := new(pb.OtherMessage) - err = proto.Unmarshal(b, msg2) - if err != nil { - t.Fatalf("[%s] Error unmarshaling message: %v", test.name, err) - } - e, err := proto.GetExtension(msg2, pb.E_RComplex) - if err != nil { - t.Fatalf("[%s] Error getting extension: %v", test.name, err) - } - ext := e.([]*pb.ComplexExtension) - if ext == nil { - t.Fatalf("[%s] Invalid extension", test.name) - } - if !reflect.DeepEqual(ext, test.ext) { - t.Errorf("[%s] Wrong value for ComplexExtension: got: %v want: %v\n", test.name, ext, test.ext) - } - } -} - -func TestUnmarshalRepeatingNonRepeatedExtension(t *testing.T) { - // We may see multiple instances of the same extension in the wire - // format. For example, the proto compiler may encode custom options in - // this way. Here, we verify that we merge the extensions together. - tests := []struct { - name string - ext []*pb.ComplexExtension - }{ - { - "two fields", - []*pb.ComplexExtension{ - {First: proto.Int32(7)}, - {Second: proto.Int32(11)}, - }, - }, - { - "repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {Third: []int32{2000}}, - }, - }, - { - "two fields and repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {First: proto.Int32(9)}, - {Second: proto.Int32(21)}, - {Third: []int32{2000}}, - }, - }, - } - for _, test := range tests { - var buf bytes.Buffer - var want pb.ComplexExtension - - // Generate a serialized representation of a repeated extension - // by catenating bytes together. - for i, e := range test.ext { - // Merge to create the wanted proto. - proto.Merge(&want, e) - - // serialize the message - msg := new(pb.OtherMessage) - err := proto.SetExtension(msg, pb.E_Complex, e) - if err != nil { - t.Fatalf("[%s] Error setting extension %d: %v", test.name, i, err) - } - b, err := proto.Marshal(msg) - if err != nil { - t.Fatalf("[%s] Error marshaling message %d: %v", test.name, i, err) - } - buf.Write(b) - } - - // Unmarshal and read the merged proto. - msg2 := new(pb.OtherMessage) - err := proto.Unmarshal(buf.Bytes(), msg2) - if err != nil { - t.Fatalf("[%s] Error unmarshaling message: %v", test.name, err) - } - e, err := proto.GetExtension(msg2, pb.E_Complex) - if err != nil { - t.Fatalf("[%s] Error getting extension: %v", test.name, err) - } - ext := e.(*pb.ComplexExtension) - if ext == nil { - t.Fatalf("[%s] Invalid extension", test.name) - } - if !reflect.DeepEqual(*ext, want) { - t.Errorf("[%s] Wrong value for ComplexExtension: got: %s want: %s\n", test.name, ext, want) - } - } -} - -func TestClearAllExtensions(t *testing.T) { - // unregistered extension - desc := &proto.ExtensionDesc{ - ExtendedType: (*pb.MyMessage)(nil), - ExtensionType: (*bool)(nil), - Field: 101010100, - Name: "emptyextension", - Tag: "varint,0,opt", - } - m := &pb.MyMessage{} - if proto.HasExtension(m, desc) { - t.Errorf("proto.HasExtension(%s): got true, want false", proto.MarshalTextString(m)) - } - if err := proto.SetExtension(m, desc, proto.Bool(true)); err != nil { - t.Errorf("proto.SetExtension(m, desc, true): got error %q, want nil", err) - } - if !proto.HasExtension(m, desc) { - t.Errorf("proto.HasExtension(%s): got false, want true", proto.MarshalTextString(m)) - } - proto.ClearAllExtensions(m) - if proto.HasExtension(m, desc) { - t.Errorf("proto.HasExtension(%s): got true, want false", proto.MarshalTextString(m)) - } -} - -func TestMarshalRace(t *testing.T) { - // unregistered extension - desc := &proto.ExtensionDesc{ - ExtendedType: (*pb.MyMessage)(nil), - ExtensionType: (*bool)(nil), - Field: 101010100, - Name: "emptyextension", - Tag: "varint,0,opt", - } - - m := &pb.MyMessage{Count: proto.Int32(4)} - if err := proto.SetExtension(m, desc, proto.Bool(true)); err != nil { - t.Errorf("proto.SetExtension(m, desc, true): got error %q, want nil", err) - } - - var g errgroup.Group - for n := 3; n > 0; n-- { - g.Go(func() error { - _, err := proto.Marshal(m) - return err - }) - } - if err := g.Wait(); err != nil { - t.Fatal(err) - } -} diff --git a/vendor/github.com/golang/protobuf/proto/map_test.go b/vendor/github.com/golang/protobuf/proto/map_test.go deleted file mode 100644 index 313e8792..00000000 --- a/vendor/github.com/golang/protobuf/proto/map_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package proto_test - -import ( - "fmt" - "testing" - - "github.com/golang/protobuf/proto" - ppb "github.com/golang/protobuf/proto/proto3_proto" -) - -func marshalled() []byte { - m := &ppb.IntMaps{} - for i := 0; i < 1000; i++ { - m.Maps = append(m.Maps, &ppb.IntMap{ - Rtt: map[int32]int32{1: 2}, - }) - } - b, err := proto.Marshal(m) - if err != nil { - panic(fmt.Sprintf("Can't marshal %+v: %v", m, err)) - } - return b -} - -func BenchmarkConcurrentMapUnmarshal(b *testing.B) { - in := marshalled() - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - var out ppb.IntMaps - if err := proto.Unmarshal(in, &out); err != nil { - b.Errorf("Can't unmarshal ppb.IntMaps: %v", err) - } - } - }) -} - -func BenchmarkSequentialMapUnmarshal(b *testing.B) { - in := marshalled() - b.ResetTimer() - for i := 0; i < b.N; i++ { - var out ppb.IntMaps - if err := proto.Unmarshal(in, &out); err != nil { - b.Errorf("Can't unmarshal ppb.IntMaps: %v", err) - } - } -} diff --git a/vendor/github.com/golang/protobuf/proto/message_set_test.go b/vendor/github.com/golang/protobuf/proto/message_set_test.go deleted file mode 100644 index 353a3ea7..00000000 --- a/vendor/github.com/golang/protobuf/proto/message_set_test.go +++ /dev/null @@ -1,66 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto - -import ( - "bytes" - "testing" -) - -func TestUnmarshalMessageSetWithDuplicate(t *testing.T) { - // Check that a repeated message set entry will be concatenated. - in := &messageSet{ - Item: []*_MessageSet_Item{ - {TypeId: Int32(12345), Message: []byte("hoo")}, - {TypeId: Int32(12345), Message: []byte("hah")}, - }, - } - b, err := Marshal(in) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - t.Logf("Marshaled bytes: %q", b) - - var extensions XXX_InternalExtensions - if err := UnmarshalMessageSet(b, &extensions); err != nil { - t.Fatalf("UnmarshalMessageSet: %v", err) - } - ext, ok := extensions.p.extensionMap[12345] - if !ok { - t.Fatalf("Didn't retrieve extension 12345; map is %v", extensions.p.extensionMap) - } - // Skip wire type/field number and length varints. - got := skipVarint(skipVarint(ext.enc)) - if want := []byte("hoohah"); !bytes.Equal(got, want) { - t.Errorf("Combined extension is %q, want %q", got, want) - } -} diff --git a/vendor/github.com/golang/protobuf/proto/proto3_test.go b/vendor/github.com/golang/protobuf/proto/proto3_test.go deleted file mode 100644 index 735837f2..00000000 --- a/vendor/github.com/golang/protobuf/proto/proto3_test.go +++ /dev/null @@ -1,135 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto_test - -import ( - "testing" - - "github.com/golang/protobuf/proto" - pb "github.com/golang/protobuf/proto/proto3_proto" - tpb "github.com/golang/protobuf/proto/testdata" -) - -func TestProto3ZeroValues(t *testing.T) { - tests := []struct { - desc string - m proto.Message - }{ - {"zero message", &pb.Message{}}, - {"empty bytes field", &pb.Message{Data: []byte{}}}, - } - for _, test := range tests { - b, err := proto.Marshal(test.m) - if err != nil { - t.Errorf("%s: proto.Marshal: %v", test.desc, err) - continue - } - if len(b) > 0 { - t.Errorf("%s: Encoding is non-empty: %q", test.desc, b) - } - } -} - -func TestRoundTripProto3(t *testing.T) { - m := &pb.Message{ - Name: "David", // (2 | 1<<3): 0x0a 0x05 "David" - Hilarity: pb.Message_PUNS, // (0 | 2<<3): 0x10 0x01 - HeightInCm: 178, // (0 | 3<<3): 0x18 0xb2 0x01 - Data: []byte("roboto"), // (2 | 4<<3): 0x20 0x06 "roboto" - ResultCount: 47, // (0 | 7<<3): 0x38 0x2f - TrueScotsman: true, // (0 | 8<<3): 0x40 0x01 - Score: 8.1, // (5 | 9<<3): 0x4d <8.1> - - Key: []uint64{1, 0xdeadbeef}, - Nested: &pb.Nested{ - Bunny: "Monty", - }, - } - t.Logf(" m: %v", m) - - b, err := proto.Marshal(m) - if err != nil { - t.Fatalf("proto.Marshal: %v", err) - } - t.Logf(" b: %q", b) - - m2 := new(pb.Message) - if err := proto.Unmarshal(b, m2); err != nil { - t.Fatalf("proto.Unmarshal: %v", err) - } - t.Logf("m2: %v", m2) - - if !proto.Equal(m, m2) { - t.Errorf("proto.Equal returned false:\n m: %v\nm2: %v", m, m2) - } -} - -func TestGettersForBasicTypesExist(t *testing.T) { - var m pb.Message - if got := m.GetNested().GetBunny(); got != "" { - t.Errorf("m.GetNested().GetBunny() = %q, want empty string", got) - } - if got := m.GetNested().GetCute(); got { - t.Errorf("m.GetNested().GetCute() = %t, want false", got) - } -} - -func TestProto3SetDefaults(t *testing.T) { - in := &pb.Message{ - Terrain: map[string]*pb.Nested{ - "meadow": new(pb.Nested), - }, - Proto2Field: new(tpb.SubDefaults), - Proto2Value: map[string]*tpb.SubDefaults{ - "badlands": new(tpb.SubDefaults), - }, - } - - got := proto.Clone(in).(*pb.Message) - proto.SetDefaults(got) - - // There are no defaults in proto3. Everything should be the zero value, but - // we need to remember to set defaults for nested proto2 messages. - want := &pb.Message{ - Terrain: map[string]*pb.Nested{ - "meadow": new(pb.Nested), - }, - Proto2Field: &tpb.SubDefaults{N: proto.Int64(7)}, - Proto2Value: map[string]*tpb.SubDefaults{ - "badlands": &tpb.SubDefaults{N: proto.Int64(7)}, - }, - } - - if !proto.Equal(got, want) { - t.Errorf("with in = %v\nproto.SetDefaults(in) =>\ngot %v\nwant %v", in, got, want) - } -} diff --git a/vendor/github.com/golang/protobuf/proto/size2_test.go b/vendor/github.com/golang/protobuf/proto/size2_test.go deleted file mode 100644 index a2729c39..00000000 --- a/vendor/github.com/golang/protobuf/proto/size2_test.go +++ /dev/null @@ -1,63 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto - -import ( - "testing" -) - -// This is a separate file and package from size_test.go because that one uses -// generated messages and thus may not be in package proto without having a circular -// dependency, whereas this file tests unexported details of size.go. - -func TestVarintSize(t *testing.T) { - // Check the edge cases carefully. - testCases := []struct { - n uint64 - size int - }{ - {0, 1}, - {1, 1}, - {127, 1}, - {128, 2}, - {16383, 2}, - {16384, 3}, - {1<<63 - 1, 9}, - {1 << 63, 10}, - } - for _, tc := range testCases { - size := sizeVarint(tc.n) - if size != tc.size { - t.Errorf("sizeVarint(%d) = %d, want %d", tc.n, size, tc.size) - } - } -} diff --git a/vendor/github.com/golang/protobuf/proto/size_test.go b/vendor/github.com/golang/protobuf/proto/size_test.go deleted file mode 100644 index af1034dc..00000000 --- a/vendor/github.com/golang/protobuf/proto/size_test.go +++ /dev/null @@ -1,164 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto_test - -import ( - "log" - "strings" - "testing" - - . "github.com/golang/protobuf/proto" - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - pb "github.com/golang/protobuf/proto/testdata" -) - -var messageWithExtension1 = &pb.MyMessage{Count: Int32(7)} - -// messageWithExtension2 is in equal_test.go. -var messageWithExtension3 = &pb.MyMessage{Count: Int32(8)} - -func init() { - if err := SetExtension(messageWithExtension1, pb.E_Ext_More, &pb.Ext{Data: String("Abbott")}); err != nil { - log.Panicf("SetExtension: %v", err) - } - if err := SetExtension(messageWithExtension3, pb.E_Ext_More, &pb.Ext{Data: String("Costello")}); err != nil { - log.Panicf("SetExtension: %v", err) - } - - // Force messageWithExtension3 to have the extension encoded. - Marshal(messageWithExtension3) - -} - -var SizeTests = []struct { - desc string - pb Message -}{ - {"empty", &pb.OtherMessage{}}, - // Basic types. - {"bool", &pb.Defaults{F_Bool: Bool(true)}}, - {"int32", &pb.Defaults{F_Int32: Int32(12)}}, - {"negative int32", &pb.Defaults{F_Int32: Int32(-1)}}, - {"small int64", &pb.Defaults{F_Int64: Int64(1)}}, - {"big int64", &pb.Defaults{F_Int64: Int64(1 << 20)}}, - {"negative int64", &pb.Defaults{F_Int64: Int64(-1)}}, - {"fixed32", &pb.Defaults{F_Fixed32: Uint32(71)}}, - {"fixed64", &pb.Defaults{F_Fixed64: Uint64(72)}}, - {"uint32", &pb.Defaults{F_Uint32: Uint32(123)}}, - {"uint64", &pb.Defaults{F_Uint64: Uint64(124)}}, - {"float", &pb.Defaults{F_Float: Float32(12.6)}}, - {"double", &pb.Defaults{F_Double: Float64(13.9)}}, - {"string", &pb.Defaults{F_String: String("niles")}}, - {"bytes", &pb.Defaults{F_Bytes: []byte("wowsa")}}, - {"bytes, empty", &pb.Defaults{F_Bytes: []byte{}}}, - {"sint32", &pb.Defaults{F_Sint32: Int32(65)}}, - {"sint64", &pb.Defaults{F_Sint64: Int64(67)}}, - {"enum", &pb.Defaults{F_Enum: pb.Defaults_BLUE.Enum()}}, - // Repeated. - {"empty repeated bool", &pb.MoreRepeated{Bools: []bool{}}}, - {"repeated bool", &pb.MoreRepeated{Bools: []bool{false, true, true, false}}}, - {"packed repeated bool", &pb.MoreRepeated{BoolsPacked: []bool{false, true, true, false, true, true, true}}}, - {"repeated int32", &pb.MoreRepeated{Ints: []int32{1, 12203, 1729, -1}}}, - {"repeated int32 packed", &pb.MoreRepeated{IntsPacked: []int32{1, 12203, 1729}}}, - {"repeated int64 packed", &pb.MoreRepeated{Int64SPacked: []int64{ - // Need enough large numbers to verify that the header is counting the number of bytes - // for the field, not the number of elements. - 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, - 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, - }}}, - {"repeated string", &pb.MoreRepeated{Strings: []string{"r", "ken", "gri"}}}, - {"repeated fixed", &pb.MoreRepeated{Fixeds: []uint32{1, 2, 3, 4}}}, - // Nested. - {"nested", &pb.OldMessage{Nested: &pb.OldMessage_Nested{Name: String("whatever")}}}, - {"group", &pb.GroupOld{G: &pb.GroupOld_G{X: Int32(12345)}}}, - // Other things. - {"unrecognized", &pb.MoreRepeated{XXX_unrecognized: []byte{13<<3 | 0, 4}}}, - {"extension (unencoded)", messageWithExtension1}, - {"extension (encoded)", messageWithExtension3}, - // proto3 message - {"proto3 empty", &proto3pb.Message{}}, - {"proto3 bool", &proto3pb.Message{TrueScotsman: true}}, - {"proto3 int64", &proto3pb.Message{ResultCount: 1}}, - {"proto3 uint32", &proto3pb.Message{HeightInCm: 123}}, - {"proto3 float", &proto3pb.Message{Score: 12.6}}, - {"proto3 string", &proto3pb.Message{Name: "Snezana"}}, - {"proto3 bytes", &proto3pb.Message{Data: []byte("wowsa")}}, - {"proto3 bytes, empty", &proto3pb.Message{Data: []byte{}}}, - {"proto3 enum", &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, - {"proto3 map field with empty bytes", &proto3pb.MessageWithMap{ByteMapping: map[bool][]byte{false: []byte{}}}}, - - {"map field", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob", 7: "Andrew"}}}, - {"map field with message", &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{0x7001: &pb.FloatingPoint{F: Float64(2.0)}}}}, - {"map field with bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte("this time for sure")}}}, - {"map field with empty bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte{}}}}, - - {"map field with big entry", &pb.MessageWithMap{NameMapping: map[int32]string{8: strings.Repeat("x", 125)}}}, - {"map field with big key and val", &pb.MessageWithMap{StrToStr: map[string]string{strings.Repeat("x", 70): strings.Repeat("y", 70)}}}, - {"map field with big numeric key", &pb.MessageWithMap{NameMapping: map[int32]string{0xf00d: "om nom nom"}}}, - - {"oneof not set", &pb.Oneof{}}, - {"oneof bool", &pb.Oneof{Union: &pb.Oneof_F_Bool{true}}}, - {"oneof zero int32", &pb.Oneof{Union: &pb.Oneof_F_Int32{0}}}, - {"oneof big int32", &pb.Oneof{Union: &pb.Oneof_F_Int32{1 << 20}}}, - {"oneof int64", &pb.Oneof{Union: &pb.Oneof_F_Int64{42}}}, - {"oneof fixed32", &pb.Oneof{Union: &pb.Oneof_F_Fixed32{43}}}, - {"oneof fixed64", &pb.Oneof{Union: &pb.Oneof_F_Fixed64{44}}}, - {"oneof uint32", &pb.Oneof{Union: &pb.Oneof_F_Uint32{45}}}, - {"oneof uint64", &pb.Oneof{Union: &pb.Oneof_F_Uint64{46}}}, - {"oneof float", &pb.Oneof{Union: &pb.Oneof_F_Float{47.1}}}, - {"oneof double", &pb.Oneof{Union: &pb.Oneof_F_Double{48.9}}}, - {"oneof string", &pb.Oneof{Union: &pb.Oneof_F_String{"Rhythmic Fman"}}}, - {"oneof bytes", &pb.Oneof{Union: &pb.Oneof_F_Bytes{[]byte("let go")}}}, - {"oneof sint32", &pb.Oneof{Union: &pb.Oneof_F_Sint32{50}}}, - {"oneof sint64", &pb.Oneof{Union: &pb.Oneof_F_Sint64{51}}}, - {"oneof enum", &pb.Oneof{Union: &pb.Oneof_F_Enum{pb.MyMessage_BLUE}}}, - {"message for oneof", &pb.GoTestField{Label: String("k"), Type: String("v")}}, - {"oneof message", &pb.Oneof{Union: &pb.Oneof_F_Message{&pb.GoTestField{Label: String("k"), Type: String("v")}}}}, - {"oneof group", &pb.Oneof{Union: &pb.Oneof_FGroup{&pb.Oneof_F_Group{X: Int32(52)}}}}, - {"oneof largest tag", &pb.Oneof{Union: &pb.Oneof_F_Largest_Tag{1}}}, - {"multiple oneofs", &pb.Oneof{Union: &pb.Oneof_F_Int32{1}, Tormato: &pb.Oneof_Value{2}}}, -} - -func TestSize(t *testing.T) { - for _, tc := range SizeTests { - size := Size(tc.pb) - b, err := Marshal(tc.pb) - if err != nil { - t.Errorf("%v: Marshal failed: %v", tc.desc, err) - continue - } - if size != len(b) { - t.Errorf("%v: Size(%v) = %d, want %d", tc.desc, tc.pb, size, len(b)) - t.Logf("%v: bytes: %#v", tc.desc, b) - } - } -} diff --git a/vendor/github.com/golang/protobuf/proto/text_parser_test.go b/vendor/github.com/golang/protobuf/proto/text_parser_test.go deleted file mode 100644 index 8f7cb4d2..00000000 --- a/vendor/github.com/golang/protobuf/proto/text_parser_test.go +++ /dev/null @@ -1,673 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto_test - -import ( - "math" - "reflect" - "testing" - - . "github.com/golang/protobuf/proto" - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - . "github.com/golang/protobuf/proto/testdata" -) - -type UnmarshalTextTest struct { - in string - err string // if "", no error expected - out *MyMessage -} - -func buildExtStructTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - SetExtension(msg, E_Ext_More, &Ext{ - Data: String("Hello, world!"), - }) - return UnmarshalTextTest{in: text, out: msg} -} - -func buildExtDataTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - SetExtension(msg, E_Ext_Text, String("Hello, world!")) - SetExtension(msg, E_Ext_Number, Int32(1729)) - return UnmarshalTextTest{in: text, out: msg} -} - -func buildExtRepStringTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - if err := SetExtension(msg, E_Greeting, []string{"bula", "hola"}); err != nil { - panic(err) - } - return UnmarshalTextTest{in: text, out: msg} -} - -var unMarshalTextTests = []UnmarshalTextTest{ - // Basic - { - in: " count:42\n name:\"Dave\" ", - out: &MyMessage{ - Count: Int32(42), - Name: String("Dave"), - }, - }, - - // Empty quoted string - { - in: `count:42 name:""`, - out: &MyMessage{ - Count: Int32(42), - Name: String(""), - }, - }, - - // Quoted string concatenation with double quotes - { - in: `count:42 name: "My name is "` + "\n" + `"elsewhere"`, - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string concatenation with single quotes - { - in: "count:42 name: 'My name is '\n'elsewhere'", - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string concatenations with mixed quotes - { - in: "count:42 name: 'My name is '\n\"elsewhere\"", - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - { - in: "count:42 name: \"My name is \"\n'elsewhere'", - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string with escaped apostrophe - { - in: `count:42 name: "HOLIDAY - New Year\'s Day"`, - out: &MyMessage{ - Count: Int32(42), - Name: String("HOLIDAY - New Year's Day"), - }, - }, - - // Quoted string with single quote - { - in: `count:42 name: 'Roger "The Ramster" Ramjet'`, - out: &MyMessage{ - Count: Int32(42), - Name: String(`Roger "The Ramster" Ramjet`), - }, - }, - - // Quoted string with all the accepted special characters from the C++ test - { - in: `count:42 name: ` + "\"\\\"A string with \\' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"", - out: &MyMessage{ - Count: Int32(42), - Name: String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces"), - }, - }, - - // Quoted string with quoted backslash - { - in: `count:42 name: "\\'xyz"`, - out: &MyMessage{ - Count: Int32(42), - Name: String(`\'xyz`), - }, - }, - - // Quoted string with UTF-8 bytes. - { - in: "count:42 name: '\303\277\302\201\xAB'", - out: &MyMessage{ - Count: Int32(42), - Name: String("\303\277\302\201\xAB"), - }, - }, - - // Bad quoted string - { - in: `inner: < host: "\0" >` + "\n", - err: `line 1.15: invalid quoted string "\0": \0 requires 2 following digits`, - }, - - // Number too large for int64 - { - in: "count: 1 others { key: 123456789012345678901 }", - err: "line 1.23: invalid int64: 123456789012345678901", - }, - - // Number too large for int32 - { - in: "count: 1234567890123", - err: "line 1.7: invalid int32: 1234567890123", - }, - - // Number in hexadecimal - { - in: "count: 0x2beef", - out: &MyMessage{ - Count: Int32(0x2beef), - }, - }, - - // Number in octal - { - in: "count: 024601", - out: &MyMessage{ - Count: Int32(024601), - }, - }, - - // Floating point number with "f" suffix - { - in: "count: 4 others:< weight: 17.0f >", - out: &MyMessage{ - Count: Int32(4), - Others: []*OtherMessage{ - { - Weight: Float32(17), - }, - }, - }, - }, - - // Floating point positive infinity - { - in: "count: 4 bigfloat: inf", - out: &MyMessage{ - Count: Int32(4), - Bigfloat: Float64(math.Inf(1)), - }, - }, - - // Floating point negative infinity - { - in: "count: 4 bigfloat: -inf", - out: &MyMessage{ - Count: Int32(4), - Bigfloat: Float64(math.Inf(-1)), - }, - }, - - // Number too large for float32 - { - in: "others:< weight: 12345678901234567890123456789012345678901234567890 >", - err: "line 1.17: invalid float32: 12345678901234567890123456789012345678901234567890", - }, - - // Number posing as a quoted string - { - in: `inner: < host: 12 >` + "\n", - err: `line 1.15: invalid string: 12`, - }, - - // Quoted string posing as int32 - { - in: `count: "12"`, - err: `line 1.7: invalid int32: "12"`, - }, - - // Quoted string posing a float32 - { - in: `others:< weight: "17.4" >`, - err: `line 1.17: invalid float32: "17.4"`, - }, - - // Enum - { - in: `count:42 bikeshed: BLUE`, - out: &MyMessage{ - Count: Int32(42), - Bikeshed: MyMessage_BLUE.Enum(), - }, - }, - - // Repeated field - { - in: `count:42 pet: "horsey" pet:"bunny"`, - out: &MyMessage{ - Count: Int32(42), - Pet: []string{"horsey", "bunny"}, - }, - }, - - // Repeated field with list notation - { - in: `count:42 pet: ["horsey", "bunny"]`, - out: &MyMessage{ - Count: Int32(42), - Pet: []string{"horsey", "bunny"}, - }, - }, - - // Repeated message with/without colon and <>/{} - { - in: `count:42 others:{} others{} others:<> others:{}`, - out: &MyMessage{ - Count: Int32(42), - Others: []*OtherMessage{ - {}, - {}, - {}, - {}, - }, - }, - }, - - // Missing colon for inner message - { - in: `count:42 inner < host: "cauchy.syd" >`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("cauchy.syd"), - }, - }, - }, - - // Missing colon for string field - { - in: `name "Dave"`, - err: `line 1.5: expected ':', found "\"Dave\""`, - }, - - // Missing colon for int32 field - { - in: `count 42`, - err: `line 1.6: expected ':', found "42"`, - }, - - // Missing required field - { - in: `name: "Pawel"`, - err: `proto: required field "testdata.MyMessage.count" not set`, - out: &MyMessage{ - Name: String("Pawel"), - }, - }, - - // Missing required field in a required submessage - { - in: `count: 42 we_must_go_deeper < leo_finally_won_an_oscar <> >`, - err: `proto: required field "testdata.InnerMessage.host" not set`, - out: &MyMessage{ - Count: Int32(42), - WeMustGoDeeper: &RequiredInnerMessage{LeoFinallyWonAnOscar: &InnerMessage{}}, - }, - }, - - // Repeated non-repeated field - { - in: `name: "Rob" name: "Russ"`, - err: `line 1.12: non-repeated field "name" was repeated`, - }, - - // Group - { - in: `count: 17 SomeGroup { group_field: 12 }`, - out: &MyMessage{ - Count: Int32(17), - Somegroup: &MyMessage_SomeGroup{ - GroupField: Int32(12), - }, - }, - }, - - // Semicolon between fields - { - in: `count:3;name:"Calvin"`, - out: &MyMessage{ - Count: Int32(3), - Name: String("Calvin"), - }, - }, - // Comma between fields - { - in: `count:4,name:"Ezekiel"`, - out: &MyMessage{ - Count: Int32(4), - Name: String("Ezekiel"), - }, - }, - - // Boolean false - { - in: `count:42 inner { host: "example.com" connected: false }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean true - { - in: `count:42 inner { host: "example.com" connected: true }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - // Boolean 0 - { - in: `count:42 inner { host: "example.com" connected: 0 }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean 1 - { - in: `count:42 inner { host: "example.com" connected: 1 }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - // Boolean f - { - in: `count:42 inner { host: "example.com" connected: f }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean t - { - in: `count:42 inner { host: "example.com" connected: t }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - // Boolean False - { - in: `count:42 inner { host: "example.com" connected: False }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean True - { - in: `count:42 inner { host: "example.com" connected: True }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - - // Extension - buildExtStructTest(`count: 42 [testdata.Ext.more]:`), - buildExtStructTest(`count: 42 [testdata.Ext.more] {data:"Hello, world!"}`), - buildExtDataTest(`count: 42 [testdata.Ext.text]:"Hello, world!" [testdata.Ext.number]:1729`), - buildExtRepStringTest(`count: 42 [testdata.greeting]:"bula" [testdata.greeting]:"hola"`), - - // Big all-in-one - { - in: "count:42 # Meaning\n" + - `name:"Dave" ` + - `quote:"\"I didn't want to go.\"" ` + - `pet:"bunny" ` + - `pet:"kitty" ` + - `pet:"horsey" ` + - `inner:<` + - ` host:"footrest.syd" ` + - ` port:7001 ` + - ` connected:true ` + - `> ` + - `others:<` + - ` key:3735928559 ` + - ` value:"\x01A\a\f" ` + - `> ` + - `others:<` + - " weight:58.9 # Atomic weight of Co\n" + - ` inner:<` + - ` host:"lesha.mtv" ` + - ` port:8002 ` + - ` >` + - `>`, - out: &MyMessage{ - Count: Int32(42), - Name: String("Dave"), - Quote: String(`"I didn't want to go."`), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &InnerMessage{ - Host: String("footrest.syd"), - Port: Int32(7001), - Connected: Bool(true), - }, - Others: []*OtherMessage{ - { - Key: Int64(3735928559), - Value: []byte{0x1, 'A', '\a', '\f'}, - }, - { - Weight: Float32(58.9), - Inner: &InnerMessage{ - Host: String("lesha.mtv"), - Port: Int32(8002), - }, - }, - }, - }, - }, -} - -func TestUnmarshalText(t *testing.T) { - for i, test := range unMarshalTextTests { - pb := new(MyMessage) - err := UnmarshalText(test.in, pb) - if test.err == "" { - // We don't expect failure. - if err != nil { - t.Errorf("Test %d: Unexpected error: %v", i, err) - } else if !reflect.DeepEqual(pb, test.out) { - t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", - i, pb, test.out) - } - } else { - // We do expect failure. - if err == nil { - t.Errorf("Test %d: Didn't get expected error: %v", i, test.err) - } else if err.Error() != test.err { - t.Errorf("Test %d: Incorrect error.\nHave: %v\nWant: %v", - i, err.Error(), test.err) - } else if _, ok := err.(*RequiredNotSetError); ok && test.out != nil && !reflect.DeepEqual(pb, test.out) { - t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", - i, pb, test.out) - } - } - } -} - -func TestUnmarshalTextCustomMessage(t *testing.T) { - msg := &textMessage{} - if err := UnmarshalText("custom", msg); err != nil { - t.Errorf("Unexpected error from custom unmarshal: %v", err) - } - if UnmarshalText("not custom", msg) == nil { - t.Errorf("Didn't get expected error from custom unmarshal") - } -} - -// Regression test; this caused a panic. -func TestRepeatedEnum(t *testing.T) { - pb := new(RepeatedEnum) - if err := UnmarshalText("color: RED", pb); err != nil { - t.Fatal(err) - } - exp := &RepeatedEnum{ - Color: []RepeatedEnum_Color{RepeatedEnum_RED}, - } - if !Equal(pb, exp) { - t.Errorf("Incorrect populated \nHave: %v\nWant: %v", pb, exp) - } -} - -func TestProto3TextParsing(t *testing.T) { - m := new(proto3pb.Message) - const in = `name: "Wallace" true_scotsman: true` - want := &proto3pb.Message{ - Name: "Wallace", - TrueScotsman: true, - } - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } -} - -func TestMapParsing(t *testing.T) { - m := new(MessageWithMap) - const in = `name_mapping: name_mapping:` + - `msg_mapping:,>` + // separating commas are okay - `msg_mapping>` + // no colon after "value" - `msg_mapping:>` + // omitted key - `msg_mapping:` + // omitted value - `byte_mapping:` + - `byte_mapping:<>` // omitted key and value - want := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Beatles", - 1234: "Feist", - }, - MsgMapping: map[int64]*FloatingPoint{ - -4: {F: Float64(2.0)}, - -2: {F: Float64(4.0)}, - 0: {F: Float64(5.0)}, - 1: nil, - }, - ByteMapping: map[bool][]byte{ - false: nil, - true: []byte("so be it"), - }, - } - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } -} - -func TestOneofParsing(t *testing.T) { - const in = `name:"Shrek"` - m := new(Communique) - want := &Communique{Union: &Communique_Name{"Shrek"}} - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } - - const inOverwrite = `name:"Shrek" number:42` - m = new(Communique) - testErr := "line 1.13: field 'number' would overwrite already parsed oneof 'Union'" - if err := UnmarshalText(inOverwrite, m); err == nil { - t.Errorf("TestOneofParsing: Didn't get expected error: %v", testErr) - } else if err.Error() != testErr { - t.Errorf("TestOneofParsing: Incorrect error.\nHave: %v\nWant: %v", - err.Error(), testErr) - } - -} - -var benchInput string - -func init() { - benchInput = "count: 4\n" - for i := 0; i < 1000; i++ { - benchInput += "pet: \"fido\"\n" - } - - // Check it is valid input. - pb := new(MyMessage) - err := UnmarshalText(benchInput, pb) - if err != nil { - panic("Bad benchmark input: " + err.Error()) - } -} - -func BenchmarkUnmarshalText(b *testing.B) { - pb := new(MyMessage) - for i := 0; i < b.N; i++ { - UnmarshalText(benchInput, pb) - } - b.SetBytes(int64(len(benchInput))) -} diff --git a/vendor/github.com/golang/protobuf/proto/text_test.go b/vendor/github.com/golang/protobuf/proto/text_test.go deleted file mode 100644 index 3eabacac..00000000 --- a/vendor/github.com/golang/protobuf/proto/text_test.go +++ /dev/null @@ -1,474 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto_test - -import ( - "bytes" - "errors" - "io/ioutil" - "math" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - pb "github.com/golang/protobuf/proto/testdata" -) - -// textMessage implements the methods that allow it to marshal and unmarshal -// itself as text. -type textMessage struct { -} - -func (*textMessage) MarshalText() ([]byte, error) { - return []byte("custom"), nil -} - -func (*textMessage) UnmarshalText(bytes []byte) error { - if string(bytes) != "custom" { - return errors.New("expected 'custom'") - } - return nil -} - -func (*textMessage) Reset() {} -func (*textMessage) String() string { return "" } -func (*textMessage) ProtoMessage() {} - -func newTestMessage() *pb.MyMessage { - msg := &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - Quote: proto.String(`"I didn't want to go."`), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &pb.InnerMessage{ - Host: proto.String("footrest.syd"), - Port: proto.Int32(7001), - Connected: proto.Bool(true), - }, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(0xdeadbeef), - Value: []byte{1, 65, 7, 12}, - }, - { - Weight: proto.Float32(6.022), - Inner: &pb.InnerMessage{ - Host: proto.String("lesha.mtv"), - Port: proto.Int32(8002), - }, - }, - }, - Bikeshed: pb.MyMessage_BLUE.Enum(), - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(8), - }, - // One normally wouldn't do this. - // This is an undeclared tag 13, as a varint (wire type 0) with value 4. - XXX_unrecognized: []byte{13<<3 | 0, 4}, - } - ext := &pb.Ext{ - Data: proto.String("Big gobs for big rats"), - } - if err := proto.SetExtension(msg, pb.E_Ext_More, ext); err != nil { - panic(err) - } - greetings := []string{"adg", "easy", "cow"} - if err := proto.SetExtension(msg, pb.E_Greeting, greetings); err != nil { - panic(err) - } - - // Add an unknown extension. We marshal a pb.Ext, and fake the ID. - b, err := proto.Marshal(&pb.Ext{Data: proto.String("3G skiing")}) - if err != nil { - panic(err) - } - b = append(proto.EncodeVarint(201<<3|proto.WireBytes), b...) - proto.SetRawExtension(msg, 201, b) - - // Extensions can be plain fields, too, so let's test that. - b = append(proto.EncodeVarint(202<<3|proto.WireVarint), 19) - proto.SetRawExtension(msg, 202, b) - - return msg -} - -const text = `count: 42 -name: "Dave" -quote: "\"I didn't want to go.\"" -pet: "bunny" -pet: "kitty" -pet: "horsey" -inner: < - host: "footrest.syd" - port: 7001 - connected: true -> -others: < - key: 3735928559 - value: "\001A\007\014" -> -others: < - weight: 6.022 - inner: < - host: "lesha.mtv" - port: 8002 - > -> -bikeshed: BLUE -SomeGroup { - group_field: 8 -} -/* 2 unknown bytes */ -13: 4 -[testdata.Ext.more]: < - data: "Big gobs for big rats" -> -[testdata.greeting]: "adg" -[testdata.greeting]: "easy" -[testdata.greeting]: "cow" -/* 13 unknown bytes */ -201: "\t3G skiing" -/* 3 unknown bytes */ -202: 19 -` - -func TestMarshalText(t *testing.T) { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, newTestMessage()); err != nil { - t.Fatalf("proto.MarshalText: %v", err) - } - s := buf.String() - if s != text { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, text) - } -} - -func TestMarshalTextCustomMessage(t *testing.T) { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, &textMessage{}); err != nil { - t.Fatalf("proto.MarshalText: %v", err) - } - s := buf.String() - if s != "custom" { - t.Errorf("Got %q, expected %q", s, "custom") - } -} -func TestMarshalTextNil(t *testing.T) { - want := "" - tests := []proto.Message{nil, (*pb.MyMessage)(nil)} - for i, test := range tests { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, test); err != nil { - t.Fatal(err) - } - if got := buf.String(); got != want { - t.Errorf("%d: got %q want %q", i, got, want) - } - } -} - -func TestMarshalTextUnknownEnum(t *testing.T) { - // The Color enum only specifies values 0-2. - m := &pb.MyMessage{Bikeshed: pb.MyMessage_Color(3).Enum()} - got := m.String() - const want = `bikeshed:3 ` - if got != want { - t.Errorf("\n got %q\nwant %q", got, want) - } -} - -func TestTextOneof(t *testing.T) { - tests := []struct { - m proto.Message - want string - }{ - // zero message - {&pb.Communique{}, ``}, - // scalar field - {&pb.Communique{Union: &pb.Communique_Number{4}}, `number:4`}, - // message field - {&pb.Communique{Union: &pb.Communique_Msg{ - &pb.Strings{StringField: proto.String("why hello!")}, - }}, `msg:`}, - // bad oneof (should not panic) - {&pb.Communique{Union: &pb.Communique_Msg{nil}}, `msg:/* nil */`}, - } - for _, test := range tests { - got := strings.TrimSpace(test.m.String()) - if got != test.want { - t.Errorf("\n got %s\nwant %s", got, test.want) - } - } -} - -func BenchmarkMarshalTextBuffered(b *testing.B) { - buf := new(bytes.Buffer) - m := newTestMessage() - for i := 0; i < b.N; i++ { - buf.Reset() - proto.MarshalText(buf, m) - } -} - -func BenchmarkMarshalTextUnbuffered(b *testing.B) { - w := ioutil.Discard - m := newTestMessage() - for i := 0; i < b.N; i++ { - proto.MarshalText(w, m) - } -} - -func compact(src string) string { - // s/[ \n]+/ /g; s/ $//; - dst := make([]byte, len(src)) - space, comment := false, false - j := 0 - for i := 0; i < len(src); i++ { - if strings.HasPrefix(src[i:], "/*") { - comment = true - i++ - continue - } - if comment && strings.HasPrefix(src[i:], "*/") { - comment = false - i++ - continue - } - if comment { - continue - } - c := src[i] - if c == ' ' || c == '\n' { - space = true - continue - } - if j > 0 && (dst[j-1] == ':' || dst[j-1] == '<' || dst[j-1] == '{') { - space = false - } - if c == '{' { - space = false - } - if space { - dst[j] = ' ' - j++ - space = false - } - dst[j] = c - j++ - } - if space { - dst[j] = ' ' - j++ - } - return string(dst[0:j]) -} - -var compactText = compact(text) - -func TestCompactText(t *testing.T) { - s := proto.CompactTextString(newTestMessage()) - if s != compactText { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v\n===\n", s, compactText) - } -} - -func TestStringEscaping(t *testing.T) { - testCases := []struct { - in *pb.Strings - out string - }{ - { - // Test data from C++ test (TextFormatTest.StringEscape). - // Single divergence: we don't escape apostrophes. - &pb.Strings{StringField: proto.String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces")}, - "string_field: \"\\\"A string with ' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"\n", - }, - { - // Test data from the same C++ test. - &pb.Strings{StringField: proto.String("\350\260\267\346\255\214")}, - "string_field: \"\\350\\260\\267\\346\\255\\214\"\n", - }, - { - // Some UTF-8. - &pb.Strings{StringField: proto.String("\x00\x01\xff\x81")}, - `string_field: "\000\001\377\201"` + "\n", - }, - } - - for i, tc := range testCases { - var buf bytes.Buffer - if err := proto.MarshalText(&buf, tc.in); err != nil { - t.Errorf("proto.MarsalText: %v", err) - continue - } - s := buf.String() - if s != tc.out { - t.Errorf("#%d: Got:\n%s\nExpected:\n%s\n", i, s, tc.out) - continue - } - - // Check round-trip. - pb := new(pb.Strings) - if err := proto.UnmarshalText(s, pb); err != nil { - t.Errorf("#%d: UnmarshalText: %v", i, err) - continue - } - if !proto.Equal(pb, tc.in) { - t.Errorf("#%d: Round-trip failed:\nstart: %v\n end: %v", i, tc.in, pb) - } - } -} - -// A limitedWriter accepts some output before it fails. -// This is a proxy for something like a nearly-full or imminently-failing disk, -// or a network connection that is about to die. -type limitedWriter struct { - b bytes.Buffer - limit int -} - -var outOfSpace = errors.New("proto: insufficient space") - -func (w *limitedWriter) Write(p []byte) (n int, err error) { - var avail = w.limit - w.b.Len() - if avail <= 0 { - return 0, outOfSpace - } - if len(p) <= avail { - return w.b.Write(p) - } - n, _ = w.b.Write(p[:avail]) - return n, outOfSpace -} - -func TestMarshalTextFailing(t *testing.T) { - // Try lots of different sizes to exercise more error code-paths. - for lim := 0; lim < len(text); lim++ { - buf := new(limitedWriter) - buf.limit = lim - err := proto.MarshalText(buf, newTestMessage()) - // We expect a certain error, but also some partial results in the buffer. - if err != outOfSpace { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", err, outOfSpace) - } - s := buf.b.String() - x := text[:buf.limit] - if s != x { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, x) - } - } -} - -func TestFloats(t *testing.T) { - tests := []struct { - f float64 - want string - }{ - {0, "0"}, - {4.7, "4.7"}, - {math.Inf(1), "inf"}, - {math.Inf(-1), "-inf"}, - {math.NaN(), "nan"}, - } - for _, test := range tests { - msg := &pb.FloatingPoint{F: &test.f} - got := strings.TrimSpace(msg.String()) - want := `f:` + test.want - if got != want { - t.Errorf("f=%f: got %q, want %q", test.f, got, want) - } - } -} - -func TestRepeatedNilText(t *testing.T) { - m := &pb.MessageList{ - Message: []*pb.MessageList_Message{ - nil, - &pb.MessageList_Message{ - Name: proto.String("Horse"), - }, - nil, - }, - } - want := `Message -Message { - name: "Horse" -} -Message -` - if s := proto.MarshalTextString(m); s != want { - t.Errorf(" got: %s\nwant: %s", s, want) - } -} - -func TestProto3Text(t *testing.T) { - tests := []struct { - m proto.Message - want string - }{ - // zero message - {&proto3pb.Message{}, ``}, - // zero message except for an empty byte slice - {&proto3pb.Message{Data: []byte{}}, ``}, - // trivial case - {&proto3pb.Message{Name: "Rob", HeightInCm: 175}, `name:"Rob" height_in_cm:175`}, - // empty map - {&pb.MessageWithMap{}, ``}, - // non-empty map; map format is the same as a repeated struct, - // and they are sorted by key (numerically for numeric keys). - { - &pb.MessageWithMap{NameMapping: map[int32]string{ - -1: "Negatory", - 7: "Lucky", - 1234: "Feist", - 6345789: "Otis", - }}, - `name_mapping: ` + - `name_mapping: ` + - `name_mapping: ` + - `name_mapping:`, - }, - // map with nil value; not well-defined, but we shouldn't crash - { - &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{7: nil}}, - `msg_mapping:`, - }, - } - for _, test := range tests { - got := strings.TrimSpace(test.m.String()) - if got != test.want { - t.Errorf("\n got %s\nwant %s", got, test.want) - } - } -} diff --git a/vendor/github.com/jmank88/nuts/.gitignore b/vendor/github.com/jmank88/nuts/.gitignore deleted file mode 100644 index f562d2c8..00000000 --- a/vendor/github.com/jmank88/nuts/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -.idea -testdata -vendor/ \ No newline at end of file diff --git a/vendor/github.com/jmank88/nuts/.travis.yml b/vendor/github.com/jmank88/nuts/.travis.yml deleted file mode 100644 index 66385620..00000000 --- a/vendor/github.com/jmank88/nuts/.travis.yml +++ /dev/null @@ -1,9 +0,0 @@ -language: go - -go: - - 1.x - - tip - -install: - - go get -u github.com/golang/dep/... - - dep ensure -vendor-only \ No newline at end of file diff --git a/vendor/github.com/jmank88/nuts/Gopkg.lock b/vendor/github.com/jmank88/nuts/Gopkg.lock deleted file mode 100644 index e6473ae6..00000000 --- a/vendor/github.com/jmank88/nuts/Gopkg.lock +++ /dev/null @@ -1,21 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - name = "github.com/boltdb/bolt" - packages = ["."] - revision = "2f1ce7a837dcb8da3ec595b1dac9d0632f0f99e8" - version = "v1.3.1" - -[[projects]] - branch = "master" - name = "golang.org/x/sys" - packages = ["unix"] - revision = "7ddbeae9ae08c6a06a59597f0c9edbc5ff2444ce" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - inputs-digest = "568758fa97eac2946d6043bc72b7e728f802aeba2169c527f8fbad2222e74700" - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/vendor/github.com/jmank88/nuts/Gopkg.toml b/vendor/github.com/jmank88/nuts/Gopkg.toml deleted file mode 100644 index f6598803..00000000 --- a/vendor/github.com/jmank88/nuts/Gopkg.toml +++ /dev/null @@ -1,3 +0,0 @@ -[[constraint]] - name = "github.com/boltdb/bolt" - version = "^1.0.0" diff --git a/vendor/github.com/jmank88/nuts/README.md b/vendor/github.com/jmank88/nuts/README.md deleted file mode 100644 index ad81fb58..00000000 --- a/vendor/github.com/jmank88/nuts/README.md +++ /dev/null @@ -1,53 +0,0 @@ -# Nuts - BoltDB Utilities - -[![GoDoc](https://godoc.org/github.com/jmank88/nuts?status.svg)](https://godoc.org/github.com/jmank88/nuts) [![Go Report Card](https://goreportcard.com/badge/github.com/jmank88/nuts)](https://goreportcard.com/report/github.com/jmank88/nuts) [![Coverage Status](https://coveralls.io/repos/github/jmank88/nuts/badge.svg?branch=master)](https://coveralls.io/github/jmank88/nuts?branch=master) - -A collection of [BoltDB](https://github.com/boltdb/bolt) utilities. - -## Path Prefix Scans - -The prefix scanning functions `SeekPathConflict` and `SeekPathMatch` facilitate maintenance and access to buckets of -paths supporting *variable elements* with *exclusive matches*. Paths are `/` delimited, must begin with a `/`, and -elements beginning with `:` or `*` are variable. - -Examples: - -``` -/ -/blogs/ -/blogs/:blog_id -``` - -### Variable Elements - -Path elements beginning with a `:` match any single element. Path elements beginning with `*` match any remaining -elements, and therefore must be last. - -Examples: - -``` -Path: /blogs/:blog_id -Match: /blogs/someblog -``` - -``` -Path: /blogs/:blog_id/comments/:comment_id/*suffix -Match: /blogs/42/comments/100/edit -``` - -### Exclusive Matches - -Using `SeekPathConflict` before putting new paths to ensure the bucket remains conflict-free guarantees that `SeekPathMatch` -will never match more than one path. - -Examples: - -``` -Conflicts: `/blogs/:blog_id`, `/blogs/golang` -Match: `/blogs/golang` -``` - -``` -Conflicts: `/blogs/*`, `/blogs/:blog_id/comments` -Match: `/blogs/42/comments` -``` diff --git a/vendor/github.com/jmank88/nuts/example_test.go b/vendor/github.com/jmank88/nuts/example_test.go deleted file mode 100644 index e209c6a7..00000000 --- a/vendor/github.com/jmank88/nuts/example_test.go +++ /dev/null @@ -1,22 +0,0 @@ -package nuts - -import ( - "fmt" -) - -func ExampleKey_UUID() { - type uuid struct{ a, b uint64 } - - u := uuid{ - a: 0xaaaaaaaaaaaaaaaa, - b: 0xbbbbbbbbbbbbbbbb, - } - - key := make(Key, 16) - key[:8].Put(u.a) - key[8:].Put(u.b) - fmt.Printf("%#x", key) - - // Output: - // 0xaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbb -} diff --git a/vendor/github.com/jmank88/nuts/key_test.go b/vendor/github.com/jmank88/nuts/key_test.go deleted file mode 100644 index 8fbcf783..00000000 --- a/vendor/github.com/jmank88/nuts/key_test.go +++ /dev/null @@ -1,114 +0,0 @@ -package nuts - -import ( - "bytes" - "strconv" - "testing" -) - -func TestKeyLen(t *testing.T) { - for _, test := range []struct { - x uint64 - exp int - }{ - {0, 1}, - {1, 1}, - {1 << 8, 2}, - {1 << 16, 3}, - {1 << 24, 4}, - {1 << 32, 5}, - {1 << 40, 6}, - {1 << 48, 7}, - {1 << 56, 8}, - } { - got := KeyLen(test.x) - if got != test.exp { - t.Errorf("%d: expected length %d but got %d", test.x, test.exp, got) - } - } -} - -func TestKey(t *testing.T) { - for _, test := range []struct { - max int - xs []uint64 - bs [][]byte - }{ - { - max: 1 << 7, - xs: []uint64{0, 1, (1 << 8) - 1}, - bs: [][]byte{ - {0x00}, {0x01}, {0xFF}, - }, - }, - { - max: 1 << 15, - xs: []uint64{0, 1, (1 << 16) - 1}, - bs: [][]byte{ - {0x00, 0x00}, {0x00, 0x01}, {0xFF, 0xFF}, - }, - }, - { - max: 1 << 23, - xs: []uint64{0, 1, (1 << 24) - 1}, - bs: [][]byte{ - {0x00, 0x00, 0x00}, {0x00, 0x00, 0x01}, {0xFF, 0xFF, 0xFF}, - }, - }, - { - max: 1 << 31, - xs: []uint64{0, 1, (1 << 32) - 1}, - bs: [][]byte{ - {0x00, 0x00, 0x00, 0x00}, - {0x00, 0x00, 0x00, 0x01}, - {0xFF, 0xFF, 0xFF, 0xFF}, - }, - }, - { - max: 1 << 39, - xs: []uint64{0, 1, (1 << 40) - 1}, - bs: [][]byte{ - {0x00, 0x00, 0x00, 0x00, 0x00}, - {0x00, 0x00, 0x00, 0x00, 0x01}, - {0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, - }, - }, - { - max: 1 << 47, - xs: []uint64{0, 1, (1 << 48) - 1}, - bs: [][]byte{ - {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x00, 0x00, 0x00, 0x00, 0x00, 0x01}, - {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, - }, - }, - { - max: 1 << 55, - xs: []uint64{0, 1, (1 << 56) - 1}, - bs: [][]byte{ - {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}, - {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, - }, - }, - { - max: 1 << 60, - xs: []uint64{0, 1, (1 << 60) - 1}, - bs: [][]byte{ - {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}, - {0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, - }, - }, - } { - t.Run(strconv.Itoa(test.max), func(t *testing.T) { - k := make(Key, KeyLen(uint64(test.max))) - for i, x := range test.xs { - k.Put(x) - if !bytes.Equal(k, test.bs[i]) { - t.Errorf("unexpected serialized integer %d:\n\t(GOT): %#x\n\t(WNT): %#x", x, k, test.bs[i]) - } - } - }) - } -} diff --git a/vendor/github.com/jmank88/nuts/paths_test.go b/vendor/github.com/jmank88/nuts/paths_test.go deleted file mode 100644 index 33a698b0..00000000 --- a/vendor/github.com/jmank88/nuts/paths_test.go +++ /dev/null @@ -1,338 +0,0 @@ -//go:generate rm -rf testdata -// -//go:generate go run cmd/testpaths/main.go testdata standard 10 100 1000 10000 100000 1000000 -//go:generate go run cmd/testpaths/main.go testdata segmentCount 1 5 10 50 100 -//go:generate go run cmd/testpaths/main.go testdata branchFactor 1 5 10 50 100 500 1000 5000 10000 -//go:generate go run cmd/testpaths/main.go testdata segmentSize 1 5 10 50 100 200 -// -//go:generate go run cmd/testdb/main.go testdata -package nuts - -import ( - "bufio" - "bytes" - "errors" - "fmt" - "io/ioutil" - "log" - "os" - "path/filepath" - "strings" - "testing" - - "github.com/boltdb/bolt" -) - -var bucketName = []byte("testBucket") - -func exDB(f func(db *bolt.DB)) { - tmp := tempfile() - defer os.Remove(tmp) - db, err := bolt.Open(tmp, 0666, nil) - if err != nil { - log.Fatal(err) - } - defer db.Close() - f(db) -} - -func ExampleSeekPathMatch() { - exDB(func(db *bolt.DB) { - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket(bucketName) - if err != nil { - return err - } - - // Put a variable path. - return b.Put([]byte("/blogs/:blog_id/comments/:comment_id"), []byte{}) - }); err != nil { - log.Fatal(err) - } - - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket(bucketName) - - // Match path. - path, _ := SeekPathMatch(b.Cursor(), []byte("/blogs/asdf/comments/42")) - fmt.Println(string(path)) - - return nil - }); err != nil { - log.Fatal(err) - } - }) - - // Output: /blogs/:blog_id/comments/:comment_id -} - -func ExampleSeekPathConflict() { - exDB(func(db *bolt.DB) { - insert := func(path string) { - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucketIfNotExists(bucketName) - if err != nil { - return err - } - - // Check for conflicts. - if k, _ := SeekPathConflict(b.Cursor(), []byte(path)); k != nil { - fmt.Printf("Put(%s) blocked - conflict: %s\n", path, string(k)) - return nil - } - - // Put. - if err := b.Put([]byte(path), []byte{}); err != nil { - return err - } - fmt.Printf("Put(%s)\n", path) - return nil - }); err != nil { - log.Fatal(err) - } - } - // Put - insert("/blogs/") - // Put - insert("/blogs/:blog_id") - // Conflict - insert("/blogs/a_blog") - }) - - // Output: - // Put(/blogs/) - // Put(/blogs/:blog_id) - // Put(/blogs/a_blog) blocked - conflict: /blogs/:blog_id -} - -var matchTests = []struct { - path string - matches []string -}{ - {`/blogs`, []string{`/blogs`}}, - {`/blogs/`, []string{`/blogs/`}}, - {`/blogs/:blog_id`, []string{`/blogs/123`}}, - {`/blogs/:blog_id/comments`, []string{`/blogs/123/comments`}}, - {`/blogs/:blog_id/comments/`, []string{`/blogs/123/comments/`}}, - {`/blogs/:blog_id/comments/:comment_id`, []string{`/blogs/123/comments/456`}}, - {`/blogs/:blog_id/comments/:comment_id/*suffix`, - []string{`/blogs/123/comments/456/test`, `/blogs/123/comments/456/test/test`}}, -} - -func TestMatchPath(t *testing.T) { - testDB(t, func(db *bolt.DB) { - bucketName := []byte("testBucket") - - // Setup - Put all paths - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket(bucketName) - if err != nil { - return err - } - for _, test := range matchTests { - err := b.Put([]byte(test.path), []byte{}) - if err != nil { - return err - } - } - return nil - }); err != nil { - t.Fatal("failed to insert paths:", err) - } - - // Test - Match each - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket(bucketName) - for _, test := range matchTests { - for _, match := range test.matches { - k, _ := SeekPathMatch(b.Cursor(), []byte(match)) - if k == nil { - t.Errorf("expected %q to match %q but got none", match, test.path) - } else if !bytes.Equal(k, []byte(test.path)) { - t.Errorf("expected %q to match %q but got %q", match, test.path, string(k)) - } - } - } - return nil - }); err != nil { - t.Fatal("tests failed:", err) - } - }) -} - -func TestConflicts(t *testing.T) { - for _, test := range []struct { - path string - conflicts []string - }{ - {`/test/test`, []string{`/test/test`, `/:test`, `/*test`, `/test/:test`, `/test/*test`, `/:test/test`}}, - {`/:test`, []string{`/:tst`, `/test`, `/*test`}}, - {`/test/*test`, []string{`/test/*tst`, `/test/test`, `/test/:tst`, `/test/test/test`, `/test/test/:test`, `/test/test/*test`}}, - } { - testDB(t, func(db *bolt.DB) { - // Setup - Put path - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket(bucketName) - if err != nil { - return err - } - return b.Put([]byte(test.path), []byte{}) - }); err != nil { - t.Fatal("failed to insert path", err) - } - - // Test - Verify all conflicts - if err := db.View(func(tx *bolt.Tx) error { - b := tx.Bucket(bucketName) - for _, c := range test.conflicts { - k, _ := SeekPathConflict(b.Cursor(), []byte(c)) - kStr := string(k) - if kStr != test.path { - t.Errorf("expected %q to match %q but got %q", c, test.path, kStr) - } - } - return nil - }); err != nil { - t.Fatal("failed to run tests", err) - } - }) - } -} - -// Attempts to put all matchTests w/o conflict. -func TestNoConflicts(t *testing.T) { - testDB(t, func(db *bolt.DB) { - bucketName := []byte("testBucket") - - if err := db.Update(func(tx *bolt.Tx) error { - b, err := tx.CreateBucket(bucketName) - if err != nil { - return err - } - c := b.Cursor() - for _, test := range matchTests { - pathB := []byte(test.path) - if k, _ := SeekPathConflict(c, pathB); k != nil { - t.Errorf("unexpected conflict with %q: %s", test.path, string(k)) - } - - if err := b.Put(pathB, []byte{}); err != nil { - return err - } - } - return nil - }); err != nil { - t.Fatal("failed to insert paths:", err) - } - }) -} - -func Benchmark(b *testing.B) { - b.Run("standard", forEachDB("standard", strings.NewReplacer(":", "", "*", "").Replace)) - b.Run("branchFactor", forEachDB("branchFactor", nil)) - b.Run("segmentCount", forEachDB("segmentCount", nil)) - b.Run("segmentSize", forEachDB("segmentSize", nil)) -} - -func forEachDB(testname string, fn func(path string) string) func(*testing.B) { - return func(b *testing.B) { - dir := filepath.Join("testdata", testname) - err := filepath.Walk(dir, func(testfile string, info os.FileInfo, err error) error { - if !info.IsDir() && filepath.Ext(testfile) == ".db" { - arg := strings.TrimSuffix(filepath.Base(testfile), ".db") - - b.Run(arg, benchMatch(testfile, fn)) - } - return nil - }) - if err != nil { - b.Fatal(err) - } - } -} - -func benchMatch(testdb string, pathFn func(path string) string) func(b *testing.B) { - return func(b *testing.B) { - db, err := bolt.Open(testdb, 0666, nil) - if err != nil { - b.Fatalf("failed to open database %s: %s", testdb, err) - } - defer db.Close() - - testtxt := strings.TrimSuffix(testdb, ".db") + ".txt" - f, err := os.Open(testtxt) - if err != nil { - b.Fatalf("failed to open file %s: %s", testtxt, err) - } - - var paths [][]byte - func() { - defer f.Close() - - // Use default, ScanLines - s := bufio.NewScanner(f) - - paths = make([][]byte, 0, b.N) - for s.Scan() { - if pathFn == nil { - paths = append(paths, s.Bytes()) - } else { - paths = append(paths, []byte(pathFn(s.Text()))) - } - - if len(paths) == cap(paths) { - break - } - } - if s.Err() != nil { - b.Fatal("failed to read text paths:", s.Err()) - } - }() - - b.ResetTimer() - - lookup := func(path []byte) error { - return db.View(func(tx *bolt.Tx) error { - bk := tx.Bucket([]byte("paths")) - k, _ := SeekPathMatch(bk.Cursor(), path) - if k == nil { - return errors.New("no match found") - } - return nil - }) - } - - for i := 0; i < b.N; i++ { - path := paths[i%len(paths)] - - if err := lookup(path); err != nil { - b.Fatalf("failed to match %q: %s", string(path), err) - } - } - } -} - -func testDB(t *testing.T, f func(db *bolt.DB)) { - tmp := tempfile() - defer os.Remove(tmp) - db, err := bolt.Open(tmp, 0666, nil) - if err != nil { - t.Fatal("failed to open db:", err) - } - defer db.Close() - f(db) -} - -func tempfile() string { - f, err := ioutil.TempFile("", "nuts-bolt-") - if err != nil { - panic(err) - } - if err := f.Close(); err != nil { - panic(err) - } - if err := os.Remove(f.Name()); err != nil { - panic(err) - } - return f.Name() -} diff --git a/vendor/github.com/nightlyone/lockfile/.gitignore b/vendor/github.com/nightlyone/lockfile/.gitignore deleted file mode 100644 index 5a05665d..00000000 --- a/vendor/github.com/nightlyone/lockfile/.gitignore +++ /dev/null @@ -1,27 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# popular temporaries -.err -.out -.diff - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe diff --git a/vendor/github.com/nightlyone/lockfile/.gitmodules b/vendor/github.com/nightlyone/lockfile/.gitmodules deleted file mode 100644 index 6faa9e34..00000000 --- a/vendor/github.com/nightlyone/lockfile/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "git-hooks"] - path = git-hooks - url = https://github.com/nightlyone/git-hooks diff --git a/vendor/github.com/nightlyone/lockfile/.travis.yml b/vendor/github.com/nightlyone/lockfile/.travis.yml deleted file mode 100644 index 76e5962b..00000000 --- a/vendor/github.com/nightlyone/lockfile/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ -language: go -go: - - 1.4.3 - - 1.6.2 - - tip - -# Only test commits to production branch and all pull requests -branches: - only: - - master - -matrix: - allow_failures: - - go: tip diff --git a/vendor/github.com/nightlyone/lockfile/README.md b/vendor/github.com/nightlyone/lockfile/README.md deleted file mode 100644 index c35235cd..00000000 --- a/vendor/github.com/nightlyone/lockfile/README.md +++ /dev/null @@ -1,52 +0,0 @@ -lockfile -========= -Handle locking via pid files. - -[![Build Status Unix][1]][2] -[![Build status Windows][3]][4] - -[1]: https://secure.travis-ci.org/nightlyone/lockfile.png -[2]: https://travis-ci.org/nightlyone/lockfile -[3]: https://ci.appveyor.com/api/projects/status/7mojkmauj81uvp8u/branch/master?svg=true -[4]: https://ci.appveyor.com/project/nightlyone/lockfile/branch/master - - - -install -------- -Install [Go 1][5], either [from source][6] or [with a prepackaged binary][7]. -For Windows suport, Go 1.4 or newer is required. - -Then run - - go get github.com/nightlyone/lockfile - -[5]: http://golang.org -[6]: http://golang.org/doc/install/source -[7]: http://golang.org/doc/install - -LICENSE -------- -MIT - -documentation -------------- -[package documentation at godoc.org](http://godoc.org/github.com/nightlyone/lockfile) - -install -------------------- - go get github.com/nightlyone/lockfile - - -contributing -============ - -Contributions are welcome. Please open an issue or send me a pull request for a dedicated branch. -Make sure the git commit hooks show it works. - -git commit hooks ------------------------ -enable commit hooks via - - cd .git ; rm -rf hooks; ln -s ../git-hooks hooks ; cd .. - diff --git a/vendor/github.com/nightlyone/lockfile/appveyor.yml b/vendor/github.com/nightlyone/lockfile/appveyor.yml deleted file mode 100644 index cf72a58b..00000000 --- a/vendor/github.com/nightlyone/lockfile/appveyor.yml +++ /dev/null @@ -1,12 +0,0 @@ -clone_folder: c:\gopath\src\github.com\nightlyone\lockfile - -environment: - GOPATH: c:\gopath - -install: - - go version - - go env - - go get -v -t ./... - -build_script: - - go test -v ./... diff --git a/vendor/github.com/nightlyone/lockfile/lockfile_test.go b/vendor/github.com/nightlyone/lockfile/lockfile_test.go deleted file mode 100644 index be2c821e..00000000 --- a/vendor/github.com/nightlyone/lockfile/lockfile_test.go +++ /dev/null @@ -1,308 +0,0 @@ -package lockfile - -import ( - "fmt" - "io/ioutil" - "math/rand" - "os" - "path/filepath" - "strconv" - "testing" -) - -func ExampleLockfile() { - lock, err := New(filepath.Join(os.TempDir(), "lock.me.now.lck")) - if err != nil { - fmt.Printf("Cannot init lock. reason: %v", err) - panic(err) // handle properly please! - } - err = lock.TryLock() - - // Error handling is essential, as we only try to get the lock. - if err != nil { - fmt.Printf("Cannot lock %q, reason: %v", lock, err) - panic(err) // handle properly please! - } - - defer lock.Unlock() - - fmt.Println("Do stuff under lock") - // Output: Do stuff under lock -} - -func TestBasicLockUnlock(t *testing.T) { - path, err := filepath.Abs("test_lockfile.pid") - if err != nil { - panic(err) - } - - lf, err := New(path) - if err != nil { - t.Fail() - fmt.Println("Error making lockfile: ", err) - return - } - - err = lf.TryLock() - if err != nil { - t.Fail() - fmt.Println("Error locking lockfile: ", err) - return - } - - err = lf.Unlock() - if err != nil { - t.Fail() - fmt.Println("Error unlocking lockfile: ", err) - return - } -} - -func GetDeadPID() int { - // I have no idea how windows handles large PIDs, or if they even exist. - // So limit it to be less or equal to 4096 to be safe. - - const maxPid = 4095 - - // limited iteration, so we finish one day - seen := map[int]bool{} - for len(seen) < maxPid { - pid := rand.Intn(maxPid + 1) // see https://godoc.org/math/rand#Intn why - if seen[pid] { - continue - } - seen[pid] = true - running, err := isRunning(pid) - if err != nil { - fmt.Println("Error checking PID: ", err) - continue - } - - if !running { - return pid - } - } - panic(fmt.Sprintf("all pids lower %d are used, cannot test this", maxPid)) -} - -func TestBusy(t *testing.T) { - path, err := filepath.Abs("test_lockfile.pid") - if err != nil { - t.Fatal(err) - return - } - - pid := os.Getppid() - - if err := ioutil.WriteFile(path, []byte(strconv.Itoa(pid)+"\n"), 0666); err != nil { - t.Fatal(err) - return - } - defer os.Remove(path) - - lf, err := New(path) - if err != nil { - t.Fatal(err) - return - } - - got := lf.TryLock() - if got != ErrBusy { - t.Fatalf("expected error %q, got %v", ErrBusy, got) - return - } -} - -func TestRogueDeletion(t *testing.T) { - path, err := filepath.Abs("test_lockfile.pid") - if err != nil { - t.Fatal(err) - return - } - lf, err := New(path) - if err != nil { - t.Fatal(err) - return - } - err = lf.TryLock() - if err != nil { - t.Fatal(err) - return - } - err = os.Remove(path) - if err != nil { - t.Fatal(err) - return - } - - got := lf.Unlock() - if got != ErrRogueDeletion { - t.Fatalf("unexpected error: %v", got) - return - } -} - -func TestRogueDeletionDeadPid(t *testing.T) { - path, err := filepath.Abs("test_lockfile.pid") - if err != nil { - t.Fatal(err) - return - } - lf, err := New(path) - if err != nil { - t.Fatal(err) - return - } - err = lf.TryLock() - if err != nil { - t.Fatal(err) - return - } - - pid := GetDeadPID() - if err := ioutil.WriteFile(path, []byte(strconv.Itoa(pid)+"\n"), 0666); err != nil { - t.Fatal(err) - return - } - defer os.Remove(path) - - err = lf.Unlock() - if err != ErrRogueDeletion { - t.Fatalf("unexpected error: %v", err) - return - } - - if _, err := os.Stat(path); os.IsNotExist(err) { - t.Fatal("lockfile should not be deleted by us, if we didn't create it") - } else { - if err != nil { - t.Fatalf("unexpected error %v", err) - } - } -} - -func TestRemovesStaleLockOnDeadOwner(t *testing.T) { - path, err := filepath.Abs("test_lockfile.pid") - if err != nil { - t.Fatal(err) - return - } - lf, err := New(path) - if err != nil { - t.Fatal(err) - return - } - pid := GetDeadPID() - if err := ioutil.WriteFile(path, []byte(strconv.Itoa(pid)+"\n"), 0666); err != nil { - t.Fatal(err) - return - } - err = lf.TryLock() - if err != nil { - t.Fatal(err) - return - } - - if err := lf.Unlock(); err != nil { - t.Fatal(err) - return - } -} - -func TestInvalidPidLeadToReplacedLockfileAndSuccess(t *testing.T) { - path, err := filepath.Abs("test_lockfile.pid") - if err != nil { - t.Fatal(err) - return - } - if err := ioutil.WriteFile(path, []byte("\n"), 0666); err != nil { - t.Fatal(err) - return - } - defer os.Remove(path) - - lf, err := New(path) - if err != nil { - t.Fatal(err) - return - } - - if err := lf.TryLock(); err != nil { - t.Fatalf("unexpected error: %v", err) - return - } - - // now check if file exists and contains the correct content - got, err := ioutil.ReadFile(path) - if err != nil { - t.Fatalf("unexpected error %v", err) - return - } - want := fmt.Sprintf("%d\n", os.Getpid()) - if string(got) != want { - t.Fatalf("got %q, want %q", got, want) - } -} - -func TestScanPidLine(t *testing.T) { - tests := [...]struct { - input []byte - pid int - xfail error - }{ - { - xfail: ErrInvalidPid, - }, - { - input: []byte(""), - xfail: ErrInvalidPid, - }, - { - input: []byte("\n"), - xfail: ErrInvalidPid, - }, - { - input: []byte("-1\n"), - xfail: ErrInvalidPid, - }, - { - input: []byte("0\n"), - xfail: ErrInvalidPid, - }, - { - input: []byte("a\n"), - xfail: ErrInvalidPid, - }, - { - input: []byte("1\n"), - pid: 1, - }, - } - - // test positive cases first - for step, tc := range tests { - if tc.xfail != nil { - continue - } - want := tc.pid - got, err := scanPidLine(tc.input) - if err != nil { - t.Fatalf("%d: unexpected error %v", step, err) - } - if got != want { - t.Errorf("%d: expected pid %d, got %d", step, want, got) - } - } - - // test negative cases now - for step, tc := range tests { - if tc.xfail == nil { - continue - } - want := tc.xfail - _, got := scanPidLine(tc.input) - if got != want { - t.Errorf("%d: expected error %v, got %v", step, want, got) - } - } -} diff --git a/vendor/github.com/pelletier/go-toml/.gitignore b/vendor/github.com/pelletier/go-toml/.gitignore deleted file mode 100644 index 99e38bbc..00000000 --- a/vendor/github.com/pelletier/go-toml/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -test_program/test_program_bin -fuzz/ diff --git a/vendor/github.com/pelletier/go-toml/.travis.yml b/vendor/github.com/pelletier/go-toml/.travis.yml deleted file mode 100644 index 6e644fdf..00000000 --- a/vendor/github.com/pelletier/go-toml/.travis.yml +++ /dev/null @@ -1,22 +0,0 @@ -sudo: false -language: go -go: - - 1.8.4 - - 1.9.1 - - tip -matrix: - allow_failures: - - go: tip - fast_finish: true -script: - - if [ -n "$(go fmt ./...)" ]; then exit 1; fi - - ./test.sh - - ./benchmark.sh $TRAVIS_BRANCH https://github.com/$TRAVIS_REPO_SLUG.git -before_install: - - go get github.com/axw/gocov/gocov - - go get github.com/mattn/goveralls - - if ! go get code.google.com/p/go.tools/cmd/cover; then go get golang.org/x/tools/cmd/cover; fi -branches: - only: [master] -after_success: - - $HOME/gopath/bin/goveralls -service=travis-ci -coverprofile=coverage.out -repotoken $COVERALLS_TOKEN diff --git a/vendor/github.com/pelletier/go-toml/README.md b/vendor/github.com/pelletier/go-toml/README.md deleted file mode 100644 index 0d357acf..00000000 --- a/vendor/github.com/pelletier/go-toml/README.md +++ /dev/null @@ -1,131 +0,0 @@ -# go-toml - -Go library for the [TOML](https://github.com/mojombo/toml) format. - -This library supports TOML version -[v0.4.0](https://github.com/toml-lang/toml/blob/master/versions/en/toml-v0.4.0.md) - -[![GoDoc](https://godoc.org/github.com/pelletier/go-toml?status.svg)](http://godoc.org/github.com/pelletier/go-toml) -[![license](https://img.shields.io/github/license/pelletier/go-toml.svg)](https://github.com/pelletier/go-toml/blob/master/LICENSE) -[![Build Status](https://travis-ci.org/pelletier/go-toml.svg?branch=master)](https://travis-ci.org/pelletier/go-toml) -[![Coverage Status](https://coveralls.io/repos/github/pelletier/go-toml/badge.svg?branch=master)](https://coveralls.io/github/pelletier/go-toml?branch=master) -[![Go Report Card](https://goreportcard.com/badge/github.com/pelletier/go-toml)](https://goreportcard.com/report/github.com/pelletier/go-toml) - -## Features - -Go-toml provides the following features for using data parsed from TOML documents: - -* Load TOML documents from files and string data -* Easily navigate TOML structure using Tree -* Mashaling and unmarshaling to and from data structures -* Line & column position data for all parsed elements -* [Query support similar to JSON-Path](query/) -* Syntax errors contain line and column numbers - -## Import - -```go -import "github.com/pelletier/go-toml" -``` - -## Usage example - -Read a TOML document: - -```go -config, _ := toml.Load(` -[postgres] -user = "pelletier" -password = "mypassword"`) -// retrieve data directly -user := config.Get("postgres.user").(string) - -// or using an intermediate object -postgresConfig := config.Get("postgres").(*toml.Tree) -password := postgresConfig.Get("password").(string) -``` - -Or use Unmarshal: - -```go -type Postgres struct { - User string - Password string -} -type Config struct { - Postgres Postgres -} - -doc := []byte(` -[Postgres] -User = "pelletier" -Password = "mypassword"`) - -config := Config{} -toml.Unmarshal(doc, &config) -fmt.Println("user=", config.Postgres.User) -``` - -Or use a query: - -```go -// use a query to gather elements without walking the tree -q, _ := query.Compile("$..[user,password]") -results := q.Execute(config) -for ii, item := range results.Values() { - fmt.Println("Query result %d: %v", ii, item) -} -``` - -## Documentation - -The documentation and additional examples are available at -[godoc.org](http://godoc.org/github.com/pelletier/go-toml). - -## Tools - -Go-toml provides two handy command line tools: - -* `tomll`: Reads TOML files and lint them. - - ``` - go install github.com/pelletier/go-toml/cmd/tomll - tomll --help - ``` -* `tomljson`: Reads a TOML file and outputs its JSON representation. - - ``` - go install github.com/pelletier/go-toml/cmd/tomljson - tomljson --help - ``` - -## Contribute - -Feel free to report bugs and patches using GitHub's pull requests system on -[pelletier/go-toml](https://github.com/pelletier/go-toml). Any feedback would be -much appreciated! - -### Run tests - -You have to make sure two kind of tests run: - -1. The Go unit tests -2. The TOML examples base - -You can run both of them using `./test.sh`. - -### Fuzzing - -The script `./fuzz.sh` is available to -run [go-fuzz](https://github.com/dvyukov/go-fuzz) on go-toml. - -## Versioning - -Go-toml follows [Semantic Versioning](http://semver.org/). The supported version -of [TOML](https://github.com/toml-lang/toml) is indicated at the beginning of -this document. The last two major versions of Go are supported -(see [Go Release Policy](https://golang.org/doc/devel/release.html#policy)). - -## License - -The MIT License (MIT). Read [LICENSE](LICENSE). diff --git a/vendor/github.com/pelletier/go-toml/benchmark.json b/vendor/github.com/pelletier/go-toml/benchmark.json deleted file mode 100644 index 86f99c6a..00000000 --- a/vendor/github.com/pelletier/go-toml/benchmark.json +++ /dev/null @@ -1,164 +0,0 @@ -{ - "array": { - "key1": [ - 1, - 2, - 3 - ], - "key2": [ - "red", - "yellow", - "green" - ], - "key3": [ - [ - 1, - 2 - ], - [ - 3, - 4, - 5 - ] - ], - "key4": [ - [ - 1, - 2 - ], - [ - "a", - "b", - "c" - ] - ], - "key5": [ - 1, - 2, - 3 - ], - "key6": [ - 1, - 2 - ] - }, - "boolean": { - "False": false, - "True": true - }, - "datetime": { - "key1": "1979-05-27T07:32:00Z", - "key2": "1979-05-27T00:32:00-07:00", - "key3": "1979-05-27T00:32:00.999999-07:00" - }, - "float": { - "both": { - "key": 6.626e-34 - }, - "exponent": { - "key1": 5e+22, - "key2": 1000000, - "key3": -0.02 - }, - "fractional": { - "key1": 1, - "key2": 3.1415, - "key3": -0.01 - }, - "underscores": { - "key1": 9224617.445991227, - "key2": 1e+100 - } - }, - "fruit": [{ - "name": "apple", - "physical": { - "color": "red", - "shape": "round" - }, - "variety": [{ - "name": "red delicious" - }, - { - "name": "granny smith" - } - ] - }, - { - "name": "banana", - "variety": [{ - "name": "plantain" - }] - } - ], - "integer": { - "key1": 99, - "key2": 42, - "key3": 0, - "key4": -17, - "underscores": { - "key1": 1000, - "key2": 5349221, - "key3": 12345 - } - }, - "products": [{ - "name": "Hammer", - "sku": 738594937 - }, - {}, - { - "color": "gray", - "name": "Nail", - "sku": 284758393 - } - ], - "string": { - "basic": { - "basic": "I'm a string. \"You can quote me\". Name\tJosé\nLocation\tSF." - }, - "literal": { - "multiline": { - "lines": "The first newline is\ntrimmed in raw strings.\n All other whitespace\n is preserved.\n", - "regex2": "I [dw]on't need \\d{2} apples" - }, - "quoted": "Tom \"Dubs\" Preston-Werner", - "regex": "\u003c\\i\\c*\\s*\u003e", - "winpath": "C:\\Users\\nodejs\\templates", - "winpath2": "\\\\ServerX\\admin$\\system32\\" - }, - "multiline": { - "continued": { - "key1": "The quick brown fox jumps over the lazy dog.", - "key2": "The quick brown fox jumps over the lazy dog.", - "key3": "The quick brown fox jumps over the lazy dog." - }, - "key1": "One\nTwo", - "key2": "One\nTwo", - "key3": "One\nTwo" - } - }, - "table": { - "inline": { - "name": { - "first": "Tom", - "last": "Preston-Werner" - }, - "point": { - "x": 1, - "y": 2 - } - }, - "key": "value", - "subtable": { - "key": "another value" - } - }, - "x": { - "y": { - "z": { - "w": {} - } - } - } -} diff --git a/vendor/github.com/pelletier/go-toml/benchmark.sh b/vendor/github.com/pelletier/go-toml/benchmark.sh deleted file mode 100755 index 8b8bb528..00000000 --- a/vendor/github.com/pelletier/go-toml/benchmark.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/bin/bash - -set -e - -reference_ref=${1:-master} -reference_git=${2:-.} - -if ! `hash benchstat 2>/dev/null`; then - echo "Installing benchstat" - go get golang.org/x/perf/cmd/benchstat - go install golang.org/x/perf/cmd/benchstat -fi - -tempdir=`mktemp -d /tmp/go-toml-benchmark-XXXXXX` -ref_tempdir="${tempdir}/ref" -ref_benchmark="${ref_tempdir}/benchmark-`echo -n ${reference_ref}|tr -s '/' '-'`.txt" -local_benchmark="`pwd`/benchmark-local.txt" - -echo "=== ${reference_ref} (${ref_tempdir})" -git clone ${reference_git} ${ref_tempdir} >/dev/null 2>/dev/null -pushd ${ref_tempdir} >/dev/null -git checkout ${reference_ref} >/dev/null 2>/dev/null -go test -bench=. -benchmem | tee ${ref_benchmark} -popd >/dev/null - -echo "" -echo "=== local" -go test -bench=. -benchmem | tee ${local_benchmark} - -echo "" -echo "=== diff" -benchstat -delta-test=none ${ref_benchmark} ${local_benchmark} \ No newline at end of file diff --git a/vendor/github.com/pelletier/go-toml/benchmark.toml b/vendor/github.com/pelletier/go-toml/benchmark.toml deleted file mode 100644 index dfd77e09..00000000 --- a/vendor/github.com/pelletier/go-toml/benchmark.toml +++ /dev/null @@ -1,244 +0,0 @@ -################################################################################ -## Comment - -# Speak your mind with the hash symbol. They go from the symbol to the end of -# the line. - - -################################################################################ -## Table - -# Tables (also known as hash tables or dictionaries) are collections of -# key/value pairs. They appear in square brackets on a line by themselves. - -[table] - -key = "value" # Yeah, you can do this. - -# Nested tables are denoted by table names with dots in them. Name your tables -# whatever crap you please, just don't use #, ., [ or ]. - -[table.subtable] - -key = "another value" - -# You don't need to specify all the super-tables if you don't want to. TOML -# knows how to do it for you. - -# [x] you -# [x.y] don't -# [x.y.z] need these -[x.y.z.w] # for this to work - - -################################################################################ -## Inline Table - -# Inline tables provide a more compact syntax for expressing tables. They are -# especially useful for grouped data that can otherwise quickly become verbose. -# Inline tables are enclosed in curly braces `{` and `}`. No newlines are -# allowed between the curly braces unless they are valid within a value. - -[table.inline] - -name = { first = "Tom", last = "Preston-Werner" } -point = { x = 1, y = 2 } - - -################################################################################ -## String - -# There are four ways to express strings: basic, multi-line basic, literal, and -# multi-line literal. All strings must contain only valid UTF-8 characters. - -[string.basic] - -basic = "I'm a string. \"You can quote me\". Name\tJos\u00E9\nLocation\tSF." - -[string.multiline] - -# The following strings are byte-for-byte equivalent: -key1 = "One\nTwo" -key2 = """One\nTwo""" -key3 = """ -One -Two""" - -[string.multiline.continued] - -# The following strings are byte-for-byte equivalent: -key1 = "The quick brown fox jumps over the lazy dog." - -key2 = """ -The quick brown \ - - - fox jumps over \ - the lazy dog.""" - -key3 = """\ - The quick brown \ - fox jumps over \ - the lazy dog.\ - """ - -[string.literal] - -# What you see is what you get. -winpath = 'C:\Users\nodejs\templates' -winpath2 = '\\ServerX\admin$\system32\' -quoted = 'Tom "Dubs" Preston-Werner' -regex = '<\i\c*\s*>' - - -[string.literal.multiline] - -regex2 = '''I [dw]on't need \d{2} apples''' -lines = ''' -The first newline is -trimmed in raw strings. - All other whitespace - is preserved. -''' - - -################################################################################ -## Integer - -# Integers are whole numbers. Positive numbers may be prefixed with a plus sign. -# Negative numbers are prefixed with a minus sign. - -[integer] - -key1 = +99 -key2 = 42 -key3 = 0 -key4 = -17 - -[integer.underscores] - -# For large numbers, you may use underscores to enhance readability. Each -# underscore must be surrounded by at least one digit. -key1 = 1_000 -key2 = 5_349_221 -key3 = 1_2_3_4_5 # valid but inadvisable - - -################################################################################ -## Float - -# A float consists of an integer part (which may be prefixed with a plus or -# minus sign) followed by a fractional part and/or an exponent part. - -[float.fractional] - -key1 = +1.0 -key2 = 3.1415 -key3 = -0.01 - -[float.exponent] - -key1 = 5e+22 -key2 = 1e6 -key3 = -2E-2 - -[float.both] - -key = 6.626e-34 - -[float.underscores] - -key1 = 9_224_617.445_991_228_313 -key2 = 1e1_00 - - -################################################################################ -## Boolean - -# Booleans are just the tokens you're used to. Always lowercase. - -[boolean] - -True = true -False = false - - -################################################################################ -## Datetime - -# Datetimes are RFC 3339 dates. - -[datetime] - -key1 = 1979-05-27T07:32:00Z -key2 = 1979-05-27T00:32:00-07:00 -key3 = 1979-05-27T00:32:00.999999-07:00 - - -################################################################################ -## Array - -# Arrays are square brackets with other primitives inside. Whitespace is -# ignored. Elements are separated by commas. Data types may not be mixed. - -[array] - -key1 = [ 1, 2, 3 ] -key2 = [ "red", "yellow", "green" ] -key3 = [ [ 1, 2 ], [3, 4, 5] ] -#key4 = [ [ 1, 2 ], ["a", "b", "c"] ] # this is ok - -# Arrays can also be multiline. So in addition to ignoring whitespace, arrays -# also ignore newlines between the brackets. Terminating commas are ok before -# the closing bracket. - -key5 = [ - 1, 2, 3 -] -key6 = [ - 1, - 2, # this is ok -] - - -################################################################################ -## Array of Tables - -# These can be expressed by using a table name in double brackets. Each table -# with the same double bracketed name will be an element in the array. The -# tables are inserted in the order encountered. - -[[products]] - -name = "Hammer" -sku = 738594937 - -[[products]] - -[[products]] - -name = "Nail" -sku = 284758393 -color = "gray" - - -# You can create nested arrays of tables as well. - -[[fruit]] - name = "apple" - - [fruit.physical] - color = "red" - shape = "round" - - [[fruit.variety]] - name = "red delicious" - - [[fruit.variety]] - name = "granny smith" - -[[fruit]] - name = "banana" - - [[fruit.variety]] - name = "plantain" diff --git a/vendor/github.com/pelletier/go-toml/benchmark.yml b/vendor/github.com/pelletier/go-toml/benchmark.yml deleted file mode 100644 index 0bd19f08..00000000 --- a/vendor/github.com/pelletier/go-toml/benchmark.yml +++ /dev/null @@ -1,121 +0,0 @@ ---- -array: - key1: - - 1 - - 2 - - 3 - key2: - - red - - yellow - - green - key3: - - - 1 - - 2 - - - 3 - - 4 - - 5 - key4: - - - 1 - - 2 - - - a - - b - - c - key5: - - 1 - - 2 - - 3 - key6: - - 1 - - 2 -boolean: - 'False': false - 'True': true -datetime: - key1: '1979-05-27T07:32:00Z' - key2: '1979-05-27T00:32:00-07:00' - key3: '1979-05-27T00:32:00.999999-07:00' -float: - both: - key: 6.626e-34 - exponent: - key1: 5.0e+22 - key2: 1000000 - key3: -0.02 - fractional: - key1: 1 - key2: 3.1415 - key3: -0.01 - underscores: - key1: 9224617.445991227 - key2: 1.0e+100 -fruit: -- name: apple - physical: - color: red - shape: round - variety: - - name: red delicious - - name: granny smith -- name: banana - variety: - - name: plantain -integer: - key1: 99 - key2: 42 - key3: 0 - key4: -17 - underscores: - key1: 1000 - key2: 5349221 - key3: 12345 -products: -- name: Hammer - sku: 738594937 -- {} -- color: gray - name: Nail - sku: 284758393 -string: - basic: - basic: "I'm a string. \"You can quote me\". Name\tJosé\nLocation\tSF." - literal: - multiline: - lines: | - The first newline is - trimmed in raw strings. - All other whitespace - is preserved. - regex2: I [dw]on't need \d{2} apples - quoted: Tom "Dubs" Preston-Werner - regex: "<\\i\\c*\\s*>" - winpath: C:\Users\nodejs\templates - winpath2: "\\\\ServerX\\admin$\\system32\\" - multiline: - continued: - key1: The quick brown fox jumps over the lazy dog. - key2: The quick brown fox jumps over the lazy dog. - key3: The quick brown fox jumps over the lazy dog. - key1: |- - One - Two - key2: |- - One - Two - key3: |- - One - Two -table: - inline: - name: - first: Tom - last: Preston-Werner - point: - x: 1 - y: 2 - key: value - subtable: - key: another value -x: - y: - z: - w: {} diff --git a/vendor/github.com/pelletier/go-toml/benchmark_test.go b/vendor/github.com/pelletier/go-toml/benchmark_test.go deleted file mode 100644 index e1f209df..00000000 --- a/vendor/github.com/pelletier/go-toml/benchmark_test.go +++ /dev/null @@ -1,192 +0,0 @@ -package toml - -import ( - "bytes" - "encoding/json" - "io/ioutil" - "testing" - "time" - - burntsushi "github.com/BurntSushi/toml" - yaml "gopkg.in/yaml.v2" -) - -type benchmarkDoc struct { - Table struct { - Key string - Subtable struct { - Key string - } - Inline struct { - Name struct { - First string - Last string - } - Point struct { - X int64 - U int64 - } - } - } - String struct { - Basic struct { - Basic string - } - Multiline struct { - Key1 string - Key2 string - Key3 string - Continued struct { - Key1 string - Key2 string - Key3 string - } - } - Literal struct { - Winpath string - Winpath2 string - Quoted string - Regex string - Multiline struct { - Regex2 string - Lines string - } - } - } - Integer struct { - Key1 int64 - Key2 int64 - Key3 int64 - Key4 int64 - Underscores struct { - Key1 int64 - Key2 int64 - Key3 int64 - } - } - Float struct { - Fractional struct { - Key1 float64 - Key2 float64 - Key3 float64 - } - Exponent struct { - Key1 float64 - Key2 float64 - Key3 float64 - } - Both struct { - Key float64 - } - Underscores struct { - Key1 float64 - Key2 float64 - } - } - Boolean struct { - True bool - False bool - } - Datetime struct { - Key1 time.Time - Key2 time.Time - Key3 time.Time - } - Array struct { - Key1 []int64 - Key2 []string - Key3 [][]int64 - // TODO: Key4 not supported by go-toml's Unmarshal - Key5 []int64 - Key6 []int64 - } - Products []struct { - Name string - Sku int64 - Color string - } - Fruit []struct { - Name string - Physical struct { - Color string - Shape string - Variety []struct { - Name string - } - } - } -} - -func BenchmarkParseToml(b *testing.B) { - fileBytes, err := ioutil.ReadFile("benchmark.toml") - if err != nil { - b.Fatal(err) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, err := LoadReader(bytes.NewReader(fileBytes)) - if err != nil { - b.Fatal(err) - } - } -} - -func BenchmarkUnmarshalToml(b *testing.B) { - bytes, err := ioutil.ReadFile("benchmark.toml") - if err != nil { - b.Fatal(err) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - target := benchmarkDoc{} - err := Unmarshal(bytes, &target) - if err != nil { - b.Fatal(err) - } - } -} - -func BenchmarkUnmarshalBurntSushiToml(b *testing.B) { - bytes, err := ioutil.ReadFile("benchmark.toml") - if err != nil { - b.Fatal(err) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - target := benchmarkDoc{} - err := burntsushi.Unmarshal(bytes, &target) - if err != nil { - b.Fatal(err) - } - } -} - -func BenchmarkUnmarshalJson(b *testing.B) { - bytes, err := ioutil.ReadFile("benchmark.json") - if err != nil { - b.Fatal(err) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - target := benchmarkDoc{} - err := json.Unmarshal(bytes, &target) - if err != nil { - b.Fatal(err) - } - } -} - -func BenchmarkUnmarshalYaml(b *testing.B) { - bytes, err := ioutil.ReadFile("benchmark.yml") - if err != nil { - b.Fatal(err) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - target := benchmarkDoc{} - err := yaml.Unmarshal(bytes, &target) - if err != nil { - b.Fatal(err) - } - } -} diff --git a/vendor/github.com/pelletier/go-toml/doc_test.go b/vendor/github.com/pelletier/go-toml/doc_test.go deleted file mode 100644 index 3b8171b2..00000000 --- a/vendor/github.com/pelletier/go-toml/doc_test.go +++ /dev/null @@ -1,105 +0,0 @@ -// code examples for godoc - -package toml_test - -import ( - "fmt" - "log" - - toml "github.com/pelletier/go-toml" -) - -func Example_tree() { - config, err := toml.LoadFile("config.toml") - - if err != nil { - fmt.Println("Error ", err.Error()) - } else { - // retrieve data directly - user := config.Get("postgres.user").(string) - password := config.Get("postgres.password").(string) - - // or using an intermediate object - configTree := config.Get("postgres").(*toml.Tree) - user = configTree.Get("user").(string) - password = configTree.Get("password").(string) - fmt.Println("User is", user, " and password is", password) - - // show where elements are in the file - fmt.Printf("User position: %v\n", configTree.GetPosition("user")) - fmt.Printf("Password position: %v\n", configTree.GetPosition("password")) - } -} - -func Example_unmarshal() { - type Employer struct { - Name string - Phone string - } - type Person struct { - Name string - Age int64 - Employer Employer - } - - document := []byte(` - name = "John" - age = 30 - [employer] - name = "Company Inc." - phone = "+1 234 567 89012" - `) - - person := Person{} - toml.Unmarshal(document, &person) - fmt.Println(person.Name, "is", person.Age, "and works at", person.Employer.Name) - // Output: - // John is 30 and works at Company Inc. -} - -func ExampleMarshal() { - type Postgres struct { - User string `toml:"user"` - Password string `toml:"password"` - Database string `toml:"db" commented:"true" comment:"not used anymore"` - } - type Config struct { - Postgres Postgres `toml:"postgres" comment:"Postgres configuration"` - } - - config := Config{Postgres{User: "pelletier", Password: "mypassword", Database: "old_database"}} - b, err := toml.Marshal(config) - if err != nil { - log.Fatal(err) - } - fmt.Println(string(b)) - // Output: - // # Postgres configuration - // [postgres] - // - // # not used anymore - // # db = "old_database" - // password = "mypassword" - // user = "pelletier" -} - -func ExampleUnmarshal() { - type Postgres struct { - User string - Password string - } - type Config struct { - Postgres Postgres - } - - doc := []byte(` - [postgres] - user = "pelletier" - password = "mypassword"`) - - config := Config{} - toml.Unmarshal(doc, &config) - fmt.Println("user=", config.Postgres.User) - // Output: - // user= pelletier -} diff --git a/vendor/github.com/pelletier/go-toml/example-crlf.toml b/vendor/github.com/pelletier/go-toml/example-crlf.toml deleted file mode 100644 index 12950a16..00000000 --- a/vendor/github.com/pelletier/go-toml/example-crlf.toml +++ /dev/null @@ -1,29 +0,0 @@ -# This is a TOML document. Boom. - -title = "TOML Example" - -[owner] -name = "Tom Preston-Werner" -organization = "GitHub" -bio = "GitHub Cofounder & CEO\nLikes tater tots and beer." -dob = 1979-05-27T07:32:00Z # First class dates? Why not? - -[database] -server = "192.168.1.1" -ports = [ 8001, 8001, 8002 ] -connection_max = 5000 -enabled = true - -[servers] - - # You can indent as you please. Tabs or spaces. TOML don't care. - [servers.alpha] - ip = "10.0.0.1" - dc = "eqdc10" - - [servers.beta] - ip = "10.0.0.2" - dc = "eqdc10" - -[clients] -data = [ ["gamma", "delta"], [1, 2] ] # just an update to make sure parsers support it diff --git a/vendor/github.com/pelletier/go-toml/example.toml b/vendor/github.com/pelletier/go-toml/example.toml deleted file mode 100644 index 3d902f28..00000000 --- a/vendor/github.com/pelletier/go-toml/example.toml +++ /dev/null @@ -1,29 +0,0 @@ -# This is a TOML document. Boom. - -title = "TOML Example" - -[owner] -name = "Tom Preston-Werner" -organization = "GitHub" -bio = "GitHub Cofounder & CEO\nLikes tater tots and beer." -dob = 1979-05-27T07:32:00Z # First class dates? Why not? - -[database] -server = "192.168.1.1" -ports = [ 8001, 8001, 8002 ] -connection_max = 5000 -enabled = true - -[servers] - - # You can indent as you please. Tabs or spaces. TOML don't care. - [servers.alpha] - ip = "10.0.0.1" - dc = "eqdc10" - - [servers.beta] - ip = "10.0.0.2" - dc = "eqdc10" - -[clients] -data = [ ["gamma", "delta"], [1, 2] ] # just an update to make sure parsers support it diff --git a/vendor/github.com/pelletier/go-toml/fuzz.sh b/vendor/github.com/pelletier/go-toml/fuzz.sh deleted file mode 100755 index 3204b4c4..00000000 --- a/vendor/github.com/pelletier/go-toml/fuzz.sh +++ /dev/null @@ -1,15 +0,0 @@ -#! /bin/sh -set -eu - -go get github.com/dvyukov/go-fuzz/go-fuzz -go get github.com/dvyukov/go-fuzz/go-fuzz-build - -if [ ! -e toml-fuzz.zip ]; then - go-fuzz-build github.com/pelletier/go-toml -fi - -rm -fr fuzz -mkdir -p fuzz/corpus -cp *.toml fuzz/corpus - -go-fuzz -bin=toml-fuzz.zip -workdir=fuzz diff --git a/vendor/github.com/pelletier/go-toml/keysparsing_test.go b/vendor/github.com/pelletier/go-toml/keysparsing_test.go deleted file mode 100644 index 7aa4cd64..00000000 --- a/vendor/github.com/pelletier/go-toml/keysparsing_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package toml - -import ( - "fmt" - "testing" -) - -func testResult(t *testing.T, key string, expected []string) { - parsed, err := parseKey(key) - t.Logf("key=%s expected=%s parsed=%s", key, expected, parsed) - if err != nil { - t.Fatal("Unexpected error:", err) - } - if len(expected) != len(parsed) { - t.Fatal("Expected length", len(expected), "but", len(parsed), "parsed") - } - for index, expectedKey := range expected { - if expectedKey != parsed[index] { - t.Fatal("Expected", expectedKey, "at index", index, "but found", parsed[index]) - } - } -} - -func testError(t *testing.T, key string, expectedError string) { - res, err := parseKey(key) - if err == nil { - t.Fatalf("Expected error, but succesfully parsed key %s", res) - } - if fmt.Sprintf("%s", err) != expectedError { - t.Fatalf("Expected error \"%s\", but got \"%s\".", expectedError, err) - } -} - -func TestBareKeyBasic(t *testing.T) { - testResult(t, "test", []string{"test"}) -} - -func TestBareKeyDotted(t *testing.T) { - testResult(t, "this.is.a.key", []string{"this", "is", "a", "key"}) -} - -func TestDottedKeyBasic(t *testing.T) { - testResult(t, "\"a.dotted.key\"", []string{"a.dotted.key"}) -} - -func TestBaseKeyPound(t *testing.T) { - testError(t, "hello#world", "invalid bare character: #") -} - -func TestQuotedKeys(t *testing.T) { - testResult(t, `hello."foo".bar`, []string{"hello", "foo", "bar"}) - testResult(t, `"hello!"`, []string{"hello!"}) - testResult(t, `"hello\tworld"`, []string{"hello\tworld"}) - testResult(t, `"\U0001F914"`, []string{"\U0001F914"}) - testResult(t, `"\u2764"`, []string{"\u2764"}) - - testResult(t, `hello.'foo'.bar`, []string{"hello", "foo", "bar"}) - testResult(t, `'hello!'`, []string{"hello!"}) - testResult(t, `'hello\tworld'`, []string{`hello\tworld`}) - - testError(t, `"\w"`, `invalid escape sequence \w`) - testError(t, `"\`, `unfinished escape sequence`) - testError(t, `"\t`, `mismatched quotes`) -} - -func TestEmptyKey(t *testing.T) { - testError(t, "", "empty key") - testError(t, " ", "empty key") - testResult(t, `""`, []string{""}) -} diff --git a/vendor/github.com/pelletier/go-toml/lexer_test.go b/vendor/github.com/pelletier/go-toml/lexer_test.go deleted file mode 100644 index 313b83c5..00000000 --- a/vendor/github.com/pelletier/go-toml/lexer_test.go +++ /dev/null @@ -1,750 +0,0 @@ -package toml - -import ( - "reflect" - "testing" -) - -func testFlow(t *testing.T, input string, expectedFlow []token) { - tokens := lexToml([]byte(input)) - if !reflect.DeepEqual(tokens, expectedFlow) { - t.Fatal("Different flows. Expected\n", expectedFlow, "\nGot:\n", tokens) - } -} - -func TestValidKeyGroup(t *testing.T) { - testFlow(t, "[hello world]", []token{ - {Position{1, 1}, tokenLeftBracket, "["}, - {Position{1, 2}, tokenKeyGroup, "hello world"}, - {Position{1, 13}, tokenRightBracket, "]"}, - {Position{1, 14}, tokenEOF, ""}, - }) -} - -func TestNestedQuotedUnicodeKeyGroup(t *testing.T) { - testFlow(t, `[ j . "ʞ" . l ]`, []token{ - {Position{1, 1}, tokenLeftBracket, "["}, - {Position{1, 2}, tokenKeyGroup, ` j . "ʞ" . l `}, - {Position{1, 15}, tokenRightBracket, "]"}, - {Position{1, 16}, tokenEOF, ""}, - }) -} - -func TestUnclosedKeyGroup(t *testing.T) { - testFlow(t, "[hello world", []token{ - {Position{1, 1}, tokenLeftBracket, "["}, - {Position{1, 2}, tokenError, "unclosed table key"}, - }) -} - -func TestComment(t *testing.T) { - testFlow(t, "# blahblah", []token{ - {Position{1, 11}, tokenEOF, ""}, - }) -} - -func TestKeyGroupComment(t *testing.T) { - testFlow(t, "[hello world] # blahblah", []token{ - {Position{1, 1}, tokenLeftBracket, "["}, - {Position{1, 2}, tokenKeyGroup, "hello world"}, - {Position{1, 13}, tokenRightBracket, "]"}, - {Position{1, 25}, tokenEOF, ""}, - }) -} - -func TestMultipleKeyGroupsComment(t *testing.T) { - testFlow(t, "[hello world] # blahblah\n[test]", []token{ - {Position{1, 1}, tokenLeftBracket, "["}, - {Position{1, 2}, tokenKeyGroup, "hello world"}, - {Position{1, 13}, tokenRightBracket, "]"}, - {Position{2, 1}, tokenLeftBracket, "["}, - {Position{2, 2}, tokenKeyGroup, "test"}, - {Position{2, 6}, tokenRightBracket, "]"}, - {Position{2, 7}, tokenEOF, ""}, - }) -} - -func TestSimpleWindowsCRLF(t *testing.T) { - testFlow(t, "a=4\r\nb=2", []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 2}, tokenEqual, "="}, - {Position{1, 3}, tokenInteger, "4"}, - {Position{2, 1}, tokenKey, "b"}, - {Position{2, 2}, tokenEqual, "="}, - {Position{2, 3}, tokenInteger, "2"}, - {Position{2, 4}, tokenEOF, ""}, - }) -} - -func TestBasicKey(t *testing.T) { - testFlow(t, "hello", []token{ - {Position{1, 1}, tokenKey, "hello"}, - {Position{1, 6}, tokenEOF, ""}, - }) -} - -func TestBasicKeyWithUnderscore(t *testing.T) { - testFlow(t, "hello_hello", []token{ - {Position{1, 1}, tokenKey, "hello_hello"}, - {Position{1, 12}, tokenEOF, ""}, - }) -} - -func TestBasicKeyWithDash(t *testing.T) { - testFlow(t, "hello-world", []token{ - {Position{1, 1}, tokenKey, "hello-world"}, - {Position{1, 12}, tokenEOF, ""}, - }) -} - -func TestBasicKeyWithUppercaseMix(t *testing.T) { - testFlow(t, "helloHELLOHello", []token{ - {Position{1, 1}, tokenKey, "helloHELLOHello"}, - {Position{1, 16}, tokenEOF, ""}, - }) -} - -func TestBasicKeyWithInternationalCharacters(t *testing.T) { - testFlow(t, "héllÖ", []token{ - {Position{1, 1}, tokenKey, "héllÖ"}, - {Position{1, 6}, tokenEOF, ""}, - }) -} - -func TestBasicKeyAndEqual(t *testing.T) { - testFlow(t, "hello =", []token{ - {Position{1, 1}, tokenKey, "hello"}, - {Position{1, 7}, tokenEqual, "="}, - {Position{1, 8}, tokenEOF, ""}, - }) -} - -func TestKeyWithSharpAndEqual(t *testing.T) { - testFlow(t, "key#name = 5", []token{ - {Position{1, 1}, tokenError, "keys cannot contain # character"}, - }) -} - -func TestKeyWithSymbolsAndEqual(t *testing.T) { - testFlow(t, "~!@$^&*()_+-`1234567890[]\\|/?><.,;:' = 5", []token{ - {Position{1, 1}, tokenError, "keys cannot contain ~ character"}, - }) -} - -func TestKeyEqualStringEscape(t *testing.T) { - testFlow(t, `foo = "hello\""`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, "hello\""}, - {Position{1, 16}, tokenEOF, ""}, - }) -} - -func TestKeyEqualStringUnfinished(t *testing.T) { - testFlow(t, `foo = "bar`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenError, "unclosed string"}, - }) -} - -func TestKeyEqualString(t *testing.T) { - testFlow(t, `foo = "bar"`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, "bar"}, - {Position{1, 12}, tokenEOF, ""}, - }) -} - -func TestKeyEqualTrue(t *testing.T) { - testFlow(t, "foo = true", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenTrue, "true"}, - {Position{1, 11}, tokenEOF, ""}, - }) -} - -func TestKeyEqualFalse(t *testing.T) { - testFlow(t, "foo = false", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenFalse, "false"}, - {Position{1, 12}, tokenEOF, ""}, - }) -} - -func TestArrayNestedString(t *testing.T) { - testFlow(t, `a = [ ["hello", "world"] ]`, []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 3}, tokenEqual, "="}, - {Position{1, 5}, tokenLeftBracket, "["}, - {Position{1, 7}, tokenLeftBracket, "["}, - {Position{1, 9}, tokenString, "hello"}, - {Position{1, 15}, tokenComma, ","}, - {Position{1, 18}, tokenString, "world"}, - {Position{1, 24}, tokenRightBracket, "]"}, - {Position{1, 26}, tokenRightBracket, "]"}, - {Position{1, 27}, tokenEOF, ""}, - }) -} - -func TestArrayNestedInts(t *testing.T) { - testFlow(t, "a = [ [42, 21], [10] ]", []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 3}, tokenEqual, "="}, - {Position{1, 5}, tokenLeftBracket, "["}, - {Position{1, 7}, tokenLeftBracket, "["}, - {Position{1, 8}, tokenInteger, "42"}, - {Position{1, 10}, tokenComma, ","}, - {Position{1, 12}, tokenInteger, "21"}, - {Position{1, 14}, tokenRightBracket, "]"}, - {Position{1, 15}, tokenComma, ","}, - {Position{1, 17}, tokenLeftBracket, "["}, - {Position{1, 18}, tokenInteger, "10"}, - {Position{1, 20}, tokenRightBracket, "]"}, - {Position{1, 22}, tokenRightBracket, "]"}, - {Position{1, 23}, tokenEOF, ""}, - }) -} - -func TestArrayInts(t *testing.T) { - testFlow(t, "a = [ 42, 21, 10, ]", []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 3}, tokenEqual, "="}, - {Position{1, 5}, tokenLeftBracket, "["}, - {Position{1, 7}, tokenInteger, "42"}, - {Position{1, 9}, tokenComma, ","}, - {Position{1, 11}, tokenInteger, "21"}, - {Position{1, 13}, tokenComma, ","}, - {Position{1, 15}, tokenInteger, "10"}, - {Position{1, 17}, tokenComma, ","}, - {Position{1, 19}, tokenRightBracket, "]"}, - {Position{1, 20}, tokenEOF, ""}, - }) -} - -func TestMultilineArrayComments(t *testing.T) { - testFlow(t, "a = [1, # wow\n2, # such items\n3, # so array\n]", []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 3}, tokenEqual, "="}, - {Position{1, 5}, tokenLeftBracket, "["}, - {Position{1, 6}, tokenInteger, "1"}, - {Position{1, 7}, tokenComma, ","}, - {Position{2, 1}, tokenInteger, "2"}, - {Position{2, 2}, tokenComma, ","}, - {Position{3, 1}, tokenInteger, "3"}, - {Position{3, 2}, tokenComma, ","}, - {Position{4, 1}, tokenRightBracket, "]"}, - {Position{4, 2}, tokenEOF, ""}, - }) -} - -func TestNestedArraysComment(t *testing.T) { - toml := ` -someArray = [ -# does not work -["entry1"] -]` - testFlow(t, toml, []token{ - {Position{2, 1}, tokenKey, "someArray"}, - {Position{2, 11}, tokenEqual, "="}, - {Position{2, 13}, tokenLeftBracket, "["}, - {Position{4, 1}, tokenLeftBracket, "["}, - {Position{4, 3}, tokenString, "entry1"}, - {Position{4, 10}, tokenRightBracket, "]"}, - {Position{5, 1}, tokenRightBracket, "]"}, - {Position{5, 2}, tokenEOF, ""}, - }) -} - -func TestKeyEqualArrayBools(t *testing.T) { - testFlow(t, "foo = [true, false, true]", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenLeftBracket, "["}, - {Position{1, 8}, tokenTrue, "true"}, - {Position{1, 12}, tokenComma, ","}, - {Position{1, 14}, tokenFalse, "false"}, - {Position{1, 19}, tokenComma, ","}, - {Position{1, 21}, tokenTrue, "true"}, - {Position{1, 25}, tokenRightBracket, "]"}, - {Position{1, 26}, tokenEOF, ""}, - }) -} - -func TestKeyEqualArrayBoolsWithComments(t *testing.T) { - testFlow(t, "foo = [true, false, true] # YEAH", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenLeftBracket, "["}, - {Position{1, 8}, tokenTrue, "true"}, - {Position{1, 12}, tokenComma, ","}, - {Position{1, 14}, tokenFalse, "false"}, - {Position{1, 19}, tokenComma, ","}, - {Position{1, 21}, tokenTrue, "true"}, - {Position{1, 25}, tokenRightBracket, "]"}, - {Position{1, 33}, tokenEOF, ""}, - }) -} - -func TestDateRegexp(t *testing.T) { - if dateRegexp.FindString("1979-05-27T07:32:00Z") == "" { - t.Error("basic lexing") - } - if dateRegexp.FindString("1979-05-27T00:32:00-07:00") == "" { - t.Error("offset lexing") - } - if dateRegexp.FindString("1979-05-27T00:32:00.999999-07:00") == "" { - t.Error("nano precision lexing") - } -} - -func TestKeyEqualDate(t *testing.T) { - testFlow(t, "foo = 1979-05-27T07:32:00Z", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenDate, "1979-05-27T07:32:00Z"}, - {Position{1, 27}, tokenEOF, ""}, - }) - testFlow(t, "foo = 1979-05-27T00:32:00-07:00", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenDate, "1979-05-27T00:32:00-07:00"}, - {Position{1, 32}, tokenEOF, ""}, - }) - testFlow(t, "foo = 1979-05-27T00:32:00.999999-07:00", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenDate, "1979-05-27T00:32:00.999999-07:00"}, - {Position{1, 39}, tokenEOF, ""}, - }) -} - -func TestFloatEndingWithDot(t *testing.T) { - testFlow(t, "foo = 42.", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenError, "float cannot end with a dot"}, - }) -} - -func TestFloatWithTwoDots(t *testing.T) { - testFlow(t, "foo = 4.2.", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenError, "cannot have two dots in one float"}, - }) -} - -func TestFloatWithExponent1(t *testing.T) { - testFlow(t, "a = 5e+22", []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 3}, tokenEqual, "="}, - {Position{1, 5}, tokenFloat, "5e+22"}, - {Position{1, 10}, tokenEOF, ""}, - }) -} - -func TestFloatWithExponent2(t *testing.T) { - testFlow(t, "a = 5E+22", []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 3}, tokenEqual, "="}, - {Position{1, 5}, tokenFloat, "5E+22"}, - {Position{1, 10}, tokenEOF, ""}, - }) -} - -func TestFloatWithExponent3(t *testing.T) { - testFlow(t, "a = -5e+22", []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 3}, tokenEqual, "="}, - {Position{1, 5}, tokenFloat, "-5e+22"}, - {Position{1, 11}, tokenEOF, ""}, - }) -} - -func TestFloatWithExponent4(t *testing.T) { - testFlow(t, "a = -5e-22", []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 3}, tokenEqual, "="}, - {Position{1, 5}, tokenFloat, "-5e-22"}, - {Position{1, 11}, tokenEOF, ""}, - }) -} - -func TestFloatWithExponent5(t *testing.T) { - testFlow(t, "a = 6.626e-34", []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 3}, tokenEqual, "="}, - {Position{1, 5}, tokenFloat, "6.626e-34"}, - {Position{1, 14}, tokenEOF, ""}, - }) -} - -func TestInvalidEsquapeSequence(t *testing.T) { - testFlow(t, `foo = "\x"`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenError, "invalid escape sequence: \\x"}, - }) -} - -func TestNestedArrays(t *testing.T) { - testFlow(t, "foo = [[[]]]", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenLeftBracket, "["}, - {Position{1, 8}, tokenLeftBracket, "["}, - {Position{1, 9}, tokenLeftBracket, "["}, - {Position{1, 10}, tokenRightBracket, "]"}, - {Position{1, 11}, tokenRightBracket, "]"}, - {Position{1, 12}, tokenRightBracket, "]"}, - {Position{1, 13}, tokenEOF, ""}, - }) -} - -func TestKeyEqualNumber(t *testing.T) { - testFlow(t, "foo = 42", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenInteger, "42"}, - {Position{1, 9}, tokenEOF, ""}, - }) - - testFlow(t, "foo = +42", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenInteger, "+42"}, - {Position{1, 10}, tokenEOF, ""}, - }) - - testFlow(t, "foo = -42", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenInteger, "-42"}, - {Position{1, 10}, tokenEOF, ""}, - }) - - testFlow(t, "foo = 4.2", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenFloat, "4.2"}, - {Position{1, 10}, tokenEOF, ""}, - }) - - testFlow(t, "foo = +4.2", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenFloat, "+4.2"}, - {Position{1, 11}, tokenEOF, ""}, - }) - - testFlow(t, "foo = -4.2", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenFloat, "-4.2"}, - {Position{1, 11}, tokenEOF, ""}, - }) - - testFlow(t, "foo = 1_000", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenInteger, "1_000"}, - {Position{1, 12}, tokenEOF, ""}, - }) - - testFlow(t, "foo = 5_349_221", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenInteger, "5_349_221"}, - {Position{1, 16}, tokenEOF, ""}, - }) - - testFlow(t, "foo = 1_2_3_4_5", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenInteger, "1_2_3_4_5"}, - {Position{1, 16}, tokenEOF, ""}, - }) - - testFlow(t, "flt8 = 9_224_617.445_991_228_313", []token{ - {Position{1, 1}, tokenKey, "flt8"}, - {Position{1, 6}, tokenEqual, "="}, - {Position{1, 8}, tokenFloat, "9_224_617.445_991_228_313"}, - {Position{1, 33}, tokenEOF, ""}, - }) - - testFlow(t, "foo = +", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenError, "no digit in that number"}, - }) -} - -func TestMultiline(t *testing.T) { - testFlow(t, "foo = 42\nbar=21", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 7}, tokenInteger, "42"}, - {Position{2, 1}, tokenKey, "bar"}, - {Position{2, 4}, tokenEqual, "="}, - {Position{2, 5}, tokenInteger, "21"}, - {Position{2, 7}, tokenEOF, ""}, - }) -} - -func TestKeyEqualStringUnicodeEscape(t *testing.T) { - testFlow(t, `foo = "hello \u2665"`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, "hello ♥"}, - {Position{1, 21}, tokenEOF, ""}, - }) - testFlow(t, `foo = "hello \U000003B4"`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, "hello δ"}, - {Position{1, 25}, tokenEOF, ""}, - }) - testFlow(t, `foo = "\uabcd"`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, "\uabcd"}, - {Position{1, 15}, tokenEOF, ""}, - }) - testFlow(t, `foo = "\uABCD"`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, "\uABCD"}, - {Position{1, 15}, tokenEOF, ""}, - }) - testFlow(t, `foo = "\U000bcdef"`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, "\U000bcdef"}, - {Position{1, 19}, tokenEOF, ""}, - }) - testFlow(t, `foo = "\U000BCDEF"`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, "\U000BCDEF"}, - {Position{1, 19}, tokenEOF, ""}, - }) - testFlow(t, `foo = "\u2"`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenError, "unfinished unicode escape"}, - }) - testFlow(t, `foo = "\U2"`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenError, "unfinished unicode escape"}, - }) -} - -func TestKeyEqualStringNoEscape(t *testing.T) { - testFlow(t, "foo = \"hello \u0002\"", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenError, "unescaped control character U+0002"}, - }) - testFlow(t, "foo = \"hello \u001F\"", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenError, "unescaped control character U+001F"}, - }) -} - -func TestLiteralString(t *testing.T) { - testFlow(t, `foo = 'C:\Users\nodejs\templates'`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, `C:\Users\nodejs\templates`}, - {Position{1, 34}, tokenEOF, ""}, - }) - testFlow(t, `foo = '\\ServerX\admin$\system32\'`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, `\\ServerX\admin$\system32\`}, - {Position{1, 35}, tokenEOF, ""}, - }) - testFlow(t, `foo = 'Tom "Dubs" Preston-Werner'`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, `Tom "Dubs" Preston-Werner`}, - {Position{1, 34}, tokenEOF, ""}, - }) - testFlow(t, `foo = '<\i\c*\s*>'`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, `<\i\c*\s*>`}, - {Position{1, 19}, tokenEOF, ""}, - }) - testFlow(t, `foo = 'C:\Users\nodejs\unfinis`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenError, "unclosed string"}, - }) -} - -func TestMultilineLiteralString(t *testing.T) { - testFlow(t, `foo = '''hello 'literal' world'''`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 10}, tokenString, `hello 'literal' world`}, - {Position{1, 34}, tokenEOF, ""}, - }) - - testFlow(t, "foo = '''\nhello\n'literal'\nworld'''", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{2, 1}, tokenString, "hello\n'literal'\nworld"}, - {Position{4, 9}, tokenEOF, ""}, - }) - testFlow(t, "foo = '''\r\nhello\r\n'literal'\r\nworld'''", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{2, 1}, tokenString, "hello\r\n'literal'\r\nworld"}, - {Position{4, 9}, tokenEOF, ""}, - }) -} - -func TestMultilineString(t *testing.T) { - testFlow(t, `foo = """hello "literal" world"""`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 10}, tokenString, `hello "literal" world`}, - {Position{1, 34}, tokenEOF, ""}, - }) - - testFlow(t, "foo = \"\"\"\r\nhello\\\r\n\"literal\"\\\nworld\"\"\"", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{2, 1}, tokenString, "hello\"literal\"world"}, - {Position{4, 9}, tokenEOF, ""}, - }) - - testFlow(t, "foo = \"\"\"\\\n \\\n \\\n hello\\\nmultiline\\\nworld\"\"\"", []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 10}, tokenString, "hellomultilineworld"}, - {Position{6, 9}, tokenEOF, ""}, - }) - - testFlow(t, "key2 = \"\"\"\nThe quick brown \\\n\n\n fox jumps over \\\n the lazy dog.\"\"\"", []token{ - {Position{1, 1}, tokenKey, "key2"}, - {Position{1, 6}, tokenEqual, "="}, - {Position{2, 1}, tokenString, "The quick brown fox jumps over the lazy dog."}, - {Position{6, 21}, tokenEOF, ""}, - }) - - testFlow(t, "key2 = \"\"\"\\\n The quick brown \\\n fox jumps over \\\n the lazy dog.\\\n \"\"\"", []token{ - {Position{1, 1}, tokenKey, "key2"}, - {Position{1, 6}, tokenEqual, "="}, - {Position{1, 11}, tokenString, "The quick brown fox jumps over the lazy dog."}, - {Position{5, 11}, tokenEOF, ""}, - }) - - testFlow(t, `key2 = "Roses are red\nViolets are blue"`, []token{ - {Position{1, 1}, tokenKey, "key2"}, - {Position{1, 6}, tokenEqual, "="}, - {Position{1, 9}, tokenString, "Roses are red\nViolets are blue"}, - {Position{1, 41}, tokenEOF, ""}, - }) - - testFlow(t, "key2 = \"\"\"\nRoses are red\nViolets are blue\"\"\"", []token{ - {Position{1, 1}, tokenKey, "key2"}, - {Position{1, 6}, tokenEqual, "="}, - {Position{2, 1}, tokenString, "Roses are red\nViolets are blue"}, - {Position{3, 20}, tokenEOF, ""}, - }) -} - -func TestUnicodeString(t *testing.T) { - testFlow(t, `foo = "hello ♥ world"`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, "hello ♥ world"}, - {Position{1, 22}, tokenEOF, ""}, - }) -} -func TestEscapeInString(t *testing.T) { - testFlow(t, `foo = "\b\f\/"`, []token{ - {Position{1, 1}, tokenKey, "foo"}, - {Position{1, 5}, tokenEqual, "="}, - {Position{1, 8}, tokenString, "\b\f/"}, - {Position{1, 15}, tokenEOF, ""}, - }) -} - -func TestKeyGroupArray(t *testing.T) { - testFlow(t, "[[foo]]", []token{ - {Position{1, 1}, tokenDoubleLeftBracket, "[["}, - {Position{1, 3}, tokenKeyGroupArray, "foo"}, - {Position{1, 6}, tokenDoubleRightBracket, "]]"}, - {Position{1, 8}, tokenEOF, ""}, - }) -} - -func TestQuotedKey(t *testing.T) { - testFlow(t, "\"a b\" = 42", []token{ - {Position{1, 1}, tokenKey, "\"a b\""}, - {Position{1, 7}, tokenEqual, "="}, - {Position{1, 9}, tokenInteger, "42"}, - {Position{1, 11}, tokenEOF, ""}, - }) -} - -func TestKeyNewline(t *testing.T) { - testFlow(t, "a\n= 4", []token{ - {Position{1, 1}, tokenError, "keys cannot contain new lines"}, - }) -} - -func TestInvalidFloat(t *testing.T) { - testFlow(t, "a=7e1_", []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 2}, tokenEqual, "="}, - {Position{1, 3}, tokenFloat, "7e1_"}, - {Position{1, 7}, tokenEOF, ""}, - }) -} - -func TestLexUnknownRvalue(t *testing.T) { - testFlow(t, `a = !b`, []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 3}, tokenEqual, "="}, - {Position{1, 5}, tokenError, "no value can start with !"}, - }) - - testFlow(t, `a = \b`, []token{ - {Position{1, 1}, tokenKey, "a"}, - {Position{1, 3}, tokenEqual, "="}, - {Position{1, 5}, tokenError, `no value can start with \`}, - }) -} - -func BenchmarkLexer(b *testing.B) { - sample := `title = "Hugo: A Fast and Flexible Website Generator" -baseurl = "http://gohugo.io/" -MetaDataFormat = "yaml" -pluralizeListTitles = false - -[params] - description = "Documentation of Hugo, a fast and flexible static site generator built with love by spf13, bep and friends in Go" - author = "Steve Francia (spf13) and friends" - release = "0.22-DEV" - -[[menu.main]] - name = "Download Hugo" - pre = "" - url = "https://github.com/spf13/hugo/releases" - weight = -200 -` - b.ResetTimer() - for i := 0; i < b.N; i++ { - lexToml([]byte(sample)) - } -} diff --git a/vendor/github.com/pelletier/go-toml/marshal_test.go b/vendor/github.com/pelletier/go-toml/marshal_test.go deleted file mode 100644 index 82268aa7..00000000 --- a/vendor/github.com/pelletier/go-toml/marshal_test.go +++ /dev/null @@ -1,806 +0,0 @@ -package toml - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "reflect" - "strings" - "testing" - "time" -) - -type basicMarshalTestStruct struct { - String string `toml:"string"` - StringList []string `toml:"strlist"` - Sub basicMarshalTestSubStruct `toml:"subdoc"` - SubList []basicMarshalTestSubStruct `toml:"sublist"` -} - -type basicMarshalTestSubStruct struct { - String2 string -} - -var basicTestData = basicMarshalTestStruct{ - String: "Hello", - StringList: []string{"Howdy", "Hey There"}, - Sub: basicMarshalTestSubStruct{"One"}, - SubList: []basicMarshalTestSubStruct{{"Two"}, {"Three"}}, -} - -var basicTestToml = []byte(`string = "Hello" -strlist = ["Howdy","Hey There"] - -[subdoc] - String2 = "One" - -[[sublist]] - String2 = "Two" - -[[sublist]] - String2 = "Three" -`) - -func TestBasicMarshal(t *testing.T) { - result, err := Marshal(basicTestData) - if err != nil { - t.Fatal(err) - } - expected := basicTestToml - if !bytes.Equal(result, expected) { - t.Errorf("Bad marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -func TestBasicUnmarshal(t *testing.T) { - result := basicMarshalTestStruct{} - err := Unmarshal(basicTestToml, &result) - expected := basicTestData - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(result, expected) { - t.Errorf("Bad unmarshal: expected %v, got %v", expected, result) - } -} - -type testDoc struct { - Title string `toml:"title"` - Basics testDocBasics `toml:"basic"` - BasicLists testDocBasicLists `toml:"basic_lists"` - BasicMap map[string]string `toml:"basic_map"` - Subdocs testDocSubs `toml:"subdoc"` - SubDocList []testSubDoc `toml:"subdoclist"` - SubDocPtrs []*testSubDoc `toml:"subdocptrs"` - err int `toml:"shouldntBeHere"` - unexported int `toml:"shouldntBeHere"` - Unexported2 int `toml:"-"` -} - -type testDocBasics struct { - Bool bool `toml:"bool"` - Date time.Time `toml:"date"` - Float float32 `toml:"float"` - Int int `toml:"int"` - Uint uint `toml:"uint"` - String *string `toml:"string"` - unexported int `toml:"shouldntBeHere"` -} - -type testDocBasicLists struct { - Bools []bool `toml:"bools"` - Dates []time.Time `toml:"dates"` - Floats []*float32 `toml:"floats"` - Ints []int `toml:"ints"` - Strings []string `toml:"strings"` - UInts []uint `toml:"uints"` -} - -type testDocSubs struct { - First testSubDoc `toml:"first"` - Second *testSubDoc `toml:"second"` -} - -type testSubDoc struct { - Name string `toml:"name"` - unexported int `toml:"shouldntBeHere"` -} - -var biteMe = "Bite me" -var float1 float32 = 12.3 -var float2 float32 = 45.6 -var float3 float32 = 78.9 -var subdoc = testSubDoc{"Second", 0} - -var docData = testDoc{ - Title: "TOML Marshal Testing", - unexported: 0, - Unexported2: 0, - Basics: testDocBasics{ - Bool: true, - Date: time.Date(1979, 5, 27, 7, 32, 0, 0, time.UTC), - Float: 123.4, - Int: 5000, - Uint: 5001, - String: &biteMe, - unexported: 0, - }, - BasicLists: testDocBasicLists{ - Bools: []bool{true, false, true}, - Dates: []time.Time{ - time.Date(1979, 5, 27, 7, 32, 0, 0, time.UTC), - time.Date(1980, 5, 27, 7, 32, 0, 0, time.UTC), - }, - Floats: []*float32{&float1, &float2, &float3}, - Ints: []int{8001, 8001, 8002}, - Strings: []string{"One", "Two", "Three"}, - UInts: []uint{5002, 5003}, - }, - BasicMap: map[string]string{ - "one": "one", - "two": "two", - }, - Subdocs: testDocSubs{ - First: testSubDoc{"First", 0}, - Second: &subdoc, - }, - SubDocList: []testSubDoc{ - testSubDoc{"List.First", 0}, - testSubDoc{"List.Second", 0}, - }, - SubDocPtrs: []*testSubDoc{&subdoc}, -} - -func TestDocMarshal(t *testing.T) { - result, err := Marshal(docData) - if err != nil { - t.Fatal(err) - } - expected, _ := ioutil.ReadFile("marshal_test.toml") - if !bytes.Equal(result, expected) { - t.Errorf("Bad marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -func TestDocUnmarshal(t *testing.T) { - result := testDoc{} - tomlData, _ := ioutil.ReadFile("marshal_test.toml") - err := Unmarshal(tomlData, &result) - expected := docData - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(result, expected) { - resStr, _ := json.MarshalIndent(result, "", " ") - expStr, _ := json.MarshalIndent(expected, "", " ") - t.Errorf("Bad unmarshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expStr, resStr) - } -} - -func TestDocPartialUnmarshal(t *testing.T) { - result := testDocSubs{} - - tree, _ := LoadFile("marshal_test.toml") - subTree := tree.Get("subdoc").(*Tree) - err := subTree.Unmarshal(&result) - expected := docData.Subdocs - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(result, expected) { - resStr, _ := json.MarshalIndent(result, "", " ") - expStr, _ := json.MarshalIndent(expected, "", " ") - t.Errorf("Bad partial unmartial: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expStr, resStr) - } -} - -type tomlTypeCheckTest struct { - name string - item interface{} - typ int //0=primitive, 1=otherslice, 2=treeslice, 3=tree -} - -func TestTypeChecks(t *testing.T) { - tests := []tomlTypeCheckTest{ - {"integer", 2, 0}, - {"time", time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC), 0}, - {"stringlist", []string{"hello", "hi"}, 1}, - {"timelist", []time.Time{time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC)}, 1}, - {"objectlist", []tomlTypeCheckTest{}, 2}, - {"object", tomlTypeCheckTest{}, 3}, - } - - for _, test := range tests { - expected := []bool{false, false, false, false} - expected[test.typ] = true - result := []bool{ - isPrimitive(reflect.TypeOf(test.item)), - isOtherSlice(reflect.TypeOf(test.item)), - isTreeSlice(reflect.TypeOf(test.item)), - isTree(reflect.TypeOf(test.item)), - } - if !reflect.DeepEqual(expected, result) { - t.Errorf("Bad type check on %q: expected %v, got %v", test.name, expected, result) - } - } -} - -type unexportedMarshalTestStruct struct { - String string `toml:"string"` - StringList []string `toml:"strlist"` - Sub basicMarshalTestSubStruct `toml:"subdoc"` - SubList []basicMarshalTestSubStruct `toml:"sublist"` - unexported int `toml:"shouldntBeHere"` - Unexported2 int `toml:"-"` -} - -var unexportedTestData = unexportedMarshalTestStruct{ - String: "Hello", - StringList: []string{"Howdy", "Hey There"}, - Sub: basicMarshalTestSubStruct{"One"}, - SubList: []basicMarshalTestSubStruct{{"Two"}, {"Three"}}, - unexported: 0, - Unexported2: 0, -} - -var unexportedTestToml = []byte(`string = "Hello" -strlist = ["Howdy","Hey There"] -unexported = 1 -shouldntBeHere = 2 - -[subdoc] - String2 = "One" - -[[sublist]] - String2 = "Two" - -[[sublist]] - String2 = "Three" -`) - -func TestUnexportedUnmarshal(t *testing.T) { - result := unexportedMarshalTestStruct{} - err := Unmarshal(unexportedTestToml, &result) - expected := unexportedTestData - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(result, expected) { - t.Errorf("Bad unexported unmarshal: expected %v, got %v", expected, result) - } -} - -type errStruct struct { - Bool bool `toml:"bool"` - Date time.Time `toml:"date"` - Float float64 `toml:"float"` - Int int16 `toml:"int"` - String *string `toml:"string"` -} - -var errTomls = []string{ - "bool = truly\ndate = 1979-05-27T07:32:00Z\nfloat = 123.4\nint = 5000\nstring = \"Bite me\"", - "bool = true\ndate = 1979-05-27T07:3200Z\nfloat = 123.4\nint = 5000\nstring = \"Bite me\"", - "bool = true\ndate = 1979-05-27T07:32:00Z\nfloat = 123a4\nint = 5000\nstring = \"Bite me\"", - "bool = true\ndate = 1979-05-27T07:32:00Z\nfloat = 123.4\nint = j000\nstring = \"Bite me\"", - "bool = true\ndate = 1979-05-27T07:32:00Z\nfloat = 123.4\nint = 5000\nstring = Bite me", - "bool = true\ndate = 1979-05-27T07:32:00Z\nfloat = 123.4\nint = 5000\nstring = Bite me", - "bool = 1\ndate = 1979-05-27T07:32:00Z\nfloat = 123.4\nint = 5000\nstring = \"Bite me\"", - "bool = true\ndate = 1\nfloat = 123.4\nint = 5000\nstring = \"Bite me\"", - "bool = true\ndate = 1979-05-27T07:32:00Z\n\"sorry\"\nint = 5000\nstring = \"Bite me\"", - "bool = true\ndate = 1979-05-27T07:32:00Z\nfloat = 123.4\nint = \"sorry\"\nstring = \"Bite me\"", - "bool = true\ndate = 1979-05-27T07:32:00Z\nfloat = 123.4\nint = 5000\nstring = 1", -} - -type mapErr struct { - Vals map[string]float64 -} - -type intErr struct { - Int1 int - Int2 int8 - Int3 int16 - Int4 int32 - Int5 int64 - UInt1 uint - UInt2 uint8 - UInt3 uint16 - UInt4 uint32 - UInt5 uint64 - Flt1 float32 - Flt2 float64 -} - -var intErrTomls = []string{ - "Int1 = []\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0", - "Int1 = 1\nInt2 = []\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0", - "Int1 = 1\nInt2 = 2\nInt3 = []\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0", - "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = []\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0", - "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = []\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0", - "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = []\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0", - "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = []\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0", - "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = []\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0", - "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = []\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = 2.0", - "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = []\nFlt1 = 1.0\nFlt2 = 2.0", - "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = []\nFlt2 = 2.0", - "Int1 = 1\nInt2 = 2\nInt3 = 3\nInt4 = 4\nInt5 = 5\nUInt1 = 1\nUInt2 = 2\nUInt3 = 3\nUInt4 = 4\nUInt5 = 5\nFlt1 = 1.0\nFlt2 = []", -} - -func TestErrUnmarshal(t *testing.T) { - for ind, toml := range errTomls { - result := errStruct{} - err := Unmarshal([]byte(toml), &result) - if err == nil { - t.Errorf("Expected err from case %d\n", ind) - } - } - result2 := mapErr{} - err := Unmarshal([]byte("[Vals]\nfred=\"1.2\""), &result2) - if err == nil { - t.Errorf("Expected err from map") - } - for ind, toml := range intErrTomls { - result3 := intErr{} - err := Unmarshal([]byte(toml), &result3) - if err == nil { - t.Errorf("Expected int err from case %d\n", ind) - } - } -} - -type emptyMarshalTestStruct struct { - Title string `toml:"title"` - Bool bool `toml:"bool"` - Int int `toml:"int"` - String string `toml:"string"` - StringList []string `toml:"stringlist"` - Ptr *basicMarshalTestStruct `toml:"ptr"` - Map map[string]string `toml:"map"` -} - -var emptyTestData = emptyMarshalTestStruct{ - Title: "Placeholder", - Bool: false, - Int: 0, - String: "", - StringList: []string{}, - Ptr: nil, - Map: map[string]string{}, -} - -var emptyTestToml = []byte(`bool = false -int = 0 -string = "" -stringlist = [] -title = "Placeholder" - -[map] -`) - -type emptyMarshalTestStruct2 struct { - Title string `toml:"title"` - Bool bool `toml:"bool,omitempty"` - Int int `toml:"int, omitempty"` - String string `toml:"string,omitempty "` - StringList []string `toml:"stringlist,omitempty"` - Ptr *basicMarshalTestStruct `toml:"ptr,omitempty"` - Map map[string]string `toml:"map,omitempty"` -} - -var emptyTestData2 = emptyMarshalTestStruct2{ - Title: "Placeholder", - Bool: false, - Int: 0, - String: "", - StringList: []string{}, - Ptr: nil, - Map: map[string]string{}, -} - -var emptyTestToml2 = []byte(`title = "Placeholder" -`) - -func TestEmptyMarshal(t *testing.T) { - result, err := Marshal(emptyTestData) - if err != nil { - t.Fatal(err) - } - expected := emptyTestToml - if !bytes.Equal(result, expected) { - t.Errorf("Bad empty marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -func TestEmptyMarshalOmit(t *testing.T) { - result, err := Marshal(emptyTestData2) - if err != nil { - t.Fatal(err) - } - expected := emptyTestToml2 - if !bytes.Equal(result, expected) { - t.Errorf("Bad empty omit marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -func TestEmptyUnmarshal(t *testing.T) { - result := emptyMarshalTestStruct{} - err := Unmarshal(emptyTestToml, &result) - expected := emptyTestData - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(result, expected) { - t.Errorf("Bad empty unmarshal: expected %v, got %v", expected, result) - } -} - -func TestEmptyUnmarshalOmit(t *testing.T) { - result := emptyMarshalTestStruct2{} - err := Unmarshal(emptyTestToml, &result) - expected := emptyTestData2 - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(result, expected) { - t.Errorf("Bad empty omit unmarshal: expected %v, got %v", expected, result) - } -} - -type pointerMarshalTestStruct struct { - Str *string - List *[]string - ListPtr *[]*string - Map *map[string]string - MapPtr *map[string]*string - EmptyStr *string - EmptyList *[]string - EmptyMap *map[string]string - DblPtr *[]*[]*string -} - -var pointerStr = "Hello" -var pointerList = []string{"Hello back"} -var pointerListPtr = []*string{&pointerStr} -var pointerMap = map[string]string{"response": "Goodbye"} -var pointerMapPtr = map[string]*string{"alternate": &pointerStr} -var pointerTestData = pointerMarshalTestStruct{ - Str: &pointerStr, - List: &pointerList, - ListPtr: &pointerListPtr, - Map: &pointerMap, - MapPtr: &pointerMapPtr, - EmptyStr: nil, - EmptyList: nil, - EmptyMap: nil, -} - -var pointerTestToml = []byte(`List = ["Hello back"] -ListPtr = ["Hello"] -Str = "Hello" - -[Map] - response = "Goodbye" - -[MapPtr] - alternate = "Hello" -`) - -func TestPointerMarshal(t *testing.T) { - result, err := Marshal(pointerTestData) - if err != nil { - t.Fatal(err) - } - expected := pointerTestToml - if !bytes.Equal(result, expected) { - t.Errorf("Bad pointer marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -func TestPointerUnmarshal(t *testing.T) { - result := pointerMarshalTestStruct{} - err := Unmarshal(pointerTestToml, &result) - expected := pointerTestData - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(result, expected) { - t.Errorf("Bad pointer unmarshal: expected %v, got %v", expected, result) - } -} - -func TestUnmarshalTypeMismatch(t *testing.T) { - result := pointerMarshalTestStruct{} - err := Unmarshal([]byte("List = 123"), &result) - if !strings.HasPrefix(err.Error(), "(1, 1): Can't convert 123(int64) to []string(slice)") { - t.Errorf("Type mismatch must be reported: got %v", err.Error()) - } -} - -type nestedMarshalTestStruct struct { - String [][]string - //Struct [][]basicMarshalTestSubStruct - StringPtr *[]*[]*string - // StructPtr *[]*[]*basicMarshalTestSubStruct -} - -var str1 = "Three" -var str2 = "Four" -var strPtr = []*string{&str1, &str2} -var strPtr2 = []*[]*string{&strPtr} - -var nestedTestData = nestedMarshalTestStruct{ - String: [][]string{[]string{"Five", "Six"}, []string{"One", "Two"}}, - StringPtr: &strPtr2, -} - -var nestedTestToml = []byte(`String = [["Five","Six"],["One","Two"]] -StringPtr = [["Three","Four"]] -`) - -func TestNestedMarshal(t *testing.T) { - result, err := Marshal(nestedTestData) - if err != nil { - t.Fatal(err) - } - expected := nestedTestToml - if !bytes.Equal(result, expected) { - t.Errorf("Bad nested marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -func TestNestedUnmarshal(t *testing.T) { - result := nestedMarshalTestStruct{} - err := Unmarshal(nestedTestToml, &result) - expected := nestedTestData - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(result, expected) { - t.Errorf("Bad nested unmarshal: expected %v, got %v", expected, result) - } -} - -type customMarshalerParent struct { - Self customMarshaler `toml:"me"` - Friends []customMarshaler `toml:"friends"` -} - -type customMarshaler struct { - FirsName string - LastName string -} - -func (c customMarshaler) MarshalTOML() ([]byte, error) { - fullName := fmt.Sprintf("%s %s", c.FirsName, c.LastName) - return []byte(fullName), nil -} - -var customMarshalerData = customMarshaler{FirsName: "Sally", LastName: "Fields"} -var customMarshalerToml = []byte(`Sally Fields`) -var nestedCustomMarshalerData = customMarshalerParent{ - Self: customMarshaler{FirsName: "Maiku", LastName: "Suteda"}, - Friends: []customMarshaler{customMarshalerData}, -} -var nestedCustomMarshalerToml = []byte(`friends = ["Sally Fields"] -me = "Maiku Suteda" -`) - -func TestCustomMarshaler(t *testing.T) { - result, err := Marshal(customMarshalerData) - if err != nil { - t.Fatal(err) - } - expected := customMarshalerToml - if !bytes.Equal(result, expected) { - t.Errorf("Bad custom marshaler: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -func TestNestedCustomMarshaler(t *testing.T) { - result, err := Marshal(nestedCustomMarshalerData) - if err != nil { - t.Fatal(err) - } - expected := nestedCustomMarshalerToml - if !bytes.Equal(result, expected) { - t.Errorf("Bad nested custom marshaler: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -var commentTestToml = []byte(` -# it's a comment on type -[postgres] - # isCommented = "dvalue" - noComment = "cvalue" - - # A comment on AttrB with a - # break line - password = "bvalue" - - # A comment on AttrA - user = "avalue" - - [[postgres.My]] - - # a comment on my on typeC - My = "Foo" - - [[postgres.My]] - - # a comment on my on typeC - My = "Baar" -`) - -func TestMarshalComment(t *testing.T) { - type TypeC struct { - My string `comment:"a comment on my on typeC"` - } - type TypeB struct { - AttrA string `toml:"user" comment:"A comment on AttrA"` - AttrB string `toml:"password" comment:"A comment on AttrB with a\n break line"` - AttrC string `toml:"noComment"` - AttrD string `toml:"isCommented" commented:"true"` - My []TypeC - } - type TypeA struct { - TypeB TypeB `toml:"postgres" comment:"it's a comment on type"` - } - - ta := []TypeC{{My: "Foo"}, {My: "Baar"}} - config := TypeA{TypeB{AttrA: "avalue", AttrB: "bvalue", AttrC: "cvalue", AttrD: "dvalue", My: ta}} - result, err := Marshal(config) - if err != nil { - t.Fatal(err) - } - expected := commentTestToml - if !bytes.Equal(result, expected) { - t.Errorf("Bad marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -type mapsTestStruct struct { - Simple map[string]string - Paths map[string]string - Other map[string]float64 - X struct { - Y struct { - Z map[string]bool - } - } -} - -var mapsTestData = mapsTestStruct{ - Simple: map[string]string{ - "one plus one": "two", - "next": "three", - }, - Paths: map[string]string{ - "/this/is/a/path": "/this/is/also/a/path", - "/heloo.txt": "/tmp/lololo.txt", - }, - Other: map[string]float64{ - "testing": 3.9999, - }, - X: struct{ Y struct{ Z map[string]bool } }{ - Y: struct{ Z map[string]bool }{ - Z: map[string]bool{ - "is.Nested": true, - }, - }, - }, -} -var mapsTestToml = []byte(` -[Other] - "testing" = 3.9999 - -[Paths] - "/heloo.txt" = "/tmp/lololo.txt" - "/this/is/a/path" = "/this/is/also/a/path" - -[Simple] - "next" = "three" - "one plus one" = "two" - -[X] - - [X.Y] - - [X.Y.Z] - "is.Nested" = true -`) - -func TestEncodeQuotedMapKeys(t *testing.T) { - var buf bytes.Buffer - if err := NewEncoder(&buf).QuoteMapKeys(true).Encode(mapsTestData); err != nil { - t.Fatal(err) - } - result := buf.Bytes() - expected := mapsTestToml - if !bytes.Equal(result, expected) { - t.Errorf("Bad maps marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, result) - } -} - -func TestDecodeQuotedMapKeys(t *testing.T) { - result := mapsTestStruct{} - err := NewDecoder(bytes.NewBuffer(mapsTestToml)).Decode(&result) - expected := mapsTestData - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(result, expected) { - t.Errorf("Bad maps unmarshal: expected %v, got %v", expected, result) - } -} - -type structArrayNoTag struct { - A struct { - B []int64 - C []int64 - } -} - -func TestMarshalArray(t *testing.T) { - expected := []byte(` -[A] - B = [1,2,3] - C = [1] -`) - - m := structArrayNoTag{ - A: struct { - B []int64 - C []int64 - }{ - B: []int64{1, 2, 3}, - C: []int64{1}, - }, - } - - b, err := Marshal(m) - - if err != nil { - t.Fatal(err) - } - - if !bytes.Equal(b, expected) { - t.Errorf("Bad arrays marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, b) - } -} - -func TestMarshalArrayOnePerLine(t *testing.T) { - expected := []byte(` -[A] - B = [ - 1, - 2, - 3 - ] - C = [1] -`) - - m := structArrayNoTag{ - A: struct { - B []int64 - C []int64 - }{ - B: []int64{1, 2, 3}, - C: []int64{1}, - }, - } - - var buf bytes.Buffer - encoder := NewEncoder(&buf).ArraysWithOneElementPerLine(true) - err := encoder.Encode(m) - - if err != nil { - t.Fatal(err) - } - - b := buf.Bytes() - - if !bytes.Equal(b, expected) { - t.Errorf("Bad arrays marshal: expected\n-----\n%s\n-----\ngot\n-----\n%s\n-----\n", expected, b) - } -} diff --git a/vendor/github.com/pelletier/go-toml/marshal_test.toml b/vendor/github.com/pelletier/go-toml/marshal_test.toml deleted file mode 100644 index 1c5f98e7..00000000 --- a/vendor/github.com/pelletier/go-toml/marshal_test.toml +++ /dev/null @@ -1,38 +0,0 @@ -title = "TOML Marshal Testing" - -[basic] - bool = true - date = 1979-05-27T07:32:00Z - float = 123.4 - int = 5000 - string = "Bite me" - uint = 5001 - -[basic_lists] - bools = [true,false,true] - dates = [1979-05-27T07:32:00Z,1980-05-27T07:32:00Z] - floats = [12.3,45.6,78.9] - ints = [8001,8001,8002] - strings = ["One","Two","Three"] - uints = [5002,5003] - -[basic_map] - one = "one" - two = "two" - -[subdoc] - - [subdoc.first] - name = "First" - - [subdoc.second] - name = "Second" - -[[subdoclist]] - name = "List.First" - -[[subdoclist]] - name = "List.Second" - -[[subdocptrs]] - name = "Second" diff --git a/vendor/github.com/pelletier/go-toml/parser_test.go b/vendor/github.com/pelletier/go-toml/parser_test.go deleted file mode 100644 index bc7903c8..00000000 --- a/vendor/github.com/pelletier/go-toml/parser_test.go +++ /dev/null @@ -1,785 +0,0 @@ -package toml - -import ( - "fmt" - "reflect" - "testing" - "time" - - "github.com/davecgh/go-spew/spew" -) - -func assertSubTree(t *testing.T, path []string, tree *Tree, err error, ref map[string]interface{}) { - if err != nil { - t.Error("Non-nil error:", err.Error()) - return - } - for k, v := range ref { - nextPath := append(path, k) - t.Log("asserting path", nextPath) - // NOTE: directly access key instead of resolve by path - // NOTE: see TestSpecialKV - switch node := tree.GetPath([]string{k}).(type) { - case []*Tree: - t.Log("\tcomparing key", nextPath, "by array iteration") - for idx, item := range node { - assertSubTree(t, nextPath, item, err, v.([]map[string]interface{})[idx]) - } - case *Tree: - t.Log("\tcomparing key", nextPath, "by subtree assestion") - assertSubTree(t, nextPath, node, err, v.(map[string]interface{})) - default: - t.Log("\tcomparing key", nextPath, "by string representation because it's of type", reflect.TypeOf(node)) - if fmt.Sprintf("%v", node) != fmt.Sprintf("%v", v) { - t.Errorf("was expecting %v at %v but got %v", v, k, node) - } - } - } -} - -func assertTree(t *testing.T, tree *Tree, err error, ref map[string]interface{}) { - t.Log("Asserting tree:\n", spew.Sdump(tree)) - assertSubTree(t, []string{}, tree, err, ref) - t.Log("Finished tree assertion.") -} - -func TestCreateSubTree(t *testing.T) { - tree := newTree() - tree.createSubTree([]string{"a", "b", "c"}, Position{}) - tree.Set("a.b.c", "", false, 42) - if tree.Get("a.b.c") != 42 { - t.Fail() - } -} - -func TestSimpleKV(t *testing.T) { - tree, err := Load("a = 42") - assertTree(t, tree, err, map[string]interface{}{ - "a": int64(42), - }) - - tree, _ = Load("a = 42\nb = 21") - assertTree(t, tree, err, map[string]interface{}{ - "a": int64(42), - "b": int64(21), - }) -} - -func TestNumberInKey(t *testing.T) { - tree, err := Load("hello2 = 42") - assertTree(t, tree, err, map[string]interface{}{ - "hello2": int64(42), - }) -} - -func TestSimpleNumbers(t *testing.T) { - tree, err := Load("a = +42\nb = -21\nc = +4.2\nd = -2.1") - assertTree(t, tree, err, map[string]interface{}{ - "a": int64(42), - "b": int64(-21), - "c": float64(4.2), - "d": float64(-2.1), - }) -} - -func TestNumbersWithUnderscores(t *testing.T) { - tree, err := Load("a = 1_000") - assertTree(t, tree, err, map[string]interface{}{ - "a": int64(1000), - }) - - tree, err = Load("a = 5_349_221") - assertTree(t, tree, err, map[string]interface{}{ - "a": int64(5349221), - }) - - tree, err = Load("a = 1_2_3_4_5") - assertTree(t, tree, err, map[string]interface{}{ - "a": int64(12345), - }) - - tree, err = Load("flt8 = 9_224_617.445_991_228_313") - assertTree(t, tree, err, map[string]interface{}{ - "flt8": float64(9224617.445991228313), - }) - - tree, err = Load("flt9 = 1e1_00") - assertTree(t, tree, err, map[string]interface{}{ - "flt9": float64(1e100), - }) -} - -func TestFloatsWithExponents(t *testing.T) { - tree, err := Load("a = 5e+22\nb = 5E+22\nc = -5e+22\nd = -5e-22\ne = 6.626e-34") - assertTree(t, tree, err, map[string]interface{}{ - "a": float64(5e+22), - "b": float64(5E+22), - "c": float64(-5e+22), - "d": float64(-5e-22), - "e": float64(6.626e-34), - }) -} - -func TestSimpleDate(t *testing.T) { - tree, err := Load("a = 1979-05-27T07:32:00Z") - assertTree(t, tree, err, map[string]interface{}{ - "a": time.Date(1979, time.May, 27, 7, 32, 0, 0, time.UTC), - }) -} - -func TestDateOffset(t *testing.T) { - tree, err := Load("a = 1979-05-27T00:32:00-07:00") - assertTree(t, tree, err, map[string]interface{}{ - "a": time.Date(1979, time.May, 27, 0, 32, 0, 0, time.FixedZone("", -7*60*60)), - }) -} - -func TestDateNano(t *testing.T) { - tree, err := Load("a = 1979-05-27T00:32:00.999999999-07:00") - assertTree(t, tree, err, map[string]interface{}{ - "a": time.Date(1979, time.May, 27, 0, 32, 0, 999999999, time.FixedZone("", -7*60*60)), - }) -} - -func TestSimpleString(t *testing.T) { - tree, err := Load("a = \"hello world\"") - assertTree(t, tree, err, map[string]interface{}{ - "a": "hello world", - }) -} - -func TestSpaceKey(t *testing.T) { - tree, err := Load("\"a b\" = \"hello world\"") - assertTree(t, tree, err, map[string]interface{}{ - "a b": "hello world", - }) -} - -func TestStringEscapables(t *testing.T) { - tree, err := Load("a = \"a \\n b\"") - assertTree(t, tree, err, map[string]interface{}{ - "a": "a \n b", - }) - - tree, err = Load("a = \"a \\t b\"") - assertTree(t, tree, err, map[string]interface{}{ - "a": "a \t b", - }) - - tree, err = Load("a = \"a \\r b\"") - assertTree(t, tree, err, map[string]interface{}{ - "a": "a \r b", - }) - - tree, err = Load("a = \"a \\\\ b\"") - assertTree(t, tree, err, map[string]interface{}{ - "a": "a \\ b", - }) -} - -func TestEmptyQuotedString(t *testing.T) { - tree, err := Load(`[""] -"" = 1`) - assertTree(t, tree, err, map[string]interface{}{ - "": map[string]interface{}{ - "": int64(1), - }, - }) -} - -func TestBools(t *testing.T) { - tree, err := Load("a = true\nb = false") - assertTree(t, tree, err, map[string]interface{}{ - "a": true, - "b": false, - }) -} - -func TestNestedKeys(t *testing.T) { - tree, err := Load("[a.b.c]\nd = 42") - assertTree(t, tree, err, map[string]interface{}{ - "a": map[string]interface{}{ - "b": map[string]interface{}{ - "c": map[string]interface{}{ - "d": int64(42), - }, - }, - }, - }) -} - -func TestNestedQuotedUnicodeKeys(t *testing.T) { - tree, err := Load("[ j . \"ʞ\" . l ]\nd = 42") - assertTree(t, tree, err, map[string]interface{}{ - "j": map[string]interface{}{ - "ʞ": map[string]interface{}{ - "l": map[string]interface{}{ - "d": int64(42), - }, - }, - }, - }) - - tree, err = Load("[ g . h . i ]\nd = 42") - assertTree(t, tree, err, map[string]interface{}{ - "g": map[string]interface{}{ - "h": map[string]interface{}{ - "i": map[string]interface{}{ - "d": int64(42), - }, - }, - }, - }) - - tree, err = Load("[ d.e.f ]\nk = 42") - assertTree(t, tree, err, map[string]interface{}{ - "d": map[string]interface{}{ - "e": map[string]interface{}{ - "f": map[string]interface{}{ - "k": int64(42), - }, - }, - }, - }) -} - -func TestArrayOne(t *testing.T) { - tree, err := Load("a = [1]") - assertTree(t, tree, err, map[string]interface{}{ - "a": []int64{int64(1)}, - }) -} - -func TestArrayZero(t *testing.T) { - tree, err := Load("a = []") - assertTree(t, tree, err, map[string]interface{}{ - "a": []interface{}{}, - }) -} - -func TestArraySimple(t *testing.T) { - tree, err := Load("a = [42, 21, 10]") - assertTree(t, tree, err, map[string]interface{}{ - "a": []int64{int64(42), int64(21), int64(10)}, - }) - - tree, _ = Load("a = [42, 21, 10,]") - assertTree(t, tree, err, map[string]interface{}{ - "a": []int64{int64(42), int64(21), int64(10)}, - }) -} - -func TestArrayMultiline(t *testing.T) { - tree, err := Load("a = [42,\n21, 10,]") - assertTree(t, tree, err, map[string]interface{}{ - "a": []int64{int64(42), int64(21), int64(10)}, - }) -} - -func TestArrayNested(t *testing.T) { - tree, err := Load("a = [[42, 21], [10]]") - assertTree(t, tree, err, map[string]interface{}{ - "a": [][]int64{{int64(42), int64(21)}, {int64(10)}}, - }) -} - -func TestNestedArrayComment(t *testing.T) { - tree, err := Load(` -someArray = [ -# does not work -["entry1"] -]`) - assertTree(t, tree, err, map[string]interface{}{ - "someArray": [][]string{{"entry1"}}, - }) -} - -func TestNestedEmptyArrays(t *testing.T) { - tree, err := Load("a = [[[]]]") - assertTree(t, tree, err, map[string]interface{}{ - "a": [][][]interface{}{{{}}}, - }) -} - -func TestArrayMixedTypes(t *testing.T) { - _, err := Load("a = [42, 16.0]") - if err.Error() != "(1, 10): mixed types in array" { - t.Error("Bad error message:", err.Error()) - } - - _, err = Load("a = [42, \"hello\"]") - if err.Error() != "(1, 11): mixed types in array" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestArrayNestedStrings(t *testing.T) { - tree, err := Load("data = [ [\"gamma\", \"delta\"], [\"Foo\"] ]") - assertTree(t, tree, err, map[string]interface{}{ - "data": [][]string{{"gamma", "delta"}, {"Foo"}}, - }) -} - -func TestParseUnknownRvalue(t *testing.T) { - _, err := Load("a = !bssss") - if err == nil { - t.Error("Expecting a parse error") - } - - _, err = Load("a = /b") - if err == nil { - t.Error("Expecting a parse error") - } -} - -func TestMissingValue(t *testing.T) { - _, err := Load("a = ") - if err.Error() != "(1, 5): expecting a value" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestUnterminatedArray(t *testing.T) { - _, err := Load("a = [1,") - if err.Error() != "(1, 8): unterminated array" { - t.Error("Bad error message:", err.Error()) - } - - _, err = Load("a = [1") - if err.Error() != "(1, 7): unterminated array" { - t.Error("Bad error message:", err.Error()) - } - - _, err = Load("a = [1 2") - if err.Error() != "(1, 8): missing comma" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestNewlinesInArrays(t *testing.T) { - tree, err := Load("a = [1,\n2,\n3]") - assertTree(t, tree, err, map[string]interface{}{ - "a": []int64{int64(1), int64(2), int64(3)}, - }) -} - -func TestArrayWithExtraComma(t *testing.T) { - tree, err := Load("a = [1,\n2,\n3,\n]") - assertTree(t, tree, err, map[string]interface{}{ - "a": []int64{int64(1), int64(2), int64(3)}, - }) -} - -func TestArrayWithExtraCommaComment(t *testing.T) { - tree, err := Load("a = [1, # wow\n2, # such items\n3, # so array\n]") - assertTree(t, tree, err, map[string]interface{}{ - "a": []int64{int64(1), int64(2), int64(3)}, - }) -} - -func TestSimpleInlineGroup(t *testing.T) { - tree, err := Load("key = {a = 42}") - assertTree(t, tree, err, map[string]interface{}{ - "key": map[string]interface{}{ - "a": int64(42), - }, - }) -} - -func TestDoubleInlineGroup(t *testing.T) { - tree, err := Load("key = {a = 42, b = \"foo\"}") - assertTree(t, tree, err, map[string]interface{}{ - "key": map[string]interface{}{ - "a": int64(42), - "b": "foo", - }, - }) -} - -func TestExampleInlineGroup(t *testing.T) { - tree, err := Load(`name = { first = "Tom", last = "Preston-Werner" } -point = { x = 1, y = 2 }`) - assertTree(t, tree, err, map[string]interface{}{ - "name": map[string]interface{}{ - "first": "Tom", - "last": "Preston-Werner", - }, - "point": map[string]interface{}{ - "x": int64(1), - "y": int64(2), - }, - }) -} - -func TestExampleInlineGroupInArray(t *testing.T) { - tree, err := Load(`points = [{ x = 1, y = 2 }]`) - assertTree(t, tree, err, map[string]interface{}{ - "points": []map[string]interface{}{ - { - "x": int64(1), - "y": int64(2), - }, - }, - }) -} - -func TestInlineTableUnterminated(t *testing.T) { - _, err := Load("foo = {") - if err.Error() != "(1, 8): unterminated inline table" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestInlineTableCommaExpected(t *testing.T) { - _, err := Load("foo = {hello = 53 test = foo}") - if err.Error() != "(1, 19): comma expected between fields in inline table" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestInlineTableCommaStart(t *testing.T) { - _, err := Load("foo = {, hello = 53}") - if err.Error() != "(1, 8): inline table cannot start with a comma" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestInlineTableDoubleComma(t *testing.T) { - _, err := Load("foo = {hello = 53,, foo = 17}") - if err.Error() != "(1, 19): need field between two commas in inline table" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestDuplicateGroups(t *testing.T) { - _, err := Load("[foo]\na=2\n[foo]b=3") - if err.Error() != "(3, 2): duplicated tables" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestDuplicateKeys(t *testing.T) { - _, err := Load("foo = 2\nfoo = 3") - if err.Error() != "(2, 1): The following key was defined twice: foo" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestEmptyIntermediateTable(t *testing.T) { - _, err := Load("[foo..bar]") - if err.Error() != "(1, 2): invalid table array key: empty table key" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestImplicitDeclarationBefore(t *testing.T) { - tree, err := Load("[a.b.c]\nanswer = 42\n[a]\nbetter = 43") - assertTree(t, tree, err, map[string]interface{}{ - "a": map[string]interface{}{ - "b": map[string]interface{}{ - "c": map[string]interface{}{ - "answer": int64(42), - }, - }, - "better": int64(43), - }, - }) -} - -func TestFloatsWithoutLeadingZeros(t *testing.T) { - _, err := Load("a = .42") - if err.Error() != "(1, 5): cannot start float with a dot" { - t.Error("Bad error message:", err.Error()) - } - - _, err = Load("a = -.42") - if err.Error() != "(1, 5): cannot start float with a dot" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestMissingFile(t *testing.T) { - _, err := LoadFile("foo.toml") - if err.Error() != "open foo.toml: no such file or directory" && - err.Error() != "open foo.toml: The system cannot find the file specified." { - t.Error("Bad error message:", err.Error()) - } -} - -func TestParseFile(t *testing.T) { - tree, err := LoadFile("example.toml") - - assertTree(t, tree, err, map[string]interface{}{ - "title": "TOML Example", - "owner": map[string]interface{}{ - "name": "Tom Preston-Werner", - "organization": "GitHub", - "bio": "GitHub Cofounder & CEO\nLikes tater tots and beer.", - "dob": time.Date(1979, time.May, 27, 7, 32, 0, 0, time.UTC), - }, - "database": map[string]interface{}{ - "server": "192.168.1.1", - "ports": []int64{8001, 8001, 8002}, - "connection_max": 5000, - "enabled": true, - }, - "servers": map[string]interface{}{ - "alpha": map[string]interface{}{ - "ip": "10.0.0.1", - "dc": "eqdc10", - }, - "beta": map[string]interface{}{ - "ip": "10.0.0.2", - "dc": "eqdc10", - }, - }, - "clients": map[string]interface{}{ - "data": []interface{}{ - []string{"gamma", "delta"}, - []int64{1, 2}, - }, - }, - }) -} - -func TestParseFileCRLF(t *testing.T) { - tree, err := LoadFile("example-crlf.toml") - - assertTree(t, tree, err, map[string]interface{}{ - "title": "TOML Example", - "owner": map[string]interface{}{ - "name": "Tom Preston-Werner", - "organization": "GitHub", - "bio": "GitHub Cofounder & CEO\nLikes tater tots and beer.", - "dob": time.Date(1979, time.May, 27, 7, 32, 0, 0, time.UTC), - }, - "database": map[string]interface{}{ - "server": "192.168.1.1", - "ports": []int64{8001, 8001, 8002}, - "connection_max": 5000, - "enabled": true, - }, - "servers": map[string]interface{}{ - "alpha": map[string]interface{}{ - "ip": "10.0.0.1", - "dc": "eqdc10", - }, - "beta": map[string]interface{}{ - "ip": "10.0.0.2", - "dc": "eqdc10", - }, - }, - "clients": map[string]interface{}{ - "data": []interface{}{ - []string{"gamma", "delta"}, - []int64{1, 2}, - }, - }, - }) -} - -func TestParseKeyGroupArray(t *testing.T) { - tree, err := Load("[[foo.bar]] a = 42\n[[foo.bar]] a = 69") - assertTree(t, tree, err, map[string]interface{}{ - "foo": map[string]interface{}{ - "bar": []map[string]interface{}{ - {"a": int64(42)}, - {"a": int64(69)}, - }, - }, - }) -} - -func TestParseKeyGroupArrayUnfinished(t *testing.T) { - _, err := Load("[[foo.bar]\na = 42") - if err.Error() != "(1, 10): was expecting token [[, but got unclosed table array key instead" { - t.Error("Bad error message:", err.Error()) - } - - _, err = Load("[[foo.[bar]\na = 42") - if err.Error() != "(1, 3): unexpected token table array key cannot contain ']', was expecting a table array key" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestParseKeyGroupArrayQueryExample(t *testing.T) { - tree, err := Load(` - [[book]] - title = "The Stand" - author = "Stephen King" - [[book]] - title = "For Whom the Bell Tolls" - author = "Ernest Hemmingway" - [[book]] - title = "Neuromancer" - author = "William Gibson" - `) - - assertTree(t, tree, err, map[string]interface{}{ - "book": []map[string]interface{}{ - {"title": "The Stand", "author": "Stephen King"}, - {"title": "For Whom the Bell Tolls", "author": "Ernest Hemmingway"}, - {"title": "Neuromancer", "author": "William Gibson"}, - }, - }) -} - -func TestParseKeyGroupArraySpec(t *testing.T) { - tree, err := Load("[[fruit]]\n name=\"apple\"\n [fruit.physical]\n color=\"red\"\n shape=\"round\"\n [[fruit]]\n name=\"banana\"") - assertTree(t, tree, err, map[string]interface{}{ - "fruit": []map[string]interface{}{ - {"name": "apple", "physical": map[string]interface{}{"color": "red", "shape": "round"}}, - {"name": "banana"}, - }, - }) -} - -func TestTomlValueStringRepresentation(t *testing.T) { - for idx, item := range []struct { - Value interface{} - Expect string - }{ - {int64(12345), "12345"}, - {uint64(50), "50"}, - {float64(123.45), "123.45"}, - {bool(true), "true"}, - {"hello world", "\"hello world\""}, - {"\b\t\n\f\r\"\\", "\"\\b\\t\\n\\f\\r\\\"\\\\\""}, - {"\x05", "\"\\u0005\""}, - {time.Date(1979, time.May, 27, 7, 32, 0, 0, time.UTC), - "1979-05-27T07:32:00Z"}, - {[]interface{}{"gamma", "delta"}, - "[\"gamma\",\"delta\"]"}, - {nil, ""}, - } { - result, err := tomlValueStringRepresentation(item.Value, "", false) - if err != nil { - t.Errorf("Test %d - unexpected error: %s", idx, err) - } - if result != item.Expect { - t.Errorf("Test %d - got '%s', expected '%s'", idx, result, item.Expect) - } - } -} - -func TestToStringMapStringString(t *testing.T) { - tree, err := TreeFromMap(map[string]interface{}{"m": map[string]interface{}{"v": "abc"}}) - if err != nil { - t.Fatalf("unexpected error: %s", err) - } - want := "\n[m]\n v = \"abc\"\n" - got := tree.String() - - if got != want { - t.Errorf("want:\n%q\ngot:\n%q", want, got) - } -} - -func assertPosition(t *testing.T, text string, ref map[string]Position) { - tree, err := Load(text) - if err != nil { - t.Errorf("Error loading document text: `%v`", text) - t.Errorf("Error: %v", err) - } - for path, pos := range ref { - testPos := tree.GetPosition(path) - if testPos.Invalid() { - t.Errorf("Failed to query tree path or path has invalid position: %s", path) - } else if pos != testPos { - t.Errorf("Expected position %v, got %v instead", pos, testPos) - } - } -} - -func TestDocumentPositions(t *testing.T) { - assertPosition(t, - "[foo]\nbar=42\nbaz=69", - map[string]Position{ - "": {1, 1}, - "foo": {1, 1}, - "foo.bar": {2, 1}, - "foo.baz": {3, 1}, - }) -} - -func TestDocumentPositionsWithSpaces(t *testing.T) { - assertPosition(t, - " [foo]\n bar=42\n baz=69", - map[string]Position{ - "": {1, 1}, - "foo": {1, 3}, - "foo.bar": {2, 3}, - "foo.baz": {3, 3}, - }) -} - -func TestDocumentPositionsWithGroupArray(t *testing.T) { - assertPosition(t, - "[[foo]]\nbar=42\nbaz=69", - map[string]Position{ - "": {1, 1}, - "foo": {1, 1}, - "foo.bar": {2, 1}, - "foo.baz": {3, 1}, - }) -} - -func TestNestedTreePosition(t *testing.T) { - assertPosition(t, - "[foo.bar]\na=42\nb=69", - map[string]Position{ - "": {1, 1}, - "foo": {1, 1}, - "foo.bar": {1, 1}, - "foo.bar.a": {2, 1}, - "foo.bar.b": {3, 1}, - }) -} - -func TestInvalidGroupArray(t *testing.T) { - _, err := Load("[table#key]\nanswer = 42") - if err == nil { - t.Error("Should error") - } - - _, err = Load("[foo.[bar]\na = 42") - if err.Error() != "(1, 2): unexpected token table key cannot contain ']', was expecting a table key" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestDoubleEqual(t *testing.T) { - _, err := Load("foo= = 2") - if err.Error() != "(1, 6): cannot have multiple equals for the same key" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestGroupArrayReassign(t *testing.T) { - _, err := Load("[hello]\n[[hello]]") - if err.Error() != "(2, 3): key \"hello\" is already assigned and not of type table array" { - t.Error("Bad error message:", err.Error()) - } -} - -func TestInvalidFloatParsing(t *testing.T) { - _, err := Load("a=1e_2") - if err.Error() != "(1, 3): invalid use of _ in number" { - t.Error("Bad error message:", err.Error()) - } - - _, err = Load("a=1e2_") - if err.Error() != "(1, 3): invalid use of _ in number" { - t.Error("Bad error message:", err.Error()) - } - - _, err = Load("a=1__2") - if err.Error() != "(1, 3): invalid use of _ in number" { - t.Error("Bad error message:", err.Error()) - } - - _, err = Load("a=_1_2") - if err.Error() != "(1, 3): cannot start number with underscore" { - t.Error("Bad error message:", err.Error()) - } -} diff --git a/vendor/github.com/pelletier/go-toml/position_test.go b/vendor/github.com/pelletier/go-toml/position_test.go deleted file mode 100644 index 63ad1afc..00000000 --- a/vendor/github.com/pelletier/go-toml/position_test.go +++ /dev/null @@ -1,29 +0,0 @@ -// Testing support for go-toml - -package toml - -import ( - "testing" -) - -func TestPositionString(t *testing.T) { - p := Position{123, 456} - expected := "(123, 456)" - value := p.String() - - if value != expected { - t.Errorf("Expected %v, got %v instead", expected, value) - } -} - -func TestInvalid(t *testing.T) { - for i, v := range []Position{ - {0, 1234}, - {1234, 0}, - {0, 0}, - } { - if !v.Invalid() { - t.Errorf("Position at %v is valid: %v", i, v) - } - } -} diff --git a/vendor/github.com/pelletier/go-toml/test.sh b/vendor/github.com/pelletier/go-toml/test.sh deleted file mode 100755 index 91a88967..00000000 --- a/vendor/github.com/pelletier/go-toml/test.sh +++ /dev/null @@ -1,90 +0,0 @@ -#!/bin/bash -# fail out of the script if anything here fails -set -e - -# set the path to the present working directory -export GOPATH=`pwd` - -function git_clone() { - path=$1 - branch=$2 - version=$3 - if [ ! -d "src/$path" ]; then - mkdir -p src/$path - git clone https://$path.git src/$path - fi - pushd src/$path - git checkout "$branch" - git reset --hard "$version" - popd -} - -# Remove potential previous runs -rm -rf src test_program_bin toml-test - -# Run go vet -go vet ./... - -go get github.com/pelletier/go-buffruneio -go get github.com/davecgh/go-spew/spew -go get gopkg.in/yaml.v2 -go get github.com/BurntSushi/toml - -# get code for BurntSushi TOML validation -# pinning all to 'HEAD' for version 0.3.x work (TODO: pin to commit hash when tests stabilize) -git_clone github.com/BurntSushi/toml master HEAD -git_clone github.com/BurntSushi/toml-test master HEAD #was: 0.2.0 HEAD - -# build the BurntSushi test application -go build -o toml-test github.com/BurntSushi/toml-test - -# vendorize the current lib for testing -# NOTE: this basically mocks an install without having to go back out to github for code -mkdir -p src/github.com/pelletier/go-toml/cmd -mkdir -p src/github.com/pelletier/go-toml/query -cp *.go *.toml src/github.com/pelletier/go-toml -cp -R cmd/* src/github.com/pelletier/go-toml/cmd -cp -R query/* src/github.com/pelletier/go-toml/query -go build -o test_program_bin src/github.com/pelletier/go-toml/cmd/test_program.go - -# Run basic unit tests -go test github.com/pelletier/go-toml -covermode=count -coverprofile=coverage.out -go test github.com/pelletier/go-toml/cmd/tomljson -go test github.com/pelletier/go-toml/query - -# run the entire BurntSushi test suite -if [[ $# -eq 0 ]] ; then - echo "Running all BurntSushi tests" - ./toml-test ./test_program_bin | tee test_out -else - # run a specific test - test=$1 - test_path='src/github.com/BurntSushi/toml-test/tests' - valid_test="$test_path/valid/$test" - invalid_test="$test_path/invalid/$test" - - if [ -e "$valid_test.toml" ]; then - echo "Valid Test TOML for $test:" - echo "====" - cat "$valid_test.toml" - - echo "Valid Test JSON for $test:" - echo "====" - cat "$valid_test.json" - - echo "Go-TOML Output for $test:" - echo "====" - cat "$valid_test.toml" | ./test_program_bin - fi - - if [ -e "$invalid_test.toml" ]; then - echo "Invalid Test TOML for $test:" - echo "====" - cat "$invalid_test.toml" - - echo "Go-TOML Output for $test:" - echo "====" - echo "go-toml Output:" - cat "$invalid_test.toml" | ./test_program_bin - fi -fi diff --git a/vendor/github.com/pelletier/go-toml/token_test.go b/vendor/github.com/pelletier/go-toml/token_test.go deleted file mode 100644 index 20b560d5..00000000 --- a/vendor/github.com/pelletier/go-toml/token_test.go +++ /dev/null @@ -1,67 +0,0 @@ -package toml - -import "testing" - -func TestTokenStringer(t *testing.T) { - var tests = []struct { - tt tokenType - expect string - }{ - {tokenError, "Error"}, - {tokenEOF, "EOF"}, - {tokenComment, "Comment"}, - {tokenKey, "Key"}, - {tokenString, "String"}, - {tokenInteger, "Integer"}, - {tokenTrue, "True"}, - {tokenFalse, "False"}, - {tokenFloat, "Float"}, - {tokenEqual, "="}, - {tokenLeftBracket, "["}, - {tokenRightBracket, "]"}, - {tokenLeftCurlyBrace, "{"}, - {tokenRightCurlyBrace, "}"}, - {tokenLeftParen, "("}, - {tokenRightParen, ")"}, - {tokenDoubleLeftBracket, "]]"}, - {tokenDoubleRightBracket, "[["}, - {tokenDate, "Date"}, - {tokenKeyGroup, "KeyGroup"}, - {tokenKeyGroupArray, "KeyGroupArray"}, - {tokenComma, ","}, - {tokenColon, ":"}, - {tokenDollar, "$"}, - {tokenStar, "*"}, - {tokenQuestion, "?"}, - {tokenDot, "."}, - {tokenDotDot, ".."}, - {tokenEOL, "EOL"}, - {tokenEOL + 1, "Unknown"}, - } - - for i, test := range tests { - got := test.tt.String() - if got != test.expect { - t.Errorf("[%d] invalid string of token type; got %q, expected %q", i, got, test.expect) - } - } -} - -func TestTokenString(t *testing.T) { - var tests = []struct { - tok token - expect string - }{ - {token{Position{1, 1}, tokenEOF, ""}, "EOF"}, - {token{Position{1, 1}, tokenError, "Δt"}, "Δt"}, - {token{Position{1, 1}, tokenString, "bar"}, `"bar"`}, - {token{Position{1, 1}, tokenString, "123456789012345"}, `"123456789012345"`}, - } - - for i, test := range tests { - got := test.tok.String() - if got != test.expect { - t.Errorf("[%d] invalid of string token; got %q, expected %q", i, got, test.expect) - } - } -} diff --git a/vendor/github.com/pelletier/go-toml/toml_test.go b/vendor/github.com/pelletier/go-toml/toml_test.go deleted file mode 100644 index ab9c2425..00000000 --- a/vendor/github.com/pelletier/go-toml/toml_test.go +++ /dev/null @@ -1,106 +0,0 @@ -// Testing support for go-toml - -package toml - -import ( - "testing" -) - -func TestTomlHas(t *testing.T) { - tree, _ := Load(` - [test] - key = "value" - `) - - if !tree.Has("test.key") { - t.Errorf("Has - expected test.key to exists") - } - - if tree.Has("") { - t.Errorf("Should return false if the key is not provided") - } -} - -func TestTomlGet(t *testing.T) { - tree, _ := Load(` - [test] - key = "value" - `) - - if tree.Get("") != tree { - t.Errorf("Get should return the tree itself when given an empty path") - } - - if tree.Get("test.key") != "value" { - t.Errorf("Get should return the value") - } - if tree.Get(`\`) != nil { - t.Errorf("should return nil when the key is malformed") - } -} - -func TestTomlGetDefault(t *testing.T) { - tree, _ := Load(` - [test] - key = "value" - `) - - if tree.GetDefault("", "hello") != tree { - t.Error("GetDefault should return the tree itself when given an empty path") - } - - if tree.GetDefault("test.key", "hello") != "value" { - t.Error("Get should return the value") - } - - if tree.GetDefault("whatever", "hello") != "hello" { - t.Error("GetDefault should return the default value if the key does not exist") - } -} - -func TestTomlHasPath(t *testing.T) { - tree, _ := Load(` - [test] - key = "value" - `) - - if !tree.HasPath([]string{"test", "key"}) { - t.Errorf("HasPath - expected test.key to exists") - } -} - -func TestTomlGetPath(t *testing.T) { - node := newTree() - //TODO: set other node data - - for idx, item := range []struct { - Path []string - Expected *Tree - }{ - { // empty path test - []string{}, - node, - }, - } { - result := node.GetPath(item.Path) - if result != item.Expected { - t.Errorf("GetPath[%d] %v - expected %v, got %v instead.", idx, item.Path, item.Expected, result) - } - } - - tree, _ := Load("[foo.bar]\na=1\nb=2\n[baz.foo]\na=3\nb=4\n[gorf.foo]\na=5\nb=6") - if tree.GetPath([]string{"whatever"}) != nil { - t.Error("GetPath should return nil when the key does not exist") - } -} - -func TestTomlFromMap(t *testing.T) { - simpleMap := map[string]interface{}{"hello": 42} - tree, err := TreeFromMap(simpleMap) - if err != nil { - t.Fatal("unexpected error:", err) - } - if tree.Get("hello") != int64(42) { - t.Fatal("hello should be 42, not", tree.Get("hello")) - } -} diff --git a/vendor/github.com/pelletier/go-toml/tomltree_create_test.go b/vendor/github.com/pelletier/go-toml/tomltree_create_test.go deleted file mode 100644 index 1ca108a5..00000000 --- a/vendor/github.com/pelletier/go-toml/tomltree_create_test.go +++ /dev/null @@ -1,126 +0,0 @@ -package toml - -import ( - "strconv" - "testing" - "time" -) - -type customString string - -type stringer struct{} - -func (s stringer) String() string { - return "stringer" -} - -func validate(t *testing.T, path string, object interface{}) { - switch o := object.(type) { - case *Tree: - for key, tree := range o.values { - validate(t, path+"."+key, tree) - } - case []*Tree: - for index, tree := range o { - validate(t, path+"."+strconv.Itoa(index), tree) - } - case *tomlValue: - switch o.value.(type) { - case int64, uint64, bool, string, float64, time.Time, - []int64, []uint64, []bool, []string, []float64, []time.Time: - default: - t.Fatalf("tomlValue at key %s containing incorrect type %T", path, o.value) - } - default: - t.Fatalf("value at key %s is of incorrect type %T", path, object) - } - t.Logf("validation ok %s as %T", path, object) -} - -func validateTree(t *testing.T, tree *Tree) { - validate(t, "", tree) -} - -func TestTreeCreateToTree(t *testing.T) { - data := map[string]interface{}{ - "a_string": "bar", - "an_int": 42, - "time": time.Now(), - "int8": int8(2), - "int16": int16(2), - "int32": int32(2), - "uint8": uint8(2), - "uint16": uint16(2), - "uint32": uint32(2), - "float32": float32(2), - "a_bool": false, - "stringer": stringer{}, - "nested": map[string]interface{}{ - "foo": "bar", - }, - "array": []string{"a", "b", "c"}, - "array_uint": []uint{uint(1), uint(2)}, - "array_table": []map[string]interface{}{map[string]interface{}{"sub_map": 52}}, - "array_times": []time.Time{time.Now(), time.Now()}, - "map_times": map[string]time.Time{"now": time.Now()}, - "custom_string_map_key": map[customString]interface{}{customString("custom"): "custom"}, - } - tree, err := TreeFromMap(data) - if err != nil { - t.Fatal("unexpected error:", err) - } - validateTree(t, tree) -} - -func TestTreeCreateToTreeInvalidLeafType(t *testing.T) { - _, err := TreeFromMap(map[string]interface{}{"foo": t}) - expected := "cannot convert type *testing.T to Tree" - if err.Error() != expected { - t.Fatalf("expected error %s, got %s", expected, err.Error()) - } -} - -func TestTreeCreateToTreeInvalidMapKeyType(t *testing.T) { - _, err := TreeFromMap(map[string]interface{}{"foo": map[int]interface{}{2: 1}}) - expected := "map key needs to be a string, not int (int)" - if err.Error() != expected { - t.Fatalf("expected error %s, got %s", expected, err.Error()) - } -} - -func TestTreeCreateToTreeInvalidArrayMemberType(t *testing.T) { - _, err := TreeFromMap(map[string]interface{}{"foo": []*testing.T{t}}) - expected := "cannot convert type *testing.T to Tree" - if err.Error() != expected { - t.Fatalf("expected error %s, got %s", expected, err.Error()) - } -} - -func TestTreeCreateToTreeInvalidTableGroupType(t *testing.T) { - _, err := TreeFromMap(map[string]interface{}{"foo": []map[string]interface{}{map[string]interface{}{"hello": t}}}) - expected := "cannot convert type *testing.T to Tree" - if err.Error() != expected { - t.Fatalf("expected error %s, got %s", expected, err.Error()) - } -} - -func TestRoundTripArrayOfTables(t *testing.T) { - orig := "\n[[stuff]]\n name = \"foo\"\n things = [\"a\",\"b\"]\n" - tree, err := Load(orig) - if err != nil { - t.Fatalf("unexpected error: %s", err) - } - - m := tree.ToMap() - - tree, err = TreeFromMap(m) - if err != nil { - t.Fatalf("unexpected error: %s", err) - } - want := orig - got := tree.String() - - if got != want { - t.Errorf("want:\n%s\ngot:\n%s", want, got) - } -} diff --git a/vendor/github.com/pelletier/go-toml/tomltree_write_test.go b/vendor/github.com/pelletier/go-toml/tomltree_write_test.go deleted file mode 100644 index 5ea59bc1..00000000 --- a/vendor/github.com/pelletier/go-toml/tomltree_write_test.go +++ /dev/null @@ -1,358 +0,0 @@ -package toml - -import ( - "bytes" - "errors" - "fmt" - "reflect" - "strings" - "testing" - "time" -) - -type failingWriter struct { - failAt int - written int - buffer bytes.Buffer -} - -func (f *failingWriter) Write(p []byte) (n int, err error) { - count := len(p) - toWrite := f.failAt - (count + f.written) - if toWrite < 0 { - toWrite = 0 - } - if toWrite > count { - f.written += count - f.buffer.Write(p) - return count, nil - } - - f.buffer.Write(p[:toWrite]) - f.written = f.failAt - return toWrite, fmt.Errorf("failingWriter failed after writing %d bytes", f.written) -} - -func assertErrorString(t *testing.T, expected string, err error) { - expectedErr := errors.New(expected) - if err == nil || err.Error() != expectedErr.Error() { - t.Errorf("expecting error %s, but got %s instead", expected, err) - } -} - -func TestTreeWriteToEmptyTable(t *testing.T) { - doc := `[[empty-tables]] -[[empty-tables]]` - - toml, err := Load(doc) - if err != nil { - t.Fatal("Unexpected Load error:", err) - } - tomlString, err := toml.ToTomlString() - if err != nil { - t.Fatal("Unexpected ToTomlString error:", err) - } - - expected := ` -[[empty-tables]] - -[[empty-tables]] -` - - if tomlString != expected { - t.Fatalf("Expected:\n%s\nGot:\n%s", expected, tomlString) - } -} - -func TestTreeWriteToTomlString(t *testing.T) { - toml, err := Load(`name = { first = "Tom", last = "Preston-Werner" } -points = { x = 1, y = 2 }`) - - if err != nil { - t.Fatal("Unexpected error:", err) - } - - tomlString, _ := toml.ToTomlString() - reparsedTree, err := Load(tomlString) - - assertTree(t, reparsedTree, err, map[string]interface{}{ - "name": map[string]interface{}{ - "first": "Tom", - "last": "Preston-Werner", - }, - "points": map[string]interface{}{ - "x": int64(1), - "y": int64(2), - }, - }) -} - -func TestTreeWriteToTomlStringSimple(t *testing.T) { - tree, err := Load("[foo]\n\n[[foo.bar]]\na = 42\n\n[[foo.bar]]\na = 69\n") - if err != nil { - t.Errorf("Test failed to parse: %v", err) - return - } - result, err := tree.ToTomlString() - if err != nil { - t.Errorf("Unexpected error: %s", err) - } - expected := "\n[foo]\n\n [[foo.bar]]\n a = 42\n\n [[foo.bar]]\n a = 69\n" - if result != expected { - t.Errorf("Expected got '%s', expected '%s'", result, expected) - } -} - -func TestTreeWriteToTomlStringKeysOrders(t *testing.T) { - for i := 0; i < 100; i++ { - tree, _ := Load(` - foobar = true - bar = "baz" - foo = 1 - [qux] - foo = 1 - bar = "baz2"`) - - stringRepr, _ := tree.ToTomlString() - - t.Log("Intermediate string representation:") - t.Log(stringRepr) - - r := strings.NewReader(stringRepr) - toml, err := LoadReader(r) - - if err != nil { - t.Fatal("Unexpected error:", err) - } - - assertTree(t, toml, err, map[string]interface{}{ - "foobar": true, - "bar": "baz", - "foo": 1, - "qux": map[string]interface{}{ - "foo": 1, - "bar": "baz2", - }, - }) - } -} - -func testMaps(t *testing.T, actual, expected map[string]interface{}) { - if !reflect.DeepEqual(actual, expected) { - t.Fatal("trees aren't equal.\n", "Expected:\n", expected, "\nActual:\n", actual) - } -} - -func TestTreeWriteToMapSimple(t *testing.T) { - tree, _ := Load("a = 42\nb = 17") - - expected := map[string]interface{}{ - "a": int64(42), - "b": int64(17), - } - - testMaps(t, tree.ToMap(), expected) -} - -func TestTreeWriteToInvalidTreeSimpleValue(t *testing.T) { - tree := Tree{values: map[string]interface{}{"foo": int8(1)}} - _, err := tree.ToTomlString() - assertErrorString(t, "invalid value type at foo: int8", err) -} - -func TestTreeWriteToInvalidTreeTomlValue(t *testing.T) { - tree := Tree{values: map[string]interface{}{"foo": &tomlValue{value: int8(1), comment: "", position: Position{}}}} - _, err := tree.ToTomlString() - assertErrorString(t, "unsupported value type int8: 1", err) -} - -func TestTreeWriteToInvalidTreeTomlValueArray(t *testing.T) { - tree := Tree{values: map[string]interface{}{"foo": &tomlValue{value: int8(1), comment: "", position: Position{}}}} - _, err := tree.ToTomlString() - assertErrorString(t, "unsupported value type int8: 1", err) -} - -func TestTreeWriteToFailingWriterInSimpleValue(t *testing.T) { - toml, _ := Load(`a = 2`) - writer := failingWriter{failAt: 0, written: 0} - _, err := toml.WriteTo(&writer) - assertErrorString(t, "failingWriter failed after writing 0 bytes", err) -} - -func TestTreeWriteToFailingWriterInTable(t *testing.T) { - toml, _ := Load(` -[b] -a = 2`) - writer := failingWriter{failAt: 2, written: 0} - _, err := toml.WriteTo(&writer) - assertErrorString(t, "failingWriter failed after writing 2 bytes", err) - - writer = failingWriter{failAt: 13, written: 0} - _, err = toml.WriteTo(&writer) - assertErrorString(t, "failingWriter failed after writing 13 bytes", err) -} - -func TestTreeWriteToFailingWriterInArray(t *testing.T) { - toml, _ := Load(` -[[b]] -a = 2`) - writer := failingWriter{failAt: 2, written: 0} - _, err := toml.WriteTo(&writer) - assertErrorString(t, "failingWriter failed after writing 2 bytes", err) - - writer = failingWriter{failAt: 15, written: 0} - _, err = toml.WriteTo(&writer) - assertErrorString(t, "failingWriter failed after writing 15 bytes", err) -} - -func TestTreeWriteToMapExampleFile(t *testing.T) { - tree, _ := LoadFile("example.toml") - expected := map[string]interface{}{ - "title": "TOML Example", - "owner": map[string]interface{}{ - "name": "Tom Preston-Werner", - "organization": "GitHub", - "bio": "GitHub Cofounder & CEO\nLikes tater tots and beer.", - "dob": time.Date(1979, time.May, 27, 7, 32, 0, 0, time.UTC), - }, - "database": map[string]interface{}{ - "server": "192.168.1.1", - "ports": []interface{}{int64(8001), int64(8001), int64(8002)}, - "connection_max": int64(5000), - "enabled": true, - }, - "servers": map[string]interface{}{ - "alpha": map[string]interface{}{ - "ip": "10.0.0.1", - "dc": "eqdc10", - }, - "beta": map[string]interface{}{ - "ip": "10.0.0.2", - "dc": "eqdc10", - }, - }, - "clients": map[string]interface{}{ - "data": []interface{}{ - []interface{}{"gamma", "delta"}, - []interface{}{int64(1), int64(2)}, - }, - }, - } - testMaps(t, tree.ToMap(), expected) -} - -func TestTreeWriteToMapWithTablesInMultipleChunks(t *testing.T) { - tree, _ := Load(` - [[menu.main]] - a = "menu 1" - b = "menu 2" - [[menu.main]] - c = "menu 3" - d = "menu 4"`) - expected := map[string]interface{}{ - "menu": map[string]interface{}{ - "main": []interface{}{ - map[string]interface{}{"a": "menu 1", "b": "menu 2"}, - map[string]interface{}{"c": "menu 3", "d": "menu 4"}, - }, - }, - } - treeMap := tree.ToMap() - - testMaps(t, treeMap, expected) -} - -func TestTreeWriteToMapWithArrayOfInlineTables(t *testing.T) { - tree, _ := Load(` - [params] - language_tabs = [ - { key = "shell", name = "Shell" }, - { key = "ruby", name = "Ruby" }, - { key = "python", name = "Python" } - ]`) - - expected := map[string]interface{}{ - "params": map[string]interface{}{ - "language_tabs": []interface{}{ - map[string]interface{}{ - "key": "shell", - "name": "Shell", - }, - map[string]interface{}{ - "key": "ruby", - "name": "Ruby", - }, - map[string]interface{}{ - "key": "python", - "name": "Python", - }, - }, - }, - } - - treeMap := tree.ToMap() - testMaps(t, treeMap, expected) -} - -func TestTreeWriteToFloat(t *testing.T) { - tree, err := Load(`a = 3.0`) - if err != nil { - t.Fatal(err) - } - str, err := tree.ToTomlString() - if err != nil { - t.Fatal(err) - } - expected := `a = 3.0` - if strings.TrimSpace(str) != strings.TrimSpace(expected) { - t.Fatalf("Expected:\n%s\nGot:\n%s", expected, str) - } -} - -func BenchmarkTreeToTomlString(b *testing.B) { - toml, err := Load(sampleHard) - if err != nil { - b.Fatal("Unexpected error:", err) - } - - for i := 0; i < b.N; i++ { - _, err := toml.ToTomlString() - if err != nil { - b.Fatal(err) - } - } -} - -var sampleHard = `# Test file for TOML -# Only this one tries to emulate a TOML file written by a user of the kind of parser writers probably hate -# This part you'll really hate - -[the] -test_string = "You'll hate me after this - #" # " Annoying, isn't it? - - [the.hard] - test_array = [ "] ", " # "] # ] There you go, parse this! - test_array2 = [ "Test #11 ]proved that", "Experiment #9 was a success" ] - # You didn't think it'd as easy as chucking out the last #, did you? - another_test_string = " Same thing, but with a string #" - harder_test_string = " And when \"'s are in the string, along with # \"" # "and comments are there too" - # Things will get harder - - [the.hard."bit#"] - "what?" = "You don't think some user won't do that?" - multi_line_array = [ - "]", - # ] Oh yes I did - ] - -# Each of the following keygroups/key value pairs should produce an error. Uncomment to them to test - -#[error] if you didn't catch this, your parser is broken -#string = "Anything other than tabs, spaces and newline after a keygroup or key value pair has ended should produce an error unless it is a comment" like this -#array = [ -# "This might most likely happen in multiline arrays", -# Like here, -# "or here, -# and here" -# ] End of array comment, forgot the # -#number = 3.14 pi <--again forgot the # ` diff --git a/vendor/github.com/pkg/errors/.gitignore b/vendor/github.com/pkg/errors/.gitignore deleted file mode 100644 index daf913b1..00000000 --- a/vendor/github.com/pkg/errors/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof diff --git a/vendor/github.com/pkg/errors/.travis.yml b/vendor/github.com/pkg/errors/.travis.yml deleted file mode 100644 index 588ceca1..00000000 --- a/vendor/github.com/pkg/errors/.travis.yml +++ /dev/null @@ -1,11 +0,0 @@ -language: go -go_import_path: github.com/pkg/errors -go: - - 1.4.3 - - 1.5.4 - - 1.6.2 - - 1.7.1 - - tip - -script: - - go test -v ./... diff --git a/vendor/github.com/pkg/errors/README.md b/vendor/github.com/pkg/errors/README.md deleted file mode 100644 index 273db3c9..00000000 --- a/vendor/github.com/pkg/errors/README.md +++ /dev/null @@ -1,52 +0,0 @@ -# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) - -Package errors provides simple error handling primitives. - -`go get github.com/pkg/errors` - -The traditional error handling idiom in Go is roughly akin to -```go -if err != nil { - return err -} -``` -which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error. - -## Adding context to an error - -The errors.Wrap function returns a new error that adds context to the original error. For example -```go -_, err := ioutil.ReadAll(r) -if err != nil { - return errors.Wrap(err, "read failed") -} -``` -## Retrieving the cause of an error - -Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`. -```go -type causer interface { - Cause() error -} -``` -`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example: -```go -switch err := errors.Cause(err).(type) { -case *MyError: - // handle specifically -default: - // unknown error -} -``` - -[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors). - -## Contributing - -We welcome pull requests, bug fixes and issue reports. With that said, the bar for adding new symbols to this package is intentionally set high. - -Before proposing a change, please discuss your change by raising an issue. - -## Licence - -BSD-2-Clause diff --git a/vendor/github.com/pkg/errors/appveyor.yml b/vendor/github.com/pkg/errors/appveyor.yml deleted file mode 100644 index a932eade..00000000 --- a/vendor/github.com/pkg/errors/appveyor.yml +++ /dev/null @@ -1,32 +0,0 @@ -version: build-{build}.{branch} - -clone_folder: C:\gopath\src\github.com\pkg\errors -shallow_clone: true # for startup speed - -environment: - GOPATH: C:\gopath - -platform: - - x64 - -# http://www.appveyor.com/docs/installed-software -install: - # some helpful output for debugging builds - - go version - - go env - # pre-installed MinGW at C:\MinGW is 32bit only - # but MSYS2 at C:\msys64 has mingw64 - - set PATH=C:\msys64\mingw64\bin;%PATH% - - gcc --version - - g++ --version - -build_script: - - go install -v ./... - -test_script: - - set PATH=C:\gopath\bin;%PATH% - - go test -v ./... - -#artifacts: -# - path: '%GOPATH%\bin\*.exe' -deploy: off diff --git a/vendor/github.com/pkg/errors/bench_test.go b/vendor/github.com/pkg/errors/bench_test.go deleted file mode 100644 index 0416a3cb..00000000 --- a/vendor/github.com/pkg/errors/bench_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// +build go1.7 - -package errors - -import ( - "fmt" - "testing" - - stderrors "errors" -) - -func noErrors(at, depth int) error { - if at >= depth { - return stderrors.New("no error") - } - return noErrors(at+1, depth) -} -func yesErrors(at, depth int) error { - if at >= depth { - return New("ye error") - } - return yesErrors(at+1, depth) -} - -func BenchmarkErrors(b *testing.B) { - var toperr error - type run struct { - stack int - std bool - } - runs := []run{ - {10, false}, - {10, true}, - {100, false}, - {100, true}, - {1000, false}, - {1000, true}, - } - for _, r := range runs { - part := "pkg/errors" - if r.std { - part = "errors" - } - name := fmt.Sprintf("%s-stack-%d", part, r.stack) - b.Run(name, func(b *testing.B) { - var err error - f := yesErrors - if r.std { - f = noErrors - } - b.ReportAllocs() - for i := 0; i < b.N; i++ { - err = f(0, r.stack) - } - b.StopTimer() - toperr = err - }) - } -} diff --git a/vendor/github.com/pkg/errors/errors_test.go b/vendor/github.com/pkg/errors/errors_test.go deleted file mode 100644 index 1d8c6355..00000000 --- a/vendor/github.com/pkg/errors/errors_test.go +++ /dev/null @@ -1,226 +0,0 @@ -package errors - -import ( - "errors" - "fmt" - "io" - "reflect" - "testing" -) - -func TestNew(t *testing.T) { - tests := []struct { - err string - want error - }{ - {"", fmt.Errorf("")}, - {"foo", fmt.Errorf("foo")}, - {"foo", New("foo")}, - {"string with format specifiers: %v", errors.New("string with format specifiers: %v")}, - } - - for _, tt := range tests { - got := New(tt.err) - if got.Error() != tt.want.Error() { - t.Errorf("New.Error(): got: %q, want %q", got, tt.want) - } - } -} - -func TestWrapNil(t *testing.T) { - got := Wrap(nil, "no error") - if got != nil { - t.Errorf("Wrap(nil, \"no error\"): got %#v, expected nil", got) - } -} - -func TestWrap(t *testing.T) { - tests := []struct { - err error - message string - want string - }{ - {io.EOF, "read error", "read error: EOF"}, - {Wrap(io.EOF, "read error"), "client error", "client error: read error: EOF"}, - } - - for _, tt := range tests { - got := Wrap(tt.err, tt.message).Error() - if got != tt.want { - t.Errorf("Wrap(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want) - } - } -} - -type nilError struct{} - -func (nilError) Error() string { return "nil error" } - -func TestCause(t *testing.T) { - x := New("error") - tests := []struct { - err error - want error - }{{ - // nil error is nil - err: nil, - want: nil, - }, { - // explicit nil error is nil - err: (error)(nil), - want: nil, - }, { - // typed nil is nil - err: (*nilError)(nil), - want: (*nilError)(nil), - }, { - // uncaused error is unaffected - err: io.EOF, - want: io.EOF, - }, { - // caused error returns cause - err: Wrap(io.EOF, "ignored"), - want: io.EOF, - }, { - err: x, // return from errors.New - want: x, - }, { - WithMessage(nil, "whoops"), - nil, - }, { - WithMessage(io.EOF, "whoops"), - io.EOF, - }, { - WithStack(nil), - nil, - }, { - WithStack(io.EOF), - io.EOF, - }} - - for i, tt := range tests { - got := Cause(tt.err) - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("test %d: got %#v, want %#v", i+1, got, tt.want) - } - } -} - -func TestWrapfNil(t *testing.T) { - got := Wrapf(nil, "no error") - if got != nil { - t.Errorf("Wrapf(nil, \"no error\"): got %#v, expected nil", got) - } -} - -func TestWrapf(t *testing.T) { - tests := []struct { - err error - message string - want string - }{ - {io.EOF, "read error", "read error: EOF"}, - {Wrapf(io.EOF, "read error without format specifiers"), "client error", "client error: read error without format specifiers: EOF"}, - {Wrapf(io.EOF, "read error with %d format specifier", 1), "client error", "client error: read error with 1 format specifier: EOF"}, - } - - for _, tt := range tests { - got := Wrapf(tt.err, tt.message).Error() - if got != tt.want { - t.Errorf("Wrapf(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want) - } - } -} - -func TestErrorf(t *testing.T) { - tests := []struct { - err error - want string - }{ - {Errorf("read error without format specifiers"), "read error without format specifiers"}, - {Errorf("read error with %d format specifier", 1), "read error with 1 format specifier"}, - } - - for _, tt := range tests { - got := tt.err.Error() - if got != tt.want { - t.Errorf("Errorf(%v): got: %q, want %q", tt.err, got, tt.want) - } - } -} - -func TestWithStackNil(t *testing.T) { - got := WithStack(nil) - if got != nil { - t.Errorf("WithStack(nil): got %#v, expected nil", got) - } -} - -func TestWithStack(t *testing.T) { - tests := []struct { - err error - want string - }{ - {io.EOF, "EOF"}, - {WithStack(io.EOF), "EOF"}, - } - - for _, tt := range tests { - got := WithStack(tt.err).Error() - if got != tt.want { - t.Errorf("WithStack(%v): got: %v, want %v", tt.err, got, tt.want) - } - } -} - -func TestWithMessageNil(t *testing.T) { - got := WithMessage(nil, "no error") - if got != nil { - t.Errorf("WithMessage(nil, \"no error\"): got %#v, expected nil", got) - } -} - -func TestWithMessage(t *testing.T) { - tests := []struct { - err error - message string - want string - }{ - {io.EOF, "read error", "read error: EOF"}, - {WithMessage(io.EOF, "read error"), "client error", "client error: read error: EOF"}, - } - - for _, tt := range tests { - got := WithMessage(tt.err, tt.message).Error() - if got != tt.want { - t.Errorf("WithMessage(%v, %q): got: %q, want %q", tt.err, tt.message, got, tt.want) - } - } - -} - -// errors.New, etc values are not expected to be compared by value -// but the change in errors#27 made them incomparable. Assert that -// various kinds of errors have a functional equality operator, even -// if the result of that equality is always false. -func TestErrorEquality(t *testing.T) { - vals := []error{ - nil, - io.EOF, - errors.New("EOF"), - New("EOF"), - Errorf("EOF"), - Wrap(io.EOF, "EOF"), - Wrapf(io.EOF, "EOF%d", 2), - WithMessage(nil, "whoops"), - WithMessage(io.EOF, "whoops"), - WithStack(io.EOF), - WithStack(nil), - } - - for i := range vals { - for j := range vals { - _ = vals[i] == vals[j] // mustn't panic - } - } -} diff --git a/vendor/github.com/pkg/errors/example_test.go b/vendor/github.com/pkg/errors/example_test.go deleted file mode 100644 index c1fc13e3..00000000 --- a/vendor/github.com/pkg/errors/example_test.go +++ /dev/null @@ -1,205 +0,0 @@ -package errors_test - -import ( - "fmt" - - "github.com/pkg/errors" -) - -func ExampleNew() { - err := errors.New("whoops") - fmt.Println(err) - - // Output: whoops -} - -func ExampleNew_printf() { - err := errors.New("whoops") - fmt.Printf("%+v", err) - - // Example output: - // whoops - // github.com/pkg/errors_test.ExampleNew_printf - // /home/dfc/src/github.com/pkg/errors/example_test.go:17 - // testing.runExample - // /home/dfc/go/src/testing/example.go:114 - // testing.RunExamples - // /home/dfc/go/src/testing/example.go:38 - // testing.(*M).Run - // /home/dfc/go/src/testing/testing.go:744 - // main.main - // /github.com/pkg/errors/_test/_testmain.go:106 - // runtime.main - // /home/dfc/go/src/runtime/proc.go:183 - // runtime.goexit - // /home/dfc/go/src/runtime/asm_amd64.s:2059 -} - -func ExampleWithMessage() { - cause := errors.New("whoops") - err := errors.WithMessage(cause, "oh noes") - fmt.Println(err) - - // Output: oh noes: whoops -} - -func ExampleWithStack() { - cause := errors.New("whoops") - err := errors.WithStack(cause) - fmt.Println(err) - - // Output: whoops -} - -func ExampleWithStack_printf() { - cause := errors.New("whoops") - err := errors.WithStack(cause) - fmt.Printf("%+v", err) - - // Example Output: - // whoops - // github.com/pkg/errors_test.ExampleWithStack_printf - // /home/fabstu/go/src/github.com/pkg/errors/example_test.go:55 - // testing.runExample - // /usr/lib/go/src/testing/example.go:114 - // testing.RunExamples - // /usr/lib/go/src/testing/example.go:38 - // testing.(*M).Run - // /usr/lib/go/src/testing/testing.go:744 - // main.main - // github.com/pkg/errors/_test/_testmain.go:106 - // runtime.main - // /usr/lib/go/src/runtime/proc.go:183 - // runtime.goexit - // /usr/lib/go/src/runtime/asm_amd64.s:2086 - // github.com/pkg/errors_test.ExampleWithStack_printf - // /home/fabstu/go/src/github.com/pkg/errors/example_test.go:56 - // testing.runExample - // /usr/lib/go/src/testing/example.go:114 - // testing.RunExamples - // /usr/lib/go/src/testing/example.go:38 - // testing.(*M).Run - // /usr/lib/go/src/testing/testing.go:744 - // main.main - // github.com/pkg/errors/_test/_testmain.go:106 - // runtime.main - // /usr/lib/go/src/runtime/proc.go:183 - // runtime.goexit - // /usr/lib/go/src/runtime/asm_amd64.s:2086 -} - -func ExampleWrap() { - cause := errors.New("whoops") - err := errors.Wrap(cause, "oh noes") - fmt.Println(err) - - // Output: oh noes: whoops -} - -func fn() error { - e1 := errors.New("error") - e2 := errors.Wrap(e1, "inner") - e3 := errors.Wrap(e2, "middle") - return errors.Wrap(e3, "outer") -} - -func ExampleCause() { - err := fn() - fmt.Println(err) - fmt.Println(errors.Cause(err)) - - // Output: outer: middle: inner: error - // error -} - -func ExampleWrap_extended() { - err := fn() - fmt.Printf("%+v\n", err) - - // Example output: - // error - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:47 - // github.com/pkg/errors_test.ExampleCause_printf - // /home/dfc/src/github.com/pkg/errors/example_test.go:63 - // testing.runExample - // /home/dfc/go/src/testing/example.go:114 - // testing.RunExamples - // /home/dfc/go/src/testing/example.go:38 - // testing.(*M).Run - // /home/dfc/go/src/testing/testing.go:744 - // main.main - // /github.com/pkg/errors/_test/_testmain.go:104 - // runtime.main - // /home/dfc/go/src/runtime/proc.go:183 - // runtime.goexit - // /home/dfc/go/src/runtime/asm_amd64.s:2059 - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:48: inner - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:49: middle - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:50: outer -} - -func ExampleWrapf() { - cause := errors.New("whoops") - err := errors.Wrapf(cause, "oh noes #%d", 2) - fmt.Println(err) - - // Output: oh noes #2: whoops -} - -func ExampleErrorf_extended() { - err := errors.Errorf("whoops: %s", "foo") - fmt.Printf("%+v", err) - - // Example output: - // whoops: foo - // github.com/pkg/errors_test.ExampleErrorf - // /home/dfc/src/github.com/pkg/errors/example_test.go:101 - // testing.runExample - // /home/dfc/go/src/testing/example.go:114 - // testing.RunExamples - // /home/dfc/go/src/testing/example.go:38 - // testing.(*M).Run - // /home/dfc/go/src/testing/testing.go:744 - // main.main - // /github.com/pkg/errors/_test/_testmain.go:102 - // runtime.main - // /home/dfc/go/src/runtime/proc.go:183 - // runtime.goexit - // /home/dfc/go/src/runtime/asm_amd64.s:2059 -} - -func Example_stackTrace() { - type stackTracer interface { - StackTrace() errors.StackTrace - } - - err, ok := errors.Cause(fn()).(stackTracer) - if !ok { - panic("oops, err does not implement stackTracer") - } - - st := err.StackTrace() - fmt.Printf("%+v", st[0:2]) // top two frames - - // Example output: - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:47 - // github.com/pkg/errors_test.Example_stackTrace - // /home/dfc/src/github.com/pkg/errors/example_test.go:127 -} - -func ExampleCause_printf() { - err := errors.Wrap(func() error { - return func() error { - return errors.Errorf("hello %s", fmt.Sprintf("world")) - }() - }(), "failed") - - fmt.Printf("%v", err) - - // Output: failed: hello world -} diff --git a/vendor/github.com/pkg/errors/format_test.go b/vendor/github.com/pkg/errors/format_test.go deleted file mode 100644 index 15fd7d89..00000000 --- a/vendor/github.com/pkg/errors/format_test.go +++ /dev/null @@ -1,535 +0,0 @@ -package errors - -import ( - "errors" - "fmt" - "io" - "regexp" - "strings" - "testing" -) - -func TestFormatNew(t *testing.T) { - tests := []struct { - error - format string - want string - }{{ - New("error"), - "%s", - "error", - }, { - New("error"), - "%v", - "error", - }, { - New("error"), - "%+v", - "error\n" + - "github.com/pkg/errors.TestFormatNew\n" + - "\t.+/github.com/pkg/errors/format_test.go:26", - }, { - New("error"), - "%q", - `"error"`, - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.error, tt.format, tt.want) - } -} - -func TestFormatErrorf(t *testing.T) { - tests := []struct { - error - format string - want string - }{{ - Errorf("%s", "error"), - "%s", - "error", - }, { - Errorf("%s", "error"), - "%v", - "error", - }, { - Errorf("%s", "error"), - "%+v", - "error\n" + - "github.com/pkg/errors.TestFormatErrorf\n" + - "\t.+/github.com/pkg/errors/format_test.go:56", - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.error, tt.format, tt.want) - } -} - -func TestFormatWrap(t *testing.T) { - tests := []struct { - error - format string - want string - }{{ - Wrap(New("error"), "error2"), - "%s", - "error2: error", - }, { - Wrap(New("error"), "error2"), - "%v", - "error2: error", - }, { - Wrap(New("error"), "error2"), - "%+v", - "error\n" + - "github.com/pkg/errors.TestFormatWrap\n" + - "\t.+/github.com/pkg/errors/format_test.go:82", - }, { - Wrap(io.EOF, "error"), - "%s", - "error: EOF", - }, { - Wrap(io.EOF, "error"), - "%v", - "error: EOF", - }, { - Wrap(io.EOF, "error"), - "%+v", - "EOF\n" + - "error\n" + - "github.com/pkg/errors.TestFormatWrap\n" + - "\t.+/github.com/pkg/errors/format_test.go:96", - }, { - Wrap(Wrap(io.EOF, "error1"), "error2"), - "%+v", - "EOF\n" + - "error1\n" + - "github.com/pkg/errors.TestFormatWrap\n" + - "\t.+/github.com/pkg/errors/format_test.go:103\n", - }, { - Wrap(New("error with space"), "context"), - "%q", - `"context: error with space"`, - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.error, tt.format, tt.want) - } -} - -func TestFormatWrapf(t *testing.T) { - tests := []struct { - error - format string - want string - }{{ - Wrapf(io.EOF, "error%d", 2), - "%s", - "error2: EOF", - }, { - Wrapf(io.EOF, "error%d", 2), - "%v", - "error2: EOF", - }, { - Wrapf(io.EOF, "error%d", 2), - "%+v", - "EOF\n" + - "error2\n" + - "github.com/pkg/errors.TestFormatWrapf\n" + - "\t.+/github.com/pkg/errors/format_test.go:134", - }, { - Wrapf(New("error"), "error%d", 2), - "%s", - "error2: error", - }, { - Wrapf(New("error"), "error%d", 2), - "%v", - "error2: error", - }, { - Wrapf(New("error"), "error%d", 2), - "%+v", - "error\n" + - "github.com/pkg/errors.TestFormatWrapf\n" + - "\t.+/github.com/pkg/errors/format_test.go:149", - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.error, tt.format, tt.want) - } -} - -func TestFormatWithStack(t *testing.T) { - tests := []struct { - error - format string - want []string - }{{ - WithStack(io.EOF), - "%s", - []string{"EOF"}, - }, { - WithStack(io.EOF), - "%v", - []string{"EOF"}, - }, { - WithStack(io.EOF), - "%+v", - []string{"EOF", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:175"}, - }, { - WithStack(New("error")), - "%s", - []string{"error"}, - }, { - WithStack(New("error")), - "%v", - []string{"error"}, - }, { - WithStack(New("error")), - "%+v", - []string{"error", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:189", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:189"}, - }, { - WithStack(WithStack(io.EOF)), - "%+v", - []string{"EOF", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:197", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:197"}, - }, { - WithStack(WithStack(Wrapf(io.EOF, "message"))), - "%+v", - []string{"EOF", - "message", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:205", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:205", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:205"}, - }, { - WithStack(Errorf("error%d", 1)), - "%+v", - []string{"error1", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:216", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:216"}, - }} - - for i, tt := range tests { - testFormatCompleteCompare(t, i, tt.error, tt.format, tt.want, true) - } -} - -func TestFormatWithMessage(t *testing.T) { - tests := []struct { - error - format string - want []string - }{{ - WithMessage(New("error"), "error2"), - "%s", - []string{"error2: error"}, - }, { - WithMessage(New("error"), "error2"), - "%v", - []string{"error2: error"}, - }, { - WithMessage(New("error"), "error2"), - "%+v", - []string{ - "error", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:244", - "error2"}, - }, { - WithMessage(io.EOF, "addition1"), - "%s", - []string{"addition1: EOF"}, - }, { - WithMessage(io.EOF, "addition1"), - "%v", - []string{"addition1: EOF"}, - }, { - WithMessage(io.EOF, "addition1"), - "%+v", - []string{"EOF", "addition1"}, - }, { - WithMessage(WithMessage(io.EOF, "addition1"), "addition2"), - "%v", - []string{"addition2: addition1: EOF"}, - }, { - WithMessage(WithMessage(io.EOF, "addition1"), "addition2"), - "%+v", - []string{"EOF", "addition1", "addition2"}, - }, { - Wrap(WithMessage(io.EOF, "error1"), "error2"), - "%+v", - []string{"EOF", "error1", "error2", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:272"}, - }, { - WithMessage(Errorf("error%d", 1), "error2"), - "%+v", - []string{"error1", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:278", - "error2"}, - }, { - WithMessage(WithStack(io.EOF), "error"), - "%+v", - []string{ - "EOF", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:285", - "error"}, - }, { - WithMessage(Wrap(WithStack(io.EOF), "inside-error"), "outside-error"), - "%+v", - []string{ - "EOF", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:293", - "inside-error", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:293", - "outside-error"}, - }} - - for i, tt := range tests { - testFormatCompleteCompare(t, i, tt.error, tt.format, tt.want, true) - } -} - -func TestFormatGeneric(t *testing.T) { - starts := []struct { - err error - want []string - }{ - {New("new-error"), []string{ - "new-error", - "github.com/pkg/errors.TestFormatGeneric\n" + - "\t.+/github.com/pkg/errors/format_test.go:315"}, - }, {Errorf("errorf-error"), []string{ - "errorf-error", - "github.com/pkg/errors.TestFormatGeneric\n" + - "\t.+/github.com/pkg/errors/format_test.go:319"}, - }, {errors.New("errors-new-error"), []string{ - "errors-new-error"}, - }, - } - - wrappers := []wrapper{ - { - func(err error) error { return WithMessage(err, "with-message") }, - []string{"with-message"}, - }, { - func(err error) error { return WithStack(err) }, - []string{ - "github.com/pkg/errors.(func·002|TestFormatGeneric.func2)\n\t" + - ".+/github.com/pkg/errors/format_test.go:333", - }, - }, { - func(err error) error { return Wrap(err, "wrap-error") }, - []string{ - "wrap-error", - "github.com/pkg/errors.(func·003|TestFormatGeneric.func3)\n\t" + - ".+/github.com/pkg/errors/format_test.go:339", - }, - }, { - func(err error) error { return Wrapf(err, "wrapf-error%d", 1) }, - []string{ - "wrapf-error1", - "github.com/pkg/errors.(func·004|TestFormatGeneric.func4)\n\t" + - ".+/github.com/pkg/errors/format_test.go:346", - }, - }, - } - - for s := range starts { - err := starts[s].err - want := starts[s].want - testFormatCompleteCompare(t, s, err, "%+v", want, false) - testGenericRecursive(t, err, want, wrappers, 3) - } -} - -func testFormatRegexp(t *testing.T, n int, arg interface{}, format, want string) { - got := fmt.Sprintf(format, arg) - gotLines := strings.SplitN(got, "\n", -1) - wantLines := strings.SplitN(want, "\n", -1) - - if len(wantLines) > len(gotLines) { - t.Errorf("test %d: wantLines(%d) > gotLines(%d):\n got: %q\nwant: %q", n+1, len(wantLines), len(gotLines), got, want) - return - } - - for i, w := range wantLines { - match, err := regexp.MatchString(w, gotLines[i]) - if err != nil { - t.Fatal(err) - } - if !match { - t.Errorf("test %d: line %d: fmt.Sprintf(%q, err):\n got: %q\nwant: %q", n+1, i+1, format, got, want) - } - } -} - -var stackLineR = regexp.MustCompile(`\.`) - -// parseBlocks parses input into a slice, where: -// - incase entry contains a newline, its a stacktrace -// - incase entry contains no newline, its a solo line. -// -// Detecting stack boundaries only works incase the WithStack-calls are -// to be found on the same line, thats why it is optionally here. -// -// Example use: -// -// for _, e := range blocks { -// if strings.ContainsAny(e, "\n") { -// // Match as stack -// } else { -// // Match as line -// } -// } -// -func parseBlocks(input string, detectStackboundaries bool) ([]string, error) { - var blocks []string - - stack := "" - wasStack := false - lines := map[string]bool{} // already found lines - - for _, l := range strings.Split(input, "\n") { - isStackLine := stackLineR.MatchString(l) - - switch { - case !isStackLine && wasStack: - blocks = append(blocks, stack, l) - stack = "" - lines = map[string]bool{} - case isStackLine: - if wasStack { - // Detecting two stacks after another, possible cause lines match in - // our tests due to WithStack(WithStack(io.EOF)) on same line. - if detectStackboundaries { - if lines[l] { - if len(stack) == 0 { - return nil, errors.New("len of block must not be zero here") - } - - blocks = append(blocks, stack) - stack = l - lines = map[string]bool{l: true} - continue - } - } - - stack = stack + "\n" + l - } else { - stack = l - } - lines[l] = true - case !isStackLine && !wasStack: - blocks = append(blocks, l) - default: - return nil, errors.New("must not happen") - } - - wasStack = isStackLine - } - - // Use up stack - if stack != "" { - blocks = append(blocks, stack) - } - return blocks, nil -} - -func testFormatCompleteCompare(t *testing.T, n int, arg interface{}, format string, want []string, detectStackBoundaries bool) { - gotStr := fmt.Sprintf(format, arg) - - got, err := parseBlocks(gotStr, detectStackBoundaries) - if err != nil { - t.Fatal(err) - } - - if len(got) != len(want) { - t.Fatalf("test %d: fmt.Sprintf(%s, err) -> wrong number of blocks: got(%d) want(%d)\n got: %s\nwant: %s\ngotStr: %q", - n+1, format, len(got), len(want), prettyBlocks(got), prettyBlocks(want), gotStr) - } - - for i := range got { - if strings.ContainsAny(want[i], "\n") { - // Match as stack - match, err := regexp.MatchString(want[i], got[i]) - if err != nil { - t.Fatal(err) - } - if !match { - t.Fatalf("test %d: block %d: fmt.Sprintf(%q, err):\ngot:\n%q\nwant:\n%q\nall-got:\n%s\nall-want:\n%s\n", - n+1, i+1, format, got[i], want[i], prettyBlocks(got), prettyBlocks(want)) - } - } else { - // Match as message - if got[i] != want[i] { - t.Fatalf("test %d: fmt.Sprintf(%s, err) at block %d got != want:\n got: %q\nwant: %q", n+1, format, i+1, got[i], want[i]) - } - } - } -} - -type wrapper struct { - wrap func(err error) error - want []string -} - -func prettyBlocks(blocks []string, prefix ...string) string { - var out []string - - for _, b := range blocks { - out = append(out, fmt.Sprintf("%v", b)) - } - - return " " + strings.Join(out, "\n ") -} - -func testGenericRecursive(t *testing.T, beforeErr error, beforeWant []string, list []wrapper, maxDepth int) { - if len(beforeWant) == 0 { - panic("beforeWant must not be empty") - } - for _, w := range list { - if len(w.want) == 0 { - panic("want must not be empty") - } - - err := w.wrap(beforeErr) - - // Copy required cause append(beforeWant, ..) modified beforeWant subtly. - beforeCopy := make([]string, len(beforeWant)) - copy(beforeCopy, beforeWant) - - beforeWant := beforeCopy - last := len(beforeWant) - 1 - var want []string - - // Merge two stacks behind each other. - if strings.ContainsAny(beforeWant[last], "\n") && strings.ContainsAny(w.want[0], "\n") { - want = append(beforeWant[:last], append([]string{beforeWant[last] + "((?s).*)" + w.want[0]}, w.want[1:]...)...) - } else { - want = append(beforeWant, w.want...) - } - - testFormatCompleteCompare(t, maxDepth, err, "%+v", want, false) - if maxDepth > 0 { - testGenericRecursive(t, err, want, list, maxDepth-1) - } - } -} diff --git a/vendor/github.com/pkg/errors/stack_test.go b/vendor/github.com/pkg/errors/stack_test.go deleted file mode 100644 index 510c27a9..00000000 --- a/vendor/github.com/pkg/errors/stack_test.go +++ /dev/null @@ -1,292 +0,0 @@ -package errors - -import ( - "fmt" - "runtime" - "testing" -) - -var initpc, _, _, _ = runtime.Caller(0) - -func TestFrameLine(t *testing.T) { - var tests = []struct { - Frame - want int - }{{ - Frame(initpc), - 9, - }, { - func() Frame { - var pc, _, _, _ = runtime.Caller(0) - return Frame(pc) - }(), - 20, - }, { - func() Frame { - var pc, _, _, _ = runtime.Caller(1) - return Frame(pc) - }(), - 28, - }, { - Frame(0), // invalid PC - 0, - }} - - for _, tt := range tests { - got := tt.Frame.line() - want := tt.want - if want != got { - t.Errorf("Frame(%v): want: %v, got: %v", uintptr(tt.Frame), want, got) - } - } -} - -type X struct{} - -func (x X) val() Frame { - var pc, _, _, _ = runtime.Caller(0) - return Frame(pc) -} - -func (x *X) ptr() Frame { - var pc, _, _, _ = runtime.Caller(0) - return Frame(pc) -} - -func TestFrameFormat(t *testing.T) { - var tests = []struct { - Frame - format string - want string - }{{ - Frame(initpc), - "%s", - "stack_test.go", - }, { - Frame(initpc), - "%+s", - "github.com/pkg/errors.init\n" + - "\t.+/github.com/pkg/errors/stack_test.go", - }, { - Frame(0), - "%s", - "unknown", - }, { - Frame(0), - "%+s", - "unknown", - }, { - Frame(initpc), - "%d", - "9", - }, { - Frame(0), - "%d", - "0", - }, { - Frame(initpc), - "%n", - "init", - }, { - func() Frame { - var x X - return x.ptr() - }(), - "%n", - `\(\*X\).ptr`, - }, { - func() Frame { - var x X - return x.val() - }(), - "%n", - "X.val", - }, { - Frame(0), - "%n", - "", - }, { - Frame(initpc), - "%v", - "stack_test.go:9", - }, { - Frame(initpc), - "%+v", - "github.com/pkg/errors.init\n" + - "\t.+/github.com/pkg/errors/stack_test.go:9", - }, { - Frame(0), - "%v", - "unknown:0", - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.Frame, tt.format, tt.want) - } -} - -func TestFuncname(t *testing.T) { - tests := []struct { - name, want string - }{ - {"", ""}, - {"runtime.main", "main"}, - {"github.com/pkg/errors.funcname", "funcname"}, - {"funcname", "funcname"}, - {"io.copyBuffer", "copyBuffer"}, - {"main.(*R).Write", "(*R).Write"}, - } - - for _, tt := range tests { - got := funcname(tt.name) - want := tt.want - if got != want { - t.Errorf("funcname(%q): want: %q, got %q", tt.name, want, got) - } - } -} - -func TestTrimGOPATH(t *testing.T) { - var tests = []struct { - Frame - want string - }{{ - Frame(initpc), - "github.com/pkg/errors/stack_test.go", - }} - - for i, tt := range tests { - pc := tt.Frame.pc() - fn := runtime.FuncForPC(pc) - file, _ := fn.FileLine(pc) - got := trimGOPATH(fn.Name(), file) - testFormatRegexp(t, i, got, "%s", tt.want) - } -} - -func TestStackTrace(t *testing.T) { - tests := []struct { - err error - want []string - }{{ - New("ooh"), []string{ - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:172", - }, - }, { - Wrap(New("ooh"), "ahh"), []string{ - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:177", // this is the stack of Wrap, not New - }, - }, { - Cause(Wrap(New("ooh"), "ahh")), []string{ - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:182", // this is the stack of New - }, - }, { - func() error { return New("ooh") }(), []string{ - `github.com/pkg/errors.(func·009|TestStackTrace.func1)` + - "\n\t.+/github.com/pkg/errors/stack_test.go:187", // this is the stack of New - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:187", // this is the stack of New's caller - }, - }, { - Cause(func() error { - return func() error { - return Errorf("hello %s", fmt.Sprintf("world")) - }() - }()), []string{ - `github.com/pkg/errors.(func·010|TestStackTrace.func2.1)` + - "\n\t.+/github.com/pkg/errors/stack_test.go:196", // this is the stack of Errorf - `github.com/pkg/errors.(func·011|TestStackTrace.func2)` + - "\n\t.+/github.com/pkg/errors/stack_test.go:197", // this is the stack of Errorf's caller - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:198", // this is the stack of Errorf's caller's caller - }, - }} - for i, tt := range tests { - x, ok := tt.err.(interface { - StackTrace() StackTrace - }) - if !ok { - t.Errorf("expected %#v to implement StackTrace() StackTrace", tt.err) - continue - } - st := x.StackTrace() - for j, want := range tt.want { - testFormatRegexp(t, i, st[j], "%+v", want) - } - } -} - -func stackTrace() StackTrace { - const depth = 8 - var pcs [depth]uintptr - n := runtime.Callers(1, pcs[:]) - var st stack = pcs[0:n] - return st.StackTrace() -} - -func TestStackTraceFormat(t *testing.T) { - tests := []struct { - StackTrace - format string - want string - }{{ - nil, - "%s", - `\[\]`, - }, { - nil, - "%v", - `\[\]`, - }, { - nil, - "%+v", - "", - }, { - nil, - "%#v", - `\[\]errors.Frame\(nil\)`, - }, { - make(StackTrace, 0), - "%s", - `\[\]`, - }, { - make(StackTrace, 0), - "%v", - `\[\]`, - }, { - make(StackTrace, 0), - "%+v", - "", - }, { - make(StackTrace, 0), - "%#v", - `\[\]errors.Frame{}`, - }, { - stackTrace()[:2], - "%s", - `\[stack_test.go stack_test.go\]`, - }, { - stackTrace()[:2], - "%v", - `\[stack_test.go:225 stack_test.go:272\]`, - }, { - stackTrace()[:2], - "%+v", - "\n" + - "github.com/pkg/errors.stackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:225\n" + - "github.com/pkg/errors.TestStackTraceFormat\n" + - "\t.+/github.com/pkg/errors/stack_test.go:276", - }, { - stackTrace()[:2], - "%#v", - `\[\]errors.Frame{stack_test.go:225, stack_test.go:284}`, - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.StackTrace, tt.format, tt.want) - } -} diff --git a/vendor/github.com/sdboyer/constext/README.md b/vendor/github.com/sdboyer/constext/README.md deleted file mode 100644 index e267fd54..00000000 --- a/vendor/github.com/sdboyer/constext/README.md +++ /dev/null @@ -1,78 +0,0 @@ -# constext [![Doc Status](https://godoc.org/github.com/sdboyer/constext?status.png)](https://godoc.org/github.com/sdboyer/constext) - -constext allows you to [`cons`](https://en.wikipedia.org/wiki/Cons) `Context`s -together as a pair, conjoining them for the purpose of all `Context` behaviors: - -1. If either parent context is canceled, the constext is canceled. The - err is set to whatever the err of the parent that was canceled. -2. If either parent has a deadline, the constext uses that same - deadline. If both have a deadline, it uses the sooner/lesser one. -3. Values from both parents are unioned together. When a key is present in both - parent trees, the left (first) context supercedes the right (second). - -Paired contexts can be recombined using the standard `context.With*()` -functions. - -## Usage - -Use is simple, and patterned after the `context` package. The `constext.Cons()` -function takes two `context.Context` arguments and returns a single, unified -one, along with a `context.CancelFunc`. - -```go -cctx, cancelFunc := constext.Cons(context.Background(), context.Background()) -``` - -True to the spirit of `cons`, recursive trees can be formed through -nesting: - -```go -bg := context.Background() -cctx := constext.Cons(bg, constext.Cons(bg, constext.Cons(bg, bg))) -``` - -This probably isn't a good idea, but it's possible. - -## Rationale - -While the unary model of context works well for the original vision - an object -operating within an [HTTP] request's scope - there are times when we need a -little more. - -For example: in [dep](https://github.com/golang/dep), the subsystem that -manages interaction with source repositories is called a -[`SourceManager`](https://godoc.org/github.com/sdboyer/gps#SourceManager). It -is a long-lived object; generally, only one is created over the course of any -single `dep` invocation. The `SourceManager` has a number of methods on it that -may initiate network and/or disk interaction. As such, these methods need to -take a `context.Context`, so that the caller can cancel them if needed. - -However, this is not sufficient. The `SourceManager` itself may need to be -terminated (e.g., if the process received a signal). In such a case, in-flight -method calls also need to be canceled, to avoid leaving disk in inconsistent -state. - -As a result, each in-flight request serves two parents - the initator of the -request, and the `SourceManager` itself. We can abstract away this complexity -by having a `Context` for each, and `Cons`ing them together on a per-call -basis. - -## Caveats - -_tl;dr: GC doesn't work right, so explicitly cancel constexts when done with them._ - -The stdlib context packages uses internal tree-walking trickery to avoid -spawning goroutines unless it actually has to. We can't rely on that same -trickery, in part because we can't access the tree internals, but also because -it's not so straightforward when multiple parents are involved. Consequently, -`Cons()` almost always must spawn a goroutine to ensure correct cancellation -behavior, whereas e.g. `context.WithCancel()` rarely has to. - -If, as in the use case above, your constext has one short-lived and one -long-lived parent, and the short-lived parent is not explicitly canceled (which -is typical), then until the long-lived parent is canceled, neither the -constext, nor any otherwise-unreachable members of the short-lived context tree -will be GCed. - -So, for now, explicitly cancel your constexts before they go out of scope, -otherwise you'll leak memory. diff --git a/vendor/github.com/sdboyer/constext/constext_test.go b/vendor/github.com/sdboyer/constext/constext_test.go deleted file mode 100644 index 907483b2..00000000 --- a/vendor/github.com/sdboyer/constext/constext_test.go +++ /dev/null @@ -1,156 +0,0 @@ -package constext - -import ( - "context" - "runtime" - "testing" - "time" -) - -var bgc = context.Background() - -func TestConsCancel(t *testing.T) { - c1, cancel1 := context.WithCancel(bgc) - c2, cancel2 := context.WithCancel(bgc) - - cc, _ := Cons(c1, c2) - if _, has := cc.Deadline(); has { - t.Fatal("constext should not have a deadline if parents do not") - } - - cancel1() - select { - case <-cc.Done(): - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for parent to quit; stacks:\n%s", buf[:n]) - } - - cc, _ = Cons(c1, c2) - if cc.Err() == nil { - t.Fatal("pre-canceled car constext did not begin canceled") - } - - cc, _ = Cons(c2, c1) - if cc.Err() == nil { - t.Fatal("pre-canceled cdr constext did not begin canceled") - } - - c3, _ := context.WithCancel(bgc) - cc, _ = Cons(c3, c2) - cancel2() - select { - case <-cc.Done(): - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for cdr to quit; stacks:\n%s", buf[:n]) - } -} - -func TestCancelPassdown(t *testing.T) { - c1, cancel1 := context.WithCancel(bgc) - c2, _ := context.WithCancel(bgc) - cc, _ := Cons(c1, c2) - c3, _ := context.WithCancel(cc) - - cancel1() - select { - case <-c3.Done(): - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for parent to quit; stacks:\n%s", buf[:n]) - } - - c1, cancel1 = context.WithCancel(bgc) - cc, _ = Cons(c1, c2) - c3 = context.WithValue(cc, "foo", "bar") - - cancel1() - select { - case <-c3.Done(): - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for parent to quit; stacks:\n%s", buf[:n]) - } -} - -func TestValueUnion(t *testing.T) { - c1 := context.WithValue(bgc, "foo", "bar") - c2 := context.WithValue(bgc, "foo", "baz") - cc, _ := Cons(c1, c2) - - v := cc.Value("foo") - if v != "bar" { - t.Fatalf("wanted value of \"foo\" from car, \"bar\", got %q", v) - } - - c3 := context.WithValue(bgc, "bar", "quux") - cc2, _ := Cons(c1, c3) - v = cc2.Value("bar") - if v != "quux" { - t.Fatalf("wanted value from cdr, \"quux\", got %q", v) - } - - cc, _ = Cons(cc, c3) - v = cc.Value("bar") - if v != "quux" { - t.Fatalf("wanted value from nested cdr, \"quux\", got %q", v) - } -} - -func TestDeadline(t *testing.T) { - t1 := time.Now().Add(1 * time.Second) - c1, _ := context.WithDeadline(bgc, t1) - cc, _ := Cons(c1, bgc) - - cct, ok := cc.Deadline() - if !ok { - t.Fatal("constext claimed to not have any deadline, but car did") - } - if cct != t1 { - t.Fatal("constext did not have correct deadline") - } - - cc, _ = Cons(bgc, c1) - cct, ok = cc.Deadline() - if !ok { - t.Fatal("constext claimed to not have any deadline, but cdr did") - } - if cct != t1 { - t.Fatal("constext did not have correct deadline") - } - - t2 := time.Now().Add(1 * time.Second) - c2, _ := context.WithDeadline(bgc, t2) - cc, _ = Cons(c1, c2) - cct, ok = cc.Deadline() - if !ok { - t.Fatal("constext claimed to not have any deadline, but both parents did") - } - - if cct != t1 { - t.Fatal("got wrong deadline time back") - } - - cc, _ = Cons(c2, c1) - cct, ok = cc.Deadline() - if !ok { - t.Fatal("constext claimed to not have any deadline, but both parents did") - } - - if cct != t1 { - t.Fatal("got wrong deadline time back") - } - - select { - case <-cc.Done(): - case <-time.After(t1.Sub(time.Now()) + 5*time.Millisecond): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("car did not quit after deadline; stacks:\n%s", buf[:n]) - } -} diff --git a/vendor/golang.org/x/net/.gitattributes b/vendor/golang.org/x/net/.gitattributes deleted file mode 100644 index d2f212e5..00000000 --- a/vendor/golang.org/x/net/.gitattributes +++ /dev/null @@ -1,10 +0,0 @@ -# Treat all files in this repo as binary, with no git magic updating -# line endings. Windows users contributing to Go will need to use a -# modern version of git and editors capable of LF line endings. -# -# We'll prevent accidental CRLF line endings from entering the repo -# via the git-review gofmt checks. -# -# See golang.org/issue/9281 - -* -text diff --git a/vendor/golang.org/x/net/.gitignore b/vendor/golang.org/x/net/.gitignore deleted file mode 100644 index 8339fd61..00000000 --- a/vendor/golang.org/x/net/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -# Add no patterns to .hgignore except for files generated by the build. -last-change diff --git a/vendor/golang.org/x/net/CONTRIBUTING.md b/vendor/golang.org/x/net/CONTRIBUTING.md deleted file mode 100644 index 88dff59b..00000000 --- a/vendor/golang.org/x/net/CONTRIBUTING.md +++ /dev/null @@ -1,31 +0,0 @@ -# Contributing to Go - -Go is an open source project. - -It is the work of hundreds of contributors. We appreciate your help! - - -## Filing issues - -When [filing an issue](https://golang.org/issue/new), make sure to answer these five questions: - -1. What version of Go are you using (`go version`)? -2. What operating system and processor architecture are you using? -3. What did you do? -4. What did you expect to see? -5. What did you see instead? - -General questions should go to the [golang-nuts mailing list](https://groups.google.com/group/golang-nuts) instead of the issue tracker. -The gophers there will answer or ask you to file an issue if you've tripped over a bug. - -## Contributing code - -Please read the [Contribution Guidelines](https://golang.org/doc/contribute.html) -before sending patches. - -**We do not accept GitHub pull requests** -(we use [Gerrit](https://code.google.com/p/gerrit/) instead for code review). - -Unless otherwise noted, the Go source files are distributed under -the BSD-style license found in the LICENSE file. - diff --git a/vendor/golang.org/x/net/README b/vendor/golang.org/x/net/README deleted file mode 100644 index 6b13d8e5..00000000 --- a/vendor/golang.org/x/net/README +++ /dev/null @@ -1,3 +0,0 @@ -This repository holds supplementary Go networking libraries. - -To submit changes to this repository, see http://golang.org/doc/contribute.html. diff --git a/vendor/golang.org/x/net/codereview.cfg b/vendor/golang.org/x/net/codereview.cfg deleted file mode 100644 index 3f8b14b6..00000000 --- a/vendor/golang.org/x/net/codereview.cfg +++ /dev/null @@ -1 +0,0 @@ -issuerepo: golang/go diff --git a/vendor/golang.org/x/net/context/context_test.go b/vendor/golang.org/x/net/context/context_test.go deleted file mode 100644 index 62844131..00000000 --- a/vendor/golang.org/x/net/context/context_test.go +++ /dev/null @@ -1,583 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.7 - -package context - -import ( - "fmt" - "math/rand" - "runtime" - "strings" - "sync" - "testing" - "time" -) - -// otherContext is a Context that's not one of the types defined in context.go. -// This lets us test code paths that differ based on the underlying type of the -// Context. -type otherContext struct { - Context -} - -func TestBackground(t *testing.T) { - c := Background() - if c == nil { - t.Fatalf("Background returned nil") - } - select { - case x := <-c.Done(): - t.Errorf("<-c.Done() == %v want nothing (it should block)", x) - default: - } - if got, want := fmt.Sprint(c), "context.Background"; got != want { - t.Errorf("Background().String() = %q want %q", got, want) - } -} - -func TestTODO(t *testing.T) { - c := TODO() - if c == nil { - t.Fatalf("TODO returned nil") - } - select { - case x := <-c.Done(): - t.Errorf("<-c.Done() == %v want nothing (it should block)", x) - default: - } - if got, want := fmt.Sprint(c), "context.TODO"; got != want { - t.Errorf("TODO().String() = %q want %q", got, want) - } -} - -func TestWithCancel(t *testing.T) { - c1, cancel := WithCancel(Background()) - - if got, want := fmt.Sprint(c1), "context.Background.WithCancel"; got != want { - t.Errorf("c1.String() = %q want %q", got, want) - } - - o := otherContext{c1} - c2, _ := WithCancel(o) - contexts := []Context{c1, o, c2} - - for i, c := range contexts { - if d := c.Done(); d == nil { - t.Errorf("c[%d].Done() == %v want non-nil", i, d) - } - if e := c.Err(); e != nil { - t.Errorf("c[%d].Err() == %v want nil", i, e) - } - - select { - case x := <-c.Done(): - t.Errorf("<-c.Done() == %v want nothing (it should block)", x) - default: - } - } - - cancel() - time.Sleep(100 * time.Millisecond) // let cancelation propagate - - for i, c := range contexts { - select { - case <-c.Done(): - default: - t.Errorf("<-c[%d].Done() blocked, but shouldn't have", i) - } - if e := c.Err(); e != Canceled { - t.Errorf("c[%d].Err() == %v want %v", i, e, Canceled) - } - } -} - -func TestParentFinishesChild(t *testing.T) { - // Context tree: - // parent -> cancelChild - // parent -> valueChild -> timerChild - parent, cancel := WithCancel(Background()) - cancelChild, stop := WithCancel(parent) - defer stop() - valueChild := WithValue(parent, "key", "value") - timerChild, stop := WithTimeout(valueChild, 10000*time.Hour) - defer stop() - - select { - case x := <-parent.Done(): - t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) - case x := <-cancelChild.Done(): - t.Errorf("<-cancelChild.Done() == %v want nothing (it should block)", x) - case x := <-timerChild.Done(): - t.Errorf("<-timerChild.Done() == %v want nothing (it should block)", x) - case x := <-valueChild.Done(): - t.Errorf("<-valueChild.Done() == %v want nothing (it should block)", x) - default: - } - - // The parent's children should contain the two cancelable children. - pc := parent.(*cancelCtx) - cc := cancelChild.(*cancelCtx) - tc := timerChild.(*timerCtx) - pc.mu.Lock() - if len(pc.children) != 2 || !pc.children[cc] || !pc.children[tc] { - t.Errorf("bad linkage: pc.children = %v, want %v and %v", - pc.children, cc, tc) - } - pc.mu.Unlock() - - if p, ok := parentCancelCtx(cc.Context); !ok || p != pc { - t.Errorf("bad linkage: parentCancelCtx(cancelChild.Context) = %v, %v want %v, true", p, ok, pc) - } - if p, ok := parentCancelCtx(tc.Context); !ok || p != pc { - t.Errorf("bad linkage: parentCancelCtx(timerChild.Context) = %v, %v want %v, true", p, ok, pc) - } - - cancel() - - pc.mu.Lock() - if len(pc.children) != 0 { - t.Errorf("pc.cancel didn't clear pc.children = %v", pc.children) - } - pc.mu.Unlock() - - // parent and children should all be finished. - check := func(ctx Context, name string) { - select { - case <-ctx.Done(): - default: - t.Errorf("<-%s.Done() blocked, but shouldn't have", name) - } - if e := ctx.Err(); e != Canceled { - t.Errorf("%s.Err() == %v want %v", name, e, Canceled) - } - } - check(parent, "parent") - check(cancelChild, "cancelChild") - check(valueChild, "valueChild") - check(timerChild, "timerChild") - - // WithCancel should return a canceled context on a canceled parent. - precanceledChild := WithValue(parent, "key", "value") - select { - case <-precanceledChild.Done(): - default: - t.Errorf("<-precanceledChild.Done() blocked, but shouldn't have") - } - if e := precanceledChild.Err(); e != Canceled { - t.Errorf("precanceledChild.Err() == %v want %v", e, Canceled) - } -} - -func TestChildFinishesFirst(t *testing.T) { - cancelable, stop := WithCancel(Background()) - defer stop() - for _, parent := range []Context{Background(), cancelable} { - child, cancel := WithCancel(parent) - - select { - case x := <-parent.Done(): - t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) - case x := <-child.Done(): - t.Errorf("<-child.Done() == %v want nothing (it should block)", x) - default: - } - - cc := child.(*cancelCtx) - pc, pcok := parent.(*cancelCtx) // pcok == false when parent == Background() - if p, ok := parentCancelCtx(cc.Context); ok != pcok || (ok && pc != p) { - t.Errorf("bad linkage: parentCancelCtx(cc.Context) = %v, %v want %v, %v", p, ok, pc, pcok) - } - - if pcok { - pc.mu.Lock() - if len(pc.children) != 1 || !pc.children[cc] { - t.Errorf("bad linkage: pc.children = %v, cc = %v", pc.children, cc) - } - pc.mu.Unlock() - } - - cancel() - - if pcok { - pc.mu.Lock() - if len(pc.children) != 0 { - t.Errorf("child's cancel didn't remove self from pc.children = %v", pc.children) - } - pc.mu.Unlock() - } - - // child should be finished. - select { - case <-child.Done(): - default: - t.Errorf("<-child.Done() blocked, but shouldn't have") - } - if e := child.Err(); e != Canceled { - t.Errorf("child.Err() == %v want %v", e, Canceled) - } - - // parent should not be finished. - select { - case x := <-parent.Done(): - t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) - default: - } - if e := parent.Err(); e != nil { - t.Errorf("parent.Err() == %v want nil", e) - } - } -} - -func testDeadline(c Context, wait time.Duration, t *testing.T) { - select { - case <-time.After(wait): - t.Fatalf("context should have timed out") - case <-c.Done(): - } - if e := c.Err(); e != DeadlineExceeded { - t.Errorf("c.Err() == %v want %v", e, DeadlineExceeded) - } -} - -func TestDeadline(t *testing.T) { - t.Parallel() - const timeUnit = 500 * time.Millisecond - c, _ := WithDeadline(Background(), time.Now().Add(1*timeUnit)) - if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) { - t.Errorf("c.String() = %q want prefix %q", got, prefix) - } - testDeadline(c, 2*timeUnit, t) - - c, _ = WithDeadline(Background(), time.Now().Add(1*timeUnit)) - o := otherContext{c} - testDeadline(o, 2*timeUnit, t) - - c, _ = WithDeadline(Background(), time.Now().Add(1*timeUnit)) - o = otherContext{c} - c, _ = WithDeadline(o, time.Now().Add(3*timeUnit)) - testDeadline(c, 2*timeUnit, t) -} - -func TestTimeout(t *testing.T) { - t.Parallel() - const timeUnit = 500 * time.Millisecond - c, _ := WithTimeout(Background(), 1*timeUnit) - if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) { - t.Errorf("c.String() = %q want prefix %q", got, prefix) - } - testDeadline(c, 2*timeUnit, t) - - c, _ = WithTimeout(Background(), 1*timeUnit) - o := otherContext{c} - testDeadline(o, 2*timeUnit, t) - - c, _ = WithTimeout(Background(), 1*timeUnit) - o = otherContext{c} - c, _ = WithTimeout(o, 3*timeUnit) - testDeadline(c, 2*timeUnit, t) -} - -func TestCanceledTimeout(t *testing.T) { - t.Parallel() - const timeUnit = 500 * time.Millisecond - c, _ := WithTimeout(Background(), 2*timeUnit) - o := otherContext{c} - c, cancel := WithTimeout(o, 4*timeUnit) - cancel() - time.Sleep(1 * timeUnit) // let cancelation propagate - select { - case <-c.Done(): - default: - t.Errorf("<-c.Done() blocked, but shouldn't have") - } - if e := c.Err(); e != Canceled { - t.Errorf("c.Err() == %v want %v", e, Canceled) - } -} - -type key1 int -type key2 int - -var k1 = key1(1) -var k2 = key2(1) // same int as k1, different type -var k3 = key2(3) // same type as k2, different int - -func TestValues(t *testing.T) { - check := func(c Context, nm, v1, v2, v3 string) { - if v, ok := c.Value(k1).(string); ok == (len(v1) == 0) || v != v1 { - t.Errorf(`%s.Value(k1).(string) = %q, %t want %q, %t`, nm, v, ok, v1, len(v1) != 0) - } - if v, ok := c.Value(k2).(string); ok == (len(v2) == 0) || v != v2 { - t.Errorf(`%s.Value(k2).(string) = %q, %t want %q, %t`, nm, v, ok, v2, len(v2) != 0) - } - if v, ok := c.Value(k3).(string); ok == (len(v3) == 0) || v != v3 { - t.Errorf(`%s.Value(k3).(string) = %q, %t want %q, %t`, nm, v, ok, v3, len(v3) != 0) - } - } - - c0 := Background() - check(c0, "c0", "", "", "") - - c1 := WithValue(Background(), k1, "c1k1") - check(c1, "c1", "c1k1", "", "") - - if got, want := fmt.Sprint(c1), `context.Background.WithValue(1, "c1k1")`; got != want { - t.Errorf("c.String() = %q want %q", got, want) - } - - c2 := WithValue(c1, k2, "c2k2") - check(c2, "c2", "c1k1", "c2k2", "") - - c3 := WithValue(c2, k3, "c3k3") - check(c3, "c2", "c1k1", "c2k2", "c3k3") - - c4 := WithValue(c3, k1, nil) - check(c4, "c4", "", "c2k2", "c3k3") - - o0 := otherContext{Background()} - check(o0, "o0", "", "", "") - - o1 := otherContext{WithValue(Background(), k1, "c1k1")} - check(o1, "o1", "c1k1", "", "") - - o2 := WithValue(o1, k2, "o2k2") - check(o2, "o2", "c1k1", "o2k2", "") - - o3 := otherContext{c4} - check(o3, "o3", "", "c2k2", "c3k3") - - o4 := WithValue(o3, k3, nil) - check(o4, "o4", "", "c2k2", "") -} - -func TestAllocs(t *testing.T) { - bg := Background() - for _, test := range []struct { - desc string - f func() - limit float64 - gccgoLimit float64 - }{ - { - desc: "Background()", - f: func() { Background() }, - limit: 0, - gccgoLimit: 0, - }, - { - desc: fmt.Sprintf("WithValue(bg, %v, nil)", k1), - f: func() { - c := WithValue(bg, k1, nil) - c.Value(k1) - }, - limit: 3, - gccgoLimit: 3, - }, - { - desc: "WithTimeout(bg, 15*time.Millisecond)", - f: func() { - c, _ := WithTimeout(bg, 15*time.Millisecond) - <-c.Done() - }, - limit: 8, - gccgoLimit: 16, - }, - { - desc: "WithCancel(bg)", - f: func() { - c, cancel := WithCancel(bg) - cancel() - <-c.Done() - }, - limit: 5, - gccgoLimit: 8, - }, - { - desc: "WithTimeout(bg, 100*time.Millisecond)", - f: func() { - c, cancel := WithTimeout(bg, 100*time.Millisecond) - cancel() - <-c.Done() - }, - limit: 8, - gccgoLimit: 25, - }, - } { - limit := test.limit - if runtime.Compiler == "gccgo" { - // gccgo does not yet do escape analysis. - // TODO(iant): Remove this when gccgo does do escape analysis. - limit = test.gccgoLimit - } - if n := testing.AllocsPerRun(100, test.f); n > limit { - t.Errorf("%s allocs = %f want %d", test.desc, n, int(limit)) - } - } -} - -func TestSimultaneousCancels(t *testing.T) { - root, cancel := WithCancel(Background()) - m := map[Context]CancelFunc{root: cancel} - q := []Context{root} - // Create a tree of contexts. - for len(q) != 0 && len(m) < 100 { - parent := q[0] - q = q[1:] - for i := 0; i < 4; i++ { - ctx, cancel := WithCancel(parent) - m[ctx] = cancel - q = append(q, ctx) - } - } - // Start all the cancels in a random order. - var wg sync.WaitGroup - wg.Add(len(m)) - for _, cancel := range m { - go func(cancel CancelFunc) { - cancel() - wg.Done() - }(cancel) - } - // Wait on all the contexts in a random order. - for ctx := range m { - select { - case <-ctx.Done(): - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for <-ctx.Done(); stacks:\n%s", buf[:n]) - } - } - // Wait for all the cancel functions to return. - done := make(chan struct{}) - go func() { - wg.Wait() - close(done) - }() - select { - case <-done: - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for cancel functions; stacks:\n%s", buf[:n]) - } -} - -func TestInterlockedCancels(t *testing.T) { - parent, cancelParent := WithCancel(Background()) - child, cancelChild := WithCancel(parent) - go func() { - parent.Done() - cancelChild() - }() - cancelParent() - select { - case <-child.Done(): - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for child.Done(); stacks:\n%s", buf[:n]) - } -} - -func TestLayersCancel(t *testing.T) { - testLayers(t, time.Now().UnixNano(), false) -} - -func TestLayersTimeout(t *testing.T) { - testLayers(t, time.Now().UnixNano(), true) -} - -func testLayers(t *testing.T, seed int64, testTimeout bool) { - rand.Seed(seed) - errorf := func(format string, a ...interface{}) { - t.Errorf(fmt.Sprintf("seed=%d: %s", seed, format), a...) - } - const ( - timeout = 200 * time.Millisecond - minLayers = 30 - ) - type value int - var ( - vals []*value - cancels []CancelFunc - numTimers int - ctx = Background() - ) - for i := 0; i < minLayers || numTimers == 0 || len(cancels) == 0 || len(vals) == 0; i++ { - switch rand.Intn(3) { - case 0: - v := new(value) - ctx = WithValue(ctx, v, v) - vals = append(vals, v) - case 1: - var cancel CancelFunc - ctx, cancel = WithCancel(ctx) - cancels = append(cancels, cancel) - case 2: - var cancel CancelFunc - ctx, cancel = WithTimeout(ctx, timeout) - cancels = append(cancels, cancel) - numTimers++ - } - } - checkValues := func(when string) { - for _, key := range vals { - if val := ctx.Value(key).(*value); key != val { - errorf("%s: ctx.Value(%p) = %p want %p", when, key, val, key) - } - } - } - select { - case <-ctx.Done(): - errorf("ctx should not be canceled yet") - default: - } - if s, prefix := fmt.Sprint(ctx), "context.Background."; !strings.HasPrefix(s, prefix) { - t.Errorf("ctx.String() = %q want prefix %q", s, prefix) - } - t.Log(ctx) - checkValues("before cancel") - if testTimeout { - select { - case <-ctx.Done(): - case <-time.After(timeout + 100*time.Millisecond): - errorf("ctx should have timed out") - } - checkValues("after timeout") - } else { - cancel := cancels[rand.Intn(len(cancels))] - cancel() - select { - case <-ctx.Done(): - default: - errorf("ctx should be canceled") - } - checkValues("after cancel") - } -} - -func TestCancelRemoves(t *testing.T) { - checkChildren := func(when string, ctx Context, want int) { - if got := len(ctx.(*cancelCtx).children); got != want { - t.Errorf("%s: context has %d children, want %d", when, got, want) - } - } - - ctx, _ := WithCancel(Background()) - checkChildren("after creation", ctx, 0) - _, cancel := WithCancel(ctx) - checkChildren("with WithCancel child ", ctx, 1) - cancel() - checkChildren("after cancelling WithCancel child", ctx, 0) - - ctx, _ = WithCancel(Background()) - checkChildren("after creation", ctx, 0) - _, cancel = WithTimeout(ctx, 60*time.Minute) - checkChildren("with WithTimeout child ", ctx, 1) - cancel() - checkChildren("after cancelling WithTimeout child", ctx, 0) -} diff --git a/vendor/golang.org/x/net/context/withtimeout_test.go b/vendor/golang.org/x/net/context/withtimeout_test.go deleted file mode 100644 index e6f56691..00000000 --- a/vendor/golang.org/x/net/context/withtimeout_test.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package context_test - -import ( - "fmt" - "time" - - "golang.org/x/net/context" -) - -// This example passes a context with a timeout to tell a blocking function that -// it should abandon its work after the timeout elapses. -func ExampleWithTimeout() { - // Pass a context with a timeout to tell a blocking function that it - // should abandon its work after the timeout elapses. - ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) - defer cancel() - - select { - case <-time.After(1 * time.Second): - fmt.Println("overslept") - case <-ctx.Done(): - fmt.Println(ctx.Err()) // prints "context deadline exceeded" - } - - // Output: - // context deadline exceeded -} diff --git a/vendor/golang.org/x/sync/CONTRIBUTING.md b/vendor/golang.org/x/sync/CONTRIBUTING.md deleted file mode 100644 index 88dff59b..00000000 --- a/vendor/golang.org/x/sync/CONTRIBUTING.md +++ /dev/null @@ -1,31 +0,0 @@ -# Contributing to Go - -Go is an open source project. - -It is the work of hundreds of contributors. We appreciate your help! - - -## Filing issues - -When [filing an issue](https://golang.org/issue/new), make sure to answer these five questions: - -1. What version of Go are you using (`go version`)? -2. What operating system and processor architecture are you using? -3. What did you do? -4. What did you expect to see? -5. What did you see instead? - -General questions should go to the [golang-nuts mailing list](https://groups.google.com/group/golang-nuts) instead of the issue tracker. -The gophers there will answer or ask you to file an issue if you've tripped over a bug. - -## Contributing code - -Please read the [Contribution Guidelines](https://golang.org/doc/contribute.html) -before sending patches. - -**We do not accept GitHub pull requests** -(we use [Gerrit](https://code.google.com/p/gerrit/) instead for code review). - -Unless otherwise noted, the Go source files are distributed under -the BSD-style license found in the LICENSE file. - diff --git a/vendor/golang.org/x/sync/README b/vendor/golang.org/x/sync/README deleted file mode 100644 index 59c9dcb4..00000000 --- a/vendor/golang.org/x/sync/README +++ /dev/null @@ -1,2 +0,0 @@ -This repository provides Go concurrency primitives in addition to the -ones provided by the language and "sync" and "sync/atomic" packages. diff --git a/vendor/golang.org/x/sync/codereview.cfg b/vendor/golang.org/x/sync/codereview.cfg deleted file mode 100644 index 3f8b14b6..00000000 --- a/vendor/golang.org/x/sync/codereview.cfg +++ /dev/null @@ -1 +0,0 @@ -issuerepo: golang/go diff --git a/vendor/golang.org/x/sync/errgroup/errgroup_example_md5all_test.go b/vendor/golang.org/x/sync/errgroup/errgroup_example_md5all_test.go deleted file mode 100644 index 714b5aea..00000000 --- a/vendor/golang.org/x/sync/errgroup/errgroup_example_md5all_test.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package errgroup_test - -import ( - "crypto/md5" - "fmt" - "io/ioutil" - "log" - "os" - "path/filepath" - - "golang.org/x/net/context" - "golang.org/x/sync/errgroup" -) - -// Pipeline demonstrates the use of a Group to implement a multi-stage -// pipeline: a version of the MD5All function with bounded parallelism from -// https://blog.golang.org/pipelines. -func ExampleGroup_pipeline() { - m, err := MD5All(context.Background(), ".") - if err != nil { - log.Fatal(err) - } - - for k, sum := range m { - fmt.Printf("%s:\t%x\n", k, sum) - } -} - -type result struct { - path string - sum [md5.Size]byte -} - -// MD5All reads all the files in the file tree rooted at root and returns a map -// from file path to the MD5 sum of the file's contents. If the directory walk -// fails or any read operation fails, MD5All returns an error. -func MD5All(ctx context.Context, root string) (map[string][md5.Size]byte, error) { - // ctx is canceled when g.Wait() returns. When this version of MD5All returns - // - even in case of error! - we know that all of the goroutines have finished - // and the memory they were using can be garbage-collected. - g, ctx := errgroup.WithContext(ctx) - paths := make(chan string) - - g.Go(func() error { - defer close(paths) - return filepath.Walk(root, func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - if !info.Mode().IsRegular() { - return nil - } - select { - case paths <- path: - case <-ctx.Done(): - return ctx.Err() - } - return nil - }) - }) - - // Start a fixed number of goroutines to read and digest files. - c := make(chan result) - const numDigesters = 20 - for i := 0; i < numDigesters; i++ { - g.Go(func() error { - for path := range paths { - data, err := ioutil.ReadFile(path) - if err != nil { - return err - } - select { - case c <- result{path, md5.Sum(data)}: - case <-ctx.Done(): - return ctx.Err() - } - } - return nil - }) - } - go func() { - g.Wait() - close(c) - }() - - m := make(map[string][md5.Size]byte) - for r := range c { - m[r.path] = r.sum - } - // Check whether any of the goroutines failed. Since g is accumulating the - // errors, we don't need to send them (or check for them) in the individual - // results sent on the channel. - if err := g.Wait(); err != nil { - return nil, err - } - return m, nil -} diff --git a/vendor/golang.org/x/sync/errgroup/errgroup_test.go b/vendor/golang.org/x/sync/errgroup/errgroup_test.go deleted file mode 100644 index 6a9696ef..00000000 --- a/vendor/golang.org/x/sync/errgroup/errgroup_test.go +++ /dev/null @@ -1,176 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package errgroup_test - -import ( - "errors" - "fmt" - "net/http" - "os" - "testing" - - "golang.org/x/net/context" - "golang.org/x/sync/errgroup" -) - -var ( - Web = fakeSearch("web") - Image = fakeSearch("image") - Video = fakeSearch("video") -) - -type Result string -type Search func(ctx context.Context, query string) (Result, error) - -func fakeSearch(kind string) Search { - return func(_ context.Context, query string) (Result, error) { - return Result(fmt.Sprintf("%s result for %q", kind, query)), nil - } -} - -// JustErrors illustrates the use of a Group in place of a sync.WaitGroup to -// simplify goroutine counting and error handling. This example is derived from -// the sync.WaitGroup example at https://golang.org/pkg/sync/#example_WaitGroup. -func ExampleGroup_justErrors() { - var g errgroup.Group - var urls = []string{ - "http://www.golang.org/", - "http://www.google.com/", - "http://www.somestupidname.com/", - } - for _, url := range urls { - // Launch a goroutine to fetch the URL. - url := url // https://golang.org/doc/faq#closures_and_goroutines - g.Go(func() error { - // Fetch the URL. - resp, err := http.Get(url) - if err == nil { - resp.Body.Close() - } - return err - }) - } - // Wait for all HTTP fetches to complete. - if err := g.Wait(); err == nil { - fmt.Println("Successfully fetched all URLs.") - } -} - -// Parallel illustrates the use of a Group for synchronizing a simple parallel -// task: the "Google Search 2.0" function from -// https://talks.golang.org/2012/concurrency.slide#46, augmented with a Context -// and error-handling. -func ExampleGroup_parallel() { - Google := func(ctx context.Context, query string) ([]Result, error) { - g, ctx := errgroup.WithContext(ctx) - - searches := []Search{Web, Image, Video} - results := make([]Result, len(searches)) - for i, search := range searches { - i, search := i, search // https://golang.org/doc/faq#closures_and_goroutines - g.Go(func() error { - result, err := search(ctx, query) - if err == nil { - results[i] = result - } - return err - }) - } - if err := g.Wait(); err != nil { - return nil, err - } - return results, nil - } - - results, err := Google(context.Background(), "golang") - if err != nil { - fmt.Fprintln(os.Stderr, err) - return - } - for _, result := range results { - fmt.Println(result) - } - - // Output: - // web result for "golang" - // image result for "golang" - // video result for "golang" -} - -func TestZeroGroup(t *testing.T) { - err1 := errors.New("errgroup_test: 1") - err2 := errors.New("errgroup_test: 2") - - cases := []struct { - errs []error - }{ - {errs: []error{}}, - {errs: []error{nil}}, - {errs: []error{err1}}, - {errs: []error{err1, nil}}, - {errs: []error{err1, nil, err2}}, - } - - for _, tc := range cases { - var g errgroup.Group - - var firstErr error - for i, err := range tc.errs { - err := err - g.Go(func() error { return err }) - - if firstErr == nil && err != nil { - firstErr = err - } - - if gErr := g.Wait(); gErr != firstErr { - t.Errorf("after %T.Go(func() error { return err }) for err in %v\n"+ - "g.Wait() = %v; want %v", - g, tc.errs[:i+1], err, firstErr) - } - } - } -} - -func TestWithContext(t *testing.T) { - errDoom := errors.New("group_test: doomed") - - cases := []struct { - errs []error - want error - }{ - {want: nil}, - {errs: []error{nil}, want: nil}, - {errs: []error{errDoom}, want: errDoom}, - {errs: []error{errDoom, nil}, want: errDoom}, - } - - for _, tc := range cases { - g, ctx := errgroup.WithContext(context.Background()) - - for _, err := range tc.errs { - err := err - g.Go(func() error { return err }) - } - - if err := g.Wait(); err != tc.want { - t.Errorf("after %T.Go(func() error { return err }) for err in %v\n"+ - "g.Wait() = %v; want %v", - g, tc.errs, err, tc.want) - } - - canceled := false - select { - case <-ctx.Done(): - canceled = true - default: - } - if !canceled { - t.Errorf("after %T.Go(func() error { return err }) for err in %v\n"+ - "ctx.Done() was not closed", - g, tc.errs) - } - } -} diff --git a/vendor/golang.org/x/sys/.gitattributes b/vendor/golang.org/x/sys/.gitattributes deleted file mode 100644 index d2f212e5..00000000 --- a/vendor/golang.org/x/sys/.gitattributes +++ /dev/null @@ -1,10 +0,0 @@ -# Treat all files in this repo as binary, with no git magic updating -# line endings. Windows users contributing to Go will need to use a -# modern version of git and editors capable of LF line endings. -# -# We'll prevent accidental CRLF line endings from entering the repo -# via the git-review gofmt checks. -# -# See golang.org/issue/9281 - -* -text diff --git a/vendor/golang.org/x/sys/.gitignore b/vendor/golang.org/x/sys/.gitignore deleted file mode 100644 index 8339fd61..00000000 --- a/vendor/golang.org/x/sys/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -# Add no patterns to .hgignore except for files generated by the build. -last-change diff --git a/vendor/golang.org/x/sys/CONTRIBUTING.md b/vendor/golang.org/x/sys/CONTRIBUTING.md deleted file mode 100644 index 88dff59b..00000000 --- a/vendor/golang.org/x/sys/CONTRIBUTING.md +++ /dev/null @@ -1,31 +0,0 @@ -# Contributing to Go - -Go is an open source project. - -It is the work of hundreds of contributors. We appreciate your help! - - -## Filing issues - -When [filing an issue](https://golang.org/issue/new), make sure to answer these five questions: - -1. What version of Go are you using (`go version`)? -2. What operating system and processor architecture are you using? -3. What did you do? -4. What did you expect to see? -5. What did you see instead? - -General questions should go to the [golang-nuts mailing list](https://groups.google.com/group/golang-nuts) instead of the issue tracker. -The gophers there will answer or ask you to file an issue if you've tripped over a bug. - -## Contributing code - -Please read the [Contribution Guidelines](https://golang.org/doc/contribute.html) -before sending patches. - -**We do not accept GitHub pull requests** -(we use [Gerrit](https://code.google.com/p/gerrit/) instead for code review). - -Unless otherwise noted, the Go source files are distributed under -the BSD-style license found in the LICENSE file. - diff --git a/vendor/golang.org/x/sys/README b/vendor/golang.org/x/sys/README deleted file mode 100644 index bd422b40..00000000 --- a/vendor/golang.org/x/sys/README +++ /dev/null @@ -1,3 +0,0 @@ -This repository holds supplemental Go packages for low-level interactions with the operating system. - -To submit changes to this repository, see http://golang.org/doc/contribute.html. diff --git a/vendor/golang.org/x/sys/codereview.cfg b/vendor/golang.org/x/sys/codereview.cfg deleted file mode 100644 index 3f8b14b6..00000000 --- a/vendor/golang.org/x/sys/codereview.cfg +++ /dev/null @@ -1 +0,0 @@ -issuerepo: golang/go diff --git a/vendor/golang.org/x/sys/unix/.gitignore b/vendor/golang.org/x/sys/unix/.gitignore deleted file mode 100644 index e4827159..00000000 --- a/vendor/golang.org/x/sys/unix/.gitignore +++ /dev/null @@ -1 +0,0 @@ -_obj/ diff --git a/vendor/golang.org/x/sys/unix/README.md b/vendor/golang.org/x/sys/unix/README.md deleted file mode 100644 index bc6f6031..00000000 --- a/vendor/golang.org/x/sys/unix/README.md +++ /dev/null @@ -1,173 +0,0 @@ -# Building `sys/unix` - -The sys/unix package provides access to the raw system call interface of the -underlying operating system. See: https://godoc.org/golang.org/x/sys/unix - -Porting Go to a new architecture/OS combination or adding syscalls, types, or -constants to an existing architecture/OS pair requires some manual effort; -however, there are tools that automate much of the process. - -## Build Systems - -There are currently two ways we generate the necessary files. We are currently -migrating the build system to use containers so the builds are reproducible. -This is being done on an OS-by-OS basis. Please update this documentation as -components of the build system change. - -### Old Build System (currently for `GOOS != "Linux" || GOARCH == "sparc64"`) - -The old build system generates the Go files based on the C header files -present on your system. This means that files -for a given GOOS/GOARCH pair must be generated on a system with that OS and -architecture. This also means that the generated code can differ from system -to system, based on differences in the header files. - -To avoid this, if you are using the old build system, only generate the Go -files on an installation with unmodified header files. It is also important to -keep track of which version of the OS the files were generated from (ex. -Darwin 14 vs Darwin 15). This makes it easier to track the progress of changes -and have each OS upgrade correspond to a single change. - -To build the files for your current OS and architecture, make sure GOOS and -GOARCH are set correctly and run `mkall.sh`. This will generate the files for -your specific system. Running `mkall.sh -n` shows the commands that will be run. - -Requirements: bash, perl, go - -### New Build System (currently for `GOOS == "Linux" && GOARCH != "sparc64"`) - -The new build system uses a Docker container to generate the go files directly -from source checkouts of the kernel and various system libraries. This means -that on any platform that supports Docker, all the files using the new build -system can be generated at once, and generated files will not change based on -what the person running the scripts has installed on their computer. - -The OS specific files for the new build system are located in the `${GOOS}` -directory, and the build is coordinated by the `${GOOS}/mkall.go` program. When -the kernel or system library updates, modify the Dockerfile at -`${GOOS}/Dockerfile` to checkout the new release of the source. - -To build all the files under the new build system, you must be on an amd64/Linux -system and have your GOOS and GOARCH set accordingly. Running `mkall.sh` will -then generate all of the files for all of the GOOS/GOARCH pairs in the new build -system. Running `mkall.sh -n` shows the commands that will be run. - -Requirements: bash, perl, go, docker - -## Component files - -This section describes the various files used in the code generation process. -It also contains instructions on how to modify these files to add a new -architecture/OS or to add additional syscalls, types, or constants. Note that -if you are using the new build system, the scripts cannot be called normally. -They must be called from within the docker container. - -### asm files - -The hand-written assembly file at `asm_${GOOS}_${GOARCH}.s` implements system -call dispatch. There are three entry points: -``` - func Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr) - func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr) - func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr) -``` -The first and second are the standard ones; they differ only in how many -arguments can be passed to the kernel. The third is for low-level use by the -ForkExec wrapper. Unlike the first two, it does not call into the scheduler to -let it know that a system call is running. - -When porting Go to an new architecture/OS, this file must be implemented for -each GOOS/GOARCH pair. - -### mksysnum - -Mksysnum is a script located at `${GOOS}/mksysnum.pl` (or `mksysnum_${GOOS}.pl` -for the old system). This script takes in a list of header files containing the -syscall number declarations and parses them to produce the corresponding list of -Go numeric constants. See `zsysnum_${GOOS}_${GOARCH}.go` for the generated -constants. - -Adding new syscall numbers is mostly done by running the build on a sufficiently -new installation of the target OS (or updating the source checkouts for the -new build system). However, depending on the OS, you make need to update the -parsing in mksysnum. - -### mksyscall.pl - -The `syscall.go`, `syscall_${GOOS}.go`, `syscall_${GOOS}_${GOARCH}.go` are -hand-written Go files which implement system calls (for unix, the specific OS, -or the specific OS/Architecture pair respectively) that need special handling -and list `//sys` comments giving prototypes for ones that can be generated. - -The mksyscall.pl script takes the `//sys` and `//sysnb` comments and converts -them into syscalls. This requires the name of the prototype in the comment to -match a syscall number in the `zsysnum_${GOOS}_${GOARCH}.go` file. The function -prototype can be exported (capitalized) or not. - -Adding a new syscall often just requires adding a new `//sys` function prototype -with the desired arguments and a capitalized name so it is exported. However, if -you want the interface to the syscall to be different, often one will make an -unexported `//sys` prototype, an then write a custom wrapper in -`syscall_${GOOS}.go`. - -### types files - -For each OS, there is a hand-written Go file at `${GOOS}/types.go` (or -`types_${GOOS}.go` on the old system). This file includes standard C headers and -creates Go type aliases to the corresponding C types. The file is then fed -through godef to get the Go compatible definitions. Finally, the generated code -is fed though mkpost.go to format the code correctly and remove any hidden or -private identifiers. This cleaned-up code is written to -`ztypes_${GOOS}_${GOARCH}.go`. - -The hardest part about preparing this file is figuring out which headers to -include and which symbols need to be `#define`d to get the actual data -structures that pass through to the kernel system calls. Some C libraries -preset alternate versions for binary compatibility and translate them on the -way in and out of system calls, but there is almost always a `#define` that can -get the real ones. -See `types_darwin.go` and `linux/types.go` for examples. - -To add a new type, add in the necessary include statement at the top of the -file (if it is not already there) and add in a type alias line. Note that if -your type is significantly different on different architectures, you may need -some `#if/#elif` macros in your include statements. - -### mkerrors.sh - -This script is used to generate the system's various constants. This doesn't -just include the error numbers and error strings, but also the signal numbers -an a wide variety of miscellaneous constants. The constants come from the list -of include files in the `includes_${uname}` variable. A regex then picks out -the desired `#define` statements, and generates the corresponding Go constants. -The error numbers and strings are generated from `#include `, and the -signal numbers and strings are generated from `#include `. All of -these constants are written to `zerrors_${GOOS}_${GOARCH}.go` via a C program, -`_errors.c`, which prints out all the constants. - -To add a constant, add the header that includes it to the appropriate variable. -Then, edit the regex (if necessary) to match the desired constant. Avoid making -the regex too broad to avoid matching unintended constants. - - -## Generated files - -### `zerror_${GOOS}_${GOARCH}.go` - -A file containing all of the system's generated error numbers, error strings, -signal numbers, and constants. Generated by `mkerrors.sh` (see above). - -### `zsyscall_${GOOS}_${GOARCH}.go` - -A file containing all the generated syscalls for a specific GOOS and GOARCH. -Generated by `mksyscall.pl` (see above). - -### `zsysnum_${GOOS}_${GOARCH}.go` - -A list of numeric constants for all the syscall number of the specific GOOS -and GOARCH. Generated by mksysnum (see above). - -### `ztypes_${GOOS}_${GOARCH}.go` - -A file containing Go types for passing into (or returning from) syscalls. -Generated by godefs and the types file (see above). diff --git a/vendor/golang.org/x/sys/unix/creds_test.go b/vendor/golang.org/x/sys/unix/creds_test.go deleted file mode 100644 index 7ae33053..00000000 --- a/vendor/golang.org/x/sys/unix/creds_test.go +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build linux - -package unix_test - -import ( - "bytes" - "net" - "os" - "syscall" - "testing" - - "golang.org/x/sys/unix" -) - -// TestSCMCredentials tests the sending and receiving of credentials -// (PID, UID, GID) in an ancillary message between two UNIX -// sockets. The SO_PASSCRED socket option is enabled on the sending -// socket for this to work. -func TestSCMCredentials(t *testing.T) { - socketTypeTests := []struct { - socketType int - dataLen int - }{ - { - unix.SOCK_STREAM, - 1, - }, { - unix.SOCK_DGRAM, - 0, - }, - } - - for _, tt := range socketTypeTests { - fds, err := unix.Socketpair(unix.AF_LOCAL, tt.socketType, 0) - if err != nil { - t.Fatalf("Socketpair: %v", err) - } - defer unix.Close(fds[0]) - defer unix.Close(fds[1]) - - err = unix.SetsockoptInt(fds[0], unix.SOL_SOCKET, unix.SO_PASSCRED, 1) - if err != nil { - t.Fatalf("SetsockoptInt: %v", err) - } - - srvFile := os.NewFile(uintptr(fds[0]), "server") - defer srvFile.Close() - srv, err := net.FileConn(srvFile) - if err != nil { - t.Errorf("FileConn: %v", err) - return - } - defer srv.Close() - - cliFile := os.NewFile(uintptr(fds[1]), "client") - defer cliFile.Close() - cli, err := net.FileConn(cliFile) - if err != nil { - t.Errorf("FileConn: %v", err) - return - } - defer cli.Close() - - var ucred unix.Ucred - if os.Getuid() != 0 { - ucred.Pid = int32(os.Getpid()) - ucred.Uid = 0 - ucred.Gid = 0 - oob := unix.UnixCredentials(&ucred) - _, _, err := cli.(*net.UnixConn).WriteMsgUnix(nil, oob, nil) - if op, ok := err.(*net.OpError); ok { - err = op.Err - } - if sys, ok := err.(*os.SyscallError); ok { - err = sys.Err - } - if err != syscall.EPERM { - t.Fatalf("WriteMsgUnix failed with %v, want EPERM", err) - } - } - - ucred.Pid = int32(os.Getpid()) - ucred.Uid = uint32(os.Getuid()) - ucred.Gid = uint32(os.Getgid()) - oob := unix.UnixCredentials(&ucred) - - // On SOCK_STREAM, this is internally going to send a dummy byte - n, oobn, err := cli.(*net.UnixConn).WriteMsgUnix(nil, oob, nil) - if err != nil { - t.Fatalf("WriteMsgUnix: %v", err) - } - if n != 0 { - t.Fatalf("WriteMsgUnix n = %d, want 0", n) - } - if oobn != len(oob) { - t.Fatalf("WriteMsgUnix oobn = %d, want %d", oobn, len(oob)) - } - - oob2 := make([]byte, 10*len(oob)) - n, oobn2, flags, _, err := srv.(*net.UnixConn).ReadMsgUnix(nil, oob2) - if err != nil { - t.Fatalf("ReadMsgUnix: %v", err) - } - if flags != 0 { - t.Fatalf("ReadMsgUnix flags = 0x%x, want 0", flags) - } - if n != tt.dataLen { - t.Fatalf("ReadMsgUnix n = %d, want %d", n, tt.dataLen) - } - if oobn2 != oobn { - // without SO_PASSCRED set on the socket, ReadMsgUnix will - // return zero oob bytes - t.Fatalf("ReadMsgUnix oobn = %d, want %d", oobn2, oobn) - } - oob2 = oob2[:oobn2] - if !bytes.Equal(oob, oob2) { - t.Fatal("ReadMsgUnix oob bytes don't match") - } - - scm, err := unix.ParseSocketControlMessage(oob2) - if err != nil { - t.Fatalf("ParseSocketControlMessage: %v", err) - } - newUcred, err := unix.ParseUnixCredentials(&scm[0]) - if err != nil { - t.Fatalf("ParseUnixCredentials: %v", err) - } - if *newUcred != ucred { - t.Fatalf("ParseUnixCredentials = %+v, want %+v", newUcred, ucred) - } - } -} diff --git a/vendor/golang.org/x/sys/unix/dev_linux_test.go b/vendor/golang.org/x/sys/unix/dev_linux_test.go deleted file mode 100644 index 6e001f37..00000000 --- a/vendor/golang.org/x/sys/unix/dev_linux_test.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package unix_test - -import ( - "fmt" - "testing" - - "golang.org/x/sys/unix" -) - -func TestDevices(t *testing.T) { - testCases := []struct { - path string - major uint32 - minor uint32 - }{ - // well known major/minor numbers according to - // https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/Documentation/admin-guide/devices.txt - {"/dev/null", 1, 3}, - {"/dev/zero", 1, 5}, - {"/dev/random", 1, 8}, - {"/dev/full", 1, 7}, - {"/dev/urandom", 1, 9}, - {"/dev/tty", 5, 0}, - } - for _, tc := range testCases { - t.Run(fmt.Sprintf("%s %v:%v", tc.path, tc.major, tc.minor), func(t *testing.T) { - var stat unix.Stat_t - err := unix.Stat(tc.path, &stat) - if err != nil { - t.Errorf("failed to stat device: %v", err) - return - } - - dev := uint64(stat.Rdev) - if unix.Major(dev) != tc.major { - t.Errorf("for %s Major(%#x) == %d, want %d", tc.path, dev, unix.Major(dev), tc.major) - } - if unix.Minor(dev) != tc.minor { - t.Errorf("for %s Minor(%#x) == %d, want %d", tc.path, dev, unix.Minor(dev), tc.minor) - } - if unix.Mkdev(tc.major, tc.minor) != dev { - t.Errorf("for %s Mkdev(%d, %d) == %#x, want %#x", tc.path, tc.major, tc.minor, unix.Mkdev(tc.major, tc.minor), dev) - } - }) - - } -} diff --git a/vendor/golang.org/x/sys/unix/export_test.go b/vendor/golang.org/x/sys/unix/export_test.go deleted file mode 100644 index b4fdd970..00000000 --- a/vendor/golang.org/x/sys/unix/export_test.go +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd linux netbsd openbsd solaris - -package unix - -var Itoa = itoa diff --git a/vendor/golang.org/x/sys/unix/mkall.sh b/vendor/golang.org/x/sys/unix/mkall.sh deleted file mode 100755 index c3a08092..00000000 --- a/vendor/golang.org/x/sys/unix/mkall.sh +++ /dev/null @@ -1,197 +0,0 @@ -#!/usr/bin/env bash -# Copyright 2009 The Go Authors. All rights reserved. -# Use of this source code is governed by a BSD-style -# license that can be found in the LICENSE file. - -# This script runs or (given -n) prints suggested commands to generate files for -# the Architecture/OS specified by the GOARCH and GOOS environment variables. -# See README.md for more information about how the build system works. - -GOOSARCH="${GOOS}_${GOARCH}" - -# defaults -mksyscall="./mksyscall.pl" -mkerrors="./mkerrors.sh" -zerrors="zerrors_$GOOSARCH.go" -mksysctl="" -zsysctl="zsysctl_$GOOSARCH.go" -mksysnum= -mktypes= -run="sh" -cmd="" - -case "$1" in --syscalls) - for i in zsyscall*go - do - # Run the command line that appears in the first line - # of the generated file to regenerate it. - sed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i - rm _$i - done - exit 0 - ;; --n) - run="cat" - cmd="echo" - shift -esac - -case "$#" in -0) - ;; -*) - echo 'usage: mkall.sh [-n]' 1>&2 - exit 2 -esac - -if [[ "$GOOS" = "linux" ]] && [[ "$GOARCH" != "sparc64" ]]; then - # Use then new build system - # Files generated through docker (use $cmd so you can Ctl-C the build or run) - $cmd docker build --tag generate:$GOOS $GOOS - $cmd docker run --interactive --tty --volume $(dirname "$(readlink -f "$0")"):/build generate:$GOOS - exit -fi - -GOOSARCH_in=syscall_$GOOSARCH.go -case "$GOOSARCH" in -_* | *_ | _) - echo 'undefined $GOOS_$GOARCH:' "$GOOSARCH" 1>&2 - exit 1 - ;; -darwin_386) - mkerrors="$mkerrors -m32" - mksyscall="./mksyscall.pl -l32" - mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -darwin_amd64) - mkerrors="$mkerrors -m64" - mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -darwin_arm) - mkerrors="$mkerrors" - mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -darwin_arm64) - mkerrors="$mkerrors -m64" - mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -dragonfly_386) - mkerrors="$mkerrors -m32" - mksyscall="./mksyscall.pl -l32 -dragonfly" - mksysnum="curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -dragonfly_amd64) - mkerrors="$mkerrors -m64" - mksyscall="./mksyscall.pl -dragonfly" - mksysnum="curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -freebsd_386) - mkerrors="$mkerrors -m32" - mksyscall="./mksyscall.pl -l32" - mksysnum="curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -freebsd_amd64) - mkerrors="$mkerrors -m64" - mksysnum="curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -freebsd_arm) - mkerrors="$mkerrors" - mksyscall="./mksyscall.pl -l32 -arm" - mksysnum="curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl" - # Let the type of C char be signed for making the bare syscall - # API consistent across platforms. - mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" - ;; -linux_sparc64) - GOOSARCH_in=syscall_linux_sparc64.go - unistd_h=/usr/include/sparc64-linux-gnu/asm/unistd.h - mkerrors="$mkerrors -m64" - mksysnum="./mksysnum_linux.pl $unistd_h" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -netbsd_386) - mkerrors="$mkerrors -m32" - mksyscall="./mksyscall.pl -l32 -netbsd" - mksysnum="curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -netbsd_amd64) - mkerrors="$mkerrors -m64" - mksyscall="./mksyscall.pl -netbsd" - mksysnum="curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -netbsd_arm) - mkerrors="$mkerrors" - mksyscall="./mksyscall.pl -l32 -netbsd -arm" - mksysnum="curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl" - # Let the type of C char be signed for making the bare syscall - # API consistent across platforms. - mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" - ;; -openbsd_386) - mkerrors="$mkerrors -m32" - mksyscall="./mksyscall.pl -l32 -openbsd" - mksysctl="./mksysctl_openbsd.pl" - zsysctl="zsysctl_openbsd.go" - mksysnum="curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -openbsd_amd64) - mkerrors="$mkerrors -m64" - mksyscall="./mksyscall.pl -openbsd" - mksysctl="./mksysctl_openbsd.pl" - zsysctl="zsysctl_openbsd.go" - mksysnum="curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -openbsd_arm) - mkerrors="$mkerrors" - mksyscall="./mksyscall.pl -l32 -openbsd -arm" - mksysctl="./mksysctl_openbsd.pl" - zsysctl="zsysctl_openbsd.go" - mksysnum="curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl" - # Let the type of C char be signed for making the bare syscall - # API consistent across platforms. - mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" - ;; -solaris_amd64) - mksyscall="./mksyscall_solaris.pl" - mkerrors="$mkerrors -m64" - mksysnum= - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -*) - echo 'unrecognized $GOOS_$GOARCH: ' "$GOOSARCH" 1>&2 - exit 1 - ;; -esac - -( - if [ -n "$mkerrors" ]; then echo "$mkerrors |gofmt >$zerrors"; fi - case "$GOOS" in - *) - syscall_goos="syscall_$GOOS.go" - case "$GOOS" in - darwin | dragonfly | freebsd | netbsd | openbsd) - syscall_goos="syscall_bsd.go $syscall_goos" - ;; - esac - if [ -n "$mksyscall" ]; then echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go"; fi - ;; - esac - if [ -n "$mksysctl" ]; then echo "$mksysctl |gofmt >$zsysctl"; fi - if [ -n "$mksysnum" ]; then echo "$mksysnum |gofmt >zsysnum_$GOOSARCH.go"; fi - if [ -n "$mktypes" ]; then - echo "$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go"; - fi -) | $run diff --git a/vendor/golang.org/x/sys/unix/mkerrors.sh b/vendor/golang.org/x/sys/unix/mkerrors.sh deleted file mode 100755 index 2c434f7a..00000000 --- a/vendor/golang.org/x/sys/unix/mkerrors.sh +++ /dev/null @@ -1,563 +0,0 @@ -#!/usr/bin/env bash -# Copyright 2009 The Go Authors. All rights reserved. -# Use of this source code is governed by a BSD-style -# license that can be found in the LICENSE file. - -# Generate Go code listing errors and other #defined constant -# values (ENAMETOOLONG etc.), by asking the preprocessor -# about the definitions. - -unset LANG -export LC_ALL=C -export LC_CTYPE=C - -if test -z "$GOARCH" -o -z "$GOOS"; then - echo 1>&2 "GOARCH or GOOS not defined in environment" - exit 1 -fi - -# Check that we are using the new build system if we should -if [[ "$GOOS" -eq "linux" ]] && [[ "$GOARCH" != "sparc64" ]]; then - if [[ "$GOLANG_SYS_BUILD" -ne "docker" ]]; then - echo 1>&2 "In the new build system, mkerrors should not be called directly." - echo 1>&2 "See README.md" - exit 1 - fi -fi - -CC=${CC:-cc} - -if [[ "$GOOS" -eq "solaris" ]]; then - # Assumes GNU versions of utilities in PATH. - export PATH=/usr/gnu/bin:$PATH -fi - -uname=$(uname) - -includes_Darwin=' -#define _DARWIN_C_SOURCE -#define KERNEL -#define _DARWIN_USE_64_BIT_INODE -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -' - -includes_DragonFly=' -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -' - -includes_FreeBSD=' -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if __FreeBSD__ >= 10 -#define IFT_CARP 0xf8 // IFT_CARP is deprecated in FreeBSD 10 -#undef SIOCAIFADDR -#define SIOCAIFADDR _IOW(105, 26, struct oifaliasreq) // ifaliasreq contains if_data -#undef SIOCSIFPHYADDR -#define SIOCSIFPHYADDR _IOW(105, 70, struct oifaliasreq) // ifaliasreq contains if_data -#endif -' - -includes_Linux=' -#define _LARGEFILE_SOURCE -#define _LARGEFILE64_SOURCE -#ifndef __LP64__ -#define _FILE_OFFSET_BITS 64 -#endif -#define _GNU_SOURCE - -// is broken on powerpc64, as it fails to include definitions of -// these structures. We just include them copied from . -#if defined(__powerpc__) -struct sgttyb { - char sg_ispeed; - char sg_ospeed; - char sg_erase; - char sg_kill; - short sg_flags; -}; - -struct tchars { - char t_intrc; - char t_quitc; - char t_startc; - char t_stopc; - char t_eofc; - char t_brkc; -}; - -struct ltchars { - char t_suspc; - char t_dsuspc; - char t_rprntc; - char t_flushc; - char t_werasc; - char t_lnextc; -}; -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef MSG_FASTOPEN -#define MSG_FASTOPEN 0x20000000 -#endif - -#ifndef PTRACE_GETREGS -#define PTRACE_GETREGS 0xc -#endif - -#ifndef PTRACE_SETREGS -#define PTRACE_SETREGS 0xd -#endif - -#ifndef SOL_NETLINK -#define SOL_NETLINK 270 -#endif - -#ifdef SOL_BLUETOOTH -// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h -// but it is already in bluetooth_linux.go -#undef SOL_BLUETOOTH -#endif - -// Certain constants are missing from the fs/crypto UAPI -#define FS_KEY_DESC_PREFIX "fscrypt:" -#define FS_KEY_DESC_PREFIX_SIZE 8 -#define FS_MAX_KEY_SIZE 64 -' - -includes_NetBSD=' -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// Needed since refers to it... -#define schedppq 1 -' - -includes_OpenBSD=' -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// We keep some constants not supported in OpenBSD 5.5 and beyond for -// the promise of compatibility. -#define EMUL_ENABLED 0x1 -#define EMUL_NATIVE 0x2 -#define IPV6_FAITH 0x1d -#define IPV6_OPTIONS 0x1 -#define IPV6_RTHDR_STRICT 0x1 -#define IPV6_SOCKOPT_RESERVED1 0x3 -#define SIOCGIFGENERIC 0xc020693a -#define SIOCSIFGENERIC 0x80206939 -#define WALTSIG 0x4 -' - -includes_SunOS=' -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -' - - -includes=' -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -' -ccflags="$@" - -# Write go tool cgo -godefs input. -( - echo package unix - echo - echo '/*' - indirect="includes_$(uname)" - echo "${!indirect} $includes" - echo '*/' - echo 'import "C"' - echo 'import "syscall"' - echo - echo 'const (' - - # The gcc command line prints all the #defines - # it encounters while processing the input - echo "${!indirect} $includes" | $CC -x c - -E -dM $ccflags | - awk ' - $1 != "#define" || $2 ~ /\(/ || $3 == "" {next} - - $2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next} # 386 registers - $2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next} - $2 ~ /^(SCM_SRCRT)$/ {next} - $2 ~ /^(MAP_FAILED)$/ {next} - $2 ~ /^ELF_.*$/ {next}# contains ELF_ARCH, etc. - - $2 ~ /^EXTATTR_NAMESPACE_NAMES/ || - $2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next} - - $2 !~ /^ETH_/ && - $2 !~ /^EPROC_/ && - $2 !~ /^EQUIV_/ && - $2 !~ /^EXPR_/ && - $2 ~ /^E[A-Z0-9_]+$/ || - $2 ~ /^B[0-9_]+$/ || - $2 == "BOTHER" || - $2 ~ /^CI?BAUD(EX)?$/ || - $2 == "IBSHIFT" || - $2 ~ /^V[A-Z0-9]+$/ || - $2 ~ /^CS[A-Z0-9]/ || - $2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ || - $2 ~ /^IGN/ || - $2 ~ /^IX(ON|ANY|OFF)$/ || - $2 ~ /^IN(LCR|PCK)$/ || - $2 ~ /(^FLU?SH)|(FLU?SH$)/ || - $2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ || - $2 == "BRKINT" || - $2 == "HUPCL" || - $2 == "PENDIN" || - $2 == "TOSTOP" || - $2 == "XCASE" || - $2 == "ALTWERASE" || - $2 == "NOKERNINFO" || - $2 ~ /^PAR/ || - $2 ~ /^SIG[^_]/ || - $2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ || - $2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ || - $2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ || - $2 ~ /^O?XTABS$/ || - $2 ~ /^TC[IO](ON|OFF)$/ || - $2 ~ /^IN_/ || - $2 ~ /^LOCK_(SH|EX|NB|UN)$/ || - $2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ || - $2 ~ /^FALLOC_/ || - $2 == "ICMPV6_FILTER" || - $2 == "SOMAXCONN" || - $2 == "NAME_MAX" || - $2 == "IFNAMSIZ" || - $2 ~ /^CTL_(MAXNAME|NET|QUERY)$/ || - $2 ~ /^SYSCTL_VERS/ || - $2 ~ /^(MS|MNT|UMOUNT)_/ || - $2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ || - $2 ~ /^(O|F|E?FD|NAME|S|PTRACE|PT)_/ || - $2 ~ /^LINUX_REBOOT_CMD_/ || - $2 ~ /^LINUX_REBOOT_MAGIC[12]$/ || - $2 !~ "NLA_TYPE_MASK" && - $2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ || - $2 ~ /^SIOC/ || - $2 ~ /^TIOC/ || - $2 ~ /^TCGET/ || - $2 ~ /^TCSET/ || - $2 ~ /^TC(FLSH|SBRKP?|XONC)$/ || - $2 !~ "RTF_BITS" && - $2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ || - $2 ~ /^BIOC/ || - $2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ || - $2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ || - $2 ~ /^PRIO_(PROCESS|PGRP|USER)/ || - $2 ~ /^CLONE_[A-Z_]+/ || - $2 !~ /^(BPF_TIMEVAL)$/ && - $2 ~ /^(BPF|DLT)_/ || - $2 ~ /^CLOCK_/ || - $2 ~ /^CAN_/ || - $2 ~ /^CAP_/ || - $2 ~ /^ALG_/ || - $2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE|IOC_(GET|SET)_ENCRYPTION)/ || - $2 ~ /^GRND_/ || - $2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ || - $2 ~ /^KEYCTL_/ || - $2 ~ /^PERF_EVENT_IOC_/ || - $2 ~ /^SECCOMP_MODE_/ || - $2 ~ /^SPLICE_/ || - $2 ~ /^(VM|VMADDR)_/ || - $2 ~ /^(TASKSTATS|TS)_/ || - $2 ~ /^GENL_/ || - $2 ~ /^XATTR_(CREATE|REPLACE)/ || - $2 !~ "WMESGLEN" && - $2 ~ /^W[A-Z0-9]+$/ || - $2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf("\t%s = C.%s\n", $2, $2)} - $2 ~ /^__WCOREFLAG$/ {next} - $2 ~ /^__W[A-Z0-9]+$/ {printf("\t%s = C.%s\n", substr($2,3), $2)} - - {next} - ' | sort - - echo ')' -) >_const.go - -# Pull out the error names for later. -errors=$( - echo '#include ' | $CC -x c - -E -dM $ccflags | - awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' | - sort -) - -# Pull out the signal names for later. -signals=$( - echo '#include ' | $CC -x c - -E -dM $ccflags | - awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' | - egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' | - sort -) - -# Again, writing regexps to a file. -echo '#include ' | $CC -x c - -E -dM $ccflags | - awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print "^\t" $2 "[ \t]*=" }' | - sort >_error.grep -echo '#include ' | $CC -x c - -E -dM $ccflags | - awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print "^\t" $2 "[ \t]*=" }' | - egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' | - sort >_signal.grep - -echo '// mkerrors.sh' "$@" -echo '// Code generated by the command above; see README.md. DO NOT EDIT.' -echo -echo "// +build ${GOARCH},${GOOS}" -echo -go tool cgo -godefs -- "$@" _const.go >_error.out -cat _error.out | grep -vf _error.grep | grep -vf _signal.grep -echo -echo '// Errors' -echo 'const (' -cat _error.out | grep -f _error.grep | sed 's/=\(.*\)/= syscall.Errno(\1)/' -echo ')' - -echo -echo '// Signals' -echo 'const (' -cat _error.out | grep -f _signal.grep | sed 's/=\(.*\)/= syscall.Signal(\1)/' -echo ')' - -# Run C program to print error and syscall strings. -( - echo -E " -#include -#include -#include -#include -#include -#include - -#define nelem(x) (sizeof(x)/sizeof((x)[0])) - -enum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below - -int errors[] = { -" - for i in $errors - do - echo -E ' '$i, - done - - echo -E " -}; - -int signals[] = { -" - for i in $signals - do - echo -E ' '$i, - done - - # Use -E because on some systems bash builtin interprets \n itself. - echo -E ' -}; - -static int -intcmp(const void *a, const void *b) -{ - return *(int*)a - *(int*)b; -} - -int -main(void) -{ - int i, e; - char buf[1024], *p; - - printf("\n\n// Error table\n"); - printf("var errors = [...]string {\n"); - qsort(errors, nelem(errors), sizeof errors[0], intcmp); - for(i=0; i 0 && errors[i-1] == e) - continue; - strcpy(buf, strerror(e)); - // lowercase first letter: Bad -> bad, but STREAM -> STREAM. - if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z) - buf[0] += a - A; - printf("\t%d: \"%s\",\n", e, buf); - } - printf("}\n\n"); - - printf("\n\n// Signal table\n"); - printf("var signals = [...]string {\n"); - qsort(signals, nelem(signals), sizeof signals[0], intcmp); - for(i=0; i 0 && signals[i-1] == e) - continue; - strcpy(buf, strsignal(e)); - // lowercase first letter: Bad -> bad, but STREAM -> STREAM. - if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z) - buf[0] += a - A; - // cut trailing : number. - p = strrchr(buf, ":"[0]); - if(p) - *p = '\0'; - printf("\t%d: \"%s\",\n", e, buf); - } - printf("}\n\n"); - - return 0; -} - -' -) >_errors.c - -$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out diff --git a/vendor/golang.org/x/sys/unix/mksyscall.pl b/vendor/golang.org/x/sys/unix/mksyscall.pl deleted file mode 100755 index fb929b4c..00000000 --- a/vendor/golang.org/x/sys/unix/mksyscall.pl +++ /dev/null @@ -1,328 +0,0 @@ -#!/usr/bin/env perl -# Copyright 2009 The Go Authors. All rights reserved. -# Use of this source code is governed by a BSD-style -# license that can be found in the LICENSE file. - -# This program reads a file containing function prototypes -# (like syscall_darwin.go) and generates system call bodies. -# The prototypes are marked by lines beginning with "//sys" -# and read like func declarations if //sys is replaced by func, but: -# * The parameter lists must give a name for each argument. -# This includes return parameters. -# * The parameter lists must give a type for each argument: -# the (x, y, z int) shorthand is not allowed. -# * If the return parameter is an error number, it must be named errno. - -# A line beginning with //sysnb is like //sys, except that the -# goroutine will not be suspended during the execution of the system -# call. This must only be used for system calls which can never -# block, as otherwise the system call could cause all goroutines to -# hang. - -use strict; - -my $cmdline = "mksyscall.pl " . join(' ', @ARGV); -my $errors = 0; -my $_32bit = ""; -my $plan9 = 0; -my $openbsd = 0; -my $netbsd = 0; -my $dragonfly = 0; -my $arm = 0; # 64-bit value should use (even, odd)-pair -my $tags = ""; # build tags - -if($ARGV[0] eq "-b32") { - $_32bit = "big-endian"; - shift; -} elsif($ARGV[0] eq "-l32") { - $_32bit = "little-endian"; - shift; -} -if($ARGV[0] eq "-plan9") { - $plan9 = 1; - shift; -} -if($ARGV[0] eq "-openbsd") { - $openbsd = 1; - shift; -} -if($ARGV[0] eq "-netbsd") { - $netbsd = 1; - shift; -} -if($ARGV[0] eq "-dragonfly") { - $dragonfly = 1; - shift; -} -if($ARGV[0] eq "-arm") { - $arm = 1; - shift; -} -if($ARGV[0] eq "-tags") { - shift; - $tags = $ARGV[0]; - shift; -} - -if($ARGV[0] =~ /^-/) { - print STDERR "usage: mksyscall.pl [-b32 | -l32] [-tags x,y] [file ...]\n"; - exit 1; -} - -# Check that we are using the new build system if we should -if($ENV{'GOOS'} eq "linux" && $ENV{'GOARCH'} ne "sparc64") { - if($ENV{'GOLANG_SYS_BUILD'} ne "docker") { - print STDERR "In the new build system, mksyscall should not be called directly.\n"; - print STDERR "See README.md\n"; - exit 1; - } -} - - -sub parseparamlist($) { - my ($list) = @_; - $list =~ s/^\s*//; - $list =~ s/\s*$//; - if($list eq "") { - return (); - } - return split(/\s*,\s*/, $list); -} - -sub parseparam($) { - my ($p) = @_; - if($p !~ /^(\S*) (\S*)$/) { - print STDERR "$ARGV:$.: malformed parameter: $p\n"; - $errors = 1; - return ("xx", "int"); - } - return ($1, $2); -} - -my $text = ""; -while(<>) { - chomp; - s/\s+/ /g; - s/^\s+//; - s/\s+$//; - my $nonblock = /^\/\/sysnb /; - next if !/^\/\/sys / && !$nonblock; - - # Line must be of the form - # func Open(path string, mode int, perm int) (fd int, errno error) - # Split into name, in params, out params. - if(!/^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*((?i)SYS_[A-Z0-9_]+))?$/) { - print STDERR "$ARGV:$.: malformed //sys declaration\n"; - $errors = 1; - next; - } - my ($func, $in, $out, $sysname) = ($2, $3, $4, $5); - - # Split argument lists on comma. - my @in = parseparamlist($in); - my @out = parseparamlist($out); - - # Try in vain to keep people from editing this file. - # The theory is that they jump into the middle of the file - # without reading the header. - $text .= "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n"; - - # Go function header. - my $out_decl = @out ? sprintf(" (%s)", join(', ', @out)) : ""; - $text .= sprintf "func %s(%s)%s {\n", $func, join(', ', @in), $out_decl; - - # Check if err return available - my $errvar = ""; - foreach my $p (@out) { - my ($name, $type) = parseparam($p); - if($type eq "error") { - $errvar = $name; - last; - } - } - - # Prepare arguments to Syscall. - my @args = (); - my $n = 0; - foreach my $p (@in) { - my ($name, $type) = parseparam($p); - if($type =~ /^\*/) { - push @args, "uintptr(unsafe.Pointer($name))"; - } elsif($type eq "string" && $errvar ne "") { - $text .= "\tvar _p$n *byte\n"; - $text .= "\t_p$n, $errvar = BytePtrFromString($name)\n"; - $text .= "\tif $errvar != nil {\n\t\treturn\n\t}\n"; - push @args, "uintptr(unsafe.Pointer(_p$n))"; - $n++; - } elsif($type eq "string") { - print STDERR "$ARGV:$.: $func uses string arguments, but has no error return\n"; - $text .= "\tvar _p$n *byte\n"; - $text .= "\t_p$n, _ = BytePtrFromString($name)\n"; - push @args, "uintptr(unsafe.Pointer(_p$n))"; - $n++; - } elsif($type =~ /^\[\](.*)/) { - # Convert slice into pointer, length. - # Have to be careful not to take address of &a[0] if len == 0: - # pass dummy pointer in that case. - # Used to pass nil, but some OSes or simulators reject write(fd, nil, 0). - $text .= "\tvar _p$n unsafe.Pointer\n"; - $text .= "\tif len($name) > 0 {\n\t\t_p$n = unsafe.Pointer(\&${name}[0])\n\t}"; - $text .= " else {\n\t\t_p$n = unsafe.Pointer(&_zero)\n\t}"; - $text .= "\n"; - push @args, "uintptr(_p$n)", "uintptr(len($name))"; - $n++; - } elsif($type eq "int64" && ($openbsd || $netbsd)) { - push @args, "0"; - if($_32bit eq "big-endian") { - push @args, "uintptr($name>>32)", "uintptr($name)"; - } elsif($_32bit eq "little-endian") { - push @args, "uintptr($name)", "uintptr($name>>32)"; - } else { - push @args, "uintptr($name)"; - } - } elsif($type eq "int64" && $dragonfly) { - if ($func !~ /^extp(read|write)/i) { - push @args, "0"; - } - if($_32bit eq "big-endian") { - push @args, "uintptr($name>>32)", "uintptr($name)"; - } elsif($_32bit eq "little-endian") { - push @args, "uintptr($name)", "uintptr($name>>32)"; - } else { - push @args, "uintptr($name)"; - } - } elsif($type eq "int64" && $_32bit ne "") { - if(@args % 2 && $arm) { - # arm abi specifies 64-bit argument uses - # (even, odd) pair - push @args, "0" - } - if($_32bit eq "big-endian") { - push @args, "uintptr($name>>32)", "uintptr($name)"; - } else { - push @args, "uintptr($name)", "uintptr($name>>32)"; - } - } else { - push @args, "uintptr($name)"; - } - } - - # Determine which form to use; pad args with zeros. - my $asm = "Syscall"; - if ($nonblock) { - $asm = "RawSyscall"; - } - if(@args <= 3) { - while(@args < 3) { - push @args, "0"; - } - } elsif(@args <= 6) { - $asm .= "6"; - while(@args < 6) { - push @args, "0"; - } - } elsif(@args <= 9) { - $asm .= "9"; - while(@args < 9) { - push @args, "0"; - } - } else { - print STDERR "$ARGV:$.: too many arguments to system call\n"; - } - - # System call number. - if($sysname eq "") { - $sysname = "SYS_$func"; - $sysname =~ s/([a-z])([A-Z])/${1}_$2/g; # turn FooBar into Foo_Bar - $sysname =~ y/a-z/A-Z/; - } - - # Actual call. - my $args = join(', ', @args); - my $call = "$asm($sysname, $args)"; - - # Assign return values. - my $body = ""; - my @ret = ("_", "_", "_"); - my $do_errno = 0; - for(my $i=0; $i<@out; $i++) { - my $p = $out[$i]; - my ($name, $type) = parseparam($p); - my $reg = ""; - if($name eq "err" && !$plan9) { - $reg = "e1"; - $ret[2] = $reg; - $do_errno = 1; - } elsif($name eq "err" && $plan9) { - $ret[0] = "r0"; - $ret[2] = "e1"; - next; - } else { - $reg = sprintf("r%d", $i); - $ret[$i] = $reg; - } - if($type eq "bool") { - $reg = "$reg != 0"; - } - if($type eq "int64" && $_32bit ne "") { - # 64-bit number in r1:r0 or r0:r1. - if($i+2 > @out) { - print STDERR "$ARGV:$.: not enough registers for int64 return\n"; - } - if($_32bit eq "big-endian") { - $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i, $i+1); - } else { - $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i+1, $i); - } - $ret[$i] = sprintf("r%d", $i); - $ret[$i+1] = sprintf("r%d", $i+1); - } - if($reg ne "e1" || $plan9) { - $body .= "\t$name = $type($reg)\n"; - } - } - if ($ret[0] eq "_" && $ret[1] eq "_" && $ret[2] eq "_") { - $text .= "\t$call\n"; - } else { - $text .= "\t$ret[0], $ret[1], $ret[2] := $call\n"; - } - $text .= $body; - - if ($plan9 && $ret[2] eq "e1") { - $text .= "\tif int32(r0) == -1 {\n"; - $text .= "\t\terr = e1\n"; - $text .= "\t}\n"; - } elsif ($do_errno) { - $text .= "\tif e1 != 0 {\n"; - $text .= "\t\terr = errnoErr(e1)\n"; - $text .= "\t}\n"; - } - $text .= "\treturn\n"; - $text .= "}\n\n"; -} - -chomp $text; -chomp $text; - -if($errors) { - exit 1; -} - -print <) { - chomp; - s/\s+/ /g; - s/^\s+//; - s/\s+$//; - $package = $1 if !$package && /^package (\S+)$/; - my $nonblock = /^\/\/sysnb /; - next if !/^\/\/sys / && !$nonblock; - - # Line must be of the form - # func Open(path string, mode int, perm int) (fd int, err error) - # Split into name, in params, out params. - if(!/^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*(?:(\w*)\.)?(\w*))?$/) { - print STDERR "$ARGV:$.: malformed //sys declaration\n"; - $errors = 1; - next; - } - my ($nb, $func, $in, $out, $modname, $sysname) = ($1, $2, $3, $4, $5, $6); - - # Split argument lists on comma. - my @in = parseparamlist($in); - my @out = parseparamlist($out); - - # So file name. - if($modname eq "") { - $modname = "libc"; - } - - # System call name. - if($sysname eq "") { - $sysname = "$func"; - } - - # System call pointer variable name. - my $sysvarname = "proc$sysname"; - - my $strconvfunc = "BytePtrFromString"; - my $strconvtype = "*byte"; - - $sysname =~ y/A-Z/a-z/; # All libc functions are lowercase. - - # Runtime import of function to allow cross-platform builds. - $dynimports .= "//go:cgo_import_dynamic libc_${sysname} ${sysname} \"$modname.so\"\n"; - # Link symbol to proc address variable. - $linknames .= "//go:linkname ${sysvarname} libc_${sysname}\n"; - # Library proc address variable. - push @vars, $sysvarname; - - # Go function header. - $out = join(', ', @out); - if($out ne "") { - $out = " ($out)"; - } - if($text ne "") { - $text .= "\n" - } - $text .= sprintf "func %s(%s)%s {\n", $func, join(', ', @in), $out; - - # Check if err return available - my $errvar = ""; - foreach my $p (@out) { - my ($name, $type) = parseparam($p); - if($type eq "error") { - $errvar = $name; - last; - } - } - - # Prepare arguments to Syscall. - my @args = (); - my $n = 0; - foreach my $p (@in) { - my ($name, $type) = parseparam($p); - if($type =~ /^\*/) { - push @args, "uintptr(unsafe.Pointer($name))"; - } elsif($type eq "string" && $errvar ne "") { - $text .= "\tvar _p$n $strconvtype\n"; - $text .= "\t_p$n, $errvar = $strconvfunc($name)\n"; - $text .= "\tif $errvar != nil {\n\t\treturn\n\t}\n"; - push @args, "uintptr(unsafe.Pointer(_p$n))"; - $n++; - } elsif($type eq "string") { - print STDERR "$ARGV:$.: $func uses string arguments, but has no error return\n"; - $text .= "\tvar _p$n $strconvtype\n"; - $text .= "\t_p$n, _ = $strconvfunc($name)\n"; - push @args, "uintptr(unsafe.Pointer(_p$n))"; - $n++; - } elsif($type =~ /^\[\](.*)/) { - # Convert slice into pointer, length. - # Have to be careful not to take address of &a[0] if len == 0: - # pass nil in that case. - $text .= "\tvar _p$n *$1\n"; - $text .= "\tif len($name) > 0 {\n\t\t_p$n = \&$name\[0]\n\t}\n"; - push @args, "uintptr(unsafe.Pointer(_p$n))", "uintptr(len($name))"; - $n++; - } elsif($type eq "int64" && $_32bit ne "") { - if($_32bit eq "big-endian") { - push @args, "uintptr($name >> 32)", "uintptr($name)"; - } else { - push @args, "uintptr($name)", "uintptr($name >> 32)"; - } - } elsif($type eq "bool") { - $text .= "\tvar _p$n uint32\n"; - $text .= "\tif $name {\n\t\t_p$n = 1\n\t} else {\n\t\t_p$n = 0\n\t}\n"; - push @args, "uintptr(_p$n)"; - $n++; - } else { - push @args, "uintptr($name)"; - } - } - my $nargs = @args; - - # Determine which form to use; pad args with zeros. - my $asm = "sysvicall6"; - if ($nonblock) { - $asm = "rawSysvicall6"; - } - if(@args <= 6) { - while(@args < 6) { - push @args, "0"; - } - } else { - print STDERR "$ARGV:$.: too many arguments to system call\n"; - } - - # Actual call. - my $args = join(', ', @args); - my $call = "$asm(uintptr(unsafe.Pointer(&$sysvarname)), $nargs, $args)"; - - # Assign return values. - my $body = ""; - my $failexpr = ""; - my @ret = ("_", "_", "_"); - my @pout= (); - my $do_errno = 0; - for(my $i=0; $i<@out; $i++) { - my $p = $out[$i]; - my ($name, $type) = parseparam($p); - my $reg = ""; - if($name eq "err") { - $reg = "e1"; - $ret[2] = $reg; - $do_errno = 1; - } else { - $reg = sprintf("r%d", $i); - $ret[$i] = $reg; - } - if($type eq "bool") { - $reg = "$reg != 0"; - } - if($type eq "int64" && $_32bit ne "") { - # 64-bit number in r1:r0 or r0:r1. - if($i+2 > @out) { - print STDERR "$ARGV:$.: not enough registers for int64 return\n"; - } - if($_32bit eq "big-endian") { - $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i, $i+1); - } else { - $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i+1, $i); - } - $ret[$i] = sprintf("r%d", $i); - $ret[$i+1] = sprintf("r%d", $i+1); - } - if($reg ne "e1") { - $body .= "\t$name = $type($reg)\n"; - } - } - if ($ret[0] eq "_" && $ret[1] eq "_" && $ret[2] eq "_") { - $text .= "\t$call\n"; - } else { - $text .= "\t$ret[0], $ret[1], $ret[2] := $call\n"; - } - $text .= $body; - - if ($do_errno) { - $text .= "\tif e1 != 0 {\n"; - $text .= "\t\terr = e1\n"; - $text .= "\t}\n"; - } - $text .= "\treturn\n"; - $text .= "}\n"; -} - -if($errors) { - exit 1; -} - -print < "net.inet", - "net.inet.ipproto" => "net.inet", - "net.inet6.ipv6proto" => "net.inet6", - "net.inet6.ipv6" => "net.inet6.ip6", - "net.inet.icmpv6" => "net.inet6.icmp6", - "net.inet6.divert6" => "net.inet6.divert", - "net.inet6.tcp6" => "net.inet.tcp", - "net.inet6.udp6" => "net.inet.udp", - "mpls" => "net.mpls", - "swpenc" => "vm.swapencrypt" -); - -# Node mappings -my %node_map = ( - "net.inet.ip.ifq" => "net.ifq", - "net.inet.pfsync" => "net.pfsync", - "net.mpls.ifq" => "net.ifq" -); - -my $ctlname; -my %mib = (); -my %sysctl = (); -my $node; - -sub debug() { - print STDERR "$_[0]\n" if $debug; -} - -# Walk the MIB and build a sysctl name to OID mapping. -sub build_sysctl() { - my ($node, $name, $oid) = @_; - my %node = %{$node}; - my @oid = @{$oid}; - - foreach my $key (sort keys %node) { - my @node = @{$node{$key}}; - my $nodename = $name.($name ne '' ? '.' : '').$key; - my @nodeoid = (@oid, $node[0]); - if ($node[1] eq 'CTLTYPE_NODE') { - if (exists $node_map{$nodename}) { - $node = \%mib; - $ctlname = $node_map{$nodename}; - foreach my $part (split /\./, $ctlname) { - $node = \%{@{$$node{$part}}[2]}; - } - } else { - $node = $node[2]; - } - &build_sysctl($node, $nodename, \@nodeoid); - } elsif ($node[1] ne '') { - $sysctl{$nodename} = \@nodeoid; - } - } -} - -foreach my $ctl (@ctls) { - $ctls{$ctl} = $ctl; -} - -# Build MIB -foreach my $header (@headers) { - &debug("Processing $header..."); - open HEADER, "/usr/include/$header" || - print STDERR "Failed to open $header\n"; - while (
) { - if ($_ =~ /^#define\s+(CTL_NAMES)\s+{/ || - $_ =~ /^#define\s+(CTL_(.*)_NAMES)\s+{/ || - $_ =~ /^#define\s+((.*)CTL_NAMES)\s+{/) { - if ($1 eq 'CTL_NAMES') { - # Top level. - $node = \%mib; - } else { - # Node. - my $nodename = lc($2); - if ($header =~ /^netinet\//) { - $ctlname = "net.inet.$nodename"; - } elsif ($header =~ /^netinet6\//) { - $ctlname = "net.inet6.$nodename"; - } elsif ($header =~ /^net\//) { - $ctlname = "net.$nodename"; - } else { - $ctlname = "$nodename"; - $ctlname =~ s/^(fs|net|kern)_/$1\./; - } - if (exists $ctl_map{$ctlname}) { - $ctlname = $ctl_map{$ctlname}; - } - if (not exists $ctls{$ctlname}) { - &debug("Ignoring $ctlname..."); - next; - } - - # Walk down from the top of the MIB. - $node = \%mib; - foreach my $part (split /\./, $ctlname) { - if (not exists $$node{$part}) { - &debug("Missing node $part"); - $$node{$part} = [ 0, '', {} ]; - } - $node = \%{@{$$node{$part}}[2]}; - } - } - - # Populate current node with entries. - my $i = -1; - while (defined($_) && $_ !~ /^}/) { - $_ =
; - $i++ if $_ =~ /{.*}/; - next if $_ !~ /{\s+"(\w+)",\s+(CTLTYPE_[A-Z]+)\s+}/; - $$node{$1} = [ $i, $2, {} ]; - } - } - } - close HEADER; -} - -&build_sysctl(\%mib, "", []); - -print <){ - if(/^#define\s+SYS_(\w+)\s+([0-9]+)/){ - my $name = $1; - my $num = $2; - $name =~ y/a-z/A-Z/; - print " SYS_$name = $num;" - } -} - -print <){ - if(/^([0-9]+)\s+STD\s+({ \S+\s+(\w+).*)$/){ - my $num = $1; - my $proto = $2; - my $name = "SYS_$3"; - $name =~ y/a-z/A-Z/; - - # There are multiple entries for enosys and nosys, so comment them out. - if($name =~ /^SYS_E?NOSYS$/){ - $name = "// $name"; - } - if($name eq 'SYS_SYS_EXIT'){ - $name = 'SYS_EXIT'; - } - - print " $name = $num; // $proto\n"; - } -} - -print <){ - if(/^([0-9]+)\s+\S+\s+STD\s+({ \S+\s+(\w+).*)$/){ - my $num = $1; - my $proto = $2; - my $name = "SYS_$3"; - $name =~ y/a-z/A-Z/; - - # There are multiple entries for enosys and nosys, so comment them out. - if($name =~ /^SYS_E?NOSYS$/){ - $name = "// $name"; - } - if($name eq 'SYS_SYS_EXIT'){ - $name = 'SYS_EXIT'; - } - - print " $name = $num; // $proto\n"; - } -} - -print <){ - if($line =~ /^(.*)\\$/) { - # Handle continuation - $line = $1; - $_ =~ s/^\s+//; - $line .= $_; - } else { - # New line - $line = $_; - } - next if $line =~ /\\$/; - if($line =~ /^([0-9]+)\s+((STD)|(NOERR))\s+(RUMP\s+)?({\s+\S+\s*\*?\s*\|(\S+)\|(\S*)\|(\w+).*\s+})(\s+(\S+))?$/) { - my $num = $1; - my $proto = $6; - my $compat = $8; - my $name = "$7_$9"; - - $name = "$7_$11" if $11 ne ''; - $name =~ y/a-z/A-Z/; - - if($compat eq '' || $compat eq '13' || $compat eq '30' || $compat eq '50') { - print " $name = $num; // $proto\n"; - } - } -} - -print <){ - if(/^([0-9]+)\s+STD\s+(NOLOCK\s+)?({ \S+\s+\*?(\w+).*)$/){ - my $num = $1; - my $proto = $3; - my $name = $4; - $name =~ y/a-z/A-Z/; - - # There are multiple entries for enosys and nosys, so comment them out. - if($name =~ /^SYS_E?NOSYS$/){ - $name = "// $name"; - } - if($name eq 'SYS_SYS_EXIT'){ - $name = 'SYS_EXIT'; - } - - print " $name = $num; // $proto\n"; - } -} - -print <= 0 { - t.Fatal("bad math") - } - s := unix.Itoa(i) - f := fmt.Sprint(i) - if s != f { - t.Fatalf("itoa(%d) = %s, want %s", i, s, f) - } -} diff --git a/vendor/golang.org/x/sys/unix/syscall_unix_test.go b/vendor/golang.org/x/sys/unix/syscall_unix_test.go deleted file mode 100644 index 394b3502..00000000 --- a/vendor/golang.org/x/sys/unix/syscall_unix_test.go +++ /dev/null @@ -1,345 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd linux netbsd openbsd solaris - -package unix_test - -import ( - "flag" - "fmt" - "io/ioutil" - "net" - "os" - "os/exec" - "path/filepath" - "runtime" - "testing" - "time" - - "golang.org/x/sys/unix" -) - -// Tests that below functions, structures and constants are consistent -// on all Unix-like systems. -func _() { - // program scheduling priority functions and constants - var ( - _ func(int, int, int) error = unix.Setpriority - _ func(int, int) (int, error) = unix.Getpriority - ) - const ( - _ int = unix.PRIO_USER - _ int = unix.PRIO_PROCESS - _ int = unix.PRIO_PGRP - ) - - // termios constants - const ( - _ int = unix.TCIFLUSH - _ int = unix.TCIOFLUSH - _ int = unix.TCOFLUSH - ) - - // fcntl file locking structure and constants - var ( - _ = unix.Flock_t{ - Type: int16(0), - Whence: int16(0), - Start: int64(0), - Len: int64(0), - Pid: int32(0), - } - ) - const ( - _ = unix.F_GETLK - _ = unix.F_SETLK - _ = unix.F_SETLKW - ) -} - -// TestFcntlFlock tests whether the file locking structure matches -// the calling convention of each kernel. -func TestFcntlFlock(t *testing.T) { - name := filepath.Join(os.TempDir(), "TestFcntlFlock") - fd, err := unix.Open(name, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0) - if err != nil { - t.Fatalf("Open failed: %v", err) - } - defer unix.Unlink(name) - defer unix.Close(fd) - flock := unix.Flock_t{ - Type: unix.F_RDLCK, - Start: 0, Len: 0, Whence: 1, - } - if err := unix.FcntlFlock(uintptr(fd), unix.F_GETLK, &flock); err != nil { - t.Fatalf("FcntlFlock failed: %v", err) - } -} - -// TestPassFD tests passing a file descriptor over a Unix socket. -// -// This test involved both a parent and child process. The parent -// process is invoked as a normal test, with "go test", which then -// runs the child process by running the current test binary with args -// "-test.run=^TestPassFD$" and an environment variable used to signal -// that the test should become the child process instead. -func TestPassFD(t *testing.T) { - if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" { - passFDChild() - return - } - - tempDir, err := ioutil.TempDir("", "TestPassFD") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tempDir) - - fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0) - if err != nil { - t.Fatalf("Socketpair: %v", err) - } - defer unix.Close(fds[0]) - defer unix.Close(fds[1]) - writeFile := os.NewFile(uintptr(fds[0]), "child-writes") - readFile := os.NewFile(uintptr(fds[1]), "parent-reads") - defer writeFile.Close() - defer readFile.Close() - - cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir) - cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"} - if lp := os.Getenv("LD_LIBRARY_PATH"); lp != "" { - cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+lp) - } - cmd.ExtraFiles = []*os.File{writeFile} - - out, err := cmd.CombinedOutput() - if len(out) > 0 || err != nil { - t.Fatalf("child process: %q, %v", out, err) - } - - c, err := net.FileConn(readFile) - if err != nil { - t.Fatalf("FileConn: %v", err) - } - defer c.Close() - - uc, ok := c.(*net.UnixConn) - if !ok { - t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c) - } - - buf := make([]byte, 32) // expect 1 byte - oob := make([]byte, 32) // expect 24 bytes - closeUnix := time.AfterFunc(5*time.Second, func() { - t.Logf("timeout reading from unix socket") - uc.Close() - }) - _, oobn, _, _, err := uc.ReadMsgUnix(buf, oob) - closeUnix.Stop() - - scms, err := unix.ParseSocketControlMessage(oob[:oobn]) - if err != nil { - t.Fatalf("ParseSocketControlMessage: %v", err) - } - if len(scms) != 1 { - t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms) - } - scm := scms[0] - gotFds, err := unix.ParseUnixRights(&scm) - if err != nil { - t.Fatalf("unix.ParseUnixRights: %v", err) - } - if len(gotFds) != 1 { - t.Fatalf("wanted 1 fd; got %#v", gotFds) - } - - f := os.NewFile(uintptr(gotFds[0]), "fd-from-child") - defer f.Close() - - got, err := ioutil.ReadAll(f) - want := "Hello from child process!\n" - if string(got) != want { - t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want) - } -} - -// passFDChild is the child process used by TestPassFD. -func passFDChild() { - defer os.Exit(0) - - // Look for our fd. It should be fd 3, but we work around an fd leak - // bug here (http://golang.org/issue/2603) to let it be elsewhere. - var uc *net.UnixConn - for fd := uintptr(3); fd <= 10; fd++ { - f := os.NewFile(fd, "unix-conn") - var ok bool - netc, _ := net.FileConn(f) - uc, ok = netc.(*net.UnixConn) - if ok { - break - } - } - if uc == nil { - fmt.Println("failed to find unix fd") - return - } - - // Make a file f to send to our parent process on uc. - // We make it in tempDir, which our parent will clean up. - flag.Parse() - tempDir := flag.Arg(0) - f, err := ioutil.TempFile(tempDir, "") - if err != nil { - fmt.Printf("TempFile: %v", err) - return - } - - f.Write([]byte("Hello from child process!\n")) - f.Seek(0, 0) - - rights := unix.UnixRights(int(f.Fd())) - dummyByte := []byte("x") - n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil) - if err != nil { - fmt.Printf("WriteMsgUnix: %v", err) - return - } - if n != 1 || oobn != len(rights) { - fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights)) - return - } -} - -// TestUnixRightsRoundtrip tests that UnixRights, ParseSocketControlMessage, -// and ParseUnixRights are able to successfully round-trip lists of file descriptors. -func TestUnixRightsRoundtrip(t *testing.T) { - testCases := [...][][]int{ - {{42}}, - {{1, 2}}, - {{3, 4, 5}}, - {{}}, - {{1, 2}, {3, 4, 5}, {}, {7}}, - } - for _, testCase := range testCases { - b := []byte{} - var n int - for _, fds := range testCase { - // Last assignment to n wins - n = len(b) + unix.CmsgLen(4*len(fds)) - b = append(b, unix.UnixRights(fds...)...) - } - // Truncate b - b = b[:n] - - scms, err := unix.ParseSocketControlMessage(b) - if err != nil { - t.Fatalf("ParseSocketControlMessage: %v", err) - } - if len(scms) != len(testCase) { - t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms) - } - for i, scm := range scms { - gotFds, err := unix.ParseUnixRights(&scm) - if err != nil { - t.Fatalf("ParseUnixRights: %v", err) - } - wantFds := testCase[i] - if len(gotFds) != len(wantFds) { - t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds) - } - for j, fd := range gotFds { - if fd != wantFds[j] { - t.Fatalf("expected fd %v, got %v", wantFds[j], fd) - } - } - } - } -} - -func TestRlimit(t *testing.T) { - var rlimit, zero unix.Rlimit - err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlimit) - if err != nil { - t.Fatalf("Getrlimit: save failed: %v", err) - } - if zero == rlimit { - t.Fatalf("Getrlimit: save failed: got zero value %#v", rlimit) - } - set := rlimit - set.Cur = set.Max - 1 - err = unix.Setrlimit(unix.RLIMIT_NOFILE, &set) - if err != nil { - t.Fatalf("Setrlimit: set failed: %#v %v", set, err) - } - var get unix.Rlimit - err = unix.Getrlimit(unix.RLIMIT_NOFILE, &get) - if err != nil { - t.Fatalf("Getrlimit: get failed: %v", err) - } - set = rlimit - set.Cur = set.Max - 1 - if set != get { - // Seems like Darwin requires some privilege to - // increase the soft limit of rlimit sandbox, though - // Setrlimit never reports an error. - switch runtime.GOOS { - case "darwin": - default: - t.Fatalf("Rlimit: change failed: wanted %#v got %#v", set, get) - } - } - err = unix.Setrlimit(unix.RLIMIT_NOFILE, &rlimit) - if err != nil { - t.Fatalf("Setrlimit: restore failed: %#v %v", rlimit, err) - } -} - -func TestSeekFailure(t *testing.T) { - _, err := unix.Seek(-1, 0, 0) - if err == nil { - t.Fatalf("Seek(-1, 0, 0) did not fail") - } - str := err.Error() // used to crash on Linux - t.Logf("Seek: %v", str) - if str == "" { - t.Fatalf("Seek(-1, 0, 0) return error with empty message") - } -} - -func TestDup(t *testing.T) { - file, err := ioutil.TempFile("", "TestDup") - if err != nil { - t.Fatalf("Tempfile failed: %v", err) - } - defer os.Remove(file.Name()) - defer file.Close() - f := int(file.Fd()) - - newFd, err := unix.Dup(f) - if err != nil { - t.Fatalf("Dup: %v", err) - } - - err = unix.Dup2(newFd, newFd+1) - if err != nil { - t.Fatalf("Dup2: %v", err) - } - - b1 := []byte("Test123") - b2 := make([]byte, 7) - _, err = unix.Write(newFd+1, b1) - if err != nil { - t.Fatalf("Write to dup2 fd failed: %v", err) - } - _, err = unix.Seek(f, 0, 0) - _, err = unix.Read(f, b2) - if err != nil { - t.Fatalf("Read back failed: %v", err) - } - if string(b1) != string(b2) { - t.Errorf("Dup: stdout write not in file, expected %v, got %v", string(b1), string(b2)) - } -}