From 14a303072007288c84d3d4b435d072b3de07b149 Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Mon, 9 Sep 2019 19:12:09 +0200 Subject: [PATCH] Remove vendor folder Signed-off-by: Knut Ahlers --- vendor/github.com/Luzifer/rconfig/.travis.yml | 8 - vendor/github.com/Luzifer/rconfig/History.md | 9 - vendor/github.com/Luzifer/rconfig/LICENSE | 13 - vendor/github.com/Luzifer/rconfig/README.md | 87 - vendor/github.com/Luzifer/rconfig/config.go | 356 - .../Luzifer/rconfig/vardefault_providers.go | 27 - vendor/github.com/Sirupsen/logrus/.gitignore | 1 - vendor/github.com/Sirupsen/logrus/.travis.yml | 13 - .../github.com/Sirupsen/logrus/CHANGELOG.md | 123 - vendor/github.com/Sirupsen/logrus/LICENSE | 21 - vendor/github.com/Sirupsen/logrus/README.md | 461 - vendor/github.com/Sirupsen/logrus/alt_exit.go | 64 - .../github.com/Sirupsen/logrus/appveyor.yml | 14 - vendor/github.com/Sirupsen/logrus/doc.go | 26 - vendor/github.com/Sirupsen/logrus/entry.go | 300 - vendor/github.com/Sirupsen/logrus/exported.go | 201 - .../github.com/Sirupsen/logrus/formatter.go | 51 - vendor/github.com/Sirupsen/logrus/hooks.go | 34 - .../Sirupsen/logrus/json_formatter.go | 89 - vendor/github.com/Sirupsen/logrus/logger.go | 337 - vendor/github.com/Sirupsen/logrus/logrus.go | 143 - .../Sirupsen/logrus/terminal_bsd.go | 10 - .../logrus/terminal_check_appengine.go | 11 - .../logrus/terminal_check_notappengine.go | 19 - .../Sirupsen/logrus/terminal_linux.go | 14 - .../Sirupsen/logrus/text_formatter.go | 195 - vendor/github.com/Sirupsen/logrus/writer.go | 62 - vendor/github.com/alecthomas/template/LICENSE | 27 - .../github.com/alecthomas/template/README.md | 25 - vendor/github.com/alecthomas/template/doc.go | 406 - vendor/github.com/alecthomas/template/exec.go | 845 - .../github.com/alecthomas/template/funcs.go | 598 - .../github.com/alecthomas/template/helper.go | 108 - .../alecthomas/template/parse/lex.go | 556 - .../alecthomas/template/parse/node.go | 834 - .../alecthomas/template/parse/parse.go | 700 - .../alecthomas/template/template.go | 218 - .../github.com/boombuler/barcode/.gitignore | 1 - vendor/github.com/boombuler/barcode/LICENSE | 21 - vendor/github.com/boombuler/barcode/README.md | 53 - .../github.com/boombuler/barcode/barcode.go | 42 - .../boombuler/barcode/qr/alphanumeric.go | 66 - .../boombuler/barcode/qr/automatic.go | 23 - .../github.com/boombuler/barcode/qr/blocks.go | 59 - .../boombuler/barcode/qr/encoder.go | 416 - .../boombuler/barcode/qr/errorcorrection.go | 29 - .../boombuler/barcode/qr/numeric.go | 56 - .../github.com/boombuler/barcode/qr/qrcode.go | 166 - .../boombuler/barcode/qr/unicode.go | 27 - .../boombuler/barcode/qr/versioninfo.go | 310 - .../boombuler/barcode/scaledbarcode.go | 134 - .../boombuler/barcode/utils/base1dcode.go | 57 - .../boombuler/barcode/utils/bitlist.go | 119 - .../boombuler/barcode/utils/galoisfield.go | 65 - .../boombuler/barcode/utils/gfpoly.go | 103 - .../boombuler/barcode/utils/reedsolomon.go | 44 - .../boombuler/barcode/utils/runeint.go | 19 - vendor/github.com/golang/snappy/.gitignore | 16 - vendor/github.com/golang/snappy/AUTHORS | 15 - vendor/github.com/golang/snappy/CONTRIBUTORS | 37 - vendor/github.com/golang/snappy/LICENSE | 27 - vendor/github.com/golang/snappy/README | 107 - vendor/github.com/golang/snappy/decode.go | 237 - .../github.com/golang/snappy/decode_amd64.go | 14 - .../github.com/golang/snappy/decode_amd64.s | 490 - .../github.com/golang/snappy/decode_other.go | 101 - vendor/github.com/golang/snappy/encode.go | 285 - .../github.com/golang/snappy/encode_amd64.go | 29 - .../github.com/golang/snappy/encode_amd64.s | 730 - .../github.com/golang/snappy/encode_other.go | 238 - vendor/github.com/golang/snappy/snappy.go | 98 - vendor/github.com/gorilla/context/.travis.yml | 19 - vendor/github.com/gorilla/context/LICENSE | 27 - vendor/github.com/gorilla/context/README.md | 10 - vendor/github.com/gorilla/context/context.go | 143 - vendor/github.com/gorilla/context/doc.go | 88 - vendor/github.com/gorilla/mux/.travis.yml | 23 - .../github.com/gorilla/mux/ISSUE_TEMPLATE.md | 11 - vendor/github.com/gorilla/mux/LICENSE | 27 - vendor/github.com/gorilla/mux/README.md | 649 - .../github.com/gorilla/mux/context_gorilla.go | 26 - .../github.com/gorilla/mux/context_native.go | 24 - vendor/github.com/gorilla/mux/doc.go | 306 - vendor/github.com/gorilla/mux/middleware.go | 72 - vendor/github.com/gorilla/mux/mux.go | 588 - vendor/github.com/gorilla/mux/regexp.go | 332 - vendor/github.com/gorilla/mux/route.go | 763 - vendor/github.com/gorilla/mux/test_helpers.go | 19 - .../gorilla/securecookie/.travis.yml | 19 - .../github.com/gorilla/securecookie/LICENSE | 27 - .../github.com/gorilla/securecookie/README.md | 80 - vendor/github.com/gorilla/securecookie/doc.go | 61 - .../github.com/gorilla/securecookie/fuzz.go | 25 - .../gorilla/securecookie/securecookie.go | 646 - .../github.com/gorilla/sessions/.travis.yml | 22 - vendor/github.com/gorilla/sessions/AUTHORS | 43 - vendor/github.com/gorilla/sessions/LICENSE | 27 - vendor/github.com/gorilla/sessions/README.md | 92 - vendor/github.com/gorilla/sessions/doc.go | 198 - vendor/github.com/gorilla/sessions/go.mod | 6 - vendor/github.com/gorilla/sessions/lex.go | 102 - .../github.com/gorilla/sessions/sessions.go | 243 - vendor/github.com/gorilla/sessions/store.go | 295 - vendor/github.com/hashicorp/errwrap/LICENSE | 354 - vendor/github.com/hashicorp/errwrap/README.md | 89 - .../github.com/hashicorp/errwrap/errwrap.go | 169 - vendor/github.com/hashicorp/errwrap/go.mod | 1 - .../github.com/hashicorp/go-cleanhttp/LICENSE | 363 - .../hashicorp/go-cleanhttp/README.md | 30 - .../hashicorp/go-cleanhttp/cleanhttp.go | 57 - .../github.com/hashicorp/go-cleanhttp/doc.go | 20 - .../github.com/hashicorp/go-cleanhttp/go.mod | 1 - .../hashicorp/go-cleanhttp/handlers.go | 43 - .../hashicorp/go-multierror/.travis.yml | 12 - .../hashicorp/go-multierror/LICENSE | 353 - .../hashicorp/go-multierror/Makefile | 31 - .../hashicorp/go-multierror/README.md | 97 - .../hashicorp/go-multierror/append.go | 41 - .../hashicorp/go-multierror/flatten.go | 26 - .../hashicorp/go-multierror/format.go | 27 - .../github.com/hashicorp/go-multierror/go.mod | 3 - .../github.com/hashicorp/go-multierror/go.sum | 4 - .../hashicorp/go-multierror/multierror.go | 51 - .../hashicorp/go-multierror/prefix.go | 37 - .../hashicorp/go-multierror/sort.go | 16 - .../hashicorp/go-retryablehttp/.gitignore | 3 - .../hashicorp/go-retryablehttp/.travis.yml | 12 - .../hashicorp/go-retryablehttp/LICENSE | 363 - .../hashicorp/go-retryablehttp/Makefile | 11 - .../hashicorp/go-retryablehttp/README.md | 46 - .../hashicorp/go-retryablehttp/client.go | 500 - .../hashicorp/go-rootcerts/.travis.yml | 12 - .../github.com/hashicorp/go-rootcerts/LICENSE | 363 - .../hashicorp/go-rootcerts/Makefile | 8 - .../hashicorp/go-rootcerts/README.md | 43 - .../github.com/hashicorp/go-rootcerts/doc.go | 9 - .../hashicorp/go-rootcerts/rootcerts.go | 103 - .../hashicorp/go-rootcerts/rootcerts_base.go | 12 - .../go-rootcerts/rootcerts_darwin.go | 48 - .../capath-with-symlinks/securetrust.pem | 1 - .../capath-with-symlinks/thawte.pem | 1 - .../hashicorp/go-sockaddr/.gitignore | 26 - .../hashicorp/go-sockaddr/GNUmakefile | 65 - .../github.com/hashicorp/go-sockaddr/LICENSE | 373 - .../hashicorp/go-sockaddr/README.md | 118 - .../github.com/hashicorp/go-sockaddr/doc.go | 5 - .../hashicorp/go-sockaddr/ifaddr.go | 254 - .../hashicorp/go-sockaddr/ifaddrs.go | 1281 - .../hashicorp/go-sockaddr/ifattr.go | 65 - .../hashicorp/go-sockaddr/ipaddr.go | 169 - .../hashicorp/go-sockaddr/ipaddrs.go | 98 - .../hashicorp/go-sockaddr/ipv4addr.go | 516 - .../hashicorp/go-sockaddr/ipv6addr.go | 591 - .../github.com/hashicorp/go-sockaddr/rfc.go | 948 - .../hashicorp/go-sockaddr/route_info.go | 19 - .../hashicorp/go-sockaddr/route_info_bsd.go | 36 - .../go-sockaddr/route_info_default.go | 10 - .../hashicorp/go-sockaddr/route_info_linux.go | 40 - .../go-sockaddr/route_info_solaris.go | 37 - .../go-sockaddr/route_info_windows.go | 41 - .../hashicorp/go-sockaddr/sockaddr.go | 206 - .../hashicorp/go-sockaddr/sockaddrs.go | 193 - .../hashicorp/go-sockaddr/unixsock.go | 135 - vendor/github.com/hashicorp/hcl/.gitignore | 9 - vendor/github.com/hashicorp/hcl/.travis.yml | 13 - vendor/github.com/hashicorp/hcl/LICENSE | 354 - vendor/github.com/hashicorp/hcl/Makefile | 18 - vendor/github.com/hashicorp/hcl/README.md | 125 - vendor/github.com/hashicorp/hcl/appveyor.yml | 19 - vendor/github.com/hashicorp/hcl/decoder.go | 729 - vendor/github.com/hashicorp/hcl/go.mod | 3 - vendor/github.com/hashicorp/hcl/go.sum | 2 - vendor/github.com/hashicorp/hcl/hcl.go | 11 - .../github.com/hashicorp/hcl/hcl/ast/ast.go | 219 - .../github.com/hashicorp/hcl/hcl/ast/walk.go | 52 - .../hashicorp/hcl/hcl/parser/error.go | 17 - .../hashicorp/hcl/hcl/parser/parser.go | 532 - .../hashicorp/hcl/hcl/scanner/scanner.go | 652 - .../hashicorp/hcl/hcl/strconv/quote.go | 241 - .../hashicorp/hcl/hcl/token/position.go | 46 - .../hashicorp/hcl/hcl/token/token.go | 219 - .../hashicorp/hcl/json/parser/flatten.go | 117 - .../hashicorp/hcl/json/parser/parser.go | 313 - .../hashicorp/hcl/json/scanner/scanner.go | 451 - .../hashicorp/hcl/json/token/position.go | 46 - .../hashicorp/hcl/json/token/token.go | 118 - vendor/github.com/hashicorp/hcl/lex.go | 38 - vendor/github.com/hashicorp/hcl/parse.go | 39 - vendor/github.com/hashicorp/vault/LICENSE | 363 - vendor/github.com/hashicorp/vault/api/auth.go | 11 - .../hashicorp/vault/api/auth_token.go | 274 - .../github.com/hashicorp/vault/api/client.go | 759 - vendor/github.com/hashicorp/vault/api/help.go | 29 - .../github.com/hashicorp/vault/api/logical.go | 267 - .../github.com/hashicorp/vault/api/renewer.go | 349 - .../github.com/hashicorp/vault/api/request.go | 145 - .../hashicorp/vault/api/response.go | 77 - .../github.com/hashicorp/vault/api/secret.go | 320 - vendor/github.com/hashicorp/vault/api/ssh.go | 62 - .../hashicorp/vault/api/ssh_agent.go | 234 - vendor/github.com/hashicorp/vault/api/sys.go | 11 - .../hashicorp/vault/api/sys_audit.go | 136 - .../hashicorp/vault/api/sys_auth.go | 118 - .../hashicorp/vault/api/sys_capabilities.go | 54 - .../hashicorp/vault/api/sys_config_cors.go | 105 - .../hashicorp/vault/api/sys_generate_root.go | 124 - .../hashicorp/vault/api/sys_health.go | 39 - .../hashicorp/vault/api/sys_init.go | 61 - .../hashicorp/vault/api/sys_leader.go | 28 - .../hashicorp/vault/api/sys_leases.go | 105 - .../hashicorp/vault/api/sys_mounts.go | 173 - .../hashicorp/vault/api/sys_plugins.go | 131 - .../hashicorp/vault/api/sys_policy.go | 109 - .../hashicorp/vault/api/sys_rekey.go | 388 - .../hashicorp/vault/api/sys_rotate.go | 77 - .../hashicorp/vault/api/sys_seal.go | 69 - .../hashicorp/vault/api/sys_stepdown.go | 15 - .../vault/helper/compressutil/compress.go | 192 - .../hashicorp/vault/helper/consts/consts.go | 14 - .../hashicorp/vault/helper/consts/error.go | 16 - .../vault/helper/consts/replication.go | 87 - .../hashicorp/vault/helper/hclutil/hcl.go | 36 - .../hashicorp/vault/helper/jsonutil/json.go | 100 - .../vault/helper/parseutil/parseutil.go | 163 - .../hashicorp/vault/helper/strutil/strutil.go | 348 - .../hashicorp/vault/website/LICENSE.md | 10 - .../website/source/api/system/license.html.md | 87 - .../github.com/mitchellh/go-homedir/LICENSE | 21 - .../github.com/mitchellh/go-homedir/README.md | 14 - vendor/github.com/mitchellh/go-homedir/go.mod | 1 - .../mitchellh/go-homedir/homedir.go | 157 - .../mitchellh/mapstructure/.travis.yml | 8 - .../github.com/mitchellh/mapstructure/LICENSE | 21 - .../mitchellh/mapstructure/README.md | 46 - .../mitchellh/mapstructure/decode_hooks.go | 171 - .../mitchellh/mapstructure/error.go | 50 - .../github.com/mitchellh/mapstructure/go.mod | 1 - .../mitchellh/mapstructure/mapstructure.go | 1064 - vendor/github.com/pquerna/otp/.travis.yml | 6 - vendor/github.com/pquerna/otp/LICENSE | 202 - vendor/github.com/pquerna/otp/NOTICE | 5 - vendor/github.com/pquerna/otp/README.md | 60 - vendor/github.com/pquerna/otp/doc.go | 70 - vendor/github.com/pquerna/otp/hotp/hotp.go | 188 - vendor/github.com/pquerna/otp/otp.go | 202 - vendor/github.com/pquerna/otp/totp/totp.go | 193 - .../github.com/ryanuber/go-glob/.travis.yml | 5 - vendor/github.com/ryanuber/go-glob/LICENSE | 21 - vendor/github.com/ryanuber/go-glob/README.md | 29 - vendor/github.com/ryanuber/go-glob/glob.go | 51 - vendor/github.com/spf13/pflag/.gitignore | 2 - vendor/github.com/spf13/pflag/.travis.yml | 21 - vendor/github.com/spf13/pflag/LICENSE | 28 - vendor/github.com/spf13/pflag/README.md | 296 - vendor/github.com/spf13/pflag/bool.go | 94 - vendor/github.com/spf13/pflag/bool_slice.go | 147 - vendor/github.com/spf13/pflag/bytes.go | 209 - vendor/github.com/spf13/pflag/count.go | 96 - vendor/github.com/spf13/pflag/duration.go | 86 - .../github.com/spf13/pflag/duration_slice.go | 128 - vendor/github.com/spf13/pflag/flag.go | 1224 - vendor/github.com/spf13/pflag/float32.go | 88 - vendor/github.com/spf13/pflag/float64.go | 84 - vendor/github.com/spf13/pflag/golangflag.go | 105 - vendor/github.com/spf13/pflag/int.go | 84 - vendor/github.com/spf13/pflag/int16.go | 88 - vendor/github.com/spf13/pflag/int32.go | 88 - vendor/github.com/spf13/pflag/int64.go | 84 - vendor/github.com/spf13/pflag/int8.go | 88 - vendor/github.com/spf13/pflag/int_slice.go | 128 - vendor/github.com/spf13/pflag/ip.go | 94 - vendor/github.com/spf13/pflag/ip_slice.go | 148 - vendor/github.com/spf13/pflag/ipmask.go | 122 - vendor/github.com/spf13/pflag/ipnet.go | 98 - vendor/github.com/spf13/pflag/string.go | 80 - vendor/github.com/spf13/pflag/string_array.go | 103 - vendor/github.com/spf13/pflag/string_slice.go | 149 - vendor/github.com/spf13/pflag/uint.go | 88 - vendor/github.com/spf13/pflag/uint16.go | 88 - vendor/github.com/spf13/pflag/uint32.go | 88 - vendor/github.com/spf13/pflag/uint64.go | 88 - vendor/github.com/spf13/pflag/uint8.go | 88 - vendor/github.com/spf13/pflag/uint_slice.go | 126 - .../github.com/tdewolff/minify/.gitattributes | 1 - vendor/github.com/tdewolff/minify/.gitignore | 4 - .../tdewolff/minify/.goreleaser.yml | 28 - vendor/github.com/tdewolff/minify/.travis.yml | 5 - vendor/github.com/tdewolff/minify/LICENSE.md | 22 - vendor/github.com/tdewolff/minify/README.md | 590 - vendor/github.com/tdewolff/minify/common.go | 462 - .../github.com/tdewolff/minify/html/buffer.go | 131 - .../github.com/tdewolff/minify/html/html.go | 467 - .../github.com/tdewolff/minify/html/table.go | 186 - vendor/github.com/tdewolff/minify/js/js.go | 97 - vendor/github.com/tdewolff/minify/minify.go | 279 - vendor/github.com/tdewolff/parse/.travis.yml | 5 - vendor/github.com/tdewolff/parse/LICENSE.md | 22 - vendor/github.com/tdewolff/parse/README.md | 66 - .../tdewolff/parse/buffer/buffer.go | 15 - .../github.com/tdewolff/parse/buffer/lexer.go | 158 - .../tdewolff/parse/buffer/reader.go | 44 - .../tdewolff/parse/buffer/streamlexer.go | 223 - .../tdewolff/parse/buffer/writer.go | 41 - vendor/github.com/tdewolff/parse/common.go | 231 - vendor/github.com/tdewolff/parse/error.go | 49 - .../github.com/tdewolff/parse/html/README.md | 98 - vendor/github.com/tdewolff/parse/html/hash.go | 831 - vendor/github.com/tdewolff/parse/html/lex.go | 498 - vendor/github.com/tdewolff/parse/html/util.go | 129 - vendor/github.com/tdewolff/parse/js/README.md | 89 - vendor/github.com/tdewolff/parse/js/hash.go | 156 - vendor/github.com/tdewolff/parse/js/lex.go | 669 - vendor/github.com/tdewolff/parse/position.go | 79 - .../tdewolff/parse/strconv/float.go | 251 - .../github.com/tdewolff/parse/strconv/int.go | 83 - .../tdewolff/parse/strconv/price.go | 83 - vendor/github.com/tdewolff/parse/util.go | 196 - vendor/golang.org/x/crypto/AUTHORS | 3 - vendor/golang.org/x/crypto/CONTRIBUTORS | 3 - vendor/golang.org/x/crypto/LICENSE | 27 - vendor/golang.org/x/crypto/PATENTS | 22 - .../x/crypto/ssh/terminal/terminal.go | 951 - .../golang.org/x/crypto/ssh/terminal/util.go | 114 - .../x/crypto/ssh/terminal/util_bsd.go | 12 - .../x/crypto/ssh/terminal/util_linux.go | 10 - .../x/crypto/ssh/terminal/util_plan9.go | 58 - .../x/crypto/ssh/terminal/util_solaris.go | 124 - .../x/crypto/ssh/terminal/util_windows.go | 103 - vendor/golang.org/x/net/AUTHORS | 3 - vendor/golang.org/x/net/CONTRIBUTORS | 3 - vendor/golang.org/x/net/LICENSE | 27 - vendor/golang.org/x/net/PATENTS | 22 - vendor/golang.org/x/net/context/context.go | 56 - vendor/golang.org/x/net/context/go17.go | 72 - vendor/golang.org/x/net/context/go19.go | 20 - vendor/golang.org/x/net/context/pre_go17.go | 300 - vendor/golang.org/x/net/context/pre_go19.go | 109 - vendor/golang.org/x/net/http/httpguts/guts.go | 50 - .../golang.org/x/net/http/httpguts/httplex.go | 346 - vendor/golang.org/x/net/http2/.gitignore | 2 - vendor/golang.org/x/net/http2/Dockerfile | 51 - vendor/golang.org/x/net/http2/Makefile | 3 - vendor/golang.org/x/net/http2/README | 20 - vendor/golang.org/x/net/http2/ciphers.go | 641 - .../x/net/http2/client_conn_pool.go | 282 - .../x/net/http2/configure_transport.go | 82 - vendor/golang.org/x/net/http2/databuffer.go | 146 - vendor/golang.org/x/net/http2/errors.go | 133 - vendor/golang.org/x/net/http2/flow.go | 50 - vendor/golang.org/x/net/http2/frame.go | 1614 - vendor/golang.org/x/net/http2/go111.go | 26 - vendor/golang.org/x/net/http2/go16.go | 16 - vendor/golang.org/x/net/http2/go17.go | 121 - vendor/golang.org/x/net/http2/go17_not18.go | 36 - vendor/golang.org/x/net/http2/go18.go | 56 - vendor/golang.org/x/net/http2/go19.go | 16 - vendor/golang.org/x/net/http2/gotrack.go | 170 - vendor/golang.org/x/net/http2/headermap.go | 88 - vendor/golang.org/x/net/http2/hpack/encode.go | 240 - vendor/golang.org/x/net/http2/hpack/hpack.go | 496 - .../golang.org/x/net/http2/hpack/huffman.go | 222 - vendor/golang.org/x/net/http2/hpack/tables.go | 479 - vendor/golang.org/x/net/http2/http2.go | 384 - vendor/golang.org/x/net/http2/not_go111.go | 17 - vendor/golang.org/x/net/http2/not_go16.go | 21 - vendor/golang.org/x/net/http2/not_go17.go | 95 - vendor/golang.org/x/net/http2/not_go18.go | 29 - vendor/golang.org/x/net/http2/not_go19.go | 16 - vendor/golang.org/x/net/http2/pipe.go | 163 - vendor/golang.org/x/net/http2/server.go | 2890 - vendor/golang.org/x/net/http2/transport.go | 2453 - vendor/golang.org/x/net/http2/write.go | 365 - vendor/golang.org/x/net/http2/writesched.go | 242 - .../x/net/http2/writesched_priority.go | 452 - .../x/net/http2/writesched_random.go | 72 - vendor/golang.org/x/net/idna/idna.go | 732 - vendor/golang.org/x/net/idna/punycode.go | 203 - vendor/golang.org/x/net/idna/tables.go | 4557 - vendor/golang.org/x/net/idna/trie.go | 72 - vendor/golang.org/x/net/idna/trieval.go | 119 - vendor/golang.org/x/sys/AUTHORS | 3 - vendor/golang.org/x/sys/CONTRIBUTORS | 3 - vendor/golang.org/x/sys/LICENSE | 27 - vendor/golang.org/x/sys/PATENTS | 22 - vendor/golang.org/x/sys/unix/.gitignore | 2 - vendor/golang.org/x/sys/unix/README.md | 173 - .../golang.org/x/sys/unix/affinity_linux.go | 124 - vendor/golang.org/x/sys/unix/aliases.go | 14 - vendor/golang.org/x/sys/unix/asm_darwin_386.s | 29 - .../golang.org/x/sys/unix/asm_darwin_amd64.s | 29 - vendor/golang.org/x/sys/unix/asm_darwin_arm.s | 30 - .../golang.org/x/sys/unix/asm_darwin_arm64.s | 30 - .../x/sys/unix/asm_dragonfly_amd64.s | 29 - .../golang.org/x/sys/unix/asm_freebsd_386.s | 29 - .../golang.org/x/sys/unix/asm_freebsd_amd64.s | 29 - .../golang.org/x/sys/unix/asm_freebsd_arm.s | 29 - vendor/golang.org/x/sys/unix/asm_linux_386.s | 65 - .../golang.org/x/sys/unix/asm_linux_amd64.s | 57 - vendor/golang.org/x/sys/unix/asm_linux_arm.s | 56 - .../golang.org/x/sys/unix/asm_linux_arm64.s | 52 - .../golang.org/x/sys/unix/asm_linux_mips64x.s | 56 - .../golang.org/x/sys/unix/asm_linux_mipsx.s | 54 - .../golang.org/x/sys/unix/asm_linux_ppc64x.s | 56 - .../golang.org/x/sys/unix/asm_linux_s390x.s | 56 - vendor/golang.org/x/sys/unix/asm_netbsd_386.s | 29 - .../golang.org/x/sys/unix/asm_netbsd_amd64.s | 29 - vendor/golang.org/x/sys/unix/asm_netbsd_arm.s | 29 - .../golang.org/x/sys/unix/asm_openbsd_386.s | 29 - .../golang.org/x/sys/unix/asm_openbsd_amd64.s | 29 - .../golang.org/x/sys/unix/asm_openbsd_arm.s | 29 - .../golang.org/x/sys/unix/asm_solaris_amd64.s | 17 - .../golang.org/x/sys/unix/bluetooth_linux.go | 35 - vendor/golang.org/x/sys/unix/cap_freebsd.go | 195 - vendor/golang.org/x/sys/unix/constants.go | 13 - vendor/golang.org/x/sys/unix/dev_aix_ppc.go | 37 - vendor/golang.org/x/sys/unix/dev_aix_ppc64.go | 39 - vendor/golang.org/x/sys/unix/dev_darwin.go | 24 - vendor/golang.org/x/sys/unix/dev_dragonfly.go | 30 - vendor/golang.org/x/sys/unix/dev_freebsd.go | 30 - vendor/golang.org/x/sys/unix/dev_linux.go | 42 - vendor/golang.org/x/sys/unix/dev_netbsd.go | 29 - vendor/golang.org/x/sys/unix/dev_openbsd.go | 29 - vendor/golang.org/x/sys/unix/dirent.go | 17 - vendor/golang.org/x/sys/unix/endian_big.go | 9 - vendor/golang.org/x/sys/unix/endian_little.go | 9 - vendor/golang.org/x/sys/unix/env_unix.go | 31 - .../x/sys/unix/errors_freebsd_386.go | 227 - .../x/sys/unix/errors_freebsd_amd64.go | 227 - .../x/sys/unix/errors_freebsd_arm.go | 226 - vendor/golang.org/x/sys/unix/fcntl.go | 32 - .../x/sys/unix/fcntl_linux_32bit.go | 13 - vendor/golang.org/x/sys/unix/gccgo.go | 62 - vendor/golang.org/x/sys/unix/gccgo_c.c | 39 - .../x/sys/unix/gccgo_linux_amd64.go | 20 - vendor/golang.org/x/sys/unix/ioctl.go | 30 - vendor/golang.org/x/sys/unix/mkall.sh | 198 - vendor/golang.org/x/sys/unix/mkerrors.sh | 632 - vendor/golang.org/x/sys/unix/mkpost.go | 98 - vendor/golang.org/x/sys/unix/mksyscall.pl | 341 - vendor/golang.org/x/sys/unix/mksyscall_aix.pl | 385 - .../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/openbsd_pledge.go | 95 - vendor/golang.org/x/sys/unix/pagesize_unix.go | 15 - vendor/golang.org/x/sys/unix/race.go | 30 - vendor/golang.org/x/sys/unix/race0.go | 25 - .../golang.org/x/sys/unix/sockcmsg_linux.go | 36 - vendor/golang.org/x/sys/unix/sockcmsg_unix.go | 104 - vendor/golang.org/x/sys/unix/str.go | 26 - vendor/golang.org/x/sys/unix/syscall.go | 54 - vendor/golang.org/x/sys/unix/syscall_aix.go | 562 - .../golang.org/x/sys/unix/syscall_aix_ppc.go | 34 - .../x/sys/unix/syscall_aix_ppc64.go | 34 - vendor/golang.org/x/sys/unix/syscall_bsd.go | 624 - .../golang.org/x/sys/unix/syscall_darwin.go | 700 - .../x/sys/unix/syscall_darwin_386.go | 68 - .../x/sys/unix/syscall_darwin_amd64.go | 68 - .../x/sys/unix/syscall_darwin_arm.go | 66 - .../x/sys/unix/syscall_darwin_arm64.go | 68 - .../x/sys/unix/syscall_dragonfly.go | 523 - .../x/sys/unix/syscall_dragonfly_amd64.go | 52 - .../golang.org/x/sys/unix/syscall_freebsd.go | 535 - .../x/sys/unix/syscall_freebsd_386.go | 52 - .../x/sys/unix/syscall_freebsd_amd64.go | 52 - .../x/sys/unix/syscall_freebsd_arm.go | 52 - vendor/golang.org/x/sys/unix/syscall_linux.go | 1600 - .../x/sys/unix/syscall_linux_386.go | 385 - .../x/sys/unix/syscall_linux_amd64.go | 162 - .../x/sys/unix/syscall_linux_amd64_gc.go | 13 - .../x/sys/unix/syscall_linux_arm.go | 259 - .../x/sys/unix/syscall_linux_arm64.go | 212 - .../golang.org/x/sys/unix/syscall_linux_gc.go | 14 - .../x/sys/unix/syscall_linux_gc_386.go | 16 - .../x/sys/unix/syscall_linux_gccgo_386.go | 30 - .../x/sys/unix/syscall_linux_gccgo_arm.go | 20 - .../x/sys/unix/syscall_linux_mips64x.go | 214 - .../x/sys/unix/syscall_linux_mipsx.go | 233 - .../x/sys/unix/syscall_linux_ppc64x.go | 131 - .../x/sys/unix/syscall_linux_s390x.go | 324 - .../x/sys/unix/syscall_linux_sparc64.go | 146 - .../golang.org/x/sys/unix/syscall_netbsd.go | 580 - .../x/sys/unix/syscall_netbsd_386.go | 33 - .../x/sys/unix/syscall_netbsd_amd64.go | 33 - .../x/sys/unix/syscall_netbsd_arm.go | 33 - .../golang.org/x/sys/unix/syscall_openbsd.go | 368 - .../x/sys/unix/syscall_openbsd_386.go | 33 - .../x/sys/unix/syscall_openbsd_amd64.go | 37 - .../x/sys/unix/syscall_openbsd_arm.go | 33 - .../golang.org/x/sys/unix/syscall_solaris.go | 730 - .../x/sys/unix/syscall_solaris_amd64.go | 23 - vendor/golang.org/x/sys/unix/syscall_unix.go | 394 - .../golang.org/x/sys/unix/syscall_unix_gc.go | 15 - vendor/golang.org/x/sys/unix/timestruct.go | 82 - vendor/golang.org/x/sys/unix/types_aix.go | 229 - vendor/golang.org/x/sys/unix/types_darwin.go | 277 - .../golang.org/x/sys/unix/types_dragonfly.go | 263 - vendor/golang.org/x/sys/unix/types_freebsd.go | 385 - vendor/golang.org/x/sys/unix/types_netbsd.go | 281 - vendor/golang.org/x/sys/unix/types_openbsd.go | 265 - vendor/golang.org/x/sys/unix/types_solaris.go | 266 - vendor/golang.org/x/sys/unix/xattr_bsd.go | 231 - .../golang.org/x/sys/unix/zerrors_aix_ppc.go | 1360 - .../x/sys/unix/zerrors_aix_ppc64.go | 1361 - .../x/sys/unix/zerrors_darwin_386.go | 1783 - .../x/sys/unix/zerrors_darwin_amd64.go | 1783 - .../x/sys/unix/zerrors_darwin_arm.go | 1783 - .../x/sys/unix/zerrors_darwin_arm64.go | 1783 - .../x/sys/unix/zerrors_dragonfly_amd64.go | 1616 - .../x/sys/unix/zerrors_freebsd_386.go | 1793 - .../x/sys/unix/zerrors_freebsd_amd64.go | 1794 - .../x/sys/unix/zerrors_freebsd_arm.go | 1802 - .../x/sys/unix/zerrors_linux_386.go | 2635 - .../x/sys/unix/zerrors_linux_amd64.go | 2635 - .../x/sys/unix/zerrors_linux_arm.go | 2641 - .../x/sys/unix/zerrors_linux_arm64.go | 2626 - .../x/sys/unix/zerrors_linux_mips.go | 2642 - .../x/sys/unix/zerrors_linux_mips64.go | 2642 - .../x/sys/unix/zerrors_linux_mips64le.go | 2642 - .../x/sys/unix/zerrors_linux_mipsle.go | 2642 - .../x/sys/unix/zerrors_linux_ppc64.go | 2695 - .../x/sys/unix/zerrors_linux_ppc64le.go | 2695 - .../x/sys/unix/zerrors_linux_s390x.go | 2695 - .../x/sys/unix/zerrors_linux_sparc64.go | 2142 - .../x/sys/unix/zerrors_netbsd_386.go | 1732 - .../x/sys/unix/zerrors_netbsd_amd64.go | 1722 - .../x/sys/unix/zerrors_netbsd_arm.go | 1711 - .../x/sys/unix/zerrors_openbsd_386.go | 1628 - .../x/sys/unix/zerrors_openbsd_amd64.go | 1735 - .../x/sys/unix/zerrors_openbsd_arm.go | 1630 - .../x/sys/unix/zerrors_solaris_amd64.go | 1532 - .../golang.org/x/sys/unix/zptrace386_linux.go | 80 - .../golang.org/x/sys/unix/zptracearm_linux.go | 41 - .../x/sys/unix/zptracemips_linux.go | 50 - .../x/sys/unix/zptracemipsle_linux.go | 50 - .../golang.org/x/sys/unix/zsyscall_aix_ppc.go | 1495 - .../x/sys/unix/zsyscall_aix_ppc64.go | 1495 - .../x/sys/unix/zsyscall_darwin_386.go | 1769 - .../x/sys/unix/zsyscall_darwin_amd64.go | 1769 - .../x/sys/unix/zsyscall_darwin_arm.go | 1769 - .../x/sys/unix/zsyscall_darwin_arm64.go | 1769 - .../x/sys/unix/zsyscall_dragonfly_amd64.go | 1508 - .../x/sys/unix/zsyscall_freebsd_386.go | 1935 - .../x/sys/unix/zsyscall_freebsd_amd64.go | 1935 - .../x/sys/unix/zsyscall_freebsd_arm.go | 1935 - .../x/sys/unix/zsyscall_linux_386.go | 2105 - .../x/sys/unix/zsyscall_linux_amd64.go | 2272 - .../x/sys/unix/zsyscall_linux_arm.go | 2207 - .../x/sys/unix/zsyscall_linux_arm64.go | 2114 - .../x/sys/unix/zsyscall_linux_mips.go | 2285 - .../x/sys/unix/zsyscall_linux_mips64.go | 2256 - .../x/sys/unix/zsyscall_linux_mips64le.go | 2256 - .../x/sys/unix/zsyscall_linux_mipsle.go | 2285 - .../x/sys/unix/zsyscall_linux_ppc64.go | 2319 - .../x/sys/unix/zsyscall_linux_ppc64le.go | 2319 - .../x/sys/unix/zsyscall_linux_s390x.go | 2089 - .../x/sys/unix/zsyscall_linux_sparc64.go | 2172 - .../x/sys/unix/zsyscall_netbsd_386.go | 1653 - .../x/sys/unix/zsyscall_netbsd_amd64.go | 1653 - .../x/sys/unix/zsyscall_netbsd_arm.go | 1653 - .../x/sys/unix/zsyscall_openbsd_386.go | 1508 - .../x/sys/unix/zsyscall_openbsd_amd64.go | 1508 - .../x/sys/unix/zsyscall_openbsd_arm.go | 1508 - .../x/sys/unix/zsyscall_solaris_amd64.go | 1697 - .../x/sys/unix/zsysctl_openbsd_386.go | 270 - .../x/sys/unix/zsysctl_openbsd_amd64.go | 257 - .../x/sys/unix/zsysctl_openbsd_arm.go | 270 - .../x/sys/unix/zsysnum_darwin_386.go | 436 - .../x/sys/unix/zsysnum_darwin_amd64.go | 436 - .../x/sys/unix/zsysnum_darwin_arm.go | 436 - .../x/sys/unix/zsysnum_darwin_arm64.go | 436 - .../x/sys/unix/zsysnum_dragonfly_amd64.go | 315 - .../x/sys/unix/zsysnum_freebsd_386.go | 403 - .../x/sys/unix/zsysnum_freebsd_amd64.go | 403 - .../x/sys/unix/zsysnum_freebsd_arm.go | 403 - .../x/sys/unix/zsysnum_linux_386.go | 392 - .../x/sys/unix/zsysnum_linux_amd64.go | 344 - .../x/sys/unix/zsysnum_linux_arm.go | 363 - .../x/sys/unix/zsysnum_linux_arm64.go | 287 - .../x/sys/unix/zsysnum_linux_mips.go | 377 - .../x/sys/unix/zsysnum_linux_mips64.go | 337 - .../x/sys/unix/zsysnum_linux_mips64le.go | 337 - .../x/sys/unix/zsysnum_linux_mipsle.go | 377 - .../x/sys/unix/zsysnum_linux_ppc64.go | 375 - .../x/sys/unix/zsysnum_linux_ppc64le.go | 375 - .../x/sys/unix/zsysnum_linux_s390x.go | 337 - .../x/sys/unix/zsysnum_linux_sparc64.go | 348 - .../x/sys/unix/zsysnum_netbsd_386.go | 274 - .../x/sys/unix/zsysnum_netbsd_amd64.go | 274 - .../x/sys/unix/zsysnum_netbsd_arm.go | 274 - .../x/sys/unix/zsysnum_openbsd_386.go | 207 - .../x/sys/unix/zsysnum_openbsd_amd64.go | 218 - .../x/sys/unix/zsysnum_openbsd_arm.go | 213 - .../golang.org/x/sys/unix/ztypes_aix_ppc.go | 306 - .../golang.org/x/sys/unix/ztypes_aix_ppc64.go | 313 - .../x/sys/unix/ztypes_darwin_386.go | 489 - .../x/sys/unix/ztypes_darwin_amd64.go | 499 - .../x/sys/unix/ztypes_darwin_arm.go | 490 - .../x/sys/unix/ztypes_darwin_arm64.go | 499 - .../x/sys/unix/ztypes_dragonfly_amd64.go | 469 - .../x/sys/unix/ztypes_freebsd_386.go | 536 - .../x/sys/unix/ztypes_freebsd_amd64.go | 539 - .../x/sys/unix/ztypes_freebsd_arm.go | 539 - .../golang.org/x/sys/unix/ztypes_linux_386.go | 1884 - .../x/sys/unix/ztypes_linux_amd64.go | 1906 - .../golang.org/x/sys/unix/ztypes_linux_arm.go | 1874 - .../x/sys/unix/ztypes_linux_arm64.go | 1885 - .../x/sys/unix/ztypes_linux_mips.go | 1879 - .../x/sys/unix/ztypes_linux_mips64.go | 1887 - .../x/sys/unix/ztypes_linux_mips64le.go | 1887 - .../x/sys/unix/ztypes_linux_mipsle.go | 1879 - .../x/sys/unix/ztypes_linux_ppc64.go | 1895 - .../x/sys/unix/ztypes_linux_ppc64le.go | 1895 - .../x/sys/unix/ztypes_linux_s390x.go | 1912 - .../x/sys/unix/ztypes_linux_sparc64.go | 690 - .../x/sys/unix/ztypes_netbsd_386.go | 448 - .../x/sys/unix/ztypes_netbsd_amd64.go | 455 - .../x/sys/unix/ztypes_netbsd_arm.go | 453 - .../x/sys/unix/ztypes_openbsd_386.go | 467 - .../x/sys/unix/ztypes_openbsd_amd64.go | 467 - .../x/sys/unix/ztypes_openbsd_arm.go | 460 - .../x/sys/unix/ztypes_solaris_amd64.go | 442 - vendor/golang.org/x/sys/windows/aliases.go | 13 - .../x/sys/windows/asm_windows_386.s | 13 - .../x/sys/windows/asm_windows_amd64.s | 13 - .../golang.org/x/sys/windows/dll_windows.go | 378 - .../golang.org/x/sys/windows/env_windows.go | 29 - vendor/golang.org/x/sys/windows/eventlog.go | 20 - .../golang.org/x/sys/windows/exec_windows.go | 97 - .../x/sys/windows/memory_windows.go | 26 - vendor/golang.org/x/sys/windows/mksyscall.go | 7 - vendor/golang.org/x/sys/windows/race.go | 30 - vendor/golang.org/x/sys/windows/race0.go | 25 - .../x/sys/windows/security_windows.go | 478 - vendor/golang.org/x/sys/windows/service.go | 183 - vendor/golang.org/x/sys/windows/str.go | 22 - vendor/golang.org/x/sys/windows/syscall.go | 74 - .../x/sys/windows/syscall_windows.go | 1155 - .../golang.org/x/sys/windows/types_windows.go | 1467 - .../x/sys/windows/types_windows_386.go | 22 - .../x/sys/windows/types_windows_amd64.go | 22 - .../x/sys/windows/zsyscall_windows.go | 2700 - vendor/golang.org/x/text/AUTHORS | 3 - vendor/golang.org/x/text/CONTRIBUTORS | 3 - vendor/golang.org/x/text/LICENSE | 27 - vendor/golang.org/x/text/PATENTS | 22 - .../x/text/collate/build/builder.go | 702 - .../x/text/collate/build/colelem.go | 294 - .../x/text/collate/build/contract.go | 309 - .../golang.org/x/text/collate/build/order.go | 393 - .../golang.org/x/text/collate/build/table.go | 81 - .../golang.org/x/text/collate/build/trie.go | 290 - vendor/golang.org/x/text/collate/collate.go | 403 - vendor/golang.org/x/text/collate/index.go | 32 - .../golang.org/x/text/collate/maketables.go | 553 - vendor/golang.org/x/text/collate/option.go | 239 - vendor/golang.org/x/text/collate/sort.go | 81 - vendor/golang.org/x/text/collate/tables.go | 73789 ---------------- .../x/text/internal/colltab/collelem.go | 371 - .../x/text/internal/colltab/colltab.go | 105 - .../x/text/internal/colltab/contract.go | 145 - .../x/text/internal/colltab/iter.go | 178 - .../x/text/internal/colltab/numeric.go | 236 - .../x/text/internal/colltab/table.go | 275 - .../x/text/internal/colltab/trie.go | 159 - .../x/text/internal/colltab/weighter.go | 31 - vendor/golang.org/x/text/internal/gen/code.go | 369 - vendor/golang.org/x/text/internal/gen/gen.go | 333 - vendor/golang.org/x/text/internal/tag/tag.go | 100 - .../x/text/internal/triegen/compact.go | 58 - .../x/text/internal/triegen/print.go | 251 - .../x/text/internal/triegen/triegen.go | 494 - vendor/golang.org/x/text/internal/ucd/ucd.go | 371 - vendor/golang.org/x/text/language/Makefile | 16 - vendor/golang.org/x/text/language/common.go | 16 - vendor/golang.org/x/text/language/coverage.go | 197 - vendor/golang.org/x/text/language/doc.go | 102 - vendor/golang.org/x/text/language/gen.go | 1712 - .../golang.org/x/text/language/gen_common.go | 20 - .../golang.org/x/text/language/gen_index.go | 162 - vendor/golang.org/x/text/language/go1_1.go | 38 - vendor/golang.org/x/text/language/go1_2.go | 11 - vendor/golang.org/x/text/language/index.go | 783 - vendor/golang.org/x/text/language/language.go | 907 - vendor/golang.org/x/text/language/lookup.go | 396 - vendor/golang.org/x/text/language/match.go | 933 - vendor/golang.org/x/text/language/parse.go | 859 - vendor/golang.org/x/text/language/tables.go | 3686 - vendor/golang.org/x/text/language/tags.go | 143 - .../x/text/secure/bidirule/bidirule.go | 336 - .../x/text/secure/bidirule/bidirule10.0.0.go | 11 - .../x/text/secure/bidirule/bidirule9.0.0.go | 14 - .../golang.org/x/text/transform/transform.go | 705 - vendor/golang.org/x/text/unicode/bidi/bidi.go | 198 - .../golang.org/x/text/unicode/bidi/bracket.go | 335 - vendor/golang.org/x/text/unicode/bidi/core.go | 1058 - vendor/golang.org/x/text/unicode/bidi/gen.go | 133 - .../x/text/unicode/bidi/gen_ranges.go | 57 - .../x/text/unicode/bidi/gen_trieval.go | 64 - vendor/golang.org/x/text/unicode/bidi/prop.go | 206 - .../x/text/unicode/bidi/tables10.0.0.go | 1815 - .../x/text/unicode/bidi/tables9.0.0.go | 1781 - .../golang.org/x/text/unicode/bidi/trieval.go | 60 - vendor/golang.org/x/text/unicode/cldr/base.go | 105 - vendor/golang.org/x/text/unicode/cldr/cldr.go | 130 - .../golang.org/x/text/unicode/cldr/collate.go | 359 - .../golang.org/x/text/unicode/cldr/decode.go | 171 - .../golang.org/x/text/unicode/cldr/makexml.go | 400 - .../golang.org/x/text/unicode/cldr/resolve.go | 602 - .../golang.org/x/text/unicode/cldr/slice.go | 144 - vendor/golang.org/x/text/unicode/cldr/xml.go | 1494 - .../x/text/unicode/norm/composition.go | 508 - .../x/text/unicode/norm/forminfo.go | 259 - .../golang.org/x/text/unicode/norm/input.go | 109 - vendor/golang.org/x/text/unicode/norm/iter.go | 457 - .../x/text/unicode/norm/maketables.go | 976 - .../x/text/unicode/norm/normalize.go | 609 - .../x/text/unicode/norm/readwriter.go | 125 - .../x/text/unicode/norm/tables10.0.0.go | 7653 -- .../x/text/unicode/norm/tables9.0.0.go | 7633 -- .../x/text/unicode/norm/transform.go | 88 - vendor/golang.org/x/text/unicode/norm/trie.go | 54 - .../golang.org/x/text/unicode/norm/triegen.go | 117 - .../x/text/unicode/rangetable/gen.go | 115 - .../x/text/unicode/rangetable/merge.go | 260 - .../x/text/unicode/rangetable/rangetable.go | 70 - .../x/text/unicode/rangetable/tables10.0.0.go | 6378 -- .../x/text/unicode/rangetable/tables9.0.0.go | 5737 -- vendor/golang.org/x/time/AUTHORS | 3 - vendor/golang.org/x/time/CONTRIBUTORS | 3 - vendor/golang.org/x/time/LICENSE | 27 - vendor/golang.org/x/time/PATENTS | 22 - vendor/golang.org/x/time/rate/rate.go | 384 - vendor/golang.org/x/time/rate/rate_go16.go | 21 - vendor/golang.org/x/time/rate/rate_go17.go | 21 - vendor/gopkg.in/validator.v2/.gitignore | 23 - vendor/gopkg.in/validator.v2/.travis.yml | 10 - vendor/gopkg.in/validator.v2/LICENSE | 201 - vendor/gopkg.in/validator.v2/README.md | 188 - vendor/gopkg.in/validator.v2/builtins.go | 271 - vendor/gopkg.in/validator.v2/doc.go | 265 - vendor/gopkg.in/validator.v2/validator.go | 369 - vendor/gopkg.in/yaml.v2/.travis.yml | 12 - vendor/gopkg.in/yaml.v2/LICENSE | 201 - vendor/gopkg.in/yaml.v2/LICENSE.libyaml | 31 - vendor/gopkg.in/yaml.v2/NOTICE | 13 - vendor/gopkg.in/yaml.v2/README.md | 133 - vendor/gopkg.in/yaml.v2/apic.go | 739 - vendor/gopkg.in/yaml.v2/decode.go | 775 - vendor/gopkg.in/yaml.v2/emitterc.go | 1685 - vendor/gopkg.in/yaml.v2/encode.go | 362 - vendor/gopkg.in/yaml.v2/go.mod | 5 - vendor/gopkg.in/yaml.v2/parserc.go | 1095 - vendor/gopkg.in/yaml.v2/readerc.go | 412 - vendor/gopkg.in/yaml.v2/resolve.go | 258 - vendor/gopkg.in/yaml.v2/scannerc.go | 2696 - vendor/gopkg.in/yaml.v2/sorter.go | 113 - vendor/gopkg.in/yaml.v2/writerc.go | 26 - vendor/gopkg.in/yaml.v2/yaml.go | 466 - vendor/gopkg.in/yaml.v2/yamlh.go | 738 - vendor/gopkg.in/yaml.v2/yamlprivateh.go | 173 - 765 files changed, 390962 deletions(-) delete mode 100644 vendor/github.com/Luzifer/rconfig/.travis.yml delete mode 100644 vendor/github.com/Luzifer/rconfig/History.md delete mode 100644 vendor/github.com/Luzifer/rconfig/LICENSE delete mode 100644 vendor/github.com/Luzifer/rconfig/README.md delete mode 100644 vendor/github.com/Luzifer/rconfig/config.go delete mode 100644 vendor/github.com/Luzifer/rconfig/vardefault_providers.go delete mode 100644 vendor/github.com/Sirupsen/logrus/.gitignore delete mode 100644 vendor/github.com/Sirupsen/logrus/.travis.yml delete mode 100644 vendor/github.com/Sirupsen/logrus/CHANGELOG.md delete mode 100644 vendor/github.com/Sirupsen/logrus/LICENSE delete mode 100644 vendor/github.com/Sirupsen/logrus/README.md delete mode 100644 vendor/github.com/Sirupsen/logrus/alt_exit.go delete mode 100644 vendor/github.com/Sirupsen/logrus/appveyor.yml delete mode 100644 vendor/github.com/Sirupsen/logrus/doc.go delete mode 100644 vendor/github.com/Sirupsen/logrus/entry.go delete mode 100644 vendor/github.com/Sirupsen/logrus/exported.go delete mode 100644 vendor/github.com/Sirupsen/logrus/formatter.go delete mode 100644 vendor/github.com/Sirupsen/logrus/hooks.go delete mode 100644 vendor/github.com/Sirupsen/logrus/json_formatter.go delete mode 100644 vendor/github.com/Sirupsen/logrus/logger.go delete mode 100644 vendor/github.com/Sirupsen/logrus/logrus.go delete mode 100644 vendor/github.com/Sirupsen/logrus/terminal_bsd.go delete mode 100644 vendor/github.com/Sirupsen/logrus/terminal_check_appengine.go delete mode 100644 vendor/github.com/Sirupsen/logrus/terminal_check_notappengine.go delete mode 100644 vendor/github.com/Sirupsen/logrus/terminal_linux.go delete mode 100644 vendor/github.com/Sirupsen/logrus/text_formatter.go delete mode 100644 vendor/github.com/Sirupsen/logrus/writer.go delete mode 100644 vendor/github.com/alecthomas/template/LICENSE delete mode 100644 vendor/github.com/alecthomas/template/README.md delete mode 100644 vendor/github.com/alecthomas/template/doc.go delete mode 100644 vendor/github.com/alecthomas/template/exec.go delete mode 100644 vendor/github.com/alecthomas/template/funcs.go delete mode 100644 vendor/github.com/alecthomas/template/helper.go delete mode 100644 vendor/github.com/alecthomas/template/parse/lex.go delete mode 100644 vendor/github.com/alecthomas/template/parse/node.go delete mode 100644 vendor/github.com/alecthomas/template/parse/parse.go delete mode 100644 vendor/github.com/alecthomas/template/template.go delete mode 100644 vendor/github.com/boombuler/barcode/.gitignore delete mode 100644 vendor/github.com/boombuler/barcode/LICENSE delete mode 100644 vendor/github.com/boombuler/barcode/README.md delete mode 100644 vendor/github.com/boombuler/barcode/barcode.go delete mode 100644 vendor/github.com/boombuler/barcode/qr/alphanumeric.go delete mode 100644 vendor/github.com/boombuler/barcode/qr/automatic.go delete mode 100644 vendor/github.com/boombuler/barcode/qr/blocks.go delete mode 100644 vendor/github.com/boombuler/barcode/qr/encoder.go delete mode 100644 vendor/github.com/boombuler/barcode/qr/errorcorrection.go delete mode 100644 vendor/github.com/boombuler/barcode/qr/numeric.go delete mode 100644 vendor/github.com/boombuler/barcode/qr/qrcode.go delete mode 100644 vendor/github.com/boombuler/barcode/qr/unicode.go delete mode 100644 vendor/github.com/boombuler/barcode/qr/versioninfo.go delete mode 100644 vendor/github.com/boombuler/barcode/scaledbarcode.go delete mode 100644 vendor/github.com/boombuler/barcode/utils/base1dcode.go delete mode 100644 vendor/github.com/boombuler/barcode/utils/bitlist.go delete mode 100644 vendor/github.com/boombuler/barcode/utils/galoisfield.go delete mode 100644 vendor/github.com/boombuler/barcode/utils/gfpoly.go delete mode 100644 vendor/github.com/boombuler/barcode/utils/reedsolomon.go delete mode 100644 vendor/github.com/boombuler/barcode/utils/runeint.go delete mode 100644 vendor/github.com/golang/snappy/.gitignore delete mode 100644 vendor/github.com/golang/snappy/AUTHORS delete mode 100644 vendor/github.com/golang/snappy/CONTRIBUTORS delete mode 100644 vendor/github.com/golang/snappy/LICENSE delete mode 100644 vendor/github.com/golang/snappy/README delete mode 100644 vendor/github.com/golang/snappy/decode.go delete mode 100644 vendor/github.com/golang/snappy/decode_amd64.go delete mode 100644 vendor/github.com/golang/snappy/decode_amd64.s delete mode 100644 vendor/github.com/golang/snappy/decode_other.go delete mode 100644 vendor/github.com/golang/snappy/encode.go delete mode 100644 vendor/github.com/golang/snappy/encode_amd64.go delete mode 100644 vendor/github.com/golang/snappy/encode_amd64.s delete mode 100644 vendor/github.com/golang/snappy/encode_other.go delete mode 100644 vendor/github.com/golang/snappy/snappy.go delete mode 100644 vendor/github.com/gorilla/context/.travis.yml delete mode 100644 vendor/github.com/gorilla/context/LICENSE delete mode 100644 vendor/github.com/gorilla/context/README.md delete mode 100644 vendor/github.com/gorilla/context/context.go delete mode 100644 vendor/github.com/gorilla/context/doc.go delete mode 100644 vendor/github.com/gorilla/mux/.travis.yml delete mode 100644 vendor/github.com/gorilla/mux/ISSUE_TEMPLATE.md delete mode 100644 vendor/github.com/gorilla/mux/LICENSE delete mode 100644 vendor/github.com/gorilla/mux/README.md delete mode 100644 vendor/github.com/gorilla/mux/context_gorilla.go delete mode 100644 vendor/github.com/gorilla/mux/context_native.go delete mode 100644 vendor/github.com/gorilla/mux/doc.go delete mode 100644 vendor/github.com/gorilla/mux/middleware.go delete mode 100644 vendor/github.com/gorilla/mux/mux.go delete mode 100644 vendor/github.com/gorilla/mux/regexp.go delete mode 100644 vendor/github.com/gorilla/mux/route.go delete mode 100644 vendor/github.com/gorilla/mux/test_helpers.go delete mode 100644 vendor/github.com/gorilla/securecookie/.travis.yml delete mode 100644 vendor/github.com/gorilla/securecookie/LICENSE delete mode 100644 vendor/github.com/gorilla/securecookie/README.md delete mode 100644 vendor/github.com/gorilla/securecookie/doc.go delete mode 100644 vendor/github.com/gorilla/securecookie/fuzz.go delete mode 100644 vendor/github.com/gorilla/securecookie/securecookie.go delete mode 100644 vendor/github.com/gorilla/sessions/.travis.yml delete mode 100644 vendor/github.com/gorilla/sessions/AUTHORS delete mode 100644 vendor/github.com/gorilla/sessions/LICENSE delete mode 100644 vendor/github.com/gorilla/sessions/README.md delete mode 100644 vendor/github.com/gorilla/sessions/doc.go delete mode 100644 vendor/github.com/gorilla/sessions/go.mod delete mode 100644 vendor/github.com/gorilla/sessions/lex.go delete mode 100644 vendor/github.com/gorilla/sessions/sessions.go delete mode 100644 vendor/github.com/gorilla/sessions/store.go delete mode 100644 vendor/github.com/hashicorp/errwrap/LICENSE delete mode 100644 vendor/github.com/hashicorp/errwrap/README.md delete mode 100644 vendor/github.com/hashicorp/errwrap/errwrap.go delete mode 100644 vendor/github.com/hashicorp/errwrap/go.mod delete mode 100644 vendor/github.com/hashicorp/go-cleanhttp/LICENSE delete mode 100644 vendor/github.com/hashicorp/go-cleanhttp/README.md delete mode 100644 vendor/github.com/hashicorp/go-cleanhttp/cleanhttp.go delete mode 100644 vendor/github.com/hashicorp/go-cleanhttp/doc.go delete mode 100644 vendor/github.com/hashicorp/go-cleanhttp/go.mod delete mode 100644 vendor/github.com/hashicorp/go-cleanhttp/handlers.go delete mode 100644 vendor/github.com/hashicorp/go-multierror/.travis.yml delete mode 100644 vendor/github.com/hashicorp/go-multierror/LICENSE delete mode 100644 vendor/github.com/hashicorp/go-multierror/Makefile delete mode 100644 vendor/github.com/hashicorp/go-multierror/README.md delete mode 100644 vendor/github.com/hashicorp/go-multierror/append.go delete mode 100644 vendor/github.com/hashicorp/go-multierror/flatten.go delete mode 100644 vendor/github.com/hashicorp/go-multierror/format.go delete mode 100644 vendor/github.com/hashicorp/go-multierror/go.mod delete mode 100644 vendor/github.com/hashicorp/go-multierror/go.sum delete mode 100644 vendor/github.com/hashicorp/go-multierror/multierror.go delete mode 100644 vendor/github.com/hashicorp/go-multierror/prefix.go delete mode 100644 vendor/github.com/hashicorp/go-multierror/sort.go delete mode 100644 vendor/github.com/hashicorp/go-retryablehttp/.gitignore delete mode 100644 vendor/github.com/hashicorp/go-retryablehttp/.travis.yml delete mode 100644 vendor/github.com/hashicorp/go-retryablehttp/LICENSE delete mode 100644 vendor/github.com/hashicorp/go-retryablehttp/Makefile delete mode 100644 vendor/github.com/hashicorp/go-retryablehttp/README.md delete mode 100644 vendor/github.com/hashicorp/go-retryablehttp/client.go delete mode 100644 vendor/github.com/hashicorp/go-rootcerts/.travis.yml delete mode 100644 vendor/github.com/hashicorp/go-rootcerts/LICENSE delete mode 100644 vendor/github.com/hashicorp/go-rootcerts/Makefile delete mode 100644 vendor/github.com/hashicorp/go-rootcerts/README.md delete mode 100644 vendor/github.com/hashicorp/go-rootcerts/doc.go delete mode 100644 vendor/github.com/hashicorp/go-rootcerts/rootcerts.go delete mode 100644 vendor/github.com/hashicorp/go-rootcerts/rootcerts_base.go delete mode 100644 vendor/github.com/hashicorp/go-rootcerts/rootcerts_darwin.go delete mode 120000 vendor/github.com/hashicorp/go-rootcerts/test-fixtures/capath-with-symlinks/securetrust.pem delete mode 120000 vendor/github.com/hashicorp/go-rootcerts/test-fixtures/capath-with-symlinks/thawte.pem delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/.gitignore delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/GNUmakefile delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/LICENSE delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/README.md delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/doc.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/ifaddr.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/ifaddrs.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/ifattr.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/ipaddr.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/ipaddrs.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/ipv4addr.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/ipv6addr.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/rfc.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/route_info.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/route_info_bsd.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/route_info_default.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/route_info_linux.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/route_info_solaris.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/route_info_windows.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/sockaddr.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/sockaddrs.go delete mode 100644 vendor/github.com/hashicorp/go-sockaddr/unixsock.go delete mode 100644 vendor/github.com/hashicorp/hcl/.gitignore delete mode 100644 vendor/github.com/hashicorp/hcl/.travis.yml delete mode 100644 vendor/github.com/hashicorp/hcl/LICENSE delete mode 100644 vendor/github.com/hashicorp/hcl/Makefile delete mode 100644 vendor/github.com/hashicorp/hcl/README.md delete mode 100644 vendor/github.com/hashicorp/hcl/appveyor.yml delete mode 100644 vendor/github.com/hashicorp/hcl/decoder.go delete mode 100644 vendor/github.com/hashicorp/hcl/go.mod delete mode 100644 vendor/github.com/hashicorp/hcl/go.sum delete mode 100644 vendor/github.com/hashicorp/hcl/hcl.go delete mode 100644 vendor/github.com/hashicorp/hcl/hcl/ast/ast.go delete mode 100644 vendor/github.com/hashicorp/hcl/hcl/ast/walk.go delete mode 100644 vendor/github.com/hashicorp/hcl/hcl/parser/error.go delete mode 100644 vendor/github.com/hashicorp/hcl/hcl/parser/parser.go delete mode 100644 vendor/github.com/hashicorp/hcl/hcl/scanner/scanner.go delete mode 100644 vendor/github.com/hashicorp/hcl/hcl/strconv/quote.go delete mode 100644 vendor/github.com/hashicorp/hcl/hcl/token/position.go delete mode 100644 vendor/github.com/hashicorp/hcl/hcl/token/token.go delete mode 100644 vendor/github.com/hashicorp/hcl/json/parser/flatten.go delete mode 100644 vendor/github.com/hashicorp/hcl/json/parser/parser.go delete mode 100644 vendor/github.com/hashicorp/hcl/json/scanner/scanner.go delete mode 100644 vendor/github.com/hashicorp/hcl/json/token/position.go delete mode 100644 vendor/github.com/hashicorp/hcl/json/token/token.go delete mode 100644 vendor/github.com/hashicorp/hcl/lex.go delete mode 100644 vendor/github.com/hashicorp/hcl/parse.go delete mode 100644 vendor/github.com/hashicorp/vault/LICENSE delete mode 100644 vendor/github.com/hashicorp/vault/api/auth.go delete mode 100644 vendor/github.com/hashicorp/vault/api/auth_token.go delete mode 100644 vendor/github.com/hashicorp/vault/api/client.go delete mode 100644 vendor/github.com/hashicorp/vault/api/help.go delete mode 100644 vendor/github.com/hashicorp/vault/api/logical.go delete mode 100644 vendor/github.com/hashicorp/vault/api/renewer.go delete mode 100644 vendor/github.com/hashicorp/vault/api/request.go delete mode 100644 vendor/github.com/hashicorp/vault/api/response.go delete mode 100644 vendor/github.com/hashicorp/vault/api/secret.go delete mode 100644 vendor/github.com/hashicorp/vault/api/ssh.go delete mode 100644 vendor/github.com/hashicorp/vault/api/ssh_agent.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_audit.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_auth.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_capabilities.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_config_cors.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_generate_root.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_health.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_init.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_leader.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_leases.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_mounts.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_plugins.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_policy.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_rekey.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_rotate.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_seal.go delete mode 100644 vendor/github.com/hashicorp/vault/api/sys_stepdown.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/compressutil/compress.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/consts/consts.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/consts/error.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/consts/replication.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/hclutil/hcl.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/jsonutil/json.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/parseutil/parseutil.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/strutil/strutil.go delete mode 100644 vendor/github.com/hashicorp/vault/website/LICENSE.md delete mode 100644 vendor/github.com/hashicorp/vault/website/source/api/system/license.html.md delete mode 100644 vendor/github.com/mitchellh/go-homedir/LICENSE delete mode 100644 vendor/github.com/mitchellh/go-homedir/README.md delete mode 100644 vendor/github.com/mitchellh/go-homedir/go.mod delete mode 100644 vendor/github.com/mitchellh/go-homedir/homedir.go delete mode 100644 vendor/github.com/mitchellh/mapstructure/.travis.yml delete mode 100644 vendor/github.com/mitchellh/mapstructure/LICENSE delete mode 100644 vendor/github.com/mitchellh/mapstructure/README.md delete mode 100644 vendor/github.com/mitchellh/mapstructure/decode_hooks.go delete mode 100644 vendor/github.com/mitchellh/mapstructure/error.go delete mode 100644 vendor/github.com/mitchellh/mapstructure/go.mod delete mode 100644 vendor/github.com/mitchellh/mapstructure/mapstructure.go delete mode 100644 vendor/github.com/pquerna/otp/.travis.yml delete mode 100644 vendor/github.com/pquerna/otp/LICENSE delete mode 100644 vendor/github.com/pquerna/otp/NOTICE delete mode 100644 vendor/github.com/pquerna/otp/README.md delete mode 100644 vendor/github.com/pquerna/otp/doc.go delete mode 100644 vendor/github.com/pquerna/otp/hotp/hotp.go delete mode 100644 vendor/github.com/pquerna/otp/otp.go delete mode 100644 vendor/github.com/pquerna/otp/totp/totp.go delete mode 100644 vendor/github.com/ryanuber/go-glob/.travis.yml delete mode 100644 vendor/github.com/ryanuber/go-glob/LICENSE delete mode 100644 vendor/github.com/ryanuber/go-glob/README.md delete mode 100644 vendor/github.com/ryanuber/go-glob/glob.go delete mode 100644 vendor/github.com/spf13/pflag/.gitignore delete mode 100644 vendor/github.com/spf13/pflag/.travis.yml delete mode 100644 vendor/github.com/spf13/pflag/LICENSE delete mode 100644 vendor/github.com/spf13/pflag/README.md delete mode 100644 vendor/github.com/spf13/pflag/bool.go delete mode 100644 vendor/github.com/spf13/pflag/bool_slice.go delete mode 100644 vendor/github.com/spf13/pflag/bytes.go delete mode 100644 vendor/github.com/spf13/pflag/count.go delete mode 100644 vendor/github.com/spf13/pflag/duration.go delete mode 100644 vendor/github.com/spf13/pflag/duration_slice.go delete mode 100644 vendor/github.com/spf13/pflag/flag.go delete mode 100644 vendor/github.com/spf13/pflag/float32.go delete mode 100644 vendor/github.com/spf13/pflag/float64.go delete mode 100644 vendor/github.com/spf13/pflag/golangflag.go delete mode 100644 vendor/github.com/spf13/pflag/int.go delete mode 100644 vendor/github.com/spf13/pflag/int16.go delete mode 100644 vendor/github.com/spf13/pflag/int32.go delete mode 100644 vendor/github.com/spf13/pflag/int64.go delete mode 100644 vendor/github.com/spf13/pflag/int8.go delete mode 100644 vendor/github.com/spf13/pflag/int_slice.go delete mode 100644 vendor/github.com/spf13/pflag/ip.go delete mode 100644 vendor/github.com/spf13/pflag/ip_slice.go delete mode 100644 vendor/github.com/spf13/pflag/ipmask.go delete mode 100644 vendor/github.com/spf13/pflag/ipnet.go delete mode 100644 vendor/github.com/spf13/pflag/string.go delete mode 100644 vendor/github.com/spf13/pflag/string_array.go delete mode 100644 vendor/github.com/spf13/pflag/string_slice.go delete mode 100644 vendor/github.com/spf13/pflag/uint.go delete mode 100644 vendor/github.com/spf13/pflag/uint16.go delete mode 100644 vendor/github.com/spf13/pflag/uint32.go delete mode 100644 vendor/github.com/spf13/pflag/uint64.go delete mode 100644 vendor/github.com/spf13/pflag/uint8.go delete mode 100644 vendor/github.com/spf13/pflag/uint_slice.go delete mode 100644 vendor/github.com/tdewolff/minify/.gitattributes delete mode 100644 vendor/github.com/tdewolff/minify/.gitignore delete mode 100644 vendor/github.com/tdewolff/minify/.goreleaser.yml delete mode 100644 vendor/github.com/tdewolff/minify/.travis.yml delete mode 100644 vendor/github.com/tdewolff/minify/LICENSE.md delete mode 100644 vendor/github.com/tdewolff/minify/README.md delete mode 100644 vendor/github.com/tdewolff/minify/common.go delete mode 100644 vendor/github.com/tdewolff/minify/html/buffer.go delete mode 100644 vendor/github.com/tdewolff/minify/html/html.go delete mode 100644 vendor/github.com/tdewolff/minify/html/table.go delete mode 100644 vendor/github.com/tdewolff/minify/js/js.go delete mode 100644 vendor/github.com/tdewolff/minify/minify.go delete mode 100644 vendor/github.com/tdewolff/parse/.travis.yml delete mode 100644 vendor/github.com/tdewolff/parse/LICENSE.md delete mode 100644 vendor/github.com/tdewolff/parse/README.md delete mode 100644 vendor/github.com/tdewolff/parse/buffer/buffer.go delete mode 100644 vendor/github.com/tdewolff/parse/buffer/lexer.go delete mode 100644 vendor/github.com/tdewolff/parse/buffer/reader.go delete mode 100644 vendor/github.com/tdewolff/parse/buffer/streamlexer.go delete mode 100644 vendor/github.com/tdewolff/parse/buffer/writer.go delete mode 100644 vendor/github.com/tdewolff/parse/common.go delete mode 100644 vendor/github.com/tdewolff/parse/error.go delete mode 100644 vendor/github.com/tdewolff/parse/html/README.md delete mode 100644 vendor/github.com/tdewolff/parse/html/hash.go delete mode 100644 vendor/github.com/tdewolff/parse/html/lex.go delete mode 100644 vendor/github.com/tdewolff/parse/html/util.go delete mode 100644 vendor/github.com/tdewolff/parse/js/README.md delete mode 100644 vendor/github.com/tdewolff/parse/js/hash.go delete mode 100644 vendor/github.com/tdewolff/parse/js/lex.go delete mode 100644 vendor/github.com/tdewolff/parse/position.go delete mode 100644 vendor/github.com/tdewolff/parse/strconv/float.go delete mode 100644 vendor/github.com/tdewolff/parse/strconv/int.go delete mode 100644 vendor/github.com/tdewolff/parse/strconv/price.go delete mode 100644 vendor/github.com/tdewolff/parse/util.go delete mode 100644 vendor/golang.org/x/crypto/AUTHORS delete mode 100644 vendor/golang.org/x/crypto/CONTRIBUTORS delete mode 100644 vendor/golang.org/x/crypto/LICENSE delete mode 100644 vendor/golang.org/x/crypto/PATENTS delete mode 100644 vendor/golang.org/x/crypto/ssh/terminal/terminal.go delete mode 100644 vendor/golang.org/x/crypto/ssh/terminal/util.go delete mode 100644 vendor/golang.org/x/crypto/ssh/terminal/util_bsd.go delete mode 100644 vendor/golang.org/x/crypto/ssh/terminal/util_linux.go delete mode 100644 vendor/golang.org/x/crypto/ssh/terminal/util_plan9.go delete mode 100644 vendor/golang.org/x/crypto/ssh/terminal/util_solaris.go delete mode 100644 vendor/golang.org/x/crypto/ssh/terminal/util_windows.go delete mode 100644 vendor/golang.org/x/net/AUTHORS delete mode 100644 vendor/golang.org/x/net/CONTRIBUTORS delete mode 100644 vendor/golang.org/x/net/LICENSE delete mode 100644 vendor/golang.org/x/net/PATENTS delete mode 100644 vendor/golang.org/x/net/context/context.go delete mode 100644 vendor/golang.org/x/net/context/go17.go delete mode 100644 vendor/golang.org/x/net/context/go19.go delete mode 100644 vendor/golang.org/x/net/context/pre_go17.go delete mode 100644 vendor/golang.org/x/net/context/pre_go19.go delete mode 100644 vendor/golang.org/x/net/http/httpguts/guts.go delete mode 100644 vendor/golang.org/x/net/http/httpguts/httplex.go delete mode 100644 vendor/golang.org/x/net/http2/.gitignore delete mode 100644 vendor/golang.org/x/net/http2/Dockerfile delete mode 100644 vendor/golang.org/x/net/http2/Makefile delete mode 100644 vendor/golang.org/x/net/http2/README delete mode 100644 vendor/golang.org/x/net/http2/ciphers.go delete mode 100644 vendor/golang.org/x/net/http2/client_conn_pool.go delete mode 100644 vendor/golang.org/x/net/http2/configure_transport.go delete mode 100644 vendor/golang.org/x/net/http2/databuffer.go delete mode 100644 vendor/golang.org/x/net/http2/errors.go delete mode 100644 vendor/golang.org/x/net/http2/flow.go delete mode 100644 vendor/golang.org/x/net/http2/frame.go delete mode 100644 vendor/golang.org/x/net/http2/go111.go delete mode 100644 vendor/golang.org/x/net/http2/go16.go delete mode 100644 vendor/golang.org/x/net/http2/go17.go delete mode 100644 vendor/golang.org/x/net/http2/go17_not18.go delete mode 100644 vendor/golang.org/x/net/http2/go18.go delete mode 100644 vendor/golang.org/x/net/http2/go19.go delete mode 100644 vendor/golang.org/x/net/http2/gotrack.go delete mode 100644 vendor/golang.org/x/net/http2/headermap.go delete mode 100644 vendor/golang.org/x/net/http2/hpack/encode.go delete mode 100644 vendor/golang.org/x/net/http2/hpack/hpack.go delete mode 100644 vendor/golang.org/x/net/http2/hpack/huffman.go delete mode 100644 vendor/golang.org/x/net/http2/hpack/tables.go delete mode 100644 vendor/golang.org/x/net/http2/http2.go delete mode 100644 vendor/golang.org/x/net/http2/not_go111.go delete mode 100644 vendor/golang.org/x/net/http2/not_go16.go delete mode 100644 vendor/golang.org/x/net/http2/not_go17.go delete mode 100644 vendor/golang.org/x/net/http2/not_go18.go delete mode 100644 vendor/golang.org/x/net/http2/not_go19.go delete mode 100644 vendor/golang.org/x/net/http2/pipe.go delete mode 100644 vendor/golang.org/x/net/http2/server.go delete mode 100644 vendor/golang.org/x/net/http2/transport.go delete mode 100644 vendor/golang.org/x/net/http2/write.go delete mode 100644 vendor/golang.org/x/net/http2/writesched.go delete mode 100644 vendor/golang.org/x/net/http2/writesched_priority.go delete mode 100644 vendor/golang.org/x/net/http2/writesched_random.go delete mode 100644 vendor/golang.org/x/net/idna/idna.go delete mode 100644 vendor/golang.org/x/net/idna/punycode.go delete mode 100644 vendor/golang.org/x/net/idna/tables.go delete mode 100644 vendor/golang.org/x/net/idna/trie.go delete mode 100644 vendor/golang.org/x/net/idna/trieval.go delete mode 100644 vendor/golang.org/x/sys/AUTHORS delete mode 100644 vendor/golang.org/x/sys/CONTRIBUTORS delete mode 100644 vendor/golang.org/x/sys/LICENSE delete mode 100644 vendor/golang.org/x/sys/PATENTS 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/affinity_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/aliases.go delete mode 100644 vendor/golang.org/x/sys/unix/asm_darwin_386.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_darwin_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_darwin_arm.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_darwin_arm64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_dragonfly_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_freebsd_386.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_freebsd_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_freebsd_arm.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_386.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_arm.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_arm64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_mips64x.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_mipsx.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_s390x.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_netbsd_386.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_netbsd_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_netbsd_arm.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_openbsd_386.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_openbsd_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_openbsd_arm.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_solaris_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/bluetooth_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/cap_freebsd.go delete mode 100644 vendor/golang.org/x/sys/unix/constants.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_dragonfly.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_freebsd.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_netbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_openbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/dirent.go delete mode 100644 vendor/golang.org/x/sys/unix/endian_big.go delete mode 100644 vendor/golang.org/x/sys/unix/endian_little.go delete mode 100644 vendor/golang.org/x/sys/unix/env_unix.go delete mode 100644 vendor/golang.org/x/sys/unix/errors_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/errors_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/errors_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/fcntl.go delete mode 100644 vendor/golang.org/x/sys/unix/fcntl_linux_32bit.go delete mode 100644 vendor/golang.org/x/sys/unix/gccgo.go delete mode 100644 vendor/golang.org/x/sys/unix/gccgo_c.c delete mode 100644 vendor/golang.org/x/sys/unix/gccgo_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ioctl.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 100644 vendor/golang.org/x/sys/unix/mkpost.go delete mode 100755 vendor/golang.org/x/sys/unix/mksyscall.pl delete mode 100644 vendor/golang.org/x/sys/unix/mksyscall_aix.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/openbsd_pledge.go delete mode 100644 vendor/golang.org/x/sys/unix/pagesize_unix.go delete mode 100644 vendor/golang.org/x/sys/unix/race.go delete mode 100644 vendor/golang.org/x/sys/unix/race0.go delete mode 100644 vendor/golang.org/x/sys/unix/sockcmsg_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/sockcmsg_unix.go delete mode 100644 vendor/golang.org/x/sys/unix/str.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_aix.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_bsd.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_dragonfly.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_amd64_gc.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gc.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gc_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gccgo_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gccgo_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_solaris.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_solaris_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_unix.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_unix_gc.go delete mode 100644 vendor/golang.org/x/sys/unix/timestruct.go delete mode 100644 vendor/golang.org/x/sys/unix/types_aix.go delete mode 100644 vendor/golang.org/x/sys/unix/types_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/types_dragonfly.go delete mode 100644 vendor/golang.org/x/sys/unix/types_freebsd.go delete mode 100644 vendor/golang.org/x/sys/unix/types_netbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/types_openbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/types_solaris.go delete mode 100644 vendor/golang.org/x/sys/unix/xattr_bsd.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_darwin_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_darwin_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_mips.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_solaris_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zptrace386_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zptracearm_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zptracemips_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zptracemipsle_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_darwin_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_darwin_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_darwin_386.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_darwin_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_mips.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_solaris_amd64.go delete mode 100644 vendor/golang.org/x/sys/windows/aliases.go delete mode 100644 vendor/golang.org/x/sys/windows/asm_windows_386.s delete mode 100644 vendor/golang.org/x/sys/windows/asm_windows_amd64.s delete mode 100644 vendor/golang.org/x/sys/windows/dll_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/env_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/eventlog.go delete mode 100644 vendor/golang.org/x/sys/windows/exec_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/memory_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/mksyscall.go delete mode 100644 vendor/golang.org/x/sys/windows/race.go delete mode 100644 vendor/golang.org/x/sys/windows/race0.go delete mode 100644 vendor/golang.org/x/sys/windows/security_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/service.go delete mode 100644 vendor/golang.org/x/sys/windows/str.go delete mode 100644 vendor/golang.org/x/sys/windows/syscall.go delete mode 100644 vendor/golang.org/x/sys/windows/syscall_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/types_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/types_windows_386.go delete mode 100644 vendor/golang.org/x/sys/windows/types_windows_amd64.go delete mode 100644 vendor/golang.org/x/sys/windows/zsyscall_windows.go delete mode 100644 vendor/golang.org/x/text/AUTHORS delete mode 100644 vendor/golang.org/x/text/CONTRIBUTORS delete mode 100644 vendor/golang.org/x/text/LICENSE delete mode 100644 vendor/golang.org/x/text/PATENTS delete mode 100644 vendor/golang.org/x/text/collate/build/builder.go delete mode 100644 vendor/golang.org/x/text/collate/build/colelem.go delete mode 100644 vendor/golang.org/x/text/collate/build/contract.go delete mode 100644 vendor/golang.org/x/text/collate/build/order.go delete mode 100644 vendor/golang.org/x/text/collate/build/table.go delete mode 100644 vendor/golang.org/x/text/collate/build/trie.go delete mode 100644 vendor/golang.org/x/text/collate/collate.go delete mode 100644 vendor/golang.org/x/text/collate/index.go delete mode 100644 vendor/golang.org/x/text/collate/maketables.go delete mode 100644 vendor/golang.org/x/text/collate/option.go delete mode 100644 vendor/golang.org/x/text/collate/sort.go delete mode 100644 vendor/golang.org/x/text/collate/tables.go delete mode 100644 vendor/golang.org/x/text/internal/colltab/collelem.go delete mode 100644 vendor/golang.org/x/text/internal/colltab/colltab.go delete mode 100644 vendor/golang.org/x/text/internal/colltab/contract.go delete mode 100644 vendor/golang.org/x/text/internal/colltab/iter.go delete mode 100644 vendor/golang.org/x/text/internal/colltab/numeric.go delete mode 100644 vendor/golang.org/x/text/internal/colltab/table.go delete mode 100644 vendor/golang.org/x/text/internal/colltab/trie.go delete mode 100644 vendor/golang.org/x/text/internal/colltab/weighter.go delete mode 100644 vendor/golang.org/x/text/internal/gen/code.go delete mode 100644 vendor/golang.org/x/text/internal/gen/gen.go delete mode 100644 vendor/golang.org/x/text/internal/tag/tag.go delete mode 100644 vendor/golang.org/x/text/internal/triegen/compact.go delete mode 100644 vendor/golang.org/x/text/internal/triegen/print.go delete mode 100644 vendor/golang.org/x/text/internal/triegen/triegen.go delete mode 100644 vendor/golang.org/x/text/internal/ucd/ucd.go delete mode 100644 vendor/golang.org/x/text/language/Makefile delete mode 100644 vendor/golang.org/x/text/language/common.go delete mode 100644 vendor/golang.org/x/text/language/coverage.go delete mode 100644 vendor/golang.org/x/text/language/doc.go delete mode 100644 vendor/golang.org/x/text/language/gen.go delete mode 100644 vendor/golang.org/x/text/language/gen_common.go delete mode 100644 vendor/golang.org/x/text/language/gen_index.go delete mode 100644 vendor/golang.org/x/text/language/go1_1.go delete mode 100644 vendor/golang.org/x/text/language/go1_2.go delete mode 100644 vendor/golang.org/x/text/language/index.go delete mode 100644 vendor/golang.org/x/text/language/language.go delete mode 100644 vendor/golang.org/x/text/language/lookup.go delete mode 100644 vendor/golang.org/x/text/language/match.go delete mode 100644 vendor/golang.org/x/text/language/parse.go delete mode 100644 vendor/golang.org/x/text/language/tables.go delete mode 100644 vendor/golang.org/x/text/language/tags.go delete mode 100644 vendor/golang.org/x/text/secure/bidirule/bidirule.go delete mode 100644 vendor/golang.org/x/text/secure/bidirule/bidirule10.0.0.go delete mode 100644 vendor/golang.org/x/text/secure/bidirule/bidirule9.0.0.go delete mode 100644 vendor/golang.org/x/text/transform/transform.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/bidi.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/bracket.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/core.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/gen.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/gen_ranges.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/gen_trieval.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/prop.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/tables10.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/tables9.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/trieval.go delete mode 100644 vendor/golang.org/x/text/unicode/cldr/base.go delete mode 100644 vendor/golang.org/x/text/unicode/cldr/cldr.go delete mode 100644 vendor/golang.org/x/text/unicode/cldr/collate.go delete mode 100644 vendor/golang.org/x/text/unicode/cldr/decode.go delete mode 100644 vendor/golang.org/x/text/unicode/cldr/makexml.go delete mode 100644 vendor/golang.org/x/text/unicode/cldr/resolve.go delete mode 100644 vendor/golang.org/x/text/unicode/cldr/slice.go delete mode 100644 vendor/golang.org/x/text/unicode/cldr/xml.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/composition.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/forminfo.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/input.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/iter.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/maketables.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/normalize.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/readwriter.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/tables10.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/tables9.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/transform.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/trie.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/triegen.go delete mode 100644 vendor/golang.org/x/text/unicode/rangetable/gen.go delete mode 100644 vendor/golang.org/x/text/unicode/rangetable/merge.go delete mode 100644 vendor/golang.org/x/text/unicode/rangetable/rangetable.go delete mode 100644 vendor/golang.org/x/text/unicode/rangetable/tables10.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/rangetable/tables9.0.0.go delete mode 100644 vendor/golang.org/x/time/AUTHORS delete mode 100644 vendor/golang.org/x/time/CONTRIBUTORS delete mode 100644 vendor/golang.org/x/time/LICENSE delete mode 100644 vendor/golang.org/x/time/PATENTS delete mode 100644 vendor/golang.org/x/time/rate/rate.go delete mode 100644 vendor/golang.org/x/time/rate/rate_go16.go delete mode 100644 vendor/golang.org/x/time/rate/rate_go17.go delete mode 100644 vendor/gopkg.in/validator.v2/.gitignore delete mode 100644 vendor/gopkg.in/validator.v2/.travis.yml delete mode 100644 vendor/gopkg.in/validator.v2/LICENSE delete mode 100644 vendor/gopkg.in/validator.v2/README.md delete mode 100644 vendor/gopkg.in/validator.v2/builtins.go delete mode 100644 vendor/gopkg.in/validator.v2/doc.go delete mode 100644 vendor/gopkg.in/validator.v2/validator.go delete mode 100644 vendor/gopkg.in/yaml.v2/.travis.yml delete mode 100644 vendor/gopkg.in/yaml.v2/LICENSE delete mode 100644 vendor/gopkg.in/yaml.v2/LICENSE.libyaml delete mode 100644 vendor/gopkg.in/yaml.v2/NOTICE delete mode 100644 vendor/gopkg.in/yaml.v2/README.md delete mode 100644 vendor/gopkg.in/yaml.v2/apic.go delete mode 100644 vendor/gopkg.in/yaml.v2/decode.go delete mode 100644 vendor/gopkg.in/yaml.v2/emitterc.go delete mode 100644 vendor/gopkg.in/yaml.v2/encode.go delete mode 100644 vendor/gopkg.in/yaml.v2/go.mod delete mode 100644 vendor/gopkg.in/yaml.v2/parserc.go delete mode 100644 vendor/gopkg.in/yaml.v2/readerc.go delete mode 100644 vendor/gopkg.in/yaml.v2/resolve.go delete mode 100644 vendor/gopkg.in/yaml.v2/scannerc.go delete mode 100644 vendor/gopkg.in/yaml.v2/sorter.go delete mode 100644 vendor/gopkg.in/yaml.v2/writerc.go delete mode 100644 vendor/gopkg.in/yaml.v2/yaml.go delete mode 100644 vendor/gopkg.in/yaml.v2/yamlh.go delete mode 100644 vendor/gopkg.in/yaml.v2/yamlprivateh.go diff --git a/vendor/github.com/Luzifer/rconfig/.travis.yml b/vendor/github.com/Luzifer/rconfig/.travis.yml deleted file mode 100644 index b5c25ee..0000000 --- a/vendor/github.com/Luzifer/rconfig/.travis.yml +++ /dev/null @@ -1,8 +0,0 @@ -language: go - -go: - - 1.6 - - 1.7 - - tip - -script: go test -v -race -cover ./... diff --git a/vendor/github.com/Luzifer/rconfig/History.md b/vendor/github.com/Luzifer/rconfig/History.md deleted file mode 100644 index 5adadd9..0000000 --- a/vendor/github.com/Luzifer/rconfig/History.md +++ /dev/null @@ -1,9 +0,0 @@ -# 1.2.0 / 2017-06-19 - - * Add ParseAndValidate method - -# 1.1.0 / 2016-06-28 - - * Support time.Duration config parameters - * Added goreportcard badge - * Added testcase for using bool with ENV and default diff --git a/vendor/github.com/Luzifer/rconfig/LICENSE b/vendor/github.com/Luzifer/rconfig/LICENSE deleted file mode 100644 index 4fde5d2..0000000 --- a/vendor/github.com/Luzifer/rconfig/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2015 Knut Ahlers - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/vendor/github.com/Luzifer/rconfig/README.md b/vendor/github.com/Luzifer/rconfig/README.md deleted file mode 100644 index f42a664..0000000 --- a/vendor/github.com/Luzifer/rconfig/README.md +++ /dev/null @@ -1,87 +0,0 @@ -[![Build Status](https://travis-ci.org/Luzifer/rconfig.svg?branch=master)](https://travis-ci.org/Luzifer/rconfig) -[![License: Apache v2.0](https://badge.luzifer.io/v1/badge?color=5d79b5&title=license&text=Apache+v2.0)](http://www.apache.org/licenses/LICENSE-2.0) -[![Documentation](https://badge.luzifer.io/v1/badge?title=godoc&text=reference)](https://godoc.org/github.com/Luzifer/rconfig) -[![Go Report](http://goreportcard.com/badge/Luzifer/rconfig)](http://goreportcard.com/report/Luzifer/rconfig) - -## Description - -> Package rconfig implements a CLI configuration reader with struct-embedded defaults, environment variables and posix compatible flag parsing using the [pflag](https://github.com/spf13/pflag) library. - -## Installation - -Install by running: - -``` -go get -u github.com/Luzifer/rconfig -``` - -OR fetch a specific version: - -``` -go get -u gopkg.in/luzifer/rconfig.v1 -``` - -Run tests by running: - -``` -go test -v -race -cover github.com/Luzifer/rconfig -``` - -## Usage - -A very simple usecase is to just configure a struct inside the vars section of your `main.go` and to parse the commandline flags from the `main()` function: - -```go -package main - -import ( - "fmt" - "github.com/Luzifer/rconfig" -) - -var ( - cfg = struct { - Username string `default:"unknown" flag:"user" description:"Your name"` - Details struct { - Age int `default:"25" flag:"age" env:"age" description:"Your age"` - } - }{} -) - -func main() { - rconfig.Parse(&cfg) - - fmt.Printf("Hello %s, happy birthday for your %dth birthday.", - cfg.Username, - cfg.Details.Age) -} -``` - -### Provide variable defaults by using a file - -Given you have a file `~/.myapp.yml` containing some secrets or usernames (for the example below username is assumed to be "luzifer") as a default configuration for your application you can use this source code to load the defaults from that file using the `vardefault` tag in your configuration struct. - -The order of the directives (lower number = higher precedence): - -1. Flags provided in command line -1. Environment variables -1. Variable defaults (`vardefault` tag in the struct) -1. `default` tag in the struct - -```go -var cfg = struct { - Username string `vardefault:"username" flag:"username" description:"Your username"` -} - -func main() { - rconfig.SetVariableDefaults(rconfig.VarDefaultsFromYAMLFile("~/.myapp.yml")) - rconfig.Parse(&cfg) - - fmt.Printf("Username = %s", cfg.Username) - // Output: Username = luzifer -} -``` - -## More info - -You can see the full reference documentation of the rconfig package [at godoc.org](https://godoc.org/github.com/Luzifer/rconfig), or through go's standard documentation system by running `godoc -http=:6060` and browsing to [http://localhost:6060/pkg/github.com/Luzifer/rconfig](http://localhost:6060/pkg/github.com/Luzifer/rconfig) after installation. diff --git a/vendor/github.com/Luzifer/rconfig/config.go b/vendor/github.com/Luzifer/rconfig/config.go deleted file mode 100644 index 251909d..0000000 --- a/vendor/github.com/Luzifer/rconfig/config.go +++ /dev/null @@ -1,356 +0,0 @@ -// Package rconfig implements a CLI configuration reader with struct-embedded -// defaults, environment variables and posix compatible flag parsing using -// the pflag library. -package rconfig - -import ( - "errors" - "fmt" - "os" - "reflect" - "strconv" - "strings" - "time" - - "github.com/spf13/pflag" - validator "gopkg.in/validator.v2" -) - -var ( - fs *pflag.FlagSet - variableDefaults map[string]string -) - -func init() { - variableDefaults = make(map[string]string) -} - -// Parse takes the pointer to a struct filled with variables which should be read -// from ENV, default or flag. The precedence in this is flag > ENV > default. So -// if a flag is specified on the CLI it will overwrite the ENV and otherwise ENV -// overwrites the default specified. -// -// For your configuration struct you can use the following struct-tags to control -// the behavior of rconfig: -// -// default: Set a default value -// vardefault: Read the default value from the variable defaults -// env: Read the value from this environment variable -// flag: Flag to read in format "long,short" (for example "listen,l") -// description: A help text for Usage output to guide your users -// -// The format you need to specify those values you can see in the example to this -// function. -// -func Parse(config interface{}) error { - return parse(config, nil) -} - -// ParseAndValidate works exactly like Parse but implements an additional run of -// the go-validator package on the configuration struct. Therefore additonal struct -// tags are supported like described in the readme file of the go-validator package: -// -// https://github.com/go-validator/validator/tree/v2#usage -func ParseAndValidate(config interface{}) error { - return parseAndValidate(config, nil) -} - -// Args returns the non-flag command-line arguments. -func Args() []string { - return fs.Args() -} - -// Usage prints a basic usage with the corresponding defaults for the flags to -// os.Stdout. The defaults are derived from the `default` struct-tag and the ENV. -func Usage() { - if fs != nil && fs.Parsed() { - fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) - fs.PrintDefaults() - } -} - -// SetVariableDefaults presets the parser with a map of default values to be used -// when specifying the vardefault tag -func SetVariableDefaults(defaults map[string]string) { - variableDefaults = defaults -} - -func parseAndValidate(in interface{}, args []string) error { - if err := parse(in, args); err != nil { - return err - } - - return validator.Validate(in) -} - -func parse(in interface{}, args []string) error { - if args == nil { - args = os.Args - } - - fs = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError) - if err := execTags(in, fs); err != nil { - return err - } - - return fs.Parse(args) -} - -func execTags(in interface{}, fs *pflag.FlagSet) error { - if reflect.TypeOf(in).Kind() != reflect.Ptr { - return errors.New("Calling parser with non-pointer") - } - - if reflect.ValueOf(in).Elem().Kind() != reflect.Struct { - return errors.New("Calling parser with pointer to non-struct") - } - - st := reflect.ValueOf(in).Elem() - for i := 0; i < st.NumField(); i++ { - valField := st.Field(i) - typeField := st.Type().Field(i) - - if typeField.Tag.Get("default") == "" && typeField.Tag.Get("env") == "" && typeField.Tag.Get("flag") == "" && typeField.Type.Kind() != reflect.Struct { - // None of our supported tags is present and it's not a sub-struct - continue - } - - value := varDefault(typeField.Tag.Get("vardefault"), typeField.Tag.Get("default")) - value = envDefault(typeField.Tag.Get("env"), value) - parts := strings.Split(typeField.Tag.Get("flag"), ",") - - switch typeField.Type { - case reflect.TypeOf(time.Duration(0)): - v, err := time.ParseDuration(value) - if err != nil { - if value == "" { - v = time.Duration(0) - } else { - return err - } - } - - if typeField.Tag.Get("flag") != "" { - if len(parts) == 1 { - fs.DurationVar(valField.Addr().Interface().(*time.Duration), parts[0], v, typeField.Tag.Get("description")) - } else { - fs.DurationVarP(valField.Addr().Interface().(*time.Duration), parts[0], parts[1], v, typeField.Tag.Get("description")) - } - } else { - valField.Set(reflect.ValueOf(v)) - } - continue - } - - switch typeField.Type.Kind() { - case reflect.String: - if typeField.Tag.Get("flag") != "" { - if len(parts) == 1 { - fs.StringVar(valField.Addr().Interface().(*string), parts[0], value, typeField.Tag.Get("description")) - } else { - fs.StringVarP(valField.Addr().Interface().(*string), parts[0], parts[1], value, typeField.Tag.Get("description")) - } - } else { - valField.SetString(value) - } - - case reflect.Bool: - v := value == "true" - if typeField.Tag.Get("flag") != "" { - if len(parts) == 1 { - fs.BoolVar(valField.Addr().Interface().(*bool), parts[0], v, typeField.Tag.Get("description")) - } else { - fs.BoolVarP(valField.Addr().Interface().(*bool), parts[0], parts[1], v, typeField.Tag.Get("description")) - } - } else { - valField.SetBool(v) - } - - case reflect.Int, reflect.Int8, reflect.Int32, reflect.Int64: - vt, err := strconv.ParseInt(value, 10, 64) - if err != nil { - if value == "" { - vt = 0 - } else { - return err - } - } - if typeField.Tag.Get("flag") != "" { - registerFlagInt(typeField.Type.Kind(), fs, valField.Addr().Interface(), parts, vt, typeField.Tag.Get("description")) - } else { - valField.SetInt(vt) - } - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - vt, err := strconv.ParseUint(value, 10, 64) - if err != nil { - if value == "" { - vt = 0 - } else { - return err - } - } - if typeField.Tag.Get("flag") != "" { - registerFlagUint(typeField.Type.Kind(), fs, valField.Addr().Interface(), parts, vt, typeField.Tag.Get("description")) - } else { - valField.SetUint(vt) - } - - case reflect.Float32, reflect.Float64: - vt, err := strconv.ParseFloat(value, 64) - if err != nil { - if value == "" { - vt = 0.0 - } else { - return err - } - } - if typeField.Tag.Get("flag") != "" { - registerFlagFloat(typeField.Type.Kind(), fs, valField.Addr().Interface(), parts, vt, typeField.Tag.Get("description")) - } else { - valField.SetFloat(vt) - } - - case reflect.Struct: - if err := execTags(valField.Addr().Interface(), fs); err != nil { - return err - } - - case reflect.Slice: - switch typeField.Type.Elem().Kind() { - case reflect.Int: - def := []int{} - for _, v := range strings.Split(value, ",") { - it, err := strconv.ParseInt(strings.TrimSpace(v), 10, 64) - if err != nil { - return err - } - def = append(def, int(it)) - } - if len(parts) == 1 { - fs.IntSliceVar(valField.Addr().Interface().(*[]int), parts[0], def, typeField.Tag.Get("description")) - } else { - fs.IntSliceVarP(valField.Addr().Interface().(*[]int), parts[0], parts[1], def, typeField.Tag.Get("description")) - } - case reflect.String: - del := typeField.Tag.Get("delimiter") - if len(del) == 0 { - del = "," - } - def := strings.Split(value, del) - if len(parts) == 1 { - fs.StringSliceVar(valField.Addr().Interface().(*[]string), parts[0], def, typeField.Tag.Get("description")) - } else { - fs.StringSliceVarP(valField.Addr().Interface().(*[]string), parts[0], parts[1], def, typeField.Tag.Get("description")) - } - } - } - } - - return nil -} - -func registerFlagFloat(t reflect.Kind, fs *pflag.FlagSet, field interface{}, parts []string, vt float64, desc string) { - switch t { - case reflect.Float32: - if len(parts) == 1 { - fs.Float32Var(field.(*float32), parts[0], float32(vt), desc) - } else { - fs.Float32VarP(field.(*float32), parts[0], parts[1], float32(vt), desc) - } - case reflect.Float64: - if len(parts) == 1 { - fs.Float64Var(field.(*float64), parts[0], float64(vt), desc) - } else { - fs.Float64VarP(field.(*float64), parts[0], parts[1], float64(vt), desc) - } - } -} - -func registerFlagInt(t reflect.Kind, fs *pflag.FlagSet, field interface{}, parts []string, vt int64, desc string) { - switch t { - case reflect.Int: - if len(parts) == 1 { - fs.IntVar(field.(*int), parts[0], int(vt), desc) - } else { - fs.IntVarP(field.(*int), parts[0], parts[1], int(vt), desc) - } - case reflect.Int8: - if len(parts) == 1 { - fs.Int8Var(field.(*int8), parts[0], int8(vt), desc) - } else { - fs.Int8VarP(field.(*int8), parts[0], parts[1], int8(vt), desc) - } - case reflect.Int32: - if len(parts) == 1 { - fs.Int32Var(field.(*int32), parts[0], int32(vt), desc) - } else { - fs.Int32VarP(field.(*int32), parts[0], parts[1], int32(vt), desc) - } - case reflect.Int64: - if len(parts) == 1 { - fs.Int64Var(field.(*int64), parts[0], int64(vt), desc) - } else { - fs.Int64VarP(field.(*int64), parts[0], parts[1], int64(vt), desc) - } - } -} - -func registerFlagUint(t reflect.Kind, fs *pflag.FlagSet, field interface{}, parts []string, vt uint64, desc string) { - switch t { - case reflect.Uint: - if len(parts) == 1 { - fs.UintVar(field.(*uint), parts[0], uint(vt), desc) - } else { - fs.UintVarP(field.(*uint), parts[0], parts[1], uint(vt), desc) - } - case reflect.Uint8: - if len(parts) == 1 { - fs.Uint8Var(field.(*uint8), parts[0], uint8(vt), desc) - } else { - fs.Uint8VarP(field.(*uint8), parts[0], parts[1], uint8(vt), desc) - } - case reflect.Uint16: - if len(parts) == 1 { - fs.Uint16Var(field.(*uint16), parts[0], uint16(vt), desc) - } else { - fs.Uint16VarP(field.(*uint16), parts[0], parts[1], uint16(vt), desc) - } - case reflect.Uint32: - if len(parts) == 1 { - fs.Uint32Var(field.(*uint32), parts[0], uint32(vt), desc) - } else { - fs.Uint32VarP(field.(*uint32), parts[0], parts[1], uint32(vt), desc) - } - case reflect.Uint64: - if len(parts) == 1 { - fs.Uint64Var(field.(*uint64), parts[0], uint64(vt), desc) - } else { - fs.Uint64VarP(field.(*uint64), parts[0], parts[1], uint64(vt), desc) - } - } -} - -func envDefault(env, def string) string { - value := def - - if env != "" { - if e := os.Getenv(env); e != "" { - value = e - } - } - - return value -} - -func varDefault(name, def string) string { - value := def - - if name != "" { - if v, ok := variableDefaults[name]; ok { - value = v - } - } - - return value -} diff --git a/vendor/github.com/Luzifer/rconfig/vardefault_providers.go b/vendor/github.com/Luzifer/rconfig/vardefault_providers.go deleted file mode 100644 index 2199cfa..0000000 --- a/vendor/github.com/Luzifer/rconfig/vardefault_providers.go +++ /dev/null @@ -1,27 +0,0 @@ -package rconfig - -import ( - "io/ioutil" - - "gopkg.in/yaml.v2" -) - -// VarDefaultsFromYAMLFile reads contents of a file and calls VarDefaultsFromYAML -func VarDefaultsFromYAMLFile(filename string) map[string]string { - data, err := ioutil.ReadFile(filename) - if err != nil { - return make(map[string]string) - } - - return VarDefaultsFromYAML(data) -} - -// VarDefaultsFromYAML creates a vardefaults map from YAML raw data -func VarDefaultsFromYAML(in []byte) map[string]string { - out := make(map[string]string) - err := yaml.Unmarshal(in, &out) - if err != nil { - return make(map[string]string) - } - return out -} diff --git a/vendor/github.com/Sirupsen/logrus/.gitignore b/vendor/github.com/Sirupsen/logrus/.gitignore deleted file mode 100644 index 66be63a..0000000 --- a/vendor/github.com/Sirupsen/logrus/.gitignore +++ /dev/null @@ -1 +0,0 @@ -logrus diff --git a/vendor/github.com/Sirupsen/logrus/.travis.yml b/vendor/github.com/Sirupsen/logrus/.travis.yml deleted file mode 100644 index 2f19b4a..0000000 --- a/vendor/github.com/Sirupsen/logrus/.travis.yml +++ /dev/null @@ -1,13 +0,0 @@ -language: go -go: - - 1.9.x - - 1.10.x -env: - - GOMAXPROCS=4 GORACE=halt_on_error=1 -install: - - go get github.com/stretchr/testify/assert - - go get gopkg.in/gemnasium/logrus-airbrake-hook.v2 - - go get golang.org/x/sys/unix - - go get golang.org/x/sys/windows -script: - - go test -race -v ./... diff --git a/vendor/github.com/Sirupsen/logrus/CHANGELOG.md b/vendor/github.com/Sirupsen/logrus/CHANGELOG.md deleted file mode 100644 index 1bd1deb..0000000 --- a/vendor/github.com/Sirupsen/logrus/CHANGELOG.md +++ /dev/null @@ -1,123 +0,0 @@ -# 1.0.5 - -* Fix hooks race (#707) -* Fix panic deadlock (#695) - -# 1.0.4 - -* Fix race when adding hooks (#612) -* Fix terminal check in AppEngine (#635) - -# 1.0.3 - -* Replace example files with testable examples - -# 1.0.2 - -* bug: quote non-string values in text formatter (#583) -* Make (*Logger) SetLevel a public method - -# 1.0.1 - -* bug: fix escaping in text formatter (#575) - -# 1.0.0 - -* Officially changed name to lower-case -* bug: colors on Windows 10 (#541) -* bug: fix race in accessing level (#512) - -# 0.11.5 - -* feature: add writer and writerlevel to entry (#372) - -# 0.11.4 - -* bug: fix undefined variable on solaris (#493) - -# 0.11.3 - -* formatter: configure quoting of empty values (#484) -* formatter: configure quoting character (default is `"`) (#484) -* bug: fix not importing io correctly in non-linux environments (#481) - -# 0.11.2 - -* bug: fix windows terminal detection (#476) - -# 0.11.1 - -* bug: fix tty detection with custom out (#471) - -# 0.11.0 - -* performance: Use bufferpool to allocate (#370) -* terminal: terminal detection for app-engine (#343) -* feature: exit handler (#375) - -# 0.10.0 - -* feature: Add a test hook (#180) -* feature: `ParseLevel` is now case-insensitive (#326) -* feature: `FieldLogger` interface that generalizes `Logger` and `Entry` (#308) -* performance: avoid re-allocations on `WithFields` (#335) - -# 0.9.0 - -* logrus/text_formatter: don't emit empty msg -* logrus/hooks/airbrake: move out of main repository -* logrus/hooks/sentry: move out of main repository -* logrus/hooks/papertrail: move out of main repository -* logrus/hooks/bugsnag: move out of main repository -* logrus/core: run tests with `-race` -* logrus/core: detect TTY based on `stderr` -* logrus/core: support `WithError` on logger -* logrus/core: Solaris support - -# 0.8.7 - -* logrus/core: fix possible race (#216) -* logrus/doc: small typo fixes and doc improvements - - -# 0.8.6 - -* hooks/raven: allow passing an initialized client - -# 0.8.5 - -* logrus/core: revert #208 - -# 0.8.4 - -* formatter/text: fix data race (#218) - -# 0.8.3 - -* logrus/core: fix entry log level (#208) -* logrus/core: improve performance of text formatter by 40% -* logrus/core: expose `LevelHooks` type -* logrus/core: add support for DragonflyBSD and NetBSD -* formatter/text: print structs more verbosely - -# 0.8.2 - -* logrus: fix more Fatal family functions - -# 0.8.1 - -* logrus: fix not exiting on `Fatalf` and `Fatalln` - -# 0.8.0 - -* logrus: defaults to stderr instead of stdout -* hooks/sentry: add special field for `*http.Request` -* formatter/text: ignore Windows for colors - -# 0.7.3 - -* formatter/\*: allow configuration of timestamp layout - -# 0.7.2 - -* formatter/text: Add configuration option for time format (#158) diff --git a/vendor/github.com/Sirupsen/logrus/LICENSE b/vendor/github.com/Sirupsen/logrus/LICENSE deleted file mode 100644 index f090cb4..0000000 --- a/vendor/github.com/Sirupsen/logrus/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Simon Eskildsen - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/Sirupsen/logrus/README.md b/vendor/github.com/Sirupsen/logrus/README.md deleted file mode 100644 index 072e99b..0000000 --- a/vendor/github.com/Sirupsen/logrus/README.md +++ /dev/null @@ -1,461 +0,0 @@ -# Logrus :walrus: [![Build Status](https://travis-ci.org/sirupsen/logrus.svg?branch=master)](https://travis-ci.org/sirupsen/logrus) [![GoDoc](https://godoc.org/github.com/sirupsen/logrus?status.svg)](https://godoc.org/github.com/sirupsen/logrus) - -Logrus is a structured logger for Go (golang), completely API compatible with -the standard library logger. - -**Seeing weird case-sensitive problems?** It's in the past been possible to -import Logrus as both upper- and lower-case. Due to the Go package environment, -this caused issues in the community and we needed a standard. Some environments -experienced problems with the upper-case variant, so the lower-case was decided. -Everything using `logrus` will need to use the lower-case: -`github.com/sirupsen/logrus`. Any package that isn't, should be changed. - -To fix Glide, see [these -comments](https://github.com/sirupsen/logrus/issues/553#issuecomment-306591437). -For an in-depth explanation of the casing issue, see [this -comment](https://github.com/sirupsen/logrus/issues/570#issuecomment-313933276). - -**Are you interested in assisting in maintaining Logrus?** Currently I have a -lot of obligations, and I am unable to provide Logrus with the maintainership it -needs. If you'd like to help, please reach out to me at `simon at author's -username dot com`. - -Nicely color-coded in development (when a TTY is attached, otherwise just -plain text): - -![Colored](http://i.imgur.com/PY7qMwd.png) - -With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash -or Splunk: - -```json -{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the -ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"} - -{"level":"warning","msg":"The group's number increased tremendously!", -"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"} - -{"animal":"walrus","level":"info","msg":"A giant walrus appears!", -"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"} - -{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.", -"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"} - -{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true, -"time":"2014-03-10 19:57:38.562543128 -0400 EDT"} -``` - -With the default `log.SetFormatter(&log.TextFormatter{})` when a TTY is not -attached, the output is compatible with the -[logfmt](http://godoc.org/github.com/kr/logfmt) format: - -```text -time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8 -time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10 -time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true -time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4 -time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009 -time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true -exit status 1 -``` - -#### Case-sensitivity - -The organization's name was changed to lower-case--and this will not be changed -back. If you are getting import conflicts due to case sensitivity, please use -the lower-case import: `github.com/sirupsen/logrus`. - -#### Example - -The simplest way to use Logrus is simply the package-level exported logger: - -```go -package main - -import ( - log "github.com/sirupsen/logrus" -) - -func main() { - log.WithFields(log.Fields{ - "animal": "walrus", - }).Info("A walrus appears") -} -``` - -Note that it's completely api-compatible with the stdlib logger, so you can -replace your `log` imports everywhere with `log "github.com/sirupsen/logrus"` -and you'll now have the flexibility of Logrus. You can customize it all you -want: - -```go -package main - -import ( - "os" - log "github.com/sirupsen/logrus" -) - -func init() { - // Log as JSON instead of the default ASCII formatter. - log.SetFormatter(&log.JSONFormatter{}) - - // Output to stdout instead of the default stderr - // Can be any io.Writer, see below for File example - log.SetOutput(os.Stdout) - - // Only log the warning severity or above. - log.SetLevel(log.WarnLevel) -} - -func main() { - log.WithFields(log.Fields{ - "animal": "walrus", - "size": 10, - }).Info("A group of walrus emerges from the ocean") - - log.WithFields(log.Fields{ - "omg": true, - "number": 122, - }).Warn("The group's number increased tremendously!") - - log.WithFields(log.Fields{ - "omg": true, - "number": 100, - }).Fatal("The ice breaks!") - - // A common pattern is to re-use fields between logging statements by re-using - // the logrus.Entry returned from WithFields() - contextLogger := log.WithFields(log.Fields{ - "common": "this is a common field", - "other": "I also should be logged always", - }) - - contextLogger.Info("I'll be logged with common and other field") - contextLogger.Info("Me too") -} -``` - -For more advanced usage such as logging to multiple locations from the same -application, you can also create an instance of the `logrus` Logger: - -```go -package main - -import ( - "os" - "github.com/sirupsen/logrus" -) - -// Create a new instance of the logger. You can have any number of instances. -var log = logrus.New() - -func main() { - // The API for setting attributes is a little different than the package level - // exported logger. See Godoc. - log.Out = os.Stdout - - // You could set this to any `io.Writer` such as a file - // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666) - // if err == nil { - // log.Out = file - // } else { - // log.Info("Failed to log to file, using default stderr") - // } - - log.WithFields(logrus.Fields{ - "animal": "walrus", - "size": 10, - }).Info("A group of walrus emerges from the ocean") -} -``` - -#### Fields - -Logrus encourages careful, structured logging through logging fields instead of -long, unparseable error messages. For example, instead of: `log.Fatalf("Failed -to send event %s to topic %s with key %d")`, you should log the much more -discoverable: - -```go -log.WithFields(log.Fields{ - "event": event, - "topic": topic, - "key": key, -}).Fatal("Failed to send event") -``` - -We've found this API forces you to think about logging in a way that produces -much more useful logging messages. We've been in countless situations where just -a single added field to a log statement that was already there would've saved us -hours. The `WithFields` call is optional. - -In general, with Logrus using any of the `printf`-family functions should be -seen as a hint you should add a field, however, you can still use the -`printf`-family functions with Logrus. - -#### Default Fields - -Often it's helpful to have fields _always_ attached to log statements in an -application or parts of one. For example, you may want to always log the -`request_id` and `user_ip` in the context of a request. Instead of writing -`log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})` on -every line, you can create a `logrus.Entry` to pass around instead: - -```go -requestLogger := log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip}) -requestLogger.Info("something happened on that request") # will log request_id and user_ip -requestLogger.Warn("something not great happened") -``` - -#### Hooks - -You can add hooks for logging levels. For example to send errors to an exception -tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to -multiple places simultaneously, e.g. syslog. - -Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in -`init`: - -```go -import ( - log "github.com/sirupsen/logrus" - "gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "airbrake" - logrus_syslog "github.com/sirupsen/logrus/hooks/syslog" - "log/syslog" -) - -func init() { - - // Use the Airbrake hook to report errors that have Error severity or above to - // an exception tracker. You can create custom hooks, see the Hooks section. - log.AddHook(airbrake.NewHook(123, "xyz", "production")) - - hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") - if err != nil { - log.Error("Unable to connect to local syslog daemon") - } else { - log.AddHook(hook) - } -} -``` -Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md). - -A list of currently known of service hook can be found in this wiki [page](https://github.com/sirupsen/logrus/wiki/Hooks) - - -#### Level logging - -Logrus has six logging levels: Debug, Info, Warning, Error, Fatal and Panic. - -```go -log.Debug("Useful debugging information.") -log.Info("Something noteworthy happened!") -log.Warn("You should probably take a look at this.") -log.Error("Something failed but I'm not quitting.") -// Calls os.Exit(1) after logging -log.Fatal("Bye.") -// Calls panic() after logging -log.Panic("I'm bailing.") -``` - -You can set the logging level on a `Logger`, then it will only log entries with -that severity or anything above it: - -```go -// Will log anything that is info or above (warn, error, fatal, panic). Default. -log.SetLevel(log.InfoLevel) -``` - -It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose -environment if your application has that. - -#### Entries - -Besides the fields added with `WithField` or `WithFields` some fields are -automatically added to all logging events: - -1. `time`. The timestamp when the entry was created. -2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after - the `AddFields` call. E.g. `Failed to send event.` -3. `level`. The logging level. E.g. `info`. - -#### Environments - -Logrus has no notion of environment. - -If you wish for hooks and formatters to only be used in specific environments, -you should handle that yourself. For example, if your application has a global -variable `Environment`, which is a string representation of the environment you -could do: - -```go -import ( - log "github.com/sirupsen/logrus" -) - -init() { - // do something here to set environment depending on an environment variable - // or command-line flag - if Environment == "production" { - log.SetFormatter(&log.JSONFormatter{}) - } else { - // The TextFormatter is default, you don't actually have to do this. - log.SetFormatter(&log.TextFormatter{}) - } -} -``` - -This configuration is how `logrus` was intended to be used, but JSON in -production is mostly only useful if you do log aggregation with tools like -Splunk or Logstash. - -#### Formatters - -The built-in logging formatters are: - -* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise - without colors. - * *Note:* to force colored output when there is no TTY, set the `ForceColors` - field to `true`. To force no colored output even if there is a TTY set the - `DisableColors` field to `true`. For Windows, see - [github.com/mattn/go-colorable](https://github.com/mattn/go-colorable). - * When colors are enabled, levels are truncated to 4 characters by default. To disable - truncation set the `DisableLevelTruncation` field to `true`. - * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#TextFormatter). -* `logrus.JSONFormatter`. Logs fields as JSON. - * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#JSONFormatter). - -Third party logging formatters: - -* [`FluentdFormatter`](https://github.com/joonix/log). Formats entries that can be parsed by Kubernetes and Google Container Engine. -* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events. -* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout. -* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦. - -You can define your formatter by implementing the `Formatter` interface, -requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a -`Fields` type (`map[string]interface{}`) with all your fields as well as the -default ones (see Entries section above): - -```go -type MyJSONFormatter struct { -} - -log.SetFormatter(new(MyJSONFormatter)) - -func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) { - // Note this doesn't include Time, Level and Message which are available on - // the Entry. Consult `godoc` on information about those fields or read the - // source of the official loggers. - serialized, err := json.Marshal(entry.Data) - if err != nil { - return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) - } - return append(serialized, '\n'), nil -} -``` - -#### Logger as an `io.Writer` - -Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it. - -```go -w := logger.Writer() -defer w.Close() - -srv := http.Server{ - // create a stdlib log.Logger that writes to - // logrus.Logger. - ErrorLog: log.New(w, "", 0), -} -``` - -Each line written to that writer will be printed the usual way, using formatters -and hooks. The level for those entries is `info`. - -This means that we can override the standard library logger easily: - -```go -logger := logrus.New() -logger.Formatter = &logrus.JSONFormatter{} - -// Use logrus for standard log output -// Note that `log` here references stdlib's log -// Not logrus imported under the name `log`. -log.SetOutput(logger.Writer()) -``` - -#### Rotation - -Log rotation is not provided with Logrus. Log rotation should be done by an -external program (like `logrotate(8)`) that can compress and delete old log -entries. It should not be a feature of the application-level logger. - -#### Tools - -| Tool | Description | -| ---- | ----------- | -|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will generated with different config at different environment.| -|[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper around Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) | - -#### Testing - -Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides: - -* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just add the `test` hook -* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any): - -```go -import( - "github.com/sirupsen/logrus" - "github.com/sirupsen/logrus/hooks/test" - "github.com/stretchr/testify/assert" - "testing" -) - -func TestSomething(t*testing.T){ - logger, hook := test.NewNullLogger() - logger.Error("Helloerror") - - assert.Equal(t, 1, len(hook.Entries)) - assert.Equal(t, logrus.ErrorLevel, hook.LastEntry().Level) - assert.Equal(t, "Helloerror", hook.LastEntry().Message) - - hook.Reset() - assert.Nil(t, hook.LastEntry()) -} -``` - -#### Fatal handlers - -Logrus can register one or more functions that will be called when any `fatal` -level message is logged. The registered handlers will be executed before -logrus performs a `os.Exit(1)`. This behavior may be helpful if callers need -to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted. - -``` -... -handler := func() { - // gracefully shutdown something... -} -logrus.RegisterExitHandler(handler) -... -``` - -#### Thread safety - -By default, Logger is protected by a mutex for concurrent writes. The mutex is held when calling hooks and writing logs. -If you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking. - -Situation when locking is not needed includes: - -* You have no hooks registered, or hooks calling is already thread-safe. - -* Writing to logger.Out is already thread-safe, for example: - - 1) logger.Out is protected by locks. - - 2) logger.Out is a os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allow multi-thread/multi-process writing) - - (Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/) diff --git a/vendor/github.com/Sirupsen/logrus/alt_exit.go b/vendor/github.com/Sirupsen/logrus/alt_exit.go deleted file mode 100644 index 8af9063..0000000 --- a/vendor/github.com/Sirupsen/logrus/alt_exit.go +++ /dev/null @@ -1,64 +0,0 @@ -package logrus - -// The following code was sourced and modified from the -// https://github.com/tebeka/atexit package governed by the following license: -// -// Copyright (c) 2012 Miki Tebeka . -// -// Permission is hereby granted, free of charge, to any person obtaining a copy of -// this software and associated documentation files (the "Software"), to deal in -// the Software without restriction, including without limitation the rights to -// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -// the Software, and to permit persons to whom the Software is furnished to do so, -// subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -import ( - "fmt" - "os" -) - -var handlers = []func(){} - -func runHandler(handler func()) { - defer func() { - if err := recover(); err != nil { - fmt.Fprintln(os.Stderr, "Error: Logrus exit handler error:", err) - } - }() - - handler() -} - -func runHandlers() { - for _, handler := range handlers { - runHandler(handler) - } -} - -// Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code) -func Exit(code int) { - runHandlers() - os.Exit(code) -} - -// RegisterExitHandler adds a Logrus Exit handler, call logrus.Exit to invoke -// all handlers. The handlers will also be invoked when any Fatal log entry is -// made. -// -// This method is useful when a caller wishes to use logrus to log a fatal -// message but also needs to gracefully shutdown. An example usecase could be -// closing database connections, or sending a alert that the application is -// closing. -func RegisterExitHandler(handler func()) { - handlers = append(handlers, handler) -} diff --git a/vendor/github.com/Sirupsen/logrus/appveyor.yml b/vendor/github.com/Sirupsen/logrus/appveyor.yml deleted file mode 100644 index 96c2ce1..0000000 --- a/vendor/github.com/Sirupsen/logrus/appveyor.yml +++ /dev/null @@ -1,14 +0,0 @@ -version: "{build}" -platform: x64 -clone_folder: c:\gopath\src\github.com\sirupsen\logrus -environment: - GOPATH: c:\gopath -branches: - only: - - master -install: - - set PATH=%GOPATH%\bin;c:\go\bin;%PATH% - - go version -build_script: - - go get -t - - go test diff --git a/vendor/github.com/Sirupsen/logrus/doc.go b/vendor/github.com/Sirupsen/logrus/doc.go deleted file mode 100644 index da67aba..0000000 --- a/vendor/github.com/Sirupsen/logrus/doc.go +++ /dev/null @@ -1,26 +0,0 @@ -/* -Package logrus is a structured logger for Go, completely API compatible with the standard library logger. - - -The simplest way to use Logrus is simply the package-level exported logger: - - package main - - import ( - log "github.com/sirupsen/logrus" - ) - - func main() { - log.WithFields(log.Fields{ - "animal": "walrus", - "number": 1, - "size": 10, - }).Info("A walrus appears") - } - -Output: - time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10 - -For a full guide visit https://github.com/sirupsen/logrus -*/ -package logrus diff --git a/vendor/github.com/Sirupsen/logrus/entry.go b/vendor/github.com/Sirupsen/logrus/entry.go deleted file mode 100644 index 473bd1a..0000000 --- a/vendor/github.com/Sirupsen/logrus/entry.go +++ /dev/null @@ -1,300 +0,0 @@ -package logrus - -import ( - "bytes" - "fmt" - "os" - "sync" - "time" -) - -var bufferPool *sync.Pool - -func init() { - bufferPool = &sync.Pool{ - New: func() interface{} { - return new(bytes.Buffer) - }, - } -} - -// Defines the key when adding errors using WithError. -var ErrorKey = "error" - -// An entry is the final or intermediate Logrus logging entry. It contains all -// the fields passed with WithField{,s}. It's finally logged when Debug, Info, -// Warn, Error, Fatal or Panic is called on it. These objects can be reused and -// passed around as much as you wish to avoid field duplication. -type Entry struct { - Logger *Logger - - // Contains all the fields set by the user. - Data Fields - - // Time at which the log entry was created - Time time.Time - - // Level the log entry was logged at: Debug, Info, Warn, Error, Fatal or Panic - // This field will be set on entry firing and the value will be equal to the one in Logger struct field. - Level Level - - // Message passed to Debug, Info, Warn, Error, Fatal or Panic - Message string - - // When formatter is called in entry.log(), an Buffer may be set to entry - Buffer *bytes.Buffer -} - -func NewEntry(logger *Logger) *Entry { - return &Entry{ - Logger: logger, - // Default is five fields, give a little extra room - Data: make(Fields, 5), - } -} - -// Returns the string representation from the reader and ultimately the -// formatter. -func (entry *Entry) String() (string, error) { - serialized, err := entry.Logger.Formatter.Format(entry) - if err != nil { - return "", err - } - str := string(serialized) - return str, nil -} - -// Add an error as single field (using the key defined in ErrorKey) to the Entry. -func (entry *Entry) WithError(err error) *Entry { - return entry.WithField(ErrorKey, err) -} - -// Add a single field to the Entry. -func (entry *Entry) WithField(key string, value interface{}) *Entry { - return entry.WithFields(Fields{key: value}) -} - -// Add a map of fields to the Entry. -func (entry *Entry) WithFields(fields Fields) *Entry { - data := make(Fields, len(entry.Data)+len(fields)) - for k, v := range entry.Data { - data[k] = v - } - for k, v := range fields { - data[k] = v - } - return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time} -} - -// Overrides the time of the Entry. -func (entry *Entry) WithTime(t time.Time) *Entry { - return &Entry{Logger: entry.Logger, Data: entry.Data, Time: t} -} - -// This function is not declared with a pointer value because otherwise -// race conditions will occur when using multiple goroutines -func (entry Entry) log(level Level, msg string) { - var buffer *bytes.Buffer - - // Default to now, but allow users to override if they want. - // - // We don't have to worry about polluting future calls to Entry#log() - // with this assignment because this function is declared with a - // non-pointer receiver. - if entry.Time.IsZero() { - entry.Time = time.Now() - } - - entry.Level = level - entry.Message = msg - - entry.fireHooks() - - buffer = bufferPool.Get().(*bytes.Buffer) - buffer.Reset() - defer bufferPool.Put(buffer) - entry.Buffer = buffer - - entry.write() - - entry.Buffer = nil - - // To avoid Entry#log() returning a value that only would make sense for - // panic() to use in Entry#Panic(), we avoid the allocation by checking - // directly here. - if level <= PanicLevel { - panic(&entry) - } -} - -func (entry *Entry) fireHooks() { - entry.Logger.mu.Lock() - defer entry.Logger.mu.Unlock() - err := entry.Logger.Hooks.Fire(entry.Level, entry) - if err != nil { - fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err) - } -} - -func (entry *Entry) write() { - serialized, err := entry.Logger.Formatter.Format(entry) - entry.Logger.mu.Lock() - defer entry.Logger.mu.Unlock() - if err != nil { - fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err) - } else { - _, err = entry.Logger.Out.Write(serialized) - if err != nil { - fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err) - } - } -} - -func (entry *Entry) Debug(args ...interface{}) { - if entry.Logger.level() >= DebugLevel { - entry.log(DebugLevel, fmt.Sprint(args...)) - } -} - -func (entry *Entry) Print(args ...interface{}) { - entry.Info(args...) -} - -func (entry *Entry) Info(args ...interface{}) { - if entry.Logger.level() >= InfoLevel { - entry.log(InfoLevel, fmt.Sprint(args...)) - } -} - -func (entry *Entry) Warn(args ...interface{}) { - if entry.Logger.level() >= WarnLevel { - entry.log(WarnLevel, fmt.Sprint(args...)) - } -} - -func (entry *Entry) Warning(args ...interface{}) { - entry.Warn(args...) -} - -func (entry *Entry) Error(args ...interface{}) { - if entry.Logger.level() >= ErrorLevel { - entry.log(ErrorLevel, fmt.Sprint(args...)) - } -} - -func (entry *Entry) Fatal(args ...interface{}) { - if entry.Logger.level() >= FatalLevel { - entry.log(FatalLevel, fmt.Sprint(args...)) - } - Exit(1) -} - -func (entry *Entry) Panic(args ...interface{}) { - if entry.Logger.level() >= PanicLevel { - entry.log(PanicLevel, fmt.Sprint(args...)) - } - panic(fmt.Sprint(args...)) -} - -// Entry Printf family functions - -func (entry *Entry) Debugf(format string, args ...interface{}) { - if entry.Logger.level() >= DebugLevel { - entry.Debug(fmt.Sprintf(format, args...)) - } -} - -func (entry *Entry) Infof(format string, args ...interface{}) { - if entry.Logger.level() >= InfoLevel { - entry.Info(fmt.Sprintf(format, args...)) - } -} - -func (entry *Entry) Printf(format string, args ...interface{}) { - entry.Infof(format, args...) -} - -func (entry *Entry) Warnf(format string, args ...interface{}) { - if entry.Logger.level() >= WarnLevel { - entry.Warn(fmt.Sprintf(format, args...)) - } -} - -func (entry *Entry) Warningf(format string, args ...interface{}) { - entry.Warnf(format, args...) -} - -func (entry *Entry) Errorf(format string, args ...interface{}) { - if entry.Logger.level() >= ErrorLevel { - entry.Error(fmt.Sprintf(format, args...)) - } -} - -func (entry *Entry) Fatalf(format string, args ...interface{}) { - if entry.Logger.level() >= FatalLevel { - entry.Fatal(fmt.Sprintf(format, args...)) - } - Exit(1) -} - -func (entry *Entry) Panicf(format string, args ...interface{}) { - if entry.Logger.level() >= PanicLevel { - entry.Panic(fmt.Sprintf(format, args...)) - } -} - -// Entry Println family functions - -func (entry *Entry) Debugln(args ...interface{}) { - if entry.Logger.level() >= DebugLevel { - entry.Debug(entry.sprintlnn(args...)) - } -} - -func (entry *Entry) Infoln(args ...interface{}) { - if entry.Logger.level() >= InfoLevel { - entry.Info(entry.sprintlnn(args...)) - } -} - -func (entry *Entry) Println(args ...interface{}) { - entry.Infoln(args...) -} - -func (entry *Entry) Warnln(args ...interface{}) { - if entry.Logger.level() >= WarnLevel { - entry.Warn(entry.sprintlnn(args...)) - } -} - -func (entry *Entry) Warningln(args ...interface{}) { - entry.Warnln(args...) -} - -func (entry *Entry) Errorln(args ...interface{}) { - if entry.Logger.level() >= ErrorLevel { - entry.Error(entry.sprintlnn(args...)) - } -} - -func (entry *Entry) Fatalln(args ...interface{}) { - if entry.Logger.level() >= FatalLevel { - entry.Fatal(entry.sprintlnn(args...)) - } - Exit(1) -} - -func (entry *Entry) Panicln(args ...interface{}) { - if entry.Logger.level() >= PanicLevel { - entry.Panic(entry.sprintlnn(args...)) - } -} - -// Sprintlnn => Sprint no newline. This is to get the behavior of how -// fmt.Sprintln where spaces are always added between operands, regardless of -// their type. Instead of vendoring the Sprintln implementation to spare a -// string allocation, we do the simplest thing. -func (entry *Entry) sprintlnn(args ...interface{}) string { - msg := fmt.Sprintln(args...) - return msg[:len(msg)-1] -} diff --git a/vendor/github.com/Sirupsen/logrus/exported.go b/vendor/github.com/Sirupsen/logrus/exported.go deleted file mode 100644 index eb612a6..0000000 --- a/vendor/github.com/Sirupsen/logrus/exported.go +++ /dev/null @@ -1,201 +0,0 @@ -package logrus - -import ( - "io" - "time" -) - -var ( - // std is the name of the standard logger in stdlib `log` - std = New() -) - -func StandardLogger() *Logger { - return std -} - -// SetOutput sets the standard logger output. -func SetOutput(out io.Writer) { - std.SetOutput(out) -} - -// SetFormatter sets the standard logger formatter. -func SetFormatter(formatter Formatter) { - std.mu.Lock() - defer std.mu.Unlock() - std.Formatter = formatter -} - -// SetLevel sets the standard logger level. -func SetLevel(level Level) { - std.mu.Lock() - defer std.mu.Unlock() - std.SetLevel(level) -} - -// GetLevel returns the standard logger level. -func GetLevel() Level { - std.mu.Lock() - defer std.mu.Unlock() - return std.level() -} - -// AddHook adds a hook to the standard logger hooks. -func AddHook(hook Hook) { - std.mu.Lock() - defer std.mu.Unlock() - std.Hooks.Add(hook) -} - -// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key. -func WithError(err error) *Entry { - return std.WithField(ErrorKey, err) -} - -// WithField creates an entry from the standard logger and adds a field to -// it. If you want multiple fields, use `WithFields`. -// -// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal -// or Panic on the Entry it returns. -func WithField(key string, value interface{}) *Entry { - return std.WithField(key, value) -} - -// WithFields creates an entry from the standard logger and adds multiple -// fields to it. This is simply a helper for `WithField`, invoking it -// once for each field. -// -// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal -// or Panic on the Entry it returns. -func WithFields(fields Fields) *Entry { - return std.WithFields(fields) -} - -// WithTime creats an entry from the standard logger and overrides the time of -// logs generated with it. -// -// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal -// or Panic on the Entry it returns. -func WithTime(t time.Time) *Entry { - return std.WithTime(t) -} - -// Debug logs a message at level Debug on the standard logger. -func Debug(args ...interface{}) { - std.Debug(args...) -} - -// Print logs a message at level Info on the standard logger. -func Print(args ...interface{}) { - std.Print(args...) -} - -// Info logs a message at level Info on the standard logger. -func Info(args ...interface{}) { - std.Info(args...) -} - -// Warn logs a message at level Warn on the standard logger. -func Warn(args ...interface{}) { - std.Warn(args...) -} - -// Warning logs a message at level Warn on the standard logger. -func Warning(args ...interface{}) { - std.Warning(args...) -} - -// Error logs a message at level Error on the standard logger. -func Error(args ...interface{}) { - std.Error(args...) -} - -// Panic logs a message at level Panic on the standard logger. -func Panic(args ...interface{}) { - std.Panic(args...) -} - -// Fatal logs a message at level Fatal on the standard logger then the process will exit with status set to 1. -func Fatal(args ...interface{}) { - std.Fatal(args...) -} - -// Debugf logs a message at level Debug on the standard logger. -func Debugf(format string, args ...interface{}) { - std.Debugf(format, args...) -} - -// Printf logs a message at level Info on the standard logger. -func Printf(format string, args ...interface{}) { - std.Printf(format, args...) -} - -// Infof logs a message at level Info on the standard logger. -func Infof(format string, args ...interface{}) { - std.Infof(format, args...) -} - -// Warnf logs a message at level Warn on the standard logger. -func Warnf(format string, args ...interface{}) { - std.Warnf(format, args...) -} - -// Warningf logs a message at level Warn on the standard logger. -func Warningf(format string, args ...interface{}) { - std.Warningf(format, args...) -} - -// Errorf logs a message at level Error on the standard logger. -func Errorf(format string, args ...interface{}) { - std.Errorf(format, args...) -} - -// Panicf logs a message at level Panic on the standard logger. -func Panicf(format string, args ...interface{}) { - std.Panicf(format, args...) -} - -// Fatalf logs a message at level Fatal on the standard logger then the process will exit with status set to 1. -func Fatalf(format string, args ...interface{}) { - std.Fatalf(format, args...) -} - -// Debugln logs a message at level Debug on the standard logger. -func Debugln(args ...interface{}) { - std.Debugln(args...) -} - -// Println logs a message at level Info on the standard logger. -func Println(args ...interface{}) { - std.Println(args...) -} - -// Infoln logs a message at level Info on the standard logger. -func Infoln(args ...interface{}) { - std.Infoln(args...) -} - -// Warnln logs a message at level Warn on the standard logger. -func Warnln(args ...interface{}) { - std.Warnln(args...) -} - -// Warningln logs a message at level Warn on the standard logger. -func Warningln(args ...interface{}) { - std.Warningln(args...) -} - -// Errorln logs a message at level Error on the standard logger. -func Errorln(args ...interface{}) { - std.Errorln(args...) -} - -// Panicln logs a message at level Panic on the standard logger. -func Panicln(args ...interface{}) { - std.Panicln(args...) -} - -// Fatalln logs a message at level Fatal on the standard logger then the process will exit with status set to 1. -func Fatalln(args ...interface{}) { - std.Fatalln(args...) -} diff --git a/vendor/github.com/Sirupsen/logrus/formatter.go b/vendor/github.com/Sirupsen/logrus/formatter.go deleted file mode 100644 index 83c7494..0000000 --- a/vendor/github.com/Sirupsen/logrus/formatter.go +++ /dev/null @@ -1,51 +0,0 @@ -package logrus - -import "time" - -const defaultTimestampFormat = time.RFC3339 - -// The Formatter interface is used to implement a custom Formatter. It takes an -// `Entry`. It exposes all the fields, including the default ones: -// -// * `entry.Data["msg"]`. The message passed from Info, Warn, Error .. -// * `entry.Data["time"]`. The timestamp. -// * `entry.Data["level"]. The level the entry was logged at. -// -// Any additional fields added with `WithField` or `WithFields` are also in -// `entry.Data`. Format is expected to return an array of bytes which are then -// logged to `logger.Out`. -type Formatter interface { - Format(*Entry) ([]byte, error) -} - -// This is to not silently overwrite `time`, `msg` and `level` fields when -// dumping it. If this code wasn't there doing: -// -// logrus.WithField("level", 1).Info("hello") -// -// Would just silently drop the user provided level. Instead with this code -// it'll logged as: -// -// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."} -// -// It's not exported because it's still using Data in an opinionated way. It's to -// avoid code duplication between the two default formatters. -func prefixFieldClashes(data Fields, fieldMap FieldMap) { - timeKey := fieldMap.resolve(FieldKeyTime) - if t, ok := data[timeKey]; ok { - data["fields."+timeKey] = t - delete(data, timeKey) - } - - msgKey := fieldMap.resolve(FieldKeyMsg) - if m, ok := data[msgKey]; ok { - data["fields."+msgKey] = m - delete(data, msgKey) - } - - levelKey := fieldMap.resolve(FieldKeyLevel) - if l, ok := data[levelKey]; ok { - data["fields."+levelKey] = l - delete(data, levelKey) - } -} diff --git a/vendor/github.com/Sirupsen/logrus/hooks.go b/vendor/github.com/Sirupsen/logrus/hooks.go deleted file mode 100644 index 3f151cd..0000000 --- a/vendor/github.com/Sirupsen/logrus/hooks.go +++ /dev/null @@ -1,34 +0,0 @@ -package logrus - -// A hook to be fired when logging on the logging levels returned from -// `Levels()` on your implementation of the interface. Note that this is not -// fired in a goroutine or a channel with workers, you should handle such -// functionality yourself if your call is non-blocking and you don't wish for -// the logging calls for levels returned from `Levels()` to block. -type Hook interface { - Levels() []Level - Fire(*Entry) error -} - -// Internal type for storing the hooks on a logger instance. -type LevelHooks map[Level][]Hook - -// Add a hook to an instance of logger. This is called with -// `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface. -func (hooks LevelHooks) Add(hook Hook) { - for _, level := range hook.Levels() { - hooks[level] = append(hooks[level], hook) - } -} - -// Fire all the hooks for the passed level. Used by `entry.log` to fire -// appropriate hooks for a log entry. -func (hooks LevelHooks) Fire(level Level, entry *Entry) error { - for _, hook := range hooks[level] { - if err := hook.Fire(entry); err != nil { - return err - } - } - - return nil -} diff --git a/vendor/github.com/Sirupsen/logrus/json_formatter.go b/vendor/github.com/Sirupsen/logrus/json_formatter.go deleted file mode 100644 index dab1761..0000000 --- a/vendor/github.com/Sirupsen/logrus/json_formatter.go +++ /dev/null @@ -1,89 +0,0 @@ -package logrus - -import ( - "encoding/json" - "fmt" -) - -type fieldKey string - -// FieldMap allows customization of the key names for default fields. -type FieldMap map[fieldKey]string - -// Default key names for the default fields -const ( - FieldKeyMsg = "msg" - FieldKeyLevel = "level" - FieldKeyTime = "time" -) - -func (f FieldMap) resolve(key fieldKey) string { - if k, ok := f[key]; ok { - return k - } - - return string(key) -} - -// JSONFormatter formats logs into parsable json -type JSONFormatter struct { - // TimestampFormat sets the format used for marshaling timestamps. - TimestampFormat string - - // DisableTimestamp allows disabling automatic timestamps in output - DisableTimestamp bool - - // DataKey allows users to put all the log entry parameters into a nested dictionary at a given key. - DataKey string - - // FieldMap allows users to customize the names of keys for default fields. - // As an example: - // formatter := &JSONFormatter{ - // FieldMap: FieldMap{ - // FieldKeyTime: "@timestamp", - // FieldKeyLevel: "@level", - // FieldKeyMsg: "@message", - // }, - // } - FieldMap FieldMap -} - -// Format renders a single log entry -func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { - data := make(Fields, len(entry.Data)+3) - for k, v := range entry.Data { - switch v := v.(type) { - case error: - // Otherwise errors are ignored by `encoding/json` - // https://github.com/sirupsen/logrus/issues/137 - data[k] = v.Error() - default: - data[k] = v - } - } - - if f.DataKey != "" { - newData := make(Fields, 4) - newData[f.DataKey] = data - data = newData - } - - prefixFieldClashes(data, f.FieldMap) - - timestampFormat := f.TimestampFormat - if timestampFormat == "" { - timestampFormat = defaultTimestampFormat - } - - if !f.DisableTimestamp { - data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat) - } - data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message - data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String() - - serialized, err := json.Marshal(data) - if err != nil { - return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) - } - return append(serialized, '\n'), nil -} diff --git a/vendor/github.com/Sirupsen/logrus/logger.go b/vendor/github.com/Sirupsen/logrus/logger.go deleted file mode 100644 index 342f797..0000000 --- a/vendor/github.com/Sirupsen/logrus/logger.go +++ /dev/null @@ -1,337 +0,0 @@ -package logrus - -import ( - "io" - "os" - "sync" - "sync/atomic" - "time" -) - -type Logger struct { - // The logs are `io.Copy`'d to this in a mutex. It's common to set this to a - // file, or leave it default which is `os.Stderr`. You can also set this to - // something more adventorous, such as logging to Kafka. - Out io.Writer - // Hooks for the logger instance. These allow firing events based on logging - // levels and log entries. For example, to send errors to an error tracking - // service, log to StatsD or dump the core on fatal errors. - Hooks LevelHooks - // All log entries pass through the formatter before logged to Out. The - // included formatters are `TextFormatter` and `JSONFormatter` for which - // TextFormatter is the default. In development (when a TTY is attached) it - // logs with colors, but to a file it wouldn't. You can easily implement your - // own that implements the `Formatter` interface, see the `README` or included - // formatters for examples. - Formatter Formatter - // The logging level the logger should log at. This is typically (and defaults - // to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be - // logged. - Level Level - // Used to sync writing to the log. Locking is enabled by Default - mu MutexWrap - // Reusable empty entry - entryPool sync.Pool -} - -type MutexWrap struct { - lock sync.Mutex - disabled bool -} - -func (mw *MutexWrap) Lock() { - if !mw.disabled { - mw.lock.Lock() - } -} - -func (mw *MutexWrap) Unlock() { - if !mw.disabled { - mw.lock.Unlock() - } -} - -func (mw *MutexWrap) Disable() { - mw.disabled = true -} - -// Creates a new logger. Configuration should be set by changing `Formatter`, -// `Out` and `Hooks` directly on the default logger instance. You can also just -// instantiate your own: -// -// var log = &Logger{ -// Out: os.Stderr, -// Formatter: new(JSONFormatter), -// Hooks: make(LevelHooks), -// Level: logrus.DebugLevel, -// } -// -// It's recommended to make this a global instance called `log`. -func New() *Logger { - return &Logger{ - Out: os.Stderr, - Formatter: new(TextFormatter), - Hooks: make(LevelHooks), - Level: InfoLevel, - } -} - -func (logger *Logger) newEntry() *Entry { - entry, ok := logger.entryPool.Get().(*Entry) - if ok { - return entry - } - return NewEntry(logger) -} - -func (logger *Logger) releaseEntry(entry *Entry) { - logger.entryPool.Put(entry) -} - -// Adds a field to the log entry, note that it doesn't log until you call -// Debug, Print, Info, Warn, Error, Fatal or Panic. It only creates a log entry. -// If you want multiple fields, use `WithFields`. -func (logger *Logger) WithField(key string, value interface{}) *Entry { - entry := logger.newEntry() - defer logger.releaseEntry(entry) - return entry.WithField(key, value) -} - -// Adds a struct of fields to the log entry. All it does is call `WithField` for -// each `Field`. -func (logger *Logger) WithFields(fields Fields) *Entry { - entry := logger.newEntry() - defer logger.releaseEntry(entry) - return entry.WithFields(fields) -} - -// Add an error as single field to the log entry. All it does is call -// `WithError` for the given `error`. -func (logger *Logger) WithError(err error) *Entry { - entry := logger.newEntry() - defer logger.releaseEntry(entry) - return entry.WithError(err) -} - -// Overrides the time of the log entry. -func (logger *Logger) WithTime(t time.Time) *Entry { - entry := logger.newEntry() - defer logger.releaseEntry(entry) - return entry.WithTime(t) -} - -func (logger *Logger) Debugf(format string, args ...interface{}) { - if logger.level() >= DebugLevel { - entry := logger.newEntry() - entry.Debugf(format, args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Infof(format string, args ...interface{}) { - if logger.level() >= InfoLevel { - entry := logger.newEntry() - entry.Infof(format, args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Printf(format string, args ...interface{}) { - entry := logger.newEntry() - entry.Printf(format, args...) - logger.releaseEntry(entry) -} - -func (logger *Logger) Warnf(format string, args ...interface{}) { - if logger.level() >= WarnLevel { - entry := logger.newEntry() - entry.Warnf(format, args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Warningf(format string, args ...interface{}) { - if logger.level() >= WarnLevel { - entry := logger.newEntry() - entry.Warnf(format, args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Errorf(format string, args ...interface{}) { - if logger.level() >= ErrorLevel { - entry := logger.newEntry() - entry.Errorf(format, args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Fatalf(format string, args ...interface{}) { - if logger.level() >= FatalLevel { - entry := logger.newEntry() - entry.Fatalf(format, args...) - logger.releaseEntry(entry) - } - Exit(1) -} - -func (logger *Logger) Panicf(format string, args ...interface{}) { - if logger.level() >= PanicLevel { - entry := logger.newEntry() - entry.Panicf(format, args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Debug(args ...interface{}) { - if logger.level() >= DebugLevel { - entry := logger.newEntry() - entry.Debug(args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Info(args ...interface{}) { - if logger.level() >= InfoLevel { - entry := logger.newEntry() - entry.Info(args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Print(args ...interface{}) { - entry := logger.newEntry() - entry.Info(args...) - logger.releaseEntry(entry) -} - -func (logger *Logger) Warn(args ...interface{}) { - if logger.level() >= WarnLevel { - entry := logger.newEntry() - entry.Warn(args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Warning(args ...interface{}) { - if logger.level() >= WarnLevel { - entry := logger.newEntry() - entry.Warn(args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Error(args ...interface{}) { - if logger.level() >= ErrorLevel { - entry := logger.newEntry() - entry.Error(args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Fatal(args ...interface{}) { - if logger.level() >= FatalLevel { - entry := logger.newEntry() - entry.Fatal(args...) - logger.releaseEntry(entry) - } - Exit(1) -} - -func (logger *Logger) Panic(args ...interface{}) { - if logger.level() >= PanicLevel { - entry := logger.newEntry() - entry.Panic(args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Debugln(args ...interface{}) { - if logger.level() >= DebugLevel { - entry := logger.newEntry() - entry.Debugln(args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Infoln(args ...interface{}) { - if logger.level() >= InfoLevel { - entry := logger.newEntry() - entry.Infoln(args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Println(args ...interface{}) { - entry := logger.newEntry() - entry.Println(args...) - logger.releaseEntry(entry) -} - -func (logger *Logger) Warnln(args ...interface{}) { - if logger.level() >= WarnLevel { - entry := logger.newEntry() - entry.Warnln(args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Warningln(args ...interface{}) { - if logger.level() >= WarnLevel { - entry := logger.newEntry() - entry.Warnln(args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Errorln(args ...interface{}) { - if logger.level() >= ErrorLevel { - entry := logger.newEntry() - entry.Errorln(args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Fatalln(args ...interface{}) { - if logger.level() >= FatalLevel { - entry := logger.newEntry() - entry.Fatalln(args...) - logger.releaseEntry(entry) - } - Exit(1) -} - -func (logger *Logger) Panicln(args ...interface{}) { - if logger.level() >= PanicLevel { - entry := logger.newEntry() - entry.Panicln(args...) - logger.releaseEntry(entry) - } -} - -//When file is opened with appending mode, it's safe to -//write concurrently to a file (within 4k message on Linux). -//In these cases user can choose to disable the lock. -func (logger *Logger) SetNoLock() { - logger.mu.Disable() -} - -func (logger *Logger) level() Level { - return Level(atomic.LoadUint32((*uint32)(&logger.Level))) -} - -func (logger *Logger) SetLevel(level Level) { - atomic.StoreUint32((*uint32)(&logger.Level), uint32(level)) -} - -func (logger *Logger) SetOutput(out io.Writer) { - logger.mu.Lock() - defer logger.mu.Unlock() - logger.Out = out -} - -func (logger *Logger) AddHook(hook Hook) { - logger.mu.Lock() - defer logger.mu.Unlock() - logger.Hooks.Add(hook) -} diff --git a/vendor/github.com/Sirupsen/logrus/logrus.go b/vendor/github.com/Sirupsen/logrus/logrus.go deleted file mode 100644 index dd38999..0000000 --- a/vendor/github.com/Sirupsen/logrus/logrus.go +++ /dev/null @@ -1,143 +0,0 @@ -package logrus - -import ( - "fmt" - "log" - "strings" -) - -// Fields type, used to pass to `WithFields`. -type Fields map[string]interface{} - -// Level type -type Level uint32 - -// Convert the Level to a string. E.g. PanicLevel becomes "panic". -func (level Level) String() string { - switch level { - case DebugLevel: - return "debug" - case InfoLevel: - return "info" - case WarnLevel: - return "warning" - case ErrorLevel: - return "error" - case FatalLevel: - return "fatal" - case PanicLevel: - return "panic" - } - - return "unknown" -} - -// ParseLevel takes a string level and returns the Logrus log level constant. -func ParseLevel(lvl string) (Level, error) { - switch strings.ToLower(lvl) { - case "panic": - return PanicLevel, nil - case "fatal": - return FatalLevel, nil - case "error": - return ErrorLevel, nil - case "warn", "warning": - return WarnLevel, nil - case "info": - return InfoLevel, nil - case "debug": - return DebugLevel, nil - } - - var l Level - return l, fmt.Errorf("not a valid logrus Level: %q", lvl) -} - -// A constant exposing all logging levels -var AllLevels = []Level{ - PanicLevel, - FatalLevel, - ErrorLevel, - WarnLevel, - InfoLevel, - DebugLevel, -} - -// These are the different logging levels. You can set the logging level to log -// on your instance of logger, obtained with `logrus.New()`. -const ( - // PanicLevel level, highest level of severity. Logs and then calls panic with the - // message passed to Debug, Info, ... - PanicLevel Level = iota - // FatalLevel level. Logs and then calls `os.Exit(1)`. It will exit even if the - // logging level is set to Panic. - FatalLevel - // ErrorLevel level. Logs. Used for errors that should definitely be noted. - // Commonly used for hooks to send errors to an error tracking service. - ErrorLevel - // WarnLevel level. Non-critical entries that deserve eyes. - WarnLevel - // InfoLevel level. General operational entries about what's going on inside the - // application. - InfoLevel - // DebugLevel level. Usually only enabled when debugging. Very verbose logging. - DebugLevel -) - -// Won't compile if StdLogger can't be realized by a log.Logger -var ( - _ StdLogger = &log.Logger{} - _ StdLogger = &Entry{} - _ StdLogger = &Logger{} -) - -// StdLogger is what your logrus-enabled library should take, that way -// it'll accept a stdlib logger and a logrus logger. There's no standard -// interface, this is the closest we get, unfortunately. -type StdLogger interface { - Print(...interface{}) - Printf(string, ...interface{}) - Println(...interface{}) - - Fatal(...interface{}) - Fatalf(string, ...interface{}) - Fatalln(...interface{}) - - Panic(...interface{}) - Panicf(string, ...interface{}) - Panicln(...interface{}) -} - -// The FieldLogger interface generalizes the Entry and Logger types -type FieldLogger interface { - WithField(key string, value interface{}) *Entry - WithFields(fields Fields) *Entry - WithError(err error) *Entry - - Debugf(format string, args ...interface{}) - Infof(format string, args ...interface{}) - Printf(format string, args ...interface{}) - Warnf(format string, args ...interface{}) - Warningf(format string, args ...interface{}) - Errorf(format string, args ...interface{}) - Fatalf(format string, args ...interface{}) - Panicf(format string, args ...interface{}) - - Debug(args ...interface{}) - Info(args ...interface{}) - Print(args ...interface{}) - Warn(args ...interface{}) - Warning(args ...interface{}) - Error(args ...interface{}) - Fatal(args ...interface{}) - Panic(args ...interface{}) - - Debugln(args ...interface{}) - Infoln(args ...interface{}) - Println(args ...interface{}) - Warnln(args ...interface{}) - Warningln(args ...interface{}) - Errorln(args ...interface{}) - Fatalln(args ...interface{}) - Panicln(args ...interface{}) -} diff --git a/vendor/github.com/Sirupsen/logrus/terminal_bsd.go b/vendor/github.com/Sirupsen/logrus/terminal_bsd.go deleted file mode 100644 index 4880d13..0000000 --- a/vendor/github.com/Sirupsen/logrus/terminal_bsd.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build darwin freebsd openbsd netbsd dragonfly -// +build !appengine,!gopherjs - -package logrus - -import "golang.org/x/sys/unix" - -const ioctlReadTermios = unix.TIOCGETA - -type Termios unix.Termios diff --git a/vendor/github.com/Sirupsen/logrus/terminal_check_appengine.go b/vendor/github.com/Sirupsen/logrus/terminal_check_appengine.go deleted file mode 100644 index 3de08e8..0000000 --- a/vendor/github.com/Sirupsen/logrus/terminal_check_appengine.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build appengine gopherjs - -package logrus - -import ( - "io" -) - -func checkIfTerminal(w io.Writer) bool { - return true -} diff --git a/vendor/github.com/Sirupsen/logrus/terminal_check_notappengine.go b/vendor/github.com/Sirupsen/logrus/terminal_check_notappengine.go deleted file mode 100644 index 067047a..0000000 --- a/vendor/github.com/Sirupsen/logrus/terminal_check_notappengine.go +++ /dev/null @@ -1,19 +0,0 @@ -// +build !appengine,!gopherjs - -package logrus - -import ( - "io" - "os" - - "golang.org/x/crypto/ssh/terminal" -) - -func checkIfTerminal(w io.Writer) bool { - switch v := w.(type) { - case *os.File: - return terminal.IsTerminal(int(v.Fd())) - default: - return false - } -} diff --git a/vendor/github.com/Sirupsen/logrus/terminal_linux.go b/vendor/github.com/Sirupsen/logrus/terminal_linux.go deleted file mode 100644 index f29a009..0000000 --- a/vendor/github.com/Sirupsen/logrus/terminal_linux.go +++ /dev/null @@ -1,14 +0,0 @@ -// Based on ssh/terminal: -// 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 !appengine,!gopherjs - -package logrus - -import "golang.org/x/sys/unix" - -const ioctlReadTermios = unix.TCGETS - -type Termios unix.Termios diff --git a/vendor/github.com/Sirupsen/logrus/text_formatter.go b/vendor/github.com/Sirupsen/logrus/text_formatter.go deleted file mode 100644 index 3e55040..0000000 --- a/vendor/github.com/Sirupsen/logrus/text_formatter.go +++ /dev/null @@ -1,195 +0,0 @@ -package logrus - -import ( - "bytes" - "fmt" - "sort" - "strings" - "sync" - "time" -) - -const ( - nocolor = 0 - red = 31 - green = 32 - yellow = 33 - blue = 36 - gray = 37 -) - -var ( - baseTimestamp time.Time - emptyFieldMap FieldMap -) - -func init() { - baseTimestamp = time.Now() -} - -// TextFormatter formats logs into text -type TextFormatter struct { - // Set to true to bypass checking for a TTY before outputting colors. - ForceColors bool - - // Force disabling colors. - DisableColors bool - - // Disable timestamp logging. useful when output is redirected to logging - // system that already adds timestamps. - DisableTimestamp bool - - // Enable logging the full timestamp when a TTY is attached instead of just - // the time passed since beginning of execution. - FullTimestamp bool - - // TimestampFormat to use for display when a full timestamp is printed - TimestampFormat string - - // The fields are sorted by default for a consistent output. For applications - // that log extremely frequently and don't use the JSON formatter this may not - // be desired. - DisableSorting bool - - // Disables the truncation of the level text to 4 characters. - DisableLevelTruncation bool - - // QuoteEmptyFields will wrap empty fields in quotes if true - QuoteEmptyFields bool - - // Whether the logger's out is to a terminal - isTerminal bool - - // FieldMap allows users to customize the names of keys for default fields. - // As an example: - // formatter := &TextFormatter{ - // FieldMap: FieldMap{ - // FieldKeyTime: "@timestamp", - // FieldKeyLevel: "@level", - // FieldKeyMsg: "@message"}} - FieldMap FieldMap - - sync.Once -} - -func (f *TextFormatter) init(entry *Entry) { - if entry.Logger != nil { - f.isTerminal = checkIfTerminal(entry.Logger.Out) - } -} - -// Format renders a single log entry -func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { - prefixFieldClashes(entry.Data, f.FieldMap) - - keys := make([]string, 0, len(entry.Data)) - for k := range entry.Data { - keys = append(keys, k) - } - - if !f.DisableSorting { - sort.Strings(keys) - } - - var b *bytes.Buffer - if entry.Buffer != nil { - b = entry.Buffer - } else { - b = &bytes.Buffer{} - } - - f.Do(func() { f.init(entry) }) - - isColored := (f.ForceColors || f.isTerminal) && !f.DisableColors - - timestampFormat := f.TimestampFormat - if timestampFormat == "" { - timestampFormat = defaultTimestampFormat - } - if isColored { - f.printColored(b, entry, keys, timestampFormat) - } else { - if !f.DisableTimestamp { - f.appendKeyValue(b, f.FieldMap.resolve(FieldKeyTime), entry.Time.Format(timestampFormat)) - } - f.appendKeyValue(b, f.FieldMap.resolve(FieldKeyLevel), entry.Level.String()) - if entry.Message != "" { - f.appendKeyValue(b, f.FieldMap.resolve(FieldKeyMsg), entry.Message) - } - for _, key := range keys { - f.appendKeyValue(b, key, entry.Data[key]) - } - } - - b.WriteByte('\n') - return b.Bytes(), nil -} - -func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, timestampFormat string) { - var levelColor int - switch entry.Level { - case DebugLevel: - levelColor = gray - case WarnLevel: - levelColor = yellow - case ErrorLevel, FatalLevel, PanicLevel: - levelColor = red - default: - levelColor = blue - } - - levelText := strings.ToUpper(entry.Level.String()) - if !f.DisableLevelTruncation { - levelText = levelText[0:4] - } - - if f.DisableTimestamp { - fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m %-44s ", levelColor, levelText, entry.Message) - } else if !f.FullTimestamp { - fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), entry.Message) - } else { - fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), entry.Message) - } - for _, k := range keys { - v := entry.Data[k] - fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k) - f.appendValue(b, v) - } -} - -func (f *TextFormatter) needsQuoting(text string) bool { - if f.QuoteEmptyFields && len(text) == 0 { - return true - } - for _, ch := range text { - if !((ch >= 'a' && ch <= 'z') || - (ch >= 'A' && ch <= 'Z') || - (ch >= '0' && ch <= '9') || - ch == '-' || ch == '.' || ch == '_' || ch == '/' || ch == '@' || ch == '^' || ch == '+') { - return true - } - } - return false -} - -func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) { - if b.Len() > 0 { - b.WriteByte(' ') - } - b.WriteString(key) - b.WriteByte('=') - f.appendValue(b, value) -} - -func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) { - stringVal, ok := value.(string) - if !ok { - stringVal = fmt.Sprint(value) - } - - if !f.needsQuoting(stringVal) { - b.WriteString(stringVal) - } else { - b.WriteString(fmt.Sprintf("%q", stringVal)) - } -} diff --git a/vendor/github.com/Sirupsen/logrus/writer.go b/vendor/github.com/Sirupsen/logrus/writer.go deleted file mode 100644 index 7bdebed..0000000 --- a/vendor/github.com/Sirupsen/logrus/writer.go +++ /dev/null @@ -1,62 +0,0 @@ -package logrus - -import ( - "bufio" - "io" - "runtime" -) - -func (logger *Logger) Writer() *io.PipeWriter { - return logger.WriterLevel(InfoLevel) -} - -func (logger *Logger) WriterLevel(level Level) *io.PipeWriter { - return NewEntry(logger).WriterLevel(level) -} - -func (entry *Entry) Writer() *io.PipeWriter { - return entry.WriterLevel(InfoLevel) -} - -func (entry *Entry) WriterLevel(level Level) *io.PipeWriter { - reader, writer := io.Pipe() - - var printFunc func(args ...interface{}) - - switch level { - case DebugLevel: - printFunc = entry.Debug - case InfoLevel: - printFunc = entry.Info - case WarnLevel: - printFunc = entry.Warn - case ErrorLevel: - printFunc = entry.Error - case FatalLevel: - printFunc = entry.Fatal - case PanicLevel: - printFunc = entry.Panic - default: - printFunc = entry.Print - } - - go entry.writerScanner(reader, printFunc) - runtime.SetFinalizer(writer, writerFinalizer) - - return writer -} - -func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) { - scanner := bufio.NewScanner(reader) - for scanner.Scan() { - printFunc(scanner.Text()) - } - if err := scanner.Err(); err != nil { - entry.Errorf("Error while reading from Writer: %s", err) - } - reader.Close() -} - -func writerFinalizer(writer *io.PipeWriter) { - writer.Close() -} diff --git a/vendor/github.com/alecthomas/template/LICENSE b/vendor/github.com/alecthomas/template/LICENSE deleted file mode 100644 index 7448756..0000000 --- a/vendor/github.com/alecthomas/template/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/alecthomas/template/README.md b/vendor/github.com/alecthomas/template/README.md deleted file mode 100644 index ef6a8ee..0000000 --- a/vendor/github.com/alecthomas/template/README.md +++ /dev/null @@ -1,25 +0,0 @@ -# Go's `text/template` package with newline elision - -This is a fork of Go 1.4's [text/template](http://golang.org/pkg/text/template/) package with one addition: a backslash immediately after a closing delimiter will delete all subsequent newlines until a non-newline. - -eg. - -``` -{{if true}}\ -hello -{{end}}\ -``` - -Will result in: - -``` -hello\n -``` - -Rather than: - -``` -\n -hello\n -\n -``` diff --git a/vendor/github.com/alecthomas/template/doc.go b/vendor/github.com/alecthomas/template/doc.go deleted file mode 100644 index 223c595..0000000 --- a/vendor/github.com/alecthomas/template/doc.go +++ /dev/null @@ -1,406 +0,0 @@ -// Copyright 2011 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 template implements data-driven templates for generating textual output. - -To generate HTML output, see package html/template, which has the same interface -as this package but automatically secures HTML output against certain attacks. - -Templates are executed by applying them to a data structure. Annotations in the -template refer to elements of the data structure (typically a field of a struct -or a key in a map) to control execution and derive values to be displayed. -Execution of the template walks the structure and sets the cursor, represented -by a period '.' and called "dot", to the value at the current location in the -structure as execution proceeds. - -The input text for a template is UTF-8-encoded text in any format. -"Actions"--data evaluations or control structures--are delimited by -"{{" and "}}"; all text outside actions is copied to the output unchanged. -Actions may not span newlines, although comments can. - -Once parsed, a template may be executed safely in parallel. - -Here is a trivial example that prints "17 items are made of wool". - - type Inventory struct { - Material string - Count uint - } - sweaters := Inventory{"wool", 17} - tmpl, err := template.New("test").Parse("{{.Count}} items are made of {{.Material}}") - if err != nil { panic(err) } - err = tmpl.Execute(os.Stdout, sweaters) - if err != nil { panic(err) } - -More intricate examples appear below. - -Actions - -Here is the list of actions. "Arguments" and "pipelines" are evaluations of -data, defined in detail below. - -*/ -// {{/* a comment */}} -// A comment; discarded. May contain newlines. -// Comments do not nest and must start and end at the -// delimiters, as shown here. -/* - - {{pipeline}} - The default textual representation of the value of the pipeline - is copied to the output. - - {{if pipeline}} T1 {{end}} - If the value of the pipeline is empty, no output is generated; - otherwise, T1 is executed. The empty values are false, 0, any - nil pointer or interface value, and any array, slice, map, or - string of length zero. - Dot is unaffected. - - {{if pipeline}} T1 {{else}} T0 {{end}} - If the value of the pipeline is empty, T0 is executed; - otherwise, T1 is executed. Dot is unaffected. - - {{if pipeline}} T1 {{else if pipeline}} T0 {{end}} - To simplify the appearance of if-else chains, the else action - of an if may include another if directly; the effect is exactly - the same as writing - {{if pipeline}} T1 {{else}}{{if pipeline}} T0 {{end}}{{end}} - - {{range pipeline}} T1 {{end}} - The value of the pipeline must be an array, slice, map, or channel. - If the value of the pipeline has length zero, nothing is output; - otherwise, dot is set to the successive elements of the array, - slice, or map and T1 is executed. If the value is a map and the - keys are of basic type with a defined order ("comparable"), the - elements will be visited in sorted key order. - - {{range pipeline}} T1 {{else}} T0 {{end}} - The value of the pipeline must be an array, slice, map, or channel. - If the value of the pipeline has length zero, dot is unaffected and - T0 is executed; otherwise, dot is set to the successive elements - of the array, slice, or map and T1 is executed. - - {{template "name"}} - The template with the specified name is executed with nil data. - - {{template "name" pipeline}} - The template with the specified name is executed with dot set - to the value of the pipeline. - - {{with pipeline}} T1 {{end}} - If the value of the pipeline is empty, no output is generated; - otherwise, dot is set to the value of the pipeline and T1 is - executed. - - {{with pipeline}} T1 {{else}} T0 {{end}} - If the value of the pipeline is empty, dot is unaffected and T0 - is executed; otherwise, dot is set to the value of the pipeline - and T1 is executed. - -Arguments - -An argument is a simple value, denoted by one of the following. - - - A boolean, string, character, integer, floating-point, imaginary - or complex constant in Go syntax. These behave like Go's untyped - constants, although raw strings may not span newlines. - - The keyword nil, representing an untyped Go nil. - - The character '.' (period): - . - The result is the value of dot. - - A variable name, which is a (possibly empty) alphanumeric string - preceded by a dollar sign, such as - $piOver2 - or - $ - The result is the value of the variable. - Variables are described below. - - The name of a field of the data, which must be a struct, preceded - by a period, such as - .Field - The result is the value of the field. Field invocations may be - chained: - .Field1.Field2 - Fields can also be evaluated on variables, including chaining: - $x.Field1.Field2 - - The name of a key of the data, which must be a map, preceded - by a period, such as - .Key - The result is the map element value indexed by the key. - Key invocations may be chained and combined with fields to any - depth: - .Field1.Key1.Field2.Key2 - Although the key must be an alphanumeric identifier, unlike with - field names they do not need to start with an upper case letter. - Keys can also be evaluated on variables, including chaining: - $x.key1.key2 - - The name of a niladic method of the data, preceded by a period, - such as - .Method - The result is the value of invoking the method with dot as the - receiver, dot.Method(). Such a method must have one return value (of - any type) or two return values, the second of which is an error. - If it has two and the returned error is non-nil, execution terminates - and an error is returned to the caller as the value of Execute. - Method invocations may be chained and combined with fields and keys - to any depth: - .Field1.Key1.Method1.Field2.Key2.Method2 - Methods can also be evaluated on variables, including chaining: - $x.Method1.Field - - The name of a niladic function, such as - fun - The result is the value of invoking the function, fun(). The return - types and values behave as in methods. Functions and function - names are described below. - - A parenthesized instance of one the above, for grouping. The result - may be accessed by a field or map key invocation. - print (.F1 arg1) (.F2 arg2) - (.StructValuedMethod "arg").Field - -Arguments may evaluate to any type; if they are pointers the implementation -automatically indirects to the base type when required. -If an evaluation yields a function value, such as a function-valued -field of a struct, the function is not invoked automatically, but it -can be used as a truth value for an if action and the like. To invoke -it, use the call function, defined below. - -A pipeline is a possibly chained sequence of "commands". A command is a simple -value (argument) or a function or method call, possibly with multiple arguments: - - Argument - The result is the value of evaluating the argument. - .Method [Argument...] - The method can be alone or the last element of a chain but, - unlike methods in the middle of a chain, it can take arguments. - The result is the value of calling the method with the - arguments: - dot.Method(Argument1, etc.) - functionName [Argument...] - The result is the value of calling the function associated - with the name: - function(Argument1, etc.) - Functions and function names are described below. - -Pipelines - -A pipeline may be "chained" by separating a sequence of commands with pipeline -characters '|'. In a chained pipeline, the result of the each command is -passed as the last argument of the following command. The output of the final -command in the pipeline is the value of the pipeline. - -The output of a command will be either one value or two values, the second of -which has type error. If that second value is present and evaluates to -non-nil, execution terminates and the error is returned to the caller of -Execute. - -Variables - -A pipeline inside an action may initialize a variable to capture the result. -The initialization has syntax - - $variable := pipeline - -where $variable is the name of the variable. An action that declares a -variable produces no output. - -If a "range" action initializes a variable, the variable is set to the -successive elements of the iteration. Also, a "range" may declare two -variables, separated by a comma: - - range $index, $element := pipeline - -in which case $index and $element are set to the successive values of the -array/slice index or map key and element, respectively. Note that if there is -only one variable, it is assigned the element; this is opposite to the -convention in Go range clauses. - -A variable's scope extends to the "end" action of the control structure ("if", -"with", or "range") in which it is declared, or to the end of the template if -there is no such control structure. A template invocation does not inherit -variables from the point of its invocation. - -When execution begins, $ is set to the data argument passed to Execute, that is, -to the starting value of dot. - -Examples - -Here are some example one-line templates demonstrating pipelines and variables. -All produce the quoted word "output": - - {{"\"output\""}} - A string constant. - {{`"output"`}} - A raw string constant. - {{printf "%q" "output"}} - A function call. - {{"output" | printf "%q"}} - A function call whose final argument comes from the previous - command. - {{printf "%q" (print "out" "put")}} - A parenthesized argument. - {{"put" | printf "%s%s" "out" | printf "%q"}} - A more elaborate call. - {{"output" | printf "%s" | printf "%q"}} - A longer chain. - {{with "output"}}{{printf "%q" .}}{{end}} - A with action using dot. - {{with $x := "output" | printf "%q"}}{{$x}}{{end}} - A with action that creates and uses a variable. - {{with $x := "output"}}{{printf "%q" $x}}{{end}} - A with action that uses the variable in another action. - {{with $x := "output"}}{{$x | printf "%q"}}{{end}} - The same, but pipelined. - -Functions - -During execution functions are found in two function maps: first in the -template, then in the global function map. By default, no functions are defined -in the template but the Funcs method can be used to add them. - -Predefined global functions are named as follows. - - and - Returns the boolean AND of its arguments by returning the - first empty argument or the last argument, that is, - "and x y" behaves as "if x then y else x". All the - arguments are evaluated. - call - Returns the result of calling the first argument, which - must be a function, with the remaining arguments as parameters. - Thus "call .X.Y 1 2" is, in Go notation, dot.X.Y(1, 2) where - Y is a func-valued field, map entry, or the like. - The first argument must be the result of an evaluation - that yields a value of function type (as distinct from - a predefined function such as print). The function must - return either one or two result values, the second of which - is of type error. If the arguments don't match the function - or the returned error value is non-nil, execution stops. - html - Returns the escaped HTML equivalent of the textual - representation of its arguments. - index - Returns the result of indexing its first argument by the - following arguments. Thus "index x 1 2 3" is, in Go syntax, - x[1][2][3]. Each indexed item must be a map, slice, or array. - js - Returns the escaped JavaScript equivalent of the textual - representation of its arguments. - len - Returns the integer length of its argument. - not - Returns the boolean negation of its single argument. - or - Returns the boolean OR of its arguments by returning the - first non-empty argument or the last argument, that is, - "or x y" behaves as "if x then x else y". All the - arguments are evaluated. - print - An alias for fmt.Sprint - printf - An alias for fmt.Sprintf - println - An alias for fmt.Sprintln - urlquery - Returns the escaped value of the textual representation of - its arguments in a form suitable for embedding in a URL query. - -The boolean functions take any zero value to be false and a non-zero -value to be true. - -There is also a set of binary comparison operators defined as -functions: - - eq - Returns the boolean truth of arg1 == arg2 - ne - Returns the boolean truth of arg1 != arg2 - lt - Returns the boolean truth of arg1 < arg2 - le - Returns the boolean truth of arg1 <= arg2 - gt - Returns the boolean truth of arg1 > arg2 - ge - Returns the boolean truth of arg1 >= arg2 - -For simpler multi-way equality tests, eq (only) accepts two or more -arguments and compares the second and subsequent to the first, -returning in effect - - arg1==arg2 || arg1==arg3 || arg1==arg4 ... - -(Unlike with || in Go, however, eq is a function call and all the -arguments will be evaluated.) - -The comparison functions work on basic types only (or named basic -types, such as "type Celsius float32"). They implement the Go rules -for comparison of values, except that size and exact type are -ignored, so any integer value, signed or unsigned, may be compared -with any other integer value. (The arithmetic value is compared, -not the bit pattern, so all negative integers are less than all -unsigned integers.) However, as usual, one may not compare an int -with a float32 and so on. - -Associated templates - -Each template is named by a string specified when it is created. Also, each -template is associated with zero or more other templates that it may invoke by -name; such associations are transitive and form a name space of templates. - -A template may use a template invocation to instantiate another associated -template; see the explanation of the "template" action above. The name must be -that of a template associated with the template that contains the invocation. - -Nested template definitions - -When parsing a template, another template may be defined and associated with the -template being parsed. Template definitions must appear at the top level of the -template, much like global variables in a Go program. - -The syntax of such definitions is to surround each template declaration with a -"define" and "end" action. - -The define action names the template being created by providing a string -constant. Here is a simple example: - - `{{define "T1"}}ONE{{end}} - {{define "T2"}}TWO{{end}} - {{define "T3"}}{{template "T1"}} {{template "T2"}}{{end}} - {{template "T3"}}` - -This defines two templates, T1 and T2, and a third T3 that invokes the other two -when it is executed. Finally it invokes T3. If executed this template will -produce the text - - ONE TWO - -By construction, a template may reside in only one association. If it's -necessary to have a template addressable from multiple associations, the -template definition must be parsed multiple times to create distinct *Template -values, or must be copied with the Clone or AddParseTree method. - -Parse may be called multiple times to assemble the various associated templates; -see the ParseFiles and ParseGlob functions and methods for simple ways to parse -related templates stored in files. - -A template may be executed directly or through ExecuteTemplate, which executes -an associated template identified by name. To invoke our example above, we -might write, - - err := tmpl.Execute(os.Stdout, "no data needed") - if err != nil { - log.Fatalf("execution failed: %s", err) - } - -or to invoke a particular template explicitly by name, - - err := tmpl.ExecuteTemplate(os.Stdout, "T2", "no data needed") - if err != nil { - log.Fatalf("execution failed: %s", err) - } - -*/ -package template diff --git a/vendor/github.com/alecthomas/template/exec.go b/vendor/github.com/alecthomas/template/exec.go deleted file mode 100644 index c3078e5..0000000 --- a/vendor/github.com/alecthomas/template/exec.go +++ /dev/null @@ -1,845 +0,0 @@ -// Copyright 2011 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 template - -import ( - "bytes" - "fmt" - "io" - "reflect" - "runtime" - "sort" - "strings" - - "github.com/alecthomas/template/parse" -) - -// state represents the state of an execution. It's not part of the -// template so that multiple executions of the same template -// can execute in parallel. -type state struct { - tmpl *Template - wr io.Writer - node parse.Node // current node, for errors - vars []variable // push-down stack of variable values. -} - -// variable holds the dynamic value of a variable such as $, $x etc. -type variable struct { - name string - value reflect.Value -} - -// push pushes a new variable on the stack. -func (s *state) push(name string, value reflect.Value) { - s.vars = append(s.vars, variable{name, value}) -} - -// mark returns the length of the variable stack. -func (s *state) mark() int { - return len(s.vars) -} - -// pop pops the variable stack up to the mark. -func (s *state) pop(mark int) { - s.vars = s.vars[0:mark] -} - -// setVar overwrites the top-nth variable on the stack. Used by range iterations. -func (s *state) setVar(n int, value reflect.Value) { - s.vars[len(s.vars)-n].value = value -} - -// varValue returns the value of the named variable. -func (s *state) varValue(name string) reflect.Value { - for i := s.mark() - 1; i >= 0; i-- { - if s.vars[i].name == name { - return s.vars[i].value - } - } - s.errorf("undefined variable: %s", name) - return zero -} - -var zero reflect.Value - -// at marks the state to be on node n, for error reporting. -func (s *state) at(node parse.Node) { - s.node = node -} - -// doublePercent returns the string with %'s replaced by %%, if necessary, -// so it can be used safely inside a Printf format string. -func doublePercent(str string) string { - if strings.Contains(str, "%") { - str = strings.Replace(str, "%", "%%", -1) - } - return str -} - -// errorf formats the error and terminates processing. -func (s *state) errorf(format string, args ...interface{}) { - name := doublePercent(s.tmpl.Name()) - if s.node == nil { - format = fmt.Sprintf("template: %s: %s", name, format) - } else { - location, context := s.tmpl.ErrorContext(s.node) - format = fmt.Sprintf("template: %s: executing %q at <%s>: %s", location, name, doublePercent(context), format) - } - panic(fmt.Errorf(format, args...)) -} - -// errRecover is the handler that turns panics into returns from the top -// level of Parse. -func errRecover(errp *error) { - e := recover() - if e != nil { - switch err := e.(type) { - case runtime.Error: - panic(e) - case error: - *errp = err - default: - panic(e) - } - } -} - -// ExecuteTemplate applies the template associated with t that has the given name -// to the specified data object and writes the output to wr. -// If an error occurs executing the template or writing its output, -// execution stops, but partial results may already have been written to -// the output writer. -// A template may be executed safely in parallel. -func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error { - tmpl := t.tmpl[name] - if tmpl == nil { - return fmt.Errorf("template: no template %q associated with template %q", name, t.name) - } - return tmpl.Execute(wr, data) -} - -// Execute applies a parsed template to the specified data object, -// and writes the output to wr. -// If an error occurs executing the template or writing its output, -// execution stops, but partial results may already have been written to -// the output writer. -// A template may be executed safely in parallel. -func (t *Template) Execute(wr io.Writer, data interface{}) (err error) { - defer errRecover(&err) - value := reflect.ValueOf(data) - state := &state{ - tmpl: t, - wr: wr, - vars: []variable{{"$", value}}, - } - t.init() - if t.Tree == nil || t.Root == nil { - var b bytes.Buffer - for name, tmpl := range t.tmpl { - if tmpl.Tree == nil || tmpl.Root == nil { - continue - } - if b.Len() > 0 { - b.WriteString(", ") - } - fmt.Fprintf(&b, "%q", name) - } - var s string - if b.Len() > 0 { - s = "; defined templates are: " + b.String() - } - state.errorf("%q is an incomplete or empty template%s", t.Name(), s) - } - state.walk(value, t.Root) - return -} - -// Walk functions step through the major pieces of the template structure, -// generating output as they go. -func (s *state) walk(dot reflect.Value, node parse.Node) { - s.at(node) - switch node := node.(type) { - case *parse.ActionNode: - // Do not pop variables so they persist until next end. - // Also, if the action declares variables, don't print the result. - val := s.evalPipeline(dot, node.Pipe) - if len(node.Pipe.Decl) == 0 { - s.printValue(node, val) - } - case *parse.IfNode: - s.walkIfOrWith(parse.NodeIf, dot, node.Pipe, node.List, node.ElseList) - case *parse.ListNode: - for _, node := range node.Nodes { - s.walk(dot, node) - } - case *parse.RangeNode: - s.walkRange(dot, node) - case *parse.TemplateNode: - s.walkTemplate(dot, node) - case *parse.TextNode: - if _, err := s.wr.Write(node.Text); err != nil { - s.errorf("%s", err) - } - case *parse.WithNode: - s.walkIfOrWith(parse.NodeWith, dot, node.Pipe, node.List, node.ElseList) - default: - s.errorf("unknown node: %s", node) - } -} - -// walkIfOrWith walks an 'if' or 'with' node. The two control structures -// are identical in behavior except that 'with' sets dot. -func (s *state) walkIfOrWith(typ parse.NodeType, dot reflect.Value, pipe *parse.PipeNode, list, elseList *parse.ListNode) { - defer s.pop(s.mark()) - val := s.evalPipeline(dot, pipe) - truth, ok := isTrue(val) - if !ok { - s.errorf("if/with can't use %v", val) - } - if truth { - if typ == parse.NodeWith { - s.walk(val, list) - } else { - s.walk(dot, list) - } - } else if elseList != nil { - s.walk(dot, elseList) - } -} - -// isTrue reports whether the value is 'true', in the sense of not the zero of its type, -// and whether the value has a meaningful truth value. -func isTrue(val reflect.Value) (truth, ok bool) { - if !val.IsValid() { - // Something like var x interface{}, never set. It's a form of nil. - return false, true - } - switch val.Kind() { - case reflect.Array, reflect.Map, reflect.Slice, reflect.String: - truth = val.Len() > 0 - case reflect.Bool: - truth = val.Bool() - case reflect.Complex64, reflect.Complex128: - truth = val.Complex() != 0 - case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Interface: - truth = !val.IsNil() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - truth = val.Int() != 0 - case reflect.Float32, reflect.Float64: - truth = val.Float() != 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - truth = val.Uint() != 0 - case reflect.Struct: - truth = true // Struct values are always true. - default: - return - } - return truth, true -} - -func (s *state) walkRange(dot reflect.Value, r *parse.RangeNode) { - s.at(r) - defer s.pop(s.mark()) - val, _ := indirect(s.evalPipeline(dot, r.Pipe)) - // mark top of stack before any variables in the body are pushed. - mark := s.mark() - oneIteration := func(index, elem reflect.Value) { - // Set top var (lexically the second if there are two) to the element. - if len(r.Pipe.Decl) > 0 { - s.setVar(1, elem) - } - // Set next var (lexically the first if there are two) to the index. - if len(r.Pipe.Decl) > 1 { - s.setVar(2, index) - } - s.walk(elem, r.List) - s.pop(mark) - } - switch val.Kind() { - case reflect.Array, reflect.Slice: - if val.Len() == 0 { - break - } - for i := 0; i < val.Len(); i++ { - oneIteration(reflect.ValueOf(i), val.Index(i)) - } - return - case reflect.Map: - if val.Len() == 0 { - break - } - for _, key := range sortKeys(val.MapKeys()) { - oneIteration(key, val.MapIndex(key)) - } - return - case reflect.Chan: - if val.IsNil() { - break - } - i := 0 - for ; ; i++ { - elem, ok := val.Recv() - if !ok { - break - } - oneIteration(reflect.ValueOf(i), elem) - } - if i == 0 { - break - } - return - case reflect.Invalid: - break // An invalid value is likely a nil map, etc. and acts like an empty map. - default: - s.errorf("range can't iterate over %v", val) - } - if r.ElseList != nil { - s.walk(dot, r.ElseList) - } -} - -func (s *state) walkTemplate(dot reflect.Value, t *parse.TemplateNode) { - s.at(t) - tmpl := s.tmpl.tmpl[t.Name] - if tmpl == nil { - s.errorf("template %q not defined", t.Name) - } - // Variables declared by the pipeline persist. - dot = s.evalPipeline(dot, t.Pipe) - newState := *s - newState.tmpl = tmpl - // No dynamic scoping: template invocations inherit no variables. - newState.vars = []variable{{"$", dot}} - newState.walk(dot, tmpl.Root) -} - -// Eval functions evaluate pipelines, commands, and their elements and extract -// values from the data structure by examining fields, calling methods, and so on. -// The printing of those values happens only through walk functions. - -// evalPipeline returns the value acquired by evaluating a pipeline. If the -// pipeline has a variable declaration, the variable will be pushed on the -// stack. Callers should therefore pop the stack after they are finished -// executing commands depending on the pipeline value. -func (s *state) evalPipeline(dot reflect.Value, pipe *parse.PipeNode) (value reflect.Value) { - if pipe == nil { - return - } - s.at(pipe) - for _, cmd := range pipe.Cmds { - value = s.evalCommand(dot, cmd, value) // previous value is this one's final arg. - // If the object has type interface{}, dig down one level to the thing inside. - if value.Kind() == reflect.Interface && value.Type().NumMethod() == 0 { - value = reflect.ValueOf(value.Interface()) // lovely! - } - } - for _, variable := range pipe.Decl { - s.push(variable.Ident[0], value) - } - return value -} - -func (s *state) notAFunction(args []parse.Node, final reflect.Value) { - if len(args) > 1 || final.IsValid() { - s.errorf("can't give argument to non-function %s", args[0]) - } -} - -func (s *state) evalCommand(dot reflect.Value, cmd *parse.CommandNode, final reflect.Value) reflect.Value { - firstWord := cmd.Args[0] - switch n := firstWord.(type) { - case *parse.FieldNode: - return s.evalFieldNode(dot, n, cmd.Args, final) - case *parse.ChainNode: - return s.evalChainNode(dot, n, cmd.Args, final) - case *parse.IdentifierNode: - // Must be a function. - return s.evalFunction(dot, n, cmd, cmd.Args, final) - case *parse.PipeNode: - // Parenthesized pipeline. The arguments are all inside the pipeline; final is ignored. - return s.evalPipeline(dot, n) - case *parse.VariableNode: - return s.evalVariableNode(dot, n, cmd.Args, final) - } - s.at(firstWord) - s.notAFunction(cmd.Args, final) - switch word := firstWord.(type) { - case *parse.BoolNode: - return reflect.ValueOf(word.True) - case *parse.DotNode: - return dot - case *parse.NilNode: - s.errorf("nil is not a command") - case *parse.NumberNode: - return s.idealConstant(word) - case *parse.StringNode: - return reflect.ValueOf(word.Text) - } - s.errorf("can't evaluate command %q", firstWord) - panic("not reached") -} - -// idealConstant is called to return the value of a number in a context where -// we don't know the type. In that case, the syntax of the number tells us -// its type, and we use Go rules to resolve. Note there is no such thing as -// a uint ideal constant in this situation - the value must be of int type. -func (s *state) idealConstant(constant *parse.NumberNode) reflect.Value { - // These are ideal constants but we don't know the type - // and we have no context. (If it was a method argument, - // we'd know what we need.) The syntax guides us to some extent. - s.at(constant) - switch { - case constant.IsComplex: - return reflect.ValueOf(constant.Complex128) // incontrovertible. - case constant.IsFloat && !isHexConstant(constant.Text) && strings.IndexAny(constant.Text, ".eE") >= 0: - return reflect.ValueOf(constant.Float64) - case constant.IsInt: - n := int(constant.Int64) - if int64(n) != constant.Int64 { - s.errorf("%s overflows int", constant.Text) - } - return reflect.ValueOf(n) - case constant.IsUint: - s.errorf("%s overflows int", constant.Text) - } - return zero -} - -func isHexConstant(s string) bool { - return len(s) > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X') -} - -func (s *state) evalFieldNode(dot reflect.Value, field *parse.FieldNode, args []parse.Node, final reflect.Value) reflect.Value { - s.at(field) - return s.evalFieldChain(dot, dot, field, field.Ident, args, final) -} - -func (s *state) evalChainNode(dot reflect.Value, chain *parse.ChainNode, args []parse.Node, final reflect.Value) reflect.Value { - s.at(chain) - // (pipe).Field1.Field2 has pipe as .Node, fields as .Field. Eval the pipeline, then the fields. - pipe := s.evalArg(dot, nil, chain.Node) - if len(chain.Field) == 0 { - s.errorf("internal error: no fields in evalChainNode") - } - return s.evalFieldChain(dot, pipe, chain, chain.Field, args, final) -} - -func (s *state) evalVariableNode(dot reflect.Value, variable *parse.VariableNode, args []parse.Node, final reflect.Value) reflect.Value { - // $x.Field has $x as the first ident, Field as the second. Eval the var, then the fields. - s.at(variable) - value := s.varValue(variable.Ident[0]) - if len(variable.Ident) == 1 { - s.notAFunction(args, final) - return value - } - return s.evalFieldChain(dot, value, variable, variable.Ident[1:], args, final) -} - -// evalFieldChain evaluates .X.Y.Z possibly followed by arguments. -// dot is the environment in which to evaluate arguments, while -// receiver is the value being walked along the chain. -func (s *state) evalFieldChain(dot, receiver reflect.Value, node parse.Node, ident []string, args []parse.Node, final reflect.Value) reflect.Value { - n := len(ident) - for i := 0; i < n-1; i++ { - receiver = s.evalField(dot, ident[i], node, nil, zero, receiver) - } - // Now if it's a method, it gets the arguments. - return s.evalField(dot, ident[n-1], node, args, final, receiver) -} - -func (s *state) evalFunction(dot reflect.Value, node *parse.IdentifierNode, cmd parse.Node, args []parse.Node, final reflect.Value) reflect.Value { - s.at(node) - name := node.Ident - function, ok := findFunction(name, s.tmpl) - if !ok { - s.errorf("%q is not a defined function", name) - } - return s.evalCall(dot, function, cmd, name, args, final) -} - -// evalField evaluates an expression like (.Field) or (.Field arg1 arg2). -// The 'final' argument represents the return value from the preceding -// value of the pipeline, if any. -func (s *state) evalField(dot reflect.Value, fieldName string, node parse.Node, args []parse.Node, final, receiver reflect.Value) reflect.Value { - if !receiver.IsValid() { - return zero - } - typ := receiver.Type() - receiver, _ = indirect(receiver) - // Unless it's an interface, need to get to a value of type *T to guarantee - // we see all methods of T and *T. - ptr := receiver - if ptr.Kind() != reflect.Interface && ptr.CanAddr() { - ptr = ptr.Addr() - } - if method := ptr.MethodByName(fieldName); method.IsValid() { - return s.evalCall(dot, method, node, fieldName, args, final) - } - hasArgs := len(args) > 1 || final.IsValid() - // It's not a method; must be a field of a struct or an element of a map. The receiver must not be nil. - receiver, isNil := indirect(receiver) - if isNil { - s.errorf("nil pointer evaluating %s.%s", typ, fieldName) - } - switch receiver.Kind() { - case reflect.Struct: - tField, ok := receiver.Type().FieldByName(fieldName) - if ok { - field := receiver.FieldByIndex(tField.Index) - if tField.PkgPath != "" { // field is unexported - s.errorf("%s is an unexported field of struct type %s", fieldName, typ) - } - // If it's a function, we must call it. - if hasArgs { - s.errorf("%s has arguments but cannot be invoked as function", fieldName) - } - return field - } - s.errorf("%s is not a field of struct type %s", fieldName, typ) - case reflect.Map: - // If it's a map, attempt to use the field name as a key. - nameVal := reflect.ValueOf(fieldName) - if nameVal.Type().AssignableTo(receiver.Type().Key()) { - if hasArgs { - s.errorf("%s is not a method but has arguments", fieldName) - } - return receiver.MapIndex(nameVal) - } - } - s.errorf("can't evaluate field %s in type %s", fieldName, typ) - panic("not reached") -} - -var ( - errorType = reflect.TypeOf((*error)(nil)).Elem() - fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem() -) - -// evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so -// it looks just like a function call. The arg list, if non-nil, includes (in the manner of the shell), arg[0] -// as the function itself. -func (s *state) evalCall(dot, fun reflect.Value, node parse.Node, name string, args []parse.Node, final reflect.Value) reflect.Value { - if args != nil { - args = args[1:] // Zeroth arg is function name/node; not passed to function. - } - typ := fun.Type() - numIn := len(args) - if final.IsValid() { - numIn++ - } - numFixed := len(args) - if typ.IsVariadic() { - numFixed = typ.NumIn() - 1 // last arg is the variadic one. - if numIn < numFixed { - s.errorf("wrong number of args for %s: want at least %d got %d", name, typ.NumIn()-1, len(args)) - } - } else if numIn < typ.NumIn()-1 || !typ.IsVariadic() && numIn != typ.NumIn() { - s.errorf("wrong number of args for %s: want %d got %d", name, typ.NumIn(), len(args)) - } - if !goodFunc(typ) { - // TODO: This could still be a confusing error; maybe goodFunc should provide info. - s.errorf("can't call method/function %q with %d results", name, typ.NumOut()) - } - // Build the arg list. - argv := make([]reflect.Value, numIn) - // Args must be evaluated. Fixed args first. - i := 0 - for ; i < numFixed && i < len(args); i++ { - argv[i] = s.evalArg(dot, typ.In(i), args[i]) - } - // Now the ... args. - if typ.IsVariadic() { - argType := typ.In(typ.NumIn() - 1).Elem() // Argument is a slice. - for ; i < len(args); i++ { - argv[i] = s.evalArg(dot, argType, args[i]) - } - } - // Add final value if necessary. - if final.IsValid() { - t := typ.In(typ.NumIn() - 1) - if typ.IsVariadic() { - t = t.Elem() - } - argv[i] = s.validateType(final, t) - } - result := fun.Call(argv) - // If we have an error that is not nil, stop execution and return that error to the caller. - if len(result) == 2 && !result[1].IsNil() { - s.at(node) - s.errorf("error calling %s: %s", name, result[1].Interface().(error)) - } - return result[0] -} - -// canBeNil reports whether an untyped nil can be assigned to the type. See reflect.Zero. -func canBeNil(typ reflect.Type) bool { - switch typ.Kind() { - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return true - } - return false -} - -// validateType guarantees that the value is valid and assignable to the type. -func (s *state) validateType(value reflect.Value, typ reflect.Type) reflect.Value { - if !value.IsValid() { - if typ == nil || canBeNil(typ) { - // An untyped nil interface{}. Accept as a proper nil value. - return reflect.Zero(typ) - } - s.errorf("invalid value; expected %s", typ) - } - if typ != nil && !value.Type().AssignableTo(typ) { - if value.Kind() == reflect.Interface && !value.IsNil() { - value = value.Elem() - if value.Type().AssignableTo(typ) { - return value - } - // fallthrough - } - // Does one dereference or indirection work? We could do more, as we - // do with method receivers, but that gets messy and method receivers - // are much more constrained, so it makes more sense there than here. - // Besides, one is almost always all you need. - switch { - case value.Kind() == reflect.Ptr && value.Type().Elem().AssignableTo(typ): - value = value.Elem() - if !value.IsValid() { - s.errorf("dereference of nil pointer of type %s", typ) - } - case reflect.PtrTo(value.Type()).AssignableTo(typ) && value.CanAddr(): - value = value.Addr() - default: - s.errorf("wrong type for value; expected %s; got %s", typ, value.Type()) - } - } - return value -} - -func (s *state) evalArg(dot reflect.Value, typ reflect.Type, n parse.Node) reflect.Value { - s.at(n) - switch arg := n.(type) { - case *parse.DotNode: - return s.validateType(dot, typ) - case *parse.NilNode: - if canBeNil(typ) { - return reflect.Zero(typ) - } - s.errorf("cannot assign nil to %s", typ) - case *parse.FieldNode: - return s.validateType(s.evalFieldNode(dot, arg, []parse.Node{n}, zero), typ) - case *parse.VariableNode: - return s.validateType(s.evalVariableNode(dot, arg, nil, zero), typ) - case *parse.PipeNode: - return s.validateType(s.evalPipeline(dot, arg), typ) - case *parse.IdentifierNode: - return s.evalFunction(dot, arg, arg, nil, zero) - case *parse.ChainNode: - return s.validateType(s.evalChainNode(dot, arg, nil, zero), typ) - } - switch typ.Kind() { - case reflect.Bool: - return s.evalBool(typ, n) - case reflect.Complex64, reflect.Complex128: - return s.evalComplex(typ, n) - case reflect.Float32, reflect.Float64: - return s.evalFloat(typ, n) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return s.evalInteger(typ, n) - case reflect.Interface: - if typ.NumMethod() == 0 { - return s.evalEmptyInterface(dot, n) - } - case reflect.String: - return s.evalString(typ, n) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return s.evalUnsignedInteger(typ, n) - } - s.errorf("can't handle %s for arg of type %s", n, typ) - panic("not reached") -} - -func (s *state) evalBool(typ reflect.Type, n parse.Node) reflect.Value { - s.at(n) - if n, ok := n.(*parse.BoolNode); ok { - value := reflect.New(typ).Elem() - value.SetBool(n.True) - return value - } - s.errorf("expected bool; found %s", n) - panic("not reached") -} - -func (s *state) evalString(typ reflect.Type, n parse.Node) reflect.Value { - s.at(n) - if n, ok := n.(*parse.StringNode); ok { - value := reflect.New(typ).Elem() - value.SetString(n.Text) - return value - } - s.errorf("expected string; found %s", n) - panic("not reached") -} - -func (s *state) evalInteger(typ reflect.Type, n parse.Node) reflect.Value { - s.at(n) - if n, ok := n.(*parse.NumberNode); ok && n.IsInt { - value := reflect.New(typ).Elem() - value.SetInt(n.Int64) - return value - } - s.errorf("expected integer; found %s", n) - panic("not reached") -} - -func (s *state) evalUnsignedInteger(typ reflect.Type, n parse.Node) reflect.Value { - s.at(n) - if n, ok := n.(*parse.NumberNode); ok && n.IsUint { - value := reflect.New(typ).Elem() - value.SetUint(n.Uint64) - return value - } - s.errorf("expected unsigned integer; found %s", n) - panic("not reached") -} - -func (s *state) evalFloat(typ reflect.Type, n parse.Node) reflect.Value { - s.at(n) - if n, ok := n.(*parse.NumberNode); ok && n.IsFloat { - value := reflect.New(typ).Elem() - value.SetFloat(n.Float64) - return value - } - s.errorf("expected float; found %s", n) - panic("not reached") -} - -func (s *state) evalComplex(typ reflect.Type, n parse.Node) reflect.Value { - if n, ok := n.(*parse.NumberNode); ok && n.IsComplex { - value := reflect.New(typ).Elem() - value.SetComplex(n.Complex128) - return value - } - s.errorf("expected complex; found %s", n) - panic("not reached") -} - -func (s *state) evalEmptyInterface(dot reflect.Value, n parse.Node) reflect.Value { - s.at(n) - switch n := n.(type) { - case *parse.BoolNode: - return reflect.ValueOf(n.True) - case *parse.DotNode: - return dot - case *parse.FieldNode: - return s.evalFieldNode(dot, n, nil, zero) - case *parse.IdentifierNode: - return s.evalFunction(dot, n, n, nil, zero) - case *parse.NilNode: - // NilNode is handled in evalArg, the only place that calls here. - s.errorf("evalEmptyInterface: nil (can't happen)") - case *parse.NumberNode: - return s.idealConstant(n) - case *parse.StringNode: - return reflect.ValueOf(n.Text) - case *parse.VariableNode: - return s.evalVariableNode(dot, n, nil, zero) - case *parse.PipeNode: - return s.evalPipeline(dot, n) - } - s.errorf("can't handle assignment of %s to empty interface argument", n) - panic("not reached") -} - -// indirect returns the item at the end of indirection, and a bool to indicate if it's nil. -// We indirect through pointers and empty interfaces (only) because -// non-empty interfaces have methods we might need. -func indirect(v reflect.Value) (rv reflect.Value, isNil bool) { - for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() { - if v.IsNil() { - return v, true - } - if v.Kind() == reflect.Interface && v.NumMethod() > 0 { - break - } - } - return v, false -} - -// printValue writes the textual representation of the value to the output of -// the template. -func (s *state) printValue(n parse.Node, v reflect.Value) { - s.at(n) - iface, ok := printableValue(v) - if !ok { - s.errorf("can't print %s of type %s", n, v.Type()) - } - fmt.Fprint(s.wr, iface) -} - -// printableValue returns the, possibly indirected, interface value inside v that -// is best for a call to formatted printer. -func printableValue(v reflect.Value) (interface{}, bool) { - if v.Kind() == reflect.Ptr { - v, _ = indirect(v) // fmt.Fprint handles nil. - } - if !v.IsValid() { - return "", true - } - - if !v.Type().Implements(errorType) && !v.Type().Implements(fmtStringerType) { - if v.CanAddr() && (reflect.PtrTo(v.Type()).Implements(errorType) || reflect.PtrTo(v.Type()).Implements(fmtStringerType)) { - v = v.Addr() - } else { - switch v.Kind() { - case reflect.Chan, reflect.Func: - return nil, false - } - } - } - return v.Interface(), true -} - -// Types to help sort the keys in a map for reproducible output. - -type rvs []reflect.Value - -func (x rvs) Len() int { return len(x) } -func (x rvs) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - -type rvInts struct{ rvs } - -func (x rvInts) Less(i, j int) bool { return x.rvs[i].Int() < x.rvs[j].Int() } - -type rvUints struct{ rvs } - -func (x rvUints) Less(i, j int) bool { return x.rvs[i].Uint() < x.rvs[j].Uint() } - -type rvFloats struct{ rvs } - -func (x rvFloats) Less(i, j int) bool { return x.rvs[i].Float() < x.rvs[j].Float() } - -type rvStrings struct{ rvs } - -func (x rvStrings) Less(i, j int) bool { return x.rvs[i].String() < x.rvs[j].String() } - -// sortKeys sorts (if it can) the slice of reflect.Values, which is a slice of map keys. -func sortKeys(v []reflect.Value) []reflect.Value { - if len(v) <= 1 { - return v - } - switch v[0].Kind() { - case reflect.Float32, reflect.Float64: - sort.Sort(rvFloats{v}) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - sort.Sort(rvInts{v}) - case reflect.String: - sort.Sort(rvStrings{v}) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - sort.Sort(rvUints{v}) - } - return v -} diff --git a/vendor/github.com/alecthomas/template/funcs.go b/vendor/github.com/alecthomas/template/funcs.go deleted file mode 100644 index 39ee5ed..0000000 --- a/vendor/github.com/alecthomas/template/funcs.go +++ /dev/null @@ -1,598 +0,0 @@ -// Copyright 2011 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 template - -import ( - "bytes" - "errors" - "fmt" - "io" - "net/url" - "reflect" - "strings" - "unicode" - "unicode/utf8" -) - -// FuncMap is the type of the map defining the mapping from names to functions. -// Each function must have either a single return value, or two return values of -// which the second has type error. In that case, if the second (error) -// return value evaluates to non-nil during execution, execution terminates and -// Execute returns that error. -type FuncMap map[string]interface{} - -var builtins = FuncMap{ - "and": and, - "call": call, - "html": HTMLEscaper, - "index": index, - "js": JSEscaper, - "len": length, - "not": not, - "or": or, - "print": fmt.Sprint, - "printf": fmt.Sprintf, - "println": fmt.Sprintln, - "urlquery": URLQueryEscaper, - - // Comparisons - "eq": eq, // == - "ge": ge, // >= - "gt": gt, // > - "le": le, // <= - "lt": lt, // < - "ne": ne, // != -} - -var builtinFuncs = createValueFuncs(builtins) - -// createValueFuncs turns a FuncMap into a map[string]reflect.Value -func createValueFuncs(funcMap FuncMap) map[string]reflect.Value { - m := make(map[string]reflect.Value) - addValueFuncs(m, funcMap) - return m -} - -// addValueFuncs adds to values the functions in funcs, converting them to reflect.Values. -func addValueFuncs(out map[string]reflect.Value, in FuncMap) { - for name, fn := range in { - v := reflect.ValueOf(fn) - if v.Kind() != reflect.Func { - panic("value for " + name + " not a function") - } - if !goodFunc(v.Type()) { - panic(fmt.Errorf("can't install method/function %q with %d results", name, v.Type().NumOut())) - } - out[name] = v - } -} - -// addFuncs adds to values the functions in funcs. It does no checking of the input - -// call addValueFuncs first. -func addFuncs(out, in FuncMap) { - for name, fn := range in { - out[name] = fn - } -} - -// goodFunc checks that the function or method has the right result signature. -func goodFunc(typ reflect.Type) bool { - // We allow functions with 1 result or 2 results where the second is an error. - switch { - case typ.NumOut() == 1: - return true - case typ.NumOut() == 2 && typ.Out(1) == errorType: - return true - } - return false -} - -// findFunction looks for a function in the template, and global map. -func findFunction(name string, tmpl *Template) (reflect.Value, bool) { - if tmpl != nil && tmpl.common != nil { - if fn := tmpl.execFuncs[name]; fn.IsValid() { - return fn, true - } - } - if fn := builtinFuncs[name]; fn.IsValid() { - return fn, true - } - return reflect.Value{}, false -} - -// Indexing. - -// index returns the result of indexing its first argument by the following -// arguments. Thus "index x 1 2 3" is, in Go syntax, x[1][2][3]. Each -// indexed item must be a map, slice, or array. -func index(item interface{}, indices ...interface{}) (interface{}, error) { - v := reflect.ValueOf(item) - for _, i := range indices { - index := reflect.ValueOf(i) - var isNil bool - if v, isNil = indirect(v); isNil { - return nil, fmt.Errorf("index of nil pointer") - } - switch v.Kind() { - case reflect.Array, reflect.Slice, reflect.String: - var x int64 - switch index.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - x = index.Int() - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - x = int64(index.Uint()) - default: - return nil, fmt.Errorf("cannot index slice/array with type %s", index.Type()) - } - if x < 0 || x >= int64(v.Len()) { - return nil, fmt.Errorf("index out of range: %d", x) - } - v = v.Index(int(x)) - case reflect.Map: - if !index.IsValid() { - index = reflect.Zero(v.Type().Key()) - } - if !index.Type().AssignableTo(v.Type().Key()) { - return nil, fmt.Errorf("%s is not index type for %s", index.Type(), v.Type()) - } - if x := v.MapIndex(index); x.IsValid() { - v = x - } else { - v = reflect.Zero(v.Type().Elem()) - } - default: - return nil, fmt.Errorf("can't index item of type %s", v.Type()) - } - } - return v.Interface(), nil -} - -// Length - -// length returns the length of the item, with an error if it has no defined length. -func length(item interface{}) (int, error) { - v, isNil := indirect(reflect.ValueOf(item)) - if isNil { - return 0, fmt.Errorf("len of nil pointer") - } - switch v.Kind() { - case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String: - return v.Len(), nil - } - return 0, fmt.Errorf("len of type %s", v.Type()) -} - -// Function invocation - -// call returns the result of evaluating the first argument as a function. -// The function must return 1 result, or 2 results, the second of which is an error. -func call(fn interface{}, args ...interface{}) (interface{}, error) { - v := reflect.ValueOf(fn) - typ := v.Type() - if typ.Kind() != reflect.Func { - return nil, fmt.Errorf("non-function of type %s", typ) - } - if !goodFunc(typ) { - return nil, fmt.Errorf("function called with %d args; should be 1 or 2", typ.NumOut()) - } - numIn := typ.NumIn() - var dddType reflect.Type - if typ.IsVariadic() { - if len(args) < numIn-1 { - return nil, fmt.Errorf("wrong number of args: got %d want at least %d", len(args), numIn-1) - } - dddType = typ.In(numIn - 1).Elem() - } else { - if len(args) != numIn { - return nil, fmt.Errorf("wrong number of args: got %d want %d", len(args), numIn) - } - } - argv := make([]reflect.Value, len(args)) - for i, arg := range args { - value := reflect.ValueOf(arg) - // Compute the expected type. Clumsy because of variadics. - var argType reflect.Type - if !typ.IsVariadic() || i < numIn-1 { - argType = typ.In(i) - } else { - argType = dddType - } - if !value.IsValid() && canBeNil(argType) { - value = reflect.Zero(argType) - } - if !value.Type().AssignableTo(argType) { - return nil, fmt.Errorf("arg %d has type %s; should be %s", i, value.Type(), argType) - } - argv[i] = value - } - result := v.Call(argv) - if len(result) == 2 && !result[1].IsNil() { - return result[0].Interface(), result[1].Interface().(error) - } - return result[0].Interface(), nil -} - -// Boolean logic. - -func truth(a interface{}) bool { - t, _ := isTrue(reflect.ValueOf(a)) - return t -} - -// and computes the Boolean AND of its arguments, returning -// the first false argument it encounters, or the last argument. -func and(arg0 interface{}, args ...interface{}) interface{} { - if !truth(arg0) { - return arg0 - } - for i := range args { - arg0 = args[i] - if !truth(arg0) { - break - } - } - return arg0 -} - -// or computes the Boolean OR of its arguments, returning -// the first true argument it encounters, or the last argument. -func or(arg0 interface{}, args ...interface{}) interface{} { - if truth(arg0) { - return arg0 - } - for i := range args { - arg0 = args[i] - if truth(arg0) { - break - } - } - return arg0 -} - -// not returns the Boolean negation of its argument. -func not(arg interface{}) (truth bool) { - truth, _ = isTrue(reflect.ValueOf(arg)) - return !truth -} - -// Comparison. - -// TODO: Perhaps allow comparison between signed and unsigned integers. - -var ( - errBadComparisonType = errors.New("invalid type for comparison") - errBadComparison = errors.New("incompatible types for comparison") - errNoComparison = errors.New("missing argument for comparison") -) - -type kind int - -const ( - invalidKind kind = iota - boolKind - complexKind - intKind - floatKind - integerKind - stringKind - uintKind -) - -func basicKind(v reflect.Value) (kind, error) { - switch v.Kind() { - case reflect.Bool: - return boolKind, nil - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return intKind, nil - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return uintKind, nil - case reflect.Float32, reflect.Float64: - return floatKind, nil - case reflect.Complex64, reflect.Complex128: - return complexKind, nil - case reflect.String: - return stringKind, nil - } - return invalidKind, errBadComparisonType -} - -// eq evaluates the comparison a == b || a == c || ... -func eq(arg1 interface{}, arg2 ...interface{}) (bool, error) { - v1 := reflect.ValueOf(arg1) - k1, err := basicKind(v1) - if err != nil { - return false, err - } - if len(arg2) == 0 { - return false, errNoComparison - } - for _, arg := range arg2 { - v2 := reflect.ValueOf(arg) - k2, err := basicKind(v2) - if err != nil { - return false, err - } - truth := false - if k1 != k2 { - // Special case: Can compare integer values regardless of type's sign. - switch { - case k1 == intKind && k2 == uintKind: - truth = v1.Int() >= 0 && uint64(v1.Int()) == v2.Uint() - case k1 == uintKind && k2 == intKind: - truth = v2.Int() >= 0 && v1.Uint() == uint64(v2.Int()) - default: - return false, errBadComparison - } - } else { - switch k1 { - case boolKind: - truth = v1.Bool() == v2.Bool() - case complexKind: - truth = v1.Complex() == v2.Complex() - case floatKind: - truth = v1.Float() == v2.Float() - case intKind: - truth = v1.Int() == v2.Int() - case stringKind: - truth = v1.String() == v2.String() - case uintKind: - truth = v1.Uint() == v2.Uint() - default: - panic("invalid kind") - } - } - if truth { - return true, nil - } - } - return false, nil -} - -// ne evaluates the comparison a != b. -func ne(arg1, arg2 interface{}) (bool, error) { - // != is the inverse of ==. - equal, err := eq(arg1, arg2) - return !equal, err -} - -// lt evaluates the comparison a < b. -func lt(arg1, arg2 interface{}) (bool, error) { - v1 := reflect.ValueOf(arg1) - k1, err := basicKind(v1) - if err != nil { - return false, err - } - v2 := reflect.ValueOf(arg2) - k2, err := basicKind(v2) - if err != nil { - return false, err - } - truth := false - if k1 != k2 { - // Special case: Can compare integer values regardless of type's sign. - switch { - case k1 == intKind && k2 == uintKind: - truth = v1.Int() < 0 || uint64(v1.Int()) < v2.Uint() - case k1 == uintKind && k2 == intKind: - truth = v2.Int() >= 0 && v1.Uint() < uint64(v2.Int()) - default: - return false, errBadComparison - } - } else { - switch k1 { - case boolKind, complexKind: - return false, errBadComparisonType - case floatKind: - truth = v1.Float() < v2.Float() - case intKind: - truth = v1.Int() < v2.Int() - case stringKind: - truth = v1.String() < v2.String() - case uintKind: - truth = v1.Uint() < v2.Uint() - default: - panic("invalid kind") - } - } - return truth, nil -} - -// le evaluates the comparison <= b. -func le(arg1, arg2 interface{}) (bool, error) { - // <= is < or ==. - lessThan, err := lt(arg1, arg2) - if lessThan || err != nil { - return lessThan, err - } - return eq(arg1, arg2) -} - -// gt evaluates the comparison a > b. -func gt(arg1, arg2 interface{}) (bool, error) { - // > is the inverse of <=. - lessOrEqual, err := le(arg1, arg2) - if err != nil { - return false, err - } - return !lessOrEqual, nil -} - -// ge evaluates the comparison a >= b. -func ge(arg1, arg2 interface{}) (bool, error) { - // >= is the inverse of <. - lessThan, err := lt(arg1, arg2) - if err != nil { - return false, err - } - return !lessThan, nil -} - -// HTML escaping. - -var ( - htmlQuot = []byte(""") // shorter than """ - htmlApos = []byte("'") // shorter than "'" and apos was not in HTML until HTML5 - htmlAmp = []byte("&") - htmlLt = []byte("<") - htmlGt = []byte(">") -) - -// HTMLEscape writes to w the escaped HTML equivalent of the plain text data b. -func HTMLEscape(w io.Writer, b []byte) { - last := 0 - for i, c := range b { - var html []byte - switch c { - case '"': - html = htmlQuot - case '\'': - html = htmlApos - case '&': - html = htmlAmp - case '<': - html = htmlLt - case '>': - html = htmlGt - default: - continue - } - w.Write(b[last:i]) - w.Write(html) - last = i + 1 - } - w.Write(b[last:]) -} - -// HTMLEscapeString returns the escaped HTML equivalent of the plain text data s. -func HTMLEscapeString(s string) string { - // Avoid allocation if we can. - if strings.IndexAny(s, `'"&<>`) < 0 { - return s - } - var b bytes.Buffer - HTMLEscape(&b, []byte(s)) - return b.String() -} - -// HTMLEscaper returns the escaped HTML equivalent of the textual -// representation of its arguments. -func HTMLEscaper(args ...interface{}) string { - return HTMLEscapeString(evalArgs(args)) -} - -// JavaScript escaping. - -var ( - jsLowUni = []byte(`\u00`) - hex = []byte("0123456789ABCDEF") - - jsBackslash = []byte(`\\`) - jsApos = []byte(`\'`) - jsQuot = []byte(`\"`) - jsLt = []byte(`\x3C`) - jsGt = []byte(`\x3E`) -) - -// JSEscape writes to w the escaped JavaScript equivalent of the plain text data b. -func JSEscape(w io.Writer, b []byte) { - last := 0 - for i := 0; i < len(b); i++ { - c := b[i] - - if !jsIsSpecial(rune(c)) { - // fast path: nothing to do - continue - } - w.Write(b[last:i]) - - if c < utf8.RuneSelf { - // Quotes, slashes and angle brackets get quoted. - // Control characters get written as \u00XX. - switch c { - case '\\': - w.Write(jsBackslash) - case '\'': - w.Write(jsApos) - case '"': - w.Write(jsQuot) - case '<': - w.Write(jsLt) - case '>': - w.Write(jsGt) - default: - w.Write(jsLowUni) - t, b := c>>4, c&0x0f - w.Write(hex[t : t+1]) - w.Write(hex[b : b+1]) - } - } else { - // Unicode rune. - r, size := utf8.DecodeRune(b[i:]) - if unicode.IsPrint(r) { - w.Write(b[i : i+size]) - } else { - fmt.Fprintf(w, "\\u%04X", r) - } - i += size - 1 - } - last = i + 1 - } - w.Write(b[last:]) -} - -// JSEscapeString returns the escaped JavaScript equivalent of the plain text data s. -func JSEscapeString(s string) string { - // Avoid allocation if we can. - if strings.IndexFunc(s, jsIsSpecial) < 0 { - return s - } - var b bytes.Buffer - JSEscape(&b, []byte(s)) - return b.String() -} - -func jsIsSpecial(r rune) bool { - switch r { - case '\\', '\'', '"', '<', '>': - return true - } - return r < ' ' || utf8.RuneSelf <= r -} - -// JSEscaper returns the escaped JavaScript equivalent of the textual -// representation of its arguments. -func JSEscaper(args ...interface{}) string { - return JSEscapeString(evalArgs(args)) -} - -// URLQueryEscaper returns the escaped value of the textual representation of -// its arguments in a form suitable for embedding in a URL query. -func URLQueryEscaper(args ...interface{}) string { - return url.QueryEscape(evalArgs(args)) -} - -// evalArgs formats the list of arguments into a string. It is therefore equivalent to -// fmt.Sprint(args...) -// except that each argument is indirected (if a pointer), as required, -// using the same rules as the default string evaluation during template -// execution. -func evalArgs(args []interface{}) string { - ok := false - var s string - // Fast path for simple common case. - if len(args) == 1 { - s, ok = args[0].(string) - } - if !ok { - for i, arg := range args { - a, ok := printableValue(reflect.ValueOf(arg)) - if ok { - args[i] = a - } // else left fmt do its thing - } - s = fmt.Sprint(args...) - } - return s -} diff --git a/vendor/github.com/alecthomas/template/helper.go b/vendor/github.com/alecthomas/template/helper.go deleted file mode 100644 index 3636fb5..0000000 --- a/vendor/github.com/alecthomas/template/helper.go +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright 2011 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. - -// Helper functions to make constructing templates easier. - -package template - -import ( - "fmt" - "io/ioutil" - "path/filepath" -) - -// Functions and methods to parse templates. - -// Must is a helper that wraps a call to a function returning (*Template, error) -// and panics if the error is non-nil. It is intended for use in variable -// initializations such as -// var t = template.Must(template.New("name").Parse("text")) -func Must(t *Template, err error) *Template { - if err != nil { - panic(err) - } - return t -} - -// ParseFiles creates a new Template and parses the template definitions from -// the named files. The returned template's name will have the (base) name and -// (parsed) contents of the first file. There must be at least one file. -// If an error occurs, parsing stops and the returned *Template is nil. -func ParseFiles(filenames ...string) (*Template, error) { - return parseFiles(nil, filenames...) -} - -// ParseFiles parses the named files and associates the resulting templates with -// t. If an error occurs, parsing stops and the returned template is nil; -// otherwise it is t. There must be at least one file. -func (t *Template) ParseFiles(filenames ...string) (*Template, error) { - return parseFiles(t, filenames...) -} - -// parseFiles is the helper for the method and function. If the argument -// template is nil, it is created from the first file. -func parseFiles(t *Template, filenames ...string) (*Template, error) { - if len(filenames) == 0 { - // Not really a problem, but be consistent. - return nil, fmt.Errorf("template: no files named in call to ParseFiles") - } - for _, filename := range filenames { - b, err := ioutil.ReadFile(filename) - if err != nil { - return nil, err - } - s := string(b) - name := filepath.Base(filename) - // First template becomes return value if not already defined, - // and we use that one for subsequent New calls to associate - // all the templates together. Also, if this file has the same name - // as t, this file becomes the contents of t, so - // t, err := New(name).Funcs(xxx).ParseFiles(name) - // works. Otherwise we create a new template associated with t. - var tmpl *Template - if t == nil { - t = New(name) - } - if name == t.Name() { - tmpl = t - } else { - tmpl = t.New(name) - } - _, err = tmpl.Parse(s) - if err != nil { - return nil, err - } - } - return t, nil -} - -// ParseGlob creates a new Template and parses the template definitions from the -// files identified by the pattern, which must match at least one file. The -// returned template will have the (base) name and (parsed) contents of the -// first file matched by the pattern. ParseGlob is equivalent to calling -// ParseFiles with the list of files matched by the pattern. -func ParseGlob(pattern string) (*Template, error) { - return parseGlob(nil, pattern) -} - -// ParseGlob parses the template definitions in the files identified by the -// pattern and associates the resulting templates with t. The pattern is -// processed by filepath.Glob and must match at least one file. ParseGlob is -// equivalent to calling t.ParseFiles with the list of files matched by the -// pattern. -func (t *Template) ParseGlob(pattern string) (*Template, error) { - return parseGlob(t, pattern) -} - -// parseGlob is the implementation of the function and method ParseGlob. -func parseGlob(t *Template, pattern string) (*Template, error) { - filenames, err := filepath.Glob(pattern) - if err != nil { - return nil, err - } - if len(filenames) == 0 { - return nil, fmt.Errorf("template: pattern matches no files: %#q", pattern) - } - return parseFiles(t, filenames...) -} diff --git a/vendor/github.com/alecthomas/template/parse/lex.go b/vendor/github.com/alecthomas/template/parse/lex.go deleted file mode 100644 index 55f1c05..0000000 --- a/vendor/github.com/alecthomas/template/parse/lex.go +++ /dev/null @@ -1,556 +0,0 @@ -// Copyright 2011 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 parse - -import ( - "fmt" - "strings" - "unicode" - "unicode/utf8" -) - -// item represents a token or text string returned from the scanner. -type item struct { - typ itemType // The type of this item. - pos Pos // The starting position, in bytes, of this item in the input string. - val string // The value of this item. -} - -func (i item) String() string { - switch { - case i.typ == itemEOF: - return "EOF" - case i.typ == itemError: - return i.val - case i.typ > itemKeyword: - return fmt.Sprintf("<%s>", i.val) - case len(i.val) > 10: - return fmt.Sprintf("%.10q...", i.val) - } - return fmt.Sprintf("%q", i.val) -} - -// itemType identifies the type of lex items. -type itemType int - -const ( - itemError itemType = iota // error occurred; value is text of error - itemBool // boolean constant - itemChar // printable ASCII character; grab bag for comma etc. - itemCharConstant // character constant - itemComplex // complex constant (1+2i); imaginary is just a number - itemColonEquals // colon-equals (':=') introducing a declaration - itemEOF - itemField // alphanumeric identifier starting with '.' - itemIdentifier // alphanumeric identifier not starting with '.' - itemLeftDelim // left action delimiter - itemLeftParen // '(' inside action - itemNumber // simple number, including imaginary - itemPipe // pipe symbol - itemRawString // raw quoted string (includes quotes) - itemRightDelim // right action delimiter - itemElideNewline // elide newline after right delim - itemRightParen // ')' inside action - itemSpace // run of spaces separating arguments - itemString // quoted string (includes quotes) - itemText // plain text - itemVariable // variable starting with '$', such as '$' or '$1' or '$hello' - // Keywords appear after all the rest. - itemKeyword // used only to delimit the keywords - itemDot // the cursor, spelled '.' - itemDefine // define keyword - itemElse // else keyword - itemEnd // end keyword - itemIf // if keyword - itemNil // the untyped nil constant, easiest to treat as a keyword - itemRange // range keyword - itemTemplate // template keyword - itemWith // with keyword -) - -var key = map[string]itemType{ - ".": itemDot, - "define": itemDefine, - "else": itemElse, - "end": itemEnd, - "if": itemIf, - "range": itemRange, - "nil": itemNil, - "template": itemTemplate, - "with": itemWith, -} - -const eof = -1 - -// stateFn represents the state of the scanner as a function that returns the next state. -type stateFn func(*lexer) stateFn - -// lexer holds the state of the scanner. -type lexer struct { - name string // the name of the input; used only for error reports - input string // the string being scanned - leftDelim string // start of action - rightDelim string // end of action - state stateFn // the next lexing function to enter - pos Pos // current position in the input - start Pos // start position of this item - width Pos // width of last rune read from input - lastPos Pos // position of most recent item returned by nextItem - items chan item // channel of scanned items - parenDepth int // nesting depth of ( ) exprs -} - -// next returns the next rune in the input. -func (l *lexer) next() rune { - if int(l.pos) >= len(l.input) { - l.width = 0 - return eof - } - r, w := utf8.DecodeRuneInString(l.input[l.pos:]) - l.width = Pos(w) - l.pos += l.width - return r -} - -// peek returns but does not consume the next rune in the input. -func (l *lexer) peek() rune { - r := l.next() - l.backup() - return r -} - -// backup steps back one rune. Can only be called once per call of next. -func (l *lexer) backup() { - l.pos -= l.width -} - -// emit passes an item back to the client. -func (l *lexer) emit(t itemType) { - l.items <- item{t, l.start, l.input[l.start:l.pos]} - l.start = l.pos -} - -// ignore skips over the pending input before this point. -func (l *lexer) ignore() { - l.start = l.pos -} - -// accept consumes the next rune if it's from the valid set. -func (l *lexer) accept(valid string) bool { - if strings.IndexRune(valid, l.next()) >= 0 { - return true - } - l.backup() - return false -} - -// acceptRun consumes a run of runes from the valid set. -func (l *lexer) acceptRun(valid string) { - for strings.IndexRune(valid, l.next()) >= 0 { - } - l.backup() -} - -// lineNumber reports which line we're on, based on the position of -// the previous item returned by nextItem. Doing it this way -// means we don't have to worry about peek double counting. -func (l *lexer) lineNumber() int { - return 1 + strings.Count(l.input[:l.lastPos], "\n") -} - -// errorf returns an error token and terminates the scan by passing -// back a nil pointer that will be the next state, terminating l.nextItem. -func (l *lexer) errorf(format string, args ...interface{}) stateFn { - l.items <- item{itemError, l.start, fmt.Sprintf(format, args...)} - return nil -} - -// nextItem returns the next item from the input. -func (l *lexer) nextItem() item { - item := <-l.items - l.lastPos = item.pos - return item -} - -// lex creates a new scanner for the input string. -func lex(name, input, left, right string) *lexer { - if left == "" { - left = leftDelim - } - if right == "" { - right = rightDelim - } - l := &lexer{ - name: name, - input: input, - leftDelim: left, - rightDelim: right, - items: make(chan item), - } - go l.run() - return l -} - -// run runs the state machine for the lexer. -func (l *lexer) run() { - for l.state = lexText; l.state != nil; { - l.state = l.state(l) - } -} - -// state functions - -const ( - leftDelim = "{{" - rightDelim = "}}" - leftComment = "/*" - rightComment = "*/" -) - -// lexText scans until an opening action delimiter, "{{". -func lexText(l *lexer) stateFn { - for { - if strings.HasPrefix(l.input[l.pos:], l.leftDelim) { - if l.pos > l.start { - l.emit(itemText) - } - return lexLeftDelim - } - if l.next() == eof { - break - } - } - // Correctly reached EOF. - if l.pos > l.start { - l.emit(itemText) - } - l.emit(itemEOF) - return nil -} - -// lexLeftDelim scans the left delimiter, which is known to be present. -func lexLeftDelim(l *lexer) stateFn { - l.pos += Pos(len(l.leftDelim)) - if strings.HasPrefix(l.input[l.pos:], leftComment) { - return lexComment - } - l.emit(itemLeftDelim) - l.parenDepth = 0 - return lexInsideAction -} - -// lexComment scans a comment. The left comment marker is known to be present. -func lexComment(l *lexer) stateFn { - l.pos += Pos(len(leftComment)) - i := strings.Index(l.input[l.pos:], rightComment) - if i < 0 { - return l.errorf("unclosed comment") - } - l.pos += Pos(i + len(rightComment)) - if !strings.HasPrefix(l.input[l.pos:], l.rightDelim) { - return l.errorf("comment ends before closing delimiter") - - } - l.pos += Pos(len(l.rightDelim)) - l.ignore() - return lexText -} - -// lexRightDelim scans the right delimiter, which is known to be present. -func lexRightDelim(l *lexer) stateFn { - l.pos += Pos(len(l.rightDelim)) - l.emit(itemRightDelim) - if l.peek() == '\\' { - l.pos++ - l.emit(itemElideNewline) - } - return lexText -} - -// lexInsideAction scans the elements inside action delimiters. -func lexInsideAction(l *lexer) stateFn { - // Either number, quoted string, or identifier. - // Spaces separate arguments; runs of spaces turn into itemSpace. - // Pipe symbols separate and are emitted. - if strings.HasPrefix(l.input[l.pos:], l.rightDelim+"\\") || strings.HasPrefix(l.input[l.pos:], l.rightDelim) { - if l.parenDepth == 0 { - return lexRightDelim - } - return l.errorf("unclosed left paren") - } - switch r := l.next(); { - case r == eof || isEndOfLine(r): - return l.errorf("unclosed action") - case isSpace(r): - return lexSpace - case r == ':': - if l.next() != '=' { - return l.errorf("expected :=") - } - l.emit(itemColonEquals) - case r == '|': - l.emit(itemPipe) - case r == '"': - return lexQuote - case r == '`': - return lexRawQuote - case r == '$': - return lexVariable - case r == '\'': - return lexChar - case r == '.': - // special look-ahead for ".field" so we don't break l.backup(). - if l.pos < Pos(len(l.input)) { - r := l.input[l.pos] - if r < '0' || '9' < r { - return lexField - } - } - fallthrough // '.' can start a number. - case r == '+' || r == '-' || ('0' <= r && r <= '9'): - l.backup() - return lexNumber - case isAlphaNumeric(r): - l.backup() - return lexIdentifier - case r == '(': - l.emit(itemLeftParen) - l.parenDepth++ - return lexInsideAction - case r == ')': - l.emit(itemRightParen) - l.parenDepth-- - if l.parenDepth < 0 { - return l.errorf("unexpected right paren %#U", r) - } - return lexInsideAction - case r <= unicode.MaxASCII && unicode.IsPrint(r): - l.emit(itemChar) - return lexInsideAction - default: - return l.errorf("unrecognized character in action: %#U", r) - } - return lexInsideAction -} - -// lexSpace scans a run of space characters. -// One space has already been seen. -func lexSpace(l *lexer) stateFn { - for isSpace(l.peek()) { - l.next() - } - l.emit(itemSpace) - return lexInsideAction -} - -// lexIdentifier scans an alphanumeric. -func lexIdentifier(l *lexer) stateFn { -Loop: - for { - switch r := l.next(); { - case isAlphaNumeric(r): - // absorb. - default: - l.backup() - word := l.input[l.start:l.pos] - if !l.atTerminator() { - return l.errorf("bad character %#U", r) - } - switch { - case key[word] > itemKeyword: - l.emit(key[word]) - case word[0] == '.': - l.emit(itemField) - case word == "true", word == "false": - l.emit(itemBool) - default: - l.emit(itemIdentifier) - } - break Loop - } - } - return lexInsideAction -} - -// lexField scans a field: .Alphanumeric. -// The . has been scanned. -func lexField(l *lexer) stateFn { - return lexFieldOrVariable(l, itemField) -} - -// lexVariable scans a Variable: $Alphanumeric. -// The $ has been scanned. -func lexVariable(l *lexer) stateFn { - if l.atTerminator() { // Nothing interesting follows -> "$". - l.emit(itemVariable) - return lexInsideAction - } - return lexFieldOrVariable(l, itemVariable) -} - -// lexVariable scans a field or variable: [.$]Alphanumeric. -// The . or $ has been scanned. -func lexFieldOrVariable(l *lexer, typ itemType) stateFn { - if l.atTerminator() { // Nothing interesting follows -> "." or "$". - if typ == itemVariable { - l.emit(itemVariable) - } else { - l.emit(itemDot) - } - return lexInsideAction - } - var r rune - for { - r = l.next() - if !isAlphaNumeric(r) { - l.backup() - break - } - } - if !l.atTerminator() { - return l.errorf("bad character %#U", r) - } - l.emit(typ) - return lexInsideAction -} - -// atTerminator reports whether the input is at valid termination character to -// appear after an identifier. Breaks .X.Y into two pieces. Also catches cases -// like "$x+2" not being acceptable without a space, in case we decide one -// day to implement arithmetic. -func (l *lexer) atTerminator() bool { - r := l.peek() - if isSpace(r) || isEndOfLine(r) { - return true - } - switch r { - case eof, '.', ',', '|', ':', ')', '(': - return true - } - // Does r start the delimiter? This can be ambiguous (with delim=="//", $x/2 will - // succeed but should fail) but only in extremely rare cases caused by willfully - // bad choice of delimiter. - if rd, _ := utf8.DecodeRuneInString(l.rightDelim); rd == r { - return true - } - return false -} - -// lexChar scans a character constant. The initial quote is already -// scanned. Syntax checking is done by the parser. -func lexChar(l *lexer) stateFn { -Loop: - for { - switch l.next() { - case '\\': - if r := l.next(); r != eof && r != '\n' { - break - } - fallthrough - case eof, '\n': - return l.errorf("unterminated character constant") - case '\'': - break Loop - } - } - l.emit(itemCharConstant) - return lexInsideAction -} - -// lexNumber scans a number: decimal, octal, hex, float, or imaginary. This -// isn't a perfect number scanner - for instance it accepts "." and "0x0.2" -// and "089" - but when it's wrong the input is invalid and the parser (via -// strconv) will notice. -func lexNumber(l *lexer) stateFn { - if !l.scanNumber() { - return l.errorf("bad number syntax: %q", l.input[l.start:l.pos]) - } - if sign := l.peek(); sign == '+' || sign == '-' { - // Complex: 1+2i. No spaces, must end in 'i'. - if !l.scanNumber() || l.input[l.pos-1] != 'i' { - return l.errorf("bad number syntax: %q", l.input[l.start:l.pos]) - } - l.emit(itemComplex) - } else { - l.emit(itemNumber) - } - return lexInsideAction -} - -func (l *lexer) scanNumber() bool { - // Optional leading sign. - l.accept("+-") - // Is it hex? - digits := "0123456789" - if l.accept("0") && l.accept("xX") { - digits = "0123456789abcdefABCDEF" - } - l.acceptRun(digits) - if l.accept(".") { - l.acceptRun(digits) - } - if l.accept("eE") { - l.accept("+-") - l.acceptRun("0123456789") - } - // Is it imaginary? - l.accept("i") - // Next thing mustn't be alphanumeric. - if isAlphaNumeric(l.peek()) { - l.next() - return false - } - return true -} - -// lexQuote scans a quoted string. -func lexQuote(l *lexer) stateFn { -Loop: - for { - switch l.next() { - case '\\': - if r := l.next(); r != eof && r != '\n' { - break - } - fallthrough - case eof, '\n': - return l.errorf("unterminated quoted string") - case '"': - break Loop - } - } - l.emit(itemString) - return lexInsideAction -} - -// lexRawQuote scans a raw quoted string. -func lexRawQuote(l *lexer) stateFn { -Loop: - for { - switch l.next() { - case eof, '\n': - return l.errorf("unterminated raw quoted string") - case '`': - break Loop - } - } - l.emit(itemRawString) - return lexInsideAction -} - -// isSpace reports whether r is a space character. -func isSpace(r rune) bool { - return r == ' ' || r == '\t' -} - -// isEndOfLine reports whether r is an end-of-line character. -func isEndOfLine(r rune) bool { - return r == '\r' || r == '\n' -} - -// isAlphaNumeric reports whether r is an alphabetic, digit, or underscore. -func isAlphaNumeric(r rune) bool { - return r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r) -} diff --git a/vendor/github.com/alecthomas/template/parse/node.go b/vendor/github.com/alecthomas/template/parse/node.go deleted file mode 100644 index 55c37f6..0000000 --- a/vendor/github.com/alecthomas/template/parse/node.go +++ /dev/null @@ -1,834 +0,0 @@ -// Copyright 2011 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. - -// Parse nodes. - -package parse - -import ( - "bytes" - "fmt" - "strconv" - "strings" -) - -var textFormat = "%s" // Changed to "%q" in tests for better error messages. - -// A Node is an element in the parse tree. The interface is trivial. -// The interface contains an unexported method so that only -// types local to this package can satisfy it. -type Node interface { - Type() NodeType - String() string - // Copy does a deep copy of the Node and all its components. - // To avoid type assertions, some XxxNodes also have specialized - // CopyXxx methods that return *XxxNode. - Copy() Node - Position() Pos // byte position of start of node in full original input string - // tree returns the containing *Tree. - // It is unexported so all implementations of Node are in this package. - tree() *Tree -} - -// NodeType identifies the type of a parse tree node. -type NodeType int - -// Pos represents a byte position in the original input text from which -// this template was parsed. -type Pos int - -func (p Pos) Position() Pos { - return p -} - -// Type returns itself and provides an easy default implementation -// for embedding in a Node. Embedded in all non-trivial Nodes. -func (t NodeType) Type() NodeType { - return t -} - -const ( - NodeText NodeType = iota // Plain text. - NodeAction // A non-control action such as a field evaluation. - NodeBool // A boolean constant. - NodeChain // A sequence of field accesses. - NodeCommand // An element of a pipeline. - NodeDot // The cursor, dot. - nodeElse // An else action. Not added to tree. - nodeEnd // An end action. Not added to tree. - NodeField // A field or method name. - NodeIdentifier // An identifier; always a function name. - NodeIf // An if action. - NodeList // A list of Nodes. - NodeNil // An untyped nil constant. - NodeNumber // A numerical constant. - NodePipe // A pipeline of commands. - NodeRange // A range action. - NodeString // A string constant. - NodeTemplate // A template invocation action. - NodeVariable // A $ variable. - NodeWith // A with action. -) - -// Nodes. - -// ListNode holds a sequence of nodes. -type ListNode struct { - NodeType - Pos - tr *Tree - Nodes []Node // The element nodes in lexical order. -} - -func (t *Tree) newList(pos Pos) *ListNode { - return &ListNode{tr: t, NodeType: NodeList, Pos: pos} -} - -func (l *ListNode) append(n Node) { - l.Nodes = append(l.Nodes, n) -} - -func (l *ListNode) tree() *Tree { - return l.tr -} - -func (l *ListNode) String() string { - b := new(bytes.Buffer) - for _, n := range l.Nodes { - fmt.Fprint(b, n) - } - return b.String() -} - -func (l *ListNode) CopyList() *ListNode { - if l == nil { - return l - } - n := l.tr.newList(l.Pos) - for _, elem := range l.Nodes { - n.append(elem.Copy()) - } - return n -} - -func (l *ListNode) Copy() Node { - return l.CopyList() -} - -// TextNode holds plain text. -type TextNode struct { - NodeType - Pos - tr *Tree - Text []byte // The text; may span newlines. -} - -func (t *Tree) newText(pos Pos, text string) *TextNode { - return &TextNode{tr: t, NodeType: NodeText, Pos: pos, Text: []byte(text)} -} - -func (t *TextNode) String() string { - return fmt.Sprintf(textFormat, t.Text) -} - -func (t *TextNode) tree() *Tree { - return t.tr -} - -func (t *TextNode) Copy() Node { - return &TextNode{tr: t.tr, NodeType: NodeText, Pos: t.Pos, Text: append([]byte{}, t.Text...)} -} - -// PipeNode holds a pipeline with optional declaration -type PipeNode struct { - NodeType - Pos - tr *Tree - Line int // The line number in the input (deprecated; kept for compatibility) - Decl []*VariableNode // Variable declarations in lexical order. - Cmds []*CommandNode // The commands in lexical order. -} - -func (t *Tree) newPipeline(pos Pos, line int, decl []*VariableNode) *PipeNode { - return &PipeNode{tr: t, NodeType: NodePipe, Pos: pos, Line: line, Decl: decl} -} - -func (p *PipeNode) append(command *CommandNode) { - p.Cmds = append(p.Cmds, command) -} - -func (p *PipeNode) String() string { - s := "" - if len(p.Decl) > 0 { - for i, v := range p.Decl { - if i > 0 { - s += ", " - } - s += v.String() - } - s += " := " - } - for i, c := range p.Cmds { - if i > 0 { - s += " | " - } - s += c.String() - } - return s -} - -func (p *PipeNode) tree() *Tree { - return p.tr -} - -func (p *PipeNode) CopyPipe() *PipeNode { - if p == nil { - return p - } - var decl []*VariableNode - for _, d := range p.Decl { - decl = append(decl, d.Copy().(*VariableNode)) - } - n := p.tr.newPipeline(p.Pos, p.Line, decl) - for _, c := range p.Cmds { - n.append(c.Copy().(*CommandNode)) - } - return n -} - -func (p *PipeNode) Copy() Node { - return p.CopyPipe() -} - -// ActionNode holds an action (something bounded by delimiters). -// Control actions have their own nodes; ActionNode represents simple -// ones such as field evaluations and parenthesized pipelines. -type ActionNode struct { - NodeType - Pos - tr *Tree - Line int // The line number in the input (deprecated; kept for compatibility) - Pipe *PipeNode // The pipeline in the action. -} - -func (t *Tree) newAction(pos Pos, line int, pipe *PipeNode) *ActionNode { - return &ActionNode{tr: t, NodeType: NodeAction, Pos: pos, Line: line, Pipe: pipe} -} - -func (a *ActionNode) String() string { - return fmt.Sprintf("{{%s}}", a.Pipe) - -} - -func (a *ActionNode) tree() *Tree { - return a.tr -} - -func (a *ActionNode) Copy() Node { - return a.tr.newAction(a.Pos, a.Line, a.Pipe.CopyPipe()) - -} - -// CommandNode holds a command (a pipeline inside an evaluating action). -type CommandNode struct { - NodeType - Pos - tr *Tree - Args []Node // Arguments in lexical order: Identifier, field, or constant. -} - -func (t *Tree) newCommand(pos Pos) *CommandNode { - return &CommandNode{tr: t, NodeType: NodeCommand, Pos: pos} -} - -func (c *CommandNode) append(arg Node) { - c.Args = append(c.Args, arg) -} - -func (c *CommandNode) String() string { - s := "" - for i, arg := range c.Args { - if i > 0 { - s += " " - } - if arg, ok := arg.(*PipeNode); ok { - s += "(" + arg.String() + ")" - continue - } - s += arg.String() - } - return s -} - -func (c *CommandNode) tree() *Tree { - return c.tr -} - -func (c *CommandNode) Copy() Node { - if c == nil { - return c - } - n := c.tr.newCommand(c.Pos) - for _, c := range c.Args { - n.append(c.Copy()) - } - return n -} - -// IdentifierNode holds an identifier. -type IdentifierNode struct { - NodeType - Pos - tr *Tree - Ident string // The identifier's name. -} - -// NewIdentifier returns a new IdentifierNode with the given identifier name. -func NewIdentifier(ident string) *IdentifierNode { - return &IdentifierNode{NodeType: NodeIdentifier, Ident: ident} -} - -// SetPos sets the position. NewIdentifier is a public method so we can't modify its signature. -// Chained for convenience. -// TODO: fix one day? -func (i *IdentifierNode) SetPos(pos Pos) *IdentifierNode { - i.Pos = pos - return i -} - -// SetTree sets the parent tree for the node. NewIdentifier is a public method so we can't modify its signature. -// Chained for convenience. -// TODO: fix one day? -func (i *IdentifierNode) SetTree(t *Tree) *IdentifierNode { - i.tr = t - return i -} - -func (i *IdentifierNode) String() string { - return i.Ident -} - -func (i *IdentifierNode) tree() *Tree { - return i.tr -} - -func (i *IdentifierNode) Copy() Node { - return NewIdentifier(i.Ident).SetTree(i.tr).SetPos(i.Pos) -} - -// VariableNode holds a list of variable names, possibly with chained field -// accesses. The dollar sign is part of the (first) name. -type VariableNode struct { - NodeType - Pos - tr *Tree - Ident []string // Variable name and fields in lexical order. -} - -func (t *Tree) newVariable(pos Pos, ident string) *VariableNode { - return &VariableNode{tr: t, NodeType: NodeVariable, Pos: pos, Ident: strings.Split(ident, ".")} -} - -func (v *VariableNode) String() string { - s := "" - for i, id := range v.Ident { - if i > 0 { - s += "." - } - s += id - } - return s -} - -func (v *VariableNode) tree() *Tree { - return v.tr -} - -func (v *VariableNode) Copy() Node { - return &VariableNode{tr: v.tr, NodeType: NodeVariable, Pos: v.Pos, Ident: append([]string{}, v.Ident...)} -} - -// DotNode holds the special identifier '.'. -type DotNode struct { - NodeType - Pos - tr *Tree -} - -func (t *Tree) newDot(pos Pos) *DotNode { - return &DotNode{tr: t, NodeType: NodeDot, Pos: pos} -} - -func (d *DotNode) Type() NodeType { - // Override method on embedded NodeType for API compatibility. - // TODO: Not really a problem; could change API without effect but - // api tool complains. - return NodeDot -} - -func (d *DotNode) String() string { - return "." -} - -func (d *DotNode) tree() *Tree { - return d.tr -} - -func (d *DotNode) Copy() Node { - return d.tr.newDot(d.Pos) -} - -// NilNode holds the special identifier 'nil' representing an untyped nil constant. -type NilNode struct { - NodeType - Pos - tr *Tree -} - -func (t *Tree) newNil(pos Pos) *NilNode { - return &NilNode{tr: t, NodeType: NodeNil, Pos: pos} -} - -func (n *NilNode) Type() NodeType { - // Override method on embedded NodeType for API compatibility. - // TODO: Not really a problem; could change API without effect but - // api tool complains. - return NodeNil -} - -func (n *NilNode) String() string { - return "nil" -} - -func (n *NilNode) tree() *Tree { - return n.tr -} - -func (n *NilNode) Copy() Node { - return n.tr.newNil(n.Pos) -} - -// FieldNode holds a field (identifier starting with '.'). -// The names may be chained ('.x.y'). -// The period is dropped from each ident. -type FieldNode struct { - NodeType - Pos - tr *Tree - Ident []string // The identifiers in lexical order. -} - -func (t *Tree) newField(pos Pos, ident string) *FieldNode { - return &FieldNode{tr: t, NodeType: NodeField, Pos: pos, Ident: strings.Split(ident[1:], ".")} // [1:] to drop leading period -} - -func (f *FieldNode) String() string { - s := "" - for _, id := range f.Ident { - s += "." + id - } - return s -} - -func (f *FieldNode) tree() *Tree { - return f.tr -} - -func (f *FieldNode) Copy() Node { - return &FieldNode{tr: f.tr, NodeType: NodeField, Pos: f.Pos, Ident: append([]string{}, f.Ident...)} -} - -// ChainNode holds a term followed by a chain of field accesses (identifier starting with '.'). -// The names may be chained ('.x.y'). -// The periods are dropped from each ident. -type ChainNode struct { - NodeType - Pos - tr *Tree - Node Node - Field []string // The identifiers in lexical order. -} - -func (t *Tree) newChain(pos Pos, node Node) *ChainNode { - return &ChainNode{tr: t, NodeType: NodeChain, Pos: pos, Node: node} -} - -// Add adds the named field (which should start with a period) to the end of the chain. -func (c *ChainNode) Add(field string) { - if len(field) == 0 || field[0] != '.' { - panic("no dot in field") - } - field = field[1:] // Remove leading dot. - if field == "" { - panic("empty field") - } - c.Field = append(c.Field, field) -} - -func (c *ChainNode) String() string { - s := c.Node.String() - if _, ok := c.Node.(*PipeNode); ok { - s = "(" + s + ")" - } - for _, field := range c.Field { - s += "." + field - } - return s -} - -func (c *ChainNode) tree() *Tree { - return c.tr -} - -func (c *ChainNode) Copy() Node { - return &ChainNode{tr: c.tr, NodeType: NodeChain, Pos: c.Pos, Node: c.Node, Field: append([]string{}, c.Field...)} -} - -// BoolNode holds a boolean constant. -type BoolNode struct { - NodeType - Pos - tr *Tree - True bool // The value of the boolean constant. -} - -func (t *Tree) newBool(pos Pos, true bool) *BoolNode { - return &BoolNode{tr: t, NodeType: NodeBool, Pos: pos, True: true} -} - -func (b *BoolNode) String() string { - if b.True { - return "true" - } - return "false" -} - -func (b *BoolNode) tree() *Tree { - return b.tr -} - -func (b *BoolNode) Copy() Node { - return b.tr.newBool(b.Pos, b.True) -} - -// NumberNode holds a number: signed or unsigned integer, float, or complex. -// The value is parsed and stored under all the types that can represent the value. -// This simulates in a small amount of code the behavior of Go's ideal constants. -type NumberNode struct { - NodeType - Pos - tr *Tree - IsInt bool // Number has an integral value. - IsUint bool // Number has an unsigned integral value. - IsFloat bool // Number has a floating-point value. - IsComplex bool // Number is complex. - Int64 int64 // The signed integer value. - Uint64 uint64 // The unsigned integer value. - Float64 float64 // The floating-point value. - Complex128 complex128 // The complex value. - Text string // The original textual representation from the input. -} - -func (t *Tree) newNumber(pos Pos, text string, typ itemType) (*NumberNode, error) { - n := &NumberNode{tr: t, NodeType: NodeNumber, Pos: pos, Text: text} - switch typ { - case itemCharConstant: - rune, _, tail, err := strconv.UnquoteChar(text[1:], text[0]) - if err != nil { - return nil, err - } - if tail != "'" { - return nil, fmt.Errorf("malformed character constant: %s", text) - } - n.Int64 = int64(rune) - n.IsInt = true - n.Uint64 = uint64(rune) - n.IsUint = true - n.Float64 = float64(rune) // odd but those are the rules. - n.IsFloat = true - return n, nil - case itemComplex: - // fmt.Sscan can parse the pair, so let it do the work. - if _, err := fmt.Sscan(text, &n.Complex128); err != nil { - return nil, err - } - n.IsComplex = true - n.simplifyComplex() - return n, nil - } - // Imaginary constants can only be complex unless they are zero. - if len(text) > 0 && text[len(text)-1] == 'i' { - f, err := strconv.ParseFloat(text[:len(text)-1], 64) - if err == nil { - n.IsComplex = true - n.Complex128 = complex(0, f) - n.simplifyComplex() - return n, nil - } - } - // Do integer test first so we get 0x123 etc. - u, err := strconv.ParseUint(text, 0, 64) // will fail for -0; fixed below. - if err == nil { - n.IsUint = true - n.Uint64 = u - } - i, err := strconv.ParseInt(text, 0, 64) - if err == nil { - n.IsInt = true - n.Int64 = i - if i == 0 { - n.IsUint = true // in case of -0. - n.Uint64 = u - } - } - // If an integer extraction succeeded, promote the float. - if n.IsInt { - n.IsFloat = true - n.Float64 = float64(n.Int64) - } else if n.IsUint { - n.IsFloat = true - n.Float64 = float64(n.Uint64) - } else { - f, err := strconv.ParseFloat(text, 64) - if err == nil { - n.IsFloat = true - n.Float64 = f - // If a floating-point extraction succeeded, extract the int if needed. - if !n.IsInt && float64(int64(f)) == f { - n.IsInt = true - n.Int64 = int64(f) - } - if !n.IsUint && float64(uint64(f)) == f { - n.IsUint = true - n.Uint64 = uint64(f) - } - } - } - if !n.IsInt && !n.IsUint && !n.IsFloat { - return nil, fmt.Errorf("illegal number syntax: %q", text) - } - return n, nil -} - -// simplifyComplex pulls out any other types that are represented by the complex number. -// These all require that the imaginary part be zero. -func (n *NumberNode) simplifyComplex() { - n.IsFloat = imag(n.Complex128) == 0 - if n.IsFloat { - n.Float64 = real(n.Complex128) - n.IsInt = float64(int64(n.Float64)) == n.Float64 - if n.IsInt { - n.Int64 = int64(n.Float64) - } - n.IsUint = float64(uint64(n.Float64)) == n.Float64 - if n.IsUint { - n.Uint64 = uint64(n.Float64) - } - } -} - -func (n *NumberNode) String() string { - return n.Text -} - -func (n *NumberNode) tree() *Tree { - return n.tr -} - -func (n *NumberNode) Copy() Node { - nn := new(NumberNode) - *nn = *n // Easy, fast, correct. - return nn -} - -// StringNode holds a string constant. The value has been "unquoted". -type StringNode struct { - NodeType - Pos - tr *Tree - Quoted string // The original text of the string, with quotes. - Text string // The string, after quote processing. -} - -func (t *Tree) newString(pos Pos, orig, text string) *StringNode { - return &StringNode{tr: t, NodeType: NodeString, Pos: pos, Quoted: orig, Text: text} -} - -func (s *StringNode) String() string { - return s.Quoted -} - -func (s *StringNode) tree() *Tree { - return s.tr -} - -func (s *StringNode) Copy() Node { - return s.tr.newString(s.Pos, s.Quoted, s.Text) -} - -// endNode represents an {{end}} action. -// It does not appear in the final parse tree. -type endNode struct { - NodeType - Pos - tr *Tree -} - -func (t *Tree) newEnd(pos Pos) *endNode { - return &endNode{tr: t, NodeType: nodeEnd, Pos: pos} -} - -func (e *endNode) String() string { - return "{{end}}" -} - -func (e *endNode) tree() *Tree { - return e.tr -} - -func (e *endNode) Copy() Node { - return e.tr.newEnd(e.Pos) -} - -// elseNode represents an {{else}} action. Does not appear in the final tree. -type elseNode struct { - NodeType - Pos - tr *Tree - Line int // The line number in the input (deprecated; kept for compatibility) -} - -func (t *Tree) newElse(pos Pos, line int) *elseNode { - return &elseNode{tr: t, NodeType: nodeElse, Pos: pos, Line: line} -} - -func (e *elseNode) Type() NodeType { - return nodeElse -} - -func (e *elseNode) String() string { - return "{{else}}" -} - -func (e *elseNode) tree() *Tree { - return e.tr -} - -func (e *elseNode) Copy() Node { - return e.tr.newElse(e.Pos, e.Line) -} - -// BranchNode is the common representation of if, range, and with. -type BranchNode struct { - NodeType - Pos - tr *Tree - Line int // The line number in the input (deprecated; kept for compatibility) - Pipe *PipeNode // The pipeline to be evaluated. - List *ListNode // What to execute if the value is non-empty. - ElseList *ListNode // What to execute if the value is empty (nil if absent). -} - -func (b *BranchNode) String() string { - name := "" - switch b.NodeType { - case NodeIf: - name = "if" - case NodeRange: - name = "range" - case NodeWith: - name = "with" - default: - panic("unknown branch type") - } - if b.ElseList != nil { - return fmt.Sprintf("{{%s %s}}%s{{else}}%s{{end}}", name, b.Pipe, b.List, b.ElseList) - } - return fmt.Sprintf("{{%s %s}}%s{{end}}", name, b.Pipe, b.List) -} - -func (b *BranchNode) tree() *Tree { - return b.tr -} - -func (b *BranchNode) Copy() Node { - switch b.NodeType { - case NodeIf: - return b.tr.newIf(b.Pos, b.Line, b.Pipe, b.List, b.ElseList) - case NodeRange: - return b.tr.newRange(b.Pos, b.Line, b.Pipe, b.List, b.ElseList) - case NodeWith: - return b.tr.newWith(b.Pos, b.Line, b.Pipe, b.List, b.ElseList) - default: - panic("unknown branch type") - } -} - -// IfNode represents an {{if}} action and its commands. -type IfNode struct { - BranchNode -} - -func (t *Tree) newIf(pos Pos, line int, pipe *PipeNode, list, elseList *ListNode) *IfNode { - return &IfNode{BranchNode{tr: t, NodeType: NodeIf, Pos: pos, Line: line, Pipe: pipe, List: list, ElseList: elseList}} -} - -func (i *IfNode) Copy() Node { - return i.tr.newIf(i.Pos, i.Line, i.Pipe.CopyPipe(), i.List.CopyList(), i.ElseList.CopyList()) -} - -// RangeNode represents a {{range}} action and its commands. -type RangeNode struct { - BranchNode -} - -func (t *Tree) newRange(pos Pos, line int, pipe *PipeNode, list, elseList *ListNode) *RangeNode { - return &RangeNode{BranchNode{tr: t, NodeType: NodeRange, Pos: pos, Line: line, Pipe: pipe, List: list, ElseList: elseList}} -} - -func (r *RangeNode) Copy() Node { - return r.tr.newRange(r.Pos, r.Line, r.Pipe.CopyPipe(), r.List.CopyList(), r.ElseList.CopyList()) -} - -// WithNode represents a {{with}} action and its commands. -type WithNode struct { - BranchNode -} - -func (t *Tree) newWith(pos Pos, line int, pipe *PipeNode, list, elseList *ListNode) *WithNode { - return &WithNode{BranchNode{tr: t, NodeType: NodeWith, Pos: pos, Line: line, Pipe: pipe, List: list, ElseList: elseList}} -} - -func (w *WithNode) Copy() Node { - return w.tr.newWith(w.Pos, w.Line, w.Pipe.CopyPipe(), w.List.CopyList(), w.ElseList.CopyList()) -} - -// TemplateNode represents a {{template}} action. -type TemplateNode struct { - NodeType - Pos - tr *Tree - Line int // The line number in the input (deprecated; kept for compatibility) - Name string // The name of the template (unquoted). - Pipe *PipeNode // The command to evaluate as dot for the template. -} - -func (t *Tree) newTemplate(pos Pos, line int, name string, pipe *PipeNode) *TemplateNode { - return &TemplateNode{tr: t, NodeType: NodeTemplate, Pos: pos, Line: line, Name: name, Pipe: pipe} -} - -func (t *TemplateNode) String() string { - if t.Pipe == nil { - return fmt.Sprintf("{{template %q}}", t.Name) - } - return fmt.Sprintf("{{template %q %s}}", t.Name, t.Pipe) -} - -func (t *TemplateNode) tree() *Tree { - return t.tr -} - -func (t *TemplateNode) Copy() Node { - return t.tr.newTemplate(t.Pos, t.Line, t.Name, t.Pipe.CopyPipe()) -} diff --git a/vendor/github.com/alecthomas/template/parse/parse.go b/vendor/github.com/alecthomas/template/parse/parse.go deleted file mode 100644 index 0d77ade..0000000 --- a/vendor/github.com/alecthomas/template/parse/parse.go +++ /dev/null @@ -1,700 +0,0 @@ -// Copyright 2011 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 parse builds parse trees for templates as defined by text/template -// and html/template. Clients should use those packages to construct templates -// rather than this one, which provides shared internal data structures not -// intended for general use. -package parse - -import ( - "bytes" - "fmt" - "runtime" - "strconv" - "strings" -) - -// Tree is the representation of a single parsed template. -type Tree struct { - Name string // name of the template represented by the tree. - ParseName string // name of the top-level template during parsing, for error messages. - Root *ListNode // top-level root of the tree. - text string // text parsed to create the template (or its parent) - // Parsing only; cleared after parse. - funcs []map[string]interface{} - lex *lexer - token [3]item // three-token lookahead for parser. - peekCount int - vars []string // variables defined at the moment. -} - -// Copy returns a copy of the Tree. Any parsing state is discarded. -func (t *Tree) Copy() *Tree { - if t == nil { - return nil - } - return &Tree{ - Name: t.Name, - ParseName: t.ParseName, - Root: t.Root.CopyList(), - text: t.text, - } -} - -// Parse returns a map from template name to parse.Tree, created by parsing the -// templates described in the argument string. The top-level template will be -// given the specified name. If an error is encountered, parsing stops and an -// empty map is returned with the error. -func Parse(name, text, leftDelim, rightDelim string, funcs ...map[string]interface{}) (treeSet map[string]*Tree, err error) { - treeSet = make(map[string]*Tree) - t := New(name) - t.text = text - _, err = t.Parse(text, leftDelim, rightDelim, treeSet, funcs...) - return -} - -// next returns the next token. -func (t *Tree) next() item { - if t.peekCount > 0 { - t.peekCount-- - } else { - t.token[0] = t.lex.nextItem() - } - return t.token[t.peekCount] -} - -// backup backs the input stream up one token. -func (t *Tree) backup() { - t.peekCount++ -} - -// backup2 backs the input stream up two tokens. -// The zeroth token is already there. -func (t *Tree) backup2(t1 item) { - t.token[1] = t1 - t.peekCount = 2 -} - -// backup3 backs the input stream up three tokens -// The zeroth token is already there. -func (t *Tree) backup3(t2, t1 item) { // Reverse order: we're pushing back. - t.token[1] = t1 - t.token[2] = t2 - t.peekCount = 3 -} - -// peek returns but does not consume the next token. -func (t *Tree) peek() item { - if t.peekCount > 0 { - return t.token[t.peekCount-1] - } - t.peekCount = 1 - t.token[0] = t.lex.nextItem() - return t.token[0] -} - -// nextNonSpace returns the next non-space token. -func (t *Tree) nextNonSpace() (token item) { - for { - token = t.next() - if token.typ != itemSpace { - break - } - } - return token -} - -// peekNonSpace returns but does not consume the next non-space token. -func (t *Tree) peekNonSpace() (token item) { - for { - token = t.next() - if token.typ != itemSpace { - break - } - } - t.backup() - return token -} - -// Parsing. - -// New allocates a new parse tree with the given name. -func New(name string, funcs ...map[string]interface{}) *Tree { - return &Tree{ - Name: name, - funcs: funcs, - } -} - -// ErrorContext returns a textual representation of the location of the node in the input text. -// The receiver is only used when the node does not have a pointer to the tree inside, -// which can occur in old code. -func (t *Tree) ErrorContext(n Node) (location, context string) { - pos := int(n.Position()) - tree := n.tree() - if tree == nil { - tree = t - } - text := tree.text[:pos] - byteNum := strings.LastIndex(text, "\n") - if byteNum == -1 { - byteNum = pos // On first line. - } else { - byteNum++ // After the newline. - byteNum = pos - byteNum - } - lineNum := 1 + strings.Count(text, "\n") - context = n.String() - if len(context) > 20 { - context = fmt.Sprintf("%.20s...", context) - } - return fmt.Sprintf("%s:%d:%d", tree.ParseName, lineNum, byteNum), context -} - -// errorf formats the error and terminates processing. -func (t *Tree) errorf(format string, args ...interface{}) { - t.Root = nil - format = fmt.Sprintf("template: %s:%d: %s", t.ParseName, t.lex.lineNumber(), format) - panic(fmt.Errorf(format, args...)) -} - -// error terminates processing. -func (t *Tree) error(err error) { - t.errorf("%s", err) -} - -// expect consumes the next token and guarantees it has the required type. -func (t *Tree) expect(expected itemType, context string) item { - token := t.nextNonSpace() - if token.typ != expected { - t.unexpected(token, context) - } - return token -} - -// expectOneOf consumes the next token and guarantees it has one of the required types. -func (t *Tree) expectOneOf(expected1, expected2 itemType, context string) item { - token := t.nextNonSpace() - if token.typ != expected1 && token.typ != expected2 { - t.unexpected(token, context) - } - return token -} - -// unexpected complains about the token and terminates processing. -func (t *Tree) unexpected(token item, context string) { - t.errorf("unexpected %s in %s", token, context) -} - -// recover is the handler that turns panics into returns from the top level of Parse. -func (t *Tree) recover(errp *error) { - e := recover() - if e != nil { - if _, ok := e.(runtime.Error); ok { - panic(e) - } - if t != nil { - t.stopParse() - } - *errp = e.(error) - } - return -} - -// startParse initializes the parser, using the lexer. -func (t *Tree) startParse(funcs []map[string]interface{}, lex *lexer) { - t.Root = nil - t.lex = lex - t.vars = []string{"$"} - t.funcs = funcs -} - -// stopParse terminates parsing. -func (t *Tree) stopParse() { - t.lex = nil - t.vars = nil - t.funcs = nil -} - -// Parse parses the template definition string to construct a representation of -// the template for execution. If either action delimiter string is empty, the -// default ("{{" or "}}") is used. Embedded template definitions are added to -// the treeSet map. -func (t *Tree) Parse(text, leftDelim, rightDelim string, treeSet map[string]*Tree, funcs ...map[string]interface{}) (tree *Tree, err error) { - defer t.recover(&err) - t.ParseName = t.Name - t.startParse(funcs, lex(t.Name, text, leftDelim, rightDelim)) - t.text = text - t.parse(treeSet) - t.add(treeSet) - t.stopParse() - return t, nil -} - -// add adds tree to the treeSet. -func (t *Tree) add(treeSet map[string]*Tree) { - tree := treeSet[t.Name] - if tree == nil || IsEmptyTree(tree.Root) { - treeSet[t.Name] = t - return - } - if !IsEmptyTree(t.Root) { - t.errorf("template: multiple definition of template %q", t.Name) - } -} - -// IsEmptyTree reports whether this tree (node) is empty of everything but space. -func IsEmptyTree(n Node) bool { - switch n := n.(type) { - case nil: - return true - case *ActionNode: - case *IfNode: - case *ListNode: - for _, node := range n.Nodes { - if !IsEmptyTree(node) { - return false - } - } - return true - case *RangeNode: - case *TemplateNode: - case *TextNode: - return len(bytes.TrimSpace(n.Text)) == 0 - case *WithNode: - default: - panic("unknown node: " + n.String()) - } - return false -} - -// parse is the top-level parser for a template, essentially the same -// as itemList except it also parses {{define}} actions. -// It runs to EOF. -func (t *Tree) parse(treeSet map[string]*Tree) (next Node) { - t.Root = t.newList(t.peek().pos) - for t.peek().typ != itemEOF { - if t.peek().typ == itemLeftDelim { - delim := t.next() - if t.nextNonSpace().typ == itemDefine { - newT := New("definition") // name will be updated once we know it. - newT.text = t.text - newT.ParseName = t.ParseName - newT.startParse(t.funcs, t.lex) - newT.parseDefinition(treeSet) - continue - } - t.backup2(delim) - } - n := t.textOrAction() - if n.Type() == nodeEnd { - t.errorf("unexpected %s", n) - } - t.Root.append(n) - } - return nil -} - -// parseDefinition parses a {{define}} ... {{end}} template definition and -// installs the definition in the treeSet map. The "define" keyword has already -// been scanned. -func (t *Tree) parseDefinition(treeSet map[string]*Tree) { - const context = "define clause" - name := t.expectOneOf(itemString, itemRawString, context) - var err error - t.Name, err = strconv.Unquote(name.val) - if err != nil { - t.error(err) - } - t.expect(itemRightDelim, context) - var end Node - t.Root, end = t.itemList() - if end.Type() != nodeEnd { - t.errorf("unexpected %s in %s", end, context) - } - t.add(treeSet) - t.stopParse() -} - -// itemList: -// textOrAction* -// Terminates at {{end}} or {{else}}, returned separately. -func (t *Tree) itemList() (list *ListNode, next Node) { - list = t.newList(t.peekNonSpace().pos) - for t.peekNonSpace().typ != itemEOF { - n := t.textOrAction() - switch n.Type() { - case nodeEnd, nodeElse: - return list, n - } - list.append(n) - } - t.errorf("unexpected EOF") - return -} - -// textOrAction: -// text | action -func (t *Tree) textOrAction() Node { - switch token := t.nextNonSpace(); token.typ { - case itemElideNewline: - return t.elideNewline() - case itemText: - return t.newText(token.pos, token.val) - case itemLeftDelim: - return t.action() - default: - t.unexpected(token, "input") - } - return nil -} - -// elideNewline: -// Remove newlines trailing rightDelim if \\ is present. -func (t *Tree) elideNewline() Node { - token := t.peek() - if token.typ != itemText { - t.unexpected(token, "input") - return nil - } - - t.next() - stripped := strings.TrimLeft(token.val, "\n\r") - diff := len(token.val) - len(stripped) - if diff > 0 { - // This is a bit nasty. We mutate the token in-place to remove - // preceding newlines. - token.pos += Pos(diff) - token.val = stripped - } - return t.newText(token.pos, token.val) -} - -// Action: -// control -// command ("|" command)* -// Left delim is past. Now get actions. -// First word could be a keyword such as range. -func (t *Tree) action() (n Node) { - switch token := t.nextNonSpace(); token.typ { - case itemElse: - return t.elseControl() - case itemEnd: - return t.endControl() - case itemIf: - return t.ifControl() - case itemRange: - return t.rangeControl() - case itemTemplate: - return t.templateControl() - case itemWith: - return t.withControl() - } - t.backup() - // Do not pop variables; they persist until "end". - return t.newAction(t.peek().pos, t.lex.lineNumber(), t.pipeline("command")) -} - -// Pipeline: -// declarations? command ('|' command)* -func (t *Tree) pipeline(context string) (pipe *PipeNode) { - var decl []*VariableNode - pos := t.peekNonSpace().pos - // Are there declarations? - for { - if v := t.peekNonSpace(); v.typ == itemVariable { - t.next() - // Since space is a token, we need 3-token look-ahead here in the worst case: - // in "$x foo" we need to read "foo" (as opposed to ":=") to know that $x is an - // argument variable rather than a declaration. So remember the token - // adjacent to the variable so we can push it back if necessary. - tokenAfterVariable := t.peek() - if next := t.peekNonSpace(); next.typ == itemColonEquals || (next.typ == itemChar && next.val == ",") { - t.nextNonSpace() - variable := t.newVariable(v.pos, v.val) - decl = append(decl, variable) - t.vars = append(t.vars, v.val) - if next.typ == itemChar && next.val == "," { - if context == "range" && len(decl) < 2 { - continue - } - t.errorf("too many declarations in %s", context) - } - } else if tokenAfterVariable.typ == itemSpace { - t.backup3(v, tokenAfterVariable) - } else { - t.backup2(v) - } - } - break - } - pipe = t.newPipeline(pos, t.lex.lineNumber(), decl) - for { - switch token := t.nextNonSpace(); token.typ { - case itemRightDelim, itemRightParen: - if len(pipe.Cmds) == 0 { - t.errorf("missing value for %s", context) - } - if token.typ == itemRightParen { - t.backup() - } - return - case itemBool, itemCharConstant, itemComplex, itemDot, itemField, itemIdentifier, - itemNumber, itemNil, itemRawString, itemString, itemVariable, itemLeftParen: - t.backup() - pipe.append(t.command()) - default: - t.unexpected(token, context) - } - } -} - -func (t *Tree) parseControl(allowElseIf bool, context string) (pos Pos, line int, pipe *PipeNode, list, elseList *ListNode) { - defer t.popVars(len(t.vars)) - line = t.lex.lineNumber() - pipe = t.pipeline(context) - var next Node - list, next = t.itemList() - switch next.Type() { - case nodeEnd: //done - case nodeElse: - if allowElseIf { - // Special case for "else if". If the "else" is followed immediately by an "if", - // the elseControl will have left the "if" token pending. Treat - // {{if a}}_{{else if b}}_{{end}} - // as - // {{if a}}_{{else}}{{if b}}_{{end}}{{end}}. - // To do this, parse the if as usual and stop at it {{end}}; the subsequent{{end}} - // is assumed. This technique works even for long if-else-if chains. - // TODO: Should we allow else-if in with and range? - if t.peek().typ == itemIf { - t.next() // Consume the "if" token. - elseList = t.newList(next.Position()) - elseList.append(t.ifControl()) - // Do not consume the next item - only one {{end}} required. - break - } - } - elseList, next = t.itemList() - if next.Type() != nodeEnd { - t.errorf("expected end; found %s", next) - } - } - return pipe.Position(), line, pipe, list, elseList -} - -// If: -// {{if pipeline}} itemList {{end}} -// {{if pipeline}} itemList {{else}} itemList {{end}} -// If keyword is past. -func (t *Tree) ifControl() Node { - return t.newIf(t.parseControl(true, "if")) -} - -// Range: -// {{range pipeline}} itemList {{end}} -// {{range pipeline}} itemList {{else}} itemList {{end}} -// Range keyword is past. -func (t *Tree) rangeControl() Node { - return t.newRange(t.parseControl(false, "range")) -} - -// With: -// {{with pipeline}} itemList {{end}} -// {{with pipeline}} itemList {{else}} itemList {{end}} -// If keyword is past. -func (t *Tree) withControl() Node { - return t.newWith(t.parseControl(false, "with")) -} - -// End: -// {{end}} -// End keyword is past. -func (t *Tree) endControl() Node { - return t.newEnd(t.expect(itemRightDelim, "end").pos) -} - -// Else: -// {{else}} -// Else keyword is past. -func (t *Tree) elseControl() Node { - // Special case for "else if". - peek := t.peekNonSpace() - if peek.typ == itemIf { - // We see "{{else if ... " but in effect rewrite it to {{else}}{{if ... ". - return t.newElse(peek.pos, t.lex.lineNumber()) - } - return t.newElse(t.expect(itemRightDelim, "else").pos, t.lex.lineNumber()) -} - -// Template: -// {{template stringValue pipeline}} -// Template keyword is past. The name must be something that can evaluate -// to a string. -func (t *Tree) templateControl() Node { - var name string - token := t.nextNonSpace() - switch token.typ { - case itemString, itemRawString: - s, err := strconv.Unquote(token.val) - if err != nil { - t.error(err) - } - name = s - default: - t.unexpected(token, "template invocation") - } - var pipe *PipeNode - if t.nextNonSpace().typ != itemRightDelim { - t.backup() - // Do not pop variables; they persist until "end". - pipe = t.pipeline("template") - } - return t.newTemplate(token.pos, t.lex.lineNumber(), name, pipe) -} - -// command: -// operand (space operand)* -// space-separated arguments up to a pipeline character or right delimiter. -// we consume the pipe character but leave the right delim to terminate the action. -func (t *Tree) command() *CommandNode { - cmd := t.newCommand(t.peekNonSpace().pos) - for { - t.peekNonSpace() // skip leading spaces. - operand := t.operand() - if operand != nil { - cmd.append(operand) - } - switch token := t.next(); token.typ { - case itemSpace: - continue - case itemError: - t.errorf("%s", token.val) - case itemRightDelim, itemRightParen: - t.backup() - case itemPipe: - default: - t.errorf("unexpected %s in operand; missing space?", token) - } - break - } - if len(cmd.Args) == 0 { - t.errorf("empty command") - } - return cmd -} - -// operand: -// term .Field* -// An operand is a space-separated component of a command, -// a term possibly followed by field accesses. -// A nil return means the next item is not an operand. -func (t *Tree) operand() Node { - node := t.term() - if node == nil { - return nil - } - if t.peek().typ == itemField { - chain := t.newChain(t.peek().pos, node) - for t.peek().typ == itemField { - chain.Add(t.next().val) - } - // Compatibility with original API: If the term is of type NodeField - // or NodeVariable, just put more fields on the original. - // Otherwise, keep the Chain node. - // TODO: Switch to Chains always when we can. - switch node.Type() { - case NodeField: - node = t.newField(chain.Position(), chain.String()) - case NodeVariable: - node = t.newVariable(chain.Position(), chain.String()) - default: - node = chain - } - } - return node -} - -// term: -// literal (number, string, nil, boolean) -// function (identifier) -// . -// .Field -// $ -// '(' pipeline ')' -// A term is a simple "expression". -// A nil return means the next item is not a term. -func (t *Tree) term() Node { - switch token := t.nextNonSpace(); token.typ { - case itemError: - t.errorf("%s", token.val) - case itemIdentifier: - if !t.hasFunction(token.val) { - t.errorf("function %q not defined", token.val) - } - return NewIdentifier(token.val).SetTree(t).SetPos(token.pos) - case itemDot: - return t.newDot(token.pos) - case itemNil: - return t.newNil(token.pos) - case itemVariable: - return t.useVar(token.pos, token.val) - case itemField: - return t.newField(token.pos, token.val) - case itemBool: - return t.newBool(token.pos, token.val == "true") - case itemCharConstant, itemComplex, itemNumber: - number, err := t.newNumber(token.pos, token.val, token.typ) - if err != nil { - t.error(err) - } - return number - case itemLeftParen: - pipe := t.pipeline("parenthesized pipeline") - if token := t.next(); token.typ != itemRightParen { - t.errorf("unclosed right paren: unexpected %s", token) - } - return pipe - case itemString, itemRawString: - s, err := strconv.Unquote(token.val) - if err != nil { - t.error(err) - } - return t.newString(token.pos, token.val, s) - } - t.backup() - return nil -} - -// hasFunction reports if a function name exists in the Tree's maps. -func (t *Tree) hasFunction(name string) bool { - for _, funcMap := range t.funcs { - if funcMap == nil { - continue - } - if funcMap[name] != nil { - return true - } - } - return false -} - -// popVars trims the variable list to the specified length -func (t *Tree) popVars(n int) { - t.vars = t.vars[:n] -} - -// useVar returns a node for a variable reference. It errors if the -// variable is not defined. -func (t *Tree) useVar(pos Pos, name string) Node { - v := t.newVariable(pos, name) - for _, varName := range t.vars { - if varName == v.Ident[0] { - return v - } - } - t.errorf("undefined variable %q", v.Ident[0]) - return nil -} diff --git a/vendor/github.com/alecthomas/template/template.go b/vendor/github.com/alecthomas/template/template.go deleted file mode 100644 index 447ed2a..0000000 --- a/vendor/github.com/alecthomas/template/template.go +++ /dev/null @@ -1,218 +0,0 @@ -// Copyright 2011 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 template - -import ( - "fmt" - "reflect" - - "github.com/alecthomas/template/parse" -) - -// common holds the information shared by related templates. -type common struct { - tmpl map[string]*Template - // We use two maps, one for parsing and one for execution. - // This separation makes the API cleaner since it doesn't - // expose reflection to the client. - parseFuncs FuncMap - execFuncs map[string]reflect.Value -} - -// Template is the representation of a parsed template. The *parse.Tree -// field is exported only for use by html/template and should be treated -// as unexported by all other clients. -type Template struct { - name string - *parse.Tree - *common - leftDelim string - rightDelim string -} - -// New allocates a new template with the given name. -func New(name string) *Template { - return &Template{ - name: name, - } -} - -// Name returns the name of the template. -func (t *Template) Name() string { - return t.name -} - -// New allocates a new template associated with the given one and with the same -// delimiters. The association, which is transitive, allows one template to -// invoke another with a {{template}} action. -func (t *Template) New(name string) *Template { - t.init() - return &Template{ - name: name, - common: t.common, - leftDelim: t.leftDelim, - rightDelim: t.rightDelim, - } -} - -func (t *Template) init() { - if t.common == nil { - t.common = new(common) - t.tmpl = make(map[string]*Template) - t.parseFuncs = make(FuncMap) - t.execFuncs = make(map[string]reflect.Value) - } -} - -// Clone returns a duplicate of the template, including all associated -// templates. The actual representation is not copied, but the name space of -// associated templates is, so further calls to Parse in the copy will add -// templates to the copy but not to the original. Clone can be used to prepare -// common templates and use them with variant definitions for other templates -// by adding the variants after the clone is made. -func (t *Template) Clone() (*Template, error) { - nt := t.copy(nil) - nt.init() - nt.tmpl[t.name] = nt - for k, v := range t.tmpl { - if k == t.name { // Already installed. - continue - } - // The associated templates share nt's common structure. - tmpl := v.copy(nt.common) - nt.tmpl[k] = tmpl - } - for k, v := range t.parseFuncs { - nt.parseFuncs[k] = v - } - for k, v := range t.execFuncs { - nt.execFuncs[k] = v - } - return nt, nil -} - -// copy returns a shallow copy of t, with common set to the argument. -func (t *Template) copy(c *common) *Template { - nt := New(t.name) - nt.Tree = t.Tree - nt.common = c - nt.leftDelim = t.leftDelim - nt.rightDelim = t.rightDelim - return nt -} - -// AddParseTree creates a new template with the name and parse tree -// and associates it with t. -func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error) { - if t.common != nil && t.tmpl[name] != nil { - return nil, fmt.Errorf("template: redefinition of template %q", name) - } - nt := t.New(name) - nt.Tree = tree - t.tmpl[name] = nt - return nt, nil -} - -// Templates returns a slice of the templates associated with t, including t -// itself. -func (t *Template) Templates() []*Template { - if t.common == nil { - return nil - } - // Return a slice so we don't expose the map. - m := make([]*Template, 0, len(t.tmpl)) - for _, v := range t.tmpl { - m = append(m, v) - } - return m -} - -// Delims sets the action delimiters to the specified strings, to be used in -// subsequent calls to Parse, ParseFiles, or ParseGlob. Nested template -// definitions will inherit the settings. An empty delimiter stands for the -// corresponding default: {{ or }}. -// The return value is the template, so calls can be chained. -func (t *Template) Delims(left, right string) *Template { - t.leftDelim = left - t.rightDelim = right - return t -} - -// Funcs adds the elements of the argument map to the template's function map. -// It panics if a value in the map is not a function with appropriate return -// type. However, it is legal to overwrite elements of the map. The return -// value is the template, so calls can be chained. -func (t *Template) Funcs(funcMap FuncMap) *Template { - t.init() - addValueFuncs(t.execFuncs, funcMap) - addFuncs(t.parseFuncs, funcMap) - return t -} - -// Lookup returns the template with the given name that is associated with t, -// or nil if there is no such template. -func (t *Template) Lookup(name string) *Template { - if t.common == nil { - return nil - } - return t.tmpl[name] -} - -// Parse parses a string into a template. Nested template definitions will be -// associated with the top-level template t. Parse may be called multiple times -// to parse definitions of templates to associate with t. It is an error if a -// resulting template is non-empty (contains content other than template -// definitions) and would replace a non-empty template with the same name. -// (In multiple calls to Parse with the same receiver template, only one call -// can contain text other than space, comments, and template definitions.) -func (t *Template) Parse(text string) (*Template, error) { - t.init() - trees, err := parse.Parse(t.name, text, t.leftDelim, t.rightDelim, t.parseFuncs, builtins) - if err != nil { - return nil, err - } - // Add the newly parsed trees, including the one for t, into our common structure. - for name, tree := range trees { - // If the name we parsed is the name of this template, overwrite this template. - // The associate method checks it's not a redefinition. - tmpl := t - if name != t.name { - tmpl = t.New(name) - } - // Even if t == tmpl, we need to install it in the common.tmpl map. - if replace, err := t.associate(tmpl, tree); err != nil { - return nil, err - } else if replace { - tmpl.Tree = tree - } - tmpl.leftDelim = t.leftDelim - tmpl.rightDelim = t.rightDelim - } - return t, nil -} - -// associate installs the new template into the group of templates associated -// with t. It is an error to reuse a name except to overwrite an empty -// template. The two are already known to share the common structure. -// The boolean return value reports wither to store this tree as t.Tree. -func (t *Template) associate(new *Template, tree *parse.Tree) (bool, error) { - if new.common != t.common { - panic("internal error: associate not common") - } - name := new.name - if old := t.tmpl[name]; old != nil { - oldIsEmpty := parse.IsEmptyTree(old.Root) - newIsEmpty := parse.IsEmptyTree(tree.Root) - if newIsEmpty { - // Whether old is empty or not, new is empty; no reason to replace old. - return false, nil - } - if !oldIsEmpty { - return false, fmt.Errorf("template: redefinition of template %q", name) - } - } - t.tmpl[name] = new - return true, nil -} diff --git a/vendor/github.com/boombuler/barcode/.gitignore b/vendor/github.com/boombuler/barcode/.gitignore deleted file mode 100644 index 1d74e21..0000000 --- a/vendor/github.com/boombuler/barcode/.gitignore +++ /dev/null @@ -1 +0,0 @@ -.vscode/ diff --git a/vendor/github.com/boombuler/barcode/LICENSE b/vendor/github.com/boombuler/barcode/LICENSE deleted file mode 100644 index 862b0dd..0000000 --- a/vendor/github.com/boombuler/barcode/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Florian Sundermann - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/boombuler/barcode/README.md b/vendor/github.com/boombuler/barcode/README.md deleted file mode 100644 index 2a988db..0000000 --- a/vendor/github.com/boombuler/barcode/README.md +++ /dev/null @@ -1,53 +0,0 @@ -[![Join the chat at https://gitter.im/golang-barcode/Lobby](https://badges.gitter.im/golang-barcode/Lobby.svg)](https://gitter.im/golang-barcode/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) - -## Introduction ## - -This is a package for GO which can be used to create different types of barcodes. - -## Supported Barcode Types ## -* 2 of 5 -* Aztec Code -* Codabar -* Code 128 -* Code 39 -* Code 93 -* Datamatrix -* EAN 13 -* EAN 8 -* PDF 417 -* QR Code - -## Example ## - -This is a simple example on how to create a QR-Code and write it to a png-file -```go -package main - -import ( - "image/png" - "os" - - "github.com/boombuler/barcode" - "github.com/boombuler/barcode/qr" -) - -func main() { - // Create the barcode - qrCode, _ := qr.Encode("Hello World", qr.M, qr.Auto) - - // Scale the barcode to 200x200 pixels - qrCode, _ = barcode.Scale(qrCode, 200, 200) - - // create the output file - file, _ := os.Create("qrcode.png") - defer file.Close() - - // encode the barcode as png - png.Encode(file, qrCode) -} -``` - -## Documentation ## -See [GoDoc](https://godoc.org/github.com/boombuler/barcode) - -To create a barcode use the Encode function from one of the subpackages. diff --git a/vendor/github.com/boombuler/barcode/barcode.go b/vendor/github.com/boombuler/barcode/barcode.go deleted file mode 100644 index 25f4a69..0000000 --- a/vendor/github.com/boombuler/barcode/barcode.go +++ /dev/null @@ -1,42 +0,0 @@ -package barcode - -import "image" - -const ( - TypeAztec = "Aztec" - TypeCodabar = "Codabar" - TypeCode128 = "Code 128" - TypeCode39 = "Code 39" - TypeCode93 = "Code 93" - TypeDataMatrix = "DataMatrix" - TypeEAN8 = "EAN 8" - TypeEAN13 = "EAN 13" - TypePDF = "PDF417" - TypeQR = "QR Code" - Type2of5 = "2 of 5" - Type2of5Interleaved = "2 of 5 (interleaved)" -) - -// Contains some meta information about a barcode -type Metadata struct { - // the name of the barcode kind - CodeKind string - // contains 1 for 1D barcodes or 2 for 2D barcodes - Dimensions byte -} - -// a rendered and encoded barcode -type Barcode interface { - image.Image - // returns some meta information about the barcode - Metadata() Metadata - // the data that was encoded in this barcode - Content() string -} - -// Additional interface that some barcodes might implement to provide -// the value of its checksum. -type BarcodeIntCS interface { - Barcode - CheckSum() int -} diff --git a/vendor/github.com/boombuler/barcode/qr/alphanumeric.go b/vendor/github.com/boombuler/barcode/qr/alphanumeric.go deleted file mode 100644 index 4ded7c8..0000000 --- a/vendor/github.com/boombuler/barcode/qr/alphanumeric.go +++ /dev/null @@ -1,66 +0,0 @@ -package qr - -import ( - "errors" - "fmt" - "strings" - - "github.com/boombuler/barcode/utils" -) - -const charSet string = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:" - -func stringToAlphaIdx(content string) <-chan int { - result := make(chan int) - go func() { - for _, r := range content { - idx := strings.IndexRune(charSet, r) - result <- idx - if idx < 0 { - break - } - } - close(result) - }() - - return result -} - -func encodeAlphaNumeric(content string, ecl ErrorCorrectionLevel) (*utils.BitList, *versionInfo, error) { - - contentLenIsOdd := len(content)%2 == 1 - contentBitCount := (len(content) / 2) * 11 - if contentLenIsOdd { - contentBitCount += 6 - } - vi := findSmallestVersionInfo(ecl, alphaNumericMode, contentBitCount) - if vi == nil { - return nil, nil, errors.New("To much data to encode") - } - - res := new(utils.BitList) - res.AddBits(int(alphaNumericMode), 4) - res.AddBits(len(content), vi.charCountBits(alphaNumericMode)) - - encoder := stringToAlphaIdx(content) - - for idx := 0; idx < len(content)/2; idx++ { - c1 := <-encoder - c2 := <-encoder - if c1 < 0 || c2 < 0 { - return nil, nil, fmt.Errorf("\"%s\" can not be encoded as %s", content, AlphaNumeric) - } - res.AddBits(c1*45+c2, 11) - } - if contentLenIsOdd { - c := <-encoder - if c < 0 { - return nil, nil, fmt.Errorf("\"%s\" can not be encoded as %s", content, AlphaNumeric) - } - res.AddBits(c, 6) - } - - addPaddingAndTerminator(res, vi) - - return res, vi, nil -} diff --git a/vendor/github.com/boombuler/barcode/qr/automatic.go b/vendor/github.com/boombuler/barcode/qr/automatic.go deleted file mode 100644 index e7c5601..0000000 --- a/vendor/github.com/boombuler/barcode/qr/automatic.go +++ /dev/null @@ -1,23 +0,0 @@ -package qr - -import ( - "fmt" - - "github.com/boombuler/barcode/utils" -) - -func encodeAuto(content string, ecl ErrorCorrectionLevel) (*utils.BitList, *versionInfo, error) { - bits, vi, _ := Numeric.getEncoder()(content, ecl) - if bits != nil && vi != nil { - return bits, vi, nil - } - bits, vi, _ = AlphaNumeric.getEncoder()(content, ecl) - if bits != nil && vi != nil { - return bits, vi, nil - } - bits, vi, _ = Unicode.getEncoder()(content, ecl) - if bits != nil && vi != nil { - return bits, vi, nil - } - return nil, nil, fmt.Errorf("No encoding found to encode \"%s\"", content) -} diff --git a/vendor/github.com/boombuler/barcode/qr/blocks.go b/vendor/github.com/boombuler/barcode/qr/blocks.go deleted file mode 100644 index d317378..0000000 --- a/vendor/github.com/boombuler/barcode/qr/blocks.go +++ /dev/null @@ -1,59 +0,0 @@ -package qr - -type block struct { - data []byte - ecc []byte -} -type blockList []*block - -func splitToBlocks(data <-chan byte, vi *versionInfo) blockList { - result := make(blockList, vi.NumberOfBlocksInGroup1+vi.NumberOfBlocksInGroup2) - - for b := 0; b < int(vi.NumberOfBlocksInGroup1); b++ { - blk := new(block) - blk.data = make([]byte, vi.DataCodeWordsPerBlockInGroup1) - for cw := 0; cw < int(vi.DataCodeWordsPerBlockInGroup1); cw++ { - blk.data[cw] = <-data - } - blk.ecc = ec.calcECC(blk.data, vi.ErrorCorrectionCodewordsPerBlock) - result[b] = blk - } - - for b := 0; b < int(vi.NumberOfBlocksInGroup2); b++ { - blk := new(block) - blk.data = make([]byte, vi.DataCodeWordsPerBlockInGroup2) - for cw := 0; cw < int(vi.DataCodeWordsPerBlockInGroup2); cw++ { - blk.data[cw] = <-data - } - blk.ecc = ec.calcECC(blk.data, vi.ErrorCorrectionCodewordsPerBlock) - result[int(vi.NumberOfBlocksInGroup1)+b] = blk - } - - return result -} - -func (bl blockList) interleave(vi *versionInfo) []byte { - var maxCodewordCount int - if vi.DataCodeWordsPerBlockInGroup1 > vi.DataCodeWordsPerBlockInGroup2 { - maxCodewordCount = int(vi.DataCodeWordsPerBlockInGroup1) - } else { - maxCodewordCount = int(vi.DataCodeWordsPerBlockInGroup2) - } - resultLen := (vi.DataCodeWordsPerBlockInGroup1+vi.ErrorCorrectionCodewordsPerBlock)*vi.NumberOfBlocksInGroup1 + - (vi.DataCodeWordsPerBlockInGroup2+vi.ErrorCorrectionCodewordsPerBlock)*vi.NumberOfBlocksInGroup2 - - result := make([]byte, 0, resultLen) - for i := 0; i < maxCodewordCount; i++ { - for b := 0; b < len(bl); b++ { - if len(bl[b].data) > i { - result = append(result, bl[b].data[i]) - } - } - } - for i := 0; i < int(vi.ErrorCorrectionCodewordsPerBlock); i++ { - for b := 0; b < len(bl); b++ { - result = append(result, bl[b].ecc[i]) - } - } - return result -} diff --git a/vendor/github.com/boombuler/barcode/qr/encoder.go b/vendor/github.com/boombuler/barcode/qr/encoder.go deleted file mode 100644 index 2c6ab21..0000000 --- a/vendor/github.com/boombuler/barcode/qr/encoder.go +++ /dev/null @@ -1,416 +0,0 @@ -// Package qr can be used to create QR barcodes. -package qr - -import ( - "image" - - "github.com/boombuler/barcode" - "github.com/boombuler/barcode/utils" -) - -type encodeFn func(content string, eccLevel ErrorCorrectionLevel) (*utils.BitList, *versionInfo, error) - -// Encoding mode for QR Codes. -type Encoding byte - -const ( - // Auto will choose ths best matching encoding - Auto Encoding = iota - // Numeric encoding only encodes numbers [0-9] - Numeric - // AlphaNumeric encoding only encodes uppercase letters, numbers and [Space], $, %, *, +, -, ., /, : - AlphaNumeric - // Unicode encoding encodes the string as utf-8 - Unicode - // only for testing purpose - unknownEncoding -) - -func (e Encoding) getEncoder() encodeFn { - switch e { - case Auto: - return encodeAuto - case Numeric: - return encodeNumeric - case AlphaNumeric: - return encodeAlphaNumeric - case Unicode: - return encodeUnicode - } - return nil -} - -func (e Encoding) String() string { - switch e { - case Auto: - return "Auto" - case Numeric: - return "Numeric" - case AlphaNumeric: - return "AlphaNumeric" - case Unicode: - return "Unicode" - } - return "" -} - -// Encode returns a QR barcode with the given content, error correction level and uses the given encoding -func Encode(content string, level ErrorCorrectionLevel, mode Encoding) (barcode.Barcode, error) { - bits, vi, err := mode.getEncoder()(content, level) - if err != nil { - return nil, err - } - - blocks := splitToBlocks(bits.IterateBytes(), vi) - data := blocks.interleave(vi) - result := render(data, vi) - result.content = content - return result, nil -} - -func render(data []byte, vi *versionInfo) *qrcode { - dim := vi.modulWidth() - results := make([]*qrcode, 8) - for i := 0; i < 8; i++ { - results[i] = newBarcode(dim) - } - - occupied := newBarcode(dim) - - setAll := func(x int, y int, val bool) { - occupied.Set(x, y, true) - for i := 0; i < 8; i++ { - results[i].Set(x, y, val) - } - } - - drawFinderPatterns(vi, setAll) - drawAlignmentPatterns(occupied, vi, setAll) - - //Timing Pattern: - var i int - for i = 0; i < dim; i++ { - if !occupied.Get(i, 6) { - setAll(i, 6, i%2 == 0) - } - if !occupied.Get(6, i) { - setAll(6, i, i%2 == 0) - } - } - // Dark Module - setAll(8, dim-8, true) - - drawVersionInfo(vi, setAll) - drawFormatInfo(vi, -1, occupied.Set) - for i := 0; i < 8; i++ { - drawFormatInfo(vi, i, results[i].Set) - } - - // Write the data - var curBitNo int - - for pos := range iterateModules(occupied) { - var curBit bool - if curBitNo < len(data)*8 { - curBit = ((data[curBitNo/8] >> uint(7-(curBitNo%8))) & 1) == 1 - } else { - curBit = false - } - - for i := 0; i < 8; i++ { - setMasked(pos.X, pos.Y, curBit, i, results[i].Set) - } - curBitNo++ - } - - lowestPenalty := ^uint(0) - lowestPenaltyIdx := -1 - for i := 0; i < 8; i++ { - p := results[i].calcPenalty() - if p < lowestPenalty { - lowestPenalty = p - lowestPenaltyIdx = i - } - } - return results[lowestPenaltyIdx] -} - -func setMasked(x, y int, val bool, mask int, set func(int, int, bool)) { - switch mask { - case 0: - val = val != (((y + x) % 2) == 0) - break - case 1: - val = val != ((y % 2) == 0) - break - case 2: - val = val != ((x % 3) == 0) - break - case 3: - val = val != (((y + x) % 3) == 0) - break - case 4: - val = val != (((y/2 + x/3) % 2) == 0) - break - case 5: - val = val != (((y*x)%2)+((y*x)%3) == 0) - break - case 6: - val = val != ((((y*x)%2)+((y*x)%3))%2 == 0) - break - case 7: - val = val != ((((y+x)%2)+((y*x)%3))%2 == 0) - } - set(x, y, val) -} - -func iterateModules(occupied *qrcode) <-chan image.Point { - result := make(chan image.Point) - allPoints := make(chan image.Point) - go func() { - curX := occupied.dimension - 1 - curY := occupied.dimension - 1 - isUpward := true - - for true { - if isUpward { - allPoints <- image.Pt(curX, curY) - allPoints <- image.Pt(curX-1, curY) - curY-- - if curY < 0 { - curY = 0 - curX -= 2 - if curX == 6 { - curX-- - } - if curX < 0 { - break - } - isUpward = false - } - } else { - allPoints <- image.Pt(curX, curY) - allPoints <- image.Pt(curX-1, curY) - curY++ - if curY >= occupied.dimension { - curY = occupied.dimension - 1 - curX -= 2 - if curX == 6 { - curX-- - } - isUpward = true - if curX < 0 { - break - } - } - } - } - - close(allPoints) - }() - go func() { - for pt := range allPoints { - if !occupied.Get(pt.X, pt.Y) { - result <- pt - } - } - close(result) - }() - return result -} - -func drawFinderPatterns(vi *versionInfo, set func(int, int, bool)) { - dim := vi.modulWidth() - drawPattern := func(xoff int, yoff int) { - for x := -1; x < 8; x++ { - for y := -1; y < 8; y++ { - val := (x == 0 || x == 6 || y == 0 || y == 6 || (x > 1 && x < 5 && y > 1 && y < 5)) && (x <= 6 && y <= 6 && x >= 0 && y >= 0) - - if x+xoff >= 0 && x+xoff < dim && y+yoff >= 0 && y+yoff < dim { - set(x+xoff, y+yoff, val) - } - } - } - } - drawPattern(0, 0) - drawPattern(0, dim-7) - drawPattern(dim-7, 0) -} - -func drawAlignmentPatterns(occupied *qrcode, vi *versionInfo, set func(int, int, bool)) { - drawPattern := func(xoff int, yoff int) { - for x := -2; x <= 2; x++ { - for y := -2; y <= 2; y++ { - val := x == -2 || x == 2 || y == -2 || y == 2 || (x == 0 && y == 0) - set(x+xoff, y+yoff, val) - } - } - } - positions := vi.alignmentPatternPlacements() - - for _, x := range positions { - for _, y := range positions { - if occupied.Get(x, y) { - continue - } - drawPattern(x, y) - } - } -} - -var formatInfos = map[ErrorCorrectionLevel]map[int][]bool{ - L: { - 0: []bool{true, true, true, false, true, true, true, true, true, false, false, false, true, false, false}, - 1: []bool{true, true, true, false, false, true, false, true, true, true, true, false, false, true, true}, - 2: []bool{true, true, true, true, true, false, true, true, false, true, false, true, false, true, false}, - 3: []bool{true, true, true, true, false, false, false, true, false, false, true, true, true, false, true}, - 4: []bool{true, true, false, false, true, true, false, false, false, true, false, true, true, true, true}, - 5: []bool{true, true, false, false, false, true, true, false, false, false, true, true, false, false, false}, - 6: []bool{true, true, false, true, true, false, false, false, true, false, false, false, false, false, true}, - 7: []bool{true, true, false, true, false, false, true, false, true, true, true, false, true, true, false}, - }, - M: { - 0: []bool{true, false, true, false, true, false, false, false, false, false, true, false, false, true, false}, - 1: []bool{true, false, true, false, false, false, true, false, false, true, false, false, true, false, true}, - 2: []bool{true, false, true, true, true, true, false, false, true, true, true, true, true, false, false}, - 3: []bool{true, false, true, true, false, true, true, false, true, false, false, true, false, true, true}, - 4: []bool{true, false, false, false, true, false, true, true, true, true, true, true, false, false, true}, - 5: []bool{true, false, false, false, false, false, false, true, true, false, false, true, true, true, false}, - 6: []bool{true, false, false, true, true, true, true, true, false, false, true, false, true, true, true}, - 7: []bool{true, false, false, true, false, true, false, true, false, true, false, false, false, false, false}, - }, - Q: { - 0: []bool{false, true, true, false, true, false, true, false, true, false, true, true, true, true, true}, - 1: []bool{false, true, true, false, false, false, false, false, true, true, false, true, false, false, false}, - 2: []bool{false, true, true, true, true, true, true, false, false, true, true, false, false, false, true}, - 3: []bool{false, true, true, true, false, true, false, false, false, false, false, false, true, true, false}, - 4: []bool{false, true, false, false, true, false, false, true, false, true, true, false, true, false, false}, - 5: []bool{false, true, false, false, false, false, true, true, false, false, false, false, false, true, true}, - 6: []bool{false, true, false, true, true, true, false, true, true, false, true, true, false, true, false}, - 7: []bool{false, true, false, true, false, true, true, true, true, true, false, true, true, false, true}, - }, - H: { - 0: []bool{false, false, true, false, true, true, false, true, false, false, false, true, false, false, true}, - 1: []bool{false, false, true, false, false, true, true, true, false, true, true, true, true, true, false}, - 2: []bool{false, false, true, true, true, false, false, true, true, true, false, false, true, true, true}, - 3: []bool{false, false, true, true, false, false, true, true, true, false, true, false, false, false, false}, - 4: []bool{false, false, false, false, true, true, true, false, true, true, false, false, false, true, false}, - 5: []bool{false, false, false, false, false, true, false, false, true, false, true, false, true, false, true}, - 6: []bool{false, false, false, true, true, false, true, false, false, false, false, true, true, false, false}, - 7: []bool{false, false, false, true, false, false, false, false, false, true, true, true, false, true, true}, - }, -} - -func drawFormatInfo(vi *versionInfo, usedMask int, set func(int, int, bool)) { - var formatInfo []bool - - if usedMask == -1 { - formatInfo = []bool{true, true, true, true, true, true, true, true, true, true, true, true, true, true, true} // Set all to true cause -1 --> occupied mask. - } else { - formatInfo = formatInfos[vi.Level][usedMask] - } - - if len(formatInfo) == 15 { - dim := vi.modulWidth() - set(0, 8, formatInfo[0]) - set(1, 8, formatInfo[1]) - set(2, 8, formatInfo[2]) - set(3, 8, formatInfo[3]) - set(4, 8, formatInfo[4]) - set(5, 8, formatInfo[5]) - set(7, 8, formatInfo[6]) - set(8, 8, formatInfo[7]) - set(8, 7, formatInfo[8]) - set(8, 5, formatInfo[9]) - set(8, 4, formatInfo[10]) - set(8, 3, formatInfo[11]) - set(8, 2, formatInfo[12]) - set(8, 1, formatInfo[13]) - set(8, 0, formatInfo[14]) - - set(8, dim-1, formatInfo[0]) - set(8, dim-2, formatInfo[1]) - set(8, dim-3, formatInfo[2]) - set(8, dim-4, formatInfo[3]) - set(8, dim-5, formatInfo[4]) - set(8, dim-6, formatInfo[5]) - set(8, dim-7, formatInfo[6]) - set(dim-8, 8, formatInfo[7]) - set(dim-7, 8, formatInfo[8]) - set(dim-6, 8, formatInfo[9]) - set(dim-5, 8, formatInfo[10]) - set(dim-4, 8, formatInfo[11]) - set(dim-3, 8, formatInfo[12]) - set(dim-2, 8, formatInfo[13]) - set(dim-1, 8, formatInfo[14]) - } -} - -var versionInfoBitsByVersion = map[byte][]bool{ - 7: []bool{false, false, false, true, true, true, true, true, false, false, true, false, false, true, false, true, false, false}, - 8: []bool{false, false, true, false, false, false, false, true, false, true, true, false, true, true, true, true, false, false}, - 9: []bool{false, false, true, false, false, true, true, false, true, false, true, false, false, true, true, false, false, true}, - 10: []bool{false, false, true, false, true, false, false, true, false, false, true, true, false, true, false, false, true, true}, - 11: []bool{false, false, true, false, true, true, true, false, true, true, true, true, true, true, false, true, true, false}, - 12: []bool{false, false, true, true, false, false, false, true, true, true, false, true, true, false, false, false, true, false}, - 13: []bool{false, false, true, true, false, true, true, false, false, false, false, true, false, false, false, true, true, true}, - 14: []bool{false, false, true, true, true, false, false, true, true, false, false, false, false, false, true, true, false, true}, - 15: []bool{false, false, true, true, true, true, true, false, false, true, false, false, true, false, true, false, false, false}, - 16: []bool{false, true, false, false, false, false, true, false, true, true, false, true, true, true, true, false, false, false}, - 17: []bool{false, true, false, false, false, true, false, true, false, false, false, true, false, true, true, true, false, true}, - 18: []bool{false, true, false, false, true, false, true, false, true, false, false, false, false, true, false, true, true, true}, - 19: []bool{false, true, false, false, true, true, false, true, false, true, false, false, true, true, false, false, true, false}, - 20: []bool{false, true, false, true, false, false, true, false, false, true, true, false, true, false, false, true, true, false}, - 21: []bool{false, true, false, true, false, true, false, true, true, false, true, false, false, false, false, false, true, true}, - 22: []bool{false, true, false, true, true, false, true, false, false, false, true, true, false, false, true, false, false, true}, - 23: []bool{false, true, false, true, true, true, false, true, true, true, true, true, true, false, true, true, false, false}, - 24: []bool{false, true, true, false, false, false, true, true, true, false, true, true, false, false, false, true, false, false}, - 25: []bool{false, true, true, false, false, true, false, false, false, true, true, true, true, false, false, false, false, true}, - 26: []bool{false, true, true, false, true, false, true, true, true, true, true, false, true, false, true, false, true, true}, - 27: []bool{false, true, true, false, true, true, false, false, false, false, true, false, false, false, true, true, true, false}, - 28: []bool{false, true, true, true, false, false, true, true, false, false, false, false, false, true, true, false, true, false}, - 29: []bool{false, true, true, true, false, true, false, false, true, true, false, false, true, true, true, true, true, true}, - 30: []bool{false, true, true, true, true, false, true, true, false, true, false, true, true, true, false, true, false, true}, - 31: []bool{false, true, true, true, true, true, false, false, true, false, false, true, false, true, false, false, false, false}, - 32: []bool{true, false, false, false, false, false, true, false, false, true, true, true, false, true, false, true, false, true}, - 33: []bool{true, false, false, false, false, true, false, true, true, false, true, true, true, true, false, false, false, false}, - 34: []bool{true, false, false, false, true, false, true, false, false, false, true, false, true, true, true, false, true, false}, - 35: []bool{true, false, false, false, true, true, false, true, true, true, true, false, false, true, true, true, true, true}, - 36: []bool{true, false, false, true, false, false, true, false, true, true, false, false, false, false, true, false, true, true}, - 37: []bool{true, false, false, true, false, true, false, true, false, false, false, false, true, false, true, true, true, false}, - 38: []bool{true, false, false, true, true, false, true, false, true, false, false, true, true, false, false, true, false, false}, - 39: []bool{true, false, false, true, true, true, false, true, false, true, false, true, false, false, false, false, false, true}, - 40: []bool{true, false, true, false, false, false, true, true, false, false, false, true, true, false, true, false, false, true}, -} - -func drawVersionInfo(vi *versionInfo, set func(int, int, bool)) { - versionInfoBits, ok := versionInfoBitsByVersion[vi.Version] - - if ok && len(versionInfoBits) > 0 { - for i := 0; i < len(versionInfoBits); i++ { - x := (vi.modulWidth() - 11) + i%3 - y := i / 3 - set(x, y, versionInfoBits[len(versionInfoBits)-i-1]) - set(y, x, versionInfoBits[len(versionInfoBits)-i-1]) - } - } - -} - -func addPaddingAndTerminator(bl *utils.BitList, vi *versionInfo) { - for i := 0; i < 4 && bl.Len() < vi.totalDataBytes()*8; i++ { - bl.AddBit(false) - } - - for bl.Len()%8 != 0 { - bl.AddBit(false) - } - - for i := 0; bl.Len() < vi.totalDataBytes()*8; i++ { - if i%2 == 0 { - bl.AddByte(236) - } else { - bl.AddByte(17) - } - } -} diff --git a/vendor/github.com/boombuler/barcode/qr/errorcorrection.go b/vendor/github.com/boombuler/barcode/qr/errorcorrection.go deleted file mode 100644 index 08ebf0c..0000000 --- a/vendor/github.com/boombuler/barcode/qr/errorcorrection.go +++ /dev/null @@ -1,29 +0,0 @@ -package qr - -import ( - "github.com/boombuler/barcode/utils" -) - -type errorCorrection struct { - rs *utils.ReedSolomonEncoder -} - -var ec = newErrorCorrection() - -func newErrorCorrection() *errorCorrection { - fld := utils.NewGaloisField(285, 256, 0) - return &errorCorrection{utils.NewReedSolomonEncoder(fld)} -} - -func (ec *errorCorrection) calcECC(data []byte, eccCount byte) []byte { - dataInts := make([]int, len(data)) - for i := 0; i < len(data); i++ { - dataInts[i] = int(data[i]) - } - res := ec.rs.Encode(dataInts, int(eccCount)) - result := make([]byte, len(res)) - for i := 0; i < len(res); i++ { - result[i] = byte(res[i]) - } - return result -} diff --git a/vendor/github.com/boombuler/barcode/qr/numeric.go b/vendor/github.com/boombuler/barcode/qr/numeric.go deleted file mode 100644 index 49b44cc..0000000 --- a/vendor/github.com/boombuler/barcode/qr/numeric.go +++ /dev/null @@ -1,56 +0,0 @@ -package qr - -import ( - "errors" - "fmt" - "strconv" - - "github.com/boombuler/barcode/utils" -) - -func encodeNumeric(content string, ecl ErrorCorrectionLevel) (*utils.BitList, *versionInfo, error) { - contentBitCount := (len(content) / 3) * 10 - switch len(content) % 3 { - case 1: - contentBitCount += 4 - case 2: - contentBitCount += 7 - } - vi := findSmallestVersionInfo(ecl, numericMode, contentBitCount) - if vi == nil { - return nil, nil, errors.New("To much data to encode") - } - res := new(utils.BitList) - res.AddBits(int(numericMode), 4) - res.AddBits(len(content), vi.charCountBits(numericMode)) - - for pos := 0; pos < len(content); pos += 3 { - var curStr string - if pos+3 <= len(content) { - curStr = content[pos : pos+3] - } else { - curStr = content[pos:] - } - - i, err := strconv.Atoi(curStr) - if err != nil || i < 0 { - return nil, nil, fmt.Errorf("\"%s\" can not be encoded as %s", content, Numeric) - } - var bitCnt byte - switch len(curStr) % 3 { - case 0: - bitCnt = 10 - case 1: - bitCnt = 4 - break - case 2: - bitCnt = 7 - break - } - - res.AddBits(i, bitCnt) - } - - addPaddingAndTerminator(res, vi) - return res, vi, nil -} diff --git a/vendor/github.com/boombuler/barcode/qr/qrcode.go b/vendor/github.com/boombuler/barcode/qr/qrcode.go deleted file mode 100644 index 1360760..0000000 --- a/vendor/github.com/boombuler/barcode/qr/qrcode.go +++ /dev/null @@ -1,166 +0,0 @@ -package qr - -import ( - "image" - "image/color" - "math" - - "github.com/boombuler/barcode" - "github.com/boombuler/barcode/utils" -) - -type qrcode struct { - dimension int - data *utils.BitList - content string -} - -func (qr *qrcode) Content() string { - return qr.content -} - -func (qr *qrcode) Metadata() barcode.Metadata { - return barcode.Metadata{barcode.TypeQR, 2} -} - -func (qr *qrcode) ColorModel() color.Model { - return color.Gray16Model -} - -func (qr *qrcode) Bounds() image.Rectangle { - return image.Rect(0, 0, qr.dimension, qr.dimension) -} - -func (qr *qrcode) At(x, y int) color.Color { - if qr.Get(x, y) { - return color.Black - } - return color.White -} - -func (qr *qrcode) Get(x, y int) bool { - return qr.data.GetBit(x*qr.dimension + y) -} - -func (qr *qrcode) Set(x, y int, val bool) { - qr.data.SetBit(x*qr.dimension+y, val) -} - -func (qr *qrcode) calcPenalty() uint { - return qr.calcPenaltyRule1() + qr.calcPenaltyRule2() + qr.calcPenaltyRule3() + qr.calcPenaltyRule4() -} - -func (qr *qrcode) calcPenaltyRule1() uint { - var result uint - for x := 0; x < qr.dimension; x++ { - checkForX := false - var cntX uint - checkForY := false - var cntY uint - - for y := 0; y < qr.dimension; y++ { - if qr.Get(x, y) == checkForX { - cntX++ - } else { - checkForX = !checkForX - if cntX >= 5 { - result += cntX - 2 - } - cntX = 1 - } - - if qr.Get(y, x) == checkForY { - cntY++ - } else { - checkForY = !checkForY - if cntY >= 5 { - result += cntY - 2 - } - cntY = 1 - } - } - - if cntX >= 5 { - result += cntX - 2 - } - if cntY >= 5 { - result += cntY - 2 - } - } - - return result -} - -func (qr *qrcode) calcPenaltyRule2() uint { - var result uint - for x := 0; x < qr.dimension-1; x++ { - for y := 0; y < qr.dimension-1; y++ { - check := qr.Get(x, y) - if qr.Get(x, y+1) == check && qr.Get(x+1, y) == check && qr.Get(x+1, y+1) == check { - result += 3 - } - } - } - return result -} - -func (qr *qrcode) calcPenaltyRule3() uint { - pattern1 := []bool{true, false, true, true, true, false, true, false, false, false, false} - pattern2 := []bool{false, false, false, false, true, false, true, true, true, false, true} - - var result uint - for x := 0; x <= qr.dimension-len(pattern1); x++ { - for y := 0; y < qr.dimension; y++ { - pattern1XFound := true - pattern2XFound := true - pattern1YFound := true - pattern2YFound := true - - for i := 0; i < len(pattern1); i++ { - iv := qr.Get(x+i, y) - if iv != pattern1[i] { - pattern1XFound = false - } - if iv != pattern2[i] { - pattern2XFound = false - } - iv = qr.Get(y, x+i) - if iv != pattern1[i] { - pattern1YFound = false - } - if iv != pattern2[i] { - pattern2YFound = false - } - } - if pattern1XFound || pattern2XFound { - result += 40 - } - if pattern1YFound || pattern2YFound { - result += 40 - } - } - } - - return result -} - -func (qr *qrcode) calcPenaltyRule4() uint { - totalNum := qr.data.Len() - trueCnt := 0 - for i := 0; i < totalNum; i++ { - if qr.data.GetBit(i) { - trueCnt++ - } - } - percDark := float64(trueCnt) * 100 / float64(totalNum) - floor := math.Abs(math.Floor(percDark/5) - 10) - ceil := math.Abs(math.Ceil(percDark/5) - 10) - return uint(math.Min(floor, ceil) * 10) -} - -func newBarcode(dim int) *qrcode { - res := new(qrcode) - res.dimension = dim - res.data = utils.NewBitList(dim * dim) - return res -} diff --git a/vendor/github.com/boombuler/barcode/qr/unicode.go b/vendor/github.com/boombuler/barcode/qr/unicode.go deleted file mode 100644 index a9135ab..0000000 --- a/vendor/github.com/boombuler/barcode/qr/unicode.go +++ /dev/null @@ -1,27 +0,0 @@ -package qr - -import ( - "errors" - - "github.com/boombuler/barcode/utils" -) - -func encodeUnicode(content string, ecl ErrorCorrectionLevel) (*utils.BitList, *versionInfo, error) { - data := []byte(content) - - vi := findSmallestVersionInfo(ecl, byteMode, len(data)*8) - if vi == nil { - return nil, nil, errors.New("To much data to encode") - } - - // It's not correct to add the unicode bytes to the result directly but most readers can't handle the - // required ECI header... - res := new(utils.BitList) - res.AddBits(int(byteMode), 4) - res.AddBits(len(content), vi.charCountBits(byteMode)) - for _, b := range data { - res.AddByte(b) - } - addPaddingAndTerminator(res, vi) - return res, vi, nil -} diff --git a/vendor/github.com/boombuler/barcode/qr/versioninfo.go b/vendor/github.com/boombuler/barcode/qr/versioninfo.go deleted file mode 100644 index 6852a57..0000000 --- a/vendor/github.com/boombuler/barcode/qr/versioninfo.go +++ /dev/null @@ -1,310 +0,0 @@ -package qr - -import "math" - -// ErrorCorrectionLevel indicates the amount of "backup data" stored in the QR code -type ErrorCorrectionLevel byte - -const ( - // L recovers 7% of data - L ErrorCorrectionLevel = iota - // M recovers 15% of data - M - // Q recovers 25% of data - Q - // H recovers 30% of data - H -) - -func (ecl ErrorCorrectionLevel) String() string { - switch ecl { - case L: - return "L" - case M: - return "M" - case Q: - return "Q" - case H: - return "H" - } - return "unknown" -} - -type encodingMode byte - -const ( - numericMode encodingMode = 1 - alphaNumericMode encodingMode = 2 - byteMode encodingMode = 4 - kanjiMode encodingMode = 8 -) - -type versionInfo struct { - Version byte - Level ErrorCorrectionLevel - ErrorCorrectionCodewordsPerBlock byte - NumberOfBlocksInGroup1 byte - DataCodeWordsPerBlockInGroup1 byte - NumberOfBlocksInGroup2 byte - DataCodeWordsPerBlockInGroup2 byte -} - -var versionInfos = []*versionInfo{ - &versionInfo{1, L, 7, 1, 19, 0, 0}, - &versionInfo{1, M, 10, 1, 16, 0, 0}, - &versionInfo{1, Q, 13, 1, 13, 0, 0}, - &versionInfo{1, H, 17, 1, 9, 0, 0}, - &versionInfo{2, L, 10, 1, 34, 0, 0}, - &versionInfo{2, M, 16, 1, 28, 0, 0}, - &versionInfo{2, Q, 22, 1, 22, 0, 0}, - &versionInfo{2, H, 28, 1, 16, 0, 0}, - &versionInfo{3, L, 15, 1, 55, 0, 0}, - &versionInfo{3, M, 26, 1, 44, 0, 0}, - &versionInfo{3, Q, 18, 2, 17, 0, 0}, - &versionInfo{3, H, 22, 2, 13, 0, 0}, - &versionInfo{4, L, 20, 1, 80, 0, 0}, - &versionInfo{4, M, 18, 2, 32, 0, 0}, - &versionInfo{4, Q, 26, 2, 24, 0, 0}, - &versionInfo{4, H, 16, 4, 9, 0, 0}, - &versionInfo{5, L, 26, 1, 108, 0, 0}, - &versionInfo{5, M, 24, 2, 43, 0, 0}, - &versionInfo{5, Q, 18, 2, 15, 2, 16}, - &versionInfo{5, H, 22, 2, 11, 2, 12}, - &versionInfo{6, L, 18, 2, 68, 0, 0}, - &versionInfo{6, M, 16, 4, 27, 0, 0}, - &versionInfo{6, Q, 24, 4, 19, 0, 0}, - &versionInfo{6, H, 28, 4, 15, 0, 0}, - &versionInfo{7, L, 20, 2, 78, 0, 0}, - &versionInfo{7, M, 18, 4, 31, 0, 0}, - &versionInfo{7, Q, 18, 2, 14, 4, 15}, - &versionInfo{7, H, 26, 4, 13, 1, 14}, - &versionInfo{8, L, 24, 2, 97, 0, 0}, - &versionInfo{8, M, 22, 2, 38, 2, 39}, - &versionInfo{8, Q, 22, 4, 18, 2, 19}, - &versionInfo{8, H, 26, 4, 14, 2, 15}, - &versionInfo{9, L, 30, 2, 116, 0, 0}, - &versionInfo{9, M, 22, 3, 36, 2, 37}, - &versionInfo{9, Q, 20, 4, 16, 4, 17}, - &versionInfo{9, H, 24, 4, 12, 4, 13}, - &versionInfo{10, L, 18, 2, 68, 2, 69}, - &versionInfo{10, M, 26, 4, 43, 1, 44}, - &versionInfo{10, Q, 24, 6, 19, 2, 20}, - &versionInfo{10, H, 28, 6, 15, 2, 16}, - &versionInfo{11, L, 20, 4, 81, 0, 0}, - &versionInfo{11, M, 30, 1, 50, 4, 51}, - &versionInfo{11, Q, 28, 4, 22, 4, 23}, - &versionInfo{11, H, 24, 3, 12, 8, 13}, - &versionInfo{12, L, 24, 2, 92, 2, 93}, - &versionInfo{12, M, 22, 6, 36, 2, 37}, - &versionInfo{12, Q, 26, 4, 20, 6, 21}, - &versionInfo{12, H, 28, 7, 14, 4, 15}, - &versionInfo{13, L, 26, 4, 107, 0, 0}, - &versionInfo{13, M, 22, 8, 37, 1, 38}, - &versionInfo{13, Q, 24, 8, 20, 4, 21}, - &versionInfo{13, H, 22, 12, 11, 4, 12}, - &versionInfo{14, L, 30, 3, 115, 1, 116}, - &versionInfo{14, M, 24, 4, 40, 5, 41}, - &versionInfo{14, Q, 20, 11, 16, 5, 17}, - &versionInfo{14, H, 24, 11, 12, 5, 13}, - &versionInfo{15, L, 22, 5, 87, 1, 88}, - &versionInfo{15, M, 24, 5, 41, 5, 42}, - &versionInfo{15, Q, 30, 5, 24, 7, 25}, - &versionInfo{15, H, 24, 11, 12, 7, 13}, - &versionInfo{16, L, 24, 5, 98, 1, 99}, - &versionInfo{16, M, 28, 7, 45, 3, 46}, - &versionInfo{16, Q, 24, 15, 19, 2, 20}, - &versionInfo{16, H, 30, 3, 15, 13, 16}, - &versionInfo{17, L, 28, 1, 107, 5, 108}, - &versionInfo{17, M, 28, 10, 46, 1, 47}, - &versionInfo{17, Q, 28, 1, 22, 15, 23}, - &versionInfo{17, H, 28, 2, 14, 17, 15}, - &versionInfo{18, L, 30, 5, 120, 1, 121}, - &versionInfo{18, M, 26, 9, 43, 4, 44}, - &versionInfo{18, Q, 28, 17, 22, 1, 23}, - &versionInfo{18, H, 28, 2, 14, 19, 15}, - &versionInfo{19, L, 28, 3, 113, 4, 114}, - &versionInfo{19, M, 26, 3, 44, 11, 45}, - &versionInfo{19, Q, 26, 17, 21, 4, 22}, - &versionInfo{19, H, 26, 9, 13, 16, 14}, - &versionInfo{20, L, 28, 3, 107, 5, 108}, - &versionInfo{20, M, 26, 3, 41, 13, 42}, - &versionInfo{20, Q, 30, 15, 24, 5, 25}, - &versionInfo{20, H, 28, 15, 15, 10, 16}, - &versionInfo{21, L, 28, 4, 116, 4, 117}, - &versionInfo{21, M, 26, 17, 42, 0, 0}, - &versionInfo{21, Q, 28, 17, 22, 6, 23}, - &versionInfo{21, H, 30, 19, 16, 6, 17}, - &versionInfo{22, L, 28, 2, 111, 7, 112}, - &versionInfo{22, M, 28, 17, 46, 0, 0}, - &versionInfo{22, Q, 30, 7, 24, 16, 25}, - &versionInfo{22, H, 24, 34, 13, 0, 0}, - &versionInfo{23, L, 30, 4, 121, 5, 122}, - &versionInfo{23, M, 28, 4, 47, 14, 48}, - &versionInfo{23, Q, 30, 11, 24, 14, 25}, - &versionInfo{23, H, 30, 16, 15, 14, 16}, - &versionInfo{24, L, 30, 6, 117, 4, 118}, - &versionInfo{24, M, 28, 6, 45, 14, 46}, - &versionInfo{24, Q, 30, 11, 24, 16, 25}, - &versionInfo{24, H, 30, 30, 16, 2, 17}, - &versionInfo{25, L, 26, 8, 106, 4, 107}, - &versionInfo{25, M, 28, 8, 47, 13, 48}, - &versionInfo{25, Q, 30, 7, 24, 22, 25}, - &versionInfo{25, H, 30, 22, 15, 13, 16}, - &versionInfo{26, L, 28, 10, 114, 2, 115}, - &versionInfo{26, M, 28, 19, 46, 4, 47}, - &versionInfo{26, Q, 28, 28, 22, 6, 23}, - &versionInfo{26, H, 30, 33, 16, 4, 17}, - &versionInfo{27, L, 30, 8, 122, 4, 123}, - &versionInfo{27, M, 28, 22, 45, 3, 46}, - &versionInfo{27, Q, 30, 8, 23, 26, 24}, - &versionInfo{27, H, 30, 12, 15, 28, 16}, - &versionInfo{28, L, 30, 3, 117, 10, 118}, - &versionInfo{28, M, 28, 3, 45, 23, 46}, - &versionInfo{28, Q, 30, 4, 24, 31, 25}, - &versionInfo{28, H, 30, 11, 15, 31, 16}, - &versionInfo{29, L, 30, 7, 116, 7, 117}, - &versionInfo{29, M, 28, 21, 45, 7, 46}, - &versionInfo{29, Q, 30, 1, 23, 37, 24}, - &versionInfo{29, H, 30, 19, 15, 26, 16}, - &versionInfo{30, L, 30, 5, 115, 10, 116}, - &versionInfo{30, M, 28, 19, 47, 10, 48}, - &versionInfo{30, Q, 30, 15, 24, 25, 25}, - &versionInfo{30, H, 30, 23, 15, 25, 16}, - &versionInfo{31, L, 30, 13, 115, 3, 116}, - &versionInfo{31, M, 28, 2, 46, 29, 47}, - &versionInfo{31, Q, 30, 42, 24, 1, 25}, - &versionInfo{31, H, 30, 23, 15, 28, 16}, - &versionInfo{32, L, 30, 17, 115, 0, 0}, - &versionInfo{32, M, 28, 10, 46, 23, 47}, - &versionInfo{32, Q, 30, 10, 24, 35, 25}, - &versionInfo{32, H, 30, 19, 15, 35, 16}, - &versionInfo{33, L, 30, 17, 115, 1, 116}, - &versionInfo{33, M, 28, 14, 46, 21, 47}, - &versionInfo{33, Q, 30, 29, 24, 19, 25}, - &versionInfo{33, H, 30, 11, 15, 46, 16}, - &versionInfo{34, L, 30, 13, 115, 6, 116}, - &versionInfo{34, M, 28, 14, 46, 23, 47}, - &versionInfo{34, Q, 30, 44, 24, 7, 25}, - &versionInfo{34, H, 30, 59, 16, 1, 17}, - &versionInfo{35, L, 30, 12, 121, 7, 122}, - &versionInfo{35, M, 28, 12, 47, 26, 48}, - &versionInfo{35, Q, 30, 39, 24, 14, 25}, - &versionInfo{35, H, 30, 22, 15, 41, 16}, - &versionInfo{36, L, 30, 6, 121, 14, 122}, - &versionInfo{36, M, 28, 6, 47, 34, 48}, - &versionInfo{36, Q, 30, 46, 24, 10, 25}, - &versionInfo{36, H, 30, 2, 15, 64, 16}, - &versionInfo{37, L, 30, 17, 122, 4, 123}, - &versionInfo{37, M, 28, 29, 46, 14, 47}, - &versionInfo{37, Q, 30, 49, 24, 10, 25}, - &versionInfo{37, H, 30, 24, 15, 46, 16}, - &versionInfo{38, L, 30, 4, 122, 18, 123}, - &versionInfo{38, M, 28, 13, 46, 32, 47}, - &versionInfo{38, Q, 30, 48, 24, 14, 25}, - &versionInfo{38, H, 30, 42, 15, 32, 16}, - &versionInfo{39, L, 30, 20, 117, 4, 118}, - &versionInfo{39, M, 28, 40, 47, 7, 48}, - &versionInfo{39, Q, 30, 43, 24, 22, 25}, - &versionInfo{39, H, 30, 10, 15, 67, 16}, - &versionInfo{40, L, 30, 19, 118, 6, 119}, - &versionInfo{40, M, 28, 18, 47, 31, 48}, - &versionInfo{40, Q, 30, 34, 24, 34, 25}, - &versionInfo{40, H, 30, 20, 15, 61, 16}, -} - -func (vi *versionInfo) totalDataBytes() int { - g1Data := int(vi.NumberOfBlocksInGroup1) * int(vi.DataCodeWordsPerBlockInGroup1) - g2Data := int(vi.NumberOfBlocksInGroup2) * int(vi.DataCodeWordsPerBlockInGroup2) - return (g1Data + g2Data) -} - -func (vi *versionInfo) charCountBits(m encodingMode) byte { - switch m { - case numericMode: - if vi.Version < 10 { - return 10 - } else if vi.Version < 27 { - return 12 - } - return 14 - - case alphaNumericMode: - if vi.Version < 10 { - return 9 - } else if vi.Version < 27 { - return 11 - } - return 13 - - case byteMode: - if vi.Version < 10 { - return 8 - } - return 16 - - case kanjiMode: - if vi.Version < 10 { - return 8 - } else if vi.Version < 27 { - return 10 - } - return 12 - default: - return 0 - } -} - -func (vi *versionInfo) modulWidth() int { - return ((int(vi.Version) - 1) * 4) + 21 -} - -func (vi *versionInfo) alignmentPatternPlacements() []int { - if vi.Version == 1 { - return make([]int, 0) - } - - first := 6 - last := vi.modulWidth() - 7 - space := float64(last - first) - count := int(math.Ceil(space/28)) + 1 - - result := make([]int, count) - result[0] = first - result[len(result)-1] = last - if count > 2 { - step := int(math.Ceil(float64(last-first) / float64(count-1))) - if step%2 == 1 { - frac := float64(last-first) / float64(count-1) - _, x := math.Modf(frac) - if x >= 0.5 { - frac = math.Ceil(frac) - } else { - frac = math.Floor(frac) - } - - if int(frac)%2 == 0 { - step-- - } else { - step++ - } - } - - for i := 1; i <= count-2; i++ { - result[i] = last - (step * (count - 1 - i)) - } - } - - return result -} - -func findSmallestVersionInfo(ecl ErrorCorrectionLevel, mode encodingMode, dataBits int) *versionInfo { - dataBits = dataBits + 4 // mode indicator - for _, vi := range versionInfos { - if vi.Level == ecl { - if (vi.totalDataBytes() * 8) >= (dataBits + int(vi.charCountBits(mode))) { - return vi - } - } - } - return nil -} diff --git a/vendor/github.com/boombuler/barcode/scaledbarcode.go b/vendor/github.com/boombuler/barcode/scaledbarcode.go deleted file mode 100644 index 152b180..0000000 --- a/vendor/github.com/boombuler/barcode/scaledbarcode.go +++ /dev/null @@ -1,134 +0,0 @@ -package barcode - -import ( - "errors" - "fmt" - "image" - "image/color" - "math" -) - -type wrapFunc func(x, y int) color.Color - -type scaledBarcode struct { - wrapped Barcode - wrapperFunc wrapFunc - rect image.Rectangle -} - -type intCSscaledBC struct { - scaledBarcode -} - -func (bc *scaledBarcode) Content() string { - return bc.wrapped.Content() -} - -func (bc *scaledBarcode) Metadata() Metadata { - return bc.wrapped.Metadata() -} - -func (bc *scaledBarcode) ColorModel() color.Model { - return bc.wrapped.ColorModel() -} - -func (bc *scaledBarcode) Bounds() image.Rectangle { - return bc.rect -} - -func (bc *scaledBarcode) At(x, y int) color.Color { - return bc.wrapperFunc(x, y) -} - -func (bc *intCSscaledBC) CheckSum() int { - if cs, ok := bc.wrapped.(BarcodeIntCS); ok { - return cs.CheckSum() - } - return 0 -} - -// Scale returns a resized barcode with the given width and height. -func Scale(bc Barcode, width, height int) (Barcode, error) { - switch bc.Metadata().Dimensions { - case 1: - return scale1DCode(bc, width, height) - case 2: - return scale2DCode(bc, width, height) - } - - return nil, errors.New("unsupported barcode format") -} - -func newScaledBC(wrapped Barcode, wrapperFunc wrapFunc, rect image.Rectangle) Barcode { - result := &scaledBarcode{ - wrapped: wrapped, - wrapperFunc: wrapperFunc, - rect: rect, - } - - if _, ok := wrapped.(BarcodeIntCS); ok { - return &intCSscaledBC{*result} - } - return result -} - -func scale2DCode(bc Barcode, width, height int) (Barcode, error) { - orgBounds := bc.Bounds() - orgWidth := orgBounds.Max.X - orgBounds.Min.X - orgHeight := orgBounds.Max.Y - orgBounds.Min.Y - - factor := int(math.Min(float64(width)/float64(orgWidth), float64(height)/float64(orgHeight))) - if factor <= 0 { - return nil, fmt.Errorf("can not scale barcode to an image smaller than %dx%d", orgWidth, orgHeight) - } - - offsetX := (width - (orgWidth * factor)) / 2 - offsetY := (height - (orgHeight * factor)) / 2 - - wrap := func(x, y int) color.Color { - if x < offsetX || y < offsetY { - return color.White - } - x = (x - offsetX) / factor - y = (y - offsetY) / factor - if x >= orgWidth || y >= orgHeight { - return color.White - } - return bc.At(x, y) - } - - return newScaledBC( - bc, - wrap, - image.Rect(0, 0, width, height), - ), nil -} - -func scale1DCode(bc Barcode, width, height int) (Barcode, error) { - orgBounds := bc.Bounds() - orgWidth := orgBounds.Max.X - orgBounds.Min.X - factor := int(float64(width) / float64(orgWidth)) - - if factor <= 0 { - return nil, fmt.Errorf("can not scale barcode to an image smaller than %dx1", orgWidth) - } - offsetX := (width - (orgWidth * factor)) / 2 - - wrap := func(x, y int) color.Color { - if x < offsetX { - return color.White - } - x = (x - offsetX) / factor - - if x >= orgWidth { - return color.White - } - return bc.At(x, 0) - } - - return newScaledBC( - bc, - wrap, - image.Rect(0, 0, width, height), - ), nil -} diff --git a/vendor/github.com/boombuler/barcode/utils/base1dcode.go b/vendor/github.com/boombuler/barcode/utils/base1dcode.go deleted file mode 100644 index 75e5004..0000000 --- a/vendor/github.com/boombuler/barcode/utils/base1dcode.go +++ /dev/null @@ -1,57 +0,0 @@ -// Package utils contain some utilities which are needed to create barcodes -package utils - -import ( - "image" - "image/color" - - "github.com/boombuler/barcode" -) - -type base1DCode struct { - *BitList - kind string - content string -} - -type base1DCodeIntCS struct { - base1DCode - checksum int -} - -func (c *base1DCode) Content() string { - return c.content -} - -func (c *base1DCode) Metadata() barcode.Metadata { - return barcode.Metadata{c.kind, 1} -} - -func (c *base1DCode) ColorModel() color.Model { - return color.Gray16Model -} - -func (c *base1DCode) Bounds() image.Rectangle { - return image.Rect(0, 0, c.Len(), 1) -} - -func (c *base1DCode) At(x, y int) color.Color { - if c.GetBit(x) { - return color.Black - } - return color.White -} - -func (c *base1DCodeIntCS) CheckSum() int { - return c.checksum -} - -// New1DCode creates a new 1D barcode where the bars are represented by the bits in the bars BitList -func New1DCodeIntCheckSum(codeKind, content string, bars *BitList, checksum int) barcode.BarcodeIntCS { - return &base1DCodeIntCS{base1DCode{bars, codeKind, content}, checksum} -} - -// New1DCode creates a new 1D barcode where the bars are represented by the bits in the bars BitList -func New1DCode(codeKind, content string, bars *BitList) barcode.Barcode { - return &base1DCode{bars, codeKind, content} -} diff --git a/vendor/github.com/boombuler/barcode/utils/bitlist.go b/vendor/github.com/boombuler/barcode/utils/bitlist.go deleted file mode 100644 index bb05e53..0000000 --- a/vendor/github.com/boombuler/barcode/utils/bitlist.go +++ /dev/null @@ -1,119 +0,0 @@ -package utils - -// BitList is a list that contains bits -type BitList struct { - count int - data []int32 -} - -// NewBitList returns a new BitList with the given length -// all bits are initialize with false -func NewBitList(capacity int) *BitList { - bl := new(BitList) - bl.count = capacity - x := 0 - if capacity%32 != 0 { - x = 1 - } - bl.data = make([]int32, capacity/32+x) - return bl -} - -// Len returns the number of contained bits -func (bl *BitList) Len() int { - return bl.count -} - -func (bl *BitList) grow() { - growBy := len(bl.data) - if growBy < 128 { - growBy = 128 - } else if growBy >= 1024 { - growBy = 1024 - } - - nd := make([]int32, len(bl.data)+growBy) - copy(nd, bl.data) - bl.data = nd -} - -// AddBit appends the given bits to the end of the list -func (bl *BitList) AddBit(bits ...bool) { - for _, bit := range bits { - itmIndex := bl.count / 32 - for itmIndex >= len(bl.data) { - bl.grow() - } - bl.SetBit(bl.count, bit) - bl.count++ - } -} - -// SetBit sets the bit at the given index to the given value -func (bl *BitList) SetBit(index int, value bool) { - itmIndex := index / 32 - itmBitShift := 31 - (index % 32) - if value { - bl.data[itmIndex] = bl.data[itmIndex] | 1<> uint(itmBitShift)) & 1) == 1 -} - -// AddByte appends all 8 bits of the given byte to the end of the list -func (bl *BitList) AddByte(b byte) { - for i := 7; i >= 0; i-- { - bl.AddBit(((b >> uint(i)) & 1) == 1) - } -} - -// AddBits appends the last (LSB) 'count' bits of 'b' the the end of the list -func (bl *BitList) AddBits(b int, count byte) { - for i := int(count) - 1; i >= 0; i-- { - bl.AddBit(((b >> uint(i)) & 1) == 1) - } -} - -// GetBytes returns all bits of the BitList as a []byte -func (bl *BitList) GetBytes() []byte { - len := bl.count >> 3 - if (bl.count % 8) != 0 { - len++ - } - result := make([]byte, len) - for i := 0; i < len; i++ { - shift := (3 - (i % 4)) * 8 - result[i] = (byte)((bl.data[i/4] >> uint(shift)) & 0xFF) - } - return result -} - -// IterateBytes iterates through all bytes contained in the BitList -func (bl *BitList) IterateBytes() <-chan byte { - res := make(chan byte) - - go func() { - c := bl.count - shift := 24 - i := 0 - for c > 0 { - res <- byte((bl.data[i] >> uint(shift)) & 0xFF) - shift -= 8 - if shift < 0 { - shift = 24 - i++ - } - c -= 8 - } - close(res) - }() - - return res -} diff --git a/vendor/github.com/boombuler/barcode/utils/galoisfield.go b/vendor/github.com/boombuler/barcode/utils/galoisfield.go deleted file mode 100644 index 68726fb..0000000 --- a/vendor/github.com/boombuler/barcode/utils/galoisfield.go +++ /dev/null @@ -1,65 +0,0 @@ -package utils - -// GaloisField encapsulates galois field arithmetics -type GaloisField struct { - Size int - Base int - ALogTbl []int - LogTbl []int -} - -// NewGaloisField creates a new galois field -func NewGaloisField(pp, fieldSize, b int) *GaloisField { - result := new(GaloisField) - - result.Size = fieldSize - result.Base = b - result.ALogTbl = make([]int, fieldSize) - result.LogTbl = make([]int, fieldSize) - - x := 1 - for i := 0; i < fieldSize; i++ { - result.ALogTbl[i] = x - x = x * 2 - if x >= fieldSize { - x = (x ^ pp) & (fieldSize - 1) - } - } - - for i := 0; i < fieldSize; i++ { - result.LogTbl[result.ALogTbl[i]] = int(i) - } - - return result -} - -func (gf *GaloisField) Zero() *GFPoly { - return NewGFPoly(gf, []int{0}) -} - -// AddOrSub add or substract two numbers -func (gf *GaloisField) AddOrSub(a, b int) int { - return a ^ b -} - -// Multiply multiplys two numbers -func (gf *GaloisField) Multiply(a, b int) int { - if a == 0 || b == 0 { - return 0 - } - return gf.ALogTbl[(gf.LogTbl[a]+gf.LogTbl[b])%(gf.Size-1)] -} - -// Divide divides two numbers -func (gf *GaloisField) Divide(a, b int) int { - if b == 0 { - panic("divide by zero") - } else if a == 0 { - return 0 - } - return gf.ALogTbl[(gf.LogTbl[a]-gf.LogTbl[b])%(gf.Size-1)] -} - -func (gf *GaloisField) Invers(num int) int { - return gf.ALogTbl[(gf.Size-1)-gf.LogTbl[num]] -} diff --git a/vendor/github.com/boombuler/barcode/utils/gfpoly.go b/vendor/github.com/boombuler/barcode/utils/gfpoly.go deleted file mode 100644 index c56bb40..0000000 --- a/vendor/github.com/boombuler/barcode/utils/gfpoly.go +++ /dev/null @@ -1,103 +0,0 @@ -package utils - -type GFPoly struct { - gf *GaloisField - Coefficients []int -} - -func (gp *GFPoly) Degree() int { - return len(gp.Coefficients) - 1 -} - -func (gp *GFPoly) Zero() bool { - return gp.Coefficients[0] == 0 -} - -// GetCoefficient returns the coefficient of x ^ degree -func (gp *GFPoly) GetCoefficient(degree int) int { - return gp.Coefficients[gp.Degree()-degree] -} - -func (gp *GFPoly) AddOrSubstract(other *GFPoly) *GFPoly { - if gp.Zero() { - return other - } else if other.Zero() { - return gp - } - smallCoeff := gp.Coefficients - largeCoeff := other.Coefficients - if len(smallCoeff) > len(largeCoeff) { - largeCoeff, smallCoeff = smallCoeff, largeCoeff - } - sumDiff := make([]int, len(largeCoeff)) - lenDiff := len(largeCoeff) - len(smallCoeff) - copy(sumDiff, largeCoeff[:lenDiff]) - for i := lenDiff; i < len(largeCoeff); i++ { - sumDiff[i] = int(gp.gf.AddOrSub(int(smallCoeff[i-lenDiff]), int(largeCoeff[i]))) - } - return NewGFPoly(gp.gf, sumDiff) -} - -func (gp *GFPoly) MultByMonominal(degree int, coeff int) *GFPoly { - if coeff == 0 { - return gp.gf.Zero() - } - size := len(gp.Coefficients) - result := make([]int, size+degree) - for i := 0; i < size; i++ { - result[i] = int(gp.gf.Multiply(int(gp.Coefficients[i]), int(coeff))) - } - return NewGFPoly(gp.gf, result) -} - -func (gp *GFPoly) Multiply(other *GFPoly) *GFPoly { - if gp.Zero() || other.Zero() { - return gp.gf.Zero() - } - aCoeff := gp.Coefficients - aLen := len(aCoeff) - bCoeff := other.Coefficients - bLen := len(bCoeff) - product := make([]int, aLen+bLen-1) - for i := 0; i < aLen; i++ { - ac := int(aCoeff[i]) - for j := 0; j < bLen; j++ { - bc := int(bCoeff[j]) - product[i+j] = int(gp.gf.AddOrSub(int(product[i+j]), gp.gf.Multiply(ac, bc))) - } - } - return NewGFPoly(gp.gf, product) -} - -func (gp *GFPoly) Divide(other *GFPoly) (quotient *GFPoly, remainder *GFPoly) { - quotient = gp.gf.Zero() - remainder = gp - fld := gp.gf - denomLeadTerm := other.GetCoefficient(other.Degree()) - inversDenomLeadTerm := fld.Invers(int(denomLeadTerm)) - for remainder.Degree() >= other.Degree() && !remainder.Zero() { - degreeDiff := remainder.Degree() - other.Degree() - scale := int(fld.Multiply(int(remainder.GetCoefficient(remainder.Degree())), inversDenomLeadTerm)) - term := other.MultByMonominal(degreeDiff, scale) - itQuot := NewMonominalPoly(fld, degreeDiff, scale) - quotient = quotient.AddOrSubstract(itQuot) - remainder = remainder.AddOrSubstract(term) - } - return -} - -func NewMonominalPoly(field *GaloisField, degree int, coeff int) *GFPoly { - if coeff == 0 { - return field.Zero() - } - result := make([]int, degree+1) - result[0] = coeff - return NewGFPoly(field, result) -} - -func NewGFPoly(field *GaloisField, coefficients []int) *GFPoly { - for len(coefficients) > 1 && coefficients[0] == 0 { - coefficients = coefficients[1:] - } - return &GFPoly{field, coefficients} -} diff --git a/vendor/github.com/boombuler/barcode/utils/reedsolomon.go b/vendor/github.com/boombuler/barcode/utils/reedsolomon.go deleted file mode 100644 index 53af91a..0000000 --- a/vendor/github.com/boombuler/barcode/utils/reedsolomon.go +++ /dev/null @@ -1,44 +0,0 @@ -package utils - -import ( - "sync" -) - -type ReedSolomonEncoder struct { - gf *GaloisField - polynomes []*GFPoly - m *sync.Mutex -} - -func NewReedSolomonEncoder(gf *GaloisField) *ReedSolomonEncoder { - return &ReedSolomonEncoder{ - gf, []*GFPoly{NewGFPoly(gf, []int{1})}, new(sync.Mutex), - } -} - -func (rs *ReedSolomonEncoder) getPolynomial(degree int) *GFPoly { - rs.m.Lock() - defer rs.m.Unlock() - - if degree >= len(rs.polynomes) { - last := rs.polynomes[len(rs.polynomes)-1] - for d := len(rs.polynomes); d <= degree; d++ { - next := last.Multiply(NewGFPoly(rs.gf, []int{1, rs.gf.ALogTbl[d-1+rs.gf.Base]})) - rs.polynomes = append(rs.polynomes, next) - last = next - } - } - return rs.polynomes[degree] -} - -func (rs *ReedSolomonEncoder) Encode(data []int, eccCount int) []int { - generator := rs.getPolynomial(eccCount) - info := NewGFPoly(rs.gf, data) - info = info.MultByMonominal(eccCount, 1) - _, remainder := info.Divide(generator) - - result := make([]int, eccCount) - numZero := int(eccCount) - len(remainder.Coefficients) - copy(result[numZero:], remainder.Coefficients) - return result -} diff --git a/vendor/github.com/boombuler/barcode/utils/runeint.go b/vendor/github.com/boombuler/barcode/utils/runeint.go deleted file mode 100644 index d2e5e61..0000000 --- a/vendor/github.com/boombuler/barcode/utils/runeint.go +++ /dev/null @@ -1,19 +0,0 @@ -package utils - -// RuneToInt converts a rune between '0' and '9' to an integer between 0 and 9 -// If the rune is outside of this range -1 is returned. -func RuneToInt(r rune) int { - if r >= '0' && r <= '9' { - return int(r - '0') - } - return -1 -} - -// IntToRune converts a digit 0 - 9 to the rune '0' - '9'. If the given int is outside -// of this range 'F' is returned! -func IntToRune(i int) rune { - if i >= 0 && i <= 9 { - return rune(i + '0') - } - return 'F' -} diff --git a/vendor/github.com/golang/snappy/.gitignore b/vendor/github.com/golang/snappy/.gitignore deleted file mode 100644 index 042091d..0000000 --- a/vendor/github.com/golang/snappy/.gitignore +++ /dev/null @@ -1,16 +0,0 @@ -cmd/snappytool/snappytool -testdata/bench - -# These explicitly listed benchmark data files are for an obsolete version of -# snappy_test.go. -testdata/alice29.txt -testdata/asyoulik.txt -testdata/fireworks.jpeg -testdata/geo.protodata -testdata/html -testdata/html_x_4 -testdata/kppkn.gtb -testdata/lcet10.txt -testdata/paper-100k.pdf -testdata/plrabn12.txt -testdata/urls.10K diff --git a/vendor/github.com/golang/snappy/AUTHORS b/vendor/github.com/golang/snappy/AUTHORS deleted file mode 100644 index bcfa195..0000000 --- a/vendor/github.com/golang/snappy/AUTHORS +++ /dev/null @@ -1,15 +0,0 @@ -# This is the official list of Snappy-Go authors for copyright purposes. -# This file is distinct from the CONTRIBUTORS files. -# See the latter for an explanation. - -# Names should be added to this file as -# Name or Organization -# The email address is not required for organizations. - -# Please keep the list sorted. - -Damian Gryski -Google Inc. -Jan Mercl <0xjnml@gmail.com> -Rodolfo Carvalho -Sebastien Binet diff --git a/vendor/github.com/golang/snappy/CONTRIBUTORS b/vendor/github.com/golang/snappy/CONTRIBUTORS deleted file mode 100644 index 931ae31..0000000 --- a/vendor/github.com/golang/snappy/CONTRIBUTORS +++ /dev/null @@ -1,37 +0,0 @@ -# This is the official list of people who can contribute -# (and typically have contributed) code to the Snappy-Go repository. -# The AUTHORS file lists the copyright holders; this file -# lists people. For example, Google employees are listed here -# but not in AUTHORS, because Google holds the copyright. -# -# The submission process automatically checks to make sure -# that people submitting code are listed in this file (by email address). -# -# Names should be added to this file only after verifying that -# the individual or the individual's organization has agreed to -# the appropriate Contributor License Agreement, found here: -# -# http://code.google.com/legal/individual-cla-v1.0.html -# http://code.google.com/legal/corporate-cla-v1.0.html -# -# The agreement for individuals can be filled out on the web. -# -# When adding J Random Contributor's name to this file, -# either J's name or J's organization's name should be -# added to the AUTHORS file, depending on whether the -# individual or corporate CLA was used. - -# Names should be added to this file like so: -# Name - -# Please keep the list sorted. - -Damian Gryski -Jan Mercl <0xjnml@gmail.com> -Kai Backman -Marc-Antoine Ruel -Nigel Tao -Rob Pike -Rodolfo Carvalho -Russ Cox -Sebastien Binet diff --git a/vendor/github.com/golang/snappy/LICENSE b/vendor/github.com/golang/snappy/LICENSE deleted file mode 100644 index 6050c10..0000000 --- a/vendor/github.com/golang/snappy/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2011 The Snappy-Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/golang/snappy/README b/vendor/github.com/golang/snappy/README deleted file mode 100644 index cea1287..0000000 --- a/vendor/github.com/golang/snappy/README +++ /dev/null @@ -1,107 +0,0 @@ -The Snappy compression format in the Go programming language. - -To download and install from source: -$ go get github.com/golang/snappy - -Unless otherwise noted, the Snappy-Go source files are distributed -under the BSD-style license found in the LICENSE file. - - - -Benchmarks. - -The golang/snappy benchmarks include compressing (Z) and decompressing (U) ten -or so files, the same set used by the C++ Snappy code (github.com/google/snappy -and note the "google", not "golang"). On an "Intel(R) Core(TM) i7-3770 CPU @ -3.40GHz", Go's GOARCH=amd64 numbers as of 2016-05-29: - -"go test -test.bench=." - -_UFlat0-8 2.19GB/s ± 0% html -_UFlat1-8 1.41GB/s ± 0% urls -_UFlat2-8 23.5GB/s ± 2% jpg -_UFlat3-8 1.91GB/s ± 0% jpg_200 -_UFlat4-8 14.0GB/s ± 1% pdf -_UFlat5-8 1.97GB/s ± 0% html4 -_UFlat6-8 814MB/s ± 0% txt1 -_UFlat7-8 785MB/s ± 0% txt2 -_UFlat8-8 857MB/s ± 0% txt3 -_UFlat9-8 719MB/s ± 1% txt4 -_UFlat10-8 2.84GB/s ± 0% pb -_UFlat11-8 1.05GB/s ± 0% gaviota - -_ZFlat0-8 1.04GB/s ± 0% html -_ZFlat1-8 534MB/s ± 0% urls -_ZFlat2-8 15.7GB/s ± 1% jpg -_ZFlat3-8 740MB/s ± 3% jpg_200 -_ZFlat4-8 9.20GB/s ± 1% pdf -_ZFlat5-8 991MB/s ± 0% html4 -_ZFlat6-8 379MB/s ± 0% txt1 -_ZFlat7-8 352MB/s ± 0% txt2 -_ZFlat8-8 396MB/s ± 1% txt3 -_ZFlat9-8 327MB/s ± 1% txt4 -_ZFlat10-8 1.33GB/s ± 1% pb -_ZFlat11-8 605MB/s ± 1% gaviota - - - -"go test -test.bench=. -tags=noasm" - -_UFlat0-8 621MB/s ± 2% html -_UFlat1-8 494MB/s ± 1% urls -_UFlat2-8 23.2GB/s ± 1% jpg -_UFlat3-8 1.12GB/s ± 1% jpg_200 -_UFlat4-8 4.35GB/s ± 1% pdf -_UFlat5-8 609MB/s ± 0% html4 -_UFlat6-8 296MB/s ± 0% txt1 -_UFlat7-8 288MB/s ± 0% txt2 -_UFlat8-8 309MB/s ± 1% txt3 -_UFlat9-8 280MB/s ± 1% txt4 -_UFlat10-8 753MB/s ± 0% pb -_UFlat11-8 400MB/s ± 0% gaviota - -_ZFlat0-8 409MB/s ± 1% html -_ZFlat1-8 250MB/s ± 1% urls -_ZFlat2-8 12.3GB/s ± 1% jpg -_ZFlat3-8 132MB/s ± 0% jpg_200 -_ZFlat4-8 2.92GB/s ± 0% pdf -_ZFlat5-8 405MB/s ± 1% html4 -_ZFlat6-8 179MB/s ± 1% txt1 -_ZFlat7-8 170MB/s ± 1% txt2 -_ZFlat8-8 189MB/s ± 1% txt3 -_ZFlat9-8 164MB/s ± 1% txt4 -_ZFlat10-8 479MB/s ± 1% pb -_ZFlat11-8 270MB/s ± 1% gaviota - - - -For comparison (Go's encoded output is byte-for-byte identical to C++'s), here -are the numbers from C++ Snappy's - -make CXXFLAGS="-O2 -DNDEBUG -g" clean snappy_unittest.log && cat snappy_unittest.log - -BM_UFlat/0 2.4GB/s html -BM_UFlat/1 1.4GB/s urls -BM_UFlat/2 21.8GB/s jpg -BM_UFlat/3 1.5GB/s jpg_200 -BM_UFlat/4 13.3GB/s pdf -BM_UFlat/5 2.1GB/s html4 -BM_UFlat/6 1.0GB/s txt1 -BM_UFlat/7 959.4MB/s txt2 -BM_UFlat/8 1.0GB/s txt3 -BM_UFlat/9 864.5MB/s txt4 -BM_UFlat/10 2.9GB/s pb -BM_UFlat/11 1.2GB/s gaviota - -BM_ZFlat/0 944.3MB/s html (22.31 %) -BM_ZFlat/1 501.6MB/s urls (47.78 %) -BM_ZFlat/2 14.3GB/s jpg (99.95 %) -BM_ZFlat/3 538.3MB/s jpg_200 (73.00 %) -BM_ZFlat/4 8.3GB/s pdf (83.30 %) -BM_ZFlat/5 903.5MB/s html4 (22.52 %) -BM_ZFlat/6 336.0MB/s txt1 (57.88 %) -BM_ZFlat/7 312.3MB/s txt2 (61.91 %) -BM_ZFlat/8 353.1MB/s txt3 (54.99 %) -BM_ZFlat/9 289.9MB/s txt4 (66.26 %) -BM_ZFlat/10 1.2GB/s pb (19.68 %) -BM_ZFlat/11 527.4MB/s gaviota (37.72 %) diff --git a/vendor/github.com/golang/snappy/decode.go b/vendor/github.com/golang/snappy/decode.go deleted file mode 100644 index 72efb03..0000000 --- a/vendor/github.com/golang/snappy/decode.go +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright 2011 The Snappy-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 snappy - -import ( - "encoding/binary" - "errors" - "io" -) - -var ( - // ErrCorrupt reports that the input is invalid. - ErrCorrupt = errors.New("snappy: corrupt input") - // ErrTooLarge reports that the uncompressed length is too large. - ErrTooLarge = errors.New("snappy: decoded block is too large") - // ErrUnsupported reports that the input isn't supported. - ErrUnsupported = errors.New("snappy: unsupported input") - - errUnsupportedLiteralLength = errors.New("snappy: unsupported literal length") -) - -// DecodedLen returns the length of the decoded block. -func DecodedLen(src []byte) (int, error) { - v, _, err := decodedLen(src) - return v, err -} - -// decodedLen returns the length of the decoded block and the number of bytes -// that the length header occupied. -func decodedLen(src []byte) (blockLen, headerLen int, err error) { - v, n := binary.Uvarint(src) - if n <= 0 || v > 0xffffffff { - return 0, 0, ErrCorrupt - } - - const wordSize = 32 << (^uint(0) >> 32 & 1) - if wordSize == 32 && v > 0x7fffffff { - return 0, 0, ErrTooLarge - } - return int(v), n, nil -} - -const ( - decodeErrCodeCorrupt = 1 - decodeErrCodeUnsupportedLiteralLength = 2 -) - -// Decode returns the decoded form of src. The returned slice may be a sub- -// slice of dst if dst was large enough to hold the entire decoded block. -// Otherwise, a newly allocated slice will be returned. -// -// The dst and src must not overlap. It is valid to pass a nil dst. -func Decode(dst, src []byte) ([]byte, error) { - dLen, s, err := decodedLen(src) - if err != nil { - return nil, err - } - if dLen <= len(dst) { - dst = dst[:dLen] - } else { - dst = make([]byte, dLen) - } - switch decode(dst, src[s:]) { - case 0: - return dst, nil - case decodeErrCodeUnsupportedLiteralLength: - return nil, errUnsupportedLiteralLength - } - return nil, ErrCorrupt -} - -// NewReader returns a new Reader that decompresses from r, using the framing -// format described at -// https://github.com/google/snappy/blob/master/framing_format.txt -func NewReader(r io.Reader) *Reader { - return &Reader{ - r: r, - decoded: make([]byte, maxBlockSize), - buf: make([]byte, maxEncodedLenOfMaxBlockSize+checksumSize), - } -} - -// Reader is an io.Reader that can read Snappy-compressed bytes. -type Reader struct { - r io.Reader - err error - decoded []byte - buf []byte - // decoded[i:j] contains decoded bytes that have not yet been passed on. - i, j int - readHeader bool -} - -// Reset discards any buffered data, resets all state, and switches the Snappy -// reader to read from r. This permits reusing a Reader rather than allocating -// a new one. -func (r *Reader) Reset(reader io.Reader) { - r.r = reader - r.err = nil - r.i = 0 - r.j = 0 - r.readHeader = false -} - -func (r *Reader) readFull(p []byte, allowEOF bool) (ok bool) { - if _, r.err = io.ReadFull(r.r, p); r.err != nil { - if r.err == io.ErrUnexpectedEOF || (r.err == io.EOF && !allowEOF) { - r.err = ErrCorrupt - } - return false - } - return true -} - -// Read satisfies the io.Reader interface. -func (r *Reader) Read(p []byte) (int, error) { - if r.err != nil { - return 0, r.err - } - for { - if r.i < r.j { - n := copy(p, r.decoded[r.i:r.j]) - r.i += n - return n, nil - } - if !r.readFull(r.buf[:4], true) { - return 0, r.err - } - chunkType := r.buf[0] - if !r.readHeader { - if chunkType != chunkTypeStreamIdentifier { - r.err = ErrCorrupt - return 0, r.err - } - r.readHeader = true - } - chunkLen := int(r.buf[1]) | int(r.buf[2])<<8 | int(r.buf[3])<<16 - if chunkLen > len(r.buf) { - r.err = ErrUnsupported - return 0, r.err - } - - // The chunk types are specified at - // https://github.com/google/snappy/blob/master/framing_format.txt - switch chunkType { - case chunkTypeCompressedData: - // Section 4.2. Compressed data (chunk type 0x00). - if chunkLen < checksumSize { - r.err = ErrCorrupt - return 0, r.err - } - buf := r.buf[:chunkLen] - if !r.readFull(buf, false) { - return 0, r.err - } - checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24 - buf = buf[checksumSize:] - - n, err := DecodedLen(buf) - if err != nil { - r.err = err - return 0, r.err - } - if n > len(r.decoded) { - r.err = ErrCorrupt - return 0, r.err - } - if _, err := Decode(r.decoded, buf); err != nil { - r.err = err - return 0, r.err - } - if crc(r.decoded[:n]) != checksum { - r.err = ErrCorrupt - return 0, r.err - } - r.i, r.j = 0, n - continue - - case chunkTypeUncompressedData: - // Section 4.3. Uncompressed data (chunk type 0x01). - if chunkLen < checksumSize { - r.err = ErrCorrupt - return 0, r.err - } - buf := r.buf[:checksumSize] - if !r.readFull(buf, false) { - return 0, r.err - } - checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24 - // Read directly into r.decoded instead of via r.buf. - n := chunkLen - checksumSize - if n > len(r.decoded) { - r.err = ErrCorrupt - return 0, r.err - } - if !r.readFull(r.decoded[:n], false) { - return 0, r.err - } - if crc(r.decoded[:n]) != checksum { - r.err = ErrCorrupt - return 0, r.err - } - r.i, r.j = 0, n - continue - - case chunkTypeStreamIdentifier: - // Section 4.1. Stream identifier (chunk type 0xff). - if chunkLen != len(magicBody) { - r.err = ErrCorrupt - return 0, r.err - } - if !r.readFull(r.buf[:len(magicBody)], false) { - return 0, r.err - } - for i := 0; i < len(magicBody); i++ { - if r.buf[i] != magicBody[i] { - r.err = ErrCorrupt - return 0, r.err - } - } - continue - } - - if chunkType <= 0x7f { - // Section 4.5. Reserved unskippable chunks (chunk types 0x02-0x7f). - r.err = ErrUnsupported - return 0, r.err - } - // Section 4.4 Padding (chunk type 0xfe). - // Section 4.6. Reserved skippable chunks (chunk types 0x80-0xfd). - if !r.readFull(r.buf[:chunkLen], false) { - return 0, r.err - } - } -} diff --git a/vendor/github.com/golang/snappy/decode_amd64.go b/vendor/github.com/golang/snappy/decode_amd64.go deleted file mode 100644 index fcd192b..0000000 --- a/vendor/github.com/golang/snappy/decode_amd64.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2016 The Snappy-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 !appengine -// +build gc -// +build !noasm - -package snappy - -// decode has the same semantics as in decode_other.go. -// -//go:noescape -func decode(dst, src []byte) int diff --git a/vendor/github.com/golang/snappy/decode_amd64.s b/vendor/github.com/golang/snappy/decode_amd64.s deleted file mode 100644 index e6179f6..0000000 --- a/vendor/github.com/golang/snappy/decode_amd64.s +++ /dev/null @@ -1,490 +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. - -// +build !appengine -// +build gc -// +build !noasm - -#include "textflag.h" - -// The asm code generally follows the pure Go code in decode_other.go, except -// where marked with a "!!!". - -// func decode(dst, src []byte) int -// -// All local variables fit into registers. The non-zero stack size is only to -// spill registers and push args when issuing a CALL. The register allocation: -// - AX scratch -// - BX scratch -// - CX length or x -// - DX offset -// - SI &src[s] -// - DI &dst[d] -// + R8 dst_base -// + R9 dst_len -// + R10 dst_base + dst_len -// + R11 src_base -// + R12 src_len -// + R13 src_base + src_len -// - R14 used by doCopy -// - R15 used by doCopy -// -// The registers R8-R13 (marked with a "+") are set at the start of the -// function, and after a CALL returns, and are not otherwise modified. -// -// The d variable is implicitly DI - R8, and len(dst)-d is R10 - DI. -// The s variable is implicitly SI - R11, and len(src)-s is R13 - SI. -TEXT ·decode(SB), NOSPLIT, $48-56 - // Initialize SI, DI and R8-R13. - MOVQ dst_base+0(FP), R8 - MOVQ dst_len+8(FP), R9 - MOVQ R8, DI - MOVQ R8, R10 - ADDQ R9, R10 - MOVQ src_base+24(FP), R11 - MOVQ src_len+32(FP), R12 - MOVQ R11, SI - MOVQ R11, R13 - ADDQ R12, R13 - -loop: - // for s < len(src) - CMPQ SI, R13 - JEQ end - - // CX = uint32(src[s]) - // - // switch src[s] & 0x03 - MOVBLZX (SI), CX - MOVL CX, BX - ANDL $3, BX - CMPL BX, $1 - JAE tagCopy - - // ---------------------------------------- - // The code below handles literal tags. - - // case tagLiteral: - // x := uint32(src[s] >> 2) - // switch - SHRL $2, CX - CMPL CX, $60 - JAE tagLit60Plus - - // case x < 60: - // s++ - INCQ SI - -doLit: - // This is the end of the inner "switch", when we have a literal tag. - // - // We assume that CX == x and x fits in a uint32, where x is the variable - // used in the pure Go decode_other.go code. - - // length = int(x) + 1 - // - // Unlike the pure Go code, we don't need to check if length <= 0 because - // CX can hold 64 bits, so the increment cannot overflow. - INCQ CX - - // Prepare to check if copying length bytes will run past the end of dst or - // src. - // - // AX = len(dst) - d - // BX = len(src) - s - MOVQ R10, AX - SUBQ DI, AX - MOVQ R13, BX - SUBQ SI, BX - - // !!! Try a faster technique for short (16 or fewer bytes) copies. - // - // if length > 16 || len(dst)-d < 16 || len(src)-s < 16 { - // goto callMemmove // Fall back on calling runtime·memmove. - // } - // - // The C++ snappy code calls this TryFastAppend. It also checks len(src)-s - // against 21 instead of 16, because it cannot assume that all of its input - // is contiguous in memory and so it needs to leave enough source bytes to - // read the next tag without refilling buffers, but Go's Decode assumes - // contiguousness (the src argument is a []byte). - CMPQ CX, $16 - JGT callMemmove - CMPQ AX, $16 - JLT callMemmove - CMPQ BX, $16 - JLT callMemmove - - // !!! Implement the copy from src to dst as a 16-byte load and store. - // (Decode's documentation says that dst and src must not overlap.) - // - // This always copies 16 bytes, instead of only length bytes, but that's - // OK. If the input is a valid Snappy encoding then subsequent iterations - // will fix up the overrun. Otherwise, Decode returns a nil []byte (and a - // non-nil error), so the overrun will be ignored. - // - // Note that on amd64, it is legal and cheap to issue unaligned 8-byte or - // 16-byte loads and stores. This technique probably wouldn't be as - // effective on architectures that are fussier about alignment. - MOVOU 0(SI), X0 - MOVOU X0, 0(DI) - - // d += length - // s += length - ADDQ CX, DI - ADDQ CX, SI - JMP loop - -callMemmove: - // if length > len(dst)-d || length > len(src)-s { etc } - CMPQ CX, AX - JGT errCorrupt - CMPQ CX, BX - JGT errCorrupt - - // copy(dst[d:], src[s:s+length]) - // - // This means calling runtime·memmove(&dst[d], &src[s], length), so we push - // DI, SI and CX as arguments. Coincidentally, we also need to spill those - // three registers to the stack, to save local variables across the CALL. - MOVQ DI, 0(SP) - MOVQ SI, 8(SP) - MOVQ CX, 16(SP) - MOVQ DI, 24(SP) - MOVQ SI, 32(SP) - MOVQ CX, 40(SP) - CALL runtime·memmove(SB) - - // Restore local variables: unspill registers from the stack and - // re-calculate R8-R13. - MOVQ 24(SP), DI - MOVQ 32(SP), SI - MOVQ 40(SP), CX - MOVQ dst_base+0(FP), R8 - MOVQ dst_len+8(FP), R9 - MOVQ R8, R10 - ADDQ R9, R10 - MOVQ src_base+24(FP), R11 - MOVQ src_len+32(FP), R12 - MOVQ R11, R13 - ADDQ R12, R13 - - // d += length - // s += length - ADDQ CX, DI - ADDQ CX, SI - JMP loop - -tagLit60Plus: - // !!! This fragment does the - // - // s += x - 58; if uint(s) > uint(len(src)) { etc } - // - // checks. In the asm version, we code it once instead of once per switch case. - ADDQ CX, SI - SUBQ $58, SI - MOVQ SI, BX - SUBQ R11, BX - CMPQ BX, R12 - JA errCorrupt - - // case x == 60: - CMPL CX, $61 - JEQ tagLit61 - JA tagLit62Plus - - // x = uint32(src[s-1]) - MOVBLZX -1(SI), CX - JMP doLit - -tagLit61: - // case x == 61: - // x = uint32(src[s-2]) | uint32(src[s-1])<<8 - MOVWLZX -2(SI), CX - JMP doLit - -tagLit62Plus: - CMPL CX, $62 - JA tagLit63 - - // case x == 62: - // x = uint32(src[s-3]) | uint32(src[s-2])<<8 | uint32(src[s-1])<<16 - MOVWLZX -3(SI), CX - MOVBLZX -1(SI), BX - SHLL $16, BX - ORL BX, CX - JMP doLit - -tagLit63: - // case x == 63: - // x = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24 - MOVL -4(SI), CX - JMP doLit - -// The code above handles literal tags. -// ---------------------------------------- -// The code below handles copy tags. - -tagCopy4: - // case tagCopy4: - // s += 5 - ADDQ $5, SI - - // if uint(s) > uint(len(src)) { etc } - MOVQ SI, BX - SUBQ R11, BX - CMPQ BX, R12 - JA errCorrupt - - // length = 1 + int(src[s-5])>>2 - SHRQ $2, CX - INCQ CX - - // offset = int(uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24) - MOVLQZX -4(SI), DX - JMP doCopy - -tagCopy2: - // case tagCopy2: - // s += 3 - ADDQ $3, SI - - // if uint(s) > uint(len(src)) { etc } - MOVQ SI, BX - SUBQ R11, BX - CMPQ BX, R12 - JA errCorrupt - - // length = 1 + int(src[s-3])>>2 - SHRQ $2, CX - INCQ CX - - // offset = int(uint32(src[s-2]) | uint32(src[s-1])<<8) - MOVWQZX -2(SI), DX - JMP doCopy - -tagCopy: - // We have a copy tag. We assume that: - // - BX == src[s] & 0x03 - // - CX == src[s] - CMPQ BX, $2 - JEQ tagCopy2 - JA tagCopy4 - - // case tagCopy1: - // s += 2 - ADDQ $2, SI - - // if uint(s) > uint(len(src)) { etc } - MOVQ SI, BX - SUBQ R11, BX - CMPQ BX, R12 - JA errCorrupt - - // offset = int(uint32(src[s-2])&0xe0<<3 | uint32(src[s-1])) - MOVQ CX, DX - ANDQ $0xe0, DX - SHLQ $3, DX - MOVBQZX -1(SI), BX - ORQ BX, DX - - // length = 4 + int(src[s-2])>>2&0x7 - SHRQ $2, CX - ANDQ $7, CX - ADDQ $4, CX - -doCopy: - // This is the end of the outer "switch", when we have a copy tag. - // - // We assume that: - // - CX == length && CX > 0 - // - DX == offset - - // if offset <= 0 { etc } - CMPQ DX, $0 - JLE errCorrupt - - // if d < offset { etc } - MOVQ DI, BX - SUBQ R8, BX - CMPQ BX, DX - JLT errCorrupt - - // if length > len(dst)-d { etc } - MOVQ R10, BX - SUBQ DI, BX - CMPQ CX, BX - JGT errCorrupt - - // forwardCopy(dst[d:d+length], dst[d-offset:]); d += length - // - // Set: - // - R14 = len(dst)-d - // - R15 = &dst[d-offset] - MOVQ R10, R14 - SUBQ DI, R14 - MOVQ DI, R15 - SUBQ DX, R15 - - // !!! Try a faster technique for short (16 or fewer bytes) forward copies. - // - // First, try using two 8-byte load/stores, similar to the doLit technique - // above. Even if dst[d:d+length] and dst[d-offset:] can overlap, this is - // still OK if offset >= 8. Note that this has to be two 8-byte load/stores - // and not one 16-byte load/store, and the first store has to be before the - // second load, due to the overlap if offset is in the range [8, 16). - // - // if length > 16 || offset < 8 || len(dst)-d < 16 { - // goto slowForwardCopy - // } - // copy 16 bytes - // d += length - CMPQ CX, $16 - JGT slowForwardCopy - CMPQ DX, $8 - JLT slowForwardCopy - CMPQ R14, $16 - JLT slowForwardCopy - MOVQ 0(R15), AX - MOVQ AX, 0(DI) - MOVQ 8(R15), BX - MOVQ BX, 8(DI) - ADDQ CX, DI - JMP loop - -slowForwardCopy: - // !!! If the forward copy is longer than 16 bytes, or if offset < 8, we - // can still try 8-byte load stores, provided we can overrun up to 10 extra - // bytes. As above, the overrun will be fixed up by subsequent iterations - // of the outermost loop. - // - // The C++ snappy code calls this technique IncrementalCopyFastPath. Its - // commentary says: - // - // ---- - // - // The main part of this loop is a simple copy of eight bytes at a time - // until we've copied (at least) the requested amount of bytes. However, - // if d and d-offset are less than eight bytes apart (indicating a - // repeating pattern of length < 8), we first need to expand the pattern in - // order to get the correct results. For instance, if the buffer looks like - // this, with the eight-byte and patterns marked as - // intervals: - // - // abxxxxxxxxxxxx - // [------] d-offset - // [------] d - // - // a single eight-byte copy from to will repeat the pattern - // once, after which we can move two bytes without moving : - // - // ababxxxxxxxxxx - // [------] d-offset - // [------] d - // - // and repeat the exercise until the two no longer overlap. - // - // This allows us to do very well in the special case of one single byte - // repeated many times, without taking a big hit for more general cases. - // - // The worst case of extra writing past the end of the match occurs when - // offset == 1 and length == 1; the last copy will read from byte positions - // [0..7] and write to [4..11], whereas it was only supposed to write to - // position 1. Thus, ten excess bytes. - // - // ---- - // - // That "10 byte overrun" worst case is confirmed by Go's - // TestSlowForwardCopyOverrun, which also tests the fixUpSlowForwardCopy - // and finishSlowForwardCopy algorithm. - // - // if length > len(dst)-d-10 { - // goto verySlowForwardCopy - // } - SUBQ $10, R14 - CMPQ CX, R14 - JGT verySlowForwardCopy - -makeOffsetAtLeast8: - // !!! As above, expand the pattern so that offset >= 8 and we can use - // 8-byte load/stores. - // - // for offset < 8 { - // copy 8 bytes from dst[d-offset:] to dst[d:] - // length -= offset - // d += offset - // offset += offset - // // The two previous lines together means that d-offset, and therefore - // // R15, is unchanged. - // } - CMPQ DX, $8 - JGE fixUpSlowForwardCopy - MOVQ (R15), BX - MOVQ BX, (DI) - SUBQ DX, CX - ADDQ DX, DI - ADDQ DX, DX - JMP makeOffsetAtLeast8 - -fixUpSlowForwardCopy: - // !!! Add length (which might be negative now) to d (implied by DI being - // &dst[d]) so that d ends up at the right place when we jump back to the - // top of the loop. Before we do that, though, we save DI to AX so that, if - // length is positive, copying the remaining length bytes will write to the - // right place. - MOVQ DI, AX - ADDQ CX, DI - -finishSlowForwardCopy: - // !!! Repeat 8-byte load/stores until length <= 0. Ending with a negative - // length means that we overrun, but as above, that will be fixed up by - // subsequent iterations of the outermost loop. - CMPQ CX, $0 - JLE loop - MOVQ (R15), BX - MOVQ BX, (AX) - ADDQ $8, R15 - ADDQ $8, AX - SUBQ $8, CX - JMP finishSlowForwardCopy - -verySlowForwardCopy: - // verySlowForwardCopy is a simple implementation of forward copy. In C - // parlance, this is a do/while loop instead of a while loop, since we know - // that length > 0. In Go syntax: - // - // for { - // dst[d] = dst[d - offset] - // d++ - // length-- - // if length == 0 { - // break - // } - // } - MOVB (R15), BX - MOVB BX, (DI) - INCQ R15 - INCQ DI - DECQ CX - JNZ verySlowForwardCopy - JMP loop - -// The code above handles copy tags. -// ---------------------------------------- - -end: - // This is the end of the "for s < len(src)". - // - // if d != len(dst) { etc } - CMPQ DI, R10 - JNE errCorrupt - - // return 0 - MOVQ $0, ret+48(FP) - RET - -errCorrupt: - // return decodeErrCodeCorrupt - MOVQ $1, ret+48(FP) - RET diff --git a/vendor/github.com/golang/snappy/decode_other.go b/vendor/github.com/golang/snappy/decode_other.go deleted file mode 100644 index 8c9f204..0000000 --- a/vendor/github.com/golang/snappy/decode_other.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2016 The Snappy-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 !amd64 appengine !gc noasm - -package snappy - -// decode writes the decoding of src to dst. It assumes that the varint-encoded -// length of the decompressed bytes has already been read, and that len(dst) -// equals that length. -// -// It returns 0 on success or a decodeErrCodeXxx error code on failure. -func decode(dst, src []byte) int { - var d, s, offset, length int - for s < len(src) { - switch src[s] & 0x03 { - case tagLiteral: - x := uint32(src[s] >> 2) - switch { - case x < 60: - s++ - case x == 60: - s += 2 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - x = uint32(src[s-1]) - case x == 61: - s += 3 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - x = uint32(src[s-2]) | uint32(src[s-1])<<8 - case x == 62: - s += 4 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - x = uint32(src[s-3]) | uint32(src[s-2])<<8 | uint32(src[s-1])<<16 - case x == 63: - s += 5 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - x = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24 - } - length = int(x) + 1 - if length <= 0 { - return decodeErrCodeUnsupportedLiteralLength - } - if length > len(dst)-d || length > len(src)-s { - return decodeErrCodeCorrupt - } - copy(dst[d:], src[s:s+length]) - d += length - s += length - continue - - case tagCopy1: - s += 2 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - length = 4 + int(src[s-2])>>2&0x7 - offset = int(uint32(src[s-2])&0xe0<<3 | uint32(src[s-1])) - - case tagCopy2: - s += 3 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - length = 1 + int(src[s-3])>>2 - offset = int(uint32(src[s-2]) | uint32(src[s-1])<<8) - - case tagCopy4: - s += 5 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - length = 1 + int(src[s-5])>>2 - offset = int(uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24) - } - - if offset <= 0 || d < offset || length > len(dst)-d { - return decodeErrCodeCorrupt - } - // Copy from an earlier sub-slice of dst to a later sub-slice. Unlike - // the built-in copy function, this byte-by-byte copy always runs - // forwards, even if the slices overlap. Conceptually, this is: - // - // d += forwardCopy(dst[d:d+length], dst[d-offset:]) - for end := d + length; d != end; d++ { - dst[d] = dst[d-offset] - } - } - if d != len(dst) { - return decodeErrCodeCorrupt - } - return 0 -} diff --git a/vendor/github.com/golang/snappy/encode.go b/vendor/github.com/golang/snappy/encode.go deleted file mode 100644 index 8d393e9..0000000 --- a/vendor/github.com/golang/snappy/encode.go +++ /dev/null @@ -1,285 +0,0 @@ -// Copyright 2011 The Snappy-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 snappy - -import ( - "encoding/binary" - "errors" - "io" -) - -// Encode returns the encoded form of src. The returned slice may be a sub- -// slice of dst if dst was large enough to hold the entire encoded block. -// Otherwise, a newly allocated slice will be returned. -// -// The dst and src must not overlap. It is valid to pass a nil dst. -func Encode(dst, src []byte) []byte { - if n := MaxEncodedLen(len(src)); n < 0 { - panic(ErrTooLarge) - } else if len(dst) < n { - dst = make([]byte, n) - } - - // The block starts with the varint-encoded length of the decompressed bytes. - d := binary.PutUvarint(dst, uint64(len(src))) - - for len(src) > 0 { - p := src - src = nil - if len(p) > maxBlockSize { - p, src = p[:maxBlockSize], p[maxBlockSize:] - } - if len(p) < minNonLiteralBlockSize { - d += emitLiteral(dst[d:], p) - } else { - d += encodeBlock(dst[d:], p) - } - } - return dst[:d] -} - -// inputMargin is the minimum number of extra input bytes to keep, inside -// encodeBlock's inner loop. On some architectures, this margin lets us -// implement a fast path for emitLiteral, where the copy of short (<= 16 byte) -// literals can be implemented as a single load to and store from a 16-byte -// register. That literal's actual length can be as short as 1 byte, so this -// can copy up to 15 bytes too much, but that's OK as subsequent iterations of -// the encoding loop will fix up the copy overrun, and this inputMargin ensures -// that we don't overrun the dst and src buffers. -const inputMargin = 16 - 1 - -// minNonLiteralBlockSize is the minimum size of the input to encodeBlock that -// could be encoded with a copy tag. This is the minimum with respect to the -// algorithm used by encodeBlock, not a minimum enforced by the file format. -// -// The encoded output must start with at least a 1 byte literal, as there are -// no previous bytes to copy. A minimal (1 byte) copy after that, generated -// from an emitCopy call in encodeBlock's main loop, would require at least -// another inputMargin bytes, for the reason above: we want any emitLiteral -// calls inside encodeBlock's main loop to use the fast path if possible, which -// requires being able to overrun by inputMargin bytes. Thus, -// minNonLiteralBlockSize equals 1 + 1 + inputMargin. -// -// The C++ code doesn't use this exact threshold, but it could, as discussed at -// https://groups.google.com/d/topic/snappy-compression/oGbhsdIJSJ8/discussion -// The difference between Go (2+inputMargin) and C++ (inputMargin) is purely an -// optimization. It should not affect the encoded form. This is tested by -// TestSameEncodingAsCppShortCopies. -const minNonLiteralBlockSize = 1 + 1 + inputMargin - -// MaxEncodedLen returns the maximum length of a snappy block, given its -// uncompressed length. -// -// It will return a negative value if srcLen is too large to encode. -func MaxEncodedLen(srcLen int) int { - n := uint64(srcLen) - if n > 0xffffffff { - return -1 - } - // Compressed data can be defined as: - // compressed := item* literal* - // item := literal* copy - // - // The trailing literal sequence has a space blowup of at most 62/60 - // since a literal of length 60 needs one tag byte + one extra byte - // for length information. - // - // Item blowup is trickier to measure. Suppose the "copy" op copies - // 4 bytes of data. Because of a special check in the encoding code, - // we produce a 4-byte copy only if the offset is < 65536. Therefore - // the copy op takes 3 bytes to encode, and this type of item leads - // to at most the 62/60 blowup for representing literals. - // - // Suppose the "copy" op copies 5 bytes of data. If the offset is big - // enough, it will take 5 bytes to encode the copy op. Therefore the - // worst case here is a one-byte literal followed by a five-byte copy. - // That is, 6 bytes of input turn into 7 bytes of "compressed" data. - // - // This last factor dominates the blowup, so the final estimate is: - n = 32 + n + n/6 - if n > 0xffffffff { - return -1 - } - return int(n) -} - -var errClosed = errors.New("snappy: Writer is closed") - -// NewWriter returns a new Writer that compresses to w. -// -// The Writer returned does not buffer writes. There is no need to Flush or -// Close such a Writer. -// -// Deprecated: the Writer returned is not suitable for many small writes, only -// for few large writes. Use NewBufferedWriter instead, which is efficient -// regardless of the frequency and shape of the writes, and remember to Close -// that Writer when done. -func NewWriter(w io.Writer) *Writer { - return &Writer{ - w: w, - obuf: make([]byte, obufLen), - } -} - -// NewBufferedWriter returns a new Writer that compresses to w, using the -// framing format described at -// https://github.com/google/snappy/blob/master/framing_format.txt -// -// The Writer returned buffers writes. Users must call Close to guarantee all -// data has been forwarded to the underlying io.Writer. They may also call -// Flush zero or more times before calling Close. -func NewBufferedWriter(w io.Writer) *Writer { - return &Writer{ - w: w, - ibuf: make([]byte, 0, maxBlockSize), - obuf: make([]byte, obufLen), - } -} - -// Writer is an io.Writer that can write Snappy-compressed bytes. -type Writer struct { - w io.Writer - err error - - // ibuf is a buffer for the incoming (uncompressed) bytes. - // - // Its use is optional. For backwards compatibility, Writers created by the - // NewWriter function have ibuf == nil, do not buffer incoming bytes, and - // therefore do not need to be Flush'ed or Close'd. - ibuf []byte - - // obuf is a buffer for the outgoing (compressed) bytes. - obuf []byte - - // wroteStreamHeader is whether we have written the stream header. - wroteStreamHeader bool -} - -// Reset discards the writer's state and switches the Snappy writer to write to -// w. This permits reusing a Writer rather than allocating a new one. -func (w *Writer) Reset(writer io.Writer) { - w.w = writer - w.err = nil - if w.ibuf != nil { - w.ibuf = w.ibuf[:0] - } - w.wroteStreamHeader = false -} - -// Write satisfies the io.Writer interface. -func (w *Writer) Write(p []byte) (nRet int, errRet error) { - if w.ibuf == nil { - // Do not buffer incoming bytes. This does not perform or compress well - // if the caller of Writer.Write writes many small slices. This - // behavior is therefore deprecated, but still supported for backwards - // compatibility with code that doesn't explicitly Flush or Close. - return w.write(p) - } - - // The remainder of this method is based on bufio.Writer.Write from the - // standard library. - - for len(p) > (cap(w.ibuf)-len(w.ibuf)) && w.err == nil { - var n int - if len(w.ibuf) == 0 { - // Large write, empty buffer. - // Write directly from p to avoid copy. - n, _ = w.write(p) - } else { - n = copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p) - w.ibuf = w.ibuf[:len(w.ibuf)+n] - w.Flush() - } - nRet += n - p = p[n:] - } - if w.err != nil { - return nRet, w.err - } - n := copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p) - w.ibuf = w.ibuf[:len(w.ibuf)+n] - nRet += n - return nRet, nil -} - -func (w *Writer) write(p []byte) (nRet int, errRet error) { - if w.err != nil { - return 0, w.err - } - for len(p) > 0 { - obufStart := len(magicChunk) - if !w.wroteStreamHeader { - w.wroteStreamHeader = true - copy(w.obuf, magicChunk) - obufStart = 0 - } - - var uncompressed []byte - if len(p) > maxBlockSize { - uncompressed, p = p[:maxBlockSize], p[maxBlockSize:] - } else { - uncompressed, p = p, nil - } - checksum := crc(uncompressed) - - // Compress the buffer, discarding the result if the improvement - // isn't at least 12.5%. - compressed := Encode(w.obuf[obufHeaderLen:], uncompressed) - chunkType := uint8(chunkTypeCompressedData) - chunkLen := 4 + len(compressed) - obufEnd := obufHeaderLen + len(compressed) - if len(compressed) >= len(uncompressed)-len(uncompressed)/8 { - chunkType = chunkTypeUncompressedData - chunkLen = 4 + len(uncompressed) - obufEnd = obufHeaderLen - } - - // Fill in the per-chunk header that comes before the body. - w.obuf[len(magicChunk)+0] = chunkType - w.obuf[len(magicChunk)+1] = uint8(chunkLen >> 0) - w.obuf[len(magicChunk)+2] = uint8(chunkLen >> 8) - w.obuf[len(magicChunk)+3] = uint8(chunkLen >> 16) - w.obuf[len(magicChunk)+4] = uint8(checksum >> 0) - w.obuf[len(magicChunk)+5] = uint8(checksum >> 8) - w.obuf[len(magicChunk)+6] = uint8(checksum >> 16) - w.obuf[len(magicChunk)+7] = uint8(checksum >> 24) - - if _, err := w.w.Write(w.obuf[obufStart:obufEnd]); err != nil { - w.err = err - return nRet, err - } - if chunkType == chunkTypeUncompressedData { - if _, err := w.w.Write(uncompressed); err != nil { - w.err = err - return nRet, err - } - } - nRet += len(uncompressed) - } - return nRet, nil -} - -// Flush flushes the Writer to its underlying io.Writer. -func (w *Writer) Flush() error { - if w.err != nil { - return w.err - } - if len(w.ibuf) == 0 { - return nil - } - w.write(w.ibuf) - w.ibuf = w.ibuf[:0] - return w.err -} - -// Close calls Flush and then closes the Writer. -func (w *Writer) Close() error { - w.Flush() - ret := w.err - if w.err == nil { - w.err = errClosed - } - return ret -} diff --git a/vendor/github.com/golang/snappy/encode_amd64.go b/vendor/github.com/golang/snappy/encode_amd64.go deleted file mode 100644 index 150d91b..0000000 --- a/vendor/github.com/golang/snappy/encode_amd64.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2016 The Snappy-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 !appengine -// +build gc -// +build !noasm - -package snappy - -// emitLiteral has the same semantics as in encode_other.go. -// -//go:noescape -func emitLiteral(dst, lit []byte) int - -// emitCopy has the same semantics as in encode_other.go. -// -//go:noescape -func emitCopy(dst []byte, offset, length int) int - -// extendMatch has the same semantics as in encode_other.go. -// -//go:noescape -func extendMatch(src []byte, i, j int) int - -// encodeBlock has the same semantics as in encode_other.go. -// -//go:noescape -func encodeBlock(dst, src []byte) (d int) diff --git a/vendor/github.com/golang/snappy/encode_amd64.s b/vendor/github.com/golang/snappy/encode_amd64.s deleted file mode 100644 index adfd979..0000000 --- a/vendor/github.com/golang/snappy/encode_amd64.s +++ /dev/null @@ -1,730 +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. - -// +build !appengine -// +build gc -// +build !noasm - -#include "textflag.h" - -// The XXX lines assemble on Go 1.4, 1.5 and 1.7, but not 1.6, due to a -// Go toolchain regression. See https://github.com/golang/go/issues/15426 and -// https://github.com/golang/snappy/issues/29 -// -// As a workaround, the package was built with a known good assembler, and -// those instructions were disassembled by "objdump -d" to yield the -// 4e 0f b7 7c 5c 78 movzwq 0x78(%rsp,%r11,2),%r15 -// style comments, in AT&T asm syntax. Note that rsp here is a physical -// register, not Go/asm's SP pseudo-register (see https://golang.org/doc/asm). -// The instructions were then encoded as "BYTE $0x.." sequences, which assemble -// fine on Go 1.6. - -// The asm code generally follows the pure Go code in encode_other.go, except -// where marked with a "!!!". - -// ---------------------------------------------------------------------------- - -// func emitLiteral(dst, lit []byte) int -// -// All local variables fit into registers. The register allocation: -// - AX len(lit) -// - BX n -// - DX return value -// - DI &dst[i] -// - R10 &lit[0] -// -// The 24 bytes of stack space is to call runtime·memmove. -// -// The unusual register allocation of local variables, such as R10 for the -// source pointer, matches the allocation used at the call site in encodeBlock, -// which makes it easier to manually inline this function. -TEXT ·emitLiteral(SB), NOSPLIT, $24-56 - MOVQ dst_base+0(FP), DI - MOVQ lit_base+24(FP), R10 - MOVQ lit_len+32(FP), AX - MOVQ AX, DX - MOVL AX, BX - SUBL $1, BX - - CMPL BX, $60 - JLT oneByte - CMPL BX, $256 - JLT twoBytes - -threeBytes: - MOVB $0xf4, 0(DI) - MOVW BX, 1(DI) - ADDQ $3, DI - ADDQ $3, DX - JMP memmove - -twoBytes: - MOVB $0xf0, 0(DI) - MOVB BX, 1(DI) - ADDQ $2, DI - ADDQ $2, DX - JMP memmove - -oneByte: - SHLB $2, BX - MOVB BX, 0(DI) - ADDQ $1, DI - ADDQ $1, DX - -memmove: - MOVQ DX, ret+48(FP) - - // copy(dst[i:], lit) - // - // This means calling runtime·memmove(&dst[i], &lit[0], len(lit)), so we push - // DI, R10 and AX as arguments. - MOVQ DI, 0(SP) - MOVQ R10, 8(SP) - MOVQ AX, 16(SP) - CALL runtime·memmove(SB) - RET - -// ---------------------------------------------------------------------------- - -// func emitCopy(dst []byte, offset, length int) int -// -// All local variables fit into registers. The register allocation: -// - AX length -// - SI &dst[0] -// - DI &dst[i] -// - R11 offset -// -// The unusual register allocation of local variables, such as R11 for the -// offset, matches the allocation used at the call site in encodeBlock, which -// makes it easier to manually inline this function. -TEXT ·emitCopy(SB), NOSPLIT, $0-48 - MOVQ dst_base+0(FP), DI - MOVQ DI, SI - MOVQ offset+24(FP), R11 - MOVQ length+32(FP), AX - -loop0: - // for length >= 68 { etc } - CMPL AX, $68 - JLT step1 - - // Emit a length 64 copy, encoded as 3 bytes. - MOVB $0xfe, 0(DI) - MOVW R11, 1(DI) - ADDQ $3, DI - SUBL $64, AX - JMP loop0 - -step1: - // if length > 64 { etc } - CMPL AX, $64 - JLE step2 - - // Emit a length 60 copy, encoded as 3 bytes. - MOVB $0xee, 0(DI) - MOVW R11, 1(DI) - ADDQ $3, DI - SUBL $60, AX - -step2: - // if length >= 12 || offset >= 2048 { goto step3 } - CMPL AX, $12 - JGE step3 - CMPL R11, $2048 - JGE step3 - - // Emit the remaining copy, encoded as 2 bytes. - MOVB R11, 1(DI) - SHRL $8, R11 - SHLB $5, R11 - SUBB $4, AX - SHLB $2, AX - ORB AX, R11 - ORB $1, R11 - MOVB R11, 0(DI) - ADDQ $2, DI - - // Return the number of bytes written. - SUBQ SI, DI - MOVQ DI, ret+40(FP) - RET - -step3: - // Emit the remaining copy, encoded as 3 bytes. - SUBL $1, AX - SHLB $2, AX - ORB $2, AX - MOVB AX, 0(DI) - MOVW R11, 1(DI) - ADDQ $3, DI - - // Return the number of bytes written. - SUBQ SI, DI - MOVQ DI, ret+40(FP) - RET - -// ---------------------------------------------------------------------------- - -// func extendMatch(src []byte, i, j int) int -// -// All local variables fit into registers. The register allocation: -// - DX &src[0] -// - SI &src[j] -// - R13 &src[len(src) - 8] -// - R14 &src[len(src)] -// - R15 &src[i] -// -// The unusual register allocation of local variables, such as R15 for a source -// pointer, matches the allocation used at the call site in encodeBlock, which -// makes it easier to manually inline this function. -TEXT ·extendMatch(SB), NOSPLIT, $0-48 - MOVQ src_base+0(FP), DX - MOVQ src_len+8(FP), R14 - MOVQ i+24(FP), R15 - MOVQ j+32(FP), SI - ADDQ DX, R14 - ADDQ DX, R15 - ADDQ DX, SI - MOVQ R14, R13 - SUBQ $8, R13 - -cmp8: - // As long as we are 8 or more bytes before the end of src, we can load and - // compare 8 bytes at a time. If those 8 bytes are equal, repeat. - CMPQ SI, R13 - JA cmp1 - MOVQ (R15), AX - MOVQ (SI), BX - CMPQ AX, BX - JNE bsf - ADDQ $8, R15 - ADDQ $8, SI - JMP cmp8 - -bsf: - // If those 8 bytes were not equal, XOR the two 8 byte values, and return - // the index of the first byte that differs. The BSF instruction finds the - // least significant 1 bit, the amd64 architecture is little-endian, and - // the shift by 3 converts a bit index to a byte index. - XORQ AX, BX - BSFQ BX, BX - SHRQ $3, BX - ADDQ BX, SI - - // Convert from &src[ret] to ret. - SUBQ DX, SI - MOVQ SI, ret+40(FP) - RET - -cmp1: - // In src's tail, compare 1 byte at a time. - CMPQ SI, R14 - JAE extendMatchEnd - MOVB (R15), AX - MOVB (SI), BX - CMPB AX, BX - JNE extendMatchEnd - ADDQ $1, R15 - ADDQ $1, SI - JMP cmp1 - -extendMatchEnd: - // Convert from &src[ret] to ret. - SUBQ DX, SI - MOVQ SI, ret+40(FP) - RET - -// ---------------------------------------------------------------------------- - -// func encodeBlock(dst, src []byte) (d int) -// -// All local variables fit into registers, other than "var table". The register -// allocation: -// - AX . . -// - BX . . -// - CX 56 shift (note that amd64 shifts by non-immediates must use CX). -// - DX 64 &src[0], tableSize -// - SI 72 &src[s] -// - DI 80 &dst[d] -// - R9 88 sLimit -// - R10 . &src[nextEmit] -// - R11 96 prevHash, currHash, nextHash, offset -// - R12 104 &src[base], skip -// - R13 . &src[nextS], &src[len(src) - 8] -// - R14 . len(src), bytesBetweenHashLookups, &src[len(src)], x -// - R15 112 candidate -// -// The second column (56, 64, etc) is the stack offset to spill the registers -// when calling other functions. We could pack this slightly tighter, but it's -// simpler to have a dedicated spill map independent of the function called. -// -// "var table [maxTableSize]uint16" takes up 32768 bytes of stack space. An -// extra 56 bytes, to call other functions, and an extra 64 bytes, to spill -// local variables (registers) during calls gives 32768 + 56 + 64 = 32888. -TEXT ·encodeBlock(SB), 0, $32888-56 - MOVQ dst_base+0(FP), DI - MOVQ src_base+24(FP), SI - MOVQ src_len+32(FP), R14 - - // shift, tableSize := uint32(32-8), 1<<8 - MOVQ $24, CX - MOVQ $256, DX - -calcShift: - // for ; tableSize < maxTableSize && tableSize < len(src); tableSize *= 2 { - // shift-- - // } - CMPQ DX, $16384 - JGE varTable - CMPQ DX, R14 - JGE varTable - SUBQ $1, CX - SHLQ $1, DX - JMP calcShift - -varTable: - // var table [maxTableSize]uint16 - // - // In the asm code, unlike the Go code, we can zero-initialize only the - // first tableSize elements. Each uint16 element is 2 bytes and each MOVOU - // writes 16 bytes, so we can do only tableSize/8 writes instead of the - // 2048 writes that would zero-initialize all of table's 32768 bytes. - SHRQ $3, DX - LEAQ table-32768(SP), BX - PXOR X0, X0 - -memclr: - MOVOU X0, 0(BX) - ADDQ $16, BX - SUBQ $1, DX - JNZ memclr - - // !!! DX = &src[0] - MOVQ SI, DX - - // sLimit := len(src) - inputMargin - MOVQ R14, R9 - SUBQ $15, R9 - - // !!! Pre-emptively spill CX, DX and R9 to the stack. Their values don't - // change for the rest of the function. - MOVQ CX, 56(SP) - MOVQ DX, 64(SP) - MOVQ R9, 88(SP) - - // nextEmit := 0 - MOVQ DX, R10 - - // s := 1 - ADDQ $1, SI - - // nextHash := hash(load32(src, s), shift) - MOVL 0(SI), R11 - IMULL $0x1e35a7bd, R11 - SHRL CX, R11 - -outer: - // for { etc } - - // skip := 32 - MOVQ $32, R12 - - // nextS := s - MOVQ SI, R13 - - // candidate := 0 - MOVQ $0, R15 - -inner0: - // for { etc } - - // s := nextS - MOVQ R13, SI - - // bytesBetweenHashLookups := skip >> 5 - MOVQ R12, R14 - SHRQ $5, R14 - - // nextS = s + bytesBetweenHashLookups - ADDQ R14, R13 - - // skip += bytesBetweenHashLookups - ADDQ R14, R12 - - // if nextS > sLimit { goto emitRemainder } - MOVQ R13, AX - SUBQ DX, AX - CMPQ AX, R9 - JA emitRemainder - - // candidate = int(table[nextHash]) - // XXX: MOVWQZX table-32768(SP)(R11*2), R15 - // XXX: 4e 0f b7 7c 5c 78 movzwq 0x78(%rsp,%r11,2),%r15 - BYTE $0x4e - BYTE $0x0f - BYTE $0xb7 - BYTE $0x7c - BYTE $0x5c - BYTE $0x78 - - // table[nextHash] = uint16(s) - MOVQ SI, AX - SUBQ DX, AX - - // XXX: MOVW AX, table-32768(SP)(R11*2) - // XXX: 66 42 89 44 5c 78 mov %ax,0x78(%rsp,%r11,2) - BYTE $0x66 - BYTE $0x42 - BYTE $0x89 - BYTE $0x44 - BYTE $0x5c - BYTE $0x78 - - // nextHash = hash(load32(src, nextS), shift) - MOVL 0(R13), R11 - IMULL $0x1e35a7bd, R11 - SHRL CX, R11 - - // if load32(src, s) != load32(src, candidate) { continue } break - MOVL 0(SI), AX - MOVL (DX)(R15*1), BX - CMPL AX, BX - JNE inner0 - -fourByteMatch: - // As per the encode_other.go code: - // - // A 4-byte match has been found. We'll later see etc. - - // !!! Jump to a fast path for short (<= 16 byte) literals. See the comment - // on inputMargin in encode.go. - MOVQ SI, AX - SUBQ R10, AX - CMPQ AX, $16 - JLE emitLiteralFastPath - - // ---------------------------------------- - // Begin inline of the emitLiteral call. - // - // d += emitLiteral(dst[d:], src[nextEmit:s]) - - MOVL AX, BX - SUBL $1, BX - - CMPL BX, $60 - JLT inlineEmitLiteralOneByte - CMPL BX, $256 - JLT inlineEmitLiteralTwoBytes - -inlineEmitLiteralThreeBytes: - MOVB $0xf4, 0(DI) - MOVW BX, 1(DI) - ADDQ $3, DI - JMP inlineEmitLiteralMemmove - -inlineEmitLiteralTwoBytes: - MOVB $0xf0, 0(DI) - MOVB BX, 1(DI) - ADDQ $2, DI - JMP inlineEmitLiteralMemmove - -inlineEmitLiteralOneByte: - SHLB $2, BX - MOVB BX, 0(DI) - ADDQ $1, DI - -inlineEmitLiteralMemmove: - // Spill local variables (registers) onto the stack; call; unspill. - // - // copy(dst[i:], lit) - // - // This means calling runtime·memmove(&dst[i], &lit[0], len(lit)), so we push - // DI, R10 and AX as arguments. - MOVQ DI, 0(SP) - MOVQ R10, 8(SP) - MOVQ AX, 16(SP) - ADDQ AX, DI // Finish the "d +=" part of "d += emitLiteral(etc)". - MOVQ SI, 72(SP) - MOVQ DI, 80(SP) - MOVQ R15, 112(SP) - CALL runtime·memmove(SB) - MOVQ 56(SP), CX - MOVQ 64(SP), DX - MOVQ 72(SP), SI - MOVQ 80(SP), DI - MOVQ 88(SP), R9 - MOVQ 112(SP), R15 - JMP inner1 - -inlineEmitLiteralEnd: - // End inline of the emitLiteral call. - // ---------------------------------------- - -emitLiteralFastPath: - // !!! Emit the 1-byte encoding "uint8(len(lit)-1)<<2". - MOVB AX, BX - SUBB $1, BX - SHLB $2, BX - MOVB BX, (DI) - ADDQ $1, DI - - // !!! Implement the copy from lit to dst as a 16-byte load and store. - // (Encode's documentation says that dst and src must not overlap.) - // - // This always copies 16 bytes, instead of only len(lit) bytes, but that's - // OK. Subsequent iterations will fix up the overrun. - // - // Note that on amd64, it is legal and cheap to issue unaligned 8-byte or - // 16-byte loads and stores. This technique probably wouldn't be as - // effective on architectures that are fussier about alignment. - MOVOU 0(R10), X0 - MOVOU X0, 0(DI) - ADDQ AX, DI - -inner1: - // for { etc } - - // base := s - MOVQ SI, R12 - - // !!! offset := base - candidate - MOVQ R12, R11 - SUBQ R15, R11 - SUBQ DX, R11 - - // ---------------------------------------- - // Begin inline of the extendMatch call. - // - // s = extendMatch(src, candidate+4, s+4) - - // !!! R14 = &src[len(src)] - MOVQ src_len+32(FP), R14 - ADDQ DX, R14 - - // !!! R13 = &src[len(src) - 8] - MOVQ R14, R13 - SUBQ $8, R13 - - // !!! R15 = &src[candidate + 4] - ADDQ $4, R15 - ADDQ DX, R15 - - // !!! s += 4 - ADDQ $4, SI - -inlineExtendMatchCmp8: - // As long as we are 8 or more bytes before the end of src, we can load and - // compare 8 bytes at a time. If those 8 bytes are equal, repeat. - CMPQ SI, R13 - JA inlineExtendMatchCmp1 - MOVQ (R15), AX - MOVQ (SI), BX - CMPQ AX, BX - JNE inlineExtendMatchBSF - ADDQ $8, R15 - ADDQ $8, SI - JMP inlineExtendMatchCmp8 - -inlineExtendMatchBSF: - // If those 8 bytes were not equal, XOR the two 8 byte values, and return - // the index of the first byte that differs. The BSF instruction finds the - // least significant 1 bit, the amd64 architecture is little-endian, and - // the shift by 3 converts a bit index to a byte index. - XORQ AX, BX - BSFQ BX, BX - SHRQ $3, BX - ADDQ BX, SI - JMP inlineExtendMatchEnd - -inlineExtendMatchCmp1: - // In src's tail, compare 1 byte at a time. - CMPQ SI, R14 - JAE inlineExtendMatchEnd - MOVB (R15), AX - MOVB (SI), BX - CMPB AX, BX - JNE inlineExtendMatchEnd - ADDQ $1, R15 - ADDQ $1, SI - JMP inlineExtendMatchCmp1 - -inlineExtendMatchEnd: - // End inline of the extendMatch call. - // ---------------------------------------- - - // ---------------------------------------- - // Begin inline of the emitCopy call. - // - // d += emitCopy(dst[d:], base-candidate, s-base) - - // !!! length := s - base - MOVQ SI, AX - SUBQ R12, AX - -inlineEmitCopyLoop0: - // for length >= 68 { etc } - CMPL AX, $68 - JLT inlineEmitCopyStep1 - - // Emit a length 64 copy, encoded as 3 bytes. - MOVB $0xfe, 0(DI) - MOVW R11, 1(DI) - ADDQ $3, DI - SUBL $64, AX - JMP inlineEmitCopyLoop0 - -inlineEmitCopyStep1: - // if length > 64 { etc } - CMPL AX, $64 - JLE inlineEmitCopyStep2 - - // Emit a length 60 copy, encoded as 3 bytes. - MOVB $0xee, 0(DI) - MOVW R11, 1(DI) - ADDQ $3, DI - SUBL $60, AX - -inlineEmitCopyStep2: - // if length >= 12 || offset >= 2048 { goto inlineEmitCopyStep3 } - CMPL AX, $12 - JGE inlineEmitCopyStep3 - CMPL R11, $2048 - JGE inlineEmitCopyStep3 - - // Emit the remaining copy, encoded as 2 bytes. - MOVB R11, 1(DI) - SHRL $8, R11 - SHLB $5, R11 - SUBB $4, AX - SHLB $2, AX - ORB AX, R11 - ORB $1, R11 - MOVB R11, 0(DI) - ADDQ $2, DI - JMP inlineEmitCopyEnd - -inlineEmitCopyStep3: - // Emit the remaining copy, encoded as 3 bytes. - SUBL $1, AX - SHLB $2, AX - ORB $2, AX - MOVB AX, 0(DI) - MOVW R11, 1(DI) - ADDQ $3, DI - -inlineEmitCopyEnd: - // End inline of the emitCopy call. - // ---------------------------------------- - - // nextEmit = s - MOVQ SI, R10 - - // if s >= sLimit { goto emitRemainder } - MOVQ SI, AX - SUBQ DX, AX - CMPQ AX, R9 - JAE emitRemainder - - // As per the encode_other.go code: - // - // We could immediately etc. - - // x := load64(src, s-1) - MOVQ -1(SI), R14 - - // prevHash := hash(uint32(x>>0), shift) - MOVL R14, R11 - IMULL $0x1e35a7bd, R11 - SHRL CX, R11 - - // table[prevHash] = uint16(s-1) - MOVQ SI, AX - SUBQ DX, AX - SUBQ $1, AX - - // XXX: MOVW AX, table-32768(SP)(R11*2) - // XXX: 66 42 89 44 5c 78 mov %ax,0x78(%rsp,%r11,2) - BYTE $0x66 - BYTE $0x42 - BYTE $0x89 - BYTE $0x44 - BYTE $0x5c - BYTE $0x78 - - // currHash := hash(uint32(x>>8), shift) - SHRQ $8, R14 - MOVL R14, R11 - IMULL $0x1e35a7bd, R11 - SHRL CX, R11 - - // candidate = int(table[currHash]) - // XXX: MOVWQZX table-32768(SP)(R11*2), R15 - // XXX: 4e 0f b7 7c 5c 78 movzwq 0x78(%rsp,%r11,2),%r15 - BYTE $0x4e - BYTE $0x0f - BYTE $0xb7 - BYTE $0x7c - BYTE $0x5c - BYTE $0x78 - - // table[currHash] = uint16(s) - ADDQ $1, AX - - // XXX: MOVW AX, table-32768(SP)(R11*2) - // XXX: 66 42 89 44 5c 78 mov %ax,0x78(%rsp,%r11,2) - BYTE $0x66 - BYTE $0x42 - BYTE $0x89 - BYTE $0x44 - BYTE $0x5c - BYTE $0x78 - - // if uint32(x>>8) == load32(src, candidate) { continue } - MOVL (DX)(R15*1), BX - CMPL R14, BX - JEQ inner1 - - // nextHash = hash(uint32(x>>16), shift) - SHRQ $8, R14 - MOVL R14, R11 - IMULL $0x1e35a7bd, R11 - SHRL CX, R11 - - // s++ - ADDQ $1, SI - - // break out of the inner1 for loop, i.e. continue the outer loop. - JMP outer - -emitRemainder: - // if nextEmit < len(src) { etc } - MOVQ src_len+32(FP), AX - ADDQ DX, AX - CMPQ R10, AX - JEQ encodeBlockEnd - - // d += emitLiteral(dst[d:], src[nextEmit:]) - // - // Push args. - MOVQ DI, 0(SP) - MOVQ $0, 8(SP) // Unnecessary, as the callee ignores it, but conservative. - MOVQ $0, 16(SP) // Unnecessary, as the callee ignores it, but conservative. - MOVQ R10, 24(SP) - SUBQ R10, AX - MOVQ AX, 32(SP) - MOVQ AX, 40(SP) // Unnecessary, as the callee ignores it, but conservative. - - // Spill local variables (registers) onto the stack; call; unspill. - MOVQ DI, 80(SP) - CALL ·emitLiteral(SB) - MOVQ 80(SP), DI - - // Finish the "d +=" part of "d += emitLiteral(etc)". - ADDQ 48(SP), DI - -encodeBlockEnd: - MOVQ dst_base+0(FP), AX - SUBQ AX, DI - MOVQ DI, d+48(FP) - RET diff --git a/vendor/github.com/golang/snappy/encode_other.go b/vendor/github.com/golang/snappy/encode_other.go deleted file mode 100644 index dbcae90..0000000 --- a/vendor/github.com/golang/snappy/encode_other.go +++ /dev/null @@ -1,238 +0,0 @@ -// Copyright 2016 The Snappy-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 !amd64 appengine !gc noasm - -package snappy - -func load32(b []byte, i int) uint32 { - b = b[i : i+4 : len(b)] // Help the compiler eliminate bounds checks on the next line. - return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 -} - -func load64(b []byte, i int) uint64 { - b = b[i : i+8 : len(b)] // Help the compiler eliminate bounds checks on the next line. - return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | - uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 -} - -// emitLiteral writes a literal chunk and returns the number of bytes written. -// -// It assumes that: -// dst is long enough to hold the encoded bytes -// 1 <= len(lit) && len(lit) <= 65536 -func emitLiteral(dst, lit []byte) int { - i, n := 0, uint(len(lit)-1) - switch { - case n < 60: - dst[0] = uint8(n)<<2 | tagLiteral - i = 1 - case n < 1<<8: - dst[0] = 60<<2 | tagLiteral - dst[1] = uint8(n) - i = 2 - default: - dst[0] = 61<<2 | tagLiteral - dst[1] = uint8(n) - dst[2] = uint8(n >> 8) - i = 3 - } - return i + copy(dst[i:], lit) -} - -// emitCopy writes a copy chunk and returns the number of bytes written. -// -// It assumes that: -// dst is long enough to hold the encoded bytes -// 1 <= offset && offset <= 65535 -// 4 <= length && length <= 65535 -func emitCopy(dst []byte, offset, length int) int { - i := 0 - // The maximum length for a single tagCopy1 or tagCopy2 op is 64 bytes. The - // threshold for this loop is a little higher (at 68 = 64 + 4), and the - // length emitted down below is is a little lower (at 60 = 64 - 4), because - // it's shorter to encode a length 67 copy as a length 60 tagCopy2 followed - // by a length 7 tagCopy1 (which encodes as 3+2 bytes) than to encode it as - // a length 64 tagCopy2 followed by a length 3 tagCopy2 (which encodes as - // 3+3 bytes). The magic 4 in the 64±4 is because the minimum length for a - // tagCopy1 op is 4 bytes, which is why a length 3 copy has to be an - // encodes-as-3-bytes tagCopy2 instead of an encodes-as-2-bytes tagCopy1. - for length >= 68 { - // Emit a length 64 copy, encoded as 3 bytes. - dst[i+0] = 63<<2 | tagCopy2 - dst[i+1] = uint8(offset) - dst[i+2] = uint8(offset >> 8) - i += 3 - length -= 64 - } - if length > 64 { - // Emit a length 60 copy, encoded as 3 bytes. - dst[i+0] = 59<<2 | tagCopy2 - dst[i+1] = uint8(offset) - dst[i+2] = uint8(offset >> 8) - i += 3 - length -= 60 - } - if length >= 12 || offset >= 2048 { - // Emit the remaining copy, encoded as 3 bytes. - dst[i+0] = uint8(length-1)<<2 | tagCopy2 - dst[i+1] = uint8(offset) - dst[i+2] = uint8(offset >> 8) - return i + 3 - } - // Emit the remaining copy, encoded as 2 bytes. - dst[i+0] = uint8(offset>>8)<<5 | uint8(length-4)<<2 | tagCopy1 - dst[i+1] = uint8(offset) - return i + 2 -} - -// extendMatch returns the largest k such that k <= len(src) and that -// src[i:i+k-j] and src[j:k] have the same contents. -// -// It assumes that: -// 0 <= i && i < j && j <= len(src) -func extendMatch(src []byte, i, j int) int { - for ; j < len(src) && src[i] == src[j]; i, j = i+1, j+1 { - } - return j -} - -func hash(u, shift uint32) uint32 { - return (u * 0x1e35a7bd) >> shift -} - -// encodeBlock encodes a non-empty src to a guaranteed-large-enough dst. It -// assumes that the varint-encoded length of the decompressed bytes has already -// been written. -// -// It also assumes that: -// len(dst) >= MaxEncodedLen(len(src)) && -// minNonLiteralBlockSize <= len(src) && len(src) <= maxBlockSize -func encodeBlock(dst, src []byte) (d int) { - // Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive. - // The table element type is uint16, as s < sLimit and sLimit < len(src) - // and len(src) <= maxBlockSize and maxBlockSize == 65536. - const ( - maxTableSize = 1 << 14 - // tableMask is redundant, but helps the compiler eliminate bounds - // checks. - tableMask = maxTableSize - 1 - ) - shift := uint32(32 - 8) - for tableSize := 1 << 8; tableSize < maxTableSize && tableSize < len(src); tableSize *= 2 { - shift-- - } - // In Go, all array elements are zero-initialized, so there is no advantage - // to a smaller tableSize per se. However, it matches the C++ algorithm, - // and in the asm versions of this code, we can get away with zeroing only - // the first tableSize elements. - var table [maxTableSize]uint16 - - // sLimit is when to stop looking for offset/length copies. The inputMargin - // lets us use a fast path for emitLiteral in the main loop, while we are - // looking for copies. - sLimit := len(src) - inputMargin - - // nextEmit is where in src the next emitLiteral should start from. - nextEmit := 0 - - // The encoded form must start with a literal, as there are no previous - // bytes to copy, so we start looking for hash matches at s == 1. - s := 1 - nextHash := hash(load32(src, s), shift) - - for { - // Copied from the C++ snappy implementation: - // - // Heuristic match skipping: If 32 bytes are scanned with no matches - // found, start looking only at every other byte. If 32 more bytes are - // scanned (or skipped), look at every third byte, etc.. When a match - // is found, immediately go back to looking at every byte. This is a - // small loss (~5% performance, ~0.1% density) for compressible data - // due to more bookkeeping, but for non-compressible data (such as - // JPEG) it's a huge win since the compressor quickly "realizes" the - // data is incompressible and doesn't bother looking for matches - // everywhere. - // - // The "skip" variable keeps track of how many bytes there are since - // the last match; dividing it by 32 (ie. right-shifting by five) gives - // the number of bytes to move ahead for each iteration. - skip := 32 - - nextS := s - candidate := 0 - for { - s = nextS - bytesBetweenHashLookups := skip >> 5 - nextS = s + bytesBetweenHashLookups - skip += bytesBetweenHashLookups - if nextS > sLimit { - goto emitRemainder - } - candidate = int(table[nextHash&tableMask]) - table[nextHash&tableMask] = uint16(s) - nextHash = hash(load32(src, nextS), shift) - if load32(src, s) == load32(src, candidate) { - break - } - } - - // A 4-byte match has been found. We'll later see if more than 4 bytes - // match. But, prior to the match, src[nextEmit:s] are unmatched. Emit - // them as literal bytes. - d += emitLiteral(dst[d:], src[nextEmit:s]) - - // Call emitCopy, and then see if another emitCopy could be our next - // move. Repeat until we find no match for the input immediately after - // what was consumed by the last emitCopy call. - // - // If we exit this loop normally then we need to call emitLiteral next, - // though we don't yet know how big the literal will be. We handle that - // by proceeding to the next iteration of the main loop. We also can - // exit this loop via goto if we get close to exhausting the input. - for { - // Invariant: we have a 4-byte match at s, and no need to emit any - // literal bytes prior to s. - base := s - - // Extend the 4-byte match as long as possible. - // - // This is an inlined version of: - // s = extendMatch(src, candidate+4, s+4) - s += 4 - for i := candidate + 4; s < len(src) && src[i] == src[s]; i, s = i+1, s+1 { - } - - d += emitCopy(dst[d:], base-candidate, s-base) - nextEmit = s - if s >= sLimit { - goto emitRemainder - } - - // We could immediately start working at s now, but to improve - // compression we first update the hash table at s-1 and at s. If - // another emitCopy is not our next move, also calculate nextHash - // at s+1. At least on GOARCH=amd64, these three hash calculations - // are faster as one load64 call (with some shifts) instead of - // three load32 calls. - x := load64(src, s-1) - prevHash := hash(uint32(x>>0), shift) - table[prevHash&tableMask] = uint16(s - 1) - currHash := hash(uint32(x>>8), shift) - candidate = int(table[currHash&tableMask]) - table[currHash&tableMask] = uint16(s) - if uint32(x>>8) != load32(src, candidate) { - nextHash = hash(uint32(x>>16), shift) - s++ - break - } - } - } - -emitRemainder: - if nextEmit < len(src) { - d += emitLiteral(dst[d:], src[nextEmit:]) - } - return d -} diff --git a/vendor/github.com/golang/snappy/snappy.go b/vendor/github.com/golang/snappy/snappy.go deleted file mode 100644 index ece692e..0000000 --- a/vendor/github.com/golang/snappy/snappy.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2011 The Snappy-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 snappy implements the Snappy compression format. It aims for very -// high speeds and reasonable compression. -// -// There are actually two Snappy formats: block and stream. They are related, -// but different: trying to decompress block-compressed data as a Snappy stream -// will fail, and vice versa. The block format is the Decode and Encode -// functions and the stream format is the Reader and Writer types. -// -// The block format, the more common case, is used when the complete size (the -// number of bytes) of the original data is known upfront, at the time -// compression starts. The stream format, also known as the framing format, is -// for when that isn't always true. -// -// The canonical, C++ implementation is at https://github.com/google/snappy and -// it only implements the block format. -package snappy // import "github.com/golang/snappy" - -import ( - "hash/crc32" -) - -/* -Each encoded block begins with the varint-encoded length of the decoded data, -followed by a sequence of chunks. Chunks begin and end on byte boundaries. The -first byte of each chunk is broken into its 2 least and 6 most significant bits -called l and m: l ranges in [0, 4) and m ranges in [0, 64). l is the chunk tag. -Zero means a literal tag. All other values mean a copy tag. - -For literal tags: - - If m < 60, the next 1 + m bytes are literal bytes. - - Otherwise, let n be the little-endian unsigned integer denoted by the next - m - 59 bytes. The next 1 + n bytes after that are literal bytes. - -For copy tags, length bytes are copied from offset bytes ago, in the style of -Lempel-Ziv compression algorithms. In particular: - - For l == 1, the offset ranges in [0, 1<<11) and the length in [4, 12). - The length is 4 + the low 3 bits of m. The high 3 bits of m form bits 8-10 - of the offset. The next byte is bits 0-7 of the offset. - - For l == 2, the offset ranges in [0, 1<<16) and the length in [1, 65). - The length is 1 + m. The offset is the little-endian unsigned integer - denoted by the next 2 bytes. - - For l == 3, this tag is a legacy format that is no longer issued by most - encoders. Nonetheless, the offset ranges in [0, 1<<32) and the length in - [1, 65). The length is 1 + m. The offset is the little-endian unsigned - integer denoted by the next 4 bytes. -*/ -const ( - tagLiteral = 0x00 - tagCopy1 = 0x01 - tagCopy2 = 0x02 - tagCopy4 = 0x03 -) - -const ( - checksumSize = 4 - chunkHeaderSize = 4 - magicChunk = "\xff\x06\x00\x00" + magicBody - magicBody = "sNaPpY" - - // maxBlockSize is the maximum size of the input to encodeBlock. It is not - // part of the wire format per se, but some parts of the encoder assume - // that an offset fits into a uint16. - // - // Also, for the framing format (Writer type instead of Encode function), - // https://github.com/google/snappy/blob/master/framing_format.txt says - // that "the uncompressed data in a chunk must be no longer than 65536 - // bytes". - maxBlockSize = 65536 - - // maxEncodedLenOfMaxBlockSize equals MaxEncodedLen(maxBlockSize), but is - // hard coded to be a const instead of a variable, so that obufLen can also - // be a const. Their equivalence is confirmed by - // TestMaxEncodedLenOfMaxBlockSize. - maxEncodedLenOfMaxBlockSize = 76490 - - obufHeaderLen = len(magicChunk) + checksumSize + chunkHeaderSize - obufLen = obufHeaderLen + maxEncodedLenOfMaxBlockSize -) - -const ( - chunkTypeCompressedData = 0x00 - chunkTypeUncompressedData = 0x01 - chunkTypePadding = 0xfe - chunkTypeStreamIdentifier = 0xff -) - -var crcTable = crc32.MakeTable(crc32.Castagnoli) - -// crc implements the checksum specified in section 3 of -// https://github.com/google/snappy/blob/master/framing_format.txt -func crc(b []byte) uint32 { - c := crc32.Update(0, crcTable, b) - return uint32(c>>15|c<<17) + 0xa282ead8 -} diff --git a/vendor/github.com/gorilla/context/.travis.yml b/vendor/github.com/gorilla/context/.travis.yml deleted file mode 100644 index 6f440f1..0000000 --- a/vendor/github.com/gorilla/context/.travis.yml +++ /dev/null @@ -1,19 +0,0 @@ -language: go -sudo: false - -matrix: - include: - - go: 1.3 - - go: 1.4 - - go: 1.5 - - go: 1.6 - - go: 1.7 - - go: tip - allow_failures: - - go: tip - -script: - - go get -t -v ./... - - diff -u <(echo -n) <(gofmt -d .) - - go vet $(go list ./... | grep -v /vendor/) - - go test -v -race ./... diff --git a/vendor/github.com/gorilla/context/LICENSE b/vendor/github.com/gorilla/context/LICENSE deleted file mode 100644 index 0e5fb87..0000000 --- a/vendor/github.com/gorilla/context/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012 Rodrigo Moraes. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/gorilla/context/README.md b/vendor/github.com/gorilla/context/README.md deleted file mode 100644 index 08f8669..0000000 --- a/vendor/github.com/gorilla/context/README.md +++ /dev/null @@ -1,10 +0,0 @@ -context -======= -[![Build Status](https://travis-ci.org/gorilla/context.png?branch=master)](https://travis-ci.org/gorilla/context) - -gorilla/context is a general purpose registry for global request variables. - -> Note: gorilla/context, having been born well before `context.Context` existed, does not play well -> with the shallow copying of the request that [`http.Request.WithContext`](https://golang.org/pkg/net/http/#Request.WithContext) (added to net/http Go 1.7 onwards) performs. You should either use *just* gorilla/context, or moving forward, the new `http.Request.Context()`. - -Read the full documentation here: http://www.gorillatoolkit.org/pkg/context diff --git a/vendor/github.com/gorilla/context/context.go b/vendor/github.com/gorilla/context/context.go deleted file mode 100644 index 81cb128..0000000 --- a/vendor/github.com/gorilla/context/context.go +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 2012 The Gorilla 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 - -import ( - "net/http" - "sync" - "time" -) - -var ( - mutex sync.RWMutex - data = make(map[*http.Request]map[interface{}]interface{}) - datat = make(map[*http.Request]int64) -) - -// Set stores a value for a given key in a given request. -func Set(r *http.Request, key, val interface{}) { - mutex.Lock() - if data[r] == nil { - data[r] = make(map[interface{}]interface{}) - datat[r] = time.Now().Unix() - } - data[r][key] = val - mutex.Unlock() -} - -// Get returns a value stored for a given key in a given request. -func Get(r *http.Request, key interface{}) interface{} { - mutex.RLock() - if ctx := data[r]; ctx != nil { - value := ctx[key] - mutex.RUnlock() - return value - } - mutex.RUnlock() - return nil -} - -// GetOk returns stored value and presence state like multi-value return of map access. -func GetOk(r *http.Request, key interface{}) (interface{}, bool) { - mutex.RLock() - if _, ok := data[r]; ok { - value, ok := data[r][key] - mutex.RUnlock() - return value, ok - } - mutex.RUnlock() - return nil, false -} - -// GetAll returns all stored values for the request as a map. Nil is returned for invalid requests. -func GetAll(r *http.Request) map[interface{}]interface{} { - mutex.RLock() - if context, ok := data[r]; ok { - result := make(map[interface{}]interface{}, len(context)) - for k, v := range context { - result[k] = v - } - mutex.RUnlock() - return result - } - mutex.RUnlock() - return nil -} - -// GetAllOk returns all stored values for the request as a map and a boolean value that indicates if -// the request was registered. -func GetAllOk(r *http.Request) (map[interface{}]interface{}, bool) { - mutex.RLock() - context, ok := data[r] - result := make(map[interface{}]interface{}, len(context)) - for k, v := range context { - result[k] = v - } - mutex.RUnlock() - return result, ok -} - -// Delete removes a value stored for a given key in a given request. -func Delete(r *http.Request, key interface{}) { - mutex.Lock() - if data[r] != nil { - delete(data[r], key) - } - mutex.Unlock() -} - -// Clear removes all values stored for a given request. -// -// This is usually called by a handler wrapper to clean up request -// variables at the end of a request lifetime. See ClearHandler(). -func Clear(r *http.Request) { - mutex.Lock() - clear(r) - mutex.Unlock() -} - -// clear is Clear without the lock. -func clear(r *http.Request) { - delete(data, r) - delete(datat, r) -} - -// Purge removes request data stored for longer than maxAge, in seconds. -// It returns the amount of requests removed. -// -// If maxAge <= 0, all request data is removed. -// -// This is only used for sanity check: in case context cleaning was not -// properly set some request data can be kept forever, consuming an increasing -// amount of memory. In case this is detected, Purge() must be called -// periodically until the problem is fixed. -func Purge(maxAge int) int { - mutex.Lock() - count := 0 - if maxAge <= 0 { - count = len(data) - data = make(map[*http.Request]map[interface{}]interface{}) - datat = make(map[*http.Request]int64) - } else { - min := time.Now().Unix() - int64(maxAge) - for r := range data { - if datat[r] < min { - clear(r) - count++ - } - } - } - mutex.Unlock() - return count -} - -// ClearHandler wraps an http.Handler and clears request values at the end -// of a request lifetime. -func ClearHandler(h http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - defer Clear(r) - h.ServeHTTP(w, r) - }) -} diff --git a/vendor/github.com/gorilla/context/doc.go b/vendor/github.com/gorilla/context/doc.go deleted file mode 100644 index 448d1bf..0000000 --- a/vendor/github.com/gorilla/context/doc.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 2012 The Gorilla 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 stores values shared during a request lifetime. - -Note: gorilla/context, having been born well before `context.Context` existed, -does not play well > with the shallow copying of the request that -[`http.Request.WithContext`](https://golang.org/pkg/net/http/#Request.WithContext) -(added to net/http Go 1.7 onwards) performs. You should either use *just* -gorilla/context, or moving forward, the new `http.Request.Context()`. - -For example, a router can set variables extracted from the URL and later -application handlers can access those values, or it can be used to store -sessions values to be saved at the end of a request. There are several -others common uses. - -The idea was posted by Brad Fitzpatrick to the go-nuts mailing list: - - http://groups.google.com/group/golang-nuts/msg/e2d679d303aa5d53 - -Here's the basic usage: first define the keys that you will need. The key -type is interface{} so a key can be of any type that supports equality. -Here we define a key using a custom int type to avoid name collisions: - - package foo - - import ( - "github.com/gorilla/context" - ) - - type key int - - const MyKey key = 0 - -Then set a variable. Variables are bound to an http.Request object, so you -need a request instance to set a value: - - context.Set(r, MyKey, "bar") - -The application can later access the variable using the same key you provided: - - func MyHandler(w http.ResponseWriter, r *http.Request) { - // val is "bar". - val := context.Get(r, foo.MyKey) - - // returns ("bar", true) - val, ok := context.GetOk(r, foo.MyKey) - // ... - } - -And that's all about the basic usage. We discuss some other ideas below. - -Any type can be stored in the context. To enforce a given type, make the key -private and wrap Get() and Set() to accept and return values of a specific -type: - - type key int - - const mykey key = 0 - - // GetMyKey returns a value for this package from the request values. - func GetMyKey(r *http.Request) SomeType { - if rv := context.Get(r, mykey); rv != nil { - return rv.(SomeType) - } - return nil - } - - // SetMyKey sets a value for this package in the request values. - func SetMyKey(r *http.Request, val SomeType) { - context.Set(r, mykey, val) - } - -Variables must be cleared at the end of a request, to remove all values -that were stored. This can be done in an http.Handler, after a request was -served. Just call Clear() passing the request: - - context.Clear(r) - -...or use ClearHandler(), which conveniently wraps an http.Handler to clear -variables at the end of a request lifetime. - -The Routers from the packages gorilla/mux and gorilla/pat call Clear() -so if you are using either of them you don't need to clear the context manually. -*/ -package context diff --git a/vendor/github.com/gorilla/mux/.travis.yml b/vendor/github.com/gorilla/mux/.travis.yml deleted file mode 100644 index ad0935d..0000000 --- a/vendor/github.com/gorilla/mux/.travis.yml +++ /dev/null @@ -1,23 +0,0 @@ -language: go -sudo: false - -matrix: - include: - - go: 1.5.x - - go: 1.6.x - - go: 1.7.x - - go: 1.8.x - - go: 1.9.x - - go: 1.10.x - - go: tip - allow_failures: - - go: tip - -install: - - # Skip - -script: - - go get -t -v ./... - - diff -u <(echo -n) <(gofmt -d .) - - go tool vet . - - go test -v -race ./... diff --git a/vendor/github.com/gorilla/mux/ISSUE_TEMPLATE.md b/vendor/github.com/gorilla/mux/ISSUE_TEMPLATE.md deleted file mode 100644 index 232be82..0000000 --- a/vendor/github.com/gorilla/mux/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,11 +0,0 @@ -**What version of Go are you running?** (Paste the output of `go version`) - - -**What version of gorilla/mux are you at?** (Paste the output of `git rev-parse HEAD` inside `$GOPATH/src/github.com/gorilla/mux`) - - -**Describe your problem** (and what you have tried so far) - - -**Paste a minimal, runnable, reproduction of your issue below** (use backticks to format it) - diff --git a/vendor/github.com/gorilla/mux/LICENSE b/vendor/github.com/gorilla/mux/LICENSE deleted file mode 100644 index 0e5fb87..0000000 --- a/vendor/github.com/gorilla/mux/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012 Rodrigo Moraes. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/gorilla/mux/README.md b/vendor/github.com/gorilla/mux/README.md deleted file mode 100644 index e424397..0000000 --- a/vendor/github.com/gorilla/mux/README.md +++ /dev/null @@ -1,649 +0,0 @@ -# gorilla/mux - -[![GoDoc](https://godoc.org/github.com/gorilla/mux?status.svg)](https://godoc.org/github.com/gorilla/mux) -[![Build Status](https://travis-ci.org/gorilla/mux.svg?branch=master)](https://travis-ci.org/gorilla/mux) -[![Sourcegraph](https://sourcegraph.com/github.com/gorilla/mux/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/mux?badge) - -![Gorilla Logo](http://www.gorillatoolkit.org/static/images/gorilla-icon-64.png) - -http://www.gorillatoolkit.org/pkg/mux - -Package `gorilla/mux` implements a request router and dispatcher for matching incoming requests to -their respective handler. - -The name mux stands for "HTTP request multiplexer". Like the standard `http.ServeMux`, `mux.Router` matches incoming requests against a list of registered routes and calls a handler for the route that matches the URL or other conditions. The main features are: - -* It implements the `http.Handler` interface so it is compatible with the standard `http.ServeMux`. -* Requests can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers. -* URL hosts, paths and query values can have variables with an optional regular expression. -* Registered URLs can be built, or "reversed", which helps maintaining references to resources. -* Routes can be used as subrouters: nested routes are only tested if the parent route matches. This is useful to define groups of routes that share common conditions like a host, a path prefix or other repeated attributes. As a bonus, this optimizes request matching. - ---- - -* [Install](#install) -* [Examples](#examples) -* [Matching Routes](#matching-routes) -* [Static Files](#static-files) -* [Registered URLs](#registered-urls) -* [Walking Routes](#walking-routes) -* [Graceful Shutdown](#graceful-shutdown) -* [Middleware](#middleware) -* [Testing Handlers](#testing-handlers) -* [Full Example](#full-example) - ---- - -## Install - -With a [correctly configured](https://golang.org/doc/install#testing) Go toolchain: - -```sh -go get -u github.com/gorilla/mux -``` - -## Examples - -Let's start registering a couple of URL paths and handlers: - -```go -func main() { - r := mux.NewRouter() - r.HandleFunc("/", HomeHandler) - r.HandleFunc("/products", ProductsHandler) - r.HandleFunc("/articles", ArticlesHandler) - http.Handle("/", r) -} -``` - -Here we register three routes mapping URL paths to handlers. This is equivalent to how `http.HandleFunc()` works: if an incoming request URL matches one of the paths, the corresponding handler is called passing (`http.ResponseWriter`, `*http.Request`) as parameters. - -Paths can have variables. They are defined using the format `{name}` or `{name:pattern}`. If a regular expression pattern is not defined, the matched variable will be anything until the next slash. For example: - -```go -r := mux.NewRouter() -r.HandleFunc("/products/{key}", ProductHandler) -r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler) -r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler) -``` - -The names are used to create a map of route variables which can be retrieved calling `mux.Vars()`: - -```go -func ArticlesCategoryHandler(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, "Category: %v\n", vars["category"]) -} -``` - -And this is all you need to know about the basic usage. More advanced options are explained below. - -### Matching Routes - -Routes can also be restricted to a domain or subdomain. Just define a host pattern to be matched. They can also have variables: - -```go -r := mux.NewRouter() -// Only matches if domain is "www.example.com". -r.Host("www.example.com") -// Matches a dynamic subdomain. -r.Host("{subdomain:[a-z]+}.domain.com") -``` - -There are several other matchers that can be added. To match path prefixes: - -```go -r.PathPrefix("/products/") -``` - -...or HTTP methods: - -```go -r.Methods("GET", "POST") -``` - -...or URL schemes: - -```go -r.Schemes("https") -``` - -...or header values: - -```go -r.Headers("X-Requested-With", "XMLHttpRequest") -``` - -...or query values: - -```go -r.Queries("key", "value") -``` - -...or to use a custom matcher function: - -```go -r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool { - return r.ProtoMajor == 0 -}) -``` - -...and finally, it is possible to combine several matchers in a single route: - -```go -r.HandleFunc("/products", ProductsHandler). - Host("www.example.com"). - Methods("GET"). - Schemes("http") -``` - -Routes are tested in the order they were added to the router. If two routes match, the first one wins: - -```go -r := mux.NewRouter() -r.HandleFunc("/specific", specificHandler) -r.PathPrefix("/").Handler(catchAllHandler) -``` - -Setting the same matching conditions again and again can be boring, so we have a way to group several routes that share the same requirements. We call it "subrouting". - -For example, let's say we have several URLs that should only match when the host is `www.example.com`. Create a route for that host and get a "subrouter" from it: - -```go -r := mux.NewRouter() -s := r.Host("www.example.com").Subrouter() -``` - -Then register routes in the subrouter: - -```go -s.HandleFunc("/products/", ProductsHandler) -s.HandleFunc("/products/{key}", ProductHandler) -s.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler) -``` - -The three URL paths we registered above will only be tested if the domain is `www.example.com`, because the subrouter is tested first. This is not only convenient, but also optimizes request matching. You can create subrouters combining any attribute matchers accepted by a route. - -Subrouters can be used to create domain or path "namespaces": you define subrouters in a central place and then parts of the app can register its paths relatively to a given subrouter. - -There's one more thing about subroutes. When a subrouter has a path prefix, the inner routes use it as base for their paths: - -```go -r := mux.NewRouter() -s := r.PathPrefix("/products").Subrouter() -// "/products/" -s.HandleFunc("/", ProductsHandler) -// "/products/{key}/" -s.HandleFunc("/{key}/", ProductHandler) -// "/products/{key}/details" -s.HandleFunc("/{key}/details", ProductDetailsHandler) -``` - - -### Static Files - -Note that the path provided to `PathPrefix()` represents a "wildcard": calling -`PathPrefix("/static/").Handler(...)` means that the handler will be passed any -request that matches "/static/\*". This makes it easy to serve static files with mux: - -```go -func main() { - var dir string - - flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir") - flag.Parse() - r := mux.NewRouter() - - // This will serve files under http://localhost:8000/static/ - r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir)))) - - srv := &http.Server{ - Handler: r, - Addr: "127.0.0.1:8000", - // Good practice: enforce timeouts for servers you create! - WriteTimeout: 15 * time.Second, - ReadTimeout: 15 * time.Second, - } - - log.Fatal(srv.ListenAndServe()) -} -``` - -### Registered URLs - -Now let's see how to build registered URLs. - -Routes can be named. All routes that define a name can have their URLs built, or "reversed". We define a name calling `Name()` on a route. For example: - -```go -r := mux.NewRouter() -r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). - Name("article") -``` - -To build a URL, get the route and call the `URL()` method, passing a sequence of key/value pairs for the route variables. For the previous route, we would do: - -```go -url, err := r.Get("article").URL("category", "technology", "id", "42") -``` - -...and the result will be a `url.URL` with the following path: - -``` -"/articles/technology/42" -``` - -This also works for host and query value variables: - -```go -r := mux.NewRouter() -r.Host("{subdomain}.domain.com"). - Path("/articles/{category}/{id:[0-9]+}"). - Queries("filter", "{filter}"). - HandlerFunc(ArticleHandler). - Name("article") - -// url.String() will be "http://news.domain.com/articles/technology/42?filter=gorilla" -url, err := r.Get("article").URL("subdomain", "news", - "category", "technology", - "id", "42", - "filter", "gorilla") -``` - -All variables defined in the route are required, and their values must conform to the corresponding patterns. These requirements guarantee that a generated URL will always match a registered route -- the only exception is for explicitly defined "build-only" routes which never match. - -Regex support also exists for matching Headers within a route. For example, we could do: - -```go -r.HeadersRegexp("Content-Type", "application/(text|json)") -``` - -...and the route will match both requests with a Content-Type of `application/json` as well as `application/text` - -There's also a way to build only the URL host or path for a route: use the methods `URLHost()` or `URLPath()` instead. For the previous route, we would do: - -```go -// "http://news.domain.com/" -host, err := r.Get("article").URLHost("subdomain", "news") - -// "/articles/technology/42" -path, err := r.Get("article").URLPath("category", "technology", "id", "42") -``` - -And if you use subrouters, host and path defined separately can be built as well: - -```go -r := mux.NewRouter() -s := r.Host("{subdomain}.domain.com").Subrouter() -s.Path("/articles/{category}/{id:[0-9]+}"). - HandlerFunc(ArticleHandler). - Name("article") - -// "http://news.domain.com/articles/technology/42" -url, err := r.Get("article").URL("subdomain", "news", - "category", "technology", - "id", "42") -``` - -### Walking Routes - -The `Walk` function on `mux.Router` can be used to visit all of the routes that are registered on a router. For example, -the following prints all of the registered routes: - -```go -package main - -import ( - "fmt" - "net/http" - "strings" - - "github.com/gorilla/mux" -) - -func handler(w http.ResponseWriter, r *http.Request) { - return -} - -func main() { - r := mux.NewRouter() - r.HandleFunc("/", handler) - r.HandleFunc("/products", handler).Methods("POST") - r.HandleFunc("/articles", handler).Methods("GET") - r.HandleFunc("/articles/{id}", handler).Methods("GET", "PUT") - r.HandleFunc("/authors", handler).Queries("surname", "{surname}") - err := r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error { - pathTemplate, err := route.GetPathTemplate() - if err == nil { - fmt.Println("ROUTE:", pathTemplate) - } - pathRegexp, err := route.GetPathRegexp() - if err == nil { - fmt.Println("Path regexp:", pathRegexp) - } - queriesTemplates, err := route.GetQueriesTemplates() - if err == nil { - fmt.Println("Queries templates:", strings.Join(queriesTemplates, ",")) - } - queriesRegexps, err := route.GetQueriesRegexp() - if err == nil { - fmt.Println("Queries regexps:", strings.Join(queriesRegexps, ",")) - } - methods, err := route.GetMethods() - if err == nil { - fmt.Println("Methods:", strings.Join(methods, ",")) - } - fmt.Println() - return nil - }) - - if err != nil { - fmt.Println(err) - } - - http.Handle("/", r) -} -``` - -### Graceful Shutdown - -Go 1.8 introduced the ability to [gracefully shutdown](https://golang.org/doc/go1.8#http_shutdown) a `*http.Server`. Here's how to do that alongside `mux`: - -```go -package main - -import ( - "context" - "flag" - "log" - "net/http" - "os" - "os/signal" - "time" - - "github.com/gorilla/mux" -) - -func main() { - var wait time.Duration - flag.DurationVar(&wait, "graceful-timeout", time.Second * 15, "the duration for which the server gracefully wait for existing connections to finish - e.g. 15s or 1m") - flag.Parse() - - r := mux.NewRouter() - // Add your routes as needed - - srv := &http.Server{ - Addr: "0.0.0.0:8080", - // Good practice to set timeouts to avoid Slowloris attacks. - WriteTimeout: time.Second * 15, - ReadTimeout: time.Second * 15, - IdleTimeout: time.Second * 60, - Handler: r, // Pass our instance of gorilla/mux in. - } - - // Run our server in a goroutine so that it doesn't block. - go func() { - if err := srv.ListenAndServe(); err != nil { - log.Println(err) - } - }() - - c := make(chan os.Signal, 1) - // We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C) - // SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught. - signal.Notify(c, os.Interrupt) - - // Block until we receive our signal. - <-c - - // Create a deadline to wait for. - ctx, cancel := context.WithTimeout(context.Background(), wait) - defer cancel() - // Doesn't block if no connections, but will otherwise wait - // until the timeout deadline. - srv.Shutdown(ctx) - // Optionally, you could run srv.Shutdown in a goroutine and block on - // <-ctx.Done() if your application should wait for other services - // to finalize based on context cancellation. - log.Println("shutting down") - os.Exit(0) -} -``` - -### Middleware - -Mux supports the addition of middlewares to a [Router](https://godoc.org/github.com/gorilla/mux#Router), which are executed in the order they are added if a match is found, including its subrouters. -Middlewares are (typically) small pieces of code which take one request, do something with it, and pass it down to another middleware or the final handler. Some common use cases for middleware are request logging, header manipulation, or `ResponseWriter` hijacking. - -Mux middlewares are defined using the de facto standard type: - -```go -type MiddlewareFunc func(http.Handler) http.Handler -``` - -Typically, the returned handler is a closure which does something with the http.ResponseWriter and http.Request passed to it, and then calls the handler passed as parameter to the MiddlewareFunc. This takes advantage of closures being able access variables from the context where they are created, while retaining the signature enforced by the receivers. - -A very basic middleware which logs the URI of the request being handled could be written as: - -```go -func loggingMiddleware(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // Do stuff here - log.Println(r.RequestURI) - // Call the next handler, which can be another middleware in the chain, or the final handler. - next.ServeHTTP(w, r) - }) -} -``` - -Middlewares can be added to a router using `Router.Use()`: - -```go -r := mux.NewRouter() -r.HandleFunc("/", handler) -r.Use(loggingMiddleware) -``` - -A more complex authentication middleware, which maps session token to users, could be written as: - -```go -// Define our struct -type authenticationMiddleware struct { - tokenUsers map[string]string -} - -// Initialize it somewhere -func (amw *authenticationMiddleware) Populate() { - amw.tokenUsers["00000000"] = "user0" - amw.tokenUsers["aaaaaaaa"] = "userA" - amw.tokenUsers["05f717e5"] = "randomUser" - amw.tokenUsers["deadbeef"] = "user0" -} - -// Middleware function, which will be called for each request -func (amw *authenticationMiddleware) Middleware(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - token := r.Header.Get("X-Session-Token") - - if user, found := amw.tokenUsers[token]; found { - // We found the token in our map - log.Printf("Authenticated user %s\n", user) - // Pass down the request to the next middleware (or final handler) - next.ServeHTTP(w, r) - } else { - // Write an error and stop the handler chain - http.Error(w, "Forbidden", http.StatusForbidden) - } - }) -} -``` - -```go -r := mux.NewRouter() -r.HandleFunc("/", handler) - -amw := authenticationMiddleware{} -amw.Populate() - -r.Use(amw.Middleware) -``` - -Note: The handler chain will be stopped if your middleware doesn't call `next.ServeHTTP()` with the corresponding parameters. This can be used to abort a request if the middleware writer wants to. Middlewares _should_ write to `ResponseWriter` if they _are_ going to terminate the request, and they _should not_ write to `ResponseWriter` if they _are not_ going to terminate it. - -### Testing Handlers - -Testing handlers in a Go web application is straightforward, and _mux_ doesn't complicate this any further. Given two files: `endpoints.go` and `endpoints_test.go`, here's how we'd test an application using _mux_. - -First, our simple HTTP handler: - -```go -// endpoints.go -package main - -func HealthCheckHandler(w http.ResponseWriter, r *http.Request) { - // A very simple health check. - w.WriteHeader(http.StatusOK) - w.Header().Set("Content-Type", "application/json") - - // In the future we could report back on the status of our DB, or our cache - // (e.g. Redis) by performing a simple PING, and include them in the response. - io.WriteString(w, `{"alive": true}`) -} - -func main() { - r := mux.NewRouter() - r.HandleFunc("/health", HealthCheckHandler) - - log.Fatal(http.ListenAndServe("localhost:8080", r)) -} -``` - -Our test code: - -```go -// endpoints_test.go -package main - -import ( - "net/http" - "net/http/httptest" - "testing" -) - -func TestHealthCheckHandler(t *testing.T) { - // Create a request to pass to our handler. We don't have any query parameters for now, so we'll - // pass 'nil' as the third parameter. - req, err := http.NewRequest("GET", "/health", nil) - if err != nil { - t.Fatal(err) - } - - // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response. - rr := httptest.NewRecorder() - handler := http.HandlerFunc(HealthCheckHandler) - - // Our handlers satisfy http.Handler, so we can call their ServeHTTP method - // directly and pass in our Request and ResponseRecorder. - handler.ServeHTTP(rr, req) - - // Check the status code is what we expect. - if status := rr.Code; status != http.StatusOK { - t.Errorf("handler returned wrong status code: got %v want %v", - status, http.StatusOK) - } - - // Check the response body is what we expect. - expected := `{"alive": true}` - if rr.Body.String() != expected { - t.Errorf("handler returned unexpected body: got %v want %v", - rr.Body.String(), expected) - } -} -``` - -In the case that our routes have [variables](#examples), we can pass those in the request. We could write -[table-driven tests](https://dave.cheney.net/2013/06/09/writing-table-driven-tests-in-go) to test multiple -possible route variables as needed. - -```go -// endpoints.go -func main() { - r := mux.NewRouter() - // A route with a route variable: - r.HandleFunc("/metrics/{type}", MetricsHandler) - - log.Fatal(http.ListenAndServe("localhost:8080", r)) -} -``` - -Our test file, with a table-driven test of `routeVariables`: - -```go -// endpoints_test.go -func TestMetricsHandler(t *testing.T) { - tt := []struct{ - routeVariable string - shouldPass bool - }{ - {"goroutines", true}, - {"heap", true}, - {"counters", true}, - {"queries", true}, - {"adhadaeqm3k", false}, - } - - for _, tc := range tt { - path := fmt.Sprintf("/metrics/%s", tc.routeVariable) - req, err := http.NewRequest("GET", path, nil) - if err != nil { - t.Fatal(err) - } - - rr := httptest.NewRecorder() - - // Need to create a router that we can pass the request through so that the vars will be added to the context - router := mux.NewRouter() - router.HandleFunc("/metrics/{type}", MetricsHandler) - router.ServeHTTP(rr, req) - - // In this case, our MetricsHandler returns a non-200 response - // for a route variable it doesn't know about. - if rr.Code == http.StatusOK && !tc.shouldPass { - t.Errorf("handler should have failed on routeVariable %s: got %v want %v", - tc.routeVariable, rr.Code, http.StatusOK) - } - } -} -``` - -## Full Example - -Here's a complete, runnable example of a small `mux` based server: - -```go -package main - -import ( - "net/http" - "log" - "github.com/gorilla/mux" -) - -func YourHandler(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("Gorilla!\n")) -} - -func main() { - r := mux.NewRouter() - // Routes consist of a path and a handler function. - r.HandleFunc("/", YourHandler) - - // Bind to a port and pass our router in - log.Fatal(http.ListenAndServe(":8000", r)) -} -``` - -## License - -BSD licensed. See the LICENSE file for details. diff --git a/vendor/github.com/gorilla/mux/context_gorilla.go b/vendor/github.com/gorilla/mux/context_gorilla.go deleted file mode 100644 index d7adaa8..0000000 --- a/vendor/github.com/gorilla/mux/context_gorilla.go +++ /dev/null @@ -1,26 +0,0 @@ -// +build !go1.7 - -package mux - -import ( - "net/http" - - "github.com/gorilla/context" -) - -func contextGet(r *http.Request, key interface{}) interface{} { - return context.Get(r, key) -} - -func contextSet(r *http.Request, key, val interface{}) *http.Request { - if val == nil { - return r - } - - context.Set(r, key, val) - return r -} - -func contextClear(r *http.Request) { - context.Clear(r) -} diff --git a/vendor/github.com/gorilla/mux/context_native.go b/vendor/github.com/gorilla/mux/context_native.go deleted file mode 100644 index 209cbea..0000000 --- a/vendor/github.com/gorilla/mux/context_native.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build go1.7 - -package mux - -import ( - "context" - "net/http" -) - -func contextGet(r *http.Request, key interface{}) interface{} { - return r.Context().Value(key) -} - -func contextSet(r *http.Request, key, val interface{}) *http.Request { - if val == nil { - return r - } - - return r.WithContext(context.WithValue(r.Context(), key, val)) -} - -func contextClear(r *http.Request) { - return -} diff --git a/vendor/github.com/gorilla/mux/doc.go b/vendor/github.com/gorilla/mux/doc.go deleted file mode 100644 index 38957de..0000000 --- a/vendor/github.com/gorilla/mux/doc.go +++ /dev/null @@ -1,306 +0,0 @@ -// Copyright 2012 The Gorilla 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 mux implements a request router and dispatcher. - -The name mux stands for "HTTP request multiplexer". Like the standard -http.ServeMux, mux.Router matches incoming requests against a list of -registered routes and calls a handler for the route that matches the URL -or other conditions. The main features are: - - * Requests can be matched based on URL host, path, path prefix, schemes, - header and query values, HTTP methods or using custom matchers. - * URL hosts, paths and query values can have variables with an optional - regular expression. - * Registered URLs can be built, or "reversed", which helps maintaining - references to resources. - * Routes can be used as subrouters: nested routes are only tested if the - parent route matches. This is useful to define groups of routes that - share common conditions like a host, a path prefix or other repeated - attributes. As a bonus, this optimizes request matching. - * It implements the http.Handler interface so it is compatible with the - standard http.ServeMux. - -Let's start registering a couple of URL paths and handlers: - - func main() { - r := mux.NewRouter() - r.HandleFunc("/", HomeHandler) - r.HandleFunc("/products", ProductsHandler) - r.HandleFunc("/articles", ArticlesHandler) - http.Handle("/", r) - } - -Here we register three routes mapping URL paths to handlers. This is -equivalent to how http.HandleFunc() works: if an incoming request URL matches -one of the paths, the corresponding handler is called passing -(http.ResponseWriter, *http.Request) as parameters. - -Paths can have variables. They are defined using the format {name} or -{name:pattern}. If a regular expression pattern is not defined, the matched -variable will be anything until the next slash. For example: - - r := mux.NewRouter() - r.HandleFunc("/products/{key}", ProductHandler) - r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler) - r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler) - -Groups can be used inside patterns, as long as they are non-capturing (?:re). For example: - - r.HandleFunc("/articles/{category}/{sort:(?:asc|desc|new)}", ArticlesCategoryHandler) - -The names are used to create a map of route variables which can be retrieved -calling mux.Vars(): - - vars := mux.Vars(request) - category := vars["category"] - -Note that if any capturing groups are present, mux will panic() during parsing. To prevent -this, convert any capturing groups to non-capturing, e.g. change "/{sort:(asc|desc)}" to -"/{sort:(?:asc|desc)}". This is a change from prior versions which behaved unpredictably -when capturing groups were present. - -And this is all you need to know about the basic usage. More advanced options -are explained below. - -Routes can also be restricted to a domain or subdomain. Just define a host -pattern to be matched. They can also have variables: - - r := mux.NewRouter() - // Only matches if domain is "www.example.com". - r.Host("www.example.com") - // Matches a dynamic subdomain. - r.Host("{subdomain:[a-z]+}.domain.com") - -There are several other matchers that can be added. To match path prefixes: - - r.PathPrefix("/products/") - -...or HTTP methods: - - r.Methods("GET", "POST") - -...or URL schemes: - - r.Schemes("https") - -...or header values: - - r.Headers("X-Requested-With", "XMLHttpRequest") - -...or query values: - - r.Queries("key", "value") - -...or to use a custom matcher function: - - r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool { - return r.ProtoMajor == 0 - }) - -...and finally, it is possible to combine several matchers in a single route: - - r.HandleFunc("/products", ProductsHandler). - Host("www.example.com"). - Methods("GET"). - Schemes("http") - -Setting the same matching conditions again and again can be boring, so we have -a way to group several routes that share the same requirements. -We call it "subrouting". - -For example, let's say we have several URLs that should only match when the -host is "www.example.com". Create a route for that host and get a "subrouter" -from it: - - r := mux.NewRouter() - s := r.Host("www.example.com").Subrouter() - -Then register routes in the subrouter: - - s.HandleFunc("/products/", ProductsHandler) - s.HandleFunc("/products/{key}", ProductHandler) - s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler) - -The three URL paths we registered above will only be tested if the domain is -"www.example.com", because the subrouter is tested first. This is not -only convenient, but also optimizes request matching. You can create -subrouters combining any attribute matchers accepted by a route. - -Subrouters can be used to create domain or path "namespaces": you define -subrouters in a central place and then parts of the app can register its -paths relatively to a given subrouter. - -There's one more thing about subroutes. When a subrouter has a path prefix, -the inner routes use it as base for their paths: - - r := mux.NewRouter() - s := r.PathPrefix("/products").Subrouter() - // "/products/" - s.HandleFunc("/", ProductsHandler) - // "/products/{key}/" - s.HandleFunc("/{key}/", ProductHandler) - // "/products/{key}/details" - s.HandleFunc("/{key}/details", ProductDetailsHandler) - -Note that the path provided to PathPrefix() represents a "wildcard": calling -PathPrefix("/static/").Handler(...) means that the handler will be passed any -request that matches "/static/*". This makes it easy to serve static files with mux: - - func main() { - var dir string - - flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir") - flag.Parse() - r := mux.NewRouter() - - // This will serve files under http://localhost:8000/static/ - r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir)))) - - srv := &http.Server{ - Handler: r, - Addr: "127.0.0.1:8000", - // Good practice: enforce timeouts for servers you create! - WriteTimeout: 15 * time.Second, - ReadTimeout: 15 * time.Second, - } - - log.Fatal(srv.ListenAndServe()) - } - -Now let's see how to build registered URLs. - -Routes can be named. All routes that define a name can have their URLs built, -or "reversed". We define a name calling Name() on a route. For example: - - r := mux.NewRouter() - r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). - Name("article") - -To build a URL, get the route and call the URL() method, passing a sequence of -key/value pairs for the route variables. For the previous route, we would do: - - url, err := r.Get("article").URL("category", "technology", "id", "42") - -...and the result will be a url.URL with the following path: - - "/articles/technology/42" - -This also works for host and query value variables: - - r := mux.NewRouter() - r.Host("{subdomain}.domain.com"). - Path("/articles/{category}/{id:[0-9]+}"). - Queries("filter", "{filter}"). - HandlerFunc(ArticleHandler). - Name("article") - - // url.String() will be "http://news.domain.com/articles/technology/42?filter=gorilla" - url, err := r.Get("article").URL("subdomain", "news", - "category", "technology", - "id", "42", - "filter", "gorilla") - -All variables defined in the route are required, and their values must -conform to the corresponding patterns. These requirements guarantee that a -generated URL will always match a registered route -- the only exception is -for explicitly defined "build-only" routes which never match. - -Regex support also exists for matching Headers within a route. For example, we could do: - - r.HeadersRegexp("Content-Type", "application/(text|json)") - -...and the route will match both requests with a Content-Type of `application/json` as well as -`application/text` - -There's also a way to build only the URL host or path for a route: -use the methods URLHost() or URLPath() instead. For the previous route, -we would do: - - // "http://news.domain.com/" - host, err := r.Get("article").URLHost("subdomain", "news") - - // "/articles/technology/42" - path, err := r.Get("article").URLPath("category", "technology", "id", "42") - -And if you use subrouters, host and path defined separately can be built -as well: - - r := mux.NewRouter() - s := r.Host("{subdomain}.domain.com").Subrouter() - s.Path("/articles/{category}/{id:[0-9]+}"). - HandlerFunc(ArticleHandler). - Name("article") - - // "http://news.domain.com/articles/technology/42" - url, err := r.Get("article").URL("subdomain", "news", - "category", "technology", - "id", "42") - -Mux supports the addition of middlewares to a Router, which are executed in the order they are added if a match is found, including its subrouters. Middlewares are (typically) small pieces of code which take one request, do something with it, and pass it down to another middleware or the final handler. Some common use cases for middleware are request logging, header manipulation, or ResponseWriter hijacking. - - type MiddlewareFunc func(http.Handler) http.Handler - -Typically, the returned handler is a closure which does something with the http.ResponseWriter and http.Request passed to it, and then calls the handler passed as parameter to the MiddlewareFunc (closures can access variables from the context where they are created). - -A very basic middleware which logs the URI of the request being handled could be written as: - - func simpleMw(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // Do stuff here - log.Println(r.RequestURI) - // Call the next handler, which can be another middleware in the chain, or the final handler. - next.ServeHTTP(w, r) - }) - } - -Middlewares can be added to a router using `Router.Use()`: - - r := mux.NewRouter() - r.HandleFunc("/", handler) - r.Use(simpleMw) - -A more complex authentication middleware, which maps session token to users, could be written as: - - // Define our struct - type authenticationMiddleware struct { - tokenUsers map[string]string - } - - // Initialize it somewhere - func (amw *authenticationMiddleware) Populate() { - amw.tokenUsers["00000000"] = "user0" - amw.tokenUsers["aaaaaaaa"] = "userA" - amw.tokenUsers["05f717e5"] = "randomUser" - amw.tokenUsers["deadbeef"] = "user0" - } - - // Middleware function, which will be called for each request - func (amw *authenticationMiddleware) Middleware(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - token := r.Header.Get("X-Session-Token") - - if user, found := amw.tokenUsers[token]; found { - // We found the token in our map - log.Printf("Authenticated user %s\n", user) - next.ServeHTTP(w, r) - } else { - http.Error(w, "Forbidden", http.StatusForbidden) - } - }) - } - - r := mux.NewRouter() - r.HandleFunc("/", handler) - - amw := authenticationMiddleware{} - amw.Populate() - - r.Use(amw.Middleware) - -Note: The handler chain will be stopped if your middleware doesn't call `next.ServeHTTP()` with the corresponding parameters. This can be used to abort a request if the middleware writer wants to. - -*/ -package mux diff --git a/vendor/github.com/gorilla/mux/middleware.go b/vendor/github.com/gorilla/mux/middleware.go deleted file mode 100644 index ceb812c..0000000 --- a/vendor/github.com/gorilla/mux/middleware.go +++ /dev/null @@ -1,72 +0,0 @@ -package mux - -import ( - "net/http" - "strings" -) - -// MiddlewareFunc is a function which receives an http.Handler and returns another http.Handler. -// Typically, the returned handler is a closure which does something with the http.ResponseWriter and http.Request passed -// to it, and then calls the handler passed as parameter to the MiddlewareFunc. -type MiddlewareFunc func(http.Handler) http.Handler - -// middleware interface is anything which implements a MiddlewareFunc named Middleware. -type middleware interface { - Middleware(handler http.Handler) http.Handler -} - -// Middleware allows MiddlewareFunc to implement the middleware interface. -func (mw MiddlewareFunc) Middleware(handler http.Handler) http.Handler { - return mw(handler) -} - -// Use appends a MiddlewareFunc to the chain. Middleware can be used to intercept or otherwise modify requests and/or responses, and are executed in the order that they are applied to the Router. -func (r *Router) Use(mwf ...MiddlewareFunc) { - for _, fn := range mwf { - r.middlewares = append(r.middlewares, fn) - } -} - -// useInterface appends a middleware to the chain. Middleware can be used to intercept or otherwise modify requests and/or responses, and are executed in the order that they are applied to the Router. -func (r *Router) useInterface(mw middleware) { - r.middlewares = append(r.middlewares, mw) -} - -// CORSMethodMiddleware sets the Access-Control-Allow-Methods response header -// on a request, by matching routes based only on paths. It also handles -// OPTIONS requests, by settings Access-Control-Allow-Methods, and then -// returning without calling the next http handler. -func CORSMethodMiddleware(r *Router) MiddlewareFunc { - return func(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - var allMethods []string - - err := r.Walk(func(route *Route, _ *Router, _ []*Route) error { - for _, m := range route.matchers { - if _, ok := m.(*routeRegexp); ok { - if m.Match(req, &RouteMatch{}) { - methods, err := route.GetMethods() - if err != nil { - return err - } - - allMethods = append(allMethods, methods...) - } - break - } - } - return nil - }) - - if err == nil { - w.Header().Set("Access-Control-Allow-Methods", strings.Join(append(allMethods, "OPTIONS"), ",")) - - if req.Method == "OPTIONS" { - return - } - } - - next.ServeHTTP(w, req) - }) - } -} diff --git a/vendor/github.com/gorilla/mux/mux.go b/vendor/github.com/gorilla/mux/mux.go deleted file mode 100644 index 4bbafa5..0000000 --- a/vendor/github.com/gorilla/mux/mux.go +++ /dev/null @@ -1,588 +0,0 @@ -// Copyright 2012 The Gorilla 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 mux - -import ( - "errors" - "fmt" - "net/http" - "path" - "regexp" -) - -var ( - // ErrMethodMismatch is returned when the method in the request does not match - // the method defined against the route. - ErrMethodMismatch = errors.New("method is not allowed") - // ErrNotFound is returned when no route match is found. - ErrNotFound = errors.New("no matching route was found") -) - -// NewRouter returns a new router instance. -func NewRouter() *Router { - return &Router{namedRoutes: make(map[string]*Route), KeepContext: false} -} - -// Router registers routes to be matched and dispatches a handler. -// -// It implements the http.Handler interface, so it can be registered to serve -// requests: -// -// var router = mux.NewRouter() -// -// func main() { -// http.Handle("/", router) -// } -// -// Or, for Google App Engine, register it in a init() function: -// -// func init() { -// http.Handle("/", router) -// } -// -// This will send all incoming requests to the router. -type Router struct { - // Configurable Handler to be used when no route matches. - NotFoundHandler http.Handler - - // Configurable Handler to be used when the request method does not match the route. - MethodNotAllowedHandler http.Handler - - // Parent route, if this is a subrouter. - parent parentRoute - // Routes to be matched, in order. - routes []*Route - // Routes by name for URL building. - namedRoutes map[string]*Route - // See Router.StrictSlash(). This defines the flag for new routes. - strictSlash bool - // See Router.SkipClean(). This defines the flag for new routes. - skipClean bool - // If true, do not clear the request context after handling the request. - // This has no effect when go1.7+ is used, since the context is stored - // on the request itself. - KeepContext bool - // see Router.UseEncodedPath(). This defines a flag for all routes. - useEncodedPath bool - // Slice of middlewares to be called after a match is found - middlewares []middleware -} - -// Match attempts to match the given request against the router's registered routes. -// -// If the request matches a route of this router or one of its subrouters the Route, -// Handler, and Vars fields of the the match argument are filled and this function -// returns true. -// -// If the request does not match any of this router's or its subrouters' routes -// then this function returns false. If available, a reason for the match failure -// will be filled in the match argument's MatchErr field. If the match failure type -// (eg: not found) has a registered handler, the handler is assigned to the Handler -// field of the match argument. -func (r *Router) Match(req *http.Request, match *RouteMatch) bool { - for _, route := range r.routes { - if route.Match(req, match) { - // Build middleware chain if no error was found - if match.MatchErr == nil { - for i := len(r.middlewares) - 1; i >= 0; i-- { - match.Handler = r.middlewares[i].Middleware(match.Handler) - } - } - return true - } - } - - if match.MatchErr == ErrMethodMismatch { - if r.MethodNotAllowedHandler != nil { - match.Handler = r.MethodNotAllowedHandler - return true - } - - return false - } - - // Closest match for a router (includes sub-routers) - if r.NotFoundHandler != nil { - match.Handler = r.NotFoundHandler - match.MatchErr = ErrNotFound - return true - } - - match.MatchErr = ErrNotFound - return false -} - -// ServeHTTP dispatches the handler registered in the matched route. -// -// When there is a match, the route variables can be retrieved calling -// mux.Vars(request). -func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { - if !r.skipClean { - path := req.URL.Path - if r.useEncodedPath { - path = req.URL.EscapedPath() - } - // Clean path to canonical form and redirect. - if p := cleanPath(path); p != path { - - // Added 3 lines (Philip Schlump) - It was dropping the query string and #whatever from query. - // This matches with fix in go 1.2 r.c. 4 for same problem. Go Issue: - // http://code.google.com/p/go/issues/detail?id=5252 - url := *req.URL - url.Path = p - p = url.String() - - w.Header().Set("Location", p) - w.WriteHeader(http.StatusMovedPermanently) - return - } - } - var match RouteMatch - var handler http.Handler - if r.Match(req, &match) { - handler = match.Handler - req = setVars(req, match.Vars) - req = setCurrentRoute(req, match.Route) - } - - if handler == nil && match.MatchErr == ErrMethodMismatch { - handler = methodNotAllowedHandler() - } - - if handler == nil { - handler = http.NotFoundHandler() - } - - if !r.KeepContext { - defer contextClear(req) - } - - handler.ServeHTTP(w, req) -} - -// Get returns a route registered with the given name. -func (r *Router) Get(name string) *Route { - return r.getNamedRoutes()[name] -} - -// GetRoute returns a route registered with the given name. This method -// was renamed to Get() and remains here for backwards compatibility. -func (r *Router) GetRoute(name string) *Route { - return r.getNamedRoutes()[name] -} - -// StrictSlash defines the trailing slash behavior for new routes. The initial -// value is false. -// -// When true, if the route path is "/path/", accessing "/path" will perform a redirect -// to the former and vice versa. In other words, your application will always -// see the path as specified in the route. -// -// When false, if the route path is "/path", accessing "/path/" will not match -// this route and vice versa. -// -// The re-direct is a HTTP 301 (Moved Permanently). Note that when this is set for -// routes with a non-idempotent method (e.g. POST, PUT), the subsequent re-directed -// request will be made as a GET by most clients. Use middleware or client settings -// to modify this behaviour as needed. -// -// Special case: when a route sets a path prefix using the PathPrefix() method, -// strict slash is ignored for that route because the redirect behavior can't -// be determined from a prefix alone. However, any subrouters created from that -// route inherit the original StrictSlash setting. -func (r *Router) StrictSlash(value bool) *Router { - r.strictSlash = value - return r -} - -// SkipClean defines the path cleaning behaviour for new routes. The initial -// value is false. Users should be careful about which routes are not cleaned -// -// When true, if the route path is "/path//to", it will remain with the double -// slash. This is helpful if you have a route like: /fetch/http://xkcd.com/534/ -// -// When false, the path will be cleaned, so /fetch/http://xkcd.com/534/ will -// become /fetch/http/xkcd.com/534 -func (r *Router) SkipClean(value bool) *Router { - r.skipClean = value - return r -} - -// UseEncodedPath tells the router to match the encoded original path -// to the routes. -// For eg. "/path/foo%2Fbar/to" will match the path "/path/{var}/to". -// -// If not called, the router will match the unencoded path to the routes. -// For eg. "/path/foo%2Fbar/to" will match the path "/path/foo/bar/to" -func (r *Router) UseEncodedPath() *Router { - r.useEncodedPath = true - return r -} - -// ---------------------------------------------------------------------------- -// parentRoute -// ---------------------------------------------------------------------------- - -func (r *Router) getBuildScheme() string { - if r.parent != nil { - return r.parent.getBuildScheme() - } - return "" -} - -// getNamedRoutes returns the map where named routes are registered. -func (r *Router) getNamedRoutes() map[string]*Route { - if r.namedRoutes == nil { - if r.parent != nil { - r.namedRoutes = r.parent.getNamedRoutes() - } else { - r.namedRoutes = make(map[string]*Route) - } - } - return r.namedRoutes -} - -// getRegexpGroup returns regexp definitions from the parent route, if any. -func (r *Router) getRegexpGroup() *routeRegexpGroup { - if r.parent != nil { - return r.parent.getRegexpGroup() - } - return nil -} - -func (r *Router) buildVars(m map[string]string) map[string]string { - if r.parent != nil { - m = r.parent.buildVars(m) - } - return m -} - -// ---------------------------------------------------------------------------- -// Route factories -// ---------------------------------------------------------------------------- - -// NewRoute registers an empty route. -func (r *Router) NewRoute() *Route { - route := &Route{parent: r, strictSlash: r.strictSlash, skipClean: r.skipClean, useEncodedPath: r.useEncodedPath} - r.routes = append(r.routes, route) - return route -} - -// Handle registers a new route with a matcher for the URL path. -// See Route.Path() and Route.Handler(). -func (r *Router) Handle(path string, handler http.Handler) *Route { - return r.NewRoute().Path(path).Handler(handler) -} - -// HandleFunc registers a new route with a matcher for the URL path. -// See Route.Path() and Route.HandlerFunc(). -func (r *Router) HandleFunc(path string, f func(http.ResponseWriter, - *http.Request)) *Route { - return r.NewRoute().Path(path).HandlerFunc(f) -} - -// Headers registers a new route with a matcher for request header values. -// See Route.Headers(). -func (r *Router) Headers(pairs ...string) *Route { - return r.NewRoute().Headers(pairs...) -} - -// Host registers a new route with a matcher for the URL host. -// See Route.Host(). -func (r *Router) Host(tpl string) *Route { - return r.NewRoute().Host(tpl) -} - -// MatcherFunc registers a new route with a custom matcher function. -// See Route.MatcherFunc(). -func (r *Router) MatcherFunc(f MatcherFunc) *Route { - return r.NewRoute().MatcherFunc(f) -} - -// Methods registers a new route with a matcher for HTTP methods. -// See Route.Methods(). -func (r *Router) Methods(methods ...string) *Route { - return r.NewRoute().Methods(methods...) -} - -// Path registers a new route with a matcher for the URL path. -// See Route.Path(). -func (r *Router) Path(tpl string) *Route { - return r.NewRoute().Path(tpl) -} - -// PathPrefix registers a new route with a matcher for the URL path prefix. -// See Route.PathPrefix(). -func (r *Router) PathPrefix(tpl string) *Route { - return r.NewRoute().PathPrefix(tpl) -} - -// Queries registers a new route with a matcher for URL query values. -// See Route.Queries(). -func (r *Router) Queries(pairs ...string) *Route { - return r.NewRoute().Queries(pairs...) -} - -// Schemes registers a new route with a matcher for URL schemes. -// See Route.Schemes(). -func (r *Router) Schemes(schemes ...string) *Route { - return r.NewRoute().Schemes(schemes...) -} - -// BuildVarsFunc registers a new route with a custom function for modifying -// route variables before building a URL. -func (r *Router) BuildVarsFunc(f BuildVarsFunc) *Route { - return r.NewRoute().BuildVarsFunc(f) -} - -// Walk walks the router and all its sub-routers, calling walkFn for each route -// in the tree. The routes are walked in the order they were added. Sub-routers -// are explored depth-first. -func (r *Router) Walk(walkFn WalkFunc) error { - return r.walk(walkFn, []*Route{}) -} - -// SkipRouter is used as a return value from WalkFuncs to indicate that the -// router that walk is about to descend down to should be skipped. -var SkipRouter = errors.New("skip this router") - -// WalkFunc is the type of the function called for each route visited by Walk. -// At every invocation, it is given the current route, and the current router, -// and a list of ancestor routes that lead to the current route. -type WalkFunc func(route *Route, router *Router, ancestors []*Route) error - -func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error { - for _, t := range r.routes { - err := walkFn(t, r, ancestors) - if err == SkipRouter { - continue - } - if err != nil { - return err - } - for _, sr := range t.matchers { - if h, ok := sr.(*Router); ok { - ancestors = append(ancestors, t) - err := h.walk(walkFn, ancestors) - if err != nil { - return err - } - ancestors = ancestors[:len(ancestors)-1] - } - } - if h, ok := t.handler.(*Router); ok { - ancestors = append(ancestors, t) - err := h.walk(walkFn, ancestors) - if err != nil { - return err - } - ancestors = ancestors[:len(ancestors)-1] - } - } - return nil -} - -// ---------------------------------------------------------------------------- -// Context -// ---------------------------------------------------------------------------- - -// RouteMatch stores information about a matched route. -type RouteMatch struct { - Route *Route - Handler http.Handler - Vars map[string]string - - // MatchErr is set to appropriate matching error - // It is set to ErrMethodMismatch if there is a mismatch in - // the request method and route method - MatchErr error -} - -type contextKey int - -const ( - varsKey contextKey = iota - routeKey -) - -// Vars returns the route variables for the current request, if any. -func Vars(r *http.Request) map[string]string { - if rv := contextGet(r, varsKey); rv != nil { - return rv.(map[string]string) - } - return nil -} - -// CurrentRoute returns the matched route for the current request, if any. -// This only works when called inside the handler of the matched route -// because the matched route is stored in the request context which is cleared -// after the handler returns, unless the KeepContext option is set on the -// Router. -func CurrentRoute(r *http.Request) *Route { - if rv := contextGet(r, routeKey); rv != nil { - return rv.(*Route) - } - return nil -} - -func setVars(r *http.Request, val interface{}) *http.Request { - return contextSet(r, varsKey, val) -} - -func setCurrentRoute(r *http.Request, val interface{}) *http.Request { - return contextSet(r, routeKey, val) -} - -// ---------------------------------------------------------------------------- -// Helpers -// ---------------------------------------------------------------------------- - -// cleanPath returns the canonical path for p, eliminating . and .. elements. -// Borrowed from the net/http package. -func cleanPath(p string) string { - if p == "" { - return "/" - } - if p[0] != '/' { - p = "/" + p - } - np := path.Clean(p) - // path.Clean removes trailing slash except for root; - // put the trailing slash back if necessary. - if p[len(p)-1] == '/' && np != "/" { - np += "/" - } - - return np -} - -// uniqueVars returns an error if two slices contain duplicated strings. -func uniqueVars(s1, s2 []string) error { - for _, v1 := range s1 { - for _, v2 := range s2 { - if v1 == v2 { - return fmt.Errorf("mux: duplicated route variable %q", v2) - } - } - } - return nil -} - -// checkPairs returns the count of strings passed in, and an error if -// the count is not an even number. -func checkPairs(pairs ...string) (int, error) { - length := len(pairs) - if length%2 != 0 { - return length, fmt.Errorf( - "mux: number of parameters must be multiple of 2, got %v", pairs) - } - return length, nil -} - -// mapFromPairsToString converts variadic string parameters to a -// string to string map. -func mapFromPairsToString(pairs ...string) (map[string]string, error) { - length, err := checkPairs(pairs...) - if err != nil { - return nil, err - } - m := make(map[string]string, length/2) - for i := 0; i < length; i += 2 { - m[pairs[i]] = pairs[i+1] - } - return m, nil -} - -// mapFromPairsToRegex converts variadic string parameters to a -// string to regex map. -func mapFromPairsToRegex(pairs ...string) (map[string]*regexp.Regexp, error) { - length, err := checkPairs(pairs...) - if err != nil { - return nil, err - } - m := make(map[string]*regexp.Regexp, length/2) - for i := 0; i < length; i += 2 { - regex, err := regexp.Compile(pairs[i+1]) - if err != nil { - return nil, err - } - m[pairs[i]] = regex - } - return m, nil -} - -// matchInArray returns true if the given string value is in the array. -func matchInArray(arr []string, value string) bool { - for _, v := range arr { - if v == value { - return true - } - } - return false -} - -// matchMapWithString returns true if the given key/value pairs exist in a given map. -func matchMapWithString(toCheck map[string]string, toMatch map[string][]string, canonicalKey bool) bool { - for k, v := range toCheck { - // Check if key exists. - if canonicalKey { - k = http.CanonicalHeaderKey(k) - } - if values := toMatch[k]; values == nil { - return false - } else if v != "" { - // If value was defined as an empty string we only check that the - // key exists. Otherwise we also check for equality. - valueExists := false - for _, value := range values { - if v == value { - valueExists = true - break - } - } - if !valueExists { - return false - } - } - } - return true -} - -// matchMapWithRegex returns true if the given key/value pairs exist in a given map compiled against -// the given regex -func matchMapWithRegex(toCheck map[string]*regexp.Regexp, toMatch map[string][]string, canonicalKey bool) bool { - for k, v := range toCheck { - // Check if key exists. - if canonicalKey { - k = http.CanonicalHeaderKey(k) - } - if values := toMatch[k]; values == nil { - return false - } else if v != nil { - // If value was defined as an empty string we only check that the - // key exists. Otherwise we also check for equality. - valueExists := false - for _, value := range values { - if v.MatchString(value) { - valueExists = true - break - } - } - if !valueExists { - return false - } - } - } - return true -} - -// methodNotAllowed replies to the request with an HTTP status code 405. -func methodNotAllowed(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusMethodNotAllowed) -} - -// methodNotAllowedHandler returns a simple request handler -// that replies to each request with a status code 405. -func methodNotAllowedHandler() http.Handler { return http.HandlerFunc(methodNotAllowed) } diff --git a/vendor/github.com/gorilla/mux/regexp.go b/vendor/github.com/gorilla/mux/regexp.go deleted file mode 100644 index 2b57e56..0000000 --- a/vendor/github.com/gorilla/mux/regexp.go +++ /dev/null @@ -1,332 +0,0 @@ -// Copyright 2012 The Gorilla 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 mux - -import ( - "bytes" - "fmt" - "net/http" - "net/url" - "regexp" - "strconv" - "strings" -) - -type routeRegexpOptions struct { - strictSlash bool - useEncodedPath bool -} - -type regexpType int - -const ( - regexpTypePath regexpType = 0 - regexpTypeHost regexpType = 1 - regexpTypePrefix regexpType = 2 - regexpTypeQuery regexpType = 3 -) - -// newRouteRegexp parses a route template and returns a routeRegexp, -// used to match a host, a path or a query string. -// -// It will extract named variables, assemble a regexp to be matched, create -// a "reverse" template to build URLs and compile regexps to validate variable -// values used in URL building. -// -// Previously we accepted only Python-like identifiers for variable -// names ([a-zA-Z_][a-zA-Z0-9_]*), but currently the only restriction is that -// name and pattern can't be empty, and names can't contain a colon. -func newRouteRegexp(tpl string, typ regexpType, options routeRegexpOptions) (*routeRegexp, error) { - // Check if it is well-formed. - idxs, errBraces := braceIndices(tpl) - if errBraces != nil { - return nil, errBraces - } - // Backup the original. - template := tpl - // Now let's parse it. - defaultPattern := "[^/]+" - if typ == regexpTypeQuery { - defaultPattern = ".*" - } else if typ == regexpTypeHost { - defaultPattern = "[^.]+" - } - // Only match strict slash if not matching - if typ != regexpTypePath { - options.strictSlash = false - } - // Set a flag for strictSlash. - endSlash := false - if options.strictSlash && strings.HasSuffix(tpl, "/") { - tpl = tpl[:len(tpl)-1] - endSlash = true - } - varsN := make([]string, len(idxs)/2) - varsR := make([]*regexp.Regexp, len(idxs)/2) - pattern := bytes.NewBufferString("") - pattern.WriteByte('^') - reverse := bytes.NewBufferString("") - var end int - var err error - for i := 0; i < len(idxs); i += 2 { - // Set all values we are interested in. - raw := tpl[end:idxs[i]] - end = idxs[i+1] - parts := strings.SplitN(tpl[idxs[i]+1:end-1], ":", 2) - name := parts[0] - patt := defaultPattern - if len(parts) == 2 { - patt = parts[1] - } - // Name or pattern can't be empty. - if name == "" || patt == "" { - return nil, fmt.Errorf("mux: missing name or pattern in %q", - tpl[idxs[i]:end]) - } - // Build the regexp pattern. - fmt.Fprintf(pattern, "%s(?P<%s>%s)", regexp.QuoteMeta(raw), varGroupName(i/2), patt) - - // Build the reverse template. - fmt.Fprintf(reverse, "%s%%s", raw) - - // Append variable name and compiled pattern. - varsN[i/2] = name - varsR[i/2], err = regexp.Compile(fmt.Sprintf("^%s$", patt)) - if err != nil { - return nil, err - } - } - // Add the remaining. - raw := tpl[end:] - pattern.WriteString(regexp.QuoteMeta(raw)) - if options.strictSlash { - pattern.WriteString("[/]?") - } - if typ == regexpTypeQuery { - // Add the default pattern if the query value is empty - if queryVal := strings.SplitN(template, "=", 2)[1]; queryVal == "" { - pattern.WriteString(defaultPattern) - } - } - if typ != regexpTypePrefix { - pattern.WriteByte('$') - } - reverse.WriteString(raw) - if endSlash { - reverse.WriteByte('/') - } - // Compile full regexp. - reg, errCompile := regexp.Compile(pattern.String()) - if errCompile != nil { - return nil, errCompile - } - - // Check for capturing groups which used to work in older versions - if reg.NumSubexp() != len(idxs)/2 { - panic(fmt.Sprintf("route %s contains capture groups in its regexp. ", template) + - "Only non-capturing groups are accepted: e.g. (?:pattern) instead of (pattern)") - } - - // Done! - return &routeRegexp{ - template: template, - regexpType: typ, - options: options, - regexp: reg, - reverse: reverse.String(), - varsN: varsN, - varsR: varsR, - }, nil -} - -// routeRegexp stores a regexp to match a host or path and information to -// collect and validate route variables. -type routeRegexp struct { - // The unmodified template. - template string - // The type of match - regexpType regexpType - // Options for matching - options routeRegexpOptions - // Expanded regexp. - regexp *regexp.Regexp - // Reverse template. - reverse string - // Variable names. - varsN []string - // Variable regexps (validators). - varsR []*regexp.Regexp -} - -// Match matches the regexp against the URL host or path. -func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool { - if r.regexpType != regexpTypeHost { - if r.regexpType == regexpTypeQuery { - return r.matchQueryString(req) - } - path := req.URL.Path - if r.options.useEncodedPath { - path = req.URL.EscapedPath() - } - return r.regexp.MatchString(path) - } - - return r.regexp.MatchString(getHost(req)) -} - -// url builds a URL part using the given values. -func (r *routeRegexp) url(values map[string]string) (string, error) { - urlValues := make([]interface{}, len(r.varsN)) - for k, v := range r.varsN { - value, ok := values[v] - if !ok { - return "", fmt.Errorf("mux: missing route variable %q", v) - } - if r.regexpType == regexpTypeQuery { - value = url.QueryEscape(value) - } - urlValues[k] = value - } - rv := fmt.Sprintf(r.reverse, urlValues...) - if !r.regexp.MatchString(rv) { - // The URL is checked against the full regexp, instead of checking - // individual variables. This is faster but to provide a good error - // message, we check individual regexps if the URL doesn't match. - for k, v := range r.varsN { - if !r.varsR[k].MatchString(values[v]) { - return "", fmt.Errorf( - "mux: variable %q doesn't match, expected %q", values[v], - r.varsR[k].String()) - } - } - } - return rv, nil -} - -// getURLQuery returns a single query parameter from a request URL. -// For a URL with foo=bar&baz=ding, we return only the relevant key -// value pair for the routeRegexp. -func (r *routeRegexp) getURLQuery(req *http.Request) string { - if r.regexpType != regexpTypeQuery { - return "" - } - templateKey := strings.SplitN(r.template, "=", 2)[0] - for key, vals := range req.URL.Query() { - if key == templateKey && len(vals) > 0 { - return key + "=" + vals[0] - } - } - return "" -} - -func (r *routeRegexp) matchQueryString(req *http.Request) bool { - return r.regexp.MatchString(r.getURLQuery(req)) -} - -// braceIndices returns the first level curly brace indices from a string. -// It returns an error in case of unbalanced braces. -func braceIndices(s string) ([]int, error) { - var level, idx int - var idxs []int - for i := 0; i < len(s); i++ { - switch s[i] { - case '{': - if level++; level == 1 { - idx = i - } - case '}': - if level--; level == 0 { - idxs = append(idxs, idx, i+1) - } else if level < 0 { - return nil, fmt.Errorf("mux: unbalanced braces in %q", s) - } - } - } - if level != 0 { - return nil, fmt.Errorf("mux: unbalanced braces in %q", s) - } - return idxs, nil -} - -// varGroupName builds a capturing group name for the indexed variable. -func varGroupName(idx int) string { - return "v" + strconv.Itoa(idx) -} - -// ---------------------------------------------------------------------------- -// routeRegexpGroup -// ---------------------------------------------------------------------------- - -// routeRegexpGroup groups the route matchers that carry variables. -type routeRegexpGroup struct { - host *routeRegexp - path *routeRegexp - queries []*routeRegexp -} - -// setMatch extracts the variables from the URL once a route matches. -func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route) { - // Store host variables. - if v.host != nil { - host := getHost(req) - matches := v.host.regexp.FindStringSubmatchIndex(host) - if len(matches) > 0 { - extractVars(host, matches, v.host.varsN, m.Vars) - } - } - path := req.URL.Path - if r.useEncodedPath { - path = req.URL.EscapedPath() - } - // Store path variables. - if v.path != nil { - matches := v.path.regexp.FindStringSubmatchIndex(path) - if len(matches) > 0 { - extractVars(path, matches, v.path.varsN, m.Vars) - // Check if we should redirect. - if v.path.options.strictSlash { - p1 := strings.HasSuffix(path, "/") - p2 := strings.HasSuffix(v.path.template, "/") - if p1 != p2 { - u, _ := url.Parse(req.URL.String()) - if p1 { - u.Path = u.Path[:len(u.Path)-1] - } else { - u.Path += "/" - } - m.Handler = http.RedirectHandler(u.String(), 301) - } - } - } - } - // Store query string variables. - for _, q := range v.queries { - queryURL := q.getURLQuery(req) - matches := q.regexp.FindStringSubmatchIndex(queryURL) - if len(matches) > 0 { - extractVars(queryURL, matches, q.varsN, m.Vars) - } - } -} - -// getHost tries its best to return the request host. -func getHost(r *http.Request) string { - if r.URL.IsAbs() { - return r.URL.Host - } - host := r.Host - // Slice off any port information. - if i := strings.Index(host, ":"); i != -1 { - host = host[:i] - } - return host - -} - -func extractVars(input string, matches []int, names []string, output map[string]string) { - for i, name := range names { - output[name] = input[matches[2*i+2]:matches[2*i+3]] - } -} diff --git a/vendor/github.com/gorilla/mux/route.go b/vendor/github.com/gorilla/mux/route.go deleted file mode 100644 index a591d73..0000000 --- a/vendor/github.com/gorilla/mux/route.go +++ /dev/null @@ -1,763 +0,0 @@ -// Copyright 2012 The Gorilla 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 mux - -import ( - "errors" - "fmt" - "net/http" - "net/url" - "regexp" - "strings" -) - -// Route stores information to match a request and build URLs. -type Route struct { - // Parent where the route was registered (a Router). - parent parentRoute - // Request handler for the route. - handler http.Handler - // List of matchers. - matchers []matcher - // Manager for the variables from host and path. - regexp *routeRegexpGroup - // If true, when the path pattern is "/path/", accessing "/path" will - // redirect to the former and vice versa. - strictSlash bool - // If true, when the path pattern is "/path//to", accessing "/path//to" - // will not redirect - skipClean bool - // If true, "/path/foo%2Fbar/to" will match the path "/path/{var}/to" - useEncodedPath bool - // The scheme used when building URLs. - buildScheme string - // If true, this route never matches: it is only used to build URLs. - buildOnly bool - // The name used to build URLs. - name string - // Error resulted from building a route. - err error - - buildVarsFunc BuildVarsFunc -} - -// SkipClean reports whether path cleaning is enabled for this route via -// Router.SkipClean. -func (r *Route) SkipClean() bool { - return r.skipClean -} - -// Match matches the route against the request. -func (r *Route) Match(req *http.Request, match *RouteMatch) bool { - if r.buildOnly || r.err != nil { - return false - } - - var matchErr error - - // Match everything. - for _, m := range r.matchers { - if matched := m.Match(req, match); !matched { - if _, ok := m.(methodMatcher); ok { - matchErr = ErrMethodMismatch - continue - } - matchErr = nil - return false - } - } - - if matchErr != nil { - match.MatchErr = matchErr - return false - } - - if match.MatchErr == ErrMethodMismatch { - // We found a route which matches request method, clear MatchErr - match.MatchErr = nil - // Then override the mis-matched handler - match.Handler = r.handler - } - - // Yay, we have a match. Let's collect some info about it. - if match.Route == nil { - match.Route = r - } - if match.Handler == nil { - match.Handler = r.handler - } - if match.Vars == nil { - match.Vars = make(map[string]string) - } - - // Set variables. - if r.regexp != nil { - r.regexp.setMatch(req, match, r) - } - return true -} - -// ---------------------------------------------------------------------------- -// Route attributes -// ---------------------------------------------------------------------------- - -// GetError returns an error resulted from building the route, if any. -func (r *Route) GetError() error { - return r.err -} - -// BuildOnly sets the route to never match: it is only used to build URLs. -func (r *Route) BuildOnly() *Route { - r.buildOnly = true - return r -} - -// Handler -------------------------------------------------------------------- - -// Handler sets a handler for the route. -func (r *Route) Handler(handler http.Handler) *Route { - if r.err == nil { - r.handler = handler - } - return r -} - -// HandlerFunc sets a handler function for the route. -func (r *Route) HandlerFunc(f func(http.ResponseWriter, *http.Request)) *Route { - return r.Handler(http.HandlerFunc(f)) -} - -// GetHandler returns the handler for the route, if any. -func (r *Route) GetHandler() http.Handler { - return r.handler -} - -// Name ----------------------------------------------------------------------- - -// Name sets the name for the route, used to build URLs. -// If the name was registered already it will be overwritten. -func (r *Route) Name(name string) *Route { - if r.name != "" { - r.err = fmt.Errorf("mux: route already has name %q, can't set %q", - r.name, name) - } - if r.err == nil { - r.name = name - r.getNamedRoutes()[name] = r - } - return r -} - -// GetName returns the name for the route, if any. -func (r *Route) GetName() string { - return r.name -} - -// ---------------------------------------------------------------------------- -// Matchers -// ---------------------------------------------------------------------------- - -// matcher types try to match a request. -type matcher interface { - Match(*http.Request, *RouteMatch) bool -} - -// addMatcher adds a matcher to the route. -func (r *Route) addMatcher(m matcher) *Route { - if r.err == nil { - r.matchers = append(r.matchers, m) - } - return r -} - -// addRegexpMatcher adds a host or path matcher and builder to a route. -func (r *Route) addRegexpMatcher(tpl string, typ regexpType) error { - if r.err != nil { - return r.err - } - r.regexp = r.getRegexpGroup() - if typ == regexpTypePath || typ == regexpTypePrefix { - if len(tpl) > 0 && tpl[0] != '/' { - return fmt.Errorf("mux: path must start with a slash, got %q", tpl) - } - if r.regexp.path != nil { - tpl = strings.TrimRight(r.regexp.path.template, "/") + tpl - } - } - rr, err := newRouteRegexp(tpl, typ, routeRegexpOptions{ - strictSlash: r.strictSlash, - useEncodedPath: r.useEncodedPath, - }) - if err != nil { - return err - } - for _, q := range r.regexp.queries { - if err = uniqueVars(rr.varsN, q.varsN); err != nil { - return err - } - } - if typ == regexpTypeHost { - if r.regexp.path != nil { - if err = uniqueVars(rr.varsN, r.regexp.path.varsN); err != nil { - return err - } - } - r.regexp.host = rr - } else { - if r.regexp.host != nil { - if err = uniqueVars(rr.varsN, r.regexp.host.varsN); err != nil { - return err - } - } - if typ == regexpTypeQuery { - r.regexp.queries = append(r.regexp.queries, rr) - } else { - r.regexp.path = rr - } - } - r.addMatcher(rr) - return nil -} - -// Headers -------------------------------------------------------------------- - -// headerMatcher matches the request against header values. -type headerMatcher map[string]string - -func (m headerMatcher) Match(r *http.Request, match *RouteMatch) bool { - return matchMapWithString(m, r.Header, true) -} - -// Headers adds a matcher for request header values. -// It accepts a sequence of key/value pairs to be matched. For example: -// -// r := mux.NewRouter() -// r.Headers("Content-Type", "application/json", -// "X-Requested-With", "XMLHttpRequest") -// -// The above route will only match if both request header values match. -// If the value is an empty string, it will match any value if the key is set. -func (r *Route) Headers(pairs ...string) *Route { - if r.err == nil { - var headers map[string]string - headers, r.err = mapFromPairsToString(pairs...) - return r.addMatcher(headerMatcher(headers)) - } - return r -} - -// headerRegexMatcher matches the request against the route given a regex for the header -type headerRegexMatcher map[string]*regexp.Regexp - -func (m headerRegexMatcher) Match(r *http.Request, match *RouteMatch) bool { - return matchMapWithRegex(m, r.Header, true) -} - -// HeadersRegexp accepts a sequence of key/value pairs, where the value has regex -// support. For example: -// -// r := mux.NewRouter() -// r.HeadersRegexp("Content-Type", "application/(text|json)", -// "X-Requested-With", "XMLHttpRequest") -// -// The above route will only match if both the request header matches both regular expressions. -// If the value is an empty string, it will match any value if the key is set. -// Use the start and end of string anchors (^ and $) to match an exact value. -func (r *Route) HeadersRegexp(pairs ...string) *Route { - if r.err == nil { - var headers map[string]*regexp.Regexp - headers, r.err = mapFromPairsToRegex(pairs...) - return r.addMatcher(headerRegexMatcher(headers)) - } - return r -} - -// Host ----------------------------------------------------------------------- - -// Host adds a matcher for the URL host. -// It accepts a template with zero or more URL variables enclosed by {}. -// Variables can define an optional regexp pattern to be matched: -// -// - {name} matches anything until the next dot. -// -// - {name:pattern} matches the given regexp pattern. -// -// For example: -// -// r := mux.NewRouter() -// r.Host("www.example.com") -// r.Host("{subdomain}.domain.com") -// r.Host("{subdomain:[a-z]+}.domain.com") -// -// Variable names must be unique in a given route. They can be retrieved -// calling mux.Vars(request). -func (r *Route) Host(tpl string) *Route { - r.err = r.addRegexpMatcher(tpl, regexpTypeHost) - return r -} - -// MatcherFunc ---------------------------------------------------------------- - -// MatcherFunc is the function signature used by custom matchers. -type MatcherFunc func(*http.Request, *RouteMatch) bool - -// Match returns the match for a given request. -func (m MatcherFunc) Match(r *http.Request, match *RouteMatch) bool { - return m(r, match) -} - -// MatcherFunc adds a custom function to be used as request matcher. -func (r *Route) MatcherFunc(f MatcherFunc) *Route { - return r.addMatcher(f) -} - -// Methods -------------------------------------------------------------------- - -// methodMatcher matches the request against HTTP methods. -type methodMatcher []string - -func (m methodMatcher) Match(r *http.Request, match *RouteMatch) bool { - return matchInArray(m, r.Method) -} - -// Methods adds a matcher for HTTP methods. -// It accepts a sequence of one or more methods to be matched, e.g.: -// "GET", "POST", "PUT". -func (r *Route) Methods(methods ...string) *Route { - for k, v := range methods { - methods[k] = strings.ToUpper(v) - } - return r.addMatcher(methodMatcher(methods)) -} - -// Path ----------------------------------------------------------------------- - -// Path adds a matcher for the URL path. -// It accepts a template with zero or more URL variables enclosed by {}. The -// template must start with a "/". -// Variables can define an optional regexp pattern to be matched: -// -// - {name} matches anything until the next slash. -// -// - {name:pattern} matches the given regexp pattern. -// -// For example: -// -// r := mux.NewRouter() -// r.Path("/products/").Handler(ProductsHandler) -// r.Path("/products/{key}").Handler(ProductsHandler) -// r.Path("/articles/{category}/{id:[0-9]+}"). -// Handler(ArticleHandler) -// -// Variable names must be unique in a given route. They can be retrieved -// calling mux.Vars(request). -func (r *Route) Path(tpl string) *Route { - r.err = r.addRegexpMatcher(tpl, regexpTypePath) - return r -} - -// PathPrefix ----------------------------------------------------------------- - -// PathPrefix adds a matcher for the URL path prefix. This matches if the given -// template is a prefix of the full URL path. See Route.Path() for details on -// the tpl argument. -// -// Note that it does not treat slashes specially ("/foobar/" will be matched by -// the prefix "/foo") so you may want to use a trailing slash here. -// -// Also note that the setting of Router.StrictSlash() has no effect on routes -// with a PathPrefix matcher. -func (r *Route) PathPrefix(tpl string) *Route { - r.err = r.addRegexpMatcher(tpl, regexpTypePrefix) - return r -} - -// Query ---------------------------------------------------------------------- - -// Queries adds a matcher for URL query values. -// It accepts a sequence of key/value pairs. Values may define variables. -// For example: -// -// r := mux.NewRouter() -// r.Queries("foo", "bar", "id", "{id:[0-9]+}") -// -// The above route will only match if the URL contains the defined queries -// values, e.g.: ?foo=bar&id=42. -// -// It the value is an empty string, it will match any value if the key is set. -// -// Variables can define an optional regexp pattern to be matched: -// -// - {name} matches anything until the next slash. -// -// - {name:pattern} matches the given regexp pattern. -func (r *Route) Queries(pairs ...string) *Route { - length := len(pairs) - if length%2 != 0 { - r.err = fmt.Errorf( - "mux: number of parameters must be multiple of 2, got %v", pairs) - return nil - } - for i := 0; i < length; i += 2 { - if r.err = r.addRegexpMatcher(pairs[i]+"="+pairs[i+1], regexpTypeQuery); r.err != nil { - return r - } - } - - return r -} - -// Schemes -------------------------------------------------------------------- - -// schemeMatcher matches the request against URL schemes. -type schemeMatcher []string - -func (m schemeMatcher) Match(r *http.Request, match *RouteMatch) bool { - return matchInArray(m, r.URL.Scheme) -} - -// Schemes adds a matcher for URL schemes. -// It accepts a sequence of schemes to be matched, e.g.: "http", "https". -func (r *Route) Schemes(schemes ...string) *Route { - for k, v := range schemes { - schemes[k] = strings.ToLower(v) - } - if r.buildScheme == "" && len(schemes) > 0 { - r.buildScheme = schemes[0] - } - return r.addMatcher(schemeMatcher(schemes)) -} - -// BuildVarsFunc -------------------------------------------------------------- - -// BuildVarsFunc is the function signature used by custom build variable -// functions (which can modify route variables before a route's URL is built). -type BuildVarsFunc func(map[string]string) map[string]string - -// BuildVarsFunc adds a custom function to be used to modify build variables -// before a route's URL is built. -func (r *Route) BuildVarsFunc(f BuildVarsFunc) *Route { - r.buildVarsFunc = f - return r -} - -// Subrouter ------------------------------------------------------------------ - -// Subrouter creates a subrouter for the route. -// -// It will test the inner routes only if the parent route matched. For example: -// -// r := mux.NewRouter() -// s := r.Host("www.example.com").Subrouter() -// s.HandleFunc("/products/", ProductsHandler) -// s.HandleFunc("/products/{key}", ProductHandler) -// s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler) -// -// Here, the routes registered in the subrouter won't be tested if the host -// doesn't match. -func (r *Route) Subrouter() *Router { - router := &Router{parent: r, strictSlash: r.strictSlash} - r.addMatcher(router) - return router -} - -// ---------------------------------------------------------------------------- -// URL building -// ---------------------------------------------------------------------------- - -// URL builds a URL for the route. -// -// It accepts a sequence of key/value pairs for the route variables. For -// example, given this route: -// -// r := mux.NewRouter() -// r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). -// Name("article") -// -// ...a URL for it can be built using: -// -// url, err := r.Get("article").URL("category", "technology", "id", "42") -// -// ...which will return an url.URL with the following path: -// -// "/articles/technology/42" -// -// This also works for host variables: -// -// r := mux.NewRouter() -// r.Host("{subdomain}.domain.com"). -// HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). -// Name("article") -// -// // url.String() will be "http://news.domain.com/articles/technology/42" -// url, err := r.Get("article").URL("subdomain", "news", -// "category", "technology", -// "id", "42") -// -// All variables defined in the route are required, and their values must -// conform to the corresponding patterns. -func (r *Route) URL(pairs ...string) (*url.URL, error) { - if r.err != nil { - return nil, r.err - } - if r.regexp == nil { - return nil, errors.New("mux: route doesn't have a host or path") - } - values, err := r.prepareVars(pairs...) - if err != nil { - return nil, err - } - var scheme, host, path string - queries := make([]string, 0, len(r.regexp.queries)) - if r.regexp.host != nil { - if host, err = r.regexp.host.url(values); err != nil { - return nil, err - } - scheme = "http" - if s := r.getBuildScheme(); s != "" { - scheme = s - } - } - if r.regexp.path != nil { - if path, err = r.regexp.path.url(values); err != nil { - return nil, err - } - } - for _, q := range r.regexp.queries { - var query string - if query, err = q.url(values); err != nil { - return nil, err - } - queries = append(queries, query) - } - return &url.URL{ - Scheme: scheme, - Host: host, - Path: path, - RawQuery: strings.Join(queries, "&"), - }, nil -} - -// URLHost builds the host part of the URL for a route. See Route.URL(). -// -// The route must have a host defined. -func (r *Route) URLHost(pairs ...string) (*url.URL, error) { - if r.err != nil { - return nil, r.err - } - if r.regexp == nil || r.regexp.host == nil { - return nil, errors.New("mux: route doesn't have a host") - } - values, err := r.prepareVars(pairs...) - if err != nil { - return nil, err - } - host, err := r.regexp.host.url(values) - if err != nil { - return nil, err - } - u := &url.URL{ - Scheme: "http", - Host: host, - } - if s := r.getBuildScheme(); s != "" { - u.Scheme = s - } - return u, nil -} - -// URLPath builds the path part of the URL for a route. See Route.URL(). -// -// The route must have a path defined. -func (r *Route) URLPath(pairs ...string) (*url.URL, error) { - if r.err != nil { - return nil, r.err - } - if r.regexp == nil || r.regexp.path == nil { - return nil, errors.New("mux: route doesn't have a path") - } - values, err := r.prepareVars(pairs...) - if err != nil { - return nil, err - } - path, err := r.regexp.path.url(values) - if err != nil { - return nil, err - } - return &url.URL{ - Path: path, - }, nil -} - -// GetPathTemplate returns the template used to build the -// route match. -// This is useful for building simple REST API documentation and for instrumentation -// against third-party services. -// An error will be returned if the route does not define a path. -func (r *Route) GetPathTemplate() (string, error) { - if r.err != nil { - return "", r.err - } - if r.regexp == nil || r.regexp.path == nil { - return "", errors.New("mux: route doesn't have a path") - } - return r.regexp.path.template, nil -} - -// GetPathRegexp returns the expanded regular expression used to match route path. -// This is useful for building simple REST API documentation and for instrumentation -// against third-party services. -// An error will be returned if the route does not define a path. -func (r *Route) GetPathRegexp() (string, error) { - if r.err != nil { - return "", r.err - } - if r.regexp == nil || r.regexp.path == nil { - return "", errors.New("mux: route does not have a path") - } - return r.regexp.path.regexp.String(), nil -} - -// GetQueriesRegexp returns the expanded regular expressions used to match the -// route queries. -// This is useful for building simple REST API documentation and for instrumentation -// against third-party services. -// An error will be returned if the route does not have queries. -func (r *Route) GetQueriesRegexp() ([]string, error) { - if r.err != nil { - return nil, r.err - } - if r.regexp == nil || r.regexp.queries == nil { - return nil, errors.New("mux: route doesn't have queries") - } - var queries []string - for _, query := range r.regexp.queries { - queries = append(queries, query.regexp.String()) - } - return queries, nil -} - -// GetQueriesTemplates returns the templates used to build the -// query matching. -// This is useful for building simple REST API documentation and for instrumentation -// against third-party services. -// An error will be returned if the route does not define queries. -func (r *Route) GetQueriesTemplates() ([]string, error) { - if r.err != nil { - return nil, r.err - } - if r.regexp == nil || r.regexp.queries == nil { - return nil, errors.New("mux: route doesn't have queries") - } - var queries []string - for _, query := range r.regexp.queries { - queries = append(queries, query.template) - } - return queries, nil -} - -// GetMethods returns the methods the route matches against -// This is useful for building simple REST API documentation and for instrumentation -// against third-party services. -// An error will be returned if route does not have methods. -func (r *Route) GetMethods() ([]string, error) { - if r.err != nil { - return nil, r.err - } - for _, m := range r.matchers { - if methods, ok := m.(methodMatcher); ok { - return []string(methods), nil - } - } - return nil, errors.New("mux: route doesn't have methods") -} - -// GetHostTemplate returns the template used to build the -// route match. -// This is useful for building simple REST API documentation and for instrumentation -// against third-party services. -// An error will be returned if the route does not define a host. -func (r *Route) GetHostTemplate() (string, error) { - if r.err != nil { - return "", r.err - } - if r.regexp == nil || r.regexp.host == nil { - return "", errors.New("mux: route doesn't have a host") - } - return r.regexp.host.template, nil -} - -// prepareVars converts the route variable pairs into a map. If the route has a -// BuildVarsFunc, it is invoked. -func (r *Route) prepareVars(pairs ...string) (map[string]string, error) { - m, err := mapFromPairsToString(pairs...) - if err != nil { - return nil, err - } - return r.buildVars(m), nil -} - -func (r *Route) buildVars(m map[string]string) map[string]string { - if r.parent != nil { - m = r.parent.buildVars(m) - } - if r.buildVarsFunc != nil { - m = r.buildVarsFunc(m) - } - return m -} - -// ---------------------------------------------------------------------------- -// parentRoute -// ---------------------------------------------------------------------------- - -// parentRoute allows routes to know about parent host and path definitions. -type parentRoute interface { - getBuildScheme() string - getNamedRoutes() map[string]*Route - getRegexpGroup() *routeRegexpGroup - buildVars(map[string]string) map[string]string -} - -func (r *Route) getBuildScheme() string { - if r.buildScheme != "" { - return r.buildScheme - } - if r.parent != nil { - return r.parent.getBuildScheme() - } - return "" -} - -// getNamedRoutes returns the map where named routes are registered. -func (r *Route) getNamedRoutes() map[string]*Route { - if r.parent == nil { - // During tests router is not always set. - r.parent = NewRouter() - } - return r.parent.getNamedRoutes() -} - -// getRegexpGroup returns regexp definitions from this route. -func (r *Route) getRegexpGroup() *routeRegexpGroup { - if r.regexp == nil { - if r.parent == nil { - // During tests router is not always set. - r.parent = NewRouter() - } - regexp := r.parent.getRegexpGroup() - if regexp == nil { - r.regexp = new(routeRegexpGroup) - } else { - // Copy. - r.regexp = &routeRegexpGroup{ - host: regexp.host, - path: regexp.path, - queries: regexp.queries, - } - } - } - return r.regexp -} diff --git a/vendor/github.com/gorilla/mux/test_helpers.go b/vendor/github.com/gorilla/mux/test_helpers.go deleted file mode 100644 index 32ecffd..0000000 --- a/vendor/github.com/gorilla/mux/test_helpers.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2012 The Gorilla 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 mux - -import "net/http" - -// SetURLVars sets the URL variables for the given request, to be accessed via -// mux.Vars for testing route behaviour. Arguments are not modified, a shallow -// copy is returned. -// -// This API should only be used for testing purposes; it provides a way to -// inject variables into the request context. Alternatively, URL variables -// can be set by making a route that captures the required variables, -// starting a server and sending the request to that server. -func SetURLVars(r *http.Request, val map[string]string) *http.Request { - return setVars(r, val) -} diff --git a/vendor/github.com/gorilla/securecookie/.travis.yml b/vendor/github.com/gorilla/securecookie/.travis.yml deleted file mode 100644 index 6f440f1..0000000 --- a/vendor/github.com/gorilla/securecookie/.travis.yml +++ /dev/null @@ -1,19 +0,0 @@ -language: go -sudo: false - -matrix: - include: - - go: 1.3 - - go: 1.4 - - go: 1.5 - - go: 1.6 - - go: 1.7 - - go: tip - allow_failures: - - go: tip - -script: - - go get -t -v ./... - - diff -u <(echo -n) <(gofmt -d .) - - go vet $(go list ./... | grep -v /vendor/) - - go test -v -race ./... diff --git a/vendor/github.com/gorilla/securecookie/LICENSE b/vendor/github.com/gorilla/securecookie/LICENSE deleted file mode 100644 index 0e5fb87..0000000 --- a/vendor/github.com/gorilla/securecookie/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012 Rodrigo Moraes. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/gorilla/securecookie/README.md b/vendor/github.com/gorilla/securecookie/README.md deleted file mode 100644 index aa7bd1a..0000000 --- a/vendor/github.com/gorilla/securecookie/README.md +++ /dev/null @@ -1,80 +0,0 @@ -securecookie -============ -[![GoDoc](https://godoc.org/github.com/gorilla/securecookie?status.svg)](https://godoc.org/github.com/gorilla/securecookie) [![Build Status](https://travis-ci.org/gorilla/securecookie.png?branch=master)](https://travis-ci.org/gorilla/securecookie) -[![Sourcegraph](https://sourcegraph.com/github.com/gorilla/securecookie/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/securecookie?badge) - - -securecookie encodes and decodes authenticated and optionally encrypted -cookie values. - -Secure cookies can't be forged, because their values are validated using HMAC. -When encrypted, the content is also inaccessible to malicious eyes. It is still -recommended that sensitive data not be stored in cookies, and that HTTPS be used -to prevent cookie [replay attacks](https://en.wikipedia.org/wiki/Replay_attack). - -## Examples - -To use it, first create a new SecureCookie instance: - -```go -// Hash keys should be at least 32 bytes long -var hashKey = []byte("very-secret") -// Block keys should be 16 bytes (AES-128) or 32 bytes (AES-256) long. -// Shorter keys may weaken the encryption used. -var blockKey = []byte("a-lot-secret") -var s = securecookie.New(hashKey, blockKey) -``` - -The hashKey is required, used to authenticate the cookie value using HMAC. -It is recommended to use a key with 32 or 64 bytes. - -The blockKey is optional, used to encrypt the cookie value -- set it to nil -to not use encryption. If set, the length must correspond to the block size -of the encryption algorithm. For AES, used by default, valid lengths are -16, 24, or 32 bytes to select AES-128, AES-192, or AES-256. - -Strong keys can be created using the convenience function GenerateRandomKey(). - -Once a SecureCookie instance is set, use it to encode a cookie value: - -```go -func SetCookieHandler(w http.ResponseWriter, r *http.Request) { - value := map[string]string{ - "foo": "bar", - } - if encoded, err := s.Encode("cookie-name", value); err == nil { - cookie := &http.Cookie{ - Name: "cookie-name", - Value: encoded, - Path: "/", - Secure: true, - HttpOnly: true, - } - http.SetCookie(w, cookie) - } -} -``` - -Later, use the same SecureCookie instance to decode and validate a cookie -value: - -```go -func ReadCookieHandler(w http.ResponseWriter, r *http.Request) { - if cookie, err := r.Cookie("cookie-name"); err == nil { - value := make(map[string]string) - if err = s2.Decode("cookie-name", cookie.Value, &value); err == nil { - fmt.Fprintf(w, "The value of foo is %q", value["foo"]) - } - } -} -``` - -We stored a map[string]string, but secure cookies can hold any value that -can be encoded using `encoding/gob`. To store custom types, they must be -registered first using gob.Register(). For basic types this is not needed; -it works out of the box. An optional JSON encoder that uses `encoding/json` is -available for types compatible with JSON. - -## License - -BSD licensed. See the LICENSE file for details. diff --git a/vendor/github.com/gorilla/securecookie/doc.go b/vendor/github.com/gorilla/securecookie/doc.go deleted file mode 100644 index ae89408..0000000 --- a/vendor/github.com/gorilla/securecookie/doc.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2012 The Gorilla 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 securecookie encodes and decodes authenticated and optionally -encrypted cookie values. - -Secure cookies can't be forged, because their values are validated using HMAC. -When encrypted, the content is also inaccessible to malicious eyes. - -To use it, first create a new SecureCookie instance: - - var hashKey = []byte("very-secret") - var blockKey = []byte("a-lot-secret") - var s = securecookie.New(hashKey, blockKey) - -The hashKey is required, used to authenticate the cookie value using HMAC. -It is recommended to use a key with 32 or 64 bytes. - -The blockKey is optional, used to encrypt the cookie value -- set it to nil -to not use encryption. If set, the length must correspond to the block size -of the encryption algorithm. For AES, used by default, valid lengths are -16, 24, or 32 bytes to select AES-128, AES-192, or AES-256. - -Strong keys can be created using the convenience function GenerateRandomKey(). - -Once a SecureCookie instance is set, use it to encode a cookie value: - - func SetCookieHandler(w http.ResponseWriter, r *http.Request) { - value := map[string]string{ - "foo": "bar", - } - if encoded, err := s.Encode("cookie-name", value); err == nil { - cookie := &http.Cookie{ - Name: "cookie-name", - Value: encoded, - Path: "/", - } - http.SetCookie(w, cookie) - } - } - -Later, use the same SecureCookie instance to decode and validate a cookie -value: - - func ReadCookieHandler(w http.ResponseWriter, r *http.Request) { - if cookie, err := r.Cookie("cookie-name"); err == nil { - value := make(map[string]string) - if err = s2.Decode("cookie-name", cookie.Value, &value); err == nil { - fmt.Fprintf(w, "The value of foo is %q", value["foo"]) - } - } - } - -We stored a map[string]string, but secure cookies can hold any value that -can be encoded using encoding/gob. To store custom types, they must be -registered first using gob.Register(). For basic types this is not needed; -it works out of the box. -*/ -package securecookie diff --git a/vendor/github.com/gorilla/securecookie/fuzz.go b/vendor/github.com/gorilla/securecookie/fuzz.go deleted file mode 100644 index e4d0534..0000000 --- a/vendor/github.com/gorilla/securecookie/fuzz.go +++ /dev/null @@ -1,25 +0,0 @@ -// +build gofuzz - -package securecookie - -var hashKey = []byte("very-secret12345") -var blockKey = []byte("a-lot-secret1234") -var s = New(hashKey, blockKey) - -type Cookie struct { - B bool - I int - S string -} - -func Fuzz(data []byte) int { - datas := string(data) - var c Cookie - if err := s.Decode("fuzz", datas, &c); err != nil { - return 0 - } - if _, err := s.Encode("fuzz", c); err != nil { - panic(err) - } - return 1 -} diff --git a/vendor/github.com/gorilla/securecookie/securecookie.go b/vendor/github.com/gorilla/securecookie/securecookie.go deleted file mode 100644 index cd4e097..0000000 --- a/vendor/github.com/gorilla/securecookie/securecookie.go +++ /dev/null @@ -1,646 +0,0 @@ -// Copyright 2012 The Gorilla 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 securecookie - -import ( - "bytes" - "crypto/aes" - "crypto/cipher" - "crypto/hmac" - "crypto/rand" - "crypto/sha256" - "crypto/subtle" - "encoding/base64" - "encoding/gob" - "encoding/json" - "fmt" - "hash" - "io" - "strconv" - "strings" - "time" -) - -// Error is the interface of all errors returned by functions in this library. -type Error interface { - error - - // IsUsage returns true for errors indicating the client code probably - // uses this library incorrectly. For example, the client may have - // failed to provide a valid hash key, or may have failed to configure - // the Serializer adequately for encoding value. - IsUsage() bool - - // IsDecode returns true for errors indicating that a cookie could not - // be decoded and validated. Since cookies are usually untrusted - // user-provided input, errors of this type should be expected. - // Usually, the proper action is simply to reject the request. - IsDecode() bool - - // IsInternal returns true for unexpected errors occurring in the - // securecookie implementation. - IsInternal() bool - - // Cause, if it returns a non-nil value, indicates that this error was - // propagated from some underlying library. If this method returns nil, - // this error was raised directly by this library. - // - // Cause is provided principally for debugging/logging purposes; it is - // rare that application logic should perform meaningfully different - // logic based on Cause. See, for example, the caveats described on - // (MultiError).Cause(). - Cause() error -} - -// errorType is a bitmask giving the error type(s) of an cookieError value. -type errorType int - -const ( - usageError = errorType(1 << iota) - decodeError - internalError -) - -type cookieError struct { - typ errorType - msg string - cause error -} - -func (e cookieError) IsUsage() bool { return (e.typ & usageError) != 0 } -func (e cookieError) IsDecode() bool { return (e.typ & decodeError) != 0 } -func (e cookieError) IsInternal() bool { return (e.typ & internalError) != 0 } - -func (e cookieError) Cause() error { return e.cause } - -func (e cookieError) Error() string { - parts := []string{"securecookie: "} - if e.msg == "" { - parts = append(parts, "error") - } else { - parts = append(parts, e.msg) - } - if c := e.Cause(); c != nil { - parts = append(parts, " - caused by: ", c.Error()) - } - return strings.Join(parts, "") -} - -var ( - errGeneratingIV = cookieError{typ: internalError, msg: "failed to generate random iv"} - - errNoCodecs = cookieError{typ: usageError, msg: "no codecs provided"} - errHashKeyNotSet = cookieError{typ: usageError, msg: "hash key is not set"} - errBlockKeyNotSet = cookieError{typ: usageError, msg: "block key is not set"} - errEncodedValueTooLong = cookieError{typ: usageError, msg: "the value is too long"} - - errValueToDecodeTooLong = cookieError{typ: decodeError, msg: "the value is too long"} - errTimestampInvalid = cookieError{typ: decodeError, msg: "invalid timestamp"} - errTimestampTooNew = cookieError{typ: decodeError, msg: "timestamp is too new"} - errTimestampExpired = cookieError{typ: decodeError, msg: "expired timestamp"} - errDecryptionFailed = cookieError{typ: decodeError, msg: "the value could not be decrypted"} - errValueNotByte = cookieError{typ: decodeError, msg: "value not a []byte."} - errValueNotBytePtr = cookieError{typ: decodeError, msg: "value not a pointer to []byte."} - - // ErrMacInvalid indicates that cookie decoding failed because the HMAC - // could not be extracted and verified. Direct use of this error - // variable is deprecated; it is public only for legacy compatibility, - // and may be privatized in the future, as it is rarely useful to - // distinguish between this error and other Error implementations. - ErrMacInvalid = cookieError{typ: decodeError, msg: "the value is not valid"} -) - -// Codec defines an interface to encode and decode cookie values. -type Codec interface { - Encode(name string, value interface{}) (string, error) - Decode(name, value string, dst interface{}) error -} - -// New returns a new SecureCookie. -// -// hashKey is required, used to authenticate values using HMAC. Create it using -// GenerateRandomKey(). It is recommended to use a key with 32 or 64 bytes. -// -// blockKey is optional, used to encrypt values. Create it using -// GenerateRandomKey(). The key length must correspond to the block size -// of the encryption algorithm. For AES, used by default, valid lengths are -// 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256. -// The default encoder used for cookie serialization is encoding/gob. -// -// Note that keys created using GenerateRandomKey() are not automatically -// persisted. New keys will be created when the application is restarted, and -// previously issued cookies will not be able to be decoded. -func New(hashKey, blockKey []byte) *SecureCookie { - s := &SecureCookie{ - hashKey: hashKey, - blockKey: blockKey, - hashFunc: sha256.New, - maxAge: 86400 * 30, - maxLength: 4096, - sz: GobEncoder{}, - } - if hashKey == nil { - s.err = errHashKeyNotSet - } - if blockKey != nil { - s.BlockFunc(aes.NewCipher) - } - return s -} - -// SecureCookie encodes and decodes authenticated and optionally encrypted -// cookie values. -type SecureCookie struct { - hashKey []byte - hashFunc func() hash.Hash - blockKey []byte - block cipher.Block - maxLength int - maxAge int64 - minAge int64 - err error - sz Serializer - // For testing purposes, the function that returns the current timestamp. - // If not set, it will use time.Now().UTC().Unix(). - timeFunc func() int64 -} - -// Serializer provides an interface for providing custom serializers for cookie -// values. -type Serializer interface { - Serialize(src interface{}) ([]byte, error) - Deserialize(src []byte, dst interface{}) error -} - -// GobEncoder encodes cookie values using encoding/gob. This is the simplest -// encoder and can handle complex types via gob.Register. -type GobEncoder struct{} - -// JSONEncoder encodes cookie values using encoding/json. Users who wish to -// encode complex types need to satisfy the json.Marshaller and -// json.Unmarshaller interfaces. -type JSONEncoder struct{} - -// NopEncoder does not encode cookie values, and instead simply accepts a []byte -// (as an interface{}) and returns a []byte. This is particularly useful when -// you encoding an object upstream and do not wish to re-encode it. -type NopEncoder struct{} - -// MaxLength restricts the maximum length, in bytes, for the cookie value. -// -// Default is 4096, which is the maximum value accepted by Internet Explorer. -func (s *SecureCookie) MaxLength(value int) *SecureCookie { - s.maxLength = value - return s -} - -// MaxAge restricts the maximum age, in seconds, for the cookie value. -// -// Default is 86400 * 30. Set it to 0 for no restriction. -func (s *SecureCookie) MaxAge(value int) *SecureCookie { - s.maxAge = int64(value) - return s -} - -// MinAge restricts the minimum age, in seconds, for the cookie value. -// -// Default is 0 (no restriction). -func (s *SecureCookie) MinAge(value int) *SecureCookie { - s.minAge = int64(value) - return s -} - -// HashFunc sets the hash function used to create HMAC. -// -// Default is crypto/sha256.New. -func (s *SecureCookie) HashFunc(f func() hash.Hash) *SecureCookie { - s.hashFunc = f - return s -} - -// BlockFunc sets the encryption function used to create a cipher.Block. -// -// Default is crypto/aes.New. -func (s *SecureCookie) BlockFunc(f func([]byte) (cipher.Block, error)) *SecureCookie { - if s.blockKey == nil { - s.err = errBlockKeyNotSet - } else if block, err := f(s.blockKey); err == nil { - s.block = block - } else { - s.err = cookieError{cause: err, typ: usageError} - } - return s -} - -// Encoding sets the encoding/serialization method for cookies. -// -// Default is encoding/gob. To encode special structures using encoding/gob, -// they must be registered first using gob.Register(). -func (s *SecureCookie) SetSerializer(sz Serializer) *SecureCookie { - s.sz = sz - - return s -} - -// Encode encodes a cookie value. -// -// It serializes, optionally encrypts, signs with a message authentication code, -// and finally encodes the value. -// -// The name argument is the cookie name. It is stored with the encoded value. -// The value argument is the value to be encoded. It can be any value that can -// be encoded using the currently selected serializer; see SetSerializer(). -// -// It is the client's responsibility to ensure that value, when encoded using -// the current serialization/encryption settings on s and then base64-encoded, -// is shorter than the maximum permissible length. -func (s *SecureCookie) Encode(name string, value interface{}) (string, error) { - if s.err != nil { - return "", s.err - } - if s.hashKey == nil { - s.err = errHashKeyNotSet - return "", s.err - } - var err error - var b []byte - // 1. Serialize. - if b, err = s.sz.Serialize(value); err != nil { - return "", cookieError{cause: err, typ: usageError} - } - // 2. Encrypt (optional). - if s.block != nil { - if b, err = encrypt(s.block, b); err != nil { - return "", cookieError{cause: err, typ: usageError} - } - } - b = encode(b) - // 3. Create MAC for "name|date|value". Extra pipe to be used later. - b = []byte(fmt.Sprintf("%s|%d|%s|", name, s.timestamp(), b)) - mac := createMac(hmac.New(s.hashFunc, s.hashKey), b[:len(b)-1]) - // Append mac, remove name. - b = append(b, mac...)[len(name)+1:] - // 4. Encode to base64. - b = encode(b) - // 5. Check length. - if s.maxLength != 0 && len(b) > s.maxLength { - return "", errEncodedValueTooLong - } - // Done. - return string(b), nil -} - -// Decode decodes a cookie value. -// -// It decodes, verifies a message authentication code, optionally decrypts and -// finally deserializes the value. -// -// The name argument is the cookie name. It must be the same name used when -// it was stored. The value argument is the encoded cookie value. The dst -// argument is where the cookie will be decoded. It must be a pointer. -func (s *SecureCookie) Decode(name, value string, dst interface{}) error { - if s.err != nil { - return s.err - } - if s.hashKey == nil { - s.err = errHashKeyNotSet - return s.err - } - // 1. Check length. - if s.maxLength != 0 && len(value) > s.maxLength { - return errValueToDecodeTooLong - } - // 2. Decode from base64. - b, err := decode([]byte(value)) - if err != nil { - return err - } - // 3. Verify MAC. Value is "date|value|mac". - parts := bytes.SplitN(b, []byte("|"), 3) - if len(parts) != 3 { - return ErrMacInvalid - } - h := hmac.New(s.hashFunc, s.hashKey) - b = append([]byte(name+"|"), b[:len(b)-len(parts[2])-1]...) - if err = verifyMac(h, b, parts[2]); err != nil { - return err - } - // 4. Verify date ranges. - var t1 int64 - if t1, err = strconv.ParseInt(string(parts[0]), 10, 64); err != nil { - return errTimestampInvalid - } - t2 := s.timestamp() - if s.minAge != 0 && t1 > t2-s.minAge { - return errTimestampTooNew - } - if s.maxAge != 0 && t1 < t2-s.maxAge { - return errTimestampExpired - } - // 5. Decrypt (optional). - b, err = decode(parts[1]) - if err != nil { - return err - } - if s.block != nil { - if b, err = decrypt(s.block, b); err != nil { - return err - } - } - // 6. Deserialize. - if err = s.sz.Deserialize(b, dst); err != nil { - return cookieError{cause: err, typ: decodeError} - } - // Done. - return nil -} - -// timestamp returns the current timestamp, in seconds. -// -// For testing purposes, the function that generates the timestamp can be -// overridden. If not set, it will return time.Now().UTC().Unix(). -func (s *SecureCookie) timestamp() int64 { - if s.timeFunc == nil { - return time.Now().UTC().Unix() - } - return s.timeFunc() -} - -// Authentication ------------------------------------------------------------- - -// createMac creates a message authentication code (MAC). -func createMac(h hash.Hash, value []byte) []byte { - h.Write(value) - return h.Sum(nil) -} - -// verifyMac verifies that a message authentication code (MAC) is valid. -func verifyMac(h hash.Hash, value []byte, mac []byte) error { - mac2 := createMac(h, value) - // Check that both MACs are of equal length, as subtle.ConstantTimeCompare - // does not do this prior to Go 1.4. - if len(mac) == len(mac2) && subtle.ConstantTimeCompare(mac, mac2) == 1 { - return nil - } - return ErrMacInvalid -} - -// Encryption ----------------------------------------------------------------- - -// encrypt encrypts a value using the given block in counter mode. -// -// A random initialization vector (http://goo.gl/zF67k) with the length of the -// block size is prepended to the resulting ciphertext. -func encrypt(block cipher.Block, value []byte) ([]byte, error) { - iv := GenerateRandomKey(block.BlockSize()) - if iv == nil { - return nil, errGeneratingIV - } - // Encrypt it. - stream := cipher.NewCTR(block, iv) - stream.XORKeyStream(value, value) - // Return iv + ciphertext. - return append(iv, value...), nil -} - -// decrypt decrypts a value using the given block in counter mode. -// -// The value to be decrypted must be prepended by a initialization vector -// (http://goo.gl/zF67k) with the length of the block size. -func decrypt(block cipher.Block, value []byte) ([]byte, error) { - size := block.BlockSize() - if len(value) > size { - // Extract iv. - iv := value[:size] - // Extract ciphertext. - value = value[size:] - // Decrypt it. - stream := cipher.NewCTR(block, iv) - stream.XORKeyStream(value, value) - return value, nil - } - return nil, errDecryptionFailed -} - -// Serialization -------------------------------------------------------------- - -// Serialize encodes a value using gob. -func (e GobEncoder) Serialize(src interface{}) ([]byte, error) { - buf := new(bytes.Buffer) - enc := gob.NewEncoder(buf) - if err := enc.Encode(src); err != nil { - return nil, cookieError{cause: err, typ: usageError} - } - return buf.Bytes(), nil -} - -// Deserialize decodes a value using gob. -func (e GobEncoder) Deserialize(src []byte, dst interface{}) error { - dec := gob.NewDecoder(bytes.NewBuffer(src)) - if err := dec.Decode(dst); err != nil { - return cookieError{cause: err, typ: decodeError} - } - return nil -} - -// Serialize encodes a value using encoding/json. -func (e JSONEncoder) Serialize(src interface{}) ([]byte, error) { - buf := new(bytes.Buffer) - enc := json.NewEncoder(buf) - if err := enc.Encode(src); err != nil { - return nil, cookieError{cause: err, typ: usageError} - } - return buf.Bytes(), nil -} - -// Deserialize decodes a value using encoding/json. -func (e JSONEncoder) Deserialize(src []byte, dst interface{}) error { - dec := json.NewDecoder(bytes.NewReader(src)) - if err := dec.Decode(dst); err != nil { - return cookieError{cause: err, typ: decodeError} - } - return nil -} - -// Serialize passes a []byte through as-is. -func (e NopEncoder) Serialize(src interface{}) ([]byte, error) { - if b, ok := src.([]byte); ok { - return b, nil - } - - return nil, errValueNotByte -} - -// Deserialize passes a []byte through as-is. -func (e NopEncoder) Deserialize(src []byte, dst interface{}) error { - if dat, ok := dst.(*[]byte); ok { - *dat = src - return nil - } - return errValueNotBytePtr -} - -// Encoding ------------------------------------------------------------------- - -// encode encodes a value using base64. -func encode(value []byte) []byte { - encoded := make([]byte, base64.URLEncoding.EncodedLen(len(value))) - base64.URLEncoding.Encode(encoded, value) - return encoded -} - -// decode decodes a cookie using base64. -func decode(value []byte) ([]byte, error) { - decoded := make([]byte, base64.URLEncoding.DecodedLen(len(value))) - b, err := base64.URLEncoding.Decode(decoded, value) - if err != nil { - return nil, cookieError{cause: err, typ: decodeError, msg: "base64 decode failed"} - } - return decoded[:b], nil -} - -// Helpers -------------------------------------------------------------------- - -// GenerateRandomKey creates a random key with the given length in bytes. -// On failure, returns nil. -// -// Callers should explicitly check for the possibility of a nil return, treat -// it as a failure of the system random number generator, and not continue. -func GenerateRandomKey(length int) []byte { - k := make([]byte, length) - if _, err := io.ReadFull(rand.Reader, k); err != nil { - return nil - } - return k -} - -// CodecsFromPairs returns a slice of SecureCookie instances. -// -// It is a convenience function to create a list of codecs for key rotation. Note -// that the generated Codecs will have the default options applied: callers -// should iterate over each Codec and type-assert the underlying *SecureCookie to -// change these. -// -// Example: -// -// codecs := securecookie.CodecsFromPairs( -// []byte("new-hash-key"), -// []byte("new-block-key"), -// []byte("old-hash-key"), -// []byte("old-block-key"), -// ) -// -// // Modify each instance. -// for _, s := range codecs { -// if cookie, ok := s.(*securecookie.SecureCookie); ok { -// cookie.MaxAge(86400 * 7) -// cookie.SetSerializer(securecookie.JSONEncoder{}) -// cookie.HashFunc(sha512.New512_256) -// } -// } -// -func CodecsFromPairs(keyPairs ...[]byte) []Codec { - codecs := make([]Codec, len(keyPairs)/2+len(keyPairs)%2) - for i := 0; i < len(keyPairs); i += 2 { - var blockKey []byte - if i+1 < len(keyPairs) { - blockKey = keyPairs[i+1] - } - codecs[i/2] = New(keyPairs[i], blockKey) - } - return codecs -} - -// EncodeMulti encodes a cookie value using a group of codecs. -// -// The codecs are tried in order. Multiple codecs are accepted to allow -// key rotation. -// -// On error, may return a MultiError. -func EncodeMulti(name string, value interface{}, codecs ...Codec) (string, error) { - if len(codecs) == 0 { - return "", errNoCodecs - } - - var errors MultiError - for _, codec := range codecs { - encoded, err := codec.Encode(name, value) - if err == nil { - return encoded, nil - } - errors = append(errors, err) - } - return "", errors -} - -// DecodeMulti decodes a cookie value using a group of codecs. -// -// The codecs are tried in order. Multiple codecs are accepted to allow -// key rotation. -// -// On error, may return a MultiError. -func DecodeMulti(name string, value string, dst interface{}, codecs ...Codec) error { - if len(codecs) == 0 { - return errNoCodecs - } - - var errors MultiError - for _, codec := range codecs { - err := codec.Decode(name, value, dst) - if err == nil { - return nil - } - errors = append(errors, err) - } - return errors -} - -// MultiError groups multiple errors. -type MultiError []error - -func (m MultiError) IsUsage() bool { return m.any(func(e Error) bool { return e.IsUsage() }) } -func (m MultiError) IsDecode() bool { return m.any(func(e Error) bool { return e.IsDecode() }) } -func (m MultiError) IsInternal() bool { return m.any(func(e Error) bool { return e.IsInternal() }) } - -// Cause returns nil for MultiError; there is no unique underlying cause in the -// general case. -// -// Note: we could conceivably return a non-nil Cause only when there is exactly -// one child error with a Cause. However, it would be brittle for client code -// to rely on the arity of causes inside a MultiError, so we have opted not to -// provide this functionality. Clients which really wish to access the Causes -// of the underlying errors are free to iterate through the errors themselves. -func (m MultiError) Cause() error { return nil } - -func (m MultiError) Error() string { - s, n := "", 0 - for _, e := range m { - if e != nil { - if n == 0 { - s = e.Error() - } - n++ - } - } - switch n { - case 0: - return "(0 errors)" - case 1: - return s - case 2: - return s + " (and 1 other error)" - } - return fmt.Sprintf("%s (and %d other errors)", s, n-1) -} - -// any returns true if any element of m is an Error for which pred returns true. -func (m MultiError) any(pred func(Error) bool) bool { - for _, e := range m { - if ourErr, ok := e.(Error); ok && pred(ourErr) { - return true - } - } - return false -} diff --git a/vendor/github.com/gorilla/sessions/.travis.yml b/vendor/github.com/gorilla/sessions/.travis.yml deleted file mode 100644 index db17dd3..0000000 --- a/vendor/github.com/gorilla/sessions/.travis.yml +++ /dev/null @@ -1,22 +0,0 @@ -language: go -sudo: false - -matrix: - include: - - go: 1.3 - - go: 1.4 - - go: 1.5 - - go: 1.6 - - go: 1.7 - - go: tip - allow_failures: - - go: tip - -install: - - # skip - -script: - - go get -t -v ./... - - diff -u <(echo -n) <(gofmt -d .) - - go vet $(go list ./... | grep -v /vendor/) - - go test -v -race ./... diff --git a/vendor/github.com/gorilla/sessions/AUTHORS b/vendor/github.com/gorilla/sessions/AUTHORS deleted file mode 100644 index 1e3e7ac..0000000 --- a/vendor/github.com/gorilla/sessions/AUTHORS +++ /dev/null @@ -1,43 +0,0 @@ -# This is the official list of gorilla/sessions authors for copyright purposes. -# -# Please keep the list sorted. - -Ahmadreza Zibaei -Anton Lindström -Brian Jones -Collin Stedman -Deniz Eren -Dmitry Chestnykh -Dustin Oprea -Egon Elbre -enumappstore -Geofrey Ernest -Google LLC (https://opensource.google.com/) -Jerry Saravia -Jonathan Gillham -Justin Clift -Justin Hellings -Kamil Kisiel -Keiji Yoshida -kliron -Kshitij Saraogi -Lauris BH -Lukas Rist -Mark Dain -Matt Ho -Matt Silverlock -Mattias Wadman -Michael Schuett -Michael Stapelberg -Mirco Zeiss -moraes -nvcnvn -pappz -Pontus Leitzler -QuaSoft -rcadena -rodrigo moraes -Shawn Smith -Taylor Hurt -Tortuoise -Vitor De Mario diff --git a/vendor/github.com/gorilla/sessions/LICENSE b/vendor/github.com/gorilla/sessions/LICENSE deleted file mode 100644 index 6903df6..0000000 --- a/vendor/github.com/gorilla/sessions/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012-2018 The Gorilla Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/gorilla/sessions/README.md b/vendor/github.com/gorilla/sessions/README.md deleted file mode 100644 index c9e0e92..0000000 --- a/vendor/github.com/gorilla/sessions/README.md +++ /dev/null @@ -1,92 +0,0 @@ -sessions -======== -[![GoDoc](https://godoc.org/github.com/gorilla/sessions?status.svg)](https://godoc.org/github.com/gorilla/sessions) [![Build Status](https://travis-ci.org/gorilla/sessions.svg?branch=master)](https://travis-ci.org/gorilla/sessions) -[![Sourcegraph](https://sourcegraph.com/github.com/gorilla/sessions/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/sessions?badge) - - -gorilla/sessions provides cookie and filesystem sessions and infrastructure for -custom session backends. - -The key features are: - -* Simple API: use it as an easy way to set signed (and optionally - encrypted) cookies. -* Built-in backends to store sessions in cookies or the filesystem. -* Flash messages: session values that last until read. -* Convenient way to switch session persistency (aka "remember me") and set - other attributes. -* Mechanism to rotate authentication and encryption keys. -* Multiple sessions per request, even using different backends. -* Interfaces and infrastructure for custom session backends: sessions from - different stores can be retrieved and batch-saved using a common API. - -Let's start with an example that shows the sessions API in a nutshell: - -```go - import ( - "net/http" - "github.com/gorilla/sessions" - ) - - var store = sessions.NewCookieStore([]byte("something-very-secret")) - - func MyHandler(w http.ResponseWriter, r *http.Request) { - // Get a session. We're ignoring the error resulted from decoding an - // existing session: Get() always returns a session, even if empty. - session, _ := store.Get(r, "session-name") - // Set some session values. - session.Values["foo"] = "bar" - session.Values[42] = 43 - // Save it before we write to the response/return from the handler. - session.Save(r, w) - } -``` - -First we initialize a session store calling `NewCookieStore()` and passing a -secret key used to authenticate the session. Inside the handler, we call -`store.Get()` to retrieve an existing session or create a new one. Then we set -some session values in session.Values, which is a `map[interface{}]interface{}`. -And finally we call `session.Save()` to save the session in the response. - -Important Note: If you aren't using gorilla/mux, you need to wrap your handlers -with -[`context.ClearHandler`](http://www.gorillatoolkit.org/pkg/context#ClearHandler) -or else you will leak memory! An easy way to do this is to wrap the top-level -mux when calling http.ListenAndServe: - -```go - http.ListenAndServe(":8080", context.ClearHandler(http.DefaultServeMux)) -``` - -The ClearHandler function is provided by the gorilla/context package. - -More examples are available [on the Gorilla -website](http://www.gorillatoolkit.org/pkg/sessions). - -## Store Implementations - -Other implementations of the `sessions.Store` interface: - -* [github.com/starJammer/gorilla-sessions-arangodb](https://github.com/starJammer/gorilla-sessions-arangodb) - ArangoDB -* [github.com/yosssi/boltstore](https://github.com/yosssi/boltstore) - Bolt -* [github.com/srinathgs/couchbasestore](https://github.com/srinathgs/couchbasestore) - Couchbase -* [github.com/denizeren/dynamostore](https://github.com/denizeren/dynamostore) - Dynamodb on AWS -* [github.com/savaki/dynastore](https://github.com/savaki/dynastore) - DynamoDB on AWS (Official AWS library) -* [github.com/bradleypeabody/gorilla-sessions-memcache](https://github.com/bradleypeabody/gorilla-sessions-memcache) - Memcache -* [github.com/dsoprea/go-appengine-sessioncascade](https://github.com/dsoprea/go-appengine-sessioncascade) - Memcache/Datastore/Context in AppEngine -* [github.com/kidstuff/mongostore](https://github.com/kidstuff/mongostore) - MongoDB -* [github.com/srinathgs/mysqlstore](https://github.com/srinathgs/mysqlstore) - MySQL -* [github.com/EnumApps/clustersqlstore](https://github.com/EnumApps/clustersqlstore) - MySQL Cluster -* [github.com/antonlindstrom/pgstore](https://github.com/antonlindstrom/pgstore) - PostgreSQL -* [github.com/boj/redistore](https://github.com/boj/redistore) - Redis -* [github.com/boj/rethinkstore](https://github.com/boj/rethinkstore) - RethinkDB -* [github.com/boj/riakstore](https://github.com/boj/riakstore) - Riak -* [github.com/michaeljs1990/sqlitestore](https://github.com/michaeljs1990/sqlitestore) - SQLite -* [github.com/wader/gormstore](https://github.com/wader/gormstore) - GORM (MySQL, PostgreSQL, SQLite) -* [github.com/gernest/qlstore](https://github.com/gernest/qlstore) - ql -* [github.com/quasoft/memstore](https://github.com/quasoft/memstore) - In-memory implementation for use in unit tests -* [github.com/lafriks/xormstore](https://github.com/lafriks/xormstore) - XORM (MySQL, PostgreSQL, SQLite, Microsoft SQL Server, TiDB) - -## License - -BSD licensed. See the LICENSE file for details. diff --git a/vendor/github.com/gorilla/sessions/doc.go b/vendor/github.com/gorilla/sessions/doc.go deleted file mode 100644 index 57a5291..0000000 --- a/vendor/github.com/gorilla/sessions/doc.go +++ /dev/null @@ -1,198 +0,0 @@ -// Copyright 2012 The Gorilla 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 sessions provides cookie and filesystem sessions and -infrastructure for custom session backends. - -The key features are: - - * Simple API: use it as an easy way to set signed (and optionally - encrypted) cookies. - * Built-in backends to store sessions in cookies or the filesystem. - * Flash messages: session values that last until read. - * Convenient way to switch session persistency (aka "remember me") and set - other attributes. - * Mechanism to rotate authentication and encryption keys. - * Multiple sessions per request, even using different backends. - * Interfaces and infrastructure for custom session backends: sessions from - different stores can be retrieved and batch-saved using a common API. - -Let's start with an example that shows the sessions API in a nutshell: - - import ( - "net/http" - "github.com/gorilla/sessions" - ) - - var store = sessions.NewCookieStore([]byte("something-very-secret")) - - func MyHandler(w http.ResponseWriter, r *http.Request) { - // Get a session. Get() always returns a session, even if empty. - session, err := store.Get(r, "session-name") - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - - // Set some session values. - session.Values["foo"] = "bar" - session.Values[42] = 43 - // Save it before we write to the response/return from the handler. - session.Save(r, w) - } - -First we initialize a session store calling NewCookieStore() and passing a -secret key used to authenticate the session. Inside the handler, we call -store.Get() to retrieve an existing session or a new one. Then we set some -session values in session.Values, which is a map[interface{}]interface{}. -And finally we call session.Save() to save the session in the response. - -Note that in production code, we should check for errors when calling -session.Save(r, w), and either display an error message or otherwise handle it. - -Save must be called before writing to the response, otherwise the session -cookie will not be sent to the client. - -Important Note: If you aren't using gorilla/mux, you need to wrap your handlers -with context.ClearHandler as or else you will leak memory! An easy way to do this -is to wrap the top-level mux when calling http.ListenAndServe: - - http.ListenAndServe(":8080", context.ClearHandler(http.DefaultServeMux)) - -The ClearHandler function is provided by the gorilla/context package. - -That's all you need to know for the basic usage. Let's take a look at other -options, starting with flash messages. - -Flash messages are session values that last until read. The term appeared with -Ruby On Rails a few years back. When we request a flash message, it is removed -from the session. To add a flash, call session.AddFlash(), and to get all -flashes, call session.Flashes(). Here is an example: - - func MyHandler(w http.ResponseWriter, r *http.Request) { - // Get a session. - session, err := store.Get(r, "session-name") - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - - // Get the previous flashes, if any. - if flashes := session.Flashes(); len(flashes) > 0 { - // Use the flash values. - } else { - // Set a new flash. - session.AddFlash("Hello, flash messages world!") - } - session.Save(r, w) - } - -Flash messages are useful to set information to be read after a redirection, -like after form submissions. - -There may also be cases where you want to store a complex datatype within a -session, such as a struct. Sessions are serialised using the encoding/gob package, -so it is easy to register new datatypes for storage in sessions: - - import( - "encoding/gob" - "github.com/gorilla/sessions" - ) - - type Person struct { - FirstName string - LastName string - Email string - Age int - } - - type M map[string]interface{} - - func init() { - - gob.Register(&Person{}) - gob.Register(&M{}) - } - -As it's not possible to pass a raw type as a parameter to a function, gob.Register() -relies on us passing it a value of the desired type. In the example above we've passed -it a pointer to a struct and a pointer to a custom type representing a -map[string]interface. (We could have passed non-pointer values if we wished.) This will -then allow us to serialise/deserialise values of those types to and from our sessions. - -Note that because session values are stored in a map[string]interface{}, there's -a need to type-assert data when retrieving it. We'll use the Person struct we registered above: - - func MyHandler(w http.ResponseWriter, r *http.Request) { - session, err := store.Get(r, "session-name") - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - - // Retrieve our struct and type-assert it - val := session.Values["person"] - var person = &Person{} - if person, ok := val.(*Person); !ok { - // Handle the case that it's not an expected type - } - - // Now we can use our person object - } - -By default, session cookies last for a month. This is probably too long for -some cases, but it is easy to change this and other attributes during -runtime. Sessions can be configured individually or the store can be -configured and then all sessions saved using it will use that configuration. -We access session.Options or store.Options to set a new configuration. The -fields are basically a subset of http.Cookie fields. Let's change the -maximum age of a session to one week: - - session.Options = &sessions.Options{ - Path: "/", - MaxAge: 86400 * 7, - HttpOnly: true, - } - -Sometimes we may want to change authentication and/or encryption keys without -breaking existing sessions. The CookieStore supports key rotation, and to use -it you just need to set multiple authentication and encryption keys, in pairs, -to be tested in order: - - var store = sessions.NewCookieStore( - []byte("new-authentication-key"), - []byte("new-encryption-key"), - []byte("old-authentication-key"), - []byte("old-encryption-key"), - ) - -New sessions will be saved using the first pair. Old sessions can still be -read because the first pair will fail, and the second will be tested. This -makes it easy to "rotate" secret keys and still be able to validate existing -sessions. Note: for all pairs the encryption key is optional; set it to nil -or omit it and and encryption won't be used. - -Multiple sessions can be used in the same request, even with different -session backends. When this happens, calling Save() on each session -individually would be cumbersome, so we have a way to save all sessions -at once: it's sessions.Save(). Here's an example: - - var store = sessions.NewCookieStore([]byte("something-very-secret")) - - func MyHandler(w http.ResponseWriter, r *http.Request) { - // Get a session and set a value. - session1, _ := store.Get(r, "session-one") - session1.Values["foo"] = "bar" - // Get another session and set another value. - session2, _ := store.Get(r, "session-two") - session2.Values[42] = 43 - // Save all sessions. - sessions.Save(r, w) - } - -This is possible because when we call Get() from a session store, it adds the -session to a common registry. Save() uses it to save all registered sessions. -*/ -package sessions diff --git a/vendor/github.com/gorilla/sessions/go.mod b/vendor/github.com/gorilla/sessions/go.mod deleted file mode 100644 index 44befd4..0000000 --- a/vendor/github.com/gorilla/sessions/go.mod +++ /dev/null @@ -1,6 +0,0 @@ -module "github.com/gorilla/sessions" - -require ( - "github.com/gorilla/context" v1.1.1 - "github.com/gorilla/securecookie" v1.1.1 -) diff --git a/vendor/github.com/gorilla/sessions/lex.go b/vendor/github.com/gorilla/sessions/lex.go deleted file mode 100644 index 4bbbe10..0000000 --- a/vendor/github.com/gorilla/sessions/lex.go +++ /dev/null @@ -1,102 +0,0 @@ -// This file contains code adapted from the Go standard library -// https://github.com/golang/go/blob/39ad0fd0789872f9469167be7fe9578625ff246e/src/net/http/lex.go - -package sessions - -import "strings" - -var isTokenTable = [127]bool{ - '!': true, - '#': true, - '$': true, - '%': true, - '&': true, - '\'': true, - '*': true, - '+': true, - '-': true, - '.': true, - '0': true, - '1': true, - '2': true, - '3': true, - '4': true, - '5': true, - '6': true, - '7': true, - '8': true, - '9': true, - 'A': true, - 'B': true, - 'C': true, - 'D': true, - 'E': true, - 'F': true, - 'G': true, - 'H': true, - 'I': true, - 'J': true, - 'K': true, - 'L': true, - 'M': true, - 'N': true, - 'O': true, - 'P': true, - 'Q': true, - 'R': true, - 'S': true, - 'T': true, - 'U': true, - 'W': true, - 'V': true, - 'X': true, - 'Y': true, - 'Z': true, - '^': true, - '_': true, - '`': true, - 'a': true, - 'b': true, - 'c': true, - 'd': true, - 'e': true, - 'f': true, - 'g': true, - 'h': true, - 'i': true, - 'j': true, - 'k': true, - 'l': true, - 'm': true, - 'n': true, - 'o': true, - 'p': true, - 'q': true, - 'r': true, - 's': true, - 't': true, - 'u': true, - 'v': true, - 'w': true, - 'x': true, - 'y': true, - 'z': true, - '|': true, - '~': true, -} - -func isToken(r rune) bool { - i := int(r) - return i < len(isTokenTable) && isTokenTable[i] -} - -func isNotToken(r rune) bool { - return !isToken(r) -} - -func isCookieNameValid(raw string) bool { - if raw == "" { - return false - } - return strings.IndexFunc(raw, isNotToken) < 0 -} diff --git a/vendor/github.com/gorilla/sessions/sessions.go b/vendor/github.com/gorilla/sessions/sessions.go deleted file mode 100644 index 9870e31..0000000 --- a/vendor/github.com/gorilla/sessions/sessions.go +++ /dev/null @@ -1,243 +0,0 @@ -// Copyright 2012 The Gorilla 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 sessions - -import ( - "encoding/gob" - "fmt" - "net/http" - "time" - - "github.com/gorilla/context" -) - -// Default flashes key. -const flashesKey = "_flash" - -// Options -------------------------------------------------------------------- - -// Options stores configuration for a session or session store. -// -// Fields are a subset of http.Cookie fields. -type Options struct { - Path string - Domain string - // MaxAge=0 means no Max-Age attribute specified and the cookie will be - // deleted after the browser session ends. - // MaxAge<0 means delete cookie immediately. - // MaxAge>0 means Max-Age attribute present and given in seconds. - MaxAge int - Secure bool - HttpOnly bool -} - -// Session -------------------------------------------------------------------- - -// NewSession is called by session stores to create a new session instance. -func NewSession(store Store, name string) *Session { - return &Session{ - Values: make(map[interface{}]interface{}), - store: store, - name: name, - Options: new(Options), - } -} - -// Session stores the values and optional configuration for a session. -type Session struct { - // The ID of the session, generated by stores. It should not be used for - // user data. - ID string - // Values contains the user-data for the session. - Values map[interface{}]interface{} - Options *Options - IsNew bool - store Store - name string -} - -// Flashes returns a slice of flash messages from the session. -// -// A single variadic argument is accepted, and it is optional: it defines -// the flash key. If not defined "_flash" is used by default. -func (s *Session) Flashes(vars ...string) []interface{} { - var flashes []interface{} - key := flashesKey - if len(vars) > 0 { - key = vars[0] - } - if v, ok := s.Values[key]; ok { - // Drop the flashes and return it. - delete(s.Values, key) - flashes = v.([]interface{}) - } - return flashes -} - -// AddFlash adds a flash message to the session. -// -// A single variadic argument is accepted, and it is optional: it defines -// the flash key. If not defined "_flash" is used by default. -func (s *Session) AddFlash(value interface{}, vars ...string) { - key := flashesKey - if len(vars) > 0 { - key = vars[0] - } - var flashes []interface{} - if v, ok := s.Values[key]; ok { - flashes = v.([]interface{}) - } - s.Values[key] = append(flashes, value) -} - -// Save is a convenience method to save this session. It is the same as calling -// store.Save(request, response, session). You should call Save before writing to -// the response or returning from the handler. -func (s *Session) Save(r *http.Request, w http.ResponseWriter) error { - return s.store.Save(r, w, s) -} - -// Name returns the name used to register the session. -func (s *Session) Name() string { - return s.name -} - -// Store returns the session store used to register the session. -func (s *Session) Store() Store { - return s.store -} - -// Registry ------------------------------------------------------------------- - -// sessionInfo stores a session tracked by the registry. -type sessionInfo struct { - s *Session - e error -} - -// contextKey is the type used to store the registry in the context. -type contextKey int - -// registryKey is the key used to store the registry in the context. -const registryKey contextKey = 0 - -// GetRegistry returns a registry instance for the current request. -func GetRegistry(r *http.Request) *Registry { - registry := context.Get(r, registryKey) - if registry != nil { - return registry.(*Registry) - } - newRegistry := &Registry{ - request: r, - sessions: make(map[string]sessionInfo), - } - context.Set(r, registryKey, newRegistry) - return newRegistry -} - -// Registry stores sessions used during a request. -type Registry struct { - request *http.Request - sessions map[string]sessionInfo -} - -// Get registers and returns a session for the given name and session store. -// -// It returns a new session if there are no sessions registered for the name. -func (s *Registry) Get(store Store, name string) (session *Session, err error) { - if !isCookieNameValid(name) { - return nil, fmt.Errorf("sessions: invalid character in cookie name: %s", name) - } - if info, ok := s.sessions[name]; ok { - session, err = info.s, info.e - } else { - session, err = store.New(s.request, name) - session.name = name - s.sessions[name] = sessionInfo{s: session, e: err} - } - session.store = store - return -} - -// Save saves all sessions registered for the current request. -func (s *Registry) Save(w http.ResponseWriter) error { - var errMulti MultiError - for name, info := range s.sessions { - session := info.s - if session.store == nil { - errMulti = append(errMulti, fmt.Errorf( - "sessions: missing store for session %q", name)) - } else if err := session.store.Save(s.request, w, session); err != nil { - errMulti = append(errMulti, fmt.Errorf( - "sessions: error saving session %q -- %v", name, err)) - } - } - if errMulti != nil { - return errMulti - } - return nil -} - -// Helpers -------------------------------------------------------------------- - -func init() { - gob.Register([]interface{}{}) -} - -// Save saves all sessions used during the current request. -func Save(r *http.Request, w http.ResponseWriter) error { - return GetRegistry(r).Save(w) -} - -// NewCookie returns an http.Cookie with the options set. It also sets -// the Expires field calculated based on the MaxAge value, for Internet -// Explorer compatibility. -func NewCookie(name, value string, options *Options) *http.Cookie { - cookie := &http.Cookie{ - Name: name, - Value: value, - Path: options.Path, - Domain: options.Domain, - MaxAge: options.MaxAge, - Secure: options.Secure, - HttpOnly: options.HttpOnly, - } - if options.MaxAge > 0 { - d := time.Duration(options.MaxAge) * time.Second - cookie.Expires = time.Now().Add(d) - } else if options.MaxAge < 0 { - // Set it to the past to expire now. - cookie.Expires = time.Unix(1, 0) - } - return cookie -} - -// Error ---------------------------------------------------------------------- - -// MultiError stores multiple errors. -// -// Borrowed from the App Engine SDK. -type MultiError []error - -func (m MultiError) Error() string { - s, n := "", 0 - for _, e := range m { - if e != nil { - if n == 0 { - s = e.Error() - } - n++ - } - } - switch n { - case 0: - return "(0 errors)" - case 1: - return s - case 2: - return s + " (and 1 other error)" - } - return fmt.Sprintf("%s (and %d other errors)", s, n-1) -} diff --git a/vendor/github.com/gorilla/sessions/store.go b/vendor/github.com/gorilla/sessions/store.go deleted file mode 100644 index 4ff6b6c..0000000 --- a/vendor/github.com/gorilla/sessions/store.go +++ /dev/null @@ -1,295 +0,0 @@ -// Copyright 2012 The Gorilla 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 sessions - -import ( - "encoding/base32" - "io/ioutil" - "net/http" - "os" - "path/filepath" - "strings" - "sync" - - "github.com/gorilla/securecookie" -) - -// Store is an interface for custom session stores. -// -// See CookieStore and FilesystemStore for examples. -type Store interface { - // Get should return a cached session. - Get(r *http.Request, name string) (*Session, error) - - // New should create and return a new session. - // - // Note that New should never return a nil session, even in the case of - // an error if using the Registry infrastructure to cache the session. - New(r *http.Request, name string) (*Session, error) - - // Save should persist session to the underlying store implementation. - Save(r *http.Request, w http.ResponseWriter, s *Session) error -} - -// CookieStore ---------------------------------------------------------------- - -// NewCookieStore returns a new CookieStore. -// -// Keys are defined in pairs to allow key rotation, but the common case is -// to set a single authentication key and optionally an encryption key. -// -// The first key in a pair is used for authentication and the second for -// encryption. The encryption key can be set to nil or omitted in the last -// pair, but the authentication key is required in all pairs. -// -// It is recommended to use an authentication key with 32 or 64 bytes. -// The encryption key, if set, must be either 16, 24, or 32 bytes to select -// AES-128, AES-192, or AES-256 modes. -// -// Use the convenience function securecookie.GenerateRandomKey() to create -// strong keys. -func NewCookieStore(keyPairs ...[]byte) *CookieStore { - cs := &CookieStore{ - Codecs: securecookie.CodecsFromPairs(keyPairs...), - Options: &Options{ - Path: "/", - MaxAge: 86400 * 30, - }, - } - - cs.MaxAge(cs.Options.MaxAge) - return cs -} - -// CookieStore stores sessions using secure cookies. -type CookieStore struct { - Codecs []securecookie.Codec - Options *Options // default configuration -} - -// Get returns a session for the given name after adding it to the registry. -// -// It returns a new session if the sessions doesn't exist. Access IsNew on -// the session to check if it is an existing session or a new one. -// -// It returns a new session and an error if the session exists but could -// not be decoded. -func (s *CookieStore) Get(r *http.Request, name string) (*Session, error) { - return GetRegistry(r).Get(s, name) -} - -// New returns a session for the given name without adding it to the registry. -// -// The difference between New() and Get() is that calling New() twice will -// decode the session data twice, while Get() registers and reuses the same -// decoded session after the first call. -func (s *CookieStore) New(r *http.Request, name string) (*Session, error) { - session := NewSession(s, name) - opts := *s.Options - session.Options = &opts - session.IsNew = true - var err error - if c, errCookie := r.Cookie(name); errCookie == nil { - err = securecookie.DecodeMulti(name, c.Value, &session.Values, - s.Codecs...) - if err == nil { - session.IsNew = false - } - } - return session, err -} - -// Save adds a single session to the response. -func (s *CookieStore) Save(r *http.Request, w http.ResponseWriter, - session *Session) error { - encoded, err := securecookie.EncodeMulti(session.Name(), session.Values, - s.Codecs...) - if err != nil { - return err - } - http.SetCookie(w, NewCookie(session.Name(), encoded, session.Options)) - return nil -} - -// MaxAge sets the maximum age for the store and the underlying cookie -// implementation. Individual sessions can be deleted by setting Options.MaxAge -// = -1 for that session. -func (s *CookieStore) MaxAge(age int) { - s.Options.MaxAge = age - - // Set the maxAge for each securecookie instance. - for _, codec := range s.Codecs { - if sc, ok := codec.(*securecookie.SecureCookie); ok { - sc.MaxAge(age) - } - } -} - -// FilesystemStore ------------------------------------------------------------ - -var fileMutex sync.RWMutex - -// NewFilesystemStore returns a new FilesystemStore. -// -// The path argument is the directory where sessions will be saved. If empty -// it will use os.TempDir(). -// -// See NewCookieStore() for a description of the other parameters. -func NewFilesystemStore(path string, keyPairs ...[]byte) *FilesystemStore { - if path == "" { - path = os.TempDir() - } - fs := &FilesystemStore{ - Codecs: securecookie.CodecsFromPairs(keyPairs...), - Options: &Options{ - Path: "/", - MaxAge: 86400 * 30, - }, - path: path, - } - - fs.MaxAge(fs.Options.MaxAge) - return fs -} - -// FilesystemStore stores sessions in the filesystem. -// -// It also serves as a reference for custom stores. -// -// This store is still experimental and not well tested. Feedback is welcome. -type FilesystemStore struct { - Codecs []securecookie.Codec - Options *Options // default configuration - path string -} - -// MaxLength restricts the maximum length of new sessions to l. -// If l is 0 there is no limit to the size of a session, use with caution. -// The default for a new FilesystemStore is 4096. -func (s *FilesystemStore) MaxLength(l int) { - for _, c := range s.Codecs { - if codec, ok := c.(*securecookie.SecureCookie); ok { - codec.MaxLength(l) - } - } -} - -// Get returns a session for the given name after adding it to the registry. -// -// See CookieStore.Get(). -func (s *FilesystemStore) Get(r *http.Request, name string) (*Session, error) { - return GetRegistry(r).Get(s, name) -} - -// New returns a session for the given name without adding it to the registry. -// -// See CookieStore.New(). -func (s *FilesystemStore) New(r *http.Request, name string) (*Session, error) { - session := NewSession(s, name) - opts := *s.Options - session.Options = &opts - session.IsNew = true - var err error - if c, errCookie := r.Cookie(name); errCookie == nil { - err = securecookie.DecodeMulti(name, c.Value, &session.ID, s.Codecs...) - if err == nil { - err = s.load(session) - if err == nil { - session.IsNew = false - } - } - } - return session, err -} - -// Save adds a single session to the response. -// -// If the Options.MaxAge of the session is <= 0 then the session file will be -// deleted from the store path. With this process it enforces the properly -// session cookie handling so no need to trust in the cookie management in the -// web browser. -func (s *FilesystemStore) Save(r *http.Request, w http.ResponseWriter, - session *Session) error { - // Delete if max-age is <= 0 - if session.Options.MaxAge <= 0 { - if err := s.erase(session); err != nil { - return err - } - http.SetCookie(w, NewCookie(session.Name(), "", session.Options)) - return nil - } - - if session.ID == "" { - // Because the ID is used in the filename, encode it to - // use alphanumeric characters only. - session.ID = strings.TrimRight( - base32.StdEncoding.EncodeToString( - securecookie.GenerateRandomKey(32)), "=") - } - if err := s.save(session); err != nil { - return err - } - encoded, err := securecookie.EncodeMulti(session.Name(), session.ID, - s.Codecs...) - if err != nil { - return err - } - http.SetCookie(w, NewCookie(session.Name(), encoded, session.Options)) - return nil -} - -// MaxAge sets the maximum age for the store and the underlying cookie -// implementation. Individual sessions can be deleted by setting Options.MaxAge -// = -1 for that session. -func (s *FilesystemStore) MaxAge(age int) { - s.Options.MaxAge = age - - // Set the maxAge for each securecookie instance. - for _, codec := range s.Codecs { - if sc, ok := codec.(*securecookie.SecureCookie); ok { - sc.MaxAge(age) - } - } -} - -// save writes encoded session.Values to a file. -func (s *FilesystemStore) save(session *Session) error { - encoded, err := securecookie.EncodeMulti(session.Name(), session.Values, - s.Codecs...) - if err != nil { - return err - } - filename := filepath.Join(s.path, "session_"+session.ID) - fileMutex.Lock() - defer fileMutex.Unlock() - return ioutil.WriteFile(filename, []byte(encoded), 0600) -} - -// load reads a file and decodes its content into session.Values. -func (s *FilesystemStore) load(session *Session) error { - filename := filepath.Join(s.path, "session_"+session.ID) - fileMutex.RLock() - defer fileMutex.RUnlock() - fdata, err := ioutil.ReadFile(filename) - if err != nil { - return err - } - if err = securecookie.DecodeMulti(session.Name(), string(fdata), - &session.Values, s.Codecs...); err != nil { - return err - } - return nil -} - -// delete session file -func (s *FilesystemStore) erase(session *Session) error { - filename := filepath.Join(s.path, "session_"+session.ID) - - fileMutex.RLock() - defer fileMutex.RUnlock() - - err := os.Remove(filename) - return err -} diff --git a/vendor/github.com/hashicorp/errwrap/LICENSE b/vendor/github.com/hashicorp/errwrap/LICENSE deleted file mode 100644 index c33dcc7..0000000 --- a/vendor/github.com/hashicorp/errwrap/LICENSE +++ /dev/null @@ -1,354 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. “Contributor” - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. “Contributor Version” - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor’s Contribution. - -1.3. “Contribution” - - means Covered Software of a particular Contributor. - -1.4. “Covered Software” - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. “Incompatible With Secondary Licenses” - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of version - 1.1 or earlier of the License, but not also under the terms of a - Secondary License. - -1.6. “Executable Form” - - means any form of the work other than Source Code Form. - -1.7. “Larger Work” - - means a work that combines Covered Software with other material, in a separate - file or files, that is not Covered Software. - -1.8. “License” - - means this document. - -1.9. “Licensable” - - means having the right to grant, to the maximum extent possible, whether at the - time of the initial grant or subsequently, any and all of the rights conveyed by - this License. - -1.10. “Modifications” - - means any of the following: - - a. any file in Source Code Form that results from an addition to, deletion - from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. “Patent Claims” of a Contributor - - means any patent claim(s), including without limitation, method, process, - and apparatus claims, in any patent Licensable by such Contributor that - would be infringed, but for the grant of the License, by the making, - using, selling, offering for sale, having made, import, or transfer of - either its Contributions or its Contributor Version. - -1.12. “Secondary License” - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. “Source Code Form” - - means the form of the work preferred for making modifications. - -1.14. “You” (or “Your”) - - means an individual or a legal entity exercising rights under this - License. For legal entities, “You” includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, “control” means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or as - part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its Contributions - or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution become - effective for each Contribution on the date the Contributor first distributes - such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under this - License. No additional rights or licenses will be implied from the distribution - or licensing of Covered Software under this License. Notwithstanding Section - 2.1(b) above, no patent license is granted by a Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party’s - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of its - Contributions. - - This License does not grant any rights in the trademarks, service marks, or - logos of any Contributor (except as may be necessary to comply with the - notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this License - (see Section 10.2) or under the terms of a Secondary License (if permitted - under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its Contributions - are its original creation(s) or it has sufficient rights to grant the - rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under applicable - copyright doctrines of fair use, fair dealing, or other equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under the - terms of this License. You must inform recipients that the Source Code Form - of the Covered Software is governed by the terms of this License, and how - they can obtain a copy of this License. You may not attempt to alter or - restrict the recipients’ rights in the Source Code Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this License, - or sublicense it under different terms, provided that the license for - the Executable Form does not attempt to limit or alter the recipients’ - rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for the - Covered Software. If the Larger Work is a combination of Covered Software - with a work governed by one or more Secondary Licenses, and the Covered - Software is not Incompatible With Secondary Licenses, this License permits - You to additionally distribute such Covered Software under the terms of - such Secondary License(s), so that the recipient of the Larger Work may, at - their option, further distribute the Covered Software under the terms of - either this License or such Secondary License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices (including - copyright notices, patent notices, disclaimers of warranty, or limitations - of liability) contained within the Source Code Form of the Covered - Software, except that You may alter any license notices to the extent - required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on behalf - of any Contributor. You must make it absolutely clear that any such - warranty, support, indemnity, or liability obligation is offered by You - alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, judicial - order, or regulation then You must: (a) comply with the terms of this License - to the maximum extent possible; and (b) describe the limitations and the code - they affect. Such description must be placed in a text file included with all - distributions of the Covered Software under this License. Except to the - extent prohibited by statute or regulation, such description must be - sufficiently detailed for a recipient of ordinary skill to be able to - understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing basis, - if such Contributor fails to notify You of the non-compliance by some - reasonable means prior to 60 days after You have come back into compliance. - Moreover, Your grants from a particular Contributor are reinstated on an - ongoing basis if such Contributor notifies You of the non-compliance by - some reasonable means, this is the first time You have received notice of - non-compliance with this License from such Contributor, and You become - compliant prior to 30 days after Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, counter-claims, - and cross-claims) alleging that a Contributor Version directly or - indirectly infringes any patent, then the rights granted to You by any and - all Contributors for the Covered Software under Section 2.1 of this License - shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an “as is” basis, without - warranty of any kind, either expressed, implied, or statutory, including, - without limitation, warranties that the Covered Software is free of defects, - merchantable, fit for a particular purpose or non-infringing. The entire - risk as to the quality and performance of the Covered Software is with You. - Should any Covered Software prove defective in any respect, You (not any - Contributor) assume the cost of any necessary servicing, repair, or - correction. This disclaimer of warranty constitutes an essential part of this - License. No use of any Covered Software is authorized under this License - except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from such - party’s negligence to the extent applicable law prohibits such limitation. - Some jurisdictions do not allow the exclusion or limitation of incidental or - consequential damages, so this exclusion and limitation may not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts of - a jurisdiction where the defendant maintains its principal place of business - and such litigation shall be governed by laws of that jurisdiction, without - reference to its conflict-of-law provisions. Nothing in this Section shall - prevent a party’s ability to bring cross-claims or counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject matter - hereof. If any provision of this License is held to be unenforceable, such - provision shall be reformed only to the extent necessary to make it - enforceable. Any law or regulation which provides that the language of a - contract shall be construed against the drafter shall not be used to construe - this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version of - the License under which You originally received the Covered Software, or - under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a modified - version of this License if you rename the license and remove any - references to the name of the license steward (except to note that such - modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses - If You choose to distribute Source Code Form that is Incompatible With - Secondary Licenses under the terms of this version of the License, the - notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, then -You may include the notice in a location (such as a LICENSE file in a relevant -directory) where a recipient would be likely to look for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - “Incompatible With Secondary Licenses” Notice - - This Source Code Form is “Incompatible - With Secondary Licenses”, as defined by - the Mozilla Public License, v. 2.0. - diff --git a/vendor/github.com/hashicorp/errwrap/README.md b/vendor/github.com/hashicorp/errwrap/README.md deleted file mode 100644 index 444df08..0000000 --- a/vendor/github.com/hashicorp/errwrap/README.md +++ /dev/null @@ -1,89 +0,0 @@ -# errwrap - -`errwrap` is a package for Go that formalizes the pattern of wrapping errors -and checking if an error contains another error. - -There is a common pattern in Go of taking a returned `error` value and -then wrapping it (such as with `fmt.Errorf`) before returning it. The problem -with this pattern is that you completely lose the original `error` structure. - -Arguably the _correct_ approach is that you should make a custom structure -implementing the `error` interface, and have the original error as a field -on that structure, such [as this example](http://golang.org/pkg/os/#PathError). -This is a good approach, but you have to know the entire chain of possible -rewrapping that happens, when you might just care about one. - -`errwrap` formalizes this pattern (it doesn't matter what approach you use -above) by giving a single interface for wrapping errors, checking if a specific -error is wrapped, and extracting that error. - -## Installation and Docs - -Install using `go get github.com/hashicorp/errwrap`. - -Full documentation is available at -http://godoc.org/github.com/hashicorp/errwrap - -## Usage - -#### Basic Usage - -Below is a very basic example of its usage: - -```go -// A function that always returns an error, but wraps it, like a real -// function might. -func tryOpen() error { - _, err := os.Open("/i/dont/exist") - if err != nil { - return errwrap.Wrapf("Doesn't exist: {{err}}", err) - } - - return nil -} - -func main() { - err := tryOpen() - - // We can use the Contains helpers to check if an error contains - // another error. It is safe to do this with a nil error, or with - // an error that doesn't even use the errwrap package. - if errwrap.Contains(err, "does not exist") { - // Do something - } - if errwrap.ContainsType(err, new(os.PathError)) { - // Do something - } - - // Or we can use the associated `Get` functions to just extract - // a specific error. This would return nil if that specific error doesn't - // exist. - perr := errwrap.GetType(err, new(os.PathError)) -} -``` - -#### Custom Types - -If you're already making custom types that properly wrap errors, then -you can get all the functionality of `errwraps.Contains` and such by -implementing the `Wrapper` interface with just one function. Example: - -```go -type AppError { - Code ErrorCode - Err error -} - -func (e *AppError) WrappedErrors() []error { - return []error{e.Err} -} -``` - -Now this works: - -```go -err := &AppError{Err: fmt.Errorf("an error")} -if errwrap.ContainsType(err, fmt.Errorf("")) { - // This will work! -} -``` diff --git a/vendor/github.com/hashicorp/errwrap/errwrap.go b/vendor/github.com/hashicorp/errwrap/errwrap.go deleted file mode 100644 index a733bef..0000000 --- a/vendor/github.com/hashicorp/errwrap/errwrap.go +++ /dev/null @@ -1,169 +0,0 @@ -// Package errwrap implements methods to formalize error wrapping in Go. -// -// All of the top-level functions that take an `error` are built to be able -// to take any error, not just wrapped errors. This allows you to use errwrap -// without having to type-check and type-cast everywhere. -package errwrap - -import ( - "errors" - "reflect" - "strings" -) - -// WalkFunc is the callback called for Walk. -type WalkFunc func(error) - -// Wrapper is an interface that can be implemented by custom types to -// have all the Contains, Get, etc. functions in errwrap work. -// -// When Walk reaches a Wrapper, it will call the callback for every -// wrapped error in addition to the wrapper itself. Since all the top-level -// functions in errwrap use Walk, this means that all those functions work -// with your custom type. -type Wrapper interface { - WrappedErrors() []error -} - -// Wrap defines that outer wraps inner, returning an error type that -// can be cleanly used with the other methods in this package, such as -// Contains, GetAll, etc. -// -// This function won't modify the error message at all (the outer message -// will be used). -func Wrap(outer, inner error) error { - return &wrappedError{ - Outer: outer, - Inner: inner, - } -} - -// Wrapf wraps an error with a formatting message. This is similar to using -// `fmt.Errorf` to wrap an error. If you're using `fmt.Errorf` to wrap -// errors, you should replace it with this. -// -// format is the format of the error message. The string '{{err}}' will -// be replaced with the original error message. -func Wrapf(format string, err error) error { - outerMsg := "" - if err != nil { - outerMsg = err.Error() - } - - outer := errors.New(strings.Replace( - format, "{{err}}", outerMsg, -1)) - - return Wrap(outer, err) -} - -// Contains checks if the given error contains an error with the -// message msg. If err is not a wrapped error, this will always return -// false unless the error itself happens to match this msg. -func Contains(err error, msg string) bool { - return len(GetAll(err, msg)) > 0 -} - -// ContainsType checks if the given error contains an error with -// the same concrete type as v. If err is not a wrapped error, this will -// check the err itself. -func ContainsType(err error, v interface{}) bool { - return len(GetAllType(err, v)) > 0 -} - -// Get is the same as GetAll but returns the deepest matching error. -func Get(err error, msg string) error { - es := GetAll(err, msg) - if len(es) > 0 { - return es[len(es)-1] - } - - return nil -} - -// GetType is the same as GetAllType but returns the deepest matching error. -func GetType(err error, v interface{}) error { - es := GetAllType(err, v) - if len(es) > 0 { - return es[len(es)-1] - } - - return nil -} - -// GetAll gets all the errors that might be wrapped in err with the -// given message. The order of the errors is such that the outermost -// matching error (the most recent wrap) is index zero, and so on. -func GetAll(err error, msg string) []error { - var result []error - - Walk(err, func(err error) { - if err.Error() == msg { - result = append(result, err) - } - }) - - return result -} - -// GetAllType gets all the errors that are the same type as v. -// -// The order of the return value is the same as described in GetAll. -func GetAllType(err error, v interface{}) []error { - var result []error - - var search string - if v != nil { - search = reflect.TypeOf(v).String() - } - Walk(err, func(err error) { - var needle string - if err != nil { - needle = reflect.TypeOf(err).String() - } - - if needle == search { - result = append(result, err) - } - }) - - return result -} - -// Walk walks all the wrapped errors in err and calls the callback. If -// err isn't a wrapped error, this will be called once for err. If err -// is a wrapped error, the callback will be called for both the wrapper -// that implements error as well as the wrapped error itself. -func Walk(err error, cb WalkFunc) { - if err == nil { - return - } - - switch e := err.(type) { - case *wrappedError: - cb(e.Outer) - Walk(e.Inner, cb) - case Wrapper: - cb(err) - - for _, err := range e.WrappedErrors() { - Walk(err, cb) - } - default: - cb(err) - } -} - -// wrappedError is an implementation of error that has both the -// outer and inner errors. -type wrappedError struct { - Outer error - Inner error -} - -func (w *wrappedError) Error() string { - return w.Outer.Error() -} - -func (w *wrappedError) WrappedErrors() []error { - return []error{w.Outer, w.Inner} -} diff --git a/vendor/github.com/hashicorp/errwrap/go.mod b/vendor/github.com/hashicorp/errwrap/go.mod deleted file mode 100644 index c9b8402..0000000 --- a/vendor/github.com/hashicorp/errwrap/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/hashicorp/errwrap diff --git a/vendor/github.com/hashicorp/go-cleanhttp/LICENSE b/vendor/github.com/hashicorp/go-cleanhttp/LICENSE deleted file mode 100644 index e87a115..0000000 --- a/vendor/github.com/hashicorp/go-cleanhttp/LICENSE +++ /dev/null @@ -1,363 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - diff --git a/vendor/github.com/hashicorp/go-cleanhttp/README.md b/vendor/github.com/hashicorp/go-cleanhttp/README.md deleted file mode 100644 index 036e531..0000000 --- a/vendor/github.com/hashicorp/go-cleanhttp/README.md +++ /dev/null @@ -1,30 +0,0 @@ -# cleanhttp - -Functions for accessing "clean" Go http.Client values - -------------- - -The Go standard library contains a default `http.Client` called -`http.DefaultClient`. It is a common idiom in Go code to start with -`http.DefaultClient` and tweak it as necessary, and in fact, this is -encouraged; from the `http` package documentation: - -> The Client's Transport typically has internal state (cached TCP connections), -so Clients should be reused instead of created as needed. Clients are safe for -concurrent use by multiple goroutines. - -Unfortunately, this is a shared value, and it is not uncommon for libraries to -assume that they are free to modify it at will. With enough dependencies, it -can be very easy to encounter strange problems and race conditions due to -manipulation of this shared value across libraries and goroutines (clients are -safe for concurrent use, but writing values to the client struct itself is not -protected). - -Making things worse is the fact that a bare `http.Client` will use a default -`http.Transport` called `http.DefaultTransport`, which is another global value -that behaves the same way. So it is not simply enough to replace -`http.DefaultClient` with `&http.Client{}`. - -This repository provides some simple functions to get a "clean" `http.Client` --- one that uses the same default values as the Go standard library, but -returns a client that does not share any state with other clients. diff --git a/vendor/github.com/hashicorp/go-cleanhttp/cleanhttp.go b/vendor/github.com/hashicorp/go-cleanhttp/cleanhttp.go deleted file mode 100644 index 8d306bf..0000000 --- a/vendor/github.com/hashicorp/go-cleanhttp/cleanhttp.go +++ /dev/null @@ -1,57 +0,0 @@ -package cleanhttp - -import ( - "net" - "net/http" - "runtime" - "time" -) - -// DefaultTransport returns a new http.Transport with similar default values to -// http.DefaultTransport, but with idle connections and keepalives disabled. -func DefaultTransport() *http.Transport { - transport := DefaultPooledTransport() - transport.DisableKeepAlives = true - transport.MaxIdleConnsPerHost = -1 - return transport -} - -// DefaultPooledTransport returns a new http.Transport with similar default -// values to http.DefaultTransport. Do not use this for transient transports as -// it can leak file descriptors over time. Only use this for transports that -// will be re-used for the same host(s). -func DefaultPooledTransport() *http.Transport { - transport := &http.Transport{ - Proxy: http.ProxyFromEnvironment, - DialContext: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - DualStack: true, - }).DialContext, - MaxIdleConns: 100, - IdleConnTimeout: 90 * time.Second, - TLSHandshakeTimeout: 10 * time.Second, - ExpectContinueTimeout: 1 * time.Second, - MaxIdleConnsPerHost: runtime.GOMAXPROCS(0) + 1, - } - return transport -} - -// DefaultClient returns a new http.Client with similar default values to -// http.Client, but with a non-shared Transport, idle connections disabled, and -// keepalives disabled. -func DefaultClient() *http.Client { - return &http.Client{ - Transport: DefaultTransport(), - } -} - -// DefaultPooledClient returns a new http.Client with similar default values to -// http.Client, but with a shared Transport. Do not use this function for -// transient clients as it can leak file descriptors over time. Only use this -// for clients that will be re-used for the same host(s). -func DefaultPooledClient() *http.Client { - return &http.Client{ - Transport: DefaultPooledTransport(), - } -} diff --git a/vendor/github.com/hashicorp/go-cleanhttp/doc.go b/vendor/github.com/hashicorp/go-cleanhttp/doc.go deleted file mode 100644 index 0584109..0000000 --- a/vendor/github.com/hashicorp/go-cleanhttp/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -// Package cleanhttp offers convenience utilities for acquiring "clean" -// http.Transport and http.Client structs. -// -// Values set on http.DefaultClient and http.DefaultTransport affect all -// callers. This can have detrimental effects, esepcially in TLS contexts, -// where client or root certificates set to talk to multiple endpoints can end -// up displacing each other, leading to hard-to-debug issues. This package -// provides non-shared http.Client and http.Transport structs to ensure that -// the configuration will not be overwritten by other parts of the application -// or dependencies. -// -// The DefaultClient and DefaultTransport functions disable idle connections -// and keepalives. Without ensuring that idle connections are closed before -// garbage collection, short-term clients/transports can leak file descriptors, -// eventually leading to "too many open files" errors. If you will be -// connecting to the same hosts repeatedly from the same client, you can use -// DefaultPooledClient to receive a client that has connection pooling -// semantics similar to http.DefaultClient. -// -package cleanhttp diff --git a/vendor/github.com/hashicorp/go-cleanhttp/go.mod b/vendor/github.com/hashicorp/go-cleanhttp/go.mod deleted file mode 100644 index 310f075..0000000 --- a/vendor/github.com/hashicorp/go-cleanhttp/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/hashicorp/go-cleanhttp diff --git a/vendor/github.com/hashicorp/go-cleanhttp/handlers.go b/vendor/github.com/hashicorp/go-cleanhttp/handlers.go deleted file mode 100644 index 7eda377..0000000 --- a/vendor/github.com/hashicorp/go-cleanhttp/handlers.go +++ /dev/null @@ -1,43 +0,0 @@ -package cleanhttp - -import ( - "net/http" - "strings" - "unicode" -) - -// HandlerInput provides input options to cleanhttp's handlers -type HandlerInput struct { - ErrStatus int -} - -// PrintablePathCheckHandler is a middleware that ensures the request path -// contains only printable runes. -func PrintablePathCheckHandler(next http.Handler, input *HandlerInput) http.Handler { - // Nil-check on input to make it optional - if input == nil { - input = &HandlerInput{ - ErrStatus: http.StatusBadRequest, - } - } - - // Default to http.StatusBadRequest on error - if input.ErrStatus == 0 { - input.ErrStatus = http.StatusBadRequest - } - - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // Check URL path for non-printable characters - idx := strings.IndexFunc(r.URL.Path, func(c rune) bool { - return !unicode.IsPrint(c) - }) - - if idx != -1 { - w.WriteHeader(input.ErrStatus) - return - } - - next.ServeHTTP(w, r) - return - }) -} diff --git a/vendor/github.com/hashicorp/go-multierror/.travis.yml b/vendor/github.com/hashicorp/go-multierror/.travis.yml deleted file mode 100644 index 304a835..0000000 --- a/vendor/github.com/hashicorp/go-multierror/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -sudo: false - -language: go - -go: - - 1.x - -branches: - only: - - master - -script: make test testrace diff --git a/vendor/github.com/hashicorp/go-multierror/LICENSE b/vendor/github.com/hashicorp/go-multierror/LICENSE deleted file mode 100644 index 82b4de9..0000000 --- a/vendor/github.com/hashicorp/go-multierror/LICENSE +++ /dev/null @@ -1,353 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. “Contributor” - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. “Contributor Version” - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor’s Contribution. - -1.3. “Contribution” - - means Covered Software of a particular Contributor. - -1.4. “Covered Software” - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. “Incompatible With Secondary Licenses” - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of version - 1.1 or earlier of the License, but not also under the terms of a - Secondary License. - -1.6. “Executable Form” - - means any form of the work other than Source Code Form. - -1.7. “Larger Work” - - means a work that combines Covered Software with other material, in a separate - file or files, that is not Covered Software. - -1.8. “License” - - means this document. - -1.9. “Licensable” - - means having the right to grant, to the maximum extent possible, whether at the - time of the initial grant or subsequently, any and all of the rights conveyed by - this License. - -1.10. “Modifications” - - means any of the following: - - a. any file in Source Code Form that results from an addition to, deletion - from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. “Patent Claims” of a Contributor - - means any patent claim(s), including without limitation, method, process, - and apparatus claims, in any patent Licensable by such Contributor that - would be infringed, but for the grant of the License, by the making, - using, selling, offering for sale, having made, import, or transfer of - either its Contributions or its Contributor Version. - -1.12. “Secondary License” - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. “Source Code Form” - - means the form of the work preferred for making modifications. - -1.14. “You” (or “Your”) - - means an individual or a legal entity exercising rights under this - License. For legal entities, “You” includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, “control” means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or as - part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its Contributions - or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution become - effective for each Contribution on the date the Contributor first distributes - such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under this - License. No additional rights or licenses will be implied from the distribution - or licensing of Covered Software under this License. Notwithstanding Section - 2.1(b) above, no patent license is granted by a Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party’s - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of its - Contributions. - - This License does not grant any rights in the trademarks, service marks, or - logos of any Contributor (except as may be necessary to comply with the - notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this License - (see Section 10.2) or under the terms of a Secondary License (if permitted - under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its Contributions - are its original creation(s) or it has sufficient rights to grant the - rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under applicable - copyright doctrines of fair use, fair dealing, or other equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under the - terms of this License. You must inform recipients that the Source Code Form - of the Covered Software is governed by the terms of this License, and how - they can obtain a copy of this License. You may not attempt to alter or - restrict the recipients’ rights in the Source Code Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this License, - or sublicense it under different terms, provided that the license for - the Executable Form does not attempt to limit or alter the recipients’ - rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for the - Covered Software. If the Larger Work is a combination of Covered Software - with a work governed by one or more Secondary Licenses, and the Covered - Software is not Incompatible With Secondary Licenses, this License permits - You to additionally distribute such Covered Software under the terms of - such Secondary License(s), so that the recipient of the Larger Work may, at - their option, further distribute the Covered Software under the terms of - either this License or such Secondary License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices (including - copyright notices, patent notices, disclaimers of warranty, or limitations - of liability) contained within the Source Code Form of the Covered - Software, except that You may alter any license notices to the extent - required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on behalf - of any Contributor. You must make it absolutely clear that any such - warranty, support, indemnity, or liability obligation is offered by You - alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, judicial - order, or regulation then You must: (a) comply with the terms of this License - to the maximum extent possible; and (b) describe the limitations and the code - they affect. Such description must be placed in a text file included with all - distributions of the Covered Software under this License. Except to the - extent prohibited by statute or regulation, such description must be - sufficiently detailed for a recipient of ordinary skill to be able to - understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing basis, - if such Contributor fails to notify You of the non-compliance by some - reasonable means prior to 60 days after You have come back into compliance. - Moreover, Your grants from a particular Contributor are reinstated on an - ongoing basis if such Contributor notifies You of the non-compliance by - some reasonable means, this is the first time You have received notice of - non-compliance with this License from such Contributor, and You become - compliant prior to 30 days after Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, counter-claims, - and cross-claims) alleging that a Contributor Version directly or - indirectly infringes any patent, then the rights granted to You by any and - all Contributors for the Covered Software under Section 2.1 of this License - shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an “as is” basis, without - warranty of any kind, either expressed, implied, or statutory, including, - without limitation, warranties that the Covered Software is free of defects, - merchantable, fit for a particular purpose or non-infringing. The entire - risk as to the quality and performance of the Covered Software is with You. - Should any Covered Software prove defective in any respect, You (not any - Contributor) assume the cost of any necessary servicing, repair, or - correction. This disclaimer of warranty constitutes an essential part of this - License. No use of any Covered Software is authorized under this License - except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from such - party’s negligence to the extent applicable law prohibits such limitation. - Some jurisdictions do not allow the exclusion or limitation of incidental or - consequential damages, so this exclusion and limitation may not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts of - a jurisdiction where the defendant maintains its principal place of business - and such litigation shall be governed by laws of that jurisdiction, without - reference to its conflict-of-law provisions. Nothing in this Section shall - prevent a party’s ability to bring cross-claims or counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject matter - hereof. If any provision of this License is held to be unenforceable, such - provision shall be reformed only to the extent necessary to make it - enforceable. Any law or regulation which provides that the language of a - contract shall be construed against the drafter shall not be used to construe - this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version of - the License under which You originally received the Covered Software, or - under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a modified - version of this License if you rename the license and remove any - references to the name of the license steward (except to note that such - modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses - If You choose to distribute Source Code Form that is Incompatible With - Secondary Licenses under the terms of this version of the License, the - notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, then -You may include the notice in a location (such as a LICENSE file in a relevant -directory) where a recipient would be likely to look for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - “Incompatible With Secondary Licenses” Notice - - This Source Code Form is “Incompatible - With Secondary Licenses”, as defined by - the Mozilla Public License, v. 2.0. diff --git a/vendor/github.com/hashicorp/go-multierror/Makefile b/vendor/github.com/hashicorp/go-multierror/Makefile deleted file mode 100644 index b97cd6e..0000000 --- a/vendor/github.com/hashicorp/go-multierror/Makefile +++ /dev/null @@ -1,31 +0,0 @@ -TEST?=./... - -default: test - -# test runs the test suite and vets the code. -test: generate - @echo "==> Running tests..." - @go list $(TEST) \ - | grep -v "/vendor/" \ - | xargs -n1 go test -timeout=60s -parallel=10 ${TESTARGS} - -# testrace runs the race checker -testrace: generate - @echo "==> Running tests (race)..." - @go list $(TEST) \ - | grep -v "/vendor/" \ - | xargs -n1 go test -timeout=60s -race ${TESTARGS} - -# updatedeps installs all the dependencies needed to run and build. -updatedeps: - @sh -c "'${CURDIR}/scripts/deps.sh' '${NAME}'" - -# generate runs `go generate` to build the dynamically generated source files. -generate: - @echo "==> Generating..." - @find . -type f -name '.DS_Store' -delete - @go list ./... \ - | grep -v "/vendor/" \ - | xargs -n1 go generate - -.PHONY: default test testrace updatedeps generate diff --git a/vendor/github.com/hashicorp/go-multierror/README.md b/vendor/github.com/hashicorp/go-multierror/README.md deleted file mode 100644 index ead5830..0000000 --- a/vendor/github.com/hashicorp/go-multierror/README.md +++ /dev/null @@ -1,97 +0,0 @@ -# go-multierror - -[![Build Status](http://img.shields.io/travis/hashicorp/go-multierror.svg?style=flat-square)][travis] -[![Go Documentation](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)][godocs] - -[travis]: https://travis-ci.org/hashicorp/go-multierror -[godocs]: https://godoc.org/github.com/hashicorp/go-multierror - -`go-multierror` is a package for Go that provides a mechanism for -representing a list of `error` values as a single `error`. - -This allows a function in Go to return an `error` that might actually -be a list of errors. If the caller knows this, they can unwrap the -list and access the errors. If the caller doesn't know, the error -formats to a nice human-readable format. - -`go-multierror` implements the -[errwrap](https://github.com/hashicorp/errwrap) interface so that it can -be used with that library, as well. - -## Installation and Docs - -Install using `go get github.com/hashicorp/go-multierror`. - -Full documentation is available at -http://godoc.org/github.com/hashicorp/go-multierror - -## Usage - -go-multierror is easy to use and purposely built to be unobtrusive in -existing Go applications/libraries that may not be aware of it. - -**Building a list of errors** - -The `Append` function is used to create a list of errors. This function -behaves a lot like the Go built-in `append` function: it doesn't matter -if the first argument is nil, a `multierror.Error`, or any other `error`, -the function behaves as you would expect. - -```go -var result error - -if err := step1(); err != nil { - result = multierror.Append(result, err) -} -if err := step2(); err != nil { - result = multierror.Append(result, err) -} - -return result -``` - -**Customizing the formatting of the errors** - -By specifying a custom `ErrorFormat`, you can customize the format -of the `Error() string` function: - -```go -var result *multierror.Error - -// ... accumulate errors here, maybe using Append - -if result != nil { - result.ErrorFormat = func([]error) string { - return "errors!" - } -} -``` - -**Accessing the list of errors** - -`multierror.Error` implements `error` so if the caller doesn't know about -multierror, it will work just fine. But if you're aware a multierror might -be returned, you can use type switches to access the list of errors: - -```go -if err := something(); err != nil { - if merr, ok := err.(*multierror.Error); ok { - // Use merr.Errors - } -} -``` - -**Returning a multierror only if there are errors** - -If you build a `multierror.Error`, you can use the `ErrorOrNil` function -to return an `error` implementation only if there are errors to return: - -```go -var result *multierror.Error - -// ... accumulate errors here - -// Return the `error` only if errors were added to the multierror, otherwise -// return nil since there are no errors. -return result.ErrorOrNil() -``` diff --git a/vendor/github.com/hashicorp/go-multierror/append.go b/vendor/github.com/hashicorp/go-multierror/append.go deleted file mode 100644 index 775b6e7..0000000 --- a/vendor/github.com/hashicorp/go-multierror/append.go +++ /dev/null @@ -1,41 +0,0 @@ -package multierror - -// Append is a helper function that will append more errors -// onto an Error in order to create a larger multi-error. -// -// If err is not a multierror.Error, then it will be turned into -// one. If any of the errs are multierr.Error, they will be flattened -// one level into err. -func Append(err error, errs ...error) *Error { - switch err := err.(type) { - case *Error: - // Typed nils can reach here, so initialize if we are nil - if err == nil { - err = new(Error) - } - - // Go through each error and flatten - for _, e := range errs { - switch e := e.(type) { - case *Error: - if e != nil { - err.Errors = append(err.Errors, e.Errors...) - } - default: - if e != nil { - err.Errors = append(err.Errors, e) - } - } - } - - return err - default: - newErrs := make([]error, 0, len(errs)+1) - if err != nil { - newErrs = append(newErrs, err) - } - newErrs = append(newErrs, errs...) - - return Append(&Error{}, newErrs...) - } -} diff --git a/vendor/github.com/hashicorp/go-multierror/flatten.go b/vendor/github.com/hashicorp/go-multierror/flatten.go deleted file mode 100644 index aab8e9a..0000000 --- a/vendor/github.com/hashicorp/go-multierror/flatten.go +++ /dev/null @@ -1,26 +0,0 @@ -package multierror - -// Flatten flattens the given error, merging any *Errors together into -// a single *Error. -func Flatten(err error) error { - // If it isn't an *Error, just return the error as-is - if _, ok := err.(*Error); !ok { - return err - } - - // Otherwise, make the result and flatten away! - flatErr := new(Error) - flatten(err, flatErr) - return flatErr -} - -func flatten(err error, flatErr *Error) { - switch err := err.(type) { - case *Error: - for _, e := range err.Errors { - flatten(e, flatErr) - } - default: - flatErr.Errors = append(flatErr.Errors, err) - } -} diff --git a/vendor/github.com/hashicorp/go-multierror/format.go b/vendor/github.com/hashicorp/go-multierror/format.go deleted file mode 100644 index 47f13c4..0000000 --- a/vendor/github.com/hashicorp/go-multierror/format.go +++ /dev/null @@ -1,27 +0,0 @@ -package multierror - -import ( - "fmt" - "strings" -) - -// ErrorFormatFunc is a function callback that is called by Error to -// turn the list of errors into a string. -type ErrorFormatFunc func([]error) string - -// ListFormatFunc is a basic formatter that outputs the number of errors -// that occurred along with a bullet point list of the errors. -func ListFormatFunc(es []error) string { - if len(es) == 1 { - return fmt.Sprintf("1 error occurred:\n\t* %s\n\n", es[0]) - } - - points := make([]string, len(es)) - for i, err := range es { - points[i] = fmt.Sprintf("* %s", err) - } - - return fmt.Sprintf( - "%d errors occurred:\n\t%s\n\n", - len(es), strings.Join(points, "\n\t")) -} diff --git a/vendor/github.com/hashicorp/go-multierror/go.mod b/vendor/github.com/hashicorp/go-multierror/go.mod deleted file mode 100644 index 2534331..0000000 --- a/vendor/github.com/hashicorp/go-multierror/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/hashicorp/go-multierror - -require github.com/hashicorp/errwrap v1.0.0 diff --git a/vendor/github.com/hashicorp/go-multierror/go.sum b/vendor/github.com/hashicorp/go-multierror/go.sum deleted file mode 100644 index 85b1f8f..0000000 --- a/vendor/github.com/hashicorp/go-multierror/go.sum +++ /dev/null @@ -1,4 +0,0 @@ -github.com/hashicorp/errwrap v0.0.0-20141028054710-7554cd9344ce h1:prjrVgOk2Yg6w+PflHoszQNLTUh4kaByUcEWM/9uin4= -github.com/hashicorp/errwrap v0.0.0-20141028054710-7554cd9344ce/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= -github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= diff --git a/vendor/github.com/hashicorp/go-multierror/multierror.go b/vendor/github.com/hashicorp/go-multierror/multierror.go deleted file mode 100644 index 89b1422..0000000 --- a/vendor/github.com/hashicorp/go-multierror/multierror.go +++ /dev/null @@ -1,51 +0,0 @@ -package multierror - -import ( - "fmt" -) - -// Error is an error type to track multiple errors. This is used to -// accumulate errors in cases and return them as a single "error". -type Error struct { - Errors []error - ErrorFormat ErrorFormatFunc -} - -func (e *Error) Error() string { - fn := e.ErrorFormat - if fn == nil { - fn = ListFormatFunc - } - - return fn(e.Errors) -} - -// ErrorOrNil returns an error interface if this Error represents -// a list of errors, or returns nil if the list of errors is empty. This -// function is useful at the end of accumulation to make sure that the value -// returned represents the existence of errors. -func (e *Error) ErrorOrNil() error { - if e == nil { - return nil - } - if len(e.Errors) == 0 { - return nil - } - - return e -} - -func (e *Error) GoString() string { - return fmt.Sprintf("*%#v", *e) -} - -// WrappedErrors returns the list of errors that this Error is wrapping. -// It is an implementation of the errwrap.Wrapper interface so that -// multierror.Error can be used with that library. -// -// This method is not safe to be called concurrently and is no different -// than accessing the Errors field directly. It is implemented only to -// satisfy the errwrap.Wrapper interface. -func (e *Error) WrappedErrors() []error { - return e.Errors -} diff --git a/vendor/github.com/hashicorp/go-multierror/prefix.go b/vendor/github.com/hashicorp/go-multierror/prefix.go deleted file mode 100644 index 5c477ab..0000000 --- a/vendor/github.com/hashicorp/go-multierror/prefix.go +++ /dev/null @@ -1,37 +0,0 @@ -package multierror - -import ( - "fmt" - - "github.com/hashicorp/errwrap" -) - -// Prefix is a helper function that will prefix some text -// to the given error. If the error is a multierror.Error, then -// it will be prefixed to each wrapped error. -// -// This is useful to use when appending multiple multierrors -// together in order to give better scoping. -func Prefix(err error, prefix string) error { - if err == nil { - return nil - } - - format := fmt.Sprintf("%s {{err}}", prefix) - switch err := err.(type) { - case *Error: - // Typed nils can reach here, so initialize if we are nil - if err == nil { - err = new(Error) - } - - // Wrap each of the errors - for i, e := range err.Errors { - err.Errors[i] = errwrap.Wrapf(format, e) - } - - return err - default: - return errwrap.Wrapf(format, err) - } -} diff --git a/vendor/github.com/hashicorp/go-multierror/sort.go b/vendor/github.com/hashicorp/go-multierror/sort.go deleted file mode 100644 index fecb14e..0000000 --- a/vendor/github.com/hashicorp/go-multierror/sort.go +++ /dev/null @@ -1,16 +0,0 @@ -package multierror - -// Len implements sort.Interface function for length -func (err Error) Len() int { - return len(err.Errors) -} - -// Swap implements sort.Interface function for swapping elements -func (err Error) Swap(i, j int) { - err.Errors[i], err.Errors[j] = err.Errors[j], err.Errors[i] -} - -// Less implements sort.Interface function for determining order -func (err Error) Less(i, j int) bool { - return err.Errors[i].Error() < err.Errors[j].Error() -} diff --git a/vendor/github.com/hashicorp/go-retryablehttp/.gitignore b/vendor/github.com/hashicorp/go-retryablehttp/.gitignore deleted file mode 100644 index caab963..0000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -.idea/ -*.iml -*.test diff --git a/vendor/github.com/hashicorp/go-retryablehttp/.travis.yml b/vendor/github.com/hashicorp/go-retryablehttp/.travis.yml deleted file mode 100644 index 2df4e7d..0000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -sudo: false - -language: go - -go: - - 1.8.1 - -branches: - only: - - master - -script: make updatedeps test diff --git a/vendor/github.com/hashicorp/go-retryablehttp/LICENSE b/vendor/github.com/hashicorp/go-retryablehttp/LICENSE deleted file mode 100644 index e87a115..0000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/LICENSE +++ /dev/null @@ -1,363 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - diff --git a/vendor/github.com/hashicorp/go-retryablehttp/Makefile b/vendor/github.com/hashicorp/go-retryablehttp/Makefile deleted file mode 100644 index da17640..0000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/Makefile +++ /dev/null @@ -1,11 +0,0 @@ -default: test - -test: - go vet ./... - go test -race ./... - -updatedeps: - go get -f -t -u ./... - go get -f -u ./... - -.PHONY: default test updatedeps diff --git a/vendor/github.com/hashicorp/go-retryablehttp/README.md b/vendor/github.com/hashicorp/go-retryablehttp/README.md deleted file mode 100644 index ccdc7e8..0000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/README.md +++ /dev/null @@ -1,46 +0,0 @@ -go-retryablehttp -================ - -[![Build Status](http://img.shields.io/travis/hashicorp/go-retryablehttp.svg?style=flat-square)][travis] -[![Go Documentation](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)][godocs] - -[travis]: http://travis-ci.org/hashicorp/go-retryablehttp -[godocs]: http://godoc.org/github.com/hashicorp/go-retryablehttp - -The `retryablehttp` package provides a familiar HTTP client interface with -automatic retries and exponential backoff. It is a thin wrapper over the -standard `net/http` client library and exposes nearly the same public API. This -makes `retryablehttp` very easy to drop into existing programs. - -`retryablehttp` performs automatic retries under certain conditions. Mainly, if -an error is returned by the client (connection errors, etc.), or if a 500-range -response code is received (except 501), then a retry is invoked after a wait -period. Otherwise, the response is returned and left to the caller to -interpret. - -The main difference from `net/http` is that requests which take a request body -(POST/PUT et. al) can have the body provided in a number of ways (some more or -less efficient) that allow "rewinding" the request body if the initial request -fails so that the full request can be attempted again. See the -[godoc](http://godoc.org/github.com/hashicorp/go-retryablehttp) for more -details. - -Example Use -=========== - -Using this library should look almost identical to what you would do with -`net/http`. The most simple example of a GET request is shown below: - -```go -resp, err := retryablehttp.Get("/foo") -if err != nil { - panic(err) -} -``` - -The returned response object is an `*http.Response`, the same thing you would -usually get from `net/http`. Had the request failed one or more times, the above -call would block and retry with exponential backoff. - -For more usage and examples see the -[godoc](http://godoc.org/github.com/hashicorp/go-retryablehttp). diff --git a/vendor/github.com/hashicorp/go-retryablehttp/client.go b/vendor/github.com/hashicorp/go-retryablehttp/client.go deleted file mode 100644 index 21f45e5..0000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/client.go +++ /dev/null @@ -1,500 +0,0 @@ -// The retryablehttp package provides a familiar HTTP client interface with -// automatic retries and exponential backoff. It is a thin wrapper over the -// standard net/http client library and exposes nearly the same public API. -// This makes retryablehttp very easy to drop into existing programs. -// -// retryablehttp performs automatic retries under certain conditions. Mainly, if -// an error is returned by the client (connection errors etc), or if a 500-range -// response is received, then a retry is invoked. Otherwise, the response is -// returned and left to the caller to interpret. -// -// Requests which take a request body should provide a non-nil function -// parameter. The best choice is to provide either a function satisfying -// ReaderFunc which provides multiple io.Readers in an efficient manner, a -// *bytes.Buffer (the underlying raw byte slice will be used) or a raw byte -// slice. As it is a reference type, and we will wrap it as needed by readers, -// we can efficiently re-use the request body without needing to copy it. If an -// io.Reader (such as a *bytes.Reader) is provided, the full body will be read -// prior to the first request, and will be efficiently re-used for any retries. -// ReadSeeker can be used, but some users have observed occasional data races -// between the net/http library and the Seek functionality of some -// implementations of ReadSeeker, so should be avoided if possible. -package retryablehttp - -import ( - "bytes" - "context" - "fmt" - "io" - "io/ioutil" - "log" - "math" - "math/rand" - "net/http" - "net/url" - "os" - "strings" - "time" - - "github.com/hashicorp/go-cleanhttp" -) - -var ( - // Default retry configuration - defaultRetryWaitMin = 1 * time.Second - defaultRetryWaitMax = 30 * time.Second - defaultRetryMax = 4 - - // defaultClient is used for performing requests without explicitly making - // a new client. It is purposely private to avoid modifications. - defaultClient = NewClient() - - // We need to consume response bodies to maintain http connections, but - // limit the size we consume to respReadLimit. - respReadLimit = int64(4096) -) - -// ReaderFunc is the type of function that can be given natively to NewRequest -type ReaderFunc func() (io.Reader, error) - -// LenReader is an interface implemented by many in-memory io.Reader's. Used -// for automatically sending the right Content-Length header when possible. -type LenReader interface { - Len() int -} - -// Request wraps the metadata needed to create HTTP requests. -type Request struct { - // body is a seekable reader over the request body payload. This is - // used to rewind the request data in between retries. - body ReaderFunc - - // Embed an HTTP request directly. This makes a *Request act exactly - // like an *http.Request so that all meta methods are supported. - *http.Request -} - -// WithContext returns wrapped Request with a shallow copy of underlying *http.Request -// with its context changed to ctx. The provided ctx must be non-nil. -func (r *Request) WithContext(ctx context.Context) *Request { - r.Request = r.Request.WithContext(ctx) - return r -} - -// NewRequest creates a new wrapped request. -func NewRequest(method, url string, rawBody interface{}) (*Request, error) { - var err error - var body ReaderFunc - var contentLength int64 - - if rawBody != nil { - switch rawBody.(type) { - // If they gave us a function already, great! Use it. - case ReaderFunc: - body = rawBody.(ReaderFunc) - tmp, err := body() - if err != nil { - return nil, err - } - if lr, ok := tmp.(LenReader); ok { - contentLength = int64(lr.Len()) - } - if c, ok := tmp.(io.Closer); ok { - c.Close() - } - - case func() (io.Reader, error): - body = rawBody.(func() (io.Reader, error)) - tmp, err := body() - if err != nil { - return nil, err - } - if lr, ok := tmp.(LenReader); ok { - contentLength = int64(lr.Len()) - } - if c, ok := tmp.(io.Closer); ok { - c.Close() - } - - // If a regular byte slice, we can read it over and over via new - // readers - case []byte: - buf := rawBody.([]byte) - body = func() (io.Reader, error) { - return bytes.NewReader(buf), nil - } - contentLength = int64(len(buf)) - - // If a bytes.Buffer we can read the underlying byte slice over and - // over - case *bytes.Buffer: - buf := rawBody.(*bytes.Buffer) - body = func() (io.Reader, error) { - return bytes.NewReader(buf.Bytes()), nil - } - contentLength = int64(buf.Len()) - - // We prioritize *bytes.Reader here because we don't really want to - // deal with it seeking so want it to match here instead of the - // io.ReadSeeker case. - case *bytes.Reader: - buf, err := ioutil.ReadAll(rawBody.(*bytes.Reader)) - if err != nil { - return nil, err - } - body = func() (io.Reader, error) { - return bytes.NewReader(buf), nil - } - contentLength = int64(len(buf)) - - // Compat case - case io.ReadSeeker: - raw := rawBody.(io.ReadSeeker) - body = func() (io.Reader, error) { - raw.Seek(0, 0) - return ioutil.NopCloser(raw), nil - } - if lr, ok := raw.(LenReader); ok { - contentLength = int64(lr.Len()) - } - - // Read all in so we can reset - case io.Reader: - buf, err := ioutil.ReadAll(rawBody.(io.Reader)) - if err != nil { - return nil, err - } - body = func() (io.Reader, error) { - return bytes.NewReader(buf), nil - } - contentLength = int64(len(buf)) - - default: - return nil, fmt.Errorf("cannot handle type %T", rawBody) - } - } - - httpReq, err := http.NewRequest(method, url, nil) - if err != nil { - return nil, err - } - httpReq.ContentLength = contentLength - - return &Request{body, httpReq}, nil -} - -// RequestLogHook allows a function to run before each retry. The HTTP -// request which will be made, and the retry number (0 for the initial -// request) are available to users. The internal logger is exposed to -// consumers. -type RequestLogHook func(*log.Logger, *http.Request, int) - -// ResponseLogHook is like RequestLogHook, but allows running a function -// on each HTTP response. This function will be invoked at the end of -// every HTTP request executed, regardless of whether a subsequent retry -// needs to be performed or not. If the response body is read or closed -// from this method, this will affect the response returned from Do(). -type ResponseLogHook func(*log.Logger, *http.Response) - -// CheckRetry specifies a policy for handling retries. It is called -// following each request with the response and error values returned by -// the http.Client. If CheckRetry returns false, the Client stops retrying -// and returns the response to the caller. If CheckRetry returns an error, -// that error value is returned in lieu of the error from the request. The -// Client will close any response body when retrying, but if the retry is -// aborted it is up to the CheckResponse callback to properly close any -// response body before returning. -type CheckRetry func(ctx context.Context, resp *http.Response, err error) (bool, error) - -// Backoff specifies a policy for how long to wait between retries. -// It is called after a failing request to determine the amount of time -// that should pass before trying again. -type Backoff func(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration - -// ErrorHandler is called if retries are expired, containing the last status -// from the http library. If not specified, default behavior for the library is -// to close the body and return an error indicating how many tries were -// attempted. If overriding this, be sure to close the body if needed. -type ErrorHandler func(resp *http.Response, err error, numTries int) (*http.Response, error) - -// Client is used to make HTTP requests. It adds additional functionality -// like automatic retries to tolerate minor outages. -type Client struct { - HTTPClient *http.Client // Internal HTTP client. - Logger *log.Logger // Customer logger instance. - - RetryWaitMin time.Duration // Minimum time to wait - RetryWaitMax time.Duration // Maximum time to wait - RetryMax int // Maximum number of retries - - // RequestLogHook allows a user-supplied function to be called - // before each retry. - RequestLogHook RequestLogHook - - // ResponseLogHook allows a user-supplied function to be called - // with the response from each HTTP request executed. - ResponseLogHook ResponseLogHook - - // CheckRetry specifies the policy for handling retries, and is called - // after each request. The default policy is DefaultRetryPolicy. - CheckRetry CheckRetry - - // Backoff specifies the policy for how long to wait between retries - Backoff Backoff - - // ErrorHandler specifies the custom error handler to use, if any - ErrorHandler ErrorHandler -} - -// NewClient creates a new Client with default settings. -func NewClient() *Client { - return &Client{ - HTTPClient: cleanhttp.DefaultClient(), - Logger: log.New(os.Stderr, "", log.LstdFlags), - RetryWaitMin: defaultRetryWaitMin, - RetryWaitMax: defaultRetryWaitMax, - RetryMax: defaultRetryMax, - CheckRetry: DefaultRetryPolicy, - Backoff: DefaultBackoff, - } -} - -// DefaultRetryPolicy provides a default callback for Client.CheckRetry, which -// will retry on connection errors and server errors. -func DefaultRetryPolicy(ctx context.Context, resp *http.Response, err error) (bool, error) { - // do not retry on context.Canceled or context.DeadlineExceeded - if ctx.Err() != nil { - return false, ctx.Err() - } - - if err != nil { - return true, err - } - // Check the response code. We retry on 500-range responses to allow - // the server time to recover, as 500's are typically not permanent - // errors and may relate to outages on the server side. This will catch - // invalid response codes as well, like 0 and 999. - if resp.StatusCode == 0 || (resp.StatusCode >= 500 && resp.StatusCode != 501) { - return true, nil - } - - return false, nil -} - -// DefaultBackoff provides a default callback for Client.Backoff which -// will perform exponential backoff based on the attempt number and limited -// by the provided minimum and maximum durations. -func DefaultBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration { - mult := math.Pow(2, float64(attemptNum)) * float64(min) - sleep := time.Duration(mult) - if float64(sleep) != mult || sleep > max { - sleep = max - } - return sleep -} - -// LinearJitterBackoff provides a callback for Client.Backoff which will -// perform linear backoff based on the attempt number and with jitter to -// prevent a thundering herd. -// -// min and max here are *not* absolute values. The number to be multipled by -// the attempt number will be chosen at random from between them, thus they are -// bounding the jitter. -// -// For instance: -// * To get strictly linear backoff of one second increasing each retry, set -// both to one second (1s, 2s, 3s, 4s, ...) -// * To get a small amount of jitter centered around one second increasing each -// retry, set to around one second, such as a min of 800ms and max of 1200ms -// (892ms, 2102ms, 2945ms, 4312ms, ...) -// * To get extreme jitter, set to a very wide spread, such as a min of 100ms -// and a max of 20s (15382ms, 292ms, 51321ms, 35234ms, ...) -func LinearJitterBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration { - // attemptNum always starts at zero but we want to start at 1 for multiplication - attemptNum++ - - if max <= min { - // Unclear what to do here, or they are the same, so return min * - // attemptNum - return min * time.Duration(attemptNum) - } - - // Seed rand; doing this every time is fine - rand := rand.New(rand.NewSource(int64(time.Now().Nanosecond()))) - - // Pick a random number that lies somewhere between the min and max and - // multiply by the attemptNum. attemptNum starts at zero so we always - // increment here. We first get a random percentage, then apply that to the - // difference between min and max, and add to min. - jitter := rand.Float64() * float64(max-min) - jitterMin := int64(jitter) + int64(min) - return time.Duration(jitterMin * int64(attemptNum)) -} - -// PassthroughErrorHandler is an ErrorHandler that directly passes through the -// values from the net/http library for the final request. The body is not -// closed. -func PassthroughErrorHandler(resp *http.Response, err error, _ int) (*http.Response, error) { - return resp, err -} - -// Do wraps calling an HTTP method with retries. -func (c *Client) Do(req *Request) (*http.Response, error) { - if c.Logger != nil { - c.Logger.Printf("[DEBUG] %s %s", req.Method, req.URL) - } - - var resp *http.Response - var err error - - for i := 0; ; i++ { - var code int // HTTP response code - - // Always rewind the request body when non-nil. - if req.body != nil { - body, err := req.body() - if err != nil { - return resp, err - } - if c, ok := body.(io.ReadCloser); ok { - req.Request.Body = c - } else { - req.Request.Body = ioutil.NopCloser(body) - } - } - - if c.RequestLogHook != nil { - c.RequestLogHook(c.Logger, req.Request, i) - } - - // Attempt the request - resp, err = c.HTTPClient.Do(req.Request) - if resp != nil { - code = resp.StatusCode - } - - // Check if we should continue with retries. - checkOK, checkErr := c.CheckRetry(req.Request.Context(), resp, err) - - if err != nil { - if c.Logger != nil { - c.Logger.Printf("[ERR] %s %s request failed: %v", req.Method, req.URL, err) - } - } else { - // Call this here to maintain the behavior of logging all requests, - // even if CheckRetry signals to stop. - if c.ResponseLogHook != nil { - // Call the response logger function if provided. - c.ResponseLogHook(c.Logger, resp) - } - } - - // Now decide if we should continue. - if !checkOK { - if checkErr != nil { - err = checkErr - } - return resp, err - } - - // We do this before drainBody beause there's no need for the I/O if - // we're breaking out - remain := c.RetryMax - i - if remain <= 0 { - break - } - - // We're going to retry, consume any response to reuse the connection. - if err == nil && resp != nil { - c.drainBody(resp.Body) - } - - wait := c.Backoff(c.RetryWaitMin, c.RetryWaitMax, i, resp) - desc := fmt.Sprintf("%s %s", req.Method, req.URL) - if code > 0 { - desc = fmt.Sprintf("%s (status: %d)", desc, code) - } - if c.Logger != nil { - c.Logger.Printf("[DEBUG] %s: retrying in %s (%d left)", desc, wait, remain) - } - time.Sleep(wait) - } - - if c.ErrorHandler != nil { - return c.ErrorHandler(resp, err, c.RetryMax+1) - } - - // By default, we close the response body and return an error without - // returning the response - if resp != nil { - resp.Body.Close() - } - return nil, fmt.Errorf("%s %s giving up after %d attempts", - req.Method, req.URL, c.RetryMax+1) -} - -// Try to read the response body so we can reuse this connection. -func (c *Client) drainBody(body io.ReadCloser) { - defer body.Close() - _, err := io.Copy(ioutil.Discard, io.LimitReader(body, respReadLimit)) - if err != nil { - if c.Logger != nil { - c.Logger.Printf("[ERR] error reading response body: %v", err) - } - } -} - -// Get is a shortcut for doing a GET request without making a new client. -func Get(url string) (*http.Response, error) { - return defaultClient.Get(url) -} - -// Get is a convenience helper for doing simple GET requests. -func (c *Client) Get(url string) (*http.Response, error) { - req, err := NewRequest("GET", url, nil) - if err != nil { - return nil, err - } - return c.Do(req) -} - -// Head is a shortcut for doing a HEAD request without making a new client. -func Head(url string) (*http.Response, error) { - return defaultClient.Head(url) -} - -// Head is a convenience method for doing simple HEAD requests. -func (c *Client) Head(url string) (*http.Response, error) { - req, err := NewRequest("HEAD", url, nil) - if err != nil { - return nil, err - } - return c.Do(req) -} - -// Post is a shortcut for doing a POST request without making a new client. -func Post(url, bodyType string, body interface{}) (*http.Response, error) { - return defaultClient.Post(url, bodyType, body) -} - -// Post is a convenience method for doing simple POST requests. -func (c *Client) Post(url, bodyType string, body interface{}) (*http.Response, error) { - req, err := NewRequest("POST", url, body) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", bodyType) - return c.Do(req) -} - -// PostForm is a shortcut to perform a POST with form data without creating -// a new client. -func PostForm(url string, data url.Values) (*http.Response, error) { - return defaultClient.PostForm(url, data) -} - -// PostForm is a convenience method for doing simple POST operations using -// pre-filled url.Values form data. -func (c *Client) PostForm(url string, data url.Values) (*http.Response, error) { - return c.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) -} diff --git a/vendor/github.com/hashicorp/go-rootcerts/.travis.yml b/vendor/github.com/hashicorp/go-rootcerts/.travis.yml deleted file mode 100644 index 80e1de4..0000000 --- a/vendor/github.com/hashicorp/go-rootcerts/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -sudo: false - -language: go - -go: - - 1.6 - -branches: - only: - - master - -script: make test diff --git a/vendor/github.com/hashicorp/go-rootcerts/LICENSE b/vendor/github.com/hashicorp/go-rootcerts/LICENSE deleted file mode 100644 index e87a115..0000000 --- a/vendor/github.com/hashicorp/go-rootcerts/LICENSE +++ /dev/null @@ -1,363 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - diff --git a/vendor/github.com/hashicorp/go-rootcerts/Makefile b/vendor/github.com/hashicorp/go-rootcerts/Makefile deleted file mode 100644 index c3989e7..0000000 --- a/vendor/github.com/hashicorp/go-rootcerts/Makefile +++ /dev/null @@ -1,8 +0,0 @@ -TEST?=./... - -test: - go test $(TEST) $(TESTARGS) -timeout=3s -parallel=4 - go vet $(TEST) - go test $(TEST) -race - -.PHONY: test diff --git a/vendor/github.com/hashicorp/go-rootcerts/README.md b/vendor/github.com/hashicorp/go-rootcerts/README.md deleted file mode 100644 index f5abffc..0000000 --- a/vendor/github.com/hashicorp/go-rootcerts/README.md +++ /dev/null @@ -1,43 +0,0 @@ -# rootcerts - -Functions for loading root certificates for TLS connections. - ------ - -Go's standard library `crypto/tls` provides a common mechanism for configuring -TLS connections in `tls.Config`. The `RootCAs` field on this struct is a pool -of certificates for the client to use as a trust store when verifying server -certificates. - -This library contains utility functions for loading certificates destined for -that field, as well as one other important thing: - -When the `RootCAs` field is `nil`, the standard library attempts to load the -host's root CA set. This behavior is OS-specific, and the Darwin -implementation contains [a bug that prevents trusted certificates from the -System and Login keychains from being loaded][1]. This library contains -Darwin-specific behavior that works around that bug. - -[1]: https://github.com/golang/go/issues/14514 - -## Example Usage - -Here's a snippet demonstrating how this library is meant to be used: - -```go -func httpClient() (*http.Client, error) - tlsConfig := &tls.Config{} - err := rootcerts.ConfigureTLS(tlsConfig, &rootcerts.Config{ - CAFile: os.Getenv("MYAPP_CAFILE"), - CAPath: os.Getenv("MYAPP_CAPATH"), - }) - if err != nil { - return nil, err - } - c := cleanhttp.DefaultClient() - t := cleanhttp.DefaultTransport() - t.TLSClientConfig = tlsConfig - c.Transport = t - return c, nil -} -``` diff --git a/vendor/github.com/hashicorp/go-rootcerts/doc.go b/vendor/github.com/hashicorp/go-rootcerts/doc.go deleted file mode 100644 index b55cc62..0000000 --- a/vendor/github.com/hashicorp/go-rootcerts/doc.go +++ /dev/null @@ -1,9 +0,0 @@ -// Package rootcerts contains functions to aid in loading CA certificates for -// TLS connections. -// -// In addition, its default behavior on Darwin works around an open issue [1] -// in Go's crypto/x509 that prevents certicates from being loaded from the -// System or Login keychains. -// -// [1] https://github.com/golang/go/issues/14514 -package rootcerts diff --git a/vendor/github.com/hashicorp/go-rootcerts/rootcerts.go b/vendor/github.com/hashicorp/go-rootcerts/rootcerts.go deleted file mode 100644 index aeb30ec..0000000 --- a/vendor/github.com/hashicorp/go-rootcerts/rootcerts.go +++ /dev/null @@ -1,103 +0,0 @@ -package rootcerts - -import ( - "crypto/tls" - "crypto/x509" - "fmt" - "io/ioutil" - "os" - "path/filepath" -) - -// Config determines where LoadCACerts will load certificates from. When both -// CAFile and CAPath are blank, this library's functions will either load -// system roots explicitly and return them, or set the CertPool to nil to allow -// Go's standard library to load system certs. -type Config struct { - // CAFile is a path to a PEM-encoded certificate file or bundle. Takes - // precedence over CAPath. - CAFile string - - // CAPath is a path to a directory populated with PEM-encoded certificates. - CAPath string -} - -// ConfigureTLS sets up the RootCAs on the provided tls.Config based on the -// Config specified. -func ConfigureTLS(t *tls.Config, c *Config) error { - if t == nil { - return nil - } - pool, err := LoadCACerts(c) - if err != nil { - return err - } - t.RootCAs = pool - return nil -} - -// LoadCACerts loads a CertPool based on the Config specified. -func LoadCACerts(c *Config) (*x509.CertPool, error) { - if c == nil { - c = &Config{} - } - if c.CAFile != "" { - return LoadCAFile(c.CAFile) - } - if c.CAPath != "" { - return LoadCAPath(c.CAPath) - } - - return LoadSystemCAs() -} - -// LoadCAFile loads a single PEM-encoded file from the path specified. -func LoadCAFile(caFile string) (*x509.CertPool, error) { - pool := x509.NewCertPool() - - pem, err := ioutil.ReadFile(caFile) - if err != nil { - return nil, fmt.Errorf("Error loading CA File: %s", err) - } - - ok := pool.AppendCertsFromPEM(pem) - if !ok { - return nil, fmt.Errorf("Error loading CA File: Couldn't parse PEM in: %s", caFile) - } - - return pool, nil -} - -// LoadCAPath walks the provided path and loads all certificates encounted into -// a pool. -func LoadCAPath(caPath string) (*x509.CertPool, error) { - pool := x509.NewCertPool() - walkFn := func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - - if info.IsDir() { - return nil - } - - pem, err := ioutil.ReadFile(path) - if err != nil { - return fmt.Errorf("Error loading file from CAPath: %s", err) - } - - ok := pool.AppendCertsFromPEM(pem) - if !ok { - return fmt.Errorf("Error loading CA Path: Couldn't parse PEM in: %s", path) - } - - return nil - } - - err := filepath.Walk(caPath, walkFn) - if err != nil { - return nil, err - } - - return pool, nil -} diff --git a/vendor/github.com/hashicorp/go-rootcerts/rootcerts_base.go b/vendor/github.com/hashicorp/go-rootcerts/rootcerts_base.go deleted file mode 100644 index 66b1472..0000000 --- a/vendor/github.com/hashicorp/go-rootcerts/rootcerts_base.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build !darwin - -package rootcerts - -import "crypto/x509" - -// LoadSystemCAs does nothing on non-Darwin systems. We return nil so that -// default behavior of standard TLS config libraries is triggered, which is to -// load system certs. -func LoadSystemCAs() (*x509.CertPool, error) { - return nil, nil -} diff --git a/vendor/github.com/hashicorp/go-rootcerts/rootcerts_darwin.go b/vendor/github.com/hashicorp/go-rootcerts/rootcerts_darwin.go deleted file mode 100644 index a9a0406..0000000 --- a/vendor/github.com/hashicorp/go-rootcerts/rootcerts_darwin.go +++ /dev/null @@ -1,48 +0,0 @@ -package rootcerts - -import ( - "crypto/x509" - "os/exec" - "path" - - "github.com/mitchellh/go-homedir" -) - -// LoadSystemCAs has special behavior on Darwin systems to work around -func LoadSystemCAs() (*x509.CertPool, error) { - pool := x509.NewCertPool() - - for _, keychain := range certKeychains() { - err := addCertsFromKeychain(pool, keychain) - if err != nil { - return nil, err - } - } - - return pool, nil -} - -func addCertsFromKeychain(pool *x509.CertPool, keychain string) error { - cmd := exec.Command("/usr/bin/security", "find-certificate", "-a", "-p", keychain) - data, err := cmd.Output() - if err != nil { - return err - } - - pool.AppendCertsFromPEM(data) - - return nil -} - -func certKeychains() []string { - keychains := []string{ - "/System/Library/Keychains/SystemRootCertificates.keychain", - "/Library/Keychains/System.keychain", - } - home, err := homedir.Dir() - if err == nil { - loginKeychain := path.Join(home, "Library", "Keychains", "login.keychain") - keychains = append(keychains, loginKeychain) - } - return keychains -} diff --git a/vendor/github.com/hashicorp/go-rootcerts/test-fixtures/capath-with-symlinks/securetrust.pem b/vendor/github.com/hashicorp/go-rootcerts/test-fixtures/capath-with-symlinks/securetrust.pem deleted file mode 120000 index dda0574..0000000 --- a/vendor/github.com/hashicorp/go-rootcerts/test-fixtures/capath-with-symlinks/securetrust.pem +++ /dev/null @@ -1 +0,0 @@ -../capath/securetrust.pem \ No newline at end of file diff --git a/vendor/github.com/hashicorp/go-rootcerts/test-fixtures/capath-with-symlinks/thawte.pem b/vendor/github.com/hashicorp/go-rootcerts/test-fixtures/capath-with-symlinks/thawte.pem deleted file mode 120000 index 37ed4f0..0000000 --- a/vendor/github.com/hashicorp/go-rootcerts/test-fixtures/capath-with-symlinks/thawte.pem +++ /dev/null @@ -1 +0,0 @@ -../capath/thawte.pem \ No newline at end of file diff --git a/vendor/github.com/hashicorp/go-sockaddr/.gitignore b/vendor/github.com/hashicorp/go-sockaddr/.gitignore deleted file mode 100644 index 41720b8..0000000 --- a/vendor/github.com/hashicorp/go-sockaddr/.gitignore +++ /dev/null @@ -1,26 +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 -.cover.out* -coverage.html diff --git a/vendor/github.com/hashicorp/go-sockaddr/GNUmakefile b/vendor/github.com/hashicorp/go-sockaddr/GNUmakefile deleted file mode 100644 index f3dfd24..0000000 --- a/vendor/github.com/hashicorp/go-sockaddr/GNUmakefile +++ /dev/null @@ -1,65 +0,0 @@ -TOOLS= golang.org/x/tools/cover -GOCOVER_TMPFILE?= $(GOCOVER_FILE).tmp -GOCOVER_FILE?= .cover.out -GOCOVERHTML?= coverage.html -FIND=`/usr/bin/which 2> /dev/null gfind find | /usr/bin/grep -v ^no | /usr/bin/head -n 1` -XARGS=`/usr/bin/which 2> /dev/null gxargs xargs | /usr/bin/grep -v ^no | /usr/bin/head -n 1` - -test:: $(GOCOVER_FILE) - @$(MAKE) -C cmd/sockaddr test - -cover:: coverage_report - -$(GOCOVER_FILE):: - @${FIND} . -type d ! -path '*cmd*' ! -path '*.git*' -print0 | ${XARGS} -0 -I % sh -ec "cd % && rm -f $(GOCOVER_TMPFILE) && go test -coverprofile=$(GOCOVER_TMPFILE)" - - @echo 'mode: set' > $(GOCOVER_FILE) - @${FIND} . -type f ! -path '*cmd*' ! -path '*.git*' -name "$(GOCOVER_TMPFILE)" -print0 | ${XARGS} -0 -n1 cat $(GOCOVER_TMPFILE) | grep -v '^mode: ' >> ${PWD}/$(GOCOVER_FILE) - -$(GOCOVERHTML): $(GOCOVER_FILE) - go tool cover -html=$(GOCOVER_FILE) -o $(GOCOVERHTML) - -coverage_report:: $(GOCOVER_FILE) - go tool cover -html=$(GOCOVER_FILE) - -audit_tools:: - @go get -u github.com/golang/lint/golint && echo "Installed golint:" - @go get -u github.com/fzipp/gocyclo && echo "Installed gocyclo:" - @go get -u github.com/remyoudompheng/go-misc/deadcode && echo "Installed deadcode:" - @go get -u github.com/client9/misspell/cmd/misspell && echo "Installed misspell:" - @go get -u github.com/gordonklaus/ineffassign && echo "Installed ineffassign:" - -audit:: - deadcode - go tool vet -all *.go - go tool vet -shadow=true *.go - golint *.go - ineffassign . - gocyclo -over 65 *.go - misspell *.go - -clean:: - rm -f $(GOCOVER_FILE) $(GOCOVERHTML) - -dev:: - @go build - @$(MAKE) -B -C cmd/sockaddr sockaddr - -install:: - @go install - @$(MAKE) -C cmd/sockaddr install - -doc:: - @echo Visit: http://127.0.0.1:6161/pkg/github.com/hashicorp/go-sockaddr/ - godoc -http=:6161 -goroot $GOROOT - -world:: - @set -e; \ - for os in solaris darwin freebsd linux windows; do \ - for arch in amd64; do \ - printf "Building on %s-%s\n" "$${os}" "$${arch}" ; \ - env GOOS="$${os}" GOARCH="$${arch}" go build -o /dev/null; \ - done; \ - done - - $(MAKE) -C cmd/sockaddr world diff --git a/vendor/github.com/hashicorp/go-sockaddr/LICENSE b/vendor/github.com/hashicorp/go-sockaddr/LICENSE deleted file mode 100644 index a612ad9..0000000 --- a/vendor/github.com/hashicorp/go-sockaddr/LICENSE +++ /dev/null @@ -1,373 +0,0 @@ -Mozilla Public License Version 2.0 -================================== - -1. Definitions --------------- - -1.1. "Contributor" - means each individual or legal entity that creates, contributes to - the creation of, or owns Covered Software. - -1.2. "Contributor Version" - means the combination of the Contributions of others (if any) used - by a Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - means Source Code Form to which the initial Contributor has attached - the notice in Exhibit A, the Executable Form of such Source Code - Form, and Modifications of such Source Code Form, in each case - including portions thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - (a) that the initial Contributor has attached the notice described - in Exhibit B to the Covered Software; or - - (b) that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the - terms of a Secondary License. - -1.6. "Executable Form" - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - means a work that combines Covered Software with other material, in - a separate file or files, that is not Covered Software. - -1.8. "License" - means this document. - -1.9. "Licensable" - means having the right to grant, to the maximum extent possible, - whether at the time of the initial grant or subsequently, any and - all of the rights conveyed by this License. - -1.10. "Modifications" - means any of the following: - - (a) any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered - Software; or - - (b) any new file in Source Code Form that contains any Covered - Software. - -1.11. "Patent Claims" of a Contributor - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the - License, by the making, using, selling, offering for sale, having - made, import, or transfer of either its Contributions or its - Contributor Version. - -1.12. "Secondary License" - means either the GNU General Public License, Version 2.0, the GNU - Lesser General Public License, Version 2.1, the GNU Affero General - Public License, Version 3.0, or any later versions of those - licenses. - -1.13. "Source Code Form" - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that - controls, is controlled by, or is under common control with You. For - purposes of this definition, "control" means (a) the power, direct - or indirect, to cause the direction or management of such entity, - whether by contract or otherwise, or (b) ownership of more than - fifty percent (50%) of the outstanding shares or beneficial - ownership of such entity. - -2. License Grants and Conditions --------------------------------- - -2.1. Grants - -Each Contributor hereby grants You a world-wide, royalty-free, -non-exclusive license: - -(a) under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - -(b) under Patent Claims of such Contributor to make, use, sell, offer - for sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - -The licenses granted in Section 2.1 with respect to any Contribution -become effective for each Contribution on the date the Contributor first -distributes such Contribution. - -2.3. Limitations on Grant Scope - -The licenses granted in this Section 2 are the only rights granted under -this License. No additional rights or licenses will be implied from the -distribution or licensing of Covered Software under this License. -Notwithstanding Section 2.1(b) above, no patent license is granted by a -Contributor: - -(a) for any code that a Contributor has removed from Covered Software; - or - -(b) for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - -(c) under Patent Claims infringed by Covered Software in the absence of - its Contributions. - -This License does not grant any rights in the trademarks, service marks, -or logos of any Contributor (except as may be necessary to comply with -the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - -No Contributor makes additional grants as a result of Your choice to -distribute the Covered Software under a subsequent version of this -License (see Section 10.2) or under the terms of a Secondary License (if -permitted under the terms of Section 3.3). - -2.5. Representation - -Each Contributor represents that the Contributor believes its -Contributions are its original creation(s) or it has sufficient rights -to grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - -This License is not intended to limit any rights You have under -applicable copyright doctrines of fair use, fair dealing, or other -equivalents. - -2.7. Conditions - -Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted -in Section 2.1. - -3. Responsibilities -------------------- - -3.1. Distribution of Source Form - -All distribution of Covered Software in Source Code Form, including any -Modifications that You create or to which You contribute, must be under -the terms of this License. You must inform recipients that the Source -Code Form of the Covered Software is governed by the terms of this -License, and how they can obtain a copy of this License. You may not -attempt to alter or restrict the recipients' rights in the Source Code -Form. - -3.2. Distribution of Executable Form - -If You distribute Covered Software in Executable Form then: - -(a) such Covered Software must also be made available in Source Code - Form, as described in Section 3.1, and You must inform recipients of - the Executable Form how they can obtain a copy of such Source Code - Form by reasonable means in a timely manner, at a charge no more - than the cost of distribution to the recipient; and - -(b) You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter - the recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - -You may create and distribute a Larger Work under terms of Your choice, -provided that You also comply with the requirements of this License for -the Covered Software. If the Larger Work is a combination of Covered -Software with a work governed by one or more Secondary Licenses, and the -Covered Software is not Incompatible With Secondary Licenses, this -License permits You to additionally distribute such Covered Software -under the terms of such Secondary License(s), so that the recipient of -the Larger Work may, at their option, further distribute the Covered -Software under the terms of either this License or such Secondary -License(s). - -3.4. Notices - -You may not remove or alter the substance of any license notices -(including copyright notices, patent notices, disclaimers of warranty, -or limitations of liability) contained within the Source Code Form of -the Covered Software, except that You may alter any license notices to -the extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - -You may choose to offer, and to charge a fee for, warranty, support, -indemnity or liability obligations to one or more recipients of Covered -Software. However, You may do so only on Your own behalf, and not on -behalf of any Contributor. You must make it absolutely clear that any -such warranty, support, indemnity, or liability obligation is offered by -You alone, and You hereby agree to indemnify every Contributor for any -liability incurred by such Contributor as a result of warranty, support, -indemnity or liability terms You offer. You may include additional -disclaimers of warranty and limitations of liability specific to any -jurisdiction. - -4. Inability to Comply Due to Statute or Regulation ---------------------------------------------------- - -If it is impossible for You to comply with any of the terms of this -License with respect to some or all of the Covered Software due to -statute, judicial order, or regulation then You must: (a) comply with -the terms of this License to the maximum extent possible; and (b) -describe the limitations and the code they affect. Such description must -be placed in a text file included with all distributions of the Covered -Software under this License. Except to the extent prohibited by statute -or regulation, such description must be sufficiently detailed for a -recipient of ordinary skill to be able to understand it. - -5. Termination --------------- - -5.1. The rights granted under this License will terminate automatically -if You fail to comply with any of its terms. However, if You become -compliant, then the rights granted under this License from a particular -Contributor are reinstated (a) provisionally, unless and until such -Contributor explicitly and finally terminates Your grants, and (b) on an -ongoing basis, if such Contributor fails to notify You of the -non-compliance by some reasonable means prior to 60 days after You have -come back into compliance. Moreover, Your grants from a particular -Contributor are reinstated on an ongoing basis if such Contributor -notifies You of the non-compliance by some reasonable means, this is the -first time You have received notice of non-compliance with this License -from such Contributor, and You become compliant prior to 30 days after -Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent -infringement claim (excluding declaratory judgment actions, -counter-claims, and cross-claims) alleging that a Contributor Version -directly or indirectly infringes any patent, then the rights granted to -You by any and all Contributors for the Covered Software under Section -2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all -end user license agreements (excluding distributors and resellers) which -have been validly granted by You or Your distributors under this License -prior to termination shall survive termination. - -************************************************************************ -* * -* 6. Disclaimer of Warranty * -* ------------------------- * -* * -* Covered Software is provided under this License on an "as is" * -* basis, without warranty of any kind, either expressed, implied, or * -* statutory, including, without limitation, warranties that the * -* Covered Software is free of defects, merchantable, fit for a * -* particular purpose or non-infringing. The entire risk as to the * -* quality and performance of the Covered Software is with You. * -* Should any Covered Software prove defective in any respect, You * -* (not any Contributor) assume the cost of any necessary servicing, * -* repair, or correction. This disclaimer of warranty constitutes an * -* essential part of this License. No use of any Covered Software is * -* authorized under this License except under this disclaimer. * -* * -************************************************************************ - -************************************************************************ -* * -* 7. Limitation of Liability * -* -------------------------- * -* * -* Under no circumstances and under no legal theory, whether tort * -* (including negligence), contract, or otherwise, shall any * -* Contributor, or anyone who distributes Covered Software as * -* permitted above, be liable to You for any direct, indirect, * -* special, incidental, or consequential damages of any character * -* including, without limitation, damages for lost profits, loss of * -* goodwill, work stoppage, computer failure or malfunction, or any * -* and all other commercial damages or losses, even if such party * -* shall have been informed of the possibility of such damages. This * -* limitation of liability shall not apply to liability for death or * -* personal injury resulting from such party's negligence to the * -* extent applicable law prohibits such limitation. Some * -* jurisdictions do not allow the exclusion or limitation of * -* incidental or consequential damages, so this exclusion and * -* limitation may not apply to You. * -* * -************************************************************************ - -8. Litigation -------------- - -Any litigation relating to this License may be brought only in the -courts of a jurisdiction where the defendant maintains its principal -place of business and such litigation shall be governed by laws of that -jurisdiction, without reference to its conflict-of-law provisions. -Nothing in this Section shall prevent a party's ability to bring -cross-claims or counter-claims. - -9. Miscellaneous ----------------- - -This License represents the complete agreement concerning the subject -matter hereof. If any provision of this License is held to be -unenforceable, such provision shall be reformed only to the extent -necessary to make it enforceable. Any law or regulation which provides -that the language of a contract shall be construed against the drafter -shall not be used to construe this License against a Contributor. - -10. Versions of the License ---------------------------- - -10.1. New Versions - -Mozilla Foundation is the license steward. Except as provided in Section -10.3, no one other than the license steward has the right to modify or -publish new versions of this License. Each version will be given a -distinguishing version number. - -10.2. Effect of New Versions - -You may distribute the Covered Software under the terms of the version -of the License under which You originally received the Covered Software, -or under the terms of any subsequent version published by the license -steward. - -10.3. Modified Versions - -If you create software not governed by this License, and you want to -create a new license for such software, you may create and use a -modified version of this License if you rename the license and remove -any references to the name of the license steward (except to note that -such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary -Licenses - -If You choose to distribute Source Code Form that is Incompatible With -Secondary Licenses under the terms of this version of the License, the -notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice -------------------------------------------- - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular -file, then You may include the notice in a location (such as a LICENSE -file in a relevant directory) where a recipient would be likely to look -for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice ---------------------------------------------------------- - - This Source Code Form is "Incompatible With Secondary Licenses", as - defined by the Mozilla Public License, v. 2.0. diff --git a/vendor/github.com/hashicorp/go-sockaddr/README.md b/vendor/github.com/hashicorp/go-sockaddr/README.md deleted file mode 100644 index a2e170a..0000000 --- a/vendor/github.com/hashicorp/go-sockaddr/README.md +++ /dev/null @@ -1,118 +0,0 @@ -# go-sockaddr - -## `sockaddr` Library - -Socket address convenience functions for Go. `go-sockaddr` is a convenience -library that makes doing the right thing with IP addresses easy. `go-sockaddr` -is loosely modeled after the UNIX `sockaddr_t` and creates a union of the family -of `sockaddr_t` types (see below for an ascii diagram). Library documentation -is available -at -[https://godoc.org/github.com/hashicorp/go-sockaddr](https://godoc.org/github.com/hashicorp/go-sockaddr). -The primary intent of the library was to make it possible to define heuristics -for selecting the correct IP addresses when a configuration is evaluated at -runtime. See -the -[docs](https://godoc.org/github.com/hashicorp/go-sockaddr), -[`template` package](https://godoc.org/github.com/hashicorp/go-sockaddr/template), -tests, -and -[CLI utility](https://github.com/hashicorp/go-sockaddr/tree/master/cmd/sockaddr) -for details and hints as to how to use this library. - -For example, with this library it is possible to find an IP address that: - -* is attached to a default route - ([`GetDefaultInterfaces()`](https://godoc.org/github.com/hashicorp/go-sockaddr#GetDefaultInterfaces)) -* is contained within a CIDR block ([`IfByNetwork()`](https://godoc.org/github.com/hashicorp/go-sockaddr#IfByNetwork)) -* is an RFC1918 address - ([`IfByRFC("1918")`](https://godoc.org/github.com/hashicorp/go-sockaddr#IfByRFC)) -* is ordered - ([`OrderedIfAddrBy(args)`](https://godoc.org/github.com/hashicorp/go-sockaddr#OrderedIfAddrBy) where - `args` includes, but is not limited - to, - [`AscIfType`](https://godoc.org/github.com/hashicorp/go-sockaddr#AscIfType), - [`AscNetworkSize`](https://godoc.org/github.com/hashicorp/go-sockaddr#AscNetworkSize)) -* excludes all IPv6 addresses - ([`IfByType("^(IPv4)$")`](https://godoc.org/github.com/hashicorp/go-sockaddr#IfByType)) -* is larger than a `/32` - ([`IfByMaskSize(32)`](https://godoc.org/github.com/hashicorp/go-sockaddr#IfByMaskSize)) -* is not on a `down` interface - ([`ExcludeIfs("flags", "down")`](https://godoc.org/github.com/hashicorp/go-sockaddr#ExcludeIfs)) -* preferences an IPv6 address over an IPv4 address - ([`SortIfByType()`](https://godoc.org/github.com/hashicorp/go-sockaddr#SortIfByType) + - [`ReverseIfAddrs()`](https://godoc.org/github.com/hashicorp/go-sockaddr#ReverseIfAddrs)); and -* excludes any IP in RFC6890 address - ([`IfByRFC("6890")`](https://godoc.org/github.com/hashicorp/go-sockaddr#IfByRFC)) - -Or any combination or variation therein. - -There are also a few simple helper functions such as `GetPublicIP` and -`GetPrivateIP` which both return strings and select the first public or private -IP address on the default interface, respectively. Similarly, there is also a -helper function called `GetInterfaceIP` which returns the first usable IP -address on the named interface. - -## `sockaddr` CLI - -Given the possible complexity of the `sockaddr` library, there is a CLI utility -that accompanies the library, also -called -[`sockaddr`](https://github.com/hashicorp/go-sockaddr/tree/master/cmd/sockaddr). -The -[`sockaddr`](https://github.com/hashicorp/go-sockaddr/tree/master/cmd/sockaddr) -utility exposes nearly all of the functionality of the library and can be used -either as an administrative tool or testing tool. To install -the -[`sockaddr`](https://github.com/hashicorp/go-sockaddr/tree/master/cmd/sockaddr), -run: - -```text -$ go get -u github.com/hashicorp/go-sockaddr/cmd/sockaddr -``` - -If you're familiar with UNIX's `sockaddr` struct's, the following diagram -mapping the C `sockaddr` (top) to `go-sockaddr` structs (bottom) and -interfaces will be helpful: - -``` -+-------------------------------------------------------+ -| | -| sockaddr | -| SockAddr | -| | -| +--------------+ +----------------------------------+ | -| | sockaddr_un | | | | -| | SockAddrUnix | | sockaddr_in{,6} | | -| +--------------+ | IPAddr | | -| | | | -| | +-------------+ +--------------+ | | -| | | sockaddr_in | | sockaddr_in6 | | | -| | | IPv4Addr | | IPv6Addr | | | -| | +-------------+ +--------------+ | | -| | | | -| +----------------------------------+ | -| | -+-------------------------------------------------------+ -``` - -## Inspiration and Design - -There were many subtle inspirations that led to this design, but the most direct -inspiration for the filtering syntax was -OpenBSD's -[`pf.conf(5)`](https://www.freebsd.org/cgi/man.cgi?query=pf.conf&apropos=0&sektion=0&arch=default&format=html#PARAMETERS) firewall -syntax that lets you select the first IP address on a given named interface. -The original problem stemmed from: - -* needing to create immutable images using [Packer](https://www.packer.io) that - ran the [Consul](https://www.consul.io) process (Consul can only use one IP - address at a time); -* images that may or may not have multiple interfaces or IP addresses at - runtime; and -* we didn't want to rely on configuration management to render out the correct - IP address if the VM image was being used in an auto-scaling group. - -Instead we needed some way to codify a heuristic that would correctly select the -right IP address but the input parameters were not known when the image was -created. diff --git a/vendor/github.com/hashicorp/go-sockaddr/doc.go b/vendor/github.com/hashicorp/go-sockaddr/doc.go deleted file mode 100644 index 90671de..0000000 --- a/vendor/github.com/hashicorp/go-sockaddr/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -/* -Package sockaddr is a Go implementation of the UNIX socket family data types and -related helper functions. -*/ -package sockaddr diff --git a/vendor/github.com/hashicorp/go-sockaddr/ifaddr.go b/vendor/github.com/hashicorp/go-sockaddr/ifaddr.go deleted file mode 100644 index 0811b27..0000000 --- a/vendor/github.com/hashicorp/go-sockaddr/ifaddr.go +++ /dev/null @@ -1,254 +0,0 @@ -package sockaddr - -import "strings" - -// ifAddrAttrMap is a map of the IfAddr type-specific attributes. -var ifAddrAttrMap map[AttrName]func(IfAddr) string -var ifAddrAttrs []AttrName - -func init() { - ifAddrAttrInit() -} - -// GetPrivateIP returns a string with a single IP address that is part of RFC -// 6890 and has a default route. If the system can't determine its IP address -// or find an RFC 6890 IP address, an empty string will be returned instead. -// This function is the `eval` equivalent of: -// -// ``` -// $ sockaddr eval -r '{{GetPrivateInterfaces | attr "address"}}' -/// ``` -func GetPrivateIP() (string, error) { - privateIfs, err := GetPrivateInterfaces() - if err != nil { - return "", err - } - if len(privateIfs) < 1 { - return "", nil - } - - ifAddr := privateIfs[0] - ip := *ToIPAddr(ifAddr.SockAddr) - return ip.NetIP().String(), nil -} - -// GetPrivateIPs returns a string with all IP addresses that are part of RFC -// 6890 (regardless of whether or not there is a default route, unlike -// GetPublicIP). If the system can't find any RFC 6890 IP addresses, an empty -// string will be returned instead. This function is the `eval` equivalent of: -// -// ``` -// $ sockaddr eval -r '{{GetAllInterfaces | include "RFC" "6890" | join "address" " "}}' -/// ``` -func GetPrivateIPs() (string, error) { - ifAddrs, err := GetAllInterfaces() - if err != nil { - return "", err - } else if len(ifAddrs) < 1 { - return "", nil - } - - ifAddrs, _ = FilterIfByType(ifAddrs, TypeIP) - if len(ifAddrs) == 0 { - return "", nil - } - - OrderedIfAddrBy(AscIfType, AscIfNetworkSize).Sort(ifAddrs) - - ifAddrs, _, err = IfByRFC("6890", ifAddrs) - if err != nil { - return "", err - } else if len(ifAddrs) == 0 { - return "", nil - } - - _, ifAddrs, err = IfByRFC(ForwardingBlacklistRFC, ifAddrs) - if err != nil { - return "", err - } else if len(ifAddrs) == 0 { - return "", nil - } - - ips := make([]string, 0, len(ifAddrs)) - for _, ifAddr := range ifAddrs { - ip := *ToIPAddr(ifAddr.SockAddr) - s := ip.NetIP().String() - ips = append(ips, s) - } - - return strings.Join(ips, " "), nil -} - -// GetPublicIP returns a string with a single IP address that is NOT part of RFC -// 6890 and has a default route. If the system can't determine its IP address -// or find a non RFC 6890 IP address, an empty string will be returned instead. -// This function is the `eval` equivalent of: -// -// ``` -// $ sockaddr eval -r '{{GetPublicInterfaces | attr "address"}}' -/// ``` -func GetPublicIP() (string, error) { - publicIfs, err := GetPublicInterfaces() - if err != nil { - return "", err - } else if len(publicIfs) < 1 { - return "", nil - } - - ifAddr := publicIfs[0] - ip := *ToIPAddr(ifAddr.SockAddr) - return ip.NetIP().String(), nil -} - -// GetPublicIPs returns a string with all IP addresses that are NOT part of RFC -// 6890 (regardless of whether or not there is a default route, unlike -// GetPublicIP). If the system can't find any non RFC 6890 IP addresses, an -// empty string will be returned instead. This function is the `eval` -// equivalent of: -// -// ``` -// $ sockaddr eval -r '{{GetAllInterfaces | exclude "RFC" "6890" | join "address" " "}}' -/// ``` -func GetPublicIPs() (string, error) { - ifAddrs, err := GetAllInterfaces() - if err != nil { - return "", err - } else if len(ifAddrs) < 1 { - return "", nil - } - - ifAddrs, _ = FilterIfByType(ifAddrs, TypeIP) - if len(ifAddrs) == 0 { - return "", nil - } - - OrderedIfAddrBy(AscIfType, AscIfNetworkSize).Sort(ifAddrs) - - _, ifAddrs, err = IfByRFC("6890", ifAddrs) - if err != nil { - return "", err - } else if len(ifAddrs) == 0 { - return "", nil - } - - ips := make([]string, 0, len(ifAddrs)) - for _, ifAddr := range ifAddrs { - ip := *ToIPAddr(ifAddr.SockAddr) - s := ip.NetIP().String() - ips = append(ips, s) - } - - return strings.Join(ips, " "), nil -} - -// GetInterfaceIP returns a string with a single IP address sorted by the size -// of the network (i.e. IP addresses with a smaller netmask, larger network -// size, are sorted first). This function is the `eval` equivalent of: -// -// ``` -// $ sockaddr eval -r '{{GetAllInterfaces | include "name" <> | sort "type,size" | include "flag" "forwardable" | attr "address" }}' -/// ``` -func GetInterfaceIP(namedIfRE string) (string, error) { - ifAddrs, err := GetAllInterfaces() - if err != nil { - return "", err - } - - ifAddrs, _, err = IfByName(namedIfRE, ifAddrs) - if err != nil { - return "", err - } - - ifAddrs, _, err = IfByFlag("forwardable", ifAddrs) - if err != nil { - return "", err - } - - ifAddrs, err = SortIfBy("+type,+size", ifAddrs) - if err != nil { - return "", err - } - - if len(ifAddrs) == 0 { - return "", err - } - - ip := ToIPAddr(ifAddrs[0].SockAddr) - if ip == nil { - return "", err - } - - return IPAddrAttr(*ip, "address"), nil -} - -// GetInterfaceIPs returns a string with all IPs, sorted by the size of the -// network (i.e. IP addresses with a smaller netmask, larger network size, are -// sorted first), on a named interface. This function is the `eval` equivalent -// of: -// -// ``` -// $ sockaddr eval -r '{{GetAllInterfaces | include "name" <> | sort "type,size" | join "address" " "}}' -/// ``` -func GetInterfaceIPs(namedIfRE string) (string, error) { - ifAddrs, err := GetAllInterfaces() - if err != nil { - return "", err - } - - ifAddrs, _, err = IfByName(namedIfRE, ifAddrs) - if err != nil { - return "", err - } - - ifAddrs, err = SortIfBy("+type,+size", ifAddrs) - if err != nil { - return "", err - } - - if len(ifAddrs) == 0 { - return "", err - } - - ips := make([]string, 0, len(ifAddrs)) - for _, ifAddr := range ifAddrs { - ip := *ToIPAddr(ifAddr.SockAddr) - s := ip.NetIP().String() - ips = append(ips, s) - } - - return strings.Join(ips, " "), nil -} - -// IfAddrAttrs returns a list of attributes supported by the IfAddr type -func IfAddrAttrs() []AttrName { - return ifAddrAttrs -} - -// IfAddrAttr returns a string representation of an attribute for the given -// IfAddr. -func IfAddrAttr(ifAddr IfAddr, attrName AttrName) string { - fn, found := ifAddrAttrMap[attrName] - if !found { - return "" - } - - return fn(ifAddr) -} - -// ifAddrAttrInit is called once at init() -func ifAddrAttrInit() { - // Sorted for human readability - ifAddrAttrs = []AttrName{ - "flags", - "name", - } - - ifAddrAttrMap = map[AttrName]func(ifAddr IfAddr) string{ - "flags": func(ifAddr IfAddr) string { - return ifAddr.Interface.Flags.String() - }, - "name": func(ifAddr IfAddr) string { - return ifAddr.Interface.Name - }, - } -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/ifaddrs.go b/vendor/github.com/hashicorp/go-sockaddr/ifaddrs.go deleted file mode 100644 index 2a706c3..0000000 --- a/vendor/github.com/hashicorp/go-sockaddr/ifaddrs.go +++ /dev/null @@ -1,1281 +0,0 @@ -package sockaddr - -import ( - "encoding/binary" - "errors" - "fmt" - "math/big" - "net" - "regexp" - "sort" - "strconv" - "strings" -) - -var ( - // Centralize all regexps and regexp.Copy() where necessary. - signRE *regexp.Regexp = regexp.MustCompile(`^[\s]*[+-]`) - whitespaceRE *regexp.Regexp = regexp.MustCompile(`[\s]+`) - ifNameRE *regexp.Regexp = regexp.MustCompile(`^(?:Ethernet|Wireless LAN) adapter ([^:]+):`) - ipAddrRE *regexp.Regexp = regexp.MustCompile(`^ IPv[46] Address\. \. \. \. \. \. \. \. \. \. \. : ([^\s]+)`) -) - -// IfAddrs is a slice of IfAddr -type IfAddrs []IfAddr - -func (ifs IfAddrs) Len() int { return len(ifs) } - -// CmpIfFunc is the function signature that must be met to be used in the -// OrderedIfAddrBy multiIfAddrSorter -type CmpIfAddrFunc func(p1, p2 *IfAddr) int - -// multiIfAddrSorter implements the Sort interface, sorting the IfAddrs within. -type multiIfAddrSorter struct { - ifAddrs IfAddrs - cmp []CmpIfAddrFunc -} - -// Sort sorts the argument slice according to the Cmp functions passed to -// OrderedIfAddrBy. -func (ms *multiIfAddrSorter) Sort(ifAddrs IfAddrs) { - ms.ifAddrs = ifAddrs - sort.Sort(ms) -} - -// OrderedIfAddrBy sorts SockAddr by the list of sort function pointers. -func OrderedIfAddrBy(cmpFuncs ...CmpIfAddrFunc) *multiIfAddrSorter { - return &multiIfAddrSorter{ - cmp: cmpFuncs, - } -} - -// Len is part of sort.Interface. -func (ms *multiIfAddrSorter) Len() int { - return len(ms.ifAddrs) -} - -// Less is part of sort.Interface. It is implemented by looping along the Cmp() -// functions until it finds a comparison that is either less than or greater -// than. A return value of 0 defers sorting to the next function in the -// multisorter (which means the results of sorting may leave the resutls in a -// non-deterministic order). -func (ms *multiIfAddrSorter) Less(i, j int) bool { - p, q := &ms.ifAddrs[i], &ms.ifAddrs[j] - // Try all but the last comparison. - var k int - for k = 0; k < len(ms.cmp)-1; k++ { - cmp := ms.cmp[k] - x := cmp(p, q) - switch x { - case -1: - // p < q, so we have a decision. - return true - case 1: - // p > q, so we have a decision. - return false - } - // p == q; try the next comparison. - } - // All comparisons to here said "equal", so just return whatever the - // final comparison reports. - switch ms.cmp[k](p, q) { - case -1: - return true - case 1: - return false - default: - // Still a tie! Now what? - return false - panic("undefined sort order for remaining items in the list") - } -} - -// Swap is part of sort.Interface. -func (ms *multiIfAddrSorter) Swap(i, j int) { - ms.ifAddrs[i], ms.ifAddrs[j] = ms.ifAddrs[j], ms.ifAddrs[i] -} - -// AscIfAddress is a sorting function to sort IfAddrs by their respective -// address type. Non-equal types are deferred in the sort. -func AscIfAddress(p1Ptr, p2Ptr *IfAddr) int { - return AscAddress(&p1Ptr.SockAddr, &p2Ptr.SockAddr) -} - -// AscIfDefault is a sorting function to sort IfAddrs by whether or not they -// have a default route or not. Non-equal types are deferred in the sort. -// -// FIXME: This is a particularly expensive sorting operation because of the -// non-memoized calls to NewRouteInfo(). In an ideal world the routeInfo data -// once at the start of the sort and pass it along as a context or by wrapping -// the IfAddr type with this information (this would also solve the inability to -// return errors and the possibility of failing silently). Fortunately, -// N*log(N) where N = 3 is only ~6.2 invocations. Not ideal, but not worth -// optimizing today. The common case is this gets called once or twice. -// Patches welcome. -func AscIfDefault(p1Ptr, p2Ptr *IfAddr) int { - ri, err := NewRouteInfo() - if err != nil { - return sortDeferDecision - } - - defaultIfName, err := ri.GetDefaultInterfaceName() - if err != nil { - return sortDeferDecision - } - - switch { - case p1Ptr.Interface.Name == defaultIfName && p2Ptr.Interface.Name == defaultIfName: - return sortDeferDecision - case p1Ptr.Interface.Name == defaultIfName: - return sortReceiverBeforeArg - case p2Ptr.Interface.Name == defaultIfName: - return sortArgBeforeReceiver - default: - return sortDeferDecision - } -} - -// AscIfName is a sorting function to sort IfAddrs by their interface names. -func AscIfName(p1Ptr, p2Ptr *IfAddr) int { - return strings.Compare(p1Ptr.Name, p2Ptr.Name) -} - -// AscIfNetworkSize is a sorting function to sort IfAddrs by their respective -// network mask size. -func AscIfNetworkSize(p1Ptr, p2Ptr *IfAddr) int { - return AscNetworkSize(&p1Ptr.SockAddr, &p2Ptr.SockAddr) -} - -// AscIfPort is a sorting function to sort IfAddrs by their respective -// port type. Non-equal types are deferred in the sort. -func AscIfPort(p1Ptr, p2Ptr *IfAddr) int { - return AscPort(&p1Ptr.SockAddr, &p2Ptr.SockAddr) -} - -// AscIfPrivate is a sorting function to sort IfAddrs by "private" values before -// "public" values. Both IPv4 and IPv6 are compared against RFC6890 (RFC6890 -// includes, and is not limited to, RFC1918 and RFC6598 for IPv4, and IPv6 -// includes RFC4193). -func AscIfPrivate(p1Ptr, p2Ptr *IfAddr) int { - return AscPrivate(&p1Ptr.SockAddr, &p2Ptr.SockAddr) -} - -// AscIfType is a sorting function to sort IfAddrs by their respective address -// type. Non-equal types are deferred in the sort. -func AscIfType(p1Ptr, p2Ptr *IfAddr) int { - return AscType(&p1Ptr.SockAddr, &p2Ptr.SockAddr) -} - -// DescIfAddress is identical to AscIfAddress but reverse ordered. -func DescIfAddress(p1Ptr, p2Ptr *IfAddr) int { - return -1 * AscAddress(&p1Ptr.SockAddr, &p2Ptr.SockAddr) -} - -// DescIfDefault is identical to AscIfDefault but reverse ordered. -func DescIfDefault(p1Ptr, p2Ptr *IfAddr) int { - return -1 * AscIfDefault(p1Ptr, p2Ptr) -} - -// DescIfName is identical to AscIfName but reverse ordered. -func DescIfName(p1Ptr, p2Ptr *IfAddr) int { - return -1 * strings.Compare(p1Ptr.Name, p2Ptr.Name) -} - -// DescIfNetworkSize is identical to AscIfNetworkSize but reverse ordered. -func DescIfNetworkSize(p1Ptr, p2Ptr *IfAddr) int { - return -1 * AscNetworkSize(&p1Ptr.SockAddr, &p2Ptr.SockAddr) -} - -// DescIfPort is identical to AscIfPort but reverse ordered. -func DescIfPort(p1Ptr, p2Ptr *IfAddr) int { - return -1 * AscPort(&p1Ptr.SockAddr, &p2Ptr.SockAddr) -} - -// DescIfPrivate is identical to AscIfPrivate but reverse ordered. -func DescIfPrivate(p1Ptr, p2Ptr *IfAddr) int { - return -1 * AscPrivate(&p1Ptr.SockAddr, &p2Ptr.SockAddr) -} - -// DescIfType is identical to AscIfType but reverse ordered. -func DescIfType(p1Ptr, p2Ptr *IfAddr) int { - return -1 * AscType(&p1Ptr.SockAddr, &p2Ptr.SockAddr) -} - -// FilterIfByType filters IfAddrs and returns a list of the matching type -func FilterIfByType(ifAddrs IfAddrs, type_ SockAddrType) (matchedIfs, excludedIfs IfAddrs) { - excludedIfs = make(IfAddrs, 0, len(ifAddrs)) - matchedIfs = make(IfAddrs, 0, len(ifAddrs)) - - for _, ifAddr := range ifAddrs { - if ifAddr.SockAddr.Type()&type_ != 0 { - matchedIfs = append(matchedIfs, ifAddr) - } else { - excludedIfs = append(excludedIfs, ifAddr) - } - } - return matchedIfs, excludedIfs -} - -// IfAttr forwards the selector to IfAttr.Attr() for resolution. If there is -// more than one IfAddr, only the first IfAddr is used. -func IfAttr(selectorName string, ifAddr IfAddr) (string, error) { - attrName := AttrName(strings.ToLower(selectorName)) - attrVal, err := ifAddr.Attr(attrName) - return attrVal, err -} - -// IfAttrs forwards the selector to IfAttrs.Attr() for resolution. If there is -// more than one IfAddr, only the first IfAddr is used. -func IfAttrs(selectorName string, ifAddrs IfAddrs) (string, error) { - if len(ifAddrs) == 0 { - return "", nil - } - - attrName := AttrName(strings.ToLower(selectorName)) - attrVal, err := ifAddrs[0].Attr(attrName) - return attrVal, err -} - -// GetAllInterfaces iterates over all available network interfaces and finds all -// available IP addresses on each interface and converts them to -// sockaddr.IPAddrs, and returning the result as an array of IfAddr. -func GetAllInterfaces() (IfAddrs, error) { - ifs, err := net.Interfaces() - if err != nil { - return nil, err - } - - ifAddrs := make(IfAddrs, 0, len(ifs)) - for _, intf := range ifs { - addrs, err := intf.Addrs() - if err != nil { - return nil, err - } - - for _, addr := range addrs { - var ipAddr IPAddr - ipAddr, err = NewIPAddr(addr.String()) - if err != nil { - return IfAddrs{}, fmt.Errorf("unable to create an IP address from %q", addr.String()) - } - - ifAddr := IfAddr{ - SockAddr: ipAddr, - Interface: intf, - } - ifAddrs = append(ifAddrs, ifAddr) - } - } - - return ifAddrs, nil -} - -// GetDefaultInterfaces returns IfAddrs of the addresses attached to the default -// route. -func GetDefaultInterfaces() (IfAddrs, error) { - ri, err := NewRouteInfo() - if err != nil { - return nil, err - } - - defaultIfName, err := ri.GetDefaultInterfaceName() - if err != nil { - return nil, err - } - - var defaultIfs, ifAddrs IfAddrs - ifAddrs, err = GetAllInterfaces() - for _, ifAddr := range ifAddrs { - if ifAddr.Name == defaultIfName { - defaultIfs = append(defaultIfs, ifAddr) - } - } - - return defaultIfs, nil -} - -// GetPrivateInterfaces returns an IfAddrs that are part of RFC 6890 and have a -// default route. If the system can't determine its IP address or find an RFC -// 6890 IP address, an empty IfAddrs will be returned instead. This function is -// the `eval` equivalent of: -// -// ``` -// $ sockaddr eval -r '{{GetAllInterfaces | include "type" "ip" | include "flags" "forwardable" | include "flags" "up" | sort "default,type,size" | include "RFC" "6890" }}' -/// ``` -func GetPrivateInterfaces() (IfAddrs, error) { - privateIfs, err := GetAllInterfaces() - if err != nil { - return IfAddrs{}, err - } - if len(privateIfs) == 0 { - return IfAddrs{}, nil - } - - privateIfs, _ = FilterIfByType(privateIfs, TypeIP) - if len(privateIfs) == 0 { - return IfAddrs{}, nil - } - - privateIfs, _, err = IfByFlag("forwardable", privateIfs) - if err != nil { - return IfAddrs{}, err - } - - privateIfs, _, err = IfByFlag("up", privateIfs) - if err != nil { - return IfAddrs{}, err - } - - if len(privateIfs) == 0 { - return IfAddrs{}, nil - } - - OrderedIfAddrBy(AscIfDefault, AscIfType, AscIfNetworkSize).Sort(privateIfs) - - privateIfs, _, err = IfByRFC("6890", privateIfs) - if err != nil { - return IfAddrs{}, err - } else if len(privateIfs) == 0 { - return IfAddrs{}, nil - } - - return privateIfs, nil -} - -// GetPublicInterfaces returns an IfAddrs that are NOT part of RFC 6890 and has a -// default route. If the system can't determine its IP address or find a non -// RFC 6890 IP address, an empty IfAddrs will be returned instead. This -// function is the `eval` equivalent of: -// -// ``` -// $ sockaddr eval -r '{{GetAllInterfaces | include "type" "ip" | include "flags" "forwardable" | include "flags" "up" | sort "default,type,size" | exclude "RFC" "6890" }}' -/// ``` -func GetPublicInterfaces() (IfAddrs, error) { - publicIfs, err := GetAllInterfaces() - if err != nil { - return IfAddrs{}, err - } - if len(publicIfs) == 0 { - return IfAddrs{}, nil - } - - publicIfs, _ = FilterIfByType(publicIfs, TypeIP) - if len(publicIfs) == 0 { - return IfAddrs{}, nil - } - - publicIfs, _, err = IfByFlag("forwardable", publicIfs) - if err != nil { - return IfAddrs{}, err - } - - publicIfs, _, err = IfByFlag("up", publicIfs) - if err != nil { - return IfAddrs{}, err - } - - if len(publicIfs) == 0 { - return IfAddrs{}, nil - } - - OrderedIfAddrBy(AscIfDefault, AscIfType, AscIfNetworkSize).Sort(publicIfs) - - _, publicIfs, err = IfByRFC("6890", publicIfs) - if err != nil { - return IfAddrs{}, err - } else if len(publicIfs) == 0 { - return IfAddrs{}, nil - } - - return publicIfs, nil -} - -// IfByAddress returns a list of matched and non-matched IfAddrs, or an error if -// the regexp fails to compile. -func IfByAddress(inputRe string, ifAddrs IfAddrs) (matched, remainder IfAddrs, err error) { - re, err := regexp.Compile(inputRe) - if err != nil { - return nil, nil, fmt.Errorf("Unable to compile address regexp %+q: %v", inputRe, err) - } - - matchedAddrs := make(IfAddrs, 0, len(ifAddrs)) - excludedAddrs := make(IfAddrs, 0, len(ifAddrs)) - for _, addr := range ifAddrs { - if re.MatchString(addr.SockAddr.String()) { - matchedAddrs = append(matchedAddrs, addr) - } else { - excludedAddrs = append(excludedAddrs, addr) - } - } - - return matchedAddrs, excludedAddrs, nil -} - -// IfByName returns a list of matched and non-matched IfAddrs, or an error if -// the regexp fails to compile. -func IfByName(inputRe string, ifAddrs IfAddrs) (matched, remainder IfAddrs, err error) { - re, err := regexp.Compile(inputRe) - if err != nil { - return nil, nil, fmt.Errorf("Unable to compile name regexp %+q: %v", inputRe, err) - } - - matchedAddrs := make(IfAddrs, 0, len(ifAddrs)) - excludedAddrs := make(IfAddrs, 0, len(ifAddrs)) - for _, addr := range ifAddrs { - if re.MatchString(addr.Name) { - matchedAddrs = append(matchedAddrs, addr) - } else { - excludedAddrs = append(excludedAddrs, addr) - } - } - - return matchedAddrs, excludedAddrs, nil -} - -// IfByPort returns a list of matched and non-matched IfAddrs, or an error if -// the regexp fails to compile. -func IfByPort(inputRe string, ifAddrs IfAddrs) (matchedIfs, excludedIfs IfAddrs, err error) { - re, err := regexp.Compile(inputRe) - if err != nil { - return nil, nil, fmt.Errorf("Unable to compile port regexp %+q: %v", inputRe, err) - } - - ipIfs, nonIfs := FilterIfByType(ifAddrs, TypeIP) - matchedIfs = make(IfAddrs, 0, len(ipIfs)) - excludedIfs = append(IfAddrs(nil), nonIfs...) - for _, addr := range ipIfs { - ipAddr := ToIPAddr(addr.SockAddr) - if ipAddr == nil { - continue - } - - port := strconv.FormatInt(int64((*ipAddr).IPPort()), 10) - if re.MatchString(port) { - matchedIfs = append(matchedIfs, addr) - } else { - excludedIfs = append(excludedIfs, addr) - } - } - - return matchedIfs, excludedIfs, nil -} - -// IfByRFC returns a list of matched and non-matched IfAddrs that contain the -// relevant RFC-specified traits. -func IfByRFC(selectorParam string, ifAddrs IfAddrs) (matched, remainder IfAddrs, err error) { - inputRFC, err := strconv.ParseUint(selectorParam, 10, 64) - if err != nil { - return IfAddrs{}, IfAddrs{}, fmt.Errorf("unable to parse RFC number %q: %v", selectorParam, err) - } - - matchedIfAddrs := make(IfAddrs, 0, len(ifAddrs)) - remainingIfAddrs := make(IfAddrs, 0, len(ifAddrs)) - - rfcNetMap := KnownRFCs() - rfcNets, ok := rfcNetMap[uint(inputRFC)] - if !ok { - return nil, nil, fmt.Errorf("unsupported RFC %d", inputRFC) - } - - for _, ifAddr := range ifAddrs { - var contained bool - for _, rfcNet := range rfcNets { - if rfcNet.Contains(ifAddr.SockAddr) { - matchedIfAddrs = append(matchedIfAddrs, ifAddr) - contained = true - break - } - } - if !contained { - remainingIfAddrs = append(remainingIfAddrs, ifAddr) - } - } - - return matchedIfAddrs, remainingIfAddrs, nil -} - -// IfByRFCs returns a list of matched and non-matched IfAddrs that contain the -// relevant RFC-specified traits. Multiple RFCs can be specified and separated -// by the `|` symbol. No protection is taken to ensure an IfAddr does not end -// up in both the included and excluded list. -func IfByRFCs(selectorParam string, ifAddrs IfAddrs) (matched, remainder IfAddrs, err error) { - var includedIfs, excludedIfs IfAddrs - for _, rfcStr := range strings.Split(selectorParam, "|") { - includedRFCIfs, excludedRFCIfs, err := IfByRFC(rfcStr, ifAddrs) - if err != nil { - return IfAddrs{}, IfAddrs{}, fmt.Errorf("unable to lookup RFC number %q: %v", rfcStr, err) - } - includedIfs = append(includedIfs, includedRFCIfs...) - excludedIfs = append(excludedIfs, excludedRFCIfs...) - } - - return includedIfs, excludedIfs, nil -} - -// IfByMaskSize returns a list of matched and non-matched IfAddrs that have the -// matching mask size. -func IfByMaskSize(selectorParam string, ifAddrs IfAddrs) (matchedIfs, excludedIfs IfAddrs, err error) { - maskSize, err := strconv.ParseUint(selectorParam, 10, 64) - if err != nil { - return IfAddrs{}, IfAddrs{}, fmt.Errorf("invalid exclude size argument (%q): %v", selectorParam, err) - } - - ipIfs, nonIfs := FilterIfByType(ifAddrs, TypeIP) - matchedIfs = make(IfAddrs, 0, len(ipIfs)) - excludedIfs = append(IfAddrs(nil), nonIfs...) - for _, addr := range ipIfs { - ipAddr := ToIPAddr(addr.SockAddr) - if ipAddr == nil { - return IfAddrs{}, IfAddrs{}, fmt.Errorf("unable to filter mask sizes on non-IP type %s: %v", addr.SockAddr.Type().String(), addr.SockAddr.String()) - } - - switch { - case (*ipAddr).Type()&TypeIPv4 != 0 && maskSize > 32: - return IfAddrs{}, IfAddrs{}, fmt.Errorf("mask size out of bounds for IPv4 address: %d", maskSize) - case (*ipAddr).Type()&TypeIPv6 != 0 && maskSize > 128: - return IfAddrs{}, IfAddrs{}, fmt.Errorf("mask size out of bounds for IPv6 address: %d", maskSize) - } - - if (*ipAddr).Maskbits() == int(maskSize) { - matchedIfs = append(matchedIfs, addr) - } else { - excludedIfs = append(excludedIfs, addr) - } - } - - return matchedIfs, excludedIfs, nil -} - -// IfByType returns a list of matching and non-matching IfAddr that match the -// specified type. For instance: -// -// include "type" "IPv4,IPv6" -// -// will include any IfAddrs that is either an IPv4 or IPv6 address. Any -// addresses on those interfaces that don't match will be included in the -// remainder results. -func IfByType(inputTypes string, ifAddrs IfAddrs) (matched, remainder IfAddrs, err error) { - matchingIfAddrs := make(IfAddrs, 0, len(ifAddrs)) - remainingIfAddrs := make(IfAddrs, 0, len(ifAddrs)) - - ifTypes := strings.Split(strings.ToLower(inputTypes), "|") - for _, ifType := range ifTypes { - switch ifType { - case "ip", "ipv4", "ipv6", "unix": - // Valid types - default: - return nil, nil, fmt.Errorf("unsupported type %q %q", ifType, inputTypes) - } - } - - for _, ifAddr := range ifAddrs { - for _, ifType := range ifTypes { - var matched bool - switch { - case ifType == "ip" && ifAddr.SockAddr.Type()&TypeIP != 0: - matched = true - case ifType == "ipv4" && ifAddr.SockAddr.Type()&TypeIPv4 != 0: - matched = true - case ifType == "ipv6" && ifAddr.SockAddr.Type()&TypeIPv6 != 0: - matched = true - case ifType == "unix" && ifAddr.SockAddr.Type()&TypeUnix != 0: - matched = true - } - - if matched { - matchingIfAddrs = append(matchingIfAddrs, ifAddr) - } else { - remainingIfAddrs = append(remainingIfAddrs, ifAddr) - } - } - } - - return matchingIfAddrs, remainingIfAddrs, nil -} - -// IfByFlag returns a list of matching and non-matching IfAddrs that match the -// specified type. For instance: -// -// include "flag" "up,broadcast" -// -// will include any IfAddrs that have both the "up" and "broadcast" flags set. -// Any addresses on those interfaces that don't match will be omitted from the -// results. -func IfByFlag(inputFlags string, ifAddrs IfAddrs) (matched, remainder IfAddrs, err error) { - matchedAddrs := make(IfAddrs, 0, len(ifAddrs)) - excludedAddrs := make(IfAddrs, 0, len(ifAddrs)) - - var wantForwardable, - wantGlobalUnicast, - wantInterfaceLocalMulticast, - wantLinkLocalMulticast, - wantLinkLocalUnicast, - wantLoopback, - wantMulticast, - wantUnspecified bool - var ifFlags net.Flags - var checkFlags, checkAttrs bool - for _, flagName := range strings.Split(strings.ToLower(inputFlags), "|") { - switch flagName { - case "broadcast": - checkFlags = true - ifFlags = ifFlags | net.FlagBroadcast - case "down": - checkFlags = true - ifFlags = (ifFlags &^ net.FlagUp) - case "forwardable": - checkAttrs = true - wantForwardable = true - case "global unicast": - checkAttrs = true - wantGlobalUnicast = true - case "interface-local multicast": - checkAttrs = true - wantInterfaceLocalMulticast = true - case "link-local multicast": - checkAttrs = true - wantLinkLocalMulticast = true - case "link-local unicast": - checkAttrs = true - wantLinkLocalUnicast = true - case "loopback": - checkAttrs = true - checkFlags = true - ifFlags = ifFlags | net.FlagLoopback - wantLoopback = true - case "multicast": - checkAttrs = true - checkFlags = true - ifFlags = ifFlags | net.FlagMulticast - wantMulticast = true - case "point-to-point": - checkFlags = true - ifFlags = ifFlags | net.FlagPointToPoint - case "unspecified": - checkAttrs = true - wantUnspecified = true - case "up": - checkFlags = true - ifFlags = ifFlags | net.FlagUp - default: - return nil, nil, fmt.Errorf("Unknown interface flag: %+q", flagName) - } - } - - for _, ifAddr := range ifAddrs { - var matched bool - if checkFlags && ifAddr.Interface.Flags&ifFlags == ifFlags { - matched = true - } - if checkAttrs { - if ip := ToIPAddr(ifAddr.SockAddr); ip != nil { - netIP := (*ip).NetIP() - switch { - case wantGlobalUnicast && netIP.IsGlobalUnicast(): - matched = true - case wantInterfaceLocalMulticast && netIP.IsInterfaceLocalMulticast(): - matched = true - case wantLinkLocalMulticast && netIP.IsLinkLocalMulticast(): - matched = true - case wantLinkLocalUnicast && netIP.IsLinkLocalUnicast(): - matched = true - case wantLoopback && netIP.IsLoopback(): - matched = true - case wantMulticast && netIP.IsMulticast(): - matched = true - case wantUnspecified && netIP.IsUnspecified(): - matched = true - case wantForwardable && !IsRFC(ForwardingBlacklist, ifAddr.SockAddr): - matched = true - } - } - } - if matched { - matchedAddrs = append(matchedAddrs, ifAddr) - } else { - excludedAddrs = append(excludedAddrs, ifAddr) - } - } - return matchedAddrs, excludedAddrs, nil -} - -// IfByNetwork returns an IfAddrs that are equal to or included within the -// network passed in by selector. -func IfByNetwork(selectorParam string, inputIfAddrs IfAddrs) (IfAddrs, IfAddrs, error) { - var includedIfs, excludedIfs IfAddrs - for _, netStr := range strings.Split(selectorParam, "|") { - netAddr, err := NewIPAddr(netStr) - if err != nil { - return nil, nil, fmt.Errorf("unable to create an IP address from %+q: %v", netStr, err) - } - - for _, ifAddr := range inputIfAddrs { - if netAddr.Contains(ifAddr.SockAddr) { - includedIfs = append(includedIfs, ifAddr) - } else { - excludedIfs = append(excludedIfs, ifAddr) - } - } - } - - return includedIfs, excludedIfs, nil -} - -// IfAddrMath will return a new IfAddr struct with a mutated value. -func IfAddrMath(operation, value string, inputIfAddr IfAddr) (IfAddr, error) { - // Regexp used to enforce the sign being a required part of the grammar for - // some values. - signRe := signRE.Copy() - - switch strings.ToLower(operation) { - case "address": - // "address" operates on the IP address and is allowed to overflow or - // underflow networks, however it will wrap along the underlying address's - // underlying type. - - if !signRe.MatchString(value) { - return IfAddr{}, fmt.Errorf("sign (+/-) is required for operation %q", operation) - } - - switch sockType := inputIfAddr.SockAddr.Type(); sockType { - case TypeIPv4: - // 33 == Accept any uint32 value - // TODO(seanc@): Add the ability to parse hex - i, err := strconv.ParseInt(value, 10, 33) - if err != nil { - return IfAddr{}, fmt.Errorf("unable to convert %q to int for operation %q: %v", value, operation, err) - } - - ipv4 := *ToIPv4Addr(inputIfAddr.SockAddr) - ipv4Uint32 := uint32(ipv4.Address) - ipv4Uint32 += uint32(i) - return IfAddr{ - SockAddr: IPv4Addr{ - Address: IPv4Address(ipv4Uint32), - Mask: ipv4.Mask, - }, - Interface: inputIfAddr.Interface, - }, nil - case TypeIPv6: - // 64 == Accept any int32 value - // TODO(seanc@): Add the ability to parse hex. Also parse a bignum int. - i, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return IfAddr{}, fmt.Errorf("unable to convert %q to int for operation %q: %v", value, operation, err) - } - - ipv6 := *ToIPv6Addr(inputIfAddr.SockAddr) - ipv6BigIntA := new(big.Int) - ipv6BigIntA.Set(ipv6.Address) - ipv6BigIntB := big.NewInt(i) - - ipv6Addr := ipv6BigIntA.Add(ipv6BigIntA, ipv6BigIntB) - ipv6Addr.And(ipv6Addr, ipv6HostMask) - - return IfAddr{ - SockAddr: IPv6Addr{ - Address: IPv6Address(ipv6Addr), - Mask: ipv6.Mask, - }, - Interface: inputIfAddr.Interface, - }, nil - default: - return IfAddr{}, fmt.Errorf("unsupported type for operation %q: %T", operation, sockType) - } - case "network": - // "network" operates on the network address. Positive values start at the - // network address and negative values wrap at the network address, which - // means a "-1" value on a network will be the broadcast address after - // wrapping is applied. - - if !signRe.MatchString(value) { - return IfAddr{}, fmt.Errorf("sign (+/-) is required for operation %q", operation) - } - - switch sockType := inputIfAddr.SockAddr.Type(); sockType { - case TypeIPv4: - // 33 == Accept any uint32 value - // TODO(seanc@): Add the ability to parse hex - i, err := strconv.ParseInt(value, 10, 33) - if err != nil { - return IfAddr{}, fmt.Errorf("unable to convert %q to int for operation %q: %v", value, operation, err) - } - - ipv4 := *ToIPv4Addr(inputIfAddr.SockAddr) - ipv4Uint32 := uint32(ipv4.NetworkAddress()) - - // Wrap along network mask boundaries. EZ-mode wrapping made possible by - // use of int64 vs a uint. - var wrappedMask int64 - if i >= 0 { - wrappedMask = i - } else { - wrappedMask = 1 + i + int64(^uint32(ipv4.Mask)) - } - - ipv4Uint32 = ipv4Uint32 + (uint32(wrappedMask) &^ uint32(ipv4.Mask)) - - return IfAddr{ - SockAddr: IPv4Addr{ - Address: IPv4Address(ipv4Uint32), - Mask: ipv4.Mask, - }, - Interface: inputIfAddr.Interface, - }, nil - case TypeIPv6: - // 64 == Accept any int32 value - // TODO(seanc@): Add the ability to parse hex. Also parse a bignum int. - i, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return IfAddr{}, fmt.Errorf("unable to convert %q to int for operation %q: %v", value, operation, err) - } - - ipv6 := *ToIPv6Addr(inputIfAddr.SockAddr) - ipv6BigInt := new(big.Int) - ipv6BigInt.Set(ipv6.NetworkAddress()) - - mask := new(big.Int) - mask.Set(ipv6.Mask) - if i > 0 { - wrappedMask := new(big.Int) - wrappedMask.SetInt64(i) - - wrappedMask.AndNot(wrappedMask, mask) - ipv6BigInt.Add(ipv6BigInt, wrappedMask) - } else { - // Mask off any bits that exceed the network size. Subtract the - // wrappedMask from the last usable - 1 - wrappedMask := new(big.Int) - wrappedMask.SetInt64(-1 * i) - wrappedMask.Sub(wrappedMask, big.NewInt(1)) - - wrappedMask.AndNot(wrappedMask, mask) - - lastUsable := new(big.Int) - lastUsable.Set(ipv6.LastUsable().(IPv6Addr).Address) - - ipv6BigInt = lastUsable.Sub(lastUsable, wrappedMask) - } - - return IfAddr{ - SockAddr: IPv6Addr{ - Address: IPv6Address(ipv6BigInt), - Mask: ipv6.Mask, - }, - Interface: inputIfAddr.Interface, - }, nil - default: - return IfAddr{}, fmt.Errorf("unsupported type for operation %q: %T", operation, sockType) - } - case "mask": - // "mask" operates on the IP address and returns the IP address on - // which the given integer mask has been applied. If the applied mask - // corresponds to a larger network than the mask of the IP address, - // the latter will be replaced by the former. - switch sockType := inputIfAddr.SockAddr.Type(); sockType { - case TypeIPv4: - i, err := strconv.ParseUint(value, 10, 32) - if err != nil { - return IfAddr{}, fmt.Errorf("unable to convert %q to int for operation %q: %v", value, operation, err) - } - - if i > 32 { - return IfAddr{}, fmt.Errorf("parameter for operation %q on ipv4 addresses must be between 0 and 32", operation) - } - - ipv4 := *ToIPv4Addr(inputIfAddr.SockAddr) - - ipv4Mask := net.CIDRMask(int(i), 32) - ipv4MaskUint32 := binary.BigEndian.Uint32(ipv4Mask) - - maskedIpv4 := ipv4.NetIP().Mask(ipv4Mask) - maskedIpv4Uint32 := binary.BigEndian.Uint32(maskedIpv4) - - maskedIpv4MaskUint32 := uint32(ipv4.Mask) - - if ipv4MaskUint32 < maskedIpv4MaskUint32 { - maskedIpv4MaskUint32 = ipv4MaskUint32 - } - - return IfAddr{ - SockAddr: IPv4Addr{ - Address: IPv4Address(maskedIpv4Uint32), - Mask: IPv4Mask(maskedIpv4MaskUint32), - }, - Interface: inputIfAddr.Interface, - }, nil - case TypeIPv6: - i, err := strconv.ParseUint(value, 10, 32) - if err != nil { - return IfAddr{}, fmt.Errorf("unable to convert %q to int for operation %q: %v", value, operation, err) - } - - if i > 128 { - return IfAddr{}, fmt.Errorf("parameter for operation %q on ipv6 addresses must be between 0 and 64", operation) - } - - ipv6 := *ToIPv6Addr(inputIfAddr.SockAddr) - - ipv6Mask := net.CIDRMask(int(i), 128) - ipv6MaskBigInt := new(big.Int) - ipv6MaskBigInt.SetBytes(ipv6Mask) - - maskedIpv6 := ipv6.NetIP().Mask(ipv6Mask) - maskedIpv6BigInt := new(big.Int) - maskedIpv6BigInt.SetBytes(maskedIpv6) - - maskedIpv6MaskBigInt := new(big.Int) - maskedIpv6MaskBigInt.Set(ipv6.Mask) - - if ipv6MaskBigInt.Cmp(maskedIpv6MaskBigInt) == -1 { - maskedIpv6MaskBigInt = ipv6MaskBigInt - } - - return IfAddr{ - SockAddr: IPv6Addr{ - Address: IPv6Address(maskedIpv6BigInt), - Mask: IPv6Mask(maskedIpv6MaskBigInt), - }, - Interface: inputIfAddr.Interface, - }, nil - default: - return IfAddr{}, fmt.Errorf("unsupported type for operation %q: %T", operation, sockType) - } - default: - return IfAddr{}, fmt.Errorf("unsupported math operation: %q", operation) - } -} - -// IfAddrsMath will apply an IfAddrMath operation each IfAddr struct. Any -// failure will result in zero results. -func IfAddrsMath(operation, value string, inputIfAddrs IfAddrs) (IfAddrs, error) { - outputAddrs := make(IfAddrs, 0, len(inputIfAddrs)) - for _, ifAddr := range inputIfAddrs { - result, err := IfAddrMath(operation, value, ifAddr) - if err != nil { - return IfAddrs{}, fmt.Errorf("unable to perform an IPMath operation on %s: %v", ifAddr, err) - } - outputAddrs = append(outputAddrs, result) - } - return outputAddrs, nil -} - -// IncludeIfs returns an IfAddrs based on the passed in selector. -func IncludeIfs(selectorName, selectorParam string, inputIfAddrs IfAddrs) (IfAddrs, error) { - var includedIfs IfAddrs - var err error - - switch strings.ToLower(selectorName) { - case "address": - includedIfs, _, err = IfByAddress(selectorParam, inputIfAddrs) - case "flag", "flags": - includedIfs, _, err = IfByFlag(selectorParam, inputIfAddrs) - case "name": - includedIfs, _, err = IfByName(selectorParam, inputIfAddrs) - case "network": - includedIfs, _, err = IfByNetwork(selectorParam, inputIfAddrs) - case "port": - includedIfs, _, err = IfByPort(selectorParam, inputIfAddrs) - case "rfc", "rfcs": - includedIfs, _, err = IfByRFCs(selectorParam, inputIfAddrs) - case "size": - includedIfs, _, err = IfByMaskSize(selectorParam, inputIfAddrs) - case "type": - includedIfs, _, err = IfByType(selectorParam, inputIfAddrs) - default: - return IfAddrs{}, fmt.Errorf("invalid include selector %q", selectorName) - } - - if err != nil { - return IfAddrs{}, err - } - - return includedIfs, nil -} - -// ExcludeIfs returns an IfAddrs based on the passed in selector. -func ExcludeIfs(selectorName, selectorParam string, inputIfAddrs IfAddrs) (IfAddrs, error) { - var excludedIfs IfAddrs - var err error - - switch strings.ToLower(selectorName) { - case "address": - _, excludedIfs, err = IfByAddress(selectorParam, inputIfAddrs) - case "flag", "flags": - _, excludedIfs, err = IfByFlag(selectorParam, inputIfAddrs) - case "name": - _, excludedIfs, err = IfByName(selectorParam, inputIfAddrs) - case "network": - _, excludedIfs, err = IfByNetwork(selectorParam, inputIfAddrs) - case "port": - _, excludedIfs, err = IfByPort(selectorParam, inputIfAddrs) - case "rfc", "rfcs": - _, excludedIfs, err = IfByRFCs(selectorParam, inputIfAddrs) - case "size": - _, excludedIfs, err = IfByMaskSize(selectorParam, inputIfAddrs) - case "type": - _, excludedIfs, err = IfByType(selectorParam, inputIfAddrs) - default: - return IfAddrs{}, fmt.Errorf("invalid exclude selector %q", selectorName) - } - - if err != nil { - return IfAddrs{}, err - } - - return excludedIfs, nil -} - -// SortIfBy returns an IfAddrs sorted based on the passed in selector. Multiple -// sort clauses can be passed in as a comma delimited list without whitespace. -func SortIfBy(selectorParam string, inputIfAddrs IfAddrs) (IfAddrs, error) { - sortedIfs := append(IfAddrs(nil), inputIfAddrs...) - - clauses := strings.Split(selectorParam, ",") - sortFuncs := make([]CmpIfAddrFunc, len(clauses)) - - for i, clause := range clauses { - switch strings.TrimSpace(strings.ToLower(clause)) { - case "+address", "address": - // The "address" selector returns an array of IfAddrs - // ordered by the network address. IfAddrs that are not - // comparable will be at the end of the list and in a - // non-deterministic order. - sortFuncs[i] = AscIfAddress - case "-address": - sortFuncs[i] = DescIfAddress - case "+default", "default": - sortFuncs[i] = AscIfDefault - case "-default": - sortFuncs[i] = DescIfDefault - case "+name", "name": - // The "name" selector returns an array of IfAddrs - // ordered by the interface name. - sortFuncs[i] = AscIfName - case "-name": - sortFuncs[i] = DescIfName - case "+port", "port": - // The "port" selector returns an array of IfAddrs - // ordered by the port, if included in the IfAddr. - // IfAddrs that are not comparable will be at the end of - // the list and in a non-deterministic order. - sortFuncs[i] = AscIfPort - case "-port": - sortFuncs[i] = DescIfPort - case "+private", "private": - // The "private" selector returns an array of IfAddrs - // ordered by private addresses first. IfAddrs that are - // not comparable will be at the end of the list and in - // a non-deterministic order. - sortFuncs[i] = AscIfPrivate - case "-private": - sortFuncs[i] = DescIfPrivate - case "+size", "size": - // The "size" selector returns an array of IfAddrs - // ordered by the size of the network mask, smaller mask - // (larger number of hosts per network) to largest - // (e.g. a /24 sorts before a /32). - sortFuncs[i] = AscIfNetworkSize - case "-size": - sortFuncs[i] = DescIfNetworkSize - case "+type", "type": - // The "type" selector returns an array of IfAddrs - // ordered by the type of the IfAddr. The sort order is - // Unix, IPv4, then IPv6. - sortFuncs[i] = AscIfType - case "-type": - sortFuncs[i] = DescIfType - default: - // Return an empty list for invalid sort types. - return IfAddrs{}, fmt.Errorf("unknown sort type: %q", clause) - } - } - - OrderedIfAddrBy(sortFuncs...).Sort(sortedIfs) - - return sortedIfs, nil -} - -// UniqueIfAddrsBy creates a unique set of IfAddrs based on the matching -// selector. UniqueIfAddrsBy assumes the input has already been sorted. -func UniqueIfAddrsBy(selectorName string, inputIfAddrs IfAddrs) (IfAddrs, error) { - attrName := strings.ToLower(selectorName) - - ifs := make(IfAddrs, 0, len(inputIfAddrs)) - var lastMatch string - for _, ifAddr := range inputIfAddrs { - var out string - switch attrName { - case "address": - out = ifAddr.SockAddr.String() - case "name": - out = ifAddr.Name - default: - return nil, fmt.Errorf("unsupported unique constraint %+q", selectorName) - } - - switch { - case lastMatch == "", lastMatch != out: - lastMatch = out - ifs = append(ifs, ifAddr) - case lastMatch == out: - continue - } - } - - return ifs, nil -} - -// JoinIfAddrs joins an IfAddrs and returns a string -func JoinIfAddrs(selectorName string, joinStr string, inputIfAddrs IfAddrs) (string, error) { - outputs := make([]string, 0, len(inputIfAddrs)) - attrName := AttrName(strings.ToLower(selectorName)) - - for _, ifAddr := range inputIfAddrs { - var attrVal string - var err error - attrVal, err = ifAddr.Attr(attrName) - if err != nil { - return "", err - } - outputs = append(outputs, attrVal) - } - return strings.Join(outputs, joinStr), nil -} - -// LimitIfAddrs returns a slice of IfAddrs based on the specified limit. -func LimitIfAddrs(lim uint, in IfAddrs) (IfAddrs, error) { - // Clamp the limit to the length of the array - if int(lim) > len(in) { - lim = uint(len(in)) - } - - return in[0:lim], nil -} - -// OffsetIfAddrs returns a slice of IfAddrs based on the specified offset. -func OffsetIfAddrs(off int, in IfAddrs) (IfAddrs, error) { - var end bool - if off < 0 { - end = true - off = off * -1 - } - - if off > len(in) { - return IfAddrs{}, fmt.Errorf("unable to seek past the end of the interface array: offset (%d) exceeds the number of interfaces (%d)", off, len(in)) - } - - if end { - return in[len(in)-off:], nil - } - return in[off:], nil -} - -func (ifAddr IfAddr) String() string { - return fmt.Sprintf("%s %v", ifAddr.SockAddr, ifAddr.Interface) -} - -// parseDefaultIfNameFromRoute parses standard route(8)'s output for the *BSDs -// and Solaris. -func parseDefaultIfNameFromRoute(routeOut string) (string, error) { - lines := strings.Split(routeOut, "\n") - for _, line := range lines { - kvs := strings.SplitN(line, ":", 2) - if len(kvs) != 2 { - continue - } - - if strings.TrimSpace(kvs[0]) == "interface" { - ifName := strings.TrimSpace(kvs[1]) - return ifName, nil - } - } - - return "", errors.New("No default interface found") -} - -// parseDefaultIfNameFromIPCmd parses the default interface from ip(8) for -// Linux. -func parseDefaultIfNameFromIPCmd(routeOut string) (string, error) { - lines := strings.Split(routeOut, "\n") - re := whitespaceRE.Copy() - for _, line := range lines { - kvs := re.Split(line, -1) - if len(kvs) < 5 { - continue - } - - if kvs[0] == "default" && - kvs[1] == "via" && - kvs[3] == "dev" { - ifName := strings.TrimSpace(kvs[4]) - return ifName, nil - } - } - - return "", errors.New("No default interface found") -} - -// parseDefaultIfNameWindows parses the default interface from `netstat -rn` and -// `ipconfig` on Windows. -func parseDefaultIfNameWindows(routeOut, ipconfigOut string) (string, error) { - defaultIPAddr, err := parseDefaultIPAddrWindowsRoute(routeOut) - if err != nil { - return "", err - } - - ifName, err := parseDefaultIfNameWindowsIPConfig(defaultIPAddr, ipconfigOut) - if err != nil { - return "", err - } - - return ifName, nil -} - -// parseDefaultIPAddrWindowsRoute parses the IP address on the default interface -// `netstat -rn`. -// -// NOTES(sean): Only IPv4 addresses are parsed at this time. If you have an -// IPv6 connected host, submit an issue on github.com/hashicorp/go-sockaddr with -// the output from `netstat -rn`, `ipconfig`, and version of Windows to see IPv6 -// support added. -func parseDefaultIPAddrWindowsRoute(routeOut string) (string, error) { - lines := strings.Split(routeOut, "\n") - re := whitespaceRE.Copy() - for _, line := range lines { - kvs := re.Split(strings.TrimSpace(line), -1) - if len(kvs) < 3 { - continue - } - - if kvs[0] == "0.0.0.0" && kvs[1] == "0.0.0.0" { - defaultIPAddr := strings.TrimSpace(kvs[3]) - return defaultIPAddr, nil - } - } - - return "", errors.New("No IP on default interface found") -} - -// parseDefaultIfNameWindowsIPConfig parses the output of `ipconfig` to find the -// interface name forwarding traffic to the default gateway. -func parseDefaultIfNameWindowsIPConfig(defaultIPAddr, routeOut string) (string, error) { - lines := strings.Split(routeOut, "\n") - ifNameRe := ifNameRE.Copy() - ipAddrRe := ipAddrRE.Copy() - var ifName string - for _, line := range lines { - switch ifNameMatches := ifNameRe.FindStringSubmatch(line); { - case len(ifNameMatches) > 1: - ifName = ifNameMatches[1] - continue - } - - switch ipAddrMatches := ipAddrRe.FindStringSubmatch(line); { - case len(ipAddrMatches) > 1 && ipAddrMatches[1] == defaultIPAddr: - return ifName, nil - } - } - - return "", errors.New("No default interface found with matching IP") -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/ifattr.go b/vendor/github.com/hashicorp/go-sockaddr/ifattr.go deleted file mode 100644 index 6984cb4..0000000 --- a/vendor/github.com/hashicorp/go-sockaddr/ifattr.go +++ /dev/null @@ -1,65 +0,0 @@ -package sockaddr - -import ( - "fmt" - "net" -) - -// IfAddr is a union of a SockAddr and a net.Interface. -type IfAddr struct { - SockAddr - net.Interface -} - -// Attr returns the named attribute as a string -func (ifAddr IfAddr) Attr(attrName AttrName) (string, error) { - val := IfAddrAttr(ifAddr, attrName) - if val != "" { - return val, nil - } - - return Attr(ifAddr.SockAddr, attrName) -} - -// Attr returns the named attribute as a string -func Attr(sa SockAddr, attrName AttrName) (string, error) { - switch sockType := sa.Type(); { - case sockType&TypeIP != 0: - ip := *ToIPAddr(sa) - attrVal := IPAddrAttr(ip, attrName) - if attrVal != "" { - return attrVal, nil - } - - if sockType == TypeIPv4 { - ipv4 := *ToIPv4Addr(sa) - attrVal := IPv4AddrAttr(ipv4, attrName) - if attrVal != "" { - return attrVal, nil - } - } else if sockType == TypeIPv6 { - ipv6 := *ToIPv6Addr(sa) - attrVal := IPv6AddrAttr(ipv6, attrName) - if attrVal != "" { - return attrVal, nil - } - } - - case sockType == TypeUnix: - us := *ToUnixSock(sa) - attrVal := UnixSockAttr(us, attrName) - if attrVal != "" { - return attrVal, nil - } - } - - // Non type-specific attributes - switch attrName { - case "string": - return sa.String(), nil - case "type": - return sa.Type().String(), nil - } - - return "", fmt.Errorf("unsupported attribute name %q", attrName) -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/ipaddr.go b/vendor/github.com/hashicorp/go-sockaddr/ipaddr.go deleted file mode 100644 index b47d15c..0000000 --- a/vendor/github.com/hashicorp/go-sockaddr/ipaddr.go +++ /dev/null @@ -1,169 +0,0 @@ -package sockaddr - -import ( - "fmt" - "math/big" - "net" - "strings" -) - -// Constants for the sizes of IPv3, IPv4, and IPv6 address types. -const ( - IPv3len = 6 - IPv4len = 4 - IPv6len = 16 -) - -// IPAddr is a generic IP address interface for IPv4 and IPv6 addresses, -// networks, and socket endpoints. -type IPAddr interface { - SockAddr - AddressBinString() string - AddressHexString() string - Cmp(SockAddr) int - CmpAddress(SockAddr) int - CmpPort(SockAddr) int - FirstUsable() IPAddr - Host() IPAddr - IPPort() IPPort - LastUsable() IPAddr - Maskbits() int - NetIP() *net.IP - NetIPMask() *net.IPMask - NetIPNet() *net.IPNet - Network() IPAddr - Octets() []int -} - -// IPPort is the type for an IP port number for the TCP and UDP IP transports. -type IPPort uint16 - -// IPPrefixLen is a typed integer representing the prefix length for a given -// IPAddr. -type IPPrefixLen byte - -// ipAddrAttrMap is a map of the IPAddr type-specific attributes. -var ipAddrAttrMap map[AttrName]func(IPAddr) string -var ipAddrAttrs []AttrName - -func init() { - ipAddrInit() -} - -// NewIPAddr creates a new IPAddr from a string. Returns nil if the string is -// not an IPv4 or an IPv6 address. -func NewIPAddr(addr string) (IPAddr, error) { - ipv4Addr, err := NewIPv4Addr(addr) - if err == nil { - return ipv4Addr, nil - } - - ipv6Addr, err := NewIPv6Addr(addr) - if err == nil { - return ipv6Addr, nil - } - - return nil, fmt.Errorf("invalid IPAddr %v", addr) -} - -// IPAddrAttr returns a string representation of an attribute for the given -// IPAddr. -func IPAddrAttr(ip IPAddr, selector AttrName) string { - fn, found := ipAddrAttrMap[selector] - if !found { - return "" - } - - return fn(ip) -} - -// IPAttrs returns a list of attributes supported by the IPAddr type -func IPAttrs() []AttrName { - return ipAddrAttrs -} - -// MustIPAddr is a helper method that must return an IPAddr or panic on invalid -// input. -func MustIPAddr(addr string) IPAddr { - ip, err := NewIPAddr(addr) - if err != nil { - panic(fmt.Sprintf("Unable to create an IPAddr from %+q: %v", addr, err)) - } - return ip -} - -// ipAddrInit is called once at init() -func ipAddrInit() { - // Sorted for human readability - ipAddrAttrs = []AttrName{ - "host", - "address", - "port", - "netmask", - "network", - "mask_bits", - "binary", - "hex", - "first_usable", - "last_usable", - "octets", - } - - ipAddrAttrMap = map[AttrName]func(ip IPAddr) string{ - "address": func(ip IPAddr) string { - return ip.NetIP().String() - }, - "binary": func(ip IPAddr) string { - return ip.AddressBinString() - }, - "first_usable": func(ip IPAddr) string { - return ip.FirstUsable().String() - }, - "hex": func(ip IPAddr) string { - return ip.AddressHexString() - }, - "host": func(ip IPAddr) string { - return ip.Host().String() - }, - "last_usable": func(ip IPAddr) string { - return ip.LastUsable().String() - }, - "mask_bits": func(ip IPAddr) string { - return fmt.Sprintf("%d", ip.Maskbits()) - }, - "netmask": func(ip IPAddr) string { - switch v := ip.(type) { - case IPv4Addr: - ipv4Mask := IPv4Addr{ - Address: IPv4Address(v.Mask), - Mask: IPv4HostMask, - } - return ipv4Mask.String() - case IPv6Addr: - ipv6Mask := new(big.Int) - ipv6Mask.Set(v.Mask) - ipv6MaskAddr := IPv6Addr{ - Address: IPv6Address(ipv6Mask), - Mask: ipv6HostMask, - } - return ipv6MaskAddr.String() - default: - return fmt.Sprintf("", ip) - } - }, - "network": func(ip IPAddr) string { - return ip.Network().NetIP().String() - }, - "octets": func(ip IPAddr) string { - octets := ip.Octets() - octetStrs := make([]string, 0, len(octets)) - for _, octet := range octets { - octetStrs = append(octetStrs, fmt.Sprintf("%d", octet)) - } - return strings.Join(octetStrs, " ") - }, - "port": func(ip IPAddr) string { - return fmt.Sprintf("%d", ip.IPPort()) - }, - } -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/ipaddrs.go b/vendor/github.com/hashicorp/go-sockaddr/ipaddrs.go deleted file mode 100644 index 6eeb7dd..0000000 --- a/vendor/github.com/hashicorp/go-sockaddr/ipaddrs.go +++ /dev/null @@ -1,98 +0,0 @@ -package sockaddr - -import "bytes" - -type IPAddrs []IPAddr - -func (s IPAddrs) Len() int { return len(s) } -func (s IPAddrs) Swap(i, j int) { s[i], s[j] = s[j], s[i] } - -// // SortIPAddrsByCmp is a type that satisfies sort.Interface and can be used -// // by the routines in this package. The SortIPAddrsByCmp type is used to -// // sort IPAddrs by Cmp() -// type SortIPAddrsByCmp struct{ IPAddrs } - -// // Less reports whether the element with index i should sort before the -// // element with index j. -// func (s SortIPAddrsByCmp) Less(i, j int) bool { -// // Sort by Type, then address, then port number. -// return Less(s.IPAddrs[i], s.IPAddrs[j]) -// } - -// SortIPAddrsBySpecificMaskLen is a type that satisfies sort.Interface and -// can be used by the routines in this package. The -// SortIPAddrsBySpecificMaskLen type is used to sort IPAddrs by smallest -// network (most specific to largest network). -type SortIPAddrsByNetworkSize struct{ IPAddrs } - -// Less reports whether the element with index i should sort before the -// element with index j. -func (s SortIPAddrsByNetworkSize) Less(i, j int) bool { - // Sort masks with a larger binary value (i.e. fewer hosts per network - // prefix) after masks with a smaller value (larger number of hosts per - // prefix). - switch bytes.Compare([]byte(*s.IPAddrs[i].NetIPMask()), []byte(*s.IPAddrs[j].NetIPMask())) { - case 0: - // Fall through to the second test if the net.IPMasks are the - // same. - break - case 1: - return true - case -1: - return false - default: - panic("bad, m'kay?") - } - - // Sort IPs based on the length (i.e. prefer IPv4 over IPv6). - iLen := len(*s.IPAddrs[i].NetIP()) - jLen := len(*s.IPAddrs[j].NetIP()) - if iLen != jLen { - return iLen > jLen - } - - // Sort IPs based on their network address from lowest to highest. - switch bytes.Compare(s.IPAddrs[i].NetIPNet().IP, s.IPAddrs[j].NetIPNet().IP) { - case 0: - break - case 1: - return false - case -1: - return true - default: - panic("lol wut?") - } - - // If a host does not have a port set, it always sorts after hosts - // that have a port (e.g. a host with a /32 and port number is more - // specific and should sort first over a host with a /32 but no port - // set). - if s.IPAddrs[i].IPPort() == 0 || s.IPAddrs[j].IPPort() == 0 { - return false - } - return s.IPAddrs[i].IPPort() < s.IPAddrs[j].IPPort() -} - -// SortIPAddrsBySpecificMaskLen is a type that satisfies sort.Interface and -// can be used by the routines in this package. The -// SortIPAddrsBySpecificMaskLen type is used to sort IPAddrs by smallest -// network (most specific to largest network). -type SortIPAddrsBySpecificMaskLen struct{ IPAddrs } - -// Less reports whether the element with index i should sort before the -// element with index j. -func (s SortIPAddrsBySpecificMaskLen) Less(i, j int) bool { - return s.IPAddrs[i].Maskbits() > s.IPAddrs[j].Maskbits() -} - -// SortIPAddrsByBroadMaskLen is a type that satisfies sort.Interface and can -// be used by the routines in this package. The SortIPAddrsByBroadMaskLen -// type is used to sort IPAddrs by largest network (i.e. largest subnets -// first). -type SortIPAddrsByBroadMaskLen struct{ IPAddrs } - -// Less reports whether the element with index i should sort before the -// element with index j. -func (s SortIPAddrsByBroadMaskLen) Less(i, j int) bool { - return s.IPAddrs[i].Maskbits() < s.IPAddrs[j].Maskbits() -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/ipv4addr.go b/vendor/github.com/hashicorp/go-sockaddr/ipv4addr.go deleted file mode 100644 index 4d395dc..0000000 --- a/vendor/github.com/hashicorp/go-sockaddr/ipv4addr.go +++ /dev/null @@ -1,516 +0,0 @@ -package sockaddr - -import ( - "encoding/binary" - "fmt" - "net" - "regexp" - "strconv" - "strings" -) - -type ( - // IPv4Address is a named type representing an IPv4 address. - IPv4Address uint32 - - // IPv4Network is a named type representing an IPv4 network. - IPv4Network uint32 - - // IPv4Mask is a named type representing an IPv4 network mask. - IPv4Mask uint32 -) - -// IPv4HostMask is a constant represents a /32 IPv4 Address -// (i.e. 255.255.255.255). -const IPv4HostMask = IPv4Mask(0xffffffff) - -// ipv4AddrAttrMap is a map of the IPv4Addr type-specific attributes. -var ipv4AddrAttrMap map[AttrName]func(IPv4Addr) string -var ipv4AddrAttrs []AttrName -var trailingHexNetmaskRE *regexp.Regexp - -// IPv4Addr implements a convenience wrapper around the union of Go's -// built-in net.IP and net.IPNet types. In UNIX-speak, IPv4Addr implements -// `sockaddr` when the the address family is set to AF_INET -// (i.e. `sockaddr_in`). -type IPv4Addr struct { - IPAddr - Address IPv4Address - Mask IPv4Mask - Port IPPort -} - -func init() { - ipv4AddrInit() - trailingHexNetmaskRE = regexp.MustCompile(`/([0f]{8})$`) -} - -// NewIPv4Addr creates an IPv4Addr from a string. String can be in the form -// of either an IPv4:port (e.g. `1.2.3.4:80`, in which case the mask is -// assumed to be a `/32`), an IPv4 address (e.g. `1.2.3.4`, also with a `/32` -// mask), or an IPv4 CIDR (e.g. `1.2.3.4/24`, which has its IP port -// initialized to zero). ipv4Str can not be a hostname. -// -// NOTE: Many net.*() routines will initialize and return an IPv6 address. -// To create uint32 values from net.IP, always test to make sure the address -// returned can be converted to a 4 byte array using To4(). -func NewIPv4Addr(ipv4Str string) (IPv4Addr, error) { - // Strip off any bogus hex-encoded netmasks that will be mis-parsed by Go. In - // particular, clients with the Barracuda VPN client will see something like: - // `192.168.3.51/00ffffff` as their IP address. - trailingHexNetmaskRe := trailingHexNetmaskRE.Copy() - if match := trailingHexNetmaskRe.FindStringIndex(ipv4Str); match != nil { - ipv4Str = ipv4Str[:match[0]] - } - - // Parse as an IPv4 CIDR - ipAddr, network, err := net.ParseCIDR(ipv4Str) - if err == nil { - ipv4 := ipAddr.To4() - if ipv4 == nil { - return IPv4Addr{}, fmt.Errorf("Unable to convert %s to an IPv4 address", ipv4Str) - } - - // If we see an IPv6 netmask, convert it to an IPv4 mask. - netmaskSepPos := strings.LastIndexByte(ipv4Str, '/') - if netmaskSepPos != -1 && netmaskSepPos+1 < len(ipv4Str) { - netMask, err := strconv.ParseUint(ipv4Str[netmaskSepPos+1:], 10, 8) - if err != nil { - return IPv4Addr{}, fmt.Errorf("Unable to convert %s to an IPv4 address: unable to parse CIDR netmask: %v", ipv4Str, err) - } else if netMask > 128 { - return IPv4Addr{}, fmt.Errorf("Unable to convert %s to an IPv4 address: invalid CIDR netmask", ipv4Str) - } - - if netMask >= 96 { - // Convert the IPv6 netmask to an IPv4 netmask - network.Mask = net.CIDRMask(int(netMask-96), IPv4len*8) - } - } - ipv4Addr := IPv4Addr{ - Address: IPv4Address(binary.BigEndian.Uint32(ipv4)), - Mask: IPv4Mask(binary.BigEndian.Uint32(network.Mask)), - } - return ipv4Addr, nil - } - - // Attempt to parse ipv4Str as a /32 host with a port number. - tcpAddr, err := net.ResolveTCPAddr("tcp4", ipv4Str) - if err == nil { - ipv4 := tcpAddr.IP.To4() - if ipv4 == nil { - return IPv4Addr{}, fmt.Errorf("Unable to resolve %+q as an IPv4 address", ipv4Str) - } - - ipv4Uint32 := binary.BigEndian.Uint32(ipv4) - ipv4Addr := IPv4Addr{ - Address: IPv4Address(ipv4Uint32), - Mask: IPv4HostMask, - Port: IPPort(tcpAddr.Port), - } - - return ipv4Addr, nil - } - - // Parse as a naked IPv4 address - ip := net.ParseIP(ipv4Str) - if ip != nil { - ipv4 := ip.To4() - if ipv4 == nil { - return IPv4Addr{}, fmt.Errorf("Unable to string convert %+q to an IPv4 address", ipv4Str) - } - - ipv4Uint32 := binary.BigEndian.Uint32(ipv4) - ipv4Addr := IPv4Addr{ - Address: IPv4Address(ipv4Uint32), - Mask: IPv4HostMask, - } - return ipv4Addr, nil - } - - return IPv4Addr{}, fmt.Errorf("Unable to parse %+q to an IPv4 address: %v", ipv4Str, err) -} - -// AddressBinString returns a string with the IPv4Addr's Address represented -// as a sequence of '0' and '1' characters. This method is useful for -// debugging or by operators who want to inspect an address. -func (ipv4 IPv4Addr) AddressBinString() string { - return fmt.Sprintf("%032s", strconv.FormatUint(uint64(ipv4.Address), 2)) -} - -// AddressHexString returns a string with the IPv4Addr address represented as -// a sequence of hex characters. This method is useful for debugging or by -// operators who want to inspect an address. -func (ipv4 IPv4Addr) AddressHexString() string { - return fmt.Sprintf("%08s", strconv.FormatUint(uint64(ipv4.Address), 16)) -} - -// Broadcast is an IPv4Addr-only method that returns the broadcast address of -// the network. -// -// NOTE: IPv6 only supports multicast, so this method only exists for -// IPv4Addr. -func (ipv4 IPv4Addr) Broadcast() IPAddr { - // Nothing should listen on a broadcast address. - return IPv4Addr{ - Address: IPv4Address(ipv4.BroadcastAddress()), - Mask: IPv4HostMask, - } -} - -// BroadcastAddress returns a IPv4Network of the IPv4Addr's broadcast -// address. -func (ipv4 IPv4Addr) BroadcastAddress() IPv4Network { - return IPv4Network(uint32(ipv4.Address)&uint32(ipv4.Mask) | ^uint32(ipv4.Mask)) -} - -// CmpAddress follows the Cmp() standard protocol and returns: -// -// - -1 If the receiver should sort first because its address is lower than arg -// - 0 if the SockAddr arg is equal to the receiving IPv4Addr or the argument is -// of a different type. -// - 1 If the argument should sort first. -func (ipv4 IPv4Addr) CmpAddress(sa SockAddr) int { - ipv4b, ok := sa.(IPv4Addr) - if !ok { - return sortDeferDecision - } - - switch { - case ipv4.Address == ipv4b.Address: - return sortDeferDecision - case ipv4.Address < ipv4b.Address: - return sortReceiverBeforeArg - default: - return sortArgBeforeReceiver - } -} - -// CmpPort follows the Cmp() standard protocol and returns: -// -// - -1 If the receiver should sort first because its port is lower than arg -// - 0 if the SockAddr arg's port number is equal to the receiving IPv4Addr, -// regardless of type. -// - 1 If the argument should sort first. -func (ipv4 IPv4Addr) CmpPort(sa SockAddr) int { - var saPort IPPort - switch v := sa.(type) { - case IPv4Addr: - saPort = v.Port - case IPv6Addr: - saPort = v.Port - default: - return sortDeferDecision - } - - switch { - case ipv4.Port == saPort: - return sortDeferDecision - case ipv4.Port < saPort: - return sortReceiverBeforeArg - default: - return sortArgBeforeReceiver - } -} - -// CmpRFC follows the Cmp() standard protocol and returns: -// -// - -1 If the receiver should sort first because it belongs to the RFC and its -// arg does not -// - 0 if the receiver and arg both belong to the same RFC or neither do. -// - 1 If the arg belongs to the RFC but receiver does not. -func (ipv4 IPv4Addr) CmpRFC(rfcNum uint, sa SockAddr) int { - recvInRFC := IsRFC(rfcNum, ipv4) - ipv4b, ok := sa.(IPv4Addr) - if !ok { - // If the receiver is part of the desired RFC and the SockAddr - // argument is not, return -1 so that the receiver sorts before - // the non-IPv4 SockAddr. Conversely, if the receiver is not - // part of the RFC, punt on sorting and leave it for the next - // sorter. - if recvInRFC { - return sortReceiverBeforeArg - } else { - return sortDeferDecision - } - } - - argInRFC := IsRFC(rfcNum, ipv4b) - switch { - case (recvInRFC && argInRFC), (!recvInRFC && !argInRFC): - // If a and b both belong to the RFC, or neither belong to - // rfcNum, defer sorting to the next sorter. - return sortDeferDecision - case recvInRFC && !argInRFC: - return sortReceiverBeforeArg - default: - return sortArgBeforeReceiver - } -} - -// Contains returns true if the SockAddr is contained within the receiver. -func (ipv4 IPv4Addr) Contains(sa SockAddr) bool { - ipv4b, ok := sa.(IPv4Addr) - if !ok { - return false - } - - return ipv4.ContainsNetwork(ipv4b) -} - -// ContainsAddress returns true if the IPv4Address is contained within the -// receiver. -func (ipv4 IPv4Addr) ContainsAddress(x IPv4Address) bool { - return IPv4Address(ipv4.NetworkAddress()) <= x && - IPv4Address(ipv4.BroadcastAddress()) >= x -} - -// ContainsNetwork returns true if the network from IPv4Addr is contained -// within the receiver. -func (ipv4 IPv4Addr) ContainsNetwork(x IPv4Addr) bool { - return ipv4.NetworkAddress() <= x.NetworkAddress() && - ipv4.BroadcastAddress() >= x.BroadcastAddress() -} - -// DialPacketArgs returns the arguments required to be passed to -// net.DialUDP(). If the Mask of ipv4 is not a /32 or the Port is 0, -// DialPacketArgs() will fail. See Host() to create an IPv4Addr with its -// mask set to /32. -func (ipv4 IPv4Addr) DialPacketArgs() (network, dialArgs string) { - if ipv4.Mask != IPv4HostMask || ipv4.Port == 0 { - return "udp4", "" - } - return "udp4", fmt.Sprintf("%s:%d", ipv4.NetIP().String(), ipv4.Port) -} - -// DialStreamArgs returns the arguments required to be passed to -// net.DialTCP(). If the Mask of ipv4 is not a /32 or the Port is 0, -// DialStreamArgs() will fail. See Host() to create an IPv4Addr with its -// mask set to /32. -func (ipv4 IPv4Addr) DialStreamArgs() (network, dialArgs string) { - if ipv4.Mask != IPv4HostMask || ipv4.Port == 0 { - return "tcp4", "" - } - return "tcp4", fmt.Sprintf("%s:%d", ipv4.NetIP().String(), ipv4.Port) -} - -// Equal returns true if a SockAddr is equal to the receiving IPv4Addr. -func (ipv4 IPv4Addr) Equal(sa SockAddr) bool { - ipv4b, ok := sa.(IPv4Addr) - if !ok { - return false - } - - if ipv4.Port != ipv4b.Port { - return false - } - - if ipv4.Address != ipv4b.Address { - return false - } - - if ipv4.NetIPNet().String() != ipv4b.NetIPNet().String() { - return false - } - - return true -} - -// FirstUsable returns an IPv4Addr set to the first address following the -// network prefix. The first usable address in a network is normally the -// gateway and should not be used except by devices forwarding packets -// between two administratively distinct networks (i.e. a router). This -// function does not discriminate against first usable vs "first address that -// should be used." For example, FirstUsable() on "192.168.1.10/24" would -// return the address "192.168.1.1/24". -func (ipv4 IPv4Addr) FirstUsable() IPAddr { - addr := ipv4.NetworkAddress() - - // If /32, return the address itself. If /31 assume a point-to-point - // link and return the lower address. - if ipv4.Maskbits() < 31 { - addr++ - } - - return IPv4Addr{ - Address: IPv4Address(addr), - Mask: IPv4HostMask, - } -} - -// Host returns a copy of ipv4 with its mask set to /32 so that it can be -// used by DialPacketArgs(), DialStreamArgs(), ListenPacketArgs(), or -// ListenStreamArgs(). -func (ipv4 IPv4Addr) Host() IPAddr { - // Nothing should listen on a broadcast address. - return IPv4Addr{ - Address: ipv4.Address, - Mask: IPv4HostMask, - Port: ipv4.Port, - } -} - -// IPPort returns the Port number attached to the IPv4Addr -func (ipv4 IPv4Addr) IPPort() IPPort { - return ipv4.Port -} - -// LastUsable returns the last address before the broadcast address in a -// given network. -func (ipv4 IPv4Addr) LastUsable() IPAddr { - addr := ipv4.BroadcastAddress() - - // If /32, return the address itself. If /31 assume a point-to-point - // link and return the upper address. - if ipv4.Maskbits() < 31 { - addr-- - } - - return IPv4Addr{ - Address: IPv4Address(addr), - Mask: IPv4HostMask, - } -} - -// ListenPacketArgs returns the arguments required to be passed to -// net.ListenUDP(). If the Mask of ipv4 is not a /32, ListenPacketArgs() -// will fail. See Host() to create an IPv4Addr with its mask set to /32. -func (ipv4 IPv4Addr) ListenPacketArgs() (network, listenArgs string) { - if ipv4.Mask != IPv4HostMask { - return "udp4", "" - } - return "udp4", fmt.Sprintf("%s:%d", ipv4.NetIP().String(), ipv4.Port) -} - -// ListenStreamArgs returns the arguments required to be passed to -// net.ListenTCP(). If the Mask of ipv4 is not a /32, ListenStreamArgs() -// will fail. See Host() to create an IPv4Addr with its mask set to /32. -func (ipv4 IPv4Addr) ListenStreamArgs() (network, listenArgs string) { - if ipv4.Mask != IPv4HostMask { - return "tcp4", "" - } - return "tcp4", fmt.Sprintf("%s:%d", ipv4.NetIP().String(), ipv4.Port) -} - -// Maskbits returns the number of network mask bits in a given IPv4Addr. For -// example, the Maskbits() of "192.168.1.1/24" would return 24. -func (ipv4 IPv4Addr) Maskbits() int { - mask := make(net.IPMask, IPv4len) - binary.BigEndian.PutUint32(mask, uint32(ipv4.Mask)) - maskOnes, _ := mask.Size() - return maskOnes -} - -// MustIPv4Addr is a helper method that must return an IPv4Addr or panic on -// invalid input. -func MustIPv4Addr(addr string) IPv4Addr { - ipv4, err := NewIPv4Addr(addr) - if err != nil { - panic(fmt.Sprintf("Unable to create an IPv4Addr from %+q: %v", addr, err)) - } - return ipv4 -} - -// NetIP returns the address as a net.IP (address is always presized to -// IPv4). -func (ipv4 IPv4Addr) NetIP() *net.IP { - x := make(net.IP, IPv4len) - binary.BigEndian.PutUint32(x, uint32(ipv4.Address)) - return &x -} - -// NetIPMask create a new net.IPMask from the IPv4Addr. -func (ipv4 IPv4Addr) NetIPMask() *net.IPMask { - ipv4Mask := net.IPMask{} - ipv4Mask = make(net.IPMask, IPv4len) - binary.BigEndian.PutUint32(ipv4Mask, uint32(ipv4.Mask)) - return &ipv4Mask -} - -// NetIPNet create a new net.IPNet from the IPv4Addr. -func (ipv4 IPv4Addr) NetIPNet() *net.IPNet { - ipv4net := &net.IPNet{} - ipv4net.IP = make(net.IP, IPv4len) - binary.BigEndian.PutUint32(ipv4net.IP, uint32(ipv4.NetworkAddress())) - ipv4net.Mask = *ipv4.NetIPMask() - return ipv4net -} - -// Network returns the network prefix or network address for a given network. -func (ipv4 IPv4Addr) Network() IPAddr { - return IPv4Addr{ - Address: IPv4Address(ipv4.NetworkAddress()), - Mask: ipv4.Mask, - } -} - -// NetworkAddress returns an IPv4Network of the IPv4Addr's network address. -func (ipv4 IPv4Addr) NetworkAddress() IPv4Network { - return IPv4Network(uint32(ipv4.Address) & uint32(ipv4.Mask)) -} - -// Octets returns a slice of the four octets in an IPv4Addr's Address. The -// order of the bytes is big endian. -func (ipv4 IPv4Addr) Octets() []int { - return []int{ - int(ipv4.Address >> 24), - int((ipv4.Address >> 16) & 0xff), - int((ipv4.Address >> 8) & 0xff), - int(ipv4.Address & 0xff), - } -} - -// String returns a string representation of the IPv4Addr -func (ipv4 IPv4Addr) String() string { - if ipv4.Port != 0 { - return fmt.Sprintf("%s:%d", ipv4.NetIP().String(), ipv4.Port) - } - - if ipv4.Maskbits() == 32 { - return ipv4.NetIP().String() - } - - return fmt.Sprintf("%s/%d", ipv4.NetIP().String(), ipv4.Maskbits()) -} - -// Type is used as a type switch and returns TypeIPv4 -func (IPv4Addr) Type() SockAddrType { - return TypeIPv4 -} - -// IPv4AddrAttr returns a string representation of an attribute for the given -// IPv4Addr. -func IPv4AddrAttr(ipv4 IPv4Addr, selector AttrName) string { - fn, found := ipv4AddrAttrMap[selector] - if !found { - return "" - } - - return fn(ipv4) -} - -// IPv4Attrs returns a list of attributes supported by the IPv4Addr type -func IPv4Attrs() []AttrName { - return ipv4AddrAttrs -} - -// ipv4AddrInit is called once at init() -func ipv4AddrInit() { - // Sorted for human readability - ipv4AddrAttrs = []AttrName{ - "size", // Same position as in IPv6 for output consistency - "broadcast", - "uint32", - } - - ipv4AddrAttrMap = map[AttrName]func(ipv4 IPv4Addr) string{ - "broadcast": func(ipv4 IPv4Addr) string { - return ipv4.Broadcast().String() - }, - "size": func(ipv4 IPv4Addr) string { - return fmt.Sprintf("%d", 1< 2 && ipv6Str[0] == '[' && ipv6Str[len(ipv6Str)-1] == ']' { - ipv6Str = ipv6Str[1 : len(ipv6Str)-1] - } - ip := net.ParseIP(ipv6Str) - if ip != nil { - ipv6 := ip.To16() - if ipv6 == nil { - return IPv6Addr{}, fmt.Errorf("Unable to string convert %+q to a 16byte IPv6 address", ipv6Str) - } - - ipv6BigIntAddr := new(big.Int) - ipv6BigIntAddr.SetBytes(ipv6) - - ipv6BigIntMask := new(big.Int) - ipv6BigIntMask.Set(ipv6HostMask) - - return IPv6Addr{ - Address: IPv6Address(ipv6BigIntAddr), - Mask: IPv6Mask(ipv6BigIntMask), - }, nil - } - - // Parse as an IPv6 CIDR - ipAddr, network, err := net.ParseCIDR(ipv6Str) - if err == nil { - ipv6 := ipAddr.To16() - if ipv6 == nil { - return IPv6Addr{}, fmt.Errorf("Unable to convert %+q to a 16byte IPv6 address", ipv6Str) - } - - ipv6BigIntAddr := new(big.Int) - ipv6BigIntAddr.SetBytes(ipv6) - - ipv6BigIntMask := new(big.Int) - ipv6BigIntMask.SetBytes(network.Mask) - - ipv6Addr := IPv6Addr{ - Address: IPv6Address(ipv6BigIntAddr), - Mask: IPv6Mask(ipv6BigIntMask), - } - return ipv6Addr, nil - } - - return IPv6Addr{}, fmt.Errorf("Unable to parse %+q to an IPv6 address: %v", ipv6Str, err) -} - -// AddressBinString returns a string with the IPv6Addr's Address represented -// as a sequence of '0' and '1' characters. This method is useful for -// debugging or by operators who want to inspect an address. -func (ipv6 IPv6Addr) AddressBinString() string { - bi := big.Int(*ipv6.Address) - return fmt.Sprintf("%0128s", bi.Text(2)) -} - -// AddressHexString returns a string with the IPv6Addr address represented as -// a sequence of hex characters. This method is useful for debugging or by -// operators who want to inspect an address. -func (ipv6 IPv6Addr) AddressHexString() string { - bi := big.Int(*ipv6.Address) - return fmt.Sprintf("%032s", bi.Text(16)) -} - -// CmpAddress follows the Cmp() standard protocol and returns: -// -// - -1 If the receiver should sort first because its address is lower than arg -// - 0 if the SockAddr arg equal to the receiving IPv6Addr or the argument is of a -// different type. -// - 1 If the argument should sort first. -func (ipv6 IPv6Addr) CmpAddress(sa SockAddr) int { - ipv6b, ok := sa.(IPv6Addr) - if !ok { - return sortDeferDecision - } - - ipv6aBigInt := new(big.Int) - ipv6aBigInt.Set(ipv6.Address) - ipv6bBigInt := new(big.Int) - ipv6bBigInt.Set(ipv6b.Address) - - return ipv6aBigInt.Cmp(ipv6bBigInt) -} - -// CmpPort follows the Cmp() standard protocol and returns: -// -// - -1 If the receiver should sort first because its port is lower than arg -// - 0 if the SockAddr arg's port number is equal to the receiving IPv6Addr, -// regardless of type. -// - 1 If the argument should sort first. -func (ipv6 IPv6Addr) CmpPort(sa SockAddr) int { - var saPort IPPort - switch v := sa.(type) { - case IPv4Addr: - saPort = v.Port - case IPv6Addr: - saPort = v.Port - default: - return sortDeferDecision - } - - switch { - case ipv6.Port == saPort: - return sortDeferDecision - case ipv6.Port < saPort: - return sortReceiverBeforeArg - default: - return sortArgBeforeReceiver - } -} - -// CmpRFC follows the Cmp() standard protocol and returns: -// -// - -1 If the receiver should sort first because it belongs to the RFC and its -// arg does not -// - 0 if the receiver and arg both belong to the same RFC or neither do. -// - 1 If the arg belongs to the RFC but receiver does not. -func (ipv6 IPv6Addr) CmpRFC(rfcNum uint, sa SockAddr) int { - recvInRFC := IsRFC(rfcNum, ipv6) - ipv6b, ok := sa.(IPv6Addr) - if !ok { - // If the receiver is part of the desired RFC and the SockAddr - // argument is not, sort receiver before the non-IPv6 SockAddr. - // Conversely, if the receiver is not part of the RFC, punt on - // sorting and leave it for the next sorter. - if recvInRFC { - return sortReceiverBeforeArg - } else { - return sortDeferDecision - } - } - - argInRFC := IsRFC(rfcNum, ipv6b) - switch { - case (recvInRFC && argInRFC), (!recvInRFC && !argInRFC): - // If a and b both belong to the RFC, or neither belong to - // rfcNum, defer sorting to the next sorter. - return sortDeferDecision - case recvInRFC && !argInRFC: - return sortReceiverBeforeArg - default: - return sortArgBeforeReceiver - } -} - -// Contains returns true if the SockAddr is contained within the receiver. -func (ipv6 IPv6Addr) Contains(sa SockAddr) bool { - ipv6b, ok := sa.(IPv6Addr) - if !ok { - return false - } - - return ipv6.ContainsNetwork(ipv6b) -} - -// ContainsAddress returns true if the IPv6Address is contained within the -// receiver. -func (ipv6 IPv6Addr) ContainsAddress(x IPv6Address) bool { - xAddr := IPv6Addr{ - Address: x, - Mask: ipv6HostMask, - } - - { - xIPv6 := xAddr.FirstUsable().(IPv6Addr) - yIPv6 := ipv6.FirstUsable().(IPv6Addr) - if xIPv6.CmpAddress(yIPv6) >= 1 { - return false - } - } - - { - xIPv6 := xAddr.LastUsable().(IPv6Addr) - yIPv6 := ipv6.LastUsable().(IPv6Addr) - if xIPv6.CmpAddress(yIPv6) <= -1 { - return false - } - } - return true -} - -// ContainsNetwork returns true if the network from IPv6Addr is contained within -// the receiver. -func (x IPv6Addr) ContainsNetwork(y IPv6Addr) bool { - { - xIPv6 := x.FirstUsable().(IPv6Addr) - yIPv6 := y.FirstUsable().(IPv6Addr) - if ret := xIPv6.CmpAddress(yIPv6); ret >= 1 { - return false - } - } - - { - xIPv6 := x.LastUsable().(IPv6Addr) - yIPv6 := y.LastUsable().(IPv6Addr) - if ret := xIPv6.CmpAddress(yIPv6); ret <= -1 { - return false - } - } - return true -} - -// DialPacketArgs returns the arguments required to be passed to -// net.DialUDP(). If the Mask of ipv6 is not a /128 or the Port is 0, -// DialPacketArgs() will fail. See Host() to create an IPv6Addr with its -// mask set to /128. -func (ipv6 IPv6Addr) DialPacketArgs() (network, dialArgs string) { - ipv6Mask := big.Int(*ipv6.Mask) - if ipv6Mask.Cmp(ipv6HostMask) != 0 || ipv6.Port == 0 { - return "udp6", "" - } - return "udp6", fmt.Sprintf("[%s]:%d", ipv6.NetIP().String(), ipv6.Port) -} - -// DialStreamArgs returns the arguments required to be passed to -// net.DialTCP(). If the Mask of ipv6 is not a /128 or the Port is 0, -// DialStreamArgs() will fail. See Host() to create an IPv6Addr with its -// mask set to /128. -func (ipv6 IPv6Addr) DialStreamArgs() (network, dialArgs string) { - ipv6Mask := big.Int(*ipv6.Mask) - if ipv6Mask.Cmp(ipv6HostMask) != 0 || ipv6.Port == 0 { - return "tcp6", "" - } - return "tcp6", fmt.Sprintf("[%s]:%d", ipv6.NetIP().String(), ipv6.Port) -} - -// Equal returns true if a SockAddr is equal to the receiving IPv4Addr. -func (ipv6a IPv6Addr) Equal(sa SockAddr) bool { - ipv6b, ok := sa.(IPv6Addr) - if !ok { - return false - } - - if ipv6a.NetIP().String() != ipv6b.NetIP().String() { - return false - } - - if ipv6a.NetIPNet().String() != ipv6b.NetIPNet().String() { - return false - } - - if ipv6a.Port != ipv6b.Port { - return false - } - - return true -} - -// FirstUsable returns an IPv6Addr set to the first address following the -// network prefix. The first usable address in a network is normally the -// gateway and should not be used except by devices forwarding packets -// between two administratively distinct networks (i.e. a router). This -// function does not discriminate against first usable vs "first address that -// should be used." For example, FirstUsable() on "2001:0db8::0003/64" would -// return "2001:0db8::00011". -func (ipv6 IPv6Addr) FirstUsable() IPAddr { - return IPv6Addr{ - Address: IPv6Address(ipv6.NetworkAddress()), - Mask: ipv6HostMask, - } -} - -// Host returns a copy of ipv6 with its mask set to /128 so that it can be -// used by DialPacketArgs(), DialStreamArgs(), ListenPacketArgs(), or -// ListenStreamArgs(). -func (ipv6 IPv6Addr) Host() IPAddr { - // Nothing should listen on a broadcast address. - return IPv6Addr{ - Address: ipv6.Address, - Mask: ipv6HostMask, - Port: ipv6.Port, - } -} - -// IPPort returns the Port number attached to the IPv6Addr -func (ipv6 IPv6Addr) IPPort() IPPort { - return ipv6.Port -} - -// LastUsable returns the last address in a given network. -func (ipv6 IPv6Addr) LastUsable() IPAddr { - addr := new(big.Int) - addr.Set(ipv6.Address) - - mask := new(big.Int) - mask.Set(ipv6.Mask) - - negMask := new(big.Int) - negMask.Xor(ipv6HostMask, mask) - - lastAddr := new(big.Int) - lastAddr.And(addr, mask) - lastAddr.Or(lastAddr, negMask) - - return IPv6Addr{ - Address: IPv6Address(lastAddr), - Mask: ipv6HostMask, - } -} - -// ListenPacketArgs returns the arguments required to be passed to -// net.ListenUDP(). If the Mask of ipv6 is not a /128, ListenPacketArgs() -// will fail. See Host() to create an IPv6Addr with its mask set to /128. -func (ipv6 IPv6Addr) ListenPacketArgs() (network, listenArgs string) { - ipv6Mask := big.Int(*ipv6.Mask) - if ipv6Mask.Cmp(ipv6HostMask) != 0 { - return "udp6", "" - } - return "udp6", fmt.Sprintf("[%s]:%d", ipv6.NetIP().String(), ipv6.Port) -} - -// ListenStreamArgs returns the arguments required to be passed to -// net.ListenTCP(). If the Mask of ipv6 is not a /128, ListenStreamArgs() -// will fail. See Host() to create an IPv6Addr with its mask set to /128. -func (ipv6 IPv6Addr) ListenStreamArgs() (network, listenArgs string) { - ipv6Mask := big.Int(*ipv6.Mask) - if ipv6Mask.Cmp(ipv6HostMask) != 0 { - return "tcp6", "" - } - return "tcp6", fmt.Sprintf("[%s]:%d", ipv6.NetIP().String(), ipv6.Port) -} - -// Maskbits returns the number of network mask bits in a given IPv6Addr. For -// example, the Maskbits() of "2001:0db8::0003/64" would return 64. -func (ipv6 IPv6Addr) Maskbits() int { - maskOnes, _ := ipv6.NetIPNet().Mask.Size() - - return maskOnes -} - -// MustIPv6Addr is a helper method that must return an IPv6Addr or panic on -// invalid input. -func MustIPv6Addr(addr string) IPv6Addr { - ipv6, err := NewIPv6Addr(addr) - if err != nil { - panic(fmt.Sprintf("Unable to create an IPv6Addr from %+q: %v", addr, err)) - } - return ipv6 -} - -// NetIP returns the address as a net.IP. -func (ipv6 IPv6Addr) NetIP() *net.IP { - return bigIntToNetIPv6(ipv6.Address) -} - -// NetIPMask create a new net.IPMask from the IPv6Addr. -func (ipv6 IPv6Addr) NetIPMask() *net.IPMask { - ipv6Mask := make(net.IPMask, IPv6len) - m := big.Int(*ipv6.Mask) - copy(ipv6Mask, m.Bytes()) - return &ipv6Mask -} - -// Network returns a pointer to the net.IPNet within IPv4Addr receiver. -func (ipv6 IPv6Addr) NetIPNet() *net.IPNet { - ipv6net := &net.IPNet{} - ipv6net.IP = make(net.IP, IPv6len) - copy(ipv6net.IP, *ipv6.NetIP()) - ipv6net.Mask = *ipv6.NetIPMask() - return ipv6net -} - -// Network returns the network prefix or network address for a given network. -func (ipv6 IPv6Addr) Network() IPAddr { - return IPv6Addr{ - Address: IPv6Address(ipv6.NetworkAddress()), - Mask: ipv6.Mask, - } -} - -// NetworkAddress returns an IPv6Network of the IPv6Addr's network address. -func (ipv6 IPv6Addr) NetworkAddress() IPv6Network { - addr := new(big.Int) - addr.SetBytes((*ipv6.Address).Bytes()) - - mask := new(big.Int) - mask.SetBytes(*ipv6.NetIPMask()) - - netAddr := new(big.Int) - netAddr.And(addr, mask) - - return IPv6Network(netAddr) -} - -// Octets returns a slice of the 16 octets in an IPv6Addr's Address. The -// order of the bytes is big endian. -func (ipv6 IPv6Addr) Octets() []int { - x := make([]int, IPv6len) - for i, b := range *bigIntToNetIPv6(ipv6.Address) { - x[i] = int(b) - } - - return x -} - -// String returns a string representation of the IPv6Addr -func (ipv6 IPv6Addr) String() string { - if ipv6.Port != 0 { - return fmt.Sprintf("[%s]:%d", ipv6.NetIP().String(), ipv6.Port) - } - - if ipv6.Maskbits() == 128 { - return ipv6.NetIP().String() - } - - return fmt.Sprintf("%s/%d", ipv6.NetIP().String(), ipv6.Maskbits()) -} - -// Type is used as a type switch and returns TypeIPv6 -func (IPv6Addr) Type() SockAddrType { - return TypeIPv6 -} - -// IPv6Attrs returns a list of attributes supported by the IPv6Addr type -func IPv6Attrs() []AttrName { - return ipv6AddrAttrs -} - -// IPv6AddrAttr returns a string representation of an attribute for the given -// IPv6Addr. -func IPv6AddrAttr(ipv6 IPv6Addr, selector AttrName) string { - fn, found := ipv6AddrAttrMap[selector] - if !found { - return "" - } - - return fn(ipv6) -} - -// ipv6AddrInit is called once at init() -func ipv6AddrInit() { - // Sorted for human readability - ipv6AddrAttrs = []AttrName{ - "size", // Same position as in IPv6 for output consistency - "uint128", - } - - ipv6AddrAttrMap = map[AttrName]func(ipv6 IPv6Addr) string{ - "size": func(ipv6 IPv6Addr) string { - netSize := big.NewInt(1) - netSize = netSize.Lsh(netSize, uint(IPv6len*8-ipv6.Maskbits())) - return netSize.Text(10) - }, - "uint128": func(ipv6 IPv6Addr) string { - b := big.Int(*ipv6.Address) - return b.Text(10) - }, - } -} - -// bigIntToNetIPv6 is a helper function that correctly returns a net.IP with the -// correctly padded values. -func bigIntToNetIPv6(bi *big.Int) *net.IP { - x := make(net.IP, IPv6len) - ipv6Bytes := bi.Bytes() - - // It's possibe for ipv6Bytes to be less than IPv6len bytes in size. If - // they are different sizes we to pad the size of response. - if len(ipv6Bytes) < IPv6len { - buf := new(bytes.Buffer) - buf.Grow(IPv6len) - - for i := len(ipv6Bytes); i < IPv6len; i++ { - if err := binary.Write(buf, binary.BigEndian, byte(0)); err != nil { - panic(fmt.Sprintf("Unable to pad byte %d of input %v: %v", i, bi, err)) - } - } - - for _, b := range ipv6Bytes { - if err := binary.Write(buf, binary.BigEndian, b); err != nil { - panic(fmt.Sprintf("Unable to preserve endianness of input %v: %v", bi, err)) - } - } - - ipv6Bytes = buf.Bytes() - } - i := copy(x, ipv6Bytes) - if i != IPv6len { - panic("IPv6 wrong size") - } - return &x -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/rfc.go b/vendor/github.com/hashicorp/go-sockaddr/rfc.go deleted file mode 100644 index 02e188f..0000000 --- a/vendor/github.com/hashicorp/go-sockaddr/rfc.go +++ /dev/null @@ -1,948 +0,0 @@ -package sockaddr - -// ForwardingBlacklist is a faux RFC that includes a list of non-forwardable IP -// blocks. -const ForwardingBlacklist = 4294967295 -const ForwardingBlacklistRFC = "4294967295" - -// IsRFC tests to see if an SockAddr matches the specified RFC -func IsRFC(rfcNum uint, sa SockAddr) bool { - rfcNetMap := KnownRFCs() - rfcNets, ok := rfcNetMap[rfcNum] - if !ok { - return false - } - - var contained bool - for _, rfcNet := range rfcNets { - if rfcNet.Contains(sa) { - contained = true - break - } - } - return contained -} - -// KnownRFCs returns an initial set of known RFCs. -// -// NOTE (sean@): As this list evolves over time, please submit patches to keep -// this list current. If something isn't right, inquire, as it may just be a -// bug on my part. Some of the inclusions were based on my judgement as to what -// would be a useful value (e.g. RFC3330). -// -// Useful resources: -// -// * https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml -// * https://www.iana.org/assignments/ipv6-unicast-address-assignments/ipv6-unicast-address-assignments.xhtml -// * https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml -func KnownRFCs() map[uint]SockAddrs { - // NOTE(sean@): Multiple SockAddrs per RFC lend themselves well to a - // RADIX tree, but `ENOTIME`. Patches welcome. - return map[uint]SockAddrs{ - 919: { - // [RFC919] Broadcasting Internet Datagrams - MustIPv4Addr("255.255.255.255/32"), // [RFC1122], §7 Broadcast IP Addressing - Proposed Standards - }, - 1122: { - // [RFC1122] Requirements for Internet Hosts -- Communication Layers - MustIPv4Addr("0.0.0.0/8"), // [RFC1122], §3.2.1.3 - MustIPv4Addr("127.0.0.0/8"), // [RFC1122], §3.2.1.3 - }, - 1112: { - // [RFC1112] Host Extensions for IP Multicasting - MustIPv4Addr("224.0.0.0/4"), // [RFC1112], §4 Host Group Addresses - }, - 1918: { - // [RFC1918] Address Allocation for Private Internets - MustIPv4Addr("10.0.0.0/8"), - MustIPv4Addr("172.16.0.0/12"), - MustIPv4Addr("192.168.0.0/16"), - }, - 2544: { - // [RFC2544] Benchmarking Methodology for Network - // Interconnect Devices - MustIPv4Addr("198.18.0.0/15"), - }, - 2765: { - // [RFC2765] Stateless IP/ICMP Translation Algorithm - // (SIIT) (obsoleted by RFCs 6145, which itself was - // later obsoleted by 7915). - - // [RFC2765], §2.1 Addresses - MustIPv6Addr("0:0:0:0:0:ffff:0:0/96"), - }, - 2928: { - // [RFC2928] Initial IPv6 Sub-TLA ID Assignments - MustIPv6Addr("2001::/16"), // Superblock - //MustIPv6Addr("2001:0000::/23"), // IANA - //MustIPv6Addr("2001:0200::/23"), // APNIC - //MustIPv6Addr("2001:0400::/23"), // ARIN - //MustIPv6Addr("2001:0600::/23"), // RIPE NCC - //MustIPv6Addr("2001:0800::/23"), // (future assignment) - // ... - //MustIPv6Addr("2001:FE00::/23"), // (future assignment) - }, - 3056: { // 6to4 address - // [RFC3056] Connection of IPv6 Domains via IPv4 Clouds - - // [RFC3056], §2 IPv6 Prefix Allocation - MustIPv6Addr("2002::/16"), - }, - 3068: { - // [RFC3068] An Anycast Prefix for 6to4 Relay Routers - // (obsolete by RFC7526) - - // [RFC3068], § 6to4 Relay anycast address - MustIPv4Addr("192.88.99.0/24"), - - // [RFC3068], §2.5 6to4 IPv6 relay anycast address - // - // NOTE: /120 == 128-(32-24) - MustIPv6Addr("2002:c058:6301::/120"), - }, - 3171: { - // [RFC3171] IANA Guidelines for IPv4 Multicast Address Assignments - MustIPv4Addr("224.0.0.0/4"), - }, - 3330: { - // [RFC3330] Special-Use IPv4 Addresses - - // Addresses in this block refer to source hosts on - // "this" network. Address 0.0.0.0/32 may be used as a - // source address for this host on this network; other - // addresses within 0.0.0.0/8 may be used to refer to - // specified hosts on this network [RFC1700, page 4]. - MustIPv4Addr("0.0.0.0/8"), - - // 10.0.0.0/8 - This block is set aside for use in - // private networks. Its intended use is documented in - // [RFC1918]. Addresses within this block should not - // appear on the public Internet. - MustIPv4Addr("10.0.0.0/8"), - - // 14.0.0.0/8 - This block is set aside for assignments - // to the international system of Public Data Networks - // [RFC1700, page 181]. The registry of assignments - // within this block can be accessed from the "Public - // Data Network Numbers" link on the web page at - // http://www.iana.org/numbers.html. Addresses within - // this block are assigned to users and should be - // treated as such. - - // 24.0.0.0/8 - This block was allocated in early 1996 - // for use in provisioning IP service over cable - // television systems. Although the IANA initially was - // involved in making assignments to cable operators, - // this responsibility was transferred to American - // Registry for Internet Numbers (ARIN) in May 2001. - // Addresses within this block are assigned in the - // normal manner and should be treated as such. - - // 39.0.0.0/8 - This block was used in the "Class A - // Subnet Experiment" that commenced in May 1995, as - // documented in [RFC1797]. The experiment has been - // completed and this block has been returned to the - // pool of addresses reserved for future allocation or - // assignment. This block therefore no longer has a - // special use and is subject to allocation to a - // Regional Internet Registry for assignment in the - // normal manner. - - // 127.0.0.0/8 - This block is assigned for use as the Internet host - // loopback address. A datagram sent by a higher level protocol to an - // address anywhere within this block should loop back inside the host. - // This is ordinarily implemented using only 127.0.0.1/32 for loopback, - // but no addresses within this block should ever appear on any network - // anywhere [RFC1700, page 5]. - MustIPv4Addr("127.0.0.0/8"), - - // 128.0.0.0/16 - This block, corresponding to the - // numerically lowest of the former Class B addresses, - // was initially and is still reserved by the IANA. - // Given the present classless nature of the IP address - // space, the basis for the reservation no longer - // applies and addresses in this block are subject to - // future allocation to a Regional Internet Registry for - // assignment in the normal manner. - - // 169.254.0.0/16 - This is the "link local" block. It - // is allocated for communication between hosts on a - // single link. Hosts obtain these addresses by - // auto-configuration, such as when a DHCP server may - // not be found. - MustIPv4Addr("169.254.0.0/16"), - - // 172.16.0.0/12 - This block is set aside for use in - // private networks. Its intended use is documented in - // [RFC1918]. Addresses within this block should not - // appear on the public Internet. - MustIPv4Addr("172.16.0.0/12"), - - // 191.255.0.0/16 - This block, corresponding to the numerically highest - // to the former Class B addresses, was initially and is still reserved - // by the IANA. Given the present classless nature of the IP address - // space, the basis for the reservation no longer applies and addresses - // in this block are subject to future allocation to a Regional Internet - // Registry for assignment in the normal manner. - - // 192.0.0.0/24 - This block, corresponding to the - // numerically lowest of the former Class C addresses, - // was initially and is still reserved by the IANA. - // Given the present classless nature of the IP address - // space, the basis for the reservation no longer - // applies and addresses in this block are subject to - // future allocation to a Regional Internet Registry for - // assignment in the normal manner. - - // 192.0.2.0/24 - This block is assigned as "TEST-NET" for use in - // documentation and example code. It is often used in conjunction with - // domain names example.com or example.net in vendor and protocol - // documentation. Addresses within this block should not appear on the - // public Internet. - MustIPv4Addr("192.0.2.0/24"), - - // 192.88.99.0/24 - This block is allocated for use as 6to4 relay - // anycast addresses, according to [RFC3068]. - MustIPv4Addr("192.88.99.0/24"), - - // 192.168.0.0/16 - This block is set aside for use in private networks. - // Its intended use is documented in [RFC1918]. Addresses within this - // block should not appear on the public Internet. - MustIPv4Addr("192.168.0.0/16"), - - // 198.18.0.0/15 - This block has been allocated for use - // in benchmark tests of network interconnect devices. - // Its use is documented in [RFC2544]. - MustIPv4Addr("198.18.0.0/15"), - - // 223.255.255.0/24 - This block, corresponding to the - // numerically highest of the former Class C addresses, - // was initially and is still reserved by the IANA. - // Given the present classless nature of the IP address - // space, the basis for the reservation no longer - // applies and addresses in this block are subject to - // future allocation to a Regional Internet Registry for - // assignment in the normal manner. - - // 224.0.0.0/4 - This block, formerly known as the Class - // D address space, is allocated for use in IPv4 - // multicast address assignments. The IANA guidelines - // for assignments from this space are described in - // [RFC3171]. - MustIPv4Addr("224.0.0.0/4"), - - // 240.0.0.0/4 - This block, formerly known as the Class E address - // space, is reserved. The "limited broadcast" destination address - // 255.255.255.255 should never be forwarded outside the (sub-)net of - // the source. The remainder of this space is reserved - // for future use. [RFC1700, page 4] - MustIPv4Addr("240.0.0.0/4"), - }, - 3849: { - // [RFC3849] IPv6 Address Prefix Reserved for Documentation - MustIPv6Addr("2001:db8::/32"), // [RFC3849], §4 IANA Considerations - }, - 3927: { - // [RFC3927] Dynamic Configuration of IPv4 Link-Local Addresses - MustIPv4Addr("169.254.0.0/16"), // [RFC3927], §2.1 Link-Local Address Selection - }, - 4038: { - // [RFC4038] Application Aspects of IPv6 Transition - - // [RFC4038], §4.2. IPv6 Applications in a Dual-Stack Node - MustIPv6Addr("0:0:0:0:0:ffff::/96"), - }, - 4193: { - // [RFC4193] Unique Local IPv6 Unicast Addresses - MustIPv6Addr("fc00::/7"), - }, - 4291: { - // [RFC4291] IP Version 6 Addressing Architecture - - // [RFC4291], §2.5.2 The Unspecified Address - MustIPv6Addr("::/128"), - - // [RFC4291], §2.5.3 The Loopback Address - MustIPv6Addr("::1/128"), - - // [RFC4291], §2.5.5.1. IPv4-Compatible IPv6 Address - MustIPv6Addr("::/96"), - - // [RFC4291], §2.5.5.2. IPv4-Mapped IPv6 Address - MustIPv6Addr("::ffff:0:0/96"), - - // [RFC4291], §2.5.6 Link-Local IPv6 Unicast Addresses - MustIPv6Addr("fe80::/10"), - - // [RFC4291], §2.5.7 Site-Local IPv6 Unicast Addresses - // (depreciated) - MustIPv6Addr("fec0::/10"), - - // [RFC4291], §2.7 Multicast Addresses - MustIPv6Addr("ff00::/8"), - - // IPv6 Multicast Information. - // - // In the following "table" below, `ff0x` is replaced - // with the following values depending on the scope of - // the query: - // - // IPv6 Multicast Scopes: - // * ff00/9 // reserved - // * ff01/9 // interface-local - // * ff02/9 // link-local - // * ff03/9 // realm-local - // * ff04/9 // admin-local - // * ff05/9 // site-local - // * ff08/9 // organization-local - // * ff0e/9 // global - // * ff0f/9 // reserved - // - // IPv6 Multicast Addresses: - // * ff0x::2 // All routers - // * ff02::5 // OSPFIGP - // * ff02::6 // OSPFIGP Designated Routers - // * ff02::9 // RIP Routers - // * ff02::a // EIGRP Routers - // * ff02::d // All PIM Routers - // * ff02::1a // All RPL Routers - // * ff0x::fb // mDNSv6 - // * ff0x::101 // All Network Time Protocol (NTP) servers - // * ff02::1:1 // Link Name - // * ff02::1:2 // All-dhcp-agents - // * ff02::1:3 // Link-local Multicast Name Resolution - // * ff05::1:3 // All-dhcp-servers - // * ff02::1:ff00:0/104 // Solicited-node multicast address. - // * ff02::2:ff00:0/104 // Node Information Queries - }, - 4380: { - // [RFC4380] Teredo: Tunneling IPv6 over UDP through - // Network Address Translations (NATs) - - // [RFC4380], §2.6 Global Teredo IPv6 Service Prefix - MustIPv6Addr("2001:0000::/32"), - }, - 4773: { - // [RFC4773] Administration of the IANA Special Purpose IPv6 Address Block - MustIPv6Addr("2001:0000::/23"), // IANA - }, - 4843: { - // [RFC4843] An IPv6 Prefix for Overlay Routable Cryptographic Hash Identifiers (ORCHID) - MustIPv6Addr("2001:10::/28"), // [RFC4843], §7 IANA Considerations - }, - 5180: { - // [RFC5180] IPv6 Benchmarking Methodology for Network Interconnect Devices - MustIPv6Addr("2001:0200::/48"), // [RFC5180], §8 IANA Considerations - }, - 5735: { - // [RFC5735] Special Use IPv4 Addresses - MustIPv4Addr("192.0.2.0/24"), // TEST-NET-1 - MustIPv4Addr("198.51.100.0/24"), // TEST-NET-2 - MustIPv4Addr("203.0.113.0/24"), // TEST-NET-3 - MustIPv4Addr("198.18.0.0/15"), // Benchmarks - }, - 5737: { - // [RFC5737] IPv4 Address Blocks Reserved for Documentation - MustIPv4Addr("192.0.2.0/24"), // TEST-NET-1 - MustIPv4Addr("198.51.100.0/24"), // TEST-NET-2 - MustIPv4Addr("203.0.113.0/24"), // TEST-NET-3 - }, - 6052: { - // [RFC6052] IPv6 Addressing of IPv4/IPv6 Translators - MustIPv6Addr("64:ff9b::/96"), // [RFC6052], §2.1. Well-Known Prefix - }, - 6333: { - // [RFC6333] Dual-Stack Lite Broadband Deployments Following IPv4 Exhaustion - MustIPv4Addr("192.0.0.0/29"), // [RFC6333], §5.7 Well-Known IPv4 Address - }, - 6598: { - // [RFC6598] IANA-Reserved IPv4 Prefix for Shared Address Space - MustIPv4Addr("100.64.0.0/10"), - }, - 6666: { - // [RFC6666] A Discard Prefix for IPv6 - MustIPv6Addr("0100::/64"), - }, - 6890: { - // [RFC6890] Special-Purpose IP Address Registries - - // From "RFC6890 §2.2.1 Information Requirements": - /* - The IPv4 and IPv6 Special-Purpose Address Registries maintain the - following information regarding each entry: - - o Address Block - A block of IPv4 or IPv6 addresses that has been - registered for a special purpose. - - o Name - A descriptive name for the special-purpose address block. - - o RFC - The RFC through which the special-purpose address block was - requested. - - o Allocation Date - The date upon which the special-purpose address - block was allocated. - - o Termination Date - The date upon which the allocation is to be - terminated. This field is applicable for limited-use allocations - only. - - o Source - A boolean value indicating whether an address from the - allocated special-purpose address block is valid when used as the - source address of an IP datagram that transits two devices. - - o Destination - A boolean value indicating whether an address from - the allocated special-purpose address block is valid when used as - the destination address of an IP datagram that transits two - devices. - - o Forwardable - A boolean value indicating whether a router may - forward an IP datagram whose destination address is drawn from the - allocated special-purpose address block between external - interfaces. - - o Global - A boolean value indicating whether an IP datagram whose - destination address is drawn from the allocated special-purpose - address block is forwardable beyond a specified administrative - domain. - - o Reserved-by-Protocol - A boolean value indicating whether the - special-purpose address block is reserved by IP, itself. This - value is "TRUE" if the RFC that created the special-purpose - address block requires all compliant IP implementations to behave - in a special way when processing packets either to or from - addresses contained by the address block. - - If the value of "Destination" is FALSE, the values of "Forwardable" - and "Global" must also be false. - */ - - /*+----------------------+----------------------------+ - * | Attribute | Value | - * +----------------------+----------------------------+ - * | Address Block | 0.0.0.0/8 | - * | Name | "This host on this network"| - * | RFC | [RFC1122], Section 3.2.1.3 | - * | Allocation Date | September 1981 | - * | Termination Date | N/A | - * | Source | True | - * | Destination | False | - * | Forwardable | False | - * | Global | False | - * | Reserved-by-Protocol | True | - * +----------------------+----------------------------+*/ - MustIPv4Addr("0.0.0.0/8"), - - /*+----------------------+---------------+ - * | Attribute | Value | - * +----------------------+---------------+ - * | Address Block | 10.0.0.0/8 | - * | Name | Private-Use | - * | RFC | [RFC1918] | - * | Allocation Date | February 1996 | - * | Termination Date | N/A | - * | Source | True | - * | Destination | True | - * | Forwardable | True | - * | Global | False | - * | Reserved-by-Protocol | False | - * +----------------------+---------------+ */ - MustIPv4Addr("10.0.0.0/8"), - - /*+----------------------+----------------------+ - | Attribute | Value | - +----------------------+----------------------+ - | Address Block | 100.64.0.0/10 | - | Name | Shared Address Space | - | RFC | [RFC6598] | - | Allocation Date | April 2012 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | True | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+----------------------+*/ - MustIPv4Addr("100.64.0.0/10"), - - /*+----------------------+----------------------------+ - | Attribute | Value | - +----------------------+----------------------------+ - | Address Block | 127.0.0.0/8 | - | Name | Loopback | - | RFC | [RFC1122], Section 3.2.1.3 | - | Allocation Date | September 1981 | - | Termination Date | N/A | - | Source | False [1] | - | Destination | False [1] | - | Forwardable | False [1] | - | Global | False [1] | - | Reserved-by-Protocol | True | - +----------------------+----------------------------+*/ - // [1] Several protocols have been granted exceptions to - // this rule. For examples, see [RFC4379] and - // [RFC5884]. - MustIPv4Addr("127.0.0.0/8"), - - /*+----------------------+----------------+ - | Attribute | Value | - +----------------------+----------------+ - | Address Block | 169.254.0.0/16 | - | Name | Link Local | - | RFC | [RFC3927] | - | Allocation Date | May 2005 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | True | - +----------------------+----------------+*/ - MustIPv4Addr("169.254.0.0/16"), - - /*+----------------------+---------------+ - | Attribute | Value | - +----------------------+---------------+ - | Address Block | 172.16.0.0/12 | - | Name | Private-Use | - | RFC | [RFC1918] | - | Allocation Date | February 1996 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | True | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+---------------+*/ - MustIPv4Addr("172.16.0.0/12"), - - /*+----------------------+---------------------------------+ - | Attribute | Value | - +----------------------+---------------------------------+ - | Address Block | 192.0.0.0/24 [2] | - | Name | IETF Protocol Assignments | - | RFC | Section 2.1 of this document | - | Allocation Date | January 2010 | - | Termination Date | N/A | - | Source | False | - | Destination | False | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+---------------------------------+*/ - // [2] Not usable unless by virtue of a more specific - // reservation. - MustIPv4Addr("192.0.0.0/24"), - - /*+----------------------+--------------------------------+ - | Attribute | Value | - +----------------------+--------------------------------+ - | Address Block | 192.0.0.0/29 | - | Name | IPv4 Service Continuity Prefix | - | RFC | [RFC6333], [RFC7335] | - | Allocation Date | June 2011 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | True | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+--------------------------------+*/ - MustIPv4Addr("192.0.0.0/29"), - - /*+----------------------+----------------------------+ - | Attribute | Value | - +----------------------+----------------------------+ - | Address Block | 192.0.2.0/24 | - | Name | Documentation (TEST-NET-1) | - | RFC | [RFC5737] | - | Allocation Date | January 2010 | - | Termination Date | N/A | - | Source | False | - | Destination | False | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+----------------------------+*/ - MustIPv4Addr("192.0.2.0/24"), - - /*+----------------------+--------------------+ - | Attribute | Value | - +----------------------+--------------------+ - | Address Block | 192.88.99.0/24 | - | Name | 6to4 Relay Anycast | - | RFC | [RFC3068] | - | Allocation Date | June 2001 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | True | - | Global | True | - | Reserved-by-Protocol | False | - +----------------------+--------------------+*/ - MustIPv4Addr("192.88.99.0/24"), - - /*+----------------------+----------------+ - | Attribute | Value | - +----------------------+----------------+ - | Address Block | 192.168.0.0/16 | - | Name | Private-Use | - | RFC | [RFC1918] | - | Allocation Date | February 1996 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | True | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+----------------+*/ - MustIPv4Addr("192.168.0.0/16"), - - /*+----------------------+---------------+ - | Attribute | Value | - +----------------------+---------------+ - | Address Block | 198.18.0.0/15 | - | Name | Benchmarking | - | RFC | [RFC2544] | - | Allocation Date | March 1999 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | True | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+---------------+*/ - MustIPv4Addr("198.18.0.0/15"), - - /*+----------------------+----------------------------+ - | Attribute | Value | - +----------------------+----------------------------+ - | Address Block | 198.51.100.0/24 | - | Name | Documentation (TEST-NET-2) | - | RFC | [RFC5737] | - | Allocation Date | January 2010 | - | Termination Date | N/A | - | Source | False | - | Destination | False | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+----------------------------+*/ - MustIPv4Addr("198.51.100.0/24"), - - /*+----------------------+----------------------------+ - | Attribute | Value | - +----------------------+----------------------------+ - | Address Block | 203.0.113.0/24 | - | Name | Documentation (TEST-NET-3) | - | RFC | [RFC5737] | - | Allocation Date | January 2010 | - | Termination Date | N/A | - | Source | False | - | Destination | False | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+----------------------------+*/ - MustIPv4Addr("203.0.113.0/24"), - - /*+----------------------+----------------------+ - | Attribute | Value | - +----------------------+----------------------+ - | Address Block | 240.0.0.0/4 | - | Name | Reserved | - | RFC | [RFC1112], Section 4 | - | Allocation Date | August 1989 | - | Termination Date | N/A | - | Source | False | - | Destination | False | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | True | - +----------------------+----------------------+*/ - MustIPv4Addr("240.0.0.0/4"), - - /*+----------------------+----------------------+ - | Attribute | Value | - +----------------------+----------------------+ - | Address Block | 255.255.255.255/32 | - | Name | Limited Broadcast | - | RFC | [RFC0919], Section 7 | - | Allocation Date | October 1984 | - | Termination Date | N/A | - | Source | False | - | Destination | True | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+----------------------+*/ - MustIPv4Addr("255.255.255.255/32"), - - /*+----------------------+------------------+ - | Attribute | Value | - +----------------------+------------------+ - | Address Block | ::1/128 | - | Name | Loopback Address | - | RFC | [RFC4291] | - | Allocation Date | February 2006 | - | Termination Date | N/A | - | Source | False | - | Destination | False | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | True | - +----------------------+------------------+*/ - MustIPv6Addr("::1/128"), - - /*+----------------------+---------------------+ - | Attribute | Value | - +----------------------+---------------------+ - | Address Block | ::/128 | - | Name | Unspecified Address | - | RFC | [RFC4291] | - | Allocation Date | February 2006 | - | Termination Date | N/A | - | Source | True | - | Destination | False | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | True | - +----------------------+---------------------+*/ - MustIPv6Addr("::/128"), - - /*+----------------------+---------------------+ - | Attribute | Value | - +----------------------+---------------------+ - | Address Block | 64:ff9b::/96 | - | Name | IPv4-IPv6 Translat. | - | RFC | [RFC6052] | - | Allocation Date | October 2010 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | True | - | Global | True | - | Reserved-by-Protocol | False | - +----------------------+---------------------+*/ - MustIPv6Addr("64:ff9b::/96"), - - /*+----------------------+---------------------+ - | Attribute | Value | - +----------------------+---------------------+ - | Address Block | ::ffff:0:0/96 | - | Name | IPv4-mapped Address | - | RFC | [RFC4291] | - | Allocation Date | February 2006 | - | Termination Date | N/A | - | Source | False | - | Destination | False | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | True | - +----------------------+---------------------+*/ - MustIPv6Addr("::ffff:0:0/96"), - - /*+----------------------+----------------------------+ - | Attribute | Value | - +----------------------+----------------------------+ - | Address Block | 100::/64 | - | Name | Discard-Only Address Block | - | RFC | [RFC6666] | - | Allocation Date | June 2012 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | True | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+----------------------------+*/ - MustIPv6Addr("100::/64"), - - /*+----------------------+---------------------------+ - | Attribute | Value | - +----------------------+---------------------------+ - | Address Block | 2001::/23 | - | Name | IETF Protocol Assignments | - | RFC | [RFC2928] | - | Allocation Date | September 2000 | - | Termination Date | N/A | - | Source | False[1] | - | Destination | False[1] | - | Forwardable | False[1] | - | Global | False[1] | - | Reserved-by-Protocol | False | - +----------------------+---------------------------+*/ - // [1] Unless allowed by a more specific allocation. - MustIPv6Addr("2001::/16"), - - /*+----------------------+----------------+ - | Attribute | Value | - +----------------------+----------------+ - | Address Block | 2001::/32 | - | Name | TEREDO | - | RFC | [RFC4380] | - | Allocation Date | January 2006 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | True | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+----------------+*/ - // Covered by previous entry, included for completeness. - // - // MustIPv6Addr("2001::/16"), - - /*+----------------------+----------------+ - | Attribute | Value | - +----------------------+----------------+ - | Address Block | 2001:2::/48 | - | Name | Benchmarking | - | RFC | [RFC5180] | - | Allocation Date | April 2008 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | True | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+----------------+*/ - // Covered by previous entry, included for completeness. - // - // MustIPv6Addr("2001:2::/48"), - - /*+----------------------+---------------+ - | Attribute | Value | - +----------------------+---------------+ - | Address Block | 2001:db8::/32 | - | Name | Documentation | - | RFC | [RFC3849] | - | Allocation Date | July 2004 | - | Termination Date | N/A | - | Source | False | - | Destination | False | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+---------------+*/ - // Covered by previous entry, included for completeness. - // - // MustIPv6Addr("2001:db8::/32"), - - /*+----------------------+--------------+ - | Attribute | Value | - +----------------------+--------------+ - | Address Block | 2001:10::/28 | - | Name | ORCHID | - | RFC | [RFC4843] | - | Allocation Date | March 2007 | - | Termination Date | March 2014 | - | Source | False | - | Destination | False | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+--------------+*/ - // Covered by previous entry, included for completeness. - // - // MustIPv6Addr("2001:10::/28"), - - /*+----------------------+---------------+ - | Attribute | Value | - +----------------------+---------------+ - | Address Block | 2002::/16 [2] | - | Name | 6to4 | - | RFC | [RFC3056] | - | Allocation Date | February 2001 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | True | - | Global | N/A [2] | - | Reserved-by-Protocol | False | - +----------------------+---------------+*/ - // [2] See [RFC3056] for details. - MustIPv6Addr("2002::/16"), - - /*+----------------------+--------------+ - | Attribute | Value | - +----------------------+--------------+ - | Address Block | fc00::/7 | - | Name | Unique-Local | - | RFC | [RFC4193] | - | Allocation Date | October 2005 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | True | - | Global | False | - | Reserved-by-Protocol | False | - +----------------------+--------------+*/ - MustIPv6Addr("fc00::/7"), - - /*+----------------------+-----------------------+ - | Attribute | Value | - +----------------------+-----------------------+ - | Address Block | fe80::/10 | - | Name | Linked-Scoped Unicast | - | RFC | [RFC4291] | - | Allocation Date | February 2006 | - | Termination Date | N/A | - | Source | True | - | Destination | True | - | Forwardable | False | - | Global | False | - | Reserved-by-Protocol | True | - +----------------------+-----------------------+*/ - MustIPv6Addr("fe80::/10"), - }, - 7335: { - // [RFC7335] IPv4 Service Continuity Prefix - MustIPv4Addr("192.0.0.0/29"), // [RFC7335], §6 IANA Considerations - }, - ForwardingBlacklist: { // Pseudo-RFC - // Blacklist of non-forwardable IP blocks taken from RFC6890 - // - // TODO: the attributes for forwardable should be - // searcahble and embedded in the main list of RFCs - // above. - MustIPv4Addr("0.0.0.0/8"), - MustIPv4Addr("127.0.0.0/8"), - MustIPv4Addr("169.254.0.0/16"), - MustIPv4Addr("192.0.0.0/24"), - MustIPv4Addr("192.0.2.0/24"), - MustIPv4Addr("198.51.100.0/24"), - MustIPv4Addr("203.0.113.0/24"), - MustIPv4Addr("240.0.0.0/4"), - MustIPv4Addr("255.255.255.255/32"), - MustIPv6Addr("::1/128"), - MustIPv6Addr("::/128"), - MustIPv6Addr("::ffff:0:0/96"), - - // There is no way of expressing a whitelist per RFC2928 - // atm without creating a negative mask, which I don't - // want to do atm. - //MustIPv6Addr("2001::/23"), - - MustIPv6Addr("2001:db8::/32"), - MustIPv6Addr("2001:10::/28"), - MustIPv6Addr("fe80::/10"), - }, - } -} - -// VisitAllRFCs iterates over all known RFCs and calls the visitor -func VisitAllRFCs(fn func(rfcNum uint, sockaddrs SockAddrs)) { - rfcNetMap := KnownRFCs() - - // Blacklist of faux-RFCs. Don't show the world that we're abusing the - // RFC system in this library. - rfcBlacklist := map[uint]struct{}{ - ForwardingBlacklist: {}, - } - - for rfcNum, sas := range rfcNetMap { - if _, found := rfcBlacklist[rfcNum]; !found { - fn(rfcNum, sas) - } - } -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/route_info.go b/vendor/github.com/hashicorp/go-sockaddr/route_info.go deleted file mode 100644 index 2a3ee1d..0000000 --- a/vendor/github.com/hashicorp/go-sockaddr/route_info.go +++ /dev/null @@ -1,19 +0,0 @@ -package sockaddr - -// RouteInterface specifies an interface for obtaining memoized route table and -// network information from a given OS. -type RouteInterface interface { - // GetDefaultInterfaceName returns the name of the interface that has a - // default route or an error and an empty string if a problem was - // encountered. - GetDefaultInterfaceName() (string, error) -} - -// VisitCommands visits each command used by the platform-specific RouteInfo -// implementation. -func (ri routeInfo) VisitCommands(fn func(name string, cmd []string)) { - for k, v := range ri.cmds { - cmds := append([]string(nil), v...) - fn(k, cmds) - } -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/route_info_bsd.go b/vendor/github.com/hashicorp/go-sockaddr/route_info_bsd.go deleted file mode 100644 index 705757a..0000000 --- a/vendor/github.com/hashicorp/go-sockaddr/route_info_bsd.go +++ /dev/null @@ -1,36 +0,0 @@ -// +build darwin dragonfly freebsd netbsd openbsd - -package sockaddr - -import "os/exec" - -var cmds map[string][]string = map[string][]string{ - "route": {"/sbin/route", "-n", "get", "default"}, -} - -type routeInfo struct { - cmds map[string][]string -} - -// NewRouteInfo returns a BSD-specific implementation of the RouteInfo -// interface. -func NewRouteInfo() (routeInfo, error) { - return routeInfo{ - cmds: cmds, - }, nil -} - -// GetDefaultInterfaceName returns the interface name attached to the default -// route on the default interface. -func (ri routeInfo) GetDefaultInterfaceName() (string, error) { - out, err := exec.Command(cmds["route"][0], cmds["route"][1:]...).Output() - if err != nil { - return "", err - } - - var ifName string - if ifName, err = parseDefaultIfNameFromRoute(string(out)); err != nil { - return "", err - } - return ifName, nil -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/route_info_default.go b/vendor/github.com/hashicorp/go-sockaddr/route_info_default.go deleted file mode 100644 index d1b009f..0000000 --- a/vendor/github.com/hashicorp/go-sockaddr/route_info_default.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build android nacl plan9 - -package sockaddr - -import "errors" - -// getDefaultIfName is the default interface function for unsupported platforms. -func getDefaultIfName() (string, error) { - return "", errors.New("No default interface found (unsupported platform)") -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/route_info_linux.go b/vendor/github.com/hashicorp/go-sockaddr/route_info_linux.go deleted file mode 100644 index c2ec91e..0000000 --- a/vendor/github.com/hashicorp/go-sockaddr/route_info_linux.go +++ /dev/null @@ -1,40 +0,0 @@ -package sockaddr - -import ( - "errors" - "os/exec" -) - -type routeInfo struct { - cmds map[string][]string -} - -// NewRouteInfo returns a Linux-specific implementation of the RouteInfo -// interface. -func NewRouteInfo() (routeInfo, error) { - // CoreOS Container Linux moved ip to /usr/bin/ip, so look it up on - // $PATH and fallback to /sbin/ip on error. - path, _ := exec.LookPath("ip") - if path == "" { - path = "/sbin/ip" - } - - return routeInfo{ - cmds: map[string][]string{"ip": {path, "route"}}, - }, nil -} - -// GetDefaultInterfaceName returns the interface name attached to the default -// route on the default interface. -func (ri routeInfo) GetDefaultInterfaceName() (string, error) { - out, err := exec.Command(ri.cmds["ip"][0], ri.cmds["ip"][1:]...).Output() - if err != nil { - return "", err - } - - var ifName string - if ifName, err = parseDefaultIfNameFromIPCmd(string(out)); err != nil { - return "", errors.New("No default interface found") - } - return ifName, nil -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/route_info_solaris.go b/vendor/github.com/hashicorp/go-sockaddr/route_info_solaris.go deleted file mode 100644 index ee8e798..0000000 --- a/vendor/github.com/hashicorp/go-sockaddr/route_info_solaris.go +++ /dev/null @@ -1,37 +0,0 @@ -package sockaddr - -import ( - "errors" - "os/exec" -) - -var cmds map[string][]string = map[string][]string{ - "route": {"/usr/sbin/route", "-n", "get", "default"}, -} - -type routeInfo struct { - cmds map[string][]string -} - -// NewRouteInfo returns a BSD-specific implementation of the RouteInfo -// interface. -func NewRouteInfo() (routeInfo, error) { - return routeInfo{ - cmds: cmds, - }, nil -} - -// GetDefaultInterfaceName returns the interface name attached to the default -// route on the default interface. -func (ri routeInfo) GetDefaultInterfaceName() (string, error) { - out, err := exec.Command(cmds["route"][0], cmds["route"][1:]...).Output() - if err != nil { - return "", err - } - - var ifName string - if ifName, err = parseDefaultIfNameFromRoute(string(out)); err != nil { - return "", errors.New("No default interface found") - } - return ifName, nil -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/route_info_windows.go b/vendor/github.com/hashicorp/go-sockaddr/route_info_windows.go deleted file mode 100644 index 3da9728..0000000 --- a/vendor/github.com/hashicorp/go-sockaddr/route_info_windows.go +++ /dev/null @@ -1,41 +0,0 @@ -package sockaddr - -import "os/exec" - -var cmds map[string][]string = map[string][]string{ - "netstat": {"netstat", "-rn"}, - "ipconfig": {"ipconfig"}, -} - -type routeInfo struct { - cmds map[string][]string -} - -// NewRouteInfo returns a BSD-specific implementation of the RouteInfo -// interface. -func NewRouteInfo() (routeInfo, error) { - return routeInfo{ - cmds: cmds, - }, nil -} - -// GetDefaultInterfaceName returns the interface name attached to the default -// route on the default interface. -func (ri routeInfo) GetDefaultInterfaceName() (string, error) { - ifNameOut, err := exec.Command(cmds["netstat"][0], cmds["netstat"][1:]...).Output() - if err != nil { - return "", err - } - - ipconfigOut, err := exec.Command(cmds["ipconfig"][0], cmds["ipconfig"][1:]...).Output() - if err != nil { - return "", err - } - - ifName, err := parseDefaultIfNameWindows(string(ifNameOut), string(ipconfigOut)) - if err != nil { - return "", err - } - - return ifName, nil -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/sockaddr.go b/vendor/github.com/hashicorp/go-sockaddr/sockaddr.go deleted file mode 100644 index 826c91c..0000000 --- a/vendor/github.com/hashicorp/go-sockaddr/sockaddr.go +++ /dev/null @@ -1,206 +0,0 @@ -package sockaddr - -import ( - "encoding/json" - "fmt" - "strings" -) - -type SockAddrType int -type AttrName string - -const ( - TypeUnknown SockAddrType = 0x0 - TypeUnix = 0x1 - TypeIPv4 = 0x2 - TypeIPv6 = 0x4 - - // TypeIP is the union of TypeIPv4 and TypeIPv6 - TypeIP = 0x6 -) - -type SockAddr interface { - // CmpRFC returns 0 if SockAddr exactly matches one of the matched RFC - // networks, -1 if the receiver is contained within the RFC network, or - // 1 if the address is not contained within the RFC. - CmpRFC(rfcNum uint, sa SockAddr) int - - // Contains returns true if the SockAddr arg is contained within the - // receiver - Contains(SockAddr) bool - - // Equal allows for the comparison of two SockAddrs - Equal(SockAddr) bool - - DialPacketArgs() (string, string) - DialStreamArgs() (string, string) - ListenPacketArgs() (string, string) - ListenStreamArgs() (string, string) - - // String returns the string representation of SockAddr - String() string - - // Type returns the SockAddrType - Type() SockAddrType -} - -// sockAddrAttrMap is a map of the SockAddr type-specific attributes. -var sockAddrAttrMap map[AttrName]func(SockAddr) string -var sockAddrAttrs []AttrName - -func init() { - sockAddrInit() -} - -// New creates a new SockAddr from the string. The order in which New() -// attempts to construct a SockAddr is: IPv4Addr, IPv6Addr, SockAddrUnix. -// -// NOTE: New() relies on the heuristic wherein if the path begins with either a -// '.' or '/' character before creating a new UnixSock. For UNIX sockets that -// are absolute paths or are nested within a sub-directory, this works as -// expected, however if the UNIX socket is contained in the current working -// directory, this will fail unless the path begins with "./" -// (e.g. "./my-local-socket"). Calls directly to NewUnixSock() do not suffer -// this limitation. Invalid IP addresses such as "256.0.0.0/-1" will run afoul -// of this heuristic and be assumed to be a valid UNIX socket path (which they -// are, but it is probably not what you want and you won't realize it until you -// stat(2) the file system to discover it doesn't exist). -func NewSockAddr(s string) (SockAddr, error) { - ipv4Addr, err := NewIPv4Addr(s) - if err == nil { - return ipv4Addr, nil - } - - ipv6Addr, err := NewIPv6Addr(s) - if err == nil { - return ipv6Addr, nil - } - - // Check to make sure the string begins with either a '.' or '/', or - // contains a '/'. - if len(s) > 1 && (strings.IndexAny(s[0:1], "./") != -1 || strings.IndexByte(s, '/') != -1) { - unixSock, err := NewUnixSock(s) - if err == nil { - return unixSock, nil - } - } - - return nil, fmt.Errorf("Unable to convert %q to an IPv4 or IPv6 address, or a UNIX Socket", s) -} - -// ToIPAddr returns an IPAddr type or nil if the type conversion fails. -func ToIPAddr(sa SockAddr) *IPAddr { - ipa, ok := sa.(IPAddr) - if !ok { - return nil - } - return &ipa -} - -// ToIPv4Addr returns an IPv4Addr type or nil if the type conversion fails. -func ToIPv4Addr(sa SockAddr) *IPv4Addr { - switch v := sa.(type) { - case IPv4Addr: - return &v - default: - return nil - } -} - -// ToIPv6Addr returns an IPv6Addr type or nil if the type conversion fails. -func ToIPv6Addr(sa SockAddr) *IPv6Addr { - switch v := sa.(type) { - case IPv6Addr: - return &v - default: - return nil - } -} - -// ToUnixSock returns a UnixSock type or nil if the type conversion fails. -func ToUnixSock(sa SockAddr) *UnixSock { - switch v := sa.(type) { - case UnixSock: - return &v - default: - return nil - } -} - -// SockAddrAttr returns a string representation of an attribute for the given -// SockAddr. -func SockAddrAttr(sa SockAddr, selector AttrName) string { - fn, found := sockAddrAttrMap[selector] - if !found { - return "" - } - - return fn(sa) -} - -// String() for SockAddrType returns a string representation of the -// SockAddrType (e.g. "IPv4", "IPv6", "UNIX", "IP", or "unknown"). -func (sat SockAddrType) String() string { - switch sat { - case TypeIPv4: - return "IPv4" - case TypeIPv6: - return "IPv6" - // There is no concrete "IP" type. Leaving here as a reminder. - // case TypeIP: - // return "IP" - case TypeUnix: - return "UNIX" - default: - panic("unsupported type") - } -} - -// sockAddrInit is called once at init() -func sockAddrInit() { - sockAddrAttrs = []AttrName{ - "type", // type should be first - "string", - } - - sockAddrAttrMap = map[AttrName]func(sa SockAddr) string{ - "string": func(sa SockAddr) string { - return sa.String() - }, - "type": func(sa SockAddr) string { - return sa.Type().String() - }, - } -} - -// UnixSockAttrs returns a list of attributes supported by the UnixSock type -func SockAddrAttrs() []AttrName { - return sockAddrAttrs -} - -// Although this is pretty trivial to do in a program, having the logic here is -// useful all around. Note that this marshals into a *string* -- the underlying -// string representation of the sockaddr. If you then unmarshal into this type -// in Go, all will work as expected, but externally you can take what comes out -// and use the string value directly. -type SockAddrMarshaler struct { - SockAddr -} - -func (s *SockAddrMarshaler) MarshalJSON() ([]byte, error) { - return json.Marshal(s.SockAddr.String()) -} - -func (s *SockAddrMarshaler) UnmarshalJSON(in []byte) error { - var str string - err := json.Unmarshal(in, &str) - if err != nil { - return err - } - sa, err := NewSockAddr(str) - if err != nil { - return err - } - s.SockAddr = sa - return nil -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/sockaddrs.go b/vendor/github.com/hashicorp/go-sockaddr/sockaddrs.go deleted file mode 100644 index 75fbffb..0000000 --- a/vendor/github.com/hashicorp/go-sockaddr/sockaddrs.go +++ /dev/null @@ -1,193 +0,0 @@ -package sockaddr - -import ( - "bytes" - "sort" -) - -// SockAddrs is a slice of SockAddrs -type SockAddrs []SockAddr - -func (s SockAddrs) Len() int { return len(s) } -func (s SockAddrs) Swap(i, j int) { s[i], s[j] = s[j], s[i] } - -// CmpAddrFunc is the function signature that must be met to be used in the -// OrderedAddrBy multiAddrSorter -type CmpAddrFunc func(p1, p2 *SockAddr) int - -// multiAddrSorter implements the Sort interface, sorting the SockAddrs within. -type multiAddrSorter struct { - addrs SockAddrs - cmp []CmpAddrFunc -} - -// Sort sorts the argument slice according to the Cmp functions passed to -// OrderedAddrBy. -func (ms *multiAddrSorter) Sort(sockAddrs SockAddrs) { - ms.addrs = sockAddrs - sort.Sort(ms) -} - -// OrderedAddrBy sorts SockAddr by the list of sort function pointers. -func OrderedAddrBy(cmpFuncs ...CmpAddrFunc) *multiAddrSorter { - return &multiAddrSorter{ - cmp: cmpFuncs, - } -} - -// Len is part of sort.Interface. -func (ms *multiAddrSorter) Len() int { - return len(ms.addrs) -} - -// Less is part of sort.Interface. It is implemented by looping along the -// Cmp() functions until it finds a comparison that is either less than, -// equal to, or greater than. -func (ms *multiAddrSorter) Less(i, j int) bool { - p, q := &ms.addrs[i], &ms.addrs[j] - // Try all but the last comparison. - var k int - for k = 0; k < len(ms.cmp)-1; k++ { - cmp := ms.cmp[k] - x := cmp(p, q) - switch x { - case -1: - // p < q, so we have a decision. - return true - case 1: - // p > q, so we have a decision. - return false - } - // p == q; try the next comparison. - } - // All comparisons to here said "equal", so just return whatever the - // final comparison reports. - switch ms.cmp[k](p, q) { - case -1: - return true - case 1: - return false - default: - // Still a tie! Now what? - return false - } -} - -// Swap is part of sort.Interface. -func (ms *multiAddrSorter) Swap(i, j int) { - ms.addrs[i], ms.addrs[j] = ms.addrs[j], ms.addrs[i] -} - -const ( - // NOTE (sean@): These constants are here for code readability only and - // are sprucing up the code for readability purposes. Some of the - // Cmp*() variants have confusing logic (especially when dealing with - // mixed-type comparisons) and this, I think, has made it easier to grok - // the code faster. - sortReceiverBeforeArg = -1 - sortDeferDecision = 0 - sortArgBeforeReceiver = 1 -) - -// AscAddress is a sorting function to sort SockAddrs by their respective -// address type. Non-equal types are deferred in the sort. -func AscAddress(p1Ptr, p2Ptr *SockAddr) int { - p1 := *p1Ptr - p2 := *p2Ptr - - switch v := p1.(type) { - case IPv4Addr: - return v.CmpAddress(p2) - case IPv6Addr: - return v.CmpAddress(p2) - case UnixSock: - return v.CmpAddress(p2) - default: - return sortDeferDecision - } -} - -// AscPort is a sorting function to sort SockAddrs by their respective address -// type. Non-equal types are deferred in the sort. -func AscPort(p1Ptr, p2Ptr *SockAddr) int { - p1 := *p1Ptr - p2 := *p2Ptr - - switch v := p1.(type) { - case IPv4Addr: - return v.CmpPort(p2) - case IPv6Addr: - return v.CmpPort(p2) - default: - return sortDeferDecision - } -} - -// AscPrivate is a sorting function to sort "more secure" private values before -// "more public" values. Both IPv4 and IPv6 are compared against RFC6890 -// (RFC6890 includes, and is not limited to, RFC1918 and RFC6598 for IPv4, and -// IPv6 includes RFC4193). -func AscPrivate(p1Ptr, p2Ptr *SockAddr) int { - p1 := *p1Ptr - p2 := *p2Ptr - - switch v := p1.(type) { - case IPv4Addr, IPv6Addr: - return v.CmpRFC(6890, p2) - default: - return sortDeferDecision - } -} - -// AscNetworkSize is a sorting function to sort SockAddrs based on their network -// size. Non-equal types are deferred in the sort. -func AscNetworkSize(p1Ptr, p2Ptr *SockAddr) int { - p1 := *p1Ptr - p2 := *p2Ptr - p1Type := p1.Type() - p2Type := p2.Type() - - // Network size operations on non-IP types make no sense - if p1Type != p2Type && p1Type != TypeIP { - return sortDeferDecision - } - - ipA := p1.(IPAddr) - ipB := p2.(IPAddr) - - return bytes.Compare([]byte(*ipA.NetIPMask()), []byte(*ipB.NetIPMask())) -} - -// AscType is a sorting function to sort "more secure" types before -// "less-secure" types. -func AscType(p1Ptr, p2Ptr *SockAddr) int { - p1 := *p1Ptr - p2 := *p2Ptr - p1Type := p1.Type() - p2Type := p2.Type() - switch { - case p1Type < p2Type: - return sortReceiverBeforeArg - case p1Type == p2Type: - return sortDeferDecision - case p1Type > p2Type: - return sortArgBeforeReceiver - default: - return sortDeferDecision - } -} - -// FilterByType returns two lists: a list of matched and unmatched SockAddrs -func (sas SockAddrs) FilterByType(type_ SockAddrType) (matched, excluded SockAddrs) { - matched = make(SockAddrs, 0, len(sas)) - excluded = make(SockAddrs, 0, len(sas)) - - for _, sa := range sas { - if sa.Type()&type_ != 0 { - matched = append(matched, sa) - } else { - excluded = append(excluded, sa) - } - } - return matched, excluded -} diff --git a/vendor/github.com/hashicorp/go-sockaddr/unixsock.go b/vendor/github.com/hashicorp/go-sockaddr/unixsock.go deleted file mode 100644 index f3be3f6..0000000 --- a/vendor/github.com/hashicorp/go-sockaddr/unixsock.go +++ /dev/null @@ -1,135 +0,0 @@ -package sockaddr - -import ( - "fmt" - "strings" -) - -type UnixSock struct { - SockAddr - path string -} -type UnixSocks []*UnixSock - -// unixAttrMap is a map of the UnixSockAddr type-specific attributes. -var unixAttrMap map[AttrName]func(UnixSock) string -var unixAttrs []AttrName - -func init() { - unixAttrInit() -} - -// NewUnixSock creates an UnixSock from a string path. String can be in the -// form of either URI-based string (e.g. `file:///etc/passwd`), an absolute -// path (e.g. `/etc/passwd`), or a relative path (e.g. `./foo`). -func NewUnixSock(s string) (ret UnixSock, err error) { - ret.path = s - return ret, nil -} - -// CmpAddress follows the Cmp() standard protocol and returns: -// -// - -1 If the receiver should sort first because its name lexically sorts before arg -// - 0 if the SockAddr arg is not a UnixSock, or is a UnixSock with the same path. -// - 1 If the argument should sort first. -func (us UnixSock) CmpAddress(sa SockAddr) int { - usb, ok := sa.(UnixSock) - if !ok { - return sortDeferDecision - } - - return strings.Compare(us.Path(), usb.Path()) -} - -// DialPacketArgs returns the arguments required to be passed to net.DialUnix() -// with the `unixgram` network type. -func (us UnixSock) DialPacketArgs() (network, dialArgs string) { - return "unixgram", us.path -} - -// DialStreamArgs returns the arguments required to be passed to net.DialUnix() -// with the `unix` network type. -func (us UnixSock) DialStreamArgs() (network, dialArgs string) { - return "unix", us.path -} - -// Equal returns true if a SockAddr is equal to the receiving UnixSock. -func (us UnixSock) Equal(sa SockAddr) bool { - usb, ok := sa.(UnixSock) - if !ok { - return false - } - - if us.Path() != usb.Path() { - return false - } - - return true -} - -// ListenPacketArgs returns the arguments required to be passed to -// net.ListenUnixgram() with the `unixgram` network type. -func (us UnixSock) ListenPacketArgs() (network, dialArgs string) { - return "unixgram", us.path -} - -// ListenStreamArgs returns the arguments required to be passed to -// net.ListenUnix() with the `unix` network type. -func (us UnixSock) ListenStreamArgs() (network, dialArgs string) { - return "unix", us.path -} - -// MustUnixSock is a helper method that must return an UnixSock or panic on -// invalid input. -func MustUnixSock(addr string) UnixSock { - us, err := NewUnixSock(addr) - if err != nil { - panic(fmt.Sprintf("Unable to create a UnixSock from %+q: %v", addr, err)) - } - return us -} - -// Path returns the given path of the UnixSock -func (us UnixSock) Path() string { - return us.path -} - -// String returns the path of the UnixSock -func (us UnixSock) String() string { - return fmt.Sprintf("%+q", us.path) -} - -// Type is used as a type switch and returns TypeUnix -func (UnixSock) Type() SockAddrType { - return TypeUnix -} - -// UnixSockAttrs returns a list of attributes supported by the UnixSockAddr type -func UnixSockAttrs() []AttrName { - return unixAttrs -} - -// UnixSockAttr returns a string representation of an attribute for the given -// UnixSock. -func UnixSockAttr(us UnixSock, attrName AttrName) string { - fn, found := unixAttrMap[attrName] - if !found { - return "" - } - - return fn(us) -} - -// unixAttrInit is called once at init() -func unixAttrInit() { - // Sorted for human readability - unixAttrs = []AttrName{ - "path", - } - - unixAttrMap = map[AttrName]func(us UnixSock) string{ - "path": func(us UnixSock) string { - return us.Path() - }, - } -} diff --git a/vendor/github.com/hashicorp/hcl/.gitignore b/vendor/github.com/hashicorp/hcl/.gitignore deleted file mode 100644 index 15586a2..0000000 --- a/vendor/github.com/hashicorp/hcl/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -y.output - -# ignore intellij files -.idea -*.iml -*.ipr -*.iws - -*.test diff --git a/vendor/github.com/hashicorp/hcl/.travis.yml b/vendor/github.com/hashicorp/hcl/.travis.yml deleted file mode 100644 index cb63a32..0000000 --- a/vendor/github.com/hashicorp/hcl/.travis.yml +++ /dev/null @@ -1,13 +0,0 @@ -sudo: false - -language: go - -go: - - 1.x - - tip - -branches: - only: - - master - -script: make test diff --git a/vendor/github.com/hashicorp/hcl/LICENSE b/vendor/github.com/hashicorp/hcl/LICENSE deleted file mode 100644 index c33dcc7..0000000 --- a/vendor/github.com/hashicorp/hcl/LICENSE +++ /dev/null @@ -1,354 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. “Contributor” - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. “Contributor Version” - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor’s Contribution. - -1.3. “Contribution” - - means Covered Software of a particular Contributor. - -1.4. “Covered Software” - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. “Incompatible With Secondary Licenses” - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of version - 1.1 or earlier of the License, but not also under the terms of a - Secondary License. - -1.6. “Executable Form” - - means any form of the work other than Source Code Form. - -1.7. “Larger Work” - - means a work that combines Covered Software with other material, in a separate - file or files, that is not Covered Software. - -1.8. “License” - - means this document. - -1.9. “Licensable” - - means having the right to grant, to the maximum extent possible, whether at the - time of the initial grant or subsequently, any and all of the rights conveyed by - this License. - -1.10. “Modifications” - - means any of the following: - - a. any file in Source Code Form that results from an addition to, deletion - from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. “Patent Claims” of a Contributor - - means any patent claim(s), including without limitation, method, process, - and apparatus claims, in any patent Licensable by such Contributor that - would be infringed, but for the grant of the License, by the making, - using, selling, offering for sale, having made, import, or transfer of - either its Contributions or its Contributor Version. - -1.12. “Secondary License” - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. “Source Code Form” - - means the form of the work preferred for making modifications. - -1.14. “You” (or “Your”) - - means an individual or a legal entity exercising rights under this - License. For legal entities, “You” includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, “control” means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or as - part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its Contributions - or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution become - effective for each Contribution on the date the Contributor first distributes - such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under this - License. No additional rights or licenses will be implied from the distribution - or licensing of Covered Software under this License. Notwithstanding Section - 2.1(b) above, no patent license is granted by a Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party’s - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of its - Contributions. - - This License does not grant any rights in the trademarks, service marks, or - logos of any Contributor (except as may be necessary to comply with the - notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this License - (see Section 10.2) or under the terms of a Secondary License (if permitted - under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its Contributions - are its original creation(s) or it has sufficient rights to grant the - rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under applicable - copyright doctrines of fair use, fair dealing, or other equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under the - terms of this License. You must inform recipients that the Source Code Form - of the Covered Software is governed by the terms of this License, and how - they can obtain a copy of this License. You may not attempt to alter or - restrict the recipients’ rights in the Source Code Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this License, - or sublicense it under different terms, provided that the license for - the Executable Form does not attempt to limit or alter the recipients’ - rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for the - Covered Software. If the Larger Work is a combination of Covered Software - with a work governed by one or more Secondary Licenses, and the Covered - Software is not Incompatible With Secondary Licenses, this License permits - You to additionally distribute such Covered Software under the terms of - such Secondary License(s), so that the recipient of the Larger Work may, at - their option, further distribute the Covered Software under the terms of - either this License or such Secondary License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices (including - copyright notices, patent notices, disclaimers of warranty, or limitations - of liability) contained within the Source Code Form of the Covered - Software, except that You may alter any license notices to the extent - required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on behalf - of any Contributor. You must make it absolutely clear that any such - warranty, support, indemnity, or liability obligation is offered by You - alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, judicial - order, or regulation then You must: (a) comply with the terms of this License - to the maximum extent possible; and (b) describe the limitations and the code - they affect. Such description must be placed in a text file included with all - distributions of the Covered Software under this License. Except to the - extent prohibited by statute or regulation, such description must be - sufficiently detailed for a recipient of ordinary skill to be able to - understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing basis, - if such Contributor fails to notify You of the non-compliance by some - reasonable means prior to 60 days after You have come back into compliance. - Moreover, Your grants from a particular Contributor are reinstated on an - ongoing basis if such Contributor notifies You of the non-compliance by - some reasonable means, this is the first time You have received notice of - non-compliance with this License from such Contributor, and You become - compliant prior to 30 days after Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, counter-claims, - and cross-claims) alleging that a Contributor Version directly or - indirectly infringes any patent, then the rights granted to You by any and - all Contributors for the Covered Software under Section 2.1 of this License - shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an “as is” basis, without - warranty of any kind, either expressed, implied, or statutory, including, - without limitation, warranties that the Covered Software is free of defects, - merchantable, fit for a particular purpose or non-infringing. The entire - risk as to the quality and performance of the Covered Software is with You. - Should any Covered Software prove defective in any respect, You (not any - Contributor) assume the cost of any necessary servicing, repair, or - correction. This disclaimer of warranty constitutes an essential part of this - License. No use of any Covered Software is authorized under this License - except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from such - party’s negligence to the extent applicable law prohibits such limitation. - Some jurisdictions do not allow the exclusion or limitation of incidental or - consequential damages, so this exclusion and limitation may not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts of - a jurisdiction where the defendant maintains its principal place of business - and such litigation shall be governed by laws of that jurisdiction, without - reference to its conflict-of-law provisions. Nothing in this Section shall - prevent a party’s ability to bring cross-claims or counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject matter - hereof. If any provision of this License is held to be unenforceable, such - provision shall be reformed only to the extent necessary to make it - enforceable. Any law or regulation which provides that the language of a - contract shall be construed against the drafter shall not be used to construe - this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version of - the License under which You originally received the Covered Software, or - under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a modified - version of this License if you rename the license and remove any - references to the name of the license steward (except to note that such - modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses - If You choose to distribute Source Code Form that is Incompatible With - Secondary Licenses under the terms of this version of the License, the - notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, then -You may include the notice in a location (such as a LICENSE file in a relevant -directory) where a recipient would be likely to look for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - “Incompatible With Secondary Licenses” Notice - - This Source Code Form is “Incompatible - With Secondary Licenses”, as defined by - the Mozilla Public License, v. 2.0. - diff --git a/vendor/github.com/hashicorp/hcl/Makefile b/vendor/github.com/hashicorp/hcl/Makefile deleted file mode 100644 index 84fd743..0000000 --- a/vendor/github.com/hashicorp/hcl/Makefile +++ /dev/null @@ -1,18 +0,0 @@ -TEST?=./... - -default: test - -fmt: generate - go fmt ./... - -test: generate - go get -t ./... - go test $(TEST) $(TESTARGS) - -generate: - go generate ./... - -updatedeps: - go get -u golang.org/x/tools/cmd/stringer - -.PHONY: default generate test updatedeps diff --git a/vendor/github.com/hashicorp/hcl/README.md b/vendor/github.com/hashicorp/hcl/README.md deleted file mode 100644 index c822332..0000000 --- a/vendor/github.com/hashicorp/hcl/README.md +++ /dev/null @@ -1,125 +0,0 @@ -# HCL - -[![GoDoc](https://godoc.org/github.com/hashicorp/hcl?status.png)](https://godoc.org/github.com/hashicorp/hcl) [![Build Status](https://travis-ci.org/hashicorp/hcl.svg?branch=master)](https://travis-ci.org/hashicorp/hcl) - -HCL (HashiCorp Configuration Language) is a configuration language built -by HashiCorp. The goal of HCL is to build a structured configuration language -that is both human and machine friendly for use with command-line tools, but -specifically targeted towards DevOps tools, servers, etc. - -HCL is also fully JSON compatible. That is, JSON can be used as completely -valid input to a system expecting HCL. This helps makes systems -interoperable with other systems. - -HCL is heavily inspired by -[libucl](https://github.com/vstakhov/libucl), -nginx configuration, and others similar. - -## Why? - -A common question when viewing HCL is to ask the question: why not -JSON, YAML, etc.? - -Prior to HCL, the tools we built at [HashiCorp](http://www.hashicorp.com) -used a variety of configuration languages from full programming languages -such as Ruby to complete data structure languages such as JSON. What we -learned is that some people wanted human-friendly configuration languages -and some people wanted machine-friendly languages. - -JSON fits a nice balance in this, but is fairly verbose and most -importantly doesn't support comments. With YAML, we found that beginners -had a really hard time determining what the actual structure was, and -ended up guessing more often than not whether to use a hyphen, colon, etc. -in order to represent some configuration key. - -Full programming languages such as Ruby enable complex behavior -a configuration language shouldn't usually allow, and also forces -people to learn some set of Ruby. - -Because of this, we decided to create our own configuration language -that is JSON-compatible. Our configuration language (HCL) is designed -to be written and modified by humans. The API for HCL allows JSON -as an input so that it is also machine-friendly (machines can generate -JSON instead of trying to generate HCL). - -Our goal with HCL is not to alienate other configuration languages. -It is instead to provide HCL as a specialized language for our tools, -and JSON as the interoperability layer. - -## Syntax - -For a complete grammar, please see the parser itself. A high-level overview -of the syntax and grammar is listed here. - - * Single line comments start with `#` or `//` - - * Multi-line comments are wrapped in `/*` and `*/`. Nested block comments - are not allowed. A multi-line comment (also known as a block comment) - terminates at the first `*/` found. - - * Values are assigned with the syntax `key = value` (whitespace doesn't - matter). The value can be any primitive: a string, number, boolean, - object, or list. - - * Strings are double-quoted and can contain any UTF-8 characters. - Example: `"Hello, World"` - - * Multi-line strings start with `<- - echo %Path% - - go version - - go env - - go get -t ./... - -build_script: -- cmd: go test -v ./... diff --git a/vendor/github.com/hashicorp/hcl/decoder.go b/vendor/github.com/hashicorp/hcl/decoder.go deleted file mode 100644 index bed9ebb..0000000 --- a/vendor/github.com/hashicorp/hcl/decoder.go +++ /dev/null @@ -1,729 +0,0 @@ -package hcl - -import ( - "errors" - "fmt" - "reflect" - "sort" - "strconv" - "strings" - - "github.com/hashicorp/hcl/hcl/ast" - "github.com/hashicorp/hcl/hcl/parser" - "github.com/hashicorp/hcl/hcl/token" -) - -// This is the tag to use with structures to have settings for HCL -const tagName = "hcl" - -var ( - // nodeType holds a reference to the type of ast.Node - nodeType reflect.Type = findNodeType() -) - -// Unmarshal accepts a byte slice as input and writes the -// data to the value pointed to by v. -func Unmarshal(bs []byte, v interface{}) error { - root, err := parse(bs) - if err != nil { - return err - } - - return DecodeObject(v, root) -} - -// Decode reads the given input and decodes it into the structure -// given by `out`. -func Decode(out interface{}, in string) error { - obj, err := Parse(in) - if err != nil { - return err - } - - return DecodeObject(out, obj) -} - -// DecodeObject is a lower-level version of Decode. It decodes a -// raw Object into the given output. -func DecodeObject(out interface{}, n ast.Node) error { - val := reflect.ValueOf(out) - if val.Kind() != reflect.Ptr { - return errors.New("result must be a pointer") - } - - // If we have the file, we really decode the root node - if f, ok := n.(*ast.File); ok { - n = f.Node - } - - var d decoder - return d.decode("root", n, val.Elem()) -} - -type decoder struct { - stack []reflect.Kind -} - -func (d *decoder) decode(name string, node ast.Node, result reflect.Value) error { - k := result - - // If we have an interface with a valid value, we use that - // for the check. - if result.Kind() == reflect.Interface { - elem := result.Elem() - if elem.IsValid() { - k = elem - } - } - - // Push current onto stack unless it is an interface. - if k.Kind() != reflect.Interface { - d.stack = append(d.stack, k.Kind()) - - // Schedule a pop - defer func() { - d.stack = d.stack[:len(d.stack)-1] - }() - } - - switch k.Kind() { - case reflect.Bool: - return d.decodeBool(name, node, result) - case reflect.Float32, reflect.Float64: - return d.decodeFloat(name, node, result) - case reflect.Int, reflect.Int32, reflect.Int64: - return d.decodeInt(name, node, result) - case reflect.Interface: - // When we see an interface, we make our own thing - return d.decodeInterface(name, node, result) - case reflect.Map: - return d.decodeMap(name, node, result) - case reflect.Ptr: - return d.decodePtr(name, node, result) - case reflect.Slice: - return d.decodeSlice(name, node, result) - case reflect.String: - return d.decodeString(name, node, result) - case reflect.Struct: - return d.decodeStruct(name, node, result) - default: - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("%s: unknown kind to decode into: %s", name, k.Kind()), - } - } -} - -func (d *decoder) decodeBool(name string, node ast.Node, result reflect.Value) error { - switch n := node.(type) { - case *ast.LiteralType: - if n.Token.Type == token.BOOL { - v, err := strconv.ParseBool(n.Token.Text) - if err != nil { - return err - } - - result.Set(reflect.ValueOf(v)) - return nil - } - } - - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("%s: unknown type %T", name, node), - } -} - -func (d *decoder) decodeFloat(name string, node ast.Node, result reflect.Value) error { - switch n := node.(type) { - case *ast.LiteralType: - if n.Token.Type == token.FLOAT || n.Token.Type == token.NUMBER { - v, err := strconv.ParseFloat(n.Token.Text, 64) - if err != nil { - return err - } - - result.Set(reflect.ValueOf(v).Convert(result.Type())) - return nil - } - } - - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("%s: unknown type %T", name, node), - } -} - -func (d *decoder) decodeInt(name string, node ast.Node, result reflect.Value) error { - switch n := node.(type) { - case *ast.LiteralType: - switch n.Token.Type { - case token.NUMBER: - v, err := strconv.ParseInt(n.Token.Text, 0, 0) - if err != nil { - return err - } - - if result.Kind() == reflect.Interface { - result.Set(reflect.ValueOf(int(v))) - } else { - result.SetInt(v) - } - return nil - case token.STRING: - v, err := strconv.ParseInt(n.Token.Value().(string), 0, 0) - if err != nil { - return err - } - - if result.Kind() == reflect.Interface { - result.Set(reflect.ValueOf(int(v))) - } else { - result.SetInt(v) - } - return nil - } - } - - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("%s: unknown type %T", name, node), - } -} - -func (d *decoder) decodeInterface(name string, node ast.Node, result reflect.Value) error { - // When we see an ast.Node, we retain the value to enable deferred decoding. - // Very useful in situations where we want to preserve ast.Node information - // like Pos - if result.Type() == nodeType && result.CanSet() { - result.Set(reflect.ValueOf(node)) - return nil - } - - var set reflect.Value - redecode := true - - // For testing types, ObjectType should just be treated as a list. We - // set this to a temporary var because we want to pass in the real node. - testNode := node - if ot, ok := node.(*ast.ObjectType); ok { - testNode = ot.List - } - - switch n := testNode.(type) { - case *ast.ObjectList: - // If we're at the root or we're directly within a slice, then we - // decode objects into map[string]interface{}, otherwise we decode - // them into lists. - if len(d.stack) == 0 || d.stack[len(d.stack)-1] == reflect.Slice { - var temp map[string]interface{} - tempVal := reflect.ValueOf(temp) - result := reflect.MakeMap( - reflect.MapOf( - reflect.TypeOf(""), - tempVal.Type().Elem())) - - set = result - } else { - var temp []map[string]interface{} - tempVal := reflect.ValueOf(temp) - result := reflect.MakeSlice( - reflect.SliceOf(tempVal.Type().Elem()), 0, len(n.Items)) - set = result - } - case *ast.ObjectType: - // If we're at the root or we're directly within a slice, then we - // decode objects into map[string]interface{}, otherwise we decode - // them into lists. - if len(d.stack) == 0 || d.stack[len(d.stack)-1] == reflect.Slice { - var temp map[string]interface{} - tempVal := reflect.ValueOf(temp) - result := reflect.MakeMap( - reflect.MapOf( - reflect.TypeOf(""), - tempVal.Type().Elem())) - - set = result - } else { - var temp []map[string]interface{} - tempVal := reflect.ValueOf(temp) - result := reflect.MakeSlice( - reflect.SliceOf(tempVal.Type().Elem()), 0, 1) - set = result - } - case *ast.ListType: - var temp []interface{} - tempVal := reflect.ValueOf(temp) - result := reflect.MakeSlice( - reflect.SliceOf(tempVal.Type().Elem()), 0, 0) - set = result - case *ast.LiteralType: - switch n.Token.Type { - case token.BOOL: - var result bool - set = reflect.Indirect(reflect.New(reflect.TypeOf(result))) - case token.FLOAT: - var result float64 - set = reflect.Indirect(reflect.New(reflect.TypeOf(result))) - case token.NUMBER: - var result int - set = reflect.Indirect(reflect.New(reflect.TypeOf(result))) - case token.STRING, token.HEREDOC: - set = reflect.Indirect(reflect.New(reflect.TypeOf(""))) - default: - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("%s: cannot decode into interface: %T", name, node), - } - } - default: - return fmt.Errorf( - "%s: cannot decode into interface: %T", - name, node) - } - - // Set the result to what its supposed to be, then reset - // result so we don't reflect into this method anymore. - result.Set(set) - - if redecode { - // Revisit the node so that we can use the newly instantiated - // thing and populate it. - if err := d.decode(name, node, result); err != nil { - return err - } - } - - return nil -} - -func (d *decoder) decodeMap(name string, node ast.Node, result reflect.Value) error { - if item, ok := node.(*ast.ObjectItem); ok { - node = &ast.ObjectList{Items: []*ast.ObjectItem{item}} - } - - if ot, ok := node.(*ast.ObjectType); ok { - node = ot.List - } - - n, ok := node.(*ast.ObjectList) - if !ok { - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("%s: not an object type for map (%T)", name, node), - } - } - - // If we have an interface, then we can address the interface, - // but not the slice itself, so get the element but set the interface - set := result - if result.Kind() == reflect.Interface { - result = result.Elem() - } - - resultType := result.Type() - resultElemType := resultType.Elem() - resultKeyType := resultType.Key() - if resultKeyType.Kind() != reflect.String { - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("%s: map must have string keys", name), - } - } - - // Make a map if it is nil - resultMap := result - if result.IsNil() { - resultMap = reflect.MakeMap( - reflect.MapOf(resultKeyType, resultElemType)) - } - - // Go through each element and decode it. - done := make(map[string]struct{}) - for _, item := range n.Items { - if item.Val == nil { - continue - } - - // github.com/hashicorp/terraform/issue/5740 - if len(item.Keys) == 0 { - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("%s: map must have string keys", name), - } - } - - // Get the key we're dealing with, which is the first item - keyStr := item.Keys[0].Token.Value().(string) - - // If we've already processed this key, then ignore it - if _, ok := done[keyStr]; ok { - continue - } - - // Determine the value. If we have more than one key, then we - // get the objectlist of only these keys. - itemVal := item.Val - if len(item.Keys) > 1 { - itemVal = n.Filter(keyStr) - done[keyStr] = struct{}{} - } - - // Make the field name - fieldName := fmt.Sprintf("%s.%s", name, keyStr) - - // Get the key/value as reflection values - key := reflect.ValueOf(keyStr) - val := reflect.Indirect(reflect.New(resultElemType)) - - // If we have a pre-existing value in the map, use that - oldVal := resultMap.MapIndex(key) - if oldVal.IsValid() { - val.Set(oldVal) - } - - // Decode! - if err := d.decode(fieldName, itemVal, val); err != nil { - return err - } - - // Set the value on the map - resultMap.SetMapIndex(key, val) - } - - // Set the final map if we can - set.Set(resultMap) - return nil -} - -func (d *decoder) decodePtr(name string, node ast.Node, result reflect.Value) error { - // Create an element of the concrete (non pointer) type and decode - // into that. Then set the value of the pointer to this type. - resultType := result.Type() - resultElemType := resultType.Elem() - val := reflect.New(resultElemType) - if err := d.decode(name, node, reflect.Indirect(val)); err != nil { - return err - } - - result.Set(val) - return nil -} - -func (d *decoder) decodeSlice(name string, node ast.Node, result reflect.Value) error { - // If we have an interface, then we can address the interface, - // but not the slice itself, so get the element but set the interface - set := result - if result.Kind() == reflect.Interface { - result = result.Elem() - } - // Create the slice if it isn't nil - resultType := result.Type() - resultElemType := resultType.Elem() - if result.IsNil() { - resultSliceType := reflect.SliceOf(resultElemType) - result = reflect.MakeSlice( - resultSliceType, 0, 0) - } - - // Figure out the items we'll be copying into the slice - var items []ast.Node - switch n := node.(type) { - case *ast.ObjectList: - items = make([]ast.Node, len(n.Items)) - for i, item := range n.Items { - items[i] = item - } - case *ast.ObjectType: - items = []ast.Node{n} - case *ast.ListType: - items = n.List - default: - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("unknown slice type: %T", node), - } - } - - for i, item := range items { - fieldName := fmt.Sprintf("%s[%d]", name, i) - - // Decode - val := reflect.Indirect(reflect.New(resultElemType)) - - // if item is an object that was decoded from ambiguous JSON and - // flattened, make sure it's expanded if it needs to decode into a - // defined structure. - item := expandObject(item, val) - - if err := d.decode(fieldName, item, val); err != nil { - return err - } - - // Append it onto the slice - result = reflect.Append(result, val) - } - - set.Set(result) - return nil -} - -// expandObject detects if an ambiguous JSON object was flattened to a List which -// should be decoded into a struct, and expands the ast to properly deocode. -func expandObject(node ast.Node, result reflect.Value) ast.Node { - item, ok := node.(*ast.ObjectItem) - if !ok { - return node - } - - elemType := result.Type() - - // our target type must be a struct - switch elemType.Kind() { - case reflect.Ptr: - switch elemType.Elem().Kind() { - case reflect.Struct: - //OK - default: - return node - } - case reflect.Struct: - //OK - default: - return node - } - - // A list value will have a key and field name. If it had more fields, - // it wouldn't have been flattened. - if len(item.Keys) != 2 { - return node - } - - keyToken := item.Keys[0].Token - item.Keys = item.Keys[1:] - - // we need to un-flatten the ast enough to decode - newNode := &ast.ObjectItem{ - Keys: []*ast.ObjectKey{ - &ast.ObjectKey{ - Token: keyToken, - }, - }, - Val: &ast.ObjectType{ - List: &ast.ObjectList{ - Items: []*ast.ObjectItem{item}, - }, - }, - } - - return newNode -} - -func (d *decoder) decodeString(name string, node ast.Node, result reflect.Value) error { - switch n := node.(type) { - case *ast.LiteralType: - switch n.Token.Type { - case token.NUMBER: - result.Set(reflect.ValueOf(n.Token.Text).Convert(result.Type())) - return nil - case token.STRING, token.HEREDOC: - result.Set(reflect.ValueOf(n.Token.Value()).Convert(result.Type())) - return nil - } - } - - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("%s: unknown type for string %T", name, node), - } -} - -func (d *decoder) decodeStruct(name string, node ast.Node, result reflect.Value) error { - var item *ast.ObjectItem - if it, ok := node.(*ast.ObjectItem); ok { - item = it - node = it.Val - } - - if ot, ok := node.(*ast.ObjectType); ok { - node = ot.List - } - - // Handle the special case where the object itself is a literal. Previously - // the yacc parser would always ensure top-level elements were arrays. The new - // parser does not make the same guarantees, thus we need to convert any - // top-level literal elements into a list. - if _, ok := node.(*ast.LiteralType); ok && item != nil { - node = &ast.ObjectList{Items: []*ast.ObjectItem{item}} - } - - list, ok := node.(*ast.ObjectList) - if !ok { - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("%s: not an object type for struct (%T)", name, node), - } - } - - // This slice will keep track of all the structs we'll be decoding. - // There can be more than one struct if there are embedded structs - // that are squashed. - structs := make([]reflect.Value, 1, 5) - structs[0] = result - - // Compile the list of all the fields that we're going to be decoding - // from all the structs. - type field struct { - field reflect.StructField - val reflect.Value - } - fields := []field{} - for len(structs) > 0 { - structVal := structs[0] - structs = structs[1:] - - structType := structVal.Type() - for i := 0; i < structType.NumField(); i++ { - fieldType := structType.Field(i) - tagParts := strings.Split(fieldType.Tag.Get(tagName), ",") - - // Ignore fields with tag name "-" - if tagParts[0] == "-" { - continue - } - - if fieldType.Anonymous { - fieldKind := fieldType.Type.Kind() - if fieldKind != reflect.Struct { - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("%s: unsupported type to struct: %s", - fieldType.Name, fieldKind), - } - } - - // We have an embedded field. We "squash" the fields down - // if specified in the tag. - squash := false - for _, tag := range tagParts[1:] { - if tag == "squash" { - squash = true - break - } - } - - if squash { - structs = append( - structs, result.FieldByName(fieldType.Name)) - continue - } - } - - // Normal struct field, store it away - fields = append(fields, field{fieldType, structVal.Field(i)}) - } - } - - usedKeys := make(map[string]struct{}) - decodedFields := make([]string, 0, len(fields)) - decodedFieldsVal := make([]reflect.Value, 0) - unusedKeysVal := make([]reflect.Value, 0) - for _, f := range fields { - field, fieldValue := f.field, f.val - if !fieldValue.IsValid() { - // This should never happen - panic("field is not valid") - } - - // If we can't set the field, then it is unexported or something, - // and we just continue onwards. - if !fieldValue.CanSet() { - continue - } - - fieldName := field.Name - - tagValue := field.Tag.Get(tagName) - tagParts := strings.SplitN(tagValue, ",", 2) - if len(tagParts) >= 2 { - switch tagParts[1] { - case "decodedFields": - decodedFieldsVal = append(decodedFieldsVal, fieldValue) - continue - case "key": - if item == nil { - return &parser.PosError{ - Pos: node.Pos(), - Err: fmt.Errorf("%s: %s asked for 'key', impossible", - name, fieldName), - } - } - - fieldValue.SetString(item.Keys[0].Token.Value().(string)) - continue - case "unusedKeys": - unusedKeysVal = append(unusedKeysVal, fieldValue) - continue - } - } - - if tagParts[0] != "" { - fieldName = tagParts[0] - } - - // Determine the element we'll use to decode. If it is a single - // match (only object with the field), then we decode it exactly. - // If it is a prefix match, then we decode the matches. - filter := list.Filter(fieldName) - - prefixMatches := filter.Children() - matches := filter.Elem() - if len(matches.Items) == 0 && len(prefixMatches.Items) == 0 { - continue - } - - // Track the used key - usedKeys[fieldName] = struct{}{} - - // Create the field name and decode. We range over the elements - // because we actually want the value. - fieldName = fmt.Sprintf("%s.%s", name, fieldName) - if len(prefixMatches.Items) > 0 { - if err := d.decode(fieldName, prefixMatches, fieldValue); err != nil { - return err - } - } - for _, match := range matches.Items { - var decodeNode ast.Node = match.Val - if ot, ok := decodeNode.(*ast.ObjectType); ok { - decodeNode = &ast.ObjectList{Items: ot.List.Items} - } - - if err := d.decode(fieldName, decodeNode, fieldValue); err != nil { - return err - } - } - - decodedFields = append(decodedFields, field.Name) - } - - if len(decodedFieldsVal) > 0 { - // Sort it so that it is deterministic - sort.Strings(decodedFields) - - for _, v := range decodedFieldsVal { - v.Set(reflect.ValueOf(decodedFields)) - } - } - - return nil -} - -// findNodeType returns the type of ast.Node -func findNodeType() reflect.Type { - var nodeContainer struct { - Node ast.Node - } - value := reflect.ValueOf(nodeContainer).FieldByName("Node") - return value.Type() -} diff --git a/vendor/github.com/hashicorp/hcl/go.mod b/vendor/github.com/hashicorp/hcl/go.mod deleted file mode 100644 index 4debbbe..0000000 --- a/vendor/github.com/hashicorp/hcl/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/hashicorp/hcl - -require github.com/davecgh/go-spew v1.1.1 diff --git a/vendor/github.com/hashicorp/hcl/go.sum b/vendor/github.com/hashicorp/hcl/go.sum deleted file mode 100644 index b5e2922..0000000 --- a/vendor/github.com/hashicorp/hcl/go.sum +++ /dev/null @@ -1,2 +0,0 @@ -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= diff --git a/vendor/github.com/hashicorp/hcl/hcl.go b/vendor/github.com/hashicorp/hcl/hcl.go deleted file mode 100644 index 575a20b..0000000 --- a/vendor/github.com/hashicorp/hcl/hcl.go +++ /dev/null @@ -1,11 +0,0 @@ -// Package hcl decodes HCL into usable Go structures. -// -// hcl input can come in either pure HCL format or JSON format. -// It can be parsed into an AST, and then decoded into a structure, -// or it can be decoded directly from a string into a structure. -// -// If you choose to parse HCL into a raw AST, the benefit is that you -// can write custom visitor implementations to implement custom -// semantic checks. By default, HCL does not perform any semantic -// checks. -package hcl diff --git a/vendor/github.com/hashicorp/hcl/hcl/ast/ast.go b/vendor/github.com/hashicorp/hcl/hcl/ast/ast.go deleted file mode 100644 index 6e5ef65..0000000 --- a/vendor/github.com/hashicorp/hcl/hcl/ast/ast.go +++ /dev/null @@ -1,219 +0,0 @@ -// Package ast declares the types used to represent syntax trees for HCL -// (HashiCorp Configuration Language) -package ast - -import ( - "fmt" - "strings" - - "github.com/hashicorp/hcl/hcl/token" -) - -// Node is an element in the abstract syntax tree. -type Node interface { - node() - Pos() token.Pos -} - -func (File) node() {} -func (ObjectList) node() {} -func (ObjectKey) node() {} -func (ObjectItem) node() {} -func (Comment) node() {} -func (CommentGroup) node() {} -func (ObjectType) node() {} -func (LiteralType) node() {} -func (ListType) node() {} - -// File represents a single HCL file -type File struct { - Node Node // usually a *ObjectList - Comments []*CommentGroup // list of all comments in the source -} - -func (f *File) Pos() token.Pos { - return f.Node.Pos() -} - -// ObjectList represents a list of ObjectItems. An HCL file itself is an -// ObjectList. -type ObjectList struct { - Items []*ObjectItem -} - -func (o *ObjectList) Add(item *ObjectItem) { - o.Items = append(o.Items, item) -} - -// Filter filters out the objects with the given key list as a prefix. -// -// The returned list of objects contain ObjectItems where the keys have -// this prefix already stripped off. This might result in objects with -// zero-length key lists if they have no children. -// -// If no matches are found, an empty ObjectList (non-nil) is returned. -func (o *ObjectList) Filter(keys ...string) *ObjectList { - var result ObjectList - for _, item := range o.Items { - // If there aren't enough keys, then ignore this - if len(item.Keys) < len(keys) { - continue - } - - match := true - for i, key := range item.Keys[:len(keys)] { - key := key.Token.Value().(string) - if key != keys[i] && !strings.EqualFold(key, keys[i]) { - match = false - break - } - } - if !match { - continue - } - - // Strip off the prefix from the children - newItem := *item - newItem.Keys = newItem.Keys[len(keys):] - result.Add(&newItem) - } - - return &result -} - -// Children returns further nested objects (key length > 0) within this -// ObjectList. This should be used with Filter to get at child items. -func (o *ObjectList) Children() *ObjectList { - var result ObjectList - for _, item := range o.Items { - if len(item.Keys) > 0 { - result.Add(item) - } - } - - return &result -} - -// Elem returns items in the list that are direct element assignments -// (key length == 0). This should be used with Filter to get at elements. -func (o *ObjectList) Elem() *ObjectList { - var result ObjectList - for _, item := range o.Items { - if len(item.Keys) == 0 { - result.Add(item) - } - } - - return &result -} - -func (o *ObjectList) Pos() token.Pos { - // always returns the uninitiliazed position - return o.Items[0].Pos() -} - -// ObjectItem represents a HCL Object Item. An item is represented with a key -// (or keys). It can be an assignment or an object (both normal and nested) -type ObjectItem struct { - // keys is only one length long if it's of type assignment. If it's a - // nested object it can be larger than one. In that case "assign" is - // invalid as there is no assignments for a nested object. - Keys []*ObjectKey - - // assign contains the position of "=", if any - Assign token.Pos - - // val is the item itself. It can be an object,list, number, bool or a - // string. If key length is larger than one, val can be only of type - // Object. - Val Node - - LeadComment *CommentGroup // associated lead comment - LineComment *CommentGroup // associated line comment -} - -func (o *ObjectItem) Pos() token.Pos { - // I'm not entirely sure what causes this, but removing this causes - // a test failure. We should investigate at some point. - if len(o.Keys) == 0 { - return token.Pos{} - } - - return o.Keys[0].Pos() -} - -// ObjectKeys are either an identifier or of type string. -type ObjectKey struct { - Token token.Token -} - -func (o *ObjectKey) Pos() token.Pos { - return o.Token.Pos -} - -// LiteralType represents a literal of basic type. Valid types are: -// token.NUMBER, token.FLOAT, token.BOOL and token.STRING -type LiteralType struct { - Token token.Token - - // comment types, only used when in a list - LeadComment *CommentGroup - LineComment *CommentGroup -} - -func (l *LiteralType) Pos() token.Pos { - return l.Token.Pos -} - -// ListStatement represents a HCL List type -type ListType struct { - Lbrack token.Pos // position of "[" - Rbrack token.Pos // position of "]" - List []Node // the elements in lexical order -} - -func (l *ListType) Pos() token.Pos { - return l.Lbrack -} - -func (l *ListType) Add(node Node) { - l.List = append(l.List, node) -} - -// ObjectType represents a HCL Object Type -type ObjectType struct { - Lbrace token.Pos // position of "{" - Rbrace token.Pos // position of "}" - List *ObjectList // the nodes in lexical order -} - -func (o *ObjectType) Pos() token.Pos { - return o.Lbrace -} - -// Comment node represents a single //, # style or /*- style commment -type Comment struct { - Start token.Pos // position of / or # - Text string -} - -func (c *Comment) Pos() token.Pos { - return c.Start -} - -// CommentGroup node represents a sequence of comments with no other tokens and -// no empty lines between. -type CommentGroup struct { - List []*Comment // len(List) > 0 -} - -func (c *CommentGroup) Pos() token.Pos { - return c.List[0].Pos() -} - -//------------------------------------------------------------------- -// GoStringer -//------------------------------------------------------------------- - -func (o *ObjectKey) GoString() string { return fmt.Sprintf("*%#v", *o) } -func (o *ObjectList) GoString() string { return fmt.Sprintf("*%#v", *o) } diff --git a/vendor/github.com/hashicorp/hcl/hcl/ast/walk.go b/vendor/github.com/hashicorp/hcl/hcl/ast/walk.go deleted file mode 100644 index ba07ad4..0000000 --- a/vendor/github.com/hashicorp/hcl/hcl/ast/walk.go +++ /dev/null @@ -1,52 +0,0 @@ -package ast - -import "fmt" - -// WalkFunc describes a function to be called for each node during a Walk. The -// returned node can be used to rewrite the AST. Walking stops the returned -// bool is false. -type WalkFunc func(Node) (Node, bool) - -// Walk traverses an AST in depth-first order: It starts by calling fn(node); -// node must not be nil. If fn returns true, Walk invokes fn recursively for -// each of the non-nil children of node, followed by a call of fn(nil). The -// returned node of fn can be used to rewrite the passed node to fn. -func Walk(node Node, fn WalkFunc) Node { - rewritten, ok := fn(node) - if !ok { - return rewritten - } - - switch n := node.(type) { - case *File: - n.Node = Walk(n.Node, fn) - case *ObjectList: - for i, item := range n.Items { - n.Items[i] = Walk(item, fn).(*ObjectItem) - } - case *ObjectKey: - // nothing to do - case *ObjectItem: - for i, k := range n.Keys { - n.Keys[i] = Walk(k, fn).(*ObjectKey) - } - - if n.Val != nil { - n.Val = Walk(n.Val, fn) - } - case *LiteralType: - // nothing to do - case *ListType: - for i, l := range n.List { - n.List[i] = Walk(l, fn) - } - case *ObjectType: - n.List = Walk(n.List, fn).(*ObjectList) - default: - // should we panic here? - fmt.Printf("unknown type: %T\n", n) - } - - fn(nil) - return rewritten -} diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/error.go b/vendor/github.com/hashicorp/hcl/hcl/parser/error.go deleted file mode 100644 index 5c99381..0000000 --- a/vendor/github.com/hashicorp/hcl/hcl/parser/error.go +++ /dev/null @@ -1,17 +0,0 @@ -package parser - -import ( - "fmt" - - "github.com/hashicorp/hcl/hcl/token" -) - -// PosError is a parse error that contains a position. -type PosError struct { - Pos token.Pos - Err error -} - -func (e *PosError) Error() string { - return fmt.Sprintf("At %s: %s", e.Pos, e.Err) -} diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go b/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go deleted file mode 100644 index 64c83bc..0000000 --- a/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go +++ /dev/null @@ -1,532 +0,0 @@ -// Package parser implements a parser for HCL (HashiCorp Configuration -// Language) -package parser - -import ( - "bytes" - "errors" - "fmt" - "strings" - - "github.com/hashicorp/hcl/hcl/ast" - "github.com/hashicorp/hcl/hcl/scanner" - "github.com/hashicorp/hcl/hcl/token" -) - -type Parser struct { - sc *scanner.Scanner - - // Last read token - tok token.Token - commaPrev token.Token - - comments []*ast.CommentGroup - leadComment *ast.CommentGroup // last lead comment - lineComment *ast.CommentGroup // last line comment - - enableTrace bool - indent int - n int // buffer size (max = 1) -} - -func newParser(src []byte) *Parser { - return &Parser{ - sc: scanner.New(src), - } -} - -// Parse returns the fully parsed source and returns the abstract syntax tree. -func Parse(src []byte) (*ast.File, error) { - // normalize all line endings - // since the scanner and output only work with "\n" line endings, we may - // end up with dangling "\r" characters in the parsed data. - src = bytes.Replace(src, []byte("\r\n"), []byte("\n"), -1) - - p := newParser(src) - return p.Parse() -} - -var errEofToken = errors.New("EOF token found") - -// Parse returns the fully parsed source and returns the abstract syntax tree. -func (p *Parser) Parse() (*ast.File, error) { - f := &ast.File{} - var err, scerr error - p.sc.Error = func(pos token.Pos, msg string) { - scerr = &PosError{Pos: pos, Err: errors.New(msg)} - } - - f.Node, err = p.objectList(false) - if scerr != nil { - return nil, scerr - } - if err != nil { - return nil, err - } - - f.Comments = p.comments - return f, nil -} - -// objectList parses a list of items within an object (generally k/v pairs). -// The parameter" obj" tells this whether to we are within an object (braces: -// '{', '}') or just at the top level. If we're within an object, we end -// at an RBRACE. -func (p *Parser) objectList(obj bool) (*ast.ObjectList, error) { - defer un(trace(p, "ParseObjectList")) - node := &ast.ObjectList{} - - for { - if obj { - tok := p.scan() - p.unscan() - if tok.Type == token.RBRACE { - break - } - } - - n, err := p.objectItem() - if err == errEofToken { - break // we are finished - } - - // we don't return a nil node, because might want to use already - // collected items. - if err != nil { - return node, err - } - - node.Add(n) - - // object lists can be optionally comma-delimited e.g. when a list of maps - // is being expressed, so a comma is allowed here - it's simply consumed - tok := p.scan() - if tok.Type != token.COMMA { - p.unscan() - } - } - return node, nil -} - -func (p *Parser) consumeComment() (comment *ast.Comment, endline int) { - endline = p.tok.Pos.Line - - // count the endline if it's multiline comment, ie starting with /* - if len(p.tok.Text) > 1 && p.tok.Text[1] == '*' { - // don't use range here - no need to decode Unicode code points - for i := 0; i < len(p.tok.Text); i++ { - if p.tok.Text[i] == '\n' { - endline++ - } - } - } - - comment = &ast.Comment{Start: p.tok.Pos, Text: p.tok.Text} - p.tok = p.sc.Scan() - return -} - -func (p *Parser) consumeCommentGroup(n int) (comments *ast.CommentGroup, endline int) { - var list []*ast.Comment - endline = p.tok.Pos.Line - - for p.tok.Type == token.COMMENT && p.tok.Pos.Line <= endline+n { - var comment *ast.Comment - comment, endline = p.consumeComment() - list = append(list, comment) - } - - // add comment group to the comments list - comments = &ast.CommentGroup{List: list} - p.comments = append(p.comments, comments) - - return -} - -// objectItem parses a single object item -func (p *Parser) objectItem() (*ast.ObjectItem, error) { - defer un(trace(p, "ParseObjectItem")) - - keys, err := p.objectKey() - if len(keys) > 0 && err == errEofToken { - // We ignore eof token here since it is an error if we didn't - // receive a value (but we did receive a key) for the item. - err = nil - } - if len(keys) > 0 && err != nil && p.tok.Type == token.RBRACE { - // This is a strange boolean statement, but what it means is: - // We have keys with no value, and we're likely in an object - // (since RBrace ends an object). For this, we set err to nil so - // we continue and get the error below of having the wrong value - // type. - err = nil - - // Reset the token type so we don't think it completed fine. See - // objectType which uses p.tok.Type to check if we're done with - // the object. - p.tok.Type = token.EOF - } - if err != nil { - return nil, err - } - - o := &ast.ObjectItem{ - Keys: keys, - } - - if p.leadComment != nil { - o.LeadComment = p.leadComment - p.leadComment = nil - } - - switch p.tok.Type { - case token.ASSIGN: - o.Assign = p.tok.Pos - o.Val, err = p.object() - if err != nil { - return nil, err - } - case token.LBRACE: - o.Val, err = p.objectType() - if err != nil { - return nil, err - } - default: - keyStr := make([]string, 0, len(keys)) - for _, k := range keys { - keyStr = append(keyStr, k.Token.Text) - } - - return nil, &PosError{ - Pos: p.tok.Pos, - Err: fmt.Errorf( - "key '%s' expected start of object ('{') or assignment ('=')", - strings.Join(keyStr, " ")), - } - } - - // key=#comment - // val - if p.lineComment != nil { - o.LineComment, p.lineComment = p.lineComment, nil - } - - // do a look-ahead for line comment - p.scan() - if len(keys) > 0 && o.Val.Pos().Line == keys[0].Pos().Line && p.lineComment != nil { - o.LineComment = p.lineComment - p.lineComment = nil - } - p.unscan() - return o, nil -} - -// objectKey parses an object key and returns a ObjectKey AST -func (p *Parser) objectKey() ([]*ast.ObjectKey, error) { - keyCount := 0 - keys := make([]*ast.ObjectKey, 0) - - for { - tok := p.scan() - switch tok.Type { - case token.EOF: - // It is very important to also return the keys here as well as - // the error. This is because we need to be able to tell if we - // did parse keys prior to finding the EOF, or if we just found - // a bare EOF. - return keys, errEofToken - case token.ASSIGN: - // assignment or object only, but not nested objects. this is not - // allowed: `foo bar = {}` - if keyCount > 1 { - return nil, &PosError{ - Pos: p.tok.Pos, - Err: fmt.Errorf("nested object expected: LBRACE got: %s", p.tok.Type), - } - } - - if keyCount == 0 { - return nil, &PosError{ - Pos: p.tok.Pos, - Err: errors.New("no object keys found!"), - } - } - - return keys, nil - case token.LBRACE: - var err error - - // If we have no keys, then it is a syntax error. i.e. {{}} is not - // allowed. - if len(keys) == 0 { - err = &PosError{ - Pos: p.tok.Pos, - Err: fmt.Errorf("expected: IDENT | STRING got: %s", p.tok.Type), - } - } - - // object - return keys, err - case token.IDENT, token.STRING: - keyCount++ - keys = append(keys, &ast.ObjectKey{Token: p.tok}) - case token.ILLEGAL: - return keys, &PosError{ - Pos: p.tok.Pos, - Err: fmt.Errorf("illegal character"), - } - default: - return keys, &PosError{ - Pos: p.tok.Pos, - Err: fmt.Errorf("expected: IDENT | STRING | ASSIGN | LBRACE got: %s", p.tok.Type), - } - } - } -} - -// object parses any type of object, such as number, bool, string, object or -// list. -func (p *Parser) object() (ast.Node, error) { - defer un(trace(p, "ParseType")) - tok := p.scan() - - switch tok.Type { - case token.NUMBER, token.FLOAT, token.BOOL, token.STRING, token.HEREDOC: - return p.literalType() - case token.LBRACE: - return p.objectType() - case token.LBRACK: - return p.listType() - case token.COMMENT: - // implement comment - case token.EOF: - return nil, errEofToken - } - - return nil, &PosError{ - Pos: tok.Pos, - Err: fmt.Errorf("Unknown token: %+v", tok), - } -} - -// objectType parses an object type and returns a ObjectType AST -func (p *Parser) objectType() (*ast.ObjectType, error) { - defer un(trace(p, "ParseObjectType")) - - // we assume that the currently scanned token is a LBRACE - o := &ast.ObjectType{ - Lbrace: p.tok.Pos, - } - - l, err := p.objectList(true) - - // if we hit RBRACE, we are good to go (means we parsed all Items), if it's - // not a RBRACE, it's an syntax error and we just return it. - if err != nil && p.tok.Type != token.RBRACE { - return nil, err - } - - // No error, scan and expect the ending to be a brace - if tok := p.scan(); tok.Type != token.RBRACE { - return nil, &PosError{ - Pos: tok.Pos, - Err: fmt.Errorf("object expected closing RBRACE got: %s", tok.Type), - } - } - - o.List = l - o.Rbrace = p.tok.Pos // advanced via parseObjectList - return o, nil -} - -// listType parses a list type and returns a ListType AST -func (p *Parser) listType() (*ast.ListType, error) { - defer un(trace(p, "ParseListType")) - - // we assume that the currently scanned token is a LBRACK - l := &ast.ListType{ - Lbrack: p.tok.Pos, - } - - needComma := false - for { - tok := p.scan() - if needComma { - switch tok.Type { - case token.COMMA, token.RBRACK: - default: - return nil, &PosError{ - Pos: tok.Pos, - Err: fmt.Errorf( - "error parsing list, expected comma or list end, got: %s", - tok.Type), - } - } - } - switch tok.Type { - case token.BOOL, token.NUMBER, token.FLOAT, token.STRING, token.HEREDOC: - node, err := p.literalType() - if err != nil { - return nil, err - } - - // If there is a lead comment, apply it - if p.leadComment != nil { - node.LeadComment = p.leadComment - p.leadComment = nil - } - - l.Add(node) - needComma = true - case token.COMMA: - // get next list item or we are at the end - // do a look-ahead for line comment - p.scan() - if p.lineComment != nil && len(l.List) > 0 { - lit, ok := l.List[len(l.List)-1].(*ast.LiteralType) - if ok { - lit.LineComment = p.lineComment - l.List[len(l.List)-1] = lit - p.lineComment = nil - } - } - p.unscan() - - needComma = false - continue - case token.LBRACE: - // Looks like a nested object, so parse it out - node, err := p.objectType() - if err != nil { - return nil, &PosError{ - Pos: tok.Pos, - Err: fmt.Errorf( - "error while trying to parse object within list: %s", err), - } - } - l.Add(node) - needComma = true - case token.LBRACK: - node, err := p.listType() - if err != nil { - return nil, &PosError{ - Pos: tok.Pos, - Err: fmt.Errorf( - "error while trying to parse list within list: %s", err), - } - } - l.Add(node) - case token.RBRACK: - // finished - l.Rbrack = p.tok.Pos - return l, nil - default: - return nil, &PosError{ - Pos: tok.Pos, - Err: fmt.Errorf("unexpected token while parsing list: %s", tok.Type), - } - } - } -} - -// literalType parses a literal type and returns a LiteralType AST -func (p *Parser) literalType() (*ast.LiteralType, error) { - defer un(trace(p, "ParseLiteral")) - - return &ast.LiteralType{ - Token: p.tok, - }, nil -} - -// scan returns the next token from the underlying scanner. If a token has -// been unscanned then read that instead. In the process, it collects any -// comment groups encountered, and remembers the last lead and line comments. -func (p *Parser) scan() token.Token { - // If we have a token on the buffer, then return it. - if p.n != 0 { - p.n = 0 - return p.tok - } - - // Otherwise read the next token from the scanner and Save it to the buffer - // in case we unscan later. - prev := p.tok - p.tok = p.sc.Scan() - - if p.tok.Type == token.COMMENT { - var comment *ast.CommentGroup - var endline int - - // fmt.Printf("p.tok.Pos.Line = %+v prev: %d endline %d \n", - // p.tok.Pos.Line, prev.Pos.Line, endline) - if p.tok.Pos.Line == prev.Pos.Line { - // The comment is on same line as the previous token; it - // cannot be a lead comment but may be a line comment. - comment, endline = p.consumeCommentGroup(0) - if p.tok.Pos.Line != endline { - // The next token is on a different line, thus - // the last comment group is a line comment. - p.lineComment = comment - } - } - - // consume successor comments, if any - endline = -1 - for p.tok.Type == token.COMMENT { - comment, endline = p.consumeCommentGroup(1) - } - - if endline+1 == p.tok.Pos.Line && p.tok.Type != token.RBRACE { - switch p.tok.Type { - case token.RBRACE, token.RBRACK: - // Do not count for these cases - default: - // The next token is following on the line immediately after the - // comment group, thus the last comment group is a lead comment. - p.leadComment = comment - } - } - - } - - return p.tok -} - -// unscan pushes the previously read token back onto the buffer. -func (p *Parser) unscan() { - p.n = 1 -} - -// ---------------------------------------------------------------------------- -// Parsing support - -func (p *Parser) printTrace(a ...interface{}) { - if !p.enableTrace { - return - } - - const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " - const n = len(dots) - fmt.Printf("%5d:%3d: ", p.tok.Pos.Line, p.tok.Pos.Column) - - i := 2 * p.indent - for i > n { - fmt.Print(dots) - i -= n - } - // i <= n - fmt.Print(dots[0:i]) - fmt.Println(a...) -} - -func trace(p *Parser, msg string) *Parser { - p.printTrace(msg, "(") - p.indent++ - return p -} - -// Usage pattern: defer un(trace(p, "...")) -func un(p *Parser) { - p.indent-- - p.printTrace(")") -} diff --git a/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner.go b/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner.go deleted file mode 100644 index 624a18f..0000000 --- a/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner.go +++ /dev/null @@ -1,652 +0,0 @@ -// Package scanner implements a scanner for HCL (HashiCorp Configuration -// Language) source text. -package scanner - -import ( - "bytes" - "fmt" - "os" - "regexp" - "unicode" - "unicode/utf8" - - "github.com/hashicorp/hcl/hcl/token" -) - -// eof represents a marker rune for the end of the reader. -const eof = rune(0) - -// Scanner defines a lexical scanner -type Scanner struct { - buf *bytes.Buffer // Source buffer for advancing and scanning - src []byte // Source buffer for immutable access - - // Source Position - srcPos token.Pos // current position - prevPos token.Pos // previous position, used for peek() method - - lastCharLen int // length of last character in bytes - lastLineLen int // length of last line in characters (for correct column reporting) - - tokStart int // token text start position - tokEnd int // token text end position - - // Error is called for each error encountered. If no Error - // function is set, the error is reported to os.Stderr. - Error func(pos token.Pos, msg string) - - // ErrorCount is incremented by one for each error encountered. - ErrorCount int - - // tokPos is the start position of most recently scanned token; set by - // Scan. The Filename field is always left untouched by the Scanner. If - // an error is reported (via Error) and Position is invalid, the scanner is - // not inside a token. - tokPos token.Pos -} - -// New creates and initializes a new instance of Scanner using src as -// its source content. -func New(src []byte) *Scanner { - // even though we accept a src, we read from a io.Reader compatible type - // (*bytes.Buffer). So in the future we might easily change it to streaming - // read. - b := bytes.NewBuffer(src) - s := &Scanner{ - buf: b, - src: src, - } - - // srcPosition always starts with 1 - s.srcPos.Line = 1 - return s -} - -// next reads the next rune from the bufferred reader. Returns the rune(0) if -// an error occurs (or io.EOF is returned). -func (s *Scanner) next() rune { - ch, size, err := s.buf.ReadRune() - if err != nil { - // advance for error reporting - s.srcPos.Column++ - s.srcPos.Offset += size - s.lastCharLen = size - return eof - } - - // remember last position - s.prevPos = s.srcPos - - s.srcPos.Column++ - s.lastCharLen = size - s.srcPos.Offset += size - - if ch == utf8.RuneError && size == 1 { - s.err("illegal UTF-8 encoding") - return ch - } - - if ch == '\n' { - s.srcPos.Line++ - s.lastLineLen = s.srcPos.Column - s.srcPos.Column = 0 - } - - if ch == '\x00' { - s.err("unexpected null character (0x00)") - return eof - } - - if ch == '\uE123' { - s.err("unicode code point U+E123 reserved for internal use") - return utf8.RuneError - } - - // debug - // fmt.Printf("ch: %q, offset:column: %d:%d\n", ch, s.srcPos.Offset, s.srcPos.Column) - return ch -} - -// unread unreads the previous read Rune and updates the source position -func (s *Scanner) unread() { - if err := s.buf.UnreadRune(); err != nil { - panic(err) // this is user fault, we should catch it - } - s.srcPos = s.prevPos // put back last position -} - -// peek returns the next rune without advancing the reader. -func (s *Scanner) peek() rune { - peek, _, err := s.buf.ReadRune() - if err != nil { - return eof - } - - s.buf.UnreadRune() - return peek -} - -// Scan scans the next token and returns the token. -func (s *Scanner) Scan() token.Token { - ch := s.next() - - // skip white space - for isWhitespace(ch) { - ch = s.next() - } - - var tok token.Type - - // token text markings - s.tokStart = s.srcPos.Offset - s.lastCharLen - - // token position, initial next() is moving the offset by one(size of rune - // actually), though we are interested with the starting point - s.tokPos.Offset = s.srcPos.Offset - s.lastCharLen - if s.srcPos.Column > 0 { - // common case: last character was not a '\n' - s.tokPos.Line = s.srcPos.Line - s.tokPos.Column = s.srcPos.Column - } else { - // last character was a '\n' - // (we cannot be at the beginning of the source - // since we have called next() at least once) - s.tokPos.Line = s.srcPos.Line - 1 - s.tokPos.Column = s.lastLineLen - } - - switch { - case isLetter(ch): - tok = token.IDENT - lit := s.scanIdentifier() - if lit == "true" || lit == "false" { - tok = token.BOOL - } - case isDecimal(ch): - tok = s.scanNumber(ch) - default: - switch ch { - case eof: - tok = token.EOF - case '"': - tok = token.STRING - s.scanString() - case '#', '/': - tok = token.COMMENT - s.scanComment(ch) - case '.': - tok = token.PERIOD - ch = s.peek() - if isDecimal(ch) { - tok = token.FLOAT - ch = s.scanMantissa(ch) - ch = s.scanExponent(ch) - } - case '<': - tok = token.HEREDOC - s.scanHeredoc() - case '[': - tok = token.LBRACK - case ']': - tok = token.RBRACK - case '{': - tok = token.LBRACE - case '}': - tok = token.RBRACE - case ',': - tok = token.COMMA - case '=': - tok = token.ASSIGN - case '+': - tok = token.ADD - case '-': - if isDecimal(s.peek()) { - ch := s.next() - tok = s.scanNumber(ch) - } else { - tok = token.SUB - } - default: - s.err("illegal char") - } - } - - // finish token ending - s.tokEnd = s.srcPos.Offset - - // create token literal - var tokenText string - if s.tokStart >= 0 { - tokenText = string(s.src[s.tokStart:s.tokEnd]) - } - s.tokStart = s.tokEnd // ensure idempotency of tokenText() call - - return token.Token{ - Type: tok, - Pos: s.tokPos, - Text: tokenText, - } -} - -func (s *Scanner) scanComment(ch rune) { - // single line comments - if ch == '#' || (ch == '/' && s.peek() != '*') { - if ch == '/' && s.peek() != '/' { - s.err("expected '/' for comment") - return - } - - ch = s.next() - for ch != '\n' && ch >= 0 && ch != eof { - ch = s.next() - } - if ch != eof && ch >= 0 { - s.unread() - } - return - } - - // be sure we get the character after /* This allows us to find comment's - // that are not erminated - if ch == '/' { - s.next() - ch = s.next() // read character after "/*" - } - - // look for /* - style comments - for { - if ch < 0 || ch == eof { - s.err("comment not terminated") - break - } - - ch0 := ch - ch = s.next() - if ch0 == '*' && ch == '/' { - break - } - } -} - -// scanNumber scans a HCL number definition starting with the given rune -func (s *Scanner) scanNumber(ch rune) token.Type { - if ch == '0' { - // check for hexadecimal, octal or float - ch = s.next() - if ch == 'x' || ch == 'X' { - // hexadecimal - ch = s.next() - found := false - for isHexadecimal(ch) { - ch = s.next() - found = true - } - - if !found { - s.err("illegal hexadecimal number") - } - - if ch != eof { - s.unread() - } - - return token.NUMBER - } - - // now it's either something like: 0421(octal) or 0.1231(float) - illegalOctal := false - for isDecimal(ch) { - ch = s.next() - if ch == '8' || ch == '9' { - // this is just a possibility. For example 0159 is illegal, but - // 0159.23 is valid. So we mark a possible illegal octal. If - // the next character is not a period, we'll print the error. - illegalOctal = true - } - } - - if ch == 'e' || ch == 'E' { - ch = s.scanExponent(ch) - return token.FLOAT - } - - if ch == '.' { - ch = s.scanFraction(ch) - - if ch == 'e' || ch == 'E' { - ch = s.next() - ch = s.scanExponent(ch) - } - return token.FLOAT - } - - if illegalOctal { - s.err("illegal octal number") - } - - if ch != eof { - s.unread() - } - return token.NUMBER - } - - s.scanMantissa(ch) - ch = s.next() // seek forward - if ch == 'e' || ch == 'E' { - ch = s.scanExponent(ch) - return token.FLOAT - } - - if ch == '.' { - ch = s.scanFraction(ch) - if ch == 'e' || ch == 'E' { - ch = s.next() - ch = s.scanExponent(ch) - } - return token.FLOAT - } - - if ch != eof { - s.unread() - } - return token.NUMBER -} - -// scanMantissa scans the mantissa beginning from the rune. It returns the next -// non decimal rune. It's used to determine wheter it's a fraction or exponent. -func (s *Scanner) scanMantissa(ch rune) rune { - scanned := false - for isDecimal(ch) { - ch = s.next() - scanned = true - } - - if scanned && ch != eof { - s.unread() - } - return ch -} - -// scanFraction scans the fraction after the '.' rune -func (s *Scanner) scanFraction(ch rune) rune { - if ch == '.' { - ch = s.peek() // we peek just to see if we can move forward - ch = s.scanMantissa(ch) - } - return ch -} - -// scanExponent scans the remaining parts of an exponent after the 'e' or 'E' -// rune. -func (s *Scanner) scanExponent(ch rune) rune { - if ch == 'e' || ch == 'E' { - ch = s.next() - if ch == '-' || ch == '+' { - ch = s.next() - } - ch = s.scanMantissa(ch) - } - return ch -} - -// scanHeredoc scans a heredoc string -func (s *Scanner) scanHeredoc() { - // Scan the second '<' in example: '<= len(identBytes) && identRegexp.Match(s.src[lineStart:s.srcPos.Offset-s.lastCharLen]) { - break - } - - // Not an anchor match, record the start of a new line - lineStart = s.srcPos.Offset - } - - if ch == eof { - s.err("heredoc not terminated") - return - } - } - - return -} - -// scanString scans a quoted string -func (s *Scanner) scanString() { - braces := 0 - for { - // '"' opening already consumed - // read character after quote - ch := s.next() - - if (ch == '\n' && braces == 0) || ch < 0 || ch == eof { - s.err("literal not terminated") - return - } - - if ch == '"' && braces == 0 { - break - } - - // If we're going into a ${} then we can ignore quotes for awhile - if braces == 0 && ch == '$' && s.peek() == '{' { - braces++ - s.next() - } else if braces > 0 && ch == '{' { - braces++ - } - if braces > 0 && ch == '}' { - braces-- - } - - if ch == '\\' { - s.scanEscape() - } - } - - return -} - -// scanEscape scans an escape sequence -func (s *Scanner) scanEscape() rune { - // http://en.cppreference.com/w/cpp/language/escape - ch := s.next() // read character after '/' - switch ch { - case 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', '"': - // nothing to do - case '0', '1', '2', '3', '4', '5', '6', '7': - // octal notation - ch = s.scanDigits(ch, 8, 3) - case 'x': - // hexademical notation - ch = s.scanDigits(s.next(), 16, 2) - case 'u': - // universal character name - ch = s.scanDigits(s.next(), 16, 4) - case 'U': - // universal character name - ch = s.scanDigits(s.next(), 16, 8) - default: - s.err("illegal char escape") - } - return ch -} - -// scanDigits scans a rune with the given base for n times. For example an -// octal notation \184 would yield in scanDigits(ch, 8, 3) -func (s *Scanner) scanDigits(ch rune, base, n int) rune { - start := n - for n > 0 && digitVal(ch) < base { - ch = s.next() - if ch == eof { - // If we see an EOF, we halt any more scanning of digits - // immediately. - break - } - - n-- - } - if n > 0 { - s.err("illegal char escape") - } - - if n != start && ch != eof { - // we scanned all digits, put the last non digit char back, - // only if we read anything at all - s.unread() - } - - return ch -} - -// scanIdentifier scans an identifier and returns the literal string -func (s *Scanner) scanIdentifier() string { - offs := s.srcPos.Offset - s.lastCharLen - ch := s.next() - for isLetter(ch) || isDigit(ch) || ch == '-' || ch == '.' { - ch = s.next() - } - - if ch != eof { - s.unread() // we got identifier, put back latest char - } - - return string(s.src[offs:s.srcPos.Offset]) -} - -// recentPosition returns the position of the character immediately after the -// character or token returned by the last call to Scan. -func (s *Scanner) recentPosition() (pos token.Pos) { - pos.Offset = s.srcPos.Offset - s.lastCharLen - switch { - case s.srcPos.Column > 0: - // common case: last character was not a '\n' - pos.Line = s.srcPos.Line - pos.Column = s.srcPos.Column - case s.lastLineLen > 0: - // last character was a '\n' - // (we cannot be at the beginning of the source - // since we have called next() at least once) - pos.Line = s.srcPos.Line - 1 - pos.Column = s.lastLineLen - default: - // at the beginning of the source - pos.Line = 1 - pos.Column = 1 - } - return -} - -// err prints the error of any scanning to s.Error function. If the function is -// not defined, by default it prints them to os.Stderr -func (s *Scanner) err(msg string) { - s.ErrorCount++ - pos := s.recentPosition() - - if s.Error != nil { - s.Error(pos, msg) - return - } - - fmt.Fprintf(os.Stderr, "%s: %s\n", pos, msg) -} - -// isHexadecimal returns true if the given rune is a letter -func isLetter(ch rune) bool { - return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch) -} - -// isDigit returns true if the given rune is a decimal digit -func isDigit(ch rune) bool { - return '0' <= ch && ch <= '9' || ch >= 0x80 && unicode.IsDigit(ch) -} - -// isDecimal returns true if the given rune is a decimal number -func isDecimal(ch rune) bool { - return '0' <= ch && ch <= '9' -} - -// isHexadecimal returns true if the given rune is an hexadecimal number -func isHexadecimal(ch rune) bool { - return '0' <= ch && ch <= '9' || 'a' <= ch && ch <= 'f' || 'A' <= ch && ch <= 'F' -} - -// isWhitespace returns true if the rune is a space, tab, newline or carriage return -func isWhitespace(ch rune) bool { - return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' -} - -// digitVal returns the integer value of a given octal,decimal or hexadecimal rune -func digitVal(ch rune) int { - switch { - case '0' <= ch && ch <= '9': - return int(ch - '0') - case 'a' <= ch && ch <= 'f': - return int(ch - 'a' + 10) - case 'A' <= ch && ch <= 'F': - return int(ch - 'A' + 10) - } - return 16 // larger than any legal digit val -} diff --git a/vendor/github.com/hashicorp/hcl/hcl/strconv/quote.go b/vendor/github.com/hashicorp/hcl/hcl/strconv/quote.go deleted file mode 100644 index 5f981ea..0000000 --- a/vendor/github.com/hashicorp/hcl/hcl/strconv/quote.go +++ /dev/null @@ -1,241 +0,0 @@ -package strconv - -import ( - "errors" - "unicode/utf8" -) - -// ErrSyntax indicates that a value does not have the right syntax for the target type. -var ErrSyntax = errors.New("invalid syntax") - -// Unquote interprets s as a single-quoted, double-quoted, -// or backquoted Go string literal, returning the string value -// that s quotes. (If s is single-quoted, it would be a Go -// character literal; Unquote returns the corresponding -// one-character string.) -func Unquote(s string) (t string, err error) { - n := len(s) - if n < 2 { - return "", ErrSyntax - } - quote := s[0] - if quote != s[n-1] { - return "", ErrSyntax - } - s = s[1 : n-1] - - if quote != '"' { - return "", ErrSyntax - } - if !contains(s, '$') && !contains(s, '{') && contains(s, '\n') { - return "", ErrSyntax - } - - // Is it trivial? Avoid allocation. - if !contains(s, '\\') && !contains(s, quote) && !contains(s, '$') { - switch quote { - case '"': - return s, nil - case '\'': - r, size := utf8.DecodeRuneInString(s) - if size == len(s) && (r != utf8.RuneError || size != 1) { - return s, nil - } - } - } - - var runeTmp [utf8.UTFMax]byte - buf := make([]byte, 0, 3*len(s)/2) // Try to avoid more allocations. - for len(s) > 0 { - // If we're starting a '${}' then let it through un-unquoted. - // Specifically: we don't unquote any characters within the `${}` - // section. - if s[0] == '$' && len(s) > 1 && s[1] == '{' { - buf = append(buf, '$', '{') - s = s[2:] - - // Continue reading until we find the closing brace, copying as-is - braces := 1 - for len(s) > 0 && braces > 0 { - r, size := utf8.DecodeRuneInString(s) - if r == utf8.RuneError { - return "", ErrSyntax - } - - s = s[size:] - - n := utf8.EncodeRune(runeTmp[:], r) - buf = append(buf, runeTmp[:n]...) - - switch r { - case '{': - braces++ - case '}': - braces-- - } - } - if braces != 0 { - return "", ErrSyntax - } - if len(s) == 0 { - // If there's no string left, we're done! - break - } else { - // If there's more left, we need to pop back up to the top of the loop - // in case there's another interpolation in this string. - continue - } - } - - if s[0] == '\n' { - return "", ErrSyntax - } - - c, multibyte, ss, err := unquoteChar(s, quote) - if err != nil { - return "", err - } - s = ss - if c < utf8.RuneSelf || !multibyte { - buf = append(buf, byte(c)) - } else { - n := utf8.EncodeRune(runeTmp[:], c) - buf = append(buf, runeTmp[:n]...) - } - if quote == '\'' && len(s) != 0 { - // single-quoted must be single character - return "", ErrSyntax - } - } - return string(buf), nil -} - -// contains reports whether the string contains the byte c. -func contains(s string, c byte) bool { - for i := 0; i < len(s); i++ { - if s[i] == c { - return true - } - } - return false -} - -func unhex(b byte) (v rune, ok bool) { - c := rune(b) - switch { - case '0' <= c && c <= '9': - return c - '0', true - case 'a' <= c && c <= 'f': - return c - 'a' + 10, true - case 'A' <= c && c <= 'F': - return c - 'A' + 10, true - } - return -} - -func unquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, err error) { - // easy cases - switch c := s[0]; { - case c == quote && (quote == '\'' || quote == '"'): - err = ErrSyntax - return - case c >= utf8.RuneSelf: - r, size := utf8.DecodeRuneInString(s) - return r, true, s[size:], nil - case c != '\\': - return rune(s[0]), false, s[1:], nil - } - - // hard case: c is backslash - if len(s) <= 1 { - err = ErrSyntax - return - } - c := s[1] - s = s[2:] - - switch c { - case 'a': - value = '\a' - case 'b': - value = '\b' - case 'f': - value = '\f' - case 'n': - value = '\n' - case 'r': - value = '\r' - case 't': - value = '\t' - case 'v': - value = '\v' - case 'x', 'u', 'U': - n := 0 - switch c { - case 'x': - n = 2 - case 'u': - n = 4 - case 'U': - n = 8 - } - var v rune - if len(s) < n { - err = ErrSyntax - return - } - for j := 0; j < n; j++ { - x, ok := unhex(s[j]) - if !ok { - err = ErrSyntax - return - } - v = v<<4 | x - } - s = s[n:] - if c == 'x' { - // single-byte string, possibly not UTF-8 - value = v - break - } - if v > utf8.MaxRune { - err = ErrSyntax - return - } - value = v - multibyte = true - case '0', '1', '2', '3', '4', '5', '6', '7': - v := rune(c) - '0' - if len(s) < 2 { - err = ErrSyntax - return - } - for j := 0; j < 2; j++ { // one digit already; two more - x := rune(s[j]) - '0' - if x < 0 || x > 7 { - err = ErrSyntax - return - } - v = (v << 3) | x - } - s = s[2:] - if v > 255 { - err = ErrSyntax - return - } - value = v - case '\\': - value = '\\' - case '\'', '"': - if c != quote { - err = ErrSyntax - return - } - value = rune(c) - default: - err = ErrSyntax - return - } - tail = s - return -} diff --git a/vendor/github.com/hashicorp/hcl/hcl/token/position.go b/vendor/github.com/hashicorp/hcl/hcl/token/position.go deleted file mode 100644 index 59c1bb7..0000000 --- a/vendor/github.com/hashicorp/hcl/hcl/token/position.go +++ /dev/null @@ -1,46 +0,0 @@ -package token - -import "fmt" - -// Pos describes an arbitrary source position -// including the file, line, and column location. -// A Position is valid if the line number is > 0. -type Pos struct { - Filename string // filename, if any - Offset int // offset, starting at 0 - Line int // line number, starting at 1 - Column int // column number, starting at 1 (character count) -} - -// IsValid returns true if the position is valid. -func (p *Pos) IsValid() bool { return p.Line > 0 } - -// String returns a string in one of several forms: -// -// file:line:column valid position with file name -// line:column valid position without file name -// file invalid position with file name -// - invalid position without file name -func (p Pos) String() string { - s := p.Filename - if p.IsValid() { - if s != "" { - s += ":" - } - s += fmt.Sprintf("%d:%d", p.Line, p.Column) - } - if s == "" { - s = "-" - } - return s -} - -// Before reports whether the position p is before u. -func (p Pos) Before(u Pos) bool { - return u.Offset > p.Offset || u.Line > p.Line -} - -// After reports whether the position p is after u. -func (p Pos) After(u Pos) bool { - return u.Offset < p.Offset || u.Line < p.Line -} diff --git a/vendor/github.com/hashicorp/hcl/hcl/token/token.go b/vendor/github.com/hashicorp/hcl/hcl/token/token.go deleted file mode 100644 index e37c066..0000000 --- a/vendor/github.com/hashicorp/hcl/hcl/token/token.go +++ /dev/null @@ -1,219 +0,0 @@ -// Package token defines constants representing the lexical tokens for HCL -// (HashiCorp Configuration Language) -package token - -import ( - "fmt" - "strconv" - "strings" - - hclstrconv "github.com/hashicorp/hcl/hcl/strconv" -) - -// Token defines a single HCL token which can be obtained via the Scanner -type Token struct { - Type Type - Pos Pos - Text string - JSON bool -} - -// Type is the set of lexical tokens of the HCL (HashiCorp Configuration Language) -type Type int - -const ( - // Special tokens - ILLEGAL Type = iota - EOF - COMMENT - - identifier_beg - IDENT // literals - literal_beg - NUMBER // 12345 - FLOAT // 123.45 - BOOL // true,false - STRING // "abc" - HEREDOC // < 0 { - // Pop the current item - n := len(frontier) - item := frontier[n-1] - frontier = frontier[:n-1] - - switch v := item.Val.(type) { - case *ast.ObjectType: - items, frontier = flattenObjectType(v, item, items, frontier) - case *ast.ListType: - items, frontier = flattenListType(v, item, items, frontier) - default: - items = append(items, item) - } - } - - // Reverse the list since the frontier model runs things backwards - for i := len(items)/2 - 1; i >= 0; i-- { - opp := len(items) - 1 - i - items[i], items[opp] = items[opp], items[i] - } - - // Done! Set the original items - list.Items = items - return n, true - }) -} - -func flattenListType( - ot *ast.ListType, - item *ast.ObjectItem, - items []*ast.ObjectItem, - frontier []*ast.ObjectItem) ([]*ast.ObjectItem, []*ast.ObjectItem) { - // If the list is empty, keep the original list - if len(ot.List) == 0 { - items = append(items, item) - return items, frontier - } - - // All the elements of this object must also be objects! - for _, subitem := range ot.List { - if _, ok := subitem.(*ast.ObjectType); !ok { - items = append(items, item) - return items, frontier - } - } - - // Great! We have a match go through all the items and flatten - for _, elem := range ot.List { - // Add it to the frontier so that we can recurse - frontier = append(frontier, &ast.ObjectItem{ - Keys: item.Keys, - Assign: item.Assign, - Val: elem, - LeadComment: item.LeadComment, - LineComment: item.LineComment, - }) - } - - return items, frontier -} - -func flattenObjectType( - ot *ast.ObjectType, - item *ast.ObjectItem, - items []*ast.ObjectItem, - frontier []*ast.ObjectItem) ([]*ast.ObjectItem, []*ast.ObjectItem) { - // If the list has no items we do not have to flatten anything - if ot.List.Items == nil { - items = append(items, item) - return items, frontier - } - - // All the elements of this object must also be objects! - for _, subitem := range ot.List.Items { - if _, ok := subitem.Val.(*ast.ObjectType); !ok { - items = append(items, item) - return items, frontier - } - } - - // Great! We have a match go through all the items and flatten - for _, subitem := range ot.List.Items { - // Copy the new key - keys := make([]*ast.ObjectKey, len(item.Keys)+len(subitem.Keys)) - copy(keys, item.Keys) - copy(keys[len(item.Keys):], subitem.Keys) - - // Add it to the frontier so that we can recurse - frontier = append(frontier, &ast.ObjectItem{ - Keys: keys, - Assign: item.Assign, - Val: subitem.Val, - LeadComment: item.LeadComment, - LineComment: item.LineComment, - }) - } - - return items, frontier -} diff --git a/vendor/github.com/hashicorp/hcl/json/parser/parser.go b/vendor/github.com/hashicorp/hcl/json/parser/parser.go deleted file mode 100644 index 125a5f0..0000000 --- a/vendor/github.com/hashicorp/hcl/json/parser/parser.go +++ /dev/null @@ -1,313 +0,0 @@ -package parser - -import ( - "errors" - "fmt" - - "github.com/hashicorp/hcl/hcl/ast" - hcltoken "github.com/hashicorp/hcl/hcl/token" - "github.com/hashicorp/hcl/json/scanner" - "github.com/hashicorp/hcl/json/token" -) - -type Parser struct { - sc *scanner.Scanner - - // Last read token - tok token.Token - commaPrev token.Token - - enableTrace bool - indent int - n int // buffer size (max = 1) -} - -func newParser(src []byte) *Parser { - return &Parser{ - sc: scanner.New(src), - } -} - -// Parse returns the fully parsed source and returns the abstract syntax tree. -func Parse(src []byte) (*ast.File, error) { - p := newParser(src) - return p.Parse() -} - -var errEofToken = errors.New("EOF token found") - -// Parse returns the fully parsed source and returns the abstract syntax tree. -func (p *Parser) Parse() (*ast.File, error) { - f := &ast.File{} - var err, scerr error - p.sc.Error = func(pos token.Pos, msg string) { - scerr = fmt.Errorf("%s: %s", pos, msg) - } - - // The root must be an object in JSON - object, err := p.object() - if scerr != nil { - return nil, scerr - } - if err != nil { - return nil, err - } - - // We make our final node an object list so it is more HCL compatible - f.Node = object.List - - // Flatten it, which finds patterns and turns them into more HCL-like - // AST trees. - flattenObjects(f.Node) - - return f, nil -} - -func (p *Parser) objectList() (*ast.ObjectList, error) { - defer un(trace(p, "ParseObjectList")) - node := &ast.ObjectList{} - - for { - n, err := p.objectItem() - if err == errEofToken { - break // we are finished - } - - // we don't return a nil node, because might want to use already - // collected items. - if err != nil { - return node, err - } - - node.Add(n) - - // Check for a followup comma. If it isn't a comma, then we're done - if tok := p.scan(); tok.Type != token.COMMA { - break - } - } - - return node, nil -} - -// objectItem parses a single object item -func (p *Parser) objectItem() (*ast.ObjectItem, error) { - defer un(trace(p, "ParseObjectItem")) - - keys, err := p.objectKey() - if err != nil { - return nil, err - } - - o := &ast.ObjectItem{ - Keys: keys, - } - - switch p.tok.Type { - case token.COLON: - pos := p.tok.Pos - o.Assign = hcltoken.Pos{ - Filename: pos.Filename, - Offset: pos.Offset, - Line: pos.Line, - Column: pos.Column, - } - - o.Val, err = p.objectValue() - if err != nil { - return nil, err - } - } - - return o, nil -} - -// objectKey parses an object key and returns a ObjectKey AST -func (p *Parser) objectKey() ([]*ast.ObjectKey, error) { - keyCount := 0 - keys := make([]*ast.ObjectKey, 0) - - for { - tok := p.scan() - switch tok.Type { - case token.EOF: - return nil, errEofToken - case token.STRING: - keyCount++ - keys = append(keys, &ast.ObjectKey{ - Token: p.tok.HCLToken(), - }) - case token.COLON: - // If we have a zero keycount it means that we never got - // an object key, i.e. `{ :`. This is a syntax error. - if keyCount == 0 { - return nil, fmt.Errorf("expected: STRING got: %s", p.tok.Type) - } - - // Done - return keys, nil - case token.ILLEGAL: - return nil, errors.New("illegal") - default: - return nil, fmt.Errorf("expected: STRING got: %s", p.tok.Type) - } - } -} - -// object parses any type of object, such as number, bool, string, object or -// list. -func (p *Parser) objectValue() (ast.Node, error) { - defer un(trace(p, "ParseObjectValue")) - tok := p.scan() - - switch tok.Type { - case token.NUMBER, token.FLOAT, token.BOOL, token.NULL, token.STRING: - return p.literalType() - case token.LBRACE: - return p.objectType() - case token.LBRACK: - return p.listType() - case token.EOF: - return nil, errEofToken - } - - return nil, fmt.Errorf("Expected object value, got unknown token: %+v", tok) -} - -// object parses any type of object, such as number, bool, string, object or -// list. -func (p *Parser) object() (*ast.ObjectType, error) { - defer un(trace(p, "ParseType")) - tok := p.scan() - - switch tok.Type { - case token.LBRACE: - return p.objectType() - case token.EOF: - return nil, errEofToken - } - - return nil, fmt.Errorf("Expected object, got unknown token: %+v", tok) -} - -// objectType parses an object type and returns a ObjectType AST -func (p *Parser) objectType() (*ast.ObjectType, error) { - defer un(trace(p, "ParseObjectType")) - - // we assume that the currently scanned token is a LBRACE - o := &ast.ObjectType{} - - l, err := p.objectList() - - // if we hit RBRACE, we are good to go (means we parsed all Items), if it's - // not a RBRACE, it's an syntax error and we just return it. - if err != nil && p.tok.Type != token.RBRACE { - return nil, err - } - - o.List = l - return o, nil -} - -// listType parses a list type and returns a ListType AST -func (p *Parser) listType() (*ast.ListType, error) { - defer un(trace(p, "ParseListType")) - - // we assume that the currently scanned token is a LBRACK - l := &ast.ListType{} - - for { - tok := p.scan() - switch tok.Type { - case token.NUMBER, token.FLOAT, token.STRING: - node, err := p.literalType() - if err != nil { - return nil, err - } - - l.Add(node) - case token.COMMA: - continue - case token.LBRACE: - node, err := p.objectType() - if err != nil { - return nil, err - } - - l.Add(node) - case token.BOOL: - // TODO(arslan) should we support? not supported by HCL yet - case token.LBRACK: - // TODO(arslan) should we support nested lists? Even though it's - // written in README of HCL, it's not a part of the grammar - // (not defined in parse.y) - case token.RBRACK: - // finished - return l, nil - default: - return nil, fmt.Errorf("unexpected token while parsing list: %s", tok.Type) - } - - } -} - -// literalType parses a literal type and returns a LiteralType AST -func (p *Parser) literalType() (*ast.LiteralType, error) { - defer un(trace(p, "ParseLiteral")) - - return &ast.LiteralType{ - Token: p.tok.HCLToken(), - }, nil -} - -// scan returns the next token from the underlying scanner. If a token has -// been unscanned then read that instead. -func (p *Parser) scan() token.Token { - // If we have a token on the buffer, then return it. - if p.n != 0 { - p.n = 0 - return p.tok - } - - p.tok = p.sc.Scan() - return p.tok -} - -// unscan pushes the previously read token back onto the buffer. -func (p *Parser) unscan() { - p.n = 1 -} - -// ---------------------------------------------------------------------------- -// Parsing support - -func (p *Parser) printTrace(a ...interface{}) { - if !p.enableTrace { - return - } - - const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " - const n = len(dots) - fmt.Printf("%5d:%3d: ", p.tok.Pos.Line, p.tok.Pos.Column) - - i := 2 * p.indent - for i > n { - fmt.Print(dots) - i -= n - } - // i <= n - fmt.Print(dots[0:i]) - fmt.Println(a...) -} - -func trace(p *Parser, msg string) *Parser { - p.printTrace(msg, "(") - p.indent++ - return p -} - -// Usage pattern: defer un(trace(p, "...")) -func un(p *Parser) { - p.indent-- - p.printTrace(")") -} diff --git a/vendor/github.com/hashicorp/hcl/json/scanner/scanner.go b/vendor/github.com/hashicorp/hcl/json/scanner/scanner.go deleted file mode 100644 index fe3f0f0..0000000 --- a/vendor/github.com/hashicorp/hcl/json/scanner/scanner.go +++ /dev/null @@ -1,451 +0,0 @@ -package scanner - -import ( - "bytes" - "fmt" - "os" - "unicode" - "unicode/utf8" - - "github.com/hashicorp/hcl/json/token" -) - -// eof represents a marker rune for the end of the reader. -const eof = rune(0) - -// Scanner defines a lexical scanner -type Scanner struct { - buf *bytes.Buffer // Source buffer for advancing and scanning - src []byte // Source buffer for immutable access - - // Source Position - srcPos token.Pos // current position - prevPos token.Pos // previous position, used for peek() method - - lastCharLen int // length of last character in bytes - lastLineLen int // length of last line in characters (for correct column reporting) - - tokStart int // token text start position - tokEnd int // token text end position - - // Error is called for each error encountered. If no Error - // function is set, the error is reported to os.Stderr. - Error func(pos token.Pos, msg string) - - // ErrorCount is incremented by one for each error encountered. - ErrorCount int - - // tokPos is the start position of most recently scanned token; set by - // Scan. The Filename field is always left untouched by the Scanner. If - // an error is reported (via Error) and Position is invalid, the scanner is - // not inside a token. - tokPos token.Pos -} - -// New creates and initializes a new instance of Scanner using src as -// its source content. -func New(src []byte) *Scanner { - // even though we accept a src, we read from a io.Reader compatible type - // (*bytes.Buffer). So in the future we might easily change it to streaming - // read. - b := bytes.NewBuffer(src) - s := &Scanner{ - buf: b, - src: src, - } - - // srcPosition always starts with 1 - s.srcPos.Line = 1 - return s -} - -// next reads the next rune from the bufferred reader. Returns the rune(0) if -// an error occurs (or io.EOF is returned). -func (s *Scanner) next() rune { - ch, size, err := s.buf.ReadRune() - if err != nil { - // advance for error reporting - s.srcPos.Column++ - s.srcPos.Offset += size - s.lastCharLen = size - return eof - } - - if ch == utf8.RuneError && size == 1 { - s.srcPos.Column++ - s.srcPos.Offset += size - s.lastCharLen = size - s.err("illegal UTF-8 encoding") - return ch - } - - // remember last position - s.prevPos = s.srcPos - - s.srcPos.Column++ - s.lastCharLen = size - s.srcPos.Offset += size - - if ch == '\n' { - s.srcPos.Line++ - s.lastLineLen = s.srcPos.Column - s.srcPos.Column = 0 - } - - // debug - // fmt.Printf("ch: %q, offset:column: %d:%d\n", ch, s.srcPos.Offset, s.srcPos.Column) - return ch -} - -// unread unreads the previous read Rune and updates the source position -func (s *Scanner) unread() { - if err := s.buf.UnreadRune(); err != nil { - panic(err) // this is user fault, we should catch it - } - s.srcPos = s.prevPos // put back last position -} - -// peek returns the next rune without advancing the reader. -func (s *Scanner) peek() rune { - peek, _, err := s.buf.ReadRune() - if err != nil { - return eof - } - - s.buf.UnreadRune() - return peek -} - -// Scan scans the next token and returns the token. -func (s *Scanner) Scan() token.Token { - ch := s.next() - - // skip white space - for isWhitespace(ch) { - ch = s.next() - } - - var tok token.Type - - // token text markings - s.tokStart = s.srcPos.Offset - s.lastCharLen - - // token position, initial next() is moving the offset by one(size of rune - // actually), though we are interested with the starting point - s.tokPos.Offset = s.srcPos.Offset - s.lastCharLen - if s.srcPos.Column > 0 { - // common case: last character was not a '\n' - s.tokPos.Line = s.srcPos.Line - s.tokPos.Column = s.srcPos.Column - } else { - // last character was a '\n' - // (we cannot be at the beginning of the source - // since we have called next() at least once) - s.tokPos.Line = s.srcPos.Line - 1 - s.tokPos.Column = s.lastLineLen - } - - switch { - case isLetter(ch): - lit := s.scanIdentifier() - if lit == "true" || lit == "false" { - tok = token.BOOL - } else if lit == "null" { - tok = token.NULL - } else { - s.err("illegal char") - } - case isDecimal(ch): - tok = s.scanNumber(ch) - default: - switch ch { - case eof: - tok = token.EOF - case '"': - tok = token.STRING - s.scanString() - case '.': - tok = token.PERIOD - ch = s.peek() - if isDecimal(ch) { - tok = token.FLOAT - ch = s.scanMantissa(ch) - ch = s.scanExponent(ch) - } - case '[': - tok = token.LBRACK - case ']': - tok = token.RBRACK - case '{': - tok = token.LBRACE - case '}': - tok = token.RBRACE - case ',': - tok = token.COMMA - case ':': - tok = token.COLON - case '-': - if isDecimal(s.peek()) { - ch := s.next() - tok = s.scanNumber(ch) - } else { - s.err("illegal char") - } - default: - s.err("illegal char: " + string(ch)) - } - } - - // finish token ending - s.tokEnd = s.srcPos.Offset - - // create token literal - var tokenText string - if s.tokStart >= 0 { - tokenText = string(s.src[s.tokStart:s.tokEnd]) - } - s.tokStart = s.tokEnd // ensure idempotency of tokenText() call - - return token.Token{ - Type: tok, - Pos: s.tokPos, - Text: tokenText, - } -} - -// scanNumber scans a HCL number definition starting with the given rune -func (s *Scanner) scanNumber(ch rune) token.Type { - zero := ch == '0' - pos := s.srcPos - - s.scanMantissa(ch) - ch = s.next() // seek forward - if ch == 'e' || ch == 'E' { - ch = s.scanExponent(ch) - return token.FLOAT - } - - if ch == '.' { - ch = s.scanFraction(ch) - if ch == 'e' || ch == 'E' { - ch = s.next() - ch = s.scanExponent(ch) - } - return token.FLOAT - } - - if ch != eof { - s.unread() - } - - // If we have a larger number and this is zero, error - if zero && pos != s.srcPos { - s.err("numbers cannot start with 0") - } - - return token.NUMBER -} - -// scanMantissa scans the mantissa beginning from the rune. It returns the next -// non decimal rune. It's used to determine wheter it's a fraction or exponent. -func (s *Scanner) scanMantissa(ch rune) rune { - scanned := false - for isDecimal(ch) { - ch = s.next() - scanned = true - } - - if scanned && ch != eof { - s.unread() - } - return ch -} - -// scanFraction scans the fraction after the '.' rune -func (s *Scanner) scanFraction(ch rune) rune { - if ch == '.' { - ch = s.peek() // we peek just to see if we can move forward - ch = s.scanMantissa(ch) - } - return ch -} - -// scanExponent scans the remaining parts of an exponent after the 'e' or 'E' -// rune. -func (s *Scanner) scanExponent(ch rune) rune { - if ch == 'e' || ch == 'E' { - ch = s.next() - if ch == '-' || ch == '+' { - ch = s.next() - } - ch = s.scanMantissa(ch) - } - return ch -} - -// scanString scans a quoted string -func (s *Scanner) scanString() { - braces := 0 - for { - // '"' opening already consumed - // read character after quote - ch := s.next() - - if ch == '\n' || ch < 0 || ch == eof { - s.err("literal not terminated") - return - } - - if ch == '"' { - break - } - - // If we're going into a ${} then we can ignore quotes for awhile - if braces == 0 && ch == '$' && s.peek() == '{' { - braces++ - s.next() - } else if braces > 0 && ch == '{' { - braces++ - } - if braces > 0 && ch == '}' { - braces-- - } - - if ch == '\\' { - s.scanEscape() - } - } - - return -} - -// scanEscape scans an escape sequence -func (s *Scanner) scanEscape() rune { - // http://en.cppreference.com/w/cpp/language/escape - ch := s.next() // read character after '/' - switch ch { - case 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', '"': - // nothing to do - case '0', '1', '2', '3', '4', '5', '6', '7': - // octal notation - ch = s.scanDigits(ch, 8, 3) - case 'x': - // hexademical notation - ch = s.scanDigits(s.next(), 16, 2) - case 'u': - // universal character name - ch = s.scanDigits(s.next(), 16, 4) - case 'U': - // universal character name - ch = s.scanDigits(s.next(), 16, 8) - default: - s.err("illegal char escape") - } - return ch -} - -// scanDigits scans a rune with the given base for n times. For example an -// octal notation \184 would yield in scanDigits(ch, 8, 3) -func (s *Scanner) scanDigits(ch rune, base, n int) rune { - for n > 0 && digitVal(ch) < base { - ch = s.next() - n-- - } - if n > 0 { - s.err("illegal char escape") - } - - // we scanned all digits, put the last non digit char back - s.unread() - return ch -} - -// scanIdentifier scans an identifier and returns the literal string -func (s *Scanner) scanIdentifier() string { - offs := s.srcPos.Offset - s.lastCharLen - ch := s.next() - for isLetter(ch) || isDigit(ch) || ch == '-' { - ch = s.next() - } - - if ch != eof { - s.unread() // we got identifier, put back latest char - } - - return string(s.src[offs:s.srcPos.Offset]) -} - -// recentPosition returns the position of the character immediately after the -// character or token returned by the last call to Scan. -func (s *Scanner) recentPosition() (pos token.Pos) { - pos.Offset = s.srcPos.Offset - s.lastCharLen - switch { - case s.srcPos.Column > 0: - // common case: last character was not a '\n' - pos.Line = s.srcPos.Line - pos.Column = s.srcPos.Column - case s.lastLineLen > 0: - // last character was a '\n' - // (we cannot be at the beginning of the source - // since we have called next() at least once) - pos.Line = s.srcPos.Line - 1 - pos.Column = s.lastLineLen - default: - // at the beginning of the source - pos.Line = 1 - pos.Column = 1 - } - return -} - -// err prints the error of any scanning to s.Error function. If the function is -// not defined, by default it prints them to os.Stderr -func (s *Scanner) err(msg string) { - s.ErrorCount++ - pos := s.recentPosition() - - if s.Error != nil { - s.Error(pos, msg) - return - } - - fmt.Fprintf(os.Stderr, "%s: %s\n", pos, msg) -} - -// isHexadecimal returns true if the given rune is a letter -func isLetter(ch rune) bool { - return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch) -} - -// isHexadecimal returns true if the given rune is a decimal digit -func isDigit(ch rune) bool { - return '0' <= ch && ch <= '9' || ch >= 0x80 && unicode.IsDigit(ch) -} - -// isHexadecimal returns true if the given rune is a decimal number -func isDecimal(ch rune) bool { - return '0' <= ch && ch <= '9' -} - -// isHexadecimal returns true if the given rune is an hexadecimal number -func isHexadecimal(ch rune) bool { - return '0' <= ch && ch <= '9' || 'a' <= ch && ch <= 'f' || 'A' <= ch && ch <= 'F' -} - -// isWhitespace returns true if the rune is a space, tab, newline or carriage return -func isWhitespace(ch rune) bool { - return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' -} - -// digitVal returns the integer value of a given octal,decimal or hexadecimal rune -func digitVal(ch rune) int { - switch { - case '0' <= ch && ch <= '9': - return int(ch - '0') - case 'a' <= ch && ch <= 'f': - return int(ch - 'a' + 10) - case 'A' <= ch && ch <= 'F': - return int(ch - 'A' + 10) - } - return 16 // larger than any legal digit val -} diff --git a/vendor/github.com/hashicorp/hcl/json/token/position.go b/vendor/github.com/hashicorp/hcl/json/token/position.go deleted file mode 100644 index 59c1bb7..0000000 --- a/vendor/github.com/hashicorp/hcl/json/token/position.go +++ /dev/null @@ -1,46 +0,0 @@ -package token - -import "fmt" - -// Pos describes an arbitrary source position -// including the file, line, and column location. -// A Position is valid if the line number is > 0. -type Pos struct { - Filename string // filename, if any - Offset int // offset, starting at 0 - Line int // line number, starting at 1 - Column int // column number, starting at 1 (character count) -} - -// IsValid returns true if the position is valid. -func (p *Pos) IsValid() bool { return p.Line > 0 } - -// String returns a string in one of several forms: -// -// file:line:column valid position with file name -// line:column valid position without file name -// file invalid position with file name -// - invalid position without file name -func (p Pos) String() string { - s := p.Filename - if p.IsValid() { - if s != "" { - s += ":" - } - s += fmt.Sprintf("%d:%d", p.Line, p.Column) - } - if s == "" { - s = "-" - } - return s -} - -// Before reports whether the position p is before u. -func (p Pos) Before(u Pos) bool { - return u.Offset > p.Offset || u.Line > p.Line -} - -// After reports whether the position p is after u. -func (p Pos) After(u Pos) bool { - return u.Offset < p.Offset || u.Line < p.Line -} diff --git a/vendor/github.com/hashicorp/hcl/json/token/token.go b/vendor/github.com/hashicorp/hcl/json/token/token.go deleted file mode 100644 index 95a0c3e..0000000 --- a/vendor/github.com/hashicorp/hcl/json/token/token.go +++ /dev/null @@ -1,118 +0,0 @@ -package token - -import ( - "fmt" - "strconv" - - hcltoken "github.com/hashicorp/hcl/hcl/token" -) - -// Token defines a single HCL token which can be obtained via the Scanner -type Token struct { - Type Type - Pos Pos - Text string -} - -// Type is the set of lexical tokens of the HCL (HashiCorp Configuration Language) -type Type int - -const ( - // Special tokens - ILLEGAL Type = iota - EOF - - identifier_beg - literal_beg - NUMBER // 12345 - FLOAT // 123.45 - BOOL // true,false - STRING // "abc" - NULL // null - literal_end - identifier_end - - operator_beg - LBRACK // [ - LBRACE // { - COMMA // , - PERIOD // . - COLON // : - - RBRACK // ] - RBRACE // } - - operator_end -) - -var tokens = [...]string{ - ILLEGAL: "ILLEGAL", - - EOF: "EOF", - - NUMBER: "NUMBER", - FLOAT: "FLOAT", - BOOL: "BOOL", - STRING: "STRING", - NULL: "NULL", - - LBRACK: "LBRACK", - LBRACE: "LBRACE", - COMMA: "COMMA", - PERIOD: "PERIOD", - COLON: "COLON", - - RBRACK: "RBRACK", - RBRACE: "RBRACE", -} - -// String returns the string corresponding to the token tok. -func (t Type) String() string { - s := "" - if 0 <= t && t < Type(len(tokens)) { - s = tokens[t] - } - if s == "" { - s = "token(" + strconv.Itoa(int(t)) + ")" - } - return s -} - -// IsIdentifier returns true for tokens corresponding to identifiers and basic -// type literals; it returns false otherwise. -func (t Type) IsIdentifier() bool { return identifier_beg < t && t < identifier_end } - -// IsLiteral returns true for tokens corresponding to basic type literals; it -// returns false otherwise. -func (t Type) IsLiteral() bool { return literal_beg < t && t < literal_end } - -// IsOperator returns true for tokens corresponding to operators and -// delimiters; it returns false otherwise. -func (t Type) IsOperator() bool { return operator_beg < t && t < operator_end } - -// String returns the token's literal text. Note that this is only -// applicable for certain token types, such as token.IDENT, -// token.STRING, etc.. -func (t Token) String() string { - return fmt.Sprintf("%s %s %s", t.Pos.String(), t.Type.String(), t.Text) -} - -// HCLToken converts this token to an HCL token. -// -// The token type must be a literal type or this will panic. -func (t Token) HCLToken() hcltoken.Token { - switch t.Type { - case BOOL: - return hcltoken.Token{Type: hcltoken.BOOL, Text: t.Text} - case FLOAT: - return hcltoken.Token{Type: hcltoken.FLOAT, Text: t.Text} - case NULL: - return hcltoken.Token{Type: hcltoken.STRING, Text: ""} - case NUMBER: - return hcltoken.Token{Type: hcltoken.NUMBER, Text: t.Text} - case STRING: - return hcltoken.Token{Type: hcltoken.STRING, Text: t.Text, JSON: true} - default: - panic(fmt.Sprintf("unimplemented HCLToken for type: %s", t.Type)) - } -} diff --git a/vendor/github.com/hashicorp/hcl/lex.go b/vendor/github.com/hashicorp/hcl/lex.go deleted file mode 100644 index d9993c2..0000000 --- a/vendor/github.com/hashicorp/hcl/lex.go +++ /dev/null @@ -1,38 +0,0 @@ -package hcl - -import ( - "unicode" - "unicode/utf8" -) - -type lexModeValue byte - -const ( - lexModeUnknown lexModeValue = iota - lexModeHcl - lexModeJson -) - -// lexMode returns whether we're going to be parsing in JSON -// mode or HCL mode. -func lexMode(v []byte) lexModeValue { - var ( - r rune - w int - offset int - ) - - for { - r, w = utf8.DecodeRune(v[offset:]) - offset += w - if unicode.IsSpace(r) { - continue - } - if r == '{' { - return lexModeJson - } - break - } - - return lexModeHcl -} diff --git a/vendor/github.com/hashicorp/hcl/parse.go b/vendor/github.com/hashicorp/hcl/parse.go deleted file mode 100644 index 1fca53c..0000000 --- a/vendor/github.com/hashicorp/hcl/parse.go +++ /dev/null @@ -1,39 +0,0 @@ -package hcl - -import ( - "fmt" - - "github.com/hashicorp/hcl/hcl/ast" - hclParser "github.com/hashicorp/hcl/hcl/parser" - jsonParser "github.com/hashicorp/hcl/json/parser" -) - -// ParseBytes accepts as input byte slice and returns ast tree. -// -// Input can be either JSON or HCL -func ParseBytes(in []byte) (*ast.File, error) { - return parse(in) -} - -// ParseString accepts input as a string and returns ast tree. -func ParseString(input string) (*ast.File, error) { - return parse([]byte(input)) -} - -func parse(in []byte) (*ast.File, error) { - switch lexMode(in) { - case lexModeHcl: - return hclParser.Parse(in) - case lexModeJson: - return jsonParser.Parse(in) - } - - return nil, fmt.Errorf("unknown config format") -} - -// Parse parses the given input and returns the root object. -// -// The input format can be either HCL or JSON. -func Parse(input string) (*ast.File, error) { - return parse([]byte(input)) -} diff --git a/vendor/github.com/hashicorp/vault/LICENSE b/vendor/github.com/hashicorp/vault/LICENSE deleted file mode 100644 index e87a115..0000000 --- a/vendor/github.com/hashicorp/vault/LICENSE +++ /dev/null @@ -1,363 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - diff --git a/vendor/github.com/hashicorp/vault/api/auth.go b/vendor/github.com/hashicorp/vault/api/auth.go deleted file mode 100644 index da870c1..0000000 --- a/vendor/github.com/hashicorp/vault/api/auth.go +++ /dev/null @@ -1,11 +0,0 @@ -package api - -// Auth is used to perform credential backend related operations. -type Auth struct { - c *Client -} - -// Auth is used to return the client for credential-backend API calls. -func (c *Client) Auth() *Auth { - return &Auth{c: c} -} diff --git a/vendor/github.com/hashicorp/vault/api/auth_token.go b/vendor/github.com/hashicorp/vault/api/auth_token.go deleted file mode 100644 index c66fba3..0000000 --- a/vendor/github.com/hashicorp/vault/api/auth_token.go +++ /dev/null @@ -1,274 +0,0 @@ -package api - -import "context" - -// TokenAuth is used to perform token backend operations on Vault -type TokenAuth struct { - c *Client -} - -// Token is used to return the client for token-backend API calls -func (a *Auth) Token() *TokenAuth { - return &TokenAuth{c: a.c} -} - -func (c *TokenAuth) Create(opts *TokenCreateRequest) (*Secret, error) { - r := c.c.NewRequest("POST", "/v1/auth/token/create") - if err := r.SetJSONBody(opts); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - return ParseSecret(resp.Body) -} - -func (c *TokenAuth) CreateOrphan(opts *TokenCreateRequest) (*Secret, error) { - r := c.c.NewRequest("POST", "/v1/auth/token/create-orphan") - if err := r.SetJSONBody(opts); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - return ParseSecret(resp.Body) -} - -func (c *TokenAuth) CreateWithRole(opts *TokenCreateRequest, roleName string) (*Secret, error) { - r := c.c.NewRequest("POST", "/v1/auth/token/create/"+roleName) - if err := r.SetJSONBody(opts); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - return ParseSecret(resp.Body) -} - -func (c *TokenAuth) Lookup(token string) (*Secret, error) { - r := c.c.NewRequest("POST", "/v1/auth/token/lookup") - if err := r.SetJSONBody(map[string]interface{}{ - "token": token, - }); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - return ParseSecret(resp.Body) -} - -func (c *TokenAuth) LookupAccessor(accessor string) (*Secret, error) { - r := c.c.NewRequest("POST", "/v1/auth/token/lookup-accessor") - if err := r.SetJSONBody(map[string]interface{}{ - "accessor": accessor, - }); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - return ParseSecret(resp.Body) -} - -func (c *TokenAuth) LookupSelf() (*Secret, error) { - r := c.c.NewRequest("GET", "/v1/auth/token/lookup-self") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - return ParseSecret(resp.Body) -} - -func (c *TokenAuth) Renew(token string, increment int) (*Secret, error) { - r := c.c.NewRequest("PUT", "/v1/auth/token/renew") - if err := r.SetJSONBody(map[string]interface{}{ - "token": token, - "increment": increment, - }); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - return ParseSecret(resp.Body) -} - -func (c *TokenAuth) RenewSelf(increment int) (*Secret, error) { - r := c.c.NewRequest("PUT", "/v1/auth/token/renew-self") - - body := map[string]interface{}{"increment": increment} - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - return ParseSecret(resp.Body) -} - -// RenewTokenAsSelf behaves like renew-self, but authenticates using a provided -// token instead of the token attached to the client. -func (c *TokenAuth) RenewTokenAsSelf(token string, increment int) (*Secret, error) { - r := c.c.NewRequest("PUT", "/v1/auth/token/renew-self") - r.ClientToken = token - - body := map[string]interface{}{"increment": increment} - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - return ParseSecret(resp.Body) -} - -// RevokeAccessor revokes a token associated with the given accessor -// along with all the child tokens. -func (c *TokenAuth) RevokeAccessor(accessor string) error { - r := c.c.NewRequest("POST", "/v1/auth/token/revoke-accessor") - if err := r.SetJSONBody(map[string]interface{}{ - "accessor": accessor, - }); err != nil { - return err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return err - } - defer resp.Body.Close() - - return nil -} - -// RevokeOrphan revokes a token without revoking the tree underneath it (so -// child tokens are orphaned rather than revoked) -func (c *TokenAuth) RevokeOrphan(token string) error { - r := c.c.NewRequest("PUT", "/v1/auth/token/revoke-orphan") - if err := r.SetJSONBody(map[string]interface{}{ - "token": token, - }); err != nil { - return err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return err - } - defer resp.Body.Close() - - return nil -} - -// RevokeSelf revokes the token making the call. The `token` parameter is kept -// for backwards compatibility but is ignored; only the client's set token has -// an effect. -func (c *TokenAuth) RevokeSelf(token string) error { - r := c.c.NewRequest("PUT", "/v1/auth/token/revoke-self") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return err - } - defer resp.Body.Close() - - return nil -} - -// RevokeTree is the "normal" revoke operation that revokes the given token and -// the entire tree underneath -- all of its child tokens, their child tokens, -// etc. -func (c *TokenAuth) RevokeTree(token string) error { - r := c.c.NewRequest("PUT", "/v1/auth/token/revoke") - if err := r.SetJSONBody(map[string]interface{}{ - "token": token, - }); err != nil { - return err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return err - } - defer resp.Body.Close() - - return nil -} - -// TokenCreateRequest is the options structure for creating a token. -type TokenCreateRequest struct { - ID string `json:"id,omitempty"` - Policies []string `json:"policies,omitempty"` - Metadata map[string]string `json:"meta,omitempty"` - Lease string `json:"lease,omitempty"` - TTL string `json:"ttl,omitempty"` - ExplicitMaxTTL string `json:"explicit_max_ttl,omitempty"` - Period string `json:"period,omitempty"` - NoParent bool `json:"no_parent,omitempty"` - NoDefaultPolicy bool `json:"no_default_policy,omitempty"` - DisplayName string `json:"display_name"` - NumUses int `json:"num_uses"` - Renewable *bool `json:"renewable,omitempty"` -} diff --git a/vendor/github.com/hashicorp/vault/api/client.go b/vendor/github.com/hashicorp/vault/api/client.go deleted file mode 100644 index c7ced82..0000000 --- a/vendor/github.com/hashicorp/vault/api/client.go +++ /dev/null @@ -1,759 +0,0 @@ -package api - -import ( - "context" - "crypto/tls" - "fmt" - "net" - "net/http" - "net/url" - "os" - "path" - "strconv" - "strings" - "sync" - "time" - "unicode" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-cleanhttp" - retryablehttp "github.com/hashicorp/go-retryablehttp" - "github.com/hashicorp/go-rootcerts" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/parseutil" - "golang.org/x/net/http2" - "golang.org/x/time/rate" -) - -const EnvVaultAddress = "VAULT_ADDR" -const EnvVaultCACert = "VAULT_CACERT" -const EnvVaultCAPath = "VAULT_CAPATH" -const EnvVaultClientCert = "VAULT_CLIENT_CERT" -const EnvVaultClientKey = "VAULT_CLIENT_KEY" -const EnvVaultClientTimeout = "VAULT_CLIENT_TIMEOUT" -const EnvVaultInsecure = "VAULT_SKIP_VERIFY" -const EnvVaultTLSServerName = "VAULT_TLS_SERVER_NAME" -const EnvVaultWrapTTL = "VAULT_WRAP_TTL" -const EnvVaultMaxRetries = "VAULT_MAX_RETRIES" -const EnvVaultToken = "VAULT_TOKEN" -const EnvVaultMFA = "VAULT_MFA" -const EnvRateLimit = "VAULT_RATE_LIMIT" - -// WrappingLookupFunc is a function that, given an HTTP verb and a path, -// returns an optional string duration to be used for response wrapping (e.g. -// "15s", or simply "15"). The path will not begin with "/v1/" or "v1/" or "/", -// however, end-of-path forward slashes are not trimmed, so must match your -// called path precisely. -type WrappingLookupFunc func(operation, path string) string - -// Config is used to configure the creation of the client. -type Config struct { - modifyLock sync.RWMutex - - // Address is the address of the Vault server. This should be a complete - // URL such as "http://vault.example.com". If you need a custom SSL - // cert or want to enable insecure mode, you need to specify a custom - // HttpClient. - Address string - - // HttpClient is the HTTP client to use. Vault sets sane defaults for the - // http.Client and its associated http.Transport created in DefaultConfig. - // If you must modify Vault's defaults, it is suggested that you start with - // that client and modify as needed rather than start with an empty client - // (or http.DefaultClient). - HttpClient *http.Client - - // MaxRetries controls the maximum number of times to retry when a 5xx - // error occurs. Set to 0 to disable retrying. Defaults to 2 (for a total - // of three tries). - MaxRetries int - - // Timeout is for setting custom timeout parameter in the HttpClient - Timeout time.Duration - - // If there is an error when creating the configuration, this will be the - // error - Error error - - // The Backoff function to use; a default is used if not provided - Backoff retryablehttp.Backoff - - // Limiter is the rate limiter used by the client. - // If this pointer is nil, then there will be no limit set. - // In contrast, if this pointer is set, even to an empty struct, - // then that limiter will be used. Note that an empty Limiter - // is equivalent blocking all events. - Limiter *rate.Limiter -} - -// TLSConfig contains the parameters needed to configure TLS on the HTTP client -// used to communicate with Vault. -type TLSConfig struct { - // CACert is the path to a PEM-encoded CA cert file to use to verify the - // Vault server SSL certificate. - CACert string - - // CAPath is the path to a directory of PEM-encoded CA cert files to verify - // the Vault server SSL certificate. - CAPath string - - // ClientCert is the path to the certificate for Vault communication - ClientCert string - - // ClientKey is the path to the private key for Vault communication - ClientKey string - - // TLSServerName, if set, is used to set the SNI host when connecting via - // TLS. - TLSServerName string - - // Insecure enables or disables SSL verification - Insecure bool -} - -// DefaultConfig returns a default configuration for the client. It is -// safe to modify the return value of this function. -// -// The default Address is https://127.0.0.1:8200, but this can be overridden by -// setting the `VAULT_ADDR` environment variable. -// -// If an error is encountered, this will return nil. -func DefaultConfig() *Config { - config := &Config{ - Address: "https://127.0.0.1:8200", - HttpClient: cleanhttp.DefaultClient(), - } - config.HttpClient.Timeout = time.Second * 60 - - transport := config.HttpClient.Transport.(*http.Transport) - transport.TLSHandshakeTimeout = 10 * time.Second - transport.TLSClientConfig = &tls.Config{ - MinVersion: tls.VersionTLS12, - } - if err := http2.ConfigureTransport(transport); err != nil { - config.Error = err - return config - } - - if err := config.ReadEnvironment(); err != nil { - config.Error = err - return config - } - - // Ensure redirects are not automatically followed - // Note that this is sane for the API client as it has its own - // redirect handling logic (and thus also for command/meta), - // but in e.g. http_test actual redirect handling is necessary - config.HttpClient.CheckRedirect = func(req *http.Request, via []*http.Request) error { - // Returning this value causes the Go net library to not close the - // response body and to nil out the error. Otherwise retry clients may - // try three times on every redirect because it sees an error from this - // function (to prevent redirects) passing through to it. - return http.ErrUseLastResponse - } - - config.Backoff = retryablehttp.LinearJitterBackoff - config.MaxRetries = 2 - - return config -} - -// ConfigureTLS takes a set of TLS configurations and applies those to the the -// HTTP client. -func (c *Config) ConfigureTLS(t *TLSConfig) error { - if c.HttpClient == nil { - c.HttpClient = DefaultConfig().HttpClient - } - clientTLSConfig := c.HttpClient.Transport.(*http.Transport).TLSClientConfig - - var clientCert tls.Certificate - foundClientCert := false - - switch { - case t.ClientCert != "" && t.ClientKey != "": - var err error - clientCert, err = tls.LoadX509KeyPair(t.ClientCert, t.ClientKey) - if err != nil { - return err - } - foundClientCert = true - case t.ClientCert != "" || t.ClientKey != "": - return fmt.Errorf("both client cert and client key must be provided") - } - - if t.CACert != "" || t.CAPath != "" { - rootConfig := &rootcerts.Config{ - CAFile: t.CACert, - CAPath: t.CAPath, - } - if err := rootcerts.ConfigureTLS(clientTLSConfig, rootConfig); err != nil { - return err - } - } - - if t.Insecure { - clientTLSConfig.InsecureSkipVerify = true - } - - if foundClientCert { - // We use this function to ignore the server's preferential list of - // CAs, otherwise any CA used for the cert auth backend must be in the - // server's CA pool - clientTLSConfig.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { - return &clientCert, nil - } - } - - if t.TLSServerName != "" { - clientTLSConfig.ServerName = t.TLSServerName - } - - return nil -} - -// ReadEnvironment reads configuration information from the environment. If -// there is an error, no configuration value is updated. -func (c *Config) ReadEnvironment() error { - var envAddress string - var envCACert string - var envCAPath string - var envClientCert string - var envClientKey string - var envClientTimeout time.Duration - var envInsecure bool - var envTLSServerName string - var envMaxRetries *uint64 - var limit *rate.Limiter - - // Parse the environment variables - if v := os.Getenv(EnvVaultAddress); v != "" { - envAddress = v - } - if v := os.Getenv(EnvVaultMaxRetries); v != "" { - maxRetries, err := strconv.ParseUint(v, 10, 32) - if err != nil { - return err - } - envMaxRetries = &maxRetries - } - if v := os.Getenv(EnvVaultCACert); v != "" { - envCACert = v - } - if v := os.Getenv(EnvVaultCAPath); v != "" { - envCAPath = v - } - if v := os.Getenv(EnvVaultClientCert); v != "" { - envClientCert = v - } - if v := os.Getenv(EnvVaultClientKey); v != "" { - envClientKey = v - } - if v := os.Getenv(EnvRateLimit); v != "" { - rateLimit, burstLimit, err := parseRateLimit(v) - if err != nil { - return err - } - limit = rate.NewLimiter(rate.Limit(rateLimit), burstLimit) - } - if t := os.Getenv(EnvVaultClientTimeout); t != "" { - clientTimeout, err := parseutil.ParseDurationSecond(t) - if err != nil { - return fmt.Errorf("could not parse %q", EnvVaultClientTimeout) - } - envClientTimeout = clientTimeout - } - if v := os.Getenv(EnvVaultInsecure); v != "" { - var err error - envInsecure, err = strconv.ParseBool(v) - if err != nil { - return fmt.Errorf("could not parse VAULT_SKIP_VERIFY") - } - } - if v := os.Getenv(EnvVaultTLSServerName); v != "" { - envTLSServerName = v - } - - // Configure the HTTP clients TLS configuration. - t := &TLSConfig{ - CACert: envCACert, - CAPath: envCAPath, - ClientCert: envClientCert, - ClientKey: envClientKey, - TLSServerName: envTLSServerName, - Insecure: envInsecure, - } - - c.modifyLock.Lock() - defer c.modifyLock.Unlock() - - c.Limiter = limit - - if err := c.ConfigureTLS(t); err != nil { - return err - } - - if envAddress != "" { - c.Address = envAddress - } - - if envMaxRetries != nil { - c.MaxRetries = int(*envMaxRetries) - } - - if envClientTimeout != 0 { - c.Timeout = envClientTimeout - } - - return nil -} - -func parseRateLimit(val string) (rate float64, burst int, err error) { - - _, err = fmt.Sscanf(val, "%f:%d", &rate, &burst) - if err != nil { - rate, err = strconv.ParseFloat(val, 64) - if err != nil { - err = fmt.Errorf("%v was provided but incorrectly formatted", EnvRateLimit) - } - burst = int(rate) - } - - return rate, burst, err - -} - -// Client is the client to the Vault API. Create a client with NewClient. -type Client struct { - modifyLock sync.RWMutex - addr *url.URL - config *Config - token string - headers http.Header - wrappingLookupFunc WrappingLookupFunc - mfaCreds []string - policyOverride bool -} - -// NewClient returns a new client for the given configuration. -// -// If the configuration is nil, Vault will use configuration from -// DefaultConfig(), which is the recommended starting configuration. -// -// If the environment variable `VAULT_TOKEN` is present, the token will be -// automatically added to the client. Otherwise, you must manually call -// `SetToken()`. -func NewClient(c *Config) (*Client, error) { - def := DefaultConfig() - if def == nil { - return nil, fmt.Errorf("could not create/read default configuration") - } - if def.Error != nil { - return nil, errwrap.Wrapf("error encountered setting up default configuration: {{err}}", def.Error) - } - - if c == nil { - c = def - } - - c.modifyLock.Lock() - defer c.modifyLock.Unlock() - - u, err := url.Parse(c.Address) - if err != nil { - return nil, err - } - - if c.HttpClient == nil { - c.HttpClient = def.HttpClient - } - if c.HttpClient.Transport == nil { - c.HttpClient.Transport = def.HttpClient.Transport - } - - client := &Client{ - addr: u, - config: c, - } - - if token := os.Getenv(EnvVaultToken); token != "" { - client.token = token - } - - return client, nil -} - -// Sets the address of Vault in the client. The format of address should be -// "://:". Setting this on a client will override the -// value of VAULT_ADDR environment variable. -func (c *Client) SetAddress(addr string) error { - c.modifyLock.Lock() - defer c.modifyLock.Unlock() - - parsedAddr, err := url.Parse(addr) - if err != nil { - return errwrap.Wrapf("failed to set address: {{err}}", err) - } - - c.addr = parsedAddr - return nil -} - -// Address returns the Vault URL the client is configured to connect to -func (c *Client) Address() string { - c.modifyLock.RLock() - defer c.modifyLock.RUnlock() - - return c.addr.String() -} - -// SetLimiter will set the rate limiter for this client. -// This method is thread-safe. -// rateLimit and burst are specified according to https://godoc.org/golang.org/x/time/rate#NewLimiter -func (c *Client) SetLimiter(rateLimit float64, burst int) { - c.modifyLock.RLock() - c.config.modifyLock.Lock() - defer c.config.modifyLock.Unlock() - c.modifyLock.RUnlock() - - c.config.Limiter = rate.NewLimiter(rate.Limit(rateLimit), burst) -} - -// SetMaxRetries sets the number of retries that will be used in the case of certain errors -func (c *Client) SetMaxRetries(retries int) { - c.modifyLock.RLock() - c.config.modifyLock.Lock() - defer c.config.modifyLock.Unlock() - c.modifyLock.RUnlock() - - c.config.MaxRetries = retries -} - -// SetClientTimeout sets the client request timeout -func (c *Client) SetClientTimeout(timeout time.Duration) { - c.modifyLock.RLock() - c.config.modifyLock.Lock() - defer c.config.modifyLock.Unlock() - c.modifyLock.RUnlock() - - c.config.Timeout = timeout -} - -// CurrentWrappingLookupFunc sets a lookup function that returns desired wrap TTLs -// for a given operation and path -func (c *Client) CurrentWrappingLookupFunc() WrappingLookupFunc { - c.modifyLock.RLock() - defer c.modifyLock.RUnlock() - - return c.wrappingLookupFunc -} - -// SetWrappingLookupFunc sets a lookup function that returns desired wrap TTLs -// for a given operation and path -func (c *Client) SetWrappingLookupFunc(lookupFunc WrappingLookupFunc) { - c.modifyLock.Lock() - defer c.modifyLock.Unlock() - - c.wrappingLookupFunc = lookupFunc -} - -// SetMFACreds sets the MFA credentials supplied either via the environment -// variable or via the command line. -func (c *Client) SetMFACreds(creds []string) { - c.modifyLock.Lock() - defer c.modifyLock.Unlock() - - c.mfaCreds = creds -} - -// SetNamespace sets the namespace supplied either via the environment -// variable or via the command line. -func (c *Client) SetNamespace(namespace string) { - c.modifyLock.Lock() - defer c.modifyLock.Unlock() - - if c.headers == nil { - c.headers = make(http.Header) - } - - c.headers.Set(consts.NamespaceHeaderName, namespace) -} - -// Token returns the access token being used by this client. It will -// return the empty string if there is no token set. -func (c *Client) Token() string { - c.modifyLock.RLock() - defer c.modifyLock.RUnlock() - - return c.token -} - -// SetToken sets the token directly. This won't perform any auth -// verification, it simply sets the token properly for future requests. -func (c *Client) SetToken(v string) { - c.modifyLock.Lock() - defer c.modifyLock.Unlock() - - c.token = v -} - -// ClearToken deletes the token if it is set or does nothing otherwise. -func (c *Client) ClearToken() { - c.modifyLock.Lock() - defer c.modifyLock.Unlock() - - c.token = "" -} - -// Headers gets the current set of headers used for requests. This returns a -// copy; to modify it make modifications locally and use SetHeaders. -func (c *Client) Headers() http.Header { - c.modifyLock.RLock() - defer c.modifyLock.RUnlock() - - if c.headers == nil { - return nil - } - - ret := make(http.Header) - for k, v := range c.headers { - for _, val := range v { - ret[k] = append(ret[k], val) - } - } - - return ret -} - -// SetHeaders sets the headers to be used for future requests. -func (c *Client) SetHeaders(headers http.Header) { - c.modifyLock.Lock() - defer c.modifyLock.Unlock() - - c.headers = headers -} - -// SetBackoff sets the backoff function to be used for future requests. -func (c *Client) SetBackoff(backoff retryablehttp.Backoff) { - c.modifyLock.RLock() - c.config.modifyLock.Lock() - defer c.config.modifyLock.Unlock() - c.modifyLock.RUnlock() - - c.config.Backoff = backoff -} - -// Clone creates a new client with the same configuration. Note that the same -// underlying http.Client is used; modifying the client from more than one -// goroutine at once may not be safe, so modify the client as needed and then -// clone. -func (c *Client) Clone() (*Client, error) { - c.modifyLock.RLock() - c.config.modifyLock.RLock() - config := c.config - c.modifyLock.RUnlock() - - newConfig := &Config{ - Address: config.Address, - HttpClient: config.HttpClient, - MaxRetries: config.MaxRetries, - Timeout: config.Timeout, - Backoff: config.Backoff, - Limiter: config.Limiter, - } - config.modifyLock.RUnlock() - - return NewClient(newConfig) -} - -// SetPolicyOverride sets whether requests should be sent with the policy -// override flag to request overriding soft-mandatory Sentinel policies (both -// RGPs and EGPs) -func (c *Client) SetPolicyOverride(override bool) { - c.modifyLock.Lock() - defer c.modifyLock.Unlock() - - c.policyOverride = override -} - -// NewRequest creates a new raw request object to query the Vault server -// configured for this client. This is an advanced method and generally -// doesn't need to be called externally. -func (c *Client) NewRequest(method, requestPath string) *Request { - c.modifyLock.RLock() - addr := c.addr - token := c.token - mfaCreds := c.mfaCreds - wrappingLookupFunc := c.wrappingLookupFunc - headers := c.headers - policyOverride := c.policyOverride - c.modifyLock.RUnlock() - - // if SRV records exist (see https://tools.ietf.org/html/draft-andrews-http-srv-02), lookup the SRV - // record and take the highest match; this is not designed for high-availability, just discovery - var host string = addr.Host - if addr.Port() == "" { - // Internet Draft specifies that the SRV record is ignored if a port is given - _, addrs, err := net.LookupSRV("http", "tcp", addr.Hostname()) - if err == nil && len(addrs) > 0 { - host = fmt.Sprintf("%s:%d", addrs[0].Target, addrs[0].Port) - } - } - - req := &Request{ - Method: method, - URL: &url.URL{ - User: addr.User, - Scheme: addr.Scheme, - Host: host, - Path: path.Join(addr.Path, requestPath), - }, - ClientToken: token, - Params: make(map[string][]string), - } - - var lookupPath string - switch { - case strings.HasPrefix(requestPath, "/v1/"): - lookupPath = strings.TrimPrefix(requestPath, "/v1/") - case strings.HasPrefix(requestPath, "v1/"): - lookupPath = strings.TrimPrefix(requestPath, "v1/") - default: - lookupPath = requestPath - } - - req.MFAHeaderVals = mfaCreds - - if wrappingLookupFunc != nil { - req.WrapTTL = wrappingLookupFunc(method, lookupPath) - } else { - req.WrapTTL = DefaultWrappingLookupFunc(method, lookupPath) - } - - if headers != nil { - req.Headers = headers - } - - req.PolicyOverride = policyOverride - - return req -} - -// RawRequest performs the raw request given. This request may be against -// a Vault server not configured with this client. This is an advanced operation -// that generally won't need to be called externally. -func (c *Client) RawRequest(r *Request) (*Response, error) { - return c.RawRequestWithContext(context.Background(), r) -} - -// RawRequestWithContext performs the raw request given. This request may be against -// a Vault server not configured with this client. This is an advanced operation -// that generally won't need to be called externally. -func (c *Client) RawRequestWithContext(ctx context.Context, r *Request) (*Response, error) { - c.modifyLock.RLock() - token := c.token - - c.config.modifyLock.RLock() - limiter := c.config.Limiter - maxRetries := c.config.MaxRetries - backoff := c.config.Backoff - httpClient := c.config.HttpClient - timeout := c.config.Timeout - c.config.modifyLock.RUnlock() - - c.modifyLock.RUnlock() - - if limiter != nil { - limiter.Wait(ctx) - } - - // Sanity check the token before potentially erroring from the API - idx := strings.IndexFunc(token, func(c rune) bool { - return !unicode.IsPrint(c) - }) - if idx != -1 { - return nil, fmt.Errorf("configured Vault token contains non-printable characters and cannot be used") - } - - redirectCount := 0 -START: - req, err := r.toRetryableHTTP() - if err != nil { - return nil, err - } - if req == nil { - return nil, fmt.Errorf("nil request created") - } - - if timeout != 0 { - ctx, _ = context.WithTimeout(ctx, timeout) - } - req.Request = req.Request.WithContext(ctx) - - if backoff == nil { - backoff = retryablehttp.LinearJitterBackoff - } - - client := &retryablehttp.Client{ - HTTPClient: httpClient, - RetryWaitMin: 1000 * time.Millisecond, - RetryWaitMax: 1500 * time.Millisecond, - RetryMax: maxRetries, - CheckRetry: retryablehttp.DefaultRetryPolicy, - Backoff: backoff, - ErrorHandler: retryablehttp.PassthroughErrorHandler, - } - - var result *Response - resp, err := client.Do(req) - if resp != nil { - result = &Response{Response: resp} - } - if err != nil { - if strings.Contains(err.Error(), "tls: oversized") { - err = errwrap.Wrapf( - "{{err}}\n\n"+ - "This error usually means that the server is running with TLS disabled\n"+ - "but the client is configured to use TLS. Please either enable TLS\n"+ - "on the server or run the client with -address set to an address\n"+ - "that uses the http protocol:\n\n"+ - " vault -address http://
\n\n"+ - "You can also set the VAULT_ADDR environment variable:\n\n\n"+ - " VAULT_ADDR=http://
vault \n\n"+ - "where
is replaced by the actual address to the server.", - err) - } - return result, err - } - - // Check for a redirect, only allowing for a single redirect - if (resp.StatusCode == 301 || resp.StatusCode == 302 || resp.StatusCode == 307) && redirectCount == 0 { - // Parse the updated location - respLoc, err := resp.Location() - if err != nil { - return result, err - } - - // Ensure a protocol downgrade doesn't happen - if req.URL.Scheme == "https" && respLoc.Scheme != "https" { - return result, fmt.Errorf("redirect would cause protocol downgrade") - } - - // Update the request - r.URL = respLoc - - // Reset the request body if any - if err := r.ResetJSONBody(); err != nil { - return result, err - } - - // Retry the request - redirectCount++ - goto START - } - - if err := result.Error(); err != nil { - return result, err - } - - return result, nil -} diff --git a/vendor/github.com/hashicorp/vault/api/help.go b/vendor/github.com/hashicorp/vault/api/help.go deleted file mode 100644 index 472ca03..0000000 --- a/vendor/github.com/hashicorp/vault/api/help.go +++ /dev/null @@ -1,29 +0,0 @@ -package api - -import ( - "context" - "fmt" -) - -// Help reads the help information for the given path. -func (c *Client) Help(path string) (*Help, error) { - r := c.NewRequest("GET", fmt.Sprintf("/v1/%s", path)) - r.Params.Add("help", "1") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result Help - err = resp.DecodeJSON(&result) - return &result, err -} - -type Help struct { - Help string `json:"help"` - SeeAlso []string `json:"see_also"` -} diff --git a/vendor/github.com/hashicorp/vault/api/logical.go b/vendor/github.com/hashicorp/vault/api/logical.go deleted file mode 100644 index d13daac..0000000 --- a/vendor/github.com/hashicorp/vault/api/logical.go +++ /dev/null @@ -1,267 +0,0 @@ -package api - -import ( - "bytes" - "context" - "fmt" - "io" - "net/url" - "os" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/jsonutil" -) - -const ( - wrappedResponseLocation = "cubbyhole/response" -) - -var ( - // The default TTL that will be used with `sys/wrapping/wrap`, can be - // changed - DefaultWrappingTTL = "5m" - - // The default function used if no other function is set, which honors the - // env var and wraps `sys/wrapping/wrap` - DefaultWrappingLookupFunc = func(operation, path string) string { - if os.Getenv(EnvVaultWrapTTL) != "" { - return os.Getenv(EnvVaultWrapTTL) - } - - if (operation == "PUT" || operation == "POST") && path == "sys/wrapping/wrap" { - return DefaultWrappingTTL - } - - return "" - } -) - -// Logical is used to perform logical backend operations on Vault. -type Logical struct { - c *Client -} - -// Logical is used to return the client for logical-backend API calls. -func (c *Client) Logical() *Logical { - return &Logical{c: c} -} - -func (c *Logical) Read(path string) (*Secret, error) { - return c.ReadWithData(path, nil) -} - -func (c *Logical) ReadWithData(path string, data map[string][]string) (*Secret, error) { - r := c.c.NewRequest("GET", "/v1/"+path) - - var values url.Values - for k, v := range data { - if values == nil { - values = make(url.Values) - } - for _, val := range v { - values.Add(k, val) - } - } - - if values != nil { - r.Params = values - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if resp != nil { - defer resp.Body.Close() - } - if resp != nil && resp.StatusCode == 404 { - secret, parseErr := ParseSecret(resp.Body) - switch parseErr { - case nil: - case io.EOF: - return nil, nil - default: - return nil, err - } - if secret != nil && (len(secret.Warnings) > 0 || len(secret.Data) > 0) { - return secret, nil - } - return nil, nil - } - if err != nil { - return nil, err - } - - return ParseSecret(resp.Body) -} - -func (c *Logical) List(path string) (*Secret, error) { - r := c.c.NewRequest("LIST", "/v1/"+path) - // Set this for broader compatibility, but we use LIST above to be able to - // handle the wrapping lookup function - r.Method = "GET" - r.Params.Set("list", "true") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if resp != nil { - defer resp.Body.Close() - } - if resp != nil && resp.StatusCode == 404 { - secret, parseErr := ParseSecret(resp.Body) - switch parseErr { - case nil: - case io.EOF: - return nil, nil - default: - return nil, err - } - if secret != nil && (len(secret.Warnings) > 0 || len(secret.Data) > 0) { - return secret, nil - } - return nil, nil - } - if err != nil { - return nil, err - } - - return ParseSecret(resp.Body) -} - -func (c *Logical) Write(path string, data map[string]interface{}) (*Secret, error) { - r := c.c.NewRequest("PUT", "/v1/"+path) - if err := r.SetJSONBody(data); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if resp != nil { - defer resp.Body.Close() - } - if resp != nil && resp.StatusCode == 404 { - secret, parseErr := ParseSecret(resp.Body) - switch parseErr { - case nil: - case io.EOF: - return nil, nil - default: - return nil, err - } - if secret != nil && (len(secret.Warnings) > 0 || len(secret.Data) > 0) { - return secret, err - } - } - if err != nil { - return nil, err - } - - return ParseSecret(resp.Body) -} - -func (c *Logical) Delete(path string) (*Secret, error) { - r := c.c.NewRequest("DELETE", "/v1/"+path) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if resp != nil { - defer resp.Body.Close() - } - if resp != nil && resp.StatusCode == 404 { - secret, parseErr := ParseSecret(resp.Body) - switch parseErr { - case nil: - case io.EOF: - return nil, nil - default: - return nil, err - } - if secret != nil && (len(secret.Warnings) > 0 || len(secret.Data) > 0) { - return secret, err - } - } - if err != nil { - return nil, err - } - - return ParseSecret(resp.Body) -} - -func (c *Logical) Unwrap(wrappingToken string) (*Secret, error) { - var data map[string]interface{} - if wrappingToken != "" { - if c.c.Token() == "" { - c.c.SetToken(wrappingToken) - } else if wrappingToken != c.c.Token() { - data = map[string]interface{}{ - "token": wrappingToken, - } - } - } - - r := c.c.NewRequest("PUT", "/v1/sys/wrapping/unwrap") - if err := r.SetJSONBody(data); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if resp != nil { - defer resp.Body.Close() - } - if resp == nil || resp.StatusCode != 404 { - if err != nil { - return nil, err - } - if resp == nil { - return nil, nil - } - return ParseSecret(resp.Body) - } - - // In the 404 case this may actually be a wrapped 404 error - secret, parseErr := ParseSecret(resp.Body) - switch parseErr { - case nil: - case io.EOF: - return nil, nil - default: - return nil, err - } - if secret != nil && (len(secret.Warnings) > 0 || len(secret.Data) > 0) { - return secret, nil - } - - // Otherwise this might be an old-style wrapping token so attempt the old - // method - if wrappingToken != "" { - origToken := c.c.Token() - defer c.c.SetToken(origToken) - c.c.SetToken(wrappingToken) - } - - secret, err = c.Read(wrappedResponseLocation) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error reading %q: {{err}}", wrappedResponseLocation), err) - } - if secret == nil { - return nil, fmt.Errorf("no value found at %q", wrappedResponseLocation) - } - if secret.Data == nil { - return nil, fmt.Errorf("\"data\" not found in wrapping response") - } - if _, ok := secret.Data["response"]; !ok { - return nil, fmt.Errorf("\"response\" not found in wrapping response \"data\" map") - } - - wrappedSecret := new(Secret) - buf := bytes.NewBufferString(secret.Data["response"].(string)) - if err := jsonutil.DecodeJSONFromReader(buf, wrappedSecret); err != nil { - return nil, errwrap.Wrapf("error unmarshalling wrapped secret: {{err}}", err) - } - - return wrappedSecret, nil -} diff --git a/vendor/github.com/hashicorp/vault/api/renewer.go b/vendor/github.com/hashicorp/vault/api/renewer.go deleted file mode 100644 index 1d37a19..0000000 --- a/vendor/github.com/hashicorp/vault/api/renewer.go +++ /dev/null @@ -1,349 +0,0 @@ -package api - -import ( - "errors" - "math/rand" - "sync" - "time" -) - -var ( - ErrRenewerMissingInput = errors.New("missing input to renewer") - ErrRenewerMissingSecret = errors.New("missing secret to renew") - ErrRenewerNotRenewable = errors.New("secret is not renewable") - ErrRenewerNoSecretData = errors.New("returned empty secret data") - - // DefaultRenewerRenewBuffer is the default size of the buffer for renew - // messages on the channel. - DefaultRenewerRenewBuffer = 5 -) - -// Renewer is a process for renewing a secret. -// -// renewer, err := client.NewRenewer(&RenewerInput{ -// Secret: mySecret, -// }) -// go renewer.Renew() -// defer renewer.Stop() -// -// for { -// select { -// case err := <-renewer.DoneCh(): -// if err != nil { -// log.Fatal(err) -// } -// -// // Renewal is now over -// case renewal := <-renewer.RenewCh(): -// log.Printf("Successfully renewed: %#v", renewal) -// } -// } -// -// -// The `DoneCh` will return if renewal fails or if the remaining lease duration -// after a renewal is less than or equal to the grace (in number of seconds). In -// both cases, the caller should attempt a re-read of the secret. Clients should -// check the return value of the channel to see if renewal was successful. -type Renewer struct { - l sync.Mutex - - client *Client - secret *Secret - grace time.Duration - random *rand.Rand - increment int - doneCh chan error - renewCh chan *RenewOutput - - stopped bool - stopCh chan struct{} -} - -// RenewerInput is used as input to the renew function. -type RenewerInput struct { - // Secret is the secret to renew - Secret *Secret - - // DEPRECATED: this does not do anything. - Grace time.Duration - - // Rand is the randomizer to use for underlying randomization. If not - // provided, one will be generated and seeded automatically. If provided, it - // is assumed to have already been seeded. - Rand *rand.Rand - - // RenewBuffer is the size of the buffered channel where renew messages are - // dispatched. - RenewBuffer int - - // The new TTL, in seconds, that should be set on the lease. The TTL set - // here may or may not be honored by the vault server, based on Vault - // configuration or any associated max TTL values. - Increment int -} - -// RenewOutput is the metadata returned to the client (if it's listening) to -// renew messages. -type RenewOutput struct { - // RenewedAt is the timestamp when the renewal took place (UTC). - RenewedAt time.Time - - // Secret is the underlying renewal data. It's the same struct as all data - // that is returned from Vault, but since this is renewal data, it will not - // usually include the secret itself. - Secret *Secret -} - -// NewRenewer creates a new renewer from the given input. -func (c *Client) NewRenewer(i *RenewerInput) (*Renewer, error) { - if i == nil { - return nil, ErrRenewerMissingInput - } - - secret := i.Secret - if secret == nil { - return nil, ErrRenewerMissingSecret - } - - random := i.Rand - if random == nil { - random = rand.New(rand.NewSource(int64(time.Now().Nanosecond()))) - } - - renewBuffer := i.RenewBuffer - if renewBuffer == 0 { - renewBuffer = DefaultRenewerRenewBuffer - } - - return &Renewer{ - client: c, - secret: secret, - increment: i.Increment, - random: random, - doneCh: make(chan error, 1), - renewCh: make(chan *RenewOutput, renewBuffer), - - stopped: false, - stopCh: make(chan struct{}), - }, nil -} - -// DoneCh returns the channel where the renewer will publish when renewal stops. -// If there is an error, this will be an error. -func (r *Renewer) DoneCh() <-chan error { - return r.doneCh -} - -// RenewCh is a channel that receives a message when a successful renewal takes -// place and includes metadata about the renewal. -func (r *Renewer) RenewCh() <-chan *RenewOutput { - return r.renewCh -} - -// Stop stops the renewer. -func (r *Renewer) Stop() { - r.l.Lock() - if !r.stopped { - close(r.stopCh) - r.stopped = true - } - r.l.Unlock() -} - -// Renew starts a background process for renewing this secret. When the secret -// has auth data, this attempts to renew the auth (token). When the secret has -// a lease, this attempts to renew the lease. -func (r *Renewer) Renew() { - var result error - if r.secret.Auth != nil { - result = r.renewAuth() - } else { - result = r.renewLease() - } - - r.doneCh <- result -} - -// renewAuth is a helper for renewing authentication. -func (r *Renewer) renewAuth() error { - if !r.secret.Auth.Renewable || r.secret.Auth.ClientToken == "" { - return ErrRenewerNotRenewable - } - - priorDuration := time.Duration(r.secret.Auth.LeaseDuration) * time.Second - r.calculateGrace(priorDuration) - - client, token := r.client, r.secret.Auth.ClientToken - - for { - // Check if we are stopped. - select { - case <-r.stopCh: - return nil - default: - } - - // Renew the auth. - renewal, err := client.Auth().Token().RenewTokenAsSelf(token, r.increment) - if err != nil { - return err - } - - // Push a message that a renewal took place. - select { - case r.renewCh <- &RenewOutput{time.Now().UTC(), renewal}: - default: - } - - // Somehow, sometimes, this happens. - if renewal == nil || renewal.Auth == nil { - return ErrRenewerNoSecretData - } - - // Do nothing if we are not renewable - if !renewal.Auth.Renewable { - return ErrRenewerNotRenewable - } - - // Grab the lease duration - leaseDuration := time.Duration(renewal.Auth.LeaseDuration) * time.Second - - // We keep evaluating a new grace period so long as the lease is - // extending. Once it stops extending, we've hit the max and need to - // rely on the grace duration. - if leaseDuration > priorDuration { - r.calculateGrace(leaseDuration) - } - priorDuration = leaseDuration - - // The sleep duration is set to 2/3 of the current lease duration plus - // 1/3 of the current grace period, which adds jitter. - sleepDuration := time.Duration(float64(leaseDuration.Nanoseconds())*2/3 + float64(r.grace.Nanoseconds())/3) - - // If we are within grace, return now; or, if the amount of time we - // would sleep would land us in the grace period. This helps with short - // tokens; for example, you don't want a current lease duration of 4 - // seconds, a grace period of 3 seconds, and end up sleeping for more - // than three of those seconds and having a very small budget of time - // to renew. - if leaseDuration <= r.grace || leaseDuration-sleepDuration <= r.grace { - return nil - } - - select { - case <-r.stopCh: - return nil - case <-time.After(sleepDuration): - continue - } - } -} - -// renewLease is a helper for renewing a lease. -func (r *Renewer) renewLease() error { - if !r.secret.Renewable || r.secret.LeaseID == "" { - return ErrRenewerNotRenewable - } - - priorDuration := time.Duration(r.secret.LeaseDuration) * time.Second - r.calculateGrace(priorDuration) - - client, leaseID := r.client, r.secret.LeaseID - - for { - // Check if we are stopped. - select { - case <-r.stopCh: - return nil - default: - } - - // Renew the lease. - renewal, err := client.Sys().Renew(leaseID, r.increment) - if err != nil { - return err - } - - // Push a message that a renewal took place. - select { - case r.renewCh <- &RenewOutput{time.Now().UTC(), renewal}: - default: - } - - // Somehow, sometimes, this happens. - if renewal == nil { - return ErrRenewerNoSecretData - } - - // Do nothing if we are not renewable - if !renewal.Renewable { - return ErrRenewerNotRenewable - } - - // Grab the lease duration - leaseDuration := time.Duration(renewal.LeaseDuration) * time.Second - - // We keep evaluating a new grace period so long as the lease is - // extending. Once it stops extending, we've hit the max and need to - // rely on the grace duration. - if leaseDuration > priorDuration { - r.calculateGrace(leaseDuration) - } - priorDuration = leaseDuration - - // The sleep duration is set to 2/3 of the current lease duration plus - // 1/3 of the current grace period, which adds jitter. - sleepDuration := time.Duration(float64(leaseDuration.Nanoseconds())*2/3 + float64(r.grace.Nanoseconds())/3) - - // If we are within grace, return now; or, if the amount of time we - // would sleep would land us in the grace period. This helps with short - // tokens; for example, you don't want a current lease duration of 4 - // seconds, a grace period of 3 seconds, and end up sleeping for more - // than three of those seconds and having a very small budget of time - // to renew. - if leaseDuration <= r.grace || leaseDuration-sleepDuration <= r.grace { - return nil - } - - select { - case <-r.stopCh: - return nil - case <-time.After(sleepDuration): - continue - } - } -} - -// sleepDuration calculates the time to sleep given the base lease duration. The -// base is the resulting lease duration. It will be reduced to 1/3 and -// multiplied by a random float between 0.0 and 1.0. This extra randomness -// prevents multiple clients from all trying to renew simultaneously. -func (r *Renewer) sleepDuration(base time.Duration) time.Duration { - sleep := float64(base) - - // Renew at 1/3 the remaining lease. This will give us an opportunity to retry - // at least one more time should the first renewal fail. - sleep = sleep / 3.0 - - // Use a randomness so many clients do not hit Vault simultaneously. - sleep = sleep * (r.random.Float64() + 1) / 2.0 - - return time.Duration(sleep) -} - -// calculateGrace calculates the grace period based on a reasonable set of -// assumptions given the total lease time; it also adds some jitter to not have -// clients be in sync. -func (r *Renewer) calculateGrace(leaseDuration time.Duration) { - if leaseDuration == 0 { - r.grace = 0 - return - } - - leaseNanos := float64(leaseDuration.Nanoseconds()) - jitterMax := 0.1 * leaseNanos - - // For a given lease duration, we want to allow 80-90% of that to elapse, - // so the remaining amount is the grace period - r.grace = time.Duration(jitterMax) + time.Duration(uint64(r.random.Int63())%uint64(jitterMax)) -} diff --git a/vendor/github.com/hashicorp/vault/api/request.go b/vendor/github.com/hashicorp/vault/api/request.go deleted file mode 100644 index 5bcff8c..0000000 --- a/vendor/github.com/hashicorp/vault/api/request.go +++ /dev/null @@ -1,145 +0,0 @@ -package api - -import ( - "bytes" - "encoding/json" - "io" - "io/ioutil" - "net/http" - "net/url" - - retryablehttp "github.com/hashicorp/go-retryablehttp" -) - -// Request is a raw request configuration structure used to initiate -// API requests to the Vault server. -type Request struct { - Method string - URL *url.URL - Params url.Values - Headers http.Header - ClientToken string - MFAHeaderVals []string - WrapTTL string - Obj interface{} - - // When possible, use BodyBytes as it is more efficient due to how the - // retry logic works - BodyBytes []byte - - // Fallback - Body io.Reader - BodySize int64 - - // Whether to request overriding soft-mandatory Sentinel policies (RGPs and - // EGPs). If set, the override flag will take effect for all policies - // evaluated during the request. - PolicyOverride bool -} - -// SetJSONBody is used to set a request body that is a JSON-encoded value. -func (r *Request) SetJSONBody(val interface{}) error { - buf, err := json.Marshal(val) - if err != nil { - return err - } - - r.Obj = val - r.BodyBytes = buf - return nil -} - -// ResetJSONBody is used to reset the body for a redirect -func (r *Request) ResetJSONBody() error { - if r.BodyBytes == nil { - return nil - } - return r.SetJSONBody(r.Obj) -} - -// DEPRECATED: ToHTTP turns this request into a valid *http.Request for use -// with the net/http package. -func (r *Request) ToHTTP() (*http.Request, error) { - req, err := r.toRetryableHTTP() - if err != nil { - return nil, err - } - - switch { - case r.BodyBytes == nil && r.Body == nil: - // No body - - case r.BodyBytes != nil: - req.Request.Body = ioutil.NopCloser(bytes.NewReader(r.BodyBytes)) - - default: - if c, ok := r.Body.(io.ReadCloser); ok { - req.Request.Body = c - } else { - req.Request.Body = ioutil.NopCloser(r.Body) - } - } - - return req.Request, nil -} - -func (r *Request) toRetryableHTTP() (*retryablehttp.Request, error) { - // Encode the query parameters - r.URL.RawQuery = r.Params.Encode() - - // Create the HTTP request, defaulting to retryable - var req *retryablehttp.Request - - var err error - var body interface{} - - switch { - case r.BodyBytes == nil && r.Body == nil: - // No body - - case r.BodyBytes != nil: - // Use bytes, it's more efficient - body = r.BodyBytes - - default: - body = r.Body - } - - req, err = retryablehttp.NewRequest(r.Method, r.URL.RequestURI(), body) - if err != nil { - return nil, err - } - - req.URL.User = r.URL.User - req.URL.Scheme = r.URL.Scheme - req.URL.Host = r.URL.Host - req.Host = r.URL.Host - - if r.Headers != nil { - for header, vals := range r.Headers { - for _, val := range vals { - req.Header.Add(header, val) - } - } - } - - if len(r.ClientToken) != 0 { - req.Header.Set("X-Vault-Token", r.ClientToken) - } - - if len(r.WrapTTL) != 0 { - req.Header.Set("X-Vault-Wrap-TTL", r.WrapTTL) - } - - if len(r.MFAHeaderVals) != 0 { - for _, mfaHeaderVal := range r.MFAHeaderVals { - req.Header.Add("X-Vault-MFA", mfaHeaderVal) - } - } - - if r.PolicyOverride { - req.Header.Set("X-Vault-Policy-Override", "true") - } - - return req, nil -} diff --git a/vendor/github.com/hashicorp/vault/api/response.go b/vendor/github.com/hashicorp/vault/api/response.go deleted file mode 100644 index 053a277..0000000 --- a/vendor/github.com/hashicorp/vault/api/response.go +++ /dev/null @@ -1,77 +0,0 @@ -package api - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "net/http" - - "github.com/hashicorp/vault/helper/jsonutil" -) - -// Response is a raw response that wraps an HTTP response. -type Response struct { - *http.Response -} - -// DecodeJSON will decode the response body to a JSON structure. This -// will consume the response body, but will not close it. Close must -// still be called. -func (r *Response) DecodeJSON(out interface{}) error { - return jsonutil.DecodeJSONFromReader(r.Body, out) -} - -// Error returns an error response if there is one. If there is an error, -// this will fully consume the response body, but will not close it. The -// body must still be closed manually. -func (r *Response) Error() error { - // 200 to 399 are okay status codes. 429 is the code for health status of - // standby nodes. - if (r.StatusCode >= 200 && r.StatusCode < 400) || r.StatusCode == 429 { - return nil - } - - // We have an error. Let's copy the body into our own buffer first, - // so that if we can't decode JSON, we can at least copy it raw. - bodyBuf := &bytes.Buffer{} - if _, err := io.Copy(bodyBuf, r.Body); err != nil { - return err - } - - r.Body.Close() - r.Body = ioutil.NopCloser(bodyBuf) - - // Decode the error response if we can. Note that we wrap the bodyBuf - // in a bytes.Reader here so that the JSON decoder doesn't move the - // read pointer for the original buffer. - var resp ErrorResponse - if err := jsonutil.DecodeJSON(bodyBuf.Bytes(), &resp); err != nil { - // Ignore the decoding error and just drop the raw response - return fmt.Errorf( - "Error making API request.\n\n"+ - "URL: %s %s\n"+ - "Code: %d. Raw Message:\n\n%s", - r.Request.Method, r.Request.URL.String(), - r.StatusCode, bodyBuf.String()) - } - - var errBody bytes.Buffer - errBody.WriteString(fmt.Sprintf( - "Error making API request.\n\n"+ - "URL: %s %s\n"+ - "Code: %d. Errors:\n\n", - r.Request.Method, r.Request.URL.String(), - r.StatusCode)) - for _, err := range resp.Errors { - errBody.WriteString(fmt.Sprintf("* %s", err)) - } - - return fmt.Errorf(errBody.String()) -} - -// ErrorResponse is the raw structure of errors when they're returned by the -// HTTP API. -type ErrorResponse struct { - Errors []string -} diff --git a/vendor/github.com/hashicorp/vault/api/secret.go b/vendor/github.com/hashicorp/vault/api/secret.go deleted file mode 100644 index e259626..0000000 --- a/vendor/github.com/hashicorp/vault/api/secret.go +++ /dev/null @@ -1,320 +0,0 @@ -package api - -import ( - "bytes" - "fmt" - "io" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/parseutil" -) - -// Secret is the structure returned for every secret within Vault. -type Secret struct { - // The request ID that generated this response - RequestID string `json:"request_id"` - - LeaseID string `json:"lease_id"` - LeaseDuration int `json:"lease_duration"` - Renewable bool `json:"renewable"` - - // Data is the actual contents of the secret. The format of the data - // is arbitrary and up to the secret backend. - Data map[string]interface{} `json:"data"` - - // Warnings contains any warnings related to the operation. These - // are not issues that caused the command to fail, but that the - // client should be aware of. - Warnings []string `json:"warnings"` - - // Auth, if non-nil, means that there was authentication information - // attached to this response. - Auth *SecretAuth `json:"auth,omitempty"` - - // WrapInfo, if non-nil, means that the initial response was wrapped in the - // cubbyhole of the given token (which has a TTL of the given number of - // seconds) - WrapInfo *SecretWrapInfo `json:"wrap_info,omitempty"` -} - -// TokenID returns the standardized token ID (token) for the given secret. -func (s *Secret) TokenID() (string, error) { - if s == nil { - return "", nil - } - - if s.Auth != nil && len(s.Auth.ClientToken) > 0 { - return s.Auth.ClientToken, nil - } - - if s.Data == nil || s.Data["id"] == nil { - return "", nil - } - - id, ok := s.Data["id"].(string) - if !ok { - return "", fmt.Errorf("token found but in the wrong format") - } - - return id, nil -} - -// TokenAccessor returns the standardized token accessor for the given secret. -// If the secret is nil or does not contain an accessor, this returns the empty -// string. -func (s *Secret) TokenAccessor() (string, error) { - if s == nil { - return "", nil - } - - if s.Auth != nil && len(s.Auth.Accessor) > 0 { - return s.Auth.Accessor, nil - } - - if s.Data == nil || s.Data["accessor"] == nil { - return "", nil - } - - accessor, ok := s.Data["accessor"].(string) - if !ok { - return "", fmt.Errorf("token found but in the wrong format") - } - - return accessor, nil -} - -// TokenRemainingUses returns the standardized remaining uses for the given -// secret. If the secret is nil or does not contain the "num_uses", this -// returns -1. On error, this will return -1 and a non-nil error. -func (s *Secret) TokenRemainingUses() (int, error) { - if s == nil || s.Data == nil || s.Data["num_uses"] == nil { - return -1, nil - } - - uses, err := parseutil.ParseInt(s.Data["num_uses"]) - if err != nil { - return 0, err - } - - return int(uses), nil -} - -// TokenPolicies returns the standardized list of policies for the given secret. -// If the secret is nil or does not contain any policies, this returns nil. It -// also populates the secret's Auth info with identity/token policy info. -func (s *Secret) TokenPolicies() ([]string, error) { - if s == nil { - return nil, nil - } - - if s.Auth != nil && len(s.Auth.Policies) > 0 { - return s.Auth.Policies, nil - } - - if s.Data == nil || s.Data["policies"] == nil { - return nil, nil - } - - var tokenPolicies []string - - // Token policies - { - _, ok := s.Data["policies"] - if !ok { - goto TOKEN_DONE - } - - sList, ok := s.Data["policies"].([]string) - if ok { - tokenPolicies = sList - goto TOKEN_DONE - } - - list, ok := s.Data["policies"].([]interface{}) - if !ok { - return nil, fmt.Errorf("unable to convert token policies to expected format") - } - for _, v := range list { - p, ok := v.(string) - if !ok { - return nil, fmt.Errorf("unable to convert policy %v to string", v) - } - tokenPolicies = append(tokenPolicies, p) - } - } - -TOKEN_DONE: - var identityPolicies []string - - // Identity policies - { - _, ok := s.Data["identity_policies"] - if !ok { - goto DONE - } - - sList, ok := s.Data["identity_policies"].([]string) - if ok { - identityPolicies = sList - goto DONE - } - - list, ok := s.Data["identity_policies"].([]interface{}) - if !ok { - return nil, fmt.Errorf("unable to convert identity policies to expected format") - } - for _, v := range list { - p, ok := v.(string) - if !ok { - return nil, fmt.Errorf("unable to convert policy %v to string", v) - } - identityPolicies = append(identityPolicies, p) - } - } - -DONE: - - if s.Auth == nil { - s.Auth = &SecretAuth{} - } - - policies := append(tokenPolicies, identityPolicies...) - - s.Auth.TokenPolicies = tokenPolicies - s.Auth.IdentityPolicies = identityPolicies - s.Auth.Policies = policies - - return policies, nil -} - -// TokenMetadata returns the map of metadata associated with this token, if any -// exists. If the secret is nil or does not contain the "metadata" key, this -// returns nil. -func (s *Secret) TokenMetadata() (map[string]string, error) { - if s == nil { - return nil, nil - } - - if s.Auth != nil && len(s.Auth.Metadata) > 0 { - return s.Auth.Metadata, nil - } - - if s.Data == nil || (s.Data["metadata"] == nil && s.Data["meta"] == nil) { - return nil, nil - } - - data, ok := s.Data["metadata"].(map[string]interface{}) - if !ok { - data, ok = s.Data["meta"].(map[string]interface{}) - if !ok { - return nil, fmt.Errorf("unable to convert metadata field to expected format") - } - } - - metadata := make(map[string]string, len(data)) - for k, v := range data { - typed, ok := v.(string) - if !ok { - return nil, fmt.Errorf("unable to convert metadata value %v to string", v) - } - metadata[k] = typed - } - - return metadata, nil -} - -// TokenIsRenewable returns the standardized token renewability for the given -// secret. If the secret is nil or does not contain the "renewable" key, this -// returns false. -func (s *Secret) TokenIsRenewable() (bool, error) { - if s == nil { - return false, nil - } - - if s.Auth != nil && s.Auth.Renewable { - return s.Auth.Renewable, nil - } - - if s.Data == nil || s.Data["renewable"] == nil { - return false, nil - } - - renewable, err := parseutil.ParseBool(s.Data["renewable"]) - if err != nil { - return false, errwrap.Wrapf("could not convert renewable value to a boolean: {{err}}", err) - } - - return renewable, nil -} - -// TokenTTL returns the standardized remaining token TTL for the given secret. -// If the secret is nil or does not contain a TTL, this returns 0. -func (s *Secret) TokenTTL() (time.Duration, error) { - if s == nil { - return 0, nil - } - - if s.Auth != nil && s.Auth.LeaseDuration > 0 { - return time.Duration(s.Auth.LeaseDuration) * time.Second, nil - } - - if s.Data == nil || s.Data["ttl"] == nil { - return 0, nil - } - - ttl, err := parseutil.ParseDurationSecond(s.Data["ttl"]) - if err != nil { - return 0, err - } - - return ttl, nil -} - -// SecretWrapInfo contains wrapping information if we have it. If what is -// contained is an authentication token, the accessor for the token will be -// available in WrappedAccessor. -type SecretWrapInfo struct { - Token string `json:"token"` - Accessor string `json:"accessor"` - TTL int `json:"ttl"` - CreationTime time.Time `json:"creation_time"` - CreationPath string `json:"creation_path"` - WrappedAccessor string `json:"wrapped_accessor"` -} - -// SecretAuth is the structure containing auth information if we have it. -type SecretAuth struct { - ClientToken string `json:"client_token"` - Accessor string `json:"accessor"` - Policies []string `json:"policies"` - TokenPolicies []string `json:"token_policies"` - IdentityPolicies []string `json:"identity_policies"` - Metadata map[string]string `json:"metadata"` - - LeaseDuration int `json:"lease_duration"` - Renewable bool `json:"renewable"` -} - -// ParseSecret is used to parse a secret value from JSON from an io.Reader. -func ParseSecret(r io.Reader) (*Secret, error) { - // First read the data into a buffer. Not super efficient but we want to - // know if we actually have a body or not. - var buf bytes.Buffer - _, err := buf.ReadFrom(r) - if err != nil { - return nil, err - } - if buf.Len() == 0 { - return nil, nil - } - - // First decode the JSON into a map[string]interface{} - var secret Secret - if err := jsonutil.DecodeJSONFromReader(&buf, &secret); err != nil { - return nil, err - } - - return &secret, nil -} diff --git a/vendor/github.com/hashicorp/vault/api/ssh.go b/vendor/github.com/hashicorp/vault/api/ssh.go deleted file mode 100644 index 837eac4..0000000 --- a/vendor/github.com/hashicorp/vault/api/ssh.go +++ /dev/null @@ -1,62 +0,0 @@ -package api - -import ( - "context" - "fmt" -) - -// SSH is used to return a client to invoke operations on SSH backend. -type SSH struct { - c *Client - MountPoint string -} - -// SSH returns the client for logical-backend API calls. -func (c *Client) SSH() *SSH { - return c.SSHWithMountPoint(SSHHelperDefaultMountPoint) -} - -// SSHWithMountPoint returns the client with specific SSH mount point. -func (c *Client) SSHWithMountPoint(mountPoint string) *SSH { - return &SSH{ - c: c, - MountPoint: mountPoint, - } -} - -// Credential invokes the SSH backend API to create a credential to establish an SSH session. -func (c *SSH) Credential(role string, data map[string]interface{}) (*Secret, error) { - r := c.c.NewRequest("PUT", fmt.Sprintf("/v1/%s/creds/%s", c.MountPoint, role)) - if err := r.SetJSONBody(data); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - return ParseSecret(resp.Body) -} - -// SignKey signs the given public key and returns a signed public key to pass -// along with the SSH request. -func (c *SSH) SignKey(role string, data map[string]interface{}) (*Secret, error) { - r := c.c.NewRequest("PUT", fmt.Sprintf("/v1/%s/sign/%s", c.MountPoint, role)) - if err := r.SetJSONBody(data); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - return ParseSecret(resp.Body) -} diff --git a/vendor/github.com/hashicorp/vault/api/ssh_agent.go b/vendor/github.com/hashicorp/vault/api/ssh_agent.go deleted file mode 100644 index 1dd681a..0000000 --- a/vendor/github.com/hashicorp/vault/api/ssh_agent.go +++ /dev/null @@ -1,234 +0,0 @@ -package api - -import ( - "context" - "crypto/tls" - "crypto/x509" - "fmt" - "io/ioutil" - "os" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/go-multierror" - "github.com/hashicorp/go-rootcerts" - "github.com/hashicorp/hcl" - "github.com/hashicorp/hcl/hcl/ast" - "github.com/hashicorp/vault/helper/hclutil" - "github.com/mitchellh/mapstructure" -) - -const ( - // SSHHelperDefaultMountPoint is the default path at which SSH backend will be - // mounted in the Vault server. - SSHHelperDefaultMountPoint = "ssh" - - // VerifyEchoRequest is the echo request message sent as OTP by the helper. - VerifyEchoRequest = "verify-echo-request" - - // VerifyEchoResponse is the echo response message sent as a response to OTP - // matching echo request. - VerifyEchoResponse = "verify-echo-response" -) - -// SSHHelper is a structure representing a vault-ssh-helper which can talk to vault server -// in order to verify the OTP entered by the user. It contains the path at which -// SSH backend is mounted at the server. -type SSHHelper struct { - c *Client - MountPoint string -} - -// SSHVerifyResponse is a structure representing the fields in Vault server's -// response. -type SSHVerifyResponse struct { - // Usually empty. If the request OTP is echo request message, this will - // be set to the corresponding echo response message. - Message string `json:"message" mapstructure:"message"` - - // Username associated with the OTP - Username string `json:"username" mapstructure:"username"` - - // IP associated with the OTP - IP string `json:"ip" mapstructure:"ip"` - - // Name of the role against which the OTP was issued - RoleName string `json:"role_name" mapstructure:"role_name"` -} - -// SSHHelperConfig is a structure which represents the entries from the vault-ssh-helper's configuration file. -type SSHHelperConfig struct { - VaultAddr string `hcl:"vault_addr"` - SSHMountPoint string `hcl:"ssh_mount_point"` - CACert string `hcl:"ca_cert"` - CAPath string `hcl:"ca_path"` - AllowedCidrList string `hcl:"allowed_cidr_list"` - AllowedRoles string `hcl:"allowed_roles"` - TLSSkipVerify bool `hcl:"tls_skip_verify"` - TLSServerName string `hcl:"tls_server_name"` -} - -// SetTLSParameters sets the TLS parameters for this SSH agent. -func (c *SSHHelperConfig) SetTLSParameters(clientConfig *Config, certPool *x509.CertPool) { - tlsConfig := &tls.Config{ - InsecureSkipVerify: c.TLSSkipVerify, - MinVersion: tls.VersionTLS12, - RootCAs: certPool, - ServerName: c.TLSServerName, - } - - transport := cleanhttp.DefaultTransport() - transport.TLSClientConfig = tlsConfig - clientConfig.HttpClient.Transport = transport -} - -// Returns true if any of the following conditions are true: -// * CA cert is configured -// * CA path is configured -// * configured to skip certificate verification -// * TLS server name is configured -// -func (c *SSHHelperConfig) shouldSetTLSParameters() bool { - return c.CACert != "" || c.CAPath != "" || c.TLSServerName != "" || c.TLSSkipVerify -} - -// NewClient returns a new client for the configuration. This client will be used by the -// vault-ssh-helper to communicate with Vault server and verify the OTP entered by user. -// If the configuration supplies Vault SSL certificates, then the client will -// have TLS configured in its transport. -func (c *SSHHelperConfig) NewClient() (*Client, error) { - // Creating a default client configuration for communicating with vault server. - clientConfig := DefaultConfig() - - // Pointing the client to the actual address of vault server. - clientConfig.Address = c.VaultAddr - - // Check if certificates are provided via config file. - if c.shouldSetTLSParameters() { - rootConfig := &rootcerts.Config{ - CAFile: c.CACert, - CAPath: c.CAPath, - } - certPool, err := rootcerts.LoadCACerts(rootConfig) - if err != nil { - return nil, err - } - // Enable TLS on the HTTP client information - c.SetTLSParameters(clientConfig, certPool) - } - - // Creating the client object for the given configuration - client, err := NewClient(clientConfig) - if err != nil { - return nil, err - } - - return client, nil -} - -// LoadSSHHelperConfig loads ssh-helper's configuration from the file and populates the corresponding -// in-memory structure. -// -// Vault address is a required parameter. -// Mount point defaults to "ssh". -func LoadSSHHelperConfig(path string) (*SSHHelperConfig, error) { - contents, err := ioutil.ReadFile(path) - if err != nil && !os.IsNotExist(err) { - return nil, multierror.Prefix(err, "ssh_helper:") - } - return ParseSSHHelperConfig(string(contents)) -} - -// ParseSSHHelperConfig parses the given contents as a string for the SSHHelper -// configuration. -func ParseSSHHelperConfig(contents string) (*SSHHelperConfig, error) { - root, err := hcl.Parse(string(contents)) - if err != nil { - return nil, errwrap.Wrapf("error parsing config: {{err}}", err) - } - - list, ok := root.Node.(*ast.ObjectList) - if !ok { - return nil, fmt.Errorf("error parsing config: file doesn't contain a root object") - } - - valid := []string{ - "vault_addr", - "ssh_mount_point", - "ca_cert", - "ca_path", - "allowed_cidr_list", - "allowed_roles", - "tls_skip_verify", - "tls_server_name", - } - if err := hclutil.CheckHCLKeys(list, valid); err != nil { - return nil, multierror.Prefix(err, "ssh_helper:") - } - - var c SSHHelperConfig - c.SSHMountPoint = SSHHelperDefaultMountPoint - if err := hcl.DecodeObject(&c, list); err != nil { - return nil, multierror.Prefix(err, "ssh_helper:") - } - - if c.VaultAddr == "" { - return nil, fmt.Errorf(`missing config "vault_addr"`) - } - return &c, nil -} - -// SSHHelper creates an SSHHelper object which can talk to Vault server with SSH backend -// mounted at default path ("ssh"). -func (c *Client) SSHHelper() *SSHHelper { - return c.SSHHelperWithMountPoint(SSHHelperDefaultMountPoint) -} - -// SSHHelperWithMountPoint creates an SSHHelper object which can talk to Vault server with SSH backend -// mounted at a specific mount point. -func (c *Client) SSHHelperWithMountPoint(mountPoint string) *SSHHelper { - return &SSHHelper{ - c: c, - MountPoint: mountPoint, - } -} - -// Verify verifies if the key provided by user is present in Vault server. The response -// will contain the IP address and username associated with the OTP. In case the -// OTP matches the echo request message, instead of searching an entry for the OTP, -// an echo response message is returned. This feature is used by ssh-helper to verify if -// its configured correctly. -func (c *SSHHelper) Verify(otp string) (*SSHVerifyResponse, error) { - data := map[string]interface{}{ - "otp": otp, - } - verifyPath := fmt.Sprintf("/v1/%s/verify", c.MountPoint) - r := c.c.NewRequest("PUT", verifyPath) - if err := r.SetJSONBody(data); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - - if secret.Data == nil { - return nil, nil - } - - var verifyResp SSHVerifyResponse - err = mapstructure.Decode(secret.Data, &verifyResp) - if err != nil { - return nil, err - } - return &verifyResp, nil -} diff --git a/vendor/github.com/hashicorp/vault/api/sys.go b/vendor/github.com/hashicorp/vault/api/sys.go deleted file mode 100644 index 5fb1118..0000000 --- a/vendor/github.com/hashicorp/vault/api/sys.go +++ /dev/null @@ -1,11 +0,0 @@ -package api - -// Sys is used to perform system-related operations on Vault. -type Sys struct { - c *Client -} - -// Sys is used to return the client for sys-related API calls. -func (c *Client) Sys() *Sys { - return &Sys{c: c} -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_audit.go b/vendor/github.com/hashicorp/vault/api/sys_audit.go deleted file mode 100644 index 2448c03..0000000 --- a/vendor/github.com/hashicorp/vault/api/sys_audit.go +++ /dev/null @@ -1,136 +0,0 @@ -package api - -import ( - "context" - "errors" - "fmt" - - "github.com/mitchellh/mapstructure" -) - -func (c *Sys) AuditHash(path string, input string) (string, error) { - body := map[string]interface{}{ - "input": input, - } - - r := c.c.NewRequest("PUT", fmt.Sprintf("/v1/sys/audit-hash/%s", path)) - if err := r.SetJSONBody(body); err != nil { - return "", err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return "", err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return "", err - } - if secret == nil || secret.Data == nil { - return "", errors.New("data from server response is empty") - } - - hash, ok := secret.Data["hash"] - if !ok { - return "", errors.New("hash not found in response data") - } - hashStr, ok := hash.(string) - if !ok { - return "", errors.New("could not parse hash in response data") - } - - return hashStr, nil -} - -func (c *Sys) ListAudit() (map[string]*Audit, error) { - r := c.c.NewRequest("GET", "/v1/sys/audit") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - mounts := map[string]*Audit{} - err = mapstructure.Decode(secret.Data, &mounts) - if err != nil { - return nil, err - } - - return mounts, nil -} - -// DEPRECATED: Use EnableAuditWithOptions instead -func (c *Sys) EnableAudit( - path string, auditType string, desc string, opts map[string]string) error { - return c.EnableAuditWithOptions(path, &EnableAuditOptions{ - Type: auditType, - Description: desc, - Options: opts, - }) -} - -func (c *Sys) EnableAuditWithOptions(path string, options *EnableAuditOptions) error { - r := c.c.NewRequest("PUT", fmt.Sprintf("/v1/sys/audit/%s", path)) - if err := r.SetJSONBody(options); err != nil { - return err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - - if err != nil { - return err - } - defer resp.Body.Close() - - return nil -} - -func (c *Sys) DisableAudit(path string) error { - r := c.c.NewRequest("DELETE", fmt.Sprintf("/v1/sys/audit/%s", path)) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - - if err == nil { - defer resp.Body.Close() - } - return err -} - -// Structures for the requests/resposne are all down here. They aren't -// individually documented because the map almost directly to the raw HTTP API -// documentation. Please refer to that documentation for more details. - -type EnableAuditOptions struct { - Type string `json:"type" mapstructure:"type"` - Description string `json:"description" mapstructure:"description"` - Options map[string]string `json:"options" mapstructure:"options"` - Local bool `json:"local" mapstructure:"local"` -} - -type Audit struct { - Type string `json:"type" mapstructure:"type"` - Description string `json:"description" mapstructure:"description"` - Options map[string]string `json:"options" mapstructure:"options"` - Local bool `json:"local" mapstructure:"local"` - Path string `json:"path" mapstructure:"path"` -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_auth.go b/vendor/github.com/hashicorp/vault/api/sys_auth.go deleted file mode 100644 index 447c5d5..0000000 --- a/vendor/github.com/hashicorp/vault/api/sys_auth.go +++ /dev/null @@ -1,118 +0,0 @@ -package api - -import ( - "context" - "errors" - "fmt" - - "github.com/mitchellh/mapstructure" -) - -func (c *Sys) ListAuth() (map[string]*AuthMount, error) { - r := c.c.NewRequest("GET", "/v1/sys/auth") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - mounts := map[string]*AuthMount{} - err = mapstructure.Decode(secret.Data, &mounts) - if err != nil { - return nil, err - } - - return mounts, nil -} - -// DEPRECATED: Use EnableAuthWithOptions instead -func (c *Sys) EnableAuth(path, authType, desc string) error { - return c.EnableAuthWithOptions(path, &EnableAuthOptions{ - Type: authType, - Description: desc, - }) -} - -func (c *Sys) EnableAuthWithOptions(path string, options *EnableAuthOptions) error { - r := c.c.NewRequest("POST", fmt.Sprintf("/v1/sys/auth/%s", path)) - if err := r.SetJSONBody(options); err != nil { - return err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return err - } - defer resp.Body.Close() - - return nil -} - -func (c *Sys) DisableAuth(path string) error { - r := c.c.NewRequest("DELETE", fmt.Sprintf("/v1/sys/auth/%s", path)) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -// Structures for the requests/resposne are all down here. They aren't -// individually documented because the map almost directly to the raw HTTP API -// documentation. Please refer to that documentation for more details. - -type EnableAuthOptions struct { - Type string `json:"type"` - Description string `json:"description"` - Config AuthConfigInput `json:"config"` - Local bool `json:"local"` - PluginName string `json:"plugin_name,omitempty"` - SealWrap bool `json:"seal_wrap" mapstructure:"seal_wrap"` - Options map[string]string `json:"options" mapstructure:"options"` -} - -type AuthConfigInput struct { - DefaultLeaseTTL string `json:"default_lease_ttl" mapstructure:"default_lease_ttl"` - MaxLeaseTTL string `json:"max_lease_ttl" mapstructure:"max_lease_ttl"` - PluginName string `json:"plugin_name,omitempty" mapstructure:"plugin_name"` - AuditNonHMACRequestKeys []string `json:"audit_non_hmac_request_keys,omitempty" mapstructure:"audit_non_hmac_request_keys"` - AuditNonHMACResponseKeys []string `json:"audit_non_hmac_response_keys,omitempty" mapstructure:"audit_non_hmac_response_keys"` - ListingVisibility string `json:"listing_visibility,omitempty" mapstructure:"listing_visibility"` - PassthroughRequestHeaders []string `json:"passthrough_request_headers,omitempty" mapstructure:"passthrough_request_headers"` -} - -type AuthMount struct { - Type string `json:"type" mapstructure:"type"` - Description string `json:"description" mapstructure:"description"` - Accessor string `json:"accessor" mapstructure:"accessor"` - Config AuthConfigOutput `json:"config" mapstructure:"config"` - Local bool `json:"local" mapstructure:"local"` - SealWrap bool `json:"seal_wrap" mapstructure:"seal_wrap"` - Options map[string]string `json:"options" mapstructure:"options"` -} - -type AuthConfigOutput struct { - DefaultLeaseTTL int `json:"default_lease_ttl" mapstructure:"default_lease_ttl"` - MaxLeaseTTL int `json:"max_lease_ttl" mapstructure:"max_lease_ttl"` - PluginName string `json:"plugin_name,omitempty" mapstructure:"plugin_name"` - AuditNonHMACRequestKeys []string `json:"audit_non_hmac_request_keys,omitempty" mapstructure:"audit_non_hmac_request_keys"` - AuditNonHMACResponseKeys []string `json:"audit_non_hmac_response_keys,omitempty" mapstructure:"audit_non_hmac_response_keys"` - ListingVisibility string `json:"listing_visibility,omitempty" mapstructure:"listing_visibility"` - PassthroughRequestHeaders []string `json:"passthrough_request_headers,omitempty" mapstructure:"passthrough_request_headers"` -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_capabilities.go b/vendor/github.com/hashicorp/vault/api/sys_capabilities.go deleted file mode 100644 index 242acf9..0000000 --- a/vendor/github.com/hashicorp/vault/api/sys_capabilities.go +++ /dev/null @@ -1,54 +0,0 @@ -package api - -import ( - "context" - "errors" - "fmt" - - "github.com/mitchellh/mapstructure" -) - -func (c *Sys) CapabilitiesSelf(path string) ([]string, error) { - return c.Capabilities(c.c.Token(), path) -} - -func (c *Sys) Capabilities(token, path string) ([]string, error) { - body := map[string]string{ - "token": token, - "path": path, - } - - reqPath := "/v1/sys/capabilities" - if token == c.c.Token() { - reqPath = fmt.Sprintf("%s-self", reqPath) - } - - r := c.c.NewRequest("POST", reqPath) - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - var res []string - err = mapstructure.Decode(secret.Data[path], &res) - if err != nil { - return nil, err - } - - return res, nil -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_config_cors.go b/vendor/github.com/hashicorp/vault/api/sys_config_cors.go deleted file mode 100644 index d153a47..0000000 --- a/vendor/github.com/hashicorp/vault/api/sys_config_cors.go +++ /dev/null @@ -1,105 +0,0 @@ -package api - -import ( - "context" - "errors" - - "github.com/mitchellh/mapstructure" -) - -func (c *Sys) CORSStatus() (*CORSResponse, error) { - r := c.c.NewRequest("GET", "/v1/sys/config/cors") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - var result CORSResponse - err = mapstructure.Decode(secret.Data, &result) - if err != nil { - return nil, err - } - - return &result, err -} - -func (c *Sys) ConfigureCORS(req *CORSRequest) (*CORSResponse, error) { - r := c.c.NewRequest("PUT", "/v1/sys/config/cors") - if err := r.SetJSONBody(req); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - var result CORSResponse - err = mapstructure.Decode(secret.Data, &result) - if err != nil { - return nil, err - } - - return &result, err -} - -func (c *Sys) DisableCORS() (*CORSResponse, error) { - r := c.c.NewRequest("DELETE", "/v1/sys/config/cors") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - var result CORSResponse - err = mapstructure.Decode(secret.Data, &result) - if err != nil { - return nil, err - } - - return &result, err -} - -type CORSRequest struct { - AllowedOrigins string `json:"allowed_origins" mapstructure:"allowed_origins"` - Enabled bool `json:"enabled" mapstructure:"enabled"` -} - -type CORSResponse struct { - AllowedOrigins string `json:"allowed_origins" mapstructure:"allowed_origins"` - Enabled bool `json:"enabled" mapstructure:"enabled"` -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_generate_root.go b/vendor/github.com/hashicorp/vault/api/sys_generate_root.go deleted file mode 100644 index 66f72df..0000000 --- a/vendor/github.com/hashicorp/vault/api/sys_generate_root.go +++ /dev/null @@ -1,124 +0,0 @@ -package api - -import "context" - -func (c *Sys) GenerateRootStatus() (*GenerateRootStatusResponse, error) { - return c.generateRootStatusCommon("/v1/sys/generate-root/attempt") -} - -func (c *Sys) GenerateDROperationTokenStatus() (*GenerateRootStatusResponse, error) { - return c.generateRootStatusCommon("/v1/sys/replication/dr/secondary/generate-operation-token/attempt") -} - -func (c *Sys) generateRootStatusCommon(path string) (*GenerateRootStatusResponse, error) { - r := c.c.NewRequest("GET", path) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result GenerateRootStatusResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -func (c *Sys) GenerateRootInit(otp, pgpKey string) (*GenerateRootStatusResponse, error) { - return c.generateRootInitCommon("/v1/sys/generate-root/attempt", otp, pgpKey) -} - -func (c *Sys) GenerateDROperationTokenInit(otp, pgpKey string) (*GenerateRootStatusResponse, error) { - return c.generateRootInitCommon("/v1/sys/replication/dr/secondary/generate-operation-token/attempt", otp, pgpKey) -} - -func (c *Sys) generateRootInitCommon(path, otp, pgpKey string) (*GenerateRootStatusResponse, error) { - body := map[string]interface{}{ - "otp": otp, - "pgp_key": pgpKey, - } - - r := c.c.NewRequest("PUT", path) - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result GenerateRootStatusResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -func (c *Sys) GenerateRootCancel() error { - return c.generateRootCancelCommon("/v1/sys/generate-root/attempt") -} - -func (c *Sys) GenerateDROperationTokenCancel() error { - return c.generateRootCancelCommon("/v1/sys/replication/dr/secondary/generate-operation-token/attempt") -} - -func (c *Sys) generateRootCancelCommon(path string) error { - r := c.c.NewRequest("DELETE", path) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) GenerateRootUpdate(shard, nonce string) (*GenerateRootStatusResponse, error) { - return c.generateRootUpdateCommon("/v1/sys/generate-root/update", shard, nonce) -} - -func (c *Sys) GenerateDROperationTokenUpdate(shard, nonce string) (*GenerateRootStatusResponse, error) { - return c.generateRootUpdateCommon("/v1/sys/replication/dr/secondary/generate-operation-token/update", shard, nonce) -} - -func (c *Sys) generateRootUpdateCommon(path, shard, nonce string) (*GenerateRootStatusResponse, error) { - body := map[string]interface{}{ - "key": shard, - "nonce": nonce, - } - - r := c.c.NewRequest("PUT", path) - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result GenerateRootStatusResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -type GenerateRootStatusResponse struct { - Nonce string `json:"nonce"` - Started bool `json:"started"` - Progress int `json:"progress"` - Required int `json:"required"` - Complete bool `json:"complete"` - EncodedToken string `json:"encoded_token"` - EncodedRootToken string `json:"encoded_root_token"` - PGPFingerprint string `json:"pgp_fingerprint"` - OTP string `json:"otp"` - OTPLength int `json:"otp_length"` -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_health.go b/vendor/github.com/hashicorp/vault/api/sys_health.go deleted file mode 100644 index bd74e82..0000000 --- a/vendor/github.com/hashicorp/vault/api/sys_health.go +++ /dev/null @@ -1,39 +0,0 @@ -package api - -import "context" - -func (c *Sys) Health() (*HealthResponse, error) { - r := c.c.NewRequest("GET", "/v1/sys/health") - // If the code is 400 or above it will automatically turn into an error, - // but the sys/health API defaults to returning 5xx when not sealed or - // inited, so we force this code to be something else so we parse correctly - r.Params.Add("uninitcode", "299") - r.Params.Add("sealedcode", "299") - r.Params.Add("standbycode", "299") - r.Params.Add("drsecondarycode", "299") - r.Params.Add("performancestandbycode", "299") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result HealthResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -type HealthResponse struct { - Initialized bool `json:"initialized"` - Sealed bool `json:"sealed"` - Standby bool `json:"standby"` - ReplicationPerformanceMode string `json:"replication_performance_mode"` - ReplicationDRMode string `json:"replication_dr_mode"` - ServerTimeUTC int64 `json:"server_time_utc"` - Version string `json:"version"` - ClusterName string `json:"cluster_name,omitempty"` - ClusterID string `json:"cluster_id,omitempty"` -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_init.go b/vendor/github.com/hashicorp/vault/api/sys_init.go deleted file mode 100644 index 0e499c6..0000000 --- a/vendor/github.com/hashicorp/vault/api/sys_init.go +++ /dev/null @@ -1,61 +0,0 @@ -package api - -import "context" - -func (c *Sys) InitStatus() (bool, error) { - r := c.c.NewRequest("GET", "/v1/sys/init") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return false, err - } - defer resp.Body.Close() - - var result InitStatusResponse - err = resp.DecodeJSON(&result) - return result.Initialized, err -} - -func (c *Sys) Init(opts *InitRequest) (*InitResponse, error) { - r := c.c.NewRequest("PUT", "/v1/sys/init") - if err := r.SetJSONBody(opts); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result InitResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -type InitRequest struct { - SecretShares int `json:"secret_shares"` - SecretThreshold int `json:"secret_threshold"` - StoredShares int `json:"stored_shares"` - PGPKeys []string `json:"pgp_keys"` - RecoveryShares int `json:"recovery_shares"` - RecoveryThreshold int `json:"recovery_threshold"` - RecoveryPGPKeys []string `json:"recovery_pgp_keys"` - RootTokenPGPKey string `json:"root_token_pgp_key"` -} - -type InitStatusResponse struct { - Initialized bool -} - -type InitResponse struct { - Keys []string `json:"keys"` - KeysB64 []string `json:"keys_base64"` - RecoveryKeys []string `json:"recovery_keys"` - RecoveryKeysB64 []string `json:"recovery_keys_base64"` - RootToken string `json:"root_token"` -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_leader.go b/vendor/github.com/hashicorp/vault/api/sys_leader.go deleted file mode 100644 index dfef834..0000000 --- a/vendor/github.com/hashicorp/vault/api/sys_leader.go +++ /dev/null @@ -1,28 +0,0 @@ -package api - -import "context" - -func (c *Sys) Leader() (*LeaderResponse, error) { - r := c.c.NewRequest("GET", "/v1/sys/leader") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result LeaderResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -type LeaderResponse struct { - HAEnabled bool `json:"ha_enabled"` - IsSelf bool `json:"is_self"` - LeaderAddress string `json:"leader_address"` - LeaderClusterAddress string `json:"leader_cluster_address"` - PerfStandby bool `json:"performance_standby"` - PerfStandbyLastRemoteWAL uint64 `json:"performance_standby_last_remote_wal"` -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_leases.go b/vendor/github.com/hashicorp/vault/api/sys_leases.go deleted file mode 100644 index 09c9642..0000000 --- a/vendor/github.com/hashicorp/vault/api/sys_leases.go +++ /dev/null @@ -1,105 +0,0 @@ -package api - -import ( - "context" - "errors" -) - -func (c *Sys) Renew(id string, increment int) (*Secret, error) { - r := c.c.NewRequest("PUT", "/v1/sys/leases/renew") - - body := map[string]interface{}{ - "increment": increment, - "lease_id": id, - } - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - return ParseSecret(resp.Body) -} - -func (c *Sys) Revoke(id string) error { - r := c.c.NewRequest("PUT", "/v1/sys/leases/revoke/"+id) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) RevokePrefix(id string) error { - r := c.c.NewRequest("PUT", "/v1/sys/leases/revoke-prefix/"+id) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) RevokeForce(id string) error { - r := c.c.NewRequest("PUT", "/v1/sys/leases/revoke-force/"+id) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) RevokeWithOptions(opts *RevokeOptions) error { - if opts == nil { - return errors.New("nil options provided") - } - - // Construct path - path := "/v1/sys/leases/revoke/" - switch { - case opts.Force: - path = "/v1/sys/leases/revoke-force/" - case opts.Prefix: - path = "/v1/sys/leases/revoke-prefix/" - } - path += opts.LeaseID - - r := c.c.NewRequest("PUT", path) - if !opts.Force { - body := map[string]interface{}{ - "sync": opts.Sync, - } - if err := r.SetJSONBody(body); err != nil { - return err - } - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -type RevokeOptions struct { - LeaseID string - Force bool - Prefix bool - Sync bool -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_mounts.go b/vendor/github.com/hashicorp/vault/api/sys_mounts.go deleted file mode 100644 index 8a32b09..0000000 --- a/vendor/github.com/hashicorp/vault/api/sys_mounts.go +++ /dev/null @@ -1,173 +0,0 @@ -package api - -import ( - "context" - "errors" - "fmt" - - "github.com/mitchellh/mapstructure" -) - -func (c *Sys) ListMounts() (map[string]*MountOutput, error) { - r := c.c.NewRequest("GET", "/v1/sys/mounts") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - mounts := map[string]*MountOutput{} - err = mapstructure.Decode(secret.Data, &mounts) - if err != nil { - return nil, err - } - - return mounts, nil -} - -func (c *Sys) Mount(path string, mountInfo *MountInput) error { - r := c.c.NewRequest("POST", fmt.Sprintf("/v1/sys/mounts/%s", path)) - if err := r.SetJSONBody(mountInfo); err != nil { - return err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return err - } - defer resp.Body.Close() - - return nil -} - -func (c *Sys) Unmount(path string) error { - r := c.c.NewRequest("DELETE", fmt.Sprintf("/v1/sys/mounts/%s", path)) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) Remount(from, to string) error { - body := map[string]interface{}{ - "from": from, - "to": to, - } - - r := c.c.NewRequest("POST", "/v1/sys/remount") - if err := r.SetJSONBody(body); err != nil { - return err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) TuneMount(path string, config MountConfigInput) error { - r := c.c.NewRequest("POST", fmt.Sprintf("/v1/sys/mounts/%s/tune", path)) - if err := r.SetJSONBody(config); err != nil { - return err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) MountConfig(path string) (*MountConfigOutput, error) { - r := c.c.NewRequest("GET", fmt.Sprintf("/v1/sys/mounts/%s/tune", path)) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - var result MountConfigOutput - err = mapstructure.Decode(secret.Data, &result) - if err != nil { - return nil, err - } - - return &result, err -} - -type MountInput struct { - Type string `json:"type"` - Description string `json:"description"` - Config MountConfigInput `json:"config"` - Options map[string]string `json:"options"` - Local bool `json:"local"` - PluginName string `json:"plugin_name,omitempty"` - SealWrap bool `json:"seal_wrap" mapstructure:"seal_wrap"` -} - -type MountConfigInput struct { - Options map[string]string `json:"options" mapstructure:"options"` - DefaultLeaseTTL string `json:"default_lease_ttl" mapstructure:"default_lease_ttl"` - Description *string `json:"description,omitempty" mapstructure:"description"` - MaxLeaseTTL string `json:"max_lease_ttl" mapstructure:"max_lease_ttl"` - ForceNoCache bool `json:"force_no_cache" mapstructure:"force_no_cache"` - PluginName string `json:"plugin_name,omitempty" mapstructure:"plugin_name"` - AuditNonHMACRequestKeys []string `json:"audit_non_hmac_request_keys,omitempty" mapstructure:"audit_non_hmac_request_keys"` - AuditNonHMACResponseKeys []string `json:"audit_non_hmac_response_keys,omitempty" mapstructure:"audit_non_hmac_response_keys"` - ListingVisibility string `json:"listing_visibility,omitempty" mapstructure:"listing_visibility"` - PassthroughRequestHeaders []string `json:"passthrough_request_headers,omitempty" mapstructure:"passthrough_request_headers"` -} - -type MountOutput struct { - Type string `json:"type"` - Description string `json:"description"` - Accessor string `json:"accessor"` - Config MountConfigOutput `json:"config"` - Options map[string]string `json:"options"` - Local bool `json:"local"` - SealWrap bool `json:"seal_wrap" mapstructure:"seal_wrap"` -} - -type MountConfigOutput struct { - DefaultLeaseTTL int `json:"default_lease_ttl" mapstructure:"default_lease_ttl"` - MaxLeaseTTL int `json:"max_lease_ttl" mapstructure:"max_lease_ttl"` - ForceNoCache bool `json:"force_no_cache" mapstructure:"force_no_cache"` - PluginName string `json:"plugin_name,omitempty" mapstructure:"plugin_name"` - AuditNonHMACRequestKeys []string `json:"audit_non_hmac_request_keys,omitempty" mapstructure:"audit_non_hmac_request_keys"` - AuditNonHMACResponseKeys []string `json:"audit_non_hmac_response_keys,omitempty" mapstructure:"audit_non_hmac_response_keys"` - ListingVisibility string `json:"listing_visibility,omitempty" mapstructure:"listing_visibility"` - PassthroughRequestHeaders []string `json:"passthrough_request_headers,omitempty" mapstructure:"passthrough_request_headers"` -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_plugins.go b/vendor/github.com/hashicorp/vault/api/sys_plugins.go deleted file mode 100644 index b2f18d9..0000000 --- a/vendor/github.com/hashicorp/vault/api/sys_plugins.go +++ /dev/null @@ -1,131 +0,0 @@ -package api - -import ( - "context" - "fmt" - "net/http" -) - -// ListPluginsInput is used as input to the ListPlugins function. -type ListPluginsInput struct{} - -// ListPluginsResponse is the response from the ListPlugins call. -type ListPluginsResponse struct { - // Names is the list of names of the plugins. - Names []string `json:"names"` -} - -// ListPlugins lists all plugins in the catalog and returns their names as a -// list of strings. -func (c *Sys) ListPlugins(i *ListPluginsInput) (*ListPluginsResponse, error) { - path := "/v1/sys/plugins/catalog" - req := c.c.NewRequest("LIST", path) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result struct { - Data struct { - Keys []string `json:"keys"` - } `json:"data"` - } - if err := resp.DecodeJSON(&result); err != nil { - return nil, err - } - - return &ListPluginsResponse{Names: result.Data.Keys}, nil -} - -// GetPluginInput is used as input to the GetPlugin function. -type GetPluginInput struct { - Name string `json:"-"` -} - -// GetPluginResponse is the response from the GetPlugin call. -type GetPluginResponse struct { - Args []string `json:"args"` - Builtin bool `json:"builtin"` - Command string `json:"command"` - Name string `json:"name"` - SHA256 string `json:"sha256"` -} - -func (c *Sys) GetPlugin(i *GetPluginInput) (*GetPluginResponse, error) { - path := fmt.Sprintf("/v1/sys/plugins/catalog/%s", i.Name) - req := c.c.NewRequest(http.MethodGet, path) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result struct { - Data GetPluginResponse - } - err = resp.DecodeJSON(&result) - if err != nil { - return nil, err - } - return &result.Data, err -} - -// RegisterPluginInput is used as input to the RegisterPlugin function. -type RegisterPluginInput struct { - // Name is the name of the plugin. Required. - Name string `json:"-"` - - // Args is the list of args to spawn the process with. - Args []string `json:"args,omitempty"` - - // Command is the command to run. - Command string `json:"command,omitempty"` - - // SHA256 is the shasum of the plugin. - SHA256 string `json:"sha256,omitempty"` -} - -// RegisterPlugin registers the plugin with the given information. -func (c *Sys) RegisterPlugin(i *RegisterPluginInput) error { - path := fmt.Sprintf("/v1/sys/plugins/catalog/%s", i.Name) - req := c.c.NewRequest(http.MethodPut, path) - if err := req.SetJSONBody(i); err != nil { - return err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, req) - if err == nil { - defer resp.Body.Close() - } - return err -} - -// DeregisterPluginInput is used as input to the DeregisterPlugin function. -type DeregisterPluginInput struct { - // Name is the name of the plugin. Required. - Name string `json:"-"` -} - -// DeregisterPlugin removes the plugin with the given name from the plugin -// catalog. -func (c *Sys) DeregisterPlugin(i *DeregisterPluginInput) error { - path := fmt.Sprintf("/v1/sys/plugins/catalog/%s", i.Name) - req := c.c.NewRequest(http.MethodDelete, path) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, req) - if err == nil { - defer resp.Body.Close() - } - return err -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_policy.go b/vendor/github.com/hashicorp/vault/api/sys_policy.go deleted file mode 100644 index 1fa3259..0000000 --- a/vendor/github.com/hashicorp/vault/api/sys_policy.go +++ /dev/null @@ -1,109 +0,0 @@ -package api - -import ( - "context" - "errors" - "fmt" - - "github.com/mitchellh/mapstructure" -) - -func (c *Sys) ListPolicies() ([]string, error) { - r := c.c.NewRequest("GET", "/v1/sys/policy") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - var result []string - err = mapstructure.Decode(secret.Data["policies"], &result) - if err != nil { - return nil, err - } - - return result, err -} - -func (c *Sys) GetPolicy(name string) (string, error) { - r := c.c.NewRequest("GET", fmt.Sprintf("/v1/sys/policies/acl/%s", name)) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if resp != nil { - defer resp.Body.Close() - if resp.StatusCode == 404 { - return "", nil - } - } - if err != nil { - return "", err - } - - secret, err := ParseSecret(resp.Body) - if err != nil { - return "", err - } - if secret == nil || secret.Data == nil { - return "", errors.New("data from server response is empty") - } - - if policyRaw, ok := secret.Data["policy"]; ok { - return policyRaw.(string), nil - } - - return "", fmt.Errorf("no policy found in response") -} - -func (c *Sys) PutPolicy(name, rules string) error { - body := map[string]string{ - "rules": rules, - } - - r := c.c.NewRequest("PUT", fmt.Sprintf("/v1/sys/policy/%s", name)) - if err := r.SetJSONBody(body); err != nil { - return err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return err - } - defer resp.Body.Close() - - return nil -} - -func (c *Sys) DeletePolicy(name string) error { - r := c.c.NewRequest("DELETE", fmt.Sprintf("/v1/sys/policy/%s", name)) - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -type getPoliciesResp struct { - Rules string `json:"rules"` -} - -type listPoliciesResp struct { - Policies []string `json:"policies"` -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_rekey.go b/vendor/github.com/hashicorp/vault/api/sys_rekey.go deleted file mode 100644 index 55f1a70..0000000 --- a/vendor/github.com/hashicorp/vault/api/sys_rekey.go +++ /dev/null @@ -1,388 +0,0 @@ -package api - -import ( - "context" - "errors" - - "github.com/mitchellh/mapstructure" -) - -func (c *Sys) RekeyStatus() (*RekeyStatusResponse, error) { - r := c.c.NewRequest("GET", "/v1/sys/rekey/init") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result RekeyStatusResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -func (c *Sys) RekeyRecoveryKeyStatus() (*RekeyStatusResponse, error) { - r := c.c.NewRequest("GET", "/v1/sys/rekey-recovery-key/init") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result RekeyStatusResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -func (c *Sys) RekeyVerificationStatus() (*RekeyVerificationStatusResponse, error) { - r := c.c.NewRequest("GET", "/v1/sys/rekey/verify") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result RekeyVerificationStatusResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -func (c *Sys) RekeyRecoveryKeyVerificationStatus() (*RekeyVerificationStatusResponse, error) { - r := c.c.NewRequest("GET", "/v1/sys/rekey-recovery-key/verify") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result RekeyVerificationStatusResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -func (c *Sys) RekeyInit(config *RekeyInitRequest) (*RekeyStatusResponse, error) { - r := c.c.NewRequest("PUT", "/v1/sys/rekey/init") - if err := r.SetJSONBody(config); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result RekeyStatusResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -func (c *Sys) RekeyRecoveryKeyInit(config *RekeyInitRequest) (*RekeyStatusResponse, error) { - r := c.c.NewRequest("PUT", "/v1/sys/rekey-recovery-key/init") - if err := r.SetJSONBody(config); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result RekeyStatusResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -func (c *Sys) RekeyCancel() error { - r := c.c.NewRequest("DELETE", "/v1/sys/rekey/init") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) RekeyRecoveryKeyCancel() error { - r := c.c.NewRequest("DELETE", "/v1/sys/rekey-recovery-key/init") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) RekeyVerificationCancel() error { - r := c.c.NewRequest("DELETE", "/v1/sys/rekey/verify") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) RekeyRecoveryKeyVerificationCancel() error { - r := c.c.NewRequest("DELETE", "/v1/sys/rekey-recovery-key/verify") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) RekeyUpdate(shard, nonce string) (*RekeyUpdateResponse, error) { - body := map[string]interface{}{ - "key": shard, - "nonce": nonce, - } - - r := c.c.NewRequest("PUT", "/v1/sys/rekey/update") - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result RekeyUpdateResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -func (c *Sys) RekeyRecoveryKeyUpdate(shard, nonce string) (*RekeyUpdateResponse, error) { - body := map[string]interface{}{ - "key": shard, - "nonce": nonce, - } - - r := c.c.NewRequest("PUT", "/v1/sys/rekey-recovery-key/update") - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result RekeyUpdateResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -func (c *Sys) RekeyRetrieveBackup() (*RekeyRetrieveResponse, error) { - r := c.c.NewRequest("GET", "/v1/sys/rekey/backup") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - var result RekeyRetrieveResponse - err = mapstructure.Decode(secret.Data, &result) - if err != nil { - return nil, err - } - - return &result, err -} - -func (c *Sys) RekeyRetrieveRecoveryBackup() (*RekeyRetrieveResponse, error) { - r := c.c.NewRequest("GET", "/v1/sys/rekey/recovery-backup") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - var result RekeyRetrieveResponse - err = mapstructure.Decode(secret.Data, &result) - if err != nil { - return nil, err - } - - return &result, err -} - -func (c *Sys) RekeyDeleteBackup() error { - r := c.c.NewRequest("DELETE", "/v1/sys/rekey/backup") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - - return err -} - -func (c *Sys) RekeyDeleteRecoveryBackup() error { - r := c.c.NewRequest("DELETE", "/v1/sys/rekey/recovery-backup") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - - return err -} - -func (c *Sys) RekeyVerificationUpdate(shard, nonce string) (*RekeyVerificationUpdateResponse, error) { - body := map[string]interface{}{ - "key": shard, - "nonce": nonce, - } - - r := c.c.NewRequest("PUT", "/v1/sys/rekey/verify") - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result RekeyVerificationUpdateResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -func (c *Sys) RekeyRecoveryKeyVerificationUpdate(shard, nonce string) (*RekeyVerificationUpdateResponse, error) { - body := map[string]interface{}{ - "key": shard, - "nonce": nonce, - } - - r := c.c.NewRequest("PUT", "/v1/sys/rekey-recovery-key/verify") - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result RekeyVerificationUpdateResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -type RekeyInitRequest struct { - SecretShares int `json:"secret_shares"` - SecretThreshold int `json:"secret_threshold"` - StoredShares int `json:"stored_shares"` - PGPKeys []string `json:"pgp_keys"` - Backup bool - RequireVerification bool `json:"require_verification"` -} - -type RekeyStatusResponse struct { - Nonce string `json:"nonce"` - Started bool `json:"started"` - T int `json:"t"` - N int `json:"n"` - Progress int `json:"progress"` - Required int `json:"required"` - PGPFingerprints []string `json:"pgp_fingerprints"` - Backup bool `json:"backup"` - VerificationRequired bool `json:"verification_required"` - VerificationNonce string `json:"verification_nonce"` -} - -type RekeyUpdateResponse struct { - Nonce string `json:"nonce"` - Complete bool `json:"complete"` - Keys []string `json:"keys"` - KeysB64 []string `json:"keys_base64"` - PGPFingerprints []string `json:"pgp_fingerprints"` - Backup bool `json:"backup"` - VerificationRequired bool `json:"verification_required"` - VerificationNonce string `json:"verification_nonce,omitempty"` -} - -type RekeyRetrieveResponse struct { - Nonce string `json:"nonce" mapstructure:"nonce"` - Keys map[string][]string `json:"keys" mapstructure:"keys"` - KeysB64 map[string][]string `json:"keys_base64" mapstructure:"keys_base64"` -} - -type RekeyVerificationStatusResponse struct { - Nonce string `json:"nonce"` - Started bool `json:"started"` - T int `json:"t"` - N int `json:"n"` - Progress int `json:"progress"` -} - -type RekeyVerificationUpdateResponse struct { - Nonce string `json:"nonce"` - Complete bool `json:"complete"` -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_rotate.go b/vendor/github.com/hashicorp/vault/api/sys_rotate.go deleted file mode 100644 index c525feb..0000000 --- a/vendor/github.com/hashicorp/vault/api/sys_rotate.go +++ /dev/null @@ -1,77 +0,0 @@ -package api - -import ( - "context" - "encoding/json" - "errors" - "time" -) - -func (c *Sys) Rotate() error { - r := c.c.NewRequest("POST", "/v1/sys/rotate") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) KeyStatus() (*KeyStatus, error) { - r := c.c.NewRequest("GET", "/v1/sys/key-status") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := ParseSecret(resp.Body) - if err != nil { - return nil, err - } - if secret == nil || secret.Data == nil { - return nil, errors.New("data from server response is empty") - } - - var result KeyStatus - - termRaw, ok := secret.Data["term"] - if !ok { - return nil, errors.New("term not found in response") - } - term, ok := termRaw.(json.Number) - if !ok { - return nil, errors.New("could not convert term to a number") - } - term64, err := term.Int64() - if err != nil { - return nil, err - } - result.Term = int(term64) - - installTimeRaw, ok := secret.Data["install_time"] - if !ok { - return nil, errors.New("install_time not found in response") - } - installTimeStr, ok := installTimeRaw.(string) - if !ok { - return nil, errors.New("could not convert install_time to a string") - } - installTime, err := time.Parse(time.RFC3339Nano, installTimeStr) - if err != nil { - return nil, err - } - result.InstallTime = installTime - - return &result, err -} - -type KeyStatus struct { - Term int `json:"term"` - InstallTime time.Time `json:"install_time"` -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_seal.go b/vendor/github.com/hashicorp/vault/api/sys_seal.go deleted file mode 100644 index 7cc32ac..0000000 --- a/vendor/github.com/hashicorp/vault/api/sys_seal.go +++ /dev/null @@ -1,69 +0,0 @@ -package api - -import "context" - -func (c *Sys) SealStatus() (*SealStatusResponse, error) { - r := c.c.NewRequest("GET", "/v1/sys/seal-status") - return sealStatusRequest(c, r) -} - -func (c *Sys) Seal() error { - r := c.c.NewRequest("PUT", "/v1/sys/seal") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err == nil { - defer resp.Body.Close() - } - return err -} - -func (c *Sys) ResetUnsealProcess() (*SealStatusResponse, error) { - body := map[string]interface{}{"reset": true} - - r := c.c.NewRequest("PUT", "/v1/sys/unseal") - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - return sealStatusRequest(c, r) -} - -func (c *Sys) Unseal(shard string) (*SealStatusResponse, error) { - body := map[string]interface{}{"key": shard} - - r := c.c.NewRequest("PUT", "/v1/sys/unseal") - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - return sealStatusRequest(c, r) -} - -func sealStatusRequest(c *Sys, r *Request) (*SealStatusResponse, error) { - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result SealStatusResponse - err = resp.DecodeJSON(&result) - return &result, err -} - -type SealStatusResponse struct { - Type string `json:"type"` - Sealed bool `json:"sealed"` - T int `json:"t"` - N int `json:"n"` - Progress int `json:"progress"` - Nonce string `json:"nonce"` - Version string `json:"version"` - ClusterName string `json:"cluster_name,omitempty"` - ClusterID string `json:"cluster_id,omitempty"` - RecoverySeal bool `json:"recovery_seal"` -} diff --git a/vendor/github.com/hashicorp/vault/api/sys_stepdown.go b/vendor/github.com/hashicorp/vault/api/sys_stepdown.go deleted file mode 100644 index 55dc6fb..0000000 --- a/vendor/github.com/hashicorp/vault/api/sys_stepdown.go +++ /dev/null @@ -1,15 +0,0 @@ -package api - -import "context" - -func (c *Sys) StepDown() error { - r := c.c.NewRequest("PUT", "/v1/sys/step-down") - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.c.RawRequestWithContext(ctx, r) - if resp != nil && resp.Body != nil { - resp.Body.Close() - } - return err -} diff --git a/vendor/github.com/hashicorp/vault/helper/compressutil/compress.go b/vendor/github.com/hashicorp/vault/helper/compressutil/compress.go deleted file mode 100644 index a7fb87b..0000000 --- a/vendor/github.com/hashicorp/vault/helper/compressutil/compress.go +++ /dev/null @@ -1,192 +0,0 @@ -package compressutil - -import ( - "bytes" - "compress/gzip" - "compress/lzw" - "fmt" - "io" - - "github.com/golang/snappy" - "github.com/hashicorp/errwrap" -) - -const ( - // A byte value used as a canary prefix for the compressed information - // which is used to distinguish if a JSON input is compressed or not. - // The value of this constant should not be a first character of any - // valid JSON string. - - // Byte value used as canary when using Gzip format - CompressionCanaryGzip byte = 'G' - - // Byte value used as canary when using Lzw format - CompressionCanaryLzw byte = 'L' - - // Byte value used as canary when using Snappy format - CompressionCanarySnappy byte = 'S' - - CompressionTypeLzw = "lzw" - - CompressionTypeGzip = "gzip" - - CompressionTypeSnappy = "snappy" -) - -// SnappyReadCloser embeds the snappy reader which implements the io.Reader -// interface. The decompress procedure in this utility expects an -// io.ReadCloser. This type implements the io.Closer interface to retain the -// generic way of decompression. -type SnappyReadCloser struct { - *snappy.Reader -} - -// Close is a noop method implemented only to satisfy the io.Closer interface -func (s *SnappyReadCloser) Close() error { - return nil -} - -// CompressionConfig is used to select a compression type to be performed by -// Compress and Decompress utilities. -// Supported types are: -// * CompressionTypeLzw -// * CompressionTypeGzip -// * CompressionTypeSnappy -// -// When using CompressionTypeGzip, the compression levels can also be chosen: -// * gzip.DefaultCompression -// * gzip.BestSpeed -// * gzip.BestCompression -type CompressionConfig struct { - // Type of the compression algorithm to be used - Type string - - // When using Gzip format, the compression level to employ - GzipCompressionLevel int -} - -// Compress places the canary byte in a buffer and uses the same buffer to fill -// in the compressed information of the given input. The configuration supports -// two type of compression: LZW and Gzip. When using Gzip compression format, -// if GzipCompressionLevel is not specified, the 'gzip.DefaultCompression' will -// be assumed. -func Compress(data []byte, config *CompressionConfig) ([]byte, error) { - var buf bytes.Buffer - var writer io.WriteCloser - var err error - - if config == nil { - return nil, fmt.Errorf("config is nil") - } - - // Write the canary into the buffer and create writer to compress the - // input data based on the configured type - switch config.Type { - case CompressionTypeLzw: - buf.Write([]byte{CompressionCanaryLzw}) - - writer = lzw.NewWriter(&buf, lzw.LSB, 8) - case CompressionTypeGzip: - buf.Write([]byte{CompressionCanaryGzip}) - - switch { - case config.GzipCompressionLevel == gzip.BestCompression, - config.GzipCompressionLevel == gzip.BestSpeed, - config.GzipCompressionLevel == gzip.DefaultCompression: - // These are valid compression levels - default: - // If compression level is set to NoCompression or to - // any invalid value, fallback to Defaultcompression - config.GzipCompressionLevel = gzip.DefaultCompression - } - writer, err = gzip.NewWriterLevel(&buf, config.GzipCompressionLevel) - case CompressionTypeSnappy: - buf.Write([]byte{CompressionCanarySnappy}) - writer = snappy.NewBufferedWriter(&buf) - default: - return nil, fmt.Errorf("unsupported compression type") - } - - if err != nil { - return nil, errwrap.Wrapf("failed to create a compression writer: {{err}}", err) - } - - if writer == nil { - return nil, fmt.Errorf("failed to create a compression writer") - } - - // Compress the input and place it in the same buffer containing the - // canary byte. - if _, err = writer.Write(data); err != nil { - return nil, errwrap.Wrapf("failed to compress input data: err: {{err}}", err) - } - - // Close the io.WriteCloser - if err = writer.Close(); err != nil { - return nil, err - } - - // Return the compressed bytes with canary byte at the start - return buf.Bytes(), nil -} - -// Decompress checks if the first byte in the input matches the canary byte. -// If the first byte is a canary byte, then the input past the canary byte -// will be decompressed using the method specified in the given configuration. -// If the first byte isn't a canary byte, then the utility returns a boolean -// value indicating that the input was not compressed. -func Decompress(data []byte) ([]byte, bool, error) { - var err error - var reader io.ReadCloser - if data == nil || len(data) == 0 { - return nil, false, fmt.Errorf("'data' being decompressed is empty") - } - - switch { - // If the first byte matches the canary byte, remove the canary - // byte and try to decompress the data that is after the canary. - case data[0] == CompressionCanaryGzip: - if len(data) < 2 { - return nil, false, fmt.Errorf("invalid 'data' after the canary") - } - data = data[1:] - reader, err = gzip.NewReader(bytes.NewReader(data)) - case data[0] == CompressionCanaryLzw: - if len(data) < 2 { - return nil, false, fmt.Errorf("invalid 'data' after the canary") - } - data = data[1:] - reader = lzw.NewReader(bytes.NewReader(data), lzw.LSB, 8) - - case data[0] == CompressionCanarySnappy: - if len(data) < 2 { - return nil, false, fmt.Errorf("invalid 'data' after the canary") - } - data = data[1:] - reader = &SnappyReadCloser{ - Reader: snappy.NewReader(bytes.NewReader(data)), - } - default: - // If the first byte doesn't match the canary byte, it means - // that the content was not compressed at all. Indicate the - // caller that the input was not compressed. - return nil, true, nil - } - if err != nil { - return nil, false, errwrap.Wrapf("failed to create a compression reader: {{err}}", err) - } - if reader == nil { - return nil, false, fmt.Errorf("failed to create a compression reader") - } - - // Close the io.ReadCloser - defer reader.Close() - - // Read all the compressed data into a buffer - var buf bytes.Buffer - if _, err = io.Copy(&buf, reader); err != nil { - return nil, false, err - } - - return buf.Bytes(), false, nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/consts/consts.go b/vendor/github.com/hashicorp/vault/helper/consts/consts.go deleted file mode 100644 index 972a69f..0000000 --- a/vendor/github.com/hashicorp/vault/helper/consts/consts.go +++ /dev/null @@ -1,14 +0,0 @@ -package consts - -const ( - // ExpirationRestoreWorkerCount specifies the number of workers to use while - // restoring leases into the expiration manager - ExpirationRestoreWorkerCount = 64 - - // NamespaceHeaderName is the header set to specify which namespace the - // request is indented for. - NamespaceHeaderName = "X-Vault-Namespace" - - // AuthHeaderName is the name of the header containing the token. - AuthHeaderName = "X-Vault-Token" -) diff --git a/vendor/github.com/hashicorp/vault/helper/consts/error.go b/vendor/github.com/hashicorp/vault/helper/consts/error.go deleted file mode 100644 index 06977d5..0000000 --- a/vendor/github.com/hashicorp/vault/helper/consts/error.go +++ /dev/null @@ -1,16 +0,0 @@ -package consts - -import "errors" - -var ( - // ErrSealed is returned if an operation is performed on a sealed barrier. - // No operation is expected to succeed before unsealing - ErrSealed = errors.New("Vault is sealed") - - // ErrStandby is returned if an operation is performed on a standby Vault. - // No operation is expected to succeed until active. - ErrStandby = errors.New("Vault is in standby mode") - - // Used when .. is used in a path - ErrPathContainsParentReferences = errors.New("path cannot contain parent references") -) diff --git a/vendor/github.com/hashicorp/vault/helper/consts/replication.go b/vendor/github.com/hashicorp/vault/helper/consts/replication.go deleted file mode 100644 index bdad155..0000000 --- a/vendor/github.com/hashicorp/vault/helper/consts/replication.go +++ /dev/null @@ -1,87 +0,0 @@ -package consts - -import "time" - -type ReplicationState uint32 - -var ReplicationStaleReadTimeout = 2 * time.Second - -const ( - _ ReplicationState = iota - OldReplicationPrimary - OldReplicationSecondary - OldReplicationBootstrapping - // Don't add anything here. Adding anything to this Old block would cause - // the rest of the values to change below. This was done originally to - // ensure no overlap between old and new values. - - ReplicationUnknown ReplicationState = 0 - ReplicationPerformancePrimary ReplicationState = 1 << iota - ReplicationPerformanceSecondary - OldSplitReplicationBootstrapping - ReplicationDRPrimary - ReplicationDRSecondary - ReplicationPerformanceBootstrapping - ReplicationDRBootstrapping - ReplicationPerformanceDisabled - ReplicationDRDisabled - ReplicationPerformanceStandby -) - -func (r ReplicationState) string() string { - switch r { - case ReplicationPerformanceSecondary: - return "secondary" - case ReplicationPerformancePrimary: - return "primary" - case ReplicationPerformanceBootstrapping: - return "bootstrapping" - case ReplicationPerformanceDisabled: - return "disabled" - case ReplicationDRPrimary: - return "primary" - case ReplicationDRSecondary: - return "secondary" - case ReplicationDRBootstrapping: - return "bootstrapping" - case ReplicationDRDisabled: - return "disabled" - } - - return "unknown" -} - -func (r ReplicationState) GetDRString() string { - switch { - case r.HasState(ReplicationDRBootstrapping): - return ReplicationDRBootstrapping.string() - case r.HasState(ReplicationDRPrimary): - return ReplicationDRPrimary.string() - case r.HasState(ReplicationDRSecondary): - return ReplicationDRSecondary.string() - case r.HasState(ReplicationDRDisabled): - return ReplicationDRDisabled.string() - default: - return "unknown" - } -} - -func (r ReplicationState) GetPerformanceString() string { - switch { - case r.HasState(ReplicationPerformanceBootstrapping): - return ReplicationPerformanceBootstrapping.string() - case r.HasState(ReplicationPerformancePrimary): - return ReplicationPerformancePrimary.string() - case r.HasState(ReplicationPerformanceSecondary): - return ReplicationPerformanceSecondary.string() - case r.HasState(ReplicationPerformanceDisabled): - return ReplicationPerformanceDisabled.string() - default: - return "unknown" - } -} - -func (r ReplicationState) HasState(flag ReplicationState) bool { return r&flag != 0 } -func (r *ReplicationState) AddState(flag ReplicationState) { *r |= flag } -func (r *ReplicationState) ClearState(flag ReplicationState) { *r &= ^flag } -func (r *ReplicationState) ToggleState(flag ReplicationState) { *r ^= flag } diff --git a/vendor/github.com/hashicorp/vault/helper/hclutil/hcl.go b/vendor/github.com/hashicorp/vault/helper/hclutil/hcl.go deleted file mode 100644 index 0b12036..0000000 --- a/vendor/github.com/hashicorp/vault/helper/hclutil/hcl.go +++ /dev/null @@ -1,36 +0,0 @@ -package hclutil - -import ( - "fmt" - - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/hcl/hcl/ast" -) - -// CheckHCLKeys checks whether the keys in the AST list contains any of the valid keys provided. -func CheckHCLKeys(node ast.Node, valid []string) error { - var list *ast.ObjectList - switch n := node.(type) { - case *ast.ObjectList: - list = n - case *ast.ObjectType: - list = n.List - default: - return fmt.Errorf("cannot check HCL keys of type %T", n) - } - - validMap := make(map[string]struct{}, len(valid)) - for _, v := range valid { - validMap[v] = struct{}{} - } - - var result error - for _, item := range list.Items { - key := item.Keys[0].Token.Value().(string) - if _, ok := validMap[key]; !ok { - result = multierror.Append(result, fmt.Errorf("invalid key %q on line %d", key, item.Assign.Line)) - } - } - - return result -} diff --git a/vendor/github.com/hashicorp/vault/helper/jsonutil/json.go b/vendor/github.com/hashicorp/vault/helper/jsonutil/json.go deleted file mode 100644 index d03ddef..0000000 --- a/vendor/github.com/hashicorp/vault/helper/jsonutil/json.go +++ /dev/null @@ -1,100 +0,0 @@ -package jsonutil - -import ( - "bytes" - "compress/gzip" - "encoding/json" - "fmt" - "io" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/compressutil" -) - -// Encodes/Marshals the given object into JSON -func EncodeJSON(in interface{}) ([]byte, error) { - if in == nil { - return nil, fmt.Errorf("input for encoding is nil") - } - var buf bytes.Buffer - enc := json.NewEncoder(&buf) - if err := enc.Encode(in); err != nil { - return nil, err - } - return buf.Bytes(), nil -} - -// EncodeJSONAndCompress encodes the given input into JSON and compresses the -// encoded value (using Gzip format BestCompression level, by default). A -// canary byte is placed at the beginning of the returned bytes for the logic -// in decompression method to identify compressed input. -func EncodeJSONAndCompress(in interface{}, config *compressutil.CompressionConfig) ([]byte, error) { - if in == nil { - return nil, fmt.Errorf("input for encoding is nil") - } - - // First JSON encode the given input - encodedBytes, err := EncodeJSON(in) - if err != nil { - return nil, err - } - - if config == nil { - config = &compressutil.CompressionConfig{ - Type: compressutil.CompressionTypeGzip, - GzipCompressionLevel: gzip.BestCompression, - } - } - - return compressutil.Compress(encodedBytes, config) -} - -// DecodeJSON tries to decompress the given data. The call to decompress, fails -// if the content was not compressed in the first place, which is identified by -// a canary byte before the compressed data. If the data is not compressed, it -// is JSON decoded directly. Otherwise the decompressed data will be JSON -// decoded. -func DecodeJSON(data []byte, out interface{}) error { - if data == nil || len(data) == 0 { - return fmt.Errorf("'data' being decoded is nil") - } - if out == nil { - return fmt.Errorf("output parameter 'out' is nil") - } - - // Decompress the data if it was compressed in the first place - decompressedBytes, uncompressed, err := compressutil.Decompress(data) - if err != nil { - return errwrap.Wrapf("failed to decompress JSON: {{err}}", err) - } - if !uncompressed && (decompressedBytes == nil || len(decompressedBytes) == 0) { - return fmt.Errorf("decompressed data being decoded is invalid") - } - - // If the input supplied failed to contain the compression canary, it - // will be notified by the compression utility. Decode the decompressed - // input. - if !uncompressed { - data = decompressedBytes - } - - return DecodeJSONFromReader(bytes.NewReader(data), out) -} - -// Decodes/Unmarshals the given io.Reader pointing to a JSON, into a desired object -func DecodeJSONFromReader(r io.Reader, out interface{}) error { - if r == nil { - return fmt.Errorf("'io.Reader' being decoded is nil") - } - if out == nil { - return fmt.Errorf("output parameter 'out' is nil") - } - - dec := json.NewDecoder(r) - - // While decoding JSON values, interpret the integer values as `json.Number`s instead of `float64`. - dec.UseNumber() - - // Since 'out' is an interface representing a pointer, pass it to the decoder without an '&' - return dec.Decode(out) -} diff --git a/vendor/github.com/hashicorp/vault/helper/parseutil/parseutil.go b/vendor/github.com/hashicorp/vault/helper/parseutil/parseutil.go deleted file mode 100644 index 9b32bf7..0000000 --- a/vendor/github.com/hashicorp/vault/helper/parseutil/parseutil.go +++ /dev/null @@ -1,163 +0,0 @@ -package parseutil - -import ( - "encoding/json" - "errors" - "fmt" - "strconv" - "strings" - "time" - - "github.com/hashicorp/errwrap" - sockaddr "github.com/hashicorp/go-sockaddr" - "github.com/hashicorp/vault/helper/strutil" - "github.com/mitchellh/mapstructure" -) - -func ParseDurationSecond(in interface{}) (time.Duration, error) { - var dur time.Duration - jsonIn, ok := in.(json.Number) - if ok { - in = jsonIn.String() - } - switch in.(type) { - case string: - inp := in.(string) - if inp == "" { - return time.Duration(0), nil - } - var err error - // Look for a suffix otherwise its a plain second value - if strings.HasSuffix(inp, "s") || strings.HasSuffix(inp, "m") || strings.HasSuffix(inp, "h") || strings.HasSuffix(inp, "ms") { - dur, err = time.ParseDuration(inp) - if err != nil { - return dur, err - } - } else { - // Plain integer - secs, err := strconv.ParseInt(inp, 10, 64) - if err != nil { - return dur, err - } - dur = time.Duration(secs) * time.Second - } - case int: - dur = time.Duration(in.(int)) * time.Second - case int32: - dur = time.Duration(in.(int32)) * time.Second - case int64: - dur = time.Duration(in.(int64)) * time.Second - case uint: - dur = time.Duration(in.(uint)) * time.Second - case uint32: - dur = time.Duration(in.(uint32)) * time.Second - case uint64: - dur = time.Duration(in.(uint64)) * time.Second - default: - return 0, errors.New("could not parse duration from input") - } - - return dur, nil -} - -func ParseInt(in interface{}) (int64, error) { - var ret int64 - jsonIn, ok := in.(json.Number) - if ok { - in = jsonIn.String() - } - switch in.(type) { - case string: - inp := in.(string) - if inp == "" { - return 0, nil - } - var err error - left, err := strconv.ParseInt(inp, 10, 64) - if err != nil { - return ret, err - } - ret = left - case int: - ret = int64(in.(int)) - case int32: - ret = int64(in.(int32)) - case int64: - ret = in.(int64) - case uint: - ret = int64(in.(uint)) - case uint32: - ret = int64(in.(uint32)) - case uint64: - ret = int64(in.(uint64)) - default: - return 0, errors.New("could not parse value from input") - } - - return ret, nil -} - -func ParseBool(in interface{}) (bool, error) { - var result bool - if err := mapstructure.WeakDecode(in, &result); err != nil { - return false, err - } - return result, nil -} - -func ParseCommaStringSlice(in interface{}) ([]string, error) { - var result []string - config := &mapstructure.DecoderConfig{ - Result: &result, - WeaklyTypedInput: true, - DecodeHook: mapstructure.StringToSliceHookFunc(","), - } - decoder, err := mapstructure.NewDecoder(config) - if err != nil { - return nil, err - } - if err := decoder.Decode(in); err != nil { - return nil, err - } - return strutil.TrimStrings(result), nil -} - -func ParseAddrs(addrs interface{}) ([]*sockaddr.SockAddrMarshaler, error) { - out := make([]*sockaddr.SockAddrMarshaler, 0) - stringAddrs := make([]string, 0) - - switch addrs.(type) { - case string: - stringAddrs = strutil.ParseArbitraryStringSlice(addrs.(string), ",") - if len(stringAddrs) == 0 { - return nil, fmt.Errorf("unable to parse addresses from %v", addrs) - } - - case []string: - stringAddrs = addrs.([]string) - - case []interface{}: - for _, v := range addrs.([]interface{}) { - stringAddr, ok := v.(string) - if !ok { - return nil, fmt.Errorf("error parsing %v as string", v) - } - stringAddrs = append(stringAddrs, stringAddr) - } - - default: - return nil, fmt.Errorf("unknown address input type %T", addrs) - } - - for _, addr := range stringAddrs { - sa, err := sockaddr.NewSockAddr(addr) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error parsing address %q: {{err}}", addr), err) - } - out = append(out, &sockaddr.SockAddrMarshaler{ - SockAddr: sa, - }) - } - - return out, nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/strutil/strutil.go b/vendor/github.com/hashicorp/vault/helper/strutil/strutil.go deleted file mode 100644 index 8d84c1e..0000000 --- a/vendor/github.com/hashicorp/vault/helper/strutil/strutil.go +++ /dev/null @@ -1,348 +0,0 @@ -package strutil - -import ( - "encoding/base64" - "encoding/json" - "fmt" - "sort" - "strings" - - "github.com/hashicorp/errwrap" - glob "github.com/ryanuber/go-glob" -) - -// StrListContainsGlob looks for a string in a list of strings and allows -// globs. -func StrListContainsGlob(haystack []string, needle string) bool { - for _, item := range haystack { - if glob.Glob(item, needle) { - return true - } - } - return false -} - -// StrListContains looks for a string in a list of strings. -func StrListContains(haystack []string, needle string) bool { - for _, item := range haystack { - if item == needle { - return true - } - } - return false -} - -// StrListSubset checks if a given list is a subset -// of another set -func StrListSubset(super, sub []string) bool { - for _, item := range sub { - if !StrListContains(super, item) { - return false - } - } - return true -} - -// ParseDedupAndSortStrings parses a comma separated list of strings -// into a slice of strings. The return slice will be sorted and will -// not contain duplicate or empty items. -func ParseDedupAndSortStrings(input string, sep string) []string { - input = strings.TrimSpace(input) - parsed := []string{} - if input == "" { - // Don't return nil - return parsed - } - return RemoveDuplicates(strings.Split(input, sep), false) -} - -// ParseDedupLowercaseAndSortStrings parses a comma separated list of -// strings into a slice of strings. The return slice will be sorted and -// will not contain duplicate or empty items. The values will be converted -// to lower case. -func ParseDedupLowercaseAndSortStrings(input string, sep string) []string { - input = strings.TrimSpace(input) - parsed := []string{} - if input == "" { - // Don't return nil - return parsed - } - return RemoveDuplicates(strings.Split(input, sep), true) -} - -// ParseKeyValues parses a comma separated list of `=` tuples -// into a map[string]string. -func ParseKeyValues(input string, out map[string]string, sep string) error { - if out == nil { - return fmt.Errorf("'out is nil") - } - - keyValues := ParseDedupLowercaseAndSortStrings(input, sep) - if len(keyValues) == 0 { - return nil - } - - for _, keyValue := range keyValues { - shards := strings.Split(keyValue, "=") - if len(shards) != 2 { - return fmt.Errorf("invalid format") - } - - key := strings.TrimSpace(shards[0]) - value := strings.TrimSpace(shards[1]) - if key == "" || value == "" { - return fmt.Errorf("invalid pair: key: %q value: %q", key, value) - } - out[key] = value - } - return nil -} - -// ParseArbitraryKeyValues parses arbitrary tuples. The input -// can be one of the following: -// * JSON string -// * Base64 encoded JSON string -// * Comma separated list of `=` pairs -// * Base64 encoded string containing comma separated list of -// `=` pairs -// -// Input will be parsed into the output parameter, which should -// be a non-nil map[string]string. -func ParseArbitraryKeyValues(input string, out map[string]string, sep string) error { - input = strings.TrimSpace(input) - if input == "" { - return nil - } - if out == nil { - return fmt.Errorf("'out' is nil") - } - - // Try to base64 decode the input. If successful, consider the decoded - // value as input. - inputBytes, err := base64.StdEncoding.DecodeString(input) - if err == nil { - input = string(inputBytes) - } - - // Try to JSON unmarshal the input. If successful, consider that the - // metadata was supplied as JSON input. - err = json.Unmarshal([]byte(input), &out) - if err != nil { - // If JSON unmarshalling fails, consider that the input was - // supplied as a comma separated string of 'key=value' pairs. - if err = ParseKeyValues(input, out, sep); err != nil { - return errwrap.Wrapf("failed to parse the input: {{err}}", err) - } - } - - // Validate the parsed input - for key, value := range out { - if key != "" && value == "" { - return fmt.Errorf("invalid value for key %q", key) - } - } - - return nil -} - -// ParseStringSlice parses a `sep`-separated list of strings into a -// []string with surrounding whitespace removed. -// -// The output will always be a valid slice but may be of length zero. -func ParseStringSlice(input string, sep string) []string { - input = strings.TrimSpace(input) - if input == "" { - return []string{} - } - - splitStr := strings.Split(input, sep) - ret := make([]string, len(splitStr)) - for i, val := range splitStr { - ret[i] = strings.TrimSpace(val) - } - - return ret -} - -// ParseArbitraryStringSlice parses arbitrary string slice. The input -// can be one of the following: -// * JSON string -// * Base64 encoded JSON string -// * `sep` separated list of values -// * Base64-encoded string containing a `sep` separated list of values -// -// Note that the separator is ignored if the input is found to already be in a -// structured format (e.g., JSON) -// -// The output will always be a valid slice but may be of length zero. -func ParseArbitraryStringSlice(input string, sep string) []string { - input = strings.TrimSpace(input) - if input == "" { - return []string{} - } - - // Try to base64 decode the input. If successful, consider the decoded - // value as input. - inputBytes, err := base64.StdEncoding.DecodeString(input) - if err == nil { - input = string(inputBytes) - } - - ret := []string{} - - // Try to JSON unmarshal the input. If successful, consider that the - // metadata was supplied as JSON input. - err = json.Unmarshal([]byte(input), &ret) - if err != nil { - // If JSON unmarshalling fails, consider that the input was - // supplied as a separated string of values. - return ParseStringSlice(input, sep) - } - - if ret == nil { - return []string{} - } - - return ret -} - -// TrimStrings takes a slice of strings and returns a slice of strings -// with trimmed spaces -func TrimStrings(items []string) []string { - ret := make([]string, len(items)) - for i, item := range items { - ret[i] = strings.TrimSpace(item) - } - return ret -} - -// RemoveDuplicates removes duplicate and empty elements from a slice of -// strings. This also may convert the items in the slice to lower case and -// returns a sorted slice. -func RemoveDuplicates(items []string, lowercase bool) []string { - itemsMap := map[string]bool{} - for _, item := range items { - item = strings.TrimSpace(item) - if lowercase { - item = strings.ToLower(item) - } - if item == "" { - continue - } - itemsMap[item] = true - } - items = make([]string, 0, len(itemsMap)) - for item := range itemsMap { - items = append(items, item) - } - sort.Strings(items) - return items -} - -// EquivalentSlices checks whether the given string sets are equivalent, as in, -// they contain the same values. -func EquivalentSlices(a, b []string) bool { - if a == nil && b == nil { - return true - } - - if a == nil || b == nil { - return false - } - - // First we'll build maps to ensure unique values - mapA := map[string]bool{} - mapB := map[string]bool{} - for _, keyA := range a { - mapA[keyA] = true - } - for _, keyB := range b { - mapB[keyB] = true - } - - // Now we'll build our checking slices - var sortedA, sortedB []string - for keyA := range mapA { - sortedA = append(sortedA, keyA) - } - for keyB := range mapB { - sortedB = append(sortedB, keyB) - } - sort.Strings(sortedA) - sort.Strings(sortedB) - - // Finally, compare - if len(sortedA) != len(sortedB) { - return false - } - - for i := range sortedA { - if sortedA[i] != sortedB[i] { - return false - } - } - - return true -} - -// StrListDelete removes the first occurrence of the given item from the slice -// of strings if the item exists. -func StrListDelete(s []string, d string) []string { - if s == nil { - return s - } - - for index, element := range s { - if element == d { - return append(s[:index], s[index+1:]...) - } - } - - return s -} - -// GlobbedStringsMatch compares item to val with support for a leading and/or -// trailing wildcard '*' in item. -func GlobbedStringsMatch(item, val string) bool { - if len(item) < 2 { - return val == item - } - - hasPrefix := strings.HasPrefix(item, "*") - hasSuffix := strings.HasSuffix(item, "*") - - if hasPrefix && hasSuffix { - return strings.Contains(val, item[1:len(item)-1]) - } else if hasPrefix { - return strings.HasSuffix(val, item[1:]) - } else if hasSuffix { - return strings.HasPrefix(val, item[:len(item)-1]) - } - - return val == item -} - -// AppendIfMissing adds a string to a slice if the given string is not present -func AppendIfMissing(slice []string, i string) []string { - if StrListContains(slice, i) { - return slice - } - return append(slice, i) -} - -// MergeSlices adds an arbitrary number of slices together, uniquely -func MergeSlices(args ...[]string) []string { - all := map[string]struct{}{} - for _, slice := range args { - for _, v := range slice { - all[v] = struct{}{} - } - } - - result := make([]string, 0, len(all)) - for k, _ := range all { - result = append(result, k) - } - sort.Strings(result) - return result -} diff --git a/vendor/github.com/hashicorp/vault/website/LICENSE.md b/vendor/github.com/hashicorp/vault/website/LICENSE.md deleted file mode 100644 index 3189f43..0000000 --- a/vendor/github.com/hashicorp/vault/website/LICENSE.md +++ /dev/null @@ -1,10 +0,0 @@ -# Proprietary License - -This license is temporary while a more official one is drafted. However, -this should make it clear: - -The text contents of this website are MPL 2.0 licensed. - -The design contents of this website are proprietary and may not be reproduced -or reused in any way other than to run the website locally. The license for -the design is owned solely by HashiCorp, Inc. diff --git a/vendor/github.com/hashicorp/vault/website/source/api/system/license.html.md b/vendor/github.com/hashicorp/vault/website/source/api/system/license.html.md deleted file mode 100644 index 933d277..0000000 --- a/vendor/github.com/hashicorp/vault/website/source/api/system/license.html.md +++ /dev/null @@ -1,87 +0,0 @@ ---- -layout: "api" -page_title: "/sys/license - HTTP API" -sidebar_current: "docs-http-system-license" -description: |- - The `/sys/license` endpoint is used to view and update the license used in - Vault. ---- - -# `/sys/license` - -~> **Enterprise Only** – These endpoints require Vault Enterprise. - -The `/sys/license` endpoint is used to view and update the license used in -Vault. - -## Read License - -This endpoint returns information about the currently installed license. - -| Method | Path | Produces | -| :------- | :--------------------------- | :--------------------- | -| `GET` | `/sys/license` | `200 application/json` | - -### Sample Request - -``` -$ curl \ - --header "X-Vault-Token: ..." \ - http://127.0.0.1:8200/v1/sys/license -``` - -### Sample Response - -```json -{ - "data": { - "expiration_time": "2017-11-14T16:34:36.546753-05:00", - "features": [ - "UI", - "HSM", - "Performance Replication", - "DR Replication" - ], - "license_id": "temporary", - "start_time": "2017-11-14T16:04:36.546753-05:00" - }, - "warnings": [ - "time left on license is 29m33s" - ] -} -``` - -## Install License - -This endpoint is used to install a license into Vault. - -| Method | Path | Produces | -| :------- | :--------------------------- | :--------------------- | -| `PUT` | `/sys/license` | `204 (empty body)` | - -### Parameters - -- `text` `(string: )` – The text of the license. - -*DR Secondary Specific Parameters* - - - `dr_operation_token` `(string: )` - DR operation token used to authorize this request. - - -### Sample Payload - -```json -{ - "text": "01ABCDEFG..." -} -``` - -### Sample Request - -``` -$ curl \ - --header "X-Vault-Token: ..." \ - --request PUT \ - --data @payload.json \ - http://127.0.0.1:8200/v1/sys/license -``` diff --git a/vendor/github.com/mitchellh/go-homedir/LICENSE b/vendor/github.com/mitchellh/go-homedir/LICENSE deleted file mode 100644 index f9c841a..0000000 --- a/vendor/github.com/mitchellh/go-homedir/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 Mitchell Hashimoto - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/mitchellh/go-homedir/README.md b/vendor/github.com/mitchellh/go-homedir/README.md deleted file mode 100644 index d70706d..0000000 --- a/vendor/github.com/mitchellh/go-homedir/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# go-homedir - -This is a Go library for detecting the user's home directory without -the use of cgo, so the library can be used in cross-compilation environments. - -Usage is incredibly simple, just call `homedir.Dir()` to get the home directory -for a user, and `homedir.Expand()` to expand the `~` in a path to the home -directory. - -**Why not just use `os/user`?** The built-in `os/user` package requires -cgo on Darwin systems. This means that any Go code that uses that package -cannot cross compile. But 99% of the time the use for `os/user` is just to -retrieve the home directory, which we can do for the current user without -cgo. This library does that, enabling cross-compilation. diff --git a/vendor/github.com/mitchellh/go-homedir/go.mod b/vendor/github.com/mitchellh/go-homedir/go.mod deleted file mode 100644 index 7efa09a..0000000 --- a/vendor/github.com/mitchellh/go-homedir/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/mitchellh/go-homedir diff --git a/vendor/github.com/mitchellh/go-homedir/homedir.go b/vendor/github.com/mitchellh/go-homedir/homedir.go deleted file mode 100644 index fb87bef..0000000 --- a/vendor/github.com/mitchellh/go-homedir/homedir.go +++ /dev/null @@ -1,157 +0,0 @@ -package homedir - -import ( - "bytes" - "errors" - "os" - "os/exec" - "path/filepath" - "runtime" - "strconv" - "strings" - "sync" -) - -// DisableCache will disable caching of the home directory. Caching is enabled -// by default. -var DisableCache bool - -var homedirCache string -var cacheLock sync.RWMutex - -// Dir returns the home directory for the executing user. -// -// This uses an OS-specific method for discovering the home directory. -// An error is returned if a home directory cannot be detected. -func Dir() (string, error) { - if !DisableCache { - cacheLock.RLock() - cached := homedirCache - cacheLock.RUnlock() - if cached != "" { - return cached, nil - } - } - - cacheLock.Lock() - defer cacheLock.Unlock() - - var result string - var err error - if runtime.GOOS == "windows" { - result, err = dirWindows() - } else { - // Unix-like system, so just assume Unix - result, err = dirUnix() - } - - if err != nil { - return "", err - } - homedirCache = result - return result, nil -} - -// Expand expands the path to include the home directory if the path -// is prefixed with `~`. If it isn't prefixed with `~`, the path is -// returned as-is. -func Expand(path string) (string, error) { - if len(path) == 0 { - return path, nil - } - - if path[0] != '~' { - return path, nil - } - - if len(path) > 1 && path[1] != '/' && path[1] != '\\' { - return "", errors.New("cannot expand user-specific home dir") - } - - dir, err := Dir() - if err != nil { - return "", err - } - - return filepath.Join(dir, path[1:]), nil -} - -func dirUnix() (string, error) { - homeEnv := "HOME" - if runtime.GOOS == "plan9" { - // On plan9, env vars are lowercase. - homeEnv = "home" - } - - // First prefer the HOME environmental variable - if home := os.Getenv(homeEnv); home != "" { - return home, nil - } - - var stdout bytes.Buffer - - // If that fails, try OS specific commands - if runtime.GOOS == "darwin" { - cmd := exec.Command("sh", "-c", `dscl -q . -read /Users/"$(whoami)" NFSHomeDirectory | sed 's/^[^ ]*: //'`) - cmd.Stdout = &stdout - if err := cmd.Run(); err == nil { - result := strings.TrimSpace(stdout.String()) - if result != "" { - return result, nil - } - } - } else { - cmd := exec.Command("getent", "passwd", strconv.Itoa(os.Getuid())) - cmd.Stdout = &stdout - if err := cmd.Run(); err != nil { - // If the error is ErrNotFound, we ignore it. Otherwise, return it. - if err != exec.ErrNotFound { - return "", err - } - } else { - if passwd := strings.TrimSpace(stdout.String()); passwd != "" { - // username:password:uid:gid:gecos:home:shell - passwdParts := strings.SplitN(passwd, ":", 7) - if len(passwdParts) > 5 { - return passwdParts[5], nil - } - } - } - } - - // If all else fails, try the shell - stdout.Reset() - cmd := exec.Command("sh", "-c", "cd && pwd") - cmd.Stdout = &stdout - if err := cmd.Run(); err != nil { - return "", err - } - - result := strings.TrimSpace(stdout.String()) - if result == "" { - return "", errors.New("blank output when reading home directory") - } - - return result, nil -} - -func dirWindows() (string, error) { - // First prefer the HOME environmental variable - if home := os.Getenv("HOME"); home != "" { - return home, nil - } - - // Prefer standard environment variable USERPROFILE - if home := os.Getenv("USERPROFILE"); home != "" { - return home, nil - } - - drive := os.Getenv("HOMEDRIVE") - path := os.Getenv("HOMEPATH") - home := drive + path - if drive == "" || path == "" { - return "", errors.New("HOMEDRIVE, HOMEPATH, or USERPROFILE are blank") - } - - return home, nil -} diff --git a/vendor/github.com/mitchellh/mapstructure/.travis.yml b/vendor/github.com/mitchellh/mapstructure/.travis.yml deleted file mode 100644 index d9deadb..0000000 --- a/vendor/github.com/mitchellh/mapstructure/.travis.yml +++ /dev/null @@ -1,8 +0,0 @@ -language: go - -go: - - 1.9.x - - tip - -script: - - go test diff --git a/vendor/github.com/mitchellh/mapstructure/LICENSE b/vendor/github.com/mitchellh/mapstructure/LICENSE deleted file mode 100644 index f9c841a..0000000 --- a/vendor/github.com/mitchellh/mapstructure/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 Mitchell Hashimoto - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/mitchellh/mapstructure/README.md b/vendor/github.com/mitchellh/mapstructure/README.md deleted file mode 100644 index 0018dc7..0000000 --- a/vendor/github.com/mitchellh/mapstructure/README.md +++ /dev/null @@ -1,46 +0,0 @@ -# mapstructure [![Godoc](https://godoc.org/github.com/mitchellh/mapstructure?status.svg)](https://godoc.org/github.com/mitchellh/mapstructure) - -mapstructure is a Go library for decoding generic map values to structures -and vice versa, while providing helpful error handling. - -This library is most useful when decoding values from some data stream (JSON, -Gob, etc.) where you don't _quite_ know the structure of the underlying data -until you read a part of it. You can therefore read a `map[string]interface{}` -and use this library to decode it into the proper underlying native Go -structure. - -## Installation - -Standard `go get`: - -``` -$ go get github.com/mitchellh/mapstructure -``` - -## Usage & Example - -For usage and examples see the [Godoc](http://godoc.org/github.com/mitchellh/mapstructure). - -The `Decode` function has examples associated with it there. - -## But Why?! - -Go offers fantastic standard libraries for decoding formats such as JSON. -The standard method is to have a struct pre-created, and populate that struct -from the bytes of the encoded format. This is great, but the problem is if -you have configuration or an encoding that changes slightly depending on -specific fields. For example, consider this JSON: - -```json -{ - "type": "person", - "name": "Mitchell" -} -``` - -Perhaps we can't populate a specific structure without first reading -the "type" field from the JSON. We could always do two passes over the -decoding of the JSON (reading the "type" first, and the rest later). -However, it is much simpler to just decode this into a `map[string]interface{}` -structure, read the "type" key, then use something like this library -to decode it into the proper structure. diff --git a/vendor/github.com/mitchellh/mapstructure/decode_hooks.go b/vendor/github.com/mitchellh/mapstructure/decode_hooks.go deleted file mode 100644 index 2a72757..0000000 --- a/vendor/github.com/mitchellh/mapstructure/decode_hooks.go +++ /dev/null @@ -1,171 +0,0 @@ -package mapstructure - -import ( - "errors" - "reflect" - "strconv" - "strings" - "time" -) - -// typedDecodeHook takes a raw DecodeHookFunc (an interface{}) and turns -// it into the proper DecodeHookFunc type, such as DecodeHookFuncType. -func typedDecodeHook(h DecodeHookFunc) DecodeHookFunc { - // Create variables here so we can reference them with the reflect pkg - var f1 DecodeHookFuncType - var f2 DecodeHookFuncKind - - // Fill in the variables into this interface and the rest is done - // automatically using the reflect package. - potential := []interface{}{f1, f2} - - v := reflect.ValueOf(h) - vt := v.Type() - for _, raw := range potential { - pt := reflect.ValueOf(raw).Type() - if vt.ConvertibleTo(pt) { - return v.Convert(pt).Interface() - } - } - - return nil -} - -// DecodeHookExec executes the given decode hook. This should be used -// since it'll naturally degrade to the older backwards compatible DecodeHookFunc -// that took reflect.Kind instead of reflect.Type. -func DecodeHookExec( - raw DecodeHookFunc, - from reflect.Type, to reflect.Type, - data interface{}) (interface{}, error) { - switch f := typedDecodeHook(raw).(type) { - case DecodeHookFuncType: - return f(from, to, data) - case DecodeHookFuncKind: - return f(from.Kind(), to.Kind(), data) - default: - return nil, errors.New("invalid decode hook signature") - } -} - -// ComposeDecodeHookFunc creates a single DecodeHookFunc that -// automatically composes multiple DecodeHookFuncs. -// -// The composed funcs are called in order, with the result of the -// previous transformation. -func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc { - return func( - f reflect.Type, - t reflect.Type, - data interface{}) (interface{}, error) { - var err error - for _, f1 := range fs { - data, err = DecodeHookExec(f1, f, t, data) - if err != nil { - return nil, err - } - - // Modify the from kind to be correct with the new data - f = nil - if val := reflect.ValueOf(data); val.IsValid() { - f = val.Type() - } - } - - return data, nil - } -} - -// StringToSliceHookFunc returns a DecodeHookFunc that converts -// string to []string by splitting on the given sep. -func StringToSliceHookFunc(sep string) DecodeHookFunc { - return func( - f reflect.Kind, - t reflect.Kind, - data interface{}) (interface{}, error) { - if f != reflect.String || t != reflect.Slice { - return data, nil - } - - raw := data.(string) - if raw == "" { - return []string{}, nil - } - - return strings.Split(raw, sep), nil - } -} - -// StringToTimeDurationHookFunc returns a DecodeHookFunc that converts -// strings to time.Duration. -func StringToTimeDurationHookFunc() DecodeHookFunc { - return func( - f reflect.Type, - t reflect.Type, - data interface{}) (interface{}, error) { - if f.Kind() != reflect.String { - return data, nil - } - if t != reflect.TypeOf(time.Duration(5)) { - return data, nil - } - - // Convert it by parsing - return time.ParseDuration(data.(string)) - } -} - -// StringToTimeHookFunc returns a DecodeHookFunc that converts -// strings to time.Time. -func StringToTimeHookFunc(layout string) DecodeHookFunc { - return func( - f reflect.Type, - t reflect.Type, - data interface{}) (interface{}, error) { - if f.Kind() != reflect.String { - return data, nil - } - if t != reflect.TypeOf(time.Time{}) { - return data, nil - } - - // Convert it by parsing - return time.Parse(layout, data.(string)) - } -} - -// WeaklyTypedHook is a DecodeHookFunc which adds support for weak typing to -// the decoder. -// -// Note that this is significantly different from the WeaklyTypedInput option -// of the DecoderConfig. -func WeaklyTypedHook( - f reflect.Kind, - t reflect.Kind, - data interface{}) (interface{}, error) { - dataVal := reflect.ValueOf(data) - switch t { - case reflect.String: - switch f { - case reflect.Bool: - if dataVal.Bool() { - return "1", nil - } - return "0", nil - case reflect.Float32: - return strconv.FormatFloat(dataVal.Float(), 'f', -1, 64), nil - case reflect.Int: - return strconv.FormatInt(dataVal.Int(), 10), nil - case reflect.Slice: - dataType := dataVal.Type() - elemKind := dataType.Elem().Kind() - if elemKind == reflect.Uint8 { - return string(dataVal.Interface().([]uint8)), nil - } - case reflect.Uint: - return strconv.FormatUint(dataVal.Uint(), 10), nil - } - } - - return data, nil -} diff --git a/vendor/github.com/mitchellh/mapstructure/error.go b/vendor/github.com/mitchellh/mapstructure/error.go deleted file mode 100644 index 47a99e5..0000000 --- a/vendor/github.com/mitchellh/mapstructure/error.go +++ /dev/null @@ -1,50 +0,0 @@ -package mapstructure - -import ( - "errors" - "fmt" - "sort" - "strings" -) - -// Error implements the error interface and can represents multiple -// errors that occur in the course of a single decode. -type Error struct { - Errors []string -} - -func (e *Error) Error() string { - points := make([]string, len(e.Errors)) - for i, err := range e.Errors { - points[i] = fmt.Sprintf("* %s", err) - } - - sort.Strings(points) - return fmt.Sprintf( - "%d error(s) decoding:\n\n%s", - len(e.Errors), strings.Join(points, "\n")) -} - -// WrappedErrors implements the errwrap.Wrapper interface to make this -// return value more useful with the errwrap and go-multierror libraries. -func (e *Error) WrappedErrors() []error { - if e == nil { - return nil - } - - result := make([]error, len(e.Errors)) - for i, e := range e.Errors { - result[i] = errors.New(e) - } - - return result -} - -func appendErrors(errors []string, err error) []string { - switch e := err.(type) { - case *Error: - return append(errors, e.Errors...) - default: - return append(errors, e.Error()) - } -} diff --git a/vendor/github.com/mitchellh/mapstructure/go.mod b/vendor/github.com/mitchellh/mapstructure/go.mod deleted file mode 100644 index d2a7125..0000000 --- a/vendor/github.com/mitchellh/mapstructure/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/mitchellh/mapstructure diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure.go b/vendor/github.com/mitchellh/mapstructure/mapstructure.go deleted file mode 100644 index d3222b8..0000000 --- a/vendor/github.com/mitchellh/mapstructure/mapstructure.go +++ /dev/null @@ -1,1064 +0,0 @@ -// Package mapstructure exposes functionality to convert an arbitrary -// map[string]interface{} into a native Go structure. -// -// The Go structure can be arbitrarily complex, containing slices, -// other structs, etc. and the decoder will properly decode nested -// maps and so on into the proper structures in the native Go struct. -// See the examples to see what the decoder is capable of. -package mapstructure - -import ( - "encoding/json" - "errors" - "fmt" - "reflect" - "sort" - "strconv" - "strings" -) - -// DecodeHookFunc is the callback function that can be used for -// data transformations. See "DecodeHook" in the DecoderConfig -// struct. -// -// The type should be DecodeHookFuncType or DecodeHookFuncKind. -// Either is accepted. Types are a superset of Kinds (Types can return -// Kinds) and are generally a richer thing to use, but Kinds are simpler -// if you only need those. -// -// The reason DecodeHookFunc is multi-typed is for backwards compatibility: -// we started with Kinds and then realized Types were the better solution, -// but have a promise to not break backwards compat so we now support -// both. -type DecodeHookFunc interface{} - -// DecodeHookFuncType is a DecodeHookFunc which has complete information about -// the source and target types. -type DecodeHookFuncType func(reflect.Type, reflect.Type, interface{}) (interface{}, error) - -// DecodeHookFuncKind is a DecodeHookFunc which knows only the Kinds of the -// source and target types. -type DecodeHookFuncKind func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error) - -// DecoderConfig is the configuration that is used to create a new decoder -// and allows customization of various aspects of decoding. -type DecoderConfig struct { - // DecodeHook, if set, will be called before any decoding and any - // type conversion (if WeaklyTypedInput is on). This lets you modify - // the values before they're set down onto the resulting struct. - // - // If an error is returned, the entire decode will fail with that - // error. - DecodeHook DecodeHookFunc - - // If ErrorUnused is true, then it is an error for there to exist - // keys in the original map that were unused in the decoding process - // (extra keys). - ErrorUnused bool - - // ZeroFields, if set to true, will zero fields before writing them. - // For example, a map will be emptied before decoded values are put in - // it. If this is false, a map will be merged. - ZeroFields bool - - // If WeaklyTypedInput is true, the decoder will make the following - // "weak" conversions: - // - // - bools to string (true = "1", false = "0") - // - numbers to string (base 10) - // - bools to int/uint (true = 1, false = 0) - // - strings to int/uint (base implied by prefix) - // - int to bool (true if value != 0) - // - string to bool (accepts: 1, t, T, TRUE, true, True, 0, f, F, - // FALSE, false, False. Anything else is an error) - // - empty array = empty map and vice versa - // - negative numbers to overflowed uint values (base 10) - // - slice of maps to a merged map - // - single values are converted to slices if required. Each - // element is weakly decoded. For example: "4" can become []int{4} - // if the target type is an int slice. - // - WeaklyTypedInput bool - - // Metadata is the struct that will contain extra metadata about - // the decoding. If this is nil, then no metadata will be tracked. - Metadata *Metadata - - // Result is a pointer to the struct that will contain the decoded - // value. - Result interface{} - - // The tag name that mapstructure reads for field names. This - // defaults to "mapstructure" - TagName string -} - -// A Decoder takes a raw interface value and turns it into structured -// data, keeping track of rich error information along the way in case -// anything goes wrong. Unlike the basic top-level Decode method, you can -// more finely control how the Decoder behaves using the DecoderConfig -// structure. The top-level Decode method is just a convenience that sets -// up the most basic Decoder. -type Decoder struct { - config *DecoderConfig -} - -// Metadata contains information about decoding a structure that -// is tedious or difficult to get otherwise. -type Metadata struct { - // Keys are the keys of the structure which were successfully decoded - Keys []string - - // Unused is a slice of keys that were found in the raw value but - // weren't decoded since there was no matching field in the result interface - Unused []string -} - -// Decode takes an input structure and uses reflection to translate it to -// the output structure. output must be a pointer to a map or struct. -func Decode(input interface{}, output interface{}) error { - config := &DecoderConfig{ - Metadata: nil, - Result: output, - } - - decoder, err := NewDecoder(config) - if err != nil { - return err - } - - return decoder.Decode(input) -} - -// WeakDecode is the same as Decode but is shorthand to enable -// WeaklyTypedInput. See DecoderConfig for more info. -func WeakDecode(input, output interface{}) error { - config := &DecoderConfig{ - Metadata: nil, - Result: output, - WeaklyTypedInput: true, - } - - decoder, err := NewDecoder(config) - if err != nil { - return err - } - - return decoder.Decode(input) -} - -// DecodeMetadata is the same as Decode, but is shorthand to -// enable metadata collection. See DecoderConfig for more info. -func DecodeMetadata(input interface{}, output interface{}, metadata *Metadata) error { - config := &DecoderConfig{ - Metadata: metadata, - Result: output, - } - - decoder, err := NewDecoder(config) - if err != nil { - return err - } - - return decoder.Decode(input) -} - -// WeakDecodeMetadata is the same as Decode, but is shorthand to -// enable both WeaklyTypedInput and metadata collection. See -// DecoderConfig for more info. -func WeakDecodeMetadata(input interface{}, output interface{}, metadata *Metadata) error { - config := &DecoderConfig{ - Metadata: metadata, - Result: output, - WeaklyTypedInput: true, - } - - decoder, err := NewDecoder(config) - if err != nil { - return err - } - - return decoder.Decode(input) -} - -// NewDecoder returns a new decoder for the given configuration. Once -// a decoder has been returned, the same configuration must not be used -// again. -func NewDecoder(config *DecoderConfig) (*Decoder, error) { - val := reflect.ValueOf(config.Result) - if val.Kind() != reflect.Ptr { - return nil, errors.New("result must be a pointer") - } - - val = val.Elem() - if !val.CanAddr() { - return nil, errors.New("result must be addressable (a pointer)") - } - - if config.Metadata != nil { - if config.Metadata.Keys == nil { - config.Metadata.Keys = make([]string, 0) - } - - if config.Metadata.Unused == nil { - config.Metadata.Unused = make([]string, 0) - } - } - - if config.TagName == "" { - config.TagName = "mapstructure" - } - - result := &Decoder{ - config: config, - } - - return result, nil -} - -// Decode decodes the given raw interface to the target pointer specified -// by the configuration. -func (d *Decoder) Decode(input interface{}) error { - return d.decode("", input, reflect.ValueOf(d.config.Result).Elem()) -} - -// Decodes an unknown data type into a specific reflection value. -func (d *Decoder) decode(name string, input interface{}, outVal reflect.Value) error { - if input == nil { - // If the data is nil, then we don't set anything, unless ZeroFields is set - // to true. - if d.config.ZeroFields { - outVal.Set(reflect.Zero(outVal.Type())) - - if d.config.Metadata != nil && name != "" { - d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) - } - } - return nil - } - - inputVal := reflect.ValueOf(input) - if !inputVal.IsValid() { - // If the input value is invalid, then we just set the value - // to be the zero value. - outVal.Set(reflect.Zero(outVal.Type())) - if d.config.Metadata != nil && name != "" { - d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) - } - return nil - } - - if d.config.DecodeHook != nil { - // We have a DecodeHook, so let's pre-process the input. - var err error - input, err = DecodeHookExec( - d.config.DecodeHook, - inputVal.Type(), outVal.Type(), input) - if err != nil { - return fmt.Errorf("error decoding '%s': %s", name, err) - } - } - - var err error - inputKind := getKind(outVal) - switch inputKind { - case reflect.Bool: - err = d.decodeBool(name, input, outVal) - case reflect.Interface: - err = d.decodeBasic(name, input, outVal) - case reflect.String: - err = d.decodeString(name, input, outVal) - case reflect.Int: - err = d.decodeInt(name, input, outVal) - case reflect.Uint: - err = d.decodeUint(name, input, outVal) - case reflect.Float32: - err = d.decodeFloat(name, input, outVal) - case reflect.Struct: - err = d.decodeStruct(name, input, outVal) - case reflect.Map: - err = d.decodeMap(name, input, outVal) - case reflect.Ptr: - err = d.decodePtr(name, input, outVal) - case reflect.Slice: - err = d.decodeSlice(name, input, outVal) - case reflect.Array: - err = d.decodeArray(name, input, outVal) - case reflect.Func: - err = d.decodeFunc(name, input, outVal) - default: - // If we reached this point then we weren't able to decode it - return fmt.Errorf("%s: unsupported type: %s", name, inputKind) - } - - // If we reached here, then we successfully decoded SOMETHING, so - // mark the key as used if we're tracking metainput. - if d.config.Metadata != nil && name != "" { - d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) - } - - return err -} - -// This decodes a basic type (bool, int, string, etc.) and sets the -// value to "data" of that type. -func (d *Decoder) decodeBasic(name string, data interface{}, val reflect.Value) error { - if val.IsValid() && val.Elem().IsValid() { - return d.decode(name, data, val.Elem()) - } - dataVal := reflect.ValueOf(data) - if !dataVal.IsValid() { - dataVal = reflect.Zero(val.Type()) - } - - dataValType := dataVal.Type() - if !dataValType.AssignableTo(val.Type()) { - return fmt.Errorf( - "'%s' expected type '%s', got '%s'", - name, val.Type(), dataValType) - } - - val.Set(dataVal) - return nil -} - -func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.ValueOf(data) - dataKind := getKind(dataVal) - - converted := true - switch { - case dataKind == reflect.String: - val.SetString(dataVal.String()) - case dataKind == reflect.Bool && d.config.WeaklyTypedInput: - if dataVal.Bool() { - val.SetString("1") - } else { - val.SetString("0") - } - case dataKind == reflect.Int && d.config.WeaklyTypedInput: - val.SetString(strconv.FormatInt(dataVal.Int(), 10)) - case dataKind == reflect.Uint && d.config.WeaklyTypedInput: - val.SetString(strconv.FormatUint(dataVal.Uint(), 10)) - case dataKind == reflect.Float32 && d.config.WeaklyTypedInput: - val.SetString(strconv.FormatFloat(dataVal.Float(), 'f', -1, 64)) - case dataKind == reflect.Slice && d.config.WeaklyTypedInput, - dataKind == reflect.Array && d.config.WeaklyTypedInput: - dataType := dataVal.Type() - elemKind := dataType.Elem().Kind() - switch elemKind { - case reflect.Uint8: - var uints []uint8 - if dataKind == reflect.Array { - uints = make([]uint8, dataVal.Len(), dataVal.Len()) - for i := range uints { - uints[i] = dataVal.Index(i).Interface().(uint8) - } - } else { - uints = dataVal.Interface().([]uint8) - } - val.SetString(string(uints)) - default: - converted = false - } - default: - converted = false - } - - if !converted { - return fmt.Errorf( - "'%s' expected type '%s', got unconvertible type '%s'", - name, val.Type(), dataVal.Type()) - } - - return nil -} - -func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.ValueOf(data) - dataKind := getKind(dataVal) - dataType := dataVal.Type() - - switch { - case dataKind == reflect.Int: - val.SetInt(dataVal.Int()) - case dataKind == reflect.Uint: - val.SetInt(int64(dataVal.Uint())) - case dataKind == reflect.Float32: - val.SetInt(int64(dataVal.Float())) - case dataKind == reflect.Bool && d.config.WeaklyTypedInput: - if dataVal.Bool() { - val.SetInt(1) - } else { - val.SetInt(0) - } - case dataKind == reflect.String && d.config.WeaklyTypedInput: - i, err := strconv.ParseInt(dataVal.String(), 0, val.Type().Bits()) - if err == nil { - val.SetInt(i) - } else { - return fmt.Errorf("cannot parse '%s' as int: %s", name, err) - } - case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number": - jn := data.(json.Number) - i, err := jn.Int64() - if err != nil { - return fmt.Errorf( - "error decoding json.Number into %s: %s", name, err) - } - val.SetInt(i) - default: - return fmt.Errorf( - "'%s' expected type '%s', got unconvertible type '%s'", - name, val.Type(), dataVal.Type()) - } - - return nil -} - -func (d *Decoder) decodeUint(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.ValueOf(data) - dataKind := getKind(dataVal) - - switch { - case dataKind == reflect.Int: - i := dataVal.Int() - if i < 0 && !d.config.WeaklyTypedInput { - return fmt.Errorf("cannot parse '%s', %d overflows uint", - name, i) - } - val.SetUint(uint64(i)) - case dataKind == reflect.Uint: - val.SetUint(dataVal.Uint()) - case dataKind == reflect.Float32: - f := dataVal.Float() - if f < 0 && !d.config.WeaklyTypedInput { - return fmt.Errorf("cannot parse '%s', %f overflows uint", - name, f) - } - val.SetUint(uint64(f)) - case dataKind == reflect.Bool && d.config.WeaklyTypedInput: - if dataVal.Bool() { - val.SetUint(1) - } else { - val.SetUint(0) - } - case dataKind == reflect.String && d.config.WeaklyTypedInput: - i, err := strconv.ParseUint(dataVal.String(), 0, val.Type().Bits()) - if err == nil { - val.SetUint(i) - } else { - return fmt.Errorf("cannot parse '%s' as uint: %s", name, err) - } - default: - return fmt.Errorf( - "'%s' expected type '%s', got unconvertible type '%s'", - name, val.Type(), dataVal.Type()) - } - - return nil -} - -func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.ValueOf(data) - dataKind := getKind(dataVal) - - switch { - case dataKind == reflect.Bool: - val.SetBool(dataVal.Bool()) - case dataKind == reflect.Int && d.config.WeaklyTypedInput: - val.SetBool(dataVal.Int() != 0) - case dataKind == reflect.Uint && d.config.WeaklyTypedInput: - val.SetBool(dataVal.Uint() != 0) - case dataKind == reflect.Float32 && d.config.WeaklyTypedInput: - val.SetBool(dataVal.Float() != 0) - case dataKind == reflect.String && d.config.WeaklyTypedInput: - b, err := strconv.ParseBool(dataVal.String()) - if err == nil { - val.SetBool(b) - } else if dataVal.String() == "" { - val.SetBool(false) - } else { - return fmt.Errorf("cannot parse '%s' as bool: %s", name, err) - } - default: - return fmt.Errorf( - "'%s' expected type '%s', got unconvertible type '%s'", - name, val.Type(), dataVal.Type()) - } - - return nil -} - -func (d *Decoder) decodeFloat(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.ValueOf(data) - dataKind := getKind(dataVal) - dataType := dataVal.Type() - - switch { - case dataKind == reflect.Int: - val.SetFloat(float64(dataVal.Int())) - case dataKind == reflect.Uint: - val.SetFloat(float64(dataVal.Uint())) - case dataKind == reflect.Float32: - val.SetFloat(dataVal.Float()) - case dataKind == reflect.Bool && d.config.WeaklyTypedInput: - if dataVal.Bool() { - val.SetFloat(1) - } else { - val.SetFloat(0) - } - case dataKind == reflect.String && d.config.WeaklyTypedInput: - f, err := strconv.ParseFloat(dataVal.String(), val.Type().Bits()) - if err == nil { - val.SetFloat(f) - } else { - return fmt.Errorf("cannot parse '%s' as float: %s", name, err) - } - case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number": - jn := data.(json.Number) - i, err := jn.Float64() - if err != nil { - return fmt.Errorf( - "error decoding json.Number into %s: %s", name, err) - } - val.SetFloat(i) - default: - return fmt.Errorf( - "'%s' expected type '%s', got unconvertible type '%s'", - name, val.Type(), dataVal.Type()) - } - - return nil -} - -func (d *Decoder) decodeMap(name string, data interface{}, val reflect.Value) error { - valType := val.Type() - valKeyType := valType.Key() - valElemType := valType.Elem() - - // By default we overwrite keys in the current map - valMap := val - - // If the map is nil or we're purposely zeroing fields, make a new map - if valMap.IsNil() || d.config.ZeroFields { - // Make a new map to hold our result - mapType := reflect.MapOf(valKeyType, valElemType) - valMap = reflect.MakeMap(mapType) - } - - // Check input type and based on the input type jump to the proper func - dataVal := reflect.Indirect(reflect.ValueOf(data)) - switch dataVal.Kind() { - case reflect.Map: - return d.decodeMapFromMap(name, dataVal, val, valMap) - - case reflect.Struct: - return d.decodeMapFromStruct(name, dataVal, val, valMap) - - case reflect.Array, reflect.Slice: - if d.config.WeaklyTypedInput { - return d.decodeMapFromSlice(name, dataVal, val, valMap) - } - - fallthrough - - default: - return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind()) - } -} - -func (d *Decoder) decodeMapFromSlice(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { - // Special case for BC reasons (covered by tests) - if dataVal.Len() == 0 { - val.Set(valMap) - return nil - } - - for i := 0; i < dataVal.Len(); i++ { - err := d.decode( - fmt.Sprintf("%s[%d]", name, i), - dataVal.Index(i).Interface(), val) - if err != nil { - return err - } - } - - return nil -} - -func (d *Decoder) decodeMapFromMap(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { - valType := val.Type() - valKeyType := valType.Key() - valElemType := valType.Elem() - - // Accumulate errors - errors := make([]string, 0) - - for _, k := range dataVal.MapKeys() { - fieldName := fmt.Sprintf("%s[%s]", name, k) - - // First decode the key into the proper type - currentKey := reflect.Indirect(reflect.New(valKeyType)) - if err := d.decode(fieldName, k.Interface(), currentKey); err != nil { - errors = appendErrors(errors, err) - continue - } - - // Next decode the data into the proper type - v := dataVal.MapIndex(k).Interface() - currentVal := reflect.Indirect(reflect.New(valElemType)) - if err := d.decode(fieldName, v, currentVal); err != nil { - errors = appendErrors(errors, err) - continue - } - - valMap.SetMapIndex(currentKey, currentVal) - } - - // Set the built up map to the value - val.Set(valMap) - - // If we had errors, return those - if len(errors) > 0 { - return &Error{errors} - } - - return nil -} - -func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { - typ := dataVal.Type() - for i := 0; i < typ.NumField(); i++ { - // Get the StructField first since this is a cheap operation. If the - // field is unexported, then ignore it. - f := typ.Field(i) - if f.PkgPath != "" { - continue - } - - // Next get the actual value of this field and verify it is assignable - // to the map value. - v := dataVal.Field(i) - if !v.Type().AssignableTo(valMap.Type().Elem()) { - return fmt.Errorf("cannot assign type '%s' to map value field of type '%s'", v.Type(), valMap.Type().Elem()) - } - - tagValue := f.Tag.Get(d.config.TagName) - tagParts := strings.Split(tagValue, ",") - - // Determine the name of the key in the map - keyName := f.Name - if tagParts[0] != "" { - if tagParts[0] == "-" { - continue - } - keyName = tagParts[0] - } - - // If "squash" is specified in the tag, we squash the field down. - squash := false - for _, tag := range tagParts[1:] { - if tag == "squash" { - squash = true - break - } - } - if squash && v.Kind() != reflect.Struct { - return fmt.Errorf("cannot squash non-struct type '%s'", v.Type()) - } - - switch v.Kind() { - // this is an embedded struct, so handle it differently - case reflect.Struct: - x := reflect.New(v.Type()) - x.Elem().Set(v) - - vType := valMap.Type() - vKeyType := vType.Key() - vElemType := vType.Elem() - mType := reflect.MapOf(vKeyType, vElemType) - vMap := reflect.MakeMap(mType) - - err := d.decode(keyName, x.Interface(), vMap) - if err != nil { - return err - } - - if squash { - for _, k := range vMap.MapKeys() { - valMap.SetMapIndex(k, vMap.MapIndex(k)) - } - } else { - valMap.SetMapIndex(reflect.ValueOf(keyName), vMap) - } - - default: - valMap.SetMapIndex(reflect.ValueOf(keyName), v) - } - } - - if val.CanAddr() { - val.Set(valMap) - } - - return nil -} - -func (d *Decoder) decodePtr(name string, data interface{}, val reflect.Value) error { - // Create an element of the concrete (non pointer) type and decode - // into that. Then set the value of the pointer to this type. - valType := val.Type() - valElemType := valType.Elem() - - if val.CanSet() { - realVal := val - if realVal.IsNil() || d.config.ZeroFields { - realVal = reflect.New(valElemType) - } - - if err := d.decode(name, data, reflect.Indirect(realVal)); err != nil { - return err - } - - val.Set(realVal) - } else { - if err := d.decode(name, data, reflect.Indirect(val)); err != nil { - return err - } - } - return nil -} - -func (d *Decoder) decodeFunc(name string, data interface{}, val reflect.Value) error { - // Create an element of the concrete (non pointer) type and decode - // into that. Then set the value of the pointer to this type. - dataVal := reflect.Indirect(reflect.ValueOf(data)) - if val.Type() != dataVal.Type() { - return fmt.Errorf( - "'%s' expected type '%s', got unconvertible type '%s'", - name, val.Type(), dataVal.Type()) - } - val.Set(dataVal) - return nil -} - -func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.Indirect(reflect.ValueOf(data)) - dataValKind := dataVal.Kind() - valType := val.Type() - valElemType := valType.Elem() - sliceType := reflect.SliceOf(valElemType) - - valSlice := val - if valSlice.IsNil() || d.config.ZeroFields { - // Check input type - if dataValKind != reflect.Array && dataValKind != reflect.Slice { - if d.config.WeaklyTypedInput { - switch { - // Empty maps turn into empty slices - case dataValKind == reflect.Map: - if dataVal.Len() == 0 { - val.Set(reflect.MakeSlice(sliceType, 0, 0)) - return nil - } - // Create slice of maps of other sizes - return d.decodeSlice(name, []interface{}{data}, val) - - case dataValKind == reflect.String && valElemType.Kind() == reflect.Uint8: - return d.decodeSlice(name, []byte(dataVal.String()), val) - // All other types we try to convert to the slice type - // and "lift" it into it. i.e. a string becomes a string slice. - default: - // Just re-try this function with data as a slice. - return d.decodeSlice(name, []interface{}{data}, val) - } - } - return fmt.Errorf( - "'%s': source data must be an array or slice, got %s", name, dataValKind) - - } - - // Make a new slice to hold our result, same size as the original data. - valSlice = reflect.MakeSlice(sliceType, dataVal.Len(), dataVal.Len()) - } - - // Accumulate any errors - errors := make([]string, 0) - - for i := 0; i < dataVal.Len(); i++ { - currentData := dataVal.Index(i).Interface() - for valSlice.Len() <= i { - valSlice = reflect.Append(valSlice, reflect.Zero(valElemType)) - } - currentField := valSlice.Index(i) - - fieldName := fmt.Sprintf("%s[%d]", name, i) - if err := d.decode(fieldName, currentData, currentField); err != nil { - errors = appendErrors(errors, err) - } - } - - // Finally, set the value to the slice we built up - val.Set(valSlice) - - // If there were errors, we return those - if len(errors) > 0 { - return &Error{errors} - } - - return nil -} - -func (d *Decoder) decodeArray(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.Indirect(reflect.ValueOf(data)) - dataValKind := dataVal.Kind() - valType := val.Type() - valElemType := valType.Elem() - arrayType := reflect.ArrayOf(valType.Len(), valElemType) - - valArray := val - - if valArray.Interface() == reflect.Zero(valArray.Type()).Interface() || d.config.ZeroFields { - // Check input type - if dataValKind != reflect.Array && dataValKind != reflect.Slice { - if d.config.WeaklyTypedInput { - switch { - // Empty maps turn into empty arrays - case dataValKind == reflect.Map: - if dataVal.Len() == 0 { - val.Set(reflect.Zero(arrayType)) - return nil - } - - // All other types we try to convert to the array type - // and "lift" it into it. i.e. a string becomes a string array. - default: - // Just re-try this function with data as a slice. - return d.decodeArray(name, []interface{}{data}, val) - } - } - - return fmt.Errorf( - "'%s': source data must be an array or slice, got %s", name, dataValKind) - - } - if dataVal.Len() > arrayType.Len() { - return fmt.Errorf( - "'%s': expected source data to have length less or equal to %d, got %d", name, arrayType.Len(), dataVal.Len()) - - } - - // Make a new array to hold our result, same size as the original data. - valArray = reflect.New(arrayType).Elem() - } - - // Accumulate any errors - errors := make([]string, 0) - - for i := 0; i < dataVal.Len(); i++ { - currentData := dataVal.Index(i).Interface() - currentField := valArray.Index(i) - - fieldName := fmt.Sprintf("%s[%d]", name, i) - if err := d.decode(fieldName, currentData, currentField); err != nil { - errors = appendErrors(errors, err) - } - } - - // Finally, set the value to the array we built up - val.Set(valArray) - - // If there were errors, we return those - if len(errors) > 0 { - return &Error{errors} - } - - return nil -} - -func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.Indirect(reflect.ValueOf(data)) - - // If the type of the value to write to and the data match directly, - // then we just set it directly instead of recursing into the structure. - if dataVal.Type() == val.Type() { - val.Set(dataVal) - return nil - } - - dataValKind := dataVal.Kind() - if dataValKind != reflect.Map { - return fmt.Errorf("'%s' expected a map, got '%s'", name, dataValKind) - } - - dataValType := dataVal.Type() - if kind := dataValType.Key().Kind(); kind != reflect.String && kind != reflect.Interface { - return fmt.Errorf( - "'%s' needs a map with string keys, has '%s' keys", - name, dataValType.Key().Kind()) - } - - dataValKeys := make(map[reflect.Value]struct{}) - dataValKeysUnused := make(map[interface{}]struct{}) - for _, dataValKey := range dataVal.MapKeys() { - dataValKeys[dataValKey] = struct{}{} - dataValKeysUnused[dataValKey.Interface()] = struct{}{} - } - - errors := make([]string, 0) - - // This slice will keep track of all the structs we'll be decoding. - // There can be more than one struct if there are embedded structs - // that are squashed. - structs := make([]reflect.Value, 1, 5) - structs[0] = val - - // Compile the list of all the fields that we're going to be decoding - // from all the structs. - type field struct { - field reflect.StructField - val reflect.Value - } - fields := []field{} - for len(structs) > 0 { - structVal := structs[0] - structs = structs[1:] - - structType := structVal.Type() - - for i := 0; i < structType.NumField(); i++ { - fieldType := structType.Field(i) - fieldKind := fieldType.Type.Kind() - - // If "squash" is specified in the tag, we squash the field down. - squash := false - tagParts := strings.Split(fieldType.Tag.Get(d.config.TagName), ",") - for _, tag := range tagParts[1:] { - if tag == "squash" { - squash = true - break - } - } - - if squash { - if fieldKind != reflect.Struct { - errors = appendErrors(errors, - fmt.Errorf("%s: unsupported type for squash: %s", fieldType.Name, fieldKind)) - } else { - structs = append(structs, structVal.FieldByName(fieldType.Name)) - } - continue - } - - // Normal struct field, store it away - fields = append(fields, field{fieldType, structVal.Field(i)}) - } - } - - // for fieldType, field := range fields { - for _, f := range fields { - field, fieldValue := f.field, f.val - fieldName := field.Name - - tagValue := field.Tag.Get(d.config.TagName) - tagValue = strings.SplitN(tagValue, ",", 2)[0] - if tagValue != "" { - fieldName = tagValue - } - - rawMapKey := reflect.ValueOf(fieldName) - rawMapVal := dataVal.MapIndex(rawMapKey) - if !rawMapVal.IsValid() { - // Do a slower search by iterating over each key and - // doing case-insensitive search. - for dataValKey := range dataValKeys { - mK, ok := dataValKey.Interface().(string) - if !ok { - // Not a string key - continue - } - - if strings.EqualFold(mK, fieldName) { - rawMapKey = dataValKey - rawMapVal = dataVal.MapIndex(dataValKey) - break - } - } - - if !rawMapVal.IsValid() { - // There was no matching key in the map for the value in - // the struct. Just ignore. - continue - } - } - - // Delete the key we're using from the unused map so we stop tracking - delete(dataValKeysUnused, rawMapKey.Interface()) - - if !fieldValue.IsValid() { - // This should never happen - panic("field is not valid") - } - - // If we can't set the field, then it is unexported or something, - // and we just continue onwards. - if !fieldValue.CanSet() { - continue - } - - // If the name is empty string, then we're at the root, and we - // don't dot-join the fields. - if name != "" { - fieldName = fmt.Sprintf("%s.%s", name, fieldName) - } - - if err := d.decode(fieldName, rawMapVal.Interface(), fieldValue); err != nil { - errors = appendErrors(errors, err) - } - } - - if d.config.ErrorUnused && len(dataValKeysUnused) > 0 { - keys := make([]string, 0, len(dataValKeysUnused)) - for rawKey := range dataValKeysUnused { - keys = append(keys, rawKey.(string)) - } - sort.Strings(keys) - - err := fmt.Errorf("'%s' has invalid keys: %s", name, strings.Join(keys, ", ")) - errors = appendErrors(errors, err) - } - - if len(errors) > 0 { - return &Error{errors} - } - - // Add the unused keys to the list of unused keys if we're tracking metadata - if d.config.Metadata != nil { - for rawKey := range dataValKeysUnused { - key := rawKey.(string) - if name != "" { - key = fmt.Sprintf("%s.%s", name, key) - } - - d.config.Metadata.Unused = append(d.config.Metadata.Unused, key) - } - } - - return nil -} - -func getKind(val reflect.Value) reflect.Kind { - kind := val.Kind() - - switch { - case kind >= reflect.Int && kind <= reflect.Int64: - return reflect.Int - case kind >= reflect.Uint && kind <= reflect.Uint64: - return reflect.Uint - case kind >= reflect.Float32 && kind <= reflect.Float64: - return reflect.Float32 - default: - return kind - } -} diff --git a/vendor/github.com/pquerna/otp/.travis.yml b/vendor/github.com/pquerna/otp/.travis.yml deleted file mode 100644 index d2b67f6..0000000 --- a/vendor/github.com/pquerna/otp/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -language: go - -go: - - 1.7 - - 1.8 - - tip diff --git a/vendor/github.com/pquerna/otp/LICENSE b/vendor/github.com/pquerna/otp/LICENSE deleted file mode 100644 index d645695..0000000 --- a/vendor/github.com/pquerna/otp/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/pquerna/otp/NOTICE b/vendor/github.com/pquerna/otp/NOTICE deleted file mode 100644 index 50e2e75..0000000 --- a/vendor/github.com/pquerna/otp/NOTICE +++ /dev/null @@ -1,5 +0,0 @@ -otp -Copyright (c) 2014, Paul Querna - -This product includes software developed by -Paul Querna (http://paul.querna.org/). diff --git a/vendor/github.com/pquerna/otp/README.md b/vendor/github.com/pquerna/otp/README.md deleted file mode 100644 index 148e898..0000000 --- a/vendor/github.com/pquerna/otp/README.md +++ /dev/null @@ -1,60 +0,0 @@ -# otp: One Time Password utilities Go / Golang - -[![GoDoc](https://godoc.org/github.com/pquerna/otp?status.svg)](https://godoc.org/github.com/pquerna/otp) [![Build Status](https://travis-ci.org/pquerna/otp.svg?branch=master)](https://travis-ci.org/pquerna/otp) - -# Why One Time Passwords? - -One Time Passwords (OTPs) are an mechanism to improve security over passwords alone. When a Time-based OTP (TOTP) is stored on a user's phone, and combined with something the user knows (Password), you have an easy on-ramp to [Multi-factor authentication](http://en.wikipedia.org/wiki/Multi-factor_authentication) without adding a dependency on a SMS provider. This Password and TOTP combination is used by many popular websites including Google, Github, Facebook, Salesforce and many others. - -The `otp` library enables you to easily add TOTPs to your own application, increasing your user's security against mass-password breaches and malware. - -Because TOTP is standardized and widely deployed, there are many [mobile clients and software implementations](http://en.wikipedia.org/wiki/Time-based_One-time_Password_Algorithm#Client_implementations). - -## `otp` Supports: - -* Generating QR Code images for easy user enrollment. -* Time-based One-time Password Algorithm (TOTP) (RFC 6238): Time based OTP, the most commonly used method. -* HMAC-based One-time Password Algorithm (HOTP) (RFC 4226): Counter based OTP, which TOTP is based upon. -* Generation and Validation of codes for either algorithm. - -## Implementing TOTP in your application: - -### User Enrollment - -For an example of a working enrollment work flow, [Github has documented theirs](https://help.github.com/articles/configuring-two-factor-authentication-via-a-totp-mobile-app/ -), but the basics are: - -1. Generate new TOTP Key for a User. `key,_ := totp.Generate(...)`. -1. Display the Key's Secret and QR-Code for the User. `key.Secret()` and `key.Image(...)`. -1. Test that the user can successfully use their TOTP. `totp.Validate(...)`. -1. Store TOTP Secret for the User in your backend. `key.Secret()` -1. Provide the user with "recovery codes". (See Recovery Codes bellow) - -### Code Generation - -* In either TOTP or HOTP cases, use the `GenerateCode` function and a counter or - `time.Time` struct to generate a valid code compatible with most implementations. -* For uncommon or custom settings, or to catch unlikely errors, use `GenerateCodeCustom` - in either module. - -### Validation - -1. Prompt and validate User's password as normal. -1. If the user has TOTP enabled, prompt for TOTP passcode. -1. Retrieve the User's TOTP Secret from your backend. -1. Validate the user's passcode. `totp.Validate(...)` - - -### Recovery Codes - -When a user loses access to their TOTP device, they would no longer have access to their account. Because TOTPs are often configured on mobile devices that can be lost, stolen or damaged, this is a common problem. For this reason many providers give their users "backup codes" or "recovery codes". These are a set of one time use codes that can be used instead of the TOTP. These can simply be randomly generated strings that you store in your backend. [Github's documentation provides an overview of the user experience]( -https://help.github.com/articles/downloading-your-two-factor-authentication-recovery-codes/). - - -## Improvements, bugs, adding feature, etc: - -Please [open issues in Github](https://github.com/pquerna/otp/issues) for ideas, bugs, and general thoughts. Pull requests are of course preferred :) - -## License - -`otp` is licensed under the [Apache License, Version 2.0](./LICENSE) diff --git a/vendor/github.com/pquerna/otp/doc.go b/vendor/github.com/pquerna/otp/doc.go deleted file mode 100644 index b8b4c8c..0000000 --- a/vendor/github.com/pquerna/otp/doc.go +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright 2014 Paul Querna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package otp implements both HOTP and TOTP based -// one time passcodes in a Google Authenticator compatible manner. -// -// When adding a TOTP for a user, you must store the "secret" value -// persistently. It is recommend to store the secret in an encrypted field in your -// datastore. Due to how TOTP works, it is not possible to store a hash -// for the secret value like you would a password. -// -// To enroll a user, you must first generate an OTP for them. Google -// Authenticator supports using a QR code as an enrollment method: -// -// import ( -// "github.com/pquerna/otp/totp" -// -// "bytes" -// "image/png" -// ) -// -// key, err := totp.Generate(totp.GenerateOpts{ -// Issuer: "Example.com", -// AccountName: "alice@example.com", -// }) -// -// // Convert TOTP key into a QR code encoded as a PNG image. -// var buf bytes.Buffer -// img, err := key.Image(200, 200) -// png.Encode(&buf, img) -// -// // display the QR code to the user. -// display(buf.Bytes()) -// -// // Now Validate that the user's successfully added the passcode. -// passcode := promptForPasscode() -// valid := totp.Validate(passcode, key.Secret()) -// -// if valid { -// // User successfully used their TOTP, save it to your backend! -// storeSecret("alice@example.com", key.Secret()) -// } -// -// Validating a TOTP passcode is very easy, just prompt the user for a passcode -// and retrieve the associated user's previously stored secret. -// import "github.com/pquerna/otp/totp" -// -// passcode := promptForPasscode() -// secret := getSecret("alice@example.com") -// -// valid := totp.Validate(passcode, secret) -// -// if valid { -// // Success! continue login process. -// } -package otp diff --git a/vendor/github.com/pquerna/otp/hotp/hotp.go b/vendor/github.com/pquerna/otp/hotp/hotp.go deleted file mode 100644 index 951cd0b..0000000 --- a/vendor/github.com/pquerna/otp/hotp/hotp.go +++ /dev/null @@ -1,188 +0,0 @@ -/** - * Copyright 2014 Paul Querna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package hotp - -import ( - "github.com/pquerna/otp" - - "crypto/hmac" - "crypto/rand" - "crypto/subtle" - "encoding/base32" - "encoding/binary" - "fmt" - "math" - "net/url" - "strings" -) - -const debug = false - -// Validate a HOTP passcode given a counter and secret. -// This is a shortcut for ValidateCustom, with parameters that -// are compataible with Google-Authenticator. -func Validate(passcode string, counter uint64, secret string) bool { - rv, _ := ValidateCustom( - passcode, - counter, - secret, - ValidateOpts{ - Digits: otp.DigitsSix, - Algorithm: otp.AlgorithmSHA1, - }, - ) - return rv -} - -// ValidateOpts provides options for ValidateCustom(). -type ValidateOpts struct { - // Digits as part of the input. Defaults to 6. - Digits otp.Digits - // Algorithm to use for HMAC. Defaults to SHA1. - Algorithm otp.Algorithm -} - -// GenerateCode creates a HOTP passcode given a counter and secret. -// This is a shortcut for GenerateCodeCustom, with parameters that -// are compataible with Google-Authenticator. -func GenerateCode(secret string, counter uint64) (string, error) { - return GenerateCodeCustom(secret, counter, ValidateOpts{ - Digits: otp.DigitsSix, - Algorithm: otp.AlgorithmSHA1, - }) -} - -// GenerateCodeCustom uses a counter and secret value and options struct to -// create a passcode. -func GenerateCodeCustom(secret string, counter uint64, opts ValidateOpts) (passcode string, err error) { - // As noted in issue #10 and #17 this adds support for TOTP secrets that are - // missing their padding. - secret = strings.TrimSpace(secret) - if n := len(secret) % 8; n != 0 { - secret = secret + strings.Repeat("=", 8-n) - } - - secretBytes, err := base32.StdEncoding.DecodeString(secret) - if err != nil { - return "", otp.ErrValidateSecretInvalidBase32 - } - - buf := make([]byte, 8) - mac := hmac.New(opts.Algorithm.Hash, secretBytes) - binary.BigEndian.PutUint64(buf, counter) - if debug { - fmt.Printf("counter=%v\n", counter) - fmt.Printf("buf=%v\n", buf) - } - - mac.Write(buf) - sum := mac.Sum(nil) - - // "Dynamic truncation" in RFC 4226 - // http://tools.ietf.org/html/rfc4226#section-5.4 - offset := sum[len(sum)-1] & 0xf - value := int64(((int(sum[offset]) & 0x7f) << 24) | - ((int(sum[offset+1] & 0xff)) << 16) | - ((int(sum[offset+2] & 0xff)) << 8) | - (int(sum[offset+3]) & 0xff)) - - l := opts.Digits.Length() - mod := int32(value % int64(math.Pow10(l))) - - if debug { - fmt.Printf("offset=%v\n", offset) - fmt.Printf("value=%v\n", value) - fmt.Printf("mod'ed=%v\n", mod) - } - - return opts.Digits.Format(mod), nil -} - -// ValidateCustom validates an HOTP with customizable options. Most users should -// use Validate(). -func ValidateCustom(passcode string, counter uint64, secret string, opts ValidateOpts) (bool, error) { - passcode = strings.TrimSpace(passcode) - - if len(passcode) != opts.Digits.Length() { - return false, otp.ErrValidateInputInvalidLength - } - - otpstr, err := GenerateCodeCustom(secret, counter, opts) - if err != nil { - return false, err - } - - if subtle.ConstantTimeCompare([]byte(otpstr), []byte(passcode)) == 1 { - return true, nil - } - - return false, nil -} - -// GenerateOpts provides options for .Generate() -type GenerateOpts struct { - // Name of the issuing Organization/Company. - Issuer string - // Name of the User's Account (eg, email address) - AccountName string - // Size in size of the generated Secret. Defaults to 10 bytes. - SecretSize uint - // Digits to request. Defaults to 6. - Digits otp.Digits - // Algorithm to use for HMAC. Defaults to SHA1. - Algorithm otp.Algorithm -} - -// Generate creates a new HOTP Key. -func Generate(opts GenerateOpts) (*otp.Key, error) { - // url encode the Issuer/AccountName - if opts.Issuer == "" { - return nil, otp.ErrGenerateMissingIssuer - } - - if opts.AccountName == "" { - return nil, otp.ErrGenerateMissingAccountName - } - - if opts.SecretSize == 0 { - opts.SecretSize = 10 - } - - // otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP&issuer=Example - - v := url.Values{} - secret := make([]byte, opts.SecretSize) - _, err := rand.Read(secret) - if err != nil { - return nil, err - } - - v.Set("secret", strings.TrimRight(base32.StdEncoding.EncodeToString(secret), "=")) - v.Set("issuer", opts.Issuer) - v.Set("algorithm", opts.Algorithm.String()) - v.Set("digits", opts.Digits.String()) - - u := url.URL{ - Scheme: "otpauth", - Host: "hotp", - Path: "/" + opts.Issuer + ":" + opts.AccountName, - RawQuery: v.Encode(), - } - - return otp.NewKeyFromURL(u.String()) -} diff --git a/vendor/github.com/pquerna/otp/otp.go b/vendor/github.com/pquerna/otp/otp.go deleted file mode 100644 index 88d0da1..0000000 --- a/vendor/github.com/pquerna/otp/otp.go +++ /dev/null @@ -1,202 +0,0 @@ -/** - * Copyright 2014 Paul Querna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package otp - -import ( - "github.com/boombuler/barcode" - "github.com/boombuler/barcode/qr" - - "crypto/md5" - "crypto/sha1" - "crypto/sha256" - "crypto/sha512" - "errors" - "fmt" - "hash" - "image" - "net/url" - "strings" -) - -// Error when attempting to convert the secret from base32 to raw bytes. -var ErrValidateSecretInvalidBase32 = errors.New("Decoding of secret as base32 failed.") - -// The user provided passcode length was not expected. -var ErrValidateInputInvalidLength = errors.New("Input length unexpected") - -// When generating a Key, the Issuer must be set. -var ErrGenerateMissingIssuer = errors.New("Issuer must be set") - -// When generating a Key, the Account Name must be set. -var ErrGenerateMissingAccountName = errors.New("AccountName must be set") - -// Key represents an TOTP or HTOP key. -type Key struct { - orig string - url *url.URL -} - -// NewKeyFromURL creates a new Key from an TOTP or HOTP url. -// -// The URL format is documented here: -// https://github.com/google/google-authenticator/wiki/Key-Uri-Format -// -func NewKeyFromURL(orig string) (*Key, error) { - s := strings.TrimSpace(orig) - - u, err := url.Parse(s) - - if err != nil { - return nil, err - } - - return &Key{ - orig: s, - url: u, - }, nil -} - -func (k *Key) String() string { - return k.orig -} - -// Image returns an QR-Code image of the specified width and height, -// suitable for use by many clients like Google-Authenricator -// to enroll a user's TOTP/HOTP key. -func (k *Key) Image(width int, height int) (image.Image, error) { - b, err := qr.Encode(k.orig, qr.M, qr.Auto) - - if err != nil { - return nil, err - } - - b, err = barcode.Scale(b, width, height) - - if err != nil { - return nil, err - } - - return b, nil -} - -// Type returns "hotp" or "totp". -func (k *Key) Type() string { - return k.url.Host -} - -// Issuer returns the name of the issuing organization. -func (k *Key) Issuer() string { - q := k.url.Query() - - issuer := q.Get("issuer") - - if issuer != "" { - return issuer - } - - p := strings.TrimPrefix(k.url.Path, "/") - i := strings.Index(p, ":") - - if i == -1 { - return "" - } - - return p[:i] -} - -// AccountName returns the name of the user's account. -func (k *Key) AccountName() string { - p := strings.TrimPrefix(k.url.Path, "/") - i := strings.Index(p, ":") - - if i == -1 { - return p - } - - return p[i+1:] -} - -// Secret returns the opaque secret for this Key. -func (k *Key) Secret() string { - q := k.url.Query() - - return q.Get("secret") -} - -// Algorithm represents the hashing function to use in the HMAC -// operation needed for OTPs. -type Algorithm int - -const ( - AlgorithmSHA1 Algorithm = iota - AlgorithmSHA256 - AlgorithmSHA512 - AlgorithmMD5 -) - -func (a Algorithm) String() string { - switch a { - case AlgorithmSHA1: - return "SHA1" - case AlgorithmSHA256: - return "SHA256" - case AlgorithmSHA512: - return "SHA512" - case AlgorithmMD5: - return "MD5" - } - panic("unreached") -} - -func (a Algorithm) Hash() hash.Hash { - switch a { - case AlgorithmSHA1: - return sha1.New() - case AlgorithmSHA256: - return sha256.New() - case AlgorithmSHA512: - return sha512.New() - case AlgorithmMD5: - return md5.New() - } - panic("unreached") -} - -// Digits represents the number of digits present in the -// user's OTP passcode. Six and Eight are the most common values. -type Digits int - -const ( - DigitsSix Digits = 6 - DigitsEight Digits = 8 -) - -// Format converts an integer into the zero-filled size for this Digits. -func (d Digits) Format(in int32) string { - f := fmt.Sprintf("%%0%dd", d) - return fmt.Sprintf(f, in) -} - -// Length returns the number of characters for this Digits. -func (d Digits) Length() int { - return int(d) -} - -func (d Digits) String() string { - return fmt.Sprintf("%d", d) -} diff --git a/vendor/github.com/pquerna/otp/totp/totp.go b/vendor/github.com/pquerna/otp/totp/totp.go deleted file mode 100644 index dff9ad5..0000000 --- a/vendor/github.com/pquerna/otp/totp/totp.go +++ /dev/null @@ -1,193 +0,0 @@ -/** - * Copyright 2014 Paul Querna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package totp - -import ( - "strings" - - "github.com/pquerna/otp" - "github.com/pquerna/otp/hotp" - - "crypto/rand" - "encoding/base32" - "math" - "net/url" - "strconv" - "time" -) - -// Validate a TOTP using the current time. -// A shortcut for ValidateCustom, Validate uses a configuration -// that is compatible with Google-Authenticator and most clients. -func Validate(passcode string, secret string) bool { - rv, _ := ValidateCustom( - passcode, - secret, - time.Now().UTC(), - ValidateOpts{ - Period: 30, - Skew: 1, - Digits: otp.DigitsSix, - Algorithm: otp.AlgorithmSHA1, - }, - ) - return rv -} - -// GenerateCode creates a TOTP token using the current time. -// A shortcut for GenerateCodeCustom, GenerateCode uses a configuration -// that is compatible with Google-Authenticator and most clients. -func GenerateCode(secret string, t time.Time) (string, error) { - return GenerateCodeCustom(secret, t, ValidateOpts{ - Period: 30, - Skew: 1, - Digits: otp.DigitsSix, - Algorithm: otp.AlgorithmSHA1, - }) -} - -// ValidateOpts provides options for ValidateCustom(). -type ValidateOpts struct { - // Number of seconds a TOTP hash is valid for. Defaults to 30 seconds. - Period uint - // Periods before or after the current time to allow. Value of 1 allows up to Period - // of either side of the specified time. Defaults to 0 allowed skews. Values greater - // than 1 are likely sketchy. - Skew uint - // Digits as part of the input. Defaults to 6. - Digits otp.Digits - // Algorithm to use for HMAC. Defaults to SHA1. - Algorithm otp.Algorithm -} - -// GenerateCodeCustom takes a timepoint and produces a passcode using a -// secret and the provided opts. (Under the hood, this is making an adapted -// call to hotp.GenerateCodeCustom) -func GenerateCodeCustom(secret string, t time.Time, opts ValidateOpts) (passcode string, err error) { - if opts.Period == 0 { - opts.Period = 30 - } - counter := uint64(math.Floor(float64(t.Unix()) / float64(opts.Period))) - passcode, err = hotp.GenerateCodeCustom(secret, counter, hotp.ValidateOpts{ - Digits: opts.Digits, - Algorithm: opts.Algorithm, - }) - if err != nil { - return "", err - } - return passcode, nil -} - -// ValidateCustom validates a TOTP given a user specified time and custom options. -// Most users should use Validate() to provide an interpolatable TOTP experience. -func ValidateCustom(passcode string, secret string, t time.Time, opts ValidateOpts) (bool, error) { - if opts.Period == 0 { - opts.Period = 30 - } - - counters := []uint64{} - counter := int64(math.Floor(float64(t.Unix()) / float64(opts.Period))) - - counters = append(counters, uint64(counter)) - for i := 1; i <= int(opts.Skew); i++ { - counters = append(counters, uint64(counter+int64(i))) - counters = append(counters, uint64(counter-int64(i))) - } - - for _, counter := range counters { - rv, err := hotp.ValidateCustom(passcode, counter, secret, hotp.ValidateOpts{ - Digits: opts.Digits, - Algorithm: opts.Algorithm, - }) - - if err != nil { - return false, err - } - - if rv == true { - return true, nil - } - } - - return false, nil -} - -// GenerateOpts provides options for Generate(). The default values -// are compatible with Google-Authenticator. -type GenerateOpts struct { - // Name of the issuing Organization/Company. - Issuer string - // Name of the User's Account (eg, email address) - AccountName string - // Number of seconds a TOTP hash is valid for. Defaults to 30 seconds. - Period uint - // Size in size of the generated Secret. Defaults to 10 bytes. - SecretSize uint - // Digits to request. Defaults to 6. - Digits otp.Digits - // Algorithm to use for HMAC. Defaults to SHA1. - Algorithm otp.Algorithm -} - -// Generate a new TOTP Key. -func Generate(opts GenerateOpts) (*otp.Key, error) { - // url encode the Issuer/AccountName - if opts.Issuer == "" { - return nil, otp.ErrGenerateMissingIssuer - } - - if opts.AccountName == "" { - return nil, otp.ErrGenerateMissingAccountName - } - - if opts.Period == 0 { - opts.Period = 30 - } - - if opts.SecretSize == 0 { - opts.SecretSize = 10 - } - - if opts.Digits == 0 { - opts.Digits = otp.DigitsSix - } - - // otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP&issuer=Example - - v := url.Values{} - secret := make([]byte, opts.SecretSize) - _, err := rand.Read(secret) - if err != nil { - return nil, err - } - - v.Set("secret", strings.TrimRight(base32.StdEncoding.EncodeToString(secret), "=")) - v.Set("issuer", opts.Issuer) - v.Set("period", strconv.FormatUint(uint64(opts.Period), 10)) - v.Set("algorithm", opts.Algorithm.String()) - v.Set("digits", opts.Digits.String()) - - u := url.URL{ - Scheme: "otpauth", - Host: "totp", - Path: "/" + opts.Issuer + ":" + opts.AccountName, - RawQuery: v.Encode(), - } - - return otp.NewKeyFromURL(u.String()) -} diff --git a/vendor/github.com/ryanuber/go-glob/.travis.yml b/vendor/github.com/ryanuber/go-glob/.travis.yml deleted file mode 100644 index 9d1ca3c..0000000 --- a/vendor/github.com/ryanuber/go-glob/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: go -go: - - tip -script: - - go test -v ./... diff --git a/vendor/github.com/ryanuber/go-glob/LICENSE b/vendor/github.com/ryanuber/go-glob/LICENSE deleted file mode 100644 index bdfbd95..0000000 --- a/vendor/github.com/ryanuber/go-glob/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Ryan Uber - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/ryanuber/go-glob/README.md b/vendor/github.com/ryanuber/go-glob/README.md deleted file mode 100644 index 48f7fcb..0000000 --- a/vendor/github.com/ryanuber/go-glob/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# String globbing in golang [![Build Status](https://travis-ci.org/ryanuber/go-glob.svg)](https://travis-ci.org/ryanuber/go-glob) - -`go-glob` is a single-function library implementing basic string glob support. - -Globs are an extremely user-friendly way of supporting string matching without -requiring knowledge of regular expressions or Go's particular regex engine. Most -people understand that if you put a `*` character somewhere in a string, it is -treated as a wildcard. Surprisingly, this functionality isn't found in Go's -standard library, except for `path.Match`, which is intended to be used while -comparing paths (not arbitrary strings), and contains specialized logic for this -use case. A better solution might be a POSIX basic (non-ERE) regular expression -engine for Go, which doesn't exist currently. - -Example -======= - -``` -package main - -import "github.com/ryanuber/go-glob" - -func main() { - glob.Glob("*World!", "Hello, World!") // true - glob.Glob("Hello,*", "Hello, World!") // true - glob.Glob("*ello,*", "Hello, World!") // true - glob.Glob("World!", "Hello, World!") // false - glob.Glob("/home/*", "/home/ryanuber/.bashrc") // true -} -``` diff --git a/vendor/github.com/ryanuber/go-glob/glob.go b/vendor/github.com/ryanuber/go-glob/glob.go deleted file mode 100644 index d9d4637..0000000 --- a/vendor/github.com/ryanuber/go-glob/glob.go +++ /dev/null @@ -1,51 +0,0 @@ -package glob - -import "strings" - -// The character which is treated like a glob -const GLOB = "*" - -// Glob will test a string pattern, potentially containing globs, against a -// subject string. The result is a simple true/false, determining whether or -// not the glob pattern matched the subject text. -func Glob(pattern, subj string) bool { - // Empty pattern can only match empty subject - if pattern == "" { - return subj == pattern - } - - // If the pattern _is_ a glob, it matches everything - if pattern == GLOB { - return true - } - - parts := strings.Split(pattern, GLOB) - - if len(parts) == 1 { - // No globs in pattern, so test for equality - return subj == pattern - } - - leadingGlob := strings.HasPrefix(pattern, GLOB) - trailingGlob := strings.HasSuffix(pattern, GLOB) - end := len(parts) - 1 - - // Check the first section. Requires special handling. - if !leadingGlob && !strings.HasPrefix(subj, parts[0]) { - return false - } - - // Go over the middle parts and ensure they match. - for i := 1; i < end; i++ { - if !strings.Contains(subj, parts[i]) { - return false - } - - // Trim evaluated text from subj as we loop over the pattern. - idx := strings.Index(subj, parts[i]) + len(parts[i]) - subj = subj[idx:] - } - - // Reached the last section. Requires special handling. - return trailingGlob || strings.HasSuffix(subj, parts[end]) -} diff --git a/vendor/github.com/spf13/pflag/.gitignore b/vendor/github.com/spf13/pflag/.gitignore deleted file mode 100644 index c3da290..0000000 --- a/vendor/github.com/spf13/pflag/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -.idea/* - diff --git a/vendor/github.com/spf13/pflag/.travis.yml b/vendor/github.com/spf13/pflag/.travis.yml deleted file mode 100644 index f8a63b3..0000000 --- a/vendor/github.com/spf13/pflag/.travis.yml +++ /dev/null @@ -1,21 +0,0 @@ -sudo: false - -language: go - -go: - - 1.7.3 - - 1.8.1 - - tip - -matrix: - allow_failures: - - go: tip - -install: - - go get github.com/golang/lint/golint - - export PATH=$GOPATH/bin:$PATH - - go install ./... - -script: - - verify/all.sh -v - - go test ./... diff --git a/vendor/github.com/spf13/pflag/LICENSE b/vendor/github.com/spf13/pflag/LICENSE deleted file mode 100644 index 63ed1cf..0000000 --- a/vendor/github.com/spf13/pflag/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright (c) 2012 Alex Ogier. All rights reserved. -Copyright (c) 2012 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/spf13/pflag/README.md b/vendor/github.com/spf13/pflag/README.md deleted file mode 100644 index b052414..0000000 --- a/vendor/github.com/spf13/pflag/README.md +++ /dev/null @@ -1,296 +0,0 @@ -[![Build Status](https://travis-ci.org/spf13/pflag.svg?branch=master)](https://travis-ci.org/spf13/pflag) -[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/pflag)](https://goreportcard.com/report/github.com/spf13/pflag) -[![GoDoc](https://godoc.org/github.com/spf13/pflag?status.svg)](https://godoc.org/github.com/spf13/pflag) - -## Description - -pflag is a drop-in replacement for Go's flag package, implementing -POSIX/GNU-style --flags. - -pflag is compatible with the [GNU extensions to the POSIX recommendations -for command-line options][1]. For a more precise description, see the -"Command-line flag syntax" section below. - -[1]: http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html - -pflag is available under the same style of BSD license as the Go language, -which can be found in the LICENSE file. - -## Installation - -pflag is available using the standard `go get` command. - -Install by running: - - go get github.com/spf13/pflag - -Run tests by running: - - go test github.com/spf13/pflag - -## Usage - -pflag is a drop-in replacement of Go's native flag package. If you import -pflag under the name "flag" then all code should continue to function -with no changes. - -``` go -import flag "github.com/spf13/pflag" -``` - -There is one exception to this: if you directly instantiate the Flag struct -there is one more field "Shorthand" that you will need to set. -Most code never instantiates this struct directly, and instead uses -functions such as String(), BoolVar(), and Var(), and is therefore -unaffected. - -Define flags using flag.String(), Bool(), Int(), etc. - -This declares an integer flag, -flagname, stored in the pointer ip, with type *int. - -``` go -var ip *int = flag.Int("flagname", 1234, "help message for flagname") -``` - -If you like, you can bind the flag to a variable using the Var() functions. - -``` go -var flagvar int -func init() { - flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") -} -``` - -Or you can create custom flags that satisfy the Value interface (with -pointer receivers) and couple them to flag parsing by - -``` go -flag.Var(&flagVal, "name", "help message for flagname") -``` - -For such flags, the default value is just the initial value of the variable. - -After all flags are defined, call - -``` go -flag.Parse() -``` - -to parse the command line into the defined flags. - -Flags may then be used directly. If you're using the flags themselves, -they are all pointers; if you bind to variables, they're values. - -``` go -fmt.Println("ip has value ", *ip) -fmt.Println("flagvar has value ", flagvar) -``` - -There are helpers function to get values later if you have the FlagSet but -it was difficult to keep up with all of the flag pointers in your code. -If you have a pflag.FlagSet with a flag called 'flagname' of type int you -can use GetInt() to get the int value. But notice that 'flagname' must exist -and it must be an int. GetString("flagname") will fail. - -``` go -i, err := flagset.GetInt("flagname") -``` - -After parsing, the arguments after the flag are available as the -slice flag.Args() or individually as flag.Arg(i). -The arguments are indexed from 0 through flag.NArg()-1. - -The pflag package also defines some new functions that are not in flag, -that give one-letter shorthands for flags. You can use these by appending -'P' to the name of any function that defines a flag. - -``` go -var ip = flag.IntP("flagname", "f", 1234, "help message") -var flagvar bool -func init() { - flag.BoolVarP(&flagvar, "boolname", "b", true, "help message") -} -flag.VarP(&flagVal, "varname", "v", "help message") -``` - -Shorthand letters can be used with single dashes on the command line. -Boolean shorthand flags can be combined with other shorthand flags. - -The default set of command-line flags is controlled by -top-level functions. The FlagSet type allows one to define -independent sets of flags, such as to implement subcommands -in a command-line interface. The methods of FlagSet are -analogous to the top-level functions for the command-line -flag set. - -## Setting no option default values for flags - -After you create a flag it is possible to set the pflag.NoOptDefVal for -the given flag. Doing this changes the meaning of the flag slightly. If -a flag has a NoOptDefVal and the flag is set on the command line without -an option the flag will be set to the NoOptDefVal. For example given: - -``` go -var ip = flag.IntP("flagname", "f", 1234, "help message") -flag.Lookup("flagname").NoOptDefVal = "4321" -``` - -Would result in something like - -| Parsed Arguments | Resulting Value | -| ------------- | ------------- | -| --flagname=1357 | ip=1357 | -| --flagname | ip=4321 | -| [nothing] | ip=1234 | - -## Command line flag syntax - -``` ---flag // boolean flags, or flags with no option default values ---flag x // only on flags without a default value ---flag=x -``` - -Unlike the flag package, a single dash before an option means something -different than a double dash. Single dashes signify a series of shorthand -letters for flags. All but the last shorthand letter must be boolean flags -or a flag with a default value - -``` -// boolean or flags where the 'no option default value' is set --f --f=true --abc -but --b true is INVALID - -// non-boolean and flags without a 'no option default value' --n 1234 --n=1234 --n1234 - -// mixed --abcs "hello" --absd="hello" --abcs1234 -``` - -Flag parsing stops after the terminator "--". Unlike the flag package, -flags can be interspersed with arguments anywhere on the command line -before this terminator. - -Integer flags accept 1234, 0664, 0x1234 and may be negative. -Boolean flags (in their long form) accept 1, 0, t, f, true, false, -TRUE, FALSE, True, False. -Duration flags accept any input valid for time.ParseDuration. - -## Mutating or "Normalizing" Flag names - -It is possible to set a custom flag name 'normalization function.' It allows flag names to be mutated both when created in the code and when used on the command line to some 'normalized' form. The 'normalized' form is used for comparison. Two examples of using the custom normalization func follow. - -**Example #1**: You want -, _, and . in flags to compare the same. aka --my-flag == --my_flag == --my.flag - -``` go -func wordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName { - from := []string{"-", "_"} - to := "." - for _, sep := range from { - name = strings.Replace(name, sep, to, -1) - } - return pflag.NormalizedName(name) -} - -myFlagSet.SetNormalizeFunc(wordSepNormalizeFunc) -``` - -**Example #2**: You want to alias two flags. aka --old-flag-name == --new-flag-name - -``` go -func aliasNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName { - switch name { - case "old-flag-name": - name = "new-flag-name" - break - } - return pflag.NormalizedName(name) -} - -myFlagSet.SetNormalizeFunc(aliasNormalizeFunc) -``` - -## Deprecating a flag or its shorthand -It is possible to deprecate a flag, or just its shorthand. Deprecating a flag/shorthand hides it from help text and prints a usage message when the deprecated flag/shorthand is used. - -**Example #1**: You want to deprecate a flag named "badflag" as well as inform the users what flag they should use instead. -```go -// deprecate a flag by specifying its name and a usage message -flags.MarkDeprecated("badflag", "please use --good-flag instead") -``` -This hides "badflag" from help text, and prints `Flag --badflag has been deprecated, please use --good-flag instead` when "badflag" is used. - -**Example #2**: You want to keep a flag name "noshorthandflag" but deprecate its shortname "n". -```go -// deprecate a flag shorthand by specifying its flag name and a usage message -flags.MarkShorthandDeprecated("noshorthandflag", "please use --noshorthandflag only") -``` -This hides the shortname "n" from help text, and prints `Flag shorthand -n has been deprecated, please use --noshorthandflag only` when the shorthand "n" is used. - -Note that usage message is essential here, and it should not be empty. - -## Hidden flags -It is possible to mark a flag as hidden, meaning it will still function as normal, however will not show up in usage/help text. - -**Example**: You have a flag named "secretFlag" that you need for internal use only and don't want it showing up in help text, or for its usage text to be available. -```go -// hide a flag by specifying its name -flags.MarkHidden("secretFlag") -``` - -## Disable sorting of flags -`pflag` allows you to disable sorting of flags for help and usage message. - -**Example**: -```go -flags.BoolP("verbose", "v", false, "verbose output") -flags.String("coolflag", "yeaah", "it's really cool flag") -flags.Int("usefulflag", 777, "sometimes it's very useful") -flags.SortFlags = false -flags.PrintDefaults() -``` -**Output**: -``` - -v, --verbose verbose output - --coolflag string it's really cool flag (default "yeaah") - --usefulflag int sometimes it's very useful (default 777) -``` - - -## Supporting Go flags when using pflag -In order to support flags defined using Go's `flag` package, they must be added to the `pflag` flagset. This is usually necessary -to support flags defined by third-party dependencies (e.g. `golang/glog`). - -**Example**: You want to add the Go flags to the `CommandLine` flagset -```go -import ( - goflag "flag" - flag "github.com/spf13/pflag" -) - -var ip *int = flag.Int("flagname", 1234, "help message for flagname") - -func main() { - flag.CommandLine.AddGoFlagSet(goflag.CommandLine) - flag.Parse() -} -``` - -## More info - -You can see the full reference documentation of the pflag package -[at godoc.org][3], or through go's standard documentation system by -running `godoc -http=:6060` and browsing to -[http://localhost:6060/pkg/github.com/spf13/pflag][2] after -installation. - -[2]: http://localhost:6060/pkg/github.com/spf13/pflag -[3]: http://godoc.org/github.com/spf13/pflag diff --git a/vendor/github.com/spf13/pflag/bool.go b/vendor/github.com/spf13/pflag/bool.go deleted file mode 100644 index c4c5c0b..0000000 --- a/vendor/github.com/spf13/pflag/bool.go +++ /dev/null @@ -1,94 +0,0 @@ -package pflag - -import "strconv" - -// optional interface to indicate boolean flags that can be -// supplied without "=value" text -type boolFlag interface { - Value - IsBoolFlag() bool -} - -// -- bool Value -type boolValue bool - -func newBoolValue(val bool, p *bool) *boolValue { - *p = val - return (*boolValue)(p) -} - -func (b *boolValue) Set(s string) error { - v, err := strconv.ParseBool(s) - *b = boolValue(v) - return err -} - -func (b *boolValue) Type() string { - return "bool" -} - -func (b *boolValue) String() string { return strconv.FormatBool(bool(*b)) } - -func (b *boolValue) IsBoolFlag() bool { return true } - -func boolConv(sval string) (interface{}, error) { - return strconv.ParseBool(sval) -} - -// GetBool return the bool value of a flag with the given name -func (f *FlagSet) GetBool(name string) (bool, error) { - val, err := f.getFlagType(name, "bool", boolConv) - if err != nil { - return false, err - } - return val.(bool), nil -} - -// BoolVar defines a bool flag with specified name, default value, and usage string. -// The argument p points to a bool variable in which to store the value of the flag. -func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) { - f.BoolVarP(p, name, "", value, usage) -} - -// BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) { - flag := f.VarPF(newBoolValue(value, p), name, shorthand, usage) - flag.NoOptDefVal = "true" -} - -// BoolVar defines a bool flag with specified name, default value, and usage string. -// The argument p points to a bool variable in which to store the value of the flag. -func BoolVar(p *bool, name string, value bool, usage string) { - BoolVarP(p, name, "", value, usage) -} - -// BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash. -func BoolVarP(p *bool, name, shorthand string, value bool, usage string) { - flag := CommandLine.VarPF(newBoolValue(value, p), name, shorthand, usage) - flag.NoOptDefVal = "true" -} - -// Bool defines a bool flag with specified name, default value, and usage string. -// The return value is the address of a bool variable that stores the value of the flag. -func (f *FlagSet) Bool(name string, value bool, usage string) *bool { - return f.BoolP(name, "", value, usage) -} - -// BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool { - p := new(bool) - f.BoolVarP(p, name, shorthand, value, usage) - return p -} - -// Bool defines a bool flag with specified name, default value, and usage string. -// The return value is the address of a bool variable that stores the value of the flag. -func Bool(name string, value bool, usage string) *bool { - return BoolP(name, "", value, usage) -} - -// BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash. -func BoolP(name, shorthand string, value bool, usage string) *bool { - b := CommandLine.BoolP(name, shorthand, value, usage) - return b -} diff --git a/vendor/github.com/spf13/pflag/bool_slice.go b/vendor/github.com/spf13/pflag/bool_slice.go deleted file mode 100644 index 5af02f1..0000000 --- a/vendor/github.com/spf13/pflag/bool_slice.go +++ /dev/null @@ -1,147 +0,0 @@ -package pflag - -import ( - "io" - "strconv" - "strings" -) - -// -- boolSlice Value -type boolSliceValue struct { - value *[]bool - changed bool -} - -func newBoolSliceValue(val []bool, p *[]bool) *boolSliceValue { - bsv := new(boolSliceValue) - bsv.value = p - *bsv.value = val - return bsv -} - -// Set converts, and assigns, the comma-separated boolean argument string representation as the []bool value of this flag. -// If Set is called on a flag that already has a []bool assigned, the newly converted values will be appended. -func (s *boolSliceValue) Set(val string) error { - - // remove all quote characters - rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "") - - // read flag arguments with CSV parser - boolStrSlice, err := readAsCSV(rmQuote.Replace(val)) - if err != nil && err != io.EOF { - return err - } - - // parse boolean values into slice - out := make([]bool, 0, len(boolStrSlice)) - for _, boolStr := range boolStrSlice { - b, err := strconv.ParseBool(strings.TrimSpace(boolStr)) - if err != nil { - return err - } - out = append(out, b) - } - - if !s.changed { - *s.value = out - } else { - *s.value = append(*s.value, out...) - } - - s.changed = true - - return nil -} - -// Type returns a string that uniquely represents this flag's type. -func (s *boolSliceValue) Type() string { - return "boolSlice" -} - -// String defines a "native" format for this boolean slice flag value. -func (s *boolSliceValue) String() string { - - boolStrSlice := make([]string, len(*s.value)) - for i, b := range *s.value { - boolStrSlice[i] = strconv.FormatBool(b) - } - - out, _ := writeAsCSV(boolStrSlice) - - return "[" + out + "]" -} - -func boolSliceConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // Empty string would cause a slice with one (empty) entry - if len(val) == 0 { - return []bool{}, nil - } - ss := strings.Split(val, ",") - out := make([]bool, len(ss)) - for i, t := range ss { - var err error - out[i], err = strconv.ParseBool(t) - if err != nil { - return nil, err - } - } - return out, nil -} - -// GetBoolSlice returns the []bool value of a flag with the given name. -func (f *FlagSet) GetBoolSlice(name string) ([]bool, error) { - val, err := f.getFlagType(name, "boolSlice", boolSliceConv) - if err != nil { - return []bool{}, err - } - return val.([]bool), nil -} - -// BoolSliceVar defines a boolSlice flag with specified name, default value, and usage string. -// The argument p points to a []bool variable in which to store the value of the flag. -func (f *FlagSet) BoolSliceVar(p *[]bool, name string, value []bool, usage string) { - f.VarP(newBoolSliceValue(value, p), name, "", usage) -} - -// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) { - f.VarP(newBoolSliceValue(value, p), name, shorthand, usage) -} - -// BoolSliceVar defines a []bool flag with specified name, default value, and usage string. -// The argument p points to a []bool variable in which to store the value of the flag. -func BoolSliceVar(p *[]bool, name string, value []bool, usage string) { - CommandLine.VarP(newBoolSliceValue(value, p), name, "", usage) -} - -// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash. -func BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) { - CommandLine.VarP(newBoolSliceValue(value, p), name, shorthand, usage) -} - -// BoolSlice defines a []bool flag with specified name, default value, and usage string. -// The return value is the address of a []bool variable that stores the value of the flag. -func (f *FlagSet) BoolSlice(name string, value []bool, usage string) *[]bool { - p := []bool{} - f.BoolSliceVarP(&p, name, "", value, usage) - return &p -} - -// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool { - p := []bool{} - f.BoolSliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// BoolSlice defines a []bool flag with specified name, default value, and usage string. -// The return value is the address of a []bool variable that stores the value of the flag. -func BoolSlice(name string, value []bool, usage string) *[]bool { - return CommandLine.BoolSliceP(name, "", value, usage) -} - -// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash. -func BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool { - return CommandLine.BoolSliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/bytes.go b/vendor/github.com/spf13/pflag/bytes.go deleted file mode 100644 index 67d5304..0000000 --- a/vendor/github.com/spf13/pflag/bytes.go +++ /dev/null @@ -1,209 +0,0 @@ -package pflag - -import ( - "encoding/base64" - "encoding/hex" - "fmt" - "strings" -) - -// BytesHex adapts []byte for use as a flag. Value of flag is HEX encoded -type bytesHexValue []byte - -// String implements pflag.Value.String. -func (bytesHex bytesHexValue) String() string { - return fmt.Sprintf("%X", []byte(bytesHex)) -} - -// Set implements pflag.Value.Set. -func (bytesHex *bytesHexValue) Set(value string) error { - bin, err := hex.DecodeString(strings.TrimSpace(value)) - - if err != nil { - return err - } - - *bytesHex = bin - - return nil -} - -// Type implements pflag.Value.Type. -func (*bytesHexValue) Type() string { - return "bytesHex" -} - -func newBytesHexValue(val []byte, p *[]byte) *bytesHexValue { - *p = val - return (*bytesHexValue)(p) -} - -func bytesHexConv(sval string) (interface{}, error) { - - bin, err := hex.DecodeString(sval) - - if err == nil { - return bin, nil - } - - return nil, fmt.Errorf("invalid string being converted to Bytes: %s %s", sval, err) -} - -// GetBytesHex return the []byte value of a flag with the given name -func (f *FlagSet) GetBytesHex(name string) ([]byte, error) { - val, err := f.getFlagType(name, "bytesHex", bytesHexConv) - - if err != nil { - return []byte{}, err - } - - return val.([]byte), nil -} - -// BytesHexVar defines an []byte flag with specified name, default value, and usage string. -// The argument p points to an []byte variable in which to store the value of the flag. -func (f *FlagSet) BytesHexVar(p *[]byte, name string, value []byte, usage string) { - f.VarP(newBytesHexValue(value, p), name, "", usage) -} - -// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) { - f.VarP(newBytesHexValue(value, p), name, shorthand, usage) -} - -// BytesHexVar defines an []byte flag with specified name, default value, and usage string. -// The argument p points to an []byte variable in which to store the value of the flag. -func BytesHexVar(p *[]byte, name string, value []byte, usage string) { - CommandLine.VarP(newBytesHexValue(value, p), name, "", usage) -} - -// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash. -func BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) { - CommandLine.VarP(newBytesHexValue(value, p), name, shorthand, usage) -} - -// BytesHex defines an []byte flag with specified name, default value, and usage string. -// The return value is the address of an []byte variable that stores the value of the flag. -func (f *FlagSet) BytesHex(name string, value []byte, usage string) *[]byte { - p := new([]byte) - f.BytesHexVarP(p, name, "", value, usage) - return p -} - -// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BytesHexP(name, shorthand string, value []byte, usage string) *[]byte { - p := new([]byte) - f.BytesHexVarP(p, name, shorthand, value, usage) - return p -} - -// BytesHex defines an []byte flag with specified name, default value, and usage string. -// The return value is the address of an []byte variable that stores the value of the flag. -func BytesHex(name string, value []byte, usage string) *[]byte { - return CommandLine.BytesHexP(name, "", value, usage) -} - -// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash. -func BytesHexP(name, shorthand string, value []byte, usage string) *[]byte { - return CommandLine.BytesHexP(name, shorthand, value, usage) -} - -// BytesBase64 adapts []byte for use as a flag. Value of flag is Base64 encoded -type bytesBase64Value []byte - -// String implements pflag.Value.String. -func (bytesBase64 bytesBase64Value) String() string { - return base64.StdEncoding.EncodeToString([]byte(bytesBase64)) -} - -// Set implements pflag.Value.Set. -func (bytesBase64 *bytesBase64Value) Set(value string) error { - bin, err := base64.StdEncoding.DecodeString(strings.TrimSpace(value)) - - if err != nil { - return err - } - - *bytesBase64 = bin - - return nil -} - -// Type implements pflag.Value.Type. -func (*bytesBase64Value) Type() string { - return "bytesBase64" -} - -func newBytesBase64Value(val []byte, p *[]byte) *bytesBase64Value { - *p = val - return (*bytesBase64Value)(p) -} - -func bytesBase64ValueConv(sval string) (interface{}, error) { - - bin, err := base64.StdEncoding.DecodeString(sval) - if err == nil { - return bin, nil - } - - return nil, fmt.Errorf("invalid string being converted to Bytes: %s %s", sval, err) -} - -// GetBytesBase64 return the []byte value of a flag with the given name -func (f *FlagSet) GetBytesBase64(name string) ([]byte, error) { - val, err := f.getFlagType(name, "bytesBase64", bytesBase64ValueConv) - - if err != nil { - return []byte{}, err - } - - return val.([]byte), nil -} - -// BytesBase64Var defines an []byte flag with specified name, default value, and usage string. -// The argument p points to an []byte variable in which to store the value of the flag. -func (f *FlagSet) BytesBase64Var(p *[]byte, name string, value []byte, usage string) { - f.VarP(newBytesBase64Value(value, p), name, "", usage) -} - -// BytesBase64VarP is like BytesBase64Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BytesBase64VarP(p *[]byte, name, shorthand string, value []byte, usage string) { - f.VarP(newBytesBase64Value(value, p), name, shorthand, usage) -} - -// BytesBase64Var defines an []byte flag with specified name, default value, and usage string. -// The argument p points to an []byte variable in which to store the value of the flag. -func BytesBase64Var(p *[]byte, name string, value []byte, usage string) { - CommandLine.VarP(newBytesBase64Value(value, p), name, "", usage) -} - -// BytesBase64VarP is like BytesBase64Var, but accepts a shorthand letter that can be used after a single dash. -func BytesBase64VarP(p *[]byte, name, shorthand string, value []byte, usage string) { - CommandLine.VarP(newBytesBase64Value(value, p), name, shorthand, usage) -} - -// BytesBase64 defines an []byte flag with specified name, default value, and usage string. -// The return value is the address of an []byte variable that stores the value of the flag. -func (f *FlagSet) BytesBase64(name string, value []byte, usage string) *[]byte { - p := new([]byte) - f.BytesBase64VarP(p, name, "", value, usage) - return p -} - -// BytesBase64P is like BytesBase64, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BytesBase64P(name, shorthand string, value []byte, usage string) *[]byte { - p := new([]byte) - f.BytesBase64VarP(p, name, shorthand, value, usage) - return p -} - -// BytesBase64 defines an []byte flag with specified name, default value, and usage string. -// The return value is the address of an []byte variable that stores the value of the flag. -func BytesBase64(name string, value []byte, usage string) *[]byte { - return CommandLine.BytesBase64P(name, "", value, usage) -} - -// BytesBase64P is like BytesBase64, but accepts a shorthand letter that can be used after a single dash. -func BytesBase64P(name, shorthand string, value []byte, usage string) *[]byte { - return CommandLine.BytesBase64P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/count.go b/vendor/github.com/spf13/pflag/count.go deleted file mode 100644 index aa126e4..0000000 --- a/vendor/github.com/spf13/pflag/count.go +++ /dev/null @@ -1,96 +0,0 @@ -package pflag - -import "strconv" - -// -- count Value -type countValue int - -func newCountValue(val int, p *int) *countValue { - *p = val - return (*countValue)(p) -} - -func (i *countValue) Set(s string) error { - // "+1" means that no specific value was passed, so increment - if s == "+1" { - *i = countValue(*i + 1) - return nil - } - v, err := strconv.ParseInt(s, 0, 0) - *i = countValue(v) - return err -} - -func (i *countValue) Type() string { - return "count" -} - -func (i *countValue) String() string { return strconv.Itoa(int(*i)) } - -func countConv(sval string) (interface{}, error) { - i, err := strconv.Atoi(sval) - if err != nil { - return nil, err - } - return i, nil -} - -// GetCount return the int value of a flag with the given name -func (f *FlagSet) GetCount(name string) (int, error) { - val, err := f.getFlagType(name, "count", countConv) - if err != nil { - return 0, err - } - return val.(int), nil -} - -// CountVar defines a count flag with specified name, default value, and usage string. -// The argument p points to an int variable in which to store the value of the flag. -// A count flag will add 1 to its value evey time it is found on the command line -func (f *FlagSet) CountVar(p *int, name string, usage string) { - f.CountVarP(p, name, "", usage) -} - -// CountVarP is like CountVar only take a shorthand for the flag name. -func (f *FlagSet) CountVarP(p *int, name, shorthand string, usage string) { - flag := f.VarPF(newCountValue(0, p), name, shorthand, usage) - flag.NoOptDefVal = "+1" -} - -// CountVar like CountVar only the flag is placed on the CommandLine instead of a given flag set -func CountVar(p *int, name string, usage string) { - CommandLine.CountVar(p, name, usage) -} - -// CountVarP is like CountVar only take a shorthand for the flag name. -func CountVarP(p *int, name, shorthand string, usage string) { - CommandLine.CountVarP(p, name, shorthand, usage) -} - -// Count defines a count flag with specified name, default value, and usage string. -// The return value is the address of an int variable that stores the value of the flag. -// A count flag will add 1 to its value evey time it is found on the command line -func (f *FlagSet) Count(name string, usage string) *int { - p := new(int) - f.CountVarP(p, name, "", usage) - return p -} - -// CountP is like Count only takes a shorthand for the flag name. -func (f *FlagSet) CountP(name, shorthand string, usage string) *int { - p := new(int) - f.CountVarP(p, name, shorthand, usage) - return p -} - -// Count defines a count flag with specified name, default value, and usage string. -// The return value is the address of an int variable that stores the value of the flag. -// A count flag will add 1 to its value evey time it is found on the command line -func Count(name string, usage string) *int { - return CommandLine.CountP(name, "", usage) -} - -// CountP is like Count only takes a shorthand for the flag name. -func CountP(name, shorthand string, usage string) *int { - return CommandLine.CountP(name, shorthand, usage) -} diff --git a/vendor/github.com/spf13/pflag/duration.go b/vendor/github.com/spf13/pflag/duration.go deleted file mode 100644 index e9debef..0000000 --- a/vendor/github.com/spf13/pflag/duration.go +++ /dev/null @@ -1,86 +0,0 @@ -package pflag - -import ( - "time" -) - -// -- time.Duration Value -type durationValue time.Duration - -func newDurationValue(val time.Duration, p *time.Duration) *durationValue { - *p = val - return (*durationValue)(p) -} - -func (d *durationValue) Set(s string) error { - v, err := time.ParseDuration(s) - *d = durationValue(v) - return err -} - -func (d *durationValue) Type() string { - return "duration" -} - -func (d *durationValue) String() string { return (*time.Duration)(d).String() } - -func durationConv(sval string) (interface{}, error) { - return time.ParseDuration(sval) -} - -// GetDuration return the duration value of a flag with the given name -func (f *FlagSet) GetDuration(name string) (time.Duration, error) { - val, err := f.getFlagType(name, "duration", durationConv) - if err != nil { - return 0, err - } - return val.(time.Duration), nil -} - -// DurationVar defines a time.Duration flag with specified name, default value, and usage string. -// The argument p points to a time.Duration variable in which to store the value of the flag. -func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) { - f.VarP(newDurationValue(value, p), name, "", usage) -} - -// DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) { - f.VarP(newDurationValue(value, p), name, shorthand, usage) -} - -// DurationVar defines a time.Duration flag with specified name, default value, and usage string. -// The argument p points to a time.Duration variable in which to store the value of the flag. -func DurationVar(p *time.Duration, name string, value time.Duration, usage string) { - CommandLine.VarP(newDurationValue(value, p), name, "", usage) -} - -// DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash. -func DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) { - CommandLine.VarP(newDurationValue(value, p), name, shorthand, usage) -} - -// Duration defines a time.Duration flag with specified name, default value, and usage string. -// The return value is the address of a time.Duration variable that stores the value of the flag. -func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration { - p := new(time.Duration) - f.DurationVarP(p, name, "", value, usage) - return p -} - -// DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration { - p := new(time.Duration) - f.DurationVarP(p, name, shorthand, value, usage) - return p -} - -// Duration defines a time.Duration flag with specified name, default value, and usage string. -// The return value is the address of a time.Duration variable that stores the value of the flag. -func Duration(name string, value time.Duration, usage string) *time.Duration { - return CommandLine.DurationP(name, "", value, usage) -} - -// DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash. -func DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration { - return CommandLine.DurationP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/duration_slice.go b/vendor/github.com/spf13/pflag/duration_slice.go deleted file mode 100644 index 52c6b6d..0000000 --- a/vendor/github.com/spf13/pflag/duration_slice.go +++ /dev/null @@ -1,128 +0,0 @@ -package pflag - -import ( - "fmt" - "strings" - "time" -) - -// -- durationSlice Value -type durationSliceValue struct { - value *[]time.Duration - changed bool -} - -func newDurationSliceValue(val []time.Duration, p *[]time.Duration) *durationSliceValue { - dsv := new(durationSliceValue) - dsv.value = p - *dsv.value = val - return dsv -} - -func (s *durationSliceValue) Set(val string) error { - ss := strings.Split(val, ",") - out := make([]time.Duration, len(ss)) - for i, d := range ss { - var err error - out[i], err = time.ParseDuration(d) - if err != nil { - return err - } - - } - if !s.changed { - *s.value = out - } else { - *s.value = append(*s.value, out...) - } - s.changed = true - return nil -} - -func (s *durationSliceValue) Type() string { - return "durationSlice" -} - -func (s *durationSliceValue) String() string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = fmt.Sprintf("%s", d) - } - return "[" + strings.Join(out, ",") + "]" -} - -func durationSliceConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // Empty string would cause a slice with one (empty) entry - if len(val) == 0 { - return []time.Duration{}, nil - } - ss := strings.Split(val, ",") - out := make([]time.Duration, len(ss)) - for i, d := range ss { - var err error - out[i], err = time.ParseDuration(d) - if err != nil { - return nil, err - } - - } - return out, nil -} - -// GetDurationSlice returns the []time.Duration value of a flag with the given name -func (f *FlagSet) GetDurationSlice(name string) ([]time.Duration, error) { - val, err := f.getFlagType(name, "durationSlice", durationSliceConv) - if err != nil { - return []time.Duration{}, err - } - return val.([]time.Duration), nil -} - -// DurationSliceVar defines a durationSlice flag with specified name, default value, and usage string. -// The argument p points to a []time.Duration variable in which to store the value of the flag. -func (f *FlagSet) DurationSliceVar(p *[]time.Duration, name string, value []time.Duration, usage string) { - f.VarP(newDurationSliceValue(value, p), name, "", usage) -} - -// DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) DurationSliceVarP(p *[]time.Duration, name, shorthand string, value []time.Duration, usage string) { - f.VarP(newDurationSliceValue(value, p), name, shorthand, usage) -} - -// DurationSliceVar defines a duration[] flag with specified name, default value, and usage string. -// The argument p points to a duration[] variable in which to store the value of the flag. -func DurationSliceVar(p *[]time.Duration, name string, value []time.Duration, usage string) { - CommandLine.VarP(newDurationSliceValue(value, p), name, "", usage) -} - -// DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash. -func DurationSliceVarP(p *[]time.Duration, name, shorthand string, value []time.Duration, usage string) { - CommandLine.VarP(newDurationSliceValue(value, p), name, shorthand, usage) -} - -// DurationSlice defines a []time.Duration flag with specified name, default value, and usage string. -// The return value is the address of a []time.Duration variable that stores the value of the flag. -func (f *FlagSet) DurationSlice(name string, value []time.Duration, usage string) *[]time.Duration { - p := []time.Duration{} - f.DurationSliceVarP(&p, name, "", value, usage) - return &p -} - -// DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) DurationSliceP(name, shorthand string, value []time.Duration, usage string) *[]time.Duration { - p := []time.Duration{} - f.DurationSliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// DurationSlice defines a []time.Duration flag with specified name, default value, and usage string. -// The return value is the address of a []time.Duration variable that stores the value of the flag. -func DurationSlice(name string, value []time.Duration, usage string) *[]time.Duration { - return CommandLine.DurationSliceP(name, "", value, usage) -} - -// DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash. -func DurationSliceP(name, shorthand string, value []time.Duration, usage string) *[]time.Duration { - return CommandLine.DurationSliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/flag.go b/vendor/github.com/spf13/pflag/flag.go deleted file mode 100644 index 5cc710c..0000000 --- a/vendor/github.com/spf13/pflag/flag.go +++ /dev/null @@ -1,1224 +0,0 @@ -// 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. - -/* -Package pflag is a drop-in replacement for Go's flag package, implementing -POSIX/GNU-style --flags. - -pflag is compatible with the GNU extensions to the POSIX recommendations -for command-line options. See -http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html - -Usage: - -pflag is a drop-in replacement of Go's native flag package. If you import -pflag under the name "flag" then all code should continue to function -with no changes. - - import flag "github.com/spf13/pflag" - -There is one exception to this: if you directly instantiate the Flag struct -there is one more field "Shorthand" that you will need to set. -Most code never instantiates this struct directly, and instead uses -functions such as String(), BoolVar(), and Var(), and is therefore -unaffected. - -Define flags using flag.String(), Bool(), Int(), etc. - -This declares an integer flag, -flagname, stored in the pointer ip, with type *int. - var ip = flag.Int("flagname", 1234, "help message for flagname") -If you like, you can bind the flag to a variable using the Var() functions. - var flagvar int - func init() { - flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") - } -Or you can create custom flags that satisfy the Value interface (with -pointer receivers) and couple them to flag parsing by - flag.Var(&flagVal, "name", "help message for flagname") -For such flags, the default value is just the initial value of the variable. - -After all flags are defined, call - flag.Parse() -to parse the command line into the defined flags. - -Flags may then be used directly. If you're using the flags themselves, -they are all pointers; if you bind to variables, they're values. - fmt.Println("ip has value ", *ip) - fmt.Println("flagvar has value ", flagvar) - -After parsing, the arguments after the flag are available as the -slice flag.Args() or individually as flag.Arg(i). -The arguments are indexed from 0 through flag.NArg()-1. - -The pflag package also defines some new functions that are not in flag, -that give one-letter shorthands for flags. You can use these by appending -'P' to the name of any function that defines a flag. - var ip = flag.IntP("flagname", "f", 1234, "help message") - var flagvar bool - func init() { - flag.BoolVarP("boolname", "b", true, "help message") - } - flag.VarP(&flagVar, "varname", "v", 1234, "help message") -Shorthand letters can be used with single dashes on the command line. -Boolean shorthand flags can be combined with other shorthand flags. - -Command line flag syntax: - --flag // boolean flags only - --flag=x - -Unlike the flag package, a single dash before an option means something -different than a double dash. Single dashes signify a series of shorthand -letters for flags. All but the last shorthand letter must be boolean flags. - // boolean flags - -f - -abc - // non-boolean flags - -n 1234 - -Ifile - // mixed - -abcs "hello" - -abcn1234 - -Flag parsing stops after the terminator "--". Unlike the flag package, -flags can be interspersed with arguments anywhere on the command line -before this terminator. - -Integer flags accept 1234, 0664, 0x1234 and may be negative. -Boolean flags (in their long form) accept 1, 0, t, f, true, false, -TRUE, FALSE, True, False. -Duration flags accept any input valid for time.ParseDuration. - -The default set of command-line flags is controlled by -top-level functions. The FlagSet type allows one to define -independent sets of flags, such as to implement subcommands -in a command-line interface. The methods of FlagSet are -analogous to the top-level functions for the command-line -flag set. -*/ -package pflag - -import ( - "bytes" - "errors" - goflag "flag" - "fmt" - "io" - "os" - "sort" - "strings" -) - -// ErrHelp is the error returned if the flag -help is invoked but no such flag is defined. -var ErrHelp = errors.New("pflag: help requested") - -// ErrorHandling defines how to handle flag parsing errors. -type ErrorHandling int - -const ( - // ContinueOnError will return an err from Parse() if an error is found - ContinueOnError ErrorHandling = iota - // ExitOnError will call os.Exit(2) if an error is found when parsing - ExitOnError - // PanicOnError will panic() if an error is found when parsing flags - PanicOnError -) - -// ParseErrorsWhitelist defines the parsing errors that can be ignored -type ParseErrorsWhitelist struct { - // UnknownFlags will ignore unknown flags errors and continue parsing rest of the flags - UnknownFlags bool -} - -// NormalizedName is a flag name that has been normalized according to rules -// for the FlagSet (e.g. making '-' and '_' equivalent). -type NormalizedName string - -// A FlagSet represents a set of defined flags. -type FlagSet struct { - // Usage is the function called when an error occurs while parsing flags. - // The field is a function (not a method) that may be changed to point to - // a custom error handler. - Usage func() - - // SortFlags is used to indicate, if user wants to have sorted flags in - // help/usage messages. - SortFlags bool - - // ParseErrorsWhitelist is used to configure a whitelist of errors - ParseErrorsWhitelist ParseErrorsWhitelist - - name string - parsed bool - actual map[NormalizedName]*Flag - orderedActual []*Flag - sortedActual []*Flag - formal map[NormalizedName]*Flag - orderedFormal []*Flag - sortedFormal []*Flag - shorthands map[byte]*Flag - args []string // arguments after flags - argsLenAtDash int // len(args) when a '--' was located when parsing, or -1 if no -- - errorHandling ErrorHandling - output io.Writer // nil means stderr; use out() accessor - interspersed bool // allow interspersed option/non-option args - normalizeNameFunc func(f *FlagSet, name string) NormalizedName - - addedGoFlagSets []*goflag.FlagSet -} - -// A Flag represents the state of a flag. -type Flag struct { - Name string // name as it appears on command line - Shorthand string // one-letter abbreviated flag - Usage string // help message - Value Value // value as set - DefValue string // default value (as text); for usage message - Changed bool // If the user set the value (or if left to default) - NoOptDefVal string // default value (as text); if the flag is on the command line without any options - Deprecated string // If this flag is deprecated, this string is the new or now thing to use - Hidden bool // used by cobra.Command to allow flags to be hidden from help/usage text - ShorthandDeprecated string // If the shorthand of this flag is deprecated, this string is the new or now thing to use - Annotations map[string][]string // used by cobra.Command bash autocomple code -} - -// Value is the interface to the dynamic value stored in a flag. -// (The default value is represented as a string.) -type Value interface { - String() string - Set(string) error - Type() string -} - -// sortFlags returns the flags as a slice in lexicographical sorted order. -func sortFlags(flags map[NormalizedName]*Flag) []*Flag { - list := make(sort.StringSlice, len(flags)) - i := 0 - for k := range flags { - list[i] = string(k) - i++ - } - list.Sort() - result := make([]*Flag, len(list)) - for i, name := range list { - result[i] = flags[NormalizedName(name)] - } - return result -} - -// SetNormalizeFunc allows you to add a function which can translate flag names. -// Flags added to the FlagSet will be translated and then when anything tries to -// look up the flag that will also be translated. So it would be possible to create -// a flag named "getURL" and have it translated to "geturl". A user could then pass -// "--getUrl" which may also be translated to "geturl" and everything will work. -func (f *FlagSet) SetNormalizeFunc(n func(f *FlagSet, name string) NormalizedName) { - f.normalizeNameFunc = n - f.sortedFormal = f.sortedFormal[:0] - for fname, flag := range f.formal { - nname := f.normalizeFlagName(flag.Name) - if fname == nname { - continue - } - flag.Name = string(nname) - delete(f.formal, fname) - f.formal[nname] = flag - if _, set := f.actual[fname]; set { - delete(f.actual, fname) - f.actual[nname] = flag - } - } -} - -// GetNormalizeFunc returns the previously set NormalizeFunc of a function which -// does no translation, if not set previously. -func (f *FlagSet) GetNormalizeFunc() func(f *FlagSet, name string) NormalizedName { - if f.normalizeNameFunc != nil { - return f.normalizeNameFunc - } - return func(f *FlagSet, name string) NormalizedName { return NormalizedName(name) } -} - -func (f *FlagSet) normalizeFlagName(name string) NormalizedName { - n := f.GetNormalizeFunc() - return n(f, name) -} - -func (f *FlagSet) out() io.Writer { - if f.output == nil { - return os.Stderr - } - return f.output -} - -// SetOutput sets the destination for usage and error messages. -// If output is nil, os.Stderr is used. -func (f *FlagSet) SetOutput(output io.Writer) { - f.output = output -} - -// VisitAll visits the flags in lexicographical order or -// in primordial order if f.SortFlags is false, calling fn for each. -// It visits all flags, even those not set. -func (f *FlagSet) VisitAll(fn func(*Flag)) { - if len(f.formal) == 0 { - return - } - - var flags []*Flag - if f.SortFlags { - if len(f.formal) != len(f.sortedFormal) { - f.sortedFormal = sortFlags(f.formal) - } - flags = f.sortedFormal - } else { - flags = f.orderedFormal - } - - for _, flag := range flags { - fn(flag) - } -} - -// HasFlags returns a bool to indicate if the FlagSet has any flags defined. -func (f *FlagSet) HasFlags() bool { - return len(f.formal) > 0 -} - -// HasAvailableFlags returns a bool to indicate if the FlagSet has any flags -// that are not hidden. -func (f *FlagSet) HasAvailableFlags() bool { - for _, flag := range f.formal { - if !flag.Hidden { - return true - } - } - return false -} - -// VisitAll visits the command-line flags in lexicographical order or -// in primordial order if f.SortFlags is false, calling fn for each. -// It visits all flags, even those not set. -func VisitAll(fn func(*Flag)) { - CommandLine.VisitAll(fn) -} - -// Visit visits the flags in lexicographical order or -// in primordial order if f.SortFlags is false, calling fn for each. -// It visits only those flags that have been set. -func (f *FlagSet) Visit(fn func(*Flag)) { - if len(f.actual) == 0 { - return - } - - var flags []*Flag - if f.SortFlags { - if len(f.actual) != len(f.sortedActual) { - f.sortedActual = sortFlags(f.actual) - } - flags = f.sortedActual - } else { - flags = f.orderedActual - } - - for _, flag := range flags { - fn(flag) - } -} - -// Visit visits the command-line flags in lexicographical order or -// in primordial order if f.SortFlags is false, calling fn for each. -// It visits only those flags that have been set. -func Visit(fn func(*Flag)) { - CommandLine.Visit(fn) -} - -// Lookup returns the Flag structure of the named flag, returning nil if none exists. -func (f *FlagSet) Lookup(name string) *Flag { - return f.lookup(f.normalizeFlagName(name)) -} - -// ShorthandLookup returns the Flag structure of the short handed flag, -// returning nil if none exists. -// It panics, if len(name) > 1. -func (f *FlagSet) ShorthandLookup(name string) *Flag { - if name == "" { - return nil - } - if len(name) > 1 { - msg := fmt.Sprintf("can not look up shorthand which is more than one ASCII character: %q", name) - fmt.Fprintf(f.out(), msg) - panic(msg) - } - c := name[0] - return f.shorthands[c] -} - -// lookup returns the Flag structure of the named flag, returning nil if none exists. -func (f *FlagSet) lookup(name NormalizedName) *Flag { - return f.formal[name] -} - -// func to return a given type for a given flag name -func (f *FlagSet) getFlagType(name string, ftype string, convFunc func(sval string) (interface{}, error)) (interface{}, error) { - flag := f.Lookup(name) - if flag == nil { - err := fmt.Errorf("flag accessed but not defined: %s", name) - return nil, err - } - - if flag.Value.Type() != ftype { - err := fmt.Errorf("trying to get %s value of flag of type %s", ftype, flag.Value.Type()) - return nil, err - } - - sval := flag.Value.String() - result, err := convFunc(sval) - if err != nil { - return nil, err - } - return result, nil -} - -// ArgsLenAtDash will return the length of f.Args at the moment when a -- was -// found during arg parsing. This allows your program to know which args were -// before the -- and which came after. -func (f *FlagSet) ArgsLenAtDash() int { - return f.argsLenAtDash -} - -// MarkDeprecated indicated that a flag is deprecated in your program. It will -// continue to function but will not show up in help or usage messages. Using -// this flag will also print the given usageMessage. -func (f *FlagSet) MarkDeprecated(name string, usageMessage string) error { - flag := f.Lookup(name) - if flag == nil { - return fmt.Errorf("flag %q does not exist", name) - } - if usageMessage == "" { - return fmt.Errorf("deprecated message for flag %q must be set", name) - } - flag.Deprecated = usageMessage - flag.Hidden = true - return nil -} - -// MarkShorthandDeprecated will mark the shorthand of a flag deprecated in your -// program. It will continue to function but will not show up in help or usage -// messages. Using this flag will also print the given usageMessage. -func (f *FlagSet) MarkShorthandDeprecated(name string, usageMessage string) error { - flag := f.Lookup(name) - if flag == nil { - return fmt.Errorf("flag %q does not exist", name) - } - if usageMessage == "" { - return fmt.Errorf("deprecated message for flag %q must be set", name) - } - flag.ShorthandDeprecated = usageMessage - return nil -} - -// MarkHidden sets a flag to 'hidden' in your program. It will continue to -// function but will not show up in help or usage messages. -func (f *FlagSet) MarkHidden(name string) error { - flag := f.Lookup(name) - if flag == nil { - return fmt.Errorf("flag %q does not exist", name) - } - flag.Hidden = true - return nil -} - -// Lookup returns the Flag structure of the named command-line flag, -// returning nil if none exists. -func Lookup(name string) *Flag { - return CommandLine.Lookup(name) -} - -// ShorthandLookup returns the Flag structure of the short handed flag, -// returning nil if none exists. -func ShorthandLookup(name string) *Flag { - return CommandLine.ShorthandLookup(name) -} - -// Set sets the value of the named flag. -func (f *FlagSet) Set(name, value string) error { - normalName := f.normalizeFlagName(name) - flag, ok := f.formal[normalName] - if !ok { - return fmt.Errorf("no such flag -%v", name) - } - - err := flag.Value.Set(value) - if err != nil { - var flagName string - if flag.Shorthand != "" && flag.ShorthandDeprecated == "" { - flagName = fmt.Sprintf("-%s, --%s", flag.Shorthand, flag.Name) - } else { - flagName = fmt.Sprintf("--%s", flag.Name) - } - return fmt.Errorf("invalid argument %q for %q flag: %v", value, flagName, err) - } - - if !flag.Changed { - if f.actual == nil { - f.actual = make(map[NormalizedName]*Flag) - } - f.actual[normalName] = flag - f.orderedActual = append(f.orderedActual, flag) - - flag.Changed = true - } - - if flag.Deprecated != "" { - fmt.Fprintf(f.out(), "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated) - } - return nil -} - -// SetAnnotation allows one to set arbitrary annotations on a flag in the FlagSet. -// This is sometimes used by spf13/cobra programs which want to generate additional -// bash completion information. -func (f *FlagSet) SetAnnotation(name, key string, values []string) error { - normalName := f.normalizeFlagName(name) - flag, ok := f.formal[normalName] - if !ok { - return fmt.Errorf("no such flag -%v", name) - } - if flag.Annotations == nil { - flag.Annotations = map[string][]string{} - } - flag.Annotations[key] = values - return nil -} - -// Changed returns true if the flag was explicitly set during Parse() and false -// otherwise -func (f *FlagSet) Changed(name string) bool { - flag := f.Lookup(name) - // If a flag doesn't exist, it wasn't changed.... - if flag == nil { - return false - } - return flag.Changed -} - -// Set sets the value of the named command-line flag. -func Set(name, value string) error { - return CommandLine.Set(name, value) -} - -// PrintDefaults prints, to standard error unless configured -// otherwise, the default values of all defined flags in the set. -func (f *FlagSet) PrintDefaults() { - usages := f.FlagUsages() - fmt.Fprint(f.out(), usages) -} - -// defaultIsZeroValue returns true if the default value for this flag represents -// a zero value. -func (f *Flag) defaultIsZeroValue() bool { - switch f.Value.(type) { - case boolFlag: - return f.DefValue == "false" - case *durationValue: - // Beginning in Go 1.7, duration zero values are "0s" - return f.DefValue == "0" || f.DefValue == "0s" - case *intValue, *int8Value, *int32Value, *int64Value, *uintValue, *uint8Value, *uint16Value, *uint32Value, *uint64Value, *countValue, *float32Value, *float64Value: - return f.DefValue == "0" - case *stringValue: - return f.DefValue == "" - case *ipValue, *ipMaskValue, *ipNetValue: - return f.DefValue == "" - case *intSliceValue, *stringSliceValue, *stringArrayValue: - return f.DefValue == "[]" - default: - switch f.Value.String() { - case "false": - return true - case "": - return true - case "": - return true - case "0": - return true - } - return false - } -} - -// UnquoteUsage extracts a back-quoted name from the usage -// string for a flag and returns it and the un-quoted usage. -// Given "a `name` to show" it returns ("name", "a name to show"). -// If there are no back quotes, the name is an educated guess of the -// type of the flag's value, or the empty string if the flag is boolean. -func UnquoteUsage(flag *Flag) (name string, usage string) { - // Look for a back-quoted name, but avoid the strings package. - usage = flag.Usage - for i := 0; i < len(usage); i++ { - if usage[i] == '`' { - for j := i + 1; j < len(usage); j++ { - if usage[j] == '`' { - name = usage[i+1 : j] - usage = usage[:i] + name + usage[j+1:] - return name, usage - } - } - break // Only one back quote; use type name. - } - } - - name = flag.Value.Type() - switch name { - case "bool": - name = "" - case "float64": - name = "float" - case "int64": - name = "int" - case "uint64": - name = "uint" - case "stringSlice": - name = "strings" - case "intSlice": - name = "ints" - case "uintSlice": - name = "uints" - case "boolSlice": - name = "bools" - } - - return -} - -// Splits the string `s` on whitespace into an initial substring up to -// `i` runes in length and the remainder. Will go `slop` over `i` if -// that encompasses the entire string (which allows the caller to -// avoid short orphan words on the final line). -func wrapN(i, slop int, s string) (string, string) { - if i+slop > len(s) { - return s, "" - } - - w := strings.LastIndexAny(s[:i], " \t\n") - if w <= 0 { - return s, "" - } - nlPos := strings.LastIndex(s[:i], "\n") - if nlPos > 0 && nlPos < w { - return s[:nlPos], s[nlPos+1:] - } - return s[:w], s[w+1:] -} - -// Wraps the string `s` to a maximum width `w` with leading indent -// `i`. The first line is not indented (this is assumed to be done by -// caller). Pass `w` == 0 to do no wrapping -func wrap(i, w int, s string) string { - if w == 0 { - return strings.Replace(s, "\n", "\n"+strings.Repeat(" ", i), -1) - } - - // space between indent i and end of line width w into which - // we should wrap the text. - wrap := w - i - - var r, l string - - // Not enough space for sensible wrapping. Wrap as a block on - // the next line instead. - if wrap < 24 { - i = 16 - wrap = w - i - r += "\n" + strings.Repeat(" ", i) - } - // If still not enough space then don't even try to wrap. - if wrap < 24 { - return strings.Replace(s, "\n", r, -1) - } - - // Try to avoid short orphan words on the final line, by - // allowing wrapN to go a bit over if that would fit in the - // remainder of the line. - slop := 5 - wrap = wrap - slop - - // Handle first line, which is indented by the caller (or the - // special case above) - l, s = wrapN(wrap, slop, s) - r = r + strings.Replace(l, "\n", "\n"+strings.Repeat(" ", i), -1) - - // Now wrap the rest - for s != "" { - var t string - - t, s = wrapN(wrap, slop, s) - r = r + "\n" + strings.Repeat(" ", i) + strings.Replace(t, "\n", "\n"+strings.Repeat(" ", i), -1) - } - - return r - -} - -// FlagUsagesWrapped returns a string containing the usage information -// for all flags in the FlagSet. Wrapped to `cols` columns (0 for no -// wrapping) -func (f *FlagSet) FlagUsagesWrapped(cols int) string { - buf := new(bytes.Buffer) - - lines := make([]string, 0, len(f.formal)) - - maxlen := 0 - f.VisitAll(func(flag *Flag) { - if flag.Hidden { - return - } - - line := "" - if flag.Shorthand != "" && flag.ShorthandDeprecated == "" { - line = fmt.Sprintf(" -%s, --%s", flag.Shorthand, flag.Name) - } else { - line = fmt.Sprintf(" --%s", flag.Name) - } - - varname, usage := UnquoteUsage(flag) - if varname != "" { - line += " " + varname - } - if flag.NoOptDefVal != "" { - switch flag.Value.Type() { - case "string": - line += fmt.Sprintf("[=\"%s\"]", flag.NoOptDefVal) - case "bool": - if flag.NoOptDefVal != "true" { - line += fmt.Sprintf("[=%s]", flag.NoOptDefVal) - } - case "count": - if flag.NoOptDefVal != "+1" { - line += fmt.Sprintf("[=%s]", flag.NoOptDefVal) - } - default: - line += fmt.Sprintf("[=%s]", flag.NoOptDefVal) - } - } - - // This special character will be replaced with spacing once the - // correct alignment is calculated - line += "\x00" - if len(line) > maxlen { - maxlen = len(line) - } - - line += usage - if !flag.defaultIsZeroValue() { - if flag.Value.Type() == "string" { - line += fmt.Sprintf(" (default %q)", flag.DefValue) - } else { - line += fmt.Sprintf(" (default %s)", flag.DefValue) - } - } - if len(flag.Deprecated) != 0 { - line += fmt.Sprintf(" (DEPRECATED: %s)", flag.Deprecated) - } - - lines = append(lines, line) - }) - - for _, line := range lines { - sidx := strings.Index(line, "\x00") - spacing := strings.Repeat(" ", maxlen-sidx) - // maxlen + 2 comes from + 1 for the \x00 and + 1 for the (deliberate) off-by-one in maxlen-sidx - fmt.Fprintln(buf, line[:sidx], spacing, wrap(maxlen+2, cols, line[sidx+1:])) - } - - return buf.String() -} - -// FlagUsages returns a string containing the usage information for all flags in -// the FlagSet -func (f *FlagSet) FlagUsages() string { - return f.FlagUsagesWrapped(0) -} - -// PrintDefaults prints to standard error the default values of all defined command-line flags. -func PrintDefaults() { - CommandLine.PrintDefaults() -} - -// defaultUsage is the default function to print a usage message. -func defaultUsage(f *FlagSet) { - fmt.Fprintf(f.out(), "Usage of %s:\n", f.name) - f.PrintDefaults() -} - -// NOTE: Usage is not just defaultUsage(CommandLine) -// because it serves (via godoc flag Usage) as the example -// for how to write your own usage function. - -// Usage prints to standard error a usage message documenting all defined command-line flags. -// The function is a variable that may be changed to point to a custom function. -// By default it prints a simple header and calls PrintDefaults; for details about the -// format of the output and how to control it, see the documentation for PrintDefaults. -var Usage = func() { - fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) - PrintDefaults() -} - -// NFlag returns the number of flags that have been set. -func (f *FlagSet) NFlag() int { return len(f.actual) } - -// NFlag returns the number of command-line flags that have been set. -func NFlag() int { return len(CommandLine.actual) } - -// Arg returns the i'th argument. Arg(0) is the first remaining argument -// after flags have been processed. -func (f *FlagSet) Arg(i int) string { - if i < 0 || i >= len(f.args) { - return "" - } - return f.args[i] -} - -// Arg returns the i'th command-line argument. Arg(0) is the first remaining argument -// after flags have been processed. -func Arg(i int) string { - return CommandLine.Arg(i) -} - -// NArg is the number of arguments remaining after flags have been processed. -func (f *FlagSet) NArg() int { return len(f.args) } - -// NArg is the number of arguments remaining after flags have been processed. -func NArg() int { return len(CommandLine.args) } - -// Args returns the non-flag arguments. -func (f *FlagSet) Args() []string { return f.args } - -// Args returns the non-flag command-line arguments. -func Args() []string { return CommandLine.args } - -// Var defines a flag with the specified name and usage string. The type and -// value of the flag are represented by the first argument, of type Value, which -// typically holds a user-defined implementation of Value. For instance, the -// caller could create a flag that turns a comma-separated string into a slice -// of strings by giving the slice the methods of Value; in particular, Set would -// decompose the comma-separated string into the slice. -func (f *FlagSet) Var(value Value, name string, usage string) { - f.VarP(value, name, "", usage) -} - -// VarPF is like VarP, but returns the flag created -func (f *FlagSet) VarPF(value Value, name, shorthand, usage string) *Flag { - // Remember the default value as a string; it won't change. - flag := &Flag{ - Name: name, - Shorthand: shorthand, - Usage: usage, - Value: value, - DefValue: value.String(), - } - f.AddFlag(flag) - return flag -} - -// VarP is like Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) VarP(value Value, name, shorthand, usage string) { - f.VarPF(value, name, shorthand, usage) -} - -// AddFlag will add the flag to the FlagSet -func (f *FlagSet) AddFlag(flag *Flag) { - normalizedFlagName := f.normalizeFlagName(flag.Name) - - _, alreadyThere := f.formal[normalizedFlagName] - if alreadyThere { - msg := fmt.Sprintf("%s flag redefined: %s", f.name, flag.Name) - fmt.Fprintln(f.out(), msg) - panic(msg) // Happens only if flags are declared with identical names - } - if f.formal == nil { - f.formal = make(map[NormalizedName]*Flag) - } - - flag.Name = string(normalizedFlagName) - f.formal[normalizedFlagName] = flag - f.orderedFormal = append(f.orderedFormal, flag) - - if flag.Shorthand == "" { - return - } - if len(flag.Shorthand) > 1 { - msg := fmt.Sprintf("%q shorthand is more than one ASCII character", flag.Shorthand) - fmt.Fprintf(f.out(), msg) - panic(msg) - } - if f.shorthands == nil { - f.shorthands = make(map[byte]*Flag) - } - c := flag.Shorthand[0] - used, alreadyThere := f.shorthands[c] - if alreadyThere { - msg := fmt.Sprintf("unable to redefine %q shorthand in %q flagset: it's already used for %q flag", c, f.name, used.Name) - fmt.Fprintf(f.out(), msg) - panic(msg) - } - f.shorthands[c] = flag -} - -// AddFlagSet adds one FlagSet to another. If a flag is already present in f -// the flag from newSet will be ignored. -func (f *FlagSet) AddFlagSet(newSet *FlagSet) { - if newSet == nil { - return - } - newSet.VisitAll(func(flag *Flag) { - if f.Lookup(flag.Name) == nil { - f.AddFlag(flag) - } - }) -} - -// Var defines a flag with the specified name and usage string. The type and -// value of the flag are represented by the first argument, of type Value, which -// typically holds a user-defined implementation of Value. For instance, the -// caller could create a flag that turns a comma-separated string into a slice -// of strings by giving the slice the methods of Value; in particular, Set would -// decompose the comma-separated string into the slice. -func Var(value Value, name string, usage string) { - CommandLine.VarP(value, name, "", usage) -} - -// VarP is like Var, but accepts a shorthand letter that can be used after a single dash. -func VarP(value Value, name, shorthand, usage string) { - CommandLine.VarP(value, name, shorthand, usage) -} - -// failf prints to standard error a formatted error and usage message and -// returns the error. -func (f *FlagSet) failf(format string, a ...interface{}) error { - err := fmt.Errorf(format, a...) - if f.errorHandling != ContinueOnError { - fmt.Fprintln(f.out(), err) - f.usage() - } - return err -} - -// usage calls the Usage method for the flag set, or the usage function if -// the flag set is CommandLine. -func (f *FlagSet) usage() { - if f == CommandLine { - Usage() - } else if f.Usage == nil { - defaultUsage(f) - } else { - f.Usage() - } -} - -//--unknown (args will be empty) -//--unknown --next-flag ... (args will be --next-flag ...) -//--unknown arg ... (args will be arg ...) -func stripUnknownFlagValue(args []string) []string { - if len(args) == 0 { - //--unknown - return args - } - - first := args[0] - if first[0] == '-' { - //--unknown --next-flag ... - return args - } - - //--unknown arg ... (args will be arg ...) - return args[1:] -} - -func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []string, err error) { - a = args - name := s[2:] - if len(name) == 0 || name[0] == '-' || name[0] == '=' { - err = f.failf("bad flag syntax: %s", s) - return - } - - split := strings.SplitN(name, "=", 2) - name = split[0] - flag, exists := f.formal[f.normalizeFlagName(name)] - - if !exists { - switch { - case name == "help": - f.usage() - return a, ErrHelp - case f.ParseErrorsWhitelist.UnknownFlags: - // --unknown=unknownval arg ... - // we do not want to lose arg in this case - if len(split) >= 2 { - return a, nil - } - - return stripUnknownFlagValue(a), nil - default: - err = f.failf("unknown flag: --%s", name) - return - } - } - - var value string - if len(split) == 2 { - // '--flag=arg' - value = split[1] - } else if flag.NoOptDefVal != "" { - // '--flag' (arg was optional) - value = flag.NoOptDefVal - } else if len(a) > 0 { - // '--flag arg' - value = a[0] - a = a[1:] - } else { - // '--flag' (arg was required) - err = f.failf("flag needs an argument: %s", s) - return - } - - err = fn(flag, value) - if err != nil { - f.failf(err.Error()) - } - return -} - -func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parseFunc) (outShorts string, outArgs []string, err error) { - outArgs = args - - if strings.HasPrefix(shorthands, "test.") { - return - } - - outShorts = shorthands[1:] - c := shorthands[0] - - flag, exists := f.shorthands[c] - if !exists { - switch { - case c == 'h': - f.usage() - err = ErrHelp - return - case f.ParseErrorsWhitelist.UnknownFlags: - // '-f=arg arg ...' - // we do not want to lose arg in this case - if len(shorthands) > 2 && shorthands[1] == '=' { - outShorts = "" - return - } - - outArgs = stripUnknownFlagValue(outArgs) - return - default: - err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands) - return - } - } - - var value string - if len(shorthands) > 2 && shorthands[1] == '=' { - // '-f=arg' - value = shorthands[2:] - outShorts = "" - } else if flag.NoOptDefVal != "" { - // '-f' (arg was optional) - value = flag.NoOptDefVal - } else if len(shorthands) > 1 { - // '-farg' - value = shorthands[1:] - outShorts = "" - } else if len(args) > 0 { - // '-f arg' - value = args[0] - outArgs = args[1:] - } else { - // '-f' (arg was required) - err = f.failf("flag needs an argument: %q in -%s", c, shorthands) - return - } - - if flag.ShorthandDeprecated != "" { - fmt.Fprintf(f.out(), "Flag shorthand -%s has been deprecated, %s\n", flag.Shorthand, flag.ShorthandDeprecated) - } - - err = fn(flag, value) - if err != nil { - f.failf(err.Error()) - } - return -} - -func (f *FlagSet) parseShortArg(s string, args []string, fn parseFunc) (a []string, err error) { - a = args - shorthands := s[1:] - - // "shorthands" can be a series of shorthand letters of flags (e.g. "-vvv"). - for len(shorthands) > 0 { - shorthands, a, err = f.parseSingleShortArg(shorthands, args, fn) - if err != nil { - return - } - } - - return -} - -func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) { - for len(args) > 0 { - s := args[0] - args = args[1:] - if len(s) == 0 || s[0] != '-' || len(s) == 1 { - if !f.interspersed { - f.args = append(f.args, s) - f.args = append(f.args, args...) - return nil - } - f.args = append(f.args, s) - continue - } - - if s[1] == '-' { - if len(s) == 2 { // "--" terminates the flags - f.argsLenAtDash = len(f.args) - f.args = append(f.args, args...) - break - } - args, err = f.parseLongArg(s, args, fn) - } else { - args, err = f.parseShortArg(s, args, fn) - } - if err != nil { - return - } - } - return -} - -// Parse parses flag definitions from the argument list, which should not -// include the command name. Must be called after all flags in the FlagSet -// are defined and before flags are accessed by the program. -// The return value will be ErrHelp if -help was set but not defined. -func (f *FlagSet) Parse(arguments []string) error { - if f.addedGoFlagSets != nil { - for _, goFlagSet := range f.addedGoFlagSets { - goFlagSet.Parse(nil) - } - } - f.parsed = true - - if len(arguments) < 0 { - return nil - } - - f.args = make([]string, 0, len(arguments)) - - set := func(flag *Flag, value string) error { - return f.Set(flag.Name, value) - } - - err := f.parseArgs(arguments, set) - if err != nil { - switch f.errorHandling { - case ContinueOnError: - return err - case ExitOnError: - fmt.Println(err) - os.Exit(2) - case PanicOnError: - panic(err) - } - } - return nil -} - -type parseFunc func(flag *Flag, value string) error - -// ParseAll parses flag definitions from the argument list, which should not -// include the command name. The arguments for fn are flag and value. Must be -// called after all flags in the FlagSet are defined and before flags are -// accessed by the program. The return value will be ErrHelp if -help was set -// but not defined. -func (f *FlagSet) ParseAll(arguments []string, fn func(flag *Flag, value string) error) error { - f.parsed = true - f.args = make([]string, 0, len(arguments)) - - err := f.parseArgs(arguments, fn) - if err != nil { - switch f.errorHandling { - case ContinueOnError: - return err - case ExitOnError: - os.Exit(2) - case PanicOnError: - panic(err) - } - } - return nil -} - -// Parsed reports whether f.Parse has been called. -func (f *FlagSet) Parsed() bool { - return f.parsed -} - -// Parse parses the command-line flags from os.Args[1:]. Must be called -// after all flags are defined and before flags are accessed by the program. -func Parse() { - // Ignore errors; CommandLine is set for ExitOnError. - CommandLine.Parse(os.Args[1:]) -} - -// ParseAll parses the command-line flags from os.Args[1:] and called fn for each. -// The arguments for fn are flag and value. Must be called after all flags are -// defined and before flags are accessed by the program. -func ParseAll(fn func(flag *Flag, value string) error) { - // Ignore errors; CommandLine is set for ExitOnError. - CommandLine.ParseAll(os.Args[1:], fn) -} - -// SetInterspersed sets whether to support interspersed option/non-option arguments. -func SetInterspersed(interspersed bool) { - CommandLine.SetInterspersed(interspersed) -} - -// Parsed returns true if the command-line flags have been parsed. -func Parsed() bool { - return CommandLine.Parsed() -} - -// CommandLine is the default set of command-line flags, parsed from os.Args. -var CommandLine = NewFlagSet(os.Args[0], ExitOnError) - -// NewFlagSet returns a new, empty flag set with the specified name, -// error handling property and SortFlags set to true. -func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet { - f := &FlagSet{ - name: name, - errorHandling: errorHandling, - argsLenAtDash: -1, - interspersed: true, - SortFlags: true, - } - return f -} - -// SetInterspersed sets whether to support interspersed option/non-option arguments. -func (f *FlagSet) SetInterspersed(interspersed bool) { - f.interspersed = interspersed -} - -// Init sets the name and error handling property for a flag set. -// By default, the zero FlagSet uses an empty name and the -// ContinueOnError error handling policy. -func (f *FlagSet) Init(name string, errorHandling ErrorHandling) { - f.name = name - f.errorHandling = errorHandling - f.argsLenAtDash = -1 -} diff --git a/vendor/github.com/spf13/pflag/float32.go b/vendor/github.com/spf13/pflag/float32.go deleted file mode 100644 index a243f81..0000000 --- a/vendor/github.com/spf13/pflag/float32.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- float32 Value -type float32Value float32 - -func newFloat32Value(val float32, p *float32) *float32Value { - *p = val - return (*float32Value)(p) -} - -func (f *float32Value) Set(s string) error { - v, err := strconv.ParseFloat(s, 32) - *f = float32Value(v) - return err -} - -func (f *float32Value) Type() string { - return "float32" -} - -func (f *float32Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 32) } - -func float32Conv(sval string) (interface{}, error) { - v, err := strconv.ParseFloat(sval, 32) - if err != nil { - return 0, err - } - return float32(v), nil -} - -// GetFloat32 return the float32 value of a flag with the given name -func (f *FlagSet) GetFloat32(name string) (float32, error) { - val, err := f.getFlagType(name, "float32", float32Conv) - if err != nil { - return 0, err - } - return val.(float32), nil -} - -// Float32Var defines a float32 flag with specified name, default value, and usage string. -// The argument p points to a float32 variable in which to store the value of the flag. -func (f *FlagSet) Float32Var(p *float32, name string, value float32, usage string) { - f.VarP(newFloat32Value(value, p), name, "", usage) -} - -// Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Float32VarP(p *float32, name, shorthand string, value float32, usage string) { - f.VarP(newFloat32Value(value, p), name, shorthand, usage) -} - -// Float32Var defines a float32 flag with specified name, default value, and usage string. -// The argument p points to a float32 variable in which to store the value of the flag. -func Float32Var(p *float32, name string, value float32, usage string) { - CommandLine.VarP(newFloat32Value(value, p), name, "", usage) -} - -// Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash. -func Float32VarP(p *float32, name, shorthand string, value float32, usage string) { - CommandLine.VarP(newFloat32Value(value, p), name, shorthand, usage) -} - -// Float32 defines a float32 flag with specified name, default value, and usage string. -// The return value is the address of a float32 variable that stores the value of the flag. -func (f *FlagSet) Float32(name string, value float32, usage string) *float32 { - p := new(float32) - f.Float32VarP(p, name, "", value, usage) - return p -} - -// Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Float32P(name, shorthand string, value float32, usage string) *float32 { - p := new(float32) - f.Float32VarP(p, name, shorthand, value, usage) - return p -} - -// Float32 defines a float32 flag with specified name, default value, and usage string. -// The return value is the address of a float32 variable that stores the value of the flag. -func Float32(name string, value float32, usage string) *float32 { - return CommandLine.Float32P(name, "", value, usage) -} - -// Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash. -func Float32P(name, shorthand string, value float32, usage string) *float32 { - return CommandLine.Float32P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/float64.go b/vendor/github.com/spf13/pflag/float64.go deleted file mode 100644 index 04b5492..0000000 --- a/vendor/github.com/spf13/pflag/float64.go +++ /dev/null @@ -1,84 +0,0 @@ -package pflag - -import "strconv" - -// -- float64 Value -type float64Value float64 - -func newFloat64Value(val float64, p *float64) *float64Value { - *p = val - return (*float64Value)(p) -} - -func (f *float64Value) Set(s string) error { - v, err := strconv.ParseFloat(s, 64) - *f = float64Value(v) - return err -} - -func (f *float64Value) Type() string { - return "float64" -} - -func (f *float64Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 64) } - -func float64Conv(sval string) (interface{}, error) { - return strconv.ParseFloat(sval, 64) -} - -// GetFloat64 return the float64 value of a flag with the given name -func (f *FlagSet) GetFloat64(name string) (float64, error) { - val, err := f.getFlagType(name, "float64", float64Conv) - if err != nil { - return 0, err - } - return val.(float64), nil -} - -// Float64Var defines a float64 flag with specified name, default value, and usage string. -// The argument p points to a float64 variable in which to store the value of the flag. -func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) { - f.VarP(newFloat64Value(value, p), name, "", usage) -} - -// Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Float64VarP(p *float64, name, shorthand string, value float64, usage string) { - f.VarP(newFloat64Value(value, p), name, shorthand, usage) -} - -// Float64Var defines a float64 flag with specified name, default value, and usage string. -// The argument p points to a float64 variable in which to store the value of the flag. -func Float64Var(p *float64, name string, value float64, usage string) { - CommandLine.VarP(newFloat64Value(value, p), name, "", usage) -} - -// Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash. -func Float64VarP(p *float64, name, shorthand string, value float64, usage string) { - CommandLine.VarP(newFloat64Value(value, p), name, shorthand, usage) -} - -// Float64 defines a float64 flag with specified name, default value, and usage string. -// The return value is the address of a float64 variable that stores the value of the flag. -func (f *FlagSet) Float64(name string, value float64, usage string) *float64 { - p := new(float64) - f.Float64VarP(p, name, "", value, usage) - return p -} - -// Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Float64P(name, shorthand string, value float64, usage string) *float64 { - p := new(float64) - f.Float64VarP(p, name, shorthand, value, usage) - return p -} - -// Float64 defines a float64 flag with specified name, default value, and usage string. -// The return value is the address of a float64 variable that stores the value of the flag. -func Float64(name string, value float64, usage string) *float64 { - return CommandLine.Float64P(name, "", value, usage) -} - -// Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash. -func Float64P(name, shorthand string, value float64, usage string) *float64 { - return CommandLine.Float64P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/golangflag.go b/vendor/github.com/spf13/pflag/golangflag.go deleted file mode 100644 index d3dd72b..0000000 --- a/vendor/github.com/spf13/pflag/golangflag.go +++ /dev/null @@ -1,105 +0,0 @@ -// 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. - -package pflag - -import ( - goflag "flag" - "reflect" - "strings" -) - -// flagValueWrapper implements pflag.Value around a flag.Value. The main -// difference here is the addition of the Type method that returns a string -// name of the type. As this is generally unknown, we approximate that with -// reflection. -type flagValueWrapper struct { - inner goflag.Value - flagType string -} - -// We are just copying the boolFlag interface out of goflag as that is what -// they use to decide if a flag should get "true" when no arg is given. -type goBoolFlag interface { - goflag.Value - IsBoolFlag() bool -} - -func wrapFlagValue(v goflag.Value) Value { - // If the flag.Value happens to also be a pflag.Value, just use it directly. - if pv, ok := v.(Value); ok { - return pv - } - - pv := &flagValueWrapper{ - inner: v, - } - - t := reflect.TypeOf(v) - if t.Kind() == reflect.Interface || t.Kind() == reflect.Ptr { - t = t.Elem() - } - - pv.flagType = strings.TrimSuffix(t.Name(), "Value") - return pv -} - -func (v *flagValueWrapper) String() string { - return v.inner.String() -} - -func (v *flagValueWrapper) Set(s string) error { - return v.inner.Set(s) -} - -func (v *flagValueWrapper) Type() string { - return v.flagType -} - -// PFlagFromGoFlag will return a *pflag.Flag given a *flag.Flag -// If the *flag.Flag.Name was a single character (ex: `v`) it will be accessiblei -// with both `-v` and `--v` in flags. If the golang flag was more than a single -// character (ex: `verbose`) it will only be accessible via `--verbose` -func PFlagFromGoFlag(goflag *goflag.Flag) *Flag { - // Remember the default value as a string; it won't change. - flag := &Flag{ - Name: goflag.Name, - Usage: goflag.Usage, - Value: wrapFlagValue(goflag.Value), - // Looks like golang flags don't set DefValue correctly :-( - //DefValue: goflag.DefValue, - DefValue: goflag.Value.String(), - } - // Ex: if the golang flag was -v, allow both -v and --v to work - if len(flag.Name) == 1 { - flag.Shorthand = flag.Name - } - if fv, ok := goflag.Value.(goBoolFlag); ok && fv.IsBoolFlag() { - flag.NoOptDefVal = "true" - } - return flag -} - -// AddGoFlag will add the given *flag.Flag to the pflag.FlagSet -func (f *FlagSet) AddGoFlag(goflag *goflag.Flag) { - if f.Lookup(goflag.Name) != nil { - return - } - newflag := PFlagFromGoFlag(goflag) - f.AddFlag(newflag) -} - -// AddGoFlagSet will add the given *flag.FlagSet to the pflag.FlagSet -func (f *FlagSet) AddGoFlagSet(newSet *goflag.FlagSet) { - if newSet == nil { - return - } - newSet.VisitAll(func(goflag *goflag.Flag) { - f.AddGoFlag(goflag) - }) - if f.addedGoFlagSets == nil { - f.addedGoFlagSets = make([]*goflag.FlagSet, 0) - } - f.addedGoFlagSets = append(f.addedGoFlagSets, newSet) -} diff --git a/vendor/github.com/spf13/pflag/int.go b/vendor/github.com/spf13/pflag/int.go deleted file mode 100644 index 1474b89..0000000 --- a/vendor/github.com/spf13/pflag/int.go +++ /dev/null @@ -1,84 +0,0 @@ -package pflag - -import "strconv" - -// -- int Value -type intValue int - -func newIntValue(val int, p *int) *intValue { - *p = val - return (*intValue)(p) -} - -func (i *intValue) Set(s string) error { - v, err := strconv.ParseInt(s, 0, 64) - *i = intValue(v) - return err -} - -func (i *intValue) Type() string { - return "int" -} - -func (i *intValue) String() string { return strconv.Itoa(int(*i)) } - -func intConv(sval string) (interface{}, error) { - return strconv.Atoi(sval) -} - -// GetInt return the int value of a flag with the given name -func (f *FlagSet) GetInt(name string) (int, error) { - val, err := f.getFlagType(name, "int", intConv) - if err != nil { - return 0, err - } - return val.(int), nil -} - -// IntVar defines an int flag with specified name, default value, and usage string. -// The argument p points to an int variable in which to store the value of the flag. -func (f *FlagSet) IntVar(p *int, name string, value int, usage string) { - f.VarP(newIntValue(value, p), name, "", usage) -} - -// IntVarP is like IntVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IntVarP(p *int, name, shorthand string, value int, usage string) { - f.VarP(newIntValue(value, p), name, shorthand, usage) -} - -// IntVar defines an int flag with specified name, default value, and usage string. -// The argument p points to an int variable in which to store the value of the flag. -func IntVar(p *int, name string, value int, usage string) { - CommandLine.VarP(newIntValue(value, p), name, "", usage) -} - -// IntVarP is like IntVar, but accepts a shorthand letter that can be used after a single dash. -func IntVarP(p *int, name, shorthand string, value int, usage string) { - CommandLine.VarP(newIntValue(value, p), name, shorthand, usage) -} - -// Int defines an int flag with specified name, default value, and usage string. -// The return value is the address of an int variable that stores the value of the flag. -func (f *FlagSet) Int(name string, value int, usage string) *int { - p := new(int) - f.IntVarP(p, name, "", value, usage) - return p -} - -// IntP is like Int, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IntP(name, shorthand string, value int, usage string) *int { - p := new(int) - f.IntVarP(p, name, shorthand, value, usage) - return p -} - -// Int defines an int flag with specified name, default value, and usage string. -// The return value is the address of an int variable that stores the value of the flag. -func Int(name string, value int, usage string) *int { - return CommandLine.IntP(name, "", value, usage) -} - -// IntP is like Int, but accepts a shorthand letter that can be used after a single dash. -func IntP(name, shorthand string, value int, usage string) *int { - return CommandLine.IntP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/int16.go b/vendor/github.com/spf13/pflag/int16.go deleted file mode 100644 index f1a01d0..0000000 --- a/vendor/github.com/spf13/pflag/int16.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- int16 Value -type int16Value int16 - -func newInt16Value(val int16, p *int16) *int16Value { - *p = val - return (*int16Value)(p) -} - -func (i *int16Value) Set(s string) error { - v, err := strconv.ParseInt(s, 0, 16) - *i = int16Value(v) - return err -} - -func (i *int16Value) Type() string { - return "int16" -} - -func (i *int16Value) String() string { return strconv.FormatInt(int64(*i), 10) } - -func int16Conv(sval string) (interface{}, error) { - v, err := strconv.ParseInt(sval, 0, 16) - if err != nil { - return 0, err - } - return int16(v), nil -} - -// GetInt16 returns the int16 value of a flag with the given name -func (f *FlagSet) GetInt16(name string) (int16, error) { - val, err := f.getFlagType(name, "int16", int16Conv) - if err != nil { - return 0, err - } - return val.(int16), nil -} - -// Int16Var defines an int16 flag with specified name, default value, and usage string. -// The argument p points to an int16 variable in which to store the value of the flag. -func (f *FlagSet) Int16Var(p *int16, name string, value int16, usage string) { - f.VarP(newInt16Value(value, p), name, "", usage) -} - -// Int16VarP is like Int16Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int16VarP(p *int16, name, shorthand string, value int16, usage string) { - f.VarP(newInt16Value(value, p), name, shorthand, usage) -} - -// Int16Var defines an int16 flag with specified name, default value, and usage string. -// The argument p points to an int16 variable in which to store the value of the flag. -func Int16Var(p *int16, name string, value int16, usage string) { - CommandLine.VarP(newInt16Value(value, p), name, "", usage) -} - -// Int16VarP is like Int16Var, but accepts a shorthand letter that can be used after a single dash. -func Int16VarP(p *int16, name, shorthand string, value int16, usage string) { - CommandLine.VarP(newInt16Value(value, p), name, shorthand, usage) -} - -// Int16 defines an int16 flag with specified name, default value, and usage string. -// The return value is the address of an int16 variable that stores the value of the flag. -func (f *FlagSet) Int16(name string, value int16, usage string) *int16 { - p := new(int16) - f.Int16VarP(p, name, "", value, usage) - return p -} - -// Int16P is like Int16, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int16P(name, shorthand string, value int16, usage string) *int16 { - p := new(int16) - f.Int16VarP(p, name, shorthand, value, usage) - return p -} - -// Int16 defines an int16 flag with specified name, default value, and usage string. -// The return value is the address of an int16 variable that stores the value of the flag. -func Int16(name string, value int16, usage string) *int16 { - return CommandLine.Int16P(name, "", value, usage) -} - -// Int16P is like Int16, but accepts a shorthand letter that can be used after a single dash. -func Int16P(name, shorthand string, value int16, usage string) *int16 { - return CommandLine.Int16P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/int32.go b/vendor/github.com/spf13/pflag/int32.go deleted file mode 100644 index 9b95944..0000000 --- a/vendor/github.com/spf13/pflag/int32.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- int32 Value -type int32Value int32 - -func newInt32Value(val int32, p *int32) *int32Value { - *p = val - return (*int32Value)(p) -} - -func (i *int32Value) Set(s string) error { - v, err := strconv.ParseInt(s, 0, 32) - *i = int32Value(v) - return err -} - -func (i *int32Value) Type() string { - return "int32" -} - -func (i *int32Value) String() string { return strconv.FormatInt(int64(*i), 10) } - -func int32Conv(sval string) (interface{}, error) { - v, err := strconv.ParseInt(sval, 0, 32) - if err != nil { - return 0, err - } - return int32(v), nil -} - -// GetInt32 return the int32 value of a flag with the given name -func (f *FlagSet) GetInt32(name string) (int32, error) { - val, err := f.getFlagType(name, "int32", int32Conv) - if err != nil { - return 0, err - } - return val.(int32), nil -} - -// Int32Var defines an int32 flag with specified name, default value, and usage string. -// The argument p points to an int32 variable in which to store the value of the flag. -func (f *FlagSet) Int32Var(p *int32, name string, value int32, usage string) { - f.VarP(newInt32Value(value, p), name, "", usage) -} - -// Int32VarP is like Int32Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int32VarP(p *int32, name, shorthand string, value int32, usage string) { - f.VarP(newInt32Value(value, p), name, shorthand, usage) -} - -// Int32Var defines an int32 flag with specified name, default value, and usage string. -// The argument p points to an int32 variable in which to store the value of the flag. -func Int32Var(p *int32, name string, value int32, usage string) { - CommandLine.VarP(newInt32Value(value, p), name, "", usage) -} - -// Int32VarP is like Int32Var, but accepts a shorthand letter that can be used after a single dash. -func Int32VarP(p *int32, name, shorthand string, value int32, usage string) { - CommandLine.VarP(newInt32Value(value, p), name, shorthand, usage) -} - -// Int32 defines an int32 flag with specified name, default value, and usage string. -// The return value is the address of an int32 variable that stores the value of the flag. -func (f *FlagSet) Int32(name string, value int32, usage string) *int32 { - p := new(int32) - f.Int32VarP(p, name, "", value, usage) - return p -} - -// Int32P is like Int32, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int32P(name, shorthand string, value int32, usage string) *int32 { - p := new(int32) - f.Int32VarP(p, name, shorthand, value, usage) - return p -} - -// Int32 defines an int32 flag with specified name, default value, and usage string. -// The return value is the address of an int32 variable that stores the value of the flag. -func Int32(name string, value int32, usage string) *int32 { - return CommandLine.Int32P(name, "", value, usage) -} - -// Int32P is like Int32, but accepts a shorthand letter that can be used after a single dash. -func Int32P(name, shorthand string, value int32, usage string) *int32 { - return CommandLine.Int32P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/int64.go b/vendor/github.com/spf13/pflag/int64.go deleted file mode 100644 index 0026d78..0000000 --- a/vendor/github.com/spf13/pflag/int64.go +++ /dev/null @@ -1,84 +0,0 @@ -package pflag - -import "strconv" - -// -- int64 Value -type int64Value int64 - -func newInt64Value(val int64, p *int64) *int64Value { - *p = val - return (*int64Value)(p) -} - -func (i *int64Value) Set(s string) error { - v, err := strconv.ParseInt(s, 0, 64) - *i = int64Value(v) - return err -} - -func (i *int64Value) Type() string { - return "int64" -} - -func (i *int64Value) String() string { return strconv.FormatInt(int64(*i), 10) } - -func int64Conv(sval string) (interface{}, error) { - return strconv.ParseInt(sval, 0, 64) -} - -// GetInt64 return the int64 value of a flag with the given name -func (f *FlagSet) GetInt64(name string) (int64, error) { - val, err := f.getFlagType(name, "int64", int64Conv) - if err != nil { - return 0, err - } - return val.(int64), nil -} - -// Int64Var defines an int64 flag with specified name, default value, and usage string. -// The argument p points to an int64 variable in which to store the value of the flag. -func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) { - f.VarP(newInt64Value(value, p), name, "", usage) -} - -// Int64VarP is like Int64Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int64VarP(p *int64, name, shorthand string, value int64, usage string) { - f.VarP(newInt64Value(value, p), name, shorthand, usage) -} - -// Int64Var defines an int64 flag with specified name, default value, and usage string. -// The argument p points to an int64 variable in which to store the value of the flag. -func Int64Var(p *int64, name string, value int64, usage string) { - CommandLine.VarP(newInt64Value(value, p), name, "", usage) -} - -// Int64VarP is like Int64Var, but accepts a shorthand letter that can be used after a single dash. -func Int64VarP(p *int64, name, shorthand string, value int64, usage string) { - CommandLine.VarP(newInt64Value(value, p), name, shorthand, usage) -} - -// Int64 defines an int64 flag with specified name, default value, and usage string. -// The return value is the address of an int64 variable that stores the value of the flag. -func (f *FlagSet) Int64(name string, value int64, usage string) *int64 { - p := new(int64) - f.Int64VarP(p, name, "", value, usage) - return p -} - -// Int64P is like Int64, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int64P(name, shorthand string, value int64, usage string) *int64 { - p := new(int64) - f.Int64VarP(p, name, shorthand, value, usage) - return p -} - -// Int64 defines an int64 flag with specified name, default value, and usage string. -// The return value is the address of an int64 variable that stores the value of the flag. -func Int64(name string, value int64, usage string) *int64 { - return CommandLine.Int64P(name, "", value, usage) -} - -// Int64P is like Int64, but accepts a shorthand letter that can be used after a single dash. -func Int64P(name, shorthand string, value int64, usage string) *int64 { - return CommandLine.Int64P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/int8.go b/vendor/github.com/spf13/pflag/int8.go deleted file mode 100644 index 4da9222..0000000 --- a/vendor/github.com/spf13/pflag/int8.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- int8 Value -type int8Value int8 - -func newInt8Value(val int8, p *int8) *int8Value { - *p = val - return (*int8Value)(p) -} - -func (i *int8Value) Set(s string) error { - v, err := strconv.ParseInt(s, 0, 8) - *i = int8Value(v) - return err -} - -func (i *int8Value) Type() string { - return "int8" -} - -func (i *int8Value) String() string { return strconv.FormatInt(int64(*i), 10) } - -func int8Conv(sval string) (interface{}, error) { - v, err := strconv.ParseInt(sval, 0, 8) - if err != nil { - return 0, err - } - return int8(v), nil -} - -// GetInt8 return the int8 value of a flag with the given name -func (f *FlagSet) GetInt8(name string) (int8, error) { - val, err := f.getFlagType(name, "int8", int8Conv) - if err != nil { - return 0, err - } - return val.(int8), nil -} - -// Int8Var defines an int8 flag with specified name, default value, and usage string. -// The argument p points to an int8 variable in which to store the value of the flag. -func (f *FlagSet) Int8Var(p *int8, name string, value int8, usage string) { - f.VarP(newInt8Value(value, p), name, "", usage) -} - -// Int8VarP is like Int8Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int8VarP(p *int8, name, shorthand string, value int8, usage string) { - f.VarP(newInt8Value(value, p), name, shorthand, usage) -} - -// Int8Var defines an int8 flag with specified name, default value, and usage string. -// The argument p points to an int8 variable in which to store the value of the flag. -func Int8Var(p *int8, name string, value int8, usage string) { - CommandLine.VarP(newInt8Value(value, p), name, "", usage) -} - -// Int8VarP is like Int8Var, but accepts a shorthand letter that can be used after a single dash. -func Int8VarP(p *int8, name, shorthand string, value int8, usage string) { - CommandLine.VarP(newInt8Value(value, p), name, shorthand, usage) -} - -// Int8 defines an int8 flag with specified name, default value, and usage string. -// The return value is the address of an int8 variable that stores the value of the flag. -func (f *FlagSet) Int8(name string, value int8, usage string) *int8 { - p := new(int8) - f.Int8VarP(p, name, "", value, usage) - return p -} - -// Int8P is like Int8, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int8P(name, shorthand string, value int8, usage string) *int8 { - p := new(int8) - f.Int8VarP(p, name, shorthand, value, usage) - return p -} - -// Int8 defines an int8 flag with specified name, default value, and usage string. -// The return value is the address of an int8 variable that stores the value of the flag. -func Int8(name string, value int8, usage string) *int8 { - return CommandLine.Int8P(name, "", value, usage) -} - -// Int8P is like Int8, but accepts a shorthand letter that can be used after a single dash. -func Int8P(name, shorthand string, value int8, usage string) *int8 { - return CommandLine.Int8P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/int_slice.go b/vendor/github.com/spf13/pflag/int_slice.go deleted file mode 100644 index 1e7c9ed..0000000 --- a/vendor/github.com/spf13/pflag/int_slice.go +++ /dev/null @@ -1,128 +0,0 @@ -package pflag - -import ( - "fmt" - "strconv" - "strings" -) - -// -- intSlice Value -type intSliceValue struct { - value *[]int - changed bool -} - -func newIntSliceValue(val []int, p *[]int) *intSliceValue { - isv := new(intSliceValue) - isv.value = p - *isv.value = val - return isv -} - -func (s *intSliceValue) Set(val string) error { - ss := strings.Split(val, ",") - out := make([]int, len(ss)) - for i, d := range ss { - var err error - out[i], err = strconv.Atoi(d) - if err != nil { - return err - } - - } - if !s.changed { - *s.value = out - } else { - *s.value = append(*s.value, out...) - } - s.changed = true - return nil -} - -func (s *intSliceValue) Type() string { - return "intSlice" -} - -func (s *intSliceValue) String() string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = fmt.Sprintf("%d", d) - } - return "[" + strings.Join(out, ",") + "]" -} - -func intSliceConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // Empty string would cause a slice with one (empty) entry - if len(val) == 0 { - return []int{}, nil - } - ss := strings.Split(val, ",") - out := make([]int, len(ss)) - for i, d := range ss { - var err error - out[i], err = strconv.Atoi(d) - if err != nil { - return nil, err - } - - } - return out, nil -} - -// GetIntSlice return the []int value of a flag with the given name -func (f *FlagSet) GetIntSlice(name string) ([]int, error) { - val, err := f.getFlagType(name, "intSlice", intSliceConv) - if err != nil { - return []int{}, err - } - return val.([]int), nil -} - -// IntSliceVar defines a intSlice flag with specified name, default value, and usage string. -// The argument p points to a []int variable in which to store the value of the flag. -func (f *FlagSet) IntSliceVar(p *[]int, name string, value []int, usage string) { - f.VarP(newIntSliceValue(value, p), name, "", usage) -} - -// IntSliceVarP is like IntSliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IntSliceVarP(p *[]int, name, shorthand string, value []int, usage string) { - f.VarP(newIntSliceValue(value, p), name, shorthand, usage) -} - -// IntSliceVar defines a int[] flag with specified name, default value, and usage string. -// The argument p points to a int[] variable in which to store the value of the flag. -func IntSliceVar(p *[]int, name string, value []int, usage string) { - CommandLine.VarP(newIntSliceValue(value, p), name, "", usage) -} - -// IntSliceVarP is like IntSliceVar, but accepts a shorthand letter that can be used after a single dash. -func IntSliceVarP(p *[]int, name, shorthand string, value []int, usage string) { - CommandLine.VarP(newIntSliceValue(value, p), name, shorthand, usage) -} - -// IntSlice defines a []int flag with specified name, default value, and usage string. -// The return value is the address of a []int variable that stores the value of the flag. -func (f *FlagSet) IntSlice(name string, value []int, usage string) *[]int { - p := []int{} - f.IntSliceVarP(&p, name, "", value, usage) - return &p -} - -// IntSliceP is like IntSlice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IntSliceP(name, shorthand string, value []int, usage string) *[]int { - p := []int{} - f.IntSliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// IntSlice defines a []int flag with specified name, default value, and usage string. -// The return value is the address of a []int variable that stores the value of the flag. -func IntSlice(name string, value []int, usage string) *[]int { - return CommandLine.IntSliceP(name, "", value, usage) -} - -// IntSliceP is like IntSlice, but accepts a shorthand letter that can be used after a single dash. -func IntSliceP(name, shorthand string, value []int, usage string) *[]int { - return CommandLine.IntSliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/ip.go b/vendor/github.com/spf13/pflag/ip.go deleted file mode 100644 index 3d414ba..0000000 --- a/vendor/github.com/spf13/pflag/ip.go +++ /dev/null @@ -1,94 +0,0 @@ -package pflag - -import ( - "fmt" - "net" - "strings" -) - -// -- net.IP value -type ipValue net.IP - -func newIPValue(val net.IP, p *net.IP) *ipValue { - *p = val - return (*ipValue)(p) -} - -func (i *ipValue) String() string { return net.IP(*i).String() } -func (i *ipValue) Set(s string) error { - ip := net.ParseIP(strings.TrimSpace(s)) - if ip == nil { - return fmt.Errorf("failed to parse IP: %q", s) - } - *i = ipValue(ip) - return nil -} - -func (i *ipValue) Type() string { - return "ip" -} - -func ipConv(sval string) (interface{}, error) { - ip := net.ParseIP(sval) - if ip != nil { - return ip, nil - } - return nil, fmt.Errorf("invalid string being converted to IP address: %s", sval) -} - -// GetIP return the net.IP value of a flag with the given name -func (f *FlagSet) GetIP(name string) (net.IP, error) { - val, err := f.getFlagType(name, "ip", ipConv) - if err != nil { - return nil, err - } - return val.(net.IP), nil -} - -// IPVar defines an net.IP flag with specified name, default value, and usage string. -// The argument p points to an net.IP variable in which to store the value of the flag. -func (f *FlagSet) IPVar(p *net.IP, name string, value net.IP, usage string) { - f.VarP(newIPValue(value, p), name, "", usage) -} - -// IPVarP is like IPVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) { - f.VarP(newIPValue(value, p), name, shorthand, usage) -} - -// IPVar defines an net.IP flag with specified name, default value, and usage string. -// The argument p points to an net.IP variable in which to store the value of the flag. -func IPVar(p *net.IP, name string, value net.IP, usage string) { - CommandLine.VarP(newIPValue(value, p), name, "", usage) -} - -// IPVarP is like IPVar, but accepts a shorthand letter that can be used after a single dash. -func IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) { - CommandLine.VarP(newIPValue(value, p), name, shorthand, usage) -} - -// IP defines an net.IP flag with specified name, default value, and usage string. -// The return value is the address of an net.IP variable that stores the value of the flag. -func (f *FlagSet) IP(name string, value net.IP, usage string) *net.IP { - p := new(net.IP) - f.IPVarP(p, name, "", value, usage) - return p -} - -// IPP is like IP, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPP(name, shorthand string, value net.IP, usage string) *net.IP { - p := new(net.IP) - f.IPVarP(p, name, shorthand, value, usage) - return p -} - -// IP defines an net.IP flag with specified name, default value, and usage string. -// The return value is the address of an net.IP variable that stores the value of the flag. -func IP(name string, value net.IP, usage string) *net.IP { - return CommandLine.IPP(name, "", value, usage) -} - -// IPP is like IP, but accepts a shorthand letter that can be used after a single dash. -func IPP(name, shorthand string, value net.IP, usage string) *net.IP { - return CommandLine.IPP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/ip_slice.go b/vendor/github.com/spf13/pflag/ip_slice.go deleted file mode 100644 index 7dd196f..0000000 --- a/vendor/github.com/spf13/pflag/ip_slice.go +++ /dev/null @@ -1,148 +0,0 @@ -package pflag - -import ( - "fmt" - "io" - "net" - "strings" -) - -// -- ipSlice Value -type ipSliceValue struct { - value *[]net.IP - changed bool -} - -func newIPSliceValue(val []net.IP, p *[]net.IP) *ipSliceValue { - ipsv := new(ipSliceValue) - ipsv.value = p - *ipsv.value = val - return ipsv -} - -// Set converts, and assigns, the comma-separated IP argument string representation as the []net.IP value of this flag. -// If Set is called on a flag that already has a []net.IP assigned, the newly converted values will be appended. -func (s *ipSliceValue) Set(val string) error { - - // remove all quote characters - rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "") - - // read flag arguments with CSV parser - ipStrSlice, err := readAsCSV(rmQuote.Replace(val)) - if err != nil && err != io.EOF { - return err - } - - // parse ip values into slice - out := make([]net.IP, 0, len(ipStrSlice)) - for _, ipStr := range ipStrSlice { - ip := net.ParseIP(strings.TrimSpace(ipStr)) - if ip == nil { - return fmt.Errorf("invalid string being converted to IP address: %s", ipStr) - } - out = append(out, ip) - } - - if !s.changed { - *s.value = out - } else { - *s.value = append(*s.value, out...) - } - - s.changed = true - - return nil -} - -// Type returns a string that uniquely represents this flag's type. -func (s *ipSliceValue) Type() string { - return "ipSlice" -} - -// String defines a "native" format for this net.IP slice flag value. -func (s *ipSliceValue) String() string { - - ipStrSlice := make([]string, len(*s.value)) - for i, ip := range *s.value { - ipStrSlice[i] = ip.String() - } - - out, _ := writeAsCSV(ipStrSlice) - - return "[" + out + "]" -} - -func ipSliceConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // Emtpy string would cause a slice with one (empty) entry - if len(val) == 0 { - return []net.IP{}, nil - } - ss := strings.Split(val, ",") - out := make([]net.IP, len(ss)) - for i, sval := range ss { - ip := net.ParseIP(strings.TrimSpace(sval)) - if ip == nil { - return nil, fmt.Errorf("invalid string being converted to IP address: %s", sval) - } - out[i] = ip - } - return out, nil -} - -// GetIPSlice returns the []net.IP value of a flag with the given name -func (f *FlagSet) GetIPSlice(name string) ([]net.IP, error) { - val, err := f.getFlagType(name, "ipSlice", ipSliceConv) - if err != nil { - return []net.IP{}, err - } - return val.([]net.IP), nil -} - -// IPSliceVar defines a ipSlice flag with specified name, default value, and usage string. -// The argument p points to a []net.IP variable in which to store the value of the flag. -func (f *FlagSet) IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) { - f.VarP(newIPSliceValue(value, p), name, "", usage) -} - -// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) { - f.VarP(newIPSliceValue(value, p), name, shorthand, usage) -} - -// IPSliceVar defines a []net.IP flag with specified name, default value, and usage string. -// The argument p points to a []net.IP variable in which to store the value of the flag. -func IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) { - CommandLine.VarP(newIPSliceValue(value, p), name, "", usage) -} - -// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash. -func IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) { - CommandLine.VarP(newIPSliceValue(value, p), name, shorthand, usage) -} - -// IPSlice defines a []net.IP flag with specified name, default value, and usage string. -// The return value is the address of a []net.IP variable that stores the value of that flag. -func (f *FlagSet) IPSlice(name string, value []net.IP, usage string) *[]net.IP { - p := []net.IP{} - f.IPSliceVarP(&p, name, "", value, usage) - return &p -} - -// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP { - p := []net.IP{} - f.IPSliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// IPSlice defines a []net.IP flag with specified name, default value, and usage string. -// The return value is the address of a []net.IP variable that stores the value of the flag. -func IPSlice(name string, value []net.IP, usage string) *[]net.IP { - return CommandLine.IPSliceP(name, "", value, usage) -} - -// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash. -func IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP { - return CommandLine.IPSliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/ipmask.go b/vendor/github.com/spf13/pflag/ipmask.go deleted file mode 100644 index 5bd44bd..0000000 --- a/vendor/github.com/spf13/pflag/ipmask.go +++ /dev/null @@ -1,122 +0,0 @@ -package pflag - -import ( - "fmt" - "net" - "strconv" -) - -// -- net.IPMask value -type ipMaskValue net.IPMask - -func newIPMaskValue(val net.IPMask, p *net.IPMask) *ipMaskValue { - *p = val - return (*ipMaskValue)(p) -} - -func (i *ipMaskValue) String() string { return net.IPMask(*i).String() } -func (i *ipMaskValue) Set(s string) error { - ip := ParseIPv4Mask(s) - if ip == nil { - return fmt.Errorf("failed to parse IP mask: %q", s) - } - *i = ipMaskValue(ip) - return nil -} - -func (i *ipMaskValue) Type() string { - return "ipMask" -} - -// ParseIPv4Mask written in IP form (e.g. 255.255.255.0). -// This function should really belong to the net package. -func ParseIPv4Mask(s string) net.IPMask { - mask := net.ParseIP(s) - if mask == nil { - if len(s) != 8 { - return nil - } - // net.IPMask.String() actually outputs things like ffffff00 - // so write a horrible parser for that as well :-( - m := []int{} - for i := 0; i < 4; i++ { - b := "0x" + s[2*i:2*i+2] - d, err := strconv.ParseInt(b, 0, 0) - if err != nil { - return nil - } - m = append(m, int(d)) - } - s := fmt.Sprintf("%d.%d.%d.%d", m[0], m[1], m[2], m[3]) - mask = net.ParseIP(s) - if mask == nil { - return nil - } - } - return net.IPv4Mask(mask[12], mask[13], mask[14], mask[15]) -} - -func parseIPv4Mask(sval string) (interface{}, error) { - mask := ParseIPv4Mask(sval) - if mask == nil { - return nil, fmt.Errorf("unable to parse %s as net.IPMask", sval) - } - return mask, nil -} - -// GetIPv4Mask return the net.IPv4Mask value of a flag with the given name -func (f *FlagSet) GetIPv4Mask(name string) (net.IPMask, error) { - val, err := f.getFlagType(name, "ipMask", parseIPv4Mask) - if err != nil { - return nil, err - } - return val.(net.IPMask), nil -} - -// IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string. -// The argument p points to an net.IPMask variable in which to store the value of the flag. -func (f *FlagSet) IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) { - f.VarP(newIPMaskValue(value, p), name, "", usage) -} - -// IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) { - f.VarP(newIPMaskValue(value, p), name, shorthand, usage) -} - -// IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string. -// The argument p points to an net.IPMask variable in which to store the value of the flag. -func IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) { - CommandLine.VarP(newIPMaskValue(value, p), name, "", usage) -} - -// IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash. -func IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) { - CommandLine.VarP(newIPMaskValue(value, p), name, shorthand, usage) -} - -// IPMask defines an net.IPMask flag with specified name, default value, and usage string. -// The return value is the address of an net.IPMask variable that stores the value of the flag. -func (f *FlagSet) IPMask(name string, value net.IPMask, usage string) *net.IPMask { - p := new(net.IPMask) - f.IPMaskVarP(p, name, "", value, usage) - return p -} - -// IPMaskP is like IPMask, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask { - p := new(net.IPMask) - f.IPMaskVarP(p, name, shorthand, value, usage) - return p -} - -// IPMask defines an net.IPMask flag with specified name, default value, and usage string. -// The return value is the address of an net.IPMask variable that stores the value of the flag. -func IPMask(name string, value net.IPMask, usage string) *net.IPMask { - return CommandLine.IPMaskP(name, "", value, usage) -} - -// IPMaskP is like IP, but accepts a shorthand letter that can be used after a single dash. -func IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask { - return CommandLine.IPMaskP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/ipnet.go b/vendor/github.com/spf13/pflag/ipnet.go deleted file mode 100644 index e2c1b8b..0000000 --- a/vendor/github.com/spf13/pflag/ipnet.go +++ /dev/null @@ -1,98 +0,0 @@ -package pflag - -import ( - "fmt" - "net" - "strings" -) - -// IPNet adapts net.IPNet for use as a flag. -type ipNetValue net.IPNet - -func (ipnet ipNetValue) String() string { - n := net.IPNet(ipnet) - return n.String() -} - -func (ipnet *ipNetValue) Set(value string) error { - _, n, err := net.ParseCIDR(strings.TrimSpace(value)) - if err != nil { - return err - } - *ipnet = ipNetValue(*n) - return nil -} - -func (*ipNetValue) Type() string { - return "ipNet" -} - -func newIPNetValue(val net.IPNet, p *net.IPNet) *ipNetValue { - *p = val - return (*ipNetValue)(p) -} - -func ipNetConv(sval string) (interface{}, error) { - _, n, err := net.ParseCIDR(strings.TrimSpace(sval)) - if err == nil { - return *n, nil - } - return nil, fmt.Errorf("invalid string being converted to IPNet: %s", sval) -} - -// GetIPNet return the net.IPNet value of a flag with the given name -func (f *FlagSet) GetIPNet(name string) (net.IPNet, error) { - val, err := f.getFlagType(name, "ipNet", ipNetConv) - if err != nil { - return net.IPNet{}, err - } - return val.(net.IPNet), nil -} - -// IPNetVar defines an net.IPNet flag with specified name, default value, and usage string. -// The argument p points to an net.IPNet variable in which to store the value of the flag. -func (f *FlagSet) IPNetVar(p *net.IPNet, name string, value net.IPNet, usage string) { - f.VarP(newIPNetValue(value, p), name, "", usage) -} - -// IPNetVarP is like IPNetVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPNetVarP(p *net.IPNet, name, shorthand string, value net.IPNet, usage string) { - f.VarP(newIPNetValue(value, p), name, shorthand, usage) -} - -// IPNetVar defines an net.IPNet flag with specified name, default value, and usage string. -// The argument p points to an net.IPNet variable in which to store the value of the flag. -func IPNetVar(p *net.IPNet, name string, value net.IPNet, usage string) { - CommandLine.VarP(newIPNetValue(value, p), name, "", usage) -} - -// IPNetVarP is like IPNetVar, but accepts a shorthand letter that can be used after a single dash. -func IPNetVarP(p *net.IPNet, name, shorthand string, value net.IPNet, usage string) { - CommandLine.VarP(newIPNetValue(value, p), name, shorthand, usage) -} - -// IPNet defines an net.IPNet flag with specified name, default value, and usage string. -// The return value is the address of an net.IPNet variable that stores the value of the flag. -func (f *FlagSet) IPNet(name string, value net.IPNet, usage string) *net.IPNet { - p := new(net.IPNet) - f.IPNetVarP(p, name, "", value, usage) - return p -} - -// IPNetP is like IPNet, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPNetP(name, shorthand string, value net.IPNet, usage string) *net.IPNet { - p := new(net.IPNet) - f.IPNetVarP(p, name, shorthand, value, usage) - return p -} - -// IPNet defines an net.IPNet flag with specified name, default value, and usage string. -// The return value is the address of an net.IPNet variable that stores the value of the flag. -func IPNet(name string, value net.IPNet, usage string) *net.IPNet { - return CommandLine.IPNetP(name, "", value, usage) -} - -// IPNetP is like IPNet, but accepts a shorthand letter that can be used after a single dash. -func IPNetP(name, shorthand string, value net.IPNet, usage string) *net.IPNet { - return CommandLine.IPNetP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/string.go b/vendor/github.com/spf13/pflag/string.go deleted file mode 100644 index 04e0a26..0000000 --- a/vendor/github.com/spf13/pflag/string.go +++ /dev/null @@ -1,80 +0,0 @@ -package pflag - -// -- string Value -type stringValue string - -func newStringValue(val string, p *string) *stringValue { - *p = val - return (*stringValue)(p) -} - -func (s *stringValue) Set(val string) error { - *s = stringValue(val) - return nil -} -func (s *stringValue) Type() string { - return "string" -} - -func (s *stringValue) String() string { return string(*s) } - -func stringConv(sval string) (interface{}, error) { - return sval, nil -} - -// GetString return the string value of a flag with the given name -func (f *FlagSet) GetString(name string) (string, error) { - val, err := f.getFlagType(name, "string", stringConv) - if err != nil { - return "", err - } - return val.(string), nil -} - -// StringVar defines a string flag with specified name, default value, and usage string. -// The argument p points to a string variable in which to store the value of the flag. -func (f *FlagSet) StringVar(p *string, name string, value string, usage string) { - f.VarP(newStringValue(value, p), name, "", usage) -} - -// StringVarP is like StringVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringVarP(p *string, name, shorthand string, value string, usage string) { - f.VarP(newStringValue(value, p), name, shorthand, usage) -} - -// StringVar defines a string flag with specified name, default value, and usage string. -// The argument p points to a string variable in which to store the value of the flag. -func StringVar(p *string, name string, value string, usage string) { - CommandLine.VarP(newStringValue(value, p), name, "", usage) -} - -// StringVarP is like StringVar, but accepts a shorthand letter that can be used after a single dash. -func StringVarP(p *string, name, shorthand string, value string, usage string) { - CommandLine.VarP(newStringValue(value, p), name, shorthand, usage) -} - -// String defines a string flag with specified name, default value, and usage string. -// The return value is the address of a string variable that stores the value of the flag. -func (f *FlagSet) String(name string, value string, usage string) *string { - p := new(string) - f.StringVarP(p, name, "", value, usage) - return p -} - -// StringP is like String, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringP(name, shorthand string, value string, usage string) *string { - p := new(string) - f.StringVarP(p, name, shorthand, value, usage) - return p -} - -// String defines a string flag with specified name, default value, and usage string. -// The return value is the address of a string variable that stores the value of the flag. -func String(name string, value string, usage string) *string { - return CommandLine.StringP(name, "", value, usage) -} - -// StringP is like String, but accepts a shorthand letter that can be used after a single dash. -func StringP(name, shorthand string, value string, usage string) *string { - return CommandLine.StringP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/string_array.go b/vendor/github.com/spf13/pflag/string_array.go deleted file mode 100644 index fa7bc60..0000000 --- a/vendor/github.com/spf13/pflag/string_array.go +++ /dev/null @@ -1,103 +0,0 @@ -package pflag - -// -- stringArray Value -type stringArrayValue struct { - value *[]string - changed bool -} - -func newStringArrayValue(val []string, p *[]string) *stringArrayValue { - ssv := new(stringArrayValue) - ssv.value = p - *ssv.value = val - return ssv -} - -func (s *stringArrayValue) Set(val string) error { - if !s.changed { - *s.value = []string{val} - s.changed = true - } else { - *s.value = append(*s.value, val) - } - return nil -} - -func (s *stringArrayValue) Type() string { - return "stringArray" -} - -func (s *stringArrayValue) String() string { - str, _ := writeAsCSV(*s.value) - return "[" + str + "]" -} - -func stringArrayConv(sval string) (interface{}, error) { - sval = sval[1 : len(sval)-1] - // An empty string would cause a array with one (empty) string - if len(sval) == 0 { - return []string{}, nil - } - return readAsCSV(sval) -} - -// GetStringArray return the []string value of a flag with the given name -func (f *FlagSet) GetStringArray(name string) ([]string, error) { - val, err := f.getFlagType(name, "stringArray", stringArrayConv) - if err != nil { - return []string{}, err - } - return val.([]string), nil -} - -// StringArrayVar defines a string flag with specified name, default value, and usage string. -// The argument p points to a []string variable in which to store the values of the multiple flags. -// The value of each argument will not try to be separated by comma. Use a StringSlice for that. -func (f *FlagSet) StringArrayVar(p *[]string, name string, value []string, usage string) { - f.VarP(newStringArrayValue(value, p), name, "", usage) -} - -// StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringArrayVarP(p *[]string, name, shorthand string, value []string, usage string) { - f.VarP(newStringArrayValue(value, p), name, shorthand, usage) -} - -// StringArrayVar defines a string flag with specified name, default value, and usage string. -// The argument p points to a []string variable in which to store the value of the flag. -// The value of each argument will not try to be separated by comma. Use a StringSlice for that. -func StringArrayVar(p *[]string, name string, value []string, usage string) { - CommandLine.VarP(newStringArrayValue(value, p), name, "", usage) -} - -// StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash. -func StringArrayVarP(p *[]string, name, shorthand string, value []string, usage string) { - CommandLine.VarP(newStringArrayValue(value, p), name, shorthand, usage) -} - -// StringArray defines a string flag with specified name, default value, and usage string. -// The return value is the address of a []string variable that stores the value of the flag. -// The value of each argument will not try to be separated by comma. Use a StringSlice for that. -func (f *FlagSet) StringArray(name string, value []string, usage string) *[]string { - p := []string{} - f.StringArrayVarP(&p, name, "", value, usage) - return &p -} - -// StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringArrayP(name, shorthand string, value []string, usage string) *[]string { - p := []string{} - f.StringArrayVarP(&p, name, shorthand, value, usage) - return &p -} - -// StringArray defines a string flag with specified name, default value, and usage string. -// The return value is the address of a []string variable that stores the value of the flag. -// The value of each argument will not try to be separated by comma. Use a StringSlice for that. -func StringArray(name string, value []string, usage string) *[]string { - return CommandLine.StringArrayP(name, "", value, usage) -} - -// StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash. -func StringArrayP(name, shorthand string, value []string, usage string) *[]string { - return CommandLine.StringArrayP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/string_slice.go b/vendor/github.com/spf13/pflag/string_slice.go deleted file mode 100644 index 0cd3ccc..0000000 --- a/vendor/github.com/spf13/pflag/string_slice.go +++ /dev/null @@ -1,149 +0,0 @@ -package pflag - -import ( - "bytes" - "encoding/csv" - "strings" -) - -// -- stringSlice Value -type stringSliceValue struct { - value *[]string - changed bool -} - -func newStringSliceValue(val []string, p *[]string) *stringSliceValue { - ssv := new(stringSliceValue) - ssv.value = p - *ssv.value = val - return ssv -} - -func readAsCSV(val string) ([]string, error) { - if val == "" { - return []string{}, nil - } - stringReader := strings.NewReader(val) - csvReader := csv.NewReader(stringReader) - return csvReader.Read() -} - -func writeAsCSV(vals []string) (string, error) { - b := &bytes.Buffer{} - w := csv.NewWriter(b) - err := w.Write(vals) - if err != nil { - return "", err - } - w.Flush() - return strings.TrimSuffix(b.String(), "\n"), nil -} - -func (s *stringSliceValue) Set(val string) error { - v, err := readAsCSV(val) - if err != nil { - return err - } - if !s.changed { - *s.value = v - } else { - *s.value = append(*s.value, v...) - } - s.changed = true - return nil -} - -func (s *stringSliceValue) Type() string { - return "stringSlice" -} - -func (s *stringSliceValue) String() string { - str, _ := writeAsCSV(*s.value) - return "[" + str + "]" -} - -func stringSliceConv(sval string) (interface{}, error) { - sval = sval[1 : len(sval)-1] - // An empty string would cause a slice with one (empty) string - if len(sval) == 0 { - return []string{}, nil - } - return readAsCSV(sval) -} - -// GetStringSlice return the []string value of a flag with the given name -func (f *FlagSet) GetStringSlice(name string) ([]string, error) { - val, err := f.getFlagType(name, "stringSlice", stringSliceConv) - if err != nil { - return []string{}, err - } - return val.([]string), nil -} - -// StringSliceVar defines a string flag with specified name, default value, and usage string. -// The argument p points to a []string variable in which to store the value of the flag. -// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. -// For example: -// --ss="v1,v2" -ss="v3" -// will result in -// []string{"v1", "v2", "v3"} -func (f *FlagSet) StringSliceVar(p *[]string, name string, value []string, usage string) { - f.VarP(newStringSliceValue(value, p), name, "", usage) -} - -// StringSliceVarP is like StringSliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringSliceVarP(p *[]string, name, shorthand string, value []string, usage string) { - f.VarP(newStringSliceValue(value, p), name, shorthand, usage) -} - -// StringSliceVar defines a string flag with specified name, default value, and usage string. -// The argument p points to a []string variable in which to store the value of the flag. -// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. -// For example: -// --ss="v1,v2" -ss="v3" -// will result in -// []string{"v1", "v2", "v3"} -func StringSliceVar(p *[]string, name string, value []string, usage string) { - CommandLine.VarP(newStringSliceValue(value, p), name, "", usage) -} - -// StringSliceVarP is like StringSliceVar, but accepts a shorthand letter that can be used after a single dash. -func StringSliceVarP(p *[]string, name, shorthand string, value []string, usage string) { - CommandLine.VarP(newStringSliceValue(value, p), name, shorthand, usage) -} - -// StringSlice defines a string flag with specified name, default value, and usage string. -// The return value is the address of a []string variable that stores the value of the flag. -// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. -// For example: -// --ss="v1,v2" -ss="v3" -// will result in -// []string{"v1", "v2", "v3"} -func (f *FlagSet) StringSlice(name string, value []string, usage string) *[]string { - p := []string{} - f.StringSliceVarP(&p, name, "", value, usage) - return &p -} - -// StringSliceP is like StringSlice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringSliceP(name, shorthand string, value []string, usage string) *[]string { - p := []string{} - f.StringSliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// StringSlice defines a string flag with specified name, default value, and usage string. -// The return value is the address of a []string variable that stores the value of the flag. -// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. -// For example: -// --ss="v1,v2" -ss="v3" -// will result in -// []string{"v1", "v2", "v3"} -func StringSlice(name string, value []string, usage string) *[]string { - return CommandLine.StringSliceP(name, "", value, usage) -} - -// StringSliceP is like StringSlice, but accepts a shorthand letter that can be used after a single dash. -func StringSliceP(name, shorthand string, value []string, usage string) *[]string { - return CommandLine.StringSliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/uint.go b/vendor/github.com/spf13/pflag/uint.go deleted file mode 100644 index dcbc2b7..0000000 --- a/vendor/github.com/spf13/pflag/uint.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- uint Value -type uintValue uint - -func newUintValue(val uint, p *uint) *uintValue { - *p = val - return (*uintValue)(p) -} - -func (i *uintValue) Set(s string) error { - v, err := strconv.ParseUint(s, 0, 64) - *i = uintValue(v) - return err -} - -func (i *uintValue) Type() string { - return "uint" -} - -func (i *uintValue) String() string { return strconv.FormatUint(uint64(*i), 10) } - -func uintConv(sval string) (interface{}, error) { - v, err := strconv.ParseUint(sval, 0, 0) - if err != nil { - return 0, err - } - return uint(v), nil -} - -// GetUint return the uint value of a flag with the given name -func (f *FlagSet) GetUint(name string) (uint, error) { - val, err := f.getFlagType(name, "uint", uintConv) - if err != nil { - return 0, err - } - return val.(uint), nil -} - -// UintVar defines a uint flag with specified name, default value, and usage string. -// The argument p points to a uint variable in which to store the value of the flag. -func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) { - f.VarP(newUintValue(value, p), name, "", usage) -} - -// UintVarP is like UintVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) UintVarP(p *uint, name, shorthand string, value uint, usage string) { - f.VarP(newUintValue(value, p), name, shorthand, usage) -} - -// UintVar defines a uint flag with specified name, default value, and usage string. -// The argument p points to a uint variable in which to store the value of the flag. -func UintVar(p *uint, name string, value uint, usage string) { - CommandLine.VarP(newUintValue(value, p), name, "", usage) -} - -// UintVarP is like UintVar, but accepts a shorthand letter that can be used after a single dash. -func UintVarP(p *uint, name, shorthand string, value uint, usage string) { - CommandLine.VarP(newUintValue(value, p), name, shorthand, usage) -} - -// Uint defines a uint flag with specified name, default value, and usage string. -// The return value is the address of a uint variable that stores the value of the flag. -func (f *FlagSet) Uint(name string, value uint, usage string) *uint { - p := new(uint) - f.UintVarP(p, name, "", value, usage) - return p -} - -// UintP is like Uint, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) UintP(name, shorthand string, value uint, usage string) *uint { - p := new(uint) - f.UintVarP(p, name, shorthand, value, usage) - return p -} - -// Uint defines a uint flag with specified name, default value, and usage string. -// The return value is the address of a uint variable that stores the value of the flag. -func Uint(name string, value uint, usage string) *uint { - return CommandLine.UintP(name, "", value, usage) -} - -// UintP is like Uint, but accepts a shorthand letter that can be used after a single dash. -func UintP(name, shorthand string, value uint, usage string) *uint { - return CommandLine.UintP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/uint16.go b/vendor/github.com/spf13/pflag/uint16.go deleted file mode 100644 index 7e9914e..0000000 --- a/vendor/github.com/spf13/pflag/uint16.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- uint16 value -type uint16Value uint16 - -func newUint16Value(val uint16, p *uint16) *uint16Value { - *p = val - return (*uint16Value)(p) -} - -func (i *uint16Value) Set(s string) error { - v, err := strconv.ParseUint(s, 0, 16) - *i = uint16Value(v) - return err -} - -func (i *uint16Value) Type() string { - return "uint16" -} - -func (i *uint16Value) String() string { return strconv.FormatUint(uint64(*i), 10) } - -func uint16Conv(sval string) (interface{}, error) { - v, err := strconv.ParseUint(sval, 0, 16) - if err != nil { - return 0, err - } - return uint16(v), nil -} - -// GetUint16 return the uint16 value of a flag with the given name -func (f *FlagSet) GetUint16(name string) (uint16, error) { - val, err := f.getFlagType(name, "uint16", uint16Conv) - if err != nil { - return 0, err - } - return val.(uint16), nil -} - -// Uint16Var defines a uint flag with specified name, default value, and usage string. -// The argument p points to a uint variable in which to store the value of the flag. -func (f *FlagSet) Uint16Var(p *uint16, name string, value uint16, usage string) { - f.VarP(newUint16Value(value, p), name, "", usage) -} - -// Uint16VarP is like Uint16Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) { - f.VarP(newUint16Value(value, p), name, shorthand, usage) -} - -// Uint16Var defines a uint flag with specified name, default value, and usage string. -// The argument p points to a uint variable in which to store the value of the flag. -func Uint16Var(p *uint16, name string, value uint16, usage string) { - CommandLine.VarP(newUint16Value(value, p), name, "", usage) -} - -// Uint16VarP is like Uint16Var, but accepts a shorthand letter that can be used after a single dash. -func Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) { - CommandLine.VarP(newUint16Value(value, p), name, shorthand, usage) -} - -// Uint16 defines a uint flag with specified name, default value, and usage string. -// The return value is the address of a uint variable that stores the value of the flag. -func (f *FlagSet) Uint16(name string, value uint16, usage string) *uint16 { - p := new(uint16) - f.Uint16VarP(p, name, "", value, usage) - return p -} - -// Uint16P is like Uint16, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Uint16P(name, shorthand string, value uint16, usage string) *uint16 { - p := new(uint16) - f.Uint16VarP(p, name, shorthand, value, usage) - return p -} - -// Uint16 defines a uint flag with specified name, default value, and usage string. -// The return value is the address of a uint variable that stores the value of the flag. -func Uint16(name string, value uint16, usage string) *uint16 { - return CommandLine.Uint16P(name, "", value, usage) -} - -// Uint16P is like Uint16, but accepts a shorthand letter that can be used after a single dash. -func Uint16P(name, shorthand string, value uint16, usage string) *uint16 { - return CommandLine.Uint16P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/uint32.go b/vendor/github.com/spf13/pflag/uint32.go deleted file mode 100644 index d802453..0000000 --- a/vendor/github.com/spf13/pflag/uint32.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- uint32 value -type uint32Value uint32 - -func newUint32Value(val uint32, p *uint32) *uint32Value { - *p = val - return (*uint32Value)(p) -} - -func (i *uint32Value) Set(s string) error { - v, err := strconv.ParseUint(s, 0, 32) - *i = uint32Value(v) - return err -} - -func (i *uint32Value) Type() string { - return "uint32" -} - -func (i *uint32Value) String() string { return strconv.FormatUint(uint64(*i), 10) } - -func uint32Conv(sval string) (interface{}, error) { - v, err := strconv.ParseUint(sval, 0, 32) - if err != nil { - return 0, err - } - return uint32(v), nil -} - -// GetUint32 return the uint32 value of a flag with the given name -func (f *FlagSet) GetUint32(name string) (uint32, error) { - val, err := f.getFlagType(name, "uint32", uint32Conv) - if err != nil { - return 0, err - } - return val.(uint32), nil -} - -// Uint32Var defines a uint32 flag with specified name, default value, and usage string. -// The argument p points to a uint32 variable in which to store the value of the flag. -func (f *FlagSet) Uint32Var(p *uint32, name string, value uint32, usage string) { - f.VarP(newUint32Value(value, p), name, "", usage) -} - -// Uint32VarP is like Uint32Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) { - f.VarP(newUint32Value(value, p), name, shorthand, usage) -} - -// Uint32Var defines a uint32 flag with specified name, default value, and usage string. -// The argument p points to a uint32 variable in which to store the value of the flag. -func Uint32Var(p *uint32, name string, value uint32, usage string) { - CommandLine.VarP(newUint32Value(value, p), name, "", usage) -} - -// Uint32VarP is like Uint32Var, but accepts a shorthand letter that can be used after a single dash. -func Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) { - CommandLine.VarP(newUint32Value(value, p), name, shorthand, usage) -} - -// Uint32 defines a uint32 flag with specified name, default value, and usage string. -// The return value is the address of a uint32 variable that stores the value of the flag. -func (f *FlagSet) Uint32(name string, value uint32, usage string) *uint32 { - p := new(uint32) - f.Uint32VarP(p, name, "", value, usage) - return p -} - -// Uint32P is like Uint32, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Uint32P(name, shorthand string, value uint32, usage string) *uint32 { - p := new(uint32) - f.Uint32VarP(p, name, shorthand, value, usage) - return p -} - -// Uint32 defines a uint32 flag with specified name, default value, and usage string. -// The return value is the address of a uint32 variable that stores the value of the flag. -func Uint32(name string, value uint32, usage string) *uint32 { - return CommandLine.Uint32P(name, "", value, usage) -} - -// Uint32P is like Uint32, but accepts a shorthand letter that can be used after a single dash. -func Uint32P(name, shorthand string, value uint32, usage string) *uint32 { - return CommandLine.Uint32P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/uint64.go b/vendor/github.com/spf13/pflag/uint64.go deleted file mode 100644 index f62240f..0000000 --- a/vendor/github.com/spf13/pflag/uint64.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- uint64 Value -type uint64Value uint64 - -func newUint64Value(val uint64, p *uint64) *uint64Value { - *p = val - return (*uint64Value)(p) -} - -func (i *uint64Value) Set(s string) error { - v, err := strconv.ParseUint(s, 0, 64) - *i = uint64Value(v) - return err -} - -func (i *uint64Value) Type() string { - return "uint64" -} - -func (i *uint64Value) String() string { return strconv.FormatUint(uint64(*i), 10) } - -func uint64Conv(sval string) (interface{}, error) { - v, err := strconv.ParseUint(sval, 0, 64) - if err != nil { - return 0, err - } - return uint64(v), nil -} - -// GetUint64 return the uint64 value of a flag with the given name -func (f *FlagSet) GetUint64(name string) (uint64, error) { - val, err := f.getFlagType(name, "uint64", uint64Conv) - if err != nil { - return 0, err - } - return val.(uint64), nil -} - -// Uint64Var defines a uint64 flag with specified name, default value, and usage string. -// The argument p points to a uint64 variable in which to store the value of the flag. -func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) { - f.VarP(newUint64Value(value, p), name, "", usage) -} - -// Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) { - f.VarP(newUint64Value(value, p), name, shorthand, usage) -} - -// Uint64Var defines a uint64 flag with specified name, default value, and usage string. -// The argument p points to a uint64 variable in which to store the value of the flag. -func Uint64Var(p *uint64, name string, value uint64, usage string) { - CommandLine.VarP(newUint64Value(value, p), name, "", usage) -} - -// Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash. -func Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) { - CommandLine.VarP(newUint64Value(value, p), name, shorthand, usage) -} - -// Uint64 defines a uint64 flag with specified name, default value, and usage string. -// The return value is the address of a uint64 variable that stores the value of the flag. -func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 { - p := new(uint64) - f.Uint64VarP(p, name, "", value, usage) - return p -} - -// Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Uint64P(name, shorthand string, value uint64, usage string) *uint64 { - p := new(uint64) - f.Uint64VarP(p, name, shorthand, value, usage) - return p -} - -// Uint64 defines a uint64 flag with specified name, default value, and usage string. -// The return value is the address of a uint64 variable that stores the value of the flag. -func Uint64(name string, value uint64, usage string) *uint64 { - return CommandLine.Uint64P(name, "", value, usage) -} - -// Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash. -func Uint64P(name, shorthand string, value uint64, usage string) *uint64 { - return CommandLine.Uint64P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/uint8.go b/vendor/github.com/spf13/pflag/uint8.go deleted file mode 100644 index bb0e83c..0000000 --- a/vendor/github.com/spf13/pflag/uint8.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- uint8 Value -type uint8Value uint8 - -func newUint8Value(val uint8, p *uint8) *uint8Value { - *p = val - return (*uint8Value)(p) -} - -func (i *uint8Value) Set(s string) error { - v, err := strconv.ParseUint(s, 0, 8) - *i = uint8Value(v) - return err -} - -func (i *uint8Value) Type() string { - return "uint8" -} - -func (i *uint8Value) String() string { return strconv.FormatUint(uint64(*i), 10) } - -func uint8Conv(sval string) (interface{}, error) { - v, err := strconv.ParseUint(sval, 0, 8) - if err != nil { - return 0, err - } - return uint8(v), nil -} - -// GetUint8 return the uint8 value of a flag with the given name -func (f *FlagSet) GetUint8(name string) (uint8, error) { - val, err := f.getFlagType(name, "uint8", uint8Conv) - if err != nil { - return 0, err - } - return val.(uint8), nil -} - -// Uint8Var defines a uint8 flag with specified name, default value, and usage string. -// The argument p points to a uint8 variable in which to store the value of the flag. -func (f *FlagSet) Uint8Var(p *uint8, name string, value uint8, usage string) { - f.VarP(newUint8Value(value, p), name, "", usage) -} - -// Uint8VarP is like Uint8Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) { - f.VarP(newUint8Value(value, p), name, shorthand, usage) -} - -// Uint8Var defines a uint8 flag with specified name, default value, and usage string. -// The argument p points to a uint8 variable in which to store the value of the flag. -func Uint8Var(p *uint8, name string, value uint8, usage string) { - CommandLine.VarP(newUint8Value(value, p), name, "", usage) -} - -// Uint8VarP is like Uint8Var, but accepts a shorthand letter that can be used after a single dash. -func Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) { - CommandLine.VarP(newUint8Value(value, p), name, shorthand, usage) -} - -// Uint8 defines a uint8 flag with specified name, default value, and usage string. -// The return value is the address of a uint8 variable that stores the value of the flag. -func (f *FlagSet) Uint8(name string, value uint8, usage string) *uint8 { - p := new(uint8) - f.Uint8VarP(p, name, "", value, usage) - return p -} - -// Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Uint8P(name, shorthand string, value uint8, usage string) *uint8 { - p := new(uint8) - f.Uint8VarP(p, name, shorthand, value, usage) - return p -} - -// Uint8 defines a uint8 flag with specified name, default value, and usage string. -// The return value is the address of a uint8 variable that stores the value of the flag. -func Uint8(name string, value uint8, usage string) *uint8 { - return CommandLine.Uint8P(name, "", value, usage) -} - -// Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash. -func Uint8P(name, shorthand string, value uint8, usage string) *uint8 { - return CommandLine.Uint8P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/uint_slice.go b/vendor/github.com/spf13/pflag/uint_slice.go deleted file mode 100644 index edd94c6..0000000 --- a/vendor/github.com/spf13/pflag/uint_slice.go +++ /dev/null @@ -1,126 +0,0 @@ -package pflag - -import ( - "fmt" - "strconv" - "strings" -) - -// -- uintSlice Value -type uintSliceValue struct { - value *[]uint - changed bool -} - -func newUintSliceValue(val []uint, p *[]uint) *uintSliceValue { - uisv := new(uintSliceValue) - uisv.value = p - *uisv.value = val - return uisv -} - -func (s *uintSliceValue) Set(val string) error { - ss := strings.Split(val, ",") - out := make([]uint, len(ss)) - for i, d := range ss { - u, err := strconv.ParseUint(d, 10, 0) - if err != nil { - return err - } - out[i] = uint(u) - } - if !s.changed { - *s.value = out - } else { - *s.value = append(*s.value, out...) - } - s.changed = true - return nil -} - -func (s *uintSliceValue) Type() string { - return "uintSlice" -} - -func (s *uintSliceValue) String() string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = fmt.Sprintf("%d", d) - } - return "[" + strings.Join(out, ",") + "]" -} - -func uintSliceConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // Empty string would cause a slice with one (empty) entry - if len(val) == 0 { - return []uint{}, nil - } - ss := strings.Split(val, ",") - out := make([]uint, len(ss)) - for i, d := range ss { - u, err := strconv.ParseUint(d, 10, 0) - if err != nil { - return nil, err - } - out[i] = uint(u) - } - return out, nil -} - -// GetUintSlice returns the []uint value of a flag with the given name. -func (f *FlagSet) GetUintSlice(name string) ([]uint, error) { - val, err := f.getFlagType(name, "uintSlice", uintSliceConv) - if err != nil { - return []uint{}, err - } - return val.([]uint), nil -} - -// UintSliceVar defines a uintSlice flag with specified name, default value, and usage string. -// The argument p points to a []uint variable in which to store the value of the flag. -func (f *FlagSet) UintSliceVar(p *[]uint, name string, value []uint, usage string) { - f.VarP(newUintSliceValue(value, p), name, "", usage) -} - -// UintSliceVarP is like UintSliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) UintSliceVarP(p *[]uint, name, shorthand string, value []uint, usage string) { - f.VarP(newUintSliceValue(value, p), name, shorthand, usage) -} - -// UintSliceVar defines a uint[] flag with specified name, default value, and usage string. -// The argument p points to a uint[] variable in which to store the value of the flag. -func UintSliceVar(p *[]uint, name string, value []uint, usage string) { - CommandLine.VarP(newUintSliceValue(value, p), name, "", usage) -} - -// UintSliceVarP is like the UintSliceVar, but accepts a shorthand letter that can be used after a single dash. -func UintSliceVarP(p *[]uint, name, shorthand string, value []uint, usage string) { - CommandLine.VarP(newUintSliceValue(value, p), name, shorthand, usage) -} - -// UintSlice defines a []uint flag with specified name, default value, and usage string. -// The return value is the address of a []uint variable that stores the value of the flag. -func (f *FlagSet) UintSlice(name string, value []uint, usage string) *[]uint { - p := []uint{} - f.UintSliceVarP(&p, name, "", value, usage) - return &p -} - -// UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) UintSliceP(name, shorthand string, value []uint, usage string) *[]uint { - p := []uint{} - f.UintSliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// UintSlice defines a []uint flag with specified name, default value, and usage string. -// The return value is the address of a []uint variable that stores the value of the flag. -func UintSlice(name string, value []uint, usage string) *[]uint { - return CommandLine.UintSliceP(name, "", value, usage) -} - -// UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash. -func UintSliceP(name, shorthand string, value []uint, usage string) *[]uint { - return CommandLine.UintSliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/tdewolff/minify/.gitattributes b/vendor/github.com/tdewolff/minify/.gitattributes deleted file mode 100644 index 4c50ee1..0000000 --- a/vendor/github.com/tdewolff/minify/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -benchmarks/sample_* linguist-generated=true diff --git a/vendor/github.com/tdewolff/minify/.gitignore b/vendor/github.com/tdewolff/minify/.gitignore deleted file mode 100644 index 3f3e864..0000000 --- a/vendor/github.com/tdewolff/minify/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -dist/ -benchmarks/* -!benchmarks/*.go -!benchmarks/sample_* diff --git a/vendor/github.com/tdewolff/minify/.goreleaser.yml b/vendor/github.com/tdewolff/minify/.goreleaser.yml deleted file mode 100644 index afaa1cb..0000000 --- a/vendor/github.com/tdewolff/minify/.goreleaser.yml +++ /dev/null @@ -1,28 +0,0 @@ -builds: - - binary: minify - main: ./cmd/minify/ - ldflags: -s -w -X main.Version={{.Version}} -X main.Commit={{.Commit}} -X main.Date={{.Date}} - env: - - CGO_ENABLED=0 - goos: - - linux - - windows - - darwin - - freebsd - - netbsd - - openbsd - goarch: - - amd64 -archive: - format: tar.gz - format_overrides: - - goos: windows - format: zip - name_template: "{{.Binary}}_{{.Version}}_{{.Os}}_{{.Arch}}" - files: - - README.md - - LICENSE.md -snapshot: - name_template: "devel" -release: - draft: true diff --git a/vendor/github.com/tdewolff/minify/.travis.yml b/vendor/github.com/tdewolff/minify/.travis.yml deleted file mode 100644 index 4c14dfb..0000000 --- a/vendor/github.com/tdewolff/minify/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: go -before_install: - - go get github.com/mattn/goveralls -script: - - goveralls -v -service travis-ci -repotoken $COVERALLS_TOKEN -ignore=cmd/minify/* || go test -v ./... diff --git a/vendor/github.com/tdewolff/minify/LICENSE.md b/vendor/github.com/tdewolff/minify/LICENSE.md deleted file mode 100644 index 41677de..0000000 --- a/vendor/github.com/tdewolff/minify/LICENSE.md +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2015 Taco de Wolff - - Permission is hereby granted, free of charge, to any person - obtaining a copy of this software and associated documentation - files (the "Software"), to deal in the Software without - restriction, including without limitation the rights to use, - copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following - conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/vendor/github.com/tdewolff/minify/README.md b/vendor/github.com/tdewolff/minify/README.md deleted file mode 100644 index f051b09..0000000 --- a/vendor/github.com/tdewolff/minify/README.md +++ /dev/null @@ -1,590 +0,0 @@ -# Minify [![Build Status](https://travis-ci.org/tdewolff/minify.svg?branch=master)](https://travis-ci.org/tdewolff/minify) [![GoDoc](http://godoc.org/github.com/tdewolff/minify?status.svg)](http://godoc.org/github.com/tdewolff/minify) [![Coverage Status](https://coveralls.io/repos/github/tdewolff/minify/badge.svg?branch=master)](https://coveralls.io/github/tdewolff/minify?branch=master) [![Join the chat at https://gitter.im/tdewolff/minify](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/tdewolff/minify?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) - -**[Online demo](http://go.tacodewolff.nl/minify) if you need to minify files *now*.** - -**[Command line tool](https://github.com/tdewolff/minify/tree/master/cmd/minify) that minifies concurrently and supports watching file changes.** - -**[All releases](https://github.com/tdewolff/minify/releases) for various platforms.** - ---- - -Minify is a minifier package written in [Go][1]. It provides HTML5, CSS3, JS, JSON, SVG and XML minifiers and an interface to implement any other minifier. Minification is the process of removing bytes from a file (such as whitespace) without changing its output and therefore shrinking its size and speeding up transmission over the internet and possibly parsing. The implemented minifiers are designed for high performance. - -The core functionality associates mimetypes with minification functions, allowing embedded resources (like CSS or JS within HTML files) to be minified as well. Users can add new implementations that are triggered based on a mimetype (or pattern), or redirect to an external command (like ClosureCompiler, UglifyCSS, ...). - -#### Table of Contents - -- [Minify](#minify) - - [Prologue](#prologue) - - [Installation](#installation) - - [API stability](#api-stability) - - [Testing](#testing) - - [Performance](#performance) - - [HTML](#html) - - [Whitespace removal](#whitespace-removal) - - [CSS](#css) - - [JS](#js) - - [JSON](#json) - - [SVG](#svg) - - [XML](#xml) - - [Usage](#usage) - - [New](#new) - - [From reader](#from-reader) - - [From bytes](#from-bytes) - - [From string](#from-string) - - [To reader](#to-reader) - - [To writer](#to-writer) - - [Middleware](#middleware) - - [Custom minifier](#custom-minifier) - - [Mediatypes](#mediatypes) - - [Examples](#examples) - - [Common minifiers](#common-minifiers) - - [Custom minifier](#custom-minifier-example) - - [ResponseWriter](#responsewriter) - - [Templates](#templates) - - [License](#license) - -### Status - -* CSS: **fully implemented** -* HTML: **fully implemented** -* JS: improved JSmin implementation -* JSON: **fully implemented** -* SVG: partially implemented; in development -* XML: **fully implemented** - -### Roadmap - -- [ ] General speed-up of all minifiers (use ASM for whitespace funcs) -- [ ] Improve JS minifiers by shortening variables and proper semicolon omission -- [ ] Speed-up SVG minifier, it is very slow -- [x] Proper parser error reporting and line number + column information -- [ ] Generation of source maps (uncertain, might slow down parsers too much if it cannot run separately nicely) -- [ ] Look into compression of images, fonts and other web resources (into package `compress`)? -- [ ] Create a cmd to pack webfiles (much like webpack), ie. merging CSS and JS files, inlining small external files, minification and gzipping. This would work on HTML files. -- [ ] Create a package to format files, much like `gofmt` for Go files? - -## Prologue -Minifiers or bindings to minifiers exist in almost all programming languages. Some implementations are merely using several regular-expressions to trim whitespace and comments (even though regex for parsing HTML/XML is ill-advised, for a good read see [Regular Expressions: Now You Have Two Problems](http://blog.codinghorror.com/regular-expressions-now-you-have-two-problems/)). Some implementations are much more profound, such as the [YUI Compressor](http://yui.github.io/yuicompressor/) and [Google Closure Compiler](https://github.com/google/closure-compiler) for JS. As most existing implementations either use JavaScript, use regexes, and don't focus on performance, they are pretty slow. - -This minifier proves to be that fast and extensive minifier that can handle HTML and any other filetype it may contain (CSS, JS, ...). It is usually orders of magnitude faster than existing minifiers. - -## Installation -Run the following command - - go get github.com/tdewolff/minify - -or add the following imports and run the project with `go get` -``` go -import ( - "github.com/tdewolff/minify" - "github.com/tdewolff/minify/css" - "github.com/tdewolff/minify/html" - "github.com/tdewolff/minify/js" - "github.com/tdewolff/minify/json" - "github.com/tdewolff/minify/svg" - "github.com/tdewolff/minify/xml" -) -``` - -## API stability -There is no guarantee for absolute stability, but I take issues and bugs seriously and don't take API changes lightly. The library will be maintained in a compatible way unless vital bugs prevent me from doing so. There has been one API change after v1 which added options support and I took the opportunity to push through some more API clean up as well. There are no plans whatsoever for future API changes. - -## Testing -For all subpackages and the imported `parse` and `buffer` packages, test coverage of 100% is pursued. Besides full coverage, the minifiers are [fuzz tested](https://github.com/tdewolff/fuzz) using [github.com/dvyukov/go-fuzz](http://www.github.com/dvyukov/go-fuzz), see [the wiki](https://github.com/tdewolff/minify/wiki) for the most important bugs found by fuzz testing. Furthermore am I working on adding visual testing to ensure that minification doesn't change anything visually. By using the WebKit browser to render the original and minified pages we can check whether any pixel is different. - -These tests ensure that everything works as intended, the code does not crash (whatever the input) and that it doesn't change the final result visually. If you still encounter a bug, please report [here](https://github.com/tdewolff/minify/issues)! - -## Performance -The benchmarks directory contains a number of standardized samples used to compare performance between changes. To give an indication of the speed of this library, I've ran the tests on my Thinkpad T460 (i5-6300U quad-core 2.4GHz running Arch Linux) using Go 1.9.2. - -``` -name time/op -CSS/sample_bootstrap.css-4 2.26ms ± 0% -CSS/sample_gumby.css-4 2.92ms ± 1% -HTML/sample_amazon.html-4 2.33ms ± 2% -HTML/sample_bbc.html-4 1.02ms ± 1% -HTML/sample_blogpost.html-4 171µs ± 2% -HTML/sample_es6.html-4 14.5ms ± 0% -HTML/sample_stackoverflow.html-4 2.41ms ± 1% -HTML/sample_wikipedia.html-4 4.76ms ± 0% -JS/sample_ace.js-4 7.41ms ± 0% -JS/sample_dot.js-4 63.7µs ± 0% -JS/sample_jquery.js-4 2.99ms ± 0% -JS/sample_jqueryui.js-4 5.92ms ± 2% -JS/sample_moment.js-4 1.09ms ± 1% -JSON/sample_large.json-4 2.95ms ± 0% -JSON/sample_testsuite.json-4 1.51ms ± 1% -JSON/sample_twitter.json-4 6.75µs ± 1% -SVG/sample_arctic.svg-4 62.3ms ± 1% -SVG/sample_gopher.svg-4 218µs ± 0% -SVG/sample_usa.svg-4 33.1ms ± 3% -XML/sample_books.xml-4 36.2µs ± 0% -XML/sample_catalog.xml-4 14.9µs ± 0% -XML/sample_omg.xml-4 6.31ms ± 1% - -name speed -CSS/sample_bootstrap.css-4 60.8MB/s ± 0% -CSS/sample_gumby.css-4 63.9MB/s ± 1% -HTML/sample_amazon.html-4 203MB/s ± 2% -HTML/sample_bbc.html-4 113MB/s ± 1% -HTML/sample_blogpost.html-4 123MB/s ± 2% -HTML/sample_es6.html-4 70.7MB/s ± 0% -HTML/sample_stackoverflow.html-4 85.2MB/s ± 1% -HTML/sample_wikipedia.html-4 93.6MB/s ± 0% -JS/sample_ace.js-4 86.9MB/s ± 0% -JS/sample_dot.js-4 81.0MB/s ± 0% -JS/sample_jquery.js-4 82.8MB/s ± 0% -JS/sample_jqueryui.js-4 79.3MB/s ± 2% -JS/sample_moment.js-4 91.2MB/s ± 1% -JSON/sample_large.json-4 258MB/s ± 0% -JSON/sample_testsuite.json-4 457MB/s ± 1% -JSON/sample_twitter.json-4 226MB/s ± 1% -SVG/sample_arctic.svg-4 23.6MB/s ± 1% -SVG/sample_gopher.svg-4 26.7MB/s ± 0% -SVG/sample_usa.svg-4 30.9MB/s ± 3% -XML/sample_books.xml-4 122MB/s ± 0% -XML/sample_catalog.xml-4 130MB/s ± 0% -XML/sample_omg.xml-4 180MB/s ± 1% -``` - -## HTML - -HTML (with JS and CSS) minification typically shaves off about 10%. - -The HTML5 minifier uses these minifications: - -- strip unnecessary whitespace and otherwise collapse it to one space (or newline if it originally contained a newline) -- strip superfluous quotes, or uses single/double quotes whichever requires fewer escapes -- strip default attribute values and attribute boolean values -- strip some empty attributes -- strip unrequired tags (`html`, `head`, `body`, ...) -- strip unrequired end tags (`tr`, `td`, `li`, ... and often `p`) -- strip default protocols (`http:`, `https:` and `javascript:`) -- strip all comments (including conditional comments, old IE versions are not supported anymore by Microsoft) -- shorten `doctype` and `meta` charset -- lowercase tags, attributes and some values to enhance gzip compression - -Options: - -- `KeepConditionalComments` preserve all IE conditional comments such as `` and ``, see https://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx#syntax -- `KeepDefaultAttrVals` preserve default attribute values such as `