summaryrefslogtreecommitdiffstats
path: root/vendor/github.com
diff options
context:
space:
mode:
authorChristopher Speller <crspeller@gmail.com>2017-06-21 19:06:17 -0700
committerCorey Hulen <corey@hulen.com>2017-06-21 19:06:17 -0700
commit42f28ab8e374137fe3f5d25424489d879d4724f8 (patch)
tree20353f2446b506d32e6d353b72a57bf48f070389 /vendor/github.com
parent6b39c308d882a0aeac533f8ab1d90b48a2ae4b5a (diff)
downloadchat-42f28ab8e374137fe3f5d25424489d879d4724f8.tar.gz
chat-42f28ab8e374137fe3f5d25424489d879d4724f8.tar.bz2
chat-42f28ab8e374137fe3f5d25424489d879d4724f8.zip
Updating server dependancies (#6712)
Diffstat (limited to 'vendor/github.com')
-rw-r--r--[-rwxr-xr-x]vendor/github.com/armon/go-metrics/.gitignore0
-rw-r--r--vendor/github.com/armon/go-metrics/inmem.go27
-rw-r--r--vendor/github.com/armon/go-metrics/inmem_test.go71
-rw-r--r--[-rwxr-xr-x]vendor/github.com/armon/go-metrics/metrics.go0
-rw-r--r--[-rwxr-xr-x]vendor/github.com/armon/go-metrics/sink.go45
-rw-r--r--[-rwxr-xr-x]vendor/github.com/armon/go-metrics/sink_test.go48
-rw-r--r--[-rwxr-xr-x]vendor/github.com/armon/go-metrics/start.go17
-rw-r--r--[-rwxr-xr-x]vendor/github.com/armon/go-metrics/start_test.go125
-rw-r--r--vendor/github.com/armon/go-metrics/statsd.go7
-rw-r--r--vendor/github.com/armon/go-metrics/statsd_test.go43
-rw-r--r--[-rwxr-xr-x]vendor/github.com/armon/go-metrics/statsite.go7
-rw-r--r--[-rwxr-xr-x]vendor/github.com/armon/go-metrics/statsite_test.go43
-rw-r--r--vendor/github.com/fsnotify/fsnotify/.travis.yml4
-rw-r--r--vendor/github.com/fsnotify/fsnotify/CHANGELOG.md6
-rw-r--r--vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md6
-rw-r--r--vendor/github.com/fsnotify/fsnotify/README.md37
-rw-r--r--vendor/github.com/fsnotify/fsnotify/fsnotify.go4
-rw-r--r--vendor/github.com/fsnotify/fsnotify/inotify.go66
-rw-r--r--vendor/github.com/fsnotify/fsnotify/inotify_test.go109
-rw-r--r--vendor/github.com/fsnotify/fsnotify/integration_darwin_test.go4
-rw-r--r--vendor/github.com/go-ini/ini/.gitignore5
-rw-r--r--vendor/github.com/go-ini/ini/.travis.yml17
-rw-r--r--vendor/github.com/go-ini/ini/LICENSE191
-rw-r--r--vendor/github.com/go-ini/ini/Makefile12
-rw-r--r--vendor/github.com/go-ini/ini/README.md740
-rw-r--r--vendor/github.com/go-ini/ini/README_ZH.md727
-rw-r--r--vendor/github.com/go-ini/ini/error.go32
-rw-r--r--vendor/github.com/go-ini/ini/ini.go556
-rw-r--r--vendor/github.com/go-ini/ini/ini_test.go484
-rw-r--r--vendor/github.com/go-ini/ini/key.go699
-rw-r--r--vendor/github.com/go-ini/ini/key_test.go573
-rw-r--r--vendor/github.com/go-ini/ini/parser.go361
-rw-r--r--vendor/github.com/go-ini/ini/parser_test.go42
-rw-r--r--vendor/github.com/go-ini/ini/section.go248
-rw-r--r--vendor/github.com/go-ini/ini/section_test.go75
-rw-r--r--vendor/github.com/go-ini/ini/struct.go450
-rw-r--r--vendor/github.com/go-ini/ini/struct_test.go337
-rw-r--r--vendor/github.com/go-ini/ini/testdata/UTF-16-BE-BOM.inibin56 -> 0 bytes
-rw-r--r--vendor/github.com/go-ini/ini/testdata/UTF-16-LE-BOM.inibin56 -> 0 bytes
-rw-r--r--vendor/github.com/go-ini/ini/testdata/UTF-8-BOM.ini2
-rw-r--r--vendor/github.com/go-ini/ini/testdata/aicc.ini11
-rw-r--r--vendor/github.com/go-ini/ini/testdata/conf.ini2
-rw-r--r--vendor/github.com/go-ldap/ldap/Makefile12
-rw-r--r--vendor/github.com/go-ldap/ldap/atomic_value.go13
-rw-r--r--vendor/github.com/go-ldap/ldap/atomic_value_go13.go28
-rw-r--r--vendor/github.com/go-ldap/ldap/conn.go33
-rw-r--r--vendor/github.com/go-ldap/ldap/conn_test.go6
-rw-r--r--vendor/github.com/go-ldap/ldap/error.go7
-rw-r--r--vendor/github.com/go-ldap/ldap/example_test.go2
-rw-r--r--vendor/github.com/go-sql-driver/mysql/.travis.yml79
-rw-r--r--vendor/github.com/go-sql-driver/mysql/.travis/docker.cnf5
-rwxr-xr-xvendor/github.com/go-sql-driver/mysql/.travis/wait_mysql.sh8
-rw-r--r--vendor/github.com/go-sql-driver/mysql/AUTHORS6
-rw-r--r--vendor/github.com/go-sql-driver/mysql/README.md48
-rw-r--r--vendor/github.com/go-sql-driver/mysql/connection.go36
-rw-r--r--vendor/github.com/go-sql-driver/mysql/driver.go2
-rw-r--r--vendor/github.com/go-sql-driver/mysql/driver_go18_test.go190
-rw-r--r--vendor/github.com/go-sql-driver/mysql/driver_test.go67
-rw-r--r--vendor/github.com/go-sql-driver/mysql/dsn.go4
-rw-r--r--vendor/github.com/go-sql-driver/mysql/infile.go3
-rw-r--r--vendor/github.com/go-sql-driver/mysql/packets.go77
-rw-r--r--vendor/github.com/go-sql-driver/mysql/packets_test.go8
-rw-r--r--vendor/github.com/go-sql-driver/mysql/rows.go112
-rw-r--r--vendor/github.com/go-sql-driver/mysql/statement.go55
-rw-r--r--vendor/github.com/golang/freetype/truetype/truetype_test.go2
-rw-r--r--vendor/github.com/golang/protobuf/README.md1
-rw-r--r--vendor/github.com/golang/protobuf/jsonpb/jsonpb.go117
-rw-r--r--vendor/github.com/golang/protobuf/jsonpb/jsonpb_test.go122
-rw-r--r--vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.pb.go120
-rw-r--r--vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.proto12
-rw-r--r--vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.pb.go218
-rw-r--r--vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.proto10
-rw-r--r--vendor/github.com/golang/protobuf/proto/decode_test.go2
-rw-r--r--vendor/github.com/golang/protobuf/proto/encode_test.go2
-rw-r--r--vendor/github.com/golang/protobuf/proto/lib.go1
-rw-r--r--vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go3
-rw-r--r--vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go.golden3
-rw-r--r--vendor/github.com/golang/protobuf/ptypes/any.go3
-rw-r--r--vendor/github.com/golang/protobuf/ptypes/duration_test.go38
-rw-r--r--vendor/github.com/golang/protobuf/ptypes/timestamp.go9
-rw-r--r--vendor/github.com/golang/protobuf/ptypes/timestamp_test.go41
-rw-r--r--vendor/github.com/gorilla/handlers/handlers.go8
-rw-r--r--vendor/github.com/gorilla/handlers/handlers_test.go24
-rw-r--r--vendor/github.com/gorilla/mux/README.md19
-rw-r--r--vendor/github.com/gorilla/mux/mux_test.go276
-rw-r--r--vendor/github.com/gorilla/mux/route.go49
-rw-r--r--vendor/github.com/gorilla/websocket/.travis.yml1
-rw-r--r--vendor/github.com/gorilla/websocket/client.go36
-rw-r--r--vendor/github.com/gorilla/websocket/client_clone.go16
-rw-r--r--vendor/github.com/gorilla/websocket/client_clone_legacy.go38
-rw-r--r--vendor/github.com/gorilla/websocket/compression.go73
-rw-r--r--vendor/github.com/gorilla/websocket/compression_test.go49
-rw-r--r--vendor/github.com/gorilla/websocket/conn.go144
-rw-r--r--vendor/github.com/gorilla/websocket/conn_broadcast_test.go134
-rw-r--r--vendor/github.com/gorilla/websocket/conn_test.go32
-rw-r--r--vendor/github.com/gorilla/websocket/doc.go23
-rw-r--r--vendor/github.com/gorilla/websocket/examples/autobahn/fuzzingclient.json1
-rw-r--r--vendor/github.com/gorilla/websocket/examples/autobahn/server.go29
-rw-r--r--vendor/github.com/gorilla/websocket/examples/chat/home.html4
-rw-r--r--vendor/github.com/gorilla/websocket/examples/chat/main.go5
-rw-r--r--vendor/github.com/gorilla/websocket/examples/command/README.md2
-rw-r--r--vendor/github.com/gorilla/websocket/examples/command/home.html56
-rw-r--r--vendor/github.com/gorilla/websocket/examples/command/main.go9
-rw-r--r--vendor/github.com/gorilla/websocket/examples/filewatch/main.go2
-rw-r--r--vendor/github.com/gorilla/websocket/mask.go12
-rw-r--r--vendor/github.com/gorilla/websocket/mask_safe.go15
-rw-r--r--vendor/github.com/gorilla/websocket/mask_test.go2
-rw-r--r--vendor/github.com/gorilla/websocket/prepared.go103
-rw-r--r--vendor/github.com/gorilla/websocket/prepared_test.go74
-rw-r--r--vendor/github.com/gorilla/websocket/server.go35
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/GNUmakefile (renamed from vendor/github.com/hashicorp/go-sockaddr/Makefile)16
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/GNUmakefile2
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/README.md9
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/regression/expected/sockaddr.out2
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/regression/expected/sockaddr_rfc-00.out2
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/regression/expected/sockaddr_rfc-01.out3
-rwxr-xr-xvendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/regression/run_all.sh4
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/vendor/github.com/mitchellh/cli/README.md1
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/vendor/github.com/mitchellh/cli/cli.go16
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/vendor/vendor.json6
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/version.go2
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/ifaddr.go128
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/ifaddr_test.go371
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/ifaddrs.go267
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/ifaddrs_test.go146
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/ipv4addr.go3
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/rfc.go1
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/template/GNUmakefile (renamed from vendor/github.com/hashicorp/go-sockaddr/template/Makefile)0
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/template/doc.go96
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/template/template.go32
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/template/template_test.go75
-rw-r--r--vendor/github.com/hashicorp/memberlist/config.go18
-rw-r--r--vendor/github.com/hashicorp/memberlist/memberlist_test.go129
-rw-r--r--vendor/github.com/hashicorp/memberlist/net.go17
-rw-r--r--vendor/github.com/hashicorp/memberlist/state_test.go2
-rw-r--r--vendor/github.com/lib/pq/conn.go6
-rw-r--r--vendor/github.com/lib/pq/conn_go18.go31
-rw-r--r--vendor/github.com/lib/pq/conn_test.go2
-rw-r--r--vendor/github.com/lib/pq/go18_test.go109
-rw-r--r--vendor/github.com/matttproud/golang_protobuf_extensions/.travis.yml6
-rw-r--r--vendor/github.com/matttproud/golang_protobuf_extensions/Makefile.TRAVIS15
-rw-r--r--vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/.gitignore1
-rw-r--r--vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/Makefile7
-rw-r--r--vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go25
-rw-r--r--vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/fixtures_test.go103
-rw-r--r--vendor/github.com/matttproud/golang_protobuf_extensions/testdata/README.THIRD_PARTY4
-rw-r--r--vendor/github.com/matttproud/golang_protobuf_extensions/testdata/test.pb.go4029
-rw-r--r--vendor/github.com/matttproud/golang_protobuf_extensions/testdata/test.proto540
-rw-r--r--vendor/github.com/miekg/dns/.travis.yml5
-rw-r--r--vendor/github.com/miekg/dns/README.md4
-rw-r--r--vendor/github.com/miekg/dns/defaults.go7
-rw-r--r--vendor/github.com/miekg/dns/parse_test.go11
-rw-r--r--vendor/github.com/miekg/dns/scan.go6
-rw-r--r--vendor/github.com/miekg/dns/xfr.go11
-rw-r--r--vendor/github.com/miekg/dns/xfr_test.go27
-rw-r--r--vendor/github.com/minio/go-homedir/LICENSE21
-rw-r--r--vendor/github.com/minio/go-homedir/README.md16
-rw-r--r--vendor/github.com/minio/go-homedir/dir_posix.go64
-rw-r--r--vendor/github.com/minio/go-homedir/dir_windows.go28
-rw-r--r--vendor/github.com/minio/go-homedir/homedir.go68
-rw-r--r--vendor/github.com/minio/go-homedir/homedir_test.go114
-rw-r--r--vendor/github.com/minio/minio-go/api-presigned.go43
-rw-r--r--vendor/github.com/minio/minio-go/api-put-bucket.go45
-rw-r--r--vendor/github.com/minio/minio-go/api-put-bucket_test.go42
-rw-r--r--vendor/github.com/minio/minio-go/api-put-object-file.go2
-rw-r--r--vendor/github.com/minio/minio-go/api-put-object-multipart.go2
-rw-r--r--vendor/github.com/minio/minio-go/api-put-object-progress.go10
-rw-r--r--vendor/github.com/minio/minio-go/api-put-object-readat.go2
-rw-r--r--vendor/github.com/minio/minio-go/api-put-object.go16
-rw-r--r--vendor/github.com/minio/minio-go/api.go150
-rw-r--r--vendor/github.com/minio/minio-go/api_functional_v4_test.go163
-rw-r--r--vendor/github.com/minio/minio-go/api_unit_test.go16
-rw-r--r--vendor/github.com/minio/minio-go/appveyor.yml2
-rw-r--r--vendor/github.com/minio/minio-go/bucket-cache.go40
-rw-r--r--vendor/github.com/minio/minio-go/bucket-cache_test.go49
-rw-r--r--vendor/github.com/minio/minio-go/core_test.go11
-rw-r--r--vendor/github.com/minio/minio-go/pkg/credentials/chain.go89
-rw-r--r--vendor/github.com/minio/minio-go/pkg/credentials/chain_test.go137
-rw-r--r--vendor/github.com/minio/minio-go/pkg/credentials/config.json.sample17
-rw-r--r--vendor/github.com/minio/minio-go/pkg/credentials/credentials.go175
-rw-r--r--vendor/github.com/minio/minio-go/pkg/credentials/credentials.sample12
-rw-r--r--vendor/github.com/minio/minio-go/pkg/credentials/credentials_test.go73
-rw-r--r--vendor/github.com/minio/minio-go/pkg/credentials/doc.go45
-rw-r--r--vendor/github.com/minio/minio-go/pkg/credentials/env_aws.go71
-rw-r--r--vendor/github.com/minio/minio-go/pkg/credentials/env_minio.go62
-rw-r--r--vendor/github.com/minio/minio-go/pkg/credentials/env_test.go105
-rw-r--r--vendor/github.com/minio/minio-go/pkg/credentials/file_aws_credentials.go120
-rw-r--r--vendor/github.com/minio/minio-go/pkg/credentials/file_minio_client.go129
-rw-r--r--vendor/github.com/minio/minio-go/pkg/credentials/file_test.go189
-rw-r--r--vendor/github.com/minio/minio-go/pkg/credentials/iam_aws.go196
-rw-r--r--vendor/github.com/minio/minio-go/pkg/credentials/iam_aws_test.go180
-rw-r--r--vendor/github.com/minio/minio-go/pkg/credentials/signature-type.go76
-rw-r--r--vendor/github.com/minio/minio-go/pkg/credentials/static.go67
-rw-r--r--vendor/github.com/minio/minio-go/pkg/credentials/static_test.go68
-rw-r--r--vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-streaming.go11
-rw-r--r--vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-streaming_test.go6
-rw-r--r--vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-v4.go13
-rw-r--r--vendor/github.com/minio/minio-go/pkg/s3signer/request-signature_test.go8
-rw-r--r--vendor/github.com/minio/minio-go/signature-type.go45
-rw-r--r--vendor/github.com/minio/minio-go/utils.go2
-rw-r--r--vendor/github.com/mitchellh/mapstructure/decode_hooks.go6
-rw-r--r--vendor/github.com/mssola/user_agent/.travis.yml2
-rw-r--r--vendor/github.com/mssola/user_agent/LICENSE2
-rw-r--r--vendor/github.com/mssola/user_agent/README.md2
-rw-r--r--vendor/github.com/mssola/user_agent/all_test.go670
-rw-r--r--vendor/github.com/mssola/user_agent/bot.go14
-rw-r--r--vendor/github.com/mssola/user_agent/browser.go40
-rw-r--r--vendor/github.com/mssola/user_agent/operating_systems.go107
-rw-r--r--vendor/github.com/mssola/user_agent/user_agent.go15
-rw-r--r--vendor/github.com/pborman/uuid/.travis.yml1
-rw-r--r--vendor/github.com/pborman/uuid/CONTRIBUTING.md10
-rw-r--r--vendor/github.com/pborman/uuid/README.md2
-rwxr-xr-x[-rw-r--r--]vendor/github.com/pborman/uuid/dce.go0
-rwxr-xr-x[-rw-r--r--]vendor/github.com/pborman/uuid/doc.go0
-rw-r--r--vendor/github.com/pborman/uuid/json.go34
-rw-r--r--vendor/github.com/pborman/uuid/json_test.go61
-rw-r--r--vendor/github.com/pborman/uuid/marshal.go83
-rw-r--r--vendor/github.com/pborman/uuid/marshal_test.go124
-rwxr-xr-x[-rw-r--r--]vendor/github.com/pborman/uuid/node.go0
-rw-r--r--vendor/github.com/pborman/uuid/sql.go8
-rw-r--r--vendor/github.com/pborman/uuid/sql_test.go9
-rwxr-xr-x[-rw-r--r--]vendor/github.com/pborman/uuid/time.go0
-rw-r--r--vendor/github.com/pborman/uuid/uuid.go27
-rw-r--r--vendor/github.com/pborman/uuid/uuid_test.go74
-rw-r--r--vendor/github.com/pelletier/go-toml/.travis.yml6
-rw-r--r--vendor/github.com/pelletier/go-toml/README.md80
-rwxr-xr-xvendor/github.com/pelletier/go-toml/benchmark.sh32
-rw-r--r--vendor/github.com/pelletier/go-toml/cmd/tomljson/main.go5
-rw-r--r--vendor/github.com/pelletier/go-toml/cmd/tomll/main.go5
-rw-r--r--vendor/github.com/pelletier/go-toml/doc.go77
-rw-r--r--vendor/github.com/pelletier/go-toml/doc_test.go28
-rw-r--r--vendor/github.com/pelletier/go-toml/lexer.go13
-rw-r--r--vendor/github.com/pelletier/go-toml/lexer_test.go29
-rw-r--r--vendor/github.com/pelletier/go-toml/marshal.go36
-rw-r--r--vendor/github.com/pelletier/go-toml/marshal_test.go19
-rw-r--r--vendor/github.com/pelletier/go-toml/query/lexer.go8
-rw-r--r--vendor/github.com/pelletier/go-toml/query/lexer_test.go2
-rw-r--r--vendor/github.com/pelletier/go-toml/query/match_test.go2
-rw-r--r--vendor/github.com/pelletier/go-toml/query/parser_test.go2
-rw-r--r--vendor/github.com/pelletier/go-toml/query/tokens.go7
-rw-r--r--vendor/github.com/pelletier/go-toml/toml.go3
-rw-r--r--vendor/github.com/pelletier/go-toml/tomltree_create.go17
-rw-r--r--vendor/github.com/pelletier/go-toml/tomltree_write.go55
-rw-r--r--vendor/github.com/pelletier/go-toml/tomltree_write_test.go87
-rw-r--r--vendor/github.com/prometheus/client_golang/.travis.yml7
-rw-r--r--vendor/github.com/prometheus/client_golang/AUTHORS.md18
-rw-r--r--vendor/github.com/prometheus/client_golang/CONTRIBUTING.md6
-rw-r--r--vendor/github.com/prometheus/client_golang/MAINTAINERS.md1
-rw-r--r--vendor/github.com/prometheus/client_golang/README.md4
-rw-r--r--vendor/github.com/prometheus/client_golang/api/client.go131
-rw-r--r--vendor/github.com/prometheus/client_golang/api/client_test.go115
-rw-r--r--vendor/github.com/prometheus/client_golang/api/prometheus/api.go (renamed from vendor/github.com/prometheus/client_golang/api/prometheus/v1/api.go)312
-rw-r--r--vendor/github.com/prometheus/client_golang/api/prometheus/api_test.go (renamed from vendor/github.com/prometheus/client_golang/api/prometheus/v1/api_test.go)402
-rw-r--r--vendor/github.com/prometheus/client_golang/examples/random/main.go21
-rw-r--r--vendor/github.com/prometheus/client_golang/examples/simple/main.go7
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/benchmark_test.go10
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/counter.go12
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/desc.go13
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/doc.go64
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/example_timer_complex_test.go71
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/example_timer_gauge_test.go48
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/example_timer_test.go40
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/examples_test.go17
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/expvar_collector_test.go2
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/gauge.go13
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/gauge_test.go20
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/go_collector.go43
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/go_collector_test.go51
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/graphite/bridge.go280
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/graphite/bridge_test.go309
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/histogram.go24
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/histogram_test.go24
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/http.go108
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/http_test.go43
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/observer.go50
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/process_collector.go104
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/process_collector_test.go24
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_1_7.go35
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_1_8.go70
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go29
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/promhttp/http_test.go6
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go95
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client_1_8.go142
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client_1_8_test.go195
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go473
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server_test.go164
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/push/example_add_from_gatherer_test.go83
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/push/examples_test.go24
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/push/push.go2
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/registry.go57
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/registry_test.go23
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/summary.go43
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/summary_test.go53
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/timer.go48
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/timer_test.go152
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/untyped.go5
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/value.go7
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/vec_test.go4
-rw-r--r--vendor/github.com/prometheus/common/README.md2
-rw-r--r--vendor/github.com/prometheus/common/log/eventlog_formatter.go10
-rw-r--r--vendor/github.com/prometheus/common/log/log.go101
-rw-r--r--vendor/github.com/prometheus/common/log/log_test.go2
-rw-r--r--vendor/github.com/prometheus/common/log/syslog_formatter.go10
-rw-r--r--vendor/github.com/prometheus/common/model/time.go14
-rw-r--r--vendor/github.com/prometheus/procfs/.travis.yml4
-rw-r--r--vendor/github.com/prometheus/procfs/Makefile16
-rw-r--r--vendor/github.com/prometheus/procfs/bcache/bcache.go84
-rw-r--r--vendor/github.com/prometheus/procfs/bcache/get.go330
-rw-r--r--vendor/github.com/prometheus/procfs/bcache/get_test.go114
-rw-r--r--vendor/github.com/prometheus/procfs/fixtures/net/xfrm_stat28
-rw-r--r--vendor/github.com/prometheus/procfs/fixtures/stat2
-rw-r--r--vendor/github.com/prometheus/procfs/stat.go193
-rw-r--r--vendor/github.com/prometheus/procfs/stat_test.go51
-rw-r--r--vendor/github.com/prometheus/procfs/sysfs/.gitignore1
-rw-r--r--vendor/github.com/prometheus/procfs/sysfs/fixtures.tar.gzbin0 -> 2865 bytes
-rw-r--r--vendor/github.com/prometheus/procfs/sysfs/fixtures/fs/xfs/sda1/stats/stats1
-rw-r--r--vendor/github.com/prometheus/procfs/sysfs/fixtures/fs/xfs/sdb1/stats/stats1
-rw-r--r--vendor/github.com/prometheus/procfs/sysfs/fs.go26
-rw-r--r--vendor/github.com/prometheus/procfs/sysfs/fs_test.go42
-rw-r--r--vendor/github.com/prometheus/procfs/xfrm.go187
-rw-r--r--vendor/github.com/prometheus/procfs/xfrm_test.go66
-rw-r--r--vendor/github.com/segmentio/analytics-go/cli/cli.go174
-rw-r--r--vendor/github.com/spf13/cobra/README.md68
-rw-r--r--vendor/github.com/spf13/cobra/bash_completions.go272
-rw-r--r--vendor/github.com/spf13/cobra/bash_completions_test.go20
-rw-r--r--vendor/github.com/spf13/cobra/cobra/cmd/add.go17
-rw-r--r--vendor/github.com/spf13/cobra/cobra/cmd/init.go20
-rw-r--r--vendor/github.com/spf13/cobra/cobra/cmd/root.go17
-rw-r--r--vendor/github.com/spf13/cobra/cobra/cmd/testdata/root.go.golden2
-rw-r--r--vendor/github.com/spf13/cobra/command.go67
-rw-r--r--vendor/github.com/spf13/cobra/command_test.go20
-rw-r--r--vendor/github.com/spf13/cobra/doc/man_docs.go3
-rw-r--r--vendor/github.com/spf13/cobra/doc/md_docs.go3
-rw-r--r--vendor/github.com/spf13/cobra/doc/yaml_docs.go3
-rw-r--r--vendor/github.com/spf13/jwalterweatherman/log_counter.go1
-rw-r--r--vendor/github.com/spf13/jwalterweatherman/notepad.go72
-rw-r--r--vendor/github.com/spf13/jwalterweatherman/notepad_test.go11
-rw-r--r--vendor/github.com/spf13/viper/README.md4
-rw-r--r--vendor/github.com/spf13/viper/viper.go37
-rw-r--r--vendor/github.com/tylerb/graceful/README.md5
-rw-r--r--vendor/github.com/xenolf/lego/.travis.yml2
341 files changed, 6320 insertions, 19797 deletions
diff --git a/vendor/github.com/armon/go-metrics/.gitignore b/vendor/github.com/armon/go-metrics/.gitignore
index 8c03ec112..8c03ec112 100755..100644
--- a/vendor/github.com/armon/go-metrics/.gitignore
+++ b/vendor/github.com/armon/go-metrics/.gitignore
diff --git a/vendor/github.com/armon/go-metrics/inmem.go b/vendor/github.com/armon/go-metrics/inmem.go
index 83fb6bba0..ac46443be 100644
--- a/vendor/github.com/armon/go-metrics/inmem.go
+++ b/vendor/github.com/armon/go-metrics/inmem.go
@@ -3,6 +3,7 @@ package metrics
import (
"fmt"
"math"
+ "net/url"
"strings"
"sync"
"time"
@@ -25,7 +26,7 @@ type InmemSink struct {
// intervals is a slice of the retained intervals
intervals []*IntervalMetrics
intervalLock sync.RWMutex
-
+
rateDenom float64
}
@@ -68,7 +69,7 @@ func NewIntervalMetrics(intv time.Time) *IntervalMetrics {
// about a sample
type AggregateSample struct {
Count int // The count of emitted pairs
- Rate float64 // The count of emitted pairs per time unit (usually 1 second)
+ Rate float64 // The count of emitted pairs per time unit (usually 1 second)
Sum float64 // The sum of values
SumSq float64 // The sum of squared values
Min float64 // Minimum value
@@ -105,7 +106,7 @@ func (a *AggregateSample) Ingest(v float64, rateDenom float64) {
if v > a.Max || a.Count == 1 {
a.Max = v
}
- a.Rate = float64(a.Count)/rateDenom
+ a.Rate = float64(a.Count) / rateDenom
a.LastUpdated = time.Now()
}
@@ -120,6 +121,24 @@ func (a *AggregateSample) String() string {
}
}
+// NewInmemSinkFromURL creates an InmemSink from a URL. It is used
+// (and tested) from NewMetricSinkFromURL.
+func NewInmemSinkFromURL(u *url.URL) (MetricSink, error) {
+ params := u.Query()
+
+ interval, err := time.ParseDuration(params.Get("interval"))
+ if err != nil {
+ return nil, fmt.Errorf("Bad 'interval' param: %s", err)
+ }
+
+ retain, err := time.ParseDuration(params.Get("retain"))
+ if err != nil {
+ return nil, fmt.Errorf("Bad 'retain' param: %s", err)
+ }
+
+ return NewInmemSink(interval, retain), nil
+}
+
// NewInmemSink is used to construct a new in-memory sink.
// Uses an aggregation interval and maximum retention period.
func NewInmemSink(interval, retain time.Duration) *InmemSink {
@@ -128,7 +147,7 @@ func NewInmemSink(interval, retain time.Duration) *InmemSink {
interval: interval,
retain: retain,
maxIntervals: int(retain / interval),
- rateDenom: float64(interval.Nanoseconds()) / float64(rateTimeUnit.Nanoseconds()),
+ rateDenom: float64(interval.Nanoseconds()) / float64(rateTimeUnit.Nanoseconds()),
}
i.intervals = make([]*IntervalMetrics, 0, i.maxIntervals)
return i
diff --git a/vendor/github.com/armon/go-metrics/inmem_test.go b/vendor/github.com/armon/go-metrics/inmem_test.go
index 1c2455114..ed3b521da 100644
--- a/vendor/github.com/armon/go-metrics/inmem_test.go
+++ b/vendor/github.com/armon/go-metrics/inmem_test.go
@@ -2,6 +2,8 @@ package metrics
import (
"math"
+ "net/url"
+ "strings"
"testing"
"time"
)
@@ -99,9 +101,78 @@ func TestInmemSink(t *testing.T) {
}
}
+func TestNewInmemSinkFromURL(t *testing.T) {
+ for _, tc := range []struct {
+ desc string
+ input string
+ expectErr string
+ expectInterval time.Duration
+ expectRetain time.Duration
+ }{
+ {
+ desc: "interval and duration are set via query params",
+ input: "inmem://?interval=11s&retain=22s",
+ expectInterval: duration(t, "11s"),
+ expectRetain: duration(t, "22s"),
+ },
+ {
+ desc: "interval is required",
+ input: "inmem://?retain=22s",
+ expectErr: "Bad 'interval' param",
+ },
+ {
+ desc: "interval must be a duration",
+ input: "inmem://?retain=30s&interval=HIYA",
+ expectErr: "Bad 'interval' param",
+ },
+ {
+ desc: "retain is required",
+ input: "inmem://?interval=30s",
+ expectErr: "Bad 'retain' param",
+ },
+ {
+ desc: "retain must be a valid duration",
+ input: "inmem://?interval=30s&retain=HELLO",
+ expectErr: "Bad 'retain' param",
+ },
+ } {
+ t.Run(tc.desc, func(t *testing.T) {
+ u, err := url.Parse(tc.input)
+ if err != nil {
+ t.Fatalf("error parsing URL: %s", err)
+ }
+ ms, err := NewInmemSinkFromURL(u)
+ if tc.expectErr != "" {
+ if !strings.Contains(err.Error(), tc.expectErr) {
+ t.Fatalf("expected err: %q, to contain: %q", err, tc.expectErr)
+ }
+ } else {
+ if err != nil {
+ t.Fatalf("unexpected err: %s", err)
+ }
+ is := ms.(*InmemSink)
+ if is.interval != tc.expectInterval {
+ t.Fatalf("expected interval %s, got: %s", tc.expectInterval, is.interval)
+ }
+ if is.retain != tc.expectRetain {
+ t.Fatalf("expected retain %s, got: %s", tc.expectRetain, is.retain)
+ }
+ }
+ })
+ }
+}
+
func min(a, b int) int {
if a < b {
return a
}
return b
}
+
+func duration(t *testing.T, s string) time.Duration {
+ dur, err := time.ParseDuration(s)
+ if err != nil {
+ t.Fatalf("error parsing duration: %s", err)
+ }
+ return dur
+}
diff --git a/vendor/github.com/armon/go-metrics/metrics.go b/vendor/github.com/armon/go-metrics/metrics.go
index b818e4182..b818e4182 100755..100644
--- a/vendor/github.com/armon/go-metrics/metrics.go
+++ b/vendor/github.com/armon/go-metrics/metrics.go
diff --git a/vendor/github.com/armon/go-metrics/sink.go b/vendor/github.com/armon/go-metrics/sink.go
index 0c240c2c4..9f7e2f6a2 100755..100644
--- a/vendor/github.com/armon/go-metrics/sink.go
+++ b/vendor/github.com/armon/go-metrics/sink.go
@@ -1,5 +1,10 @@
package metrics
+import (
+ "fmt"
+ "net/url"
+)
+
// The MetricSink interface is used to transmit metrics information
// to an external system
type MetricSink interface {
@@ -50,3 +55,43 @@ func (fh FanoutSink) AddSample(key []string, val float32) {
s.AddSample(key, val)
}
}
+
+// sinkURLFactoryFunc is an generic interface around the *SinkFromURL() function provided
+// by each sink type
+type sinkURLFactoryFunc func(*url.URL) (MetricSink, error)
+
+// sinkRegistry supports the generic NewMetricSink function by mapping URL
+// schemes to metric sink factory functions
+var sinkRegistry = map[string]sinkURLFactoryFunc{
+ "statsd": NewStatsdSinkFromURL,
+ "statsite": NewStatsiteSinkFromURL,
+ "inmem": NewInmemSinkFromURL,
+}
+
+// NewMetricSinkFromURL allows a generic URL input to configure any of the
+// supported sinks. The scheme of the URL identifies the type of the sink, the
+// and query parameters are used to set options.
+//
+// "statsd://" - Initializes a StatsdSink. The host and port are passed through
+// as the "addr" of the sink
+//
+// "statsite://" - Initializes a StatsiteSink. The host and port become the
+// "addr" of the sink
+//
+// "inmem://" - Initializes an InmemSink. The host and port are ignored. The
+// "interval" and "duration" query parameters must be specified with valid
+// durations, see NewInmemSink for details.
+func NewMetricSinkFromURL(urlStr string) (MetricSink, error) {
+ u, err := url.Parse(urlStr)
+ if err != nil {
+ return nil, err
+ }
+
+ sinkURLFactoryFunc := sinkRegistry[u.Scheme]
+ if sinkURLFactoryFunc == nil {
+ return nil, fmt.Errorf(
+ "cannot create metric sink, unrecognized sink name: %q", u.Scheme)
+ }
+
+ return sinkURLFactoryFunc(u)
+}
diff --git a/vendor/github.com/armon/go-metrics/sink_test.go b/vendor/github.com/armon/go-metrics/sink_test.go
index 15c5d771a..77c5c3278 100755..100644
--- a/vendor/github.com/armon/go-metrics/sink_test.go
+++ b/vendor/github.com/armon/go-metrics/sink_test.go
@@ -2,6 +2,7 @@ package metrics
import (
"reflect"
+ "strings"
"testing"
)
@@ -118,3 +119,50 @@ func TestFanoutSink_Sample(t *testing.T) {
t.Fatalf("val not equal")
}
}
+
+func TestNewMetricSinkFromURL(t *testing.T) {
+ for _, tc := range []struct {
+ desc string
+ input string
+ expect reflect.Type
+ expectErr string
+ }{
+ {
+ desc: "statsd scheme yields a StatsdSink",
+ input: "statsd://someserver:123",
+ expect: reflect.TypeOf(&StatsdSink{}),
+ },
+ {
+ desc: "statsite scheme yields a StatsiteSink",
+ input: "statsite://someserver:123",
+ expect: reflect.TypeOf(&StatsiteSink{}),
+ },
+ {
+ desc: "inmem scheme yields an InmemSink",
+ input: "inmem://?interval=30s&retain=30s",
+ expect: reflect.TypeOf(&InmemSink{}),
+ },
+ {
+ desc: "unknown scheme yields an error",
+ input: "notasink://whatever",
+ expectErr: "unrecognized sink name: \"notasink\"",
+ },
+ } {
+ t.Run(tc.desc, func(t *testing.T) {
+ ms, err := NewMetricSinkFromURL(tc.input)
+ if tc.expectErr != "" {
+ if !strings.Contains(err.Error(), tc.expectErr) {
+ t.Fatalf("expected err: %q to contain: %q", err, tc.expectErr)
+ }
+ } else {
+ if err != nil {
+ t.Fatalf("unexpected err: %s", err)
+ }
+ got := reflect.TypeOf(ms)
+ if got != tc.expect {
+ t.Fatalf("expected return type to be %v, got: %v", tc.expect, got)
+ }
+ }
+ })
+ }
+}
diff --git a/vendor/github.com/armon/go-metrics/start.go b/vendor/github.com/armon/go-metrics/start.go
index 44113f100..40c8d68c1 100755..100644
--- a/vendor/github.com/armon/go-metrics/start.go
+++ b/vendor/github.com/armon/go-metrics/start.go
@@ -2,6 +2,7 @@ package metrics
import (
"os"
+ "sync/atomic"
"time"
)
@@ -25,11 +26,11 @@ type Metrics struct {
}
// Shared global metrics instance
-var globalMetrics *Metrics
+var globalMetrics atomic.Value // *Metrics
func init() {
// Initialize to a blackhole sink to avoid errors
- globalMetrics = &Metrics{sink: &BlackholeSink{}}
+ globalMetrics.Store(&Metrics{sink: &BlackholeSink{}})
}
// DefaultConfig provides a sane default configuration
@@ -68,28 +69,28 @@ func New(conf *Config, sink MetricSink) (*Metrics, error) {
func NewGlobal(conf *Config, sink MetricSink) (*Metrics, error) {
metrics, err := New(conf, sink)
if err == nil {
- globalMetrics = metrics
+ globalMetrics.Store(metrics)
}
return metrics, err
}
// Proxy all the methods to the globalMetrics instance
func SetGauge(key []string, val float32) {
- globalMetrics.SetGauge(key, val)
+ globalMetrics.Load().(*Metrics).SetGauge(key, val)
}
func EmitKey(key []string, val float32) {
- globalMetrics.EmitKey(key, val)
+ globalMetrics.Load().(*Metrics).EmitKey(key, val)
}
func IncrCounter(key []string, val float32) {
- globalMetrics.IncrCounter(key, val)
+ globalMetrics.Load().(*Metrics).IncrCounter(key, val)
}
func AddSample(key []string, val float32) {
- globalMetrics.AddSample(key, val)
+ globalMetrics.Load().(*Metrics).AddSample(key, val)
}
func MeasureSince(key []string, start time.Time) {
- globalMetrics.MeasureSince(key, start)
+ globalMetrics.Load().(*Metrics).MeasureSince(key, start)
}
diff --git a/vendor/github.com/armon/go-metrics/start_test.go b/vendor/github.com/armon/go-metrics/start_test.go
index 8b3210c15..96b73d956 100755..100644
--- a/vendor/github.com/armon/go-metrics/start_test.go
+++ b/vendor/github.com/armon/go-metrics/start_test.go
@@ -1,7 +1,10 @@
package metrics
import (
+ "io/ioutil"
+ "log"
"reflect"
+ "sync/atomic"
"testing"
"time"
)
@@ -27,84 +30,70 @@ func TestDefaultConfig(t *testing.T) {
t.Fatalf("bad interval")
}
}
-
-func Test_GlobalMetrics_SetGauge(t *testing.T) {
- m := &MockSink{}
- globalMetrics = &Metrics{sink: m}
-
- k := []string{"test"}
- v := float32(42.0)
- SetGauge(k, v)
-
- if !reflect.DeepEqual(m.keys[0], k) {
- t.Fatalf("key not equal")
- }
- if !reflect.DeepEqual(m.vals[0], v) {
- t.Fatalf("val not equal")
- }
-}
-
-func Test_GlobalMetrics_EmitKey(t *testing.T) {
- m := &MockSink{}
- globalMetrics = &Metrics{sink: m}
-
- k := []string{"test"}
- v := float32(42.0)
- EmitKey(k, v)
-
- if !reflect.DeepEqual(m.keys[0], k) {
- t.Fatalf("key not equal")
- }
- if !reflect.DeepEqual(m.vals[0], v) {
- t.Fatalf("val not equal")
- }
-}
-
-func Test_GlobalMetrics_IncrCounter(t *testing.T) {
- m := &MockSink{}
- globalMetrics = &Metrics{sink: m}
-
- k := []string{"test"}
- v := float32(42.0)
- IncrCounter(k, v)
-
- if !reflect.DeepEqual(m.keys[0], k) {
- t.Fatalf("key not equal")
- }
- if !reflect.DeepEqual(m.vals[0], v) {
- t.Fatalf("val not equal")
- }
-}
-
-func Test_GlobalMetrics_AddSample(t *testing.T) {
- m := &MockSink{}
- globalMetrics = &Metrics{sink: m}
-
- k := []string{"test"}
- v := float32(42.0)
- AddSample(k, v)
-
- if !reflect.DeepEqual(m.keys[0], k) {
- t.Fatalf("key not equal")
- }
- if !reflect.DeepEqual(m.vals[0], v) {
- t.Fatalf("val not equal")
+func Test_GlobalMetrics(t *testing.T) {
+ var tests = []struct {
+ desc string
+ key []string
+ val float32
+ fn func([]string, float32)
+ }{
+ {"SetGauge", []string{"test"}, 42, SetGauge},
+ {"EmitKey", []string{"test"}, 42, EmitKey},
+ {"IncrCounter", []string{"test"}, 42, IncrCounter},
+ {"AddSample", []string{"test"}, 42, AddSample},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.desc, func(t *testing.T) {
+ s := &MockSink{}
+ globalMetrics.Store(&Metrics{sink: s})
+ tt.fn(tt.key, tt.val)
+ if got, want := s.keys[0], tt.key; !reflect.DeepEqual(got, want) {
+ t.Fatalf("got key %s want %s", got, want)
+ }
+ if got, want := s.vals[0], tt.val; !reflect.DeepEqual(got, want) {
+ t.Fatalf("got val %s want %s", got, want)
+ }
+ })
}
}
func Test_GlobalMetrics_MeasureSince(t *testing.T) {
- m := &MockSink{}
- globalMetrics = &Metrics{sink: m}
- globalMetrics.TimerGranularity = time.Millisecond
+ s := &MockSink{}
+ m := &Metrics{sink: s, Config: Config{TimerGranularity: time.Millisecond}}
+ globalMetrics.Store(m)
k := []string{"test"}
now := time.Now()
MeasureSince(k, now)
- if !reflect.DeepEqual(m.keys[0], k) {
+ if !reflect.DeepEqual(s.keys[0], k) {
t.Fatalf("key not equal")
}
- if m.vals[0] > 0.1 {
- t.Fatalf("val too large %v", m.vals[0])
+ if s.vals[0] > 0.1 {
+ t.Fatalf("val too large %v", s.vals[0])
}
}
+
+// Benchmark_GlobalMetrics_Direct/direct-8 5000000 278 ns/op
+// Benchmark_GlobalMetrics_Direct/atomic.Value-8 5000000 235 ns/op
+func Benchmark_GlobalMetrics_Direct(b *testing.B) {
+ log.SetOutput(ioutil.Discard)
+ s := &MockSink{}
+ m := &Metrics{sink: s}
+ var v atomic.Value
+ v.Store(m)
+ k := []string{"test"}
+ b.Run("direct", func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ m.IncrCounter(k, 1)
+ }
+ })
+ b.Run("atomic.Value", func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ v.Load().(*Metrics).IncrCounter(k, 1)
+ }
+ })
+ // do something with m so that the compiler does not optimize this away
+ b.Logf("%d", m.lastNumGC)
+}
diff --git a/vendor/github.com/armon/go-metrics/statsd.go b/vendor/github.com/armon/go-metrics/statsd.go
index 65a5021a0..4241e880c 100644
--- a/vendor/github.com/armon/go-metrics/statsd.go
+++ b/vendor/github.com/armon/go-metrics/statsd.go
@@ -5,6 +5,7 @@ import (
"fmt"
"log"
"net"
+ "net/url"
"strings"
"time"
)
@@ -23,6 +24,12 @@ type StatsdSink struct {
metricQueue chan string
}
+// NewStatsdSinkFromURL creates an StatsdSink from a URL. It is used
+// (and tested) from NewMetricSinkFromURL.
+func NewStatsdSinkFromURL(u *url.URL) (MetricSink, error) {
+ return NewStatsdSink(u.Host)
+}
+
// NewStatsdSink is used to create a new StatsdSink
func NewStatsdSink(addr string) (*StatsdSink, error) {
s := &StatsdSink{
diff --git a/vendor/github.com/armon/go-metrics/statsd_test.go b/vendor/github.com/armon/go-metrics/statsd_test.go
index 622eb5d3a..0602b213f 100644
--- a/vendor/github.com/armon/go-metrics/statsd_test.go
+++ b/vendor/github.com/armon/go-metrics/statsd_test.go
@@ -4,6 +4,8 @@ import (
"bufio"
"bytes"
"net"
+ "net/url"
+ "strings"
"testing"
"time"
)
@@ -103,3 +105,44 @@ func TestStatsd_Conn(t *testing.T) {
t.Fatalf("timeout")
}
}
+
+func TestNewStatsdSinkFromURL(t *testing.T) {
+ for _, tc := range []struct {
+ desc string
+ input string
+ expectErr string
+ expectAddr string
+ }{
+ {
+ desc: "address is populated",
+ input: "statsd://statsd.service.consul",
+ expectAddr: "statsd.service.consul",
+ },
+ {
+ desc: "address includes port",
+ input: "statsd://statsd.service.consul:1234",
+ expectAddr: "statsd.service.consul:1234",
+ },
+ } {
+ t.Run(tc.desc, func(t *testing.T) {
+ u, err := url.Parse(tc.input)
+ if err != nil {
+ t.Fatalf("error parsing URL: %s", err)
+ }
+ ms, err := NewStatsdSinkFromURL(u)
+ if tc.expectErr != "" {
+ if !strings.Contains(err.Error(), tc.expectErr) {
+ t.Fatalf("expected err: %q, to contain: %q", err, tc.expectErr)
+ }
+ } else {
+ if err != nil {
+ t.Fatalf("unexpected err: %s", err)
+ }
+ is := ms.(*StatsdSink)
+ if is.addr != tc.expectAddr {
+ t.Fatalf("expected addr %s, got: %s", tc.expectAddr, is.addr)
+ }
+ }
+ })
+ }
+}
diff --git a/vendor/github.com/armon/go-metrics/statsite.go b/vendor/github.com/armon/go-metrics/statsite.go
index 68730139a..572fe0571 100755..100644
--- a/vendor/github.com/armon/go-metrics/statsite.go
+++ b/vendor/github.com/armon/go-metrics/statsite.go
@@ -5,6 +5,7 @@ import (
"fmt"
"log"
"net"
+ "net/url"
"strings"
"time"
)
@@ -16,6 +17,12 @@ const (
flushInterval = 100 * time.Millisecond
)
+// NewStatsiteSinkFromURL creates an StatsiteSink from a URL. It is used
+// (and tested) from NewMetricSinkFromURL.
+func NewStatsiteSinkFromURL(u *url.URL) (MetricSink, error) {
+ return NewStatsiteSink(u.Host)
+}
+
// StatsiteSink provides a MetricSink that can be used with a
// statsite metrics server
type StatsiteSink struct {
diff --git a/vendor/github.com/armon/go-metrics/statsite_test.go b/vendor/github.com/armon/go-metrics/statsite_test.go
index d9c744f41..704474f43 100755..100644
--- a/vendor/github.com/armon/go-metrics/statsite_test.go
+++ b/vendor/github.com/armon/go-metrics/statsite_test.go
@@ -3,6 +3,8 @@ package metrics
import (
"bufio"
"net"
+ "net/url"
+ "strings"
"testing"
"time"
)
@@ -99,3 +101,44 @@ func TestStatsite_Conn(t *testing.T) {
t.Fatalf("timeout")
}
}
+
+func TestNewStatsiteSinkFromURL(t *testing.T) {
+ for _, tc := range []struct {
+ desc string
+ input string
+ expectErr string
+ expectAddr string
+ }{
+ {
+ desc: "address is populated",
+ input: "statsd://statsd.service.consul",
+ expectAddr: "statsd.service.consul",
+ },
+ {
+ desc: "address includes port",
+ input: "statsd://statsd.service.consul:1234",
+ expectAddr: "statsd.service.consul:1234",
+ },
+ } {
+ t.Run(tc.desc, func(t *testing.T) {
+ u, err := url.Parse(tc.input)
+ if err != nil {
+ t.Fatalf("error parsing URL: %s", err)
+ }
+ ms, err := NewStatsiteSinkFromURL(u)
+ if tc.expectErr != "" {
+ if !strings.Contains(err.Error(), tc.expectErr) {
+ t.Fatalf("expected err: %q, to contain: %q", err, tc.expectErr)
+ }
+ } else {
+ if err != nil {
+ t.Fatalf("unexpected err: %s", err)
+ }
+ is := ms.(*StatsiteSink)
+ if is.addr != tc.expectAddr {
+ t.Fatalf("expected addr %s, got: %s", tc.expectAddr, is.addr)
+ }
+ }
+ })
+ }
+}
diff --git a/vendor/github.com/fsnotify/fsnotify/.travis.yml b/vendor/github.com/fsnotify/fsnotify/.travis.yml
index 22e5fa43f..3a5c933bc 100644
--- a/vendor/github.com/fsnotify/fsnotify/.travis.yml
+++ b/vendor/github.com/fsnotify/fsnotify/.travis.yml
@@ -2,14 +2,12 @@ sudo: false
language: go
go:
- - 1.8
- - 1.7.x
+ - 1.6.3
- tip
matrix:
allow_failures:
- go: tip
- fast_finish: true
before_script:
- go get -u github.com/golang/lint/golint
diff --git a/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md b/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md
index 8c732c1d8..40d7660d5 100644
--- a/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md
+++ b/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md
@@ -79,7 +79,7 @@ kqueue: Fix logic for CREATE after REMOVE [#111](https://github.com/fsnotify/fsn
## v1.0.2 / 2014-08-17
-* [Fix] Missing create events on macOS. [#14](https://github.com/fsnotify/fsnotify/issues/14) (thanks @zhsso)
+* [Fix] Missing create events on OS X. [#14](https://github.com/fsnotify/fsnotify/issues/14) (thanks @zhsso)
* [Fix] Make ./path and path equivalent. (thanks @zhsso)
## v1.0.0 / 2014-08-15
@@ -142,7 +142,7 @@ kqueue: Fix logic for CREATE after REMOVE [#111](https://github.com/fsnotify/fsn
## v0.9.2 / 2014-08-17
-* [Backport] Fix missing create events on macOS. [#14](https://github.com/fsnotify/fsnotify/issues/14) (thanks @zhsso)
+* [Backport] Fix missing create events on OS X. [#14](https://github.com/fsnotify/fsnotify/issues/14) (thanks @zhsso)
## v0.9.1 / 2014-06-12
@@ -161,7 +161,7 @@ kqueue: Fix logic for CREATE after REMOVE [#111](https://github.com/fsnotify/fsn
## v0.8.11 / 2013-11-02
* [Doc] Add Changelog [#72][] (thanks @nathany)
-* [Doc] Spotlight and double modify events on macOS [#62][] (reported by @paulhammond)
+* [Doc] Spotlight and double modify events on OS X [#62][] (reported by @paulhammond)
## v0.8.10 / 2013-10-19
diff --git a/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md b/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md
index 828a60b24..6a81ba489 100644
--- a/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md
+++ b/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md
@@ -17,7 +17,7 @@ Please indicate that you have signed the CLA in your pull request.
### How fsnotify is Developed
* Development is done on feature branches.
-* Tests are run on BSD, Linux, macOS and Windows.
+* Tests are run on BSD, Linux, OS X and Windows.
* Pull requests are reviewed and [applied to master][am] using [hub][].
* Maintainers may modify or squash commits rather than asking contributors to.
* To issue a new release, the maintainers will:
@@ -44,7 +44,7 @@ This workflow is [thoroughly explained by Katrina Owen](https://splice.com/blog/
### Testing
-fsnotify uses build tags to compile different code on Linux, BSD, macOS, and Windows.
+fsnotify uses build tags to compile different code on Linux, BSD, OS X, and Windows.
Before doing a pull request, please do your best to test your changes on multiple platforms, and list which platforms you were able/unable to test on.
@@ -58,7 +58,7 @@ To aid in cross-platform testing there is a Vagrantfile for Linux and BSD.
Notice: fsnotify file system events won't trigger in shared folders. The tests get around this limitation by using the /tmp directory.
-Right now there is no equivalent solution for Windows and macOS, but there are Windows VMs [freely available from Microsoft](http://www.modern.ie/en-us/virtualization-tools#downloads).
+Right now there is no equivalent solution for Windows and OS X, but there are Windows VMs [freely available from Microsoft](http://www.modern.ie/en-us/virtualization-tools#downloads).
### Maintainers
diff --git a/vendor/github.com/fsnotify/fsnotify/README.md b/vendor/github.com/fsnotify/fsnotify/README.md
index 399320741..3c891e349 100644
--- a/vendor/github.com/fsnotify/fsnotify/README.md
+++ b/vendor/github.com/fsnotify/fsnotify/README.md
@@ -8,14 +8,14 @@ fsnotify utilizes [golang.org/x/sys](https://godoc.org/golang.org/x/sys) rather
go get -u golang.org/x/sys/...
```
-Cross platform: Windows, Linux, BSD and macOS.
+Cross platform: Windows, Linux, BSD and OS X.
|Adapter |OS |Status |
|----------|----------|----------|
|inotify |Linux 2.6.27 or later, Android\*|Supported [![Build Status](https://travis-ci.org/fsnotify/fsnotify.svg?branch=master)](https://travis-ci.org/fsnotify/fsnotify)|
-|kqueue |BSD, macOS, iOS\*|Supported [![Build Status](https://travis-ci.org/fsnotify/fsnotify.svg?branch=master)](https://travis-ci.org/fsnotify/fsnotify)|
+|kqueue |BSD, OS X, iOS\*|Supported [![Build Status](https://travis-ci.org/fsnotify/fsnotify.svg?branch=master)](https://travis-ci.org/fsnotify/fsnotify)|
|ReadDirectoryChangesW|Windows|Supported [![Build status](https://ci.appveyor.com/api/projects/status/ivwjubaih4r0udeh/branch/master?svg=true)](https://ci.appveyor.com/project/NathanYoungman/fsnotify/branch/master)|
-|FSEvents |macOS |[Planned](https://github.com/fsnotify/fsnotify/issues/11)|
+|FSEvents |OS X |[Planned](https://github.com/fsnotify/fsnotify/issues/11)|
|FEN |Solaris 11 |[In Progress](https://github.com/fsnotify/fsnotify/issues/12)|
|fanotify |Linux 2.6.37+ | |
|USN Journals |Windows |[Maybe](https://github.com/fsnotify/fsnotify/issues/53)|
@@ -23,7 +23,7 @@ Cross platform: Windows, Linux, BSD and macOS.
\* Android and iOS are untested.
-Please see [the documentation](https://godoc.org/github.com/fsnotify/fsnotify) and consult the [FAQ](#faq) for usage information.
+Please see [the documentation](https://godoc.org/github.com/fsnotify/fsnotify) for usage. Consult the [Wiki](https://github.com/fsnotify/fsnotify/wiki) for the FAQ and further information.
## API stability
@@ -41,35 +41,6 @@ Please refer to [CONTRIBUTING][] before opening an issue or pull request.
See [example_test.go](https://github.com/fsnotify/fsnotify/blob/master/example_test.go).
-## FAQ
-
-**When a file is moved to another directory is it still being watched?**
-
-No (it shouldn't be, unless you are watching where it was moved to).
-
-**When I watch a directory, are all subdirectories watched as well?**
-
-No, you must add watches for any directory you want to watch (a recursive watcher is on the roadmap [#18][]).
-
-**Do I have to watch the Error and Event channels in a separate goroutine?**
-
-As of now, yes. Looking into making this single-thread friendly (see [howeyc #7][#7])
-
-**Why am I receiving multiple events for the same file on OS X?**
-
-Spotlight indexing on OS X can result in multiple events (see [howeyc #62][#62]). A temporary workaround is to add your folder(s) to the *Spotlight Privacy settings* until we have a native FSEvents implementation (see [#11][]).
-
-**How many files can be watched at once?**
-
-There are OS-specific limits as to how many watches can be created:
-* Linux: /proc/sys/fs/inotify/max_user_watches contains the limit, reaching this limit results in a "no space left on device" error.
-* BSD / OSX: sysctl variables "kern.maxfiles" and "kern.maxfilesperproc", reaching these limits results in a "too many open files" error.
-
-[#62]: https://github.com/howeyc/fsnotify/issues/62
-[#18]: https://github.com/fsnotify/fsnotify/issues/18
-[#11]: https://github.com/fsnotify/fsnotify/issues/11
-[#7]: https://github.com/howeyc/fsnotify/issues/7
-
[contributing]: https://github.com/fsnotify/fsnotify/blob/master/CONTRIBUTING.md
## Related Projects
diff --git a/vendor/github.com/fsnotify/fsnotify/fsnotify.go b/vendor/github.com/fsnotify/fsnotify/fsnotify.go
index 190bf0de5..e7f55fee7 100644
--- a/vendor/github.com/fsnotify/fsnotify/fsnotify.go
+++ b/vendor/github.com/fsnotify/fsnotify/fsnotify.go
@@ -9,7 +9,6 @@ package fsnotify
import (
"bytes"
- "errors"
"fmt"
)
@@ -61,6 +60,3 @@ func (op Op) String() string {
func (e Event) String() string {
return fmt.Sprintf("%q: %s", e.Name, e.Op.String())
}
-
-// Common errors that can be reported by a watcher
-var ErrEventOverflow = errors.New("fsnotify queue overflow")
diff --git a/vendor/github.com/fsnotify/fsnotify/inotify.go b/vendor/github.com/fsnotify/fsnotify/inotify.go
index d9fd1b88a..f3b74c51f 100644
--- a/vendor/github.com/fsnotify/fsnotify/inotify.go
+++ b/vendor/github.com/fsnotify/fsnotify/inotify.go
@@ -24,6 +24,7 @@ type Watcher struct {
Events chan Event
Errors chan error
mu sync.Mutex // Map access
+ cv *sync.Cond // sync removing on rm_watch with IN_IGNORE
fd int
poller *fdPoller
watches map[string]*watch // Map of inotify watches (key: path)
@@ -55,6 +56,7 @@ func NewWatcher() (*Watcher, error) {
done: make(chan struct{}),
doneResp: make(chan struct{}),
}
+ w.cv = sync.NewCond(&w.mu)
go w.readEvents()
return w, nil
@@ -101,23 +103,21 @@ func (w *Watcher) Add(name string) error {
var flags uint32 = agnosticEvents
w.mu.Lock()
- defer w.mu.Unlock()
- watchEntry := w.watches[name]
- if watchEntry != nil {
- flags |= watchEntry.flags | unix.IN_MASK_ADD
+ watchEntry, found := w.watches[name]
+ w.mu.Unlock()
+ if found {
+ watchEntry.flags |= flags
+ flags |= unix.IN_MASK_ADD
}
wd, errno := unix.InotifyAddWatch(w.fd, name, flags)
if wd == -1 {
return errno
}
- if watchEntry == nil {
- w.watches[name] = &watch{wd: uint32(wd), flags: flags}
- w.paths[wd] = name
- } else {
- watchEntry.wd = uint32(wd)
- watchEntry.flags = flags
- }
+ w.mu.Lock()
+ w.watches[name] = &watch{wd: uint32(wd), flags: flags}
+ w.paths[wd] = name
+ w.mu.Unlock()
return nil
}
@@ -135,13 +135,6 @@ func (w *Watcher) Remove(name string) error {
if !ok {
return fmt.Errorf("can't remove non-existent inotify watch for: %s", name)
}
-
- // We successfully removed the watch if InotifyRmWatch doesn't return an
- // error, we need to clean up our internal state to ensure it matches
- // inotify's kernel state.
- delete(w.paths, int(watch.wd))
- delete(w.watches, name)
-
// inotify_rm_watch will return EINVAL if the file has been deleted;
// the inotify will already have been removed.
// watches and pathes are deleted in ignoreLinux() implicitly and asynchronously
@@ -159,6 +152,13 @@ func (w *Watcher) Remove(name string) error {
return errno
}
+ // wait until ignoreLinux() deleting maps
+ exists := true
+ for exists {
+ w.cv.Wait()
+ _, exists = w.watches[name]
+ }
+
return nil
}
@@ -245,31 +245,13 @@ func (w *Watcher) readEvents() {
mask := uint32(raw.Mask)
nameLen := uint32(raw.Len)
-
- if mask&unix.IN_Q_OVERFLOW != 0 {
- select {
- case w.Errors <- ErrEventOverflow:
- case <-w.done:
- return
- }
- }
-
// If the event happened to the watched directory or the watched file, the kernel
// doesn't append the filename to the event, but we would like to always fill the
// the "Name" field with a valid filename. We retrieve the path of the watch from
// the "paths" map.
w.mu.Lock()
- name, ok := w.paths[int(raw.Wd)]
- // IN_DELETE_SELF occurs when the file/directory being watched is removed.
- // This is a sign to clean up the maps, otherwise we are no longer in sync
- // with the inotify kernel state which has already deleted the watch
- // automatically.
- if ok && mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF {
- delete(w.paths, int(raw.Wd))
- delete(w.watches, name)
- }
+ name := w.paths[int(raw.Wd)]
w.mu.Unlock()
-
if nameLen > 0 {
// Point "bytes" at the first byte of the filename
bytes := (*[unix.PathMax]byte)(unsafe.Pointer(&buf[offset+unix.SizeofInotifyEvent]))
@@ -280,7 +262,7 @@ func (w *Watcher) readEvents() {
event := newEvent(name, mask)
// Send the events that are not ignored on the events channel
- if !event.ignoreLinux(mask) {
+ if !event.ignoreLinux(w, raw.Wd, mask) {
select {
case w.Events <- event:
case <-w.done:
@@ -297,9 +279,15 @@ func (w *Watcher) readEvents() {
// Certain types of events can be "ignored" and not sent over the Events
// channel. Such as events marked ignore by the kernel, or MODIFY events
// against files that do not exist.
-func (e *Event) ignoreLinux(mask uint32) bool {
+func (e *Event) ignoreLinux(w *Watcher, wd int32, mask uint32) bool {
// Ignore anything the inotify API says to ignore
if mask&unix.IN_IGNORED == unix.IN_IGNORED {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ name := w.paths[int(wd)]
+ delete(w.paths, int(wd))
+ delete(w.watches, name)
+ w.cv.Broadcast()
return true
}
diff --git a/vendor/github.com/fsnotify/fsnotify/inotify_test.go b/vendor/github.com/fsnotify/fsnotify/inotify_test.go
index 2cc6d93d2..a4bb202d1 100644
--- a/vendor/github.com/fsnotify/fsnotify/inotify_test.go
+++ b/vendor/github.com/fsnotify/fsnotify/inotify_test.go
@@ -293,23 +293,25 @@ func TestInotifyRemoveTwice(t *testing.T) {
t.Fatalf("Failed to add testFile: %v", err)
}
- err = w.Remove(testFile)
+ err = os.Remove(testFile)
if err != nil {
- t.Fatalf("wanted successful remove but got:", err)
+ t.Fatalf("Failed to remove testFile: %v", err)
}
err = w.Remove(testFile)
if err == nil {
t.Fatalf("no error on removing invalid file")
}
+ s1 := fmt.Sprintf("%s", err)
- w.mu.Lock()
- defer w.mu.Unlock()
- if len(w.watches) != 0 {
- t.Fatalf("Expected watches len is 0, but got: %d, %v", len(w.watches), w.watches)
+ err = w.Remove(testFile)
+ if err == nil {
+ t.Fatalf("no error on removing invalid file")
}
- if len(w.paths) != 0 {
- t.Fatalf("Expected paths len is 0, but got: %d, %v", len(w.paths), w.paths)
+ s2 := fmt.Sprintf("%s", err)
+
+ if s1 != s2 {
+ t.Fatalf("receive different error - %s / %s", s1, s2)
}
}
@@ -356,94 +358,3 @@ func TestInotifyInnerMapLength(t *testing.T) {
t.Fatalf("Expected paths len is 0, but got: %d, %v", len(w.paths), w.paths)
}
}
-
-func TestInotifyOverflow(t *testing.T) {
- // We need to generate many more events than the
- // fs.inotify.max_queued_events sysctl setting.
- // We use multiple goroutines (one per directory)
- // to speed up file creation.
- numDirs := 128
- numFiles := 1024
-
- testDir := tempMkdir(t)
- defer os.RemoveAll(testDir)
-
- w, err := NewWatcher()
- if err != nil {
- t.Fatalf("Failed to create watcher: %v", err)
- }
- defer w.Close()
-
- for dn := 0; dn < numDirs; dn++ {
- testSubdir := fmt.Sprintf("%s/%d", testDir, dn)
-
- err := os.Mkdir(testSubdir, 0777)
- if err != nil {
- t.Fatalf("Cannot create subdir: %v", err)
- }
-
- err = w.Add(testSubdir)
- if err != nil {
- t.Fatalf("Failed to add subdir: %v", err)
- }
- }
-
- errChan := make(chan error, numDirs*numFiles)
-
- for dn := 0; dn < numDirs; dn++ {
- testSubdir := fmt.Sprintf("%s/%d", testDir, dn)
-
- go func() {
- for fn := 0; fn < numFiles; fn++ {
- testFile := fmt.Sprintf("%s/%d", testSubdir, fn)
-
- handle, err := os.Create(testFile)
- if err != nil {
- errChan <- fmt.Errorf("Create failed: %v", err)
- continue
- }
-
- err = handle.Close()
- if err != nil {
- errChan <- fmt.Errorf("Close failed: %v", err)
- continue
- }
- }
- }()
- }
-
- creates := 0
- overflows := 0
-
- after := time.After(10 * time.Second)
- for overflows == 0 && creates < numDirs*numFiles {
- select {
- case <-after:
- t.Fatalf("Not done")
- case err := <-errChan:
- t.Fatalf("Got an error from file creator goroutine: %v", err)
- case err := <-w.Errors:
- if err == ErrEventOverflow {
- overflows++
- } else {
- t.Fatalf("Got an error from watcher: %v", err)
- }
- case evt := <-w.Events:
- if !strings.HasPrefix(evt.Name, testDir) {
- t.Fatalf("Got an event for an unknown file: %s", evt.Name)
- }
- if evt.Op == Create {
- creates++
- }
- }
- }
-
- if creates == numDirs*numFiles {
- t.Fatalf("Could not trigger overflow")
- }
-
- if overflows == 0 {
- t.Fatalf("No overflow and not enough creates (expected %d, got %d)",
- numDirs*numFiles, creates)
- }
-}
diff --git a/vendor/github.com/fsnotify/fsnotify/integration_darwin_test.go b/vendor/github.com/fsnotify/fsnotify/integration_darwin_test.go
index cd6adc273..5564554f7 100644
--- a/vendor/github.com/fsnotify/fsnotify/integration_darwin_test.go
+++ b/vendor/github.com/fsnotify/fsnotify/integration_darwin_test.go
@@ -13,9 +13,9 @@ import (
"golang.org/x/sys/unix"
)
-// testExchangedataForWatcher tests the watcher with the exchangedata operation on macOS.
+// testExchangedataForWatcher tests the watcher with the exchangedata operation on OS X.
//
-// This is widely used for atomic saves on macOS, e.g. TextMate and in Apple's NSDocument.
+// This is widely used for atomic saves on OS X, e.g. TextMate and in Apple's NSDocument.
//
// See https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man2/exchangedata.2.html
// Also see: https://github.com/textmate/textmate/blob/cd016be29489eba5f3c09b7b70b06da134dda550/Frameworks/io/src/swap_file_data.cc#L20
diff --git a/vendor/github.com/go-ini/ini/.gitignore b/vendor/github.com/go-ini/ini/.gitignore
deleted file mode 100644
index c5203bf6e..000000000
--- a/vendor/github.com/go-ini/ini/.gitignore
+++ /dev/null
@@ -1,5 +0,0 @@
-testdata/conf_out.ini
-ini.sublime-project
-ini.sublime-workspace
-testdata/conf_reflect.ini
-.idea
diff --git a/vendor/github.com/go-ini/ini/.travis.yml b/vendor/github.com/go-ini/ini/.travis.yml
deleted file mode 100644
index 65c872bad..000000000
--- a/vendor/github.com/go-ini/ini/.travis.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-sudo: false
-language: go
-go:
- - 1.4.x
- - 1.5.x
- - 1.6.x
- - 1.7.x
- - master
-
-script:
- - go get golang.org/x/tools/cmd/cover
- - go get github.com/smartystreets/goconvey
- - go test -v -cover -race
-
-notifications:
- email:
- - u@gogs.io
diff --git a/vendor/github.com/go-ini/ini/LICENSE b/vendor/github.com/go-ini/ini/LICENSE
deleted file mode 100644
index 37ec93a14..000000000
--- a/vendor/github.com/go-ini/ini/LICENSE
+++ /dev/null
@@ -1,191 +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:
-
-You must give any other recipients of the Work or Derivative Works a copy of
-this License; and
-You must cause any modified files to carry prominent notices stating that You
-changed the files; and
-You must retain, in the Source form of any Derivative Works that You distribute,
-all copyright, patent, trademark, and attribution notices from the Source form
-of the Work, excluding those notices that do not pertain to any part of the
-Derivative Works; and
-If the Work includes a "NOTICE" text file as part of its distribution, then any
-Derivative Works that You distribute must include a readable copy of the
-attribution notices contained within such NOTICE file, excluding those notices
-that do not pertain to any part of the Derivative Works, in at least one of the
-following places: within a NOTICE text file distributed as part of the
-Derivative Works; within the Source form or documentation, if provided along
-with the Derivative Works; or, within a display generated by the Derivative
-Works, if and wherever such third-party notices normally appear. The contents of
-the NOTICE file are for informational purposes only and do not modify the
-License. You may add Your own attribution notices within Derivative Works that
-You distribute, alongside or as an addendum to the NOTICE text from the Work,
-provided that such additional attribution notices cannot be construed as
-modifying the License.
-You may add Your own copyright statement to Your modifications and may provide
-additional or different license terms and conditions for use, reproduction, or
-distribution of Your modifications, or for any such Derivative Works as a whole,
-provided Your use, reproduction, and distribution of the Work otherwise complies
-with the conditions stated in this License.
-
-5. Submission of Contributions.
-
-Unless You explicitly state otherwise, any Contribution intentionally submitted
-for inclusion in the Work by You to the Licensor shall be under the terms and
-conditions of this License, without any additional terms or conditions.
-Notwithstanding the above, nothing herein shall supersede or modify the terms of
-any separate license agreement you may have executed with Licensor regarding
-such Contributions.
-
-6. Trademarks.
-
-This License does not grant permission to use the trade names, trademarks,
-service marks, or product names of the Licensor, except as required for
-reasonable and customary use in describing the origin of the Work and
-reproducing the content of the NOTICE file.
-
-7. Disclaimer of Warranty.
-
-Unless required by applicable law or agreed to in writing, Licensor provides the
-Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
-including, without limitation, any warranties or conditions of TITLE,
-NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
-solely responsible for determining the appropriateness of using or
-redistributing the Work and assume any risks associated with Your exercise of
-permissions under this License.
-
-8. Limitation of Liability.
-
-In no event and under no legal theory, whether in tort (including negligence),
-contract, or otherwise, unless required by applicable law (such as deliberate
-and grossly negligent acts) or agreed to in writing, shall any Contributor be
-liable to You for damages, including any direct, indirect, special, incidental,
-or consequential damages of any character arising as a result of this License or
-out of the use or inability to use the Work (including but not limited to
-damages for loss of goodwill, work stoppage, computer failure or malfunction, or
-any and all other commercial damages or losses), even if such Contributor has
-been advised of the possibility of such damages.
-
-9. Accepting Warranty or Additional Liability.
-
-While redistributing the Work or Derivative Works thereof, You may choose to
-offer, and charge a fee for, acceptance of support, warranty, indemnity, or
-other liability obligations and/or rights consistent with this License. However,
-in accepting such obligations, You may act only on Your own behalf and on Your
-sole responsibility, not on behalf of any other Contributor, and only if You
-agree to indemnify, defend, and hold each Contributor harmless for any liability
-incurred by, or claims asserted against, such Contributor by reason of your
-accepting any such warranty or additional liability.
-
-END OF TERMS AND CONDITIONS
-
-APPENDIX: How to apply the Apache License to your work
-
-To apply the Apache License to your work, attach the following boilerplate
-notice, with the fields enclosed by brackets "[]" replaced with your own
-identifying information. (Don't include the brackets!) The text should be
-enclosed in the appropriate comment syntax for the file format. We also
-recommend that a file or class name and description of purpose be included on
-the same "printed page" as the copyright notice for easier identification within
-third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
diff --git a/vendor/github.com/go-ini/ini/Makefile b/vendor/github.com/go-ini/ini/Makefile
deleted file mode 100644
index ac034e525..000000000
--- a/vendor/github.com/go-ini/ini/Makefile
+++ /dev/null
@@ -1,12 +0,0 @@
-.PHONY: build test bench vet
-
-build: vet bench
-
-test:
- go test -v -cover -race
-
-bench:
- go test -v -cover -race -test.bench=. -test.benchmem
-
-vet:
- go vet
diff --git a/vendor/github.com/go-ini/ini/README.md b/vendor/github.com/go-ini/ini/README.md
deleted file mode 100644
index 85947422d..000000000
--- a/vendor/github.com/go-ini/ini/README.md
+++ /dev/null
@@ -1,740 +0,0 @@
-INI [![Build Status](https://travis-ci.org/go-ini/ini.svg?branch=master)](https://travis-ci.org/go-ini/ini) [![Sourcegraph](https://sourcegraph.com/github.com/go-ini/ini/-/badge.svg)](https://sourcegraph.com/github.com/go-ini/ini?badge)
-===
-
-![](https://avatars0.githubusercontent.com/u/10216035?v=3&s=200)
-
-Package ini provides INI file read and write functionality in Go.
-
-[简体中文](README_ZH.md)
-
-## Feature
-
-- Load multiple data sources(`[]byte`, file and `io.ReadCloser`) with overwrites.
-- Read with recursion values.
-- Read with parent-child sections.
-- Read with auto-increment key names.
-- Read with multiple-line values.
-- Read with tons of helper methods.
-- Read and convert values to Go types.
-- Read and **WRITE** comments of sections and keys.
-- Manipulate sections, keys and comments with ease.
-- Keep sections and keys in order as you parse and save.
-
-## Installation
-
-To use a tagged revision:
-
- go get gopkg.in/ini.v1
-
-To use with latest changes:
-
- go get github.com/go-ini/ini
-
-Please add `-u` flag to update in the future.
-
-### Testing
-
-If you want to test on your machine, please apply `-t` flag:
-
- go get -t gopkg.in/ini.v1
-
-Please add `-u` flag to update in the future.
-
-## Getting Started
-
-### Loading from data sources
-
-A **Data Source** is either raw data in type `[]byte`, a file name with type `string` or `io.ReadCloser`. You can load **as many data sources as you want**. Passing other types will simply return an error.
-
-```go
-cfg, err := ini.Load([]byte("raw data"), "filename", ioutil.NopCloser(bytes.NewReader([]byte("some other data"))))
-```
-
-Or start with an empty object:
-
-```go
-cfg := ini.Empty()
-```
-
-When you cannot decide how many data sources to load at the beginning, you will still be able to **Append()** them later.
-
-```go
-err := cfg.Append("other file", []byte("other raw data"))
-```
-
-If you have a list of files with possibilities that some of them may not available at the time, and you don't know exactly which ones, you can use `LooseLoad` to ignore nonexistent files without returning error.
-
-```go
-cfg, err := ini.LooseLoad("filename", "filename_404")
-```
-
-The cool thing is, whenever the file is available to load while you're calling `Reload` method, it will be counted as usual.
-
-#### Ignore cases of key name
-
-When you do not care about cases of section and key names, you can use `InsensitiveLoad` to force all names to be lowercased while parsing.
-
-```go
-cfg, err := ini.InsensitiveLoad("filename")
-//...
-
-// sec1 and sec2 are the exactly same section object
-sec1, err := cfg.GetSection("Section")
-sec2, err := cfg.GetSection("SecTIOn")
-
-// key1 and key2 are the exactly same key object
-key1, err := cfg.GetKey("Key")
-key2, err := cfg.GetKey("KeY")
-```
-
-#### MySQL-like boolean key
-
-MySQL's configuration allows a key without value as follows:
-
-```ini
-[mysqld]
-...
-skip-host-cache
-skip-name-resolve
-```
-
-By default, this is considered as missing value. But if you know you're going to deal with those cases, you can assign advanced load options:
-
-```go
-cfg, err := LoadSources(LoadOptions{AllowBooleanKeys: true}, "my.cnf"))
-```
-
-The value of those keys are always `true`, and when you save to a file, it will keep in the same foramt as you read.
-
-To generate such keys in your program, you could use `NewBooleanKey`:
-
-```go
-key, err := sec.NewBooleanKey("skip-host-cache")
-```
-
-#### Comment
-
-Take care that following format will be treated as comment:
-
-1. Line begins with `#` or `;`
-2. Words after `#` or `;`
-3. Words after section name (i.e words after `[some section name]`)
-
-If you want to save a value with `#` or `;`, please quote them with ``` ` ``` or ``` """ ```.
-
-### Working with sections
-
-To get a section, you would need to:
-
-```go
-section, err := cfg.GetSection("section name")
-```
-
-For a shortcut for default section, just give an empty string as name:
-
-```go
-section, err := cfg.GetSection("")
-```
-
-When you're pretty sure the section exists, following code could make your life easier:
-
-```go
-section := cfg.Section("section name")
-```
-
-What happens when the section somehow does not exist? Don't panic, it automatically creates and returns a new section to you.
-
-To create a new section:
-
-```go
-err := cfg.NewSection("new section")
-```
-
-To get a list of sections or section names:
-
-```go
-sections := cfg.Sections()
-names := cfg.SectionStrings()
-```
-
-### Working with keys
-
-To get a key under a section:
-
-```go
-key, err := cfg.Section("").GetKey("key name")
-```
-
-Same rule applies to key operations:
-
-```go
-key := cfg.Section("").Key("key name")
-```
-
-To check if a key exists:
-
-```go
-yes := cfg.Section("").HasKey("key name")
-```
-
-To create a new key:
-
-```go
-err := cfg.Section("").NewKey("name", "value")
-```
-
-To get a list of keys or key names:
-
-```go
-keys := cfg.Section("").Keys()
-names := cfg.Section("").KeyStrings()
-```
-
-To get a clone hash of keys and corresponding values:
-
-```go
-hash := cfg.Section("").KeysHash()
-```
-
-### Working with values
-
-To get a string value:
-
-```go
-val := cfg.Section("").Key("key name").String()
-```
-
-To validate key value on the fly:
-
-```go
-val := cfg.Section("").Key("key name").Validate(func(in string) string {
- if len(in) == 0 {
- return "default"
- }
- return in
-})
-```
-
-If you do not want any auto-transformation (such as recursive read) for the values, you can get raw value directly (this way you get much better performance):
-
-```go
-val := cfg.Section("").Key("key name").Value()
-```
-
-To check if raw value exists:
-
-```go
-yes := cfg.Section("").HasValue("test value")
-```
-
-To get value with types:
-
-```go
-// For boolean values:
-// true when value is: 1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On
-// false when value is: 0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off
-v, err = cfg.Section("").Key("BOOL").Bool()
-v, err = cfg.Section("").Key("FLOAT64").Float64()
-v, err = cfg.Section("").Key("INT").Int()
-v, err = cfg.Section("").Key("INT64").Int64()
-v, err = cfg.Section("").Key("UINT").Uint()
-v, err = cfg.Section("").Key("UINT64").Uint64()
-v, err = cfg.Section("").Key("TIME").TimeFormat(time.RFC3339)
-v, err = cfg.Section("").Key("TIME").Time() // RFC3339
-
-v = cfg.Section("").Key("BOOL").MustBool()
-v = cfg.Section("").Key("FLOAT64").MustFloat64()
-v = cfg.Section("").Key("INT").MustInt()
-v = cfg.Section("").Key("INT64").MustInt64()
-v = cfg.Section("").Key("UINT").MustUint()
-v = cfg.Section("").Key("UINT64").MustUint64()
-v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339)
-v = cfg.Section("").Key("TIME").MustTime() // RFC3339
-
-// Methods start with Must also accept one argument for default value
-// when key not found or fail to parse value to given type.
-// Except method MustString, which you have to pass a default value.
-
-v = cfg.Section("").Key("String").MustString("default")
-v = cfg.Section("").Key("BOOL").MustBool(true)
-v = cfg.Section("").Key("FLOAT64").MustFloat64(1.25)
-v = cfg.Section("").Key("INT").MustInt(10)
-v = cfg.Section("").Key("INT64").MustInt64(99)
-v = cfg.Section("").Key("UINT").MustUint(3)
-v = cfg.Section("").Key("UINT64").MustUint64(6)
-v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339, time.Now())
-v = cfg.Section("").Key("TIME").MustTime(time.Now()) // RFC3339
-```
-
-What if my value is three-line long?
-
-```ini
-[advance]
-ADDRESS = """404 road,
-NotFound, State, 5000
-Earth"""
-```
-
-Not a problem!
-
-```go
-cfg.Section("advance").Key("ADDRESS").String()
-
-/* --- start ---
-404 road,
-NotFound, State, 5000
-Earth
------- end --- */
-```
-
-That's cool, how about continuation lines?
-
-```ini
-[advance]
-two_lines = how about \
- continuation lines?
-lots_of_lines = 1 \
- 2 \
- 3 \
- 4
-```
-
-Piece of cake!
-
-```go
-cfg.Section("advance").Key("two_lines").String() // how about continuation lines?
-cfg.Section("advance").Key("lots_of_lines").String() // 1 2 3 4
-```
-
-Well, I hate continuation lines, how do I disable that?
-
-```go
-cfg, err := ini.LoadSources(ini.LoadOptions{
- IgnoreContinuation: true,
-}, "filename")
-```
-
-Holy crap!
-
-Note that single quotes around values will be stripped:
-
-```ini
-foo = "some value" // foo: some value
-bar = 'some value' // bar: some value
-```
-
-That's all? Hmm, no.
-
-#### Helper methods of working with values
-
-To get value with given candidates:
-
-```go
-v = cfg.Section("").Key("STRING").In("default", []string{"str", "arr", "types"})
-v = cfg.Section("").Key("FLOAT64").InFloat64(1.1, []float64{1.25, 2.5, 3.75})
-v = cfg.Section("").Key("INT").InInt(5, []int{10, 20, 30})
-v = cfg.Section("").Key("INT64").InInt64(10, []int64{10, 20, 30})
-v = cfg.Section("").Key("UINT").InUint(4, []int{3, 6, 9})
-v = cfg.Section("").Key("UINT64").InUint64(8, []int64{3, 6, 9})
-v = cfg.Section("").Key("TIME").InTimeFormat(time.RFC3339, time.Now(), []time.Time{time1, time2, time3})
-v = cfg.Section("").Key("TIME").InTime(time.Now(), []time.Time{time1, time2, time3}) // RFC3339
-```
-
-Default value will be presented if value of key is not in candidates you given, and default value does not need be one of candidates.
-
-To validate value in a given range:
-
-```go
-vals = cfg.Section("").Key("FLOAT64").RangeFloat64(0.0, 1.1, 2.2)
-vals = cfg.Section("").Key("INT").RangeInt(0, 10, 20)
-vals = cfg.Section("").Key("INT64").RangeInt64(0, 10, 20)
-vals = cfg.Section("").Key("UINT").RangeUint(0, 3, 9)
-vals = cfg.Section("").Key("UINT64").RangeUint64(0, 3, 9)
-vals = cfg.Section("").Key("TIME").RangeTimeFormat(time.RFC3339, time.Now(), minTime, maxTime)
-vals = cfg.Section("").Key("TIME").RangeTime(time.Now(), minTime, maxTime) // RFC3339
-```
-
-##### Auto-split values into a slice
-
-To use zero value of type for invalid inputs:
-
-```go
-// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4]
-// Input: how, 2.2, are, you -> [0.0 2.2 0.0 0.0]
-vals = cfg.Section("").Key("STRINGS").Strings(",")
-vals = cfg.Section("").Key("FLOAT64S").Float64s(",")
-vals = cfg.Section("").Key("INTS").Ints(",")
-vals = cfg.Section("").Key("INT64S").Int64s(",")
-vals = cfg.Section("").Key("UINTS").Uints(",")
-vals = cfg.Section("").Key("UINT64S").Uint64s(",")
-vals = cfg.Section("").Key("TIMES").Times(",")
-```
-
-To exclude invalid values out of result slice:
-
-```go
-// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4]
-// Input: how, 2.2, are, you -> [2.2]
-vals = cfg.Section("").Key("FLOAT64S").ValidFloat64s(",")
-vals = cfg.Section("").Key("INTS").ValidInts(",")
-vals = cfg.Section("").Key("INT64S").ValidInt64s(",")
-vals = cfg.Section("").Key("UINTS").ValidUints(",")
-vals = cfg.Section("").Key("UINT64S").ValidUint64s(",")
-vals = cfg.Section("").Key("TIMES").ValidTimes(",")
-```
-
-Or to return nothing but error when have invalid inputs:
-
-```go
-// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4]
-// Input: how, 2.2, are, you -> error
-vals = cfg.Section("").Key("FLOAT64S").StrictFloat64s(",")
-vals = cfg.Section("").Key("INTS").StrictInts(",")
-vals = cfg.Section("").Key("INT64S").StrictInt64s(",")
-vals = cfg.Section("").Key("UINTS").StrictUints(",")
-vals = cfg.Section("").Key("UINT64S").StrictUint64s(",")
-vals = cfg.Section("").Key("TIMES").StrictTimes(",")
-```
-
-### Save your configuration
-
-Finally, it's time to save your configuration to somewhere.
-
-A typical way to save configuration is writing it to a file:
-
-```go
-// ...
-err = cfg.SaveTo("my.ini")
-err = cfg.SaveToIndent("my.ini", "\t")
-```
-
-Another way to save is writing to a `io.Writer` interface:
-
-```go
-// ...
-cfg.WriteTo(writer)
-cfg.WriteToIndent(writer, "\t")
-```
-
-By default, spaces are used to align "=" sign between key and values, to disable that:
-
-```go
-ini.PrettyFormat = false
-```
-
-## Advanced Usage
-
-### Recursive Values
-
-For all value of keys, there is a special syntax `%(<name>)s`, where `<name>` is the key name in same section or default section, and `%(<name>)s` will be replaced by corresponding value(empty string if key not found). You can use this syntax at most 99 level of recursions.
-
-```ini
-NAME = ini
-
-[author]
-NAME = Unknwon
-GITHUB = https://github.com/%(NAME)s
-
-[package]
-FULL_NAME = github.com/go-ini/%(NAME)s
-```
-
-```go
-cfg.Section("author").Key("GITHUB").String() // https://github.com/Unknwon
-cfg.Section("package").Key("FULL_NAME").String() // github.com/go-ini/ini
-```
-
-### Parent-child Sections
-
-You can use `.` in section name to indicate parent-child relationship between two or more sections. If the key not found in the child section, library will try again on its parent section until there is no parent section.
-
-```ini
-NAME = ini
-VERSION = v1
-IMPORT_PATH = gopkg.in/%(NAME)s.%(VERSION)s
-
-[package]
-CLONE_URL = https://%(IMPORT_PATH)s
-
-[package.sub]
-```
-
-```go
-cfg.Section("package.sub").Key("CLONE_URL").String() // https://gopkg.in/ini.v1
-```
-
-#### Retrieve parent keys available to a child section
-
-```go
-cfg.Section("package.sub").ParentKeys() // ["CLONE_URL"]
-```
-
-### Unparseable Sections
-
-Sometimes, you have sections that do not contain key-value pairs but raw content, to handle such case, you can use `LoadOptions.UnparsableSections`:
-
-```go
-cfg, err := LoadSources(LoadOptions{UnparseableSections: []string{"COMMENTS"}}, `[COMMENTS]
-<1><L.Slide#2> This slide has the fuel listed in the wrong units <e.1>`))
-
-body := cfg.Section("COMMENTS").Body()
-
-/* --- start ---
-<1><L.Slide#2> This slide has the fuel listed in the wrong units <e.1>
------- end --- */
-```
-
-### Auto-increment Key Names
-
-If key name is `-` in data source, then it would be seen as special syntax for auto-increment key name start from 1, and every section is independent on counter.
-
-```ini
-[features]
--: Support read/write comments of keys and sections
--: Support auto-increment of key names
--: Support load multiple files to overwrite key values
-```
-
-```go
-cfg.Section("features").KeyStrings() // []{"#1", "#2", "#3"}
-```
-
-### Map To Struct
-
-Want more objective way to play with INI? Cool.
-
-```ini
-Name = Unknwon
-age = 21
-Male = true
-Born = 1993-01-01T20:17:05Z
-
-[Note]
-Content = Hi is a good man!
-Cities = HangZhou, Boston
-```
-
-```go
-type Note struct {
- Content string
- Cities []string
-}
-
-type Person struct {
- Name string
- Age int `ini:"age"`
- Male bool
- Born time.Time
- Note
- Created time.Time `ini:"-"`
-}
-
-func main() {
- cfg, err := ini.Load("path/to/ini")
- // ...
- p := new(Person)
- err = cfg.MapTo(p)
- // ...
-
- // Things can be simpler.
- err = ini.MapTo(p, "path/to/ini")
- // ...
-
- // Just map a section? Fine.
- n := new(Note)
- err = cfg.Section("Note").MapTo(n)
- // ...
-}
-```
-
-Can I have default value for field? Absolutely.
-
-Assign it before you map to struct. It will keep the value as it is if the key is not presented or got wrong type.
-
-```go
-// ...
-p := &Person{
- Name: "Joe",
-}
-// ...
-```
-
-It's really cool, but what's the point if you can't give me my file back from struct?
-
-### Reflect From Struct
-
-Why not?
-
-```go
-type Embeded struct {
- Dates []time.Time `delim:"|"`
- Places []string `ini:"places,omitempty"`
- None []int `ini:",omitempty"`
-}
-
-type Author struct {
- Name string `ini:"NAME"`
- Male bool
- Age int
- GPA float64
- NeverMind string `ini:"-"`
- *Embeded
-}
-
-func main() {
- a := &Author{"Unknwon", true, 21, 2.8, "",
- &Embeded{
- []time.Time{time.Now(), time.Now()},
- []string{"HangZhou", "Boston"},
- []int{},
- }}
- cfg := ini.Empty()
- err = ini.ReflectFrom(cfg, a)
- // ...
-}
-```
-
-So, what do I get?
-
-```ini
-NAME = Unknwon
-Male = true
-Age = 21
-GPA = 2.8
-
-[Embeded]
-Dates = 2015-08-07T22:14:22+08:00|2015-08-07T22:14:22+08:00
-places = HangZhou,Boston
-```
-
-#### Name Mapper
-
-To save your time and make your code cleaner, this library supports [`NameMapper`](https://gowalker.org/gopkg.in/ini.v1#NameMapper) between struct field and actual section and key name.
-
-There are 2 built-in name mappers:
-
-- `AllCapsUnderscore`: it converts to format `ALL_CAPS_UNDERSCORE` then match section or key.
-- `TitleUnderscore`: it converts to format `title_underscore` then match section or key.
-
-To use them:
-
-```go
-type Info struct {
- PackageName string
-}
-
-func main() {
- err = ini.MapToWithMapper(&Info{}, ini.TitleUnderscore, []byte("package_name=ini"))
- // ...
-
- cfg, err := ini.Load([]byte("PACKAGE_NAME=ini"))
- // ...
- info := new(Info)
- cfg.NameMapper = ini.AllCapsUnderscore
- err = cfg.MapTo(info)
- // ...
-}
-```
-
-Same rules of name mapper apply to `ini.ReflectFromWithMapper` function.
-
-#### Value Mapper
-
-To expand values (e.g. from environment variables), you can use the `ValueMapper` to transform values:
-
-```go
-type Env struct {
- Foo string `ini:"foo"`
-}
-
-func main() {
- cfg, err := ini.Load([]byte("[env]\nfoo = ${MY_VAR}\n")
- cfg.ValueMapper = os.ExpandEnv
- // ...
- env := &Env{}
- err = cfg.Section("env").MapTo(env)
-}
-```
-
-This would set the value of `env.Foo` to the value of the environment variable `MY_VAR`.
-
-#### Other Notes On Map/Reflect
-
-Any embedded struct is treated as a section by default, and there is no automatic parent-child relations in map/reflect feature:
-
-```go
-type Child struct {
- Age string
-}
-
-type Parent struct {
- Name string
- Child
-}
-
-type Config struct {
- City string
- Parent
-}
-```
-
-Example configuration:
-
-```ini
-City = Boston
-
-[Parent]
-Name = Unknwon
-
-[Child]
-Age = 21
-```
-
-What if, yes, I'm paranoid, I want embedded struct to be in the same section. Well, all roads lead to Rome.
-
-```go
-type Child struct {
- Age string
-}
-
-type Parent struct {
- Name string
- Child `ini:"Parent"`
-}
-
-type Config struct {
- City string
- Parent
-}
-```
-
-Example configuration:
-
-```ini
-City = Boston
-
-[Parent]
-Name = Unknwon
-Age = 21
-```
-
-## Getting Help
-
-- [API Documentation](https://gowalker.org/gopkg.in/ini.v1)
-- [File An Issue](https://github.com/go-ini/ini/issues/new)
-
-## FAQs
-
-### What does `BlockMode` field do?
-
-By default, library lets you read and write values so we need a locker to make sure your data is safe. But in cases that you are very sure about only reading data through the library, you can set `cfg.BlockMode = false` to speed up read operations about **50-70%** faster.
-
-### Why another INI library?
-
-Many people are using my another INI library [goconfig](https://github.com/Unknwon/goconfig), so the reason for this one is I would like to make more Go style code. Also when you set `cfg.BlockMode = false`, this one is about **10-30%** faster.
-
-To make those changes I have to confirm API broken, so it's safer to keep it in another place and start using `gopkg.in` to version my package at this time.(PS: shorter import path)
-
-## License
-
-This project is under Apache v2 License. See the [LICENSE](LICENSE) file for the full license text.
diff --git a/vendor/github.com/go-ini/ini/README_ZH.md b/vendor/github.com/go-ini/ini/README_ZH.md
deleted file mode 100644
index 163432db9..000000000
--- a/vendor/github.com/go-ini/ini/README_ZH.md
+++ /dev/null
@@ -1,727 +0,0 @@
-本包提供了 Go 语言中读写 INI 文件的功能。
-
-## 功能特性
-
-- 支持覆盖加载多个数据源(`[]byte`、文件和 `io.ReadCloser`)
-- 支持递归读取键值
-- 支持读取父子分区
-- 支持读取自增键名
-- 支持读取多行的键值
-- 支持大量辅助方法
-- 支持在读取时直接转换为 Go 语言类型
-- 支持读取和 **写入** 分区和键的注释
-- 轻松操作分区、键值和注释
-- 在保存文件时分区和键值会保持原有的顺序
-
-## 下载安装
-
-使用一个特定版本:
-
- go get gopkg.in/ini.v1
-
-使用最新版:
-
- go get github.com/go-ini/ini
-
-如需更新请添加 `-u` 选项。
-
-### 测试安装
-
-如果您想要在自己的机器上运行测试,请使用 `-t` 标记:
-
- go get -t gopkg.in/ini.v1
-
-如需更新请添加 `-u` 选项。
-
-## 开始使用
-
-### 从数据源加载
-
-一个 **数据源** 可以是 `[]byte` 类型的原始数据,`string` 类型的文件路径或 `io.ReadCloser`。您可以加载 **任意多个** 数据源。如果您传递其它类型的数据源,则会直接返回错误。
-
-```go
-cfg, err := ini.Load([]byte("raw data"), "filename", ioutil.NopCloser(bytes.NewReader([]byte("some other data"))))
-```
-
-或者从一个空白的文件开始:
-
-```go
-cfg := ini.Empty()
-```
-
-当您在一开始无法决定需要加载哪些数据源时,仍可以使用 **Append()** 在需要的时候加载它们。
-
-```go
-err := cfg.Append("other file", []byte("other raw data"))
-```
-
-当您想要加载一系列文件,但是不能够确定其中哪些文件是不存在的,可以通过调用函数 `LooseLoad` 来忽略它们(`Load` 会因为文件不存在而返回错误):
-
-```go
-cfg, err := ini.LooseLoad("filename", "filename_404")
-```
-
-更牛逼的是,当那些之前不存在的文件在重新调用 `Reload` 方法的时候突然出现了,那么它们会被正常加载。
-
-#### 忽略键名的大小写
-
-有时候分区和键的名称大小写混合非常烦人,这个时候就可以通过 `InsensitiveLoad` 将所有分区和键名在读取里强制转换为小写:
-
-```go
-cfg, err := ini.InsensitiveLoad("filename")
-//...
-
-// sec1 和 sec2 指向同一个分区对象
-sec1, err := cfg.GetSection("Section")
-sec2, err := cfg.GetSection("SecTIOn")
-
-// key1 和 key2 指向同一个键对象
-key1, err := cfg.GetKey("Key")
-key2, err := cfg.GetKey("KeY")
-```
-
-#### 类似 MySQL 配置中的布尔值键
-
-MySQL 的配置文件中会出现没有具体值的布尔类型的键:
-
-```ini
-[mysqld]
-...
-skip-host-cache
-skip-name-resolve
-```
-
-默认情况下这被认为是缺失值而无法完成解析,但可以通过高级的加载选项对它们进行处理:
-
-```go
-cfg, err := LoadSources(LoadOptions{AllowBooleanKeys: true}, "my.cnf"))
-```
-
-这些键的值永远为 `true`,且在保存到文件时也只会输出键名。
-
-如果您想要通过程序来生成此类键,则可以使用 `NewBooleanKey`:
-
-```go
-key, err := sec.NewBooleanKey("skip-host-cache")
-```
-
-#### 关于注释
-
-下述几种情况的内容将被视为注释:
-
-1. 所有以 `#` 或 `;` 开头的行
-2. 所有在 `#` 或 `;` 之后的内容
-3. 分区标签后的文字 (即 `[分区名]` 之后的内容)
-
-如果你希望使用包含 `#` 或 `;` 的值,请使用 ``` ` ``` 或 ``` """ ``` 进行包覆。
-
-### 操作分区(Section)
-
-获取指定分区:
-
-```go
-section, err := cfg.GetSection("section name")
-```
-
-如果您想要获取默认分区,则可以用空字符串代替分区名:
-
-```go
-section, err := cfg.GetSection("")
-```
-
-当您非常确定某个分区是存在的,可以使用以下简便方法:
-
-```go
-section := cfg.Section("section name")
-```
-
-如果不小心判断错了,要获取的分区其实是不存在的,那会发生什么呢?没事的,它会自动创建并返回一个对应的分区对象给您。
-
-创建一个分区:
-
-```go
-err := cfg.NewSection("new section")
-```
-
-获取所有分区对象或名称:
-
-```go
-sections := cfg.Sections()
-names := cfg.SectionStrings()
-```
-
-### 操作键(Key)
-
-获取某个分区下的键:
-
-```go
-key, err := cfg.Section("").GetKey("key name")
-```
-
-和分区一样,您也可以直接获取键而忽略错误处理:
-
-```go
-key := cfg.Section("").Key("key name")
-```
-
-判断某个键是否存在:
-
-```go
-yes := cfg.Section("").HasKey("key name")
-```
-
-创建一个新的键:
-
-```go
-err := cfg.Section("").NewKey("name", "value")
-```
-
-获取分区下的所有键或键名:
-
-```go
-keys := cfg.Section("").Keys()
-names := cfg.Section("").KeyStrings()
-```
-
-获取分区下的所有键值对的克隆:
-
-```go
-hash := cfg.Section("").KeysHash()
-```
-
-### 操作键值(Value)
-
-获取一个类型为字符串(string)的值:
-
-```go
-val := cfg.Section("").Key("key name").String()
-```
-
-获取值的同时通过自定义函数进行处理验证:
-
-```go
-val := cfg.Section("").Key("key name").Validate(func(in string) string {
- if len(in) == 0 {
- return "default"
- }
- return in
-})
-```
-
-如果您不需要任何对值的自动转变功能(例如递归读取),可以直接获取原值(这种方式性能最佳):
-
-```go
-val := cfg.Section("").Key("key name").Value()
-```
-
-判断某个原值是否存在:
-
-```go
-yes := cfg.Section("").HasValue("test value")
-```
-
-获取其它类型的值:
-
-```go
-// 布尔值的规则:
-// true 当值为:1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On
-// false 当值为:0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off
-v, err = cfg.Section("").Key("BOOL").Bool()
-v, err = cfg.Section("").Key("FLOAT64").Float64()
-v, err = cfg.Section("").Key("INT").Int()
-v, err = cfg.Section("").Key("INT64").Int64()
-v, err = cfg.Section("").Key("UINT").Uint()
-v, err = cfg.Section("").Key("UINT64").Uint64()
-v, err = cfg.Section("").Key("TIME").TimeFormat(time.RFC3339)
-v, err = cfg.Section("").Key("TIME").Time() // RFC3339
-
-v = cfg.Section("").Key("BOOL").MustBool()
-v = cfg.Section("").Key("FLOAT64").MustFloat64()
-v = cfg.Section("").Key("INT").MustInt()
-v = cfg.Section("").Key("INT64").MustInt64()
-v = cfg.Section("").Key("UINT").MustUint()
-v = cfg.Section("").Key("UINT64").MustUint64()
-v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339)
-v = cfg.Section("").Key("TIME").MustTime() // RFC3339
-
-// 由 Must 开头的方法名允许接收一个相同类型的参数来作为默认值,
-// 当键不存在或者转换失败时,则会直接返回该默认值。
-// 但是,MustString 方法必须传递一个默认值。
-
-v = cfg.Seciont("").Key("String").MustString("default")
-v = cfg.Section("").Key("BOOL").MustBool(true)
-v = cfg.Section("").Key("FLOAT64").MustFloat64(1.25)
-v = cfg.Section("").Key("INT").MustInt(10)
-v = cfg.Section("").Key("INT64").MustInt64(99)
-v = cfg.Section("").Key("UINT").MustUint(3)
-v = cfg.Section("").Key("UINT64").MustUint64(6)
-v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339, time.Now())
-v = cfg.Section("").Key("TIME").MustTime(time.Now()) // RFC3339
-```
-
-如果我的值有好多行怎么办?
-
-```ini
-[advance]
-ADDRESS = """404 road,
-NotFound, State, 5000
-Earth"""
-```
-
-嗯哼?小 case!
-
-```go
-cfg.Section("advance").Key("ADDRESS").String()
-
-/* --- start ---
-404 road,
-NotFound, State, 5000
-Earth
------- end --- */
-```
-
-赞爆了!那要是我属于一行的内容写不下想要写到第二行怎么办?
-
-```ini
-[advance]
-two_lines = how about \
- continuation lines?
-lots_of_lines = 1 \
- 2 \
- 3 \
- 4
-```
-
-简直是小菜一碟!
-
-```go
-cfg.Section("advance").Key("two_lines").String() // how about continuation lines?
-cfg.Section("advance").Key("lots_of_lines").String() // 1 2 3 4
-```
-
-可是我有时候觉得两行连在一起特别没劲,怎么才能不自动连接两行呢?
-
-```go
-cfg, err := ini.LoadSources(ini.LoadOptions{
- IgnoreContinuation: true,
-}, "filename")
-```
-
-哇靠给力啊!
-
-需要注意的是,值两侧的单引号会被自动剔除:
-
-```ini
-foo = "some value" // foo: some value
-bar = 'some value' // bar: some value
-```
-
-这就是全部了?哈哈,当然不是。
-
-#### 操作键值的辅助方法
-
-获取键值时设定候选值:
-
-```go
-v = cfg.Section("").Key("STRING").In("default", []string{"str", "arr", "types"})
-v = cfg.Section("").Key("FLOAT64").InFloat64(1.1, []float64{1.25, 2.5, 3.75})
-v = cfg.Section("").Key("INT").InInt(5, []int{10, 20, 30})
-v = cfg.Section("").Key("INT64").InInt64(10, []int64{10, 20, 30})
-v = cfg.Section("").Key("UINT").InUint(4, []int{3, 6, 9})
-v = cfg.Section("").Key("UINT64").InUint64(8, []int64{3, 6, 9})
-v = cfg.Section("").Key("TIME").InTimeFormat(time.RFC3339, time.Now(), []time.Time{time1, time2, time3})
-v = cfg.Section("").Key("TIME").InTime(time.Now(), []time.Time{time1, time2, time3}) // RFC3339
-```
-
-如果获取到的值不是候选值的任意一个,则会返回默认值,而默认值不需要是候选值中的一员。
-
-验证获取的值是否在指定范围内:
-
-```go
-vals = cfg.Section("").Key("FLOAT64").RangeFloat64(0.0, 1.1, 2.2)
-vals = cfg.Section("").Key("INT").RangeInt(0, 10, 20)
-vals = cfg.Section("").Key("INT64").RangeInt64(0, 10, 20)
-vals = cfg.Section("").Key("UINT").RangeUint(0, 3, 9)
-vals = cfg.Section("").Key("UINT64").RangeUint64(0, 3, 9)
-vals = cfg.Section("").Key("TIME").RangeTimeFormat(time.RFC3339, time.Now(), minTime, maxTime)
-vals = cfg.Section("").Key("TIME").RangeTime(time.Now(), minTime, maxTime) // RFC3339
-```
-
-##### 自动分割键值到切片(slice)
-
-当存在无效输入时,使用零值代替:
-
-```go
-// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4]
-// Input: how, 2.2, are, you -> [0.0 2.2 0.0 0.0]
-vals = cfg.Section("").Key("STRINGS").Strings(",")
-vals = cfg.Section("").Key("FLOAT64S").Float64s(",")
-vals = cfg.Section("").Key("INTS").Ints(",")
-vals = cfg.Section("").Key("INT64S").Int64s(",")
-vals = cfg.Section("").Key("UINTS").Uints(",")
-vals = cfg.Section("").Key("UINT64S").Uint64s(",")
-vals = cfg.Section("").Key("TIMES").Times(",")
-```
-
-从结果切片中剔除无效输入:
-
-```go
-// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4]
-// Input: how, 2.2, are, you -> [2.2]
-vals = cfg.Section("").Key("FLOAT64S").ValidFloat64s(",")
-vals = cfg.Section("").Key("INTS").ValidInts(",")
-vals = cfg.Section("").Key("INT64S").ValidInt64s(",")
-vals = cfg.Section("").Key("UINTS").ValidUints(",")
-vals = cfg.Section("").Key("UINT64S").ValidUint64s(",")
-vals = cfg.Section("").Key("TIMES").ValidTimes(",")
-```
-
-当存在无效输入时,直接返回错误:
-
-```go
-// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4]
-// Input: how, 2.2, are, you -> error
-vals = cfg.Section("").Key("FLOAT64S").StrictFloat64s(",")
-vals = cfg.Section("").Key("INTS").StrictInts(",")
-vals = cfg.Section("").Key("INT64S").StrictInt64s(",")
-vals = cfg.Section("").Key("UINTS").StrictUints(",")
-vals = cfg.Section("").Key("UINT64S").StrictUint64s(",")
-vals = cfg.Section("").Key("TIMES").StrictTimes(",")
-```
-
-### 保存配置
-
-终于到了这个时刻,是时候保存一下配置了。
-
-比较原始的做法是输出配置到某个文件:
-
-```go
-// ...
-err = cfg.SaveTo("my.ini")
-err = cfg.SaveToIndent("my.ini", "\t")
-```
-
-另一个比较高级的做法是写入到任何实现 `io.Writer` 接口的对象中:
-
-```go
-// ...
-cfg.WriteTo(writer)
-cfg.WriteToIndent(writer, "\t")
-```
-
-默认情况下,空格将被用于对齐键值之间的等号以美化输出结果,以下代码可以禁用该功能:
-
-```go
-ini.PrettyFormat = false
-```
-
-## 高级用法
-
-### 递归读取键值
-
-在获取所有键值的过程中,特殊语法 `%(<name>)s` 会被应用,其中 `<name>` 可以是相同分区或者默认分区下的键名。字符串 `%(<name>)s` 会被相应的键值所替代,如果指定的键不存在,则会用空字符串替代。您可以最多使用 99 层的递归嵌套。
-
-```ini
-NAME = ini
-
-[author]
-NAME = Unknwon
-GITHUB = https://github.com/%(NAME)s
-
-[package]
-FULL_NAME = github.com/go-ini/%(NAME)s
-```
-
-```go
-cfg.Section("author").Key("GITHUB").String() // https://github.com/Unknwon
-cfg.Section("package").Key("FULL_NAME").String() // github.com/go-ini/ini
-```
-
-### 读取父子分区
-
-您可以在分区名称中使用 `.` 来表示两个或多个分区之间的父子关系。如果某个键在子分区中不存在,则会去它的父分区中再次寻找,直到没有父分区为止。
-
-```ini
-NAME = ini
-VERSION = v1
-IMPORT_PATH = gopkg.in/%(NAME)s.%(VERSION)s
-
-[package]
-CLONE_URL = https://%(IMPORT_PATH)s
-
-[package.sub]
-```
-
-```go
-cfg.Section("package.sub").Key("CLONE_URL").String() // https://gopkg.in/ini.v1
-```
-
-#### 获取上级父分区下的所有键名
-
-```go
-cfg.Section("package.sub").ParentKeys() // ["CLONE_URL"]
-```
-
-### 无法解析的分区
-
-如果遇到一些比较特殊的分区,它们不包含常见的键值对,而是没有固定格式的纯文本,则可以使用 `LoadOptions.UnparsableSections` 进行处理:
-
-```go
-cfg, err := LoadSources(LoadOptions{UnparseableSections: []string{"COMMENTS"}}, `[COMMENTS]
-<1><L.Slide#2> This slide has the fuel listed in the wrong units <e.1>`))
-
-body := cfg.Section("COMMENTS").Body()
-
-/* --- start ---
-<1><L.Slide#2> This slide has the fuel listed in the wrong units <e.1>
------- end --- */
-```
-
-### 读取自增键名
-
-如果数据源中的键名为 `-`,则认为该键使用了自增键名的特殊语法。计数器从 1 开始,并且分区之间是相互独立的。
-
-```ini
-[features]
--: Support read/write comments of keys and sections
--: Support auto-increment of key names
--: Support load multiple files to overwrite key values
-```
-
-```go
-cfg.Section("features").KeyStrings() // []{"#1", "#2", "#3"}
-```
-
-### 映射到结构
-
-想要使用更加面向对象的方式玩转 INI 吗?好主意。
-
-```ini
-Name = Unknwon
-age = 21
-Male = true
-Born = 1993-01-01T20:17:05Z
-
-[Note]
-Content = Hi is a good man!
-Cities = HangZhou, Boston
-```
-
-```go
-type Note struct {
- Content string
- Cities []string
-}
-
-type Person struct {
- Name string
- Age int `ini:"age"`
- Male bool
- Born time.Time
- Note
- Created time.Time `ini:"-"`
-}
-
-func main() {
- cfg, err := ini.Load("path/to/ini")
- // ...
- p := new(Person)
- err = cfg.MapTo(p)
- // ...
-
- // 一切竟可以如此的简单。
- err = ini.MapTo(p, "path/to/ini")
- // ...
-
- // 嗯哼?只需要映射一个分区吗?
- n := new(Note)
- err = cfg.Section("Note").MapTo(n)
- // ...
-}
-```
-
-结构的字段怎么设置默认值呢?很简单,只要在映射之前对指定字段进行赋值就可以了。如果键未找到或者类型错误,该值不会发生改变。
-
-```go
-// ...
-p := &Person{
- Name: "Joe",
-}
-// ...
-```
-
-这样玩 INI 真的好酷啊!然而,如果不能还给我原来的配置文件,有什么卵用?
-
-### 从结构反射
-
-可是,我有说不能吗?
-
-```go
-type Embeded struct {
- Dates []time.Time `delim:"|"`
- Places []string `ini:"places,omitempty"`
- None []int `ini:",omitempty"`
-}
-
-type Author struct {
- Name string `ini:"NAME"`
- Male bool
- Age int
- GPA float64
- NeverMind string `ini:"-"`
- *Embeded
-}
-
-func main() {
- a := &Author{"Unknwon", true, 21, 2.8, "",
- &Embeded{
- []time.Time{time.Now(), time.Now()},
- []string{"HangZhou", "Boston"},
- []int{},
- }}
- cfg := ini.Empty()
- err = ini.ReflectFrom(cfg, a)
- // ...
-}
-```
-
-瞧瞧,奇迹发生了。
-
-```ini
-NAME = Unknwon
-Male = true
-Age = 21
-GPA = 2.8
-
-[Embeded]
-Dates = 2015-08-07T22:14:22+08:00|2015-08-07T22:14:22+08:00
-places = HangZhou,Boston
-```
-
-#### 名称映射器(Name Mapper)
-
-为了节省您的时间并简化代码,本库支持类型为 [`NameMapper`](https://gowalker.org/gopkg.in/ini.v1#NameMapper) 的名称映射器,该映射器负责结构字段名与分区名和键名之间的映射。
-
-目前有 2 款内置的映射器:
-
-- `AllCapsUnderscore`:该映射器将字段名转换至格式 `ALL_CAPS_UNDERSCORE` 后再去匹配分区名和键名。
-- `TitleUnderscore`:该映射器将字段名转换至格式 `title_underscore` 后再去匹配分区名和键名。
-
-使用方法:
-
-```go
-type Info struct{
- PackageName string
-}
-
-func main() {
- err = ini.MapToWithMapper(&Info{}, ini.TitleUnderscore, []byte("package_name=ini"))
- // ...
-
- cfg, err := ini.Load([]byte("PACKAGE_NAME=ini"))
- // ...
- info := new(Info)
- cfg.NameMapper = ini.AllCapsUnderscore
- err = cfg.MapTo(info)
- // ...
-}
-```
-
-使用函数 `ini.ReflectFromWithMapper` 时也可应用相同的规则。
-
-#### 值映射器(Value Mapper)
-
-值映射器允许使用一个自定义函数自动展开值的具体内容,例如:运行时获取环境变量:
-
-```go
-type Env struct {
- Foo string `ini:"foo"`
-}
-
-func main() {
- cfg, err := ini.Load([]byte("[env]\nfoo = ${MY_VAR}\n")
- cfg.ValueMapper = os.ExpandEnv
- // ...
- env := &Env{}
- err = cfg.Section("env").MapTo(env)
-}
-```
-
-本例中,`env.Foo` 将会是运行时所获取到环境变量 `MY_VAR` 的值。
-
-#### 映射/反射的其它说明
-
-任何嵌入的结构都会被默认认作一个不同的分区,并且不会自动产生所谓的父子分区关联:
-
-```go
-type Child struct {
- Age string
-}
-
-type Parent struct {
- Name string
- Child
-}
-
-type Config struct {
- City string
- Parent
-}
-```
-
-示例配置文件:
-
-```ini
-City = Boston
-
-[Parent]
-Name = Unknwon
-
-[Child]
-Age = 21
-```
-
-很好,但是,我就是要嵌入结构也在同一个分区。好吧,你爹是李刚!
-
-```go
-type Child struct {
- Age string
-}
-
-type Parent struct {
- Name string
- Child `ini:"Parent"`
-}
-
-type Config struct {
- City string
- Parent
-}
-```
-
-示例配置文件:
-
-```ini
-City = Boston
-
-[Parent]
-Name = Unknwon
-Age = 21
-```
-
-## 获取帮助
-
-- [API 文档](https://gowalker.org/gopkg.in/ini.v1)
-- [创建工单](https://github.com/go-ini/ini/issues/new)
-
-## 常见问题
-
-### 字段 `BlockMode` 是什么?
-
-默认情况下,本库会在您进行读写操作时采用锁机制来确保数据时间。但在某些情况下,您非常确定只进行读操作。此时,您可以通过设置 `cfg.BlockMode = false` 来将读操作提升大约 **50-70%** 的性能。
-
-### 为什么要写另一个 INI 解析库?
-
-许多人都在使用我的 [goconfig](https://github.com/Unknwon/goconfig) 来完成对 INI 文件的操作,但我希望使用更加 Go 风格的代码。并且当您设置 `cfg.BlockMode = false` 时,会有大约 **10-30%** 的性能提升。
-
-为了做出这些改变,我必须对 API 进行破坏,所以新开一个仓库是最安全的做法。除此之外,本库直接使用 `gopkg.in` 来进行版本化发布。(其实真相是导入路径更短了)
diff --git a/vendor/github.com/go-ini/ini/error.go b/vendor/github.com/go-ini/ini/error.go
deleted file mode 100644
index 80afe7431..000000000
--- a/vendor/github.com/go-ini/ini/error.go
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright 2016 Unknwon
-//
-// 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 ini
-
-import (
- "fmt"
-)
-
-type ErrDelimiterNotFound struct {
- Line string
-}
-
-func IsErrDelimiterNotFound(err error) bool {
- _, ok := err.(ErrDelimiterNotFound)
- return ok
-}
-
-func (err ErrDelimiterNotFound) Error() string {
- return fmt.Sprintf("key-value delimiter not found: %s", err.Line)
-}
diff --git a/vendor/github.com/go-ini/ini/ini.go b/vendor/github.com/go-ini/ini/ini.go
deleted file mode 100644
index 5211d5abc..000000000
--- a/vendor/github.com/go-ini/ini/ini.go
+++ /dev/null
@@ -1,556 +0,0 @@
-// Copyright 2014 Unknwon
-//
-// 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 ini provides INI file read and write functionality in Go.
-package ini
-
-import (
- "bytes"
- "errors"
- "fmt"
- "io"
- "io/ioutil"
- "os"
- "regexp"
- "runtime"
- "strconv"
- "strings"
- "sync"
- "time"
-)
-
-const (
- // Name for default section. You can use this constant or the string literal.
- // In most of cases, an empty string is all you need to access the section.
- DEFAULT_SECTION = "DEFAULT"
-
- // Maximum allowed depth when recursively substituing variable names.
- _DEPTH_VALUES = 99
- _VERSION = "1.27.0"
-)
-
-// Version returns current package version literal.
-func Version() string {
- return _VERSION
-}
-
-var (
- // Delimiter to determine or compose a new line.
- // This variable will be changed to "\r\n" automatically on Windows
- // at package init time.
- LineBreak = "\n"
-
- // Variable regexp pattern: %(variable)s
- varPattern = regexp.MustCompile(`%\(([^\)]+)\)s`)
-
- // Indicate whether to align "=" sign with spaces to produce pretty output
- // or reduce all possible spaces for compact format.
- PrettyFormat = true
-
- // Explicitly write DEFAULT section header
- DefaultHeader = false
-)
-
-func init() {
- if runtime.GOOS == "windows" {
- LineBreak = "\r\n"
- }
-}
-
-func inSlice(str string, s []string) bool {
- for _, v := range s {
- if str == v {
- return true
- }
- }
- return false
-}
-
-// dataSource is an interface that returns object which can be read and closed.
-type dataSource interface {
- ReadCloser() (io.ReadCloser, error)
-}
-
-// sourceFile represents an object that contains content on the local file system.
-type sourceFile struct {
- name string
-}
-
-func (s sourceFile) ReadCloser() (_ io.ReadCloser, err error) {
- return os.Open(s.name)
-}
-
-type bytesReadCloser struct {
- reader io.Reader
-}
-
-func (rc *bytesReadCloser) Read(p []byte) (n int, err error) {
- return rc.reader.Read(p)
-}
-
-func (rc *bytesReadCloser) Close() error {
- return nil
-}
-
-// sourceData represents an object that contains content in memory.
-type sourceData struct {
- data []byte
-}
-
-func (s *sourceData) ReadCloser() (io.ReadCloser, error) {
- return ioutil.NopCloser(bytes.NewReader(s.data)), nil
-}
-
-// sourceReadCloser represents an input stream with Close method.
-type sourceReadCloser struct {
- reader io.ReadCloser
-}
-
-func (s *sourceReadCloser) ReadCloser() (io.ReadCloser, error) {
- return s.reader, nil
-}
-
-// File represents a combination of a or more INI file(s) in memory.
-type File struct {
- // Should make things safe, but sometimes doesn't matter.
- BlockMode bool
- // Make sure data is safe in multiple goroutines.
- lock sync.RWMutex
-
- // Allow combination of multiple data sources.
- dataSources []dataSource
- // Actual data is stored here.
- sections map[string]*Section
-
- // To keep data in order.
- sectionList []string
-
- options LoadOptions
-
- NameMapper
- ValueMapper
-}
-
-// newFile initializes File object with given data sources.
-func newFile(dataSources []dataSource, opts LoadOptions) *File {
- return &File{
- BlockMode: true,
- dataSources: dataSources,
- sections: make(map[string]*Section),
- sectionList: make([]string, 0, 10),
- options: opts,
- }
-}
-
-func parseDataSource(source interface{}) (dataSource, error) {
- switch s := source.(type) {
- case string:
- return sourceFile{s}, nil
- case []byte:
- return &sourceData{s}, nil
- case io.ReadCloser:
- return &sourceReadCloser{s}, nil
- default:
- return nil, fmt.Errorf("error parsing data source: unknown type '%s'", s)
- }
-}
-
-type LoadOptions struct {
- // Loose indicates whether the parser should ignore nonexistent files or return error.
- Loose bool
- // Insensitive indicates whether the parser forces all section and key names to lowercase.
- Insensitive bool
- // IgnoreContinuation indicates whether to ignore continuation lines while parsing.
- IgnoreContinuation bool
- // IgnoreInlineComment indicates whether to ignore comments at the end of value and treat it as part of value.
- IgnoreInlineComment bool
- // AllowBooleanKeys indicates whether to allow boolean type keys or treat as value is missing.
- // This type of keys are mostly used in my.cnf.
- AllowBooleanKeys bool
- // AllowShadows indicates whether to keep track of keys with same name under same section.
- AllowShadows bool
- // Some INI formats allow group blocks that store a block of raw content that doesn't otherwise
- // conform to key/value pairs. Specify the names of those blocks here.
- UnparseableSections []string
-}
-
-func LoadSources(opts LoadOptions, source interface{}, others ...interface{}) (_ *File, err error) {
- sources := make([]dataSource, len(others)+1)
- sources[0], err = parseDataSource(source)
- if err != nil {
- return nil, err
- }
- for i := range others {
- sources[i+1], err = parseDataSource(others[i])
- if err != nil {
- return nil, err
- }
- }
- f := newFile(sources, opts)
- if err = f.Reload(); err != nil {
- return nil, err
- }
- return f, nil
-}
-
-// Load loads and parses from INI data sources.
-// Arguments can be mixed of file name with string type, or raw data in []byte.
-// It will return error if list contains nonexistent files.
-func Load(source interface{}, others ...interface{}) (*File, error) {
- return LoadSources(LoadOptions{}, source, others...)
-}
-
-// LooseLoad has exactly same functionality as Load function
-// except it ignores nonexistent files instead of returning error.
-func LooseLoad(source interface{}, others ...interface{}) (*File, error) {
- return LoadSources(LoadOptions{Loose: true}, source, others...)
-}
-
-// InsensitiveLoad has exactly same functionality as Load function
-// except it forces all section and key names to be lowercased.
-func InsensitiveLoad(source interface{}, others ...interface{}) (*File, error) {
- return LoadSources(LoadOptions{Insensitive: true}, source, others...)
-}
-
-// InsensitiveLoad has exactly same functionality as Load function
-// except it allows have shadow keys.
-func ShadowLoad(source interface{}, others ...interface{}) (*File, error) {
- return LoadSources(LoadOptions{AllowShadows: true}, source, others...)
-}
-
-// Empty returns an empty file object.
-func Empty() *File {
- // Ignore error here, we sure our data is good.
- f, _ := Load([]byte(""))
- return f
-}
-
-// NewSection creates a new section.
-func (f *File) NewSection(name string) (*Section, error) {
- if len(name) == 0 {
- return nil, errors.New("error creating new section: empty section name")
- } else if f.options.Insensitive && name != DEFAULT_SECTION {
- name = strings.ToLower(name)
- }
-
- if f.BlockMode {
- f.lock.Lock()
- defer f.lock.Unlock()
- }
-
- if inSlice(name, f.sectionList) {
- return f.sections[name], nil
- }
-
- f.sectionList = append(f.sectionList, name)
- f.sections[name] = newSection(f, name)
- return f.sections[name], nil
-}
-
-// NewRawSection creates a new section with an unparseable body.
-func (f *File) NewRawSection(name, body string) (*Section, error) {
- section, err := f.NewSection(name)
- if err != nil {
- return nil, err
- }
-
- section.isRawSection = true
- section.rawBody = body
- return section, nil
-}
-
-// NewSections creates a list of sections.
-func (f *File) NewSections(names ...string) (err error) {
- for _, name := range names {
- if _, err = f.NewSection(name); err != nil {
- return err
- }
- }
- return nil
-}
-
-// GetSection returns section by given name.
-func (f *File) GetSection(name string) (*Section, error) {
- if len(name) == 0 {
- name = DEFAULT_SECTION
- } else if f.options.Insensitive {
- name = strings.ToLower(name)
- }
-
- if f.BlockMode {
- f.lock.RLock()
- defer f.lock.RUnlock()
- }
-
- sec := f.sections[name]
- if sec == nil {
- return nil, fmt.Errorf("section '%s' does not exist", name)
- }
- return sec, nil
-}
-
-// Section assumes named section exists and returns a zero-value when not.
-func (f *File) Section(name string) *Section {
- sec, err := f.GetSection(name)
- if err != nil {
- // Note: It's OK here because the only possible error is empty section name,
- // but if it's empty, this piece of code won't be executed.
- sec, _ = f.NewSection(name)
- return sec
- }
- return sec
-}
-
-// Section returns list of Section.
-func (f *File) Sections() []*Section {
- sections := make([]*Section, len(f.sectionList))
- for i := range f.sectionList {
- sections[i] = f.Section(f.sectionList[i])
- }
- return sections
-}
-
-// ChildSections returns a list of child sections of given section name.
-func (f *File) ChildSections(name string) []*Section {
- return f.Section(name).ChildSections()
-}
-
-// SectionStrings returns list of section names.
-func (f *File) SectionStrings() []string {
- list := make([]string, len(f.sectionList))
- copy(list, f.sectionList)
- return list
-}
-
-// DeleteSection deletes a section.
-func (f *File) DeleteSection(name string) {
- if f.BlockMode {
- f.lock.Lock()
- defer f.lock.Unlock()
- }
-
- if len(name) == 0 {
- name = DEFAULT_SECTION
- }
-
- for i, s := range f.sectionList {
- if s == name {
- f.sectionList = append(f.sectionList[:i], f.sectionList[i+1:]...)
- delete(f.sections, name)
- return
- }
- }
-}
-
-func (f *File) reload(s dataSource) error {
- r, err := s.ReadCloser()
- if err != nil {
- return err
- }
- defer r.Close()
-
- return f.parse(r)
-}
-
-// Reload reloads and parses all data sources.
-func (f *File) Reload() (err error) {
- for _, s := range f.dataSources {
- if err = f.reload(s); err != nil {
- // In loose mode, we create an empty default section for nonexistent files.
- if os.IsNotExist(err) && f.options.Loose {
- f.parse(bytes.NewBuffer(nil))
- continue
- }
- return err
- }
- }
- return nil
-}
-
-// Append appends one or more data sources and reloads automatically.
-func (f *File) Append(source interface{}, others ...interface{}) error {
- ds, err := parseDataSource(source)
- if err != nil {
- return err
- }
- f.dataSources = append(f.dataSources, ds)
- for _, s := range others {
- ds, err = parseDataSource(s)
- if err != nil {
- return err
- }
- f.dataSources = append(f.dataSources, ds)
- }
- return f.Reload()
-}
-
-// WriteToIndent writes content into io.Writer with given indention.
-// If PrettyFormat has been set to be true,
-// it will align "=" sign with spaces under each section.
-func (f *File) WriteToIndent(w io.Writer, indent string) (n int64, err error) {
- equalSign := "="
- if PrettyFormat {
- equalSign = " = "
- }
-
- // Use buffer to make sure target is safe until finish encoding.
- buf := bytes.NewBuffer(nil)
- for i, sname := range f.sectionList {
- sec := f.Section(sname)
- if len(sec.Comment) > 0 {
- if sec.Comment[0] != '#' && sec.Comment[0] != ';' {
- sec.Comment = "; " + sec.Comment
- }
- if _, err = buf.WriteString(sec.Comment + LineBreak); err != nil {
- return 0, err
- }
- }
-
- if i > 0 || DefaultHeader {
- if _, err = buf.WriteString("[" + sname + "]" + LineBreak); err != nil {
- return 0, err
- }
- } else {
- // Write nothing if default section is empty
- if len(sec.keyList) == 0 {
- continue
- }
- }
-
- if sec.isRawSection {
- if _, err = buf.WriteString(sec.rawBody); err != nil {
- return 0, err
- }
- continue
- }
-
- // Count and generate alignment length and buffer spaces using the
- // longest key. Keys may be modifed if they contain certain characters so
- // we need to take that into account in our calculation.
- alignLength := 0
- if PrettyFormat {
- for _, kname := range sec.keyList {
- keyLength := len(kname)
- // First case will surround key by ` and second by """
- if strings.ContainsAny(kname, "\"=:") {
- keyLength += 2
- } else if strings.Contains(kname, "`") {
- keyLength += 6
- }
-
- if keyLength > alignLength {
- alignLength = keyLength
- }
- }
- }
- alignSpaces := bytes.Repeat([]byte(" "), alignLength)
-
- KEY_LIST:
- for _, kname := range sec.keyList {
- key := sec.Key(kname)
- if len(key.Comment) > 0 {
- if len(indent) > 0 && sname != DEFAULT_SECTION {
- buf.WriteString(indent)
- }
- if key.Comment[0] != '#' && key.Comment[0] != ';' {
- key.Comment = "; " + key.Comment
- }
- if _, err = buf.WriteString(key.Comment + LineBreak); err != nil {
- return 0, err
- }
- }
-
- if len(indent) > 0 && sname != DEFAULT_SECTION {
- buf.WriteString(indent)
- }
-
- switch {
- case key.isAutoIncrement:
- kname = "-"
- case strings.ContainsAny(kname, "\"=:"):
- kname = "`" + kname + "`"
- case strings.Contains(kname, "`"):
- kname = `"""` + kname + `"""`
- }
-
- for _, val := range key.ValueWithShadows() {
- if _, err = buf.WriteString(kname); err != nil {
- return 0, err
- }
-
- if key.isBooleanType {
- if kname != sec.keyList[len(sec.keyList)-1] {
- buf.WriteString(LineBreak)
- }
- continue KEY_LIST
- }
-
- // Write out alignment spaces before "=" sign
- if PrettyFormat {
- buf.Write(alignSpaces[:alignLength-len(kname)])
- }
-
- // In case key value contains "\n", "`", "\"", "#" or ";"
- if strings.ContainsAny(val, "\n`") {
- val = `"""` + val + `"""`
- } else if strings.ContainsAny(val, "#;") {
- val = "`" + val + "`"
- }
- if _, err = buf.WriteString(equalSign + val + LineBreak); err != nil {
- return 0, err
- }
- }
- }
-
- // Put a line between sections
- if _, err = buf.WriteString(LineBreak); err != nil {
- return 0, err
- }
- }
-
- return buf.WriteTo(w)
-}
-
-// WriteTo writes file content into io.Writer.
-func (f *File) WriteTo(w io.Writer) (int64, error) {
- return f.WriteToIndent(w, "")
-}
-
-// SaveToIndent writes content to file system with given value indention.
-func (f *File) SaveToIndent(filename, indent string) error {
- // Note: Because we are truncating with os.Create,
- // so it's safer to save to a temporary file location and rename afte done.
- tmpPath := filename + "." + strconv.Itoa(time.Now().Nanosecond()) + ".tmp"
- defer os.Remove(tmpPath)
-
- fw, err := os.Create(tmpPath)
- if err != nil {
- return err
- }
-
- if _, err = f.WriteToIndent(fw, indent); err != nil {
- fw.Close()
- return err
- }
- fw.Close()
-
- // Remove old file and rename the new one.
- os.Remove(filename)
- return os.Rename(tmpPath, filename)
-}
-
-// SaveTo writes content to file system.
-func (f *File) SaveTo(filename string) error {
- return f.SaveToIndent(filename, "")
-}
diff --git a/vendor/github.com/go-ini/ini/ini_test.go b/vendor/github.com/go-ini/ini/ini_test.go
deleted file mode 100644
index 4ed6ab00a..000000000
--- a/vendor/github.com/go-ini/ini/ini_test.go
+++ /dev/null
@@ -1,484 +0,0 @@
-// Copyright 2014 Unknwon
-//
-// 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 ini
-
-import (
- "bytes"
- "io/ioutil"
- "strings"
- "testing"
- "time"
-
- . "github.com/smartystreets/goconvey/convey"
-)
-
-func Test_Version(t *testing.T) {
- Convey("Get version", t, func() {
- So(Version(), ShouldEqual, _VERSION)
- })
-}
-
-const _CONF_DATA = `
-; Package name
-NAME = ini
-; Package version
-VERSION = v1
-; Package import path
-IMPORT_PATH = gopkg.in/%(NAME)s.%(VERSION)s
-
-# Information about package author
-# Bio can be written in multiple lines.
-[author]
-NAME = Unknwon ; Succeeding comment
-E-MAIL = fake@localhost
-GITHUB = https://github.com/%(NAME)s
-BIO = """Gopher.
-Coding addict.
-Good man.
-""" # Succeeding comment
-
-[package]
-CLONE_URL = https://%(IMPORT_PATH)s
-
-[package.sub]
-UNUSED_KEY = should be deleted
-
-[features]
--: Support read/write comments of keys and sections
--: Support auto-increment of key names
--: Support load multiple files to overwrite key values
-
-[types]
-STRING = str
-BOOL = true
-BOOL_FALSE = false
-FLOAT64 = 1.25
-INT = 10
-TIME = 2015-01-01T20:17:05Z
-DURATION = 2h45m
-UINT = 3
-
-[array]
-STRINGS = en, zh, de
-FLOAT64S = 1.1, 2.2, 3.3
-INTS = 1, 2, 3
-UINTS = 1, 2, 3
-TIMES = 2015-01-01T20:17:05Z,2015-01-01T20:17:05Z,2015-01-01T20:17:05Z
-
-[note]
-empty_lines = next line is empty\
-
-; Comment before the section
-[comments] ; This is a comment for the section too
-; Comment before key
-key = "value"
-key2 = "value2" ; This is a comment for key2
-key3 = "one", "two", "three"
-
-[advance]
-value with quotes = "some value"
-value quote2 again = 'some value'
-includes comment sign = ` + "`" + "my#password" + "`" + `
-includes comment sign2 = ` + "`" + "my;password" + "`" + `
-true = 2+3=5
-"1+1=2" = true
-"""6+1=7""" = true
-"""` + "`" + `5+5` + "`" + `""" = 10
-` + "`" + `"6+6"` + "`" + ` = 12
-` + "`" + `7-2=4` + "`" + ` = false
-ADDRESS = ` + "`" + `404 road,
-NotFound, State, 50000` + "`" + `
-
-two_lines = how about \
- continuation lines?
-lots_of_lines = 1 \
- 2 \
- 3 \
- 4 \
-`
-
-func Test_Load(t *testing.T) {
- Convey("Load from data sources", t, func() {
-
- Convey("Load with empty data", func() {
- So(Empty(), ShouldNotBeNil)
- })
-
- Convey("Load with multiple data sources", func() {
- cfg, err := Load([]byte(_CONF_DATA), "testdata/conf.ini", ioutil.NopCloser(bytes.NewReader([]byte(_CONF_DATA))))
- So(err, ShouldBeNil)
- So(cfg, ShouldNotBeNil)
-
- f, err := Load([]byte(_CONF_DATA), "testdata/404.ini")
- So(err, ShouldNotBeNil)
- So(f, ShouldBeNil)
- })
-
- Convey("Load with io.ReadCloser", func() {
- cfg, err := Load(ioutil.NopCloser(bytes.NewReader([]byte(_CONF_DATA))))
- So(err, ShouldBeNil)
- So(cfg, ShouldNotBeNil)
-
- So(cfg.Section("").Key("NAME").String(), ShouldEqual, "ini")
- })
- })
-
- Convey("Bad load process", t, func() {
-
- Convey("Load from invalid data sources", func() {
- _, err := Load(_CONF_DATA)
- So(err, ShouldNotBeNil)
-
- f, err := Load("testdata/404.ini")
- So(err, ShouldNotBeNil)
- So(f, ShouldBeNil)
-
- _, err = Load(1)
- So(err, ShouldNotBeNil)
-
- _, err = Load([]byte(""), 1)
- So(err, ShouldNotBeNil)
- })
-
- Convey("Load with bad section name", func() {
- _, err := Load([]byte("[]"))
- So(err, ShouldNotBeNil)
-
- _, err = Load([]byte("["))
- So(err, ShouldNotBeNil)
- })
-
- Convey("Load with bad keys", func() {
- _, err := Load([]byte(`"""name`))
- So(err, ShouldNotBeNil)
-
- _, err = Load([]byte(`"""name"""`))
- So(err, ShouldNotBeNil)
-
- _, err = Load([]byte(`""=1`))
- So(err, ShouldNotBeNil)
-
- _, err = Load([]byte(`=`))
- So(err, ShouldNotBeNil)
-
- _, err = Load([]byte(`name`))
- So(err, ShouldNotBeNil)
- })
-
- Convey("Load with bad values", func() {
- _, err := Load([]byte(`name="""Unknwon`))
- So(err, ShouldNotBeNil)
- })
- })
-
- Convey("Get section and key insensitively", t, func() {
- cfg, err := InsensitiveLoad([]byte(_CONF_DATA), "testdata/conf.ini")
- So(err, ShouldBeNil)
- So(cfg, ShouldNotBeNil)
-
- sec, err := cfg.GetSection("Author")
- So(err, ShouldBeNil)
- So(sec, ShouldNotBeNil)
-
- key, err := sec.GetKey("E-mail")
- So(err, ShouldBeNil)
- So(key, ShouldNotBeNil)
- })
-
- Convey("Load with ignoring continuation lines", t, func() {
- cfg, err := LoadSources(LoadOptions{IgnoreContinuation: true}, []byte(`key1=a\b\
-key2=c\d\`))
- So(err, ShouldBeNil)
- So(cfg, ShouldNotBeNil)
-
- So(cfg.Section("").Key("key1").String(), ShouldEqual, `a\b\`)
- So(cfg.Section("").Key("key2").String(), ShouldEqual, `c\d\`)
- })
-
- Convey("Load with ignoring inline comments", t, func() {
- cfg, err := LoadSources(LoadOptions{IgnoreInlineComment: true}, []byte(`key1=value ;comment
-key2=value #comment2`))
- So(err, ShouldBeNil)
- So(cfg, ShouldNotBeNil)
-
- So(cfg.Section("").Key("key1").String(), ShouldEqual, `value ;comment`)
- So(cfg.Section("").Key("key2").String(), ShouldEqual, `value #comment2`)
- })
-
- Convey("Load with boolean type keys", t, func() {
- cfg, err := LoadSources(LoadOptions{AllowBooleanKeys: true}, []byte(`key1=hello
-key2
-#key3
-key4
-key5`))
- So(err, ShouldBeNil)
- So(cfg, ShouldNotBeNil)
-
- So(strings.Join(cfg.Section("").KeyStrings(), ","), ShouldEqual, "key1,key2,key4,key5")
- So(cfg.Section("").Key("key2").MustBool(false), ShouldBeTrue)
-
- var buf bytes.Buffer
- cfg.WriteTo(&buf)
- // there is always a trailing \n at the end of the section
- So(buf.String(), ShouldEqual, `key1 = hello
-key2
-#key3
-key4
-key5
-`)
- })
-}
-
-func Test_File_ChildSections(t *testing.T) {
- Convey("Find child sections by parent name", t, func() {
- cfg, err := Load([]byte(`
-[node]
-
-[node.biz1]
-
-[node.biz2]
-
-[node.biz3]
-
-[node.bizN]
-`))
- So(err, ShouldBeNil)
- So(cfg, ShouldNotBeNil)
-
- children := cfg.ChildSections("node")
- names := make([]string, len(children))
- for i := range children {
- names[i] = children[i].name
- }
- So(strings.Join(names, ","), ShouldEqual, "node.biz1,node.biz2,node.biz3,node.bizN")
- })
-}
-
-func Test_LooseLoad(t *testing.T) {
- Convey("Loose load from data sources", t, func() {
- Convey("Loose load mixed with nonexistent file", func() {
- cfg, err := LooseLoad("testdata/404.ini")
- So(err, ShouldBeNil)
- So(cfg, ShouldNotBeNil)
- var fake struct {
- Name string `ini:"name"`
- }
- So(cfg.MapTo(&fake), ShouldBeNil)
-
- cfg, err = LooseLoad([]byte("name=Unknwon"), "testdata/404.ini")
- So(err, ShouldBeNil)
- So(cfg.Section("").Key("name").String(), ShouldEqual, "Unknwon")
- So(cfg.MapTo(&fake), ShouldBeNil)
- So(fake.Name, ShouldEqual, "Unknwon")
- })
- })
-
-}
-
-func Test_File_Append(t *testing.T) {
- Convey("Append data sources", t, func() {
- cfg, err := Load([]byte(""))
- So(err, ShouldBeNil)
- So(cfg, ShouldNotBeNil)
-
- So(cfg.Append([]byte(""), []byte("")), ShouldBeNil)
-
- Convey("Append bad data sources", func() {
- So(cfg.Append(1), ShouldNotBeNil)
- So(cfg.Append([]byte(""), 1), ShouldNotBeNil)
- })
- })
-}
-
-func Test_File_WriteTo(t *testing.T) {
- Convey("Write to somewhere", t, func() {
- var buf bytes.Buffer
- cfg := Empty()
- cfg.WriteTo(&buf)
- })
-}
-
-func Test_File_SaveTo_WriteTo(t *testing.T) {
- Convey("Save file", t, func() {
- cfg, err := Load([]byte(_CONF_DATA), "testdata/conf.ini")
- So(err, ShouldBeNil)
- So(cfg, ShouldNotBeNil)
-
- cfg.Section("").Key("NAME").Comment = "Package name"
- cfg.Section("author").Comment = `Information about package author
-# Bio can be written in multiple lines.`
- cfg.Section("advanced").Key("val w/ pound").SetValue("my#password")
- cfg.Section("advanced").Key("longest key has a colon : yes/no").SetValue("yes")
- So(cfg.SaveTo("testdata/conf_out.ini"), ShouldBeNil)
-
- cfg.Section("author").Key("NAME").Comment = "This is author name"
-
- So(cfg.SaveToIndent("testdata/conf_out.ini", "\t"), ShouldBeNil)
-
- var buf bytes.Buffer
- _, err = cfg.WriteToIndent(&buf, "\t")
- So(err, ShouldBeNil)
- So(buf.String(), ShouldEqual, `; Package name
-NAME = ini
-; Package version
-VERSION = v1
-; Package import path
-IMPORT_PATH = gopkg.in/%(NAME)s.%(VERSION)s
-
-; Information about package author
-# Bio can be written in multiple lines.
-[author]
- ; This is author name
- NAME = Unknwon
- E-MAIL = u@gogs.io
- GITHUB = https://github.com/%(NAME)s
- # Succeeding comment
- BIO = """Gopher.
-Coding addict.
-Good man.
-"""
-
-[package]
- CLONE_URL = https://%(IMPORT_PATH)s
-
-[package.sub]
- UNUSED_KEY = should be deleted
-
-[features]
- - = Support read/write comments of keys and sections
- - = Support auto-increment of key names
- - = Support load multiple files to overwrite key values
-
-[types]
- STRING = str
- BOOL = true
- BOOL_FALSE = false
- FLOAT64 = 1.25
- INT = 10
- TIME = 2015-01-01T20:17:05Z
- DURATION = 2h45m
- UINT = 3
-
-[array]
- STRINGS = en, zh, de
- FLOAT64S = 1.1, 2.2, 3.3
- INTS = 1, 2, 3
- UINTS = 1, 2, 3
- TIMES = 2015-01-01T20:17:05Z,2015-01-01T20:17:05Z,2015-01-01T20:17:05Z
-
-[note]
- empty_lines = next line is empty
-
-; Comment before the section
-; This is a comment for the section too
-[comments]
- ; Comment before key
- key = value
- ; This is a comment for key2
- key2 = value2
- key3 = "one", "two", "three"
-
-[advance]
- value with quotes = some value
- value quote2 again = some value
- includes comment sign = `+"`"+"my#password"+"`"+`
- includes comment sign2 = `+"`"+"my;password"+"`"+`
- true = 2+3=5
- `+"`"+`1+1=2`+"`"+` = true
- `+"`"+`6+1=7`+"`"+` = true
- """`+"`"+`5+5`+"`"+`""" = 10
- `+"`"+`"6+6"`+"`"+` = 12
- `+"`"+`7-2=4`+"`"+` = false
- ADDRESS = """404 road,
-NotFound, State, 50000"""
- two_lines = how about continuation lines?
- lots_of_lines = 1 2 3 4
-
-[advanced]
- val w/ pound = `+"`"+`my#password`+"`"+`
- `+"`"+`longest key has a colon : yes/no`+"`"+` = yes
-
-`)
- })
-}
-
-func Test_File_WriteTo_SectionRaw(t *testing.T) {
- Convey("Write a INI with a raw section", t, func() {
- var buf bytes.Buffer
- cfg, err := LoadSources(
- LoadOptions{
- UnparseableSections: []string{"CORE_LESSON", "COMMENTS"},
- },
- "testdata/aicc.ini")
- So(err, ShouldBeNil)
- So(cfg, ShouldNotBeNil)
- cfg.WriteToIndent(&buf, "\t")
- So(buf.String(), ShouldEqual, `[Core]
- Lesson_Location = 87
- Lesson_Status = C
- Score = 3
- Time = 00:02:30
-
-[CORE_LESSON]
-my lesson state data – 1111111111111111111000000000000000001110000
-111111111111111111100000000000111000000000 – end my lesson state data
-[COMMENTS]
-<1><L.Slide#2> This slide has the fuel listed in the wrong units <e.1>
-`)
- })
-}
-
-// Helpers for slice tests.
-func float64sEqual(values []float64, expected ...float64) {
- So(values, ShouldHaveLength, len(expected))
- for i, v := range expected {
- So(values[i], ShouldEqual, v)
- }
-}
-
-func intsEqual(values []int, expected ...int) {
- So(values, ShouldHaveLength, len(expected))
- for i, v := range expected {
- So(values[i], ShouldEqual, v)
- }
-}
-
-func int64sEqual(values []int64, expected ...int64) {
- So(values, ShouldHaveLength, len(expected))
- for i, v := range expected {
- So(values[i], ShouldEqual, v)
- }
-}
-
-func uintsEqual(values []uint, expected ...uint) {
- So(values, ShouldHaveLength, len(expected))
- for i, v := range expected {
- So(values[i], ShouldEqual, v)
- }
-}
-
-func uint64sEqual(values []uint64, expected ...uint64) {
- So(values, ShouldHaveLength, len(expected))
- for i, v := range expected {
- So(values[i], ShouldEqual, v)
- }
-}
-
-func timesEqual(values []time.Time, expected ...time.Time) {
- So(values, ShouldHaveLength, len(expected))
- for i, v := range expected {
- So(values[i].String(), ShouldEqual, v.String())
- }
-}
diff --git a/vendor/github.com/go-ini/ini/key.go b/vendor/github.com/go-ini/ini/key.go
deleted file mode 100644
index 838356af0..000000000
--- a/vendor/github.com/go-ini/ini/key.go
+++ /dev/null
@@ -1,699 +0,0 @@
-// Copyright 2014 Unknwon
-//
-// 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 ini
-
-import (
- "errors"
- "fmt"
- "strconv"
- "strings"
- "time"
-)
-
-// Key represents a key under a section.
-type Key struct {
- s *Section
- name string
- value string
- isAutoIncrement bool
- isBooleanType bool
-
- isShadow bool
- shadows []*Key
-
- Comment string
-}
-
-// newKey simply return a key object with given values.
-func newKey(s *Section, name, val string) *Key {
- return &Key{
- s: s,
- name: name,
- value: val,
- }
-}
-
-func (k *Key) addShadow(val string) error {
- if k.isShadow {
- return errors.New("cannot add shadow to another shadow key")
- } else if k.isAutoIncrement || k.isBooleanType {
- return errors.New("cannot add shadow to auto-increment or boolean key")
- }
-
- shadow := newKey(k.s, k.name, val)
- shadow.isShadow = true
- k.shadows = append(k.shadows, shadow)
- return nil
-}
-
-// AddShadow adds a new shadow key to itself.
-func (k *Key) AddShadow(val string) error {
- if !k.s.f.options.AllowShadows {
- return errors.New("shadow key is not allowed")
- }
- return k.addShadow(val)
-}
-
-// ValueMapper represents a mapping function for values, e.g. os.ExpandEnv
-type ValueMapper func(string) string
-
-// Name returns name of key.
-func (k *Key) Name() string {
- return k.name
-}
-
-// Value returns raw value of key for performance purpose.
-func (k *Key) Value() string {
- return k.value
-}
-
-// ValueWithShadows returns raw values of key and its shadows if any.
-func (k *Key) ValueWithShadows() []string {
- if len(k.shadows) == 0 {
- return []string{k.value}
- }
- vals := make([]string, len(k.shadows)+1)
- vals[0] = k.value
- for i := range k.shadows {
- vals[i+1] = k.shadows[i].value
- }
- return vals
-}
-
-// transformValue takes a raw value and transforms to its final string.
-func (k *Key) transformValue(val string) string {
- if k.s.f.ValueMapper != nil {
- val = k.s.f.ValueMapper(val)
- }
-
- // Fail-fast if no indicate char found for recursive value
- if !strings.Contains(val, "%") {
- return val
- }
- for i := 0; i < _DEPTH_VALUES; i++ {
- vr := varPattern.FindString(val)
- if len(vr) == 0 {
- break
- }
-
- // Take off leading '%(' and trailing ')s'.
- noption := strings.TrimLeft(vr, "%(")
- noption = strings.TrimRight(noption, ")s")
-
- // Search in the same section.
- nk, err := k.s.GetKey(noption)
- if err != nil {
- // Search again in default section.
- nk, _ = k.s.f.Section("").GetKey(noption)
- }
-
- // Substitute by new value and take off leading '%(' and trailing ')s'.
- val = strings.Replace(val, vr, nk.value, -1)
- }
- return val
-}
-
-// String returns string representation of value.
-func (k *Key) String() string {
- return k.transformValue(k.value)
-}
-
-// Validate accepts a validate function which can
-// return modifed result as key value.
-func (k *Key) Validate(fn func(string) string) string {
- return fn(k.String())
-}
-
-// parseBool returns the boolean value represented by the string.
-//
-// It accepts 1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On,
-// 0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off.
-// Any other value returns an error.
-func parseBool(str string) (value bool, err error) {
- switch str {
- case "1", "t", "T", "true", "TRUE", "True", "YES", "yes", "Yes", "y", "ON", "on", "On":
- return true, nil
- case "0", "f", "F", "false", "FALSE", "False", "NO", "no", "No", "n", "OFF", "off", "Off":
- return false, nil
- }
- return false, fmt.Errorf("parsing \"%s\": invalid syntax", str)
-}
-
-// Bool returns bool type value.
-func (k *Key) Bool() (bool, error) {
- return parseBool(k.String())
-}
-
-// Float64 returns float64 type value.
-func (k *Key) Float64() (float64, error) {
- return strconv.ParseFloat(k.String(), 64)
-}
-
-// Int returns int type value.
-func (k *Key) Int() (int, error) {
- return strconv.Atoi(k.String())
-}
-
-// Int64 returns int64 type value.
-func (k *Key) Int64() (int64, error) {
- return strconv.ParseInt(k.String(), 10, 64)
-}
-
-// Uint returns uint type valued.
-func (k *Key) Uint() (uint, error) {
- u, e := strconv.ParseUint(k.String(), 10, 64)
- return uint(u), e
-}
-
-// Uint64 returns uint64 type value.
-func (k *Key) Uint64() (uint64, error) {
- return strconv.ParseUint(k.String(), 10, 64)
-}
-
-// Duration returns time.Duration type value.
-func (k *Key) Duration() (time.Duration, error) {
- return time.ParseDuration(k.String())
-}
-
-// TimeFormat parses with given format and returns time.Time type value.
-func (k *Key) TimeFormat(format string) (time.Time, error) {
- return time.Parse(format, k.String())
-}
-
-// Time parses with RFC3339 format and returns time.Time type value.
-func (k *Key) Time() (time.Time, error) {
- return k.TimeFormat(time.RFC3339)
-}
-
-// MustString returns default value if key value is empty.
-func (k *Key) MustString(defaultVal string) string {
- val := k.String()
- if len(val) == 0 {
- k.value = defaultVal
- return defaultVal
- }
- return val
-}
-
-// MustBool always returns value without error,
-// it returns false if error occurs.
-func (k *Key) MustBool(defaultVal ...bool) bool {
- val, err := k.Bool()
- if len(defaultVal) > 0 && err != nil {
- k.value = strconv.FormatBool(defaultVal[0])
- return defaultVal[0]
- }
- return val
-}
-
-// MustFloat64 always returns value without error,
-// it returns 0.0 if error occurs.
-func (k *Key) MustFloat64(defaultVal ...float64) float64 {
- val, err := k.Float64()
- if len(defaultVal) > 0 && err != nil {
- k.value = strconv.FormatFloat(defaultVal[0], 'f', -1, 64)
- return defaultVal[0]
- }
- return val
-}
-
-// MustInt always returns value without error,
-// it returns 0 if error occurs.
-func (k *Key) MustInt(defaultVal ...int) int {
- val, err := k.Int()
- if len(defaultVal) > 0 && err != nil {
- k.value = strconv.FormatInt(int64(defaultVal[0]), 10)
- return defaultVal[0]
- }
- return val
-}
-
-// MustInt64 always returns value without error,
-// it returns 0 if error occurs.
-func (k *Key) MustInt64(defaultVal ...int64) int64 {
- val, err := k.Int64()
- if len(defaultVal) > 0 && err != nil {
- k.value = strconv.FormatInt(defaultVal[0], 10)
- return defaultVal[0]
- }
- return val
-}
-
-// MustUint always returns value without error,
-// it returns 0 if error occurs.
-func (k *Key) MustUint(defaultVal ...uint) uint {
- val, err := k.Uint()
- if len(defaultVal) > 0 && err != nil {
- k.value = strconv.FormatUint(uint64(defaultVal[0]), 10)
- return defaultVal[0]
- }
- return val
-}
-
-// MustUint64 always returns value without error,
-// it returns 0 if error occurs.
-func (k *Key) MustUint64(defaultVal ...uint64) uint64 {
- val, err := k.Uint64()
- if len(defaultVal) > 0 && err != nil {
- k.value = strconv.FormatUint(defaultVal[0], 10)
- return defaultVal[0]
- }
- return val
-}
-
-// MustDuration always returns value without error,
-// it returns zero value if error occurs.
-func (k *Key) MustDuration(defaultVal ...time.Duration) time.Duration {
- val, err := k.Duration()
- if len(defaultVal) > 0 && err != nil {
- k.value = defaultVal[0].String()
- return defaultVal[0]
- }
- return val
-}
-
-// MustTimeFormat always parses with given format and returns value without error,
-// it returns zero value if error occurs.
-func (k *Key) MustTimeFormat(format string, defaultVal ...time.Time) time.Time {
- val, err := k.TimeFormat(format)
- if len(defaultVal) > 0 && err != nil {
- k.value = defaultVal[0].Format(format)
- return defaultVal[0]
- }
- return val
-}
-
-// MustTime always parses with RFC3339 format and returns value without error,
-// it returns zero value if error occurs.
-func (k *Key) MustTime(defaultVal ...time.Time) time.Time {
- return k.MustTimeFormat(time.RFC3339, defaultVal...)
-}
-
-// In always returns value without error,
-// it returns default value if error occurs or doesn't fit into candidates.
-func (k *Key) In(defaultVal string, candidates []string) string {
- val := k.String()
- for _, cand := range candidates {
- if val == cand {
- return val
- }
- }
- return defaultVal
-}
-
-// InFloat64 always returns value without error,
-// it returns default value if error occurs or doesn't fit into candidates.
-func (k *Key) InFloat64(defaultVal float64, candidates []float64) float64 {
- val := k.MustFloat64()
- for _, cand := range candidates {
- if val == cand {
- return val
- }
- }
- return defaultVal
-}
-
-// InInt always returns value without error,
-// it returns default value if error occurs or doesn't fit into candidates.
-func (k *Key) InInt(defaultVal int, candidates []int) int {
- val := k.MustInt()
- for _, cand := range candidates {
- if val == cand {
- return val
- }
- }
- return defaultVal
-}
-
-// InInt64 always returns value without error,
-// it returns default value if error occurs or doesn't fit into candidates.
-func (k *Key) InInt64(defaultVal int64, candidates []int64) int64 {
- val := k.MustInt64()
- for _, cand := range candidates {
- if val == cand {
- return val
- }
- }
- return defaultVal
-}
-
-// InUint always returns value without error,
-// it returns default value if error occurs or doesn't fit into candidates.
-func (k *Key) InUint(defaultVal uint, candidates []uint) uint {
- val := k.MustUint()
- for _, cand := range candidates {
- if val == cand {
- return val
- }
- }
- return defaultVal
-}
-
-// InUint64 always returns value without error,
-// it returns default value if error occurs or doesn't fit into candidates.
-func (k *Key) InUint64(defaultVal uint64, candidates []uint64) uint64 {
- val := k.MustUint64()
- for _, cand := range candidates {
- if val == cand {
- return val
- }
- }
- return defaultVal
-}
-
-// InTimeFormat always parses with given format and returns value without error,
-// it returns default value if error occurs or doesn't fit into candidates.
-func (k *Key) InTimeFormat(format string, defaultVal time.Time, candidates []time.Time) time.Time {
- val := k.MustTimeFormat(format)
- for _, cand := range candidates {
- if val == cand {
- return val
- }
- }
- return defaultVal
-}
-
-// InTime always parses with RFC3339 format and returns value without error,
-// it returns default value if error occurs or doesn't fit into candidates.
-func (k *Key) InTime(defaultVal time.Time, candidates []time.Time) time.Time {
- return k.InTimeFormat(time.RFC3339, defaultVal, candidates)
-}
-
-// RangeFloat64 checks if value is in given range inclusively,
-// and returns default value if it's not.
-func (k *Key) RangeFloat64(defaultVal, min, max float64) float64 {
- val := k.MustFloat64()
- if val < min || val > max {
- return defaultVal
- }
- return val
-}
-
-// RangeInt checks if value is in given range inclusively,
-// and returns default value if it's not.
-func (k *Key) RangeInt(defaultVal, min, max int) int {
- val := k.MustInt()
- if val < min || val > max {
- return defaultVal
- }
- return val
-}
-
-// RangeInt64 checks if value is in given range inclusively,
-// and returns default value if it's not.
-func (k *Key) RangeInt64(defaultVal, min, max int64) int64 {
- val := k.MustInt64()
- if val < min || val > max {
- return defaultVal
- }
- return val
-}
-
-// RangeTimeFormat checks if value with given format is in given range inclusively,
-// and returns default value if it's not.
-func (k *Key) RangeTimeFormat(format string, defaultVal, min, max time.Time) time.Time {
- val := k.MustTimeFormat(format)
- if val.Unix() < min.Unix() || val.Unix() > max.Unix() {
- return defaultVal
- }
- return val
-}
-
-// RangeTime checks if value with RFC3339 format is in given range inclusively,
-// and returns default value if it's not.
-func (k *Key) RangeTime(defaultVal, min, max time.Time) time.Time {
- return k.RangeTimeFormat(time.RFC3339, defaultVal, min, max)
-}
-
-// Strings returns list of string divided by given delimiter.
-func (k *Key) Strings(delim string) []string {
- str := k.String()
- if len(str) == 0 {
- return []string{}
- }
-
- vals := strings.Split(str, delim)
- for i := range vals {
- // vals[i] = k.transformValue(strings.TrimSpace(vals[i]))
- vals[i] = strings.TrimSpace(vals[i])
- }
- return vals
-}
-
-// StringsWithShadows returns list of string divided by given delimiter.
-// Shadows will also be appended if any.
-func (k *Key) StringsWithShadows(delim string) []string {
- vals := k.ValueWithShadows()
- results := make([]string, 0, len(vals)*2)
- for i := range vals {
- if len(vals) == 0 {
- continue
- }
-
- results = append(results, strings.Split(vals[i], delim)...)
- }
-
- for i := range results {
- results[i] = k.transformValue(strings.TrimSpace(results[i]))
- }
- return results
-}
-
-// Float64s returns list of float64 divided by given delimiter. Any invalid input will be treated as zero value.
-func (k *Key) Float64s(delim string) []float64 {
- vals, _ := k.parseFloat64s(k.Strings(delim), true, false)
- return vals
-}
-
-// Ints returns list of int divided by given delimiter. Any invalid input will be treated as zero value.
-func (k *Key) Ints(delim string) []int {
- vals, _ := k.parseInts(k.Strings(delim), true, false)
- return vals
-}
-
-// Int64s returns list of int64 divided by given delimiter. Any invalid input will be treated as zero value.
-func (k *Key) Int64s(delim string) []int64 {
- vals, _ := k.parseInt64s(k.Strings(delim), true, false)
- return vals
-}
-
-// Uints returns list of uint divided by given delimiter. Any invalid input will be treated as zero value.
-func (k *Key) Uints(delim string) []uint {
- vals, _ := k.parseUints(k.Strings(delim), true, false)
- return vals
-}
-
-// Uint64s returns list of uint64 divided by given delimiter. Any invalid input will be treated as zero value.
-func (k *Key) Uint64s(delim string) []uint64 {
- vals, _ := k.parseUint64s(k.Strings(delim), true, false)
- return vals
-}
-
-// TimesFormat parses with given format and returns list of time.Time divided by given delimiter.
-// Any invalid input will be treated as zero value (0001-01-01 00:00:00 +0000 UTC).
-func (k *Key) TimesFormat(format, delim string) []time.Time {
- vals, _ := k.parseTimesFormat(format, k.Strings(delim), true, false)
- return vals
-}
-
-// Times parses with RFC3339 format and returns list of time.Time divided by given delimiter.
-// Any invalid input will be treated as zero value (0001-01-01 00:00:00 +0000 UTC).
-func (k *Key) Times(delim string) []time.Time {
- return k.TimesFormat(time.RFC3339, delim)
-}
-
-// ValidFloat64s returns list of float64 divided by given delimiter. If some value is not float, then
-// it will not be included to result list.
-func (k *Key) ValidFloat64s(delim string) []float64 {
- vals, _ := k.parseFloat64s(k.Strings(delim), false, false)
- return vals
-}
-
-// ValidInts returns list of int divided by given delimiter. If some value is not integer, then it will
-// not be included to result list.
-func (k *Key) ValidInts(delim string) []int {
- vals, _ := k.parseInts(k.Strings(delim), false, false)
- return vals
-}
-
-// ValidInt64s returns list of int64 divided by given delimiter. If some value is not 64-bit integer,
-// then it will not be included to result list.
-func (k *Key) ValidInt64s(delim string) []int64 {
- vals, _ := k.parseInt64s(k.Strings(delim), false, false)
- return vals
-}
-
-// ValidUints returns list of uint divided by given delimiter. If some value is not unsigned integer,
-// then it will not be included to result list.
-func (k *Key) ValidUints(delim string) []uint {
- vals, _ := k.parseUints(k.Strings(delim), false, false)
- return vals
-}
-
-// ValidUint64s returns list of uint64 divided by given delimiter. If some value is not 64-bit unsigned
-// integer, then it will not be included to result list.
-func (k *Key) ValidUint64s(delim string) []uint64 {
- vals, _ := k.parseUint64s(k.Strings(delim), false, false)
- return vals
-}
-
-// ValidTimesFormat parses with given format and returns list of time.Time divided by given delimiter.
-func (k *Key) ValidTimesFormat(format, delim string) []time.Time {
- vals, _ := k.parseTimesFormat(format, k.Strings(delim), false, false)
- return vals
-}
-
-// ValidTimes parses with RFC3339 format and returns list of time.Time divided by given delimiter.
-func (k *Key) ValidTimes(delim string) []time.Time {
- return k.ValidTimesFormat(time.RFC3339, delim)
-}
-
-// StrictFloat64s returns list of float64 divided by given delimiter or error on first invalid input.
-func (k *Key) StrictFloat64s(delim string) ([]float64, error) {
- return k.parseFloat64s(k.Strings(delim), false, true)
-}
-
-// StrictInts returns list of int divided by given delimiter or error on first invalid input.
-func (k *Key) StrictInts(delim string) ([]int, error) {
- return k.parseInts(k.Strings(delim), false, true)
-}
-
-// StrictInt64s returns list of int64 divided by given delimiter or error on first invalid input.
-func (k *Key) StrictInt64s(delim string) ([]int64, error) {
- return k.parseInt64s(k.Strings(delim), false, true)
-}
-
-// StrictUints returns list of uint divided by given delimiter or error on first invalid input.
-func (k *Key) StrictUints(delim string) ([]uint, error) {
- return k.parseUints(k.Strings(delim), false, true)
-}
-
-// StrictUint64s returns list of uint64 divided by given delimiter or error on first invalid input.
-func (k *Key) StrictUint64s(delim string) ([]uint64, error) {
- return k.parseUint64s(k.Strings(delim), false, true)
-}
-
-// StrictTimesFormat parses with given format and returns list of time.Time divided by given delimiter
-// or error on first invalid input.
-func (k *Key) StrictTimesFormat(format, delim string) ([]time.Time, error) {
- return k.parseTimesFormat(format, k.Strings(delim), false, true)
-}
-
-// StrictTimes parses with RFC3339 format and returns list of time.Time divided by given delimiter
-// or error on first invalid input.
-func (k *Key) StrictTimes(delim string) ([]time.Time, error) {
- return k.StrictTimesFormat(time.RFC3339, delim)
-}
-
-// parseFloat64s transforms strings to float64s.
-func (k *Key) parseFloat64s(strs []string, addInvalid, returnOnInvalid bool) ([]float64, error) {
- vals := make([]float64, 0, len(strs))
- for _, str := range strs {
- val, err := strconv.ParseFloat(str, 64)
- if err != nil && returnOnInvalid {
- return nil, err
- }
- if err == nil || addInvalid {
- vals = append(vals, val)
- }
- }
- return vals, nil
-}
-
-// parseInts transforms strings to ints.
-func (k *Key) parseInts(strs []string, addInvalid, returnOnInvalid bool) ([]int, error) {
- vals := make([]int, 0, len(strs))
- for _, str := range strs {
- val, err := strconv.Atoi(str)
- if err != nil && returnOnInvalid {
- return nil, err
- }
- if err == nil || addInvalid {
- vals = append(vals, val)
- }
- }
- return vals, nil
-}
-
-// parseInt64s transforms strings to int64s.
-func (k *Key) parseInt64s(strs []string, addInvalid, returnOnInvalid bool) ([]int64, error) {
- vals := make([]int64, 0, len(strs))
- for _, str := range strs {
- val, err := strconv.ParseInt(str, 10, 64)
- if err != nil && returnOnInvalid {
- return nil, err
- }
- if err == nil || addInvalid {
- vals = append(vals, val)
- }
- }
- return vals, nil
-}
-
-// parseUints transforms strings to uints.
-func (k *Key) parseUints(strs []string, addInvalid, returnOnInvalid bool) ([]uint, error) {
- vals := make([]uint, 0, len(strs))
- for _, str := range strs {
- val, err := strconv.ParseUint(str, 10, 0)
- if err != nil && returnOnInvalid {
- return nil, err
- }
- if err == nil || addInvalid {
- vals = append(vals, uint(val))
- }
- }
- return vals, nil
-}
-
-// parseUint64s transforms strings to uint64s.
-func (k *Key) parseUint64s(strs []string, addInvalid, returnOnInvalid bool) ([]uint64, error) {
- vals := make([]uint64, 0, len(strs))
- for _, str := range strs {
- val, err := strconv.ParseUint(str, 10, 64)
- if err != nil && returnOnInvalid {
- return nil, err
- }
- if err == nil || addInvalid {
- vals = append(vals, val)
- }
- }
- return vals, nil
-}
-
-// parseTimesFormat transforms strings to times in given format.
-func (k *Key) parseTimesFormat(format string, strs []string, addInvalid, returnOnInvalid bool) ([]time.Time, error) {
- vals := make([]time.Time, 0, len(strs))
- for _, str := range strs {
- val, err := time.Parse(format, str)
- if err != nil && returnOnInvalid {
- return nil, err
- }
- if err == nil || addInvalid {
- vals = append(vals, val)
- }
- }
- return vals, nil
-}
-
-// SetValue changes key value.
-func (k *Key) SetValue(v string) {
- if k.s.f.BlockMode {
- k.s.f.lock.Lock()
- defer k.s.f.lock.Unlock()
- }
-
- k.value = v
- k.s.keysHash[k.name] = v
-}
diff --git a/vendor/github.com/go-ini/ini/key_test.go b/vendor/github.com/go-ini/ini/key_test.go
deleted file mode 100644
index 1281d5bf0..000000000
--- a/vendor/github.com/go-ini/ini/key_test.go
+++ /dev/null
@@ -1,573 +0,0 @@
-// Copyright 2014 Unknwon
-//
-// 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 ini
-
-import (
- "bytes"
- "fmt"
- "strings"
- "testing"
- "time"
-
- . "github.com/smartystreets/goconvey/convey"
-)
-
-func Test_Key(t *testing.T) {
- Convey("Test getting and setting values", t, func() {
- cfg, err := Load([]byte(_CONF_DATA), "testdata/conf.ini")
- So(err, ShouldBeNil)
- So(cfg, ShouldNotBeNil)
-
- Convey("Get values in default section", func() {
- sec := cfg.Section("")
- So(sec, ShouldNotBeNil)
- So(sec.Key("NAME").Value(), ShouldEqual, "ini")
- So(sec.Key("NAME").String(), ShouldEqual, "ini")
- So(sec.Key("NAME").Validate(func(in string) string {
- return in
- }), ShouldEqual, "ini")
- So(sec.Key("NAME").Comment, ShouldEqual, "; Package name")
- So(sec.Key("IMPORT_PATH").String(), ShouldEqual, "gopkg.in/ini.v1")
- })
-
- Convey("Get values in non-default section", func() {
- sec := cfg.Section("author")
- So(sec, ShouldNotBeNil)
- So(sec.Key("NAME").String(), ShouldEqual, "Unknwon")
- So(sec.Key("GITHUB").String(), ShouldEqual, "https://github.com/Unknwon")
-
- sec = cfg.Section("package")
- So(sec, ShouldNotBeNil)
- So(sec.Key("CLONE_URL").String(), ShouldEqual, "https://gopkg.in/ini.v1")
- })
-
- Convey("Get auto-increment key names", func() {
- keys := cfg.Section("features").Keys()
- for i, k := range keys {
- So(k.Name(), ShouldEqual, fmt.Sprintf("#%d", i+1))
- }
- })
-
- Convey("Get parent-keys that are available to the child section", func() {
- parentKeys := cfg.Section("package.sub").ParentKeys()
- for _, k := range parentKeys {
- So(k.Name(), ShouldEqual, "CLONE_URL")
- }
- })
-
- Convey("Get overwrite value", func() {
- So(cfg.Section("author").Key("E-MAIL").String(), ShouldEqual, "u@gogs.io")
- })
-
- Convey("Get sections", func() {
- sections := cfg.Sections()
- for i, name := range []string{DEFAULT_SECTION, "author", "package", "package.sub", "features", "types", "array", "note", "comments", "advance"} {
- So(sections[i].Name(), ShouldEqual, name)
- }
- })
-
- Convey("Get parent section value", func() {
- So(cfg.Section("package.sub").Key("CLONE_URL").String(), ShouldEqual, "https://gopkg.in/ini.v1")
- So(cfg.Section("package.fake.sub").Key("CLONE_URL").String(), ShouldEqual, "https://gopkg.in/ini.v1")
- })
-
- Convey("Get multiple line value", func() {
- So(cfg.Section("author").Key("BIO").String(), ShouldEqual, "Gopher.\nCoding addict.\nGood man.\n")
- })
-
- Convey("Get values with type", func() {
- sec := cfg.Section("types")
- v1, err := sec.Key("BOOL").Bool()
- So(err, ShouldBeNil)
- So(v1, ShouldBeTrue)
-
- v1, err = sec.Key("BOOL_FALSE").Bool()
- So(err, ShouldBeNil)
- So(v1, ShouldBeFalse)
-
- v2, err := sec.Key("FLOAT64").Float64()
- So(err, ShouldBeNil)
- So(v2, ShouldEqual, 1.25)
-
- v3, err := sec.Key("INT").Int()
- So(err, ShouldBeNil)
- So(v3, ShouldEqual, 10)
-
- v4, err := sec.Key("INT").Int64()
- So(err, ShouldBeNil)
- So(v4, ShouldEqual, 10)
-
- v5, err := sec.Key("UINT").Uint()
- So(err, ShouldBeNil)
- So(v5, ShouldEqual, 3)
-
- v6, err := sec.Key("UINT").Uint64()
- So(err, ShouldBeNil)
- So(v6, ShouldEqual, 3)
-
- t, err := time.Parse(time.RFC3339, "2015-01-01T20:17:05Z")
- So(err, ShouldBeNil)
- v7, err := sec.Key("TIME").Time()
- So(err, ShouldBeNil)
- So(v7.String(), ShouldEqual, t.String())
-
- Convey("Must get values with type", func() {
- So(sec.Key("STRING").MustString("404"), ShouldEqual, "str")
- So(sec.Key("BOOL").MustBool(), ShouldBeTrue)
- So(sec.Key("FLOAT64").MustFloat64(), ShouldEqual, 1.25)
- So(sec.Key("INT").MustInt(), ShouldEqual, 10)
- So(sec.Key("INT").MustInt64(), ShouldEqual, 10)
- So(sec.Key("UINT").MustUint(), ShouldEqual, 3)
- So(sec.Key("UINT").MustUint64(), ShouldEqual, 3)
- So(sec.Key("TIME").MustTime().String(), ShouldEqual, t.String())
-
- dur, err := time.ParseDuration("2h45m")
- So(err, ShouldBeNil)
- So(sec.Key("DURATION").MustDuration().Seconds(), ShouldEqual, dur.Seconds())
-
- Convey("Must get values with default value", func() {
- So(sec.Key("STRING_404").MustString("404"), ShouldEqual, "404")
- So(sec.Key("BOOL_404").MustBool(true), ShouldBeTrue)
- So(sec.Key("FLOAT64_404").MustFloat64(2.5), ShouldEqual, 2.5)
- So(sec.Key("INT_404").MustInt(15), ShouldEqual, 15)
- So(sec.Key("INT64_404").MustInt64(15), ShouldEqual, 15)
- So(sec.Key("UINT_404").MustUint(6), ShouldEqual, 6)
- So(sec.Key("UINT64_404").MustUint64(6), ShouldEqual, 6)
-
- t, err := time.Parse(time.RFC3339, "2014-01-01T20:17:05Z")
- So(err, ShouldBeNil)
- So(sec.Key("TIME_404").MustTime(t).String(), ShouldEqual, t.String())
-
- So(sec.Key("DURATION_404").MustDuration(dur).Seconds(), ShouldEqual, dur.Seconds())
-
- Convey("Must should set default as key value", func() {
- So(sec.Key("STRING_404").String(), ShouldEqual, "404")
- So(sec.Key("BOOL_404").String(), ShouldEqual, "true")
- So(sec.Key("FLOAT64_404").String(), ShouldEqual, "2.5")
- So(sec.Key("INT_404").String(), ShouldEqual, "15")
- So(sec.Key("INT64_404").String(), ShouldEqual, "15")
- So(sec.Key("UINT_404").String(), ShouldEqual, "6")
- So(sec.Key("UINT64_404").String(), ShouldEqual, "6")
- So(sec.Key("TIME_404").String(), ShouldEqual, "2014-01-01T20:17:05Z")
- So(sec.Key("DURATION_404").String(), ShouldEqual, "2h45m0s")
- })
- })
- })
- })
-
- Convey("Get value with candidates", func() {
- sec := cfg.Section("types")
- So(sec.Key("STRING").In("", []string{"str", "arr", "types"}), ShouldEqual, "str")
- So(sec.Key("FLOAT64").InFloat64(0, []float64{1.25, 2.5, 3.75}), ShouldEqual, 1.25)
- So(sec.Key("INT").InInt(0, []int{10, 20, 30}), ShouldEqual, 10)
- So(sec.Key("INT").InInt64(0, []int64{10, 20, 30}), ShouldEqual, 10)
- So(sec.Key("UINT").InUint(0, []uint{3, 6, 9}), ShouldEqual, 3)
- So(sec.Key("UINT").InUint64(0, []uint64{3, 6, 9}), ShouldEqual, 3)
-
- zt, err := time.Parse(time.RFC3339, "0001-01-01T01:00:00Z")
- So(err, ShouldBeNil)
- t, err := time.Parse(time.RFC3339, "2015-01-01T20:17:05Z")
- So(err, ShouldBeNil)
- So(sec.Key("TIME").InTime(zt, []time.Time{t, time.Now(), time.Now().Add(1 * time.Second)}).String(), ShouldEqual, t.String())
-
- Convey("Get value with candidates and default value", func() {
- So(sec.Key("STRING_404").In("str", []string{"str", "arr", "types"}), ShouldEqual, "str")
- So(sec.Key("FLOAT64_404").InFloat64(1.25, []float64{1.25, 2.5, 3.75}), ShouldEqual, 1.25)
- So(sec.Key("INT_404").InInt(10, []int{10, 20, 30}), ShouldEqual, 10)
- So(sec.Key("INT64_404").InInt64(10, []int64{10, 20, 30}), ShouldEqual, 10)
- So(sec.Key("UINT_404").InUint(3, []uint{3, 6, 9}), ShouldEqual, 3)
- So(sec.Key("UINT_404").InUint64(3, []uint64{3, 6, 9}), ShouldEqual, 3)
- So(sec.Key("TIME_404").InTime(t, []time.Time{time.Now(), time.Now(), time.Now().Add(1 * time.Second)}).String(), ShouldEqual, t.String())
- })
- })
-
- Convey("Get values in range", func() {
- sec := cfg.Section("types")
- So(sec.Key("FLOAT64").RangeFloat64(0, 1, 2), ShouldEqual, 1.25)
- So(sec.Key("INT").RangeInt(0, 10, 20), ShouldEqual, 10)
- So(sec.Key("INT").RangeInt64(0, 10, 20), ShouldEqual, 10)
-
- minT, err := time.Parse(time.RFC3339, "0001-01-01T01:00:00Z")
- So(err, ShouldBeNil)
- midT, err := time.Parse(time.RFC3339, "2013-01-01T01:00:00Z")
- So(err, ShouldBeNil)
- maxT, err := time.Parse(time.RFC3339, "9999-01-01T01:00:00Z")
- So(err, ShouldBeNil)
- t, err := time.Parse(time.RFC3339, "2015-01-01T20:17:05Z")
- So(err, ShouldBeNil)
- So(sec.Key("TIME").RangeTime(t, minT, maxT).String(), ShouldEqual, t.String())
-
- Convey("Get value in range with default value", func() {
- So(sec.Key("FLOAT64").RangeFloat64(5, 0, 1), ShouldEqual, 5)
- So(sec.Key("INT").RangeInt(7, 0, 5), ShouldEqual, 7)
- So(sec.Key("INT").RangeInt64(7, 0, 5), ShouldEqual, 7)
- So(sec.Key("TIME").RangeTime(t, minT, midT).String(), ShouldEqual, t.String())
- })
- })
-
- Convey("Get values into slice", func() {
- sec := cfg.Section("array")
- So(strings.Join(sec.Key("STRINGS").Strings(","), ","), ShouldEqual, "en,zh,de")
- So(len(sec.Key("STRINGS_404").Strings(",")), ShouldEqual, 0)
-
- vals1 := sec.Key("FLOAT64S").Float64s(",")
- float64sEqual(vals1, 1.1, 2.2, 3.3)
-
- vals2 := sec.Key("INTS").Ints(",")
- intsEqual(vals2, 1, 2, 3)
-
- vals3 := sec.Key("INTS").Int64s(",")
- int64sEqual(vals3, 1, 2, 3)
-
- vals4 := sec.Key("UINTS").Uints(",")
- uintsEqual(vals4, 1, 2, 3)
-
- vals5 := sec.Key("UINTS").Uint64s(",")
- uint64sEqual(vals5, 1, 2, 3)
-
- t, err := time.Parse(time.RFC3339, "2015-01-01T20:17:05Z")
- So(err, ShouldBeNil)
- vals6 := sec.Key("TIMES").Times(",")
- timesEqual(vals6, t, t, t)
- })
-
- Convey("Get valid values into slice", func() {
- sec := cfg.Section("array")
- vals1 := sec.Key("FLOAT64S").ValidFloat64s(",")
- float64sEqual(vals1, 1.1, 2.2, 3.3)
-
- vals2 := sec.Key("INTS").ValidInts(",")
- intsEqual(vals2, 1, 2, 3)
-
- vals3 := sec.Key("INTS").ValidInt64s(",")
- int64sEqual(vals3, 1, 2, 3)
-
- vals4 := sec.Key("UINTS").ValidUints(",")
- uintsEqual(vals4, 1, 2, 3)
-
- vals5 := sec.Key("UINTS").ValidUint64s(",")
- uint64sEqual(vals5, 1, 2, 3)
-
- t, err := time.Parse(time.RFC3339, "2015-01-01T20:17:05Z")
- So(err, ShouldBeNil)
- vals6 := sec.Key("TIMES").ValidTimes(",")
- timesEqual(vals6, t, t, t)
- })
-
- Convey("Get values one type into slice of another type", func() {
- sec := cfg.Section("array")
- vals1 := sec.Key("STRINGS").ValidFloat64s(",")
- So(vals1, ShouldBeEmpty)
-
- vals2 := sec.Key("STRINGS").ValidInts(",")
- So(vals2, ShouldBeEmpty)
-
- vals3 := sec.Key("STRINGS").ValidInt64s(",")
- So(vals3, ShouldBeEmpty)
-
- vals4 := sec.Key("STRINGS").ValidUints(",")
- So(vals4, ShouldBeEmpty)
-
- vals5 := sec.Key("STRINGS").ValidUint64s(",")
- So(vals5, ShouldBeEmpty)
-
- vals6 := sec.Key("STRINGS").ValidTimes(",")
- So(vals6, ShouldBeEmpty)
- })
-
- Convey("Get valid values into slice without errors", func() {
- sec := cfg.Section("array")
- vals1, err := sec.Key("FLOAT64S").StrictFloat64s(",")
- So(err, ShouldBeNil)
- float64sEqual(vals1, 1.1, 2.2, 3.3)
-
- vals2, err := sec.Key("INTS").StrictInts(",")
- So(err, ShouldBeNil)
- intsEqual(vals2, 1, 2, 3)
-
- vals3, err := sec.Key("INTS").StrictInt64s(",")
- So(err, ShouldBeNil)
- int64sEqual(vals3, 1, 2, 3)
-
- vals4, err := sec.Key("UINTS").StrictUints(",")
- So(err, ShouldBeNil)
- uintsEqual(vals4, 1, 2, 3)
-
- vals5, err := sec.Key("UINTS").StrictUint64s(",")
- So(err, ShouldBeNil)
- uint64sEqual(vals5, 1, 2, 3)
-
- t, err := time.Parse(time.RFC3339, "2015-01-01T20:17:05Z")
- So(err, ShouldBeNil)
- vals6, err := sec.Key("TIMES").StrictTimes(",")
- So(err, ShouldBeNil)
- timesEqual(vals6, t, t, t)
- })
-
- Convey("Get invalid values into slice", func() {
- sec := cfg.Section("array")
- vals1, err := sec.Key("STRINGS").StrictFloat64s(",")
- So(vals1, ShouldBeEmpty)
- So(err, ShouldNotBeNil)
-
- vals2, err := sec.Key("STRINGS").StrictInts(",")
- So(vals2, ShouldBeEmpty)
- So(err, ShouldNotBeNil)
-
- vals3, err := sec.Key("STRINGS").StrictInt64s(",")
- So(vals3, ShouldBeEmpty)
- So(err, ShouldNotBeNil)
-
- vals4, err := sec.Key("STRINGS").StrictUints(",")
- So(vals4, ShouldBeEmpty)
- So(err, ShouldNotBeNil)
-
- vals5, err := sec.Key("STRINGS").StrictUint64s(",")
- So(vals5, ShouldBeEmpty)
- So(err, ShouldNotBeNil)
-
- vals6, err := sec.Key("STRINGS").StrictTimes(",")
- So(vals6, ShouldBeEmpty)
- So(err, ShouldNotBeNil)
- })
-
- Convey("Get key hash", func() {
- cfg.Section("").KeysHash()
- })
-
- Convey("Set key value", func() {
- k := cfg.Section("author").Key("NAME")
- k.SetValue("无闻")
- So(k.String(), ShouldEqual, "无闻")
- })
-
- Convey("Get key strings", func() {
- So(strings.Join(cfg.Section("types").KeyStrings(), ","), ShouldEqual, "STRING,BOOL,BOOL_FALSE,FLOAT64,INT,TIME,DURATION,UINT")
- })
-
- Convey("Delete a key", func() {
- cfg.Section("package.sub").DeleteKey("UNUSED_KEY")
- _, err := cfg.Section("package.sub").GetKey("UNUSED_KEY")
- So(err, ShouldNotBeNil)
- })
-
- Convey("Has Key (backwards compatible)", func() {
- sec := cfg.Section("package.sub")
- haskey1 := sec.Haskey("UNUSED_KEY")
- haskey2 := sec.Haskey("CLONE_URL")
- haskey3 := sec.Haskey("CLONE_URL_NO")
- So(haskey1, ShouldBeTrue)
- So(haskey2, ShouldBeTrue)
- So(haskey3, ShouldBeFalse)
- })
-
- Convey("Has Key", func() {
- sec := cfg.Section("package.sub")
- haskey1 := sec.HasKey("UNUSED_KEY")
- haskey2 := sec.HasKey("CLONE_URL")
- haskey3 := sec.HasKey("CLONE_URL_NO")
- So(haskey1, ShouldBeTrue)
- So(haskey2, ShouldBeTrue)
- So(haskey3, ShouldBeFalse)
- })
-
- Convey("Has Value", func() {
- sec := cfg.Section("author")
- hasvalue1 := sec.HasValue("Unknwon")
- hasvalue2 := sec.HasValue("doc")
- So(hasvalue1, ShouldBeTrue)
- So(hasvalue2, ShouldBeFalse)
- })
- })
-
- Convey("Test getting and setting bad values", t, func() {
- cfg, err := Load([]byte(_CONF_DATA), "testdata/conf.ini")
- So(err, ShouldBeNil)
- So(cfg, ShouldNotBeNil)
-
- Convey("Create new key with empty name", func() {
- k, err := cfg.Section("").NewKey("", "")
- So(err, ShouldNotBeNil)
- So(k, ShouldBeNil)
- })
-
- Convey("Create new section with empty name", func() {
- s, err := cfg.NewSection("")
- So(err, ShouldNotBeNil)
- So(s, ShouldBeNil)
- })
-
- Convey("Create new sections with empty name", func() {
- So(cfg.NewSections(""), ShouldNotBeNil)
- })
-
- Convey("Get section that not exists", func() {
- s, err := cfg.GetSection("404")
- So(err, ShouldNotBeNil)
- So(s, ShouldBeNil)
-
- s = cfg.Section("404")
- So(s, ShouldNotBeNil)
- })
- })
-
- Convey("Test key hash clone", t, func() {
- cfg, err := Load([]byte(strings.Replace("network=tcp,addr=127.0.0.1:6379,db=4,pool_size=100,idle_timeout=180", ",", "\n", -1)))
- So(err, ShouldBeNil)
- for _, v := range cfg.Section("").KeysHash() {
- So(len(v), ShouldBeGreaterThan, 0)
- }
- })
-
- Convey("Key has empty value", t, func() {
- _conf := `key1=
-key2= ; comment`
- cfg, err := Load([]byte(_conf))
- So(err, ShouldBeNil)
- So(cfg.Section("").Key("key1").Value(), ShouldBeEmpty)
- })
-}
-
-const _CONF_GIT_CONFIG = `
-[remote "origin"]
- url = https://github.com/Antergone/test1.git
- url = https://github.com/Antergone/test2.git
-`
-
-func Test_Key_Shadows(t *testing.T) {
- Convey("Shadows keys", t, func() {
- Convey("Disable shadows", func() {
- cfg, err := Load([]byte(_CONF_GIT_CONFIG))
- So(err, ShouldBeNil)
- So(cfg.Section(`remote "origin"`).Key("url").String(), ShouldEqual, "https://github.com/Antergone/test2.git")
- })
-
- Convey("Enable shadows", func() {
- cfg, err := ShadowLoad([]byte(_CONF_GIT_CONFIG))
- So(err, ShouldBeNil)
- So(cfg.Section(`remote "origin"`).Key("url").String(), ShouldEqual, "https://github.com/Antergone/test1.git")
- So(strings.Join(cfg.Section(`remote "origin"`).Key("url").ValueWithShadows(), " "), ShouldEqual,
- "https://github.com/Antergone/test1.git https://github.com/Antergone/test2.git")
-
- Convey("Save with shadows", func() {
- var buf bytes.Buffer
- _, err := cfg.WriteTo(&buf)
- So(err, ShouldBeNil)
- So(buf.String(), ShouldEqual, `[remote "origin"]
-url = https://github.com/Antergone/test1.git
-url = https://github.com/Antergone/test2.git
-
-`)
- })
- })
- })
-}
-
-func newTestFile(block bool) *File {
- c, _ := Load([]byte(_CONF_DATA))
- c.BlockMode = block
- return c
-}
-
-func Benchmark_Key_Value(b *testing.B) {
- c := newTestFile(true)
- for i := 0; i < b.N; i++ {
- c.Section("").Key("NAME").Value()
- }
-}
-
-func Benchmark_Key_Value_NonBlock(b *testing.B) {
- c := newTestFile(false)
- for i := 0; i < b.N; i++ {
- c.Section("").Key("NAME").Value()
- }
-}
-
-func Benchmark_Key_Value_ViaSection(b *testing.B) {
- c := newTestFile(true)
- sec := c.Section("")
- for i := 0; i < b.N; i++ {
- sec.Key("NAME").Value()
- }
-}
-
-func Benchmark_Key_Value_ViaSection_NonBlock(b *testing.B) {
- c := newTestFile(false)
- sec := c.Section("")
- for i := 0; i < b.N; i++ {
- sec.Key("NAME").Value()
- }
-}
-
-func Benchmark_Key_Value_Direct(b *testing.B) {
- c := newTestFile(true)
- key := c.Section("").Key("NAME")
- for i := 0; i < b.N; i++ {
- key.Value()
- }
-}
-
-func Benchmark_Key_Value_Direct_NonBlock(b *testing.B) {
- c := newTestFile(false)
- key := c.Section("").Key("NAME")
- for i := 0; i < b.N; i++ {
- key.Value()
- }
-}
-
-func Benchmark_Key_String(b *testing.B) {
- c := newTestFile(true)
- for i := 0; i < b.N; i++ {
- _ = c.Section("").Key("NAME").String()
- }
-}
-
-func Benchmark_Key_String_NonBlock(b *testing.B) {
- c := newTestFile(false)
- for i := 0; i < b.N; i++ {
- _ = c.Section("").Key("NAME").String()
- }
-}
-
-func Benchmark_Key_String_ViaSection(b *testing.B) {
- c := newTestFile(true)
- sec := c.Section("")
- for i := 0; i < b.N; i++ {
- _ = sec.Key("NAME").String()
- }
-}
-
-func Benchmark_Key_String_ViaSection_NonBlock(b *testing.B) {
- c := newTestFile(false)
- sec := c.Section("")
- for i := 0; i < b.N; i++ {
- _ = sec.Key("NAME").String()
- }
-}
-
-func Benchmark_Key_SetValue(b *testing.B) {
- c := newTestFile(true)
- for i := 0; i < b.N; i++ {
- c.Section("").Key("NAME").SetValue("10")
- }
-}
-
-func Benchmark_Key_SetValue_VisSection(b *testing.B) {
- c := newTestFile(true)
- sec := c.Section("")
- for i := 0; i < b.N; i++ {
- sec.Key("NAME").SetValue("10")
- }
-}
diff --git a/vendor/github.com/go-ini/ini/parser.go b/vendor/github.com/go-ini/ini/parser.go
deleted file mode 100644
index 6c0b10745..000000000
--- a/vendor/github.com/go-ini/ini/parser.go
+++ /dev/null
@@ -1,361 +0,0 @@
-// Copyright 2015 Unknwon
-//
-// 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 ini
-
-import (
- "bufio"
- "bytes"
- "fmt"
- "io"
- "strconv"
- "strings"
- "unicode"
-)
-
-type tokenType int
-
-const (
- _TOKEN_INVALID tokenType = iota
- _TOKEN_COMMENT
- _TOKEN_SECTION
- _TOKEN_KEY
-)
-
-type parser struct {
- buf *bufio.Reader
- isEOF bool
- count int
- comment *bytes.Buffer
-}
-
-func newParser(r io.Reader) *parser {
- return &parser{
- buf: bufio.NewReader(r),
- count: 1,
- comment: &bytes.Buffer{},
- }
-}
-
-// BOM handles header of UTF-8, UTF-16 LE and UTF-16 BE's BOM format.
-// http://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding
-func (p *parser) BOM() error {
- mask, err := p.buf.Peek(2)
- if err != nil && err != io.EOF {
- return err
- } else if len(mask) < 2 {
- return nil
- }
-
- switch {
- case mask[0] == 254 && mask[1] == 255:
- fallthrough
- case mask[0] == 255 && mask[1] == 254:
- p.buf.Read(mask)
- case mask[0] == 239 && mask[1] == 187:
- mask, err := p.buf.Peek(3)
- if err != nil && err != io.EOF {
- return err
- } else if len(mask) < 3 {
- return nil
- }
- if mask[2] == 191 {
- p.buf.Read(mask)
- }
- }
- return nil
-}
-
-func (p *parser) readUntil(delim byte) ([]byte, error) {
- data, err := p.buf.ReadBytes(delim)
- if err != nil {
- if err == io.EOF {
- p.isEOF = true
- } else {
- return nil, err
- }
- }
- return data, nil
-}
-
-func cleanComment(in []byte) ([]byte, bool) {
- i := bytes.IndexAny(in, "#;")
- if i == -1 {
- return nil, false
- }
- return in[i:], true
-}
-
-func readKeyName(in []byte) (string, int, error) {
- line := string(in)
-
- // Check if key name surrounded by quotes.
- var keyQuote string
- if line[0] == '"' {
- if len(line) > 6 && string(line[0:3]) == `"""` {
- keyQuote = `"""`
- } else {
- keyQuote = `"`
- }
- } else if line[0] == '`' {
- keyQuote = "`"
- }
-
- // Get out key name
- endIdx := -1
- if len(keyQuote) > 0 {
- startIdx := len(keyQuote)
- // FIXME: fail case -> """"""name"""=value
- pos := strings.Index(line[startIdx:], keyQuote)
- if pos == -1 {
- return "", -1, fmt.Errorf("missing closing key quote: %s", line)
- }
- pos += startIdx
-
- // Find key-value delimiter
- i := strings.IndexAny(line[pos+startIdx:], "=:")
- if i < 0 {
- return "", -1, ErrDelimiterNotFound{line}
- }
- endIdx = pos + i
- return strings.TrimSpace(line[startIdx:pos]), endIdx + startIdx + 1, nil
- }
-
- endIdx = strings.IndexAny(line, "=:")
- if endIdx < 0 {
- return "", -1, ErrDelimiterNotFound{line}
- }
- return strings.TrimSpace(line[0:endIdx]), endIdx + 1, nil
-}
-
-func (p *parser) readMultilines(line, val, valQuote string) (string, error) {
- for {
- data, err := p.readUntil('\n')
- if err != nil {
- return "", err
- }
- next := string(data)
-
- pos := strings.LastIndex(next, valQuote)
- if pos > -1 {
- val += next[:pos]
-
- comment, has := cleanComment([]byte(next[pos:]))
- if has {
- p.comment.Write(bytes.TrimSpace(comment))
- }
- break
- }
- val += next
- if p.isEOF {
- return "", fmt.Errorf("missing closing key quote from '%s' to '%s'", line, next)
- }
- }
- return val, nil
-}
-
-func (p *parser) readContinuationLines(val string) (string, error) {
- for {
- data, err := p.readUntil('\n')
- if err != nil {
- return "", err
- }
- next := strings.TrimSpace(string(data))
-
- if len(next) == 0 {
- break
- }
- val += next
- if val[len(val)-1] != '\\' {
- break
- }
- val = val[:len(val)-1]
- }
- return val, nil
-}
-
-// hasSurroundedQuote check if and only if the first and last characters
-// are quotes \" or \'.
-// It returns false if any other parts also contain same kind of quotes.
-func hasSurroundedQuote(in string, quote byte) bool {
- return len(in) > 2 && in[0] == quote && in[len(in)-1] == quote &&
- strings.IndexByte(in[1:], quote) == len(in)-2
-}
-
-func (p *parser) readValue(in []byte, ignoreContinuation, ignoreInlineComment bool) (string, error) {
- line := strings.TrimLeftFunc(string(in), unicode.IsSpace)
- if len(line) == 0 {
- return "", nil
- }
-
- var valQuote string
- if len(line) > 3 && string(line[0:3]) == `"""` {
- valQuote = `"""`
- } else if line[0] == '`' {
- valQuote = "`"
- }
-
- if len(valQuote) > 0 {
- startIdx := len(valQuote)
- pos := strings.LastIndex(line[startIdx:], valQuote)
- // Check for multi-line value
- if pos == -1 {
- return p.readMultilines(line, line[startIdx:], valQuote)
- }
-
- return line[startIdx : pos+startIdx], nil
- }
-
- // Won't be able to reach here if value only contains whitespace
- line = strings.TrimSpace(line)
-
- // Check continuation lines when desired
- if !ignoreContinuation && line[len(line)-1] == '\\' {
- return p.readContinuationLines(line[:len(line)-1])
- }
-
- // Check if ignore inline comment
- if !ignoreInlineComment {
- i := strings.IndexAny(line, "#;")
- if i > -1 {
- p.comment.WriteString(line[i:])
- line = strings.TrimSpace(line[:i])
- }
- }
-
- // Trim single quotes
- if hasSurroundedQuote(line, '\'') ||
- hasSurroundedQuote(line, '"') {
- line = line[1 : len(line)-1]
- }
- return line, nil
-}
-
-// parse parses data through an io.Reader.
-func (f *File) parse(reader io.Reader) (err error) {
- p := newParser(reader)
- if err = p.BOM(); err != nil {
- return fmt.Errorf("BOM: %v", err)
- }
-
- // Ignore error because default section name is never empty string.
- section, _ := f.NewSection(DEFAULT_SECTION)
-
- var line []byte
- var inUnparseableSection bool
- for !p.isEOF {
- line, err = p.readUntil('\n')
- if err != nil {
- return err
- }
-
- line = bytes.TrimLeftFunc(line, unicode.IsSpace)
- if len(line) == 0 {
- continue
- }
-
- // Comments
- if line[0] == '#' || line[0] == ';' {
- // Note: we do not care ending line break,
- // it is needed for adding second line,
- // so just clean it once at the end when set to value.
- p.comment.Write(line)
- continue
- }
-
- // Section
- if line[0] == '[' {
- // Read to the next ']' (TODO: support quoted strings)
- // TODO(unknwon): use LastIndexByte when stop supporting Go1.4
- closeIdx := bytes.LastIndex(line, []byte("]"))
- if closeIdx == -1 {
- return fmt.Errorf("unclosed section: %s", line)
- }
-
- name := string(line[1:closeIdx])
- section, err = f.NewSection(name)
- if err != nil {
- return err
- }
-
- comment, has := cleanComment(line[closeIdx+1:])
- if has {
- p.comment.Write(comment)
- }
-
- section.Comment = strings.TrimSpace(p.comment.String())
-
- // Reset aotu-counter and comments
- p.comment.Reset()
- p.count = 1
-
- inUnparseableSection = false
- for i := range f.options.UnparseableSections {
- if f.options.UnparseableSections[i] == name ||
- (f.options.Insensitive && strings.ToLower(f.options.UnparseableSections[i]) == strings.ToLower(name)) {
- inUnparseableSection = true
- continue
- }
- }
- continue
- }
-
- if inUnparseableSection {
- section.isRawSection = true
- section.rawBody += string(line)
- continue
- }
-
- kname, offset, err := readKeyName(line)
- if err != nil {
- // Treat as boolean key when desired, and whole line is key name.
- if IsErrDelimiterNotFound(err) && f.options.AllowBooleanKeys {
- kname, err := p.readValue(line, f.options.IgnoreContinuation, f.options.IgnoreInlineComment)
- if err != nil {
- return err
- }
- key, err := section.NewBooleanKey(kname)
- if err != nil {
- return err
- }
- key.Comment = strings.TrimSpace(p.comment.String())
- p.comment.Reset()
- continue
- }
- return err
- }
-
- // Auto increment.
- isAutoIncr := false
- if kname == "-" {
- isAutoIncr = true
- kname = "#" + strconv.Itoa(p.count)
- p.count++
- }
-
- value, err := p.readValue(line[offset:], f.options.IgnoreContinuation, f.options.IgnoreInlineComment)
- if err != nil {
- return err
- }
-
- key, err := section.NewKey(kname, value)
- if err != nil {
- return err
- }
- key.isAutoIncrement = isAutoIncr
- key.Comment = strings.TrimSpace(p.comment.String())
- p.comment.Reset()
- }
- return nil
-}
diff --git a/vendor/github.com/go-ini/ini/parser_test.go b/vendor/github.com/go-ini/ini/parser_test.go
deleted file mode 100644
index 05258195b..000000000
--- a/vendor/github.com/go-ini/ini/parser_test.go
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright 2016 Unknwon
-//
-// 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 ini
-
-import (
- "testing"
-
- . "github.com/smartystreets/goconvey/convey"
-)
-
-func Test_BOM(t *testing.T) {
- Convey("Test handling BOM", t, func() {
- Convey("UTF-8-BOM", func() {
- cfg, err := Load("testdata/UTF-8-BOM.ini")
- So(err, ShouldBeNil)
- So(cfg, ShouldNotBeNil)
-
- So(cfg.Section("author").Key("E-MAIL").String(), ShouldEqual, "u@gogs.io")
- })
-
- Convey("UTF-16-LE-BOM", func() {
- cfg, err := Load("testdata/UTF-16-LE-BOM.ini")
- So(err, ShouldBeNil)
- So(cfg, ShouldNotBeNil)
- })
-
- Convey("UTF-16-BE-BOM", func() {
- })
- })
-}
diff --git a/vendor/github.com/go-ini/ini/section.go b/vendor/github.com/go-ini/ini/section.go
deleted file mode 100644
index 94f7375ed..000000000
--- a/vendor/github.com/go-ini/ini/section.go
+++ /dev/null
@@ -1,248 +0,0 @@
-// Copyright 2014 Unknwon
-//
-// 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 ini
-
-import (
- "errors"
- "fmt"
- "strings"
-)
-
-// Section represents a config section.
-type Section struct {
- f *File
- Comment string
- name string
- keys map[string]*Key
- keyList []string
- keysHash map[string]string
-
- isRawSection bool
- rawBody string
-}
-
-func newSection(f *File, name string) *Section {
- return &Section{
- f: f,
- name: name,
- keys: make(map[string]*Key),
- keyList: make([]string, 0, 10),
- keysHash: make(map[string]string),
- }
-}
-
-// Name returns name of Section.
-func (s *Section) Name() string {
- return s.name
-}
-
-// Body returns rawBody of Section if the section was marked as unparseable.
-// It still follows the other rules of the INI format surrounding leading/trailing whitespace.
-func (s *Section) Body() string {
- return strings.TrimSpace(s.rawBody)
-}
-
-// NewKey creates a new key to given section.
-func (s *Section) NewKey(name, val string) (*Key, error) {
- if len(name) == 0 {
- return nil, errors.New("error creating new key: empty key name")
- } else if s.f.options.Insensitive {
- name = strings.ToLower(name)
- }
-
- if s.f.BlockMode {
- s.f.lock.Lock()
- defer s.f.lock.Unlock()
- }
-
- if inSlice(name, s.keyList) {
- if s.f.options.AllowShadows {
- if err := s.keys[name].addShadow(val); err != nil {
- return nil, err
- }
- } else {
- s.keys[name].value = val
- }
- return s.keys[name], nil
- }
-
- s.keyList = append(s.keyList, name)
- s.keys[name] = newKey(s, name, val)
- s.keysHash[name] = val
- return s.keys[name], nil
-}
-
-// NewBooleanKey creates a new boolean type key to given section.
-func (s *Section) NewBooleanKey(name string) (*Key, error) {
- key, err := s.NewKey(name, "true")
- if err != nil {
- return nil, err
- }
-
- key.isBooleanType = true
- return key, nil
-}
-
-// GetKey returns key in section by given name.
-func (s *Section) GetKey(name string) (*Key, error) {
- // FIXME: change to section level lock?
- if s.f.BlockMode {
- s.f.lock.RLock()
- }
- if s.f.options.Insensitive {
- name = strings.ToLower(name)
- }
- key := s.keys[name]
- if s.f.BlockMode {
- s.f.lock.RUnlock()
- }
-
- if key == nil {
- // Check if it is a child-section.
- sname := s.name
- for {
- if i := strings.LastIndex(sname, "."); i > -1 {
- sname = sname[:i]
- sec, err := s.f.GetSection(sname)
- if err != nil {
- continue
- }
- return sec.GetKey(name)
- } else {
- break
- }
- }
- return nil, fmt.Errorf("error when getting key of section '%s': key '%s' not exists", s.name, name)
- }
- return key, nil
-}
-
-// HasKey returns true if section contains a key with given name.
-func (s *Section) HasKey(name string) bool {
- key, _ := s.GetKey(name)
- return key != nil
-}
-
-// Haskey is a backwards-compatible name for HasKey.
-func (s *Section) Haskey(name string) bool {
- return s.HasKey(name)
-}
-
-// HasValue returns true if section contains given raw value.
-func (s *Section) HasValue(value string) bool {
- if s.f.BlockMode {
- s.f.lock.RLock()
- defer s.f.lock.RUnlock()
- }
-
- for _, k := range s.keys {
- if value == k.value {
- return true
- }
- }
- return false
-}
-
-// Key assumes named Key exists in section and returns a zero-value when not.
-func (s *Section) Key(name string) *Key {
- key, err := s.GetKey(name)
- if err != nil {
- // It's OK here because the only possible error is empty key name,
- // but if it's empty, this piece of code won't be executed.
- key, _ = s.NewKey(name, "")
- return key
- }
- return key
-}
-
-// Keys returns list of keys of section.
-func (s *Section) Keys() []*Key {
- keys := make([]*Key, len(s.keyList))
- for i := range s.keyList {
- keys[i] = s.Key(s.keyList[i])
- }
- return keys
-}
-
-// ParentKeys returns list of keys of parent section.
-func (s *Section) ParentKeys() []*Key {
- var parentKeys []*Key
- sname := s.name
- for {
- if i := strings.LastIndex(sname, "."); i > -1 {
- sname = sname[:i]
- sec, err := s.f.GetSection(sname)
- if err != nil {
- continue
- }
- parentKeys = append(parentKeys, sec.Keys()...)
- } else {
- break
- }
-
- }
- return parentKeys
-}
-
-// KeyStrings returns list of key names of section.
-func (s *Section) KeyStrings() []string {
- list := make([]string, len(s.keyList))
- copy(list, s.keyList)
- return list
-}
-
-// KeysHash returns keys hash consisting of names and values.
-func (s *Section) KeysHash() map[string]string {
- if s.f.BlockMode {
- s.f.lock.RLock()
- defer s.f.lock.RUnlock()
- }
-
- hash := map[string]string{}
- for key, value := range s.keysHash {
- hash[key] = value
- }
- return hash
-}
-
-// DeleteKey deletes a key from section.
-func (s *Section) DeleteKey(name string) {
- if s.f.BlockMode {
- s.f.lock.Lock()
- defer s.f.lock.Unlock()
- }
-
- for i, k := range s.keyList {
- if k == name {
- s.keyList = append(s.keyList[:i], s.keyList[i+1:]...)
- delete(s.keys, name)
- return
- }
- }
-}
-
-// ChildSections returns a list of child sections of current section.
-// For example, "[parent.child1]" and "[parent.child12]" are child sections
-// of section "[parent]".
-func (s *Section) ChildSections() []*Section {
- prefix := s.name + "."
- children := make([]*Section, 0, 3)
- for _, name := range s.f.sectionList {
- if strings.HasPrefix(name, prefix) {
- children = append(children, s.f.sections[name])
- }
- }
- return children
-}
diff --git a/vendor/github.com/go-ini/ini/section_test.go b/vendor/github.com/go-ini/ini/section_test.go
deleted file mode 100644
index 80282c197..000000000
--- a/vendor/github.com/go-ini/ini/section_test.go
+++ /dev/null
@@ -1,75 +0,0 @@
-// Copyright 2014 Unknwon
-//
-// 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 ini
-
-import (
- "strings"
- "testing"
-
- . "github.com/smartystreets/goconvey/convey"
-)
-
-func Test_Section(t *testing.T) {
- Convey("Test CRD sections", t, func() {
- cfg, err := Load([]byte(_CONF_DATA), "testdata/conf.ini")
- So(err, ShouldBeNil)
- So(cfg, ShouldNotBeNil)
-
- Convey("Get section strings", func() {
- So(strings.Join(cfg.SectionStrings(), ","), ShouldEqual, "DEFAULT,author,package,package.sub,features,types,array,note,comments,advance")
- })
-
- Convey("Delete a section", func() {
- cfg.DeleteSection("")
- So(cfg.SectionStrings()[0], ShouldNotEqual, DEFAULT_SECTION)
- })
-
- Convey("Create new sections", func() {
- cfg.NewSections("test", "test2")
- _, err := cfg.GetSection("test")
- So(err, ShouldBeNil)
- _, err = cfg.GetSection("test2")
- So(err, ShouldBeNil)
- })
- })
-}
-
-func Test_SectionRaw(t *testing.T) {
- Convey("Test section raw string", t, func() {
- cfg, err := LoadSources(
- LoadOptions{
- Insensitive: true,
- UnparseableSections: []string{"core_lesson", "comments"},
- },
- "testdata/aicc.ini")
- So(err, ShouldBeNil)
- So(cfg, ShouldNotBeNil)
-
- Convey("Get section strings", func() {
- So(strings.Join(cfg.SectionStrings(), ","), ShouldEqual, "DEFAULT,core,core_lesson,comments")
- })
-
- Convey("Validate non-raw section", func() {
- val, err := cfg.Section("core").GetKey("lesson_status")
- So(err, ShouldBeNil)
- So(val.String(), ShouldEqual, "C")
- })
-
- Convey("Validate raw section", func() {
- So(cfg.Section("core_lesson").Body(), ShouldEqual, `my lesson state data – 1111111111111111111000000000000000001110000
-111111111111111111100000000000111000000000 – end my lesson state data`)
- })
- })
-} \ No newline at end of file
diff --git a/vendor/github.com/go-ini/ini/struct.go b/vendor/github.com/go-ini/ini/struct.go
deleted file mode 100644
index 031c78b8e..000000000
--- a/vendor/github.com/go-ini/ini/struct.go
+++ /dev/null
@@ -1,450 +0,0 @@
-// Copyright 2014 Unknwon
-//
-// 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 ini
-
-import (
- "bytes"
- "errors"
- "fmt"
- "reflect"
- "strings"
- "time"
- "unicode"
-)
-
-// NameMapper represents a ini tag name mapper.
-type NameMapper func(string) string
-
-// Built-in name getters.
-var (
- // AllCapsUnderscore converts to format ALL_CAPS_UNDERSCORE.
- AllCapsUnderscore NameMapper = func(raw string) string {
- newstr := make([]rune, 0, len(raw))
- for i, chr := range raw {
- if isUpper := 'A' <= chr && chr <= 'Z'; isUpper {
- if i > 0 {
- newstr = append(newstr, '_')
- }
- }
- newstr = append(newstr, unicode.ToUpper(chr))
- }
- return string(newstr)
- }
- // TitleUnderscore converts to format title_underscore.
- TitleUnderscore NameMapper = func(raw string) string {
- newstr := make([]rune, 0, len(raw))
- for i, chr := range raw {
- if isUpper := 'A' <= chr && chr <= 'Z'; isUpper {
- if i > 0 {
- newstr = append(newstr, '_')
- }
- chr -= ('A' - 'a')
- }
- newstr = append(newstr, chr)
- }
- return string(newstr)
- }
-)
-
-func (s *Section) parseFieldName(raw, actual string) string {
- if len(actual) > 0 {
- return actual
- }
- if s.f.NameMapper != nil {
- return s.f.NameMapper(raw)
- }
- return raw
-}
-
-func parseDelim(actual string) string {
- if len(actual) > 0 {
- return actual
- }
- return ","
-}
-
-var reflectTime = reflect.TypeOf(time.Now()).Kind()
-
-// setSliceWithProperType sets proper values to slice based on its type.
-func setSliceWithProperType(key *Key, field reflect.Value, delim string, allowShadow bool) error {
- var strs []string
- if allowShadow {
- strs = key.StringsWithShadows(delim)
- } else {
- strs = key.Strings(delim)
- }
-
- numVals := len(strs)
- if numVals == 0 {
- return nil
- }
-
- var vals interface{}
-
- sliceOf := field.Type().Elem().Kind()
- switch sliceOf {
- case reflect.String:
- vals = strs
- case reflect.Int:
- vals, _ = key.parseInts(strs, true, false)
- case reflect.Int64:
- vals, _ = key.parseInt64s(strs, true, false)
- case reflect.Uint:
- vals, _ = key.parseUints(strs, true, false)
- case reflect.Uint64:
- vals, _ = key.parseUint64s(strs, true, false)
- case reflect.Float64:
- vals, _ = key.parseFloat64s(strs, true, false)
- case reflectTime:
- vals, _ = key.parseTimesFormat(time.RFC3339, strs, true, false)
- default:
- return fmt.Errorf("unsupported type '[]%s'", sliceOf)
- }
-
- slice := reflect.MakeSlice(field.Type(), numVals, numVals)
- for i := 0; i < numVals; i++ {
- switch sliceOf {
- case reflect.String:
- slice.Index(i).Set(reflect.ValueOf(vals.([]string)[i]))
- case reflect.Int:
- slice.Index(i).Set(reflect.ValueOf(vals.([]int)[i]))
- case reflect.Int64:
- slice.Index(i).Set(reflect.ValueOf(vals.([]int64)[i]))
- case reflect.Uint:
- slice.Index(i).Set(reflect.ValueOf(vals.([]uint)[i]))
- case reflect.Uint64:
- slice.Index(i).Set(reflect.ValueOf(vals.([]uint64)[i]))
- case reflect.Float64:
- slice.Index(i).Set(reflect.ValueOf(vals.([]float64)[i]))
- case reflectTime:
- slice.Index(i).Set(reflect.ValueOf(vals.([]time.Time)[i]))
- }
- }
- field.Set(slice)
- return nil
-}
-
-// setWithProperType sets proper value to field based on its type,
-// but it does not return error for failing parsing,
-// because we want to use default value that is already assigned to strcut.
-func setWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string, allowShadow bool) error {
- switch t.Kind() {
- case reflect.String:
- if len(key.String()) == 0 {
- return nil
- }
- field.SetString(key.String())
- case reflect.Bool:
- boolVal, err := key.Bool()
- if err != nil {
- return nil
- }
- field.SetBool(boolVal)
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- durationVal, err := key.Duration()
- // Skip zero value
- if err == nil && int(durationVal) > 0 {
- field.Set(reflect.ValueOf(durationVal))
- return nil
- }
-
- intVal, err := key.Int64()
- if err != nil || intVal == 0 {
- return nil
- }
- field.SetInt(intVal)
- // byte is an alias for uint8, so supporting uint8 breaks support for byte
- case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- durationVal, err := key.Duration()
- // Skip zero value
- if err == nil && int(durationVal) > 0 {
- field.Set(reflect.ValueOf(durationVal))
- return nil
- }
-
- uintVal, err := key.Uint64()
- if err != nil {
- return nil
- }
- field.SetUint(uintVal)
-
- case reflect.Float32, reflect.Float64:
- floatVal, err := key.Float64()
- if err != nil {
- return nil
- }
- field.SetFloat(floatVal)
- case reflectTime:
- timeVal, err := key.Time()
- if err != nil {
- return nil
- }
- field.Set(reflect.ValueOf(timeVal))
- case reflect.Slice:
- return setSliceWithProperType(key, field, delim, allowShadow)
- default:
- return fmt.Errorf("unsupported type '%s'", t)
- }
- return nil
-}
-
-func parseTagOptions(tag string) (rawName string, omitEmpty bool, allowShadow bool) {
- opts := strings.SplitN(tag, ",", 3)
- rawName = opts[0]
- if len(opts) > 1 {
- omitEmpty = opts[1] == "omitempty"
- }
- if len(opts) > 2 {
- allowShadow = opts[2] == "allowshadow"
- }
- return rawName, omitEmpty, allowShadow
-}
-
-func (s *Section) mapTo(val reflect.Value) error {
- if val.Kind() == reflect.Ptr {
- val = val.Elem()
- }
- typ := val.Type()
-
- for i := 0; i < typ.NumField(); i++ {
- field := val.Field(i)
- tpField := typ.Field(i)
-
- tag := tpField.Tag.Get("ini")
- if tag == "-" {
- continue
- }
-
- rawName, _, allowShadow := parseTagOptions(tag)
- fieldName := s.parseFieldName(tpField.Name, rawName)
- if len(fieldName) == 0 || !field.CanSet() {
- continue
- }
-
- isAnonymous := tpField.Type.Kind() == reflect.Ptr && tpField.Anonymous
- isStruct := tpField.Type.Kind() == reflect.Struct
- if isAnonymous {
- field.Set(reflect.New(tpField.Type.Elem()))
- }
-
- if isAnonymous || isStruct {
- if sec, err := s.f.GetSection(fieldName); err == nil {
- if err = sec.mapTo(field); err != nil {
- return fmt.Errorf("error mapping field(%s): %v", fieldName, err)
- }
- continue
- }
- }
-
- if key, err := s.GetKey(fieldName); err == nil {
- delim := parseDelim(tpField.Tag.Get("delim"))
- if err = setWithProperType(tpField.Type, key, field, delim, allowShadow); err != nil {
- return fmt.Errorf("error mapping field(%s): %v", fieldName, err)
- }
- }
- }
- return nil
-}
-
-// MapTo maps section to given struct.
-func (s *Section) MapTo(v interface{}) error {
- typ := reflect.TypeOf(v)
- val := reflect.ValueOf(v)
- if typ.Kind() == reflect.Ptr {
- typ = typ.Elem()
- val = val.Elem()
- } else {
- return errors.New("cannot map to non-pointer struct")
- }
-
- return s.mapTo(val)
-}
-
-// MapTo maps file to given struct.
-func (f *File) MapTo(v interface{}) error {
- return f.Section("").MapTo(v)
-}
-
-// MapTo maps data sources to given struct with name mapper.
-func MapToWithMapper(v interface{}, mapper NameMapper, source interface{}, others ...interface{}) error {
- cfg, err := Load(source, others...)
- if err != nil {
- return err
- }
- cfg.NameMapper = mapper
- return cfg.MapTo(v)
-}
-
-// MapTo maps data sources to given struct.
-func MapTo(v, source interface{}, others ...interface{}) error {
- return MapToWithMapper(v, nil, source, others...)
-}
-
-// reflectSliceWithProperType does the opposite thing as setSliceWithProperType.
-func reflectSliceWithProperType(key *Key, field reflect.Value, delim string) error {
- slice := field.Slice(0, field.Len())
- if field.Len() == 0 {
- return nil
- }
-
- var buf bytes.Buffer
- sliceOf := field.Type().Elem().Kind()
- for i := 0; i < field.Len(); i++ {
- switch sliceOf {
- case reflect.String:
- buf.WriteString(slice.Index(i).String())
- case reflect.Int, reflect.Int64:
- buf.WriteString(fmt.Sprint(slice.Index(i).Int()))
- case reflect.Uint, reflect.Uint64:
- buf.WriteString(fmt.Sprint(slice.Index(i).Uint()))
- case reflect.Float64:
- buf.WriteString(fmt.Sprint(slice.Index(i).Float()))
- case reflectTime:
- buf.WriteString(slice.Index(i).Interface().(time.Time).Format(time.RFC3339))
- default:
- return fmt.Errorf("unsupported type '[]%s'", sliceOf)
- }
- buf.WriteString(delim)
- }
- key.SetValue(buf.String()[:buf.Len()-1])
- return nil
-}
-
-// reflectWithProperType does the opposite thing as setWithProperType.
-func reflectWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string) error {
- switch t.Kind() {
- case reflect.String:
- key.SetValue(field.String())
- case reflect.Bool:
- key.SetValue(fmt.Sprint(field.Bool()))
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- key.SetValue(fmt.Sprint(field.Int()))
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- key.SetValue(fmt.Sprint(field.Uint()))
- case reflect.Float32, reflect.Float64:
- key.SetValue(fmt.Sprint(field.Float()))
- case reflectTime:
- key.SetValue(fmt.Sprint(field.Interface().(time.Time).Format(time.RFC3339)))
- case reflect.Slice:
- return reflectSliceWithProperType(key, field, delim)
- default:
- return fmt.Errorf("unsupported type '%s'", t)
- }
- return nil
-}
-
-// CR: copied from encoding/json/encode.go with modifications of time.Time support.
-// TODO: add more test coverage.
-func isEmptyValue(v reflect.Value) bool {
- switch v.Kind() {
- case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
- return v.Len() == 0
- case reflect.Bool:
- return !v.Bool()
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- return v.Int() == 0
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
- return v.Uint() == 0
- case reflect.Float32, reflect.Float64:
- return v.Float() == 0
- case reflectTime:
- return v.Interface().(time.Time).IsZero()
- case reflect.Interface, reflect.Ptr:
- return v.IsNil()
- }
- return false
-}
-
-func (s *Section) reflectFrom(val reflect.Value) error {
- if val.Kind() == reflect.Ptr {
- val = val.Elem()
- }
- typ := val.Type()
-
- for i := 0; i < typ.NumField(); i++ {
- field := val.Field(i)
- tpField := typ.Field(i)
-
- tag := tpField.Tag.Get("ini")
- if tag == "-" {
- continue
- }
-
- opts := strings.SplitN(tag, ",", 2)
- if len(opts) == 2 && opts[1] == "omitempty" && isEmptyValue(field) {
- continue
- }
-
- fieldName := s.parseFieldName(tpField.Name, opts[0])
- if len(fieldName) == 0 || !field.CanSet() {
- continue
- }
-
- if (tpField.Type.Kind() == reflect.Ptr && tpField.Anonymous) ||
- (tpField.Type.Kind() == reflect.Struct && tpField.Type.Name() != "Time") {
- // Note: The only error here is section doesn't exist.
- sec, err := s.f.GetSection(fieldName)
- if err != nil {
- // Note: fieldName can never be empty here, ignore error.
- sec, _ = s.f.NewSection(fieldName)
- }
- if err = sec.reflectFrom(field); err != nil {
- return fmt.Errorf("error reflecting field (%s): %v", fieldName, err)
- }
- continue
- }
-
- // Note: Same reason as secion.
- key, err := s.GetKey(fieldName)
- if err != nil {
- key, _ = s.NewKey(fieldName, "")
- }
- if err = reflectWithProperType(tpField.Type, key, field, parseDelim(tpField.Tag.Get("delim"))); err != nil {
- return fmt.Errorf("error reflecting field (%s): %v", fieldName, err)
- }
-
- }
- return nil
-}
-
-// ReflectFrom reflects secion from given struct.
-func (s *Section) ReflectFrom(v interface{}) error {
- typ := reflect.TypeOf(v)
- val := reflect.ValueOf(v)
- if typ.Kind() == reflect.Ptr {
- typ = typ.Elem()
- val = val.Elem()
- } else {
- return errors.New("cannot reflect from non-pointer struct")
- }
-
- return s.reflectFrom(val)
-}
-
-// ReflectFrom reflects file from given struct.
-func (f *File) ReflectFrom(v interface{}) error {
- return f.Section("").ReflectFrom(v)
-}
-
-// ReflectFrom reflects data sources from given struct with name mapper.
-func ReflectFromWithMapper(cfg *File, v interface{}, mapper NameMapper) error {
- cfg.NameMapper = mapper
- return cfg.ReflectFrom(v)
-}
-
-// ReflectFrom reflects data sources from given struct.
-func ReflectFrom(cfg *File, v interface{}) error {
- return ReflectFromWithMapper(cfg, v, nil)
-}
diff --git a/vendor/github.com/go-ini/ini/struct_test.go b/vendor/github.com/go-ini/ini/struct_test.go
deleted file mode 100644
index 7237715a8..000000000
--- a/vendor/github.com/go-ini/ini/struct_test.go
+++ /dev/null
@@ -1,337 +0,0 @@
-// Copyright 2014 Unknwon
-//
-// 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 ini
-
-import (
- "bytes"
- "fmt"
- "strings"
- "testing"
- "time"
-
- . "github.com/smartystreets/goconvey/convey"
-)
-
-type testNested struct {
- Cities []string `delim:"|"`
- Visits []time.Time
- Years []int
- Numbers []int64
- Ages []uint
- Populations []uint64
- Coordinates []float64
- Note string
- Unused int `ini:"-"`
-}
-
-type testEmbeded struct {
- GPA float64
-}
-
-type testStruct struct {
- Name string `ini:"NAME"`
- Age int
- Male bool
- Money float64
- Born time.Time
- Time time.Duration `ini:"Duration"`
- Others testNested
- *testEmbeded `ini:"grade"`
- Unused int `ini:"-"`
- Unsigned uint
- Omitted bool `ini:"omitthis,omitempty"`
- Shadows []string `ini:",,allowshadow"`
- ShadowInts []int `ini:"Shadows,,allowshadow"`
-}
-
-const _CONF_DATA_STRUCT = `
-NAME = Unknwon
-Age = 21
-Male = true
-Money = 1.25
-Born = 1993-10-07T20:17:05Z
-Duration = 2h45m
-Unsigned = 3
-omitthis = true
-Shadows = 1, 2
-Shadows = 3, 4
-
-[Others]
-Cities = HangZhou|Boston
-Visits = 1993-10-07T20:17:05Z, 1993-10-07T20:17:05Z
-Years = 1993,1994
-Numbers = 10010,10086
-Ages = 18,19
-Populations = 12345678,98765432
-Coordinates = 192.168,10.11
-Note = Hello world!
-
-[grade]
-GPA = 2.8
-
-[foo.bar]
-Here = there
-When = then
-`
-
-type unsupport struct {
- Byte byte
-}
-
-type unsupport2 struct {
- Others struct {
- Cities byte
- }
-}
-
-type unsupport3 struct {
- Cities byte
-}
-
-type unsupport4 struct {
- *unsupport3 `ini:"Others"`
-}
-
-type defaultValue struct {
- Name string
- Age int
- Male bool
- Money float64
- Born time.Time
- Cities []string
-}
-
-type fooBar struct {
- Here, When string
-}
-
-const _INVALID_DATA_CONF_STRUCT = `
-Name =
-Age = age
-Male = 123
-Money = money
-Born = nil
-Cities =
-`
-
-func Test_Struct(t *testing.T) {
- Convey("Map to struct", t, func() {
- Convey("Map file to struct", func() {
- ts := new(testStruct)
- So(MapTo(ts, []byte(_CONF_DATA_STRUCT)), ShouldBeNil)
-
- So(ts.Name, ShouldEqual, "Unknwon")
- So(ts.Age, ShouldEqual, 21)
- So(ts.Male, ShouldBeTrue)
- So(ts.Money, ShouldEqual, 1.25)
- So(ts.Unsigned, ShouldEqual, 3)
-
- t, err := time.Parse(time.RFC3339, "1993-10-07T20:17:05Z")
- So(err, ShouldBeNil)
- So(ts.Born.String(), ShouldEqual, t.String())
-
- dur, err := time.ParseDuration("2h45m")
- So(err, ShouldBeNil)
- So(ts.Time.Seconds(), ShouldEqual, dur.Seconds())
-
- So(strings.Join(ts.Others.Cities, ","), ShouldEqual, "HangZhou,Boston")
- So(ts.Others.Visits[0].String(), ShouldEqual, t.String())
- So(fmt.Sprint(ts.Others.Years), ShouldEqual, "[1993 1994]")
- So(fmt.Sprint(ts.Others.Numbers), ShouldEqual, "[10010 10086]")
- So(fmt.Sprint(ts.Others.Ages), ShouldEqual, "[18 19]")
- So(fmt.Sprint(ts.Others.Populations), ShouldEqual, "[12345678 98765432]")
- So(fmt.Sprint(ts.Others.Coordinates), ShouldEqual, "[192.168 10.11]")
- So(ts.Others.Note, ShouldEqual, "Hello world!")
- So(ts.testEmbeded.GPA, ShouldEqual, 2.8)
- })
-
- Convey("Map section to struct", func() {
- foobar := new(fooBar)
- f, err := Load([]byte(_CONF_DATA_STRUCT))
- So(err, ShouldBeNil)
-
- So(f.Section("foo.bar").MapTo(foobar), ShouldBeNil)
- So(foobar.Here, ShouldEqual, "there")
- So(foobar.When, ShouldEqual, "then")
- })
-
- Convey("Map to non-pointer struct", func() {
- cfg, err := Load([]byte(_CONF_DATA_STRUCT))
- So(err, ShouldBeNil)
- So(cfg, ShouldNotBeNil)
-
- So(cfg.MapTo(testStruct{}), ShouldNotBeNil)
- })
-
- Convey("Map to unsupported type", func() {
- cfg, err := Load([]byte(_CONF_DATA_STRUCT))
- So(err, ShouldBeNil)
- So(cfg, ShouldNotBeNil)
-
- cfg.NameMapper = func(raw string) string {
- if raw == "Byte" {
- return "NAME"
- }
- return raw
- }
- So(cfg.MapTo(&unsupport{}), ShouldNotBeNil)
- So(cfg.MapTo(&unsupport2{}), ShouldNotBeNil)
- So(cfg.MapTo(&unsupport4{}), ShouldNotBeNil)
- })
-
- Convey("Map to omitempty field", func() {
- ts := new(testStruct)
- So(MapTo(ts, []byte(_CONF_DATA_STRUCT)), ShouldBeNil)
-
- So(ts.Omitted, ShouldEqual, true)
- })
-
- Convey("Map with shadows", func() {
- cfg, err := LoadSources(LoadOptions{AllowShadows: true}, []byte(_CONF_DATA_STRUCT))
- So(err, ShouldBeNil)
- ts := new(testStruct)
- So(cfg.MapTo(ts), ShouldBeNil)
-
- So(strings.Join(ts.Shadows, " "), ShouldEqual, "1 2 3 4")
- So(fmt.Sprintf("%v", ts.ShadowInts), ShouldEqual, "[1 2 3 4]")
- })
-
- Convey("Map from invalid data source", func() {
- So(MapTo(&testStruct{}, "hi"), ShouldNotBeNil)
- })
-
- Convey("Map to wrong types and gain default values", func() {
- cfg, err := Load([]byte(_INVALID_DATA_CONF_STRUCT))
- So(err, ShouldBeNil)
-
- t, err := time.Parse(time.RFC3339, "1993-10-07T20:17:05Z")
- So(err, ShouldBeNil)
- dv := &defaultValue{"Joe", 10, true, 1.25, t, []string{"HangZhou", "Boston"}}
- So(cfg.MapTo(dv), ShouldBeNil)
- So(dv.Name, ShouldEqual, "Joe")
- So(dv.Age, ShouldEqual, 10)
- So(dv.Male, ShouldBeTrue)
- So(dv.Money, ShouldEqual, 1.25)
- So(dv.Born.String(), ShouldEqual, t.String())
- So(strings.Join(dv.Cities, ","), ShouldEqual, "HangZhou,Boston")
- })
- })
-
- Convey("Reflect from struct", t, func() {
- type Embeded struct {
- Dates []time.Time `delim:"|"`
- Places []string
- Years []int
- Numbers []int64
- Ages []uint
- Populations []uint64
- Coordinates []float64
- None []int
- }
- type Author struct {
- Name string `ini:"NAME"`
- Male bool
- Age int
- Height uint
- GPA float64
- Date time.Time
- NeverMind string `ini:"-"`
- *Embeded `ini:"infos"`
- }
-
- t, err := time.Parse(time.RFC3339, "1993-10-07T20:17:05Z")
- So(err, ShouldBeNil)
- a := &Author{"Unknwon", true, 21, 100, 2.8, t, "",
- &Embeded{
- []time.Time{t, t},
- []string{"HangZhou", "Boston"},
- []int{1993, 1994},
- []int64{10010, 10086},
- []uint{18, 19},
- []uint64{12345678, 98765432},
- []float64{192.168, 10.11},
- []int{},
- }}
- cfg := Empty()
- So(ReflectFrom(cfg, a), ShouldBeNil)
-
- var buf bytes.Buffer
- _, err = cfg.WriteTo(&buf)
- So(err, ShouldBeNil)
- So(buf.String(), ShouldEqual, `NAME = Unknwon
-Male = true
-Age = 21
-Height = 100
-GPA = 2.8
-Date = 1993-10-07T20:17:05Z
-
-[infos]
-Dates = 1993-10-07T20:17:05Z|1993-10-07T20:17:05Z
-Places = HangZhou,Boston
-Years = 1993,1994
-Numbers = 10010,10086
-Ages = 18,19
-Populations = 12345678,98765432
-Coordinates = 192.168,10.11
-None =
-
-`)
-
- Convey("Reflect from non-point struct", func() {
- So(ReflectFrom(cfg, Author{}), ShouldNotBeNil)
- })
-
- Convey("Reflect from struct with omitempty", func() {
- cfg := Empty()
- type SpecialStruct struct {
- FirstName string `ini:"first_name"`
- LastName string `ini:"last_name"`
- JustOmitMe string `ini:"omitempty"`
- LastLogin time.Time `ini:"last_login,omitempty"`
- LastLogin2 time.Time `ini:",omitempty"`
- NotEmpty int `ini:"omitempty"`
- }
-
- So(ReflectFrom(cfg, &SpecialStruct{FirstName: "John", LastName: "Doe", NotEmpty: 9}), ShouldBeNil)
-
- var buf bytes.Buffer
- _, err = cfg.WriteTo(&buf)
- So(buf.String(), ShouldEqual, `first_name = John
-last_name = Doe
-omitempty = 9
-
-`)
- })
- })
-}
-
-type testMapper struct {
- PackageName string
-}
-
-func Test_NameGetter(t *testing.T) {
- Convey("Test name mappers", t, func() {
- So(MapToWithMapper(&testMapper{}, TitleUnderscore, []byte("packag_name=ini")), ShouldBeNil)
-
- cfg, err := Load([]byte("PACKAGE_NAME=ini"))
- So(err, ShouldBeNil)
- So(cfg, ShouldNotBeNil)
-
- cfg.NameMapper = AllCapsUnderscore
- tg := new(testMapper)
- So(cfg.MapTo(tg), ShouldBeNil)
- So(tg.PackageName, ShouldEqual, "ini")
- })
-}
diff --git a/vendor/github.com/go-ini/ini/testdata/UTF-16-BE-BOM.ini b/vendor/github.com/go-ini/ini/testdata/UTF-16-BE-BOM.ini
deleted file mode 100644
index c8bf82c8f..000000000
--- a/vendor/github.com/go-ini/ini/testdata/UTF-16-BE-BOM.ini
+++ /dev/null
Binary files differ
diff --git a/vendor/github.com/go-ini/ini/testdata/UTF-16-LE-BOM.ini b/vendor/github.com/go-ini/ini/testdata/UTF-16-LE-BOM.ini
deleted file mode 100644
index 27f62186e..000000000
--- a/vendor/github.com/go-ini/ini/testdata/UTF-16-LE-BOM.ini
+++ /dev/null
Binary files differ
diff --git a/vendor/github.com/go-ini/ini/testdata/UTF-8-BOM.ini b/vendor/github.com/go-ini/ini/testdata/UTF-8-BOM.ini
deleted file mode 100644
index 2ed0ac1d3..000000000
--- a/vendor/github.com/go-ini/ini/testdata/UTF-8-BOM.ini
+++ /dev/null
@@ -1,2 +0,0 @@
-[author]
-E-MAIL = u@gogs.io \ No newline at end of file
diff --git a/vendor/github.com/go-ini/ini/testdata/aicc.ini b/vendor/github.com/go-ini/ini/testdata/aicc.ini
deleted file mode 100644
index 59a61970d..000000000
--- a/vendor/github.com/go-ini/ini/testdata/aicc.ini
+++ /dev/null
@@ -1,11 +0,0 @@
-[Core]
- Lesson_Location = 87
-Lesson_Status = C
- Score = 3
-Time = 00:02:30
-
-[CORE_LESSON]
-my lesson state data – 1111111111111111111000000000000000001110000
-111111111111111111100000000000111000000000 – end my lesson state data
-[COMMENTS]
-<1><L.Slide#2> This slide has the fuel listed in the wrong units <e.1>
diff --git a/vendor/github.com/go-ini/ini/testdata/conf.ini b/vendor/github.com/go-ini/ini/testdata/conf.ini
deleted file mode 100644
index f8e7ec89f..000000000
--- a/vendor/github.com/go-ini/ini/testdata/conf.ini
+++ /dev/null
@@ -1,2 +0,0 @@
-[author]
-E-MAIL = u@gogs.io \ No newline at end of file
diff --git a/vendor/github.com/go-ldap/ldap/Makefile b/vendor/github.com/go-ldap/ldap/Makefile
index f7899f59a..c1fc96657 100644
--- a/vendor/github.com/go-ldap/ldap/Makefile
+++ b/vendor/github.com/go-ldap/ldap/Makefile
@@ -1,15 +1,5 @@
.PHONY: default install build test quicktest fmt vet lint
-GO_VERSION := $(shell go version | cut -d' ' -f3 | cut -d. -f2)
-
-# Only use the `-race` flag on newer versions of Go
-IS_OLD_GO := $(shell test $(GO_VERSION) -le 2 && echo true)
-ifeq ($(IS_OLD_GO),true)
- RACE_FLAG :=
-else
- RACE_FLAG := -race
-endif
-
default: fmt vet lint build quicktest
install:
@@ -19,7 +9,7 @@ build:
go build -v ./...
test:
- go test -v $(RACE_FLAG) -cover ./...
+ go test -v -cover ./...
quicktest:
go test ./...
diff --git a/vendor/github.com/go-ldap/ldap/atomic_value.go b/vendor/github.com/go-ldap/ldap/atomic_value.go
deleted file mode 100644
index bccf7573e..000000000
--- a/vendor/github.com/go-ldap/ldap/atomic_value.go
+++ /dev/null
@@ -1,13 +0,0 @@
-// +build go1.4
-
-package ldap
-
-import (
- "sync/atomic"
-)
-
-// For compilers that support it, we just use the underlying sync/atomic.Value
-// type.
-type atomicValue struct {
- atomic.Value
-}
diff --git a/vendor/github.com/go-ldap/ldap/atomic_value_go13.go b/vendor/github.com/go-ldap/ldap/atomic_value_go13.go
deleted file mode 100644
index 04920bb26..000000000
--- a/vendor/github.com/go-ldap/ldap/atomic_value_go13.go
+++ /dev/null
@@ -1,28 +0,0 @@
-// +build !go1.4
-
-package ldap
-
-import (
- "sync"
-)
-
-// This is a helper type that emulates the use of the "sync/atomic.Value"
-// struct that's available in Go 1.4 and up.
-type atomicValue struct {
- value interface{}
- lock sync.RWMutex
-}
-
-func (av *atomicValue) Store(val interface{}) {
- av.lock.Lock()
- av.value = val
- av.lock.Unlock()
-}
-
-func (av *atomicValue) Load() interface{} {
- av.lock.RLock()
- ret := av.value
- av.lock.RUnlock()
-
- return ret
-}
diff --git a/vendor/github.com/go-ldap/ldap/conn.go b/vendor/github.com/go-ldap/ldap/conn.go
index e701a9b66..b5bd99adb 100644
--- a/vendor/github.com/go-ldap/ldap/conn.go
+++ b/vendor/github.com/go-ldap/ldap/conn.go
@@ -11,7 +11,6 @@ import (
"log"
"net"
"sync"
- "sync/atomic"
"time"
"gopkg.in/asn1-ber.v1"
@@ -83,8 +82,8 @@ const (
type Conn struct {
conn net.Conn
isTLS bool
- closeCount uint32
- closeErr atomicValue
+ isClosing bool
+ closeErr error
isStartingTLS bool
Debug debugging
chanConfirm chan bool
@@ -159,20 +158,10 @@ func (l *Conn) Start() {
l.wgClose.Add(1)
}
-// isClosing returns whether or not we're currently closing.
-func (l *Conn) isClosing() bool {
- return atomic.LoadUint32(&l.closeCount) > 0
-}
-
-// setClosing sets the closing value to true
-func (l *Conn) setClosing() {
- atomic.AddUint32(&l.closeCount, 1)
-}
-
// Close closes the connection.
func (l *Conn) Close() {
l.once.Do(func() {
- l.setClosing()
+ l.isClosing = true
l.wgSender.Wait()
l.Debug.Printf("Sending quit message and waiting for confirmation")
@@ -269,7 +258,7 @@ func (l *Conn) sendMessage(packet *ber.Packet) (*messageContext, error) {
}
func (l *Conn) sendMessageWithFlags(packet *ber.Packet, flags sendMessageFlags) (*messageContext, error) {
- if l.isClosing() {
+ if l.isClosing {
return nil, NewError(ErrorNetwork, errors.New("ldap: connection closed"))
}
l.messageMutex.Lock()
@@ -308,7 +297,7 @@ func (l *Conn) sendMessageWithFlags(packet *ber.Packet, flags sendMessageFlags)
func (l *Conn) finishMessage(msgCtx *messageContext) {
close(msgCtx.done)
- if l.isClosing() {
+ if l.isClosing {
return
}
@@ -327,7 +316,7 @@ func (l *Conn) finishMessage(msgCtx *messageContext) {
}
func (l *Conn) sendProcessMessage(message *messagePacket) bool {
- if l.isClosing() {
+ if l.isClosing {
return false
}
l.wgSender.Add(1)
@@ -344,8 +333,8 @@ func (l *Conn) processMessages() {
for messageID, msgCtx := range l.messageContexts {
// If we are closing due to an error, inform anyone who
// is waiting about the error.
- if l.isClosing() && l.closeErr.Load() != nil {
- msgCtx.sendResponse(&PacketResponse{Error: l.closeErr.Load().(error)})
+ if l.isClosing && l.closeErr != nil {
+ msgCtx.sendResponse(&PacketResponse{Error: l.closeErr})
}
l.Debug.Printf("Closing channel for MessageID %d", messageID)
close(msgCtx.responses)
@@ -408,7 +397,7 @@ func (l *Conn) processMessages() {
if msgCtx, ok := l.messageContexts[message.MessageID]; ok {
msgCtx.sendResponse(&PacketResponse{message.Packet, nil})
} else {
- log.Printf("Received unexpected message %d, %v", message.MessageID, l.isClosing())
+ log.Printf("Received unexpected message %d, %v", message.MessageID, l.isClosing)
ber.PrintPacket(message.Packet)
}
case MessageTimeout:
@@ -450,8 +439,8 @@ func (l *Conn) reader() {
packet, err := ber.ReadPacket(l.conn)
if err != nil {
// A read error is expected here if we are closing the connection...
- if !l.isClosing() {
- l.closeErr.Store(fmt.Errorf("unable to read LDAP response packet: %s", err))
+ if !l.isClosing {
+ l.closeErr = fmt.Errorf("unable to read LDAP response packet: %s", err)
l.Debug.Printf("reader error: %s", err.Error())
}
return
diff --git a/vendor/github.com/go-ldap/ldap/conn_test.go b/vendor/github.com/go-ldap/ldap/conn_test.go
index 30554d23c..10766bbd4 100644
--- a/vendor/github.com/go-ldap/ldap/conn_test.go
+++ b/vendor/github.com/go-ldap/ldap/conn_test.go
@@ -60,7 +60,7 @@ func TestUnresponsiveConnection(t *testing.T) {
// TestFinishMessage tests that we do not enter deadlock when a goroutine makes
// a request but does not handle all responses from the server.
-func TestFinishMessage(t *testing.T) {
+func TestConn(t *testing.T) {
ptc := newPacketTranslatorConn()
defer ptc.Close()
@@ -174,12 +174,16 @@ func testSendUnhandledResponsesAndFinish(t *testing.T, ptc *packetTranslatorConn
}
func runWithTimeout(t *testing.T, timeout time.Duration, f func()) {
+ runtime.Gosched()
+
done := make(chan struct{})
go func() {
f()
close(done)
}()
+ runtime.Gosched()
+
select {
case <-done: // Success!
case <-time.After(timeout):
diff --git a/vendor/github.com/go-ldap/ldap/error.go b/vendor/github.com/go-ldap/ldap/error.go
index 4cccb537f..ff697873d 100644
--- a/vendor/github.com/go-ldap/ldap/error.go
+++ b/vendor/github.com/go-ldap/ldap/error.go
@@ -97,13 +97,6 @@ var LDAPResultCodeMap = map[uint8]string{
LDAPResultObjectClassModsProhibited: "Object Class Mods Prohibited",
LDAPResultAffectsMultipleDSAs: "Affects Multiple DSAs",
LDAPResultOther: "Other",
-
- ErrorNetwork: "Network Error",
- ErrorFilterCompile: "Filter Compile Error",
- ErrorFilterDecompile: "Filter Decompile Error",
- ErrorDebugging: "Debugging Error",
- ErrorUnexpectedMessage: "Unexpected Message",
- ErrorUnexpectedResponse: "Unexpected Response",
}
func getLDAPResultCode(packet *ber.Packet) (code uint8, description string) {
diff --git a/vendor/github.com/go-ldap/ldap/example_test.go b/vendor/github.com/go-ldap/ldap/example_test.go
index 821189bd6..b018a9664 100644
--- a/vendor/github.com/go-ldap/ldap/example_test.go
+++ b/vendor/github.com/go-ldap/ldap/example_test.go
@@ -193,7 +193,7 @@ func Example_userAuthentication() {
searchRequest := ldap.NewSearchRequest(
"dc=example,dc=com",
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
- fmt.Sprintf("(&(objectClass=organizationalPerson)(uid=%s))", username),
+ fmt.Sprintf("(&(objectClass=organizationalPerson)&(uid=%s))", username),
[]string{"dn"},
nil,
)
diff --git a/vendor/github.com/go-sql-driver/mysql/.travis.yml b/vendor/github.com/go-sql-driver/mysql/.travis.yml
index a551785b8..c1cc10aaf 100644
--- a/vendor/github.com/go-sql-driver/mysql/.travis.yml
+++ b/vendor/github.com/go-sql-driver/mysql/.travis.yml
@@ -7,86 +7,7 @@ go:
- 1.5
- 1.6
- 1.7
- - 1.8
- tip
-before_install:
- - go get golang.org/x/tools/cmd/cover
- - go get github.com/mattn/goveralls
-
-matrix:
- include:
- - env: DB=MYSQL57
- sudo: required
- dist: trusty
- go: 1.8
- services:
- - docker
- before_install:
- - go get golang.org/x/tools/cmd/cover
- - go get github.com/mattn/goveralls
- - docker pull mysql:5.7
- - docker run -d -p 127.0.0.1:3307:3306 --name mysqld -e MYSQL_DATABASE=gotest -e MYSQL_USER=gotest -e MYSQL_PASSWORD=secret -e MYSQL_ROOT_PASSWORD=verysecret
- mysql:5.7 --innodb_log_file_size=256MB --innodb_buffer_pool_size=512MB --max_allowed_packet=16MB
- - sleep 30
- - cp .travis/docker.cnf ~/.my.cnf
- - mysql --print-defaults
- - .travis/wait_mysql.sh
- before_script:
- - export MYSQL_TEST_USER=gotest
- - export MYSQL_TEST_PASS=secret
- - export MYSQL_TEST_ADDR=127.0.0.1:3307
- - export MYSQL_TEST_CONCURRENT=1
-
- - env: DB=MARIA55
- sudo: required
- dist: trusty
- go: 1.8
- services:
- - docker
- before_install:
- - go get golang.org/x/tools/cmd/cover
- - go get github.com/mattn/goveralls
- - docker pull mariadb:5.5
- - docker run -d -p 127.0.0.1:3307:3306 --name mysqld -e MYSQL_DATABASE=gotest -e MYSQL_USER=gotest -e MYSQL_PASSWORD=secret -e MYSQL_ROOT_PASSWORD=verysecret
- mariadb:5.5 --innodb_log_file_size=256MB --innodb_buffer_pool_size=512MB --max_allowed_packet=16MB
- - sleep 30
- - cp .travis/docker.cnf ~/.my.cnf
- - mysql --print-defaults
- - .travis/wait_mysql.sh
- before_script:
- - export MYSQL_TEST_USER=gotest
- - export MYSQL_TEST_PASS=secret
- - export MYSQL_TEST_ADDR=127.0.0.1:3307
- - export MYSQL_TEST_CONCURRENT=1
-
- - env: DB=MARIA10_1
- sudo: required
- dist: trusty
- go: 1.8
- services:
- - docker
- before_install:
- - go get golang.org/x/tools/cmd/cover
- - go get github.com/mattn/goveralls
- - docker pull mariadb:10.1
- - docker run -d -p 127.0.0.1:3307:3306 --name mysqld -e MYSQL_DATABASE=gotest -e MYSQL_USER=gotest -e MYSQL_PASSWORD=secret -e MYSQL_ROOT_PASSWORD=verysecret
- mariadb:10.1 --innodb_log_file_size=256MB --innodb_buffer_pool_size=512MB --max_allowed_packet=16MB
- - sleep 30
- - cp .travis/docker.cnf ~/.my.cnf
- - mysql --print-defaults
- - .travis/wait_mysql.sh
- before_script:
- - export MYSQL_TEST_USER=gotest
- - export MYSQL_TEST_PASS=secret
- - export MYSQL_TEST_ADDR=127.0.0.1:3307
- - export MYSQL_TEST_CONCURRENT=1
-
-
before_script:
- mysql -e 'create database gotest;'
-script:
- - go test -v -covermode=count -coverprofile=coverage.out
- - go vet ./...
- - test -z "$(gofmt -d -s . | tee /dev/stderr)"
- - $HOME/gopath/bin/goveralls -coverprofile=coverage.out -service=travis-ci
diff --git a/vendor/github.com/go-sql-driver/mysql/.travis/docker.cnf b/vendor/github.com/go-sql-driver/mysql/.travis/docker.cnf
deleted file mode 100644
index e57754e5a..000000000
--- a/vendor/github.com/go-sql-driver/mysql/.travis/docker.cnf
+++ /dev/null
@@ -1,5 +0,0 @@
-[client]
-user = gotest
-password = secret
-host = 127.0.0.1
-port = 3307
diff --git a/vendor/github.com/go-sql-driver/mysql/.travis/wait_mysql.sh b/vendor/github.com/go-sql-driver/mysql/.travis/wait_mysql.sh
deleted file mode 100755
index abcf5f0ae..000000000
--- a/vendor/github.com/go-sql-driver/mysql/.travis/wait_mysql.sh
+++ /dev/null
@@ -1,8 +0,0 @@
-#!/bin/sh
-while :
-do
- sleep 3
- if mysql -e 'select version()'; then
- break
- fi
-done
diff --git a/vendor/github.com/go-sql-driver/mysql/AUTHORS b/vendor/github.com/go-sql-driver/mysql/AUTHORS
index 1928dac89..692c186fd 100644
--- a/vendor/github.com/go-sql-driver/mysql/AUTHORS
+++ b/vendor/github.com/go-sql-driver/mysql/AUTHORS
@@ -13,31 +13,26 @@
Aaron Hopkins <go-sql-driver at die.net>
Arne Hormann <arnehormann at gmail.com>
-Asta Xie <xiemengjun at gmail.com>
Carlos Nieto <jose.carlos at menteslibres.net>
Chris Moos <chris at tech9computers.com>
Daniel Nichter <nil at codenode.com>
Daniël van Eeden <git at myname.nl>
DisposaBoy <disposaboy at dby.me>
-Egor Smolyakov <egorsmkv at gmail.com>
Frederick Mayle <frederickmayle at gmail.com>
Gustavo Kristic <gkristic at gmail.com>
Hanno Braun <mail at hannobraun.com>
Henri Yandell <flamefew at gmail.com>
Hirotaka Yamamoto <ymmt2005 at gmail.com>
INADA Naoki <songofacandy at gmail.com>
-Jacek Szwec <szwec.jacek at gmail.com>
James Harr <james.harr at gmail.com>
Jian Zhen <zhenjl at gmail.com>
Joshua Prunier <joshua.prunier at gmail.com>
Julien Lefevre <julien.lefevr at gmail.com>
Julien Schmidt <go-sql-driver at julienschmidt.com>
-Justin Nuß <nuss.justin at gmail.com>
Kamil Dziedzic <kamil at klecza.pl>
Kevin Malachowski <kevin at chowski.com>
Lennart Rudolph <lrudolph at hmc.edu>
Leonardo YongUk Kim <dalinaum at gmail.com>
-Lion Yang <lion at aosc.xyz>
Luca Looz <luca.looz92 at gmail.com>
Lucas Liu <extrafliu at gmail.com>
Luke Scott <luke at webconnex.com>
@@ -45,7 +40,6 @@ Michael Woolnough <michael.woolnough at gmail.com>
Nicola Peduzzi <thenikso at gmail.com>
Olivier Mengué <dolmen at cpan.org>
Paul Bonser <misterpib at gmail.com>
-Peter Schultz <peter.schultz at classmarkets.com>
Runrioter Wung <runrioter at gmail.com>
Soroush Pour <me at soroushjp.com>
Stan Putrya <root.vagner at gmail.com>
diff --git a/vendor/github.com/go-sql-driver/mysql/README.md b/vendor/github.com/go-sql-driver/mysql/README.md
index a060e3cfd..a16012f81 100644
--- a/vendor/github.com/go-sql-driver/mysql/README.md
+++ b/vendor/github.com/go-sql-driver/mysql/README.md
@@ -1,6 +1,6 @@
# Go-MySQL-Driver
-A MySQL-Driver for Go's [database/sql](https://golang.org/pkg/database/sql/) package
+A MySQL-Driver for Go's [database/sql](http://golang.org/pkg/database/sql) package
![Go-MySQL-Driver logo](https://raw.github.com/wiki/go-sql-driver/mysql/gomysql_m.png "Golang Gopher holding the MySQL Dolphin")
@@ -15,7 +15,6 @@ A MySQL-Driver for Go's [database/sql](https://golang.org/pkg/database/sql/) pac
* [Address](#address)
* [Parameters](#parameters)
* [Examples](#examples)
- * [Connection pool and timeouts](#connection-pool-and-timeouts)
* [LOAD DATA LOCAL INFILE support](#load-data-local-infile-support)
* [time.Time support](#timetime-support)
* [Unicode support](#unicode-support)
@@ -27,11 +26,11 @@ A MySQL-Driver for Go's [database/sql](https://golang.org/pkg/database/sql/) pac
## Features
* Lightweight and [fast](https://github.com/go-sql-driver/sql-benchmark "golang MySQL-Driver performance")
* Native Go implementation. No C-bindings, just pure Go
- * Connections over TCP/IPv4, TCP/IPv6, Unix domain sockets or [custom protocols](https://godoc.org/github.com/go-sql-driver/mysql#DialFunc)
+ * Connections over TCP/IPv4, TCP/IPv6, Unix domain sockets or [custom protocols](http://godoc.org/github.com/go-sql-driver/mysql#DialFunc)
* Automatic handling of broken connections
* Automatic Connection Pooling *(by database/sql package)*
* Supports queries larger than 16MB
- * Full [`sql.RawBytes`](https://golang.org/pkg/database/sql/#RawBytes) support.
+ * Full [`sql.RawBytes`](http://golang.org/pkg/database/sql/#RawBytes) support.
* Intelligent `LONG DATA` handling in prepared statements
* Secure `LOAD DATA LOCAL INFILE` support with file Whitelisting and `io.Reader` support
* Optional `time.Time` parsing
@@ -44,14 +43,14 @@ A MySQL-Driver for Go's [database/sql](https://golang.org/pkg/database/sql/) pac
---------------------------------------
## Installation
-Simple install the package to your [$GOPATH](https://github.com/golang/go/wiki/GOPATH "GOPATH") with the [go tool](https://golang.org/cmd/go/ "go command") from shell:
+Simple install the package to your [$GOPATH](http://code.google.com/p/go-wiki/wiki/GOPATH "GOPATH") with the [go tool](http://golang.org/cmd/go/ "go command") from shell:
```bash
$ go get github.com/go-sql-driver/mysql
```
-Make sure [Git is installed](https://git-scm.com/downloads) on your machine and in your system's `PATH`.
+Make sure [Git is installed](http://git-scm.com/downloads) on your machine and in your system's `PATH`.
## Usage
-_Go MySQL Driver_ is an implementation of Go's `database/sql/driver` interface. You only need to import the driver and can use the full [`database/sql`](https://golang.org/pkg/database/sql/) API then.
+_Go MySQL Driver_ is an implementation of Go's `database/sql/driver` interface. You only need to import the driver and can use the full [`database/sql`](http://golang.org/pkg/database/sql) API then.
Use `mysql` as `driverName` and a valid [DSN](#dsn-data-source-name) as `dataSourceName`:
```go
@@ -96,13 +95,13 @@ Alternatively, [Config.FormatDSN](https://godoc.org/github.com/go-sql-driver/mys
Passwords can consist of any character. Escaping is **not** necessary.
#### Protocol
-See [net.Dial](https://golang.org/pkg/net/#Dial) for more information which networks are available.
+See [net.Dial](http://golang.org/pkg/net/#Dial) for more information which networks are available.
In general you should use an Unix domain socket if available and TCP otherwise for best performance.
#### Address
For TCP and UDP networks, addresses have the form `host:port`.
If `host` is a literal IPv6 address, it must be enclosed in square brackets.
-The functions [net.JoinHostPort](https://golang.org/pkg/net/#JoinHostPort) and [net.SplitHostPort](https://golang.org/pkg/net/#SplitHostPort) manipulate addresses in this form.
+The functions [net.JoinHostPort](http://golang.org/pkg/net/#JoinHostPort) and [net.SplitHostPort](http://golang.org/pkg/net/#SplitHostPort) manipulate addresses in this form.
For Unix domain sockets the address is the absolute path to the MySQL-Server-socket, e.g. `/var/run/mysqld/mysqld.sock` or `/tmp/mysql.sock`.
@@ -221,11 +220,11 @@ Valid Values: <escaped name>
Default: UTC
```
-Sets the location for time.Time values (when using `parseTime=true`). *"Local"* sets the system's location. See [time.LoadLocation](https://golang.org/pkg/time/#LoadLocation) for details.
+Sets the location for time.Time values (when using `parseTime=true`). *"Local"* sets the system's location. See [time.LoadLocation](http://golang.org/pkg/time/#LoadLocation) for details.
Note that this sets the location for time.Time values but does not change MySQL's [time_zone setting](https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html). For that see the [time_zone system variable](#system-variables), which can also be set as a DSN parameter.
-Please keep in mind, that param values must be [url.QueryEscape](https://golang.org/pkg/net/url/#QueryEscape)'ed. Alternatively you can manually replace the `/` with `%2F`. For example `US/Pacific` would be `loc=US%2FPacific`.
+Please keep in mind, that param values must be [url.QueryEscape](http://golang.org/pkg/net/url/#QueryEscape)'ed. Alternatively you can manually replace the `/` with `%2F`. For example `US/Pacific` would be `loc=US%2FPacific`.
##### `maxAllowedPacket`
```
@@ -261,11 +260,11 @@ Default: false
##### `readTimeout`
```
-Type: duration
+Type: decimal number
Default: 0
```
-I/O read timeout. The value must be a decimal number with a unit suffix (*"ms"*, *"s"*, *"m"*, *"h"*), such as *"30s"*, *"0.5m"* or *"1m30s"*.
+I/O read timeout. The value must be a decimal number with an unit suffix ( *"ms"*, *"s"*, *"m"*, *"h"* ), such as *"30s"*, *"0.5m"* or *"1m30s"*.
##### `strict`
@@ -284,11 +283,11 @@ By default MySQL also treats notes as warnings. Use [`sql_notes=false`](http://d
##### `timeout`
```
-Type: duration
+Type: decimal number
Default: OS default
```
-Timeout for establishing connections, aka dial timeout. The value must be a decimal number with a unit suffix (*"ms"*, *"s"*, *"m"*, *"h"*), such as *"30s"*, *"0.5m"* or *"1m30s"*.
+*Driver* side connection timeout. The value must be a decimal number with an unit suffix ( *"ms"*, *"s"*, *"m"*, *"h"* ), such as *"30s"*, *"0.5m"* or *"1m30s"*. To set a server side timeout, use the parameter [`wait_timeout`](http://dev.mysql.com/doc/refman/5.6/en/server-system-variables.html#sysvar_wait_timeout).
##### `tls`
@@ -298,16 +297,16 @@ Valid Values: true, false, skip-verify, <name>
Default: false
```
-`tls=true` enables TLS / SSL encrypted connection to the server. Use `skip-verify` if you want to use a self-signed or invalid certificate (server side). Use a custom value registered with [`mysql.RegisterTLSConfig`](https://godoc.org/github.com/go-sql-driver/mysql#RegisterTLSConfig).
+`tls=true` enables TLS / SSL encrypted connection to the server. Use `skip-verify` if you want to use a self-signed or invalid certificate (server side). Use a custom value registered with [`mysql.RegisterTLSConfig`](http://godoc.org/github.com/go-sql-driver/mysql#RegisterTLSConfig).
##### `writeTimeout`
```
-Type: duration
+Type: decimal number
Default: 0
```
-I/O write timeout. The value must be a decimal number with a unit suffix (*"ms"*, *"s"*, *"m"*, *"h"*), such as *"30s"*, *"0.5m"* or *"1m30s"*.
+I/O write timeout. The value must be a decimal number with an unit suffix ( *"ms"*, *"s"*, *"m"*, *"h"* ), such as *"30s"*, *"0.5m"* or *"1m30s"*.
##### System Variables
@@ -381,11 +380,6 @@ No Database preselected:
user:password@/
```
-
-### Connection pool and timeouts
-The connection pool is managed by Go's database/sql package. For details on how to configure the size of the pool and how long connections stay in the pool see `*DB.SetMaxOpenConns`, `*DB.SetMaxIdleConns`, and `*DB.SetConnMaxLifetime` in the [database/sql documentation](https://golang.org/pkg/database/sql/). The read, write, and dial timeouts for each individual connection are configured with the DSN parameters [`readTimeout`](#readtimeout), [`writeTimeout`](#writetimeout), and [`timeout`](#timeout), respectively.
-
-
### `LOAD DATA LOCAL INFILE` support
For this feature you need direct access to the package. Therefore you must change the import path (no `_`):
```go
@@ -396,17 +390,17 @@ Files must be whitelisted by registering them with `mysql.RegisterLocalFile(file
To use a `io.Reader` a handler function must be registered with `mysql.RegisterReaderHandler(name, handler)` which returns a `io.Reader` or `io.ReadCloser`. The Reader is available with the filepath `Reader::<name>` then. Choose different names for different handlers and `DeregisterReaderHandler` when you don't need it anymore.
-See the [godoc of Go-MySQL-Driver](https://godoc.org/github.com/go-sql-driver/mysql "golang mysql driver documentation") for details.
+See the [godoc of Go-MySQL-Driver](http://godoc.org/github.com/go-sql-driver/mysql "golang mysql driver documentation") for details.
### `time.Time` support
The default internal output type of MySQL `DATE` and `DATETIME` values is `[]byte` which allows you to scan the value into a `[]byte`, `string` or `sql.RawBytes` variable in your programm.
-However, many want to scan MySQL `DATE` and `DATETIME` values into `time.Time` variables, which is the logical opposite in Go to `DATE` and `DATETIME` in MySQL. You can do that by changing the internal output type from `[]byte` to `time.Time` with the DSN parameter `parseTime=true`. You can set the default [`time.Time` location](https://golang.org/pkg/time/#Location) with the `loc` DSN parameter.
+However, many want to scan MySQL `DATE` and `DATETIME` values into `time.Time` variables, which is the logical opposite in Go to `DATE` and `DATETIME` in MySQL. You can do that by changing the internal output type from `[]byte` to `time.Time` with the DSN parameter `parseTime=true`. You can set the default [`time.Time` location](http://golang.org/pkg/time/#Location) with the `loc` DSN parameter.
**Caution:** As of Go 1.1, this makes `time.Time` the only variable type you can scan `DATE` and `DATETIME` values into. This breaks for example [`sql.RawBytes` support](https://github.com/go-sql-driver/mysql/wiki/Examples#rawbytes).
-Alternatively you can use the [`NullTime`](https://godoc.org/github.com/go-sql-driver/mysql#NullTime) type as the scan destination, which works with both `time.Time` and `string` / `[]byte`.
+Alternatively you can use the [`NullTime`](http://godoc.org/github.com/go-sql-driver/mysql#NullTime) type as the scan destination, which works with both `time.Time` and `string` / `[]byte`.
### Unicode support
@@ -441,7 +435,7 @@ That means:
* When distributing, you **must publish** the source code of any **changed files** licensed under the MPL 2.0 under a) the MPL 2.0 itself or b) a compatible license (e.g. GPL 3.0 or Apache License 2.0)
* You **needn't publish** the source code of your library as long as the files licensed under the MPL 2.0 are **unchanged**
-Please read the [MPL 2.0 FAQ](https://www.mozilla.org/en-US/MPL/2.0/FAQ/) if you have further questions regarding the license.
+Please read the [MPL 2.0 FAQ](http://www.mozilla.org/MPL/2.0/FAQ.html) if you have further questions regarding the license.
You can read the full terms here: [LICENSE](https://raw.github.com/go-sql-driver/mysql/master/LICENSE)
diff --git a/vendor/github.com/go-sql-driver/mysql/connection.go b/vendor/github.com/go-sql-driver/mysql/connection.go
index cdce3e30f..d82c728f3 100644
--- a/vendor/github.com/go-sql-driver/mysql/connection.go
+++ b/vendor/github.com/go-sql-driver/mysql/connection.go
@@ -10,7 +10,6 @@ package mysql
import (
"database/sql/driver"
- "io"
"net"
"strconv"
"strings"
@@ -272,6 +271,7 @@ func (mc *mysqlConn) Exec(query string, args []driver.Value) (driver.Result, err
return nil, err
}
query = prepared
+ args = nil
}
mc.affectedRows = 0
mc.insertId = 0
@@ -289,29 +289,22 @@ func (mc *mysqlConn) Exec(query string, args []driver.Value) (driver.Result, err
// Internal function to execute commands
func (mc *mysqlConn) exec(query string) error {
// Send command
- if err := mc.writeCommandPacketStr(comQuery, query); err != nil {
+ err := mc.writeCommandPacketStr(comQuery, query)
+ if err != nil {
return err
}
// Read Result
resLen, err := mc.readResultSetHeaderPacket()
- if err != nil {
- return err
- }
-
- if resLen > 0 {
- // columns
- if err := mc.readUntilEOF(); err != nil {
+ if err == nil && resLen > 0 {
+ if err = mc.readUntilEOF(); err != nil {
return err
}
- // rows
- if err := mc.readUntilEOF(); err != nil {
- return err
- }
+ err = mc.readUntilEOF()
}
- return mc.discardResults()
+ return err
}
func (mc *mysqlConn) Query(query string, args []driver.Value) (driver.Rows, error) {
@@ -329,6 +322,7 @@ func (mc *mysqlConn) Query(query string, args []driver.Value) (driver.Rows, erro
return nil, err
}
query = prepared
+ args = nil
}
// Send command
err := mc.writeCommandPacketStr(comQuery, query)
@@ -341,17 +335,11 @@ func (mc *mysqlConn) Query(query string, args []driver.Value) (driver.Rows, erro
rows.mc = mc
if resLen == 0 {
- rows.rs.done = true
-
- switch err := rows.NextResultSet(); err {
- case nil, io.EOF:
- return rows, nil
- default:
- return nil, err
- }
+ // no columns, no more data
+ return emptyRows{}, nil
}
// Columns
- rows.rs.columns, err = mc.readColumns(resLen)
+ rows.columns, err = mc.readColumns(resLen)
return rows, err
}
}
@@ -371,7 +359,7 @@ func (mc *mysqlConn) getSystemVar(name string) ([]byte, error) {
if err == nil {
rows := new(textRows)
rows.mc = mc
- rows.rs.columns = []mysqlField{{fieldType: fieldTypeVarChar}}
+ rows.columns = []mysqlField{{fieldType: fieldTypeVarChar}}
if resLen > 0 {
// Columns
diff --git a/vendor/github.com/go-sql-driver/mysql/driver.go b/vendor/github.com/go-sql-driver/mysql/driver.go
index e51d98a3c..0022d1f1e 100644
--- a/vendor/github.com/go-sql-driver/mysql/driver.go
+++ b/vendor/github.com/go-sql-driver/mysql/driver.go
@@ -4,7 +4,7 @@
// 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/.
-// Package mysql provides a MySQL driver for Go's database/sql package.
+// Package mysql provides a MySQL driver for Go's database/sql package
//
// The driver should be used via the database/sql package:
//
diff --git a/vendor/github.com/go-sql-driver/mysql/driver_go18_test.go b/vendor/github.com/go-sql-driver/mysql/driver_go18_test.go
deleted file mode 100644
index 93918ad46..000000000
--- a/vendor/github.com/go-sql-driver/mysql/driver_go18_test.go
+++ /dev/null
@@ -1,190 +0,0 @@
-// +build go1.8
-
-package mysql
-
-import (
- "database/sql"
- "fmt"
- "reflect"
- "testing"
-)
-
-func TestMultiResultSet(t *testing.T) {
- type result struct {
- values [][]int
- columns []string
- }
-
- // checkRows is a helper test function to validate rows containing 3 result
- // sets with specific values and columns. The basic query would look like this:
- //
- // SELECT 1 AS col1, 2 AS col2 UNION SELECT 3, 4;
- // SELECT 0 UNION SELECT 1;
- // SELECT 1 AS col1, 2 AS col2, 3 AS col3 UNION SELECT 4, 5, 6;
- //
- // to distinguish test cases the first string argument is put in front of
- // every error or fatal message.
- checkRows := func(desc string, rows *sql.Rows, dbt *DBTest) {
- expected := []result{
- {
- values: [][]int{{1, 2}, {3, 4}},
- columns: []string{"col1", "col2"},
- },
- {
- values: [][]int{{1, 2, 3}, {4, 5, 6}},
- columns: []string{"col1", "col2", "col3"},
- },
- }
-
- var res1 result
- for rows.Next() {
- var res [2]int
- if err := rows.Scan(&res[0], &res[1]); err != nil {
- dbt.Fatal(err)
- }
- res1.values = append(res1.values, res[:])
- }
-
- cols, err := rows.Columns()
- if err != nil {
- dbt.Fatal(desc, err)
- }
- res1.columns = cols
-
- if !reflect.DeepEqual(expected[0], res1) {
- dbt.Error(desc, "want =", expected[0], "got =", res1)
- }
-
- if !rows.NextResultSet() {
- dbt.Fatal(desc, "expected next result set")
- }
-
- // ignoring one result set
-
- if !rows.NextResultSet() {
- dbt.Fatal(desc, "expected next result set")
- }
-
- var res2 result
- cols, err = rows.Columns()
- if err != nil {
- dbt.Fatal(desc, err)
- }
- res2.columns = cols
-
- for rows.Next() {
- var res [3]int
- if err := rows.Scan(&res[0], &res[1], &res[2]); err != nil {
- dbt.Fatal(desc, err)
- }
- res2.values = append(res2.values, res[:])
- }
-
- if !reflect.DeepEqual(expected[1], res2) {
- dbt.Error(desc, "want =", expected[1], "got =", res2)
- }
-
- if rows.NextResultSet() {
- dbt.Error(desc, "unexpected next result set")
- }
-
- if err := rows.Err(); err != nil {
- dbt.Error(desc, err)
- }
- }
-
- runTestsWithMultiStatement(t, dsn, func(dbt *DBTest) {
- rows := dbt.mustQuery(`DO 1;
- SELECT 1 AS col1, 2 AS col2 UNION SELECT 3, 4;
- DO 1;
- SELECT 0 UNION SELECT 1;
- SELECT 1 AS col1, 2 AS col2, 3 AS col3 UNION SELECT 4, 5, 6;`)
- defer rows.Close()
- checkRows("query: ", rows, dbt)
- })
-
- runTestsWithMultiStatement(t, dsn, func(dbt *DBTest) {
- queries := []string{
- `
- DROP PROCEDURE IF EXISTS test_mrss;
- CREATE PROCEDURE test_mrss()
- BEGIN
- DO 1;
- SELECT 1 AS col1, 2 AS col2 UNION SELECT 3, 4;
- DO 1;
- SELECT 0 UNION SELECT 1;
- SELECT 1 AS col1, 2 AS col2, 3 AS col3 UNION SELECT 4, 5, 6;
- END
- `,
- `
- DROP PROCEDURE IF EXISTS test_mrss;
- CREATE PROCEDURE test_mrss()
- BEGIN
- SELECT 1 AS col1, 2 AS col2 UNION SELECT 3, 4;
- SELECT 0 UNION SELECT 1;
- SELECT 1 AS col1, 2 AS col2, 3 AS col3 UNION SELECT 4, 5, 6;
- END
- `,
- }
-
- defer dbt.mustExec("DROP PROCEDURE IF EXISTS test_mrss")
-
- for i, query := range queries {
- dbt.mustExec(query)
-
- stmt, err := dbt.db.Prepare("CALL test_mrss()")
- if err != nil {
- dbt.Fatalf("%v (i=%d)", err, i)
- }
- defer stmt.Close()
-
- for j := 0; j < 2; j++ {
- rows, err := stmt.Query()
- if err != nil {
- dbt.Fatalf("%v (i=%d) (j=%d)", err, i, j)
- }
- checkRows(fmt.Sprintf("prepared stmt query (i=%d) (j=%d): ", i, j), rows, dbt)
- }
- }
- })
-}
-
-func TestMultiResultSetNoSelect(t *testing.T) {
- runTestsWithMultiStatement(t, dsn, func(dbt *DBTest) {
- rows := dbt.mustQuery("DO 1; DO 2;")
- defer rows.Close()
-
- if rows.Next() {
- dbt.Error("unexpected row")
- }
-
- if rows.NextResultSet() {
- dbt.Error("unexpected next result set")
- }
-
- if err := rows.Err(); err != nil {
- dbt.Error("expected nil; got ", err)
- }
- })
-}
-
-// tests if rows are set in a proper state if some results were ignored before
-// calling rows.NextResultSet.
-func TestSkipResults(t *testing.T) {
- runTests(t, dsn, func(dbt *DBTest) {
- rows := dbt.mustQuery("SELECT 1, 2")
- defer rows.Close()
-
- if !rows.Next() {
- dbt.Error("expected row")
- }
-
- if rows.NextResultSet() {
- dbt.Error("unexpected next result set")
- }
-
- if err := rows.Err(); err != nil {
- dbt.Error("expected nil; got ", err)
- }
- })
-}
diff --git a/vendor/github.com/go-sql-driver/mysql/driver_test.go b/vendor/github.com/go-sql-driver/mysql/driver_test.go
index 07f7e79b9..78e68f5d0 100644
--- a/vendor/github.com/go-sql-driver/mysql/driver_test.go
+++ b/vendor/github.com/go-sql-driver/mysql/driver_test.go
@@ -684,7 +684,7 @@ func TestDateTime(t *testing.T) {
for _, setup := range setups.tests {
allowBinTime := true
if setup.s == "" {
- // fill time string wherever Go can reliable produce it
+ // fill time string whereever Go can reliable produce it
setup.s = setup.t.Format(setups.tlayout)
} else if setup.s[0] == '!' {
// skip tests using setup.t as source in queries
@@ -856,14 +856,14 @@ func TestNULL(t *testing.T) {
dbt.Fatal(err)
}
if b != nil {
- dbt.Error("non-nil []byte which should be nil")
+ dbt.Error("non-nil []byte wich should be nil")
}
// Read non-nil
if err = nonNullStmt.QueryRow().Scan(&b); err != nil {
dbt.Fatal(err)
}
if b == nil {
- dbt.Error("nil []byte which should be non-nil")
+ dbt.Error("nil []byte wich should be non-nil")
}
// Insert nil
b = nil
@@ -1054,36 +1054,22 @@ func TestLoadData(t *testing.T) {
dbt.Fatalf("rows count mismatch. Got %d, want 4", i)
}
}
-
- dbt.db.Exec("DROP TABLE IF EXISTS test")
- dbt.mustExec("CREATE TABLE test (id INT NOT NULL PRIMARY KEY, value TEXT NOT NULL) CHARACTER SET utf8")
-
- // Local File
file, err := ioutil.TempFile("", "gotest")
defer os.Remove(file.Name())
if err != nil {
dbt.Fatal(err)
}
- RegisterLocalFile(file.Name())
-
- // Try first with empty file
- dbt.mustExec(fmt.Sprintf("LOAD DATA LOCAL INFILE %q INTO TABLE test", file.Name()))
- var count int
- err = dbt.db.QueryRow("SELECT COUNT(*) FROM test").Scan(&count)
- if err != nil {
- dbt.Fatal(err.Error())
- }
- if count != 0 {
- dbt.Fatalf("unexpected row count: got %d, want 0", count)
- }
-
- // Then fille File with data and try to load it
file.WriteString("1\ta string\n2\ta string containing a \\t\n3\ta string containing a \\n\n4\ta string containing both \\t\\n\n")
file.Close()
+
+ dbt.db.Exec("DROP TABLE IF EXISTS test")
+ dbt.mustExec("CREATE TABLE test (id INT NOT NULL PRIMARY KEY, value TEXT NOT NULL) CHARACTER SET utf8")
+
+ // Local File
+ RegisterLocalFile(file.Name())
dbt.mustExec(fmt.Sprintf("LOAD DATA LOCAL INFILE %q INTO TABLE test", file.Name()))
verifyLoadDataResult()
-
- // Try with non-existing file
+ // negative test
_, err = dbt.db.Exec("LOAD DATA LOCAL INFILE 'doesnotexist' INTO TABLE test")
if err == nil {
dbt.Fatal("load non-existent file didn't fail")
@@ -1916,36 +1902,3 @@ func TestInterruptBySignal(t *testing.T) {
}
})
}
-
-func TestColumnsReusesSlice(t *testing.T) {
- rows := mysqlRows{
- rs: resultSet{
- columns: []mysqlField{
- {
- tableName: "test",
- name: "A",
- },
- {
- tableName: "test",
- name: "B",
- },
- },
- },
- }
-
- allocs := testing.AllocsPerRun(1, func() {
- cols := rows.Columns()
-
- if len(cols) != 2 {
- t.Fatalf("expected 2 columns, got %d", len(cols))
- }
- })
-
- if allocs != 0 {
- t.Fatalf("expected 0 allocations, got %d", int(allocs))
- }
-
- if rows.rs.columnNames == nil {
- t.Fatalf("expected columnNames to be set, got nil")
- }
-}
diff --git a/vendor/github.com/go-sql-driver/mysql/dsn.go b/vendor/github.com/go-sql-driver/mysql/dsn.go
index 5c828bf90..ac00dcedd 100644
--- a/vendor/github.com/go-sql-driver/mysql/dsn.go
+++ b/vendor/github.com/go-sql-driver/mysql/dsn.go
@@ -494,10 +494,6 @@ func parseDSNParams(cfg *Config, params string) (err error) {
if boolValue {
cfg.TLSConfig = "true"
cfg.tls = &tls.Config{}
- host, _, err := net.SplitHostPort(cfg.Addr)
- if err == nil {
- cfg.tls.ServerName = host
- }
} else {
cfg.TLSConfig = "false"
}
diff --git a/vendor/github.com/go-sql-driver/mysql/infile.go b/vendor/github.com/go-sql-driver/mysql/infile.go
index 4020f9192..547357cfa 100644
--- a/vendor/github.com/go-sql-driver/mysql/infile.go
+++ b/vendor/github.com/go-sql-driver/mysql/infile.go
@@ -147,8 +147,7 @@ func (mc *mysqlConn) handleInFileRequest(name string) (err error) {
}
// send content packets
- // if packetSize == 0, the Reader contains no data
- if err == nil && packetSize > 0 {
+ if err == nil {
data := make([]byte, 4+packetSize)
var n int
for err == nil {
diff --git a/vendor/github.com/go-sql-driver/mysql/packets.go b/vendor/github.com/go-sql-driver/mysql/packets.go
index cb21397a2..aafe9793e 100644
--- a/vendor/github.com/go-sql-driver/mysql/packets.go
+++ b/vendor/github.com/go-sql-driver/mysql/packets.go
@@ -486,24 +486,23 @@ func (mc *mysqlConn) readResultOK() ([]byte, error) {
plugin := string(data[1:pluginEndIndex])
cipher := data[pluginEndIndex+1 : len(data)-1]
- switch plugin {
- case "mysql_old_password":
+ if plugin == "mysql_old_password" {
// using old_passwords
return cipher, ErrOldPassword
- case "mysql_clear_password":
+ } else if plugin == "mysql_clear_password" {
// using clear text password
return cipher, ErrCleartextPassword
- case "mysql_native_password":
+ } else if plugin == "mysql_native_password" {
// using mysql default authentication method
return cipher, ErrNativePassword
- default:
+ } else {
return cipher, ErrUnknownPlugin
}
+ } else {
+ // https://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::OldAuthSwitchRequest
+ return nil, ErrOldPassword
}
- // https://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::OldAuthSwitchRequest
- return nil, ErrOldPassword
-
default: // Error otherwise
return nil, mc.handleErrorPacket(data)
}
@@ -585,8 +584,8 @@ func (mc *mysqlConn) handleOkPacket(data []byte) error {
// server_status [2 bytes]
mc.status = readStatus(data[1+n+m : 1+n+m+2])
- if mc.status&statusMoreResultsExists != 0 {
- return nil
+ if err := mc.discardResults(); err != nil {
+ return err
}
// warning count [2 bytes]
@@ -699,10 +698,6 @@ func (mc *mysqlConn) readColumns(count int) ([]mysqlField, error) {
func (rows *textRows) readRow(dest []driver.Value) error {
mc := rows.mc
- if rows.rs.done {
- return io.EOF
- }
-
data, err := mc.readPacket()
if err != nil {
return err
@@ -712,11 +707,15 @@ func (rows *textRows) readRow(dest []driver.Value) error {
if data[0] == iEOF && len(data) == 5 {
// server_status [2 bytes]
rows.mc.status = readStatus(data[3:])
- rows.rs.done = true
- if !rows.HasNextResultSet() {
- rows.mc = nil
+ err = rows.mc.discardResults()
+ if err == nil {
+ err = io.EOF
+ } else {
+ // connection unusable
+ rows.mc.Close()
}
- return io.EOF
+ rows.mc = nil
+ return err
}
if data[0] == iERR {
rows.mc = nil
@@ -737,7 +736,7 @@ func (rows *textRows) readRow(dest []driver.Value) error {
if !mc.parseTime {
continue
} else {
- switch rows.rs.columns[i].fieldType {
+ switch rows.columns[i].fieldType {
case fieldTypeTimestamp, fieldTypeDateTime,
fieldTypeDate, fieldTypeNewDate:
dest[i], err = parseDateTime(
@@ -1098,6 +1097,8 @@ func (mc *mysqlConn) discardResults() error {
if err := mc.readUntilEOF(); err != nil {
return err
}
+ } else {
+ mc.status &^= statusMoreResultsExists
}
}
return nil
@@ -1115,11 +1116,15 @@ func (rows *binaryRows) readRow(dest []driver.Value) error {
// EOF Packet
if data[0] == iEOF && len(data) == 5 {
rows.mc.status = readStatus(data[3:])
- rows.rs.done = true
- if !rows.HasNextResultSet() {
- rows.mc = nil
+ err = rows.mc.discardResults()
+ if err == nil {
+ err = io.EOF
+ } else {
+ // connection unusable
+ rows.mc.Close()
}
- return io.EOF
+ rows.mc = nil
+ return err
}
rows.mc = nil
@@ -1140,14 +1145,14 @@ func (rows *binaryRows) readRow(dest []driver.Value) error {
}
// Convert to byte-coded string
- switch rows.rs.columns[i].fieldType {
+ switch rows.columns[i].fieldType {
case fieldTypeNULL:
dest[i] = nil
continue
// Numeric Types
case fieldTypeTiny:
- if rows.rs.columns[i].flags&flagUnsigned != 0 {
+ if rows.columns[i].flags&flagUnsigned != 0 {
dest[i] = int64(data[pos])
} else {
dest[i] = int64(int8(data[pos]))
@@ -1156,7 +1161,7 @@ func (rows *binaryRows) readRow(dest []driver.Value) error {
continue
case fieldTypeShort, fieldTypeYear:
- if rows.rs.columns[i].flags&flagUnsigned != 0 {
+ if rows.columns[i].flags&flagUnsigned != 0 {
dest[i] = int64(binary.LittleEndian.Uint16(data[pos : pos+2]))
} else {
dest[i] = int64(int16(binary.LittleEndian.Uint16(data[pos : pos+2])))
@@ -1165,7 +1170,7 @@ func (rows *binaryRows) readRow(dest []driver.Value) error {
continue
case fieldTypeInt24, fieldTypeLong:
- if rows.rs.columns[i].flags&flagUnsigned != 0 {
+ if rows.columns[i].flags&flagUnsigned != 0 {
dest[i] = int64(binary.LittleEndian.Uint32(data[pos : pos+4]))
} else {
dest[i] = int64(int32(binary.LittleEndian.Uint32(data[pos : pos+4])))
@@ -1174,7 +1179,7 @@ func (rows *binaryRows) readRow(dest []driver.Value) error {
continue
case fieldTypeLongLong:
- if rows.rs.columns[i].flags&flagUnsigned != 0 {
+ if rows.columns[i].flags&flagUnsigned != 0 {
val := binary.LittleEndian.Uint64(data[pos : pos+8])
if val > math.MaxInt64 {
dest[i] = uint64ToString(val)
@@ -1188,7 +1193,7 @@ func (rows *binaryRows) readRow(dest []driver.Value) error {
continue
case fieldTypeFloat:
- dest[i] = math.Float32frombits(binary.LittleEndian.Uint32(data[pos : pos+4]))
+ dest[i] = float32(math.Float32frombits(binary.LittleEndian.Uint32(data[pos : pos+4])))
pos += 4
continue
@@ -1228,10 +1233,10 @@ func (rows *binaryRows) readRow(dest []driver.Value) error {
case isNull:
dest[i] = nil
continue
- case rows.rs.columns[i].fieldType == fieldTypeTime:
+ case rows.columns[i].fieldType == fieldTypeTime:
// database/sql does not support an equivalent to TIME, return a string
var dstlen uint8
- switch decimals := rows.rs.columns[i].decimals; decimals {
+ switch decimals := rows.columns[i].decimals; decimals {
case 0x00, 0x1f:
dstlen = 8
case 1, 2, 3, 4, 5, 6:
@@ -1239,7 +1244,7 @@ func (rows *binaryRows) readRow(dest []driver.Value) error {
default:
return fmt.Errorf(
"protocol error, illegal decimals value %d",
- rows.rs.columns[i].decimals,
+ rows.columns[i].decimals,
)
}
dest[i], err = formatBinaryDateTime(data[pos:pos+int(num)], dstlen, true)
@@ -1247,10 +1252,10 @@ func (rows *binaryRows) readRow(dest []driver.Value) error {
dest[i], err = parseBinaryDateTime(num, data[pos:], rows.mc.cfg.Loc)
default:
var dstlen uint8
- if rows.rs.columns[i].fieldType == fieldTypeDate {
+ if rows.columns[i].fieldType == fieldTypeDate {
dstlen = 10
} else {
- switch decimals := rows.rs.columns[i].decimals; decimals {
+ switch decimals := rows.columns[i].decimals; decimals {
case 0x00, 0x1f:
dstlen = 19
case 1, 2, 3, 4, 5, 6:
@@ -1258,7 +1263,7 @@ func (rows *binaryRows) readRow(dest []driver.Value) error {
default:
return fmt.Errorf(
"protocol error, illegal decimals value %d",
- rows.rs.columns[i].decimals,
+ rows.columns[i].decimals,
)
}
}
@@ -1274,7 +1279,7 @@ func (rows *binaryRows) readRow(dest []driver.Value) error {
// Please report if this happens!
default:
- return fmt.Errorf("unknown field type %d", rows.rs.columns[i].fieldType)
+ return fmt.Errorf("unknown field type %d", rows.columns[i].fieldType)
}
}
diff --git a/vendor/github.com/go-sql-driver/mysql/packets_test.go b/vendor/github.com/go-sql-driver/mysql/packets_test.go
index b1d64f5c7..98404586a 100644
--- a/vendor/github.com/go-sql-driver/mysql/packets_test.go
+++ b/vendor/github.com/go-sql-driver/mysql/packets_test.go
@@ -101,7 +101,7 @@ func TestReadPacketSingleByte(t *testing.T) {
t.Fatal(err)
}
if len(packet) != 1 {
- t.Fatalf("unexpected packet length: expected %d, got %d", 1, len(packet))
+ t.Fatalf("unexpected packet lenght: expected %d, got %d", 1, len(packet))
}
if packet[0] != 0xff {
t.Fatalf("unexpected packet content: expected %x, got %x", 0xff, packet[0])
@@ -171,7 +171,7 @@ func TestReadPacketSplit(t *testing.T) {
t.Fatal(err)
}
if len(packet) != maxPacketSize {
- t.Fatalf("unexpected packet length: expected %d, got %d", maxPacketSize, len(packet))
+ t.Fatalf("unexpected packet lenght: expected %d, got %d", maxPacketSize, len(packet))
}
if packet[0] != 0x11 {
t.Fatalf("unexpected payload start: expected %x, got %x", 0x11, packet[0])
@@ -205,7 +205,7 @@ func TestReadPacketSplit(t *testing.T) {
t.Fatal(err)
}
if len(packet) != 2*maxPacketSize {
- t.Fatalf("unexpected packet length: expected %d, got %d", 2*maxPacketSize, len(packet))
+ t.Fatalf("unexpected packet lenght: expected %d, got %d", 2*maxPacketSize, len(packet))
}
if packet[0] != 0x11 {
t.Fatalf("unexpected payload start: expected %x, got %x", 0x11, packet[0])
@@ -231,7 +231,7 @@ func TestReadPacketSplit(t *testing.T) {
t.Fatal(err)
}
if len(packet) != maxPacketSize+42 {
- t.Fatalf("unexpected packet length: expected %d, got %d", maxPacketSize+42, len(packet))
+ t.Fatalf("unexpected packet lenght: expected %d, got %d", maxPacketSize+42, len(packet))
}
if packet[0] != 0x11 {
t.Fatalf("unexpected payload start: expected %x, got %x", 0x11, packet[0])
diff --git a/vendor/github.com/go-sql-driver/mysql/rows.go b/vendor/github.com/go-sql-driver/mysql/rows.go
index 13905e216..c08255eee 100644
--- a/vendor/github.com/go-sql-driver/mysql/rows.go
+++ b/vendor/github.com/go-sql-driver/mysql/rows.go
@@ -21,15 +21,9 @@ type mysqlField struct {
decimals byte
}
-type resultSet struct {
- columns []mysqlField
- columnNames []string
- done bool
-}
-
type mysqlRows struct {
- mc *mysqlConn
- rs resultSet
+ mc *mysqlConn
+ columns []mysqlField
}
type binaryRows struct {
@@ -40,31 +34,27 @@ type textRows struct {
mysqlRows
}
-func (rows *mysqlRows) Columns() []string {
- if rows.rs.columnNames != nil {
- return rows.rs.columnNames
- }
+type emptyRows struct{}
- columns := make([]string, len(rows.rs.columns))
+func (rows *mysqlRows) Columns() []string {
+ columns := make([]string, len(rows.columns))
if rows.mc != nil && rows.mc.cfg.ColumnsWithAlias {
for i := range columns {
- if tableName := rows.rs.columns[i].tableName; len(tableName) > 0 {
- columns[i] = tableName + "." + rows.rs.columns[i].name
+ if tableName := rows.columns[i].tableName; len(tableName) > 0 {
+ columns[i] = tableName + "." + rows.columns[i].name
} else {
- columns[i] = rows.rs.columns[i].name
+ columns[i] = rows.columns[i].name
}
}
} else {
for i := range columns {
- columns[i] = rows.rs.columns[i].name
+ columns[i] = rows.columns[i].name
}
}
-
- rows.rs.columnNames = columns
return columns
}
-func (rows *mysqlRows) Close() (err error) {
+func (rows *mysqlRows) Close() error {
mc := rows.mc
if mc == nil {
return nil
@@ -74,9 +64,7 @@ func (rows *mysqlRows) Close() (err error) {
}
// Remove unread packets from stream
- if !rows.rs.done {
- err = mc.readUntilEOF()
- }
+ err := mc.readUntilEOF()
if err == nil {
if err = mc.discardResults(); err != nil {
return err
@@ -87,62 +75,6 @@ func (rows *mysqlRows) Close() (err error) {
return err
}
-func (rows *mysqlRows) HasNextResultSet() (b bool) {
- if rows.mc == nil {
- return false
- }
- return rows.mc.status&statusMoreResultsExists != 0
-}
-
-func (rows *mysqlRows) nextResultSet() (int, error) {
- if rows.mc == nil {
- return 0, io.EOF
- }
- if rows.mc.netConn == nil {
- return 0, ErrInvalidConn
- }
-
- // Remove unread packets from stream
- if !rows.rs.done {
- if err := rows.mc.readUntilEOF(); err != nil {
- return 0, err
- }
- rows.rs.done = true
- }
-
- if !rows.HasNextResultSet() {
- rows.mc = nil
- return 0, io.EOF
- }
- rows.rs = resultSet{}
- return rows.mc.readResultSetHeaderPacket()
-}
-
-func (rows *mysqlRows) nextNotEmptyResultSet() (int, error) {
- for {
- resLen, err := rows.nextResultSet()
- if err != nil {
- return 0, err
- }
-
- if resLen > 0 {
- return resLen, nil
- }
-
- rows.rs.done = true
- }
-}
-
-func (rows *binaryRows) NextResultSet() error {
- resLen, err := rows.nextNotEmptyResultSet()
- if err != nil {
- return err
- }
-
- rows.rs.columns, err = rows.mc.readColumns(resLen)
- return err
-}
-
func (rows *binaryRows) Next(dest []driver.Value) error {
if mc := rows.mc; mc != nil {
if mc.netConn == nil {
@@ -155,16 +87,6 @@ func (rows *binaryRows) Next(dest []driver.Value) error {
return io.EOF
}
-func (rows *textRows) NextResultSet() (err error) {
- resLen, err := rows.nextNotEmptyResultSet()
- if err != nil {
- return err
- }
-
- rows.rs.columns, err = rows.mc.readColumns(resLen)
- return err
-}
-
func (rows *textRows) Next(dest []driver.Value) error {
if mc := rows.mc; mc != nil {
if mc.netConn == nil {
@@ -176,3 +98,15 @@ func (rows *textRows) Next(dest []driver.Value) error {
}
return io.EOF
}
+
+func (rows emptyRows) Columns() []string {
+ return nil
+}
+
+func (rows emptyRows) Close() error {
+ return nil
+}
+
+func (rows emptyRows) Next(dest []driver.Value) error {
+ return io.EOF
+}
diff --git a/vendor/github.com/go-sql-driver/mysql/statement.go b/vendor/github.com/go-sql-driver/mysql/statement.go
index e5071276a..7f9b04585 100644
--- a/vendor/github.com/go-sql-driver/mysql/statement.go
+++ b/vendor/github.com/go-sql-driver/mysql/statement.go
@@ -11,7 +11,6 @@ package mysql
import (
"database/sql/driver"
"fmt"
- "io"
"reflect"
"strconv"
)
@@ -20,6 +19,7 @@ type mysqlStmt struct {
mc *mysqlConn
id uint32
paramCount int
+ columns []mysqlField // cached from the first query
}
func (stmt *mysqlStmt) Close() error {
@@ -62,30 +62,26 @@ func (stmt *mysqlStmt) Exec(args []driver.Value) (driver.Result, error) {
// Read Result
resLen, err := mc.readResultSetHeaderPacket()
- if err != nil {
- return nil, err
- }
-
- if resLen > 0 {
- // Columns
- if err = mc.readUntilEOF(); err != nil {
- return nil, err
+ if err == nil {
+ if resLen > 0 {
+ // Columns
+ err = mc.readUntilEOF()
+ if err != nil {
+ return nil, err
+ }
+
+ // Rows
+ err = mc.readUntilEOF()
}
-
- // Rows
- if err := mc.readUntilEOF(); err != nil {
- return nil, err
+ if err == nil {
+ return &mysqlResult{
+ affectedRows: int64(mc.affectedRows),
+ insertId: int64(mc.insertId),
+ }, nil
}
}
- if err := mc.discardResults(); err != nil {
- return nil, err
- }
-
- return &mysqlResult{
- affectedRows: int64(mc.affectedRows),
- insertId: int64(mc.insertId),
- }, nil
+ return nil, err
}
func (stmt *mysqlStmt) Query(args []driver.Value) (driver.Rows, error) {
@@ -111,15 +107,14 @@ func (stmt *mysqlStmt) Query(args []driver.Value) (driver.Rows, error) {
if resLen > 0 {
rows.mc = mc
- rows.rs.columns, err = mc.readColumns(resLen)
- } else {
- rows.rs.done = true
-
- switch err := rows.NextResultSet(); err {
- case nil, io.EOF:
- return rows, nil
- default:
- return nil, err
+ // Columns
+ // If not cached, read them and cache them
+ if stmt.columns == nil {
+ rows.columns, err = mc.readColumns(resLen)
+ stmt.columns = rows.columns
+ } else {
+ rows.columns = stmt.columns
+ err = mc.readUntilEOF()
}
}
diff --git a/vendor/github.com/golang/freetype/truetype/truetype_test.go b/vendor/github.com/golang/freetype/truetype/truetype_test.go
index bd62d1da1..a194f3703 100644
--- a/vendor/github.com/golang/freetype/truetype/truetype_test.go
+++ b/vendor/github.com/golang/freetype/truetype/truetype_test.go
@@ -282,7 +282,7 @@ func scalingTestParse(line string) (ret scalingTestData) {
}
// scalingTestEquals is equivalent to, but faster than, calling
-// reflect.DeepEquals(a, b), and also returns the index of the first non-equal
+// reflect.DeepEqual(a, b), and also returns the index of the first non-equal
// element. It also treats a nil []Point and an empty non-nil []Point as equal.
// a and b must have equal length.
func scalingTestEquals(a, b []Point) (index int, equals bool) {
diff --git a/vendor/github.com/golang/protobuf/README.md b/vendor/github.com/golang/protobuf/README.md
index aa933d788..e560b7321 100644
--- a/vendor/github.com/golang/protobuf/README.md
+++ b/vendor/github.com/golang/protobuf/README.md
@@ -104,7 +104,6 @@ for a protocol buffer variable v:
When the .proto file specifies `syntax="proto3"`, there are some differences:
- Non-repeated fields of non-message type are values instead of pointers.
- - Getters are only generated for message and oneof fields.
- Enum types do not get an Enum method.
Consider file test.proto, containing
diff --git a/vendor/github.com/golang/protobuf/jsonpb/jsonpb.go b/vendor/github.com/golang/protobuf/jsonpb/jsonpb.go
index eff41c2e6..c7a45d6f0 100644
--- a/vendor/github.com/golang/protobuf/jsonpb/jsonpb.go
+++ b/vendor/github.com/golang/protobuf/jsonpb/jsonpb.go
@@ -44,6 +44,7 @@ import (
"errors"
"fmt"
"io"
+ "math"
"reflect"
"sort"
"strconv"
@@ -74,6 +75,22 @@ type Marshaler struct {
OrigName bool
}
+// JSONPBMarshaler is implemented by protobuf messages that customize the
+// way they are marshaled to JSON. Messages that implement this should
+// also implement JSONPBUnmarshaler so that the custom format can be
+// parsed.
+type JSONPBMarshaler interface {
+ MarshalJSONPB(*Marshaler) ([]byte, error)
+}
+
+// JSONPBUnmarshaler is implemented by protobuf messages that customize
+// the way they are unmarshaled from JSON. Messages that implement this
+// should also implement JSONPBMarshaler so that the custom format can be
+// produced.
+type JSONPBUnmarshaler interface {
+ UnmarshalJSONPB(*Unmarshaler, []byte) error
+}
+
// Marshal marshals a protocol buffer into JSON.
func (m *Marshaler) Marshal(out io.Writer, pb proto.Message) error {
writer := &errWriter{writer: out}
@@ -91,6 +108,12 @@ func (m *Marshaler) MarshalToString(pb proto.Message) (string, error) {
type int32Slice []int32
+var nonFinite = map[string]float64{
+ `"NaN"`: math.NaN(),
+ `"Infinity"`: math.Inf(1),
+ `"-Infinity"`: math.Inf(-1),
+}
+
// For sorting extensions ids to ensure stable output.
func (s int32Slice) Len() int { return len(s) }
func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
@@ -102,6 +125,31 @@ type wkt interface {
// marshalObject writes a struct to the Writer.
func (m *Marshaler) marshalObject(out *errWriter, v proto.Message, indent, typeURL string) error {
+ if jsm, ok := v.(JSONPBMarshaler); ok {
+ b, err := jsm.MarshalJSONPB(m)
+ if err != nil {
+ return err
+ }
+ if typeURL != "" {
+ // we are marshaling this object to an Any type
+ var js map[string]*json.RawMessage
+ if err = json.Unmarshal(b, &js); err != nil {
+ return fmt.Errorf("type %T produced invalid JSON: %v", v, err)
+ }
+ turl, err := json.Marshal(typeURL)
+ if err != nil {
+ return fmt.Errorf("failed to marshal type URL %q to JSON: %v", typeURL, err)
+ }
+ js["@type"] = (*json.RawMessage)(&turl)
+ if b, err = json.Marshal(js); err != nil {
+ return err
+ }
+ }
+
+ out.write(string(b))
+ return out.err
+ }
+
s := reflect.ValueOf(v).Elem()
// Handle well-known types.
@@ -182,7 +230,7 @@ func (m *Marshaler) marshalObject(out *errWriter, v proto.Message, indent, typeU
// IsNil will panic on most value kinds.
switch value.Kind() {
- case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
+ case reflect.Chan, reflect.Func, reflect.Interface:
if value.IsNil() {
continue
}
@@ -210,6 +258,10 @@ func (m *Marshaler) marshalObject(out *errWriter, v proto.Message, indent, typeU
if value.Len() == 0 {
continue
}
+ case reflect.Map, reflect.Ptr, reflect.Slice:
+ if value.IsNil() {
+ continue
+ }
}
}
@@ -373,10 +425,15 @@ func (m *Marshaler) marshalField(out *errWriter, prop *proto.Properties, v refle
// marshalValue writes the value to the Writer.
func (m *Marshaler) marshalValue(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error {
-
var err error
v = reflect.Indirect(v)
+ // Handle nil pointer
+ if v.Kind() == reflect.Invalid {
+ out.write("null")
+ return out.err
+ }
+
// Handle repeated elements.
if v.Kind() == reflect.Slice && v.Type().Elem().Kind() != reflect.Uint8 {
out.write("[")
@@ -406,9 +463,6 @@ func (m *Marshaler) marshalValue(out *errWriter, prop *proto.Properties, v refle
// Handle well-known types.
// Most are handled up in marshalObject (because 99% are messages).
- type wkt interface {
- XXX_WellKnownType() string
- }
if wkt, ok := v.Interface().(wkt); ok {
switch wkt.XXX_WellKnownType() {
case "NullValue":
@@ -496,6 +550,24 @@ func (m *Marshaler) marshalValue(out *errWriter, prop *proto.Properties, v refle
return out.err
}
+ // Handle non-finite floats, e.g. NaN, Infinity and -Infinity.
+ if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 {
+ f := v.Float()
+ var sval string
+ switch {
+ case math.IsInf(f, 1):
+ sval = `"Infinity"`
+ case math.IsInf(f, -1):
+ sval = `"-Infinity"`
+ case math.IsNaN(f):
+ sval = `"NaN"`
+ }
+ if sval != "" {
+ out.write(sval)
+ return out.err
+ }
+ }
+
// Default handling defers to the encoding/json library.
b, err := json.Marshal(v.Interface())
if err != nil {
@@ -571,10 +643,11 @@ func (u *Unmarshaler) unmarshalValue(target reflect.Value, inputValue json.RawMe
return u.unmarshalValue(target.Elem(), inputValue, prop)
}
- // Handle well-known types.
- type wkt interface {
- XXX_WellKnownType() string
+ if jsu, ok := target.Addr().Interface().(JSONPBUnmarshaler); ok {
+ return jsu.UnmarshalJSONPB(u, []byte(inputValue))
}
+
+ // Handle well-known types.
if w, ok := target.Addr().Interface().(wkt); ok {
switch w.XXX_WellKnownType() {
case "DoubleValue", "FloatValue", "Int64Value", "UInt64Value",
@@ -585,19 +658,22 @@ func (u *Unmarshaler) unmarshalValue(target reflect.Value, inputValue json.RawMe
// so we don't have to do any extra work.
return u.unmarshalValue(target.Field(0), inputValue, prop)
case "Any":
- var jsonFields map[string]json.RawMessage
+ // Use json.RawMessage pointer type instead of value to support pre-1.8 version.
+ // 1.8 changed RawMessage.MarshalJSON from pointer type to value type, see
+ // https://github.com/golang/go/issues/14493
+ var jsonFields map[string]*json.RawMessage
if err := json.Unmarshal(inputValue, &jsonFields); err != nil {
return err
}
val, ok := jsonFields["@type"]
- if !ok {
+ if !ok || val == nil {
return errors.New("Any JSON doesn't have '@type'")
}
var turl string
- if err := json.Unmarshal([]byte(val), &turl); err != nil {
- return fmt.Errorf("can't unmarshal Any's '@type': %q", val)
+ if err := json.Unmarshal([]byte(*val), &turl); err != nil {
+ return fmt.Errorf("can't unmarshal Any's '@type': %q", *val)
}
target.Field(0).SetString(turl)
@@ -617,8 +693,8 @@ func (u *Unmarshaler) unmarshalValue(target reflect.Value, inputValue json.RawMe
return errors.New("Any JSON doesn't have 'value'")
}
- if err := u.unmarshalValue(reflect.ValueOf(m).Elem(), val, nil); err != nil {
- return fmt.Errorf("can't unmarshal Any's WKT: %v", err)
+ if err := u.unmarshalValue(reflect.ValueOf(m).Elem(), *val, nil); err != nil {
+ return fmt.Errorf("can't unmarshal Any nested proto %T: %v", m, err)
}
} else {
delete(jsonFields, "@type")
@@ -628,13 +704,13 @@ func (u *Unmarshaler) unmarshalValue(target reflect.Value, inputValue json.RawMe
}
if err = u.unmarshalValue(reflect.ValueOf(m).Elem(), nestedProto, nil); err != nil {
- return fmt.Errorf("can't unmarshal nested Any proto: %v", err)
+ return fmt.Errorf("can't unmarshal Any nested proto %T: %v", m, err)
}
}
b, err := proto.Marshal(m)
if err != nil {
- return fmt.Errorf("can't marshal proto into Any.Value: %v", err)
+ return fmt.Errorf("can't marshal proto %T into Any.Value: %v", m, err)
}
target.Field(1).SetBytes(b)
@@ -911,6 +987,15 @@ func (u *Unmarshaler) unmarshalValue(target reflect.Value, inputValue json.RawMe
inputValue = inputValue[1 : len(inputValue)-1]
}
+ // Non-finite numbers can be encoded as strings.
+ isFloat := targetType.Kind() == reflect.Float32 || targetType.Kind() == reflect.Float64
+ if isFloat {
+ if num, ok := nonFinite[string(inputValue)]; ok {
+ target.SetFloat(num)
+ return nil
+ }
+ }
+
// Use the encoding/json for parsing other value types.
return json.Unmarshal(inputValue, target.Addr().Interface())
}
diff --git a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test.go b/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test.go
index b0f995bfd..da93163e6 100644
--- a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test.go
+++ b/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test.go
@@ -35,6 +35,7 @@ import (
"bytes"
"encoding/json"
"io"
+ "math"
"reflect"
"strings"
"testing"
@@ -43,6 +44,7 @@ import (
pb "github.com/golang/protobuf/jsonpb/jsonpb_test_proto"
proto3pb "github.com/golang/protobuf/proto/proto3_proto"
+ "github.com/golang/protobuf/ptypes"
anypb "github.com/golang/protobuf/ptypes/any"
durpb "github.com/golang/protobuf/ptypes/duration"
stpb "github.com/golang/protobuf/ptypes/struct"
@@ -307,6 +309,23 @@ var (
"value": "1.212s"
}
}`
+
+ nonFinites = &pb.NonFinites{
+ FNan: proto.Float32(float32(math.NaN())),
+ FPinf: proto.Float32(float32(math.Inf(1))),
+ FNinf: proto.Float32(float32(math.Inf(-1))),
+ DNan: proto.Float64(float64(math.NaN())),
+ DPinf: proto.Float64(float64(math.Inf(1))),
+ DNinf: proto.Float64(float64(math.Inf(-1))),
+ }
+ nonFinitesJSON = `{` +
+ `"fNan":"NaN",` +
+ `"fPinf":"Infinity",` +
+ `"fNinf":"-Infinity",` +
+ `"dNan":"NaN",` +
+ `"dPinf":"Infinity",` +
+ `"dNinf":"-Infinity"` +
+ `}`
)
func init() {
@@ -326,6 +345,7 @@ var marshalingTests = []struct {
}{
{"simple flat object", marshaler, simpleObject, simpleObjectJSON},
{"simple pretty object", marshalerAllOptions, simpleObject, simpleObjectPrettyJSON},
+ {"non-finite floats fields object", marshaler, nonFinites, nonFinitesJSON},
{"repeated fields flat object", marshaler, repeatsObject, repeatsObjectJSON},
{"repeated fields pretty object", marshalerAllOptions, repeatsObject, repeatsObjectPrettyJSON},
{"nested message/enum flat object", marshaler, complexObject, complexObjectJSON},
@@ -350,6 +370,9 @@ var marshalingTests = []struct {
`{"rFunny":[1,2]}`},
{"empty value", marshaler, &pb.Simple3{}, `{}`},
{"empty value emitted", Marshaler{EmitDefaults: true}, &pb.Simple3{}, `{"dub":0}`},
+ {"empty repeated emitted", Marshaler{EmitDefaults: true}, &pb.SimpleSlice3{}, `{"slices":[]}`},
+ {"empty map emitted", Marshaler{EmitDefaults: true}, &pb.SimpleMap3{}, `{"stringy":{}}`},
+ {"nested struct null", Marshaler{EmitDefaults: true}, &pb.SimpleNull3{}, `{"simple":null}`},
{"map<int64, int32>", marshaler, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}, `{"nummy":{"1":2,"3":4}}`},
{"map<int64, int32>", marshalerAllOptions, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}, nummyPrettyJSON},
{"map<string, string>", marshaler,
@@ -439,6 +462,36 @@ func TestMarshaling(t *testing.T) {
}
}
+func TestMarshalJSONPBMarshaler(t *testing.T) {
+ rawJson := `{ "foo": "bar", "baz": [0, 1, 2, 3] }`
+ msg := dynamicMessage{rawJson: rawJson}
+ str, err := new(Marshaler).MarshalToString(&msg)
+ if err != nil {
+ t.Errorf("an unexpected error occurred when marshalling JSONPBMarshaler: %v", err)
+ }
+ if str != rawJson {
+ t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", str, rawJson)
+ }
+}
+
+func TestMarshalAnyJSONPBMarshaler(t *testing.T) {
+ msg := dynamicMessage{rawJson: `{ "foo": "bar", "baz": [0, 1, 2, 3] }`}
+ a, err := ptypes.MarshalAny(&msg)
+ if err != nil {
+ t.Errorf("an unexpected error occurred when marshalling to Any: %v", err)
+ }
+ str, err := new(Marshaler).MarshalToString(a)
+ if err != nil {
+ t.Errorf("an unexpected error occurred when marshalling Any to JSON: %v", err)
+ }
+ // after custom marshaling, it's round-tripped through JSON decoding/encoding already,
+ // so the keys are sorted, whitespace is compacted, and "@type" key has been added
+ expected := `{"@type":"type.googleapis.com/` + dynamicMessageName +`","baz":[0,1,2,3],"foo":"bar"}`
+ if str != expected {
+ t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", str, expected)
+ }
+}
+
var unmarshalingTests = []struct {
desc string
unmarshaler Unmarshaler
@@ -477,6 +530,9 @@ var unmarshalingTests = []struct {
}}},
{"unquoted int64 object", Unmarshaler{}, `{"oInt64":-314}`, &pb.Simple{OInt64: proto.Int64(-314)}},
{"unquoted uint64 object", Unmarshaler{}, `{"oUint64":123}`, &pb.Simple{OUint64: proto.Uint64(123)}},
+ {"NaN", Unmarshaler{}, `{"oDouble":"NaN"}`, &pb.Simple{ODouble: proto.Float64(math.NaN())}},
+ {"Inf", Unmarshaler{}, `{"oFloat":"Infinity"}`, &pb.Simple{OFloat: proto.Float32(float32(math.Inf(1)))}},
+ {"-Inf", Unmarshaler{}, `{"oDouble":"-Infinity"}`, &pb.Simple{ODouble: proto.Float64(math.Inf(-1))}},
{"map<int64, int32>", Unmarshaler{}, `{"nummy":{"1":2,"3":4}}`, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}},
{"map<string, string>", Unmarshaler{}, `{"strry":{"\"one\"":"two","three":"four"}}`, &pb.Mappy{Strry: map[string]string{`"one"`: "two", "three": "four"}}},
{"map<int32, Object>", Unmarshaler{}, `{"objjy":{"1":{"dub":1}}}`, &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: &pb.Simple3{Dub: 1}}}},
@@ -635,3 +691,69 @@ func TestUnmarshalingBadInput(t *testing.T) {
}
}
}
+
+func TestUnmarshalJSONPBUnmarshaler(t *testing.T) {
+ rawJson := `{ "foo": "bar", "baz": [0, 1, 2, 3] }`
+ var msg dynamicMessage
+ if err := Unmarshal(strings.NewReader(rawJson), &msg); err != nil {
+ t.Errorf("an unexpected error occurred when parsing into JSONPBUnmarshaler: %v", err)
+ }
+ if msg.rawJson != rawJson {
+ t.Errorf("message contents not set correctly after unmarshalling JSON: got %s, wanted %s", msg.rawJson, rawJson)
+ }
+}
+
+func TestUnmarshalAnyJSONPBUnmarshaler(t *testing.T) {
+ rawJson := `{ "@type": "blah.com/` + dynamicMessageName + `", "foo": "bar", "baz": [0, 1, 2, 3] }`
+ var got anypb.Any
+ if err := Unmarshal(strings.NewReader(rawJson), &got); err != nil {
+ t.Errorf("an unexpected error occurred when parsing into JSONPBUnmarshaler: %v", err)
+ }
+
+ dm := &dynamicMessage{rawJson: `{"baz":[0,1,2,3],"foo":"bar"}`}
+ var want anypb.Any
+ if b, err := proto.Marshal(dm); err != nil {
+ t.Errorf("an unexpected error occurred when marshaling message: %v", err)
+ } else {
+ want.TypeUrl = "blah.com/" + dynamicMessageName
+ want.Value = b
+ }
+
+ if !proto.Equal(&got, &want) {
+ t.Errorf("message contents not set correctly after unmarshalling JSON: got %s, wanted %s", got, want)
+ }
+}
+
+const (
+ dynamicMessageName = "google.protobuf.jsonpb.testing.dynamicMessage"
+)
+func init() {
+ // we register the custom type below so that we can use it in Any types
+ proto.RegisterType((*dynamicMessage)(nil), dynamicMessageName)
+}
+
+// dynamicMessage implements protobuf.Message but is not a normal generated message type.
+// It provides implementations of JSONPBMarshaler and JSONPBUnmarshaler for JSON support.
+type dynamicMessage struct {
+ rawJson string `protobuf:"bytes,1,opt,name=rawJson"`
+}
+
+func (m *dynamicMessage) Reset() {
+ m.rawJson = "{}"
+}
+
+func (m *dynamicMessage) String() string {
+ return m.rawJson
+}
+
+func (m *dynamicMessage) ProtoMessage() {
+}
+
+func (m *dynamicMessage) MarshalJSONPB(jm *Marshaler) ([]byte, error) {
+ return []byte(m.rawJson), nil
+}
+
+func (m *dynamicMessage) UnmarshalJSONPB(jum *Unmarshaler, js []byte) error {
+ m.rawJson = string(js)
+ return nil
+} \ No newline at end of file
diff --git a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.pb.go b/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.pb.go
index 96700fe80..ebb180e88 100644
--- a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.pb.go
+++ b/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.pb.go
@@ -10,8 +10,12 @@ It is generated from these files:
It has these top-level messages:
Simple3
+ SimpleSlice3
+ SimpleMap3
+ SimpleNull3
Mappy
Simple
+ NonFinites
Repeats
Widget
Maps
@@ -77,6 +81,54 @@ func (m *Simple3) GetDub() float64 {
return 0
}
+type SimpleSlice3 struct {
+ Slices []string `protobuf:"bytes,1,rep,name=slices" json:"slices,omitempty"`
+}
+
+func (m *SimpleSlice3) Reset() { *m = SimpleSlice3{} }
+func (m *SimpleSlice3) String() string { return proto.CompactTextString(m) }
+func (*SimpleSlice3) ProtoMessage() {}
+func (*SimpleSlice3) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
+
+func (m *SimpleSlice3) GetSlices() []string {
+ if m != nil {
+ return m.Slices
+ }
+ return nil
+}
+
+type SimpleMap3 struct {
+ Stringy map[string]string `protobuf:"bytes,1,rep,name=stringy" json:"stringy,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+}
+
+func (m *SimpleMap3) Reset() { *m = SimpleMap3{} }
+func (m *SimpleMap3) String() string { return proto.CompactTextString(m) }
+func (*SimpleMap3) ProtoMessage() {}
+func (*SimpleMap3) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
+
+func (m *SimpleMap3) GetStringy() map[string]string {
+ if m != nil {
+ return m.Stringy
+ }
+ return nil
+}
+
+type SimpleNull3 struct {
+ Simple *Simple3 `protobuf:"bytes,1,opt,name=simple" json:"simple,omitempty"`
+}
+
+func (m *SimpleNull3) Reset() { *m = SimpleNull3{} }
+func (m *SimpleNull3) String() string { return proto.CompactTextString(m) }
+func (*SimpleNull3) ProtoMessage() {}
+func (*SimpleNull3) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} }
+
+func (m *SimpleNull3) GetSimple() *Simple3 {
+ if m != nil {
+ return m.Simple
+ }
+ return nil
+}
+
type Mappy struct {
Nummy map[int64]int32 `protobuf:"bytes,1,rep,name=nummy" json:"nummy,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
Strry map[string]string `protobuf:"bytes,2,rep,name=strry" json:"strry,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
@@ -93,7 +145,7 @@ type Mappy struct {
func (m *Mappy) Reset() { *m = Mappy{} }
func (m *Mappy) String() string { return proto.CompactTextString(m) }
func (*Mappy) ProtoMessage() {}
-func (*Mappy) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
+func (*Mappy) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} }
func (m *Mappy) GetNummy() map[int64]int32 {
if m != nil {
@@ -167,6 +219,9 @@ func (m *Mappy) GetU64Booly() map[uint64]bool {
func init() {
proto.RegisterType((*Simple3)(nil), "jsonpb.Simple3")
+ proto.RegisterType((*SimpleSlice3)(nil), "jsonpb.SimpleSlice3")
+ proto.RegisterType((*SimpleMap3)(nil), "jsonpb.SimpleMap3")
+ proto.RegisterType((*SimpleNull3)(nil), "jsonpb.SimpleNull3")
proto.RegisterType((*Mappy)(nil), "jsonpb.Mappy")
proto.RegisterEnum("jsonpb.Numeral", Numeral_name, Numeral_value)
}
@@ -174,33 +229,38 @@ func init() {
func init() { proto.RegisterFile("more_test_objects.proto", fileDescriptor0) }
var fileDescriptor0 = []byte{
- // 444 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x94, 0xc1, 0x6b, 0xdb, 0x30,
- 0x14, 0x87, 0xe7, 0xa4, 0x4e, 0xec, 0x17, 0xba, 0x19, 0x31, 0x98, 0x58, 0x2f, 0xa1, 0x30, 0x08,
- 0x83, 0xf9, 0x90, 0x8c, 0xad, 0x6c, 0xa7, 0x74, 0xf4, 0x50, 0x46, 0x1d, 0x70, 0x09, 0x3b, 0x96,
- 0x78, 0x13, 0x65, 0x9e, 0x6d, 0x19, 0xdb, 0x1a, 0xe8, 0x8f, 0x1f, 0x8c, 0x27, 0xcb, 0xb5, 0x6c,
- 0x14, 0xd2, 0x9b, 0xcc, 0xef, 0xfb, 0xf2, 0x9e, 0xf4, 0x1e, 0x81, 0x37, 0x39, 0xaf, 0xd8, 0x43,
- 0xc3, 0xea, 0xe6, 0x81, 0x27, 0x29, 0xfb, 0xd9, 0xd4, 0x61, 0x59, 0xf1, 0x86, 0x93, 0x59, 0x5a,
- 0xf3, 0xa2, 0x4c, 0x2e, 0x2f, 0x60, 0x7e, 0xff, 0x3b, 0x2f, 0x33, 0xb6, 0x21, 0x01, 0x4c, 0x7f,
- 0x89, 0x84, 0x3a, 0x4b, 0x67, 0xe5, 0xc4, 0x78, 0xbc, 0xfc, 0xe7, 0x81, 0x7b, 0x77, 0x28, 0x4b,
- 0x49, 0x42, 0x70, 0x0b, 0x91, 0xe7, 0x92, 0x3a, 0xcb, 0xe9, 0x6a, 0xb1, 0xa6, 0x61, 0xab, 0x87,
- 0x2a, 0x0d, 0x23, 0x8c, 0x6e, 0x8a, 0xa6, 0x92, 0x71, 0x8b, 0x21, 0x5f, 0x37, 0x55, 0x25, 0xe9,
- 0xc4, 0xc6, 0xdf, 0x63, 0xa4, 0x79, 0x85, 0x21, 0xcf, 0x93, 0x34, 0x95, 0x74, 0x6a, 0xe3, 0x77,
- 0x18, 0x69, 0x5e, 0x61, 0xc8, 0x27, 0xe2, 0xf1, 0x51, 0xd2, 0x33, 0x1b, 0x7f, 0x8d, 0x91, 0xe6,
- 0x15, 0xa6, 0x78, 0xce, 0x33, 0x49, 0x5d, 0x2b, 0x8f, 0x51, 0xc7, 0xe3, 0x19, 0x79, 0x56, 0x88,
- 0x5c, 0xd2, 0x99, 0x8d, 0xbf, 0xc1, 0x48, 0xf3, 0x0a, 0x23, 0x9f, 0xc1, 0xab, 0x37, 0xeb, 0xb6,
- 0xc4, 0x5c, 0x29, 0x17, 0xa3, 0x2b, 0xeb, 0xb4, 0xb5, 0x9e, 0x60, 0x25, 0x7e, 0xfa, 0xd8, 0x8a,
- 0x9e, 0x55, 0xd4, 0x69, 0x27, 0xea, 0x4f, 0x14, 0x45, 0x57, 0xd1, 0xb7, 0x89, 0xfb, 0x61, 0x45,
- 0x61, 0x54, 0x14, 0x5d, 0x45, 0xb0, 0x8a, 0xc3, 0x8a, 0x1d, 0xfc, 0xf6, 0x0a, 0xa0, 0x1f, 0x34,
- 0x6e, 0xcb, 0x1f, 0x26, 0xd5, 0xb6, 0x4c, 0x63, 0x3c, 0x92, 0xd7, 0xe0, 0xfe, 0x3d, 0x64, 0x82,
- 0xd1, 0xc9, 0xd2, 0x59, 0xb9, 0x71, 0xfb, 0xf1, 0x65, 0x72, 0xe5, 0xa0, 0xd9, 0x8f, 0xdc, 0x34,
- 0x7d, 0x8b, 0xe9, 0x9b, 0xe6, 0x2d, 0x40, 0x3f, 0x7c, 0xd3, 0x74, 0x5b, 0xf3, 0x9d, 0x69, 0x2e,
- 0xd6, 0xaf, 0xba, 0x9b, 0xe8, 0x9d, 0x1e, 0x35, 0xd1, 0xef, 0xc5, 0xa9, 0xf6, 0xfd, 0xb1, 0xf9,
- 0xf4, 0x20, 0xa6, 0xe9, 0x59, 0x4c, 0x6f, 0xd4, 0x7e, 0xbf, 0x2b, 0x96, 0x8b, 0x0f, 0xda, 0x7f,
- 0xd9, 0xb7, 0x1f, 0x89, 0x9c, 0x55, 0x87, 0xcc, 0xfc, 0xa9, 0xaf, 0x70, 0x3e, 0xd8, 0x21, 0xcb,
- 0x63, 0x1c, 0xef, 0x03, 0x65, 0x73, 0xaa, 0xa7, 0xae, 0x3f, 0x96, 0xf7, 0xc7, 0x2a, 0x9f, 0x3f,
- 0x47, 0x3e, 0x56, 0xf9, 0xec, 0x84, 0xfc, 0xfe, 0x03, 0xcc, 0xf5, 0x4b, 0x90, 0x05, 0xcc, 0xf7,
- 0xd1, 0xf7, 0x68, 0xf7, 0x23, 0x0a, 0x5e, 0x10, 0x80, 0xd9, 0x36, 0xde, 0x5e, 0xdf, 0x7e, 0x0b,
- 0x1c, 0xe2, 0x83, 0x1b, 0xef, 0xee, 0xb6, 0x51, 0x30, 0x49, 0x66, 0xea, 0xaf, 0x6d, 0xf3, 0x3f,
- 0x00, 0x00, 0xff, 0xff, 0xa2, 0x4b, 0xe1, 0x77, 0xf5, 0x04, 0x00, 0x00,
+ // 526 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0xdd, 0x6b, 0xdb, 0x3c,
+ 0x14, 0x87, 0x5f, 0x27, 0xf5, 0xd7, 0x49, 0xfb, 0x2e, 0x88, 0xb1, 0x99, 0xf4, 0x62, 0xc5, 0xb0,
+ 0xad, 0x0c, 0xe6, 0x8b, 0x78, 0x74, 0x5d, 0x77, 0x95, 0x8e, 0x5e, 0x94, 0x11, 0x07, 0x1c, 0xc2,
+ 0x2e, 0x4b, 0xdc, 0x99, 0x90, 0xcc, 0x5f, 0xd8, 0xd6, 0xc0, 0xd7, 0xfb, 0xbb, 0x07, 0xe3, 0x48,
+ 0x72, 0x2d, 0x07, 0x85, 0x6c, 0x77, 0x52, 0x7e, 0xcf, 0xe3, 0x73, 0x24, 0x1d, 0x02, 0x2f, 0xd3,
+ 0xbc, 0x8c, 0x1f, 0xea, 0xb8, 0xaa, 0x1f, 0xf2, 0x68, 0x17, 0x3f, 0xd6, 0x95, 0x57, 0x94, 0x79,
+ 0x9d, 0x13, 0x63, 0x57, 0xe5, 0x59, 0x11, 0xb9, 0xe7, 0x60, 0x2e, 0xb7, 0x69, 0x91, 0xc4, 0x3e,
+ 0x19, 0xc3, 0xf0, 0x3b, 0x8d, 0x1c, 0xed, 0x42, 0xbb, 0xd4, 0x42, 0x5c, 0xba, 0x6f, 0xe0, 0x94,
+ 0x87, 0xcb, 0x64, 0xfb, 0x18, 0xfb, 0xe4, 0x05, 0x18, 0x15, 0xae, 0x2a, 0x47, 0xbb, 0x18, 0x5e,
+ 0xda, 0xa1, 0xd8, 0xb9, 0xbf, 0x34, 0x00, 0x0e, 0xce, 0xd7, 0x85, 0x4f, 0x3e, 0x81, 0x59, 0xd5,
+ 0xe5, 0x36, 0xdb, 0x34, 0x8c, 0x1b, 0x4d, 0x5f, 0x79, 0xbc, 0x9a, 0xd7, 0x41, 0xde, 0x92, 0x13,
+ 0x77, 0x59, 0x5d, 0x36, 0x61, 0xcb, 0x4f, 0x6e, 0xe0, 0x54, 0x0e, 0xb0, 0xa7, 0x1f, 0x71, 0xc3,
+ 0x7a, 0xb2, 0x43, 0x5c, 0x92, 0xe7, 0xa0, 0xff, 0x5c, 0x27, 0x34, 0x76, 0x06, 0xec, 0x37, 0xbe,
+ 0xb9, 0x19, 0x5c, 0x6b, 0xee, 0x15, 0x8c, 0xf8, 0xf7, 0x03, 0x9a, 0x24, 0x3e, 0x79, 0x0b, 0x46,
+ 0xc5, 0xb6, 0xcc, 0x1e, 0x4d, 0x9f, 0xf5, 0x9b, 0xf0, 0x43, 0x11, 0xbb, 0xbf, 0x2d, 0xd0, 0xe7,
+ 0xeb, 0xa2, 0x68, 0x88, 0x07, 0x7a, 0x46, 0xd3, 0xb4, 0x6d, 0xdb, 0x69, 0x0d, 0x96, 0x7a, 0x01,
+ 0x46, 0xbc, 0x5f, 0x8e, 0x21, 0x5f, 0xd5, 0x65, 0xd9, 0x38, 0x03, 0x15, 0xbf, 0xc4, 0x48, 0xf0,
+ 0x0c, 0x43, 0x3e, 0x8f, 0x76, 0xbb, 0xc6, 0x19, 0xaa, 0xf8, 0x05, 0x46, 0x82, 0x67, 0x18, 0xf2,
+ 0x11, 0xdd, 0x6c, 0x1a, 0xe7, 0x44, 0xc5, 0xdf, 0x62, 0x24, 0x78, 0x86, 0x31, 0x3e, 0xcf, 0x93,
+ 0xc6, 0xd1, 0x95, 0x3c, 0x46, 0x2d, 0x8f, 0x6b, 0xe4, 0xe3, 0x8c, 0xa6, 0x8d, 0x63, 0xa8, 0xf8,
+ 0x3b, 0x8c, 0x04, 0xcf, 0x30, 0xf2, 0x11, 0xac, 0xca, 0x9f, 0xf2, 0x12, 0x26, 0x53, 0xce, 0xf7,
+ 0x8e, 0x2c, 0x52, 0x6e, 0x3d, 0xc1, 0x4c, 0xbc, 0xfa, 0xc0, 0x45, 0x4b, 0x29, 0x8a, 0xb4, 0x15,
+ 0xc5, 0x16, 0x45, 0xda, 0x56, 0xb4, 0x55, 0xe2, 0xaa, 0x5f, 0x91, 0x4a, 0x15, 0x69, 0x5b, 0x11,
+ 0x94, 0x62, 0xbf, 0x62, 0x0b, 0x4f, 0xae, 0x01, 0xba, 0x87, 0x96, 0xe7, 0x6f, 0xa8, 0x98, 0x3f,
+ 0x5d, 0x9a, 0x3f, 0x34, 0xbb, 0x27, 0xff, 0x97, 0xc9, 0x9d, 0xdc, 0x03, 0x74, 0x8f, 0x2f, 0x9b,
+ 0x3a, 0x37, 0x5f, 0xcb, 0xa6, 0x62, 0x92, 0xfb, 0x4d, 0x74, 0x73, 0x71, 0xac, 0x7d, 0x7b, 0xdf,
+ 0x7c, 0xba, 0x10, 0xd9, 0xb4, 0x14, 0xa6, 0xb5, 0xd7, 0x7e, 0x37, 0x2b, 0x8a, 0x83, 0xf7, 0xda,
+ 0xff, 0xbf, 0x6b, 0x3f, 0xa0, 0x69, 0x5c, 0xae, 0x13, 0xf9, 0x53, 0x9f, 0xe1, 0xac, 0x37, 0x43,
+ 0x8a, 0xcb, 0x38, 0xdc, 0x07, 0xca, 0xf2, 0xab, 0x1e, 0x3b, 0xfe, 0xbe, 0xbc, 0x3a, 0x54, 0xf9,
+ 0xec, 0x6f, 0xe4, 0x43, 0x95, 0x4f, 0x8e, 0xc8, 0xef, 0xde, 0x83, 0x29, 0x6e, 0x82, 0x8c, 0xc0,
+ 0x5c, 0x05, 0x5f, 0x83, 0xc5, 0xb7, 0x60, 0xfc, 0x1f, 0x01, 0x30, 0x66, 0xe1, 0xec, 0xf6, 0xfe,
+ 0xcb, 0x58, 0x23, 0x36, 0xe8, 0xe1, 0x62, 0x3e, 0x0b, 0xc6, 0x83, 0xc8, 0x60, 0x7f, 0xe0, 0xfe,
+ 0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xdc, 0x84, 0x34, 0xaf, 0xdb, 0x05, 0x00, 0x00,
}
diff --git a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.proto b/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.proto
index 43b440e2d..d254fa5fa 100644
--- a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.proto
+++ b/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.proto
@@ -37,6 +37,18 @@ message Simple3 {
double dub = 1;
}
+message SimpleSlice3 {
+ repeated string slices = 1;
+}
+
+message SimpleMap3 {
+ map<string,string> stringy = 1;
+}
+
+message SimpleNull3 {
+ Simple3 simple = 1;
+}
+
enum Numeral {
UNKNOWN = 0;
ARABIC = 1;
diff --git a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.pb.go b/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.pb.go
index a95f94702..d413d740d 100644
--- a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.pb.go
+++ b/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.pb.go
@@ -52,7 +52,7 @@ func (x *Widget_Color) UnmarshalJSON(data []byte) error {
*x = Widget_Color(value)
return nil
}
-func (Widget_Color) EnumDescriptor() ([]byte, []int) { return fileDescriptor1, []int{2, 0} }
+func (Widget_Color) EnumDescriptor() ([]byte, []int) { return fileDescriptor1, []int{3, 0} }
// Test message for holding primitive types.
type Simple struct {
@@ -152,6 +152,64 @@ func (m *Simple) GetOBytes() []byte {
return nil
}
+// Test message for holding special non-finites primitives.
+type NonFinites struct {
+ FNan *float32 `protobuf:"fixed32,1,opt,name=f_nan,json=fNan" json:"f_nan,omitempty"`
+ FPinf *float32 `protobuf:"fixed32,2,opt,name=f_pinf,json=fPinf" json:"f_pinf,omitempty"`
+ FNinf *float32 `protobuf:"fixed32,3,opt,name=f_ninf,json=fNinf" json:"f_ninf,omitempty"`
+ DNan *float64 `protobuf:"fixed64,4,opt,name=d_nan,json=dNan" json:"d_nan,omitempty"`
+ DPinf *float64 `protobuf:"fixed64,5,opt,name=d_pinf,json=dPinf" json:"d_pinf,omitempty"`
+ DNinf *float64 `protobuf:"fixed64,6,opt,name=d_ninf,json=dNinf" json:"d_ninf,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *NonFinites) Reset() { *m = NonFinites{} }
+func (m *NonFinites) String() string { return proto.CompactTextString(m) }
+func (*NonFinites) ProtoMessage() {}
+func (*NonFinites) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{1} }
+
+func (m *NonFinites) GetFNan() float32 {
+ if m != nil && m.FNan != nil {
+ return *m.FNan
+ }
+ return 0
+}
+
+func (m *NonFinites) GetFPinf() float32 {
+ if m != nil && m.FPinf != nil {
+ return *m.FPinf
+ }
+ return 0
+}
+
+func (m *NonFinites) GetFNinf() float32 {
+ if m != nil && m.FNinf != nil {
+ return *m.FNinf
+ }
+ return 0
+}
+
+func (m *NonFinites) GetDNan() float64 {
+ if m != nil && m.DNan != nil {
+ return *m.DNan
+ }
+ return 0
+}
+
+func (m *NonFinites) GetDPinf() float64 {
+ if m != nil && m.DPinf != nil {
+ return *m.DPinf
+ }
+ return 0
+}
+
+func (m *NonFinites) GetDNinf() float64 {
+ if m != nil && m.DNinf != nil {
+ return *m.DNinf
+ }
+ return 0
+}
+
// Test message for holding repeated primitives.
type Repeats struct {
RBool []bool `protobuf:"varint,1,rep,name=r_bool,json=rBool" json:"r_bool,omitempty"`
@@ -171,7 +229,7 @@ type Repeats struct {
func (m *Repeats) Reset() { *m = Repeats{} }
func (m *Repeats) String() string { return proto.CompactTextString(m) }
func (*Repeats) ProtoMessage() {}
-func (*Repeats) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{1} }
+func (*Repeats) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{2} }
func (m *Repeats) GetRBool() []bool {
if m != nil {
@@ -264,7 +322,7 @@ type Widget struct {
func (m *Widget) Reset() { *m = Widget{} }
func (m *Widget) String() string { return proto.CompactTextString(m) }
func (*Widget) ProtoMessage() {}
-func (*Widget) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{2} }
+func (*Widget) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{3} }
func (m *Widget) GetColor() Widget_Color {
if m != nil && m.Color != nil {
@@ -317,7 +375,7 @@ type Maps struct {
func (m *Maps) Reset() { *m = Maps{} }
func (m *Maps) String() string { return proto.CompactTextString(m) }
func (*Maps) ProtoMessage() {}
-func (*Maps) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{3} }
+func (*Maps) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{4} }
func (m *Maps) GetMInt64Str() map[int64]string {
if m != nil {
@@ -346,7 +404,7 @@ type MsgWithOneof struct {
func (m *MsgWithOneof) Reset() { *m = MsgWithOneof{} }
func (m *MsgWithOneof) String() string { return proto.CompactTextString(m) }
func (*MsgWithOneof) ProtoMessage() {}
-func (*MsgWithOneof) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{4} }
+func (*MsgWithOneof) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{5} }
type isMsgWithOneof_Union interface {
isMsgWithOneof_Union()
@@ -509,7 +567,7 @@ type Real struct {
func (m *Real) Reset() { *m = Real{} }
func (m *Real) String() string { return proto.CompactTextString(m) }
func (*Real) ProtoMessage() {}
-func (*Real) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{5} }
+func (*Real) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{6} }
var extRange_Real = []proto.ExtensionRange{
{100, 536870911},
@@ -535,7 +593,7 @@ type Complex struct {
func (m *Complex) Reset() { *m = Complex{} }
func (m *Complex) String() string { return proto.CompactTextString(m) }
func (*Complex) ProtoMessage() {}
-func (*Complex) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{6} }
+func (*Complex) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{7} }
var extRange_Complex = []proto.ExtensionRange{
{100, 536870911},
@@ -583,7 +641,7 @@ type KnownTypes struct {
func (m *KnownTypes) Reset() { *m = KnownTypes{} }
func (m *KnownTypes) String() string { return proto.CompactTextString(m) }
func (*KnownTypes) ProtoMessage() {}
-func (*KnownTypes) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{7} }
+func (*KnownTypes) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{8} }
func (m *KnownTypes) GetAn() *google_protobuf.Any {
if m != nil {
@@ -701,6 +759,7 @@ var E_Name = &proto.ExtensionDesc{
func init() {
proto.RegisterType((*Simple)(nil), "jsonpb.Simple")
+ proto.RegisterType((*NonFinites)(nil), "jsonpb.NonFinites")
proto.RegisterType((*Repeats)(nil), "jsonpb.Repeats")
proto.RegisterType((*Widget)(nil), "jsonpb.Widget")
proto.RegisterType((*Maps)(nil), "jsonpb.Maps")
@@ -716,73 +775,78 @@ func init() {
func init() { proto.RegisterFile("test_objects.proto", fileDescriptor1) }
var fileDescriptor1 = []byte{
- // 1085 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x95, 0xd1, 0x72, 0xdb, 0x44,
- 0x17, 0xc7, 0x2b, 0xc9, 0x92, 0xed, 0x75, 0x9a, 0xfa, 0xdb, 0x49, 0x5b, 0xc5, 0x5f, 0x00, 0x8d,
- 0x29, 0x45, 0x14, 0xea, 0x0e, 0x8a, 0xc7, 0xc3, 0x14, 0x6e, 0x92, 0xc6, 0x50, 0x86, 0xa6, 0xcc,
- 0x6c, 0x1a, 0x7a, 0xe9, 0x91, 0xe3, 0x8d, 0xab, 0x22, 0x6b, 0x3d, 0xbb, 0xab, 0xa4, 0x1e, 0xb8,
- 0xc8, 0x35, 0xd7, 0xbc, 0x02, 0x3c, 0x02, 0x17, 0x3c, 0x1d, 0x73, 0xce, 0x4a, 0x56, 0x62, 0xc7,
- 0x57, 0xf1, 0xd1, 0xf9, 0x9f, 0x7f, 0x76, 0x7f, 0x7b, 0x76, 0x0f, 0xa1, 0x9a, 0x2b, 0x3d, 0x12,
- 0xe3, 0xf7, 0xfc, 0x4c, 0xab, 0xde, 0x5c, 0x0a, 0x2d, 0xa8, 0xf7, 0x5e, 0x89, 0x6c, 0x3e, 0xee,
- 0xec, 0x4e, 0x85, 0x98, 0xa6, 0xfc, 0x19, 0x7e, 0x1d, 0xe7, 0xe7, 0xcf, 0xe2, 0x6c, 0x61, 0x24,
- 0x9d, 0x8f, 0x57, 0x53, 0x93, 0x5c, 0xc6, 0x3a, 0x11, 0x59, 0x91, 0xdf, 0x5b, 0xcd, 0x2b, 0x2d,
- 0xf3, 0x33, 0x5d, 0x64, 0x3f, 0x59, 0xcd, 0xea, 0x64, 0xc6, 0x95, 0x8e, 0x67, 0xf3, 0x4d, 0xf6,
- 0x97, 0x32, 0x9e, 0xcf, 0xb9, 0x2c, 0x56, 0xd8, 0xfd, 0xcb, 0x26, 0xde, 0x49, 0x32, 0x9b, 0xa7,
- 0x9c, 0xde, 0x27, 0x9e, 0x18, 0x8d, 0x85, 0x48, 0x7d, 0x2b, 0xb0, 0xc2, 0x06, 0x73, 0xc5, 0xa1,
- 0x10, 0x29, 0x7d, 0x48, 0xea, 0x62, 0x94, 0x64, 0x7a, 0x3f, 0xf2, 0xed, 0xc0, 0x0a, 0x5d, 0xe6,
- 0x89, 0x1f, 0x21, 0x5a, 0x26, 0x06, 0x7d, 0xdf, 0x09, 0xac, 0xd0, 0x31, 0x89, 0x41, 0x9f, 0xee,
- 0x92, 0x86, 0x18, 0xe5, 0xa6, 0xa4, 0x16, 0x58, 0xe1, 0x5d, 0x56, 0x17, 0xa7, 0x18, 0x56, 0xa9,
- 0x41, 0xdf, 0x77, 0x03, 0x2b, 0xac, 0x15, 0xa9, 0xb2, 0x4a, 0x99, 0x2a, 0x2f, 0xb0, 0xc2, 0xff,
- 0xb1, 0xba, 0x38, 0xb9, 0x56, 0xa5, 0x4c, 0x55, 0x3d, 0xb0, 0x42, 0x5a, 0xa4, 0x06, 0x7d, 0xb3,
- 0x88, 0xf3, 0x54, 0xc4, 0xda, 0x6f, 0x04, 0x56, 0x68, 0x33, 0x4f, 0x7c, 0x0f, 0x91, 0xa9, 0x99,
- 0x88, 0x7c, 0x9c, 0x72, 0xbf, 0x19, 0x58, 0xa1, 0xc5, 0xea, 0xe2, 0x08, 0xc3, 0xc2, 0x4e, 0xcb,
- 0x24, 0x9b, 0xfa, 0x24, 0xb0, 0xc2, 0x26, 0xd8, 0x61, 0x68, 0xec, 0xc6, 0x0b, 0xcd, 0x95, 0xdf,
- 0x0a, 0xac, 0x70, 0x8b, 0x79, 0xe2, 0x10, 0xa2, 0xee, 0xdf, 0x36, 0xa9, 0x33, 0x3e, 0xe7, 0xb1,
- 0x56, 0x00, 0x4a, 0x96, 0xa0, 0x1c, 0x00, 0x25, 0x4b, 0x50, 0x72, 0x09, 0xca, 0x01, 0x50, 0x72,
- 0x09, 0x4a, 0x2e, 0x41, 0x39, 0x00, 0x4a, 0x2e, 0x41, 0xc9, 0x0a, 0x94, 0x03, 0xa0, 0x64, 0x05,
- 0x4a, 0x56, 0xa0, 0x1c, 0x00, 0x25, 0x2b, 0x50, 0xb2, 0x02, 0xe5, 0x00, 0x28, 0x79, 0x72, 0xad,
- 0x6a, 0x09, 0xca, 0x01, 0x50, 0xb2, 0x02, 0x25, 0x97, 0xa0, 0x1c, 0x00, 0x25, 0x97, 0xa0, 0x64,
- 0x05, 0xca, 0x01, 0x50, 0xb2, 0x02, 0x25, 0x2b, 0x50, 0x0e, 0x80, 0x92, 0x15, 0x28, 0xb9, 0x04,
- 0xe5, 0x00, 0x28, 0x69, 0x40, 0xfd, 0x63, 0x13, 0xef, 0x6d, 0x32, 0x99, 0x72, 0x4d, 0x9f, 0x10,
- 0xf7, 0x4c, 0xa4, 0x42, 0x62, 0x3f, 0x6d, 0x47, 0x3b, 0x3d, 0x73, 0x1b, 0x7a, 0x26, 0xdd, 0x7b,
- 0x01, 0x39, 0x66, 0x24, 0xf4, 0x29, 0xf8, 0x19, 0x35, 0xc0, 0xdb, 0xa4, 0xf6, 0x24, 0xfe, 0xa5,
- 0x8f, 0x89, 0xa7, 0xb0, 0x6b, 0xf1, 0x00, 0x5b, 0xd1, 0x76, 0xa9, 0x36, 0xbd, 0xcc, 0x8a, 0x2c,
- 0xfd, 0xc2, 0x00, 0x41, 0x25, 0xac, 0x73, 0x5d, 0x09, 0x80, 0x0a, 0x69, 0x5d, 0x9a, 0x03, 0xf6,
- 0x77, 0xd0, 0xf3, 0x5e, 0xa9, 0x2c, 0xce, 0x9d, 0x95, 0x79, 0xfa, 0x15, 0x69, 0xca, 0x51, 0x29,
- 0xbe, 0x8f, 0xb6, 0x6b, 0xe2, 0x86, 0x2c, 0x7e, 0x75, 0x3f, 0x23, 0xae, 0x59, 0x74, 0x9d, 0x38,
- 0x6c, 0x78, 0xd4, 0xbe, 0x43, 0x9b, 0xc4, 0xfd, 0x81, 0x0d, 0x87, 0xaf, 0xdb, 0x16, 0x6d, 0x90,
- 0xda, 0xe1, 0xab, 0xd3, 0x61, 0xdb, 0xee, 0xfe, 0x69, 0x93, 0xda, 0x71, 0x3c, 0x57, 0xf4, 0x5b,
- 0xd2, 0x9a, 0x99, 0x76, 0x01, 0xf6, 0xd8, 0x63, 0xad, 0xe8, 0xff, 0xa5, 0x3f, 0x48, 0x7a, 0xc7,
- 0xd8, 0x3f, 0x27, 0x5a, 0x0e, 0x33, 0x2d, 0x17, 0xac, 0x39, 0x2b, 0x63, 0x7a, 0x40, 0xee, 0xce,
- 0xb0, 0x37, 0xcb, 0x5d, 0xdb, 0x58, 0xfe, 0xd1, 0xcd, 0x72, 0xe8, 0x57, 0xb3, 0x6d, 0x63, 0xd0,
- 0x9a, 0x55, 0x5f, 0x3a, 0xdf, 0x91, 0xed, 0x9b, 0xfe, 0xb4, 0x4d, 0x9c, 0x5f, 0xf9, 0x02, 0x8f,
- 0xd1, 0x61, 0xf0, 0x93, 0xee, 0x10, 0xf7, 0x22, 0x4e, 0x73, 0x8e, 0x4f, 0x42, 0x93, 0x99, 0xe0,
- 0xb9, 0xfd, 0x8d, 0xd5, 0x79, 0x4d, 0xda, 0xab, 0xf6, 0xd7, 0xeb, 0x1b, 0xa6, 0xfe, 0xd1, 0xf5,
- 0xfa, 0xf5, 0x43, 0xa9, 0xfc, 0xba, 0x7f, 0x58, 0x64, 0xeb, 0x58, 0x4d, 0xdf, 0x26, 0xfa, 0xdd,
- 0xcf, 0x19, 0x17, 0xe7, 0xf4, 0x01, 0x71, 0x75, 0xa2, 0x53, 0x8e, 0x76, 0xcd, 0x97, 0x77, 0x98,
- 0x09, 0xa9, 0x4f, 0x3c, 0x15, 0xa7, 0xb1, 0x5c, 0xa0, 0xa7, 0xf3, 0xf2, 0x0e, 0x2b, 0x62, 0xda,
- 0x21, 0xf5, 0x17, 0x22, 0x87, 0x95, 0xe0, 0x43, 0x05, 0x35, 0xe5, 0x07, 0xfa, 0x29, 0xd9, 0x7a,
- 0x27, 0x66, 0x7c, 0x14, 0x4f, 0x26, 0x92, 0x2b, 0x85, 0xef, 0x15, 0x08, 0x5a, 0xf0, 0xf5, 0xc0,
- 0x7c, 0x3c, 0xac, 0x13, 0x37, 0xcf, 0x12, 0x91, 0x75, 0x1f, 0x93, 0x1a, 0xe3, 0x71, 0x5a, 0x6d,
- 0xdf, 0xc2, 0x97, 0xc5, 0x04, 0x4f, 0x1a, 0x8d, 0x49, 0xfb, 0xea, 0xea, 0xea, 0xca, 0xee, 0x5e,
- 0xc2, 0x7f, 0x84, 0x9d, 0x7c, 0xa0, 0x7b, 0xa4, 0x99, 0xcc, 0xe2, 0x69, 0x92, 0xc1, 0xca, 0x8c,
- 0xbc, 0xfa, 0x50, 0x95, 0x44, 0x47, 0x64, 0x5b, 0xf2, 0x38, 0x1d, 0xf1, 0x0f, 0x9a, 0x67, 0x2a,
- 0x11, 0x19, 0xdd, 0xaa, 0x5a, 0x2a, 0x4e, 0xfd, 0xdf, 0x6e, 0xf6, 0x64, 0x61, 0xcf, 0xee, 0x42,
- 0xd1, 0xb0, 0xac, 0xe9, 0xfe, 0xeb, 0x12, 0xf2, 0x53, 0x26, 0x2e, 0xb3, 0x37, 0x8b, 0x39, 0x57,
- 0xf4, 0x11, 0xb1, 0xe3, 0xcc, 0xdf, 0xc6, 0xd2, 0x9d, 0x9e, 0x19, 0x05, 0xbd, 0x72, 0x14, 0xf4,
- 0x0e, 0xb2, 0x05, 0xb3, 0xe3, 0x8c, 0x7e, 0x49, 0x9c, 0x49, 0x6e, 0x6e, 0x69, 0x2b, 0xda, 0x5d,
- 0x93, 0x1d, 0x15, 0x03, 0x89, 0x81, 0x8a, 0x7e, 0x4e, 0x6c, 0xa5, 0xfd, 0x2d, 0xd4, 0x3e, 0x5c,
- 0xd3, 0x9e, 0xe0, 0x70, 0x62, 0xb6, 0x82, 0xdb, 0x6f, 0x6b, 0x55, 0x9c, 0x6f, 0x67, 0x4d, 0xf8,
- 0xa6, 0x9c, 0x53, 0xcc, 0xd6, 0x0a, 0xb4, 0xe9, 0x85, 0x7f, 0x6f, 0x83, 0xf6, 0x55, 0xa2, 0xf4,
- 0x2f, 0x40, 0x98, 0xd9, 0xe9, 0x05, 0x0d, 0x89, 0x73, 0x11, 0xa7, 0x7e, 0x1b, 0xc5, 0x0f, 0xd6,
- 0xc4, 0x46, 0x08, 0x12, 0xda, 0x23, 0xce, 0x64, 0x9c, 0xe2, 0x99, 0xb7, 0xa2, 0xbd, 0xf5, 0x7d,
- 0xe1, 0x23, 0x57, 0xe8, 0x27, 0xe3, 0x94, 0x3e, 0x25, 0xce, 0x79, 0xaa, 0xb1, 0x05, 0xe0, 0xc2,
- 0xad, 0xea, 0xf1, 0xb9, 0x2c, 0xe4, 0xe7, 0xa9, 0x06, 0x79, 0x52, 0x8c, 0xb1, 0xdb, 0xe4, 0x78,
- 0x85, 0x0a, 0x79, 0x32, 0xe8, 0xc3, 0x6a, 0xf2, 0x41, 0x1f, 0x47, 0xdb, 0x6d, 0xab, 0x39, 0xbd,
- 0xae, 0xcf, 0x07, 0x7d, 0xb4, 0xdf, 0x8f, 0x70, 0xde, 0x6d, 0xb0, 0xdf, 0x8f, 0x4a, 0xfb, 0xfd,
- 0x08, 0xed, 0xf7, 0x23, 0x1c, 0x82, 0x9b, 0xec, 0x97, 0xfa, 0x1c, 0xf5, 0x35, 0x1c, 0x61, 0xcd,
- 0x0d, 0xd0, 0xe1, 0x0e, 0x1b, 0x39, 0xea, 0xc0, 0x1f, 0x5e, 0x23, 0xb2, 0xc1, 0xdf, 0x8c, 0x85,
- 0xc2, 0x5f, 0x69, 0x49, 0xbf, 0x26, 0x6e, 0x35, 0x47, 0x6f, 0xdb, 0x00, 0x8e, 0x0b, 0x53, 0x60,
- 0x94, 0xcf, 0x03, 0x52, 0xcb, 0xe2, 0x19, 0x5f, 0x69, 0xfc, 0xdf, 0xf1, 0x85, 0xc1, 0xcc, 0x7f,
- 0x01, 0x00, 0x00, 0xff, 0xff, 0x46, 0x96, 0x41, 0x24, 0x64, 0x09, 0x00, 0x00,
+ // 1160 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x95, 0x41, 0x73, 0xdb, 0x44,
+ 0x14, 0xc7, 0x23, 0xc9, 0x92, 0xed, 0x75, 0x92, 0x9a, 0x6d, 0xda, 0x2a, 0x26, 0x80, 0xc6, 0x94,
+ 0x22, 0x0a, 0x75, 0x07, 0xc7, 0xe3, 0x61, 0x0a, 0x97, 0xa4, 0x71, 0x29, 0x43, 0x13, 0x98, 0x4d,
+ 0x43, 0x8f, 0x1e, 0x39, 0x5a, 0xbb, 0x2a, 0xf2, 0xae, 0x67, 0x77, 0x95, 0xd4, 0x03, 0x87, 0x9c,
+ 0x39, 0x32, 0x7c, 0x05, 0xf8, 0x08, 0x1c, 0xf8, 0x74, 0xcc, 0xdb, 0x95, 0xac, 0xc4, 0x8e, 0x4f,
+ 0xf1, 0x7b, 0xef, 0xff, 0xfe, 0x59, 0xed, 0x6f, 0x77, 0x1f, 0xc2, 0x8a, 0x4a, 0x35, 0xe4, 0xa3,
+ 0x77, 0xf4, 0x5c, 0xc9, 0xce, 0x4c, 0x70, 0xc5, 0xb1, 0xf7, 0x4e, 0x72, 0x36, 0x1b, 0xb5, 0x76,
+ 0x27, 0x9c, 0x4f, 0x52, 0xfa, 0x54, 0x67, 0x47, 0xd9, 0xf8, 0x69, 0xc4, 0xe6, 0x46, 0xd2, 0xfa,
+ 0x78, 0xb9, 0x14, 0x67, 0x22, 0x52, 0x09, 0x67, 0x79, 0x7d, 0x6f, 0xb9, 0x2e, 0x95, 0xc8, 0xce,
+ 0x55, 0x5e, 0xfd, 0x64, 0xb9, 0xaa, 0x92, 0x29, 0x95, 0x2a, 0x9a, 0xce, 0xd6, 0xd9, 0x5f, 0x8a,
+ 0x68, 0x36, 0xa3, 0x22, 0x5f, 0x61, 0xfb, 0x6f, 0x1b, 0x79, 0xa7, 0xc9, 0x74, 0x96, 0x52, 0x7c,
+ 0x0f, 0x79, 0x7c, 0x38, 0xe2, 0x3c, 0xf5, 0xad, 0xc0, 0x0a, 0x6b, 0xc4, 0xe5, 0x87, 0x9c, 0xa7,
+ 0xf8, 0x01, 0xaa, 0xf2, 0x61, 0xc2, 0xd4, 0x7e, 0xd7, 0xb7, 0x03, 0x2b, 0x74, 0x89, 0xc7, 0x7f,
+ 0x80, 0x68, 0x51, 0xe8, 0xf7, 0x7c, 0x27, 0xb0, 0x42, 0xc7, 0x14, 0xfa, 0x3d, 0xbc, 0x8b, 0x6a,
+ 0x7c, 0x98, 0x99, 0x96, 0x4a, 0x60, 0x85, 0x5b, 0xa4, 0xca, 0xcf, 0x74, 0x58, 0x96, 0xfa, 0x3d,
+ 0xdf, 0x0d, 0xac, 0xb0, 0x92, 0x97, 0x8a, 0x2e, 0x69, 0xba, 0xbc, 0xc0, 0x0a, 0x3f, 0x20, 0x55,
+ 0x7e, 0x7a, 0xad, 0x4b, 0x9a, 0xae, 0x6a, 0x60, 0x85, 0x38, 0x2f, 0xf5, 0x7b, 0x66, 0x11, 0xe3,
+ 0x94, 0x47, 0xca, 0xaf, 0x05, 0x56, 0x68, 0x13, 0x8f, 0xbf, 0x80, 0xc8, 0xf4, 0xc4, 0x3c, 0x1b,
+ 0xa5, 0xd4, 0xaf, 0x07, 0x56, 0x68, 0x91, 0x2a, 0x3f, 0xd2, 0x61, 0x6e, 0xa7, 0x44, 0xc2, 0x26,
+ 0x3e, 0x0a, 0xac, 0xb0, 0x0e, 0x76, 0x3a, 0x34, 0x76, 0xa3, 0xb9, 0xa2, 0xd2, 0x6f, 0x04, 0x56,
+ 0xb8, 0x49, 0x3c, 0x7e, 0x08, 0x51, 0xfb, 0x4f, 0x0b, 0xa1, 0x13, 0xce, 0x5e, 0x24, 0x2c, 0x51,
+ 0x54, 0xe2, 0xbb, 0xc8, 0x1d, 0x0f, 0x59, 0xc4, 0xf4, 0x56, 0xd9, 0xa4, 0x32, 0x3e, 0x89, 0x18,
+ 0x6c, 0xe0, 0x78, 0x38, 0x4b, 0xd8, 0x58, 0x6f, 0x94, 0x4d, 0xdc, 0xf1, 0xcf, 0x09, 0x1b, 0x9b,
+ 0x34, 0x83, 0xb4, 0x93, 0xa7, 0x4f, 0x20, 0x7d, 0x17, 0xb9, 0xb1, 0xb6, 0xa8, 0xe8, 0xd5, 0x55,
+ 0xe2, 0xdc, 0x22, 0x36, 0x16, 0xae, 0xce, 0xba, 0x71, 0x61, 0x11, 0x1b, 0x0b, 0x2f, 0x4f, 0x83,
+ 0x45, 0xfb, 0x1f, 0x1b, 0x55, 0x09, 0x9d, 0xd1, 0x48, 0x49, 0x90, 0x88, 0x82, 0x9e, 0x03, 0xf4,
+ 0x44, 0x41, 0x4f, 0x2c, 0xe8, 0x39, 0x40, 0x4f, 0x2c, 0xe8, 0x89, 0x05, 0x3d, 0x07, 0xe8, 0x89,
+ 0x05, 0x3d, 0x51, 0xd2, 0x73, 0x80, 0x9e, 0x28, 0xe9, 0x89, 0x92, 0x9e, 0x03, 0xf4, 0x44, 0x49,
+ 0x4f, 0x94, 0xf4, 0x1c, 0xa0, 0x27, 0x4e, 0xaf, 0x75, 0x2d, 0xe8, 0x39, 0x40, 0x4f, 0x94, 0xf4,
+ 0xc4, 0x82, 0x9e, 0x03, 0xf4, 0xc4, 0x82, 0x9e, 0x28, 0xe9, 0x39, 0x40, 0x4f, 0x94, 0xf4, 0x44,
+ 0x49, 0xcf, 0x01, 0x7a, 0xa2, 0xa4, 0x27, 0x16, 0xf4, 0x1c, 0xa0, 0x27, 0x0c, 0xbd, 0x7f, 0x6d,
+ 0xe4, 0xbd, 0x49, 0xe2, 0x09, 0x55, 0xf8, 0x31, 0x72, 0xcf, 0x79, 0xca, 0x85, 0x26, 0xb7, 0xdd,
+ 0xdd, 0xe9, 0x98, 0x2b, 0xda, 0x31, 0xe5, 0xce, 0x73, 0xa8, 0x11, 0x23, 0xc1, 0x4f, 0xc0, 0xcf,
+ 0xa8, 0x61, 0xf3, 0xd6, 0xa9, 0x3d, 0xa1, 0xff, 0xe2, 0x47, 0xc8, 0x93, 0xfa, 0x2a, 0xe9, 0x53,
+ 0xd5, 0xe8, 0x6e, 0x17, 0x6a, 0x73, 0xc1, 0x48, 0x5e, 0xc5, 0x5f, 0x98, 0x0d, 0xd1, 0x4a, 0x58,
+ 0xe7, 0xaa, 0x12, 0x36, 0x28, 0x97, 0x56, 0x85, 0x01, 0xec, 0xef, 0x68, 0xcf, 0x3b, 0x85, 0x32,
+ 0xe7, 0x4e, 0x8a, 0x3a, 0xfe, 0x0a, 0xd5, 0xc5, 0xb0, 0x10, 0xdf, 0xd3, 0xb6, 0x2b, 0xe2, 0x9a,
+ 0xc8, 0x7f, 0xb5, 0x3f, 0x43, 0xae, 0x59, 0x74, 0x15, 0x39, 0x64, 0x70, 0xd4, 0xdc, 0xc0, 0x75,
+ 0xe4, 0x7e, 0x4f, 0x06, 0x83, 0x93, 0xa6, 0x85, 0x6b, 0xa8, 0x72, 0xf8, 0xea, 0x6c, 0xd0, 0xb4,
+ 0xdb, 0x7f, 0xd9, 0xa8, 0x72, 0x1c, 0xcd, 0x24, 0xfe, 0x16, 0x35, 0xa6, 0xe6, 0xb8, 0xc0, 0xde,
+ 0xeb, 0x33, 0xd6, 0xe8, 0x7e, 0x58, 0xf8, 0x83, 0xa4, 0x73, 0xac, 0xcf, 0xcf, 0xa9, 0x12, 0x03,
+ 0xa6, 0xc4, 0x9c, 0xd4, 0xa7, 0x45, 0x8c, 0x0f, 0xd0, 0xd6, 0x54, 0x9f, 0xcd, 0xe2, 0xab, 0x6d,
+ 0xdd, 0xfe, 0xd1, 0xcd, 0x76, 0x38, 0xaf, 0xe6, 0xb3, 0x8d, 0x41, 0x63, 0x5a, 0x66, 0x5a, 0xdf,
+ 0xa1, 0xed, 0x9b, 0xfe, 0xb8, 0x89, 0x9c, 0x5f, 0xe9, 0x5c, 0x63, 0x74, 0x08, 0xfc, 0xc4, 0x3b,
+ 0xc8, 0xbd, 0x88, 0xd2, 0x8c, 0xea, 0xeb, 0x57, 0x27, 0x26, 0x78, 0x66, 0x7f, 0x63, 0xb5, 0x4e,
+ 0x50, 0x73, 0xd9, 0xfe, 0x7a, 0x7f, 0xcd, 0xf4, 0x3f, 0xbc, 0xde, 0xbf, 0x0a, 0xa5, 0xf4, 0x6b,
+ 0xff, 0x61, 0xa1, 0xcd, 0x63, 0x39, 0x79, 0x93, 0xa8, 0xb7, 0x3f, 0x31, 0xca, 0xc7, 0xf8, 0x3e,
+ 0x72, 0x55, 0xa2, 0x52, 0xaa, 0xed, 0xea, 0x2f, 0x37, 0x88, 0x09, 0xb1, 0x8f, 0x3c, 0x19, 0xa5,
+ 0x91, 0x98, 0x6b, 0x4f, 0xe7, 0xe5, 0x06, 0xc9, 0x63, 0xdc, 0x42, 0xd5, 0xe7, 0x3c, 0x83, 0x95,
+ 0xe8, 0x67, 0x01, 0x7a, 0x8a, 0x04, 0xfe, 0x14, 0x6d, 0xbe, 0xe5, 0x53, 0x3a, 0x8c, 0xe2, 0x58,
+ 0x50, 0x29, 0xf5, 0x0b, 0x01, 0x82, 0x06, 0x64, 0x0f, 0x4c, 0xf2, 0xb0, 0x8a, 0xdc, 0x8c, 0x25,
+ 0x9c, 0xb5, 0x1f, 0xa1, 0x0a, 0xa1, 0x51, 0x5a, 0x7e, 0xbe, 0x65, 0xde, 0x08, 0x1d, 0x3c, 0xae,
+ 0xd5, 0xe2, 0xe6, 0xd5, 0xd5, 0xd5, 0x95, 0xdd, 0xbe, 0x84, 0xff, 0x08, 0x5f, 0xf2, 0x1e, 0xef,
+ 0xa1, 0x7a, 0x32, 0x8d, 0x26, 0x09, 0x83, 0x95, 0x19, 0x79, 0x99, 0x28, 0x5b, 0xba, 0x47, 0x68,
+ 0x5b, 0xd0, 0x28, 0x1d, 0xd2, 0xf7, 0x8a, 0x32, 0x99, 0x70, 0x86, 0x37, 0xcb, 0x23, 0x15, 0xa5,
+ 0xfe, 0x6f, 0x37, 0xcf, 0x64, 0x6e, 0x4f, 0xb6, 0xa0, 0x69, 0x50, 0xf4, 0xb4, 0xff, 0x73, 0x11,
+ 0xfa, 0x91, 0xf1, 0x4b, 0xf6, 0x7a, 0x3e, 0xa3, 0x12, 0x3f, 0x44, 0x76, 0xc4, 0xfc, 0x6d, 0xdd,
+ 0xba, 0xd3, 0x31, 0xf3, 0xa9, 0x53, 0xcc, 0xa7, 0xce, 0x01, 0x9b, 0x13, 0x3b, 0x62, 0xf8, 0x4b,
+ 0xe4, 0xc4, 0x99, 0xb9, 0xa5, 0x8d, 0xee, 0xee, 0x8a, 0xec, 0x28, 0x9f, 0x92, 0x04, 0x54, 0xf8,
+ 0x73, 0x64, 0x4b, 0xe5, 0x6f, 0x6a, 0xed, 0x83, 0x15, 0xed, 0xa9, 0x9e, 0x98, 0xc4, 0x96, 0x70,
+ 0xfb, 0x6d, 0x25, 0x73, 0xbe, 0xad, 0x15, 0xe1, 0xeb, 0x62, 0x78, 0x12, 0x5b, 0x49, 0xd0, 0xa6,
+ 0x17, 0xfe, 0x9d, 0x35, 0xda, 0x57, 0x89, 0x54, 0xbf, 0xc0, 0x0e, 0x13, 0x3b, 0xbd, 0xc0, 0x21,
+ 0x72, 0x2e, 0xa2, 0xd4, 0x6f, 0x6a, 0xf1, 0xfd, 0x15, 0xb1, 0x11, 0x82, 0x04, 0x77, 0x90, 0x13,
+ 0x8f, 0x52, 0xcd, 0xbc, 0xd1, 0xdd, 0x5b, 0xfd, 0x2e, 0xfd, 0xc8, 0xe5, 0xfa, 0x78, 0x94, 0xe2,
+ 0x27, 0xc8, 0x19, 0xa7, 0x4a, 0x1f, 0x01, 0xb8, 0x70, 0xcb, 0x7a, 0xfd, 0x5c, 0xe6, 0xf2, 0x71,
+ 0xaa, 0x40, 0x9e, 0xe4, 0xb3, 0xf5, 0x36, 0xb9, 0xbe, 0x42, 0xb9, 0x3c, 0xe9, 0xf7, 0x60, 0x35,
+ 0x59, 0xbf, 0xa7, 0xa7, 0xca, 0x6d, 0xab, 0x39, 0xbb, 0xae, 0xcf, 0xfa, 0x3d, 0x6d, 0xbf, 0xdf,
+ 0xd5, 0x43, 0x78, 0x8d, 0xfd, 0x7e, 0xb7, 0xb0, 0xdf, 0xef, 0x6a, 0xfb, 0xfd, 0xae, 0x9e, 0xcc,
+ 0xeb, 0xec, 0x17, 0xfa, 0x4c, 0xeb, 0x2b, 0x7a, 0x84, 0xd5, 0xd7, 0x6c, 0x3a, 0xdc, 0x61, 0x23,
+ 0xd7, 0x3a, 0xf0, 0x87, 0xd7, 0x08, 0xad, 0xf1, 0x37, 0x63, 0x21, 0xf7, 0x97, 0x4a, 0xe0, 0xaf,
+ 0x91, 0x5b, 0x0e, 0xf7, 0xdb, 0x3e, 0x40, 0x8f, 0x0b, 0xd3, 0x60, 0x94, 0xcf, 0x02, 0x54, 0x61,
+ 0xd1, 0x94, 0x2e, 0x1d, 0xfc, 0xdf, 0xf5, 0x0b, 0xa3, 0x2b, 0xff, 0x07, 0x00, 0x00, 0xff, 0xff,
+ 0xd5, 0x39, 0x32, 0x09, 0xf9, 0x09, 0x00, 0x00,
}
diff --git a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.proto b/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.proto
index a493ecc24..0d2fc1fad 100644
--- a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.proto
+++ b/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.proto
@@ -54,6 +54,16 @@ message Simple {
optional bytes o_bytes = 11;
}
+// Test message for holding special non-finites primitives.
+message NonFinites {
+ optional float f_nan = 1;
+ optional float f_pinf = 2;
+ optional float f_ninf = 3;
+ optional double d_nan = 4;
+ optional double d_pinf = 5;
+ optional double d_ninf = 6;
+}
+
// Test message for holding repeated primitives.
message Repeats {
repeated bool r_bool = 1;
diff --git a/vendor/github.com/golang/protobuf/proto/decode_test.go b/vendor/github.com/golang/protobuf/proto/decode_test.go
index b1f130449..2c4c31d12 100644
--- a/vendor/github.com/golang/protobuf/proto/decode_test.go
+++ b/vendor/github.com/golang/protobuf/proto/decode_test.go
@@ -29,6 +29,8 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// +build go1.7
+
package proto_test
import (
diff --git a/vendor/github.com/golang/protobuf/proto/encode_test.go b/vendor/github.com/golang/protobuf/proto/encode_test.go
index 0b36a0e9f..a7209475f 100644
--- a/vendor/github.com/golang/protobuf/proto/encode_test.go
+++ b/vendor/github.com/golang/protobuf/proto/encode_test.go
@@ -29,6 +29,8 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// +build go1.7
+
package proto_test
import (
diff --git a/vendor/github.com/golang/protobuf/proto/lib.go b/vendor/github.com/golang/protobuf/proto/lib.go
index ac4ddbc07..1c225504a 100644
--- a/vendor/github.com/golang/protobuf/proto/lib.go
+++ b/vendor/github.com/golang/protobuf/proto/lib.go
@@ -73,7 +73,6 @@ for a protocol buffer variable v:
When the .proto file specifies `syntax="proto3"`, there are some differences:
- Non-repeated fields of non-message type are values instead of pointers.
- - Getters are only generated for message and oneof fields.
- Enum types do not get an Enum method.
The simplest way to describe this is to see an example.
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go
index d8717d57d..1954e3fb7 100644
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go
@@ -1,6 +1,5 @@
-// Code generated by protoc-gen-go.
+// Code generated by protoc-gen-go. DO NOT EDIT.
// source: my_test/test.proto
-// DO NOT EDIT!
/*
Package my_test is a generated protocol buffer package.
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go.golden b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go.golden
index d8717d57d..1954e3fb7 100644
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go.golden
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go.golden
@@ -1,6 +1,5 @@
-// Code generated by protoc-gen-go.
+// Code generated by protoc-gen-go. DO NOT EDIT.
// source: my_test/test.proto
-// DO NOT EDIT!
/*
Package my_test is a generated protocol buffer package.
diff --git a/vendor/github.com/golang/protobuf/ptypes/any.go b/vendor/github.com/golang/protobuf/ptypes/any.go
index 89e07ae19..b2af97f4a 100644
--- a/vendor/github.com/golang/protobuf/ptypes/any.go
+++ b/vendor/github.com/golang/protobuf/ptypes/any.go
@@ -51,6 +51,9 @@ const googleApis = "type.googleapis.com/"
// function. AnyMessageName is provided for less common use cases like filtering a
// sequence of Any messages based on a set of allowed message type names.
func AnyMessageName(any *any.Any) (string, error) {
+ if any == nil {
+ return "", fmt.Errorf("message is nil")
+ }
slash := strings.LastIndex(any.TypeUrl, "/")
if slash < 0 {
return "", fmt.Errorf("message type url %q is invalid", any.TypeUrl)
diff --git a/vendor/github.com/golang/protobuf/ptypes/duration_test.go b/vendor/github.com/golang/protobuf/ptypes/duration_test.go
index e761289f1..e00491a34 100644
--- a/vendor/github.com/golang/protobuf/ptypes/duration_test.go
+++ b/vendor/github.com/golang/protobuf/ptypes/duration_test.go
@@ -52,37 +52,37 @@ var durationTests = []struct {
dur time.Duration
}{
// The zero duration.
- {&durpb.Duration{0, 0}, true, true, 0},
+ {&durpb.Duration{Seconds: 0, Nanos: 0}, true, true, 0},
// Some ordinary non-zero durations.
- {&durpb.Duration{100, 0}, true, true, 100 * time.Second},
- {&durpb.Duration{-100, 0}, true, true, -100 * time.Second},
- {&durpb.Duration{100, 987}, true, true, 100*time.Second + 987},
- {&durpb.Duration{-100, -987}, true, true, -(100*time.Second + 987)},
+ {&durpb.Duration{Seconds: 100, Nanos: 0}, true, true, 100 * time.Second},
+ {&durpb.Duration{Seconds: -100, Nanos: 0}, true, true, -100 * time.Second},
+ {&durpb.Duration{Seconds: 100, Nanos: 987}, true, true, 100*time.Second + 987},
+ {&durpb.Duration{Seconds: -100, Nanos: -987}, true, true, -(100*time.Second + 987)},
// The largest duration representable in Go.
- {&durpb.Duration{maxGoSeconds, int32(math.MaxInt64 - 1e9*maxGoSeconds)}, true, true, math.MaxInt64},
+ {&durpb.Duration{Seconds: maxGoSeconds, Nanos: int32(math.MaxInt64 - 1e9*maxGoSeconds)}, true, true, math.MaxInt64},
// The smallest duration representable in Go.
- {&durpb.Duration{minGoSeconds, int32(math.MinInt64 - 1e9*minGoSeconds)}, true, true, math.MinInt64},
+ {&durpb.Duration{Seconds: minGoSeconds, Nanos: int32(math.MinInt64 - 1e9*minGoSeconds)}, true, true, math.MinInt64},
{nil, false, false, 0},
- {&durpb.Duration{-100, 987}, false, false, 0},
- {&durpb.Duration{100, -987}, false, false, 0},
- {&durpb.Duration{math.MinInt64, 0}, false, false, 0},
- {&durpb.Duration{math.MaxInt64, 0}, false, false, 0},
+ {&durpb.Duration{Seconds: -100, Nanos: 987}, false, false, 0},
+ {&durpb.Duration{Seconds: 100, Nanos: -987}, false, false, 0},
+ {&durpb.Duration{Seconds: math.MinInt64, Nanos: 0}, false, false, 0},
+ {&durpb.Duration{Seconds: math.MaxInt64, Nanos: 0}, false, false, 0},
// The largest valid duration.
- {&durpb.Duration{maxSeconds, 1e9 - 1}, true, false, 0},
+ {&durpb.Duration{Seconds: maxSeconds, Nanos: 1e9 - 1}, true, false, 0},
// The smallest valid duration.
- {&durpb.Duration{minSeconds, -(1e9 - 1)}, true, false, 0},
+ {&durpb.Duration{Seconds: minSeconds, Nanos: -(1e9 - 1)}, true, false, 0},
// The smallest invalid duration above the valid range.
- {&durpb.Duration{maxSeconds + 1, 0}, false, false, 0},
+ {&durpb.Duration{Seconds: maxSeconds + 1, Nanos: 0}, false, false, 0},
// The largest invalid duration below the valid range.
- {&durpb.Duration{minSeconds - 1, -(1e9 - 1)}, false, false, 0},
+ {&durpb.Duration{Seconds: minSeconds - 1, Nanos: -(1e9 - 1)}, false, false, 0},
// One nanosecond past the largest duration representable in Go.
- {&durpb.Duration{maxGoSeconds, int32(math.MaxInt64-1e9*maxGoSeconds) + 1}, true, false, 0},
+ {&durpb.Duration{Seconds: maxGoSeconds, Nanos: int32(math.MaxInt64-1e9*maxGoSeconds) + 1}, true, false, 0},
// One nanosecond past the smallest duration representable in Go.
- {&durpb.Duration{minGoSeconds, int32(math.MinInt64-1e9*minGoSeconds) - 1}, true, false, 0},
+ {&durpb.Duration{Seconds: minGoSeconds, Nanos: int32(math.MinInt64-1e9*minGoSeconds) - 1}, true, false, 0},
// One second past the largest duration representable in Go.
- {&durpb.Duration{maxGoSeconds + 1, int32(math.MaxInt64 - 1e9*maxGoSeconds)}, true, false, 0},
+ {&durpb.Duration{Seconds: maxGoSeconds + 1, Nanos: int32(math.MaxInt64 - 1e9*maxGoSeconds)}, true, false, 0},
// One second past the smallest duration representable in Go.
- {&durpb.Duration{minGoSeconds - 1, int32(math.MinInt64 - 1e9*minGoSeconds)}, true, false, 0},
+ {&durpb.Duration{Seconds: minGoSeconds - 1, Nanos: int32(math.MinInt64 - 1e9*minGoSeconds)}, true, false, 0},
}
func TestValidateDuration(t *testing.T) {
diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp.go b/vendor/github.com/golang/protobuf/ptypes/timestamp.go
index 1b3657622..47f10dbc2 100644
--- a/vendor/github.com/golang/protobuf/ptypes/timestamp.go
+++ b/vendor/github.com/golang/protobuf/ptypes/timestamp.go
@@ -99,6 +99,15 @@ func Timestamp(ts *tspb.Timestamp) (time.Time, error) {
return t, validateTimestamp(ts)
}
+// TimestampNow returns a google.protobuf.Timestamp for the current time.
+func TimestampNow() *tspb.Timestamp {
+ ts, err := TimestampProto(time.Now())
+ if err != nil {
+ panic("ptypes: time.Now() out of Timestamp range")
+ }
+ return ts
+}
+
// TimestampProto converts the time.Time to a google.protobuf.Timestamp proto.
// It returns an error if the resulting Timestamp is invalid.
func TimestampProto(t time.Time) (*tspb.Timestamp, error) {
diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp_test.go b/vendor/github.com/golang/protobuf/ptypes/timestamp_test.go
index 114a7f9fc..6e3c969b9 100644
--- a/vendor/github.com/golang/protobuf/ptypes/timestamp_test.go
+++ b/vendor/github.com/golang/protobuf/ptypes/timestamp_test.go
@@ -46,32 +46,32 @@ var tests = []struct {
t time.Time
}{
// The timestamp representing the Unix epoch date.
- {&tspb.Timestamp{0, 0}, true, utcDate(1970, 1, 1)},
+ {&tspb.Timestamp{Seconds: 0, Nanos: 0}, true, utcDate(1970, 1, 1)},
// The smallest representable timestamp.
- {&tspb.Timestamp{math.MinInt64, math.MinInt32}, false,
+ {&tspb.Timestamp{Seconds: math.MinInt64, Nanos: math.MinInt32}, false,
time.Unix(math.MinInt64, math.MinInt32).UTC()},
// The smallest representable timestamp with non-negative nanos.
- {&tspb.Timestamp{math.MinInt64, 0}, false, time.Unix(math.MinInt64, 0).UTC()},
+ {&tspb.Timestamp{Seconds: math.MinInt64, Nanos: 0}, false, time.Unix(math.MinInt64, 0).UTC()},
// The earliest valid timestamp.
- {&tspb.Timestamp{minValidSeconds, 0}, true, utcDate(1, 1, 1)},
+ {&tspb.Timestamp{Seconds: minValidSeconds, Nanos: 0}, true, utcDate(1, 1, 1)},
//"0001-01-01T00:00:00Z"},
// The largest representable timestamp.
- {&tspb.Timestamp{math.MaxInt64, math.MaxInt32}, false,
+ {&tspb.Timestamp{Seconds: math.MaxInt64, Nanos: math.MaxInt32}, false,
time.Unix(math.MaxInt64, math.MaxInt32).UTC()},
// The largest representable timestamp with nanos in range.
- {&tspb.Timestamp{math.MaxInt64, 1e9 - 1}, false,
+ {&tspb.Timestamp{Seconds: math.MaxInt64, Nanos: 1e9 - 1}, false,
time.Unix(math.MaxInt64, 1e9-1).UTC()},
// The largest valid timestamp.
- {&tspb.Timestamp{maxValidSeconds - 1, 1e9 - 1}, true,
+ {&tspb.Timestamp{Seconds: maxValidSeconds - 1, Nanos: 1e9 - 1}, true,
time.Date(9999, 12, 31, 23, 59, 59, 1e9-1, time.UTC)},
// The smallest invalid timestamp that is larger than the valid range.
- {&tspb.Timestamp{maxValidSeconds, 0}, false, time.Unix(maxValidSeconds, 0).UTC()},
+ {&tspb.Timestamp{Seconds: maxValidSeconds, Nanos: 0}, false, time.Unix(maxValidSeconds, 0).UTC()},
// A date before the epoch.
- {&tspb.Timestamp{-281836800, 0}, true, utcDate(1961, 1, 26)},
+ {&tspb.Timestamp{Seconds: -281836800, Nanos: 0}, true, utcDate(1961, 1, 26)},
// A date after the epoch.
- {&tspb.Timestamp{1296000000, 0}, true, utcDate(2011, 1, 26)},
+ {&tspb.Timestamp{Seconds: 1296000000, Nanos: 0}, true, utcDate(2011, 1, 26)},
// A date after the epoch, in the middle of the day.
- {&tspb.Timestamp{1296012345, 940483}, true,
+ {&tspb.Timestamp{Seconds: 1296012345, Nanos: 940483}, true,
time.Date(2011, 1, 26, 3, 25, 45, 940483, time.UTC)},
}
@@ -123,8 +123,8 @@ func TestTimestampString(t *testing.T) {
}{
// Not much testing needed because presumably time.Format is
// well-tested.
- {&tspb.Timestamp{0, 0}, "1970-01-01T00:00:00Z"},
- {&tspb.Timestamp{minValidSeconds - 1, 0}, "(timestamp: seconds:-62135596801 before 0001-01-01)"},
+ {&tspb.Timestamp{Seconds: 0, Nanos: 0}, "1970-01-01T00:00:00Z"},
+ {&tspb.Timestamp{Seconds: minValidSeconds - 1, Nanos: 0}, "(timestamp: seconds:-62135596801 before 0001-01-01)"},
} {
got := TimestampString(test.ts)
if got != test.want {
@@ -136,3 +136,18 @@ func TestTimestampString(t *testing.T) {
func utcDate(year, month, day int) time.Time {
return time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC)
}
+
+func TestTimestampNow(t *testing.T) {
+ // Bracket the expected time.
+ before := time.Now()
+ ts := TimestampNow()
+ after := time.Now()
+
+ tm, err := Timestamp(ts)
+ if err != nil {
+ t.Errorf("between %v and %v\nTimestampNow() = %v\nwhich is invalid (%v)", before, after, ts, err)
+ }
+ if tm.Before(before) || tm.After(after) {
+ t.Errorf("between %v and %v\nTimestamp(TimestampNow()) = %v", before, after, tm)
+ }
+}
diff --git a/vendor/github.com/gorilla/handlers/handlers.go b/vendor/github.com/gorilla/handlers/handlers.go
index 551f8ff05..75db7f87b 100644
--- a/vendor/github.com/gorilla/handlers/handlers.go
+++ b/vendor/github.com/gorilla/handlers/handlers.go
@@ -79,9 +79,9 @@ func (h combinedLoggingHandler) ServeHTTP(w http.ResponseWriter, req *http.Reque
}
func makeLogger(w http.ResponseWriter) loggingResponseWriter {
- var logger loggingResponseWriter = &responseLogger{w: w}
+ var logger loggingResponseWriter = &responseLogger{w: w, status: http.StatusOK}
if _, ok := w.(http.Hijacker); ok {
- logger = &hijackLogger{responseLogger{w: w}}
+ logger = &hijackLogger{responseLogger{w: w, status: http.StatusOK}}
}
h, ok1 := logger.(http.Hijacker)
c, ok2 := w.(http.CloseNotifier)
@@ -114,10 +114,6 @@ func (l *responseLogger) Header() http.Header {
}
func (l *responseLogger) Write(b []byte) (int, error) {
- if l.status == 0 {
- // The status will be StatusOK if WriteHeader has not been called yet
- l.status = http.StatusOK
- }
size, err := l.w.Write(b)
l.size += size
return size, err
diff --git a/vendor/github.com/gorilla/handlers/handlers_test.go b/vendor/github.com/gorilla/handlers/handlers_test.go
index 6ea7c7fa6..04ee24497 100644
--- a/vendor/github.com/gorilla/handlers/handlers_test.go
+++ b/vendor/github.com/gorilla/handlers/handlers_test.go
@@ -73,6 +73,30 @@ func TestMethodHandler(t *testing.T) {
}
}
+func TestMakeLogger(t *testing.T) {
+ rec := httptest.NewRecorder()
+ logger := makeLogger(rec)
+ // initial status
+ if logger.Status() != http.StatusOK {
+ t.Fatalf("wrong status, got %d want %d", logger.Status(), http.StatusOK)
+ }
+ // WriteHeader
+ logger.WriteHeader(http.StatusInternalServerError)
+ if logger.Status() != http.StatusInternalServerError {
+ t.Fatalf("wrong status, got %d want %d", logger.Status(), http.StatusInternalServerError)
+ }
+ // Write
+ logger.Write([]byte(ok))
+ if logger.Size() != len(ok) {
+ t.Fatalf("wrong size, got %d want %d", logger.Size(), len(ok))
+ }
+ // Header
+ logger.Header().Set("key", "value")
+ if val := logger.Header().Get("key"); val != "value" {
+ t.Fatalf("wrong header, got %s want %s", val, "value")
+ }
+}
+
func TestWriteLog(t *testing.T) {
loc, err := time.LoadLocation("Europe/Warsaw")
if err != nil {
diff --git a/vendor/github.com/gorilla/mux/README.md b/vendor/github.com/gorilla/mux/README.md
index cdab8784d..56c67134f 100644
--- a/vendor/github.com/gorilla/mux/README.md
+++ b/vendor/github.com/gorilla/mux/README.md
@@ -179,6 +179,7 @@ package main
import (
"fmt"
"net/http"
+ "strings"
"github.com/gorilla/mux"
)
@@ -190,15 +191,25 @@ func handler(w http.ResponseWriter, r *http.Request) {
func main() {
r := mux.NewRouter()
r.HandleFunc("/", handler)
- r.HandleFunc("/products", handler)
- r.HandleFunc("/articles", handler)
- r.HandleFunc("/articles/{id}", handler)
+ r.Methods("POST").HandleFunc("/products", handler)
+ r.Methods("GET").HandleFunc("/articles", handler)
+ r.Methods("GET", "PUT").HandleFunc("/articles/{id}", handler)
r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
t, err := route.GetPathTemplate()
if err != nil {
return err
}
- fmt.Println(t)
+ // p will contain regular expression is compatible with regular expression in Perl, Python, and other languages.
+ // for instance the regular expression for path '/articles/{id}' will be '^/articles/(?P<v0>[^/]+)$'
+ p, err := route.GetPathRegexp()
+ if err != nil {
+ return err
+ }
+ m, err := route.GetMethods()
+ if err != nil {
+ return err
+ }
+ fmt.Println(strings.Join(m, ","), t, p)
return nil
})
http.Handle("/", r)
diff --git a/vendor/github.com/gorilla/mux/mux_test.go b/vendor/github.com/gorilla/mux/mux_test.go
index 1dec7abef..19ef5a8cc 100644
--- a/vendor/github.com/gorilla/mux/mux_test.go
+++ b/vendor/github.com/gorilla/mux/mux_test.go
@@ -10,6 +10,7 @@ import (
"errors"
"fmt"
"net/http"
+ "net/url"
"strings"
"testing"
)
@@ -31,10 +32,13 @@ type routeTest struct {
route *Route // the route being tested
request *http.Request // a request to test the route
vars map[string]string // the expected vars of the match
- host string // the expected host of the match
- path string // the expected path of the match
- pathTemplate string // the expected path template to match
- hostTemplate string // the expected host template to match
+ scheme string // the expected scheme of the built URL
+ host string // the expected host of the built URL
+ path string // the expected path of the built URL
+ pathTemplate string // the expected path template of the route
+ hostTemplate string // the expected host template of the route
+ methods []string // the expected route methods
+ pathRegexp string // the expected path regexp
shouldMatch bool // whether the request is expected to match the route at all
shouldRedirect bool // whether the request should result in a redirect
}
@@ -195,46 +199,6 @@ func TestHost(t *testing.T) {
hostTemplate: `{v-1:[a-z]{3}}.{v-2:[a-z]{3}}.{v-3:[a-z]{3}}`,
shouldMatch: true,
},
- {
- title: "Path route with single pattern with pipe, match",
- route: new(Route).Path("/{category:a|b/c}"),
- request: newRequest("GET", "http://localhost/a"),
- vars: map[string]string{"category": "a"},
- host: "",
- path: "/a",
- pathTemplate: `/{category:a|b/c}`,
- shouldMatch: true,
- },
- {
- title: "Path route with single pattern with pipe, match",
- route: new(Route).Path("/{category:a|b/c}"),
- request: newRequest("GET", "http://localhost/b/c"),
- vars: map[string]string{"category": "b/c"},
- host: "",
- path: "/b/c",
- pathTemplate: `/{category:a|b/c}`,
- shouldMatch: true,
- },
- {
- title: "Path route with multiple patterns with pipe, match",
- route: new(Route).Path("/{category:a|b/c}/{product}/{id:[0-9]+}"),
- request: newRequest("GET", "http://localhost/a/product_name/1"),
- vars: map[string]string{"category": "a", "product": "product_name", "id": "1"},
- host: "",
- path: "/a/product_name/1",
- pathTemplate: `/{category:a|b/c}/{product}/{id:[0-9]+}`,
- shouldMatch: true,
- },
- {
- title: "Path route with multiple patterns with pipe, match",
- route: new(Route).Path("/{category:a|b/c}/{product}/{id:[0-9]+}"),
- request: newRequest("GET", "http://localhost/b/c/product_name/1"),
- vars: map[string]string{"category": "b/c", "product": "product_name", "id": "1"},
- host: "",
- path: "/b/c/product_name/1",
- pathTemplate: `/{category:a|b/c}/{product}/{id:[0-9]+}`,
- shouldMatch: true,
- },
}
for _, test := range tests {
testRoute(t, test)
@@ -270,6 +234,7 @@ func TestPath(t *testing.T) {
host: "",
path: "/111",
pathTemplate: `/111/`,
+ pathRegexp: `^/111/$`,
shouldMatch: false,
},
{
@@ -290,6 +255,7 @@ func TestPath(t *testing.T) {
host: "",
path: "/",
pathTemplate: `/`,
+ pathRegexp: `^/$`,
shouldMatch: true,
},
{
@@ -333,6 +299,7 @@ func TestPath(t *testing.T) {
host: "",
path: "/111/222/333",
pathTemplate: `/111/{v1:[0-9]{3}}/333`,
+ pathRegexp: `^/111/(?P<v0>[0-9]{3})/333$`,
shouldMatch: false,
},
{
@@ -343,6 +310,7 @@ func TestPath(t *testing.T) {
host: "",
path: "/111/222/333",
pathTemplate: `/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}`,
+ pathRegexp: `^/(?P<v0>[0-9]{3})/(?P<v1>[0-9]{3})/(?P<v2>[0-9]{3})$`,
shouldMatch: true,
},
{
@@ -353,6 +321,7 @@ func TestPath(t *testing.T) {
host: "",
path: "/111/222/333",
pathTemplate: `/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}`,
+ pathRegexp: `^/(?P<v0>[0-9]{3})/(?P<v1>[0-9]{3})/(?P<v2>[0-9]{3})$`,
shouldMatch: false,
},
{
@@ -363,6 +332,7 @@ func TestPath(t *testing.T) {
host: "",
path: "/a/product_name/1",
pathTemplate: `/{category:a|(?:b/c)}/{product}/{id:[0-9]+}`,
+ pathRegexp: `^/(?P<v0>a|(?:b/c))/(?P<v1>[^/]+)/(?P<v2>[0-9]+)$`,
shouldMatch: true,
},
{
@@ -373,6 +343,7 @@ func TestPath(t *testing.T) {
host: "",
path: "/111/222/333",
pathTemplate: `/111/{v-1:[0-9]{3}}/333`,
+ pathRegexp: `^/111/(?P<v0>[0-9]{3})/333$`,
shouldMatch: true,
},
{
@@ -383,6 +354,7 @@ func TestPath(t *testing.T) {
host: "",
path: "/111/222/333",
pathTemplate: `/{v-1:[0-9]{3}}/{v-2:[0-9]{3}}/{v-3:[0-9]{3}}`,
+ pathRegexp: `^/(?P<v0>[0-9]{3})/(?P<v1>[0-9]{3})/(?P<v2>[0-9]{3})$`,
shouldMatch: true,
},
{
@@ -393,6 +365,7 @@ func TestPath(t *testing.T) {
host: "",
path: "/a/product_name/1",
pathTemplate: `/{product-category:a|(?:b/c)}/{product-name}/{product-id:[0-9]+}`,
+ pathRegexp: `^/(?P<v0>a|(?:b/c))/(?P<v1>[^/]+)/(?P<v2>[0-9]+)$`,
shouldMatch: true,
},
{
@@ -403,6 +376,7 @@ func TestPath(t *testing.T) {
host: "",
path: "/daily-2016-01-01",
pathTemplate: `/{type:(?i:daily|mini|variety)}-{date:\d{4,4}-\d{2,2}-\d{2,2}}`,
+ pathRegexp: `^/(?P<v0>(?i:daily|mini|variety))-(?P<v1>\d{4,4}-\d{2,2}-\d{2,2})$`,
shouldMatch: true,
},
{
@@ -413,6 +387,47 @@ func TestPath(t *testing.T) {
host: "",
path: "/111/222",
pathTemplate: `/{v1:[0-9]*}{v2:[a-z]*}/{v3:[0-9]*}`,
+ pathRegexp: `^/(?P<v0>[0-9]*)(?P<v1>[a-z]*)/(?P<v2>[0-9]*)$`,
+ shouldMatch: true,
+ },
+ {
+ title: "Path route with single pattern with pipe, match",
+ route: new(Route).Path("/{category:a|b/c}"),
+ request: newRequest("GET", "http://localhost/a"),
+ vars: map[string]string{"category": "a"},
+ host: "",
+ path: "/a",
+ pathTemplate: `/{category:a|b/c}`,
+ shouldMatch: true,
+ },
+ {
+ title: "Path route with single pattern with pipe, match",
+ route: new(Route).Path("/{category:a|b/c}"),
+ request: newRequest("GET", "http://localhost/b/c"),
+ vars: map[string]string{"category": "b/c"},
+ host: "",
+ path: "/b/c",
+ pathTemplate: `/{category:a|b/c}`,
+ shouldMatch: true,
+ },
+ {
+ title: "Path route with multiple patterns with pipe, match",
+ route: new(Route).Path("/{category:a|b/c}/{product}/{id:[0-9]+}"),
+ request: newRequest("GET", "http://localhost/a/product_name/1"),
+ vars: map[string]string{"category": "a", "product": "product_name", "id": "1"},
+ host: "",
+ path: "/a/product_name/1",
+ pathTemplate: `/{category:a|b/c}/{product}/{id:[0-9]+}`,
+ shouldMatch: true,
+ },
+ {
+ title: "Path route with multiple patterns with pipe, match",
+ route: new(Route).Path("/{category:a|b/c}/{product}/{id:[0-9]+}"),
+ request: newRequest("GET", "http://localhost/b/c/product_name/1"),
+ vars: map[string]string{"category": "b/c", "product": "product_name", "id": "1"},
+ host: "",
+ path: "/b/c/product_name/1",
+ pathTemplate: `/{category:a|b/c}/{product}/{id:[0-9]+}`,
shouldMatch: true,
},
}
@@ -421,6 +436,7 @@ func TestPath(t *testing.T) {
testRoute(t, test)
testTemplate(t, test)
testUseEscapedRoute(t, test)
+ testRegexp(t, test)
}
}
@@ -502,15 +518,28 @@ func TestPathPrefix(t *testing.T) {
}
}
-func TestHostPath(t *testing.T) {
+func TestSchemeHostPath(t *testing.T) {
tests := []routeTest{
{
title: "Host and Path route, match",
route: new(Route).Host("aaa.bbb.ccc").Path("/111/222/333"),
request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
vars: map[string]string{},
- host: "",
- path: "",
+ scheme: "http",
+ host: "aaa.bbb.ccc",
+ path: "/111/222/333",
+ pathTemplate: `/111/222/333`,
+ hostTemplate: `aaa.bbb.ccc`,
+ shouldMatch: true,
+ },
+ {
+ title: "Scheme, Host, and Path route, match",
+ route: new(Route).Schemes("https").Host("aaa.bbb.ccc").Path("/111/222/333"),
+ request: newRequest("GET", "https://aaa.bbb.ccc/111/222/333"),
+ vars: map[string]string{},
+ scheme: "https",
+ host: "aaa.bbb.ccc",
+ path: "/111/222/333",
pathTemplate: `/111/222/333`,
hostTemplate: `aaa.bbb.ccc`,
shouldMatch: true,
@@ -520,8 +549,9 @@ func TestHostPath(t *testing.T) {
route: new(Route).Host("aaa.bbb.ccc").Path("/111/222/333"),
request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
vars: map[string]string{},
- host: "",
- path: "",
+ scheme: "http",
+ host: "aaa.bbb.ccc",
+ path: "/111/222/333",
pathTemplate: `/111/222/333`,
hostTemplate: `aaa.bbb.ccc`,
shouldMatch: false,
@@ -531,6 +561,19 @@ func TestHostPath(t *testing.T) {
route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"),
request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
vars: map[string]string{"v1": "bbb", "v2": "222"},
+ scheme: "http",
+ host: "aaa.bbb.ccc",
+ path: "/111/222/333",
+ pathTemplate: `/111/{v2:[0-9]{3}}/333`,
+ hostTemplate: `aaa.{v1:[a-z]{3}}.ccc`,
+ shouldMatch: true,
+ },
+ {
+ title: "Scheme, Host, and Path route with host and path patterns, match",
+ route: new(Route).Schemes("ftp", "ssss").Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"),
+ request: newRequest("GET", "ssss://aaa.bbb.ccc/111/222/333"),
+ vars: map[string]string{"v1": "bbb", "v2": "222"},
+ scheme: "ftp",
host: "aaa.bbb.ccc",
path: "/111/222/333",
pathTemplate: `/111/{v2:[0-9]{3}}/333`,
@@ -542,6 +585,7 @@ func TestHostPath(t *testing.T) {
route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"),
request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
vars: map[string]string{"v1": "bbb", "v2": "222"},
+ scheme: "http",
host: "aaa.bbb.ccc",
path: "/111/222/333",
pathTemplate: `/111/{v2:[0-9]{3}}/333`,
@@ -553,6 +597,7 @@ func TestHostPath(t *testing.T) {
route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}").Path("/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}"),
request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc", "v4": "111", "v5": "222", "v6": "333"},
+ scheme: "http",
host: "aaa.bbb.ccc",
path: "/111/222/333",
pathTemplate: `/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}`,
@@ -564,6 +609,7 @@ func TestHostPath(t *testing.T) {
route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}").Path("/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}"),
request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc", "v4": "111", "v5": "222", "v6": "333"},
+ scheme: "http",
host: "aaa.bbb.ccc",
path: "/111/222/333",
pathTemplate: `/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}`,
@@ -635,7 +681,6 @@ func TestHeaders(t *testing.T) {
testRoute(t, test)
testTemplate(t, test)
}
-
}
func TestMethods(t *testing.T) {
@@ -647,6 +692,7 @@ func TestMethods(t *testing.T) {
vars: map[string]string{},
host: "",
path: "",
+ methods: []string{"GET", "POST"},
shouldMatch: true,
},
{
@@ -656,6 +702,7 @@ func TestMethods(t *testing.T) {
vars: map[string]string{},
host: "",
path: "",
+ methods: []string{"GET", "POST"},
shouldMatch: true,
},
{
@@ -665,13 +712,25 @@ func TestMethods(t *testing.T) {
vars: map[string]string{},
host: "",
path: "",
+ methods: []string{"GET", "POST"},
shouldMatch: false,
},
+ {
+ title: "Route without methods",
+ route: new(Route),
+ request: newRequest("PUT", "http://localhost"),
+ vars: map[string]string{},
+ host: "",
+ path: "",
+ methods: []string{},
+ shouldMatch: true,
+ },
}
for _, test := range tests {
testRoute(t, test)
testTemplate(t, test)
+ testMethods(t, test)
}
}
@@ -910,30 +969,43 @@ func TestSchemes(t *testing.T) {
tests := []routeTest{
// Schemes
{
- title: "Schemes route, match https",
- route: new(Route).Schemes("https", "ftp"),
+ title: "Schemes route, default scheme, match http, build http",
+ route: new(Route).Host("localhost"),
+ request: newRequest("GET", "http://localhost"),
+ scheme: "http",
+ host: "localhost",
+ shouldMatch: true,
+ },
+ {
+ title: "Schemes route, match https, build https",
+ route: new(Route).Schemes("https", "ftp").Host("localhost"),
request: newRequest("GET", "https://localhost"),
- vars: map[string]string{},
- host: "",
- path: "",
+ scheme: "https",
+ host: "localhost",
shouldMatch: true,
},
{
- title: "Schemes route, match ftp",
- route: new(Route).Schemes("https", "ftp"),
+ title: "Schemes route, match ftp, build https",
+ route: new(Route).Schemes("https", "ftp").Host("localhost"),
request: newRequest("GET", "ftp://localhost"),
- vars: map[string]string{},
- host: "",
- path: "",
+ scheme: "https",
+ host: "localhost",
+ shouldMatch: true,
+ },
+ {
+ title: "Schemes route, match ftp, build ftp",
+ route: new(Route).Schemes("ftp", "https").Host("localhost"),
+ request: newRequest("GET", "ftp://localhost"),
+ scheme: "ftp",
+ host: "localhost",
shouldMatch: true,
},
{
title: "Schemes route, bad scheme",
- route: new(Route).Schemes("https", "ftp"),
+ route: new(Route).Schemes("https", "ftp").Host("localhost"),
request: newRequest("GET", "http://localhost"),
- vars: map[string]string{},
- host: "",
- path: "",
+ scheme: "https",
+ host: "localhost",
shouldMatch: false,
},
}
@@ -1420,10 +1492,15 @@ func testRoute(t *testing.T, test routeTest) {
route := test.route
vars := test.vars
shouldMatch := test.shouldMatch
- host := test.host
- path := test.path
- url := test.host + test.path
shouldRedirect := test.shouldRedirect
+ uri := url.URL{
+ Scheme: test.scheme,
+ Host: test.host,
+ Path: test.path,
+ }
+ if uri.Scheme == "" {
+ uri.Scheme = "http"
+ }
var match RouteMatch
ok := route.Match(request, &match)
@@ -1436,28 +1513,51 @@ func testRoute(t *testing.T, test routeTest) {
return
}
if shouldMatch {
- if test.vars != nil && !stringMapEqual(test.vars, match.Vars) {
+ if vars != nil && !stringMapEqual(vars, match.Vars) {
t.Errorf("(%v) Vars not equal: expected %v, got %v", test.title, vars, match.Vars)
return
}
- if host != "" {
- u, _ := test.route.URLHost(mapToPairs(match.Vars)...)
- if host != u.Host {
- t.Errorf("(%v) URLHost not equal: expected %v, got %v -- %v", test.title, host, u.Host, getRouteTemplate(route))
+ if test.scheme != "" {
+ u, err := route.URL(mapToPairs(match.Vars)...)
+ if err != nil {
+ t.Fatalf("(%v) URL error: %v -- %v", test.title, err, getRouteTemplate(route))
+ }
+ if uri.Scheme != u.Scheme {
+ t.Errorf("(%v) URLScheme not equal: expected %v, got %v", test.title, uri.Scheme, u.Scheme)
return
}
}
- if path != "" {
- u, _ := route.URLPath(mapToPairs(match.Vars)...)
- if path != u.Path {
- t.Errorf("(%v) URLPath not equal: expected %v, got %v -- %v", test.title, path, u.Path, getRouteTemplate(route))
+ if test.host != "" {
+ u, err := test.route.URLHost(mapToPairs(match.Vars)...)
+ if err != nil {
+ t.Fatalf("(%v) URLHost error: %v -- %v", test.title, err, getRouteTemplate(route))
+ }
+ if uri.Scheme != u.Scheme {
+ t.Errorf("(%v) URLHost scheme not equal: expected %v, got %v -- %v", test.title, uri.Scheme, u.Scheme, getRouteTemplate(route))
+ return
+ }
+ if uri.Host != u.Host {
+ t.Errorf("(%v) URLHost host not equal: expected %v, got %v -- %v", test.title, uri.Host, u.Host, getRouteTemplate(route))
+ return
+ }
+ }
+ if test.path != "" {
+ u, err := route.URLPath(mapToPairs(match.Vars)...)
+ if err != nil {
+ t.Fatalf("(%v) URLPath error: %v -- %v", test.title, err, getRouteTemplate(route))
+ }
+ if uri.Path != u.Path {
+ t.Errorf("(%v) URLPath not equal: expected %v, got %v -- %v", test.title, uri.Path, u.Path, getRouteTemplate(route))
return
}
}
- if url != "" {
- u, _ := route.URL(mapToPairs(match.Vars)...)
- if url != u.Host+u.Path {
- t.Errorf("(%v) URL not equal: expected %v, got %v -- %v", test.title, url, u.Host+u.Path, getRouteTemplate(route))
+ if test.host != "" && test.path != "" {
+ u, err := route.URL(mapToPairs(match.Vars)...)
+ if err != nil {
+ t.Fatalf("(%v) URL error: %v -- %v", test.title, err, getRouteTemplate(route))
+ }
+ if expected, got := uri.String(), u.String(); expected != got {
+ t.Errorf("(%v) URL not equal: expected %v, got %v -- %v", test.title, expected, got, getRouteTemplate(route))
return
}
}
@@ -1499,6 +1599,22 @@ func testTemplate(t *testing.T, test routeTest) {
}
}
+func testMethods(t *testing.T, test routeTest) {
+ route := test.route
+ methods, _ := route.GetMethods()
+ if strings.Join(methods, ",") != strings.Join(test.methods, ",") {
+ t.Errorf("(%v) GetMethods not equal: expected %v, got %v", test.title, test.methods, methods)
+ }
+}
+
+func testRegexp(t *testing.T, test routeTest) {
+ route := test.route
+ routePathRegexp, regexpErr := route.GetPathRegexp()
+ if test.pathRegexp != "" && regexpErr == nil && routePathRegexp != test.pathRegexp {
+ t.Errorf("(%v) GetPathRegexp not equal: expected %v, got %v", test.title, test.pathRegexp, routePathRegexp)
+ }
+}
+
type TestA301ResponseWriter struct {
hh http.Header
status int
diff --git a/vendor/github.com/gorilla/mux/route.go b/vendor/github.com/gorilla/mux/route.go
index 5544c1fd6..56dcbbdc5 100644
--- a/vendor/github.com/gorilla/mux/route.go
+++ b/vendor/github.com/gorilla/mux/route.go
@@ -31,6 +31,8 @@ type Route struct {
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.
@@ -394,6 +396,9 @@ 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))
}
@@ -478,11 +483,13 @@ func (r *Route) URL(pairs ...string) (*url.URL, error) {
}
var scheme, host, path string
if r.regexp.host != nil {
- // Set a default scheme.
- scheme = "http"
if host, err = r.regexp.host.url(values); err != nil {
return nil, err
}
+ scheme = "http"
+ if r.buildScheme != "" {
+ scheme = r.buildScheme
+ }
}
if r.regexp.path != nil {
if path, err = r.regexp.path.url(values); err != nil {
@@ -514,10 +521,14 @@ func (r *Route) URLHost(pairs ...string) (*url.URL, error) {
if err != nil {
return nil, err
}
- return &url.URL{
+ u := &url.URL{
Scheme: "http",
Host: host,
- }, nil
+ }
+ if r.buildScheme != "" {
+ u.Scheme = r.buildScheme
+ }
+ return u, nil
}
// URLPath builds the path part of the URL for a route. See Route.URL().
@@ -558,6 +569,36 @@ func (r *Route) GetPathTemplate() (string, error) {
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
+}
+
+// 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 empty list 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, nil
+}
+
// GetHostTemplate returns the template used to build the
// route match.
// This is useful for building simple REST API documentation and for instrumentation
diff --git a/vendor/github.com/gorilla/websocket/.travis.yml b/vendor/github.com/gorilla/websocket/.travis.yml
index 3d8d29cf3..4ea1e7a1f 100644
--- a/vendor/github.com/gorilla/websocket/.travis.yml
+++ b/vendor/github.com/gorilla/websocket/.travis.yml
@@ -7,7 +7,6 @@ matrix:
- go: 1.5
- go: 1.6
- go: 1.7
- - go: 1.8
- go: tip
allow_failures:
- go: tip
diff --git a/vendor/github.com/gorilla/websocket/client.go b/vendor/github.com/gorilla/websocket/client.go
index 43a87c753..78d932877 100644
--- a/vendor/github.com/gorilla/websocket/client.go
+++ b/vendor/github.com/gorilla/websocket/client.go
@@ -66,9 +66,8 @@ type Dialer struct {
// HandshakeTimeout specifies the duration for the handshake to complete.
HandshakeTimeout time.Duration
- // ReadBufferSize and WriteBufferSize specify I/O buffer sizes. If a buffer
- // size is zero, then a useful default size is used. The I/O buffer sizes
- // do not limit the size of the messages that can be sent or received.
+ // Input and output buffer sizes. If the buffer size is zero, then a
+ // default value of 4096 is used.
ReadBufferSize, WriteBufferSize int
// Subprotocols specifies the client's requested subprotocols.
@@ -369,7 +368,7 @@ func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Re
return nil, resp, ErrBadHandshake
}
- for _, ext := range parseExtensions(resp.Header) {
+ for _, ext := range parseExtensions(req.Header) {
if ext[""] != "permessage-deflate" {
continue
}
@@ -390,3 +389,32 @@ func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Re
netConn = nil // to avoid close in defer.
return conn, resp, nil
}
+
+// cloneTLSConfig clones all public fields except the fields
+// SessionTicketsDisabled and SessionTicketKey. This avoids copying the
+// sync.Mutex in the sync.Once and makes it safe to call cloneTLSConfig on a
+// config in active use.
+func cloneTLSConfig(cfg *tls.Config) *tls.Config {
+ if cfg == nil {
+ return &tls.Config{}
+ }
+ return &tls.Config{
+ Rand: cfg.Rand,
+ Time: cfg.Time,
+ Certificates: cfg.Certificates,
+ NameToCertificate: cfg.NameToCertificate,
+ GetCertificate: cfg.GetCertificate,
+ RootCAs: cfg.RootCAs,
+ NextProtos: cfg.NextProtos,
+ ServerName: cfg.ServerName,
+ ClientAuth: cfg.ClientAuth,
+ ClientCAs: cfg.ClientCAs,
+ InsecureSkipVerify: cfg.InsecureSkipVerify,
+ CipherSuites: cfg.CipherSuites,
+ PreferServerCipherSuites: cfg.PreferServerCipherSuites,
+ ClientSessionCache: cfg.ClientSessionCache,
+ MinVersion: cfg.MinVersion,
+ MaxVersion: cfg.MaxVersion,
+ CurvePreferences: cfg.CurvePreferences,
+ }
+}
diff --git a/vendor/github.com/gorilla/websocket/client_clone.go b/vendor/github.com/gorilla/websocket/client_clone.go
deleted file mode 100644
index 4f0d94372..000000000
--- a/vendor/github.com/gorilla/websocket/client_clone.go
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build go1.8
-
-package websocket
-
-import "crypto/tls"
-
-func cloneTLSConfig(cfg *tls.Config) *tls.Config {
- if cfg == nil {
- return &tls.Config{}
- }
- return cfg.Clone()
-}
diff --git a/vendor/github.com/gorilla/websocket/client_clone_legacy.go b/vendor/github.com/gorilla/websocket/client_clone_legacy.go
deleted file mode 100644
index babb007fb..000000000
--- a/vendor/github.com/gorilla/websocket/client_clone_legacy.go
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build !go1.8
-
-package websocket
-
-import "crypto/tls"
-
-// cloneTLSConfig clones all public fields except the fields
-// SessionTicketsDisabled and SessionTicketKey. This avoids copying the
-// sync.Mutex in the sync.Once and makes it safe to call cloneTLSConfig on a
-// config in active use.
-func cloneTLSConfig(cfg *tls.Config) *tls.Config {
- if cfg == nil {
- return &tls.Config{}
- }
- return &tls.Config{
- Rand: cfg.Rand,
- Time: cfg.Time,
- Certificates: cfg.Certificates,
- NameToCertificate: cfg.NameToCertificate,
- GetCertificate: cfg.GetCertificate,
- RootCAs: cfg.RootCAs,
- NextProtos: cfg.NextProtos,
- ServerName: cfg.ServerName,
- ClientAuth: cfg.ClientAuth,
- ClientCAs: cfg.ClientCAs,
- InsecureSkipVerify: cfg.InsecureSkipVerify,
- CipherSuites: cfg.CipherSuites,
- PreferServerCipherSuites: cfg.PreferServerCipherSuites,
- ClientSessionCache: cfg.ClientSessionCache,
- MinVersion: cfg.MinVersion,
- MaxVersion: cfg.MaxVersion,
- CurvePreferences: cfg.CurvePreferences,
- }
-}
diff --git a/vendor/github.com/gorilla/websocket/compression.go b/vendor/github.com/gorilla/websocket/compression.go
index 813ffb1e8..72c166b2a 100644
--- a/vendor/github.com/gorilla/websocket/compression.go
+++ b/vendor/github.com/gorilla/websocket/compression.go
@@ -12,45 +12,31 @@ import (
"sync"
)
-const (
- minCompressionLevel = -2 // flate.HuffmanOnly not defined in Go < 1.6
- maxCompressionLevel = flate.BestCompression
- defaultCompressionLevel = 1
-)
-
var (
- flateWriterPools [maxCompressionLevel - minCompressionLevel + 1]sync.Pool
- flateReaderPool = sync.Pool{New: func() interface{} {
- return flate.NewReader(nil)
- }}
+ flateWriterPool = sync.Pool{}
)
-func decompressNoContextTakeover(r io.Reader) io.ReadCloser {
+func decompressNoContextTakeover(r io.Reader) io.Reader {
const tail =
// Add four bytes as specified in RFC
"\x00\x00\xff\xff" +
// Add final block to squelch unexpected EOF error from flate reader.
"\x01\x00\x00\xff\xff"
-
- fr, _ := flateReaderPool.Get().(io.ReadCloser)
- fr.(flate.Resetter).Reset(io.MultiReader(r, strings.NewReader(tail)), nil)
- return &flateReadWrapper{fr}
+ return flate.NewReader(io.MultiReader(r, strings.NewReader(tail)))
}
-func isValidCompressionLevel(level int) bool {
- return minCompressionLevel <= level && level <= maxCompressionLevel
-}
-
-func compressNoContextTakeover(w io.WriteCloser, level int) io.WriteCloser {
- p := &flateWriterPools[level-minCompressionLevel]
+func compressNoContextTakeover(w io.WriteCloser) (io.WriteCloser, error) {
tw := &truncWriter{w: w}
- fw, _ := p.Get().(*flate.Writer)
- if fw == nil {
- fw, _ = flate.NewWriter(tw, level)
+ i := flateWriterPool.Get()
+ var fw *flate.Writer
+ var err error
+ if i == nil {
+ fw, err = flate.NewWriter(tw, 3)
} else {
+ fw = i.(*flate.Writer)
fw.Reset(tw)
}
- return &flateWriteWrapper{fw: fw, tw: tw, p: p}
+ return &flateWrapper{fw: fw, tw: tw}, err
}
// truncWriter is an io.Writer that writes all but the last four bytes of the
@@ -89,25 +75,24 @@ func (w *truncWriter) Write(p []byte) (int, error) {
return n + nn, err
}
-type flateWriteWrapper struct {
+type flateWrapper struct {
fw *flate.Writer
tw *truncWriter
- p *sync.Pool
}
-func (w *flateWriteWrapper) Write(p []byte) (int, error) {
+func (w *flateWrapper) Write(p []byte) (int, error) {
if w.fw == nil {
return 0, errWriteClosed
}
return w.fw.Write(p)
}
-func (w *flateWriteWrapper) Close() error {
+func (w *flateWrapper) Close() error {
if w.fw == nil {
return errWriteClosed
}
err1 := w.fw.Flush()
- w.p.Put(w.fw)
+ flateWriterPool.Put(w.fw)
w.fw = nil
if w.tw.p != [4]byte{0, 0, 0xff, 0xff} {
return errors.New("websocket: internal error, unexpected bytes at end of flate stream")
@@ -118,31 +103,3 @@ func (w *flateWriteWrapper) Close() error {
}
return err2
}
-
-type flateReadWrapper struct {
- fr io.ReadCloser
-}
-
-func (r *flateReadWrapper) Read(p []byte) (int, error) {
- if r.fr == nil {
- return 0, io.ErrClosedPipe
- }
- n, err := r.fr.Read(p)
- if err == io.EOF {
- // Preemptively place the reader back in the pool. This helps with
- // scenarios where the application does not call NextReader() soon after
- // this final read.
- r.Close()
- }
- return n, err
-}
-
-func (r *flateReadWrapper) Close() error {
- if r.fr == nil {
- return io.ErrClosedPipe
- }
- err := r.fr.Close()
- flateReaderPool.Put(r.fr)
- r.fr = nil
- return err
-}
diff --git a/vendor/github.com/gorilla/websocket/compression_test.go b/vendor/github.com/gorilla/websocket/compression_test.go
index 659cf4215..cad70fb51 100644
--- a/vendor/github.com/gorilla/websocket/compression_test.go
+++ b/vendor/github.com/gorilla/websocket/compression_test.go
@@ -2,9 +2,7 @@ package websocket
import (
"bytes"
- "fmt"
"io"
- "io/ioutil"
"testing"
)
@@ -31,50 +29,3 @@ func TestTruncWriter(t *testing.T) {
}
}
}
-
-func textMessages(num int) [][]byte {
- messages := make([][]byte, num)
- for i := 0; i < num; i++ {
- msg := fmt.Sprintf("planet: %d, country: %d, city: %d, street: %d", i, i, i, i)
- messages[i] = []byte(msg)
- }
- return messages
-}
-
-func BenchmarkWriteNoCompression(b *testing.B) {
- w := ioutil.Discard
- c := newConn(fakeNetConn{Reader: nil, Writer: w}, false, 1024, 1024)
- messages := textMessages(100)
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- c.WriteMessage(TextMessage, messages[i%len(messages)])
- }
- b.ReportAllocs()
-}
-
-func BenchmarkWriteWithCompression(b *testing.B) {
- w := ioutil.Discard
- c := newConn(fakeNetConn{Reader: nil, Writer: w}, false, 1024, 1024)
- messages := textMessages(100)
- c.enableWriteCompression = true
- c.newCompressionWriter = compressNoContextTakeover
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- c.WriteMessage(TextMessage, messages[i%len(messages)])
- }
- b.ReportAllocs()
-}
-
-func TestValidCompressionLevel(t *testing.T) {
- c := newConn(fakeNetConn{}, false, 1024, 1024)
- for _, level := range []int{minCompressionLevel - 1, maxCompressionLevel + 1} {
- if err := c.SetCompressionLevel(level); err == nil {
- t.Errorf("no error for level %d", level)
- }
- }
- for _, level := range []int{minCompressionLevel, maxCompressionLevel} {
- if err := c.SetCompressionLevel(level); err != nil {
- t.Errorf("error for level %d", level)
- }
- }
-}
diff --git a/vendor/github.com/gorilla/websocket/conn.go b/vendor/github.com/gorilla/websocket/conn.go
index 97e1dbacb..ce7f0a615 100644
--- a/vendor/github.com/gorilla/websocket/conn.go
+++ b/vendor/github.com/gorilla/websocket/conn.go
@@ -10,7 +10,6 @@ import (
"errors"
"io"
"io/ioutil"
- "math/rand"
"net"
"strconv"
"sync"
@@ -181,11 +180,6 @@ var (
errInvalidControlFrame = errors.New("websocket: invalid control frame")
)
-func newMaskKey() [4]byte {
- n := rand.Uint32()
- return [4]byte{byte(n), byte(n >> 8), byte(n >> 16), byte(n >> 24)}
-}
-
func hideTempErr(err error) error {
if e, ok := err.(net.Error); ok && e.Temporary() {
err = &netError{msg: e.Error(), timeout: e.Timeout()}
@@ -241,11 +235,9 @@ type Conn struct {
writeErr error
enableWriteCompression bool
- compressionLevel int
- newCompressionWriter func(io.WriteCloser, int) io.WriteCloser
+ newCompressionWriter func(io.WriteCloser) (io.WriteCloser, error)
// Read fields
- reader io.ReadCloser // the current reader returned to the application
readErr error
br *bufio.Reader
readRemaining int64 // bytes remaining in current frame.
@@ -261,76 +253,31 @@ type Conn struct {
messageReader *messageReader // the current low-level reader
readDecompress bool // whether last read frame had RSV1 set
- newDecompressionReader func(io.Reader) io.ReadCloser
+ newDecompressionReader func(io.Reader) io.Reader
}
func newConn(conn net.Conn, isServer bool, readBufferSize, writeBufferSize int) *Conn {
- return newConnBRW(conn, isServer, readBufferSize, writeBufferSize, nil)
-}
-
-type writeHook struct {
- p []byte
-}
-
-func (wh *writeHook) Write(p []byte) (int, error) {
- wh.p = p
- return len(p), nil
-}
-
-func newConnBRW(conn net.Conn, isServer bool, readBufferSize, writeBufferSize int, brw *bufio.ReadWriter) *Conn {
mu := make(chan bool, 1)
mu <- true
- var br *bufio.Reader
- if readBufferSize == 0 && brw != nil && brw.Reader != nil {
- // Reuse the supplied bufio.Reader if the buffer has a useful size.
- // This code assumes that peek on a reader returns
- // bufio.Reader.buf[:0].
- brw.Reader.Reset(conn)
- if p, err := brw.Reader.Peek(0); err == nil && cap(p) >= 256 {
- br = brw.Reader
- }
+ if readBufferSize == 0 {
+ readBufferSize = defaultReadBufferSize
}
- if br == nil {
- if readBufferSize == 0 {
- readBufferSize = defaultReadBufferSize
- }
- if readBufferSize < maxControlFramePayloadSize {
- readBufferSize = maxControlFramePayloadSize
- }
- br = bufio.NewReaderSize(conn, readBufferSize)
- }
-
- var writeBuf []byte
- if writeBufferSize == 0 && brw != nil && brw.Writer != nil {
- // Use the bufio.Writer's buffer if the buffer has a useful size. This
- // code assumes that bufio.Writer.buf[:1] is passed to the
- // bufio.Writer's underlying writer.
- var wh writeHook
- brw.Writer.Reset(&wh)
- brw.Writer.WriteByte(0)
- brw.Flush()
- if cap(wh.p) >= maxFrameHeaderSize+256 {
- writeBuf = wh.p[:cap(wh.p)]
- }
+ if readBufferSize < maxControlFramePayloadSize {
+ readBufferSize = maxControlFramePayloadSize
}
-
- if writeBuf == nil {
- if writeBufferSize == 0 {
- writeBufferSize = defaultWriteBufferSize
- }
- writeBuf = make([]byte, writeBufferSize+maxFrameHeaderSize)
+ if writeBufferSize == 0 {
+ writeBufferSize = defaultWriteBufferSize
}
c := &Conn{
isServer: isServer,
- br: br,
+ br: bufio.NewReaderSize(conn, readBufferSize),
conn: conn,
mu: mu,
readFinal: true,
- writeBuf: writeBuf,
+ writeBuf: make([]byte, writeBufferSize+maxFrameHeaderSize),
enableWriteCompression: true,
- compressionLevel: defaultCompressionLevel,
}
c.SetCloseHandler(nil)
c.SetPingHandler(nil)
@@ -496,7 +443,11 @@ func (c *Conn) NextWriter(messageType int) (io.WriteCloser, error) {
}
c.writer = mw
if c.newCompressionWriter != nil && c.enableWriteCompression && isData(messageType) {
- w := c.newCompressionWriter(c.writer, c.compressionLevel)
+ w, err := c.newCompressionWriter(c.writer)
+ if err != nil {
+ c.writer = nil
+ return nil, err
+ }
mw.compress = true
c.writer = w
}
@@ -703,33 +654,12 @@ func (w *messageWriter) Close() error {
return nil
}
-// WritePreparedMessage writes prepared message into connection.
-func (c *Conn) WritePreparedMessage(pm *PreparedMessage) error {
- frameType, frameData, err := pm.frame(prepareKey{
- isServer: c.isServer,
- compress: c.newCompressionWriter != nil && c.enableWriteCompression && isData(pm.messageType),
- compressionLevel: c.compressionLevel,
- })
- if err != nil {
- return err
- }
- if c.isWriting {
- panic("concurrent write to websocket connection")
- }
- c.isWriting = true
- err = c.write(frameType, c.writeDeadline, frameData, nil)
- if !c.isWriting {
- panic("concurrent write to websocket connection")
- }
- c.isWriting = false
- return err
-}
-
// WriteMessage is a helper method for getting a writer using NextWriter,
// writing the message and closing the writer.
func (c *Conn) WriteMessage(messageType int, data []byte) error {
if c.isServer && (c.newCompressionWriter == nil || !c.enableWriteCompression) {
+
// Fast path with no allocations and single frame.
if err := c.prepWrite(messageType); err != nil {
@@ -925,11 +855,6 @@ func (c *Conn) handleProtocolError(message string) error {
// permanent. Once this method returns a non-nil error, all subsequent calls to
// this method return the same error.
func (c *Conn) NextReader() (messageType int, r io.Reader, err error) {
- // Close previous reader, only relevant for decompression.
- if c.reader != nil {
- c.reader.Close()
- c.reader = nil
- }
c.messageReader = nil
c.readLength = 0
@@ -942,11 +867,11 @@ func (c *Conn) NextReader() (messageType int, r io.Reader, err error) {
}
if frameType == TextMessage || frameType == BinaryMessage {
c.messageReader = &messageReader{c}
- c.reader = c.messageReader
+ var r io.Reader = c.messageReader
if c.readDecompress {
- c.reader = c.newDecompressionReader(c.reader)
+ r = c.newDecompressionReader(r)
}
- return frameType, c.reader, nil
+ return frameType, r, nil
}
}
@@ -1008,10 +933,6 @@ func (r *messageReader) Read(b []byte) (int, error) {
return 0, err
}
-func (r *messageReader) Close() error {
- return nil
-}
-
// ReadMessage is a helper method for getting a reader using NextReader and
// reading from that reader to a buffer.
func (c *Conn) ReadMessage() (messageType int, p []byte, err error) {
@@ -1048,15 +969,6 @@ func (c *Conn) CloseHandler() func(code int, text string) error {
// The code argument to h is the received close code or CloseNoStatusReceived
// if the close message is empty. The default close handler sends a close frame
// back to the peer.
-//
-// The application must read the connection to process close messages as
-// described in the section on Control Frames above.
-//
-// The connection read methods return a CloseError when a close frame is
-// received. Most applications should handle close messages as part of their
-// normal error handling. Applications should only set a close handler when the
-// application must perform some action before sending a close frame back to
-// the peer.
func (c *Conn) SetCloseHandler(h func(code int, text string) error) {
if h == nil {
h = func(code int, text string) error {
@@ -1079,9 +991,6 @@ func (c *Conn) PingHandler() func(appData string) error {
// SetPingHandler sets the handler for ping messages received from the peer.
// The appData argument to h is the PING frame application data. The default
// ping handler sends a pong to the peer.
-//
-// The application must read the connection to process ping messages as
-// described in the section on Control Frames above.
func (c *Conn) SetPingHandler(h func(appData string) error) {
if h == nil {
h = func(message string) error {
@@ -1105,9 +1014,6 @@ func (c *Conn) PongHandler() func(appData string) error {
// SetPongHandler sets the handler for pong messages received from the peer.
// The appData argument to h is the PONG frame application data. The default
// pong handler does nothing.
-//
-// The application must read the connection to process ping messages as
-// described in the section on Control Frames above.
func (c *Conn) SetPongHandler(h func(appData string) error) {
if h == nil {
h = func(string) error { return nil }
@@ -1128,18 +1034,6 @@ func (c *Conn) EnableWriteCompression(enable bool) {
c.enableWriteCompression = enable
}
-// SetCompressionLevel sets the flate compression level for subsequent text and
-// binary messages. This function is a noop if compression was not negotiated
-// with the peer. See the compress/flate package for a description of
-// compression levels.
-func (c *Conn) SetCompressionLevel(level int) error {
- if !isValidCompressionLevel(level) {
- return errors.New("websocket: invalid compression level")
- }
- c.compressionLevel = level
- return nil
-}
-
// FormatCloseMessage formats closeCode and text as a WebSocket close message.
func FormatCloseMessage(closeCode int, text string) []byte {
buf := make([]byte, 2+len(text))
diff --git a/vendor/github.com/gorilla/websocket/conn_broadcast_test.go b/vendor/github.com/gorilla/websocket/conn_broadcast_test.go
deleted file mode 100644
index 45038e488..000000000
--- a/vendor/github.com/gorilla/websocket/conn_broadcast_test.go
+++ /dev/null
@@ -1,134 +0,0 @@
-// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build go1.7
-
-package websocket
-
-import (
- "io"
- "io/ioutil"
- "sync/atomic"
- "testing"
-)
-
-// broadcastBench allows to run broadcast benchmarks.
-// In every broadcast benchmark we create many connections, then send the same
-// message into every connection and wait for all writes complete. This emulates
-// an application where many connections listen to the same data - i.e. PUB/SUB
-// scenarios with many subscribers in one channel.
-type broadcastBench struct {
- w io.Writer
- message *broadcastMessage
- closeCh chan struct{}
- doneCh chan struct{}
- count int32
- conns []*broadcastConn
- compression bool
- usePrepared bool
-}
-
-type broadcastMessage struct {
- payload []byte
- prepared *PreparedMessage
-}
-
-type broadcastConn struct {
- conn *Conn
- msgCh chan *broadcastMessage
-}
-
-func newBroadcastConn(c *Conn) *broadcastConn {
- return &broadcastConn{
- conn: c,
- msgCh: make(chan *broadcastMessage, 1),
- }
-}
-
-func newBroadcastBench(usePrepared, compression bool) *broadcastBench {
- bench := &broadcastBench{
- w: ioutil.Discard,
- doneCh: make(chan struct{}),
- closeCh: make(chan struct{}),
- usePrepared: usePrepared,
- compression: compression,
- }
- msg := &broadcastMessage{
- payload: textMessages(1)[0],
- }
- if usePrepared {
- pm, _ := NewPreparedMessage(TextMessage, msg.payload)
- msg.prepared = pm
- }
- bench.message = msg
- bench.makeConns(10000)
- return bench
-}
-
-func (b *broadcastBench) makeConns(numConns int) {
- conns := make([]*broadcastConn, numConns)
-
- for i := 0; i < numConns; i++ {
- c := newConn(fakeNetConn{Reader: nil, Writer: b.w}, true, 1024, 1024)
- if b.compression {
- c.enableWriteCompression = true
- c.newCompressionWriter = compressNoContextTakeover
- }
- conns[i] = newBroadcastConn(c)
- go func(c *broadcastConn) {
- for {
- select {
- case msg := <-c.msgCh:
- if b.usePrepared {
- c.conn.WritePreparedMessage(msg.prepared)
- } else {
- c.conn.WriteMessage(TextMessage, msg.payload)
- }
- val := atomic.AddInt32(&b.count, 1)
- if val%int32(numConns) == 0 {
- b.doneCh <- struct{}{}
- }
- case <-b.closeCh:
- return
- }
- }
- }(conns[i])
- }
- b.conns = conns
-}
-
-func (b *broadcastBench) close() {
- close(b.closeCh)
-}
-
-func (b *broadcastBench) runOnce() {
- for _, c := range b.conns {
- c.msgCh <- b.message
- }
- <-b.doneCh
-}
-
-func BenchmarkBroadcast(b *testing.B) {
- benchmarks := []struct {
- name string
- usePrepared bool
- compression bool
- }{
- {"NoCompression", false, false},
- {"WithCompression", false, true},
- {"NoCompressionPrepared", true, false},
- {"WithCompressionPrepared", true, true},
- }
- for _, bm := range benchmarks {
- b.Run(bm.name, func(b *testing.B) {
- bench := newBroadcastBench(bm.usePrepared, bm.compression)
- defer bench.close()
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- bench.runOnce()
- }
- b.ReportAllocs()
- })
- }
-}
diff --git a/vendor/github.com/gorilla/websocket/conn_test.go b/vendor/github.com/gorilla/websocket/conn_test.go
index 06e9bc3f5..7431383b1 100644
--- a/vendor/github.com/gorilla/websocket/conn_test.go
+++ b/vendor/github.com/gorilla/websocket/conn_test.go
@@ -463,35 +463,3 @@ func TestFailedConnectionReadPanic(t *testing.T) {
}
t.Fatal("should not get here")
}
-
-func TestBufioReuse(t *testing.T) {
- brw := bufio.NewReadWriter(bufio.NewReader(nil), bufio.NewWriter(nil))
- c := newConnBRW(nil, false, 0, 0, brw)
-
- if c.br != brw.Reader {
- t.Error("connection did not reuse bufio.Reader")
- }
-
- var wh writeHook
- brw.Writer.Reset(&wh)
- brw.WriteByte(0)
- brw.Flush()
- if &c.writeBuf[0] != &wh.p[0] {
- t.Error("connection did not reuse bufio.Writer")
- }
-
- brw = bufio.NewReadWriter(bufio.NewReaderSize(nil, 0), bufio.NewWriterSize(nil, 0))
- c = newConnBRW(nil, false, 0, 0, brw)
-
- if c.br == brw.Reader {
- t.Error("connection used bufio.Reader with small size")
- }
-
- brw.Writer.Reset(&wh)
- brw.WriteByte(0)
- brw.Flush()
- if &c.writeBuf[0] != &wh.p[0] {
- t.Error("connection used bufio.Writer with small size")
- }
-
-}
diff --git a/vendor/github.com/gorilla/websocket/doc.go b/vendor/github.com/gorilla/websocket/doc.go
index e291a952c..610acf712 100644
--- a/vendor/github.com/gorilla/websocket/doc.go
+++ b/vendor/github.com/gorilla/websocket/doc.go
@@ -118,10 +118,9 @@
//
// Applications are responsible for ensuring that no more than one goroutine
// calls the write methods (NextWriter, SetWriteDeadline, WriteMessage,
-// WriteJSON, EnableWriteCompression, SetCompressionLevel) concurrently and
-// that no more than one goroutine calls the read methods (NextReader,
-// SetReadDeadline, ReadMessage, ReadJSON, SetPongHandler, SetPingHandler)
-// concurrently.
+// WriteJSON) concurrently and that no more than one goroutine calls the read
+// methods (NextReader, SetReadDeadline, ReadMessage, ReadJSON, SetPongHandler,
+// SetPingHandler) concurrently.
//
// The Close and WriteControl methods can be called concurrently with all other
// methods.
@@ -151,25 +150,19 @@
// application's responsibility to check the Origin header before calling
// Upgrade.
//
-// Compression EXPERIMENTAL
+// Compression [Experimental]
//
// Per message compression extensions (RFC 7692) are experimentally supported
// by this package in a limited capacity. Setting the EnableCompression option
// to true in Dialer or Upgrader will attempt to negotiate per message deflate
-// support.
-//
-// var upgrader = websocket.Upgrader{
-// EnableCompression: true,
-// }
-//
-// If compression was successfully negotiated with the connection's peer, any
-// message received in compressed form will be automatically decompressed.
-// All Read methods will return uncompressed bytes.
+// support. If compression was successfully negotiated with the connection's
+// peer, any message received in compressed form will be automatically
+// decompressed. All Read methods will return uncompressed bytes.
//
// Per message compression of messages written to a connection can be enabled
// or disabled by calling the corresponding Conn method:
//
-// conn.EnableWriteCompression(false)
+// conn.EnableWriteCompression(true)
//
// Currently this package does not support compression with "context takeover".
// This means that messages must be compressed and decompressed in isolation,
diff --git a/vendor/github.com/gorilla/websocket/examples/autobahn/fuzzingclient.json b/vendor/github.com/gorilla/websocket/examples/autobahn/fuzzingclient.json
index aa3a0bc0a..27d5a5b14 100644
--- a/vendor/github.com/gorilla/websocket/examples/autobahn/fuzzingclient.json
+++ b/vendor/github.com/gorilla/websocket/examples/autobahn/fuzzingclient.json
@@ -4,7 +4,6 @@
"outdir": "./reports/clients",
"servers": [
{"agent": "ReadAllWriteMessage", "url": "ws://localhost:9000/m", "options": {"version": 18}},
- {"agent": "ReadAllWritePreparedMessage", "url": "ws://localhost:9000/p", "options": {"version": 18}},
{"agent": "ReadAllWrite", "url": "ws://localhost:9000/r", "options": {"version": 18}},
{"agent": "CopyFull", "url": "ws://localhost:9000/f", "options": {"version": 18}},
{"agent": "CopyWriterOnly", "url": "ws://localhost:9000/c", "options": {"version": 18}}
diff --git a/vendor/github.com/gorilla/websocket/examples/autobahn/server.go b/vendor/github.com/gorilla/websocket/examples/autobahn/server.go
index 3db880f90..e98563be9 100644
--- a/vendor/github.com/gorilla/websocket/examples/autobahn/server.go
+++ b/vendor/github.com/gorilla/websocket/examples/autobahn/server.go
@@ -85,7 +85,7 @@ func echoCopyFull(w http.ResponseWriter, r *http.Request) {
// echoReadAll echoes messages from the client by reading the entire message
// with ioutil.ReadAll.
-func echoReadAll(w http.ResponseWriter, r *http.Request, writeMessage, writePrepared bool) {
+func echoReadAll(w http.ResponseWriter, r *http.Request, writeMessage bool) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println("Upgrade:", err)
@@ -109,21 +109,9 @@ func echoReadAll(w http.ResponseWriter, r *http.Request, writeMessage, writePrep
}
}
if writeMessage {
- if !writePrepared {
- err = conn.WriteMessage(mt, b)
- if err != nil {
- log.Println("WriteMessage:", err)
- }
- } else {
- pm, err := websocket.NewPreparedMessage(mt, b)
- if err != nil {
- log.Println("NewPreparedMessage:", err)
- return
- }
- err = conn.WritePreparedMessage(pm)
- if err != nil {
- log.Println("WritePreparedMessage:", err)
- }
+ err = conn.WriteMessage(mt, b)
+ if err != nil {
+ log.Println("WriteMessage:", err)
}
} else {
w, err := conn.NextWriter(mt)
@@ -144,15 +132,11 @@ func echoReadAll(w http.ResponseWriter, r *http.Request, writeMessage, writePrep
}
func echoReadAllWriter(w http.ResponseWriter, r *http.Request) {
- echoReadAll(w, r, false, false)
+ echoReadAll(w, r, false)
}
func echoReadAllWriteMessage(w http.ResponseWriter, r *http.Request) {
- echoReadAll(w, r, true, false)
-}
-
-func echoReadAllWritePreparedMessage(w http.ResponseWriter, r *http.Request) {
- echoReadAll(w, r, true, true)
+ echoReadAll(w, r, true)
}
func serveHome(w http.ResponseWriter, r *http.Request) {
@@ -177,7 +161,6 @@ func main() {
http.HandleFunc("/f", echoCopyFull)
http.HandleFunc("/r", echoReadAllWriter)
http.HandleFunc("/m", echoReadAllWriteMessage)
- http.HandleFunc("/p", echoReadAllWritePreparedMessage)
err := http.ListenAndServe(*addr, nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
diff --git a/vendor/github.com/gorilla/websocket/examples/chat/home.html b/vendor/github.com/gorilla/websocket/examples/chat/home.html
index a39a0c276..7262918ec 100644
--- a/vendor/github.com/gorilla/websocket/examples/chat/home.html
+++ b/vendor/github.com/gorilla/websocket/examples/chat/home.html
@@ -9,7 +9,7 @@ window.onload = function () {
var log = document.getElementById("log");
function appendLog(item) {
- var doScroll = log.scrollTop > log.scrollHeight - log.clientHeight - 1;
+ var doScroll = log.scrollTop === log.scrollHeight - log.clientHeight;
log.appendChild(item);
if (doScroll) {
log.scrollTop = log.scrollHeight - log.clientHeight;
@@ -29,7 +29,7 @@ window.onload = function () {
};
if (window["WebSocket"]) {
- conn = new WebSocket("ws://" + document.location.host + "/ws");
+ conn = new WebSocket("ws://{{$}}/ws");
conn.onclose = function (evt) {
var item = document.createElement("div");
item.innerHTML = "<b>Connection closed.</b>";
diff --git a/vendor/github.com/gorilla/websocket/examples/chat/main.go b/vendor/github.com/gorilla/websocket/examples/chat/main.go
index 74615d59c..a865ffec5 100644
--- a/vendor/github.com/gorilla/websocket/examples/chat/main.go
+++ b/vendor/github.com/gorilla/websocket/examples/chat/main.go
@@ -8,9 +8,11 @@ import (
"flag"
"log"
"net/http"
+ "text/template"
)
var addr = flag.String("addr", ":8080", "http service address")
+var homeTemplate = template.Must(template.ParseFiles("home.html"))
func serveHome(w http.ResponseWriter, r *http.Request) {
log.Println(r.URL)
@@ -22,7 +24,8 @@ func serveHome(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Method not allowed", 405)
return
}
- http.ServeFile(w, r, "home.html")
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ homeTemplate.Execute(w, r.Host)
}
func main() {
diff --git a/vendor/github.com/gorilla/websocket/examples/command/README.md b/vendor/github.com/gorilla/websocket/examples/command/README.md
index ed6f78684..c30d3979a 100644
--- a/vendor/github.com/gorilla/websocket/examples/command/README.md
+++ b/vendor/github.com/gorilla/websocket/examples/command/README.md
@@ -2,7 +2,7 @@
This example connects a websocket connection to stdin and stdout of a command.
Received messages are written to stdin followed by a `\n`. Each line read from
-standard out is sent as a message to the client.
+from standard out is sent as a message to the client.
$ go get github.com/gorilla/websocket
$ cd `go list -f '{{.Dir}}' github.com/gorilla/websocket/examples/command`
diff --git a/vendor/github.com/gorilla/websocket/examples/command/home.html b/vendor/github.com/gorilla/websocket/examples/command/home.html
index 19c46128a..72fd02b2a 100644
--- a/vendor/github.com/gorilla/websocket/examples/command/home.html
+++ b/vendor/github.com/gorilla/websocket/examples/command/home.html
@@ -2,53 +2,47 @@
<html lang="en">
<head>
<title>Command Example</title>
+<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript">
-window.onload = function () {
+ $(function() {
+
var conn;
- var msg = document.getElementById("msg");
- var log = document.getElementById("log");
+ var msg = $("#msg");
+ var log = $("#log");
- function appendLog(item) {
- var doScroll = log.scrollTop > log.scrollHeight - log.clientHeight - 1;
- log.appendChild(item);
+ function appendLog(msg) {
+ var d = log[0]
+ var doScroll = d.scrollTop == d.scrollHeight - d.clientHeight;
+ msg.appendTo(log)
if (doScroll) {
- log.scrollTop = log.scrollHeight - log.clientHeight;
+ d.scrollTop = d.scrollHeight - d.clientHeight;
}
}
- document.getElementById("form").onsubmit = function () {
+ $("#form").submit(function() {
if (!conn) {
return false;
}
- if (!msg.value) {
+ if (!msg.val()) {
return false;
}
- conn.send(msg.value);
- msg.value = "";
- return false;
- };
+ conn.send(msg.val());
+ msg.val("");
+ return false
+ });
if (window["WebSocket"]) {
- conn = new WebSocket("ws://" + document.location.host + "/ws");
- conn.onclose = function (evt) {
- var item = document.createElement("div");
- item.innerHTML = "<b>Connection closed.</b>";
- appendLog(item);
- };
- conn.onmessage = function (evt) {
- var messages = evt.data.split('\n');
- for (var i = 0; i < messages.length; i++) {
- var item = document.createElement("div");
- item.innerText = messages[i];
- appendLog(item);
- }
- };
+ conn = new WebSocket("ws://{{$}}/ws");
+ conn.onclose = function(evt) {
+ appendLog($("<div><b>Connection closed.</b></div>"))
+ }
+ conn.onmessage = function(evt) {
+ appendLog($("<pre/>").text(evt.data))
+ }
} else {
- var item = document.createElement("div");
- item.innerHTML = "<b>Your browser does not support WebSockets.</b>";
- appendLog(item);
+ appendLog($("<div><b>Your browser does not support WebSockets.</b></div>"))
}
-};
+ });
</script>
<style type="text/css">
html {
diff --git a/vendor/github.com/gorilla/websocket/examples/command/main.go b/vendor/github.com/gorilla/websocket/examples/command/main.go
index 239c5c85c..438fb8328 100644
--- a/vendor/github.com/gorilla/websocket/examples/command/main.go
+++ b/vendor/github.com/gorilla/websocket/examples/command/main.go
@@ -12,14 +12,16 @@ import (
"net/http"
"os"
"os/exec"
+ "text/template"
"time"
"github.com/gorilla/websocket"
)
var (
- addr = flag.String("addr", "127.0.0.1:8080", "http service address")
- cmdPath string
+ addr = flag.String("addr", "127.0.0.1:8080", "http service address")
+ cmdPath string
+ homeTempl = template.Must(template.ParseFiles("home.html"))
)
const (
@@ -174,7 +176,8 @@ func serveHome(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Method not allowed", 405)
return
}
- http.ServeFile(w, r, "home.html")
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ homeTempl.Execute(w, r.Host)
}
func main() {
diff --git a/vendor/github.com/gorilla/websocket/examples/filewatch/main.go b/vendor/github.com/gorilla/websocket/examples/filewatch/main.go
index f5f9da5c3..2ac2b324f 100644
--- a/vendor/github.com/gorilla/websocket/examples/filewatch/main.go
+++ b/vendor/github.com/gorilla/websocket/examples/filewatch/main.go
@@ -6,12 +6,12 @@ package main
import (
"flag"
- "html/template"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
+ "text/template"
"time"
"github.com/gorilla/websocket"
diff --git a/vendor/github.com/gorilla/websocket/mask.go b/vendor/github.com/gorilla/websocket/mask.go
index 6a88bbc74..6758a2cb7 100644
--- a/vendor/github.com/gorilla/websocket/mask.go
+++ b/vendor/github.com/gorilla/websocket/mask.go
@@ -2,14 +2,20 @@
// this source code is governed by a BSD-style license that can be found in the
// LICENSE file.
-// +build !appengine
-
package websocket
-import "unsafe"
+import (
+ "math/rand"
+ "unsafe"
+)
const wordSize = int(unsafe.Sizeof(uintptr(0)))
+func newMaskKey() [4]byte {
+ n := rand.Uint32()
+ return [4]byte{byte(n), byte(n >> 8), byte(n >> 16), byte(n >> 24)}
+}
+
func maskBytes(key [4]byte, pos int, b []byte) int {
// Mask one byte at a time for small buffers.
diff --git a/vendor/github.com/gorilla/websocket/mask_safe.go b/vendor/github.com/gorilla/websocket/mask_safe.go
deleted file mode 100644
index 2aac060e5..000000000
--- a/vendor/github.com/gorilla/websocket/mask_safe.go
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of
-// this source code is governed by a BSD-style license that can be found in the
-// LICENSE file.
-
-// +build appengine
-
-package websocket
-
-func maskBytes(key [4]byte, pos int, b []byte) int {
- for i := range b {
- b[i] ^= key[pos&3]
- pos++
- }
- return pos & 3
-}
diff --git a/vendor/github.com/gorilla/websocket/mask_test.go b/vendor/github.com/gorilla/websocket/mask_test.go
index 298a1e509..de0602993 100644
--- a/vendor/github.com/gorilla/websocket/mask_test.go
+++ b/vendor/github.com/gorilla/websocket/mask_test.go
@@ -3,7 +3,7 @@
// LICENSE file.
// Require 1.7 for sub-bencmarks
-// +build go1.7,!appengine
+// +build go1.7
package websocket
diff --git a/vendor/github.com/gorilla/websocket/prepared.go b/vendor/github.com/gorilla/websocket/prepared.go
deleted file mode 100644
index 1efffbd1e..000000000
--- a/vendor/github.com/gorilla/websocket/prepared.go
+++ /dev/null
@@ -1,103 +0,0 @@
-// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package websocket
-
-import (
- "bytes"
- "net"
- "sync"
- "time"
-)
-
-// PreparedMessage caches on the wire representations of a message payload.
-// Use PreparedMessage to efficiently send a message payload to multiple
-// connections. PreparedMessage is especially useful when compression is used
-// because the CPU and memory expensive compression operation can be executed
-// once for a given set of compression options.
-type PreparedMessage struct {
- messageType int
- data []byte
- err error
- mu sync.Mutex
- frames map[prepareKey]*preparedFrame
-}
-
-// prepareKey defines a unique set of options to cache prepared frames in PreparedMessage.
-type prepareKey struct {
- isServer bool
- compress bool
- compressionLevel int
-}
-
-// preparedFrame contains data in wire representation.
-type preparedFrame struct {
- once sync.Once
- data []byte
-}
-
-// NewPreparedMessage returns an initialized PreparedMessage. You can then send
-// it to connection using WritePreparedMessage method. Valid wire
-// representation will be calculated lazily only once for a set of current
-// connection options.
-func NewPreparedMessage(messageType int, data []byte) (*PreparedMessage, error) {
- pm := &PreparedMessage{
- messageType: messageType,
- frames: make(map[prepareKey]*preparedFrame),
- data: data,
- }
-
- // Prepare a plain server frame.
- _, frameData, err := pm.frame(prepareKey{isServer: true, compress: false})
- if err != nil {
- return nil, err
- }
-
- // To protect against caller modifying the data argument, remember the data
- // copied to the plain server frame.
- pm.data = frameData[len(frameData)-len(data):]
- return pm, nil
-}
-
-func (pm *PreparedMessage) frame(key prepareKey) (int, []byte, error) {
- pm.mu.Lock()
- frame, ok := pm.frames[key]
- if !ok {
- frame = &preparedFrame{}
- pm.frames[key] = frame
- }
- pm.mu.Unlock()
-
- var err error
- frame.once.Do(func() {
- // Prepare a frame using a 'fake' connection.
- // TODO: Refactor code in conn.go to allow more direct construction of
- // the frame.
- mu := make(chan bool, 1)
- mu <- true
- var nc prepareConn
- c := &Conn{
- conn: &nc,
- mu: mu,
- isServer: key.isServer,
- compressionLevel: key.compressionLevel,
- enableWriteCompression: true,
- writeBuf: make([]byte, defaultWriteBufferSize+maxFrameHeaderSize),
- }
- if key.compress {
- c.newCompressionWriter = compressNoContextTakeover
- }
- err = c.WriteMessage(pm.messageType, pm.data)
- frame.data = nc.buf.Bytes()
- })
- return pm.messageType, frame.data, err
-}
-
-type prepareConn struct {
- buf bytes.Buffer
- net.Conn
-}
-
-func (pc *prepareConn) Write(p []byte) (int, error) { return pc.buf.Write(p) }
-func (pc *prepareConn) SetWriteDeadline(t time.Time) error { return nil }
diff --git a/vendor/github.com/gorilla/websocket/prepared_test.go b/vendor/github.com/gorilla/websocket/prepared_test.go
deleted file mode 100644
index cf98c6c10..000000000
--- a/vendor/github.com/gorilla/websocket/prepared_test.go
+++ /dev/null
@@ -1,74 +0,0 @@
-// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package websocket
-
-import (
- "bytes"
- "compress/flate"
- "math/rand"
- "testing"
-)
-
-var preparedMessageTests = []struct {
- messageType int
- isServer bool
- enableWriteCompression bool
- compressionLevel int
-}{
- // Server
- {TextMessage, true, false, flate.BestSpeed},
- {TextMessage, true, true, flate.BestSpeed},
- {TextMessage, true, true, flate.BestCompression},
- {PingMessage, true, false, flate.BestSpeed},
- {PingMessage, true, true, flate.BestSpeed},
-
- // Client
- {TextMessage, false, false, flate.BestSpeed},
- {TextMessage, false, true, flate.BestSpeed},
- {TextMessage, false, true, flate.BestCompression},
- {PingMessage, false, false, flate.BestSpeed},
- {PingMessage, false, true, flate.BestSpeed},
-}
-
-func TestPreparedMessage(t *testing.T) {
- for _, tt := range preparedMessageTests {
- var data = []byte("this is a test")
- var buf bytes.Buffer
- c := newConn(fakeNetConn{Reader: nil, Writer: &buf}, tt.isServer, 1024, 1024)
- if tt.enableWriteCompression {
- c.newCompressionWriter = compressNoContextTakeover
- }
- c.SetCompressionLevel(tt.compressionLevel)
-
- // Seed random number generator for consistent frame mask.
- rand.Seed(1234)
-
- if err := c.WriteMessage(tt.messageType, data); err != nil {
- t.Fatal(err)
- }
- want := buf.String()
-
- pm, err := NewPreparedMessage(tt.messageType, data)
- if err != nil {
- t.Fatal(err)
- }
-
- // Scribble on data to ensure that NewPreparedMessage takes a snapshot.
- copy(data, "hello world")
-
- // Seed random number generator for consistent frame mask.
- rand.Seed(1234)
-
- buf.Reset()
- if err := c.WritePreparedMessage(pm); err != nil {
- t.Fatal(err)
- }
- got := buf.String()
-
- if got != want {
- t.Errorf("write message != prepared message for %+v", tt)
- }
- }
-}
diff --git a/vendor/github.com/gorilla/websocket/server.go b/vendor/github.com/gorilla/websocket/server.go
index 3495e0f1a..aaedebdbe 100644
--- a/vendor/github.com/gorilla/websocket/server.go
+++ b/vendor/github.com/gorilla/websocket/server.go
@@ -28,9 +28,8 @@ type Upgrader struct {
HandshakeTimeout time.Duration
// ReadBufferSize and WriteBufferSize specify I/O buffer sizes. If a buffer
- // size is zero, then buffers allocated by the HTTP server are used. The
- // I/O buffer sizes do not limit the size of the messages that can be sent
- // or received.
+ // size is zero, then a default value of 4096 is used. The I/O buffer sizes
+ // do not limit the size of the messages that can be sent or received.
ReadBufferSize, WriteBufferSize int
// Subprotocols specifies the server's supported protocols in order of
@@ -105,23 +104,23 @@ func (u *Upgrader) selectSubprotocol(r *http.Request, responseHeader http.Header
// response.
func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) {
if r.Method != "GET" {
- return u.returnError(w, r, http.StatusMethodNotAllowed, "websocket: not a websocket handshake: request method is not GET")
+ return u.returnError(w, r, http.StatusMethodNotAllowed, "websocket: method not GET")
}
if _, ok := responseHeader["Sec-Websocket-Extensions"]; ok {
- return u.returnError(w, r, http.StatusInternalServerError, "websocket: application specific 'Sec-Websocket-Extensions' headers are unsupported")
+ return u.returnError(w, r, http.StatusInternalServerError, "websocket: application specific Sec-Websocket-Extensions headers are unsupported")
}
- if !tokenListContainsValue(r.Header, "Connection", "upgrade") {
- return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: 'upgrade' token not found in 'Connection' header")
+ if !tokenListContainsValue(r.Header, "Sec-Websocket-Version", "13") {
+ return u.returnError(w, r, http.StatusBadRequest, "websocket: version != 13")
}
- if !tokenListContainsValue(r.Header, "Upgrade", "websocket") {
- return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: 'websocket' token not found in 'Upgrade' header")
+ if !tokenListContainsValue(r.Header, "Connection", "upgrade") {
+ return u.returnError(w, r, http.StatusBadRequest, "websocket: could not find connection header with token 'upgrade'")
}
- if !tokenListContainsValue(r.Header, "Sec-Websocket-Version", "13") {
- return u.returnError(w, r, http.StatusBadRequest, "websocket: unsupported version: 13 not found in 'Sec-Websocket-Version' header")
+ if !tokenListContainsValue(r.Header, "Upgrade", "websocket") {
+ return u.returnError(w, r, http.StatusBadRequest, "websocket: could not find upgrade header with token 'websocket'")
}
checkOrigin := u.CheckOrigin
@@ -129,12 +128,12 @@ func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeade
checkOrigin = checkSameOrigin
}
if !checkOrigin(r) {
- return u.returnError(w, r, http.StatusForbidden, "websocket: 'Origin' header value not allowed")
+ return u.returnError(w, r, http.StatusForbidden, "websocket: origin not allowed")
}
challengeKey := r.Header.Get("Sec-Websocket-Key")
if challengeKey == "" {
- return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: `Sec-Websocket-Key' header is missing or blank")
+ return u.returnError(w, r, http.StatusBadRequest, "websocket: key missing or blank")
}
subprotocol := u.selectSubprotocol(r, responseHeader)
@@ -153,6 +152,7 @@ func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeade
var (
netConn net.Conn
+ br *bufio.Reader
err error
)
@@ -160,18 +160,19 @@ func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeade
if !ok {
return u.returnError(w, r, http.StatusInternalServerError, "websocket: response does not implement http.Hijacker")
}
- var brw *bufio.ReadWriter
- netConn, brw, err = h.Hijack()
+ var rw *bufio.ReadWriter
+ netConn, rw, err = h.Hijack()
if err != nil {
return u.returnError(w, r, http.StatusInternalServerError, err.Error())
}
+ br = rw.Reader
- if brw.Reader.Buffered() > 0 {
+ if br.Buffered() > 0 {
netConn.Close()
return nil, errors.New("websocket: client sent data before handshake is complete")
}
- c := newConnBRW(netConn, true, u.ReadBufferSize, u.WriteBufferSize, brw)
+ c := newConn(netConn, true, u.ReadBufferSize, u.WriteBufferSize)
c.subprotocol = subprotocol
if compress {
diff --git a/vendor/github.com/hashicorp/go-sockaddr/Makefile b/vendor/github.com/hashicorp/go-sockaddr/GNUmakefile
index 224135dc1..f3dfd24cf 100644
--- a/vendor/github.com/hashicorp/go-sockaddr/Makefile
+++ b/vendor/github.com/hashicorp/go-sockaddr/GNUmakefile
@@ -2,6 +2,8 @@ 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
@@ -9,10 +11,10 @@ test:: $(GOCOVER_FILE)
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)"
+ @${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)
+ @${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)
@@ -41,15 +43,15 @@ clean::
dev::
@go build
- @make -B -C cmd/sockaddr sockaddr
+ @$(MAKE) -B -C cmd/sockaddr sockaddr
install::
@go install
- @make -C cmd/sockaddr install
+ @$(MAKE) -C cmd/sockaddr install
doc::
- echo Visit: http://127.0.0.1:6060/pkg/github.com/hashicorp/go-sockaddr/
- godoc -http=:6060 -goroot $GOROOT
+ @echo Visit: http://127.0.0.1:6161/pkg/github.com/hashicorp/go-sockaddr/
+ godoc -http=:6161 -goroot $GOROOT
world::
@set -e; \
@@ -60,4 +62,4 @@ world::
done; \
done
- make -C cmd/sockaddr world
+ $(MAKE) -C cmd/sockaddr world
diff --git a/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/GNUmakefile b/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/GNUmakefile
index 90232d2f0..6d0039ae5 100644
--- a/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/GNUmakefile
+++ b/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/GNUmakefile
@@ -21,7 +21,7 @@ install:: $(BIN)
.PHONY: test
test:: $(BIN)
- @make -C regression
+ @$(MAKE) -C regression
.PHONY: world
world::
diff --git a/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/README.md b/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/README.md
index cc247afb5..e9914ffc1 100644
--- a/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/README.md
+++ b/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/README.md
@@ -119,7 +119,7 @@ Options:
Here are a few impractical examples to get you started:
```text
-$ sockaddr eval 'GetDefaultInterfaces | sort "type,size" | include "RFC" "6890" | attr "address"'
+$ sockaddr eval 'GetAllInterfaces | include "flags" "forwardable" | include "up" | sort "default,type,size" | include "RFC" "6890" | attr "address"'
172.14.6.167
$ sockaddr eval 'GetDefaultInterfaces | sort "type,size" | include "RFC" "6890" | limit 1 | join "address" " "'
172.14.6.167
@@ -133,7 +133,7 @@ $ sockaddr eval 'GetAllInterfaces | include "network" "172.14.6.0/24" | attr "ad
172.14.6.167
$ sockaddr eval 'GetPrivateInterfaces | join "type" " "'
IPv4 IPv6
-$ sockaddr eval 'GetPublicInterfaces | include "flags" "up|forwardable" | join "address" " "'
+$ sockaddr eval 'GetAllInterfaces | include "flags" "forwardable" | join "address" " "'
203.0.113.4 2001:0DB8::1
$ sockaddr eval 'GetAllInterfaces | include "name" "lo0" | include "type" "IPv6" | sort "address" | join "address" " "'
100:: fe80::1
@@ -147,6 +147,11 @@ $ cat <<'EOF' | sockaddr eval -
{{. | include "name" "lo0" | include "type" "IPv6" | sort "address" | join "address" " "}}
EOF
100:: fe80::1
+$ sockaddr eval 'GetPrivateInterfaces | include "flags" "forwardable|up" | include "type" "IPv4" | math "network" "+2" | attr "address"'
+172.14.6.2
+$ cat <<'EOF' | sudo tee -a /etc/profile
+export CONSUL_HTTP_ADDR="http://`sockaddr eval 'GetInterfaceIP \"eth0\"'`:8500"
+EOF
```
## `sockaddr rfc`
diff --git a/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/regression/expected/sockaddr.out b/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/regression/expected/sockaddr.out
index b836500e5..858f1516e 100644
--- a/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/regression/expected/sockaddr.out
+++ b/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/regression/expected/sockaddr.out
@@ -1,4 +1,4 @@
-usage: sockaddr [--version] [--help] <command> [<args>]
+Usage: sockaddr [--version] [--help] <command> [<args>]
Available commands are:
dump Parses input as an IP or interface name(s) and dumps various information
diff --git a/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/regression/expected/sockaddr_rfc-00.out b/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/regression/expected/sockaddr_rfc-00.out
index d638c462a..82f4f4e13 100644
--- a/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/regression/expected/sockaddr_rfc-00.out
+++ b/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/regression/expected/sockaddr_rfc-00.out
@@ -10,6 +10,4 @@ Options:
-s Silent, only return different exit codes
Subcommands:
-
list Lists all known RFCs
-
diff --git a/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/regression/expected/sockaddr_rfc-01.out b/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/regression/expected/sockaddr_rfc-01.out
index 555d039c8..82f4f4e13 100644
--- a/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/regression/expected/sockaddr_rfc-01.out
+++ b/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/regression/expected/sockaddr_rfc-01.out
@@ -8,3 +8,6 @@ Usage: sockaddr rfc [RFC Number] [IP Address]
Options:
-s Silent, only return different exit codes
+
+Subcommands:
+ list Lists all known RFCs
diff --git a/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/regression/run_all.sh b/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/regression/run_all.sh
index 4b6d8a746..9fa39ee9e 100755
--- a/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/regression/run_all.sh
+++ b/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/regression/run_all.sh
@@ -1,11 +1,13 @@
#!/bin/sh --
+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`
set -e
set -u
num_cpus=$(getconf NPROCESSORS_ONLN)
set +e
-find . -name 'test_*.sh' -depth 1 | xargs -n1 -P${num_cpus} ./run_one.sh
+${FIND} . -maxdepth 1 -name 'test_*.sh' -print0 | ${XARGS} -0 -n1 -P${num_cpus} ./run_one.sh
set -e
# rune_one.sh generates the .diff files
diff --git a/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/vendor/github.com/mitchellh/cli/README.md b/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/vendor/github.com/mitchellh/cli/README.md
index 1f69ccb20..dd211cf0e 100644
--- a/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/vendor/github.com/mitchellh/cli/README.md
+++ b/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/vendor/github.com/mitchellh/cli/README.md
@@ -5,6 +5,7 @@ cli is the library that powers the CLI for
[Packer](https://github.com/mitchellh/packer),
[Serf](https://github.com/hashicorp/serf),
[Consul](https://github.com/hashicorp/consul),
+[Vault](https://github.com/hashicorp/vault),
[Terraform](https://github.com/hashicorp/terraform), and
[Nomad](https://github.com/hashicorp/nomad).
diff --git a/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/vendor/github.com/mitchellh/cli/cli.go b/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/vendor/github.com/mitchellh/cli/cli.go
index 353edb6c2..4a69d176d 100644
--- a/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/vendor/github.com/mitchellh/cli/cli.go
+++ b/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/vendor/github.com/mitchellh/cli/cli.go
@@ -120,7 +120,13 @@ func (c *CLI) Run() (int, error) {
// Just show the version and exit if instructed.
if c.IsVersion() && c.Version != "" {
c.HelpWriter.Write([]byte(c.Version + "\n"))
- return 1, nil
+ return 0, nil
+ }
+
+ // Just print the help when only '-h' or '--help' is passed.
+ if c.IsHelp() && c.Subcommand() == "" {
+ c.HelpWriter.Write([]byte(c.HelpFunc(c.Commands) + "\n"))
+ return 0, nil
}
// Attempt to get the factory function for creating the command
@@ -133,13 +139,13 @@ func (c *CLI) Run() (int, error) {
command, err := raw.(CommandFactory)()
if err != nil {
- return 0, err
+ return 1, err
}
// If we've been instructed to just print the help, then print it
if c.IsHelp() {
c.commandHelp(command)
- return 1, nil
+ return 0, nil
}
// If there is an invalid flag, then error
@@ -454,7 +460,7 @@ const defaultHelpTemplate = `
{{.Help}}{{if gt (len .Subcommands) 0}}
Subcommands:
-{{ range $value := .Subcommands }}
+{{- range $value := .Subcommands }}
{{ $value.NameAligned }} {{ $value.Synopsis }}{{ end }}
-{{ end }}
+{{- end }}
`
diff --git a/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/vendor/vendor.json b/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/vendor/vendor.json
index 7514b1ac4..cc56af3f9 100644
--- a/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/vendor/vendor.json
+++ b/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/vendor/vendor.json
@@ -27,10 +27,10 @@
"revisionTime": "2016-08-06T12:27:52Z"
},
{
- "checksumSHA1": "W6WsJ7dtBT0coA3S5FpGR0k4IEU=",
+ "checksumSHA1": "UP+pXl+ic9y6qrpZA5MqDIAuGfw=",
"path": "github.com/mitchellh/cli",
- "revision": "494eb006fe29e9dc75fea6da4df4818f7e046b73",
- "revisionTime": "2017-02-08T07:23:55Z"
+ "revision": "ee8578a9c12a5bb9d55303b9665cc448772c81b8",
+ "revisionTime": "2017-03-28T05:23:52Z"
},
{
"checksumSHA1": "L3leymg2RT8hFl5uL+5KP/LpBkg=",
diff --git a/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/version.go b/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/version.go
index 32cac2d47..10da3e698 100644
--- a/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/version.go
+++ b/vendor/github.com/hashicorp/go-sockaddr/cmd/sockaddr/version.go
@@ -12,7 +12,7 @@ var (
)
// The main version number that is being run at the moment.
-const Version = "0.1.0"
+const Version = "0.2.0"
// A pre-release marker for the version. If this is "" (empty string)
// then it means that it is a final release. Otherwise, this is a pre-release
diff --git a/vendor/github.com/hashicorp/go-sockaddr/ifaddr.go b/vendor/github.com/hashicorp/go-sockaddr/ifaddr.go
index 3e4ff9fca..0811b2759 100644
--- a/vendor/github.com/hashicorp/go-sockaddr/ifaddr.go
+++ b/vendor/github.com/hashicorp/go-sockaddr/ifaddr.go
@@ -1,5 +1,7 @@
package sockaddr
+import "strings"
+
// ifAddrAttrMap is a map of the IfAddr type-specific attributes.
var ifAddrAttrMap map[AttrName]func(IfAddr) string
var ifAddrAttrs []AttrName
@@ -30,6 +32,53 @@ func GetPrivateIP() (string, error) {
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.
@@ -51,6 +100,47 @@ func GetPublicIP() (string, error) {
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:
@@ -91,6 +181,44 @@ func GetInterfaceIP(namedIfRE string) (string, error) {
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" <<ARG>> | 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
diff --git a/vendor/github.com/hashicorp/go-sockaddr/ifaddr_test.go b/vendor/github.com/hashicorp/go-sockaddr/ifaddr_test.go
index 9737ef35c..859c3e421 100644
--- a/vendor/github.com/hashicorp/go-sockaddr/ifaddr_test.go
+++ b/vendor/github.com/hashicorp/go-sockaddr/ifaddr_test.go
@@ -45,6 +45,42 @@ func havePublicIP() bool {
return boolEnvVar("SOCKADDR_HAVE_PUBLIC_IP", false)
}
+func TestGetPrivateIP(t *testing.T) {
+ reportOnPrivate := func(args ...interface{}) {
+ if havePrivateIP() {
+ t.Fatalf(args[0].(string), args[1:]...)
+ } else {
+ t.Skipf(args[0].(string), args[1:]...)
+ }
+ }
+ ip, err := sockaddr.GetPrivateIP()
+ if err != nil {
+ reportOnPrivate("unable to get a private IP: %v", err)
+ }
+
+ if ip == "" {
+ reportOnPrivate("it's hard to test this reliably")
+ }
+}
+
+func TestGetPrivateIPs(t *testing.T) {
+ reportOnPrivate := func(args ...interface{}) {
+ if havePrivateIP() {
+ t.Fatalf(args[0].(string), args[1:]...)
+ } else {
+ t.Skipf(args[0].(string), args[1:]...)
+ }
+ }
+ ips, err := sockaddr.GetPrivateIPs()
+ if err != nil {
+ reportOnPrivate("unable to get a private IPs: %v", err)
+ }
+
+ if ips == "" {
+ reportOnPrivate("it's hard to test this reliably")
+ }
+}
+
func TestGetPublicIP(t *testing.T) {
reportOnPublic := func(args ...interface{}) {
if havePublicIP() {
@@ -63,6 +99,24 @@ func TestGetPublicIP(t *testing.T) {
}
}
+func TestGetPublicIPs(t *testing.T) {
+ reportOnPublic := func(args ...interface{}) {
+ if havePublicIP() {
+ t.Fatalf(args[0].(string), args[1:]...)
+ } else {
+ t.Skipf(args[0].(string), args[1:]...)
+ }
+ }
+ ips, err := sockaddr.GetPublicIPs()
+ if err != nil {
+ reportOnPublic("unable to get a public IPs: %v", err)
+ }
+
+ if ips == "" {
+ reportOnPublic("it's hard to test this reliably")
+ }
+}
+
func TestGetInterfaceIP(t *testing.T) {
ip, err := sockaddr.GetInterfaceIP(`^.*[\d]$`)
if err != nil {
@@ -98,7 +152,7 @@ func TestIfAddrAttr(t *testing.T) {
t.Fatalf("test %d must have a name", i)
}
- result, err := sockaddr.IfAttr(test.attr, sockaddr.IfAddrs{test.ifAddr})
+ result, err := sockaddr.IfAttr(test.attr, test.ifAddr)
if err != nil {
t.Errorf("failed to get attr %q from %v", test.name, test.ifAddr)
}
@@ -107,14 +161,317 @@ func TestIfAddrAttr(t *testing.T) {
t.Errorf("unexpected result")
}
}
+}
- // Test an empty array
- result, err := sockaddr.IfAttr("name", sockaddr.IfAddrs{})
- if err != nil {
- t.Error(`failed to get attr "name" from an empty array`)
+func TestIfAddrMath(t *testing.T) {
+ tests := []struct {
+ name string
+ ifAddr sockaddr.IfAddr
+ operation string
+ value string
+ expected string
+ wantFail bool
+ }{
+ {
+ name: "ipv4 address +2",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("127.0.0.1/8"),
+ },
+ operation: "address",
+ value: "+2",
+ expected: "127.0.0.3/8",
+ },
+ {
+ name: "ipv4 address -2",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("127.0.0.1/8"),
+ },
+ operation: "address",
+ value: "-2",
+ expected: "126.255.255.255/8",
+ },
+ {
+ name: "ipv4 address + overflow 0xff00ff03",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("127.0.0.1/8"),
+ },
+ operation: "address",
+ value: fmt.Sprintf("+%d", 0xff00ff03),
+ expected: "126.0.255.4/8",
+ },
+ {
+ name: "ipv4 address - underflow 0xff00ff04",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("127.0.0.1/8"),
+ },
+ operation: "address",
+ value: fmt.Sprintf("-%d", 0xff00ff04),
+ expected: "127.255.0.253/8",
+ },
+ {
+ name: "ipv6 address +2",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv6Addr("::1/128"),
+ },
+ operation: "address",
+ value: "+2",
+ expected: "::3",
+ },
+ {
+ name: "ipv6 address -3",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv6Addr("::4/128"),
+ },
+ operation: "address",
+ value: "-3",
+ expected: "::1",
+ },
+ {
+ name: "ipv6 address + overflow",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv6Addr("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128"),
+ },
+ operation: "address",
+ value: fmt.Sprintf("+%d", 0x03),
+ expected: "::2",
+ },
+ {
+ name: "ipv6 address + underflow",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv6Addr("::1/128"),
+ },
+ operation: "address",
+ value: fmt.Sprintf("-%d", 0x03),
+ expected: "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe",
+ },
+ {
+ name: "ipv4 network +2",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("127.0.0.1/8"),
+ },
+ operation: "network",
+ value: "+2",
+ expected: "127.0.0.2/8",
+ },
+ {
+ name: "ipv4 network -2",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("127.0.0.1/8"),
+ },
+ operation: "network",
+ value: "-2",
+ expected: "127.255.255.254/8",
+ },
+ {
+ // Value exceeds /8
+ name: "ipv4 network + overflow 0xff00ff03",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("127.0.0.1/8"),
+ },
+ operation: "network",
+ value: fmt.Sprintf("+%d", 0xff00ff03),
+ expected: "127.0.255.3/8",
+ },
+ {
+ // Value exceeds /8
+ name: "ipv4 network - underflow+wrap 0xff00ff04",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("127.0.0.1/8"),
+ },
+ operation: "network",
+ value: fmt.Sprintf("-%d", 0xff00ff04),
+ expected: "127.255.0.252/8",
+ },
+ {
+ name: "ipv6 network +6",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv6Addr("fe80::1/64"),
+ },
+ operation: "network",
+ value: "+6",
+ expected: "fe80::6/64",
+ },
+ {
+ name: "ipv6 network -6",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv6Addr("fe80::ff/64"),
+ },
+ operation: "network",
+ value: "-6",
+ expected: "fe80::ffff:ffff:ffff:fffa/64",
+ },
+ {
+ // Value exceeds /104 mask
+ name: "ipv6 network + overflow 0xff00ff03",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv6Addr("fe80::1/104"),
+ },
+ operation: "network",
+ value: fmt.Sprintf("+%d", 0xff00ff03),
+ expected: "fe80::ff03/104",
+ },
+ {
+ // Value exceeds /104
+ name: "ipv6 network - underflow+wrap 0xff00ff04",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv6Addr("fe80::1/104"),
+ },
+ operation: "network",
+ value: fmt.Sprintf("-%d", 0xff00ff04),
+ expected: "fe80::ff:fc/104",
+ },
+ {
+ name: "ipv4 address missing sign",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("127.0.0.1/8"),
+ },
+ operation: "address",
+ value: "123",
+ wantFail: true,
+ },
+ {
+ name: "ipv4 network missing sign",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("127.0.0.1/8"),
+ },
+ operation: "network",
+ value: "123",
+ wantFail: true,
+ },
+ {
+ name: "ipv6 address missing sign",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv6Addr("::1/128"),
+ },
+ operation: "address",
+ value: "123",
+ wantFail: true,
+ },
+ {
+ name: "ipv6 network missing sign",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv6Addr("::1/128"),
+ },
+ operation: "network",
+ value: "123",
+ wantFail: true,
+ },
+ {
+ name: "ipv4 address bad value",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("127.0.0.1/8"),
+ },
+ operation: "address",
+ value: "+xyz",
+ wantFail: true,
+ },
+ {
+ name: "ipv4 network bad value",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("127.0.0.1/8"),
+ },
+ operation: "network",
+ value: "-xyz",
+ wantFail: true,
+ },
+ {
+ name: "ipv6 address bad value",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv6Addr("::1/128"),
+ },
+ operation: "address",
+ value: "+xyz",
+ wantFail: true,
+ },
+ {
+ name: "ipv6 network bad value",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv6Addr("::1/128"),
+ },
+ operation: "network",
+ value: "-xyz",
+ wantFail: true,
+ },
+ {
+ name: "ipv4 bad operation",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("127.0.0.1/8"),
+ },
+ operation: "gooz",
+ value: "+xyz",
+ wantFail: true,
+ },
+ {
+ name: "ipv6 bad operation",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv6Addr("::1/128"),
+ },
+ operation: "frabba",
+ value: "+xyz",
+ wantFail: true,
+ },
+ {
+ name: "unix unsupported operation",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustUnixSock("/tmp/bar"),
+ },
+ operation: "address",
+ value: "+123",
+ wantFail: true,
+ },
+ {
+ name: "unix unsupported operation",
+ ifAddr: sockaddr.IfAddr{
+ SockAddr: sockaddr.MustUnixSock("/tmp/foo"),
+ },
+ operation: "network",
+ value: "+123",
+ wantFail: true,
+ },
}
- if result != "" {
- t.Errorf("unexpected result")
+ for i, test := range tests {
+ if test.name == "" {
+ t.Fatalf("test %d must have a name", i)
+ }
+
+ results, err := sockaddr.IfAddrsMath(test.operation, test.value, sockaddr.IfAddrs{test.ifAddr})
+ if test.wantFail {
+ if err != nil {
+ continue
+ } else {
+ t.Fatalf("%s: failed to fail math operation %q with value %q on %v", test.name, test.operation, test.value, test.ifAddr)
+ }
+ } else if err != nil {
+ t.Fatalf("%s: failed to compute math operation %q with value %q on %v", test.name, test.operation, test.value, test.ifAddr)
+ }
+ if len(results) != 1 {
+ t.Fatalf("%s: bad", test.name)
+ }
+
+ result := results[0]
+
+ switch saType := result.Type(); saType {
+ case sockaddr.TypeIPv4:
+ ipv4 := sockaddr.ToIPv4Addr(result.SockAddr)
+ if ipv4 == nil {
+ t.Fatalf("bad: %T %+#v", result, result)
+ }
+
+ if got := ipv4.String(); got != test.expected {
+ t.Errorf("unexpected result %q: want %q got %q", test.name, test.expected, got)
+ }
+ case sockaddr.TypeIPv6:
+ ipv6 := sockaddr.ToIPv6Addr(result.SockAddr)
+ if ipv6 == nil {
+ t.Fatalf("bad: %T %+#v", result, result)
+ }
+
+ if got := ipv6.String(); got != test.expected {
+ t.Errorf("unexpected result %q: want %q got %q", test.name, test.expected, got)
+ }
+ default:
+ t.Fatalf("bad")
+ }
}
}
diff --git a/vendor/github.com/hashicorp/go-sockaddr/ifaddrs.go b/vendor/github.com/hashicorp/go-sockaddr/ifaddrs.go
index 8233be202..b87589a22 100644
--- a/vendor/github.com/hashicorp/go-sockaddr/ifaddrs.go
+++ b/vendor/github.com/hashicorp/go-sockaddr/ifaddrs.go
@@ -3,6 +3,7 @@ package sockaddr
import (
"errors"
"fmt"
+ "math/big"
"net"
"regexp"
"sort"
@@ -10,6 +11,14 @@ import (
"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 adapter ([^\s:]+):`)
+ ipAddrRE *regexp.Regexp = regexp.MustCompile(`^ IPv[46] Address\. \. \. \. \. \. \. \. \. \. \. : ([^\s]+)`)
+)
+
// IfAddrs is a slice of IfAddr
type IfAddrs []IfAddr
@@ -91,6 +100,40 @@ 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)
@@ -127,6 +170,11 @@ 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)
@@ -169,7 +217,15 @@ func FilterIfByType(ifAddrs IfAddrs, type_ SockAddrType) (matchedIfs, excludedIf
// 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, ifAddrs IfAddrs) (string, error) {
+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
}
@@ -243,10 +299,10 @@ func GetDefaultInterfaces() (IfAddrs, error) {
// the `eval` equivalent of:
//
// ```
-// $ sockaddr eval -r '{{GetDefaultInterfaces | include "type" "ip" | include "flags" "forwardable|up" | sort "type,size" | include "RFC" "6890" }}'
+// $ 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 := GetDefaultInterfaces()
+ privateIfs, err := GetAllInterfaces()
if err != nil {
return IfAddrs{}, err
}
@@ -259,15 +315,21 @@ func GetPrivateInterfaces() (IfAddrs, error) {
return IfAddrs{}, nil
}
- privateIfs, _, err = IfByFlag("forwardable|up", privateIfs)
+ 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(AscIfType, AscIfNetworkSize).Sort(privateIfs)
+ OrderedIfAddrBy(AscIfDefault, AscIfType, AscIfNetworkSize).Sort(privateIfs)
privateIfs, _, err = IfByRFC("6890", privateIfs)
if err != nil {
@@ -285,10 +347,10 @@ func GetPrivateInterfaces() (IfAddrs, error) {
// function is the `eval` equivalent of:
//
// ```
-// $ sockaddr eval -r '{{GetDefaultInterfaces | include "type" "ip" | include "flags" "forwardable|up" | sort "type,size" | exclude "RFC" "6890" }}'
+// $ 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 := GetDefaultInterfaces()
+ publicIfs, err := GetAllInterfaces()
if err != nil {
return IfAddrs{}, err
}
@@ -301,15 +363,21 @@ func GetPublicInterfaces() (IfAddrs, error) {
return IfAddrs{}, nil
}
- publicIfs, _, err = IfByFlag("forwardable|up", publicIfs)
+ 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(AscIfType, AscIfNetworkSize).Sort(publicIfs)
+ OrderedIfAddrBy(AscIfDefault, AscIfType, AscIfNetworkSize).Sort(publicIfs)
_, publicIfs, err = IfByRFC("6890", publicIfs)
if err != nil {
@@ -652,6 +720,171 @@ func IfByNetwork(selectorParam string, inputIfAddrs IfAddrs) (IfAddrs, IfAddrs,
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)
+ }
+ 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
@@ -736,6 +969,10 @@ func SortIfBy(selectorParam string, inputIfAddrs IfAddrs) (IfAddrs, error) {
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.
@@ -886,7 +1123,7 @@ func parseDefaultIfNameFromRoute(routeOut string) (string, error) {
// Linux.
func parseDefaultIfNameFromIPCmd(routeOut string) (string, error) {
lines := strings.Split(routeOut, "\n")
- re := regexp.MustCompile(`[\s]+`)
+ re := whitespaceRE.Copy()
for _, line := range lines {
kvs := re.Split(line, -1)
if len(kvs) < 5 {
@@ -929,7 +1166,7 @@ func parseDefaultIfNameWindows(routeOut, ipconfigOut string) (string, error) {
// support added.
func parseDefaultIPAddrWindowsRoute(routeOut string) (string, error) {
lines := strings.Split(routeOut, "\n")
- re := regexp.MustCompile(`[\s]+`)
+ re := whitespaceRE.Copy()
for _, line := range lines {
kvs := re.Split(strings.TrimSpace(line), -1)
if len(kvs) < 3 {
@@ -949,17 +1186,17 @@ func parseDefaultIPAddrWindowsRoute(routeOut string) (string, error) {
// interface name forwarding traffic to the default gateway.
func parseDefaultIfNameWindowsIPConfig(defaultIPAddr, routeOut string) (string, error) {
lines := strings.Split(routeOut, "\n")
- ifNameRE := regexp.MustCompile(`^Ethernet adapter ([^\s:]+):`)
- ipAddrRE := regexp.MustCompile(`^ IPv[46] Address\. \. \. \. \. \. \. \. \. \. \. : ([^\s]+)`)
+ ifNameRe := ifNameRE.Copy()
+ ipAddrRe := ipAddrRE.Copy()
var ifName string
for _, line := range lines {
- switch ifNameMatches := ifNameRE.FindStringSubmatch(line); {
+ switch ifNameMatches := ifNameRe.FindStringSubmatch(line); {
case len(ifNameMatches) > 1:
ifName = ifNameMatches[1]
continue
}
- switch ipAddrMatches := ipAddrRE.FindStringSubmatch(line); {
+ switch ipAddrMatches := ipAddrRe.FindStringSubmatch(line); {
case len(ipAddrMatches) > 1 && ipAddrMatches[1] == defaultIPAddr:
return ifName, nil
}
diff --git a/vendor/github.com/hashicorp/go-sockaddr/ifaddrs_test.go b/vendor/github.com/hashicorp/go-sockaddr/ifaddrs_test.go
index e89dae1ef..aed847808 100644
--- a/vendor/github.com/hashicorp/go-sockaddr/ifaddrs_test.go
+++ b/vendor/github.com/hashicorp/go-sockaddr/ifaddrs_test.go
@@ -9,6 +9,13 @@ import (
sockaddr "github.com/hashicorp/go-sockaddr"
)
+const (
+ // NOTE(seanc@): Assume "en0" is the interface with a default route attached
+ // to it. When this is not the case, change this one constant and tests
+ // should pass (i.e. "net0").
+ ifNameWithDefault = "en0"
+)
+
// NOTE: A number of these code paths are exercised in template/ and
// cmd/sockaddr/.
//
@@ -690,30 +697,54 @@ func TestGetDefaultInterface(t *testing.T) {
}
}
-func TestGetPrivateIP(t *testing.T) {
- reportOnPrivate := func(args ...interface{}) {
- if havePrivateIP() {
- t.Fatalf(args[0].(string), args[1:]...)
- } else {
- t.Skipf(args[0].(string), args[1:]...)
- }
+func TestIfAddrAttrs(t *testing.T) {
+ const expectedNumAttrs = 2
+ attrs := sockaddr.IfAddrAttrs()
+ if len(attrs) != expectedNumAttrs {
+ t.Fatalf("wrong number of attrs")
}
- ip, err := sockaddr.GetPrivateIP()
- if err != nil {
- reportOnPrivate("private IP failed: %v", err)
+ tests := []struct {
+ name string
+ ifAddr sockaddr.IfAddr
+ attr string
+ expected string
+ }{
+ {
+ name: "name",
+ ifAddr: sockaddr.IfAddr{
+ Interface: net.Interface{
+ Name: "abc0",
+ },
+ },
+ attr: "name",
+ expected: "abc0",
+ },
}
- if len(ip) == 0 {
- reportOnPrivate("no private IP found", nil)
+ for i, test := range tests {
+ if test.name == "" {
+ t.Fatalf("test %d must have a name", i)
+ }
+
+ result, err := sockaddr.IfAttrs(test.attr, sockaddr.IfAddrs{test.ifAddr})
+ if err != nil {
+ t.Errorf("failed to get attr %q from %v", test.name, test.ifAddr)
+ }
+
+ if result != test.expected {
+ t.Errorf("unexpected result")
+ }
}
-}
-func TestIfAddrAttrs(t *testing.T) {
- const expectedNumAttrs = 2
- attrs := sockaddr.IfAddrAttrs()
- if len(attrs) != expectedNumAttrs {
- t.Fatalf("wrong number of attrs")
+ // Test an empty array
+ result, err := sockaddr.IfAttrs("name", sockaddr.IfAddrs{})
+ if err != nil {
+ t.Error(`failed to get attr "name" from an empty array`)
+ }
+
+ if result != "" {
+ t.Errorf("unexpected result")
}
}
@@ -788,7 +819,7 @@ func TestGetPrivateInterfaces(t *testing.T) {
}
if len(ifAddrs) == 0 {
- reportOnPrivate("no public IPs found", nil)
+ reportOnPrivate("no public IPs found")
}
if len(ifAddrs[0].String()) == 0 {
@@ -1669,6 +1700,82 @@ func TestSortIfBy(t *testing.T) {
},
},
{
+ // NOTE(seanc@): This test requires macOS, or at least a computer where
+ // en0 has the default route.
+ name: "sort default",
+ sortStr: "default",
+ in: sockaddr.IfAddrs{
+ sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("1.2.3.4"),
+ Interface: net.Interface{Name: ifNameWithDefault},
+ },
+ sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("1.2.3.3"),
+ Interface: net.Interface{Name: "other0"},
+ },
+ },
+ out: sockaddr.IfAddrs{
+ sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("1.2.3.4"),
+ Interface: net.Interface{Name: ifNameWithDefault},
+ },
+ sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("1.2.3.3"),
+ Interface: net.Interface{Name: "other0"},
+ },
+ },
+ },
+ {
+ // NOTE(seanc@): This test requires macOS, or at least a computer where
+ // en0 has the default route.
+ name: "sort +default",
+ sortStr: "+default",
+ in: sockaddr.IfAddrs{
+ sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("1.2.3.4"),
+ Interface: net.Interface{Name: "other0"},
+ },
+ sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("1.2.3.3"),
+ Interface: net.Interface{Name: ifNameWithDefault},
+ },
+ },
+ out: sockaddr.IfAddrs{
+ sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("1.2.3.3"),
+ Interface: net.Interface{Name: ifNameWithDefault},
+ },
+ sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("1.2.3.4"),
+ Interface: net.Interface{Name: "other0"},
+ },
+ },
+ },
+ {
+ name: "sort -default",
+ sortStr: "-default",
+ in: sockaddr.IfAddrs{
+ sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("1.2.3.3"),
+ Interface: net.Interface{Name: ifNameWithDefault},
+ },
+ sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("1.2.3.4"),
+ Interface: net.Interface{Name: "other0"},
+ },
+ },
+ out: sockaddr.IfAddrs{
+ sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("1.2.3.4"),
+ Interface: net.Interface{Name: "other0"},
+ },
+ sockaddr.IfAddr{
+ SockAddr: sockaddr.MustIPv4Addr("1.2.3.3"),
+ Interface: net.Interface{Name: ifNameWithDefault},
+ },
+ },
+ },
+ {
name: "sort name",
sortStr: "name",
in: sockaddr.IfAddrs{
@@ -1877,5 +1984,4 @@ func TestSortIfBy(t *testing.T) {
}
})
}
-
}
diff --git a/vendor/github.com/hashicorp/go-sockaddr/ipv4addr.go b/vendor/github.com/hashicorp/go-sockaddr/ipv4addr.go
index 9f2616a69..4d395dc95 100644
--- a/vendor/github.com/hashicorp/go-sockaddr/ipv4addr.go
+++ b/vendor/github.com/hashicorp/go-sockaddr/ipv4addr.go
@@ -58,7 +58,8 @@ 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.
- if match := trailingHexNetmaskRE.FindStringIndex(ipv4Str); match != nil {
+ trailingHexNetmaskRe := trailingHexNetmaskRE.Copy()
+ if match := trailingHexNetmaskRe.FindStringIndex(ipv4Str); match != nil {
ipv4Str = ipv4Str[:match[0]]
}
diff --git a/vendor/github.com/hashicorp/go-sockaddr/rfc.go b/vendor/github.com/hashicorp/go-sockaddr/rfc.go
index fd9be940b..02e188f6f 100644
--- a/vendor/github.com/hashicorp/go-sockaddr/rfc.go
+++ b/vendor/github.com/hashicorp/go-sockaddr/rfc.go
@@ -3,6 +3,7 @@ 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 {
diff --git a/vendor/github.com/hashicorp/go-sockaddr/template/Makefile b/vendor/github.com/hashicorp/go-sockaddr/template/GNUmakefile
index ce1e274e4..ce1e274e4 100644
--- a/vendor/github.com/hashicorp/go-sockaddr/template/Makefile
+++ b/vendor/github.com/hashicorp/go-sockaddr/template/GNUmakefile
diff --git a/vendor/github.com/hashicorp/go-sockaddr/template/doc.go b/vendor/github.com/hashicorp/go-sockaddr/template/doc.go
index 59945d7be..90c8784a3 100644
--- a/vendor/github.com/hashicorp/go-sockaddr/template/doc.go
+++ b/vendor/github.com/hashicorp/go-sockaddr/template/doc.go
@@ -53,23 +53,22 @@ Example:
{{ GetDefaultInterfaces }}
`GetPrivateInterfaces` - Returns one IfAddr for every forwardable IP address
-that is included in RFC 6890, is attached to the interface with the default
-route, and whose interface is marked as up. NOTE: RFC 6890 is a more exhaustive
-version of RFC1918 because it spans IPv4 and IPv6, however it does permit the
+that is included in RFC 6890 and whose interface is marked as up. NOTE: RFC 6890 is a more exhaustive
+version of RFC1918 because it spans IPv4 and IPv6, however, RFC6890 does permit the
inclusion of likely undesired addresses such as multicast, therefore our version
of "private" also filters out non-forwardable addresses.
Example:
- {{ GetPrivateInterfaces | include "flags" "up" }}
+ {{ GetPrivateInterfaces | sort "default" | join "address" " " }}
-`GetPublicInterfaces` - Returns a list of IfAddr that do not match RFC 6890, is
-attached to the default route, and whose interface is marked as up.
+`GetPublicInterfaces` - Returns a list of IfAddr structs whos IPs are
+forwardable, do not match RFC 6890, and whose interface is marked up.
Example:
- {{ GetPublicInterfaces | include "flags" "up" }}
+ {{ GetPublicInterfaces | sort "default" | join "name" " " }}
`GetPrivateIP` - Helper function that returns a string of the first IP address
@@ -80,6 +79,14 @@ Example:
{{ GetPrivateIP }}
+`GetPrivateIPs` - Helper function that returns a string of the all private IP
+addresses on the host.
+
+Example:
+
+ {{ GetPrivateIPs }}
+
+
`GetPublicIP` - Helper function that returns a string of the first IP from
GetPublicInterfaces.
@@ -87,12 +94,29 @@ Example:
{{ GetPublicIP }}
+`GetPublicIPs` - Helper function that returns a space-delimited string of the
+all public IP addresses on the host.
+
+Example:
+
+ {{ GetPrivateIPs }}
+
+
`GetInterfaceIP` - Helper function that returns a string of the first IP from
the named interface.
Example:
- {{ GetInterfaceIP }}
+ {{ GetInterfaceIP "en0" }}
+
+
+
+`GetInterfaceIPs` - Helper function that returns a space-delimited list of all
+IPs on a given interface.
+
+Example:
+
+ {{ GetInterfaceIPs "en0" }}
`sort` - Sorts the IfAddrs result based on its arguments. `sort` takes one
@@ -100,6 +124,8 @@ argument, a list of ways to sort its IfAddrs argument. The list of sort
criteria is comma separated (`,`):
- `address`, `+address`: Ascending sort of IfAddrs by Address
- `-address`: Descending sort of IfAddrs by Address
+ - `default`, `+default`: Ascending sort of IfAddrs, IfAddr with a default route first
+ - `-default`: Descending sort of IfAddrs, IfAttr with default route last
- `name`, `+name`: Ascending sort of IfAddrs by lexical ordering of interface name
- `-name`: Descending sort of IfAddrs by lexical ordering of interface name
- `port`, `+port`: Ascending sort of IfAddrs by port number
@@ -116,7 +142,7 @@ criteria is comma separated (`,`):
Example:
- {{ GetPrivateInterfaces | sort "type,size,address" }}
+ {{ GetPrivateInterfaces | sort "default,-type,size,+address" }}
`exclude` and `include`: Filters IfAddrs based on the selector criteria and its
@@ -142,7 +168,7 @@ available filtering criteria is:
Example:
- {{ GetPrivateInterfaces | exclude "type" "IPv6" | include "flag" "up|forwardable" }}
+ {{ GetPrivateInterfaces | exclude "type" "IPv6" }}
`unique`: Removes duplicate entries from the IfAddrs list, assuming the list has
@@ -152,14 +178,14 @@ already been sorted. `unique` only takes one argument:
Example:
- {{ GetPrivateInterfaces | sort "type,address" | unique "name" }}
+ {{ GetAllInterfaces | sort "default,-type,address" | unique "name" }}
`limit`: Reduces the size of the list to the specified value.
Example:
- {{ GetPrivateInterfaces | include "flags" "forwardable|up" | limit 1 }}
+ {{ GetPrivateInterfaces | limit 1 }}
`offset`: Seeks into the list by the specified value. A negative value can be
@@ -167,7 +193,33 @@ used to seek from the end of the list.
Example:
- {{ GetPrivateInterfaces | include "flags" "forwardable|up" | offset "-2" | limit 1 }}
+ {{ GetPrivateInterfaces | offset "-2" | limit 1 }}
+
+
+`math`: Perform a "math" operation on each member of the list and return new
+values. `math` takes two arguments, the attribute to operate on and the
+operation's value.
+
+Supported operations include:
+
+ - `address`: Adds the value, a positive or negative value expressed as a
+ decimal string, to the address. The sign is required. This value is
+ allowed to over or underflow networks (e.g. 127.255.255.255 `"address" "+1"`
+ will return "128.0.0.0"). Addresses will wrap at IPv4 or IPv6 boundaries.
+ - `network`: Add the value, a positive or negative value expressed as a
+ decimal string, to the network address. The sign is required. Positive
+ values are added to the network address. Negative values are subtracted
+ from the network's broadcast address (e.g. 127.0.0.1 `"network" "-1"` will
+ return "127.255.255.255"). Values that overflow the network size will
+ safely wrap.
+
+Example:
+
+ {{ GetPrivateInterfaces | include "type" "IP" | math "address" "+256" | attr "address" }}
+ {{ GetPrivateInterfaces | include "type" "IP" | math "address" "-256" | attr "address" }}
+ {{ GetPrivateInterfaces | include "type" "IP" | math "network" "+2" | attr "address" }}
+ {{ GetPrivateInterfaces | include "type" "IP" | math "network" "-2" | attr "address" }}
+ {{ GetPrivateInterfaces | include "flags" "forwardable|up" | include "type" "IPv4" | math "network" "+2" | attr "address" }}
`attr`: Extracts a single attribute of the first member of the list and returns
@@ -177,7 +229,19 @@ supported attributes.
Example:
- {{ GetPrivateInterfaces | include "flags" "forwardable|up" | attr "address" }}
+ {{ GetAllInterfaces | exclude "flags" "up" | attr "address" }}
+
+
+`Attr`: Extracts a single attribute from an `IfAttr` and in every other way
+performs the same as the `attr`.
+
+Example:
+
+ {{ with $ifAddrs := GetAllInterfaces | include "type" "IP" | sort "+type,+address" -}}
+ {{- range $ifAddrs -}}
+ {{- Attr "address" . }} -- {{ Attr "network" . }}/{{ Attr "size" . -}}
+ {{- end -}}
+ {{- end }}
`join`: Similar to `attr`, `join` extracts all matching attributes of the list
@@ -187,7 +251,7 @@ and returns them as a string joined by the separator, the second argument to
Example:
- {{ GetPrivateInterfaces | include "flags" "forwardable|up" | join "address" " " }}
+ {{ GetAllInterfaces | include "flags" "forwardable" | join "address" " " }}
`exclude` and `include` flags:
@@ -205,7 +269,7 @@ Example:
- `up`: Is the interface up?
-Attributes for `attr` and `join`:
+Attributes for `attr`, `Attr`, and `join`:
SockAddr Type:
- `string`
diff --git a/vendor/github.com/hashicorp/go-sockaddr/template/template.go b/vendor/github.com/hashicorp/go-sockaddr/template/template.go
index ffe467b7f..bbed51361 100644
--- a/vendor/github.com/hashicorp/go-sockaddr/template/template.go
+++ b/vendor/github.com/hashicorp/go-sockaddr/template/template.go
@@ -64,23 +64,53 @@ func init() {
HelperFuncs = template.FuncMap{
// Misc functions that operate on IfAddrs inputs
- "attr": sockaddr.IfAttr,
+ "attr": Attr,
"join": sockaddr.JoinIfAddrs,
"limit": sockaddr.LimitIfAddrs,
"offset": sockaddr.OffsetIfAddrs,
"unique": sockaddr.UniqueIfAddrsBy,
+ // Misc math functions that operate on a single IfAddr input
+ "math": sockaddr.IfAddrsMath,
+
// Return a Private RFC 6890 IP address string that is attached
// to the default route and a forwardable address.
"GetPrivateIP": sockaddr.GetPrivateIP,
+ // Return all Private RFC 6890 IP addresses as a space-delimited string of
+ // IP addresses. Addresses returned do not have to be on the interface with
+ // a default route.
+ "GetPrivateIPs": sockaddr.GetPrivateIPs,
+
// Return a Public RFC 6890 IP address string that is attached
// to the default route and a forwardable address.
"GetPublicIP": sockaddr.GetPublicIP,
+ // Return allPublic RFC 6890 IP addresses as a space-delimited string of IP
+ // addresses. Addresses returned do not have to be on the interface with a
+ // default route.
+ "GetPublicIPs": sockaddr.GetPublicIPs,
+
// Return the first IP address of the named interface, sorted by
// the largest network size.
"GetInterfaceIP": sockaddr.GetInterfaceIP,
+
+ // Return all IP addresses on the named interface, sorted by the largest
+ // network size.
+ "GetInterfaceIPs": sockaddr.GetInterfaceIPs,
+ }
+}
+
+// Attr returns the attribute from the ifAddrRaw argument. If the argument is
+// an IfAddrs, only the first element will be evaluated for resolution.
+func Attr(selectorName string, ifAddrsRaw interface{}) (string, error) {
+ switch v := ifAddrsRaw.(type) {
+ case sockaddr.IfAddr:
+ return sockaddr.IfAttr(selectorName, v)
+ case sockaddr.IfAddrs:
+ return sockaddr.IfAttrs(selectorName, v)
+ default:
+ return "", fmt.Errorf("unable to obtain attribute %s from type %T (%v)", selectorName, ifAddrsRaw, ifAddrsRaw)
}
}
diff --git a/vendor/github.com/hashicorp/go-sockaddr/template/template_test.go b/vendor/github.com/hashicorp/go-sockaddr/template/template_test.go
index 6f2b47828..ec9822e77 100644
--- a/vendor/github.com/hashicorp/go-sockaddr/template/template_test.go
+++ b/vendor/github.com/hashicorp/go-sockaddr/template/template_test.go
@@ -181,6 +181,81 @@ func TestSockAddr_Parse(t *testing.T) {
{{- end -}}`,
output: `true`,
},
+ {
+ name: "math address +",
+ input: `{{GetAllInterfaces | include "name" "^lo0$" | include "type" "IP" | math "address" "+2" | sort "+type,+address" | join "address" " " }}`,
+ output: `127.0.0.3 ::3 fe80::3`,
+ },
+ {
+ name: "math address + overflow",
+ input: `|{{- with $ifAddrs := GetAllInterfaces | include "name" "^lo0$" | include "type" "IP" | math "address" "+16777217" | sort "+type,+address" -}}
+ {{- range $ifAddrs -}}
+ {{- attr "address" . }} -- {{ attr "network" . }}/{{ attr "size" . }}|{{ end -}}
+{{- end -}}`,
+ output: `|128.0.0.2 -- 128.0.0.0/16777216|::100:2 -- ::100:2/1|fe80::100:2 -- fe80::/18446744073709551616|`,
+ },
+ {
+ name: "math address + overflow+wrap",
+ input: `{{GetAllInterfaces | include "name" "^lo0$" | include "type" "IP" | math "address" "+4294967294" | sort "+type,+address" | join "address" " " }}`,
+ output: `126.255.255.255 ::ffff:ffff fe80::ffff:ffff`,
+ },
+ {
+ name: "math address -",
+ input: `{{GetAllInterfaces | include "name" "^lo0$" | include "type" "IP" | math "address" "-256" | sort "+type,+address" | join "address" " " }}`,
+ output: `126.255.255.1 fe7f:ffff:ffff:ffff:ffff:ffff:ffff:ff01 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff01`,
+ },
+ {
+ name: "math address - underflow",
+ input: `{{GetAllInterfaces | include "name" "^lo0$" | include "type" "IP" | math "address" "-4278190082" | sort "+type,+address" | join "address" " " }}`,
+ output: `127.255.255.255 fe7f:ffff:ffff:ffff:ffff:ffff:ff:ffff ffff:ffff:ffff:ffff:ffff:ffff:ff:ffff`,
+ },
+ {
+ // Note to readers: lo0's link-local address (::1) address has a mask of
+ // /128 which means its value never changes and this is expected. lo0's
+ // site-local address has a /64 address and is expected to change.
+ name: "math network",
+ input: `{{GetAllInterfaces | include "name" "^lo0$" | include "type" "IP" | math "network" "+2" | sort "+type,+address" | join "address" " " }}`,
+ output: `127.0.0.2 ::1 fe80::2`,
+ },
+ {
+ // Assume an IPv4 input of 127.0.0.1. With a value of 0xff00ff01, we wrap once on purpose.
+ name: "math network + wrap",
+ input: `{{GetAllInterfaces | include "name" "^lo0$" | include "type" "IP" | math "network" "+4278255368" | sort "+type,+address" | join "address" " " }}`,
+ output: `127.0.255.8 ::1 fe80::ff00:ff08`,
+ },
+ {
+ name: "math network -",
+ input: `{{GetAllInterfaces | include "name" "^lo0$" | include "type" "IP" | math "network" "-2" | sort "+type,+address" | join "address" " " }}`,
+ output: `127.255.255.254 ::1 fe80::ffff:ffff:ffff:fffe`,
+ },
+ {
+ // Assume an IPv4 input of 127.0.0.1. With a value of 0xff000008 it
+ // should wrap and underflow by 8. Assume an IPv6 input of ::1. With a
+ // value of -0xff000008 the value underflows and wraps.
+ name: "math network - underflow+wrap",
+ input: `{{GetAllInterfaces | include "name" "^lo0$" | include "type" "IP" | sort "+type,+address" | math "network" "-4278190088" | join "address" " " }}`,
+ output: `127.255.255.248 ::1 fe80::ffff:ffff:ff:fff8`,
+ },
+ {
+ // Assume the private IPs available on the host are: 10.1.2.3
+ // fe80::1025:f732:1001:203
+ name: "GetPrivateIPs",
+ input: `{{GetPrivateIPs}}`,
+ output: `10.1.2.3 fe80::1025:f732:1001:203`,
+ },
+ {
+ // Assume the public IPs available on the host are: 1.2.3.4 6.7.8.9
+ name: "GetPublicIPs",
+ input: `{{GetPublicIPs}}`,
+ output: `1.2.3.4 6.7.8.9`,
+ },
+ {
+ // Assume the private IPs on this host are just the IPv4 addresses:
+ // 10.1.2.3 and 172.16.4.6
+ name: "GetInterfaceIPs",
+ input: `{{GetInterfaceIPs "en0"}}`,
+ output: `10.1.2.3 and 172.16.4.6`,
+ },
}
for i, test := range tests {
diff --git a/vendor/github.com/hashicorp/memberlist/config.go b/vendor/github.com/hashicorp/memberlist/config.go
index 2f43d14cb..5cad4ed54 100644
--- a/vendor/github.com/hashicorp/memberlist/config.go
+++ b/vendor/github.com/hashicorp/memberlist/config.go
@@ -141,6 +141,16 @@ type Config struct {
GossipNodes int
GossipToTheDeadTime time.Duration
+ // GossipVerifyIncoming controls whether to enforce encryption for incoming
+ // gossip. It is used for upshifting from unencrypted to encrypted gossip on
+ // a running cluster.
+ GossipVerifyIncoming bool
+
+ // GossipVerifyOutgoing controls whether to enforce encryption for outgoing
+ // gossip. It is used for upshifting from unencrypted to encrypted gossip on
+ // a running cluster.
+ GossipVerifyOutgoing bool
+
// EnableCompression is used to control message compression. This can
// be used to reduce bandwidth usage at the cost of slightly more CPU
// utilization. This is only available starting at protocol version 1.
@@ -233,9 +243,11 @@ func DefaultLANConfig() *Config {
DisableTcpPings: false, // TCP pings are safe, even with mixed versions
AwarenessMaxMultiplier: 8, // Probe interval backs off to 8 seconds
- GossipNodes: 3, // Gossip to 3 nodes
- GossipInterval: 200 * time.Millisecond, // Gossip more rapidly
- GossipToTheDeadTime: 30 * time.Second, // Same as push/pull
+ GossipNodes: 3, // Gossip to 3 nodes
+ GossipInterval: 200 * time.Millisecond, // Gossip more rapidly
+ GossipToTheDeadTime: 30 * time.Second, // Same as push/pull
+ GossipVerifyIncoming: true,
+ GossipVerifyOutgoing: true,
EnableCompression: true, // Enable compression by default
diff --git a/vendor/github.com/hashicorp/memberlist/memberlist_test.go b/vendor/github.com/hashicorp/memberlist/memberlist_test.go
index ff03ab3e4..964112dfd 100644
--- a/vendor/github.com/hashicorp/memberlist/memberlist_test.go
+++ b/vendor/github.com/hashicorp/memberlist/memberlist_test.go
@@ -326,6 +326,12 @@ func TestMemberList_ResolveAddr(t *testing.T) {
if _, err := m.resolveAddr("[2001:db8:a0b:12f0::1]:80"); err != nil {
t.Fatalf("Could not understand hostname port combo: %s", err)
}
+ if _, err := m.resolveAddr("127.0.0.1"); err != nil {
+ t.Fatalf("Could not understand IPv4 only %s", err)
+ }
+ if _, err := m.resolveAddr("[2001:db8:a0b:12f0::1]"); err != nil {
+ t.Fatalf("Could not understand IPv6 only %s", err)
+ }
}
type dnsHandler struct {
@@ -1315,6 +1321,129 @@ func TestMemberlist_PingDelegate(t *testing.T) {
}
}
+func TestMemberlist_EncryptedGossipTransition(t *testing.T) {
+ m1 := GetMemberlist(t)
+ m1.setAlive()
+ m1.schedule()
+ defer m1.Shutdown()
+
+ // Create a second node with the first stage of gossip transition settings
+ conf2 := DefaultLANConfig()
+ addr2 := getBindAddr()
+ conf2.Name = addr2.String()
+ conf2.BindAddr = addr2.String()
+ conf2.BindPort = m1.config.BindPort
+ conf2.GossipInterval = time.Millisecond
+ conf2.SecretKey = []byte("Hi16ZXu2lNCRVwtr20khAg==")
+ conf2.GossipVerifyIncoming = false
+ conf2.GossipVerifyOutgoing = false
+
+ m2, err := Create(conf2)
+ if err != nil {
+ t.Fatalf("unexpected err: %s", err)
+ }
+ defer m2.Shutdown()
+
+ // Join the second node. m1 has no encryption while m2 has encryption configured and
+ // can receive encrypted gossip, but will not encrypt outgoing gossip.
+ num, err := m2.Join([]string{m1.config.BindAddr})
+ if num != 1 {
+ t.Fatalf("unexpected 1: %d", num)
+ }
+ if err != nil {
+ t.Fatalf("unexpected err: %s", err)
+ }
+
+ // Check the hosts
+ if len(m2.Members()) != 2 {
+ t.Fatalf("should have 2 nodes! %v", m2.Members())
+ }
+ if m2.estNumNodes() != 2 {
+ t.Fatalf("should have 2 nodes! %v", m2.Members())
+ }
+
+ // Leave with the first node
+ m1.Leave(time.Second)
+
+ // Wait for leave
+ time.Sleep(10 * time.Millisecond)
+
+ // Create a third node that has the second stage of gossip transition settings
+ conf3 := DefaultLANConfig()
+ addr3 := getBindAddr()
+ conf3.Name = addr3.String()
+ conf3.BindAddr = addr3.String()
+ conf3.BindPort = m1.config.BindPort
+ conf3.GossipInterval = time.Millisecond
+ conf3.SecretKey = conf2.SecretKey
+ conf3.GossipVerifyIncoming = false
+
+ m3, err := Create(conf3)
+ if err != nil {
+ t.Fatalf("unexpected err: %s", err)
+ }
+ defer m3.Shutdown()
+
+ // Join the third node to the second node. At this step, both nodes have encryption
+ // configured but only m3 is sending encrypted gossip.
+ num, err = m3.Join([]string{m2.config.BindAddr})
+ if num != 1 {
+ t.Fatalf("unexpected 1: %d", num)
+ }
+ if err != nil {
+ t.Fatalf("unexpected err: %s", err)
+ }
+
+ // Check the hosts
+ if len(m3.Members()) != 2 {
+ t.Fatalf("should have 2 nodes! %v", m3.Members())
+
+ }
+ if m3.estNumNodes() != 2 {
+ t.Fatalf("should have 2 nodes! %v", m3.Members())
+ }
+
+ // Leave with the second node
+ m2.Leave(time.Second)
+
+ // Wait for leave
+ time.Sleep(10 * time.Millisecond)
+
+ // Create a fourth node that has the second stage of gossip transition settings
+ conf4 := DefaultLANConfig()
+ addr4 := getBindAddr()
+ conf4.Name = addr4.String()
+ conf4.BindAddr = addr4.String()
+ conf4.BindPort = m3.config.BindPort
+ conf4.GossipInterval = time.Millisecond
+ conf4.SecretKey = conf2.SecretKey
+
+ m4, err := Create(conf4)
+ if err != nil {
+ t.Fatalf("unexpected err: %s", err)
+ }
+ defer m4.Shutdown()
+
+ // Join the fourth node to the third node. At this step, both m3 and m4 are speaking
+ // encrypted gossip and m3 is still accepting insecure gossip.
+ num, err = m4.Join([]string{m3.config.BindAddr})
+ if num != 1 {
+ t.Fatalf("unexpected 1: %d", num)
+ }
+ if err != nil {
+ t.Fatalf("unexpected err: %s", err)
+ }
+
+ // Check the hosts
+ if len(m4.Members()) != 2 {
+ t.Fatalf("should have 2 nodes! %v", m4.Members())
+
+ }
+ if m4.estNumNodes() != 2 {
+ t.Fatalf("should have 2 nodes! %v", m4.Members())
+ }
+}
+
// Consul bug, rapid restart (before failure detection),
// with an updated meta data. Should be at incarnation 1 for
// both.
diff --git a/vendor/github.com/hashicorp/memberlist/net.go b/vendor/github.com/hashicorp/memberlist/net.go
index e0036d01d..65a60159d 100644
--- a/vendor/github.com/hashicorp/memberlist/net.go
+++ b/vendor/github.com/hashicorp/memberlist/net.go
@@ -283,8 +283,13 @@ func (m *Memberlist) ingestPacket(buf []byte, from net.Addr, timestamp time.Time
// Decrypt the payload
plain, err := decryptPayload(m.config.Keyring.GetKeys(), buf, nil)
if err != nil {
- m.logger.Printf("[ERR] memberlist: Decrypt packet failed: %v %s", err, LogAddress(from))
- return
+ if !m.config.GossipVerifyIncoming {
+ // Treat the message as plaintext
+ plain = buf
+ } else {
+ m.logger.Printf("[ERR] memberlist: Decrypt packet failed: %v %s", err, LogAddress(from))
+ return
+ }
}
// Continue processing the plaintext buffer
@@ -557,7 +562,7 @@ func (m *Memberlist) encodeAndSendMsg(addr string, msgType messageType, msg inte
func (m *Memberlist) sendMsg(addr string, msg []byte) error {
// Check if we can piggy back any messages
bytesAvail := m.config.UDPBufferSize - len(msg) - compoundHeaderOverhead
- if m.config.EncryptionEnabled() {
+ if m.config.EncryptionEnabled() && m.config.GossipVerifyOutgoing {
bytesAvail -= encryptOverhead(m.encryptionVersion())
}
extra := m.getBroadcasts(compoundOverhead, bytesAvail)
@@ -621,7 +626,7 @@ func (m *Memberlist) rawSendMsgPacket(addr string, node *Node, msg []byte) error
}
// Check if we have encryption enabled
- if m.config.EncryptionEnabled() {
+ if m.config.EncryptionEnabled() && m.config.GossipVerifyOutgoing {
// Encrypt the payload
var buf bytes.Buffer
primaryKey := m.config.Keyring.GetPrimaryKey()
@@ -652,7 +657,7 @@ func (m *Memberlist) rawSendMsgStream(conn net.Conn, sendBuf []byte) error {
}
// Check if encryption is enabled
- if m.config.EncryptionEnabled() {
+ if m.config.EncryptionEnabled() && m.config.GossipVerifyOutgoing {
crypt, err := m.encryptLocalState(sendBuf)
if err != nil {
m.logger.Printf("[ERROR] memberlist: Failed to encrypt local state: %v", err)
@@ -876,7 +881,7 @@ func (m *Memberlist) readStream(conn net.Conn) (messageType, io.Reader, *codec.D
// Reset message type and bufConn
msgType = messageType(plain[0])
bufConn = bytes.NewReader(plain[1:])
- } else if m.config.EncryptionEnabled() {
+ } else if m.config.EncryptionEnabled() && m.config.GossipVerifyIncoming {
return 0, nil, nil,
fmt.Errorf("Encryption is configured but remote state is not encrypted")
}
diff --git a/vendor/github.com/hashicorp/memberlist/state_test.go b/vendor/github.com/hashicorp/memberlist/state_test.go
index 8b9c8aaf7..71e93ca4e 100644
--- a/vendor/github.com/hashicorp/memberlist/state_test.go
+++ b/vendor/github.com/hashicorp/memberlist/state_test.go
@@ -669,7 +669,7 @@ func TestMemberList_ProbeNode_Awareness_MissedNack(t *testing.T) {
// We should have gotten dinged for the missed nack.
time.Sleep(probeTimeMax)
- if score := m1.GetHealthScore(); score != 2 {
+ if score := m1.GetHealthScore(); score != 1 {
t.Fatalf("bad: %d", score)
}
}
diff --git a/vendor/github.com/lib/pq/conn.go b/vendor/github.com/lib/pq/conn.go
index 3e3a5cabc..3b322bc06 100644
--- a/vendor/github.com/lib/pq/conn.go
+++ b/vendor/github.com/lib/pq/conn.go
@@ -506,13 +506,17 @@ func (cn *conn) checkIsInTransaction(intxn bool) {
}
func (cn *conn) Begin() (_ driver.Tx, err error) {
+ return cn.begin("")
+}
+
+func (cn *conn) begin(mode string) (_ driver.Tx, err error) {
if cn.bad {
return nil, driver.ErrBadConn
}
defer cn.errRecover(&err)
cn.checkIsInTransaction(false)
- _, commandTag, err := cn.simpleExec("BEGIN")
+ _, commandTag, err := cn.simpleExec("BEGIN" + mode)
if err != nil {
return nil, err
}
diff --git a/vendor/github.com/lib/pq/conn_go18.go b/vendor/github.com/lib/pq/conn_go18.go
index fa3755d99..ab97a104d 100644
--- a/vendor/github.com/lib/pq/conn_go18.go
+++ b/vendor/github.com/lib/pq/conn_go18.go
@@ -4,8 +4,9 @@ package pq
import (
"context"
+ "database/sql"
"database/sql/driver"
- "errors"
+ "fmt"
"io"
"io/ioutil"
)
@@ -19,6 +20,9 @@ func (cn *conn) QueryContext(ctx context.Context, query string, args []driver.Na
finish := cn.watchCancel(ctx)
r, err := cn.query(query, list)
if err != nil {
+ if finish != nil {
+ finish()
+ }
return nil, err
}
r.finish = finish
@@ -41,13 +45,30 @@ func (cn *conn) ExecContext(ctx context.Context, query string, args []driver.Nam
// Implement the "ConnBeginTx" interface
func (cn *conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) {
- if opts.Isolation != 0 {
- return nil, errors.New("isolation levels not supported")
+ var mode string
+
+ switch sql.IsolationLevel(opts.Isolation) {
+ case sql.LevelDefault:
+ // Don't touch mode: use the server's default
+ case sql.LevelReadUncommitted:
+ mode = " ISOLATION LEVEL READ UNCOMMITTED"
+ case sql.LevelReadCommitted:
+ mode = " ISOLATION LEVEL READ COMMITTED"
+ case sql.LevelRepeatableRead:
+ mode = " ISOLATION LEVEL REPEATABLE READ"
+ case sql.LevelSerializable:
+ mode = " ISOLATION LEVEL SERIALIZABLE"
+ default:
+ return nil, fmt.Errorf("pq: isolation level not supported: %d", opts.Isolation)
}
+
if opts.ReadOnly {
- return nil, errors.New("read-only transactions not supported")
+ mode += " READ ONLY"
+ } else {
+ mode += " READ WRITE"
}
- tx, err := cn.Begin()
+
+ tx, err := cn.begin(mode)
if err != nil {
return nil, err
}
diff --git a/vendor/github.com/lib/pq/conn_test.go b/vendor/github.com/lib/pq/conn_test.go
index c9135b727..8c6187fc6 100644
--- a/vendor/github.com/lib/pq/conn_test.go
+++ b/vendor/github.com/lib/pq/conn_test.go
@@ -160,11 +160,11 @@ func TestPgpass(t *testing.T) {
rows, err := txn.Query("SELECT USER")
if err != nil {
txn.Rollback()
- rows.Close()
if expected != "fail" {
t.Fatalf(reason, err)
}
} else {
+ rows.Close()
if expected != "ok" {
t.Fatalf(reason, err)
}
diff --git a/vendor/github.com/lib/pq/go18_test.go b/vendor/github.com/lib/pq/go18_test.go
index cddbfb6a4..4bf6391ef 100644
--- a/vendor/github.com/lib/pq/go18_test.go
+++ b/vendor/github.com/lib/pq/go18_test.go
@@ -5,6 +5,8 @@ package pq
import (
"context"
"database/sql"
+ "runtime"
+ "strings"
"testing"
"time"
)
@@ -155,6 +157,36 @@ func TestContextCancelQuery(t *testing.T) {
}
}
+// TestIssue617 tests that a failed query in QueryContext doesn't lead to a
+// goroutine leak.
+func TestIssue617(t *testing.T) {
+ db := openTestConn(t)
+ defer db.Close()
+
+ const N = 10
+
+ numGoroutineStart := runtime.NumGoroutine()
+ for i := 0; i < N; i++ {
+ func() {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ _, err := db.QueryContext(ctx, `SELECT * FROM DOESNOTEXIST`)
+ pqErr, _ := err.(*Error)
+ // Expecting "pq: relation \"doesnotexist\" does not exist" error.
+ if err == nil || pqErr == nil || pqErr.Code != "42P01" {
+ t.Fatalf("expected undefined table error, got %v", err)
+ }
+ }()
+ }
+ numGoroutineFinish := runtime.NumGoroutine()
+
+ // We use N/2 and not N because the GC and other actors may increase or
+ // decrease the number of goroutines.
+ if numGoroutineFinish-numGoroutineStart >= N/2 {
+ t.Errorf("goroutine leak detected, was %d, now %d", numGoroutineStart, numGoroutineFinish)
+ }
+}
+
func TestContextCancelBegin(t *testing.T) {
db := openTestConn(t)
defer db.Close()
@@ -208,3 +240,80 @@ func TestContextCancelBegin(t *testing.T) {
}
}
}
+
+func TestTxOptions(t *testing.T) {
+ db := openTestConn(t)
+ defer db.Close()
+ ctx := context.Background()
+
+ tests := []struct {
+ level sql.IsolationLevel
+ isolation string
+ }{
+ {
+ level: sql.LevelDefault,
+ isolation: "",
+ },
+ {
+ level: sql.LevelReadUncommitted,
+ isolation: "read uncommitted",
+ },
+ {
+ level: sql.LevelReadCommitted,
+ isolation: "read committed",
+ },
+ {
+ level: sql.LevelRepeatableRead,
+ isolation: "repeatable read",
+ },
+ {
+ level: sql.LevelSerializable,
+ isolation: "serializable",
+ },
+ }
+
+ for _, test := range tests {
+ for _, ro := range []bool{true, false} {
+ tx, err := db.BeginTx(ctx, &sql.TxOptions{
+ Isolation: test.level,
+ ReadOnly: ro,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ var isolation string
+ err = tx.QueryRow("select current_setting('transaction_isolation')").Scan(&isolation)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if test.isolation != "" && isolation != test.isolation {
+ t.Errorf("wrong isolation level: %s != %s", isolation, test.isolation)
+ }
+
+ var isRO string
+ err = tx.QueryRow("select current_setting('transaction_read_only')").Scan(&isRO)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if ro != (isRO == "on") {
+ t.Errorf("read/[write,only] not set: %t != %s for level %s",
+ ro, isRO, test.isolation)
+ }
+
+ tx.Rollback()
+ }
+ }
+
+ _, err := db.BeginTx(ctx, &sql.TxOptions{
+ Isolation: sql.LevelLinearizable,
+ })
+ if err == nil {
+ t.Fatal("expected LevelLinearizable to fail")
+ }
+ if !strings.Contains(err.Error(), "isolation level not supported") {
+ t.Errorf("Expected error to mention isolation level, got %q", err)
+ }
+}
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/.travis.yml b/vendor/github.com/matttproud/golang_protobuf_extensions/.travis.yml
index 5db258039..f1309c9f8 100644
--- a/vendor/github.com/matttproud/golang_protobuf_extensions/.travis.yml
+++ b/vendor/github.com/matttproud/golang_protobuf_extensions/.travis.yml
@@ -1,8 +1,2 @@
language: go
-go:
- - 1.5
- - 1.6
- - tip
-
-script: make -f Makefile.TRAVIS
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/Makefile.TRAVIS b/vendor/github.com/matttproud/golang_protobuf_extensions/Makefile.TRAVIS
deleted file mode 100644
index 24f9649e2..000000000
--- a/vendor/github.com/matttproud/golang_protobuf_extensions/Makefile.TRAVIS
+++ /dev/null
@@ -1,15 +0,0 @@
-all: build cover test vet
-
-build:
- go build -v ./...
-
-cover: test
- $(MAKE) -C pbutil cover
-
-test: build
- go test -v ./...
-
-vet: build
- go vet -v ./...
-
-.PHONY: build cover test vet
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/.gitignore b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/.gitignore
deleted file mode 100644
index e16fb946b..000000000
--- a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-cover.dat
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/Makefile b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/Makefile
deleted file mode 100644
index 81be21437..000000000
--- a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/Makefile
+++ /dev/null
@@ -1,7 +0,0 @@
-all:
-
-cover:
- go test -cover -v -coverprofile=cover.dat ./...
- go tool cover -func cover.dat
-
-.PHONY: cover
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go
index a793c8856..5c463722d 100644
--- a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go
+++ b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go
@@ -18,15 +18,14 @@ import (
"bytes"
"testing"
- "github.com/golang/protobuf/proto"
-
- . "github.com/matttproud/golang_protobuf_extensions/testdata"
+ . "github.com/golang/protobuf/proto"
+ . "github.com/golang/protobuf/proto/testdata"
)
func TestWriteDelimited(t *testing.T) {
t.Parallel()
for _, test := range []struct {
- msg proto.Message
+ msg Message
buf []byte
n int
err error
@@ -43,7 +42,7 @@ func TestWriteDelimited(t *testing.T) {
},
{
msg: &Strings{
- StringField: proto.String(`This is my gigantic, unhappy string. It exceeds
+ StringField: String(`This is my gigantic, unhappy string. It exceeds
the encoding size of a single byte varint. We are using it to fuzz test the
correctness of the header decoding mechanisms, which may prove problematic.
I expect it may. Let's hope you enjoy testing as much as we do.`),
@@ -83,7 +82,7 @@ func TestReadDelimited(t *testing.T) {
t.Parallel()
for _, test := range []struct {
buf []byte
- msg proto.Message
+ msg Message
n int
err error
}{
@@ -117,7 +116,7 @@ func TestReadDelimited(t *testing.T) {
106, 111, 121, 32, 116, 101, 115, 116, 105, 110, 103, 32, 97, 115, 32,
109, 117, 99, 104, 32, 97, 115, 32, 119, 101, 32, 100, 111, 46},
msg: &Strings{
- StringField: proto.String(`This is my gigantic, unhappy string. It exceeds
+ StringField: String(`This is my gigantic, unhappy string. It exceeds
the encoding size of a single byte varint. We are using it to fuzz test the
correctness of the header decoding mechanisms, which may prove problematic.
I expect it may. Let's hope you enjoy testing as much as we do.`),
@@ -125,12 +124,12 @@ I expect it may. Let's hope you enjoy testing as much as we do.`),
n: 271,
},
} {
- msg := proto.Clone(test.msg)
+ msg := Clone(test.msg)
msg.Reset()
if n, err := ReadDelimited(bytes.NewBuffer(test.buf), msg); n != test.n || err != test.err {
t.Fatalf("ReadDelimited(%v, msg) = %v, %v; want %v, %v", test.buf, n, err, test.n, test.err)
}
- if !proto.Equal(msg, test.msg) {
+ if !Equal(msg, test.msg) {
t.Fatalf("ReadDelimited(%v, msg); msg = %v; want %v", test.buf, msg, test.msg)
}
}
@@ -138,12 +137,12 @@ I expect it may. Let's hope you enjoy testing as much as we do.`),
func TestEndToEndValid(t *testing.T) {
t.Parallel()
- for _, test := range [][]proto.Message{
+ for _, test := range [][]Message{
{&Empty{}},
{&GoEnum{Foo: FOO_FOO1.Enum()}, &Empty{}, &GoEnum{Foo: FOO_FOO1.Enum()}},
{&GoEnum{Foo: FOO_FOO1.Enum()}},
{&Strings{
- StringField: proto.String(`This is my gigantic, unhappy string. It exceeds
+ StringField: String(`This is my gigantic, unhappy string. It exceeds
the encoding size of a single byte varint. We are using it to fuzz test the
correctness of the header decoding mechanisms, which may prove problematic.
I expect it may. Let's hope you enjoy testing as much as we do.`),
@@ -162,12 +161,12 @@ I expect it may. Let's hope you enjoy testing as much as we do.`),
}
var read int
for i, msg := range test {
- out := proto.Clone(msg)
+ out := Clone(msg)
out.Reset()
n, _ := ReadDelimited(&buf, out)
// Decide to do EOF checking?
read += n
- if !proto.Equal(out, msg) {
+ if !Equal(out, msg) {
t.Fatalf("out = %v; want %v[%d] = %#v", out, test, i, msg)
}
}
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/fixtures_test.go b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/fixtures_test.go
new file mode 100644
index 000000000..d6d9b2559
--- /dev/null
+++ b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/fixtures_test.go
@@ -0,0 +1,103 @@
+// Copyright 2010 The Go Authors. All rights reserved.
+// http://github.com/golang/protobuf/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+package pbutil
+
+import (
+ . "github.com/golang/protobuf/proto"
+ . "github.com/golang/protobuf/proto/testdata"
+)
+
+// FROM https://github.com/golang/protobuf/blob/master/proto/all_test.go.
+
+func initGoTestField() *GoTestField {
+ f := new(GoTestField)
+ f.Label = String("label")
+ f.Type = String("type")
+ return f
+}
+
+// These are all structurally equivalent but the tag numbers differ.
+// (It's remarkable that required, optional, and repeated all have
+// 8 letters.)
+func initGoTest_RequiredGroup() *GoTest_RequiredGroup {
+ return &GoTest_RequiredGroup{
+ RequiredField: String("required"),
+ }
+}
+
+func initGoTest_OptionalGroup() *GoTest_OptionalGroup {
+ return &GoTest_OptionalGroup{
+ RequiredField: String("optional"),
+ }
+}
+
+func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup {
+ return &GoTest_RepeatedGroup{
+ RequiredField: String("repeated"),
+ }
+}
+
+func initGoTest(setdefaults bool) *GoTest {
+ pb := new(GoTest)
+ if setdefaults {
+ pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted)
+ pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted)
+ pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted)
+ pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted)
+ pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted)
+ pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted)
+ pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted)
+ pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted)
+ pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted)
+ pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted)
+ pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted
+ pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted)
+ pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted)
+ }
+
+ pb.Kind = GoTest_TIME.Enum()
+ pb.RequiredField = initGoTestField()
+ pb.F_BoolRequired = Bool(true)
+ pb.F_Int32Required = Int32(3)
+ pb.F_Int64Required = Int64(6)
+ pb.F_Fixed32Required = Uint32(32)
+ pb.F_Fixed64Required = Uint64(64)
+ pb.F_Uint32Required = Uint32(3232)
+ pb.F_Uint64Required = Uint64(6464)
+ pb.F_FloatRequired = Float32(3232)
+ pb.F_DoubleRequired = Float64(6464)
+ pb.F_StringRequired = String("string")
+ pb.F_BytesRequired = []byte("bytes")
+ pb.F_Sint32Required = Int32(-32)
+ pb.F_Sint64Required = Int64(-64)
+ pb.Requiredgroup = initGoTest_RequiredGroup()
+
+ return pb
+}
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/testdata/README.THIRD_PARTY b/vendor/github.com/matttproud/golang_protobuf_extensions/testdata/README.THIRD_PARTY
deleted file mode 100644
index 0c1f84246..000000000
--- a/vendor/github.com/matttproud/golang_protobuf_extensions/testdata/README.THIRD_PARTY
+++ /dev/null
@@ -1,4 +0,0 @@
-test.pb.go and test.proto are third-party data.
-
-SOURCE: https://github.com/golang/protobuf
-REVISION: bf531ff1a004f24ee53329dfd5ce0b41bfdc17df
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/testdata/test.pb.go b/vendor/github.com/matttproud/golang_protobuf_extensions/testdata/test.pb.go
deleted file mode 100644
index 772adcb62..000000000
--- a/vendor/github.com/matttproud/golang_protobuf_extensions/testdata/test.pb.go
+++ /dev/null
@@ -1,4029 +0,0 @@
-// Code generated by protoc-gen-go.
-// source: test.proto
-// DO NOT EDIT!
-
-/*
-Package testdata is a generated protocol buffer package.
-
-It is generated from these files:
- test.proto
-
-It has these top-level messages:
- GoEnum
- GoTestField
- GoTest
- GoSkipTest
- NonPackedTest
- PackedTest
- MaxTag
- OldMessage
- NewMessage
- InnerMessage
- OtherMessage
- RequiredInnerMessage
- MyMessage
- Ext
- ComplexExtension
- DefaultsMessage
- MyMessageSet
- Empty
- MessageList
- Strings
- Defaults
- SubDefaults
- RepeatedEnum
- MoreRepeated
- GroupOld
- GroupNew
- FloatingPoint
- MessageWithMap
- Oneof
- Communique
-*/
-package testdata
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-const _ = proto.ProtoPackageIsVersion1
-
-type FOO int32
-
-const (
- FOO_FOO1 FOO = 1
-)
-
-var FOO_name = map[int32]string{
- 1: "FOO1",
-}
-var FOO_value = map[string]int32{
- "FOO1": 1,
-}
-
-func (x FOO) Enum() *FOO {
- p := new(FOO)
- *p = x
- return p
-}
-func (x FOO) String() string {
- return proto.EnumName(FOO_name, int32(x))
-}
-func (x *FOO) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(FOO_value, data, "FOO")
- if err != nil {
- return err
- }
- *x = FOO(value)
- return nil
-}
-func (FOO) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
-
-// An enum, for completeness.
-type GoTest_KIND int32
-
-const (
- GoTest_VOID GoTest_KIND = 0
- // Basic types
- GoTest_BOOL GoTest_KIND = 1
- GoTest_BYTES GoTest_KIND = 2
- GoTest_FINGERPRINT GoTest_KIND = 3
- GoTest_FLOAT GoTest_KIND = 4
- GoTest_INT GoTest_KIND = 5
- GoTest_STRING GoTest_KIND = 6
- GoTest_TIME GoTest_KIND = 7
- // Groupings
- GoTest_TUPLE GoTest_KIND = 8
- GoTest_ARRAY GoTest_KIND = 9
- GoTest_MAP GoTest_KIND = 10
- // Table types
- GoTest_TABLE GoTest_KIND = 11
- // Functions
- GoTest_FUNCTION GoTest_KIND = 12
-)
-
-var GoTest_KIND_name = map[int32]string{
- 0: "VOID",
- 1: "BOOL",
- 2: "BYTES",
- 3: "FINGERPRINT",
- 4: "FLOAT",
- 5: "INT",
- 6: "STRING",
- 7: "TIME",
- 8: "TUPLE",
- 9: "ARRAY",
- 10: "MAP",
- 11: "TABLE",
- 12: "FUNCTION",
-}
-var GoTest_KIND_value = map[string]int32{
- "VOID": 0,
- "BOOL": 1,
- "BYTES": 2,
- "FINGERPRINT": 3,
- "FLOAT": 4,
- "INT": 5,
- "STRING": 6,
- "TIME": 7,
- "TUPLE": 8,
- "ARRAY": 9,
- "MAP": 10,
- "TABLE": 11,
- "FUNCTION": 12,
-}
-
-func (x GoTest_KIND) Enum() *GoTest_KIND {
- p := new(GoTest_KIND)
- *p = x
- return p
-}
-func (x GoTest_KIND) String() string {
- return proto.EnumName(GoTest_KIND_name, int32(x))
-}
-func (x *GoTest_KIND) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(GoTest_KIND_value, data, "GoTest_KIND")
- if err != nil {
- return err
- }
- *x = GoTest_KIND(value)
- return nil
-}
-func (GoTest_KIND) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 0} }
-
-type MyMessage_Color int32
-
-const (
- MyMessage_RED MyMessage_Color = 0
- MyMessage_GREEN MyMessage_Color = 1
- MyMessage_BLUE MyMessage_Color = 2
-)
-
-var MyMessage_Color_name = map[int32]string{
- 0: "RED",
- 1: "GREEN",
- 2: "BLUE",
-}
-var MyMessage_Color_value = map[string]int32{
- "RED": 0,
- "GREEN": 1,
- "BLUE": 2,
-}
-
-func (x MyMessage_Color) Enum() *MyMessage_Color {
- p := new(MyMessage_Color)
- *p = x
- return p
-}
-func (x MyMessage_Color) String() string {
- return proto.EnumName(MyMessage_Color_name, int32(x))
-}
-func (x *MyMessage_Color) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(MyMessage_Color_value, data, "MyMessage_Color")
- if err != nil {
- return err
- }
- *x = MyMessage_Color(value)
- return nil
-}
-func (MyMessage_Color) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{12, 0} }
-
-type DefaultsMessage_DefaultsEnum int32
-
-const (
- DefaultsMessage_ZERO DefaultsMessage_DefaultsEnum = 0
- DefaultsMessage_ONE DefaultsMessage_DefaultsEnum = 1
- DefaultsMessage_TWO DefaultsMessage_DefaultsEnum = 2
-)
-
-var DefaultsMessage_DefaultsEnum_name = map[int32]string{
- 0: "ZERO",
- 1: "ONE",
- 2: "TWO",
-}
-var DefaultsMessage_DefaultsEnum_value = map[string]int32{
- "ZERO": 0,
- "ONE": 1,
- "TWO": 2,
-}
-
-func (x DefaultsMessage_DefaultsEnum) Enum() *DefaultsMessage_DefaultsEnum {
- p := new(DefaultsMessage_DefaultsEnum)
- *p = x
- return p
-}
-func (x DefaultsMessage_DefaultsEnum) String() string {
- return proto.EnumName(DefaultsMessage_DefaultsEnum_name, int32(x))
-}
-func (x *DefaultsMessage_DefaultsEnum) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(DefaultsMessage_DefaultsEnum_value, data, "DefaultsMessage_DefaultsEnum")
- if err != nil {
- return err
- }
- *x = DefaultsMessage_DefaultsEnum(value)
- return nil
-}
-func (DefaultsMessage_DefaultsEnum) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor0, []int{15, 0}
-}
-
-type Defaults_Color int32
-
-const (
- Defaults_RED Defaults_Color = 0
- Defaults_GREEN Defaults_Color = 1
- Defaults_BLUE Defaults_Color = 2
-)
-
-var Defaults_Color_name = map[int32]string{
- 0: "RED",
- 1: "GREEN",
- 2: "BLUE",
-}
-var Defaults_Color_value = map[string]int32{
- "RED": 0,
- "GREEN": 1,
- "BLUE": 2,
-}
-
-func (x Defaults_Color) Enum() *Defaults_Color {
- p := new(Defaults_Color)
- *p = x
- return p
-}
-func (x Defaults_Color) String() string {
- return proto.EnumName(Defaults_Color_name, int32(x))
-}
-func (x *Defaults_Color) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(Defaults_Color_value, data, "Defaults_Color")
- if err != nil {
- return err
- }
- *x = Defaults_Color(value)
- return nil
-}
-func (Defaults_Color) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{20, 0} }
-
-type RepeatedEnum_Color int32
-
-const (
- RepeatedEnum_RED RepeatedEnum_Color = 1
-)
-
-var RepeatedEnum_Color_name = map[int32]string{
- 1: "RED",
-}
-var RepeatedEnum_Color_value = map[string]int32{
- "RED": 1,
-}
-
-func (x RepeatedEnum_Color) Enum() *RepeatedEnum_Color {
- p := new(RepeatedEnum_Color)
- *p = x
- return p
-}
-func (x RepeatedEnum_Color) String() string {
- return proto.EnumName(RepeatedEnum_Color_name, int32(x))
-}
-func (x *RepeatedEnum_Color) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(RepeatedEnum_Color_value, data, "RepeatedEnum_Color")
- if err != nil {
- return err
- }
- *x = RepeatedEnum_Color(value)
- return nil
-}
-func (RepeatedEnum_Color) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{22, 0} }
-
-type GoEnum struct {
- Foo *FOO `protobuf:"varint,1,req,name=foo,enum=testdata.FOO" json:"foo,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GoEnum) Reset() { *m = GoEnum{} }
-func (m *GoEnum) String() string { return proto.CompactTextString(m) }
-func (*GoEnum) ProtoMessage() {}
-func (*GoEnum) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
-
-func (m *GoEnum) GetFoo() FOO {
- if m != nil && m.Foo != nil {
- return *m.Foo
- }
- return FOO_FOO1
-}
-
-type GoTestField struct {
- Label *string `protobuf:"bytes,1,req,name=Label,json=label" json:"Label,omitempty"`
- Type *string `protobuf:"bytes,2,req,name=Type,json=type" json:"Type,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GoTestField) Reset() { *m = GoTestField{} }
-func (m *GoTestField) String() string { return proto.CompactTextString(m) }
-func (*GoTestField) ProtoMessage() {}
-func (*GoTestField) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
-
-func (m *GoTestField) GetLabel() string {
- if m != nil && m.Label != nil {
- return *m.Label
- }
- return ""
-}
-
-func (m *GoTestField) GetType() string {
- if m != nil && m.Type != nil {
- return *m.Type
- }
- return ""
-}
-
-type GoTest struct {
- // Some typical parameters
- Kind *GoTest_KIND `protobuf:"varint,1,req,name=Kind,json=kind,enum=testdata.GoTest_KIND" json:"Kind,omitempty"`
- Table *string `protobuf:"bytes,2,opt,name=Table,json=table" json:"Table,omitempty"`
- Param *int32 `protobuf:"varint,3,opt,name=Param,json=param" json:"Param,omitempty"`
- // Required, repeated and optional foreign fields.
- RequiredField *GoTestField `protobuf:"bytes,4,req,name=RequiredField,json=requiredField" json:"RequiredField,omitempty"`
- RepeatedField []*GoTestField `protobuf:"bytes,5,rep,name=RepeatedField,json=repeatedField" json:"RepeatedField,omitempty"`
- OptionalField *GoTestField `protobuf:"bytes,6,opt,name=OptionalField,json=optionalField" json:"OptionalField,omitempty"`
- // Required fields of all basic types
- F_BoolRequired *bool `protobuf:"varint,10,req,name=F_Bool_required,json=fBoolRequired" json:"F_Bool_required,omitempty"`
- F_Int32Required *int32 `protobuf:"varint,11,req,name=F_Int32_required,json=fInt32Required" json:"F_Int32_required,omitempty"`
- F_Int64Required *int64 `protobuf:"varint,12,req,name=F_Int64_required,json=fInt64Required" json:"F_Int64_required,omitempty"`
- F_Fixed32Required *uint32 `protobuf:"fixed32,13,req,name=F_Fixed32_required,json=fFixed32Required" json:"F_Fixed32_required,omitempty"`
- F_Fixed64Required *uint64 `protobuf:"fixed64,14,req,name=F_Fixed64_required,json=fFixed64Required" json:"F_Fixed64_required,omitempty"`
- F_Uint32Required *uint32 `protobuf:"varint,15,req,name=F_Uint32_required,json=fUint32Required" json:"F_Uint32_required,omitempty"`
- F_Uint64Required *uint64 `protobuf:"varint,16,req,name=F_Uint64_required,json=fUint64Required" json:"F_Uint64_required,omitempty"`
- F_FloatRequired *float32 `protobuf:"fixed32,17,req,name=F_Float_required,json=fFloatRequired" json:"F_Float_required,omitempty"`
- F_DoubleRequired *float64 `protobuf:"fixed64,18,req,name=F_Double_required,json=fDoubleRequired" json:"F_Double_required,omitempty"`
- F_StringRequired *string `protobuf:"bytes,19,req,name=F_String_required,json=fStringRequired" json:"F_String_required,omitempty"`
- F_BytesRequired []byte `protobuf:"bytes,101,req,name=F_Bytes_required,json=fBytesRequired" json:"F_Bytes_required,omitempty"`
- F_Sint32Required *int32 `protobuf:"zigzag32,102,req,name=F_Sint32_required,json=fSint32Required" json:"F_Sint32_required,omitempty"`
- F_Sint64Required *int64 `protobuf:"zigzag64,103,req,name=F_Sint64_required,json=fSint64Required" json:"F_Sint64_required,omitempty"`
- // Repeated fields of all basic types
- F_BoolRepeated []bool `protobuf:"varint,20,rep,name=F_Bool_repeated,json=fBoolRepeated" json:"F_Bool_repeated,omitempty"`
- F_Int32Repeated []int32 `protobuf:"varint,21,rep,name=F_Int32_repeated,json=fInt32Repeated" json:"F_Int32_repeated,omitempty"`
- F_Int64Repeated []int64 `protobuf:"varint,22,rep,name=F_Int64_repeated,json=fInt64Repeated" json:"F_Int64_repeated,omitempty"`
- F_Fixed32Repeated []uint32 `protobuf:"fixed32,23,rep,name=F_Fixed32_repeated,json=fFixed32Repeated" json:"F_Fixed32_repeated,omitempty"`
- F_Fixed64Repeated []uint64 `protobuf:"fixed64,24,rep,name=F_Fixed64_repeated,json=fFixed64Repeated" json:"F_Fixed64_repeated,omitempty"`
- F_Uint32Repeated []uint32 `protobuf:"varint,25,rep,name=F_Uint32_repeated,json=fUint32Repeated" json:"F_Uint32_repeated,omitempty"`
- F_Uint64Repeated []uint64 `protobuf:"varint,26,rep,name=F_Uint64_repeated,json=fUint64Repeated" json:"F_Uint64_repeated,omitempty"`
- F_FloatRepeated []float32 `protobuf:"fixed32,27,rep,name=F_Float_repeated,json=fFloatRepeated" json:"F_Float_repeated,omitempty"`
- F_DoubleRepeated []float64 `protobuf:"fixed64,28,rep,name=F_Double_repeated,json=fDoubleRepeated" json:"F_Double_repeated,omitempty"`
- F_StringRepeated []string `protobuf:"bytes,29,rep,name=F_String_repeated,json=fStringRepeated" json:"F_String_repeated,omitempty"`
- F_BytesRepeated [][]byte `protobuf:"bytes,201,rep,name=F_Bytes_repeated,json=fBytesRepeated" json:"F_Bytes_repeated,omitempty"`
- F_Sint32Repeated []int32 `protobuf:"zigzag32,202,rep,name=F_Sint32_repeated,json=fSint32Repeated" json:"F_Sint32_repeated,omitempty"`
- F_Sint64Repeated []int64 `protobuf:"zigzag64,203,rep,name=F_Sint64_repeated,json=fSint64Repeated" json:"F_Sint64_repeated,omitempty"`
- // Optional fields of all basic types
- F_BoolOptional *bool `protobuf:"varint,30,opt,name=F_Bool_optional,json=fBoolOptional" json:"F_Bool_optional,omitempty"`
- F_Int32Optional *int32 `protobuf:"varint,31,opt,name=F_Int32_optional,json=fInt32Optional" json:"F_Int32_optional,omitempty"`
- F_Int64Optional *int64 `protobuf:"varint,32,opt,name=F_Int64_optional,json=fInt64Optional" json:"F_Int64_optional,omitempty"`
- F_Fixed32Optional *uint32 `protobuf:"fixed32,33,opt,name=F_Fixed32_optional,json=fFixed32Optional" json:"F_Fixed32_optional,omitempty"`
- F_Fixed64Optional *uint64 `protobuf:"fixed64,34,opt,name=F_Fixed64_optional,json=fFixed64Optional" json:"F_Fixed64_optional,omitempty"`
- F_Uint32Optional *uint32 `protobuf:"varint,35,opt,name=F_Uint32_optional,json=fUint32Optional" json:"F_Uint32_optional,omitempty"`
- F_Uint64Optional *uint64 `protobuf:"varint,36,opt,name=F_Uint64_optional,json=fUint64Optional" json:"F_Uint64_optional,omitempty"`
- F_FloatOptional *float32 `protobuf:"fixed32,37,opt,name=F_Float_optional,json=fFloatOptional" json:"F_Float_optional,omitempty"`
- F_DoubleOptional *float64 `protobuf:"fixed64,38,opt,name=F_Double_optional,json=fDoubleOptional" json:"F_Double_optional,omitempty"`
- F_StringOptional *string `protobuf:"bytes,39,opt,name=F_String_optional,json=fStringOptional" json:"F_String_optional,omitempty"`
- F_BytesOptional []byte `protobuf:"bytes,301,opt,name=F_Bytes_optional,json=fBytesOptional" json:"F_Bytes_optional,omitempty"`
- F_Sint32Optional *int32 `protobuf:"zigzag32,302,opt,name=F_Sint32_optional,json=fSint32Optional" json:"F_Sint32_optional,omitempty"`
- F_Sint64Optional *int64 `protobuf:"zigzag64,303,opt,name=F_Sint64_optional,json=fSint64Optional" json:"F_Sint64_optional,omitempty"`
- // Default-valued fields of all basic types
- F_BoolDefaulted *bool `protobuf:"varint,40,opt,name=F_Bool_defaulted,json=fBoolDefaulted,def=1" json:"F_Bool_defaulted,omitempty"`
- F_Int32Defaulted *int32 `protobuf:"varint,41,opt,name=F_Int32_defaulted,json=fInt32Defaulted,def=32" json:"F_Int32_defaulted,omitempty"`
- F_Int64Defaulted *int64 `protobuf:"varint,42,opt,name=F_Int64_defaulted,json=fInt64Defaulted,def=64" json:"F_Int64_defaulted,omitempty"`
- F_Fixed32Defaulted *uint32 `protobuf:"fixed32,43,opt,name=F_Fixed32_defaulted,json=fFixed32Defaulted,def=320" json:"F_Fixed32_defaulted,omitempty"`
- F_Fixed64Defaulted *uint64 `protobuf:"fixed64,44,opt,name=F_Fixed64_defaulted,json=fFixed64Defaulted,def=640" json:"F_Fixed64_defaulted,omitempty"`
- F_Uint32Defaulted *uint32 `protobuf:"varint,45,opt,name=F_Uint32_defaulted,json=fUint32Defaulted,def=3200" json:"F_Uint32_defaulted,omitempty"`
- F_Uint64Defaulted *uint64 `protobuf:"varint,46,opt,name=F_Uint64_defaulted,json=fUint64Defaulted,def=6400" json:"F_Uint64_defaulted,omitempty"`
- F_FloatDefaulted *float32 `protobuf:"fixed32,47,opt,name=F_Float_defaulted,json=fFloatDefaulted,def=314159" json:"F_Float_defaulted,omitempty"`
- F_DoubleDefaulted *float64 `protobuf:"fixed64,48,opt,name=F_Double_defaulted,json=fDoubleDefaulted,def=271828" json:"F_Double_defaulted,omitempty"`
- F_StringDefaulted *string `protobuf:"bytes,49,opt,name=F_String_defaulted,json=fStringDefaulted,def=hello, \"world!\"\n" json:"F_String_defaulted,omitempty"`
- F_BytesDefaulted []byte `protobuf:"bytes,401,opt,name=F_Bytes_defaulted,json=fBytesDefaulted,def=Bignose" json:"F_Bytes_defaulted,omitempty"`
- F_Sint32Defaulted *int32 `protobuf:"zigzag32,402,opt,name=F_Sint32_defaulted,json=fSint32Defaulted,def=-32" json:"F_Sint32_defaulted,omitempty"`
- F_Sint64Defaulted *int64 `protobuf:"zigzag64,403,opt,name=F_Sint64_defaulted,json=fSint64Defaulted,def=-64" json:"F_Sint64_defaulted,omitempty"`
- // Packed repeated fields (no string or bytes).
- F_BoolRepeatedPacked []bool `protobuf:"varint,50,rep,packed,name=F_Bool_repeated_packed,json=fBoolRepeatedPacked" json:"F_Bool_repeated_packed,omitempty"`
- F_Int32RepeatedPacked []int32 `protobuf:"varint,51,rep,packed,name=F_Int32_repeated_packed,json=fInt32RepeatedPacked" json:"F_Int32_repeated_packed,omitempty"`
- F_Int64RepeatedPacked []int64 `protobuf:"varint,52,rep,packed,name=F_Int64_repeated_packed,json=fInt64RepeatedPacked" json:"F_Int64_repeated_packed,omitempty"`
- F_Fixed32RepeatedPacked []uint32 `protobuf:"fixed32,53,rep,packed,name=F_Fixed32_repeated_packed,json=fFixed32RepeatedPacked" json:"F_Fixed32_repeated_packed,omitempty"`
- F_Fixed64RepeatedPacked []uint64 `protobuf:"fixed64,54,rep,packed,name=F_Fixed64_repeated_packed,json=fFixed64RepeatedPacked" json:"F_Fixed64_repeated_packed,omitempty"`
- F_Uint32RepeatedPacked []uint32 `protobuf:"varint,55,rep,packed,name=F_Uint32_repeated_packed,json=fUint32RepeatedPacked" json:"F_Uint32_repeated_packed,omitempty"`
- F_Uint64RepeatedPacked []uint64 `protobuf:"varint,56,rep,packed,name=F_Uint64_repeated_packed,json=fUint64RepeatedPacked" json:"F_Uint64_repeated_packed,omitempty"`
- F_FloatRepeatedPacked []float32 `protobuf:"fixed32,57,rep,packed,name=F_Float_repeated_packed,json=fFloatRepeatedPacked" json:"F_Float_repeated_packed,omitempty"`
- F_DoubleRepeatedPacked []float64 `protobuf:"fixed64,58,rep,packed,name=F_Double_repeated_packed,json=fDoubleRepeatedPacked" json:"F_Double_repeated_packed,omitempty"`
- F_Sint32RepeatedPacked []int32 `protobuf:"zigzag32,502,rep,packed,name=F_Sint32_repeated_packed,json=fSint32RepeatedPacked" json:"F_Sint32_repeated_packed,omitempty"`
- F_Sint64RepeatedPacked []int64 `protobuf:"zigzag64,503,rep,packed,name=F_Sint64_repeated_packed,json=fSint64RepeatedPacked" json:"F_Sint64_repeated_packed,omitempty"`
- Requiredgroup *GoTest_RequiredGroup `protobuf:"group,70,req,name=RequiredGroup,json=requiredgroup" json:"requiredgroup,omitempty"`
- Repeatedgroup []*GoTest_RepeatedGroup `protobuf:"group,80,rep,name=RepeatedGroup,json=repeatedgroup" json:"repeatedgroup,omitempty"`
- Optionalgroup *GoTest_OptionalGroup `protobuf:"group,90,opt,name=OptionalGroup,json=optionalgroup" json:"optionalgroup,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GoTest) Reset() { *m = GoTest{} }
-func (m *GoTest) String() string { return proto.CompactTextString(m) }
-func (*GoTest) ProtoMessage() {}
-func (*GoTest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
-
-const Default_GoTest_F_BoolDefaulted bool = true
-const Default_GoTest_F_Int32Defaulted int32 = 32
-const Default_GoTest_F_Int64Defaulted int64 = 64
-const Default_GoTest_F_Fixed32Defaulted uint32 = 320
-const Default_GoTest_F_Fixed64Defaulted uint64 = 640
-const Default_GoTest_F_Uint32Defaulted uint32 = 3200
-const Default_GoTest_F_Uint64Defaulted uint64 = 6400
-const Default_GoTest_F_FloatDefaulted float32 = 314159
-const Default_GoTest_F_DoubleDefaulted float64 = 271828
-const Default_GoTest_F_StringDefaulted string = "hello, \"world!\"\n"
-
-var Default_GoTest_F_BytesDefaulted []byte = []byte("Bignose")
-
-const Default_GoTest_F_Sint32Defaulted int32 = -32
-const Default_GoTest_F_Sint64Defaulted int64 = -64
-
-func (m *GoTest) GetKind() GoTest_KIND {
- if m != nil && m.Kind != nil {
- return *m.Kind
- }
- return GoTest_VOID
-}
-
-func (m *GoTest) GetTable() string {
- if m != nil && m.Table != nil {
- return *m.Table
- }
- return ""
-}
-
-func (m *GoTest) GetParam() int32 {
- if m != nil && m.Param != nil {
- return *m.Param
- }
- return 0
-}
-
-func (m *GoTest) GetRequiredField() *GoTestField {
- if m != nil {
- return m.RequiredField
- }
- return nil
-}
-
-func (m *GoTest) GetRepeatedField() []*GoTestField {
- if m != nil {
- return m.RepeatedField
- }
- return nil
-}
-
-func (m *GoTest) GetOptionalField() *GoTestField {
- if m != nil {
- return m.OptionalField
- }
- return nil
-}
-
-func (m *GoTest) GetF_BoolRequired() bool {
- if m != nil && m.F_BoolRequired != nil {
- return *m.F_BoolRequired
- }
- return false
-}
-
-func (m *GoTest) GetF_Int32Required() int32 {
- if m != nil && m.F_Int32Required != nil {
- return *m.F_Int32Required
- }
- return 0
-}
-
-func (m *GoTest) GetF_Int64Required() int64 {
- if m != nil && m.F_Int64Required != nil {
- return *m.F_Int64Required
- }
- return 0
-}
-
-func (m *GoTest) GetF_Fixed32Required() uint32 {
- if m != nil && m.F_Fixed32Required != nil {
- return *m.F_Fixed32Required
- }
- return 0
-}
-
-func (m *GoTest) GetF_Fixed64Required() uint64 {
- if m != nil && m.F_Fixed64Required != nil {
- return *m.F_Fixed64Required
- }
- return 0
-}
-
-func (m *GoTest) GetF_Uint32Required() uint32 {
- if m != nil && m.F_Uint32Required != nil {
- return *m.F_Uint32Required
- }
- return 0
-}
-
-func (m *GoTest) GetF_Uint64Required() uint64 {
- if m != nil && m.F_Uint64Required != nil {
- return *m.F_Uint64Required
- }
- return 0
-}
-
-func (m *GoTest) GetF_FloatRequired() float32 {
- if m != nil && m.F_FloatRequired != nil {
- return *m.F_FloatRequired
- }
- return 0
-}
-
-func (m *GoTest) GetF_DoubleRequired() float64 {
- if m != nil && m.F_DoubleRequired != nil {
- return *m.F_DoubleRequired
- }
- return 0
-}
-
-func (m *GoTest) GetF_StringRequired() string {
- if m != nil && m.F_StringRequired != nil {
- return *m.F_StringRequired
- }
- return ""
-}
-
-func (m *GoTest) GetF_BytesRequired() []byte {
- if m != nil {
- return m.F_BytesRequired
- }
- return nil
-}
-
-func (m *GoTest) GetF_Sint32Required() int32 {
- if m != nil && m.F_Sint32Required != nil {
- return *m.F_Sint32Required
- }
- return 0
-}
-
-func (m *GoTest) GetF_Sint64Required() int64 {
- if m != nil && m.F_Sint64Required != nil {
- return *m.F_Sint64Required
- }
- return 0
-}
-
-func (m *GoTest) GetF_BoolRepeated() []bool {
- if m != nil {
- return m.F_BoolRepeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_Int32Repeated() []int32 {
- if m != nil {
- return m.F_Int32Repeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_Int64Repeated() []int64 {
- if m != nil {
- return m.F_Int64Repeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_Fixed32Repeated() []uint32 {
- if m != nil {
- return m.F_Fixed32Repeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_Fixed64Repeated() []uint64 {
- if m != nil {
- return m.F_Fixed64Repeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_Uint32Repeated() []uint32 {
- if m != nil {
- return m.F_Uint32Repeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_Uint64Repeated() []uint64 {
- if m != nil {
- return m.F_Uint64Repeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_FloatRepeated() []float32 {
- if m != nil {
- return m.F_FloatRepeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_DoubleRepeated() []float64 {
- if m != nil {
- return m.F_DoubleRepeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_StringRepeated() []string {
- if m != nil {
- return m.F_StringRepeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_BytesRepeated() [][]byte {
- if m != nil {
- return m.F_BytesRepeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_Sint32Repeated() []int32 {
- if m != nil {
- return m.F_Sint32Repeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_Sint64Repeated() []int64 {
- if m != nil {
- return m.F_Sint64Repeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_BoolOptional() bool {
- if m != nil && m.F_BoolOptional != nil {
- return *m.F_BoolOptional
- }
- return false
-}
-
-func (m *GoTest) GetF_Int32Optional() int32 {
- if m != nil && m.F_Int32Optional != nil {
- return *m.F_Int32Optional
- }
- return 0
-}
-
-func (m *GoTest) GetF_Int64Optional() int64 {
- if m != nil && m.F_Int64Optional != nil {
- return *m.F_Int64Optional
- }
- return 0
-}
-
-func (m *GoTest) GetF_Fixed32Optional() uint32 {
- if m != nil && m.F_Fixed32Optional != nil {
- return *m.F_Fixed32Optional
- }
- return 0
-}
-
-func (m *GoTest) GetF_Fixed64Optional() uint64 {
- if m != nil && m.F_Fixed64Optional != nil {
- return *m.F_Fixed64Optional
- }
- return 0
-}
-
-func (m *GoTest) GetF_Uint32Optional() uint32 {
- if m != nil && m.F_Uint32Optional != nil {
- return *m.F_Uint32Optional
- }
- return 0
-}
-
-func (m *GoTest) GetF_Uint64Optional() uint64 {
- if m != nil && m.F_Uint64Optional != nil {
- return *m.F_Uint64Optional
- }
- return 0
-}
-
-func (m *GoTest) GetF_FloatOptional() float32 {
- if m != nil && m.F_FloatOptional != nil {
- return *m.F_FloatOptional
- }
- return 0
-}
-
-func (m *GoTest) GetF_DoubleOptional() float64 {
- if m != nil && m.F_DoubleOptional != nil {
- return *m.F_DoubleOptional
- }
- return 0
-}
-
-func (m *GoTest) GetF_StringOptional() string {
- if m != nil && m.F_StringOptional != nil {
- return *m.F_StringOptional
- }
- return ""
-}
-
-func (m *GoTest) GetF_BytesOptional() []byte {
- if m != nil {
- return m.F_BytesOptional
- }
- return nil
-}
-
-func (m *GoTest) GetF_Sint32Optional() int32 {
- if m != nil && m.F_Sint32Optional != nil {
- return *m.F_Sint32Optional
- }
- return 0
-}
-
-func (m *GoTest) GetF_Sint64Optional() int64 {
- if m != nil && m.F_Sint64Optional != nil {
- return *m.F_Sint64Optional
- }
- return 0
-}
-
-func (m *GoTest) GetF_BoolDefaulted() bool {
- if m != nil && m.F_BoolDefaulted != nil {
- return *m.F_BoolDefaulted
- }
- return Default_GoTest_F_BoolDefaulted
-}
-
-func (m *GoTest) GetF_Int32Defaulted() int32 {
- if m != nil && m.F_Int32Defaulted != nil {
- return *m.F_Int32Defaulted
- }
- return Default_GoTest_F_Int32Defaulted
-}
-
-func (m *GoTest) GetF_Int64Defaulted() int64 {
- if m != nil && m.F_Int64Defaulted != nil {
- return *m.F_Int64Defaulted
- }
- return Default_GoTest_F_Int64Defaulted
-}
-
-func (m *GoTest) GetF_Fixed32Defaulted() uint32 {
- if m != nil && m.F_Fixed32Defaulted != nil {
- return *m.F_Fixed32Defaulted
- }
- return Default_GoTest_F_Fixed32Defaulted
-}
-
-func (m *GoTest) GetF_Fixed64Defaulted() uint64 {
- if m != nil && m.F_Fixed64Defaulted != nil {
- return *m.F_Fixed64Defaulted
- }
- return Default_GoTest_F_Fixed64Defaulted
-}
-
-func (m *GoTest) GetF_Uint32Defaulted() uint32 {
- if m != nil && m.F_Uint32Defaulted != nil {
- return *m.F_Uint32Defaulted
- }
- return Default_GoTest_F_Uint32Defaulted
-}
-
-func (m *GoTest) GetF_Uint64Defaulted() uint64 {
- if m != nil && m.F_Uint64Defaulted != nil {
- return *m.F_Uint64Defaulted
- }
- return Default_GoTest_F_Uint64Defaulted
-}
-
-func (m *GoTest) GetF_FloatDefaulted() float32 {
- if m != nil && m.F_FloatDefaulted != nil {
- return *m.F_FloatDefaulted
- }
- return Default_GoTest_F_FloatDefaulted
-}
-
-func (m *GoTest) GetF_DoubleDefaulted() float64 {
- if m != nil && m.F_DoubleDefaulted != nil {
- return *m.F_DoubleDefaulted
- }
- return Default_GoTest_F_DoubleDefaulted
-}
-
-func (m *GoTest) GetF_StringDefaulted() string {
- if m != nil && m.F_StringDefaulted != nil {
- return *m.F_StringDefaulted
- }
- return Default_GoTest_F_StringDefaulted
-}
-
-func (m *GoTest) GetF_BytesDefaulted() []byte {
- if m != nil && m.F_BytesDefaulted != nil {
- return m.F_BytesDefaulted
- }
- return append([]byte(nil), Default_GoTest_F_BytesDefaulted...)
-}
-
-func (m *GoTest) GetF_Sint32Defaulted() int32 {
- if m != nil && m.F_Sint32Defaulted != nil {
- return *m.F_Sint32Defaulted
- }
- return Default_GoTest_F_Sint32Defaulted
-}
-
-func (m *GoTest) GetF_Sint64Defaulted() int64 {
- if m != nil && m.F_Sint64Defaulted != nil {
- return *m.F_Sint64Defaulted
- }
- return Default_GoTest_F_Sint64Defaulted
-}
-
-func (m *GoTest) GetF_BoolRepeatedPacked() []bool {
- if m != nil {
- return m.F_BoolRepeatedPacked
- }
- return nil
-}
-
-func (m *GoTest) GetF_Int32RepeatedPacked() []int32 {
- if m != nil {
- return m.F_Int32RepeatedPacked
- }
- return nil
-}
-
-func (m *GoTest) GetF_Int64RepeatedPacked() []int64 {
- if m != nil {
- return m.F_Int64RepeatedPacked
- }
- return nil
-}
-
-func (m *GoTest) GetF_Fixed32RepeatedPacked() []uint32 {
- if m != nil {
- return m.F_Fixed32RepeatedPacked
- }
- return nil
-}
-
-func (m *GoTest) GetF_Fixed64RepeatedPacked() []uint64 {
- if m != nil {
- return m.F_Fixed64RepeatedPacked
- }
- return nil
-}
-
-func (m *GoTest) GetF_Uint32RepeatedPacked() []uint32 {
- if m != nil {
- return m.F_Uint32RepeatedPacked
- }
- return nil
-}
-
-func (m *GoTest) GetF_Uint64RepeatedPacked() []uint64 {
- if m != nil {
- return m.F_Uint64RepeatedPacked
- }
- return nil
-}
-
-func (m *GoTest) GetF_FloatRepeatedPacked() []float32 {
- if m != nil {
- return m.F_FloatRepeatedPacked
- }
- return nil
-}
-
-func (m *GoTest) GetF_DoubleRepeatedPacked() []float64 {
- if m != nil {
- return m.F_DoubleRepeatedPacked
- }
- return nil
-}
-
-func (m *GoTest) GetF_Sint32RepeatedPacked() []int32 {
- if m != nil {
- return m.F_Sint32RepeatedPacked
- }
- return nil
-}
-
-func (m *GoTest) GetF_Sint64RepeatedPacked() []int64 {
- if m != nil {
- return m.F_Sint64RepeatedPacked
- }
- return nil
-}
-
-func (m *GoTest) GetRequiredgroup() *GoTest_RequiredGroup {
- if m != nil {
- return m.Requiredgroup
- }
- return nil
-}
-
-func (m *GoTest) GetRepeatedgroup() []*GoTest_RepeatedGroup {
- if m != nil {
- return m.Repeatedgroup
- }
- return nil
-}
-
-func (m *GoTest) GetOptionalgroup() *GoTest_OptionalGroup {
- if m != nil {
- return m.Optionalgroup
- }
- return nil
-}
-
-// Required, repeated, and optional groups.
-type GoTest_RequiredGroup struct {
- RequiredField *string `protobuf:"bytes,71,req,name=RequiredField,json=requiredField" json:"RequiredField,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GoTest_RequiredGroup) Reset() { *m = GoTest_RequiredGroup{} }
-func (m *GoTest_RequiredGroup) String() string { return proto.CompactTextString(m) }
-func (*GoTest_RequiredGroup) ProtoMessage() {}
-func (*GoTest_RequiredGroup) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 0} }
-
-func (m *GoTest_RequiredGroup) GetRequiredField() string {
- if m != nil && m.RequiredField != nil {
- return *m.RequiredField
- }
- return ""
-}
-
-type GoTest_RepeatedGroup struct {
- RequiredField *string `protobuf:"bytes,81,req,name=RequiredField,json=requiredField" json:"RequiredField,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GoTest_RepeatedGroup) Reset() { *m = GoTest_RepeatedGroup{} }
-func (m *GoTest_RepeatedGroup) String() string { return proto.CompactTextString(m) }
-func (*GoTest_RepeatedGroup) ProtoMessage() {}
-func (*GoTest_RepeatedGroup) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 1} }
-
-func (m *GoTest_RepeatedGroup) GetRequiredField() string {
- if m != nil && m.RequiredField != nil {
- return *m.RequiredField
- }
- return ""
-}
-
-type GoTest_OptionalGroup struct {
- RequiredField *string `protobuf:"bytes,91,req,name=RequiredField,json=requiredField" json:"RequiredField,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GoTest_OptionalGroup) Reset() { *m = GoTest_OptionalGroup{} }
-func (m *GoTest_OptionalGroup) String() string { return proto.CompactTextString(m) }
-func (*GoTest_OptionalGroup) ProtoMessage() {}
-func (*GoTest_OptionalGroup) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 2} }
-
-func (m *GoTest_OptionalGroup) GetRequiredField() string {
- if m != nil && m.RequiredField != nil {
- return *m.RequiredField
- }
- return ""
-}
-
-// For testing skipping of unrecognized fields.
-// Numbers are all big, larger than tag numbers in GoTestField,
-// the message used in the corresponding test.
-type GoSkipTest struct {
- SkipInt32 *int32 `protobuf:"varint,11,req,name=skip_int32,json=skipInt32" json:"skip_int32,omitempty"`
- SkipFixed32 *uint32 `protobuf:"fixed32,12,req,name=skip_fixed32,json=skipFixed32" json:"skip_fixed32,omitempty"`
- SkipFixed64 *uint64 `protobuf:"fixed64,13,req,name=skip_fixed64,json=skipFixed64" json:"skip_fixed64,omitempty"`
- SkipString *string `protobuf:"bytes,14,req,name=skip_string,json=skipString" json:"skip_string,omitempty"`
- Skipgroup *GoSkipTest_SkipGroup `protobuf:"group,15,req,name=SkipGroup,json=skipgroup" json:"skipgroup,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GoSkipTest) Reset() { *m = GoSkipTest{} }
-func (m *GoSkipTest) String() string { return proto.CompactTextString(m) }
-func (*GoSkipTest) ProtoMessage() {}
-func (*GoSkipTest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} }
-
-func (m *GoSkipTest) GetSkipInt32() int32 {
- if m != nil && m.SkipInt32 != nil {
- return *m.SkipInt32
- }
- return 0
-}
-
-func (m *GoSkipTest) GetSkipFixed32() uint32 {
- if m != nil && m.SkipFixed32 != nil {
- return *m.SkipFixed32
- }
- return 0
-}
-
-func (m *GoSkipTest) GetSkipFixed64() uint64 {
- if m != nil && m.SkipFixed64 != nil {
- return *m.SkipFixed64
- }
- return 0
-}
-
-func (m *GoSkipTest) GetSkipString() string {
- if m != nil && m.SkipString != nil {
- return *m.SkipString
- }
- return ""
-}
-
-func (m *GoSkipTest) GetSkipgroup() *GoSkipTest_SkipGroup {
- if m != nil {
- return m.Skipgroup
- }
- return nil
-}
-
-type GoSkipTest_SkipGroup struct {
- GroupInt32 *int32 `protobuf:"varint,16,req,name=group_int32,json=groupInt32" json:"group_int32,omitempty"`
- GroupString *string `protobuf:"bytes,17,req,name=group_string,json=groupString" json:"group_string,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GoSkipTest_SkipGroup) Reset() { *m = GoSkipTest_SkipGroup{} }
-func (m *GoSkipTest_SkipGroup) String() string { return proto.CompactTextString(m) }
-func (*GoSkipTest_SkipGroup) ProtoMessage() {}
-func (*GoSkipTest_SkipGroup) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3, 0} }
-
-func (m *GoSkipTest_SkipGroup) GetGroupInt32() int32 {
- if m != nil && m.GroupInt32 != nil {
- return *m.GroupInt32
- }
- return 0
-}
-
-func (m *GoSkipTest_SkipGroup) GetGroupString() string {
- if m != nil && m.GroupString != nil {
- return *m.GroupString
- }
- return ""
-}
-
-// For testing packed/non-packed decoder switching.
-// A serialized instance of one should be deserializable as the other.
-type NonPackedTest struct {
- A []int32 `protobuf:"varint,1,rep,name=a" json:"a,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *NonPackedTest) Reset() { *m = NonPackedTest{} }
-func (m *NonPackedTest) String() string { return proto.CompactTextString(m) }
-func (*NonPackedTest) ProtoMessage() {}
-func (*NonPackedTest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} }
-
-func (m *NonPackedTest) GetA() []int32 {
- if m != nil {
- return m.A
- }
- return nil
-}
-
-type PackedTest struct {
- B []int32 `protobuf:"varint,1,rep,packed,name=b" json:"b,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *PackedTest) Reset() { *m = PackedTest{} }
-func (m *PackedTest) String() string { return proto.CompactTextString(m) }
-func (*PackedTest) ProtoMessage() {}
-func (*PackedTest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} }
-
-func (m *PackedTest) GetB() []int32 {
- if m != nil {
- return m.B
- }
- return nil
-}
-
-type MaxTag struct {
- // Maximum possible tag number.
- LastField *string `protobuf:"bytes,536870911,opt,name=last_field,json=lastField" json:"last_field,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *MaxTag) Reset() { *m = MaxTag{} }
-func (m *MaxTag) String() string { return proto.CompactTextString(m) }
-func (*MaxTag) ProtoMessage() {}
-func (*MaxTag) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} }
-
-func (m *MaxTag) GetLastField() string {
- if m != nil && m.LastField != nil {
- return *m.LastField
- }
- return ""
-}
-
-type OldMessage struct {
- Nested *OldMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"`
- Num *int32 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *OldMessage) Reset() { *m = OldMessage{} }
-func (m *OldMessage) String() string { return proto.CompactTextString(m) }
-func (*OldMessage) ProtoMessage() {}
-func (*OldMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} }
-
-func (m *OldMessage) GetNested() *OldMessage_Nested {
- if m != nil {
- return m.Nested
- }
- return nil
-}
-
-func (m *OldMessage) GetNum() int32 {
- if m != nil && m.Num != nil {
- return *m.Num
- }
- return 0
-}
-
-type OldMessage_Nested struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *OldMessage_Nested) Reset() { *m = OldMessage_Nested{} }
-func (m *OldMessage_Nested) String() string { return proto.CompactTextString(m) }
-func (*OldMessage_Nested) ProtoMessage() {}
-func (*OldMessage_Nested) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7, 0} }
-
-func (m *OldMessage_Nested) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-// NewMessage is wire compatible with OldMessage;
-// imagine it as a future version.
-type NewMessage struct {
- Nested *NewMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"`
- // This is an int32 in OldMessage.
- Num *int64 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *NewMessage) Reset() { *m = NewMessage{} }
-func (m *NewMessage) String() string { return proto.CompactTextString(m) }
-func (*NewMessage) ProtoMessage() {}
-func (*NewMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} }
-
-func (m *NewMessage) GetNested() *NewMessage_Nested {
- if m != nil {
- return m.Nested
- }
- return nil
-}
-
-func (m *NewMessage) GetNum() int64 {
- if m != nil && m.Num != nil {
- return *m.Num
- }
- return 0
-}
-
-type NewMessage_Nested struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- FoodGroup *string `protobuf:"bytes,2,opt,name=food_group,json=foodGroup" json:"food_group,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *NewMessage_Nested) Reset() { *m = NewMessage_Nested{} }
-func (m *NewMessage_Nested) String() string { return proto.CompactTextString(m) }
-func (*NewMessage_Nested) ProtoMessage() {}
-func (*NewMessage_Nested) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8, 0} }
-
-func (m *NewMessage_Nested) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *NewMessage_Nested) GetFoodGroup() string {
- if m != nil && m.FoodGroup != nil {
- return *m.FoodGroup
- }
- return ""
-}
-
-type InnerMessage struct {
- Host *string `protobuf:"bytes,1,req,name=host" json:"host,omitempty"`
- Port *int32 `protobuf:"varint,2,opt,name=port,def=4000" json:"port,omitempty"`
- Connected *bool `protobuf:"varint,3,opt,name=connected" json:"connected,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *InnerMessage) Reset() { *m = InnerMessage{} }
-func (m *InnerMessage) String() string { return proto.CompactTextString(m) }
-func (*InnerMessage) ProtoMessage() {}
-func (*InnerMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{9} }
-
-const Default_InnerMessage_Port int32 = 4000
-
-func (m *InnerMessage) GetHost() string {
- if m != nil && m.Host != nil {
- return *m.Host
- }
- return ""
-}
-
-func (m *InnerMessage) GetPort() int32 {
- if m != nil && m.Port != nil {
- return *m.Port
- }
- return Default_InnerMessage_Port
-}
-
-func (m *InnerMessage) GetConnected() bool {
- if m != nil && m.Connected != nil {
- return *m.Connected
- }
- return false
-}
-
-type OtherMessage struct {
- Key *int64 `protobuf:"varint,1,opt,name=key" json:"key,omitempty"`
- Value []byte `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"`
- Weight *float32 `protobuf:"fixed32,3,opt,name=weight" json:"weight,omitempty"`
- Inner *InnerMessage `protobuf:"bytes,4,opt,name=inner" json:"inner,omitempty"`
- XXX_extensions map[int32]proto.Extension `json:"-"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *OtherMessage) Reset() { *m = OtherMessage{} }
-func (m *OtherMessage) String() string { return proto.CompactTextString(m) }
-func (*OtherMessage) ProtoMessage() {}
-func (*OtherMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{10} }
-
-var extRange_OtherMessage = []proto.ExtensionRange{
- {100, 536870911},
-}
-
-func (*OtherMessage) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_OtherMessage
-}
-func (m *OtherMessage) ExtensionMap() map[int32]proto.Extension {
- if m.XXX_extensions == nil {
- m.XXX_extensions = make(map[int32]proto.Extension)
- }
- return m.XXX_extensions
-}
-
-func (m *OtherMessage) GetKey() int64 {
- if m != nil && m.Key != nil {
- return *m.Key
- }
- return 0
-}
-
-func (m *OtherMessage) GetValue() []byte {
- if m != nil {
- return m.Value
- }
- return nil
-}
-
-func (m *OtherMessage) GetWeight() float32 {
- if m != nil && m.Weight != nil {
- return *m.Weight
- }
- return 0
-}
-
-func (m *OtherMessage) GetInner() *InnerMessage {
- if m != nil {
- return m.Inner
- }
- return nil
-}
-
-type RequiredInnerMessage struct {
- LeoFinallyWonAnOscar *InnerMessage `protobuf:"bytes,1,req,name=leo_finally_won_an_oscar,json=leoFinallyWonAnOscar" json:"leo_finally_won_an_oscar,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *RequiredInnerMessage) Reset() { *m = RequiredInnerMessage{} }
-func (m *RequiredInnerMessage) String() string { return proto.CompactTextString(m) }
-func (*RequiredInnerMessage) ProtoMessage() {}
-func (*RequiredInnerMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{11} }
-
-func (m *RequiredInnerMessage) GetLeoFinallyWonAnOscar() *InnerMessage {
- if m != nil {
- return m.LeoFinallyWonAnOscar
- }
- return nil
-}
-
-type MyMessage struct {
- Count *int32 `protobuf:"varint,1,req,name=count" json:"count,omitempty"`
- Name *string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"`
- Quote *string `protobuf:"bytes,3,opt,name=quote" json:"quote,omitempty"`
- Pet []string `protobuf:"bytes,4,rep,name=pet" json:"pet,omitempty"`
- Inner *InnerMessage `protobuf:"bytes,5,opt,name=inner" json:"inner,omitempty"`
- Others []*OtherMessage `protobuf:"bytes,6,rep,name=others" json:"others,omitempty"`
- WeMustGoDeeper *RequiredInnerMessage `protobuf:"bytes,13,opt,name=we_must_go_deeper,json=weMustGoDeeper" json:"we_must_go_deeper,omitempty"`
- RepInner []*InnerMessage `protobuf:"bytes,12,rep,name=rep_inner,json=repInner" json:"rep_inner,omitempty"`
- Bikeshed *MyMessage_Color `protobuf:"varint,7,opt,name=bikeshed,enum=testdata.MyMessage_Color" json:"bikeshed,omitempty"`
- Somegroup *MyMessage_SomeGroup `protobuf:"group,8,opt,name=SomeGroup,json=somegroup" json:"somegroup,omitempty"`
- // This field becomes [][]byte in the generated code.
- RepBytes [][]byte `protobuf:"bytes,10,rep,name=rep_bytes,json=repBytes" json:"rep_bytes,omitempty"`
- Bigfloat *float64 `protobuf:"fixed64,11,opt,name=bigfloat" json:"bigfloat,omitempty"`
- XXX_extensions map[int32]proto.Extension `json:"-"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *MyMessage) Reset() { *m = MyMessage{} }
-func (m *MyMessage) String() string { return proto.CompactTextString(m) }
-func (*MyMessage) ProtoMessage() {}
-func (*MyMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{12} }
-
-var extRange_MyMessage = []proto.ExtensionRange{
- {100, 536870911},
-}
-
-func (*MyMessage) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_MyMessage
-}
-func (m *MyMessage) ExtensionMap() map[int32]proto.Extension {
- if m.XXX_extensions == nil {
- m.XXX_extensions = make(map[int32]proto.Extension)
- }
- return m.XXX_extensions
-}
-
-func (m *MyMessage) GetCount() int32 {
- if m != nil && m.Count != nil {
- return *m.Count
- }
- return 0
-}
-
-func (m *MyMessage) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *MyMessage) GetQuote() string {
- if m != nil && m.Quote != nil {
- return *m.Quote
- }
- return ""
-}
-
-func (m *MyMessage) GetPet() []string {
- if m != nil {
- return m.Pet
- }
- return nil
-}
-
-func (m *MyMessage) GetInner() *InnerMessage {
- if m != nil {
- return m.Inner
- }
- return nil
-}
-
-func (m *MyMessage) GetOthers() []*OtherMessage {
- if m != nil {
- return m.Others
- }
- return nil
-}
-
-func (m *MyMessage) GetWeMustGoDeeper() *RequiredInnerMessage {
- if m != nil {
- return m.WeMustGoDeeper
- }
- return nil
-}
-
-func (m *MyMessage) GetRepInner() []*InnerMessage {
- if m != nil {
- return m.RepInner
- }
- return nil
-}
-
-func (m *MyMessage) GetBikeshed() MyMessage_Color {
- if m != nil && m.Bikeshed != nil {
- return *m.Bikeshed
- }
- return MyMessage_RED
-}
-
-func (m *MyMessage) GetSomegroup() *MyMessage_SomeGroup {
- if m != nil {
- return m.Somegroup
- }
- return nil
-}
-
-func (m *MyMessage) GetRepBytes() [][]byte {
- if m != nil {
- return m.RepBytes
- }
- return nil
-}
-
-func (m *MyMessage) GetBigfloat() float64 {
- if m != nil && m.Bigfloat != nil {
- return *m.Bigfloat
- }
- return 0
-}
-
-type MyMessage_SomeGroup struct {
- GroupField *int32 `protobuf:"varint,9,opt,name=group_field,json=groupField" json:"group_field,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *MyMessage_SomeGroup) Reset() { *m = MyMessage_SomeGroup{} }
-func (m *MyMessage_SomeGroup) String() string { return proto.CompactTextString(m) }
-func (*MyMessage_SomeGroup) ProtoMessage() {}
-func (*MyMessage_SomeGroup) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{12, 0} }
-
-func (m *MyMessage_SomeGroup) GetGroupField() int32 {
- if m != nil && m.GroupField != nil {
- return *m.GroupField
- }
- return 0
-}
-
-type Ext struct {
- Data *string `protobuf:"bytes,1,opt,name=data" json:"data,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *Ext) Reset() { *m = Ext{} }
-func (m *Ext) String() string { return proto.CompactTextString(m) }
-func (*Ext) ProtoMessage() {}
-func (*Ext) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{13} }
-
-func (m *Ext) GetData() string {
- if m != nil && m.Data != nil {
- return *m.Data
- }
- return ""
-}
-
-var E_Ext_More = &proto.ExtensionDesc{
- ExtendedType: (*MyMessage)(nil),
- ExtensionType: (*Ext)(nil),
- Field: 103,
- Name: "testdata.Ext.more",
- Tag: "bytes,103,opt,name=more",
-}
-
-var E_Ext_Text = &proto.ExtensionDesc{
- ExtendedType: (*MyMessage)(nil),
- ExtensionType: (*string)(nil),
- Field: 104,
- Name: "testdata.Ext.text",
- Tag: "bytes,104,opt,name=text",
-}
-
-var E_Ext_Number = &proto.ExtensionDesc{
- ExtendedType: (*MyMessage)(nil),
- ExtensionType: (*int32)(nil),
- Field: 105,
- Name: "testdata.Ext.number",
- Tag: "varint,105,opt,name=number",
-}
-
-type ComplexExtension struct {
- First *int32 `protobuf:"varint,1,opt,name=first" json:"first,omitempty"`
- Second *int32 `protobuf:"varint,2,opt,name=second" json:"second,omitempty"`
- Third []int32 `protobuf:"varint,3,rep,name=third" json:"third,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *ComplexExtension) Reset() { *m = ComplexExtension{} }
-func (m *ComplexExtension) String() string { return proto.CompactTextString(m) }
-func (*ComplexExtension) ProtoMessage() {}
-func (*ComplexExtension) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{14} }
-
-func (m *ComplexExtension) GetFirst() int32 {
- if m != nil && m.First != nil {
- return *m.First
- }
- return 0
-}
-
-func (m *ComplexExtension) GetSecond() int32 {
- if m != nil && m.Second != nil {
- return *m.Second
- }
- return 0
-}
-
-func (m *ComplexExtension) GetThird() []int32 {
- if m != nil {
- return m.Third
- }
- return nil
-}
-
-type DefaultsMessage struct {
- XXX_extensions map[int32]proto.Extension `json:"-"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *DefaultsMessage) Reset() { *m = DefaultsMessage{} }
-func (m *DefaultsMessage) String() string { return proto.CompactTextString(m) }
-func (*DefaultsMessage) ProtoMessage() {}
-func (*DefaultsMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{15} }
-
-var extRange_DefaultsMessage = []proto.ExtensionRange{
- {100, 536870911},
-}
-
-func (*DefaultsMessage) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_DefaultsMessage
-}
-func (m *DefaultsMessage) ExtensionMap() map[int32]proto.Extension {
- if m.XXX_extensions == nil {
- m.XXX_extensions = make(map[int32]proto.Extension)
- }
- return m.XXX_extensions
-}
-
-type MyMessageSet struct {
- XXX_extensions map[int32]proto.Extension `json:"-"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *MyMessageSet) Reset() { *m = MyMessageSet{} }
-func (m *MyMessageSet) String() string { return proto.CompactTextString(m) }
-func (*MyMessageSet) ProtoMessage() {}
-func (*MyMessageSet) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{16} }
-
-func (m *MyMessageSet) Marshal() ([]byte, error) {
- return proto.MarshalMessageSet(m.ExtensionMap())
-}
-func (m *MyMessageSet) Unmarshal(buf []byte) error {
- return proto.UnmarshalMessageSet(buf, m.ExtensionMap())
-}
-func (m *MyMessageSet) MarshalJSON() ([]byte, error) {
- return proto.MarshalMessageSetJSON(m.XXX_extensions)
-}
-func (m *MyMessageSet) UnmarshalJSON(buf []byte) error {
- return proto.UnmarshalMessageSetJSON(buf, m.XXX_extensions)
-}
-
-// ensure MyMessageSet satisfies proto.Marshaler and proto.Unmarshaler
-var _ proto.Marshaler = (*MyMessageSet)(nil)
-var _ proto.Unmarshaler = (*MyMessageSet)(nil)
-
-var extRange_MyMessageSet = []proto.ExtensionRange{
- {100, 2147483646},
-}
-
-func (*MyMessageSet) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_MyMessageSet
-}
-func (m *MyMessageSet) ExtensionMap() map[int32]proto.Extension {
- if m.XXX_extensions == nil {
- m.XXX_extensions = make(map[int32]proto.Extension)
- }
- return m.XXX_extensions
-}
-
-type Empty struct {
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *Empty) Reset() { *m = Empty{} }
-func (m *Empty) String() string { return proto.CompactTextString(m) }
-func (*Empty) ProtoMessage() {}
-func (*Empty) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{17} }
-
-type MessageList struct {
- Message []*MessageList_Message `protobuf:"group,1,rep,name=Message,json=message" json:"message,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *MessageList) Reset() { *m = MessageList{} }
-func (m *MessageList) String() string { return proto.CompactTextString(m) }
-func (*MessageList) ProtoMessage() {}
-func (*MessageList) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{18} }
-
-func (m *MessageList) GetMessage() []*MessageList_Message {
- if m != nil {
- return m.Message
- }
- return nil
-}
-
-type MessageList_Message struct {
- Name *string `protobuf:"bytes,2,req,name=name" json:"name,omitempty"`
- Count *int32 `protobuf:"varint,3,req,name=count" json:"count,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *MessageList_Message) Reset() { *m = MessageList_Message{} }
-func (m *MessageList_Message) String() string { return proto.CompactTextString(m) }
-func (*MessageList_Message) ProtoMessage() {}
-func (*MessageList_Message) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{18, 0} }
-
-func (m *MessageList_Message) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *MessageList_Message) GetCount() int32 {
- if m != nil && m.Count != nil {
- return *m.Count
- }
- return 0
-}
-
-type Strings struct {
- StringField *string `protobuf:"bytes,1,opt,name=string_field,json=stringField" json:"string_field,omitempty"`
- BytesField []byte `protobuf:"bytes,2,opt,name=bytes_field,json=bytesField" json:"bytes_field,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *Strings) Reset() { *m = Strings{} }
-func (m *Strings) String() string { return proto.CompactTextString(m) }
-func (*Strings) ProtoMessage() {}
-func (*Strings) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{19} }
-
-func (m *Strings) GetStringField() string {
- if m != nil && m.StringField != nil {
- return *m.StringField
- }
- return ""
-}
-
-func (m *Strings) GetBytesField() []byte {
- if m != nil {
- return m.BytesField
- }
- return nil
-}
-
-type Defaults struct {
- // Default-valued fields of all basic types.
- // Same as GoTest, but copied here to make testing easier.
- F_Bool *bool `protobuf:"varint,1,opt,name=F_Bool,json=fBool,def=1" json:"F_Bool,omitempty"`
- F_Int32 *int32 `protobuf:"varint,2,opt,name=F_Int32,json=fInt32,def=32" json:"F_Int32,omitempty"`
- F_Int64 *int64 `protobuf:"varint,3,opt,name=F_Int64,json=fInt64,def=64" json:"F_Int64,omitempty"`
- F_Fixed32 *uint32 `protobuf:"fixed32,4,opt,name=F_Fixed32,json=fFixed32,def=320" json:"F_Fixed32,omitempty"`
- F_Fixed64 *uint64 `protobuf:"fixed64,5,opt,name=F_Fixed64,json=fFixed64,def=640" json:"F_Fixed64,omitempty"`
- F_Uint32 *uint32 `protobuf:"varint,6,opt,name=F_Uint32,json=fUint32,def=3200" json:"F_Uint32,omitempty"`
- F_Uint64 *uint64 `protobuf:"varint,7,opt,name=F_Uint64,json=fUint64,def=6400" json:"F_Uint64,omitempty"`
- F_Float *float32 `protobuf:"fixed32,8,opt,name=F_Float,json=fFloat,def=314159" json:"F_Float,omitempty"`
- F_Double *float64 `protobuf:"fixed64,9,opt,name=F_Double,json=fDouble,def=271828" json:"F_Double,omitempty"`
- F_String *string `protobuf:"bytes,10,opt,name=F_String,json=fString,def=hello, \"world!\"\n" json:"F_String,omitempty"`
- F_Bytes []byte `protobuf:"bytes,11,opt,name=F_Bytes,json=fBytes,def=Bignose" json:"F_Bytes,omitempty"`
- F_Sint32 *int32 `protobuf:"zigzag32,12,opt,name=F_Sint32,json=fSint32,def=-32" json:"F_Sint32,omitempty"`
- F_Sint64 *int64 `protobuf:"zigzag64,13,opt,name=F_Sint64,json=fSint64,def=-64" json:"F_Sint64,omitempty"`
- F_Enum *Defaults_Color `protobuf:"varint,14,opt,name=F_Enum,json=fEnum,enum=testdata.Defaults_Color,def=1" json:"F_Enum,omitempty"`
- // More fields with crazy defaults.
- F_Pinf *float32 `protobuf:"fixed32,15,opt,name=F_Pinf,json=fPinf,def=inf" json:"F_Pinf,omitempty"`
- F_Ninf *float32 `protobuf:"fixed32,16,opt,name=F_Ninf,json=fNinf,def=-inf" json:"F_Ninf,omitempty"`
- F_Nan *float32 `protobuf:"fixed32,17,opt,name=F_Nan,json=fNan,def=nan" json:"F_Nan,omitempty"`
- // Sub-message.
- Sub *SubDefaults `protobuf:"bytes,18,opt,name=sub" json:"sub,omitempty"`
- // Redundant but explicit defaults.
- StrZero *string `protobuf:"bytes,19,opt,name=str_zero,json=strZero,def=" json:"str_zero,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *Defaults) Reset() { *m = Defaults{} }
-func (m *Defaults) String() string { return proto.CompactTextString(m) }
-func (*Defaults) ProtoMessage() {}
-func (*Defaults) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{20} }
-
-const Default_Defaults_F_Bool bool = true
-const Default_Defaults_F_Int32 int32 = 32
-const Default_Defaults_F_Int64 int64 = 64
-const Default_Defaults_F_Fixed32 uint32 = 320
-const Default_Defaults_F_Fixed64 uint64 = 640
-const Default_Defaults_F_Uint32 uint32 = 3200
-const Default_Defaults_F_Uint64 uint64 = 6400
-const Default_Defaults_F_Float float32 = 314159
-const Default_Defaults_F_Double float64 = 271828
-const Default_Defaults_F_String string = "hello, \"world!\"\n"
-
-var Default_Defaults_F_Bytes []byte = []byte("Bignose")
-
-const Default_Defaults_F_Sint32 int32 = -32
-const Default_Defaults_F_Sint64 int64 = -64
-const Default_Defaults_F_Enum Defaults_Color = Defaults_GREEN
-
-var Default_Defaults_F_Pinf float32 = float32(math.Inf(1))
-var Default_Defaults_F_Ninf float32 = float32(math.Inf(-1))
-var Default_Defaults_F_Nan float32 = float32(math.NaN())
-
-func (m *Defaults) GetF_Bool() bool {
- if m != nil && m.F_Bool != nil {
- return *m.F_Bool
- }
- return Default_Defaults_F_Bool
-}
-
-func (m *Defaults) GetF_Int32() int32 {
- if m != nil && m.F_Int32 != nil {
- return *m.F_Int32
- }
- return Default_Defaults_F_Int32
-}
-
-func (m *Defaults) GetF_Int64() int64 {
- if m != nil && m.F_Int64 != nil {
- return *m.F_Int64
- }
- return Default_Defaults_F_Int64
-}
-
-func (m *Defaults) GetF_Fixed32() uint32 {
- if m != nil && m.F_Fixed32 != nil {
- return *m.F_Fixed32
- }
- return Default_Defaults_F_Fixed32
-}
-
-func (m *Defaults) GetF_Fixed64() uint64 {
- if m != nil && m.F_Fixed64 != nil {
- return *m.F_Fixed64
- }
- return Default_Defaults_F_Fixed64
-}
-
-func (m *Defaults) GetF_Uint32() uint32 {
- if m != nil && m.F_Uint32 != nil {
- return *m.F_Uint32
- }
- return Default_Defaults_F_Uint32
-}
-
-func (m *Defaults) GetF_Uint64() uint64 {
- if m != nil && m.F_Uint64 != nil {
- return *m.F_Uint64
- }
- return Default_Defaults_F_Uint64
-}
-
-func (m *Defaults) GetF_Float() float32 {
- if m != nil && m.F_Float != nil {
- return *m.F_Float
- }
- return Default_Defaults_F_Float
-}
-
-func (m *Defaults) GetF_Double() float64 {
- if m != nil && m.F_Double != nil {
- return *m.F_Double
- }
- return Default_Defaults_F_Double
-}
-
-func (m *Defaults) GetF_String() string {
- if m != nil && m.F_String != nil {
- return *m.F_String
- }
- return Default_Defaults_F_String
-}
-
-func (m *Defaults) GetF_Bytes() []byte {
- if m != nil && m.F_Bytes != nil {
- return m.F_Bytes
- }
- return append([]byte(nil), Default_Defaults_F_Bytes...)
-}
-
-func (m *Defaults) GetF_Sint32() int32 {
- if m != nil && m.F_Sint32 != nil {
- return *m.F_Sint32
- }
- return Default_Defaults_F_Sint32
-}
-
-func (m *Defaults) GetF_Sint64() int64 {
- if m != nil && m.F_Sint64 != nil {
- return *m.F_Sint64
- }
- return Default_Defaults_F_Sint64
-}
-
-func (m *Defaults) GetF_Enum() Defaults_Color {
- if m != nil && m.F_Enum != nil {
- return *m.F_Enum
- }
- return Default_Defaults_F_Enum
-}
-
-func (m *Defaults) GetF_Pinf() float32 {
- if m != nil && m.F_Pinf != nil {
- return *m.F_Pinf
- }
- return Default_Defaults_F_Pinf
-}
-
-func (m *Defaults) GetF_Ninf() float32 {
- if m != nil && m.F_Ninf != nil {
- return *m.F_Ninf
- }
- return Default_Defaults_F_Ninf
-}
-
-func (m *Defaults) GetF_Nan() float32 {
- if m != nil && m.F_Nan != nil {
- return *m.F_Nan
- }
- return Default_Defaults_F_Nan
-}
-
-func (m *Defaults) GetSub() *SubDefaults {
- if m != nil {
- return m.Sub
- }
- return nil
-}
-
-func (m *Defaults) GetStrZero() string {
- if m != nil && m.StrZero != nil {
- return *m.StrZero
- }
- return ""
-}
-
-type SubDefaults struct {
- N *int64 `protobuf:"varint,1,opt,name=n,def=7" json:"n,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *SubDefaults) Reset() { *m = SubDefaults{} }
-func (m *SubDefaults) String() string { return proto.CompactTextString(m) }
-func (*SubDefaults) ProtoMessage() {}
-func (*SubDefaults) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{21} }
-
-const Default_SubDefaults_N int64 = 7
-
-func (m *SubDefaults) GetN() int64 {
- if m != nil && m.N != nil {
- return *m.N
- }
- return Default_SubDefaults_N
-}
-
-type RepeatedEnum struct {
- Color []RepeatedEnum_Color `protobuf:"varint,1,rep,name=color,enum=testdata.RepeatedEnum_Color" json:"color,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *RepeatedEnum) Reset() { *m = RepeatedEnum{} }
-func (m *RepeatedEnum) String() string { return proto.CompactTextString(m) }
-func (*RepeatedEnum) ProtoMessage() {}
-func (*RepeatedEnum) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{22} }
-
-func (m *RepeatedEnum) GetColor() []RepeatedEnum_Color {
- if m != nil {
- return m.Color
- }
- return nil
-}
-
-type MoreRepeated struct {
- Bools []bool `protobuf:"varint,1,rep,name=bools" json:"bools,omitempty"`
- BoolsPacked []bool `protobuf:"varint,2,rep,packed,name=bools_packed,json=boolsPacked" json:"bools_packed,omitempty"`
- Ints []int32 `protobuf:"varint,3,rep,name=ints" json:"ints,omitempty"`
- IntsPacked []int32 `protobuf:"varint,4,rep,packed,name=ints_packed,json=intsPacked" json:"ints_packed,omitempty"`
- Int64SPacked []int64 `protobuf:"varint,7,rep,packed,name=int64s_packed,json=int64sPacked" json:"int64s_packed,omitempty"`
- Strings []string `protobuf:"bytes,5,rep,name=strings" json:"strings,omitempty"`
- Fixeds []uint32 `protobuf:"fixed32,6,rep,name=fixeds" json:"fixeds,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *MoreRepeated) Reset() { *m = MoreRepeated{} }
-func (m *MoreRepeated) String() string { return proto.CompactTextString(m) }
-func (*MoreRepeated) ProtoMessage() {}
-func (*MoreRepeated) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{23} }
-
-func (m *MoreRepeated) GetBools() []bool {
- if m != nil {
- return m.Bools
- }
- return nil
-}
-
-func (m *MoreRepeated) GetBoolsPacked() []bool {
- if m != nil {
- return m.BoolsPacked
- }
- return nil
-}
-
-func (m *MoreRepeated) GetInts() []int32 {
- if m != nil {
- return m.Ints
- }
- return nil
-}
-
-func (m *MoreRepeated) GetIntsPacked() []int32 {
- if m != nil {
- return m.IntsPacked
- }
- return nil
-}
-
-func (m *MoreRepeated) GetInt64SPacked() []int64 {
- if m != nil {
- return m.Int64SPacked
- }
- return nil
-}
-
-func (m *MoreRepeated) GetStrings() []string {
- if m != nil {
- return m.Strings
- }
- return nil
-}
-
-func (m *MoreRepeated) GetFixeds() []uint32 {
- if m != nil {
- return m.Fixeds
- }
- return nil
-}
-
-type GroupOld struct {
- G *GroupOld_G `protobuf:"group,101,opt,name=G,json=g" json:"g,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GroupOld) Reset() { *m = GroupOld{} }
-func (m *GroupOld) String() string { return proto.CompactTextString(m) }
-func (*GroupOld) ProtoMessage() {}
-func (*GroupOld) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{24} }
-
-func (m *GroupOld) GetG() *GroupOld_G {
- if m != nil {
- return m.G
- }
- return nil
-}
-
-type GroupOld_G struct {
- X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GroupOld_G) Reset() { *m = GroupOld_G{} }
-func (m *GroupOld_G) String() string { return proto.CompactTextString(m) }
-func (*GroupOld_G) ProtoMessage() {}
-func (*GroupOld_G) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{24, 0} }
-
-func (m *GroupOld_G) GetX() int32 {
- if m != nil && m.X != nil {
- return *m.X
- }
- return 0
-}
-
-type GroupNew struct {
- G *GroupNew_G `protobuf:"group,101,opt,name=G,json=g" json:"g,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GroupNew) Reset() { *m = GroupNew{} }
-func (m *GroupNew) String() string { return proto.CompactTextString(m) }
-func (*GroupNew) ProtoMessage() {}
-func (*GroupNew) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{25} }
-
-func (m *GroupNew) GetG() *GroupNew_G {
- if m != nil {
- return m.G
- }
- return nil
-}
-
-type GroupNew_G struct {
- X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"`
- Y *int32 `protobuf:"varint,3,opt,name=y" json:"y,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GroupNew_G) Reset() { *m = GroupNew_G{} }
-func (m *GroupNew_G) String() string { return proto.CompactTextString(m) }
-func (*GroupNew_G) ProtoMessage() {}
-func (*GroupNew_G) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{25, 0} }
-
-func (m *GroupNew_G) GetX() int32 {
- if m != nil && m.X != nil {
- return *m.X
- }
- return 0
-}
-
-func (m *GroupNew_G) GetY() int32 {
- if m != nil && m.Y != nil {
- return *m.Y
- }
- return 0
-}
-
-type FloatingPoint struct {
- F *float64 `protobuf:"fixed64,1,req,name=f" json:"f,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *FloatingPoint) Reset() { *m = FloatingPoint{} }
-func (m *FloatingPoint) String() string { return proto.CompactTextString(m) }
-func (*FloatingPoint) ProtoMessage() {}
-func (*FloatingPoint) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{26} }
-
-func (m *FloatingPoint) GetF() float64 {
- if m != nil && m.F != nil {
- return *m.F
- }
- return 0
-}
-
-type MessageWithMap struct {
- NameMapping map[int32]string `protobuf:"bytes,1,rep,name=name_mapping,json=nameMapping" json:"name_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- MsgMapping map[int64]*FloatingPoint `protobuf:"bytes,2,rep,name=msg_mapping,json=msgMapping" json:"msg_mapping,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- ByteMapping map[bool][]byte `protobuf:"bytes,3,rep,name=byte_mapping,json=byteMapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- StrToStr map[string]string `protobuf:"bytes,4,rep,name=str_to_str,json=strToStr" json:"str_to_str,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *MessageWithMap) Reset() { *m = MessageWithMap{} }
-func (m *MessageWithMap) String() string { return proto.CompactTextString(m) }
-func (*MessageWithMap) ProtoMessage() {}
-func (*MessageWithMap) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{27} }
-
-func (m *MessageWithMap) GetNameMapping() map[int32]string {
- if m != nil {
- return m.NameMapping
- }
- return nil
-}
-
-func (m *MessageWithMap) GetMsgMapping() map[int64]*FloatingPoint {
- if m != nil {
- return m.MsgMapping
- }
- return nil
-}
-
-func (m *MessageWithMap) GetByteMapping() map[bool][]byte {
- if m != nil {
- return m.ByteMapping
- }
- return nil
-}
-
-func (m *MessageWithMap) GetStrToStr() map[string]string {
- if m != nil {
- return m.StrToStr
- }
- return nil
-}
-
-type Oneof struct {
- // Types that are valid to be assigned to Union:
- // *Oneof_F_Bool
- // *Oneof_F_Int32
- // *Oneof_F_Int64
- // *Oneof_F_Fixed32
- // *Oneof_F_Fixed64
- // *Oneof_F_Uint32
- // *Oneof_F_Uint64
- // *Oneof_F_Float
- // *Oneof_F_Double
- // *Oneof_F_String
- // *Oneof_F_Bytes
- // *Oneof_F_Sint32
- // *Oneof_F_Sint64
- // *Oneof_F_Enum
- // *Oneof_F_Message
- // *Oneof_FGroup
- // *Oneof_F_Largest_Tag
- Union isOneof_Union `protobuf_oneof:"union"`
- // Types that are valid to be assigned to Tormato:
- // *Oneof_Value
- Tormato isOneof_Tormato `protobuf_oneof:"tormato"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *Oneof) Reset() { *m = Oneof{} }
-func (m *Oneof) String() string { return proto.CompactTextString(m) }
-func (*Oneof) ProtoMessage() {}
-func (*Oneof) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{28} }
-
-type isOneof_Union interface {
- isOneof_Union()
-}
-type isOneof_Tormato interface {
- isOneof_Tormato()
-}
-
-type Oneof_F_Bool struct {
- F_Bool bool `protobuf:"varint,1,opt,name=F_Bool,json=fBool,oneof"`
-}
-type Oneof_F_Int32 struct {
- F_Int32 int32 `protobuf:"varint,2,opt,name=F_Int32,json=fInt32,oneof"`
-}
-type Oneof_F_Int64 struct {
- F_Int64 int64 `protobuf:"varint,3,opt,name=F_Int64,json=fInt64,oneof"`
-}
-type Oneof_F_Fixed32 struct {
- F_Fixed32 uint32 `protobuf:"fixed32,4,opt,name=F_Fixed32,json=fFixed32,oneof"`
-}
-type Oneof_F_Fixed64 struct {
- F_Fixed64 uint64 `protobuf:"fixed64,5,opt,name=F_Fixed64,json=fFixed64,oneof"`
-}
-type Oneof_F_Uint32 struct {
- F_Uint32 uint32 `protobuf:"varint,6,opt,name=F_Uint32,json=fUint32,oneof"`
-}
-type Oneof_F_Uint64 struct {
- F_Uint64 uint64 `protobuf:"varint,7,opt,name=F_Uint64,json=fUint64,oneof"`
-}
-type Oneof_F_Float struct {
- F_Float float32 `protobuf:"fixed32,8,opt,name=F_Float,json=fFloat,oneof"`
-}
-type Oneof_F_Double struct {
- F_Double float64 `protobuf:"fixed64,9,opt,name=F_Double,json=fDouble,oneof"`
-}
-type Oneof_F_String struct {
- F_String string `protobuf:"bytes,10,opt,name=F_String,json=fString,oneof"`
-}
-type Oneof_F_Bytes struct {
- F_Bytes []byte `protobuf:"bytes,11,opt,name=F_Bytes,json=fBytes,oneof"`
-}
-type Oneof_F_Sint32 struct {
- F_Sint32 int32 `protobuf:"zigzag32,12,opt,name=F_Sint32,json=fSint32,oneof"`
-}
-type Oneof_F_Sint64 struct {
- F_Sint64 int64 `protobuf:"zigzag64,13,opt,name=F_Sint64,json=fSint64,oneof"`
-}
-type Oneof_F_Enum struct {
- F_Enum MyMessage_Color `protobuf:"varint,14,opt,name=F_Enum,json=fEnum,enum=testdata.MyMessage_Color,oneof"`
-}
-type Oneof_F_Message struct {
- F_Message *GoTestField `protobuf:"bytes,15,opt,name=F_Message,json=fMessage,oneof"`
-}
-type Oneof_FGroup struct {
- FGroup *Oneof_F_Group `protobuf:"group,16,opt,name=F_Group,json=fGroup,oneof"`
-}
-type Oneof_F_Largest_Tag struct {
- F_Largest_Tag int32 `protobuf:"varint,536870911,opt,name=F_Largest_Tag,json=fLargestTag,oneof"`
-}
-type Oneof_Value struct {
- Value int32 `protobuf:"varint,100,opt,name=value,oneof"`
-}
-
-func (*Oneof_F_Bool) isOneof_Union() {}
-func (*Oneof_F_Int32) isOneof_Union() {}
-func (*Oneof_F_Int64) isOneof_Union() {}
-func (*Oneof_F_Fixed32) isOneof_Union() {}
-func (*Oneof_F_Fixed64) isOneof_Union() {}
-func (*Oneof_F_Uint32) isOneof_Union() {}
-func (*Oneof_F_Uint64) isOneof_Union() {}
-func (*Oneof_F_Float) isOneof_Union() {}
-func (*Oneof_F_Double) isOneof_Union() {}
-func (*Oneof_F_String) isOneof_Union() {}
-func (*Oneof_F_Bytes) isOneof_Union() {}
-func (*Oneof_F_Sint32) isOneof_Union() {}
-func (*Oneof_F_Sint64) isOneof_Union() {}
-func (*Oneof_F_Enum) isOneof_Union() {}
-func (*Oneof_F_Message) isOneof_Union() {}
-func (*Oneof_FGroup) isOneof_Union() {}
-func (*Oneof_F_Largest_Tag) isOneof_Union() {}
-func (*Oneof_Value) isOneof_Tormato() {}
-
-func (m *Oneof) GetUnion() isOneof_Union {
- if m != nil {
- return m.Union
- }
- return nil
-}
-func (m *Oneof) GetTormato() isOneof_Tormato {
- if m != nil {
- return m.Tormato
- }
- return nil
-}
-
-func (m *Oneof) GetF_Bool() bool {
- if x, ok := m.GetUnion().(*Oneof_F_Bool); ok {
- return x.F_Bool
- }
- return false
-}
-
-func (m *Oneof) GetF_Int32() int32 {
- if x, ok := m.GetUnion().(*Oneof_F_Int32); ok {
- return x.F_Int32
- }
- return 0
-}
-
-func (m *Oneof) GetF_Int64() int64 {
- if x, ok := m.GetUnion().(*Oneof_F_Int64); ok {
- return x.F_Int64
- }
- return 0
-}
-
-func (m *Oneof) GetF_Fixed32() uint32 {
- if x, ok := m.GetUnion().(*Oneof_F_Fixed32); ok {
- return x.F_Fixed32
- }
- return 0
-}
-
-func (m *Oneof) GetF_Fixed64() uint64 {
- if x, ok := m.GetUnion().(*Oneof_F_Fixed64); ok {
- return x.F_Fixed64
- }
- return 0
-}
-
-func (m *Oneof) GetF_Uint32() uint32 {
- if x, ok := m.GetUnion().(*Oneof_F_Uint32); ok {
- return x.F_Uint32
- }
- return 0
-}
-
-func (m *Oneof) GetF_Uint64() uint64 {
- if x, ok := m.GetUnion().(*Oneof_F_Uint64); ok {
- return x.F_Uint64
- }
- return 0
-}
-
-func (m *Oneof) GetF_Float() float32 {
- if x, ok := m.GetUnion().(*Oneof_F_Float); ok {
- return x.F_Float
- }
- return 0
-}
-
-func (m *Oneof) GetF_Double() float64 {
- if x, ok := m.GetUnion().(*Oneof_F_Double); ok {
- return x.F_Double
- }
- return 0
-}
-
-func (m *Oneof) GetF_String() string {
- if x, ok := m.GetUnion().(*Oneof_F_String); ok {
- return x.F_String
- }
- return ""
-}
-
-func (m *Oneof) GetF_Bytes() []byte {
- if x, ok := m.GetUnion().(*Oneof_F_Bytes); ok {
- return x.F_Bytes
- }
- return nil
-}
-
-func (m *Oneof) GetF_Sint32() int32 {
- if x, ok := m.GetUnion().(*Oneof_F_Sint32); ok {
- return x.F_Sint32
- }
- return 0
-}
-
-func (m *Oneof) GetF_Sint64() int64 {
- if x, ok := m.GetUnion().(*Oneof_F_Sint64); ok {
- return x.F_Sint64
- }
- return 0
-}
-
-func (m *Oneof) GetF_Enum() MyMessage_Color {
- if x, ok := m.GetUnion().(*Oneof_F_Enum); ok {
- return x.F_Enum
- }
- return MyMessage_RED
-}
-
-func (m *Oneof) GetF_Message() *GoTestField {
- if x, ok := m.GetUnion().(*Oneof_F_Message); ok {
- return x.F_Message
- }
- return nil
-}
-
-func (m *Oneof) GetFGroup() *Oneof_F_Group {
- if x, ok := m.GetUnion().(*Oneof_FGroup); ok {
- return x.FGroup
- }
- return nil
-}
-
-func (m *Oneof) GetF_Largest_Tag() int32 {
- if x, ok := m.GetUnion().(*Oneof_F_Largest_Tag); ok {
- return x.F_Largest_Tag
- }
- return 0
-}
-
-func (m *Oneof) GetValue() int32 {
- if x, ok := m.GetTormato().(*Oneof_Value); ok {
- return x.Value
- }
- return 0
-}
-
-// XXX_OneofFuncs is for the internal use of the proto package.
-func (*Oneof) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
- return _Oneof_OneofMarshaler, _Oneof_OneofUnmarshaler, _Oneof_OneofSizer, []interface{}{
- (*Oneof_F_Bool)(nil),
- (*Oneof_F_Int32)(nil),
- (*Oneof_F_Int64)(nil),
- (*Oneof_F_Fixed32)(nil),
- (*Oneof_F_Fixed64)(nil),
- (*Oneof_F_Uint32)(nil),
- (*Oneof_F_Uint64)(nil),
- (*Oneof_F_Float)(nil),
- (*Oneof_F_Double)(nil),
- (*Oneof_F_String)(nil),
- (*Oneof_F_Bytes)(nil),
- (*Oneof_F_Sint32)(nil),
- (*Oneof_F_Sint64)(nil),
- (*Oneof_F_Enum)(nil),
- (*Oneof_F_Message)(nil),
- (*Oneof_FGroup)(nil),
- (*Oneof_F_Largest_Tag)(nil),
- (*Oneof_Value)(nil),
- }
-}
-
-func _Oneof_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
- m := msg.(*Oneof)
- // union
- switch x := m.Union.(type) {
- case *Oneof_F_Bool:
- t := uint64(0)
- if x.F_Bool {
- t = 1
- }
- b.EncodeVarint(1<<3 | proto.WireVarint)
- b.EncodeVarint(t)
- case *Oneof_F_Int32:
- b.EncodeVarint(2<<3 | proto.WireVarint)
- b.EncodeVarint(uint64(x.F_Int32))
- case *Oneof_F_Int64:
- b.EncodeVarint(3<<3 | proto.WireVarint)
- b.EncodeVarint(uint64(x.F_Int64))
- case *Oneof_F_Fixed32:
- b.EncodeVarint(4<<3 | proto.WireFixed32)
- b.EncodeFixed32(uint64(x.F_Fixed32))
- case *Oneof_F_Fixed64:
- b.EncodeVarint(5<<3 | proto.WireFixed64)
- b.EncodeFixed64(uint64(x.F_Fixed64))
- case *Oneof_F_Uint32:
- b.EncodeVarint(6<<3 | proto.WireVarint)
- b.EncodeVarint(uint64(x.F_Uint32))
- case *Oneof_F_Uint64:
- b.EncodeVarint(7<<3 | proto.WireVarint)
- b.EncodeVarint(uint64(x.F_Uint64))
- case *Oneof_F_Float:
- b.EncodeVarint(8<<3 | proto.WireFixed32)
- b.EncodeFixed32(uint64(math.Float32bits(x.F_Float)))
- case *Oneof_F_Double:
- b.EncodeVarint(9<<3 | proto.WireFixed64)
- b.EncodeFixed64(math.Float64bits(x.F_Double))
- case *Oneof_F_String:
- b.EncodeVarint(10<<3 | proto.WireBytes)
- b.EncodeStringBytes(x.F_String)
- case *Oneof_F_Bytes:
- b.EncodeVarint(11<<3 | proto.WireBytes)
- b.EncodeRawBytes(x.F_Bytes)
- case *Oneof_F_Sint32:
- b.EncodeVarint(12<<3 | proto.WireVarint)
- b.EncodeZigzag32(uint64(x.F_Sint32))
- case *Oneof_F_Sint64:
- b.EncodeVarint(13<<3 | proto.WireVarint)
- b.EncodeZigzag64(uint64(x.F_Sint64))
- case *Oneof_F_Enum:
- b.EncodeVarint(14<<3 | proto.WireVarint)
- b.EncodeVarint(uint64(x.F_Enum))
- case *Oneof_F_Message:
- b.EncodeVarint(15<<3 | proto.WireBytes)
- if err := b.EncodeMessage(x.F_Message); err != nil {
- return err
- }
- case *Oneof_FGroup:
- b.EncodeVarint(16<<3 | proto.WireStartGroup)
- if err := b.Marshal(x.FGroup); err != nil {
- return err
- }
- b.EncodeVarint(16<<3 | proto.WireEndGroup)
- case *Oneof_F_Largest_Tag:
- b.EncodeVarint(536870911<<3 | proto.WireVarint)
- b.EncodeVarint(uint64(x.F_Largest_Tag))
- case nil:
- default:
- return fmt.Errorf("Oneof.Union has unexpected type %T", x)
- }
- // tormato
- switch x := m.Tormato.(type) {
- case *Oneof_Value:
- b.EncodeVarint(100<<3 | proto.WireVarint)
- b.EncodeVarint(uint64(x.Value))
- case nil:
- default:
- return fmt.Errorf("Oneof.Tormato has unexpected type %T", x)
- }
- return nil
-}
-
-func _Oneof_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
- m := msg.(*Oneof)
- switch tag {
- case 1: // union.F_Bool
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Union = &Oneof_F_Bool{x != 0}
- return true, err
- case 2: // union.F_Int32
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Union = &Oneof_F_Int32{int32(x)}
- return true, err
- case 3: // union.F_Int64
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Union = &Oneof_F_Int64{int64(x)}
- return true, err
- case 4: // union.F_Fixed32
- if wire != proto.WireFixed32 {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeFixed32()
- m.Union = &Oneof_F_Fixed32{uint32(x)}
- return true, err
- case 5: // union.F_Fixed64
- if wire != proto.WireFixed64 {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeFixed64()
- m.Union = &Oneof_F_Fixed64{x}
- return true, err
- case 6: // union.F_Uint32
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Union = &Oneof_F_Uint32{uint32(x)}
- return true, err
- case 7: // union.F_Uint64
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Union = &Oneof_F_Uint64{x}
- return true, err
- case 8: // union.F_Float
- if wire != proto.WireFixed32 {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeFixed32()
- m.Union = &Oneof_F_Float{math.Float32frombits(uint32(x))}
- return true, err
- case 9: // union.F_Double
- if wire != proto.WireFixed64 {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeFixed64()
- m.Union = &Oneof_F_Double{math.Float64frombits(x)}
- return true, err
- case 10: // union.F_String
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeStringBytes()
- m.Union = &Oneof_F_String{x}
- return true, err
- case 11: // union.F_Bytes
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeRawBytes(true)
- m.Union = &Oneof_F_Bytes{x}
- return true, err
- case 12: // union.F_Sint32
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeZigzag32()
- m.Union = &Oneof_F_Sint32{int32(x)}
- return true, err
- case 13: // union.F_Sint64
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeZigzag64()
- m.Union = &Oneof_F_Sint64{int64(x)}
- return true, err
- case 14: // union.F_Enum
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Union = &Oneof_F_Enum{MyMessage_Color(x)}
- return true, err
- case 15: // union.F_Message
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- msg := new(GoTestField)
- err := b.DecodeMessage(msg)
- m.Union = &Oneof_F_Message{msg}
- return true, err
- case 16: // union.f_group
- if wire != proto.WireStartGroup {
- return true, proto.ErrInternalBadWireType
- }
- msg := new(Oneof_F_Group)
- err := b.DecodeGroup(msg)
- m.Union = &Oneof_FGroup{msg}
- return true, err
- case 536870911: // union.F_Largest_Tag
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Union = &Oneof_F_Largest_Tag{int32(x)}
- return true, err
- case 100: // tormato.value
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Tormato = &Oneof_Value{int32(x)}
- return true, err
- default:
- return false, nil
- }
-}
-
-func _Oneof_OneofSizer(msg proto.Message) (n int) {
- m := msg.(*Oneof)
- // union
- switch x := m.Union.(type) {
- case *Oneof_F_Bool:
- n += proto.SizeVarint(1<<3 | proto.WireVarint)
- n += 1
- case *Oneof_F_Int32:
- n += proto.SizeVarint(2<<3 | proto.WireVarint)
- n += proto.SizeVarint(uint64(x.F_Int32))
- case *Oneof_F_Int64:
- n += proto.SizeVarint(3<<3 | proto.WireVarint)
- n += proto.SizeVarint(uint64(x.F_Int64))
- case *Oneof_F_Fixed32:
- n += proto.SizeVarint(4<<3 | proto.WireFixed32)
- n += 4
- case *Oneof_F_Fixed64:
- n += proto.SizeVarint(5<<3 | proto.WireFixed64)
- n += 8
- case *Oneof_F_Uint32:
- n += proto.SizeVarint(6<<3 | proto.WireVarint)
- n += proto.SizeVarint(uint64(x.F_Uint32))
- case *Oneof_F_Uint64:
- n += proto.SizeVarint(7<<3 | proto.WireVarint)
- n += proto.SizeVarint(uint64(x.F_Uint64))
- case *Oneof_F_Float:
- n += proto.SizeVarint(8<<3 | proto.WireFixed32)
- n += 4
- case *Oneof_F_Double:
- n += proto.SizeVarint(9<<3 | proto.WireFixed64)
- n += 8
- case *Oneof_F_String:
- n += proto.SizeVarint(10<<3 | proto.WireBytes)
- n += proto.SizeVarint(uint64(len(x.F_String)))
- n += len(x.F_String)
- case *Oneof_F_Bytes:
- n += proto.SizeVarint(11<<3 | proto.WireBytes)
- n += proto.SizeVarint(uint64(len(x.F_Bytes)))
- n += len(x.F_Bytes)
- case *Oneof_F_Sint32:
- n += proto.SizeVarint(12<<3 | proto.WireVarint)
- n += proto.SizeVarint(uint64((uint32(x.F_Sint32) << 1) ^ uint32((int32(x.F_Sint32) >> 31))))
- case *Oneof_F_Sint64:
- n += proto.SizeVarint(13<<3 | proto.WireVarint)
- n += proto.SizeVarint(uint64(uint64(x.F_Sint64<<1) ^ uint64((int64(x.F_Sint64) >> 63))))
- case *Oneof_F_Enum:
- n += proto.SizeVarint(14<<3 | proto.WireVarint)
- n += proto.SizeVarint(uint64(x.F_Enum))
- case *Oneof_F_Message:
- s := proto.Size(x.F_Message)
- n += proto.SizeVarint(15<<3 | proto.WireBytes)
- n += proto.SizeVarint(uint64(s))
- n += s
- case *Oneof_FGroup:
- n += proto.SizeVarint(16<<3 | proto.WireStartGroup)
- n += proto.Size(x.FGroup)
- n += proto.SizeVarint(16<<3 | proto.WireEndGroup)
- case *Oneof_F_Largest_Tag:
- n += proto.SizeVarint(536870911<<3 | proto.WireVarint)
- n += proto.SizeVarint(uint64(x.F_Largest_Tag))
- case nil:
- default:
- panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
- }
- // tormato
- switch x := m.Tormato.(type) {
- case *Oneof_Value:
- n += proto.SizeVarint(100<<3 | proto.WireVarint)
- n += proto.SizeVarint(uint64(x.Value))
- case nil:
- default:
- panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
- }
- return n
-}
-
-type Oneof_F_Group struct {
- X *int32 `protobuf:"varint,17,opt,name=x" json:"x,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *Oneof_F_Group) Reset() { *m = Oneof_F_Group{} }
-func (m *Oneof_F_Group) String() string { return proto.CompactTextString(m) }
-func (*Oneof_F_Group) ProtoMessage() {}
-func (*Oneof_F_Group) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{28, 0} }
-
-func (m *Oneof_F_Group) GetX() int32 {
- if m != nil && m.X != nil {
- return *m.X
- }
- return 0
-}
-
-type Communique struct {
- MakeMeCry *bool `protobuf:"varint,1,opt,name=make_me_cry,json=makeMeCry" json:"make_me_cry,omitempty"`
- // This is a oneof, called "union".
- //
- // Types that are valid to be assigned to Union:
- // *Communique_Number
- // *Communique_Name
- // *Communique_Data
- // *Communique_TempC
- // *Communique_Col
- // *Communique_Msg
- Union isCommunique_Union `protobuf_oneof:"union"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *Communique) Reset() { *m = Communique{} }
-func (m *Communique) String() string { return proto.CompactTextString(m) }
-func (*Communique) ProtoMessage() {}
-func (*Communique) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{29} }
-
-type isCommunique_Union interface {
- isCommunique_Union()
-}
-
-type Communique_Number struct {
- Number int32 `protobuf:"varint,5,opt,name=number,oneof"`
-}
-type Communique_Name struct {
- Name string `protobuf:"bytes,6,opt,name=name,oneof"`
-}
-type Communique_Data struct {
- Data []byte `protobuf:"bytes,7,opt,name=data,oneof"`
-}
-type Communique_TempC struct {
- TempC float64 `protobuf:"fixed64,8,opt,name=temp_c,json=tempC,oneof"`
-}
-type Communique_Col struct {
- Col MyMessage_Color `protobuf:"varint,9,opt,name=col,enum=testdata.MyMessage_Color,oneof"`
-}
-type Communique_Msg struct {
- Msg *Strings `protobuf:"bytes,10,opt,name=msg,oneof"`
-}
-
-func (*Communique_Number) isCommunique_Union() {}
-func (*Communique_Name) isCommunique_Union() {}
-func (*Communique_Data) isCommunique_Union() {}
-func (*Communique_TempC) isCommunique_Union() {}
-func (*Communique_Col) isCommunique_Union() {}
-func (*Communique_Msg) isCommunique_Union() {}
-
-func (m *Communique) GetUnion() isCommunique_Union {
- if m != nil {
- return m.Union
- }
- return nil
-}
-
-func (m *Communique) GetMakeMeCry() bool {
- if m != nil && m.MakeMeCry != nil {
- return *m.MakeMeCry
- }
- return false
-}
-
-func (m *Communique) GetNumber() int32 {
- if x, ok := m.GetUnion().(*Communique_Number); ok {
- return x.Number
- }
- return 0
-}
-
-func (m *Communique) GetName() string {
- if x, ok := m.GetUnion().(*Communique_Name); ok {
- return x.Name
- }
- return ""
-}
-
-func (m *Communique) GetData() []byte {
- if x, ok := m.GetUnion().(*Communique_Data); ok {
- return x.Data
- }
- return nil
-}
-
-func (m *Communique) GetTempC() float64 {
- if x, ok := m.GetUnion().(*Communique_TempC); ok {
- return x.TempC
- }
- return 0
-}
-
-func (m *Communique) GetCol() MyMessage_Color {
- if x, ok := m.GetUnion().(*Communique_Col); ok {
- return x.Col
- }
- return MyMessage_RED
-}
-
-func (m *Communique) GetMsg() *Strings {
- if x, ok := m.GetUnion().(*Communique_Msg); ok {
- return x.Msg
- }
- return nil
-}
-
-// XXX_OneofFuncs is for the internal use of the proto package.
-func (*Communique) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
- return _Communique_OneofMarshaler, _Communique_OneofUnmarshaler, _Communique_OneofSizer, []interface{}{
- (*Communique_Number)(nil),
- (*Communique_Name)(nil),
- (*Communique_Data)(nil),
- (*Communique_TempC)(nil),
- (*Communique_Col)(nil),
- (*Communique_Msg)(nil),
- }
-}
-
-func _Communique_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
- m := msg.(*Communique)
- // union
- switch x := m.Union.(type) {
- case *Communique_Number:
- b.EncodeVarint(5<<3 | proto.WireVarint)
- b.EncodeVarint(uint64(x.Number))
- case *Communique_Name:
- b.EncodeVarint(6<<3 | proto.WireBytes)
- b.EncodeStringBytes(x.Name)
- case *Communique_Data:
- b.EncodeVarint(7<<3 | proto.WireBytes)
- b.EncodeRawBytes(x.Data)
- case *Communique_TempC:
- b.EncodeVarint(8<<3 | proto.WireFixed64)
- b.EncodeFixed64(math.Float64bits(x.TempC))
- case *Communique_Col:
- b.EncodeVarint(9<<3 | proto.WireVarint)
- b.EncodeVarint(uint64(x.Col))
- case *Communique_Msg:
- b.EncodeVarint(10<<3 | proto.WireBytes)
- if err := b.EncodeMessage(x.Msg); err != nil {
- return err
- }
- case nil:
- default:
- return fmt.Errorf("Communique.Union has unexpected type %T", x)
- }
- return nil
-}
-
-func _Communique_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
- m := msg.(*Communique)
- switch tag {
- case 5: // union.number
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Union = &Communique_Number{int32(x)}
- return true, err
- case 6: // union.name
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeStringBytes()
- m.Union = &Communique_Name{x}
- return true, err
- case 7: // union.data
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeRawBytes(true)
- m.Union = &Communique_Data{x}
- return true, err
- case 8: // union.temp_c
- if wire != proto.WireFixed64 {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeFixed64()
- m.Union = &Communique_TempC{math.Float64frombits(x)}
- return true, err
- case 9: // union.col
- if wire != proto.WireVarint {
- return true, proto.ErrInternalBadWireType
- }
- x, err := b.DecodeVarint()
- m.Union = &Communique_Col{MyMessage_Color(x)}
- return true, err
- case 10: // union.msg
- if wire != proto.WireBytes {
- return true, proto.ErrInternalBadWireType
- }
- msg := new(Strings)
- err := b.DecodeMessage(msg)
- m.Union = &Communique_Msg{msg}
- return true, err
- default:
- return false, nil
- }
-}
-
-func _Communique_OneofSizer(msg proto.Message) (n int) {
- m := msg.(*Communique)
- // union
- switch x := m.Union.(type) {
- case *Communique_Number:
- n += proto.SizeVarint(5<<3 | proto.WireVarint)
- n += proto.SizeVarint(uint64(x.Number))
- case *Communique_Name:
- n += proto.SizeVarint(6<<3 | proto.WireBytes)
- n += proto.SizeVarint(uint64(len(x.Name)))
- n += len(x.Name)
- case *Communique_Data:
- n += proto.SizeVarint(7<<3 | proto.WireBytes)
- n += proto.SizeVarint(uint64(len(x.Data)))
- n += len(x.Data)
- case *Communique_TempC:
- n += proto.SizeVarint(8<<3 | proto.WireFixed64)
- n += 8
- case *Communique_Col:
- n += proto.SizeVarint(9<<3 | proto.WireVarint)
- n += proto.SizeVarint(uint64(x.Col))
- case *Communique_Msg:
- s := proto.Size(x.Msg)
- n += proto.SizeVarint(10<<3 | proto.WireBytes)
- n += proto.SizeVarint(uint64(s))
- n += s
- case nil:
- default:
- panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
- }
- return n
-}
-
-var E_Greeting = &proto.ExtensionDesc{
- ExtendedType: (*MyMessage)(nil),
- ExtensionType: ([]string)(nil),
- Field: 106,
- Name: "testdata.greeting",
- Tag: "bytes,106,rep,name=greeting",
-}
-
-var E_Complex = &proto.ExtensionDesc{
- ExtendedType: (*OtherMessage)(nil),
- ExtensionType: (*ComplexExtension)(nil),
- Field: 200,
- Name: "testdata.complex",
- Tag: "bytes,200,opt,name=complex",
-}
-
-var E_RComplex = &proto.ExtensionDesc{
- ExtendedType: (*OtherMessage)(nil),
- ExtensionType: ([]*ComplexExtension)(nil),
- Field: 201,
- Name: "testdata.r_complex",
- Tag: "bytes,201,rep,name=r_complex,json=rComplex",
-}
-
-var E_NoDefaultDouble = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*float64)(nil),
- Field: 101,
- Name: "testdata.no_default_double",
- Tag: "fixed64,101,opt,name=no_default_double,json=noDefaultDouble",
-}
-
-var E_NoDefaultFloat = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*float32)(nil),
- Field: 102,
- Name: "testdata.no_default_float",
- Tag: "fixed32,102,opt,name=no_default_float,json=noDefaultFloat",
-}
-
-var E_NoDefaultInt32 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*int32)(nil),
- Field: 103,
- Name: "testdata.no_default_int32",
- Tag: "varint,103,opt,name=no_default_int32,json=noDefaultInt32",
-}
-
-var E_NoDefaultInt64 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*int64)(nil),
- Field: 104,
- Name: "testdata.no_default_int64",
- Tag: "varint,104,opt,name=no_default_int64,json=noDefaultInt64",
-}
-
-var E_NoDefaultUint32 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*uint32)(nil),
- Field: 105,
- Name: "testdata.no_default_uint32",
- Tag: "varint,105,opt,name=no_default_uint32,json=noDefaultUint32",
-}
-
-var E_NoDefaultUint64 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*uint64)(nil),
- Field: 106,
- Name: "testdata.no_default_uint64",
- Tag: "varint,106,opt,name=no_default_uint64,json=noDefaultUint64",
-}
-
-var E_NoDefaultSint32 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*int32)(nil),
- Field: 107,
- Name: "testdata.no_default_sint32",
- Tag: "zigzag32,107,opt,name=no_default_sint32,json=noDefaultSint32",
-}
-
-var E_NoDefaultSint64 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*int64)(nil),
- Field: 108,
- Name: "testdata.no_default_sint64",
- Tag: "zigzag64,108,opt,name=no_default_sint64,json=noDefaultSint64",
-}
-
-var E_NoDefaultFixed32 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*uint32)(nil),
- Field: 109,
- Name: "testdata.no_default_fixed32",
- Tag: "fixed32,109,opt,name=no_default_fixed32,json=noDefaultFixed32",
-}
-
-var E_NoDefaultFixed64 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*uint64)(nil),
- Field: 110,
- Name: "testdata.no_default_fixed64",
- Tag: "fixed64,110,opt,name=no_default_fixed64,json=noDefaultFixed64",
-}
-
-var E_NoDefaultSfixed32 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*int32)(nil),
- Field: 111,
- Name: "testdata.no_default_sfixed32",
- Tag: "fixed32,111,opt,name=no_default_sfixed32,json=noDefaultSfixed32",
-}
-
-var E_NoDefaultSfixed64 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*int64)(nil),
- Field: 112,
- Name: "testdata.no_default_sfixed64",
- Tag: "fixed64,112,opt,name=no_default_sfixed64,json=noDefaultSfixed64",
-}
-
-var E_NoDefaultBool = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*bool)(nil),
- Field: 113,
- Name: "testdata.no_default_bool",
- Tag: "varint,113,opt,name=no_default_bool,json=noDefaultBool",
-}
-
-var E_NoDefaultString = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*string)(nil),
- Field: 114,
- Name: "testdata.no_default_string",
- Tag: "bytes,114,opt,name=no_default_string,json=noDefaultString",
-}
-
-var E_NoDefaultBytes = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: ([]byte)(nil),
- Field: 115,
- Name: "testdata.no_default_bytes",
- Tag: "bytes,115,opt,name=no_default_bytes,json=noDefaultBytes",
-}
-
-var E_NoDefaultEnum = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*DefaultsMessage_DefaultsEnum)(nil),
- Field: 116,
- Name: "testdata.no_default_enum",
- Tag: "varint,116,opt,name=no_default_enum,json=noDefaultEnum,enum=testdata.DefaultsMessage_DefaultsEnum",
-}
-
-var E_DefaultDouble = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*float64)(nil),
- Field: 201,
- Name: "testdata.default_double",
- Tag: "fixed64,201,opt,name=default_double,json=defaultDouble,def=3.1415",
-}
-
-var E_DefaultFloat = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*float32)(nil),
- Field: 202,
- Name: "testdata.default_float",
- Tag: "fixed32,202,opt,name=default_float,json=defaultFloat,def=3.14",
-}
-
-var E_DefaultInt32 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*int32)(nil),
- Field: 203,
- Name: "testdata.default_int32",
- Tag: "varint,203,opt,name=default_int32,json=defaultInt32,def=42",
-}
-
-var E_DefaultInt64 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*int64)(nil),
- Field: 204,
- Name: "testdata.default_int64",
- Tag: "varint,204,opt,name=default_int64,json=defaultInt64,def=43",
-}
-
-var E_DefaultUint32 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*uint32)(nil),
- Field: 205,
- Name: "testdata.default_uint32",
- Tag: "varint,205,opt,name=default_uint32,json=defaultUint32,def=44",
-}
-
-var E_DefaultUint64 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*uint64)(nil),
- Field: 206,
- Name: "testdata.default_uint64",
- Tag: "varint,206,opt,name=default_uint64,json=defaultUint64,def=45",
-}
-
-var E_DefaultSint32 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*int32)(nil),
- Field: 207,
- Name: "testdata.default_sint32",
- Tag: "zigzag32,207,opt,name=default_sint32,json=defaultSint32,def=46",
-}
-
-var E_DefaultSint64 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*int64)(nil),
- Field: 208,
- Name: "testdata.default_sint64",
- Tag: "zigzag64,208,opt,name=default_sint64,json=defaultSint64,def=47",
-}
-
-var E_DefaultFixed32 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*uint32)(nil),
- Field: 209,
- Name: "testdata.default_fixed32",
- Tag: "fixed32,209,opt,name=default_fixed32,json=defaultFixed32,def=48",
-}
-
-var E_DefaultFixed64 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*uint64)(nil),
- Field: 210,
- Name: "testdata.default_fixed64",
- Tag: "fixed64,210,opt,name=default_fixed64,json=defaultFixed64,def=49",
-}
-
-var E_DefaultSfixed32 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*int32)(nil),
- Field: 211,
- Name: "testdata.default_sfixed32",
- Tag: "fixed32,211,opt,name=default_sfixed32,json=defaultSfixed32,def=50",
-}
-
-var E_DefaultSfixed64 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*int64)(nil),
- Field: 212,
- Name: "testdata.default_sfixed64",
- Tag: "fixed64,212,opt,name=default_sfixed64,json=defaultSfixed64,def=51",
-}
-
-var E_DefaultBool = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*bool)(nil),
- Field: 213,
- Name: "testdata.default_bool",
- Tag: "varint,213,opt,name=default_bool,json=defaultBool,def=1",
-}
-
-var E_DefaultString = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*string)(nil),
- Field: 214,
- Name: "testdata.default_string",
- Tag: "bytes,214,opt,name=default_string,json=defaultString,def=Hello, string",
-}
-
-var E_DefaultBytes = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: ([]byte)(nil),
- Field: 215,
- Name: "testdata.default_bytes",
- Tag: "bytes,215,opt,name=default_bytes,json=defaultBytes,def=Hello, bytes",
-}
-
-var E_DefaultEnum = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*DefaultsMessage_DefaultsEnum)(nil),
- Field: 216,
- Name: "testdata.default_enum",
- Tag: "varint,216,opt,name=default_enum,json=defaultEnum,enum=testdata.DefaultsMessage_DefaultsEnum,def=1",
-}
-
-var E_X201 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 201,
- Name: "testdata.x201",
- Tag: "bytes,201,opt,name=x201",
-}
-
-var E_X202 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 202,
- Name: "testdata.x202",
- Tag: "bytes,202,opt,name=x202",
-}
-
-var E_X203 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 203,
- Name: "testdata.x203",
- Tag: "bytes,203,opt,name=x203",
-}
-
-var E_X204 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 204,
- Name: "testdata.x204",
- Tag: "bytes,204,opt,name=x204",
-}
-
-var E_X205 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 205,
- Name: "testdata.x205",
- Tag: "bytes,205,opt,name=x205",
-}
-
-var E_X206 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 206,
- Name: "testdata.x206",
- Tag: "bytes,206,opt,name=x206",
-}
-
-var E_X207 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 207,
- Name: "testdata.x207",
- Tag: "bytes,207,opt,name=x207",
-}
-
-var E_X208 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 208,
- Name: "testdata.x208",
- Tag: "bytes,208,opt,name=x208",
-}
-
-var E_X209 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 209,
- Name: "testdata.x209",
- Tag: "bytes,209,opt,name=x209",
-}
-
-var E_X210 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 210,
- Name: "testdata.x210",
- Tag: "bytes,210,opt,name=x210",
-}
-
-var E_X211 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 211,
- Name: "testdata.x211",
- Tag: "bytes,211,opt,name=x211",
-}
-
-var E_X212 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 212,
- Name: "testdata.x212",
- Tag: "bytes,212,opt,name=x212",
-}
-
-var E_X213 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 213,
- Name: "testdata.x213",
- Tag: "bytes,213,opt,name=x213",
-}
-
-var E_X214 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 214,
- Name: "testdata.x214",
- Tag: "bytes,214,opt,name=x214",
-}
-
-var E_X215 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 215,
- Name: "testdata.x215",
- Tag: "bytes,215,opt,name=x215",
-}
-
-var E_X216 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 216,
- Name: "testdata.x216",
- Tag: "bytes,216,opt,name=x216",
-}
-
-var E_X217 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 217,
- Name: "testdata.x217",
- Tag: "bytes,217,opt,name=x217",
-}
-
-var E_X218 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 218,
- Name: "testdata.x218",
- Tag: "bytes,218,opt,name=x218",
-}
-
-var E_X219 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 219,
- Name: "testdata.x219",
- Tag: "bytes,219,opt,name=x219",
-}
-
-var E_X220 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 220,
- Name: "testdata.x220",
- Tag: "bytes,220,opt,name=x220",
-}
-
-var E_X221 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 221,
- Name: "testdata.x221",
- Tag: "bytes,221,opt,name=x221",
-}
-
-var E_X222 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 222,
- Name: "testdata.x222",
- Tag: "bytes,222,opt,name=x222",
-}
-
-var E_X223 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 223,
- Name: "testdata.x223",
- Tag: "bytes,223,opt,name=x223",
-}
-
-var E_X224 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 224,
- Name: "testdata.x224",
- Tag: "bytes,224,opt,name=x224",
-}
-
-var E_X225 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 225,
- Name: "testdata.x225",
- Tag: "bytes,225,opt,name=x225",
-}
-
-var E_X226 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 226,
- Name: "testdata.x226",
- Tag: "bytes,226,opt,name=x226",
-}
-
-var E_X227 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 227,
- Name: "testdata.x227",
- Tag: "bytes,227,opt,name=x227",
-}
-
-var E_X228 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 228,
- Name: "testdata.x228",
- Tag: "bytes,228,opt,name=x228",
-}
-
-var E_X229 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 229,
- Name: "testdata.x229",
- Tag: "bytes,229,opt,name=x229",
-}
-
-var E_X230 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 230,
- Name: "testdata.x230",
- Tag: "bytes,230,opt,name=x230",
-}
-
-var E_X231 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 231,
- Name: "testdata.x231",
- Tag: "bytes,231,opt,name=x231",
-}
-
-var E_X232 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 232,
- Name: "testdata.x232",
- Tag: "bytes,232,opt,name=x232",
-}
-
-var E_X233 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 233,
- Name: "testdata.x233",
- Tag: "bytes,233,opt,name=x233",
-}
-
-var E_X234 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 234,
- Name: "testdata.x234",
- Tag: "bytes,234,opt,name=x234",
-}
-
-var E_X235 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 235,
- Name: "testdata.x235",
- Tag: "bytes,235,opt,name=x235",
-}
-
-var E_X236 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 236,
- Name: "testdata.x236",
- Tag: "bytes,236,opt,name=x236",
-}
-
-var E_X237 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 237,
- Name: "testdata.x237",
- Tag: "bytes,237,opt,name=x237",
-}
-
-var E_X238 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 238,
- Name: "testdata.x238",
- Tag: "bytes,238,opt,name=x238",
-}
-
-var E_X239 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 239,
- Name: "testdata.x239",
- Tag: "bytes,239,opt,name=x239",
-}
-
-var E_X240 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 240,
- Name: "testdata.x240",
- Tag: "bytes,240,opt,name=x240",
-}
-
-var E_X241 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 241,
- Name: "testdata.x241",
- Tag: "bytes,241,opt,name=x241",
-}
-
-var E_X242 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 242,
- Name: "testdata.x242",
- Tag: "bytes,242,opt,name=x242",
-}
-
-var E_X243 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 243,
- Name: "testdata.x243",
- Tag: "bytes,243,opt,name=x243",
-}
-
-var E_X244 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 244,
- Name: "testdata.x244",
- Tag: "bytes,244,opt,name=x244",
-}
-
-var E_X245 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 245,
- Name: "testdata.x245",
- Tag: "bytes,245,opt,name=x245",
-}
-
-var E_X246 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 246,
- Name: "testdata.x246",
- Tag: "bytes,246,opt,name=x246",
-}
-
-var E_X247 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 247,
- Name: "testdata.x247",
- Tag: "bytes,247,opt,name=x247",
-}
-
-var E_X248 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 248,
- Name: "testdata.x248",
- Tag: "bytes,248,opt,name=x248",
-}
-
-var E_X249 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 249,
- Name: "testdata.x249",
- Tag: "bytes,249,opt,name=x249",
-}
-
-var E_X250 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 250,
- Name: "testdata.x250",
- Tag: "bytes,250,opt,name=x250",
-}
-
-func init() {
- proto.RegisterType((*GoEnum)(nil), "testdata.GoEnum")
- proto.RegisterType((*GoTestField)(nil), "testdata.GoTestField")
- proto.RegisterType((*GoTest)(nil), "testdata.GoTest")
- proto.RegisterType((*GoTest_RequiredGroup)(nil), "testdata.GoTest.RequiredGroup")
- proto.RegisterType((*GoTest_RepeatedGroup)(nil), "testdata.GoTest.RepeatedGroup")
- proto.RegisterType((*GoTest_OptionalGroup)(nil), "testdata.GoTest.OptionalGroup")
- proto.RegisterType((*GoSkipTest)(nil), "testdata.GoSkipTest")
- proto.RegisterType((*GoSkipTest_SkipGroup)(nil), "testdata.GoSkipTest.SkipGroup")
- proto.RegisterType((*NonPackedTest)(nil), "testdata.NonPackedTest")
- proto.RegisterType((*PackedTest)(nil), "testdata.PackedTest")
- proto.RegisterType((*MaxTag)(nil), "testdata.MaxTag")
- proto.RegisterType((*OldMessage)(nil), "testdata.OldMessage")
- proto.RegisterType((*OldMessage_Nested)(nil), "testdata.OldMessage.Nested")
- proto.RegisterType((*NewMessage)(nil), "testdata.NewMessage")
- proto.RegisterType((*NewMessage_Nested)(nil), "testdata.NewMessage.Nested")
- proto.RegisterType((*InnerMessage)(nil), "testdata.InnerMessage")
- proto.RegisterType((*OtherMessage)(nil), "testdata.OtherMessage")
- proto.RegisterType((*RequiredInnerMessage)(nil), "testdata.RequiredInnerMessage")
- proto.RegisterType((*MyMessage)(nil), "testdata.MyMessage")
- proto.RegisterType((*MyMessage_SomeGroup)(nil), "testdata.MyMessage.SomeGroup")
- proto.RegisterType((*Ext)(nil), "testdata.Ext")
- proto.RegisterType((*ComplexExtension)(nil), "testdata.ComplexExtension")
- proto.RegisterType((*DefaultsMessage)(nil), "testdata.DefaultsMessage")
- proto.RegisterType((*MyMessageSet)(nil), "testdata.MyMessageSet")
- proto.RegisterType((*Empty)(nil), "testdata.Empty")
- proto.RegisterType((*MessageList)(nil), "testdata.MessageList")
- proto.RegisterType((*MessageList_Message)(nil), "testdata.MessageList.Message")
- proto.RegisterType((*Strings)(nil), "testdata.Strings")
- proto.RegisterType((*Defaults)(nil), "testdata.Defaults")
- proto.RegisterType((*SubDefaults)(nil), "testdata.SubDefaults")
- proto.RegisterType((*RepeatedEnum)(nil), "testdata.RepeatedEnum")
- proto.RegisterType((*MoreRepeated)(nil), "testdata.MoreRepeated")
- proto.RegisterType((*GroupOld)(nil), "testdata.GroupOld")
- proto.RegisterType((*GroupOld_G)(nil), "testdata.GroupOld.G")
- proto.RegisterType((*GroupNew)(nil), "testdata.GroupNew")
- proto.RegisterType((*GroupNew_G)(nil), "testdata.GroupNew.G")
- proto.RegisterType((*FloatingPoint)(nil), "testdata.FloatingPoint")
- proto.RegisterType((*MessageWithMap)(nil), "testdata.MessageWithMap")
- proto.RegisterType((*Oneof)(nil), "testdata.Oneof")
- proto.RegisterType((*Oneof_F_Group)(nil), "testdata.Oneof.F_Group")
- proto.RegisterType((*Communique)(nil), "testdata.Communique")
- proto.RegisterEnum("testdata.FOO", FOO_name, FOO_value)
- proto.RegisterEnum("testdata.GoTest_KIND", GoTest_KIND_name, GoTest_KIND_value)
- proto.RegisterEnum("testdata.MyMessage_Color", MyMessage_Color_name, MyMessage_Color_value)
- proto.RegisterEnum("testdata.DefaultsMessage_DefaultsEnum", DefaultsMessage_DefaultsEnum_name, DefaultsMessage_DefaultsEnum_value)
- proto.RegisterEnum("testdata.Defaults_Color", Defaults_Color_name, Defaults_Color_value)
- proto.RegisterEnum("testdata.RepeatedEnum_Color", RepeatedEnum_Color_name, RepeatedEnum_Color_value)
- proto.RegisterExtension(E_Ext_More)
- proto.RegisterExtension(E_Ext_Text)
- proto.RegisterExtension(E_Ext_Number)
- proto.RegisterExtension(E_Greeting)
- proto.RegisterExtension(E_Complex)
- proto.RegisterExtension(E_RComplex)
- proto.RegisterExtension(E_NoDefaultDouble)
- proto.RegisterExtension(E_NoDefaultFloat)
- proto.RegisterExtension(E_NoDefaultInt32)
- proto.RegisterExtension(E_NoDefaultInt64)
- proto.RegisterExtension(E_NoDefaultUint32)
- proto.RegisterExtension(E_NoDefaultUint64)
- proto.RegisterExtension(E_NoDefaultSint32)
- proto.RegisterExtension(E_NoDefaultSint64)
- proto.RegisterExtension(E_NoDefaultFixed32)
- proto.RegisterExtension(E_NoDefaultFixed64)
- proto.RegisterExtension(E_NoDefaultSfixed32)
- proto.RegisterExtension(E_NoDefaultSfixed64)
- proto.RegisterExtension(E_NoDefaultBool)
- proto.RegisterExtension(E_NoDefaultString)
- proto.RegisterExtension(E_NoDefaultBytes)
- proto.RegisterExtension(E_NoDefaultEnum)
- proto.RegisterExtension(E_DefaultDouble)
- proto.RegisterExtension(E_DefaultFloat)
- proto.RegisterExtension(E_DefaultInt32)
- proto.RegisterExtension(E_DefaultInt64)
- proto.RegisterExtension(E_DefaultUint32)
- proto.RegisterExtension(E_DefaultUint64)
- proto.RegisterExtension(E_DefaultSint32)
- proto.RegisterExtension(E_DefaultSint64)
- proto.RegisterExtension(E_DefaultFixed32)
- proto.RegisterExtension(E_DefaultFixed64)
- proto.RegisterExtension(E_DefaultSfixed32)
- proto.RegisterExtension(E_DefaultSfixed64)
- proto.RegisterExtension(E_DefaultBool)
- proto.RegisterExtension(E_DefaultString)
- proto.RegisterExtension(E_DefaultBytes)
- proto.RegisterExtension(E_DefaultEnum)
- proto.RegisterExtension(E_X201)
- proto.RegisterExtension(E_X202)
- proto.RegisterExtension(E_X203)
- proto.RegisterExtension(E_X204)
- proto.RegisterExtension(E_X205)
- proto.RegisterExtension(E_X206)
- proto.RegisterExtension(E_X207)
- proto.RegisterExtension(E_X208)
- proto.RegisterExtension(E_X209)
- proto.RegisterExtension(E_X210)
- proto.RegisterExtension(E_X211)
- proto.RegisterExtension(E_X212)
- proto.RegisterExtension(E_X213)
- proto.RegisterExtension(E_X214)
- proto.RegisterExtension(E_X215)
- proto.RegisterExtension(E_X216)
- proto.RegisterExtension(E_X217)
- proto.RegisterExtension(E_X218)
- proto.RegisterExtension(E_X219)
- proto.RegisterExtension(E_X220)
- proto.RegisterExtension(E_X221)
- proto.RegisterExtension(E_X222)
- proto.RegisterExtension(E_X223)
- proto.RegisterExtension(E_X224)
- proto.RegisterExtension(E_X225)
- proto.RegisterExtension(E_X226)
- proto.RegisterExtension(E_X227)
- proto.RegisterExtension(E_X228)
- proto.RegisterExtension(E_X229)
- proto.RegisterExtension(E_X230)
- proto.RegisterExtension(E_X231)
- proto.RegisterExtension(E_X232)
- proto.RegisterExtension(E_X233)
- proto.RegisterExtension(E_X234)
- proto.RegisterExtension(E_X235)
- proto.RegisterExtension(E_X236)
- proto.RegisterExtension(E_X237)
- proto.RegisterExtension(E_X238)
- proto.RegisterExtension(E_X239)
- proto.RegisterExtension(E_X240)
- proto.RegisterExtension(E_X241)
- proto.RegisterExtension(E_X242)
- proto.RegisterExtension(E_X243)
- proto.RegisterExtension(E_X244)
- proto.RegisterExtension(E_X245)
- proto.RegisterExtension(E_X246)
- proto.RegisterExtension(E_X247)
- proto.RegisterExtension(E_X248)
- proto.RegisterExtension(E_X249)
- proto.RegisterExtension(E_X250)
-}
-
-var fileDescriptor0 = []byte{
- // 4407 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0x94, 0x5a, 0x59, 0x77, 0xdb, 0x48,
- 0x76, 0x36, 0xc0, 0xfd, 0x92, 0x12, 0xa1, 0xb2, 0xda, 0x4d, 0x4b, 0x5e, 0x60, 0xce, 0x74, 0x37,
- 0xbd, 0x69, 0x24, 0x10, 0xa2, 0x6d, 0xba, 0xd3, 0xe7, 0x78, 0xa1, 0x64, 0x9d, 0xb1, 0x44, 0x05,
- 0x52, 0x77, 0x9f, 0xe9, 0x3c, 0xf0, 0x50, 0x22, 0x48, 0xb3, 0x4d, 0x02, 0x34, 0x09, 0xc5, 0x52,
- 0xf2, 0xd2, 0x2f, 0xc9, 0x6b, 0xb6, 0x97, 0xbc, 0xe6, 0x29, 0x4f, 0x49, 0xce, 0xc9, 0x9f, 0x48,
- 0xba, 0x7b, 0xd6, 0x9e, 0x35, 0xeb, 0x64, 0x5f, 0x26, 0xfb, 0x36, 0x93, 0xe4, 0xa5, 0xe7, 0xd4,
- 0xad, 0x02, 0x50, 0x00, 0x09, 0x48, 0x7e, 0x12, 0x51, 0xf5, 0x7d, 0xb7, 0x6e, 0x15, 0xbe, 0xba,
- 0xb7, 0x6e, 0x41, 0x00, 0x8e, 0x39, 0x71, 0x56, 0x46, 0x63, 0xdb, 0xb1, 0x49, 0x96, 0xfe, 0xee,
- 0xb4, 0x9d, 0x76, 0xf9, 0x3a, 0xa4, 0x37, 0xed, 0x86, 0x75, 0x34, 0x24, 0x57, 0x21, 0xd1, 0xb5,
- 0xed, 0x92, 0xa4, 0xca, 0x95, 0x79, 0x6d, 0x6e, 0xc5, 0x45, 0xac, 0x6c, 0x34, 0x9b, 0x06, 0xed,
- 0x29, 0xdf, 0x81, 0xfc, 0xa6, 0xbd, 0x6f, 0x4e, 0x9c, 0x8d, 0xbe, 0x39, 0xe8, 0x90, 0x45, 0x48,
- 0x3d, 0x6d, 0x1f, 0x98, 0x03, 0x64, 0xe4, 0x8c, 0xd4, 0x80, 0x3e, 0x10, 0x02, 0xc9, 0xfd, 0x93,
- 0x91, 0x59, 0x92, 0xb1, 0x31, 0xe9, 0x9c, 0x8c, 0xcc, 0xf2, 0xaf, 0x5c, 0xa1, 0x83, 0x50, 0x26,
- 0xb9, 0x0e, 0xc9, 0x2f, 0xf7, 0xad, 0x0e, 0x1f, 0xe5, 0x35, 0x7f, 0x14, 0xd6, 0xbf, 0xf2, 0xe5,
- 0xad, 0x9d, 0xc7, 0x46, 0xf2, 0x79, 0xdf, 0x42, 0xfb, 0xfb, 0xed, 0x83, 0x01, 0x35, 0x25, 0x51,
- 0xfb, 0x0e, 0x7d, 0xa0, 0xad, 0xbb, 0xed, 0x71, 0x7b, 0x58, 0x4a, 0xa8, 0x52, 0x25, 0x65, 0xa4,
- 0x46, 0xf4, 0x81, 0xdc, 0x87, 0x39, 0xc3, 0x7c, 0x71, 0xd4, 0x1f, 0x9b, 0x1d, 0x74, 0xae, 0x94,
- 0x54, 0xe5, 0x4a, 0x7e, 0xda, 0x3e, 0x76, 0x1a, 0x73, 0x63, 0x11, 0xcb, 0xc8, 0x23, 0xb3, 0xed,
- 0xb8, 0xe4, 0x94, 0x9a, 0x88, 0x25, 0x0b, 0x58, 0x4a, 0x6e, 0x8e, 0x9c, 0xbe, 0x6d, 0xb5, 0x07,
- 0x8c, 0x9c, 0x56, 0xa5, 0x18, 0xb2, 0x2d, 0x62, 0xc9, 0x9b, 0x50, 0xdc, 0x68, 0x3d, 0xb4, 0xed,
- 0x41, 0xcb, 0xf5, 0xa8, 0x04, 0xaa, 0x5c, 0xc9, 0x1a, 0x73, 0x5d, 0xda, 0xea, 0x4e, 0x89, 0x54,
- 0x40, 0xd9, 0x68, 0x6d, 0x59, 0x4e, 0x55, 0xf3, 0x81, 0x79, 0x55, 0xae, 0xa4, 0x8c, 0xf9, 0x2e,
- 0x36, 0x4f, 0x21, 0x6b, 0xba, 0x8f, 0x2c, 0xa8, 0x72, 0x25, 0xc1, 0x90, 0x35, 0xdd, 0x43, 0xde,
- 0x02, 0xb2, 0xd1, 0xda, 0xe8, 0x1f, 0x9b, 0x1d, 0xd1, 0xea, 0x9c, 0x2a, 0x57, 0x32, 0x86, 0xd2,
- 0xe5, 0x1d, 0x33, 0xd0, 0xa2, 0xe5, 0x79, 0x55, 0xae, 0xa4, 0x5d, 0xb4, 0x60, 0xfb, 0x06, 0x2c,
- 0x6c, 0xb4, 0xde, 0xed, 0x07, 0x1d, 0x2e, 0xaa, 0x72, 0x65, 0xce, 0x28, 0x76, 0x59, 0xfb, 0x34,
- 0x56, 0x34, 0xac, 0xa8, 0x72, 0x25, 0xc9, 0xb1, 0x82, 0x5d, 0x9c, 0xdd, 0xc6, 0xc0, 0x6e, 0x3b,
- 0x3e, 0x74, 0x41, 0x95, 0x2b, 0xb2, 0x31, 0xdf, 0xc5, 0xe6, 0xa0, 0xd5, 0xc7, 0xf6, 0xd1, 0xc1,
- 0xc0, 0xf4, 0xa1, 0x44, 0x95, 0x2b, 0x92, 0x51, 0xec, 0xb2, 0xf6, 0x20, 0x76, 0xcf, 0x19, 0xf7,
- 0xad, 0x9e, 0x8f, 0x3d, 0x8f, 0xfa, 0x2d, 0x76, 0x59, 0x7b, 0xd0, 0x83, 0x87, 0x27, 0x8e, 0x39,
- 0xf1, 0xa1, 0xa6, 0x2a, 0x57, 0x0a, 0xc6, 0x7c, 0x17, 0x9b, 0x43, 0x56, 0x43, 0x6b, 0xd0, 0x55,
- 0xe5, 0xca, 0x02, 0xb5, 0x3a, 0x63, 0x0d, 0xf6, 0x42, 0x6b, 0xd0, 0x53, 0xe5, 0x0a, 0xe1, 0x58,
- 0x61, 0x0d, 0x44, 0xcd, 0x30, 0x21, 0x96, 0x16, 0xd5, 0x84, 0xa0, 0x19, 0xd6, 0x18, 0xd4, 0x0c,
- 0x07, 0xbe, 0xa6, 0x26, 0x44, 0xcd, 0x84, 0x90, 0x38, 0x38, 0x47, 0x5e, 0x50, 0x13, 0xa2, 0x66,
- 0x38, 0x32, 0xa4, 0x19, 0x8e, 0x7d, 0x5d, 0x4d, 0x04, 0x35, 0x33, 0x85, 0x16, 0x2d, 0x97, 0xd4,
- 0x44, 0x50, 0x33, 0x1c, 0x1d, 0xd4, 0x0c, 0x07, 0x5f, 0x54, 0x13, 0x01, 0xcd, 0x84, 0xb1, 0xa2,
- 0xe1, 0x25, 0x35, 0x11, 0xd0, 0x8c, 0x38, 0x3b, 0x57, 0x33, 0x1c, 0xba, 0xac, 0x26, 0x44, 0xcd,
- 0x88, 0x56, 0x3d, 0xcd, 0x70, 0xe8, 0x25, 0x35, 0x11, 0xd0, 0x8c, 0x88, 0xf5, 0x34, 0xc3, 0xb1,
- 0x97, 0xd5, 0x44, 0x40, 0x33, 0x1c, 0x7b, 0x5d, 0xd4, 0x0c, 0x87, 0x7e, 0x2c, 0xa9, 0x09, 0x51,
- 0x34, 0x1c, 0x7a, 0x33, 0x20, 0x1a, 0x8e, 0xfd, 0x84, 0x62, 0x45, 0xd5, 0x84, 0xc1, 0xe2, 0x2a,
- 0x7c, 0x4a, 0xc1, 0xa2, 0x6c, 0x38, 0xd8, 0x97, 0x8d, 0x1b, 0x82, 0x4a, 0x57, 0x54, 0xc9, 0x93,
- 0x8d, 0x1b, 0xc3, 0x44, 0xd9, 0x78, 0xc0, 0xab, 0x18, 0x6a, 0xb9, 0x6c, 0xa6, 0x90, 0x35, 0xdd,
- 0x47, 0xaa, 0xaa, 0xe4, 0xcb, 0xc6, 0x43, 0x06, 0x64, 0xe3, 0x61, 0xaf, 0xa9, 0x92, 0x28, 0x9b,
- 0x19, 0x68, 0xd1, 0x72, 0x59, 0x95, 0x44, 0xd9, 0x78, 0x68, 0x51, 0x36, 0x1e, 0xf8, 0x0b, 0xaa,
- 0x24, 0xc8, 0x66, 0x1a, 0x2b, 0x1a, 0xfe, 0xa2, 0x2a, 0x09, 0xb2, 0x09, 0xce, 0x8e, 0xc9, 0xc6,
- 0x83, 0xbe, 0xa1, 0x4a, 0xbe, 0x6c, 0x82, 0x56, 0xb9, 0x6c, 0x3c, 0xe8, 0x9b, 0xaa, 0x24, 0xc8,
- 0x26, 0x88, 0xe5, 0xb2, 0xf1, 0xb0, 0x6f, 0x61, 0x7e, 0x73, 0x65, 0xe3, 0x61, 0x05, 0xd9, 0x78,
- 0xd0, 0xdf, 0xa1, 0xb9, 0xd0, 0x93, 0x8d, 0x07, 0x15, 0x65, 0xe3, 0x61, 0x7f, 0x97, 0x62, 0x7d,
- 0xd9, 0x4c, 0x83, 0xc5, 0x55, 0xf8, 0x3d, 0x0a, 0xf6, 0x65, 0xe3, 0x81, 0x57, 0xd0, 0x09, 0x2a,
- 0x9b, 0x8e, 0xd9, 0x6d, 0x1f, 0x0d, 0xa8, 0xc4, 0x2a, 0x54, 0x37, 0xf5, 0xa4, 0x33, 0x3e, 0x32,
- 0xa9, 0x27, 0xb6, 0x3d, 0x78, 0xec, 0xf6, 0x91, 0x15, 0x6a, 0x9c, 0xc9, 0xc7, 0x27, 0x5c, 0xa7,
- 0xfa, 0xa9, 0xcb, 0x55, 0xcd, 0x28, 0x32, 0x0d, 0x4d, 0xe3, 0x6b, 0xba, 0x80, 0xbf, 0x41, 0x55,
- 0x54, 0x97, 0x6b, 0x3a, 0xc3, 0xd7, 0x74, 0x1f, 0x5f, 0x85, 0xf3, 0xbe, 0x94, 0x7c, 0xc6, 0x4d,
- 0xaa, 0xa5, 0x7a, 0xa2, 0xaa, 0xad, 0x1a, 0x0b, 0xae, 0xa0, 0x66, 0x91, 0x02, 0xc3, 0xdc, 0xa2,
- 0x92, 0xaa, 0x27, 0x6a, 0xba, 0x47, 0x12, 0x47, 0xd2, 0xa8, 0x0c, 0xb9, 0xb0, 0x7c, 0xce, 0x6d,
- 0xaa, 0xac, 0x7a, 0xb2, 0xaa, 0xad, 0xae, 0x1a, 0x0a, 0xd7, 0xd7, 0x0c, 0x4e, 0x60, 0x9c, 0x15,
- 0xaa, 0xb0, 0x7a, 0xb2, 0xa6, 0x7b, 0x9c, 0xe0, 0x38, 0x0b, 0xae, 0xd0, 0x7c, 0xca, 0x97, 0xa8,
- 0xd2, 0xea, 0xe9, 0xea, 0x9a, 0xbe, 0xb6, 0x7e, 0xcf, 0x28, 0x32, 0xc5, 0xf9, 0x1c, 0x9d, 0x8e,
- 0xc3, 0x25, 0xe7, 0x93, 0x56, 0xa9, 0xe6, 0xea, 0x69, 0xed, 0xce, 0xda, 0x5d, 0xed, 0xae, 0xa1,
- 0x70, 0xed, 0xf9, 0xac, 0x77, 0x28, 0x8b, 0x8b, 0xcf, 0x67, 0xad, 0x51, 0xf5, 0xd5, 0x95, 0x67,
- 0xe6, 0x60, 0x60, 0xdf, 0x52, 0xcb, 0x2f, 0xed, 0xf1, 0xa0, 0x73, 0xad, 0x0c, 0x86, 0xc2, 0xf5,
- 0x28, 0x8e, 0xba, 0xe0, 0x0a, 0xd2, 0xa7, 0xff, 0x1a, 0x3d, 0x87, 0x15, 0xea, 0x99, 0x87, 0xfd,
- 0x9e, 0x65, 0x4f, 0x4c, 0xa3, 0xc8, 0xa4, 0x19, 0x5a, 0x93, 0xbd, 0xf0, 0x3a, 0xfe, 0x3a, 0xa5,
- 0x2d, 0xd4, 0x13, 0xb7, 0xab, 0x1a, 0x1d, 0x69, 0xd6, 0x3a, 0xee, 0x85, 0xd7, 0xf1, 0x37, 0x28,
- 0x87, 0xd4, 0x13, 0xb7, 0x6b, 0x3a, 0xe7, 0x88, 0xeb, 0x78, 0x07, 0x2e, 0x84, 0xf2, 0x62, 0x6b,
- 0xd4, 0x3e, 0x7c, 0x6e, 0x76, 0x4a, 0x1a, 0x4d, 0x8f, 0x0f, 0x65, 0x45, 0x32, 0xce, 0x07, 0x52,
- 0xe4, 0x2e, 0x76, 0x93, 0x7b, 0xf0, 0x7a, 0x38, 0x51, 0xba, 0xcc, 0x2a, 0xcd, 0x97, 0xc8, 0x5c,
- 0x0c, 0xe6, 0xcc, 0x10, 0x55, 0x08, 0xc0, 0x2e, 0x55, 0xa7, 0x09, 0xd4, 0xa7, 0xfa, 0x91, 0x98,
- 0x53, 0x7f, 0x06, 0x2e, 0x4e, 0xa7, 0x52, 0x97, 0xbc, 0x4e, 0x33, 0x2a, 0x92, 0x2f, 0x84, 0xb3,
- 0xea, 0x14, 0x7d, 0xc6, 0xd8, 0x35, 0x9a, 0x62, 0x45, 0xfa, 0xd4, 0xe8, 0xf7, 0xa1, 0x34, 0x95,
- 0x6c, 0x5d, 0xf6, 0x1d, 0x9a, 0x73, 0x91, 0xfd, 0x5a, 0x28, 0xef, 0x86, 0xc9, 0x33, 0x86, 0xbe,
- 0x4b, 0x93, 0xb0, 0x40, 0x9e, 0x1a, 0x19, 0x97, 0x2c, 0x98, 0x8e, 0x5d, 0xee, 0x3d, 0x9a, 0x95,
- 0xf9, 0x92, 0x05, 0x32, 0xb3, 0x38, 0x6e, 0x28, 0x3f, 0xbb, 0xdc, 0x3a, 0x4d, 0xd3, 0x7c, 0xdc,
- 0x60, 0xaa, 0xe6, 0xe4, 0xb7, 0x29, 0x79, 0x6f, 0xf6, 0x8c, 0x7f, 0x9c, 0xa0, 0x09, 0x96, 0xb3,
- 0xf7, 0x66, 0x4d, 0xd9, 0x63, 0xcf, 0x98, 0xf2, 0x4f, 0x28, 0x9b, 0x08, 0xec, 0xa9, 0x39, 0x3f,
- 0x06, 0xaf, 0xe2, 0xe8, 0x8d, 0xed, 0xa3, 0x51, 0x69, 0x43, 0x95, 0x2b, 0xa0, 0x5d, 0x99, 0xaa,
- 0x7e, 0xdc, 0x43, 0xde, 0x26, 0x45, 0x19, 0x41, 0x12, 0xb3, 0xc2, 0xec, 0x32, 0x2b, 0xbb, 0x6a,
- 0x22, 0xc2, 0x0a, 0x43, 0x79, 0x56, 0x04, 0x12, 0xb5, 0xe2, 0x06, 0x7d, 0x66, 0xe5, 0x03, 0x55,
- 0x9a, 0x69, 0xc5, 0x4d, 0x01, 0xdc, 0x4a, 0x80, 0xb4, 0xb4, 0xee, 0xd7, 0x5b, 0xd8, 0x4f, 0xbe,
- 0x18, 0x2e, 0xc0, 0x36, 0xf1, 0xfc, 0x1c, 0xac, 0xb4, 0x18, 0x4d, 0x70, 0x6e, 0x9a, 0xf6, 0xb3,
- 0x11, 0xb4, 0x80, 0x37, 0xd3, 0xb4, 0x9f, 0x9b, 0x41, 0x2b, 0xff, 0xa6, 0x04, 0x49, 0x5a, 0x4f,
- 0x92, 0x2c, 0x24, 0xdf, 0x6b, 0x6e, 0x3d, 0x56, 0xce, 0xd1, 0x5f, 0x0f, 0x9b, 0xcd, 0xa7, 0x8a,
- 0x44, 0x72, 0x90, 0x7a, 0xf8, 0x95, 0xfd, 0xc6, 0x9e, 0x22, 0x93, 0x22, 0xe4, 0x37, 0xb6, 0x76,
- 0x36, 0x1b, 0xc6, 0xae, 0xb1, 0xb5, 0xb3, 0xaf, 0x24, 0x68, 0xdf, 0xc6, 0xd3, 0xe6, 0x83, 0x7d,
- 0x25, 0x49, 0x32, 0x90, 0xa0, 0x6d, 0x29, 0x02, 0x90, 0xde, 0xdb, 0x37, 0xb6, 0x76, 0x36, 0x95,
- 0x34, 0xb5, 0xb2, 0xbf, 0xb5, 0xdd, 0x50, 0x32, 0x14, 0xb9, 0xff, 0xee, 0xee, 0xd3, 0x86, 0x92,
- 0xa5, 0x3f, 0x1f, 0x18, 0xc6, 0x83, 0xaf, 0x28, 0x39, 0x4a, 0xda, 0x7e, 0xb0, 0xab, 0x00, 0x76,
- 0x3f, 0x78, 0xf8, 0xb4, 0xa1, 0xe4, 0x49, 0x01, 0xb2, 0x1b, 0xef, 0xee, 0x3c, 0xda, 0xdf, 0x6a,
- 0xee, 0x28, 0x85, 0xf2, 0x6f, 0xc9, 0x00, 0x9b, 0xf6, 0xde, 0xf3, 0xfe, 0x08, 0xab, 0xe2, 0xcb,
- 0x00, 0x93, 0xe7, 0xfd, 0x51, 0x0b, 0xa5, 0xc7, 0x2b, 0xbb, 0x1c, 0x6d, 0xc1, 0xa0, 0x43, 0xae,
- 0x41, 0x01, 0xbb, 0xbb, 0x2c, 0x14, 0x60, 0x41, 0x97, 0x31, 0xf2, 0xb4, 0x8d, 0x47, 0x87, 0x20,
- 0xa4, 0xa6, 0x63, 0x1d, 0x97, 0x16, 0x20, 0x35, 0x9d, 0x5c, 0x05, 0x7c, 0x6c, 0x4d, 0x30, 0xac,
- 0x63, 0xed, 0x96, 0x33, 0x70, 0x5c, 0x16, 0xe8, 0xc9, 0xdb, 0x80, 0x63, 0x32, 0x59, 0x14, 0xa7,
- 0x25, 0xea, 0xba, 0xbb, 0x42, 0x7f, 0x30, 0x59, 0xf8, 0x84, 0xa5, 0x26, 0xe4, 0xbc, 0x76, 0x3a,
- 0x16, 0xb6, 0xf2, 0x19, 0x29, 0x38, 0x23, 0xc0, 0x26, 0x6f, 0x4a, 0x0c, 0xc0, 0xbd, 0x59, 0x40,
- 0x6f, 0x18, 0x89, 0xb9, 0x53, 0xbe, 0x0c, 0x73, 0x3b, 0xb6, 0xc5, 0xb6, 0x10, 0xae, 0x52, 0x01,
- 0xa4, 0x76, 0x49, 0xc2, 0x12, 0x46, 0x6a, 0x97, 0xaf, 0x00, 0x08, 0x7d, 0x0a, 0x48, 0x07, 0xac,
- 0x0f, 0x37, 0xa2, 0x74, 0x50, 0xbe, 0x09, 0xe9, 0xed, 0xf6, 0xf1, 0x7e, 0xbb, 0x47, 0xae, 0x01,
- 0x0c, 0xda, 0x13, 0xa7, 0xd5, 0x45, 0xa9, 0x7c, 0xfe, 0xf9, 0xe7, 0x9f, 0x4b, 0x78, 0xe2, 0xca,
- 0xd1, 0x56, 0x26, 0x95, 0x17, 0x00, 0xcd, 0x41, 0x67, 0xdb, 0x9c, 0x4c, 0xda, 0x3d, 0x93, 0x54,
- 0x21, 0x6d, 0x99, 0x13, 0x9a, 0x72, 0x24, 0x2c, 0xe6, 0x97, 0xfd, 0x55, 0xf0, 0x51, 0x2b, 0x3b,
- 0x08, 0x31, 0x38, 0x94, 0x28, 0x90, 0xb0, 0x8e, 0x86, 0x78, 0x59, 0x91, 0x32, 0xe8, 0xcf, 0xa5,
- 0x4b, 0x90, 0x66, 0x18, 0x42, 0x20, 0x69, 0xb5, 0x87, 0x66, 0x89, 0x8d, 0x8b, 0xbf, 0xcb, 0xbf,
- 0x2a, 0x01, 0xec, 0x98, 0x2f, 0xcf, 0x30, 0xa6, 0x8f, 0x8a, 0x19, 0x33, 0xc1, 0xc6, 0xbc, 0x1f,
- 0x37, 0x26, 0xd5, 0x59, 0xd7, 0xb6, 0x3b, 0x2d, 0xf6, 0x8a, 0xd9, 0xbd, 0x4a, 0x8e, 0xb6, 0xe0,
- 0x5b, 0x2b, 0x7f, 0x00, 0x85, 0x2d, 0xcb, 0x32, 0xc7, 0xae, 0x4f, 0x04, 0x92, 0xcf, 0xec, 0x89,
- 0xc3, 0x2f, 0x78, 0xf0, 0x37, 0x29, 0x41, 0x72, 0x64, 0x8f, 0x1d, 0x36, 0xcf, 0x7a, 0x52, 0x5f,
- 0x5d, 0x5d, 0x35, 0xb0, 0x85, 0x5c, 0x82, 0xdc, 0xa1, 0x6d, 0x59, 0xe6, 0x21, 0x9d, 0x44, 0x02,
- 0x6b, 0x0b, 0xbf, 0xa1, 0xfc, 0xcb, 0x12, 0x14, 0x9a, 0xce, 0x33, 0xdf, 0xb8, 0x02, 0x89, 0xe7,
- 0xe6, 0x09, 0xba, 0x97, 0x30, 0xe8, 0x4f, 0xb2, 0x08, 0xa9, 0x9f, 0x6f, 0x0f, 0x8e, 0xd8, 0x85,
- 0x4f, 0xc1, 0x60, 0x0f, 0xe4, 0x02, 0xa4, 0x5f, 0x9a, 0xfd, 0xde, 0x33, 0x07, 0x6d, 0xca, 0x06,
- 0x7f, 0x22, 0xb7, 0x20, 0xd5, 0xa7, 0xce, 0x96, 0x92, 0xb8, 0x5e, 0x17, 0xfc, 0xf5, 0x12, 0xe7,
- 0x60, 0x30, 0xd0, 0x8d, 0x6c, 0xb6, 0xa3, 0x7c, 0xf4, 0xd1, 0x47, 0x1f, 0xc9, 0xe5, 0x2e, 0x2c,
- 0xba, 0xb1, 0x23, 0x30, 0xd9, 0x1d, 0x28, 0x0d, 0x4c, 0xbb, 0xd5, 0xed, 0x5b, 0xed, 0xc1, 0xe0,
- 0xa4, 0xf5, 0xd2, 0xb6, 0x5a, 0x6d, 0xab, 0x65, 0x4f, 0x0e, 0xdb, 0x63, 0x5c, 0x80, 0xe8, 0x21,
- 0x16, 0x07, 0xa6, 0xbd, 0xc1, 0x68, 0xef, 0xdb, 0xd6, 0x03, 0xab, 0x49, 0x39, 0xe5, 0x3f, 0x48,
- 0x42, 0x6e, 0xfb, 0xc4, 0xb5, 0xbe, 0x08, 0xa9, 0x43, 0xfb, 0xc8, 0x62, 0x6b, 0x99, 0x32, 0xd8,
- 0x83, 0xf7, 0x8e, 0x64, 0xe1, 0x1d, 0x2d, 0x42, 0xea, 0xc5, 0x91, 0xed, 0x98, 0x38, 0xdd, 0x9c,
- 0xc1, 0x1e, 0xe8, 0x6a, 0x8d, 0x4c, 0xa7, 0x94, 0xc4, 0x0a, 0x93, 0xfe, 0xf4, 0xe7, 0x9f, 0x3a,
- 0xc3, 0xfc, 0xc9, 0x0a, 0xa4, 0x6d, 0xba, 0xfa, 0x93, 0x52, 0x1a, 0x2f, 0xb7, 0x04, 0xb8, 0xf8,
- 0x56, 0x0c, 0x8e, 0x22, 0x5b, 0xb0, 0xf0, 0xd2, 0x6c, 0x0d, 0x8f, 0x26, 0x4e, 0xab, 0x67, 0xb7,
- 0x3a, 0xa6, 0x39, 0x32, 0xc7, 0xa5, 0x39, 0x1c, 0x49, 0x88, 0x09, 0xb3, 0x16, 0xd2, 0x98, 0x7f,
- 0x69, 0x6e, 0x1f, 0x4d, 0x9c, 0x4d, 0xfb, 0x31, 0xb2, 0x48, 0x15, 0x72, 0x63, 0x93, 0x46, 0x02,
- 0xea, 0x6c, 0x21, 0x3c, 0x7a, 0x80, 0x9a, 0x1d, 0x9b, 0x23, 0x6c, 0x20, 0xeb, 0x90, 0x3d, 0xe8,
- 0x3f, 0x37, 0x27, 0xcf, 0xcc, 0x4e, 0x29, 0xa3, 0x4a, 0x95, 0x79, 0xed, 0xa2, 0xcf, 0xf1, 0x96,
- 0x75, 0xe5, 0x91, 0x3d, 0xb0, 0xc7, 0x86, 0x07, 0x25, 0xf7, 0x21, 0x37, 0xb1, 0x87, 0x26, 0xd3,
- 0x77, 0x16, 0x33, 0xdb, 0xe5, 0x59, 0xbc, 0x3d, 0x7b, 0x68, 0xba, 0x11, 0xcc, 0xc5, 0x93, 0x65,
- 0xe6, 0xe8, 0x01, 0x3d, 0xbf, 0x96, 0x00, 0xeb, 0x73, 0xea, 0x10, 0x9e, 0x67, 0xc9, 0x12, 0x75,
- 0xa8, 0xd7, 0xa5, 0xc7, 0x92, 0x52, 0x1e, 0x8b, 0x3b, 0xef, 0x79, 0xe9, 0x16, 0xe4, 0x3c, 0x83,
- 0x7e, 0xe8, 0x63, 0xe1, 0x26, 0x87, 0xf1, 0x80, 0x85, 0x3e, 0x16, 0x6b, 0xde, 0x80, 0x14, 0xba,
- 0x4d, 0xd3, 0x84, 0xd1, 0xa0, 0x59, 0x29, 0x07, 0xa9, 0x4d, 0xa3, 0xd1, 0xd8, 0x51, 0x24, 0x4c,
- 0x50, 0x4f, 0xdf, 0x6d, 0x28, 0xb2, 0xa0, 0xd8, 0xdf, 0x96, 0x20, 0xd1, 0x38, 0x46, 0xb5, 0xd0,
- 0x69, 0xb8, 0x3b, 0x9a, 0xfe, 0xd6, 0x6a, 0x90, 0x1c, 0xda, 0x63, 0x93, 0x9c, 0x9f, 0x31, 0xcb,
- 0x52, 0x0f, 0xdf, 0x97, 0x70, 0x95, 0xdb, 0x38, 0x76, 0x0c, 0xc4, 0x6b, 0x6f, 0x41, 0xd2, 0x31,
- 0x8f, 0x9d, 0xd9, 0xbc, 0x67, 0x6c, 0x00, 0x0a, 0xd0, 0x6e, 0x42, 0xda, 0x3a, 0x1a, 0x1e, 0x98,
- 0xe3, 0xd9, 0xd0, 0x3e, 0x4e, 0x8f, 0x43, 0xca, 0xef, 0x81, 0xf2, 0xc8, 0x1e, 0x8e, 0x06, 0xe6,
- 0x71, 0xe3, 0xd8, 0x31, 0xad, 0x49, 0xdf, 0xb6, 0xa8, 0x9e, 0xbb, 0xfd, 0x31, 0x46, 0x11, 0xbc,
- 0xb0, 0xc5, 0x07, 0xba, 0xab, 0x27, 0xe6, 0xa1, 0x6d, 0x75, 0x78, 0xc0, 0xe4, 0x4f, 0x14, 0xed,
- 0x3c, 0xeb, 0x8f, 0x69, 0x00, 0xa1, 0x71, 0x9e, 0x3d, 0x94, 0x37, 0xa1, 0xc8, 0x0f, 0xfa, 0x13,
- 0x3e, 0x70, 0xf9, 0x06, 0x14, 0xdc, 0x26, 0xbc, 0xbd, 0xce, 0x42, 0xf2, 0x83, 0x86, 0xd1, 0x54,
- 0xce, 0xd1, 0x65, 0x6d, 0xee, 0x34, 0x14, 0x89, 0xfe, 0xd8, 0x7f, 0xbf, 0x19, 0x58, 0xca, 0x4b,
- 0x50, 0xf0, 0x7c, 0xdf, 0x33, 0x1d, 0xec, 0xa1, 0x09, 0x21, 0x53, 0x97, 0xb3, 0x52, 0x39, 0x03,
- 0xa9, 0xc6, 0x70, 0xe4, 0x9c, 0x94, 0x7f, 0x11, 0xf2, 0x1c, 0xf4, 0xb4, 0x3f, 0x71, 0xc8, 0x1d,
- 0xc8, 0x0c, 0xf9, 0x7c, 0x25, 0x3c, 0x73, 0x89, 0x9a, 0xf2, 0x71, 0xee, 0x6f, 0xc3, 0x45, 0x2f,
- 0x55, 0x21, 0x23, 0xc4, 0x52, 0xbe, 0xd5, 0x65, 0x71, 0xab, 0xb3, 0xa0, 0x90, 0x10, 0x82, 0x42,
- 0x79, 0x1b, 0x32, 0x2c, 0x03, 0x4e, 0x30, 0xab, 0xb3, 0x7a, 0x8d, 0x89, 0x89, 0xbd, 0xf9, 0x3c,
- 0x6b, 0x63, 0x57, 0xc8, 0x57, 0x21, 0x8f, 0x82, 0xe5, 0x08, 0x16, 0x3a, 0x01, 0x9b, 0x98, 0xdc,
- 0x7e, 0x3f, 0x05, 0x59, 0x77, 0xa5, 0xc8, 0x32, 0xa4, 0x59, 0x91, 0x84, 0xa6, 0xdc, 0x22, 0x3e,
- 0x85, 0x65, 0x11, 0x59, 0x86, 0x0c, 0x2f, 0x84, 0x78, 0x74, 0xa7, 0x15, 0x7b, 0x9a, 0x15, 0x3e,
- 0x5e, 0x67, 0x4d, 0xc7, 0xc0, 0xc4, 0xca, 0xf3, 0x34, 0x2b, 0x6d, 0x88, 0x0a, 0x39, 0xaf, 0x98,
- 0xc1, 0x78, 0xcc, 0x6b, 0xf1, 0xac, 0x5b, 0xbd, 0x08, 0x88, 0x9a, 0x8e, 0x11, 0x8b, 0x17, 0xde,
- 0xd9, 0xae, 0x7f, 0x3c, 0xc9, 0xba, 0x25, 0x09, 0xde, 0xa1, 0xbb, 0x55, 0x76, 0x86, 0x17, 0x21,
- 0x3e, 0xa0, 0xa6, 0x63, 0x48, 0x70, 0x4b, 0xea, 0x0c, 0x2f, 0x34, 0xc8, 0x55, 0xea, 0x22, 0x16,
- 0x0e, 0xb8, 0xf5, 0xfd, 0xfa, 0x39, 0xcd, 0xca, 0x09, 0x72, 0x8d, 0x5a, 0x60, 0xd5, 0x01, 0xee,
- 0x4b, 0xbf, 0x58, 0xce, 0xf0, 0xa2, 0x81, 0xdc, 0xa4, 0x10, 0xb6, 0xfc, 0x25, 0x88, 0xa8, 0x8c,
- 0x33, 0xbc, 0x32, 0x26, 0x2a, 0x1d, 0x10, 0xc3, 0x03, 0x86, 0x04, 0xa1, 0x0a, 0x4e, 0xb3, 0x2a,
- 0x98, 0x5c, 0x41, 0x73, 0x6c, 0x52, 0x05, 0xbf, 0xe2, 0xcd, 0xf0, 0x2a, 0xc3, 0xef, 0xc7, 0x23,
- 0x9b, 0x57, 0xdd, 0x66, 0x78, 0x1d, 0x41, 0x6a, 0xf4, 0x7d, 0x51, 0x7d, 0x97, 0xe6, 0x31, 0x08,
- 0x96, 0x7c, 0xe1, 0xb9, 0xef, 0x94, 0xc5, 0xc0, 0x3a, 0x8b, 0x20, 0x46, 0xaa, 0x8b, 0xbb, 0x61,
- 0x89, 0xf2, 0x76, 0xfb, 0x56, 0xb7, 0x54, 0xc4, 0x95, 0x48, 0xf4, 0xad, 0xae, 0x91, 0xea, 0xd2,
- 0x16, 0xa6, 0x81, 0x1d, 0xda, 0xa7, 0x60, 0x5f, 0xf2, 0x36, 0xeb, 0xa4, 0x4d, 0xa4, 0x04, 0xa9,
- 0x8d, 0xd6, 0x4e, 0xdb, 0x2a, 0x2d, 0x30, 0x9e, 0xd5, 0xb6, 0x8c, 0x64, 0x77, 0xa7, 0x6d, 0x91,
- 0xb7, 0x20, 0x31, 0x39, 0x3a, 0x28, 0x91, 0xf0, 0xe7, 0x8d, 0xbd, 0xa3, 0x03, 0xd7, 0x15, 0x83,
- 0x22, 0xc8, 0x32, 0x64, 0x27, 0xce, 0xb8, 0xf5, 0x0b, 0xe6, 0xd8, 0x2e, 0x9d, 0xc7, 0x25, 0x3c,
- 0x67, 0x64, 0x26, 0xce, 0xf8, 0x03, 0x73, 0x6c, 0x9f, 0x31, 0xf8, 0x95, 0xaf, 0x40, 0x5e, 0xb0,
- 0x4b, 0x8a, 0x20, 0x59, 0xec, 0xa4, 0x50, 0x97, 0xee, 0x18, 0x92, 0x55, 0xde, 0x87, 0x82, 0x5b,
- 0x48, 0xe0, 0x7c, 0x35, 0xba, 0x93, 0x06, 0xf6, 0x18, 0xf7, 0xe7, 0xbc, 0x76, 0x49, 0x4c, 0x51,
- 0x3e, 0x8c, 0xa7, 0x0b, 0x06, 0x2d, 0x2b, 0x21, 0x57, 0xa4, 0xf2, 0x0f, 0x25, 0x28, 0x6c, 0xdb,
- 0x63, 0xff, 0x96, 0x77, 0x11, 0x52, 0x07, 0xb6, 0x3d, 0x98, 0xa0, 0xd9, 0xac, 0xc1, 0x1e, 0xc8,
- 0x1b, 0x50, 0xc0, 0x1f, 0x6e, 0x01, 0x28, 0x7b, 0xf7, 0x0b, 0x79, 0x6c, 0xe7, 0x55, 0x1f, 0x81,
- 0x64, 0xdf, 0x72, 0x26, 0x3c, 0x92, 0xe1, 0x6f, 0xf2, 0x05, 0xc8, 0xd3, 0xbf, 0x2e, 0x33, 0xe9,
- 0x1d, 0x58, 0x81, 0x36, 0x73, 0xe2, 0x5b, 0x30, 0x87, 0x6f, 0xdf, 0x83, 0x65, 0xbc, 0xbb, 0x84,
- 0x02, 0xeb, 0xe0, 0xc0, 0x12, 0x64, 0x58, 0x28, 0x98, 0xe0, 0x27, 0xab, 0x9c, 0xe1, 0x3e, 0xd2,
- 0xf0, 0x8a, 0x95, 0x00, 0x4b, 0xf7, 0x19, 0x83, 0x3f, 0x95, 0x1f, 0x40, 0x16, 0xb3, 0x54, 0x73,
- 0xd0, 0x21, 0x65, 0x90, 0x7a, 0x25, 0x13, 0x73, 0xe4, 0xa2, 0x70, 0xcc, 0xe7, 0xdd, 0x2b, 0x9b,
- 0x86, 0xd4, 0x5b, 0x5a, 0x00, 0x69, 0x93, 0x9e, 0xbb, 0x8f, 0x79, 0x98, 0x96, 0x8e, 0xcb, 0x4d,
- 0x6e, 0x62, 0xc7, 0x7c, 0x19, 0x67, 0x62, 0xc7, 0x7c, 0xc9, 0x4c, 0x5c, 0x9d, 0x32, 0x41, 0x9f,
- 0x4e, 0xf8, 0xf7, 0x3b, 0xe9, 0x84, 0x9e, 0xf3, 0x71, 0x7b, 0xf6, 0xad, 0xde, 0xae, 0xdd, 0xb7,
- 0xf0, 0x9c, 0xdf, 0xc5, 0x73, 0x92, 0x64, 0x48, 0xdd, 0xf2, 0x67, 0x49, 0x98, 0xe7, 0x41, 0xf4,
- 0xfd, 0xbe, 0xf3, 0x6c, 0xbb, 0x3d, 0x22, 0x4f, 0xa1, 0x40, 0xe3, 0x67, 0x6b, 0xd8, 0x1e, 0x8d,
- 0xe8, 0x46, 0x95, 0xf0, 0x50, 0x71, 0x7d, 0x2a, 0x28, 0x73, 0xfc, 0xca, 0x4e, 0x7b, 0x68, 0x6e,
- 0x33, 0x6c, 0xc3, 0x72, 0xc6, 0x27, 0x46, 0xde, 0xf2, 0x5b, 0xc8, 0x16, 0xe4, 0x87, 0x93, 0x9e,
- 0x67, 0x4c, 0x46, 0x63, 0x95, 0x48, 0x63, 0xdb, 0x93, 0x5e, 0xc0, 0x16, 0x0c, 0xbd, 0x06, 0xea,
- 0x18, 0x8d, 0xbc, 0x9e, 0xad, 0xc4, 0x29, 0x8e, 0xd1, 0x20, 0x11, 0x74, 0xec, 0xc0, 0x6f, 0x21,
- 0x8f, 0x01, 0xe8, 0x46, 0x72, 0x6c, 0x5a, 0x24, 0xa1, 0x56, 0xf2, 0xda, 0x9b, 0x91, 0xb6, 0xf6,
- 0x9c, 0xf1, 0xbe, 0xbd, 0xe7, 0x8c, 0x99, 0x21, 0xba, 0x05, 0xf1, 0x71, 0xe9, 0x1d, 0x50, 0xc2,
- 0xf3, 0x17, 0xcf, 0xde, 0xa9, 0x19, 0x67, 0xef, 0x1c, 0x3f, 0x7b, 0xd7, 0xe5, 0xbb, 0xd2, 0xd2,
- 0x7b, 0x50, 0x0c, 0x4d, 0x59, 0xa4, 0x13, 0x46, 0xbf, 0x2d, 0xd2, 0xf3, 0xda, 0xeb, 0xc2, 0xd7,
- 0x63, 0xf1, 0xd5, 0x8a, 0x76, 0xdf, 0x01, 0x25, 0x3c, 0x7d, 0xd1, 0x70, 0x36, 0xa6, 0x26, 0x40,
- 0xfe, 0x7d, 0x98, 0x0b, 0x4c, 0x59, 0x24, 0xe7, 0x4e, 0x99, 0x54, 0xf9, 0x97, 0x52, 0x90, 0x6a,
- 0x5a, 0xa6, 0xdd, 0x25, 0xaf, 0x07, 0x33, 0xe2, 0x93, 0x73, 0x6e, 0x36, 0xbc, 0x18, 0xca, 0x86,
- 0x4f, 0xce, 0x79, 0xb9, 0xf0, 0x62, 0x28, 0x17, 0xba, 0x5d, 0x35, 0x9d, 0x5c, 0x9e, 0xca, 0x84,
- 0x4f, 0xce, 0x09, 0x69, 0xf0, 0xf2, 0x54, 0x1a, 0xf4, 0xbb, 0x6b, 0x3a, 0x0d, 0x9d, 0xc1, 0x1c,
- 0xf8, 0xe4, 0x9c, 0x9f, 0xff, 0x96, 0xc3, 0xf9, 0xcf, 0xeb, 0xac, 0xe9, 0xcc, 0x25, 0x21, 0xf7,
- 0xa1, 0x4b, 0x2c, 0xeb, 0x2d, 0x87, 0xb3, 0x1e, 0xf2, 0x78, 0xbe, 0x5b, 0x0e, 0xe7, 0x3b, 0xec,
- 0xe4, 0xf9, 0xed, 0x62, 0x28, 0xbf, 0xa1, 0x51, 0x96, 0xd8, 0x96, 0xc3, 0x89, 0x8d, 0xf1, 0x04,
- 0x4f, 0xc5, 0xac, 0xe6, 0x75, 0xd6, 0x74, 0xa2, 0x85, 0x52, 0x5a, 0xf4, 0xb9, 0x1e, 0xdf, 0x05,
- 0x86, 0x77, 0x9d, 0x2e, 0x9b, 0x7b, 0xe4, 0x2c, 0xc6, 0x7c, 0x60, 0xc7, 0xd5, 0x74, 0x8f, 0x5c,
- 0x1a, 0x64, 0xba, 0xbc, 0xd4, 0x55, 0x30, 0x46, 0x09, 0xb2, 0xc4, 0x97, 0xbf, 0xb2, 0xd1, 0xc2,
- 0x58, 0x85, 0xf3, 0x62, 0xa7, 0xf7, 0x0a, 0xcc, 0x6d, 0xb4, 0x9e, 0xb6, 0xc7, 0x3d, 0x73, 0xe2,
- 0xb4, 0xf6, 0xdb, 0x3d, 0xef, 0xba, 0x80, 0xbe, 0xff, 0x7c, 0x97, 0xf7, 0xec, 0xb7, 0x7b, 0xe4,
- 0x82, 0x2b, 0xae, 0x0e, 0xf6, 0x4a, 0x5c, 0x5e, 0x4b, 0xaf, 0xd3, 0x45, 0x63, 0xc6, 0x30, 0xea,
- 0x2d, 0xf0, 0xa8, 0xf7, 0x30, 0x03, 0xa9, 0x23, 0xab, 0x6f, 0x5b, 0x0f, 0x73, 0x90, 0x71, 0xec,
- 0xf1, 0xb0, 0xed, 0xd8, 0xe5, 0x1f, 0x49, 0x00, 0x8f, 0xec, 0xe1, 0xf0, 0xc8, 0xea, 0xbf, 0x38,
- 0x32, 0xc9, 0x15, 0xc8, 0x0f, 0xdb, 0xcf, 0xcd, 0xd6, 0xd0, 0x6c, 0x1d, 0x8e, 0xdd, 0x7d, 0x90,
- 0xa3, 0x4d, 0xdb, 0xe6, 0xa3, 0xf1, 0x09, 0x29, 0xb9, 0x87, 0x71, 0xd4, 0x0e, 0x4a, 0x92, 0x1f,
- 0xce, 0x17, 0xf9, 0xf1, 0x32, 0xcd, 0xdf, 0xa1, 0x7b, 0xc0, 0x64, 0x15, 0x43, 0x86, 0xbf, 0x3d,
- 0x7c, 0xa2, 0x92, 0x77, 0xcc, 0xe1, 0xa8, 0x75, 0x88, 0x52, 0xa1, 0x72, 0x48, 0xd1, 0xe7, 0x47,
- 0xe4, 0x36, 0x24, 0x0e, 0xed, 0x01, 0x8a, 0xe4, 0x94, 0xf7, 0x42, 0x71, 0xe4, 0x0d, 0x48, 0x0c,
- 0x27, 0x4c, 0x36, 0x79, 0x6d, 0x41, 0x38, 0x11, 0xb0, 0x24, 0x44, 0x61, 0xc3, 0x49, 0xcf, 0x9b,
- 0xf7, 0x8d, 0x22, 0x24, 0x36, 0x9a, 0x4d, 0x9a, 0xe5, 0x37, 0x9a, 0xcd, 0x35, 0x45, 0xaa, 0x7f,
- 0x09, 0xb2, 0xbd, 0xb1, 0x69, 0xd2, 0xf0, 0x30, 0xbb, 0xba, 0xf8, 0x10, 0xb3, 0x9a, 0x07, 0xaa,
- 0x6f, 0x43, 0xe6, 0x90, 0xd5, 0x17, 0x24, 0xa2, 0x80, 0x2d, 0xfd, 0x21, 0xbb, 0x3e, 0x59, 0xf2,
- 0xbb, 0xc3, 0x15, 0x89, 0xe1, 0xda, 0xa8, 0xef, 0x42, 0x6e, 0xdc, 0x3a, 0xcd, 0xe0, 0xc7, 0x2c,
- 0xbb, 0xc4, 0x19, 0xcc, 0x8e, 0x79, 0x53, 0xbd, 0x01, 0x0b, 0x96, 0xed, 0x7e, 0xb2, 0x68, 0x75,
- 0xd8, 0x1e, 0xbb, 0x38, 0x7d, 0x68, 0x73, 0x8d, 0x9b, 0xec, 0x33, 0xa1, 0x65, 0xf3, 0x0e, 0xb6,
- 0x2b, 0xeb, 0x8f, 0x40, 0x11, 0xcc, 0x60, 0x91, 0x19, 0x67, 0xa5, 0xcb, 0xbe, 0x4b, 0x7a, 0x56,
- 0x70, 0xdf, 0x87, 0x8c, 0xb0, 0x9d, 0x19, 0x63, 0xa4, 0xc7, 0x3e, 0xf2, 0x7a, 0x46, 0x30, 0xd4,
- 0x4d, 0x1b, 0xa1, 0xb1, 0x26, 0xda, 0xc8, 0x33, 0xf6, 0xfd, 0x57, 0x34, 0x52, 0xd3, 0x43, 0xab,
- 0x72, 0x74, 0xaa, 0x2b, 0x7d, 0xf6, 0xf9, 0xd6, 0xb3, 0xc2, 0x02, 0xe0, 0x0c, 0x33, 0xf1, 0xce,
- 0x7c, 0xc8, 0xbe, 0xec, 0x06, 0xcc, 0x4c, 0x79, 0x33, 0x39, 0xd5, 0x9b, 0xe7, 0xec, 0x33, 0xaa,
- 0x67, 0x66, 0x6f, 0x96, 0x37, 0x93, 0x53, 0xbd, 0x19, 0xb0, 0x0f, 0xac, 0x01, 0x33, 0x35, 0xbd,
- 0xbe, 0x09, 0x44, 0x7c, 0xd5, 0x3c, 0x4f, 0xc4, 0xd8, 0x19, 0xb2, 0xcf, 0xe6, 0xfe, 0xcb, 0x66,
- 0x94, 0x59, 0x86, 0xe2, 0x1d, 0xb2, 0xd8, 0x17, 0xf5, 0xa0, 0xa1, 0x9a, 0x5e, 0xdf, 0x82, 0xf3,
- 0xe2, 0xc4, 0xce, 0xe0, 0x92, 0xad, 0x4a, 0x95, 0xa2, 0xb1, 0xe0, 0x4f, 0x8d, 0x73, 0x66, 0x9a,
- 0x8a, 0x77, 0x6a, 0xa4, 0x4a, 0x15, 0x65, 0xca, 0x54, 0x4d, 0xaf, 0x3f, 0x80, 0xa2, 0x60, 0xea,
- 0x00, 0x33, 0x74, 0xb4, 0x99, 0x17, 0xec, 0x5f, 0x1b, 0x3c, 0x33, 0x34, 0xa3, 0x87, 0xdf, 0x18,
- 0xcf, 0x71, 0xd1, 0x46, 0xc6, 0xec, 0xbb, 0xbc, 0xef, 0x0b, 0x32, 0x42, 0x5b, 0x02, 0x2b, 0xed,
- 0x38, 0x2b, 0x13, 0xf6, 0xc5, 0xde, 0x77, 0x85, 0x12, 0xea, 0xfd, 0xc0, 0x74, 0x4c, 0x9a, 0xe4,
- 0x62, 0x6c, 0x38, 0x18, 0x91, 0xdf, 0x8c, 0x04, 0xac, 0x88, 0x57, 0x21, 0xc2, 0xb4, 0xe9, 0x63,
- 0x7d, 0x0b, 0xe6, 0xcf, 0x1e, 0x90, 0x3e, 0x96, 0x58, 0x5d, 0x5c, 0x5d, 0xa1, 0xa5, 0xb3, 0x31,
- 0xd7, 0x09, 0xc4, 0xa5, 0x06, 0xcc, 0x9d, 0x39, 0x28, 0x7d, 0x22, 0xb1, 0xea, 0x92, 0x5a, 0x32,
- 0x0a, 0x9d, 0x60, 0x64, 0x9a, 0x3b, 0x73, 0x58, 0xfa, 0x54, 0x62, 0x57, 0x11, 0xba, 0xe6, 0x19,
- 0x71, 0x23, 0xd3, 0xdc, 0x99, 0xc3, 0xd2, 0x57, 0x59, 0xed, 0x28, 0xeb, 0x55, 0xd1, 0x08, 0xc6,
- 0x82, 0xf9, 0xb3, 0x87, 0xa5, 0xaf, 0x49, 0x78, 0x2d, 0x21, 0xeb, 0xba, 0xb7, 0x2e, 0x5e, 0x64,
- 0x9a, 0x3f, 0x7b, 0x58, 0xfa, 0xba, 0x84, 0x97, 0x17, 0xb2, 0xbe, 0x1e, 0x30, 0x13, 0xf4, 0xe6,
- 0xf4, 0xb0, 0xf4, 0x0d, 0x09, 0xef, 0x13, 0x64, 0xbd, 0xe6, 0x99, 0xd9, 0x9b, 0xf2, 0xe6, 0xf4,
- 0xb0, 0xf4, 0x4d, 0x3c, 0xc5, 0xd7, 0x65, 0xfd, 0x4e, 0xc0, 0x0c, 0x46, 0xa6, 0xe2, 0x2b, 0x84,
- 0xa5, 0x6f, 0x49, 0x78, 0xed, 0x23, 0xeb, 0x77, 0x0d, 0x77, 0x74, 0x3f, 0x32, 0x15, 0x5f, 0x21,
- 0x2c, 0x7d, 0x26, 0xe1, 0xed, 0x90, 0xac, 0xdf, 0x0b, 0x1a, 0xc2, 0xc8, 0xa4, 0xbc, 0x4a, 0x58,
- 0xfa, 0x36, 0xb5, 0x54, 0xac, 0xcb, 0xeb, 0xab, 0x86, 0xeb, 0x80, 0x10, 0x99, 0x94, 0x57, 0x09,
- 0x4b, 0xdf, 0xa1, 0xa6, 0x94, 0xba, 0xbc, 0xbe, 0x16, 0x32, 0x55, 0xd3, 0xeb, 0x8f, 0xa0, 0x70,
- 0xd6, 0xb0, 0xf4, 0x5d, 0xf1, 0xd6, 0x2d, 0xdf, 0x11, 0x62, 0xd3, 0xae, 0xf0, 0xce, 0x4e, 0x0d,
- 0x4c, 0xdf, 0xc3, 0x1a, 0xa7, 0x3e, 0xf7, 0x84, 0xdd, 0x4c, 0x31, 0x82, 0xff, 0xfa, 0x58, 0x98,
- 0xda, 0xf6, 0xf7, 0xc7, 0xa9, 0x31, 0xea, 0xfb, 0x12, 0x5e, 0x5f, 0x15, 0xb8, 0x41, 0xc4, 0x7b,
- 0x3b, 0x85, 0x05, 0xac, 0x0f, 0xfd, 0x59, 0x9e, 0x16, 0xad, 0x7e, 0x20, 0xbd, 0x4a, 0xb8, 0xaa,
- 0x27, 0x9a, 0x3b, 0x0d, 0x6f, 0x31, 0xb0, 0xe5, 0x6d, 0x48, 0x1e, 0x6b, 0xab, 0x6b, 0xe2, 0x91,
- 0x4c, 0xbc, 0xb5, 0x65, 0x41, 0x2a, 0xaf, 0x15, 0x85, 0x8b, 0xed, 0xe1, 0xc8, 0x39, 0x31, 0x90,
- 0xc5, 0xd9, 0x5a, 0x24, 0xfb, 0x93, 0x18, 0xb6, 0xc6, 0xd9, 0xd5, 0x48, 0xf6, 0xa7, 0x31, 0xec,
- 0x2a, 0x67, 0xeb, 0x91, 0xec, 0xaf, 0xc6, 0xb0, 0x75, 0xce, 0x5e, 0x8f, 0x64, 0x7f, 0x2d, 0x86,
- 0xbd, 0xce, 0xd9, 0xb5, 0x48, 0xf6, 0xd7, 0x63, 0xd8, 0x35, 0xce, 0xbe, 0x13, 0xc9, 0xfe, 0x46,
- 0x0c, 0xfb, 0x0e, 0x67, 0xdf, 0x8d, 0x64, 0x7f, 0x33, 0x86, 0x7d, 0x97, 0xb3, 0xef, 0x45, 0xb2,
- 0xbf, 0x15, 0xc3, 0xbe, 0xc7, 0xd8, 0x6b, 0xab, 0x91, 0xec, 0xcf, 0xa2, 0xd9, 0x6b, 0xab, 0x9c,
- 0x1d, 0xad, 0xb5, 0x6f, 0xc7, 0xb0, 0xb9, 0xd6, 0xd6, 0xa2, 0xb5, 0xf6, 0x9d, 0x18, 0x36, 0xd7,
- 0xda, 0x5a, 0xb4, 0xd6, 0xbe, 0x1b, 0xc3, 0xe6, 0x5a, 0x5b, 0x8b, 0xd6, 0xda, 0xf7, 0x62, 0xd8,
- 0x5c, 0x6b, 0x6b, 0xd1, 0x5a, 0xfb, 0x7e, 0x0c, 0x9b, 0x6b, 0x6d, 0x2d, 0x5a, 0x6b, 0x3f, 0x88,
- 0x61, 0x73, 0xad, 0xad, 0x45, 0x6b, 0xed, 0x8f, 0x62, 0xd8, 0x5c, 0x6b, 0x6b, 0xd1, 0x5a, 0xfb,
- 0xe3, 0x18, 0x36, 0xd7, 0xda, 0x5a, 0xb4, 0xd6, 0xfe, 0x24, 0x86, 0xcd, 0xb5, 0xa6, 0x45, 0x6b,
- 0xed, 0x4f, 0xa3, 0xd9, 0x1a, 0xd7, 0x9a, 0x16, 0xad, 0xb5, 0x3f, 0x8b, 0x61, 0x73, 0xad, 0x69,
- 0xd1, 0x5a, 0xfb, 0xf3, 0x18, 0x36, 0xd7, 0x9a, 0x16, 0xad, 0xb5, 0x1f, 0xc6, 0xb0, 0xb9, 0xd6,
- 0xb4, 0x68, 0xad, 0xfd, 0x45, 0x0c, 0x9b, 0x6b, 0x4d, 0x8b, 0xd6, 0xda, 0x5f, 0xc6, 0xb0, 0xb9,
- 0xd6, 0xb4, 0x68, 0xad, 0xfd, 0x55, 0x0c, 0x9b, 0x6b, 0x4d, 0x8b, 0xd6, 0xda, 0x5f, 0xc7, 0xb0,
- 0xb9, 0xd6, 0xb4, 0x68, 0xad, 0xfd, 0x4d, 0x0c, 0x9b, 0x6b, 0x4d, 0x8b, 0xd6, 0xda, 0xdf, 0xc6,
- 0xb0, 0xb9, 0xd6, 0xaa, 0xd1, 0x5a, 0xfb, 0xbb, 0x68, 0x76, 0x95, 0x6b, 0xad, 0x1a, 0xad, 0xb5,
- 0xbf, 0x8f, 0x61, 0x73, 0xad, 0x55, 0xa3, 0xb5, 0xf6, 0x0f, 0x31, 0x6c, 0xae, 0xb5, 0x6a, 0xb4,
- 0xd6, 0xfe, 0x31, 0x86, 0xcd, 0xb5, 0x56, 0x8d, 0xd6, 0xda, 0x8f, 0x62, 0xd8, 0x5c, 0x6b, 0xd5,
- 0x68, 0xad, 0xfd, 0x53, 0x0c, 0x9b, 0x6b, 0xad, 0x1a, 0xad, 0xb5, 0x7f, 0x8e, 0x61, 0x73, 0xad,
- 0x55, 0xa3, 0xb5, 0xf6, 0x2f, 0x31, 0x6c, 0xae, 0xb5, 0x6a, 0xb4, 0xd6, 0xfe, 0x35, 0x86, 0xcd,
- 0xb5, 0x56, 0x8d, 0xd6, 0xda, 0xbf, 0xc5, 0xb0, 0xb9, 0xd6, 0xf4, 0x68, 0xad, 0xfd, 0x7b, 0x34,
- 0x5b, 0xe7, 0x5a, 0xd3, 0xa3, 0xb5, 0xf6, 0x1f, 0x31, 0x6c, 0xae, 0x35, 0x3d, 0x5a, 0x6b, 0xff,
- 0x19, 0xc3, 0xe6, 0x5a, 0xd3, 0xa3, 0xb5, 0xf6, 0x5f, 0x31, 0x6c, 0xae, 0x35, 0x3d, 0x5a, 0x6b,
- 0xff, 0x1d, 0xc3, 0xe6, 0x5a, 0xd3, 0xa3, 0xb5, 0xf6, 0x3f, 0x31, 0x6c, 0xae, 0x35, 0x3d, 0x5a,
- 0x6b, 0x3f, 0x8e, 0x61, 0x73, 0xad, 0xe9, 0xd1, 0x5a, 0xfb, 0x49, 0x0c, 0x9b, 0x6b, 0x4d, 0x8f,
- 0xd6, 0xda, 0xff, 0xc6, 0xb0, 0xb9, 0xd6, 0xf4, 0x68, 0xad, 0xfd, 0x5f, 0x0c, 0x9b, 0x6b, 0x6d,
- 0x3d, 0x5a, 0x6b, 0xff, 0x1f, 0xcd, 0x5e, 0x5f, 0xfd, 0x69, 0x00, 0x00, 0x00, 0xff, 0xff, 0x81,
- 0x23, 0xc6, 0xe6, 0xc6, 0x38, 0x00, 0x00,
-}
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/testdata/test.proto b/vendor/github.com/matttproud/golang_protobuf_extensions/testdata/test.proto
deleted file mode 100644
index f60711369..000000000
--- a/vendor/github.com/matttproud/golang_protobuf_extensions/testdata/test.proto
+++ /dev/null
@@ -1,540 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// A feature-rich test file for the protocol compiler and libraries.
-
-syntax = "proto2";
-
-package testdata;
-
-enum FOO { FOO1 = 1; };
-
-message GoEnum {
- required FOO foo = 1;
-}
-
-message GoTestField {
- required string Label = 1;
- required string Type = 2;
-}
-
-message GoTest {
- // An enum, for completeness.
- enum KIND {
- VOID = 0;
-
- // Basic types
- BOOL = 1;
- BYTES = 2;
- FINGERPRINT = 3;
- FLOAT = 4;
- INT = 5;
- STRING = 6;
- TIME = 7;
-
- // Groupings
- TUPLE = 8;
- ARRAY = 9;
- MAP = 10;
-
- // Table types
- TABLE = 11;
-
- // Functions
- FUNCTION = 12; // last tag
- };
-
- // Some typical parameters
- required KIND Kind = 1;
- optional string Table = 2;
- optional int32 Param = 3;
-
- // Required, repeated and optional foreign fields.
- required GoTestField RequiredField = 4;
- repeated GoTestField RepeatedField = 5;
- optional GoTestField OptionalField = 6;
-
- // Required fields of all basic types
- required bool F_Bool_required = 10;
- required int32 F_Int32_required = 11;
- required int64 F_Int64_required = 12;
- required fixed32 F_Fixed32_required = 13;
- required fixed64 F_Fixed64_required = 14;
- required uint32 F_Uint32_required = 15;
- required uint64 F_Uint64_required = 16;
- required float F_Float_required = 17;
- required double F_Double_required = 18;
- required string F_String_required = 19;
- required bytes F_Bytes_required = 101;
- required sint32 F_Sint32_required = 102;
- required sint64 F_Sint64_required = 103;
-
- // Repeated fields of all basic types
- repeated bool F_Bool_repeated = 20;
- repeated int32 F_Int32_repeated = 21;
- repeated int64 F_Int64_repeated = 22;
- repeated fixed32 F_Fixed32_repeated = 23;
- repeated fixed64 F_Fixed64_repeated = 24;
- repeated uint32 F_Uint32_repeated = 25;
- repeated uint64 F_Uint64_repeated = 26;
- repeated float F_Float_repeated = 27;
- repeated double F_Double_repeated = 28;
- repeated string F_String_repeated = 29;
- repeated bytes F_Bytes_repeated = 201;
- repeated sint32 F_Sint32_repeated = 202;
- repeated sint64 F_Sint64_repeated = 203;
-
- // Optional fields of all basic types
- optional bool F_Bool_optional = 30;
- optional int32 F_Int32_optional = 31;
- optional int64 F_Int64_optional = 32;
- optional fixed32 F_Fixed32_optional = 33;
- optional fixed64 F_Fixed64_optional = 34;
- optional uint32 F_Uint32_optional = 35;
- optional uint64 F_Uint64_optional = 36;
- optional float F_Float_optional = 37;
- optional double F_Double_optional = 38;
- optional string F_String_optional = 39;
- optional bytes F_Bytes_optional = 301;
- optional sint32 F_Sint32_optional = 302;
- optional sint64 F_Sint64_optional = 303;
-
- // Default-valued fields of all basic types
- optional bool F_Bool_defaulted = 40 [default=true];
- optional int32 F_Int32_defaulted = 41 [default=32];
- optional int64 F_Int64_defaulted = 42 [default=64];
- optional fixed32 F_Fixed32_defaulted = 43 [default=320];
- optional fixed64 F_Fixed64_defaulted = 44 [default=640];
- optional uint32 F_Uint32_defaulted = 45 [default=3200];
- optional uint64 F_Uint64_defaulted = 46 [default=6400];
- optional float F_Float_defaulted = 47 [default=314159.];
- optional double F_Double_defaulted = 48 [default=271828.];
- optional string F_String_defaulted = 49 [default="hello, \"world!\"\n"];
- optional bytes F_Bytes_defaulted = 401 [default="Bignose"];
- optional sint32 F_Sint32_defaulted = 402 [default = -32];
- optional sint64 F_Sint64_defaulted = 403 [default = -64];
-
- // Packed repeated fields (no string or bytes).
- repeated bool F_Bool_repeated_packed = 50 [packed=true];
- repeated int32 F_Int32_repeated_packed = 51 [packed=true];
- repeated int64 F_Int64_repeated_packed = 52 [packed=true];
- repeated fixed32 F_Fixed32_repeated_packed = 53 [packed=true];
- repeated fixed64 F_Fixed64_repeated_packed = 54 [packed=true];
- repeated uint32 F_Uint32_repeated_packed = 55 [packed=true];
- repeated uint64 F_Uint64_repeated_packed = 56 [packed=true];
- repeated float F_Float_repeated_packed = 57 [packed=true];
- repeated double F_Double_repeated_packed = 58 [packed=true];
- repeated sint32 F_Sint32_repeated_packed = 502 [packed=true];
- repeated sint64 F_Sint64_repeated_packed = 503 [packed=true];
-
- // Required, repeated, and optional groups.
- required group RequiredGroup = 70 {
- required string RequiredField = 71;
- };
-
- repeated group RepeatedGroup = 80 {
- required string RequiredField = 81;
- };
-
- optional group OptionalGroup = 90 {
- required string RequiredField = 91;
- };
-}
-
-// For testing skipping of unrecognized fields.
-// Numbers are all big, larger than tag numbers in GoTestField,
-// the message used in the corresponding test.
-message GoSkipTest {
- required int32 skip_int32 = 11;
- required fixed32 skip_fixed32 = 12;
- required fixed64 skip_fixed64 = 13;
- required string skip_string = 14;
- required group SkipGroup = 15 {
- required int32 group_int32 = 16;
- required string group_string = 17;
- }
-}
-
-// For testing packed/non-packed decoder switching.
-// A serialized instance of one should be deserializable as the other.
-message NonPackedTest {
- repeated int32 a = 1;
-}
-
-message PackedTest {
- repeated int32 b = 1 [packed=true];
-}
-
-message MaxTag {
- // Maximum possible tag number.
- optional string last_field = 536870911;
-}
-
-message OldMessage {
- message Nested {
- optional string name = 1;
- }
- optional Nested nested = 1;
-
- optional int32 num = 2;
-}
-
-// NewMessage is wire compatible with OldMessage;
-// imagine it as a future version.
-message NewMessage {
- message Nested {
- optional string name = 1;
- optional string food_group = 2;
- }
- optional Nested nested = 1;
-
- // This is an int32 in OldMessage.
- optional int64 num = 2;
-}
-
-// Smaller tests for ASCII formatting.
-
-message InnerMessage {
- required string host = 1;
- optional int32 port = 2 [default=4000];
- optional bool connected = 3;
-}
-
-message OtherMessage {
- optional int64 key = 1;
- optional bytes value = 2;
- optional float weight = 3;
- optional InnerMessage inner = 4;
-
- extensions 100 to max;
-}
-
-message RequiredInnerMessage {
- required InnerMessage leo_finally_won_an_oscar = 1;
-}
-
-message MyMessage {
- required int32 count = 1;
- optional string name = 2;
- optional string quote = 3;
- repeated string pet = 4;
- optional InnerMessage inner = 5;
- repeated OtherMessage others = 6;
- optional RequiredInnerMessage we_must_go_deeper = 13;
- repeated InnerMessage rep_inner = 12;
-
- enum Color {
- RED = 0;
- GREEN = 1;
- BLUE = 2;
- };
- optional Color bikeshed = 7;
-
- optional group SomeGroup = 8 {
- optional int32 group_field = 9;
- }
-
- // This field becomes [][]byte in the generated code.
- repeated bytes rep_bytes = 10;
-
- optional double bigfloat = 11;
-
- extensions 100 to max;
-}
-
-message Ext {
- extend MyMessage {
- optional Ext more = 103;
- optional string text = 104;
- optional int32 number = 105;
- }
-
- optional string data = 1;
-}
-
-extend MyMessage {
- repeated string greeting = 106;
-}
-
-message ComplexExtension {
- optional int32 first = 1;
- optional int32 second = 2;
- repeated int32 third = 3;
-}
-
-extend OtherMessage {
- optional ComplexExtension complex = 200;
- repeated ComplexExtension r_complex = 201;
-}
-
-message DefaultsMessage {
- enum DefaultsEnum {
- ZERO = 0;
- ONE = 1;
- TWO = 2;
- };
- extensions 100 to max;
-}
-
-extend DefaultsMessage {
- optional double no_default_double = 101;
- optional float no_default_float = 102;
- optional int32 no_default_int32 = 103;
- optional int64 no_default_int64 = 104;
- optional uint32 no_default_uint32 = 105;
- optional uint64 no_default_uint64 = 106;
- optional sint32 no_default_sint32 = 107;
- optional sint64 no_default_sint64 = 108;
- optional fixed32 no_default_fixed32 = 109;
- optional fixed64 no_default_fixed64 = 110;
- optional sfixed32 no_default_sfixed32 = 111;
- optional sfixed64 no_default_sfixed64 = 112;
- optional bool no_default_bool = 113;
- optional string no_default_string = 114;
- optional bytes no_default_bytes = 115;
- optional DefaultsMessage.DefaultsEnum no_default_enum = 116;
-
- optional double default_double = 201 [default = 3.1415];
- optional float default_float = 202 [default = 3.14];
- optional int32 default_int32 = 203 [default = 42];
- optional int64 default_int64 = 204 [default = 43];
- optional uint32 default_uint32 = 205 [default = 44];
- optional uint64 default_uint64 = 206 [default = 45];
- optional sint32 default_sint32 = 207 [default = 46];
- optional sint64 default_sint64 = 208 [default = 47];
- optional fixed32 default_fixed32 = 209 [default = 48];
- optional fixed64 default_fixed64 = 210 [default = 49];
- optional sfixed32 default_sfixed32 = 211 [default = 50];
- optional sfixed64 default_sfixed64 = 212 [default = 51];
- optional bool default_bool = 213 [default = true];
- optional string default_string = 214 [default = "Hello, string"];
- optional bytes default_bytes = 215 [default = "Hello, bytes"];
- optional DefaultsMessage.DefaultsEnum default_enum = 216 [default = ONE];
-}
-
-message MyMessageSet {
- option message_set_wire_format = true;
- extensions 100 to max;
-}
-
-message Empty {
-}
-
-extend MyMessageSet {
- optional Empty x201 = 201;
- optional Empty x202 = 202;
- optional Empty x203 = 203;
- optional Empty x204 = 204;
- optional Empty x205 = 205;
- optional Empty x206 = 206;
- optional Empty x207 = 207;
- optional Empty x208 = 208;
- optional Empty x209 = 209;
- optional Empty x210 = 210;
- optional Empty x211 = 211;
- optional Empty x212 = 212;
- optional Empty x213 = 213;
- optional Empty x214 = 214;
- optional Empty x215 = 215;
- optional Empty x216 = 216;
- optional Empty x217 = 217;
- optional Empty x218 = 218;
- optional Empty x219 = 219;
- optional Empty x220 = 220;
- optional Empty x221 = 221;
- optional Empty x222 = 222;
- optional Empty x223 = 223;
- optional Empty x224 = 224;
- optional Empty x225 = 225;
- optional Empty x226 = 226;
- optional Empty x227 = 227;
- optional Empty x228 = 228;
- optional Empty x229 = 229;
- optional Empty x230 = 230;
- optional Empty x231 = 231;
- optional Empty x232 = 232;
- optional Empty x233 = 233;
- optional Empty x234 = 234;
- optional Empty x235 = 235;
- optional Empty x236 = 236;
- optional Empty x237 = 237;
- optional Empty x238 = 238;
- optional Empty x239 = 239;
- optional Empty x240 = 240;
- optional Empty x241 = 241;
- optional Empty x242 = 242;
- optional Empty x243 = 243;
- optional Empty x244 = 244;
- optional Empty x245 = 245;
- optional Empty x246 = 246;
- optional Empty x247 = 247;
- optional Empty x248 = 248;
- optional Empty x249 = 249;
- optional Empty x250 = 250;
-}
-
-message MessageList {
- repeated group Message = 1 {
- required string name = 2;
- required int32 count = 3;
- }
-}
-
-message Strings {
- optional string string_field = 1;
- optional bytes bytes_field = 2;
-}
-
-message Defaults {
- enum Color {
- RED = 0;
- GREEN = 1;
- BLUE = 2;
- }
-
- // Default-valued fields of all basic types.
- // Same as GoTest, but copied here to make testing easier.
- optional bool F_Bool = 1 [default=true];
- optional int32 F_Int32 = 2 [default=32];
- optional int64 F_Int64 = 3 [default=64];
- optional fixed32 F_Fixed32 = 4 [default=320];
- optional fixed64 F_Fixed64 = 5 [default=640];
- optional uint32 F_Uint32 = 6 [default=3200];
- optional uint64 F_Uint64 = 7 [default=6400];
- optional float F_Float = 8 [default=314159.];
- optional double F_Double = 9 [default=271828.];
- optional string F_String = 10 [default="hello, \"world!\"\n"];
- optional bytes F_Bytes = 11 [default="Bignose"];
- optional sint32 F_Sint32 = 12 [default=-32];
- optional sint64 F_Sint64 = 13 [default=-64];
- optional Color F_Enum = 14 [default=GREEN];
-
- // More fields with crazy defaults.
- optional float F_Pinf = 15 [default=inf];
- optional float F_Ninf = 16 [default=-inf];
- optional float F_Nan = 17 [default=nan];
-
- // Sub-message.
- optional SubDefaults sub = 18;
-
- // Redundant but explicit defaults.
- optional string str_zero = 19 [default=""];
-}
-
-message SubDefaults {
- optional int64 n = 1 [default=7];
-}
-
-message RepeatedEnum {
- enum Color {
- RED = 1;
- }
- repeated Color color = 1;
-}
-
-message MoreRepeated {
- repeated bool bools = 1;
- repeated bool bools_packed = 2 [packed=true];
- repeated int32 ints = 3;
- repeated int32 ints_packed = 4 [packed=true];
- repeated int64 int64s_packed = 7 [packed=true];
- repeated string strings = 5;
- repeated fixed32 fixeds = 6;
-}
-
-// GroupOld and GroupNew have the same wire format.
-// GroupNew has a new field inside a group.
-
-message GroupOld {
- optional group G = 101 {
- optional int32 x = 2;
- }
-}
-
-message GroupNew {
- optional group G = 101 {
- optional int32 x = 2;
- optional int32 y = 3;
- }
-}
-
-message FloatingPoint {
- required double f = 1;
-}
-
-message MessageWithMap {
- map<int32, string> name_mapping = 1;
- map<sint64, FloatingPoint> msg_mapping = 2;
- map<bool, bytes> byte_mapping = 3;
- map<string, string> str_to_str = 4;
-}
-
-message Oneof {
- oneof union {
- bool F_Bool = 1;
- int32 F_Int32 = 2;
- int64 F_Int64 = 3;
- fixed32 F_Fixed32 = 4;
- fixed64 F_Fixed64 = 5;
- uint32 F_Uint32 = 6;
- uint64 F_Uint64 = 7;
- float F_Float = 8;
- double F_Double = 9;
- string F_String = 10;
- bytes F_Bytes = 11;
- sint32 F_Sint32 = 12;
- sint64 F_Sint64 = 13;
- MyMessage.Color F_Enum = 14;
- GoTestField F_Message = 15;
- group F_Group = 16 {
- optional int32 x = 17;
- }
- int32 F_Largest_Tag = 536870911;
- }
-
- oneof tormato {
- int32 value = 100;
- }
-}
-
-message Communique {
- optional bool make_me_cry = 1;
-
- // This is a oneof, called "union".
- oneof union {
- int32 number = 5;
- string name = 6;
- bytes data = 7;
- double temp_c = 8;
- MyMessage.Color col = 9;
- Strings msg = 10;
- }
-}
diff --git a/vendor/github.com/miekg/dns/.travis.yml b/vendor/github.com/miekg/dns/.travis.yml
index 73eef5490..bb8b8d40b 100644
--- a/vendor/github.com/miekg/dns/.travis.yml
+++ b/vendor/github.com/miekg/dns/.travis.yml
@@ -1,8 +1,9 @@
language: go
sudo: false
go:
- - 1.7
- - 1.8
+ - 1.7.x
+ - 1.8.x
+ - tip
before_install:
# don't use the miekg/dns when testing forks
diff --git a/vendor/github.com/miekg/dns/README.md b/vendor/github.com/miekg/dns/README.md
index cd5c1948e..32a49cbf5 100644
--- a/vendor/github.com/miekg/dns/README.md
+++ b/vendor/github.com/miekg/dns/README.md
@@ -13,7 +13,7 @@ can build servers and resolvers with it.
We try to keep the "master" branch as sane as possible and at the bleeding edge
of standards, avoiding breaking changes wherever reasonable. We support the last
-two versions of Go, currently: 1.6 and 1.7.
+two versions of Go, currently: 1.7 and 1.8.
# Goals
@@ -58,6 +58,8 @@ A not-so-up-to-date-list-that-may-be-actually-current:
* http://quilt.io
* https://github.com/ipdcode/hades (JD.COM)
* https://github.com/StackExchange/dnscontrol/
+* https://www.dnsperf.com/
+* https://dnssectest.net/
Send pull request if you want to be listed here.
diff --git a/vendor/github.com/miekg/dns/defaults.go b/vendor/github.com/miekg/dns/defaults.go
index 3308ec838..c34890eec 100644
--- a/vendor/github.com/miekg/dns/defaults.go
+++ b/vendor/github.com/miekg/dns/defaults.go
@@ -13,9 +13,12 @@ const hexDigit = "0123456789abcdef"
// SetReply creates a reply message from a request message.
func (dns *Msg) SetReply(request *Msg) *Msg {
dns.Id = request.Id
- dns.RecursionDesired = request.RecursionDesired // Copy rd bit
dns.Response = true
- dns.Opcode = OpcodeQuery
+ dns.Opcode = request.Opcode
+ if dns.Opcode == OpcodeQuery {
+ dns.RecursionDesired = request.RecursionDesired // Copy rd bit
+ dns.CheckingDisabled = request.CheckingDisabled // Copy cd bit
+ }
dns.Rcode = RcodeSuccess
if len(request.Question) > 0 {
dns.Question = make([]Question, 1)
diff --git a/vendor/github.com/miekg/dns/parse_test.go b/vendor/github.com/miekg/dns/parse_test.go
index 2622318df..fc5bdaf5d 100644
--- a/vendor/github.com/miekg/dns/parse_test.go
+++ b/vendor/github.com/miekg/dns/parse_test.go
@@ -1527,3 +1527,14 @@ func TestParseAVC(t *testing.T) {
}
}
}
+
+func TestUnbalancedParens(t *testing.T) {
+ sig := `example.com. 3600 IN RRSIG MX 15 2 3600 (
+ 1440021600 1438207200 3613 example.com. (
+ oL9krJun7xfBOIWcGHi7mag5/hdZrKWw15jPGrHpjQeRAvTdszaPD+QLs3f
+ x8A4M3e23mRZ9VrbpMngwcrqNAg== )`
+ _, err := NewRR(sig)
+ if err == nil {
+ t.Fatalf("Failed to detect extra opening brace")
+ }
+}
diff --git a/vendor/github.com/miekg/dns/scan.go b/vendor/github.com/miekg/dns/scan.go
index de0db32f8..8d4773c3e 100644
--- a/vendor/github.com/miekg/dns/scan.go
+++ b/vendor/github.com/miekg/dns/scan.go
@@ -811,6 +811,12 @@ func zlexer(s *scan, c chan lex) {
debug.Printf("[%+v]", l.token)
c <- l
}
+ if brace != 0 {
+ l.token = "unbalanced brace"
+ l.tokenUpper = l.token
+ l.err = true
+ c <- l
+ }
}
// Extract the class number from CLASSxx
diff --git a/vendor/github.com/miekg/dns/xfr.go b/vendor/github.com/miekg/dns/xfr.go
index 7346deffb..576c5590a 100644
--- a/vendor/github.com/miekg/dns/xfr.go
+++ b/vendor/github.com/miekg/dns/xfr.go
@@ -1,6 +1,7 @@
package dns
import (
+ "fmt"
"time"
)
@@ -81,6 +82,10 @@ func (t *Transfer) inAxfr(id uint16, c chan *Envelope) {
return
}
if first {
+ if in.Rcode != RcodeSuccess {
+ c <- &Envelope{in.Answer, &Error{err: fmt.Sprintf(errXFR, in.Rcode)}}
+ return
+ }
if !isSOAFirst(in) {
c <- &Envelope{in.Answer, ErrSoa}
return
@@ -126,6 +131,10 @@ func (t *Transfer) inIxfr(id uint16, c chan *Envelope) {
return
}
if first {
+ if in.Rcode != RcodeSuccess {
+ c <- &Envelope{in.Answer, &Error{err: fmt.Sprintf(errXFR, in.Rcode)}}
+ return
+ }
// A single SOA RR signals "no changes"
if len(in.Answer) == 1 && isSOAFirst(in) {
c <- &Envelope{in.Answer, nil}
@@ -242,3 +251,5 @@ func isSOALast(in *Msg) bool {
}
return false
}
+
+const errXFR = "bad xfr rcode: %d"
diff --git a/vendor/github.com/miekg/dns/xfr_test.go b/vendor/github.com/miekg/dns/xfr_test.go
index 1337eec65..a478963a3 100644
--- a/vendor/github.com/miekg/dns/xfr_test.go
+++ b/vendor/github.com/miekg/dns/xfr_test.go
@@ -4,6 +4,7 @@ package dns
import (
"net"
+ "strings"
"testing"
"time"
)
@@ -16,8 +17,7 @@ func getIP(s string) string {
return a[0]
}
-// flaky, need to setup local server and test from
-// that.
+// flaky, need to setup local server and test from that.
func TestAXFR_Miek(t *testing.T) {
// This test runs against a server maintained by Miek
if testing.Short() {
@@ -159,3 +159,26 @@ func testAXFRSIDN(t *testing.T, host, alg string) {
}
}
}
+
+func TestAXFRFailNotAuth(t *testing.T) {
+ // This tests run against a server maintained by SIDN labs, see:
+ // https://workbench.sidnlabs.nl/
+ if testing.Short() {
+ return
+ }
+ x := new(Transfer)
+
+ m := new(Msg)
+ m.SetAxfr("sidnlabs.nl.")
+ c, err := x.In(m, "yadifa.sidnlabs.nl:53")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for e := range c {
+ if e.Error != nil {
+ if !strings.HasPrefix(e.Error.Error(), "dns: bad xfr rcode:") {
+ t.Fatal(e.Error)
+ }
+ }
+ }
+}
diff --git a/vendor/github.com/minio/go-homedir/LICENSE b/vendor/github.com/minio/go-homedir/LICENSE
deleted file mode 100644
index f9c841a51..000000000
--- a/vendor/github.com/minio/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/minio/go-homedir/README.md b/vendor/github.com/minio/go-homedir/README.md
deleted file mode 100644
index 085f57775..000000000
--- a/vendor/github.com/minio/go-homedir/README.md
+++ /dev/null
@@ -1,16 +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 is not
-available on certain architectures such as i386 or PNaCl. Additionally
-it has a cgo dependency 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/minio/go-homedir/dir_posix.go b/vendor/github.com/minio/go-homedir/dir_posix.go
deleted file mode 100644
index 4615fe063..000000000
--- a/vendor/github.com/minio/go-homedir/dir_posix.go
+++ /dev/null
@@ -1,64 +0,0 @@
-// +build !windows
-
-// Copyright 2016 (C) Mitchell Hashimoto
-// Distributed under the MIT License.
-
-package homedir
-
-import (
- "bytes"
- "errors"
- "os"
- "os/exec"
- "os/user"
- "strconv"
- "strings"
-)
-
-// dir returns the homedir of current user for all POSIX compatible
-// operating systems.
-func dir() (string, error) {
- // First prefer the HOME environmental variable
- if home := os.Getenv("HOME"); home != "" {
- return home, nil
- }
-
- // user.Current is not implemented for i386 and PNaCL like environments.
- if currUser, err := user.Current(); err == nil {
- return currUser.HomeDir, nil
- }
-
- // If that fails, try getent
- var stdout bytes.Buffer
- cmd := exec.Command("getent", "passwd", strconv.Itoa(os.Getuid()))
- cmd.Stdout = &stdout
- if err := cmd.Run(); err != nil {
- // If "getent" is missing, ignore 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
-}
diff --git a/vendor/github.com/minio/go-homedir/dir_windows.go b/vendor/github.com/minio/go-homedir/dir_windows.go
deleted file mode 100644
index 85e5218c7..000000000
--- a/vendor/github.com/minio/go-homedir/dir_windows.go
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright 2016 (C) Mitchell Hashimoto
-// Distributed under the MIT License.
-
-package homedir
-
-import (
- "errors"
- "os"
-)
-
-// dir returns the homedir of current user for MS Windows OS.
-func dir() (string, error) {
- // First prefer the HOME environmental variable
- if home := os.Getenv("HOME"); home != "" {
- return home, nil
- }
- drive := os.Getenv("HOMEDRIVE")
- path := os.Getenv("HOMEPATH")
- home := drive + path
- if drive == "" || path == "" {
- home = os.Getenv("USERPROFILE")
- }
- if home == "" {
- return "", errors.New("HOMEDRIVE, HOMEPATH, and USERPROFILE are blank")
- }
-
- return home, nil
-}
diff --git a/vendor/github.com/minio/go-homedir/homedir.go b/vendor/github.com/minio/go-homedir/homedir.go
deleted file mode 100644
index 092373801..000000000
--- a/vendor/github.com/minio/go-homedir/homedir.go
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright 2016 (C) Mitchell Hashimoto
-// Distributed under the MIT License.
-
-// Package homedir implements a portable function to determine current user's homedir.
-package homedir
-
-import (
- "errors"
- "path/filepath"
- "sync"
-)
-
-// DisableCache will disable caching of the home directory. Caching is enabled
-// by default.
-var DisableCache bool
-
-var homedirCache string
-var cacheLock sync.Mutex
-
-// 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) {
- cacheLock.Lock()
- defer cacheLock.Unlock()
-
- // Return cached homedir if available.
- if !DisableCache {
- if homedirCache != "" {
- return homedirCache, nil
- }
- }
-
- // Determine OS speific current homedir.
- result, err := dir()
- if err != nil {
- return "", err
- }
-
- // Cache for future lookups.
- 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
-}
diff --git a/vendor/github.com/minio/go-homedir/homedir_test.go b/vendor/github.com/minio/go-homedir/homedir_test.go
deleted file mode 100644
index a45121ff1..000000000
--- a/vendor/github.com/minio/go-homedir/homedir_test.go
+++ /dev/null
@@ -1,114 +0,0 @@
-package homedir
-
-import (
- "os"
- "os/user"
- "path/filepath"
- "testing"
-)
-
-func patchEnv(key, value string) func() {
- bck := os.Getenv(key)
- deferFunc := func() {
- os.Setenv(key, bck)
- }
-
- os.Setenv(key, value)
- return deferFunc
-}
-
-func BenchmarkDir(b *testing.B) {
- // We do this for any "warmups"
- for i := 0; i < 10; i++ {
- Dir()
- }
-
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- Dir()
- }
-}
-
-func TestDir(t *testing.T) {
- // NOTE: This test is not portable. If user.Current() worked
- // everywhere, we wouldn't need our package in the first place.
- u, err := user.Current()
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- dir, err := Dir()
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- if u.HomeDir != dir {
- t.Fatalf("%#v != %#v", u.HomeDir, dir)
- }
-}
-
-func TestExpand(t *testing.T) {
- u, err := user.Current()
- if err != nil {
- t.Fatalf("err: %s", err)
- }
-
- cases := []struct {
- Input string
- Output string
- Err bool
- }{
- {
- "/foo",
- "/foo",
- false,
- },
-
- {
- "~/foo",
- filepath.Join(u.HomeDir, "foo"),
- false,
- },
-
- {
- "",
- "",
- false,
- },
-
- {
- "~",
- u.HomeDir,
- false,
- },
-
- {
- "~foo/foo",
- "",
- true,
- },
- }
-
- for _, tc := range cases {
- actual, err := Expand(tc.Input)
- if (err != nil) != tc.Err {
- t.Fatalf("Input: %#v\n\nErr: %s", tc.Input, err)
- }
-
- if actual != tc.Output {
- t.Fatalf("Input: %#v\n\nOutput: %#v", tc.Input, actual)
- }
- }
-
- DisableCache = true
- defer func() { DisableCache = false }()
- defer patchEnv("HOME", "/custom/path/")()
- expected := filepath.Join("/", "custom", "path", "foo/bar")
- actual, err := Expand("~/foo/bar")
-
- if err != nil {
- t.Errorf("No error is expected, got: %v", err)
- } else if actual != expected {
- t.Errorf("Expected: %v; actual: %v", expected, actual)
- }
-}
diff --git a/vendor/github.com/minio/minio-go/api-presigned.go b/vendor/github.com/minio/minio-go/api-presigned.go
index ece005d47..f9d05ab9b 100644
--- a/vendor/github.com/minio/minio-go/api-presigned.go
+++ b/vendor/github.com/minio/minio-go/api-presigned.go
@@ -122,38 +122,21 @@ func (c Client) PresignedPostPolicy(p *PostPolicy) (u *url.URL, formData map[str
return nil, nil, err
}
- // Get credentials from the configured credentials provider.
- credValues, err := c.credsProvider.Get()
- if err != nil {
- return nil, nil, err
- }
-
- var (
- signerType = credValues.SignerType
- sessionToken = credValues.SessionToken
- accessKeyID = credValues.AccessKeyID
- secretAccessKey = credValues.SecretAccessKey
- )
-
- if signerType.IsAnonymous() {
- return nil, nil, ErrInvalidArgument("Presigned operations are not supported for anonymous credentials")
- }
-
// Keep time.
t := time.Now().UTC()
// For signature version '2' handle here.
- if signerType.IsV2() {
+ if c.signature.isV2() {
policyBase64 := p.base64()
p.formData["policy"] = policyBase64
// For Google endpoint set this value to be 'GoogleAccessId'.
if s3utils.IsGoogleEndpoint(c.endpointURL) {
- p.formData["GoogleAccessId"] = accessKeyID
+ p.formData["GoogleAccessId"] = c.accessKeyID
} else {
// For all other endpoints set this value to be 'AWSAccessKeyId'.
- p.formData["AWSAccessKeyId"] = accessKeyID
+ p.formData["AWSAccessKeyId"] = c.accessKeyID
}
// Sign the policy.
- p.formData["signature"] = s3signer.PostPresignSignatureV2(policyBase64, secretAccessKey)
+ p.formData["signature"] = s3signer.PostPresignSignatureV2(policyBase64, c.secretAccessKey)
return u, p.formData, nil
}
@@ -176,7 +159,7 @@ func (c Client) PresignedPostPolicy(p *PostPolicy) (u *url.URL, formData map[str
}
// Add a credential policy.
- credential := s3signer.GetCredential(accessKeyID, location, t)
+ credential := s3signer.GetCredential(c.accessKeyID, location, t)
if err = p.addNewPolicy(policyCondition{
matchType: "eq",
condition: "$x-amz-credential",
@@ -185,27 +168,13 @@ func (c Client) PresignedPostPolicy(p *PostPolicy) (u *url.URL, formData map[str
return nil, nil, err
}
- if sessionToken != "" {
- if err = p.addNewPolicy(policyCondition{
- matchType: "eq",
- condition: "$x-amz-security-token",
- value: sessionToken,
- }); err != nil {
- return nil, nil, err
- }
- }
-
// Get base64 encoded policy.
policyBase64 := p.base64()
-
// Fill in the form data.
p.formData["policy"] = policyBase64
p.formData["x-amz-algorithm"] = signV4Algorithm
p.formData["x-amz-credential"] = credential
p.formData["x-amz-date"] = t.Format(iso8601DateFormat)
- if sessionToken != "" {
- p.formData["x-amz-security-token"] = sessionToken
- }
- p.formData["x-amz-signature"] = s3signer.PostPresignSignatureV4(policyBase64, t, secretAccessKey, location)
+ p.formData["x-amz-signature"] = s3signer.PostPresignSignatureV4(policyBase64, t, c.secretAccessKey, location)
return u, p.formData, nil
}
diff --git a/vendor/github.com/minio/minio-go/api-put-bucket.go b/vendor/github.com/minio/minio-go/api-put-bucket.go
index 2d91e6d16..001da6de3 100644
--- a/vendor/github.com/minio/minio-go/api-put-bucket.go
+++ b/vendor/github.com/minio/minio-go/api-put-bucket.go
@@ -1,6 +1,5 @@
/*
- * Minio Go Library for Amazon S3 Compatible Cloud Storage
- * (C) 2015, 2016, 2017 Minio, Inc.
+ * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015, 2016 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,7 +28,6 @@ import (
"net/url"
"path"
- "github.com/minio/minio-go/pkg/credentials"
"github.com/minio/minio-go/pkg/policy"
"github.com/minio/minio-go/pkg/s3signer"
)
@@ -91,7 +89,7 @@ func (c Client) MakeBucket(bucketName string, location string) (err error) {
if resp.StatusCode != http.StatusOK {
err := httpRespToErrorResponse(resp, bucketName, "")
errResp := ToErrorResponse(err)
- if resp.StatusCode == http.StatusBadRequest && errResp.Region != "" {
+ if errResp.Code == "InvalidRegion" && errResp.Region != "" {
// Fetch bucket region found in headers
// of S3 error response, attempt bucket
// create again.
@@ -137,32 +135,9 @@ func (c Client) makeBucketRequest(bucketName string, location string) (*http.Req
// set UserAgent for the request.
c.setUserAgent(req)
- // Get credentials from the configured credentials provider.
- value, err := c.credsProvider.Get()
- if err != nil {
- return nil, err
- }
-
- var (
- signerType = value.SignerType
- accessKeyID = value.AccessKeyID
- secretAccessKey = value.SecretAccessKey
- sessionToken = value.SessionToken
- )
-
- // Custom signer set then override the behavior.
- if c.overrideSignerType != credentials.SignatureDefault {
- signerType = c.overrideSignerType
- }
-
- // If signerType returned by credentials helper is anonymous,
- // then do not sign regardless of signerType override.
- if value.SignerType == credentials.SignatureAnonymous {
- signerType = credentials.SignatureAnonymous
- }
-
- // set sha256 sum for signature calculation only with signature version '4'.
- if signerType.IsV4() {
+ // set sha256 sum for signature calculation only with
+ // signature version '4'.
+ if c.signature.isV4() {
req.Header.Set("X-Amz-Content-Sha256", hex.EncodeToString(sum256([]byte{})))
}
@@ -180,19 +155,19 @@ func (c Client) makeBucketRequest(bucketName string, location string) (*http.Req
req.ContentLength = int64(len(createBucketConfigBytes))
// Set content-md5.
req.Header.Set("Content-Md5", base64.StdEncoding.EncodeToString(sumMD5(createBucketConfigBytes)))
- if signerType.IsV4() {
+ if c.signature.isV4() {
// Set sha256.
req.Header.Set("X-Amz-Content-Sha256", hex.EncodeToString(sum256(createBucketConfigBytes)))
}
}
// Sign the request.
- if signerType.IsV4() {
+ if c.signature.isV4() {
// Signature calculated for MakeBucket request should be for 'us-east-1',
// regardless of the bucket's location constraint.
- req = s3signer.SignV4(*req, accessKeyID, secretAccessKey, sessionToken, "us-east-1")
- } else if signerType.IsV2() {
- req = s3signer.SignV2(*req, accessKeyID, secretAccessKey)
+ req = s3signer.SignV4(*req, c.accessKeyID, c.secretAccessKey, "us-east-1")
+ } else if c.signature.isV2() {
+ req = s3signer.SignV2(*req, c.accessKeyID, c.secretAccessKey)
}
// Return signed request.
diff --git a/vendor/github.com/minio/minio-go/api-put-bucket_test.go b/vendor/github.com/minio/minio-go/api-put-bucket_test.go
index 4f7ddb30e..ec33c8492 100644
--- a/vendor/github.com/minio/minio-go/api-put-bucket_test.go
+++ b/vendor/github.com/minio/minio-go/api-put-bucket_test.go
@@ -1,6 +1,5 @@
/*
- * Minio Go Library for Amazon S3 Compatible Cloud Storage
- * (C) 2015, 2016, 2017 Minio, Inc.
+ * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015, 2016 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,7 +27,6 @@ import (
"path"
"testing"
- "github.com/minio/minio-go/pkg/credentials"
"github.com/minio/minio-go/pkg/s3signer"
)
@@ -50,32 +48,8 @@ func TestMakeBucketRequest(t *testing.T) {
// set UserAgent for the request.
c.setUserAgent(req)
- // Get credentials from the configured credentials provider.
- value, err := c.credsProvider.Get()
- if err != nil {
- return nil, err
- }
-
- var (
- signerType = value.SignerType
- accessKeyID = value.AccessKeyID
- secretAccessKey = value.SecretAccessKey
- sessionToken = value.SessionToken
- )
-
- // Custom signer set then override the behavior.
- if c.overrideSignerType != credentials.SignatureDefault {
- signerType = c.overrideSignerType
- }
-
- // If signerType returned by credentials helper is anonymous,
- // then do not sign regardless of signerType override.
- if value.SignerType == credentials.SignatureAnonymous {
- signerType = credentials.SignatureAnonymous
- }
-
// set sha256 sum for signature calculation only with signature version '4'.
- if signerType.IsV4() {
+ if c.signature.isV4() {
req.Header.Set("X-Amz-Content-Sha256", hex.EncodeToString(sum256([]byte{})))
}
@@ -93,19 +67,19 @@ func TestMakeBucketRequest(t *testing.T) {
req.ContentLength = int64(len(createBucketConfigBytes))
// Set content-md5.
req.Header.Set("Content-Md5", base64.StdEncoding.EncodeToString(sumMD5(createBucketConfigBytes)))
- if signerType.IsV4() {
+ if c.signature.isV4() {
// Set sha256.
req.Header.Set("X-Amz-Content-Sha256", hex.EncodeToString(sum256(createBucketConfigBytes)))
}
}
// Sign the request.
- if signerType.IsV4() {
+ if c.signature.isV4() {
// Signature calculated for MakeBucket request should be for 'us-east-1',
// regardless of the bucket's location constraint.
- req = s3signer.SignV4(*req, accessKeyID, secretAccessKey, sessionToken, "us-east-1")
- } else if signerType.IsV2() {
- req = s3signer.SignV2(*req, accessKeyID, secretAccessKey)
+ req = s3signer.SignV4(*req, c.accessKeyID, c.secretAccessKey, "us-east-1")
+ } else if c.signature.isV2() {
+ req = s3signer.SignV2(*req, c.accessKeyID, c.secretAccessKey)
}
// Return signed request.
@@ -272,7 +246,7 @@ func TestMakeBucketRequest(t *testing.T) {
}
if expectedReq.Header.Get("X-Amz-Content-Sha256") != actualReq.Header.Get("X-Amz-Content-Sha256") {
- t.Errorf("Test %d: 'X-Amz-Content-Sha256' header of the expected request %s doesn't match with that of the actual request %s", i+1, expectedReq.Header.Get("X-Amz-Content-Sha256"), actualReq.Header.Get("X-Amz-Content-Sha256"))
+ t.Errorf("Test %d: 'X-Amz-Content-Sha256' header of the expected request doesn't match with that of the actual request", i+1)
}
if expectedReq.Header.Get("User-Agent") != actualReq.Header.Get("User-Agent") {
t.Errorf("Test %d: Expected 'User-Agent' header to be \"%s\",but found \"%s\" instead", i+1, expectedReq.Header.Get("User-Agent"), actualReq.Header.Get("User-Agent"))
diff --git a/vendor/github.com/minio/minio-go/api-put-object-file.go b/vendor/github.com/minio/minio-go/api-put-object-file.go
index fc475c9a3..09fec769d 100644
--- a/vendor/github.com/minio/minio-go/api-put-object-file.go
+++ b/vendor/github.com/minio/minio-go/api-put-object-file.go
@@ -182,7 +182,7 @@ func (c Client) putObjectMultipartFromFile(bucketName, objectName string, fileRe
hashAlgos := make(map[string]hash.Hash)
hashSums := make(map[string][]byte)
hashAlgos["md5"] = md5.New()
- if c.overrideSignerType.IsV4() && !c.secure {
+ if c.signature.isV4() && !c.secure {
hashAlgos["sha256"] = sha256.New()
}
diff --git a/vendor/github.com/minio/minio-go/api-put-object-multipart.go b/vendor/github.com/minio/minio-go/api-put-object-multipart.go
index 5134a7fd2..3a299f65b 100644
--- a/vendor/github.com/minio/minio-go/api-put-object-multipart.go
+++ b/vendor/github.com/minio/minio-go/api-put-object-multipart.go
@@ -213,7 +213,7 @@ func (c Client) putObjectMultipartStream(bucketName, objectName string, reader i
hashSums := make(map[string][]byte)
hashAlgos := make(map[string]hash.Hash)
hashAlgos["md5"] = md5.New()
- if c.overrideSignerType.IsV4() && !c.secure {
+ if c.signature.isV4() && !c.secure {
hashAlgos["sha256"] = sha256.New()
}
diff --git a/vendor/github.com/minio/minio-go/api-put-object-progress.go b/vendor/github.com/minio/minio-go/api-put-object-progress.go
index e5b24ad2a..f3844127e 100644
--- a/vendor/github.com/minio/minio-go/api-put-object-progress.go
+++ b/vendor/github.com/minio/minio-go/api-put-object-progress.go
@@ -20,7 +20,6 @@ import (
"io"
"strings"
- "github.com/minio/minio-go/pkg/credentials"
"github.com/minio/minio-go/pkg/encrypt"
"github.com/minio/minio-go/pkg/s3utils"
)
@@ -104,7 +103,6 @@ func (c Client) PutObjectWithMetadata(bucketName, objectName string, reader io.R
if size < minPartSize && size >= 0 {
return c.putObjectSingle(bucketName, objectName, reader, size, metaData, progress)
}
-
// For all sizes greater than 5MiB do multipart.
n, err = c.putObjectMultipart(bucketName, objectName, reader, size, metaData, progress)
if err != nil {
@@ -145,8 +143,8 @@ func (c Client) PutObjectStreamingWithProgress(bucketName, objectName string, re
BucketName: bucketName,
}
}
-
- if c.overrideSignerType.IsV2() {
+ // This method should return error with signature v2 minioClient.
+ if c.signature.isV2() {
return 0, ErrorResponse{
Code: "NotImplemented",
Message: "AWS streaming signature v4 is not supported with minio client initialized for AWS signature v2",
@@ -175,8 +173,8 @@ func (c Client) PutObjectStreamingWithProgress(bucketName, objectName string, re
return c.putObjectMultipartStream(bucketName, objectName, reader, size, metadata, progress)
}
- // Set streaming signature.
- c.overrideSignerType = credentials.SignatureV4Streaming
+ // Set signature type to streaming signature v4.
+ c.signature = SignatureV4Streaming
if size < minPartSize && size >= 0 {
return c.putObjectNoChecksum(bucketName, objectName, reader, size, metadata, progress)
diff --git a/vendor/github.com/minio/minio-go/api-put-object-readat.go b/vendor/github.com/minio/minio-go/api-put-object-readat.go
index 0083d41fa..ebf422638 100644
--- a/vendor/github.com/minio/minio-go/api-put-object-readat.go
+++ b/vendor/github.com/minio/minio-go/api-put-object-readat.go
@@ -146,7 +146,7 @@ func (c Client) putObjectMultipartFromReadAt(bucketName, objectName string, read
hashSums := make(map[string][]byte)
hashAlgos := make(map[string]hash.Hash)
hashAlgos["md5"] = md5.New()
- if c.overrideSignerType.IsV4() && !c.secure {
+ if c.signature.isV4() && !c.secure {
hashAlgos["sha256"] = sha256.New()
}
diff --git a/vendor/github.com/minio/minio-go/api-put-object.go b/vendor/github.com/minio/minio-go/api-put-object.go
index 0b6848fff..e218075df 100644
--- a/vendor/github.com/minio/minio-go/api-put-object.go
+++ b/vendor/github.com/minio/minio-go/api-put-object.go
@@ -109,24 +109,14 @@ func getReaderSize(reader io.Reader) (size int64, err error) {
case "|0", "|1":
return
}
- var pos int64
- pos, err = v.Seek(0, 1) // SeekCurrent.
- if err != nil {
- return -1, err
- }
- size = st.Size() - pos
+ size = st.Size()
case *Object:
var st ObjectInfo
st, err = v.Stat()
if err != nil {
return
}
- var pos int64
- pos, err = v.Seek(0, 1) // SeekCurrent.
- if err != nil {
- return -1, err
- }
- size = st.Size - pos
+ size = st.Size
}
}
// Returns the size here.
@@ -210,7 +200,7 @@ func (c Client) putObjectSingle(bucketName, objectName string, reader io.Reader,
hashAlgos := make(map[string]hash.Hash)
hashSums := make(map[string][]byte)
hashAlgos["md5"] = md5.New()
- if c.overrideSignerType.IsV4() && !c.secure {
+ if c.signature.isV4() && !c.secure {
hashAlgos["sha256"] = sha256.New()
}
diff --git a/vendor/github.com/minio/minio-go/api.go b/vendor/github.com/minio/minio-go/api.go
index c04034a86..a563a18d4 100644
--- a/vendor/github.com/minio/minio-go/api.go
+++ b/vendor/github.com/minio/minio-go/api.go
@@ -1,6 +1,5 @@
/*
- * Minio Go Library for Amazon S3 Compatible Cloud Storage
- * (C) 2015, 2016, 2017 Minio, Inc.
+ * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015, 2016 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -36,7 +35,6 @@ import (
"sync"
"time"
- "github.com/minio/minio-go/pkg/credentials"
"github.com/minio/minio-go/pkg/s3signer"
"github.com/minio/minio-go/pkg/s3utils"
)
@@ -48,11 +46,14 @@ type Client struct {
// Parsed endpoint url provided by the user.
endpointURL url.URL
- // Holds various credential providers.
- credsProvider *credentials.Credentials
-
- // Custom signerType value overrides all credentials.
- overrideSignerType credentials.SignatureType
+ // AccessKeyID required for authorized requests.
+ accessKeyID string
+ // SecretAccessKey required for authorized requests.
+ secretAccessKey string
+ // Choose a signature type if necessary.
+ signature SignatureType
+ // Set to 'true' if Client has no access and secret keys.
+ anonymous bool
// User supplied.
appInfo struct {
@@ -99,58 +100,58 @@ const (
// NewV2 - instantiate minio client with Amazon S3 signature version
// '2' compatibility.
func NewV2(endpoint string, accessKeyID, secretAccessKey string, secure bool) (*Client, error) {
- creds := credentials.NewStaticV2(accessKeyID, secretAccessKey, "")
- clnt, err := privateNew(endpoint, creds, secure, "")
+ clnt, err := privateNew(endpoint, accessKeyID, secretAccessKey, secure)
if err != nil {
return nil, err
}
- clnt.overrideSignerType = credentials.SignatureV2
+
+ // Set to use signature version '2'.
+ clnt.signature = SignatureV2
return clnt, nil
}
// NewV4 - instantiate minio client with Amazon S3 signature version
// '4' compatibility.
func NewV4(endpoint string, accessKeyID, secretAccessKey string, secure bool) (*Client, error) {
- creds := credentials.NewStaticV4(accessKeyID, secretAccessKey, "")
- clnt, err := privateNew(endpoint, creds, secure, "")
+ clnt, err := privateNew(endpoint, accessKeyID, secretAccessKey, secure)
if err != nil {
return nil, err
}
- clnt.overrideSignerType = credentials.SignatureV4
+
+ // Set to use signature version '4'.
+ clnt.signature = SignatureV4
return clnt, nil
}
-// New - instantiate minio client, adds automatic verification of signature.
+// New - instantiate minio client Client, adds automatic verification of signature.
func New(endpoint, accessKeyID, secretAccessKey string, secure bool) (*Client, error) {
- creds := credentials.NewStaticV4(accessKeyID, secretAccessKey, "")
- clnt, err := privateNew(endpoint, creds, secure, "")
+ return NewWithRegion(endpoint, accessKeyID, secretAccessKey, secure, "")
+}
+
+// NewWithRegion - instantiate minio client, with region configured. Unlike New(),
+// NewWithRegion avoids bucket-location lookup operations and it is slightly faster.
+// Use this function when if your application deals with single region.
+func NewWithRegion(endpoint, accessKeyID, secretAccessKey string, secure bool, region string) (*Client, error) {
+ clnt, err := privateNew(endpoint, accessKeyID, secretAccessKey, secure)
if err != nil {
return nil, err
}
+
// Google cloud storage should be set to signature V2, force it if not.
if s3utils.IsGoogleEndpoint(clnt.endpointURL) {
- clnt.overrideSignerType = credentials.SignatureV2
+ clnt.signature = SignatureV2
}
- // If Amazon S3 set to signature v4.
+
+ // If Amazon S3 set to signature v2.n
if s3utils.IsAmazonEndpoint(clnt.endpointURL) {
- clnt.overrideSignerType = credentials.SignatureV4
+ clnt.signature = SignatureV4
}
- return clnt, nil
-}
-// NewWithCredentials - instantiate minio client with credentials provider
-// for retrieving credentials from various credentials provider such as
-// IAM, File, Env etc.
-func NewWithCredentials(endpoint string, creds *credentials.Credentials, secure bool, region string) (*Client, error) {
- return privateNew(endpoint, creds, secure, region)
-}
+ // Sets custom region, if region is empty bucket location cache is used automatically.
+ clnt.region = region
-// NewWithRegion - instantiate minio client, with region configured. Unlike New(),
-// NewWithRegion avoids bucket-location lookup operations and it is slightly faster.
-// Use this function when if your application deals with single region.
-func NewWithRegion(endpoint, accessKeyID, secretAccessKey string, secure bool, region string) (*Client, error) {
- creds := credentials.NewStaticV4(accessKeyID, secretAccessKey, "")
- return privateNew(endpoint, creds, secure, region)
+ // Success..
+ return clnt, nil
}
// lockedRandSource provides protected rand source, implements rand.Source interface.
@@ -187,7 +188,7 @@ func redirectHeaders(req *http.Request, via []*http.Request) error {
return nil
}
-func privateNew(endpoint string, creds *credentials.Credentials, secure bool, region string) (*Client, error) {
+func privateNew(endpoint, accessKeyID, secretAccessKey string, secure bool) (*Client, error) {
// construct endpoint.
endpointURL, err := getEndpointURL(endpoint, secure)
if err != nil {
@@ -196,9 +197,8 @@ func privateNew(endpoint string, creds *credentials.Credentials, secure bool, re
// instantiate new Client.
clnt := new(Client)
-
- // Save the credentials.
- clnt.credsProvider = creds
+ clnt.accessKeyID = accessKeyID
+ clnt.secretAccessKey = secretAccessKey
// Remember whether we are using https or not
clnt.secure = secure
@@ -212,10 +212,7 @@ func privateNew(endpoint string, creds *credentials.Credentials, secure bool, re
CheckRedirect: redirectHeaders,
}
- // Sets custom region, if region is empty bucket location cache is used automatically.
- clnt.region = region
-
- // Instantiate bucket location cache.
+ // Instantiae bucket location cache.
clnt.bucketLocCache = newBucketLocationCache()
// Introduce a new locked random seed.
@@ -317,12 +314,11 @@ var regSign = regexp.MustCompile("Signature=([[0-9a-f]+)")
// Filter out signature value from Authorization header.
func (c Client) filterSignature(req *http.Request) {
- origAuth := req.Header.Get("Authorization")
- if origAuth != "" {
+ if _, ok := req.Header["Authorization"]; !ok {
return
}
-
- if !strings.HasPrefix(origAuth, signV4Algorithm) {
+ // Handle if Signature V2.
+ if c.signature.isV2() {
// Set a temporary redacted auth
req.Header.Set("Authorization", "AWS **REDACTED**:**REDACTED**")
return
@@ -330,6 +326,8 @@ func (c Client) filterSignature(req *http.Request) {
/// Signature V4 authorization header.
+ // Save the original auth.
+ origAuth := req.Header.Get("Authorization")
// Strip out accessKeyID from:
// Credential=<access-key-id>/<date>/<aws-region>/<aws-service>/aws4_request
newAuth := regCred.ReplaceAllString(origAuth, "Credential=**REDACTED**/")
@@ -339,7 +337,6 @@ func (c Client) filterSignature(req *http.Request) {
// Set a temporary redacted auth
req.Header.Set("Authorization", newAuth)
-
return
}
@@ -556,7 +553,7 @@ func (c Client) executeMethod(method string, metadata requestMetadata) (res *htt
// Bucket region if set in error response and the error
// code dictates invalid region, we can retry the request
// with the new region.
- if res.StatusCode == http.StatusBadRequest && errResponse.Region != "" {
+ if errResponse.Code == "InvalidRegion" && errResponse.Region != "" {
c.bucketLocCache.Set(metadata.bucketName, errResponse.Region)
continue // Retry.
}
@@ -617,41 +614,20 @@ func (c Client) newRequest(method string, metadata requestMetadata) (req *http.R
return nil, err
}
- // Get credentials from the configured credentials provider.
- value, err := c.credsProvider.Get()
- if err != nil {
- return nil, err
- }
-
- var (
- signerType = value.SignerType
- accessKeyID = value.AccessKeyID
- secretAccessKey = value.SecretAccessKey
- sessionToken = value.SessionToken
- )
-
- // Custom signer set then override the behavior.
- if c.overrideSignerType != credentials.SignatureDefault {
- signerType = c.overrideSignerType
- }
-
- // If signerType returned by credentials helper is anonymous,
- // then do not sign regardless of signerType override.
- if value.SignerType == credentials.SignatureAnonymous {
- signerType = credentials.SignatureAnonymous
- }
+ // Anonymous request.
+ anonymous := c.accessKeyID == "" || c.secretAccessKey == ""
// Generate presign url if needed, return right here.
if metadata.expires != 0 && metadata.presignURL {
- if signerType.IsAnonymous() {
- return nil, ErrInvalidArgument("Presigned URLs cannot be generated with anonymous credentials.")
+ if anonymous {
+ return nil, ErrInvalidArgument("Requests cannot be presigned with anonymous credentials.")
}
- if signerType.IsV2() {
+ if c.signature.isV2() {
// Presign URL with signature v2.
- req = s3signer.PreSignV2(*req, accessKeyID, secretAccessKey, metadata.expires)
- } else if signerType.IsV4() {
+ req = s3signer.PreSignV2(*req, c.accessKeyID, c.secretAccessKey, metadata.expires)
+ } else if c.signature.isV4() {
// Presign URL with signature v4.
- req = s3signer.PreSignV4(*req, accessKeyID, secretAccessKey, sessionToken, location, metadata.expires)
+ req = s3signer.PreSignV4(*req, c.accessKeyID, c.secretAccessKey, location, metadata.expires)
}
return req, nil
}
@@ -674,18 +650,17 @@ func (c Client) newRequest(method string, metadata requestMetadata) (req *http.R
req.Header.Set("Content-Md5", base64.StdEncoding.EncodeToString(metadata.contentMD5Bytes))
}
- // For anonymous requests just return.
- if signerType.IsAnonymous() {
+ if anonymous {
return req, nil
- }
+ } // Sign the request for all authenticated requests.
switch {
- case signerType.IsV2():
+ case c.signature.isV2():
// Add signature version '2' authorization header.
- req = s3signer.SignV2(*req, accessKeyID, secretAccessKey)
- case signerType.IsStreamingV4() && method == "PUT":
- req = s3signer.StreamingSignV4(req, accessKeyID,
- secretAccessKey, sessionToken, location, metadata.contentLength, time.Now().UTC())
+ req = s3signer.SignV2(*req, c.accessKeyID, c.secretAccessKey)
+ case c.signature.isStreamingV4() && method == "PUT":
+ req = s3signer.StreamingSignV4(req, c.accessKeyID,
+ c.secretAccessKey, location, metadata.contentLength, time.Now().UTC())
default:
// Set sha256 sum for signature calculation only with signature version '4'.
shaHeader := unsignedPayload
@@ -695,7 +670,7 @@ func (c Client) newRequest(method string, metadata requestMetadata) (req *http.R
req.Header.Set("X-Amz-Content-Sha256", shaHeader)
// Add signature version '4' authorization header.
- req = s3signer.SignV4(*req, accessKeyID, secretAccessKey, sessionToken, location)
+ req = s3signer.SignV4(*req, c.accessKeyID, c.secretAccessKey, location)
}
// Return request.
@@ -757,16 +732,13 @@ func (c Client) makeTargetURL(bucketName, objectName, bucketLocation string, que
}
}
}
-
// If there are any query values, add them to the end.
if len(queryValues) > 0 {
urlStr = urlStr + "?" + s3utils.QueryEncode(queryValues)
}
-
u, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
-
return u, nil
}
diff --git a/vendor/github.com/minio/minio-go/api_functional_v4_test.go b/vendor/github.com/minio/minio-go/api_functional_v4_test.go
index a553ea2cd..b5e6d128a 100644
--- a/vendor/github.com/minio/minio-go/api_functional_v4_test.go
+++ b/vendor/github.com/minio/minio-go/api_functional_v4_test.go
@@ -18,6 +18,7 @@ package minio
import (
"bytes"
+ crand "crypto/rand"
"encoding/hex"
"errors"
"fmt"
@@ -200,10 +201,14 @@ func TestPutObjectReadAt(t *testing.T) {
}
// Generate data using 4 parts so that all 3 'workers' are utilized and a part is leftover.
- // Use different data for each part for multipart tests to ensure part order at the end.
- var buf []byte
- for i := 0; i < 4; i++ {
- buf = append(buf, bytes.Repeat([]byte(string('a'+i)), minPartSize)...)
+ buf := make([]byte, minPartSize*4)
+ // Use crand.Reader for multipart tests to ensure part order at the end.
+ size, err := io.ReadFull(crand.Reader, buf)
+ if err != nil {
+ t.Fatal("Error:", err)
+ }
+ if size != minPartSize*4 {
+ t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", minPartSize*4, size)
}
// Save the data
@@ -290,10 +295,14 @@ func TestPutObjectWithMetadata(t *testing.T) {
}
// Generate data using 2 parts
- // Use different data in each part for multipart tests to ensure part order at the end.
- var buf []byte
- for i := 0; i < 2; i++ {
- buf = append(buf, bytes.Repeat([]byte(string('a'+i)), minPartSize)...)
+ buf := make([]byte, minPartSize*2)
+ // Use crand.Reader for multipart tests to ensure part order at the end.
+ size, err := io.ReadFull(crand.Reader, buf)
+ if err != nil {
+ t.Fatal("Error:", err)
+ }
+ if size != minPartSize*2 {
+ t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", minPartSize*2, size)
}
// Save the data
@@ -847,6 +856,7 @@ func TestResumablePutObject(t *testing.T) {
t.Fatal("Error:", err)
}
r := bytes.NewReader(bytes.Repeat([]byte("b"), minPartSize*2))
+ // Copy 11MiB worth of random data.
n, err := io.CopyN(file, r, minPartSize*2)
if err != nil {
t.Fatal("Error:", err)
@@ -962,13 +972,16 @@ func TestResumableFPutObject(t *testing.T) {
}
// Upload 4 parts to use all 3 multipart 'workers' and have an extra part.
- // Use different data in each part for multipart tests to ensure parts are uploaded in correct order.
- var buffer []byte
- for i := 0; i < 4; i++ {
- buffer = append(buffer, bytes.Repeat([]byte(string('a'+i)), minPartSize)...)
+ buffer := make([]byte, minPartSize*4)
+ // Use crand.Reader for multipart tests to ensure parts are uploaded in correct order.
+ size, err := io.ReadFull(crand.Reader, buffer)
+ if err != nil {
+ t.Fatal("Error:", err)
}
-
- size, err := file.Write(buffer)
+ if size != minPartSize*4 {
+ t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", minPartSize*4, size)
+ }
+ size, err = file.Write(buffer)
if err != nil {
t.Fatal("Error:", err)
}
@@ -1050,12 +1063,16 @@ func TestFPutObjectMultipart(t *testing.T) {
}
// Upload 4 parts to utilize all 3 'workers' in multipart and still have a part to upload.
- var buffer []byte
- for i := 0; i < 4; i++ {
- buffer = append(buffer, bytes.Repeat([]byte(string('a'+i)), minPartSize)...)
- }
+ buffer := make([]byte, minPartSize*4)
- size, err := file.Write(buffer)
+ size, err := io.ReadFull(crand.Reader, buffer)
+ if err != nil {
+ t.Fatal("Error:", err)
+ }
+ if size != minPartSize*4 {
+ t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", minPartSize*4, size)
+ }
+ size, err = file.Write(buffer)
if err != nil {
t.Fatal("Error:", err)
}
@@ -1151,14 +1168,18 @@ func TestFPutObject(t *testing.T) {
}
// Upload 4 parts worth of data to use all 3 of multiparts 'workers' and have an extra part.
- // Use different data in part for multipart tests to check parts are uploaded in correct order.
- var buffer []byte
- for i := 0; i < 4; i++ {
- buffer = append(buffer, bytes.Repeat([]byte(string('a'+i)), minPartSize)...)
+ buffer := make([]byte, minPartSize*4)
+ // Use random data for multipart tests to check parts are uploaded in correct order.
+ size, err := io.ReadFull(crand.Reader, buffer)
+ if err != nil {
+ t.Fatal("Error:", err)
+ }
+ if size != minPartSize*4 {
+ t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", minPartSize*4, size)
}
// Write the data to the file.
- size, err := file.Write(buffer)
+ size, err = file.Write(buffer)
if err != nil {
t.Fatal("Error:", err)
}
@@ -2477,97 +2498,3 @@ func TestGetObjectObjectModified(t *testing.T) {
t.Errorf("Expected ReadAt to fail with error %s but received %s", s3ErrorResponseMap["PreconditionFailed"], err.Error())
}
}
-
-// Test validates putObject to upload a file seeked at a given offset.
-func TestPutObjectUploadSeekedObject(t *testing.T) {
- if testing.Short() {
- t.Skip("skipping functional tests for the short runs")
- }
-
- // Instantiate new minio client object.
- c, err := NewV4(
- os.Getenv("S3_ADDRESS"),
- os.Getenv("ACCESS_KEY"),
- os.Getenv("SECRET_KEY"),
- mustParseBool(os.Getenv("S3_SECURE")),
- )
- if err != nil {
- t.Fatal("Error:", err)
- }
-
- // Enable tracing, write to stderr.
- // c.TraceOn(os.Stderr)
-
- // Set user agent.
- c.SetAppInfo("Minio-go-FunctionalTest", "0.1.0")
-
- // Make a new bucket.
- bucketName := randString(60, rand.NewSource(time.Now().UnixNano()), "minio-go-test")
- err = c.MakeBucket(bucketName, "us-east-1")
- if err != nil {
- t.Fatal("Error:", err, bucketName)
- }
- defer c.RemoveBucket(bucketName)
-
- tempfile, err := ioutil.TempFile("", "minio-go-upload-test-")
- if err != nil {
- t.Fatal("Error:", err)
- }
-
- var length = 120000
- data := bytes.Repeat([]byte("1"), length)
-
- if _, err = tempfile.Write(data); err != nil {
- t.Fatal("Error:", err)
- }
-
- objectName := fmt.Sprintf("test-file-%v", rand.Uint32())
-
- offset := length / 2
- if _, err := tempfile.Seek(int64(offset), 0); err != nil {
- t.Fatal("Error:", err)
- }
-
- n, err := c.PutObject(bucketName, objectName, tempfile, "binary/octet-stream")
- if err != nil {
- t.Fatal("Error:", err)
- }
- if n != int64(length-offset) {
- t.Fatalf("Invalid length returned, want %v, got %v", int64(length-offset), n)
- }
- tempfile.Close()
- if err = os.Remove(tempfile.Name()); err != nil {
- t.Fatal("Error:", err)
- }
-
- length = int(n)
-
- obj, err := c.GetObject(bucketName, objectName)
- if err != nil {
- t.Fatal("Error:", err)
- }
-
- n, err = obj.Seek(int64(offset), 0)
- if err != nil {
- t.Fatal("Error:", err)
- }
- if n != int64(offset) {
- t.Fatalf("Invalid offset returned, want %v, got %v", int64(offset), n)
- }
-
- n, err = c.PutObject(bucketName, objectName+"getobject", obj, "binary/octet-stream")
- if err != nil {
- t.Fatal("Error:", err)
- }
- if n != int64(length-offset) {
- t.Fatalf("Invalid length returned, want %v, got %v", int64(length-offset), n)
- }
-
- if err = c.RemoveObject(bucketName, objectName); err != nil {
- t.Fatal("Error:", err)
- }
-
- if err = c.RemoveObject(bucketName, objectName+"getobject"); err != nil {
- t.Fatal("Error:", err)
- }
-}
diff --git a/vendor/github.com/minio/minio-go/api_unit_test.go b/vendor/github.com/minio/minio-go/api_unit_test.go
index 7bb5802bf..c1db0df5d 100644
--- a/vendor/github.com/minio/minio-go/api_unit_test.go
+++ b/vendor/github.com/minio/minio-go/api_unit_test.go
@@ -1,6 +1,5 @@
/*
- * Minio Go Library for Amazon S3 Compatible Cloud Storage
- * (C) 2015, 2016, 2017 Minio, Inc.
+ * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,7 +25,6 @@ import (
"strings"
"testing"
- "github.com/minio/minio-go/pkg/credentials"
"github.com/minio/minio-go/pkg/policy"
)
@@ -230,18 +228,18 @@ func TestErrorResponse(t *testing.T) {
// Tests signature type.
func TestSignatureType(t *testing.T) {
clnt := Client{}
- if !clnt.overrideSignerType.IsV4() {
+ if !clnt.signature.isV4() {
t.Fatal("Error")
}
- clnt.overrideSignerType = credentials.SignatureV2
- if !clnt.overrideSignerType.IsV2() {
+ clnt.signature = SignatureV2
+ if !clnt.signature.isV2() {
t.Fatal("Error")
}
- if clnt.overrideSignerType.IsV4() {
+ if clnt.signature.isV4() {
t.Fatal("Error")
}
- clnt.overrideSignerType = credentials.SignatureV4
- if !clnt.overrideSignerType.IsV4() {
+ clnt.signature = SignatureV4
+ if !clnt.signature.isV4() {
t.Fatal("Error")
}
}
diff --git a/vendor/github.com/minio/minio-go/appveyor.yml b/vendor/github.com/minio/minio-go/appveyor.yml
index 4f5c1b390..be746a7bf 100644
--- a/vendor/github.com/minio/minio-go/appveyor.yml
+++ b/vendor/github.com/minio/minio-go/appveyor.yml
@@ -17,8 +17,6 @@ install:
- go version
- go env
- go get -u github.com/golang/lint/golint
- - go get -u github.com/go-ini/ini
- - go get -u github.com/minio/go-homedir
- go get -u github.com/remyoudompheng/go-misc/deadcode
- go get -u github.com/gordonklaus/ineffassign
diff --git a/vendor/github.com/minio/minio-go/bucket-cache.go b/vendor/github.com/minio/minio-go/bucket-cache.go
index 7e7cc7717..28799c69d 100644
--- a/vendor/github.com/minio/minio-go/bucket-cache.go
+++ b/vendor/github.com/minio/minio-go/bucket-cache.go
@@ -1,6 +1,5 @@
/*
- * Minio Go Library for Amazon S3 Compatible Cloud Storage
- * (C) 2015, 2016, 2017 Minio, Inc.
+ * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,7 +23,6 @@ import (
"path"
"sync"
- "github.com/minio/minio-go/pkg/credentials"
"github.com/minio/minio-go/pkg/s3signer"
"github.com/minio/minio-go/pkg/s3utils"
)
@@ -183,33 +181,8 @@ func (c Client) getBucketLocationRequest(bucketName string) (*http.Request, erro
// Set UserAgent for the request.
c.setUserAgent(req)
- // Get credentials from the configured credentials provider.
- value, err := c.credsProvider.Get()
- if err != nil {
- return nil, err
- }
-
- var (
- signerType = value.SignerType
- accessKeyID = value.AccessKeyID
- secretAccessKey = value.SecretAccessKey
- sessionToken = value.SessionToken
- )
-
- // Custom signer set then override the behavior.
- if c.overrideSignerType != credentials.SignatureDefault {
- signerType = c.overrideSignerType
- }
-
- // If signerType returned by credentials helper is anonymous,
- // then do not sign regardless of signerType override.
- if value.SignerType == credentials.SignatureAnonymous {
- signerType = credentials.SignatureAnonymous
- }
-
// Set sha256 sum for signature calculation only with signature version '4'.
- switch {
- case signerType.IsV4():
+ if c.signature.isV4() {
var contentSha256 string
if c.secure {
contentSha256 = unsignedPayload
@@ -217,10 +190,13 @@ func (c Client) getBucketLocationRequest(bucketName string) (*http.Request, erro
contentSha256 = hex.EncodeToString(sum256([]byte{}))
}
req.Header.Set("X-Amz-Content-Sha256", contentSha256)
- req = s3signer.SignV4(*req, accessKeyID, secretAccessKey, sessionToken, "us-east-1")
- case signerType.IsV2():
- req = s3signer.SignV2(*req, accessKeyID, secretAccessKey)
}
+ // Sign the request.
+ if c.signature.isV4() {
+ req = s3signer.SignV4(*req, c.accessKeyID, c.secretAccessKey, "us-east-1")
+ } else if c.signature.isV2() {
+ req = s3signer.SignV2(*req, c.accessKeyID, c.secretAccessKey)
+ }
return req, nil
}
diff --git a/vendor/github.com/minio/minio-go/bucket-cache_test.go b/vendor/github.com/minio/minio-go/bucket-cache_test.go
index 6ae4e7be4..0c068c966 100644
--- a/vendor/github.com/minio/minio-go/bucket-cache_test.go
+++ b/vendor/github.com/minio/minio-go/bucket-cache_test.go
@@ -1,6 +1,5 @@
/*
- * Minio Go Library for Amazon S3 Compatible Cloud Storage
- * (C) 2015, 2016, 2017 Minio, Inc.
+ * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2016, 2016 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,7 +27,6 @@ import (
"reflect"
"testing"
- "github.com/minio/minio-go/pkg/credentials"
"github.com/minio/minio-go/pkg/s3signer"
)
@@ -88,46 +86,17 @@ func TestGetBucketLocationRequest(t *testing.T) {
// Set UserAgent for the request.
c.setUserAgent(req)
- // Get credentials from the configured credentials provider.
- value, err := c.credsProvider.Get()
- if err != nil {
- return nil, err
- }
-
- var (
- signerType = value.SignerType
- accessKeyID = value.AccessKeyID
- secretAccessKey = value.SecretAccessKey
- sessionToken = value.SessionToken
- )
-
- // Custom signer set then override the behavior.
- if c.overrideSignerType != credentials.SignatureDefault {
- signerType = c.overrideSignerType
+ // Set sha256 sum for signature calculation only with signature version '4'.
+ if c.signature.isV4() {
+ req.Header.Set("X-Amz-Content-Sha256", hex.EncodeToString(sum256([]byte{})))
}
- // If signerType returned by credentials helper is anonymous,
- // then do not sign regardless of signerType override.
- if value.SignerType == credentials.SignatureAnonymous {
- signerType = credentials.SignatureAnonymous
+ // Sign the request.
+ if c.signature.isV4() {
+ req = s3signer.SignV4(*req, c.accessKeyID, c.secretAccessKey, "us-east-1")
+ } else if c.signature.isV2() {
+ req = s3signer.SignV2(*req, c.accessKeyID, c.secretAccessKey)
}
-
- // Set sha256 sum for signature calculation only
- // with signature version '4'.
- switch {
- case signerType.IsV4():
- var contentSha256 string
- if c.secure {
- contentSha256 = unsignedPayload
- } else {
- contentSha256 = hex.EncodeToString(sum256([]byte{}))
- }
- req.Header.Set("X-Amz-Content-Sha256", contentSha256)
- req = s3signer.SignV4(*req, accessKeyID, secretAccessKey, sessionToken, "us-east-1")
- case signerType.IsV2():
- req = s3signer.SignV2(*req, accessKeyID, secretAccessKey)
- }
-
return req, nil
}
diff --git a/vendor/github.com/minio/minio-go/core_test.go b/vendor/github.com/minio/minio-go/core_test.go
index 657ad5260..c7c73d4c7 100644
--- a/vendor/github.com/minio/minio-go/core_test.go
+++ b/vendor/github.com/minio/minio-go/core_test.go
@@ -19,6 +19,7 @@ package minio
import (
"bytes"
"crypto/md5"
+ crand "crypto/rand"
"io"
"math/rand"
@@ -300,7 +301,15 @@ func TestCorePutObject(t *testing.T) {
t.Fatal("Error:", err, bucketName)
}
- buf := bytes.Repeat([]byte("a"), minPartSize)
+ buf := make([]byte, minPartSize)
+
+ size, err := io.ReadFull(crand.Reader, buf)
+ if err != nil {
+ t.Fatal("Error:", err)
+ }
+ if size != minPartSize {
+ t.Fatalf("Error: number of bytes does not match, want %v, got %v\n", minPartSize, size)
+ }
// Save the data
objectName := randString(60, rand.NewSource(time.Now().UnixNano()), "")
diff --git a/vendor/github.com/minio/minio-go/pkg/credentials/chain.go b/vendor/github.com/minio/minio-go/pkg/credentials/chain.go
deleted file mode 100644
index 6b0e57440..000000000
--- a/vendor/github.com/minio/minio-go/pkg/credentials/chain.go
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Minio Go Library for Amazon S3 Compatible Cloud Storage
- * (C) 2017 Minio, Inc.
- *
- * 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 credentials
-
-import "fmt"
-
-// A Chain will search for a provider which returns credentials
-// and cache that provider until Retrieve is called again.
-//
-// The Chain provides a way of chaining multiple providers together
-// which will pick the first available using priority order of the
-// Providers in the list.
-//
-// If none of the Providers retrieve valid credentials Value, ChainProvider's
-// Retrieve() will return the error, collecting all errors from all providers.
-//
-// If a Provider is found which returns valid credentials Value ChainProvider
-// will cache that Provider for all calls to IsExpired(), until Retrieve is
-// called again.
-//
-// creds := credentials.NewChainCredentials(
-// []credentials.Provider{
-// &credentials.EnvAWSS3{},
-// &credentials.EnvMinio{},
-// })
-//
-// // Usage of ChainCredentials.
-// mc, err := minio.NewWithCredentials(endpoint, creds, secure, "us-east-1")
-// if err != nil {
-// log.Fatalln(err)
-// }
-//
-type Chain struct {
- Providers []Provider
- curr Provider
-}
-
-// NewChainCredentials returns a pointer to a new Credentials object
-// wrapping a chain of providers.
-func NewChainCredentials(providers []Provider) *Credentials {
- return New(&Chain{
- Providers: append([]Provider{}, providers...),
- })
-}
-
-// Retrieve returns the credentials value or error if no provider returned
-// without error.
-//
-// If a provider is found it will be cached and any calls to IsExpired()
-// will return the expired state of the cached provider.
-func (c *Chain) Retrieve() (Value, error) {
- var errs []error
- for _, p := range c.Providers {
- creds, err := p.Retrieve()
- if err != nil {
- errs = append(errs, err)
- continue
- } // Success.
- c.curr = p
- return creds, nil
- }
- c.curr = nil
- return Value{}, fmt.Errorf("No valid providers found %v", errs)
-}
-
-// IsExpired will returned the expired state of the currently cached provider
-// if there is one. If there is no current provider, true will be returned.
-func (c *Chain) IsExpired() bool {
- if c.curr != nil {
- return c.curr.IsExpired()
- }
-
- return true
-}
diff --git a/vendor/github.com/minio/minio-go/pkg/credentials/chain_test.go b/vendor/github.com/minio/minio-go/pkg/credentials/chain_test.go
deleted file mode 100644
index cb5a6dda5..000000000
--- a/vendor/github.com/minio/minio-go/pkg/credentials/chain_test.go
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Minio Go Library for Amazon S3 Compatible Cloud Storage
- * (C) 2017 Minio, Inc.
- *
- * 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 credentials
-
-import (
- "errors"
- "testing"
-)
-
-type testCredProvider struct {
- creds Value
- expired bool
- err error
-}
-
-func (s *testCredProvider) Retrieve() (Value, error) {
- s.expired = false
- return s.creds, s.err
-}
-func (s *testCredProvider) IsExpired() bool {
- return s.expired
-}
-
-func TestChainGet(t *testing.T) {
- p := &Chain{
- Providers: []Provider{
- &credProvider{err: errors.New("FirstError")},
- &credProvider{err: errors.New("SecondError")},
- &testCredProvider{
- creds: Value{
- AccessKeyID: "AKIF",
- SecretAccessKey: "NOSECRET",
- SessionToken: "",
- },
- },
- &credProvider{
- creds: Value{
- AccessKeyID: "AKID",
- SecretAccessKey: "SECRET",
- SessionToken: "",
- },
- },
- },
- }
-
- creds, err := p.Retrieve()
- if err != nil {
- t.Fatal(err)
- }
-
- // Also check credentials
- if creds.AccessKeyID != "AKIF" {
- t.Fatalf("Expected 'AKIF', got %s", creds.AccessKeyID)
- }
- if creds.SecretAccessKey != "NOSECRET" {
- t.Fatalf("Expected 'NOSECRET', got %s", creds.SecretAccessKey)
- }
- if creds.SessionToken != "" {
- t.Fatalf("Expected empty token, got %s", creds.SessionToken)
- }
-}
-
-func TestChainIsExpired(t *testing.T) {
- credProvider := &credProvider{expired: true}
- p := &Chain{
- Providers: []Provider{
- credProvider,
- },
- }
-
- if !p.IsExpired() {
- t.Fatal("Expected expired to be true before any Retrieve")
- }
-
- _, err := p.Retrieve()
- if err != nil {
- t.Fatal(err)
- }
-
- if p.IsExpired() {
- t.Fatal("Expected to be not expired after Retrieve")
- }
-}
-
-func TestChainWithNoProvider(t *testing.T) {
- p := &Chain{
- Providers: []Provider{},
- }
- if !p.IsExpired() {
- t.Fatal("Expected to be expired with no providers")
- }
- _, err := p.Retrieve()
- if err != nil {
- if err.Error() != "No valid providers found []" {
- t.Error(err)
- }
- }
-}
-
-func TestChainProviderWithNoValidProvider(t *testing.T) {
- errs := []error{
- errors.New("FirstError"),
- errors.New("SecondError"),
- }
- p := &Chain{
- Providers: []Provider{
- &credProvider{err: errs[0]},
- &credProvider{err: errs[1]},
- },
- }
-
- if !p.IsExpired() {
- t.Fatal("Expected to be expired with no providers")
- }
-
- _, err := p.Retrieve()
- if err != nil {
- if err.Error() != "No valid providers found [FirstError SecondError]" {
- t.Error(err)
- }
- }
-}
diff --git a/vendor/github.com/minio/minio-go/pkg/credentials/config.json.sample b/vendor/github.com/minio/minio-go/pkg/credentials/config.json.sample
deleted file mode 100644
index 130746f4b..000000000
--- a/vendor/github.com/minio/minio-go/pkg/credentials/config.json.sample
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "version": "8",
- "hosts": {
- "play": {
- "url": "https://play.minio.io:9000",
- "accessKey": "Q3AM3UQ867SPQQA43P2F",
- "secretKey": "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG",
- "api": "S3v2"
- },
- "s3": {
- "url": "https://s3.amazonaws.com",
- "accessKey": "accessKey",
- "secretKey": "secret",
- "api": "S3v4"
- }
- }
-} \ No newline at end of file
diff --git a/vendor/github.com/minio/minio-go/pkg/credentials/credentials.go b/vendor/github.com/minio/minio-go/pkg/credentials/credentials.go
deleted file mode 100644
index cc3000532..000000000
--- a/vendor/github.com/minio/minio-go/pkg/credentials/credentials.go
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * Minio Go Library for Amazon S3 Compatible Cloud Storage
- * (C) 2017 Minio, Inc.
- *
- * 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 credentials
-
-import (
- "sync"
- "time"
-)
-
-// A Value is the AWS credentials value for individual credential fields.
-type Value struct {
- // AWS Access key ID
- AccessKeyID string
-
- // AWS Secret Access Key
- SecretAccessKey string
-
- // AWS Session Token
- SessionToken string
-
- // Signature Type.
- SignerType SignatureType
-}
-
-// A Provider is the interface for any component which will provide credentials
-// Value. A provider is required to manage its own Expired state, and what to
-// be expired means.
-type Provider interface {
- // Retrieve returns nil if it successfully retrieved the value.
- // Error is returned if the value were not obtainable, or empty.
- Retrieve() (Value, error)
-
- // IsExpired returns if the credentials are no longer valid, and need
- // to be retrieved.
- IsExpired() bool
-}
-
-// A Expiry provides shared expiration logic to be used by credentials
-// providers to implement expiry functionality.
-//
-// The best method to use this struct is as an anonymous field within the
-// provider's struct.
-//
-// Example:
-// type IAMCredentialProvider struct {
-// Expiry
-// ...
-// }
-type Expiry struct {
- // The date/time when to expire on
- expiration time.Time
-
- // If set will be used by IsExpired to determine the current time.
- // Defaults to time.Now if CurrentTime is not set.
- CurrentTime func() time.Time
-}
-
-// SetExpiration sets the expiration IsExpired will check when called.
-//
-// If window is greater than 0 the expiration time will be reduced by the
-// window value.
-//
-// Using a window is helpful to trigger credentials to expire sooner than
-// the expiration time given to ensure no requests are made with expired
-// tokens.
-func (e *Expiry) SetExpiration(expiration time.Time, window time.Duration) {
- e.expiration = expiration
- if window > 0 {
- e.expiration = e.expiration.Add(-window)
- }
-}
-
-// IsExpired returns if the credentials are expired.
-func (e *Expiry) IsExpired() bool {
- if e.CurrentTime == nil {
- e.CurrentTime = time.Now
- }
- return e.expiration.Before(e.CurrentTime())
-}
-
-// Credentials - A container for synchronous safe retrieval of credentials Value.
-// Credentials will cache the credentials value until they expire. Once the value
-// expires the next Get will attempt to retrieve valid credentials.
-//
-// Credentials is safe to use across multiple goroutines and will manage the
-// synchronous state so the Providers do not need to implement their own
-// synchronization.
-//
-// The first Credentials.Get() will always call Provider.Retrieve() to get the
-// first instance of the credentials Value. All calls to Get() after that
-// will return the cached credentials Value until IsExpired() returns true.
-type Credentials struct {
- sync.Mutex
-
- creds Value
- forceRefresh bool
- provider Provider
-}
-
-// New returns a pointer to a new Credentials with the provider set.
-func New(provider Provider) *Credentials {
- return &Credentials{
- provider: provider,
- forceRefresh: true,
- }
-}
-
-// Get returns the credentials value, or error if the credentials Value failed
-// to be retrieved.
-//
-// Will return the cached credentials Value if it has not expired. If the
-// credentials Value has expired the Provider's Retrieve() will be called
-// to refresh the credentials.
-//
-// If Credentials.Expire() was called the credentials Value will be force
-// expired, and the next call to Get() will cause them to be refreshed.
-func (c *Credentials) Get() (Value, error) {
- c.Lock()
- defer c.Unlock()
-
- if c.isExpired() {
- creds, err := c.provider.Retrieve()
- if err != nil {
- return Value{}, err
- }
- c.creds = creds
- c.forceRefresh = false
- }
-
- return c.creds, nil
-}
-
-// Expire expires the credentials and forces them to be retrieved on the
-// next call to Get().
-//
-// This will override the Provider's expired state, and force Credentials
-// to call the Provider's Retrieve().
-func (c *Credentials) Expire() {
- c.Lock()
- defer c.Unlock()
-
- c.forceRefresh = true
-}
-
-// IsExpired returns if the credentials are no longer valid, and need
-// to be refreshed.
-//
-// If the Credentials were forced to be expired with Expire() this will
-// reflect that override.
-func (c *Credentials) IsExpired() bool {
- c.Lock()
- defer c.Unlock()
-
- return c.isExpired()
-}
-
-// isExpired helper method wrapping the definition of expired credentials.
-func (c *Credentials) isExpired() bool {
- return c.forceRefresh || c.provider.IsExpired()
-}
diff --git a/vendor/github.com/minio/minio-go/pkg/credentials/credentials.sample b/vendor/github.com/minio/minio-go/pkg/credentials/credentials.sample
deleted file mode 100644
index 7fc91d9d2..000000000
--- a/vendor/github.com/minio/minio-go/pkg/credentials/credentials.sample
+++ /dev/null
@@ -1,12 +0,0 @@
-[default]
-aws_access_key_id = accessKey
-aws_secret_access_key = secret
-aws_session_token = token
-
-[no_token]
-aws_access_key_id = accessKey
-aws_secret_access_key = secret
-
-[with_colon]
-aws_access_key_id: accessKey
-aws_secret_access_key: secret
diff --git a/vendor/github.com/minio/minio-go/pkg/credentials/credentials_test.go b/vendor/github.com/minio/minio-go/pkg/credentials/credentials_test.go
deleted file mode 100644
index cbfb673b7..000000000
--- a/vendor/github.com/minio/minio-go/pkg/credentials/credentials_test.go
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Minio Go Library for Amazon S3 Compatible Cloud Storage
- * (C) 2017 Minio, Inc.
- *
- * 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 credentials
-
-import (
- "errors"
- "testing"
-)
-
-type credProvider struct {
- creds Value
- expired bool
- err error
-}
-
-func (s *credProvider) Retrieve() (Value, error) {
- s.expired = false
- return s.creds, s.err
-}
-func (s *credProvider) IsExpired() bool {
- return s.expired
-}
-
-func TestCredentialsGet(t *testing.T) {
- c := New(&credProvider{
- creds: Value{
- AccessKeyID: "UXHW",
- SecretAccessKey: "MYSECRET",
- SessionToken: "",
- },
- expired: true,
- })
-
- creds, err := c.Get()
- if err != nil {
- t.Fatal(err)
- }
- if "UXHW" != creds.AccessKeyID {
- t.Errorf("Expected \"UXHW\", got %s", creds.AccessKeyID)
- }
- if "MYSECRET" != creds.SecretAccessKey {
- t.Errorf("Expected \"MYSECRET\", got %s", creds.SecretAccessKey)
- }
- if creds.SessionToken != "" {
- t.Errorf("Expected session token to be empty, got %s", creds.SessionToken)
- }
-}
-
-func TestCredentialsGetWithError(t *testing.T) {
- c := New(&credProvider{err: errors.New("Custom error")})
-
- _, err := c.Get()
- if err != nil {
- if err.Error() != "Custom error" {
- t.Errorf("Expected \"Custom error\", got %s", err.Error())
- }
- }
-}
diff --git a/vendor/github.com/minio/minio-go/pkg/credentials/doc.go b/vendor/github.com/minio/minio-go/pkg/credentials/doc.go
deleted file mode 100644
index fa1908aeb..000000000
--- a/vendor/github.com/minio/minio-go/pkg/credentials/doc.go
+++ /dev/null
@@ -1,45 +0,0 @@
-// Package credentials provides credential retrieval and management
-// for S3 compatible object storage.
-//
-// By default the Credentials.Get() will cache the successful result of a
-// Provider's Retrieve() until Provider.IsExpired() returns true. At which
-// point Credentials will call Provider's Retrieve() to get new credential Value.
-//
-// The Provider is responsible for determining when credentials have expired.
-// It is also important to note that Credentials will always call Retrieve the
-// first time Credentials.Get() is called.
-//
-// Example of using the environment variable credentials.
-//
-// creds := NewFromEnv()
-// // Retrieve the credentials value
-// credValue, err := creds.Get()
-// if err != nil {
-// // handle error
-// }
-//
-// Example of forcing credentials to expire and be refreshed on the next Get().
-// This may be helpful to proactively expire credentials and refresh them sooner
-// than they would naturally expire on their own.
-//
-// creds := NewFromIAM("")
-// creds.Expire()
-// credsValue, err := creds.Get()
-// // New credentials will be retrieved instead of from cache.
-//
-//
-// Custom Provider
-//
-// Each Provider built into this package also provides a helper method to generate
-// a Credentials pointer setup with the provider. To use a custom Provider just
-// create a type which satisfies the Provider interface and pass it to the
-// NewCredentials method.
-//
-// type MyProvider struct{}
-// func (m *MyProvider) Retrieve() (Value, error) {...}
-// func (m *MyProvider) IsExpired() bool {...}
-//
-// creds := NewCredentials(&MyProvider{})
-// credValue, err := creds.Get()
-//
-package credentials
diff --git a/vendor/github.com/minio/minio-go/pkg/credentials/env_aws.go b/vendor/github.com/minio/minio-go/pkg/credentials/env_aws.go
deleted file mode 100644
index 11934433c..000000000
--- a/vendor/github.com/minio/minio-go/pkg/credentials/env_aws.go
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Minio Go Library for Amazon S3 Compatible Cloud Storage
- * (C) 2017 Minio, Inc.
- *
- * 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 credentials
-
-import "os"
-
-// A EnvAWS retrieves credentials from the environment variables of the
-// running process. EnvAWSironment credentials never expire.
-//
-// EnvAWSironment variables used:
-//
-// * Access Key ID: AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY.
-// * Secret Access Key: AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY.
-// * Secret Token: AWS_SESSION_TOKEN.
-type EnvAWS struct {
- retrieved bool
-}
-
-// NewEnvAWS returns a pointer to a new Credentials object
-// wrapping the environment variable provider.
-func NewEnvAWS() *Credentials {
- return New(&EnvAWS{})
-}
-
-// Retrieve retrieves the keys from the environment.
-func (e *EnvAWS) Retrieve() (Value, error) {
- e.retrieved = false
-
- id := os.Getenv("AWS_ACCESS_KEY_ID")
- if id == "" {
- id = os.Getenv("AWS_ACCESS_KEY")
- }
-
- secret := os.Getenv("AWS_SECRET_ACCESS_KEY")
- if secret == "" {
- secret = os.Getenv("AWS_SECRET_KEY")
- }
-
- signerType := SignatureV4
- if id == "" || secret == "" {
- signerType = SignatureAnonymous
- }
-
- e.retrieved = true
- return Value{
- AccessKeyID: id,
- SecretAccessKey: secret,
- SessionToken: os.Getenv("AWS_SESSION_TOKEN"),
- SignerType: signerType,
- }, nil
-}
-
-// IsExpired returns if the credentials have been retrieved.
-func (e *EnvAWS) IsExpired() bool {
- return !e.retrieved
-}
diff --git a/vendor/github.com/minio/minio-go/pkg/credentials/env_minio.go b/vendor/github.com/minio/minio-go/pkg/credentials/env_minio.go
deleted file mode 100644
index 791087ef5..000000000
--- a/vendor/github.com/minio/minio-go/pkg/credentials/env_minio.go
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Minio Go Library for Amazon S3 Compatible Cloud Storage
- * (C) 2017 Minio, Inc.
- *
- * 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 credentials
-
-import "os"
-
-// A EnvMinio retrieves credentials from the environment variables of the
-// running process. EnvMinioironment credentials never expire.
-//
-// EnvMinioironment variables used:
-//
-// * Access Key ID: MINIO_ACCESS_KEY.
-// * Secret Access Key: MINIO_SECRET_KEY.
-type EnvMinio struct {
- retrieved bool
-}
-
-// NewEnvMinio returns a pointer to a new Credentials object
-// wrapping the environment variable provider.
-func NewEnvMinio() *Credentials {
- return New(&EnvMinio{})
-}
-
-// Retrieve retrieves the keys from the environment.
-func (e *EnvMinio) Retrieve() (Value, error) {
- e.retrieved = false
-
- id := os.Getenv("MINIO_ACCESS_KEY")
- secret := os.Getenv("MINIO_SECRET_KEY")
-
- signerType := SignatureV4
- if id == "" || secret == "" {
- signerType = SignatureAnonymous
- }
-
- e.retrieved = true
- return Value{
- AccessKeyID: id,
- SecretAccessKey: secret,
- SignerType: signerType,
- }, nil
-}
-
-// IsExpired returns if the credentials have been retrieved.
-func (e *EnvMinio) IsExpired() bool {
- return !e.retrieved
-}
diff --git a/vendor/github.com/minio/minio-go/pkg/credentials/env_test.go b/vendor/github.com/minio/minio-go/pkg/credentials/env_test.go
deleted file mode 100644
index 2f72bea40..000000000
--- a/vendor/github.com/minio/minio-go/pkg/credentials/env_test.go
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Minio Go Library for Amazon S3 Compatible Cloud Storage
- * (C) 2017 Minio, Inc.
- *
- * 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 credentials
-
-import (
- "os"
- "reflect"
- "testing"
-)
-
-func TestEnvAWSRetrieve(t *testing.T) {
- os.Clearenv()
- os.Setenv("AWS_ACCESS_KEY_ID", "access")
- os.Setenv("AWS_SECRET_ACCESS_KEY", "secret")
- os.Setenv("AWS_SESSION_TOKEN", "token")
-
- e := EnvAWS{}
- if !e.IsExpired() {
- t.Error("Expect creds to be expired before retrieve.")
- }
-
- creds, err := e.Retrieve()
- if err != nil {
- t.Fatal(err)
- }
-
- expectedCreds := Value{
- AccessKeyID: "access",
- SecretAccessKey: "secret",
- SessionToken: "token",
- SignerType: SignatureV4,
- }
- if !reflect.DeepEqual(creds, expectedCreds) {
- t.Errorf("Expected %v, got %v", expectedCreds, creds)
- }
-
- if e.IsExpired() {
- t.Error("Expect creds to not be expired after retrieve.")
- }
-
- os.Clearenv()
- os.Setenv("AWS_ACCESS_KEY", "access")
- os.Setenv("AWS_SECRET_KEY", "secret")
-
- expectedCreds = Value{
- AccessKeyID: "access",
- SecretAccessKey: "secret",
- SignerType: SignatureV4,
- }
-
- creds, err = e.Retrieve()
- if err != nil {
- t.Fatal(err)
- }
-
- if !reflect.DeepEqual(creds, expectedCreds) {
- t.Errorf("Expected %v, got %v", expectedCreds, creds)
- }
-
-}
-
-func TestEnvMinioRetrieve(t *testing.T) {
- os.Clearenv()
-
- os.Setenv("MINIO_ACCESS_KEY", "access")
- os.Setenv("MINIO_SECRET_KEY", "secret")
-
- e := EnvMinio{}
- if !e.IsExpired() {
- t.Error("Expect creds to be expired before retrieve.")
- }
-
- creds, err := e.Retrieve()
- if err != nil {
- t.Fatal(err)
- }
-
- expectedCreds := Value{
- AccessKeyID: "access",
- SecretAccessKey: "secret",
- SignerType: SignatureV4,
- }
- if !reflect.DeepEqual(creds, expectedCreds) {
- t.Errorf("Expected %v, got %v", expectedCreds, creds)
- }
-
- if e.IsExpired() {
- t.Error("Expect creds to not be expired after retrieve.")
- }
-}
diff --git a/vendor/github.com/minio/minio-go/pkg/credentials/file_aws_credentials.go b/vendor/github.com/minio/minio-go/pkg/credentials/file_aws_credentials.go
deleted file mode 100644
index 1be621385..000000000
--- a/vendor/github.com/minio/minio-go/pkg/credentials/file_aws_credentials.go
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Minio Go Library for Amazon S3 Compatible Cloud Storage
- * (C) 2017 Minio, Inc.
- *
- * 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 credentials
-
-import (
- "os"
- "path/filepath"
-
- "github.com/go-ini/ini"
- homedir "github.com/minio/go-homedir"
-)
-
-// A FileAWSCredentials retrieves credentials from the current user's home
-// directory, and keeps track if those credentials are expired.
-//
-// Profile ini file example: $HOME/.aws/credentials
-type FileAWSCredentials struct {
- // Path to the shared credentials file.
- //
- // If empty will look for "AWS_SHARED_CREDENTIALS_FILE" env variable. If the
- // env value is empty will default to current user's home directory.
- // Linux/OSX: "$HOME/.aws/credentials"
- // Windows: "%USERPROFILE%\.aws\credentials"
- filename string
-
- // AWS Profile to extract credentials from the shared credentials file. If empty
- // will default to environment variable "AWS_PROFILE" or "default" if
- // environment variable is also not set.
- profile string
-
- // retrieved states if the credentials have been successfully retrieved.
- retrieved bool
-}
-
-// NewFileAWSCredentials returns a pointer to a new Credentials object
-// wrapping the Profile file provider.
-func NewFileAWSCredentials(filename string, profile string) *Credentials {
- return New(&FileAWSCredentials{
- filename: filename,
- profile: profile,
- })
-}
-
-// Retrieve reads and extracts the shared credentials from the current
-// users home directory.
-func (p *FileAWSCredentials) Retrieve() (Value, error) {
- if p.filename == "" {
- p.filename = os.Getenv("AWS_SHARED_CREDENTIALS_FILE")
- if p.filename == "" {
- homeDir, err := homedir.Dir()
- if err != nil {
- return Value{}, err
- }
- p.filename = filepath.Join(homeDir, ".aws", "credentials")
- }
- }
- if p.profile == "" {
- p.profile = os.Getenv("AWS_PROFILE")
- if p.profile == "" {
- p.profile = "default"
- }
- }
-
- p.retrieved = false
-
- iniProfile, err := loadProfile(p.filename, p.profile)
- if err != nil {
- return Value{}, err
- }
-
- // Default to empty string if not found.
- id := iniProfile.Key("aws_access_key_id")
- // Default to empty string if not found.
- secret := iniProfile.Key("aws_secret_access_key")
- // Default to empty string if not found.
- token := iniProfile.Key("aws_session_token")
-
- p.retrieved = true
- return Value{
- AccessKeyID: id.String(),
- SecretAccessKey: secret.String(),
- SessionToken: token.String(),
- SignerType: SignatureV4,
- }, nil
-}
-
-// IsExpired returns if the shared credentials have expired.
-func (p *FileAWSCredentials) IsExpired() bool {
- return !p.retrieved
-}
-
-// loadProfiles loads from the file pointed to by shared credentials filename for profile.
-// The credentials retrieved from the profile will be returned or error. Error will be
-// returned if it fails to read from the file, or the data is invalid.
-func loadProfile(filename, profile string) (*ini.Section, error) {
- config, err := ini.Load(filename)
- if err != nil {
- return nil, err
- }
- iniProfile, err := config.GetSection(profile)
- if err != nil {
- return nil, err
- }
- return iniProfile, nil
-}
diff --git a/vendor/github.com/minio/minio-go/pkg/credentials/file_minio_client.go b/vendor/github.com/minio/minio-go/pkg/credentials/file_minio_client.go
deleted file mode 100644
index 9e26dd302..000000000
--- a/vendor/github.com/minio/minio-go/pkg/credentials/file_minio_client.go
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Minio Go Library for Amazon S3 Compatible Cloud Storage
- * (C) 2017 Minio, Inc.
- *
- * 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 credentials
-
-import (
- "encoding/json"
- "io/ioutil"
- "os"
- "path/filepath"
- "runtime"
-
- homedir "github.com/minio/go-homedir"
-)
-
-// A FileMinioClient retrieves credentials from the current user's home
-// directory, and keeps track if those credentials are expired.
-//
-// Configuration file example: $HOME/.mc/config.json
-type FileMinioClient struct {
- // Path to the shared credentials file.
- //
- // If empty will look for "MINIO_SHARED_CREDENTIALS_FILE" env variable. If the
- // env value is empty will default to current user's home directory.
- // Linux/OSX: "$HOME/.mc/config.json"
- // Windows: "%USERALIAS%\mc\config.json"
- filename string
-
- // Minio Alias to extract credentials from the shared credentials file. If empty
- // will default to environment variable "MINIO_ALIAS" or "default" if
- // environment variable is also not set.
- alias string
-
- // retrieved states if the credentials have been successfully retrieved.
- retrieved bool
-}
-
-// NewFileMinioClient returns a pointer to a new Credentials object
-// wrapping the Alias file provider.
-func NewFileMinioClient(filename string, alias string) *Credentials {
- return New(&FileMinioClient{
- filename: filename,
- alias: alias,
- })
-}
-
-// Retrieve reads and extracts the shared credentials from the current
-// users home directory.
-func (p *FileMinioClient) Retrieve() (Value, error) {
- if p.filename == "" {
- homeDir, err := homedir.Dir()
- if err != nil {
- return Value{}, err
- }
- p.filename = filepath.Join(homeDir, ".mc", "config.json")
- if runtime.GOOS == "windows" {
- p.filename = filepath.Join(homeDir, "mc", "config.json")
- }
- }
-
- if p.alias == "" {
- p.alias = os.Getenv("MINIO_ALIAS")
- if p.alias == "" {
- p.alias = "s3"
- }
- }
-
- p.retrieved = false
-
- hostCfg, err := loadAlias(p.filename, p.alias)
- if err != nil {
- return Value{}, err
- }
-
- p.retrieved = true
- return Value{
- AccessKeyID: hostCfg.AccessKey,
- SecretAccessKey: hostCfg.SecretKey,
- SignerType: parseSignatureType(hostCfg.API),
- }, nil
-}
-
-// IsExpired returns if the shared credentials have expired.
-func (p *FileMinioClient) IsExpired() bool {
- return !p.retrieved
-}
-
-// hostConfig configuration of a host.
-type hostConfig struct {
- URL string `json:"url"`
- AccessKey string `json:"accessKey"`
- SecretKey string `json:"secretKey"`
- API string `json:"api"`
-}
-
-// config config version.
-type config struct {
- Version string `json:"version"`
- Hosts map[string]hostConfig `json:"hosts"`
-}
-
-// loadAliass loads from the file pointed to by shared credentials filename for alias.
-// The credentials retrieved from the alias will be returned or error. Error will be
-// returned if it fails to read from the file.
-func loadAlias(filename, alias string) (hostConfig, error) {
- cfg := &config{}
- configBytes, err := ioutil.ReadFile(filename)
- if err != nil {
- return hostConfig{}, err
- }
- if err = json.Unmarshal(configBytes, cfg); err != nil {
- return hostConfig{}, err
- }
- return cfg.Hosts[alias], nil
-}
diff --git a/vendor/github.com/minio/minio-go/pkg/credentials/file_test.go b/vendor/github.com/minio/minio-go/pkg/credentials/file_test.go
deleted file mode 100644
index c62c53365..000000000
--- a/vendor/github.com/minio/minio-go/pkg/credentials/file_test.go
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- * Minio Go Library for Amazon S3 Compatible Cloud Storage
- * (C) 2017 Minio, Inc.
- *
- * 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 credentials
-
-import (
- "os"
- "path/filepath"
- "testing"
-)
-
-func TestFileAWS(t *testing.T) {
- os.Clearenv()
-
- creds := NewFileAWSCredentials("credentials.sample", "")
- credValues, err := creds.Get()
- if err != nil {
- t.Fatal(err)
- }
-
- if credValues.AccessKeyID != "accessKey" {
- t.Errorf("Expected 'accessKey', got %s'", credValues.AccessKeyID)
- }
- if credValues.SecretAccessKey != "secret" {
- t.Errorf("Expected 'secret', got %s'", credValues.SecretAccessKey)
- }
- if credValues.SessionToken != "token" {
- t.Errorf("Expected 'token', got %s'", credValues.SessionToken)
- }
-
- os.Setenv("AWS_SHARED_CREDENTIALS_FILE", "credentials.sample")
- creds = NewFileAWSCredentials("", "")
- credValues, err = creds.Get()
- if err != nil {
- t.Fatal(err)
- }
-
- if credValues.AccessKeyID != "accessKey" {
- t.Errorf("Expected 'accessKey', got %s'", credValues.AccessKeyID)
- }
- if credValues.SecretAccessKey != "secret" {
- t.Errorf("Expected 'secret', got %s'", credValues.SecretAccessKey)
- }
- if credValues.SessionToken != "token" {
- t.Errorf("Expected 'token', got %s'", credValues.SessionToken)
- }
-
- wd, err := os.Getwd()
- if err != nil {
- t.Fatal(err)
- }
-
- os.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(wd, "credentials.sample"))
- creds = NewFileAWSCredentials("", "")
- credValues, err = creds.Get()
- if err != nil {
- t.Fatal(err)
- }
-
- if credValues.AccessKeyID != "accessKey" {
- t.Errorf("Expected 'accessKey', got %s'", credValues.AccessKeyID)
- }
- if credValues.SecretAccessKey != "secret" {
- t.Errorf("Expected 'secret', got %s'", credValues.SecretAccessKey)
- }
- if credValues.SessionToken != "token" {
- t.Errorf("Expected 'token', got %s'", credValues.SessionToken)
- }
-
- os.Clearenv()
- os.Setenv("AWS_PROFILE", "no_token")
-
- creds = NewFileAWSCredentials("credentials.sample", "")
- credValues, err = creds.Get()
- if err != nil {
- t.Fatal(err)
- }
-
- if credValues.AccessKeyID != "accessKey" {
- t.Errorf("Expected 'accessKey', got %s'", credValues.AccessKeyID)
- }
- if credValues.SecretAccessKey != "secret" {
- t.Errorf("Expected 'secret', got %s'", credValues.SecretAccessKey)
- }
-
- os.Clearenv()
-
- creds = NewFileAWSCredentials("credentials.sample", "no_token")
- credValues, err = creds.Get()
- if err != nil {
- t.Fatal(err)
- }
-
- if credValues.AccessKeyID != "accessKey" {
- t.Errorf("Expected 'accessKey', got %s'", credValues.AccessKeyID)
- }
- if credValues.SecretAccessKey != "secret" {
- t.Errorf("Expected 'secret', got %s'", credValues.SecretAccessKey)
- }
-
- creds = NewFileAWSCredentials("credentials-non-existent.sample", "no_token")
- _, err = creds.Get()
- if !os.IsNotExist(err) {
- t.Errorf("Expected open non-existent.json: no such file or directory, got %s", err)
- }
- if !creds.IsExpired() {
- t.Error("Should be expired if not loaded")
- }
-}
-
-func TestFileMinioClient(t *testing.T) {
- os.Clearenv()
-
- creds := NewFileMinioClient("config.json.sample", "")
- credValues, err := creds.Get()
- if err != nil {
- t.Fatal(err)
- }
-
- if credValues.AccessKeyID != "accessKey" {
- t.Errorf("Expected 'accessKey', got %s'", credValues.AccessKeyID)
- }
- if credValues.SecretAccessKey != "secret" {
- t.Errorf("Expected 'secret', got %s'", credValues.SecretAccessKey)
- }
- if credValues.SignerType != SignatureV4 {
- t.Errorf("Expected 'S3v4', got %s'", credValues.SignerType)
- }
-
- os.Clearenv()
- os.Setenv("MINIO_ALIAS", "play")
-
- creds = NewFileMinioClient("config.json.sample", "")
- credValues, err = creds.Get()
- if err != nil {
- t.Fatal(err)
- }
-
- if credValues.AccessKeyID != "Q3AM3UQ867SPQQA43P2F" {
- t.Errorf("Expected 'Q3AM3UQ867SPQQA43P2F', got %s'", credValues.AccessKeyID)
- }
- if credValues.SecretAccessKey != "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG" {
- t.Errorf("Expected 'zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG', got %s'", credValues.SecretAccessKey)
- }
- if credValues.SignerType != SignatureV2 {
- t.Errorf("Expected 'S3v2', got %s'", credValues.SignerType)
- }
-
- os.Clearenv()
-
- creds = NewFileMinioClient("config.json.sample", "play")
- credValues, err = creds.Get()
- if err != nil {
- t.Fatal(err)
- }
-
- if credValues.AccessKeyID != "Q3AM3UQ867SPQQA43P2F" {
- t.Errorf("Expected 'Q3AM3UQ867SPQQA43P2F', got %s'", credValues.AccessKeyID)
- }
- if credValues.SecretAccessKey != "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG" {
- t.Errorf("Expected 'zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG', got %s'", credValues.SecretAccessKey)
- }
- if credValues.SignerType != SignatureV2 {
- t.Errorf("Expected 'S3v2', got %s'", credValues.SignerType)
- }
-
- creds = NewFileMinioClient("non-existent.json", "play")
- _, err = creds.Get()
- if !os.IsNotExist(err) {
- t.Errorf("Expected open non-existent.json: no such file or directory, got %s", err)
- }
- if !creds.IsExpired() {
- t.Error("Should be expired if not loaded")
- }
-}
diff --git a/vendor/github.com/minio/minio-go/pkg/credentials/iam_aws.go b/vendor/github.com/minio/minio-go/pkg/credentials/iam_aws.go
deleted file mode 100644
index ee24a213b..000000000
--- a/vendor/github.com/minio/minio-go/pkg/credentials/iam_aws.go
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * Minio Go Library for Amazon S3 Compatible Cloud Storage
- * (C) 2017 Minio, Inc.
- *
- * 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 credentials
-
-import (
- "bufio"
- "encoding/json"
- "errors"
- "net/http"
- "net/url"
- "path"
- "time"
-)
-
-// DefaultExpiryWindow - Default expiry window.
-// ExpiryWindow will allow the credentials to trigger refreshing
-// prior to the credentials actually expiring. This is beneficial
-// so race conditions with expiring credentials do not cause
-// request to fail unexpectedly due to ExpiredTokenException exceptions.
-const DefaultExpiryWindow = time.Second * 10 // 10 secs
-
-// A IAM retrieves credentials from the EC2 service, and keeps track if
-// those credentials are expired.
-type IAM struct {
- Expiry
-
- // Required http Client to use when connecting to IAM metadata service.
- Client *http.Client
-
- // Custom endpoint in place of
- endpoint string
-}
-
-// redirectHeaders copies all headers when following a redirect URL.
-// This won't be needed anymore from go 1.8 (https://github.com/golang/go/issues/4800)
-func redirectHeaders(req *http.Request, via []*http.Request) error {
- if len(via) == 0 {
- return nil
- }
- for key, val := range via[0].Header {
- req.Header[key] = val
- }
- return nil
-}
-
-// NewIAM returns a pointer to a new Credentials object wrapping
-// the IAM. Takes a ConfigProvider to create a EC2Metadata client.
-// The ConfigProvider is satisfied by the session.Session type.
-func NewIAM(endpoint string) *Credentials {
- if endpoint == "" {
- // IAM Roles for Amazon EC2
- // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
- endpoint = "http://169.254.169.254"
- }
- p := &IAM{
- Client: &http.Client{
- Transport: http.DefaultTransport,
- CheckRedirect: redirectHeaders,
- },
- endpoint: endpoint,
- }
- return New(p)
-}
-
-// Retrieve retrieves credentials from the EC2 service.
-// Error will be returned if the request fails, or unable to extract
-// the desired
-func (m *IAM) Retrieve() (Value, error) {
- credsList, err := requestCredList(m.Client, m.endpoint)
- if err != nil {
- return Value{}, err
- }
-
- if len(credsList) == 0 {
- return Value{}, errors.New("empty EC2 Role list")
- }
- credsName := credsList[0]
-
- roleCreds, err := requestCred(m.Client, m.endpoint, credsName)
- if err != nil {
- return Value{}, err
- }
-
- // Expiry window is set to 10secs.
- m.SetExpiration(roleCreds.Expiration, DefaultExpiryWindow)
-
- return Value{
- AccessKeyID: roleCreds.AccessKeyID,
- SecretAccessKey: roleCreds.SecretAccessKey,
- SessionToken: roleCreds.Token,
- SignerType: SignatureV4,
- }, nil
-}
-
-// A ec2RoleCredRespBody provides the shape for unmarshaling credential
-// request responses.
-type ec2RoleCredRespBody struct {
- // Success State
- Expiration time.Time
- AccessKeyID string
- SecretAccessKey string
- Token string
-
- // Error state
- Code string
- Message string
-}
-
-const iamSecurityCredsPath = "/latest/meta-data/iam/security-credentials"
-
-// requestCredList requests a list of credentials from the EC2 service.
-// If there are no credentials, or there is an error making or receiving the request
-func requestCredList(client *http.Client, endpoint string) ([]string, error) {
- u, err := url.Parse(endpoint)
- if err != nil {
- return nil, err
- }
- u.Path = iamSecurityCredsPath
- req, err := http.NewRequest("GET", u.String(), nil)
- if err != nil {
- return nil, err
- }
- resp, err := client.Do(req)
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
- if resp.StatusCode != http.StatusOK {
- return nil, errors.New(resp.Status)
- }
-
- credsList := []string{}
- s := bufio.NewScanner(resp.Body)
- for s.Scan() {
- credsList = append(credsList, s.Text())
- }
-
- if err := s.Err(); err != nil {
- return nil, err
- }
-
- return credsList, nil
-}
-
-// requestCred requests the credentials for a specific credentials from the EC2 service.
-//
-// If the credentials cannot be found, or there is an error reading the response
-// and error will be returned.
-func requestCred(client *http.Client, endpoint string, credsName string) (ec2RoleCredRespBody, error) {
- u, err := url.Parse(endpoint)
- if err != nil {
- return ec2RoleCredRespBody{}, err
- }
-
- u.Path = path.Join(iamSecurityCredsPath, credsName)
- req, err := http.NewRequest("GET", u.String(), nil)
- if err != nil {
- return ec2RoleCredRespBody{}, err
- }
-
- resp, err := client.Do(req)
- if err != nil {
- return ec2RoleCredRespBody{}, err
- }
- defer resp.Body.Close()
- if resp.StatusCode != http.StatusOK {
- return ec2RoleCredRespBody{}, errors.New(resp.Status)
- }
-
- respCreds := ec2RoleCredRespBody{}
- if err := json.NewDecoder(resp.Body).Decode(&respCreds); err != nil {
- return ec2RoleCredRespBody{}, err
- }
-
- if respCreds.Code != "Success" {
- // If an error code was returned something failed requesting the role.
- return ec2RoleCredRespBody{}, errors.New(respCreds.Message)
- }
-
- return respCreds, nil
-}
diff --git a/vendor/github.com/minio/minio-go/pkg/credentials/iam_aws_test.go b/vendor/github.com/minio/minio-go/pkg/credentials/iam_aws_test.go
deleted file mode 100644
index 19553945d..000000000
--- a/vendor/github.com/minio/minio-go/pkg/credentials/iam_aws_test.go
+++ /dev/null
@@ -1,180 +0,0 @@
-package credentials
-
-import (
- "fmt"
- "net/http"
- "net/http/httptest"
- "testing"
- "time"
-)
-
-const credsRespTmpl = `{
- "Code": "Success",
- "Type": "AWS-HMAC",
- "AccessKeyId" : "accessKey",
- "SecretAccessKey" : "secret",
- "Token" : "token",
- "Expiration" : "%s",
- "LastUpdated" : "2009-11-23T0:00:00Z"
-}`
-
-const credsFailRespTmpl = `{
- "Code": "ErrorCode",
- "Message": "ErrorMsg",
- "LastUpdated": "2009-11-23T0:00:00Z"
-}`
-
-func initTestFailServer() *httptest.Server {
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- http.Error(w, "Not allowed", http.StatusBadRequest)
- }))
- return server
-}
-
-func initTestServerNoRoles() *httptest.Server {
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte(""))
- }))
- return server
-}
-
-func initTestServer(expireOn string, failAssume bool) *httptest.Server {
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.URL.Path == "/latest/meta-data/iam/security-credentials" {
- fmt.Fprintln(w, "RoleName")
- } else if r.URL.Path == "/latest/meta-data/iam/security-credentials/RoleName" {
- if failAssume {
- fmt.Fprintf(w, credsFailRespTmpl)
- } else {
- fmt.Fprintf(w, credsRespTmpl, expireOn)
- }
- } else {
- http.Error(w, "bad request", http.StatusBadRequest)
- }
- }))
-
- return server
-}
-
-func TestIAMMalformedEndpoint(t *testing.T) {
- creds := NewIAM("%%%%")
- _, err := creds.Get()
- if err == nil {
- t.Fatal("Unexpected should fail here")
- }
- if err.Error() != `parse %%%%: invalid URL escape "%%%"` {
- t.Fatalf("Expected parse %%%%%%%%: invalid URL escape \"%%%%%%\", got %s", err)
- }
-}
-
-func TestIAMFailServer(t *testing.T) {
- server := initTestFailServer()
- defer server.Close()
-
- creds := NewIAM(server.URL)
-
- _, err := creds.Get()
- if err == nil {
- t.Fatal("Unexpected should fail here")
- }
- if err.Error() != "400 Bad Request" {
- t.Fatalf("Expected '400 Bad Request', got %s", err)
- }
-}
-
-func TestIAMNoRoles(t *testing.T) {
- server := initTestServerNoRoles()
- defer server.Close()
-
- creds := NewIAM(server.URL)
- _, err := creds.Get()
- if err == nil {
- t.Fatal("Unexpected should fail here")
- }
- if err.Error() != "empty EC2 Role list" {
- t.Fatalf("Expected 'empty EC2 Role list', got %s", err)
- }
-}
-
-func TestIAM(t *testing.T) {
- server := initTestServer("2014-12-16T01:51:37Z", false)
- defer server.Close()
-
- p := &IAM{
- Client: http.DefaultClient,
- endpoint: server.URL,
- }
-
- creds, err := p.Retrieve()
- if err != nil {
- t.Fatal(err)
- }
-
- if "accessKey" != creds.AccessKeyID {
- t.Errorf("Expected \"accessKey\", got %s", creds.AccessKeyID)
- }
-
- if "secret" != creds.SecretAccessKey {
- t.Errorf("Expected \"secret\", got %s", creds.SecretAccessKey)
- }
-
- if "token" != creds.SessionToken {
- t.Errorf("Expected \"token\", got %s", creds.SessionToken)
- }
-
- if !p.IsExpired() {
- t.Error("Expected creds to be expired.")
- }
-}
-
-func TestIAMFailAssume(t *testing.T) {
- server := initTestServer("2014-12-16T01:51:37Z", true)
- defer server.Close()
-
- p := &IAM{
- Client: http.DefaultClient,
- endpoint: server.URL,
- }
-
- _, err := p.Retrieve()
- if err == nil {
- t.Fatal("Unexpected success, should fail")
- }
- if err.Error() != "ErrorMsg" {
- t.Errorf("Expected \"ErrorMsg\", got %s", err)
- }
-}
-
-func TestIAMIsExpired(t *testing.T) {
- server := initTestServer("2014-12-16T01:51:37Z", false)
- defer server.Close()
-
- p := &IAM{
- Client: http.DefaultClient,
- endpoint: server.URL,
- }
- p.CurrentTime = func() time.Time {
- return time.Date(2014, 12, 15, 21, 26, 0, 0, time.UTC)
- }
-
- if !p.IsExpired() {
- t.Error("Expected creds to be expired before retrieve.")
- }
-
- _, err := p.Retrieve()
- if err != nil {
- t.Fatal(err)
- }
-
- if p.IsExpired() {
- t.Error("Expected creds to not be expired after retrieve.")
- }
-
- p.CurrentTime = func() time.Time {
- return time.Date(3014, 12, 15, 21, 26, 0, 0, time.UTC)
- }
-
- if !p.IsExpired() {
- t.Error("Expected creds to be expired when curren time has changed")
- }
-}
diff --git a/vendor/github.com/minio/minio-go/pkg/credentials/signature-type.go b/vendor/github.com/minio/minio-go/pkg/credentials/signature-type.go
deleted file mode 100644
index c64ad6c23..000000000
--- a/vendor/github.com/minio/minio-go/pkg/credentials/signature-type.go
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2017 Minio, Inc.
- *
- * 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 credentials
-
-import "strings"
-
-// SignatureType is type of Authorization requested for a given HTTP request.
-type SignatureType int
-
-// Different types of supported signatures - default is SignatureV4 or SignatureDefault.
-const (
- // SignatureDefault is always set to v4.
- SignatureDefault SignatureType = iota
- SignatureV4
- SignatureV2
- SignatureV4Streaming
- SignatureAnonymous // Anonymous signature signifies, no signature.
-)
-
-// IsV2 - is signature SignatureV2?
-func (s SignatureType) IsV2() bool {
- return s == SignatureV2
-}
-
-// IsV4 - is signature SignatureV4?
-func (s SignatureType) IsV4() bool {
- return s == SignatureV4 || s == SignatureDefault
-}
-
-// IsStreamingV4 - is signature SignatureV4Streaming?
-func (s SignatureType) IsStreamingV4() bool {
- return s == SignatureV4Streaming
-}
-
-// IsAnonymous - is signature empty?
-func (s SignatureType) IsAnonymous() bool {
- return s == SignatureAnonymous
-}
-
-// Stringer humanized version of signature type,
-// strings returned here are case insensitive.
-func (s SignatureType) String() string {
- if s.IsV2() {
- return "S3v2"
- } else if s.IsV4() {
- return "S3v4"
- } else if s.IsStreamingV4() {
- return "S3v4Streaming"
- }
- return "Anonymous"
-}
-
-func parseSignatureType(str string) SignatureType {
- if strings.EqualFold(str, "S3v4") {
- return SignatureV4
- } else if strings.EqualFold(str, "S3v2") {
- return SignatureV2
- } else if strings.EqualFold(str, "S3v4Streaming") {
- return SignatureV4Streaming
- }
- return SignatureAnonymous
-}
diff --git a/vendor/github.com/minio/minio-go/pkg/credentials/static.go b/vendor/github.com/minio/minio-go/pkg/credentials/static.go
deleted file mode 100644
index 25aff5696..000000000
--- a/vendor/github.com/minio/minio-go/pkg/credentials/static.go
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Minio Go Library for Amazon S3 Compatible Cloud Storage
- * (C) 2017 Minio, Inc.
- *
- * 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 credentials
-
-// A Static is a set of credentials which are set programmatically,
-// and will never expire.
-type Static struct {
- Value
-}
-
-// NewStaticV2 returns a pointer to a new Credentials object
-// wrapping a static credentials value provider, signature is
-// set to v2. If access and secret are not specified then
-// regardless of signature type set it Value will return
-// as anonymous.
-func NewStaticV2(id, secret, token string) *Credentials {
- return NewStatic(id, secret, token, SignatureV2)
-}
-
-// NewStaticV4 is similar to NewStaticV2 with similar considerations.
-func NewStaticV4(id, secret, token string) *Credentials {
- return NewStatic(id, secret, token, SignatureV4)
-}
-
-// NewStatic returns a pointer to a new Credentials object
-// wrapping a static credentials value provider.
-func NewStatic(id, secret, token string, signerType SignatureType) *Credentials {
- return New(&Static{
- Value: Value{
- AccessKeyID: id,
- SecretAccessKey: secret,
- SessionToken: token,
- SignerType: signerType,
- },
- })
-}
-
-// Retrieve returns the static credentials.
-func (s *Static) Retrieve() (Value, error) {
- if s.AccessKeyID == "" || s.SecretAccessKey == "" {
- // Anonymous is not an error
- return Value{SignerType: SignatureAnonymous}, nil
- }
- return s.Value, nil
-}
-
-// IsExpired returns if the credentials are expired.
-//
-// For Static, the credentials never expired.
-func (s *Static) IsExpired() bool {
- return false
-}
diff --git a/vendor/github.com/minio/minio-go/pkg/credentials/static_test.go b/vendor/github.com/minio/minio-go/pkg/credentials/static_test.go
deleted file mode 100644
index 491b1554b..000000000
--- a/vendor/github.com/minio/minio-go/pkg/credentials/static_test.go
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Minio Go Library for Amazon S3 Compatible Cloud Storage
- * (C) 2017 Minio, Inc.
- *
- * 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 credentials
-
-import "testing"
-
-func TestStaticGet(t *testing.T) {
- creds := NewStatic("UXHW", "SECRET", "", SignatureV4)
- credValues, err := creds.Get()
- if err != nil {
- t.Fatal(err)
- }
-
- if "UXHW" != credValues.AccessKeyID {
- t.Errorf("Expected access key ID to match \"UXHW\", got %s", credValues.AccessKeyID)
- }
- if "SECRET" != credValues.SecretAccessKey {
- t.Errorf("Expected secret access key to match \"SECRET\", got %s", credValues.SecretAccessKey)
- }
-
- if credValues.SessionToken != "" {
- t.Error("Expected session token to match")
- }
-
- if credValues.SignerType != SignatureV4 {
- t.Errorf("Expected 'S3v4', got %s", credValues.SignerType)
- }
-
- if creds.IsExpired() {
- t.Error("Static credentials should never expire")
- }
-
- creds = NewStatic("", "", "", SignatureDefault)
- credValues, err = creds.Get()
- if err != nil {
- t.Fatal(err)
- }
-
- if "" != credValues.AccessKeyID {
- t.Errorf("Expected access key ID to match empty string, got %s", credValues.AccessKeyID)
- }
- if "" != credValues.SecretAccessKey {
- t.Errorf("Expected secret access key to match empty string, got %s", credValues.SecretAccessKey)
- }
-
- if !credValues.SignerType.IsAnonymous() {
- t.Errorf("Expected 'Anonymous', got %s", credValues.SignerType)
- }
-
- if creds.IsExpired() {
- t.Error("Static credentials should never expire")
- }
-}
diff --git a/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-streaming.go b/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-streaming.go
index c2f0baee6..755fd1ac5 100644
--- a/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-streaming.go
+++ b/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-streaming.go
@@ -92,12 +92,9 @@ func buildChunkStringToSign(t time.Time, region, previousSig string, chunkData [
// prepareStreamingRequest - prepares a request with appropriate
// headers before computing the seed signature.
-func prepareStreamingRequest(req *http.Request, sessionToken string, dataLen int64, timestamp time.Time) {
+func prepareStreamingRequest(req *http.Request, dataLen int64, timestamp time.Time) {
// Set x-amz-content-sha256 header.
req.Header.Set("X-Amz-Content-Sha256", streamingSignAlgorithm)
- if sessionToken != "" {
- req.Header.Set("X-Amz-Security-Token", sessionToken)
- }
req.Header.Set("Content-Encoding", streamingEncoding)
req.Header.Set("X-Amz-Date", timestamp.Format(iso8601DateFormat))
@@ -141,7 +138,6 @@ func (s *StreamingReader) setSeedSignature(req *http.Request) {
type StreamingReader struct {
accessKeyID string
secretAccessKey string
- sessionToken string
region string
prevSignature string
seedSignature string
@@ -199,17 +195,16 @@ func (s *StreamingReader) setStreamingAuthHeader(req *http.Request) {
// StreamingSignV4 - provides chunked upload signatureV4 support by
// implementing io.Reader.
-func StreamingSignV4(req *http.Request, accessKeyID, secretAccessKey, sessionToken,
+func StreamingSignV4(req *http.Request, accessKeyID, secretAccessKey,
region string, dataLen int64, reqTime time.Time) *http.Request {
// Set headers needed for streaming signature.
- prepareStreamingRequest(req, sessionToken, dataLen, reqTime)
+ prepareStreamingRequest(req, dataLen, reqTime)
stReader := &StreamingReader{
baseReadCloser: req.Body,
accessKeyID: accessKeyID,
secretAccessKey: secretAccessKey,
- sessionToken: sessionToken,
region: region,
reqTime: reqTime,
chunkBuf: make([]byte, payloadChunkSize),
diff --git a/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-streaming_test.go b/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-streaming_test.go
index 1f49f2234..084a0dbab 100644
--- a/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-streaming_test.go
+++ b/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-streaming_test.go
@@ -39,7 +39,7 @@ func TestGetSeedSignature(t *testing.T) {
t.Fatalf("Failed to parse time - %v", err)
}
- req = StreamingSignV4(req, accessKeyID, secretAccessKeyID, "", "us-east-1", int64(dataLen), reqTime)
+ req = StreamingSignV4(req, accessKeyID, secretAccessKeyID, "us-east-1", int64(dataLen), reqTime)
actualSeedSignature := req.Body.(*StreamingReader).seedSignature
expectedSeedSignature := "007480502de61457e955731b0f5d191f7e6f54a8a0f6cc7974a5ebd887965686"
@@ -72,7 +72,7 @@ func TestSetStreamingAuthorization(t *testing.T) {
dataLen := int64(65 * 1024)
reqTime, _ := time.Parse(iso8601DateFormat, "20130524T000000Z")
- req = StreamingSignV4(req, accessKeyID, secretAccessKeyID, "", location, dataLen, reqTime)
+ req = StreamingSignV4(req, accessKeyID, secretAccessKeyID, location, dataLen, reqTime)
expectedAuthorization := "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request,SignedHeaders=content-encoding;host;x-amz-content-sha256;x-amz-date;x-amz-decoded-content-length;x-amz-storage-class,Signature=007480502de61457e955731b0f5d191f7e6f54a8a0f6cc7974a5ebd887965686"
@@ -96,7 +96,7 @@ func TestStreamingReader(t *testing.T) {
baseReader := ioutil.NopCloser(bytes.NewReader(bytes.Repeat([]byte("a"), 65*1024)))
req.Body = baseReader
- req = StreamingSignV4(req, accessKeyID, secretAccessKeyID, "", location, dataLen, reqTime)
+ req = StreamingSignV4(req, accessKeyID, secretAccessKeyID, location, dataLen, reqTime)
b, err := ioutil.ReadAll(req.Body)
if err != nil {
diff --git a/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-v4.go b/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-v4.go
index 0d75dc162..245fb08c3 100644
--- a/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-v4.go
+++ b/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature-v4.go
@@ -206,7 +206,7 @@ func getStringToSignV4(t time.Time, location, canonicalRequest string) string {
// PreSignV4 presign the request, in accordance with
// http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html.
-func PreSignV4(req http.Request, accessKeyID, secretAccessKey, sessionToken, location string, expires int64) *http.Request {
+func PreSignV4(req http.Request, accessKeyID, secretAccessKey, location string, expires int64) *http.Request {
// Presign is not needed for anonymous credentials.
if accessKeyID == "" || secretAccessKey == "" {
return &req
@@ -228,10 +228,6 @@ func PreSignV4(req http.Request, accessKeyID, secretAccessKey, sessionToken, loc
query.Set("X-Amz-Expires", strconv.FormatInt(expires, 10))
query.Set("X-Amz-SignedHeaders", signedHeaders)
query.Set("X-Amz-Credential", credential)
- // Set session token if available.
- if sessionToken != "" {
- query.Set("X-Amz-Security-Token", sessionToken)
- }
req.URL.RawQuery = query.Encode()
// Get canonical request.
@@ -264,7 +260,7 @@ func PostPresignSignatureV4(policyBase64 string, t time.Time, secretAccessKey, l
// SignV4 sign the request before Do(), in accordance with
// http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html.
-func SignV4(req http.Request, accessKeyID, secretAccessKey, sessionToken, location string) *http.Request {
+func SignV4(req http.Request, accessKeyID, secretAccessKey, location string) *http.Request {
// Signature calculation is not needed for anonymous credentials.
if accessKeyID == "" || secretAccessKey == "" {
return &req
@@ -276,11 +272,6 @@ func SignV4(req http.Request, accessKeyID, secretAccessKey, sessionToken, locati
// Set x-amz-date.
req.Header.Set("X-Amz-Date", t.Format(iso8601DateFormat))
- // Set session token if available.
- if sessionToken != "" {
- req.Header.Set("X-Amz-Security-Token", sessionToken)
- }
-
// Get canonical request.
canonicalRequest := getCanonicalRequest(req, v4IgnoredHeaders)
diff --git a/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature_test.go b/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature_test.go
index 85ff063df..6f5ba1895 100644
--- a/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature_test.go
+++ b/vendor/github.com/minio/minio-go/pkg/s3signer/request-signature_test.go
@@ -28,12 +28,12 @@ func TestSignatureCalculation(t *testing.T) {
if err != nil {
t.Fatal("Error:", err)
}
- req = SignV4(*req, "", "", "", "us-east-1")
+ req = SignV4(*req, "", "", "us-east-1")
if req.Header.Get("Authorization") != "" {
t.Fatal("Error: anonymous credentials should not have Authorization header.")
}
- req = PreSignV4(*req, "", "", "", "us-east-1", 0)
+ req = PreSignV4(*req, "", "", "us-east-1", 0)
if strings.Contains(req.URL.RawQuery, "X-Amz-Signature") {
t.Fatal("Error: anonymous credentials should not have Signature query resource.")
}
@@ -48,12 +48,12 @@ func TestSignatureCalculation(t *testing.T) {
t.Fatal("Error: anonymous credentials should not have Signature query resource.")
}
- req = SignV4(*req, "ACCESS-KEY", "SECRET-KEY", "", "us-east-1")
+ req = SignV4(*req, "ACCESS-KEY", "SECRET-KEY", "us-east-1")
if req.Header.Get("Authorization") == "" {
t.Fatal("Error: normal credentials should have Authorization header.")
}
- req = PreSignV4(*req, "ACCESS-KEY", "SECRET-KEY", "", "us-east-1", 0)
+ req = PreSignV4(*req, "ACCESS-KEY", "SECRET-KEY", "us-east-1", 0)
if !strings.Contains(req.URL.RawQuery, "X-Amz-Signature") {
t.Fatal("Error: normal credentials should have Signature query resource.")
}
diff --git a/vendor/github.com/minio/minio-go/signature-type.go b/vendor/github.com/minio/minio-go/signature-type.go
new file mode 100644
index 000000000..f9a57c3f1
--- /dev/null
+++ b/vendor/github.com/minio/minio-go/signature-type.go
@@ -0,0 +1,45 @@
+/*
+ * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 Minio, Inc.
+ *
+ * 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 minio
+
+// SignatureType is type of Authorization requested for a given HTTP request.
+type SignatureType int
+
+// Different types of supported signatures - default is Latest i.e SignatureV4.
+const (
+ Latest SignatureType = iota
+ SignatureV4
+ SignatureV2
+ SignatureV4Streaming
+)
+
+var emptySHA256 = sum256(nil)
+
+// isV2 - is signature SignatureV2?
+func (s SignatureType) isV2() bool {
+ return s == SignatureV2
+}
+
+// isV4 - is signature SignatureV4?
+func (s SignatureType) isV4() bool {
+ return s == SignatureV4 || s == Latest
+}
+
+// isStreamingV4 - is signature SignatureV4Streaming?
+func (s SignatureType) isStreamingV4() bool {
+ return s == SignatureV4Streaming
+}
diff --git a/vendor/github.com/minio/minio-go/utils.go b/vendor/github.com/minio/minio-go/utils.go
index 4fa43b1ff..93cd1712f 100644
--- a/vendor/github.com/minio/minio-go/utils.go
+++ b/vendor/github.com/minio/minio-go/utils.go
@@ -110,8 +110,6 @@ func closeResponse(resp *http.Response) {
}
}
-var emptySHA256 = sum256(nil)
-
// Sentinel URL is the default url value which is invalid.
var sentinelURL = url.URL{}
diff --git a/vendor/github.com/mitchellh/mapstructure/decode_hooks.go b/vendor/github.com/mitchellh/mapstructure/decode_hooks.go
index acdaadefe..afcfd5eed 100644
--- a/vendor/github.com/mitchellh/mapstructure/decode_hooks.go
+++ b/vendor/github.com/mitchellh/mapstructure/decode_hooks.go
@@ -38,12 +38,6 @@ func DecodeHookExec(
raw DecodeHookFunc,
from reflect.Type, to reflect.Type,
data interface{}) (interface{}, error) {
- // Build our arguments that reflect expects
- argVals := make([]reflect.Value, 3)
- argVals[0] = reflect.ValueOf(from)
- argVals[1] = reflect.ValueOf(to)
- argVals[2] = reflect.ValueOf(data)
-
switch f := typedDecodeHook(raw).(type) {
case DecodeHookFuncType:
return f(from, to, data)
diff --git a/vendor/github.com/mssola/user_agent/.travis.yml b/vendor/github.com/mssola/user_agent/.travis.yml
index 33c596acb..add0c8a6c 100644
--- a/vendor/github.com/mssola/user_agent/.travis.yml
+++ b/vendor/github.com/mssola/user_agent/.travis.yml
@@ -4,8 +4,6 @@ go:
- 1.1
- 1.2
- 1.3
- - 1.4
- - 1.5
- tip
matrix:
allow_failures:
diff --git a/vendor/github.com/mssola/user_agent/LICENSE b/vendor/github.com/mssola/user_agent/LICENSE
index ede19fbfb..c02b64473 100644
--- a/vendor/github.com/mssola/user_agent/LICENSE
+++ b/vendor/github.com/mssola/user_agent/LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2012-2017 Miquel Sabaté Solà
+Copyright (c) 2012-2014 Miquel Sabaté Solà
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
diff --git a/vendor/github.com/mssola/user_agent/README.md b/vendor/github.com/mssola/user_agent/README.md
index 7b5028f83..971902560 100644
--- a/vendor/github.com/mssola/user_agent/README.md
+++ b/vendor/github.com/mssola/user_agent/README.md
@@ -48,4 +48,4 @@ func main() {
}
~~~
-Copyright &copy; 2012-2017 Miquel Sabaté Solà, released under the MIT License.
+Copyright &copy; 2012-2014 Miquel Sabaté Solà, released under the MIT License.
diff --git a/vendor/github.com/mssola/user_agent/all_test.go b/vendor/github.com/mssola/user_agent/all_test.go
index fb0cf054e..4f3c03198 100644
--- a/vendor/github.com/mssola/user_agent/all_test.go
+++ b/vendor/github.com/mssola/user_agent/all_test.go
@@ -1,4 +1,4 @@
-// Copyright (C) 2012-2017 Miquel Sabaté Solà <mikisabate@gmail.com>
+// Copyright (C) 2012-2014 Miquel Sabaté Solà <mikisabate@gmail.com>
// This file is licensed under the MIT license.
// See the LICENSE file.
@@ -6,514 +6,189 @@ package user_agent
import (
"fmt"
- "reflect"
"testing"
)
// Slice that contains all the tests. Each test is contained in a struct
-// that groups the title of the test, the User-Agent string to be tested and the expected value.
+// that groups the name of the test and the User-Agent string to be tested.
var uastrings = []struct {
- title string
- ua string
- expected string
- expectedOS *OSInfo
+ name string
+ ua string
}{
// Bots
- {
- title: "GoogleBot",
- ua: "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
- expected: "Mozilla:5.0 Browser:Googlebot-2.1 Bot:true Mobile:false",
- },
- {
- title: "GoogleBotSmartphone",
- ua: "Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
- expected: "Mozilla:5.0 Browser:Googlebot-2.1 Bot:true Mobile:true",
- },
- {
- title: "BingBot",
- ua: "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)",
- expected: "Mozilla:5.0 Browser:bingbot-2.0 Bot:true Mobile:false",
- },
- {
- title: "BaiduBot",
- ua: "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)",
- expected: "Mozilla:5.0 Browser:Baiduspider-2.0 Bot:true Mobile:false",
- },
- {
- title: "Twitterbot",
- ua: "Twitterbot",
- expected: "Browser:Twitterbot Bot:true Mobile:false",
- },
- {
- title: "YahooBot",
- ua: "Mozilla/5.0 (compatible; Yahoo! Slurp; http://help.yahoo.com/help/us/ysearch/slurp)",
- expected: "Mozilla:5.0 Browser:Yahoo! Slurp Bot:true Mobile:false",
- },
- {
- title: "FacebookExternalHit",
- ua: "facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)",
- expected: "Browser:facebookexternalhit-1.1 Bot:true Mobile:false",
- },
- {
- title: "FacebookPlatform",
- ua: "facebookplatform/1.0 (+http://developers.facebook.com)",
- expected: "Browser:facebookplatform-1.0 Bot:true Mobile:false",
- },
- {
- title: "FaceBot",
- ua: "Facebot",
- expected: "Browser:Facebot Bot:true Mobile:false",
- },
- {
- title: "NutchCVS",
- ua: "NutchCVS/0.8-dev (Nutch; http://lucene.apache.org/nutch/bot.html; nutch-agent@lucene.apache.org)",
- expected: "Browser:NutchCVS Bot:true Mobile:false",
- },
- {
- title: "MJ12bot",
- ua: "Mozilla/5.0 (compatible; MJ12bot/v1.2.4; http://www.majestic12.co.uk/bot.php?+)",
- expected: "Mozilla:5.0 Browser:MJ12bot-v1.2.4 Bot:true Mobile:false",
- },
- {
- title: "MJ12bot",
- ua: "MJ12bot/v1.0.8 (http://majestic12.co.uk/bot.php?+)",
- expected: "Browser:MJ12bot Bot:true Mobile:false",
- },
- {
- title: "AhrefsBot",
- ua: "Mozilla/5.0 (compatible; AhrefsBot/4.0; +http://ahrefs.com/robot/)",
- expected: "Mozilla:5.0 Browser:AhrefsBot-4.0 Bot:true Mobile:false",
- },
+ {"GoogleBot", "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"},
+ {"GoogleBotSmartphone", "Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"},
+ {"BingBot", "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)"},
+ {"BaiduBot", "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)"},
+ {"Twitterbot", "Twitterbot"},
+ {"YahooBot", "Mozilla/5.0 (compatible; Yahoo! Slurp; http://help.yahoo.com/help/us/ysearch/slurp)"},
+ {"FacebookExternalHit", "facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)"},
+ {"FacebookPlatform", "facebookplatform/1.0 (+http://developers.facebook.com)"},
+ {"FaceBot", "Facebot"},
// Internet Explorer
- {
- title: "IE10",
- ua: "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)",
- expected: "Mozilla:5.0 Platform:Windows OS:Windows 8 Browser:Internet Explorer-10.0 Engine:Trident Bot:false Mobile:false",
- expectedOS: &OSInfo{"Windows 8", "Windows", "8"},
- },
- {
- title: "Tablet",
- ua: "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.2; ARM; Trident/6.0; Touch; .NET4.0E; .NET4.0C; Tablet PC 2.0)",
- expected: "Mozilla:4.0 Platform:Windows OS:Windows 8 Browser:Internet Explorer-10.0 Engine:Trident Bot:false Mobile:false",
- },
- {
- title: "Touch",
- ua: "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; ARM; Trident/6.0; Touch)",
- expected: "Mozilla:5.0 Platform:Windows OS:Windows 8 Browser:Internet Explorer-10.0 Engine:Trident Bot:false Mobile:false",
- },
- {
- title: "Phone",
- ua: "Mozilla/4.0 (compatible; MSIE 7.0; Windows Phone OS 7.0; Trident/3.1; IEMobile/7.0; SAMSUNG; SGH-i917)",
- expected: "Mozilla:4.0 Platform:Windows OS:Windows Phone OS 7.0 Browser:Internet Explorer-7.0 Engine:Trident Bot:false Mobile:true",
- expectedOS: &OSInfo{"Windows Phone OS 7.0", "Windows Phone OS", "7.0"},
- },
- {
- title: "IE6",
- ua: "Mozilla/4.0 (compatible; MSIE6.0; Windows NT 5.0; .NET CLR 1.1.4322)",
- expected: "Mozilla:4.0 Platform:Windows OS:Windows 2000 Browser:Internet Explorer-6.0 Engine:Trident Bot:false Mobile:false",
- expectedOS: &OSInfo{"Windows 2000", "Windows", "2000"},
- },
- {
- title: "IE8Compatibility",
- ua: "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; MS-RTC LM 8)",
- expected: "Mozilla:4.0 Platform:Windows OS:Windows 7 Browser:Internet Explorer-8.0 Engine:Trident Bot:false Mobile:false",
- expectedOS: &OSInfo{"Windows 7", "Windows", "7"},
- },
- {
- title: "IE10Compatibility",
- ua: "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; MS-RTC LM 8)",
- expected: "Mozilla:4.0 Platform:Windows OS:Windows 7 Browser:Internet Explorer-10.0 Engine:Trident Bot:false Mobile:false",
- },
- {
- title: "IE11Win81",
- ua: "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko",
- expected: "Mozilla:5.0 Platform:Windows OS:Windows 8.1 Browser:Internet Explorer-11.0 Engine:Trident Bot:false Mobile:false",
- expectedOS: &OSInfo{"Windows 8.1", "Windows", "8.1"},
- },
- {
- title: "IE11Win7",
- ua: "Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko",
- expected: "Mozilla:5.0 Platform:Windows OS:Windows 7 Browser:Internet Explorer-11.0 Engine:Trident Bot:false Mobile:false",
- },
- {
- title: "IE11b32Win7b64",
- ua: "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko",
- expected: "Mozilla:5.0 Platform:Windows OS:Windows 7 Browser:Internet Explorer-11.0 Engine:Trident Bot:false Mobile:false",
- },
- {
- title: "IE11b32Win7b64MDDRJS",
- ua: "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; MDDRJS; rv:11.0) like Gecko",
- expected: "Mozilla:5.0 Platform:Windows OS:Windows 7 Browser:Internet Explorer-11.0 Engine:Trident Bot:false Mobile:false",
- },
- {
- title: "IE11Compatibility",
- ua: "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.3; Trident/7.0)",
- expected: "Mozilla:4.0 Platform:Windows OS:Windows 8.1 Browser:Internet Explorer-7.0 Engine:Trident Bot:false Mobile:false",
- },
-
- // Microsoft Edge
- {
- title: "EdgeDesktop",
- ua: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240",
- expected: "Mozilla:5.0 Platform:Windows OS:Windows 10 Browser:Edge-12.10240 Engine:EdgeHTML Bot:false Mobile:false",
- expectedOS: &OSInfo{"Windows 10", "Windows", "10"},
- },
- {
- title: "EdgeMobile",
- ua: "Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; DEVICE INFO) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Mobile Safari/537.36 Edge/12.10240",
- expected: "Mozilla:5.0 Platform:Windows OS:Windows Phone 10.0 Browser:Edge-12.10240 Engine:EdgeHTML Bot:false Mobile:true",
- },
+ {"IE10", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)"},
+ {"Tablet", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.2; ARM; Trident/6.0; Touch; .NET4.0E; .NET4.0C; Tablet PC 2.0)"},
+ {"Touch", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; ARM; Trident/6.0; Touch)"},
+ {"Phone", "Mozilla/4.0 (compatible; MSIE 7.0; Windows Phone OS 7.0; Trident/3.1; IEMobile/7.0; SAMSUNG; SGH-i917)"},
+ {"IE6", "Mozilla/4.0 (compatible; MSIE6.0; Windows NT 5.0; .NET CLR 1.1.4322)"},
+ {"IE8Compatibility", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; MS-RTC LM 8)"},
+ {"IE10Compatibility", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; MS-RTC LM 8)"},
+ {"IE11Win81", "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko"},
+ {"IE11Win7", "Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko"},
+ {"IE11b32Win7b64", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"},
+ {"IE11b32Win7b64MDDRJS", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; MDDRJS; rv:11.0) like Gecko"},
+ {"IE11Compatibility", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.3; Trident/7.0)"},
// Gecko
- {
- title: "FirefoxMac",
- ua: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0b8) Gecko/20100101 Firefox/4.0b8",
- expected: "Mozilla:5.0 Platform:Macintosh OS:Intel Mac OS X 10.6 Browser:Firefox-4.0b8 Engine:Gecko-20100101 Bot:false Mobile:false",
- expectedOS: &OSInfo{"Intel Mac OS X 10.6", "Mac OS X", "10.6"},
- },
- {
- title: "FirefoxMacLoc",
- ua: "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13",
- expected: "Mozilla:5.0 Platform:Macintosh OS:Intel Mac OS X 10.6 Localization:en-US Browser:Firefox-3.6.13 Engine:Gecko-20101203 Bot:false Mobile:false",
- expectedOS: &OSInfo{"Intel Mac OS X 10.6", "Mac OS X", "10.6"},
- },
- {
- title: "FirefoxLinux",
- ua: "Mozilla/5.0 (X11; Linux x86_64; rv:17.0) Gecko/20100101 Firefox/17.0",
- expected: "Mozilla:5.0 Platform:X11 OS:Linux x86_64 Browser:Firefox-17.0 Engine:Gecko-20100101 Bot:false Mobile:false",
- expectedOS: &OSInfo{"Linux x86_64", "Linux", ""},
- },
- {
- title: "FirefoxLinux - Ubuntu V50",
- ua: "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0",
- expected: "Mozilla:5.0 Platform:X11 OS:Ubuntu Browser:Firefox-50.0 Engine:Gecko-20100101 Bot:false Mobile:false",
- expectedOS: &OSInfo{"Ubuntu", "Ubuntu", ""},
- },
- {
- title: "FirefoxWin",
- ua: "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14",
- expected: "Mozilla:5.0 Platform:Windows OS:Windows XP Localization:en-US Browser:Firefox-2.0.0.14 Engine:Gecko-20080404 Bot:false Mobile:false",
- expectedOS: &OSInfo{"Windows XP", "Windows", "XP"},
- },
- {
- title: "Firefox29Win7",
- ua: "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0",
- expected: "Mozilla:5.0 Platform:Windows OS:Windows 7 Browser:Firefox-29.0 Engine:Gecko-20100101 Bot:false Mobile:false",
- },
- {
- title: "CaminoMac",
- ua: "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en; rv:1.8.1.14) Gecko/20080409 Camino/1.6 (like Firefox/2.0.0.14)",
- expected: "Mozilla:5.0 Platform:Macintosh OS:Intel Mac OS X Localization:en Browser:Camino-1.6 Engine:Gecko-20080409 Bot:false Mobile:false",
- expectedOS: &OSInfo{"Intel Mac OS X", "Mac OS X", ""},
- },
- {
- title: "Iceweasel",
- ua: "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1) Gecko/20061024 Iceweasel/2.0 (Debian-2.0+dfsg-1)",
- expected: "Mozilla:5.0 Platform:X11 OS:Linux i686 Localization:en-US Browser:Iceweasel-2.0 Engine:Gecko-20061024 Bot:false Mobile:false",
- expectedOS: &OSInfo{"Linux i686", "Linux", ""},
- },
- {
- title: "SeaMonkey",
- ua: "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.1.4) Gecko/20091017 SeaMonkey/2.0",
- expected: "Mozilla:5.0 Platform:Macintosh OS:Intel Mac OS X 10.6 Localization:en-US Browser:SeaMonkey-2.0 Engine:Gecko-20091017 Bot:false Mobile:false",
- },
- {
- title: "AndroidFirefox",
- ua: "Mozilla/5.0 (Android; Mobile; rv:17.0) Gecko/17.0 Firefox/17.0",
- expected: "Mozilla:5.0 Platform:Mobile OS:Android Browser:Firefox-17.0 Engine:Gecko-17.0 Bot:false Mobile:true",
- },
- {
- title: "AndroidFirefoxTablet",
- ua: "Mozilla/5.0 (Android; Tablet; rv:26.0) Gecko/26.0 Firefox/26.0",
- expected: "Mozilla:5.0 Platform:Tablet OS:Android Browser:Firefox-26.0 Engine:Gecko-26.0 Bot:false Mobile:true",
- expectedOS: &OSInfo{"Android", "Android", ""},
- },
- {
- title: "FirefoxOS",
- ua: "Mozilla/5.0 (Mobile; rv:26.0) Gecko/26.0 Firefox/26.0",
- expected: "Mozilla:5.0 Platform:Mobile OS:FirefoxOS Browser:Firefox-26.0 Engine:Gecko-26.0 Bot:false Mobile:true",
- expectedOS: &OSInfo{"FirefoxOS", "FirefoxOS", ""},
- },
- {
- title: "FirefoxOSTablet",
- ua: "Mozilla/5.0 (Tablet; rv:26.0) Gecko/26.0 Firefox/26.0",
- expected: "Mozilla:5.0 Platform:Tablet OS:FirefoxOS Browser:Firefox-26.0 Engine:Gecko-26.0 Bot:false Mobile:true",
- },
- {
- title: "FirefoxWinXP",
- ua: "Mozilla/5.0 (Windows NT 5.2; rv:31.0) Gecko/20100101 Firefox/31.0",
- expected: "Mozilla:5.0 Platform:Windows OS:Windows XP x64 Edition Browser:Firefox-31.0 Engine:Gecko-20100101 Bot:false Mobile:false",
- expectedOS: &OSInfo{"Windows XP x64 Edition", "Windows", "XP"},
- },
- {
- title: "FirefoxMRA",
- ua: "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:24.0) Gecko/20130405 MRA 5.5 (build 02842) Firefox/24.0 (.NET CLR 3.5.30729)",
- expected: "Mozilla:5.0 Platform:Windows OS:Windows XP Localization:en-US Browser:Firefox-24.0 Engine:Gecko-20130405 Bot:false Mobile:false",
- },
+ {"FirefoxMac", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0b8) Gecko/20100101 Firefox/4.0b8"},
+ {"FirefoxMacLoc", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13"},
+ {"FirefoxLinux", "Mozilla/5.0 (X11; Linux x86_64; rv:17.0) Gecko/20100101 Firefox/17.0"},
+ {"FirefoxWin", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14"},
+ {"Firefox29Win7", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"},
+ {"CaminoMac", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en; rv:1.8.1.14) Gecko/20080409 Camino/1.6 (like Firefox/2.0.0.14)"},
+ {"Iceweasel", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1) Gecko/20061024 Iceweasel/2.0 (Debian-2.0+dfsg-1)"},
+ {"SeaMonkey", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.1.4) Gecko/20091017 SeaMonkey/2.0"},
+ {"AndroidFirefox", "Mozilla/5.0 (Android; Mobile; rv:17.0) Gecko/17.0 Firefox/17.0"},
+ {"AndroidFirefoxTablet", "Mozilla/5.0 (Android; Tablet; rv:26.0) Gecko/26.0 Firefox/26.0"},
+ {"FirefoxOS", "Mozilla/5.0 (Mobile; rv:26.0) Gecko/26.0 Firefox/26.0"},
+ {"FirefoxOSTablet", "Mozilla/5.0 (Tablet; rv:26.0) Gecko/26.0 Firefox/26.0"},
+ {"FirefoxWinXP", "Mozilla/5.0 (Windows NT 5.2; rv:31.0) Gecko/20100101 Firefox/31.0"},
+ {"FirefoxMRA", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:24.0) Gecko/20130405 MRA 5.5 (build 02842) Firefox/24.0 (.NET CLR 3.5.30729)"},
// Opera
- {
- title: "OperaMac",
- ua: "Opera/9.27 (Macintosh; Intel Mac OS X; U; en)",
- expected: "Platform:Macintosh OS:Intel Mac OS X Localization:en Browser:Opera-9.27 Engine:Presto Bot:false Mobile:false",
- expectedOS: &OSInfo{"Intel Mac OS X", "Mac OS X", ""},
- },
- {
- title: "OperaWin",
- ua: "Opera/9.27 (Windows NT 5.1; U; en)",
- expected: "Platform:Windows OS:Windows XP Localization:en Browser:Opera-9.27 Engine:Presto Bot:false Mobile:false",
- },
- {
- title: "OperaWinNoLocale",
- ua: "Opera/9.80 (Windows NT 5.1) Presto/2.12.388 Version/12.10",
- expected: "Platform:Windows OS:Windows XP Browser:Opera-9.80 Engine:Presto-2.12.388 Bot:false Mobile:false",
- },
- {
- title: "OperaWin2Comment",
- ua: "Opera/9.80 (Windows NT 6.0; WOW64) Presto/2.12.388 Version/12.15",
- expected: "Platform:Windows OS:Windows Vista Browser:Opera-9.80 Engine:Presto-2.12.388 Bot:false Mobile:false",
- expectedOS: &OSInfo{"Windows Vista", "Windows", "Vista"},
- },
- {
- title: "OperaMinimal",
- ua: "Opera/9.80",
- expected: "Browser:Opera-9.80 Engine:Presto Bot:false Mobile:false",
- },
- {
- title: "OperaFull",
- ua: "Opera/9.80 (Windows NT 6.0; U; en) Presto/2.2.15 Version/10.10",
- expected: "Platform:Windows OS:Windows Vista Localization:en Browser:Opera-9.80 Engine:Presto-2.2.15 Bot:false Mobile:false",
- },
- {
- title: "OperaLinux",
- ua: "Opera/9.80 (X11; Linux x86_64) Presto/2.12.388 Version/12.10",
- expected: "Platform:X11 OS:Linux x86_64 Browser:Opera-9.80 Engine:Presto-2.12.388 Bot:false Mobile:false",
- },
- {
- title: "OperaLinux - Ubuntu V41",
- ua: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36 OPR/41.0.2353.69",
- expected: "Mozilla:5.0 Platform:X11 OS:Linux x86_64 Browser:Opera-41.0.2353.69 Engine:AppleWebKit-537.36 Bot:false Mobile:false",
- expectedOS: &OSInfo{"Linux x86_64", "Linux", ""},
- },
- {
- title: "OperaAndroid",
- ua: "Opera/9.80 (Android 4.2.1; Linux; Opera Mobi/ADR-1212030829) Presto/2.11.355 Version/12.10",
- expected: "Platform:Android 4.2.1 OS:Linux Browser:Opera-9.80 Engine:Presto-2.11.355 Bot:false Mobile:true",
- expectedOS: &OSInfo{"Linux", "Linux", ""},
- },
- {
- title: "OperaNested",
- ua: "Opera/9.80 (Windows NT 5.1; MRA 6.0 (build 5831)) Presto/2.12.388 Version/12.10",
- expected: "Platform:Windows OS:Windows XP Browser:Opera-9.80 Engine:Presto-2.12.388 Bot:false Mobile:false",
- },
- {
- title: "OperaMRA",
- ua: "Opera/9.80 (Windows NT 6.1; U; MRA 5.8 (build 4139); en) Presto/2.9.168 Version/11.50",
- expected: "Platform:Windows OS:Windows 7 Localization:en Browser:Opera-9.80 Engine:Presto-2.9.168 Bot:false Mobile:false",
- },
+ {"OperaMac", "Opera/9.27 (Macintosh; Intel Mac OS X; U; en)"},
+ {"OperaWin", "Opera/9.27 (Windows NT 5.1; U; en)"},
+ {"OperaWinNoLocale", "Opera/9.80 (Windows NT 5.1) Presto/2.12.388 Version/12.10"},
+ {"OperaWin2Comment", "Opera/9.80 (Windows NT 6.0; WOW64) Presto/2.12.388 Version/12.15"},
+ {"OperaMinimal", "Opera/9.80"},
+ {"OperaFull", "Opera/9.80 (Windows NT 6.0; U; en) Presto/2.2.15 Version/10.10"},
+ {"OperaLinux", "Opera/9.80 (X11; Linux x86_64) Presto/2.12.388 Version/12.10"},
+ {"OperaAndroid", "Opera/9.80 (Android 4.2.1; Linux; Opera Mobi/ADR-1212030829) Presto/2.11.355 Version/12.10"},
+ {"OperaNested", "Opera/9.80 (Windows NT 5.1; MRA 6.0 (build 5831)) Presto/2.12.388 Version/12.10"},
+ {"OperaMRA", "Opera/9.80 (Windows NT 6.1; U; MRA 5.8 (build 4139); en) Presto/2.9.168 Version/11.50"},
// Other
- {
- title: "Empty",
- ua: "",
- expected: "Bot:false Mobile:false",
- },
- {
- title: "Nil",
- ua: "nil",
- expected: "Browser:nil Bot:false Mobile:false",
- },
- {
- title: "Compatible",
- ua: "Mozilla/4.0 (compatible)",
- expected: "Browser:Mozilla-4.0 Bot:false Mobile:false",
- },
- {
- title: "Mozilla",
- ua: "Mozilla/5.0",
- expected: "Browser:Mozilla-5.0 Bot:false Mobile:false",
- },
- {
- title: "Amaya",
- ua: "amaya/9.51 libwww/5.4.0",
- expected: "Browser:amaya-9.51 Engine:libwww-5.4.0 Bot:false Mobile:false",
- },
- {
- title: "Rails",
- ua: "Rails Testing",
- expected: "Browser:Rails Engine:Testing Bot:false Mobile:false",
- },
- {
- title: "Python",
- ua: "Python-urllib/2.7",
- expected: "Browser:Python-urllib-2.7 Bot:false Mobile:false",
- },
- {
- title: "Curl",
- ua: "curl/7.28.1",
- expected: "Browser:curl-7.28.1 Bot:false Mobile:false",
- },
+ {"Empty", ""},
+ {"Nil", "nil"},
+ {"Compatible", "Mozilla/4.0 (compatible)"},
+ {"Mozilla", "Mozilla/5.0"},
+ {"Amaya", "amaya/9.51 libwww/5.4.0"},
+ {"Rails", "Rails Testing"},
+ {"Python", "Python-urllib/2.7"},
+ {"Curl", "curl/7.28.1"},
// WebKit
- {
- title: "ChromeLinux",
- ua: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11",
- expected: "Mozilla:5.0 Platform:X11 OS:Linux x86_64 Browser:Chrome-23.0.1271.97 Engine:AppleWebKit-537.11 Bot:false Mobile:false",
- expectedOS: &OSInfo{"Linux x86_64", "Linux", ""},
- },
- {
- title: "ChromeLinux - Ubuntu V55",
- ua: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36",
- expected: "Mozilla:5.0 Platform:X11 OS:Linux x86_64 Browser:Chrome-55.0.2883.75 Engine:AppleWebKit-537.36 Bot:false Mobile:false",
- },
- {
- title: "ChromeWin7",
- ua: "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19",
- expected: "Mozilla:5.0 Platform:Windows OS:Windows 7 Browser:Chrome-18.0.1025.168 Engine:AppleWebKit-535.19 Bot:false Mobile:false",
- },
- {
- title: "ChromeMinimal",
- ua: "Mozilla/5.0 AppleWebKit/534.10 Chrome/8.0.552.215 Safari/534.10",
- expected: "Mozilla:5.0 Browser:Chrome-8.0.552.215 Engine:AppleWebKit-534.10 Bot:false Mobile:false",
- },
- {
- title: "ChromeMac",
- ua: "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.231 Safari/534.10",
- expected: "Mozilla:5.0 Platform:Macintosh OS:Intel Mac OS X 10_6_5 Localization:en-US Browser:Chrome-8.0.552.231 Engine:AppleWebKit-534.10 Bot:false Mobile:false",
- expectedOS: &OSInfo{"Intel Mac OS X 10_6_5", "Mac OS X", "10.6.5"},
- },
- {
- title: "SafariMac",
- ua: "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16",
- expected: "Mozilla:5.0 Platform:Macintosh OS:Intel Mac OS X 10_6_3 Localization:en-us Browser:Safari-5.0 Engine:AppleWebKit-533.16 Bot:false Mobile:false",
- },
- {
- title: "SafariWin",
- ua: "Mozilla/5.0 (Windows; U; Windows NT 5.1; en) AppleWebKit/526.9 (KHTML, like Gecko) Version/4.0dp1 Safari/526.8",
- expected: "Mozilla:5.0 Platform:Windows OS:Windows XP Localization:en Browser:Safari-4.0dp1 Engine:AppleWebKit-526.9 Bot:false Mobile:false",
- },
- {
- title: "iPhone7",
- ua: "Mozilla/5.0 (iPhone; CPU iPhone OS 7_0_3 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11B511 Safari/9537.53",
- expected: "Mozilla:5.0 Platform:iPhone OS:CPU iPhone OS 7_0_3 like Mac OS X Browser:Safari-7.0 Engine:AppleWebKit-537.51.1 Bot:false Mobile:true",
- expectedOS: &OSInfo{"CPU iPhone OS 7_0_3 like Mac OS X", "iPhone OS", "7.0.3"},
- },
- {
- title: "iPhone",
- ua: "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/4A102 Safari/419",
- expected: "Mozilla:5.0 Platform:iPhone OS:CPU like Mac OS X Localization:en Browser:Safari-3.0 Engine:AppleWebKit-420.1 Bot:false Mobile:true",
- },
- {
- title: "iPod",
- ua: "Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/4A102 Safari/419",
- expected: "Mozilla:5.0 Platform:iPod OS:CPU like Mac OS X Localization:en Browser:Safari-3.0 Engine:AppleWebKit-420.1 Bot:false Mobile:true",
- },
- {
- title: "iPad",
- ua: "Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B367 Safari/531.21.10",
- expected: "Mozilla:5.0 Platform:iPad OS:CPU OS 3_2 like Mac OS X Localization:en-us Browser:Safari-4.0.4 Engine:AppleWebKit-531.21.10 Bot:false Mobile:true",
- },
- {
- title: "webOS",
- ua: "Mozilla/5.0 (webOS/1.4.0; U; en-US) AppleWebKit/532.2 (KHTML, like Gecko) Version/1.0 Safari/532.2 Pre/1.1",
- expected: "Mozilla:5.0 Platform:webOS OS:Palm Localization:en-US Browser:webOS-1.0 Engine:AppleWebKit-532.2 Bot:false Mobile:true",
- },
- {
- title: "Android",
- ua: "Mozilla/5.0 (Linux; U; Android 1.5; de-; HTC Magic Build/PLAT-RC33) AppleWebKit/528.5+ (KHTML, like Gecko) Version/3.1.2 Mobile Safari/525.20.1",
- expected: "Mozilla:5.0 Platform:Linux OS:Android 1.5 Localization:de- Browser:Android-3.1.2 Engine:AppleWebKit-528.5+ Bot:false Mobile:true",
- },
- {
- title: "BlackBerry",
- ua: "Mozilla/5.0 (BlackBerry; U; BlackBerry 9800; en) AppleWebKit/534.1+ (KHTML, Like Gecko) Version/6.0.0.141 Mobile Safari/534.1+",
- expected: "Mozilla:5.0 Platform:BlackBerry OS:BlackBerry 9800 Localization:en Browser:BlackBerry-6.0.0.141 Engine:AppleWebKit-534.1+ Bot:false Mobile:true",
- expectedOS: &OSInfo{"BlackBerry 9800", "BlackBerry", "9800"},
- },
- {
- title: "BB10",
- ua: "Mozilla/5.0 (BB10; Touch) AppleWebKit/537.3+ (KHTML, like Gecko) Version/10.0.9.388 Mobile Safari/537.3+",
- expected: "Mozilla:5.0 Platform:BlackBerry OS:BlackBerry Browser:BlackBerry-10.0.9.388 Engine:AppleWebKit-537.3+ Bot:false Mobile:true",
- },
- {
- title: "Ericsson",
- ua: "Mozilla/5.0 (SymbianOS/9.4; U; Series60/5.0 Profile/MIDP-2.1 Configuration/CLDC-1.1) AppleWebKit/525 (KHTML, like Gecko) Version/3.0 Safari/525",
- expected: "Mozilla:5.0 Platform:Symbian OS:SymbianOS/9.4 Browser:Symbian-3.0 Engine:AppleWebKit-525 Bot:false Mobile:true",
- expectedOS: &OSInfo{"SymbianOS/9.4", "SymbianOS", "9.4"},
- },
- {
- title: "ChromeAndroid",
- ua: "Mozilla/5.0 (Linux; Android 4.2.1; Galaxy Nexus Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19",
- expected: "Mozilla:5.0 Platform:Linux OS:Android 4.2.1 Browser:Chrome-18.0.1025.166 Engine:AppleWebKit-535.19 Bot:false Mobile:true",
- },
- {
- title: "WebkitNoPlatform",
- ua: "Mozilla/5.0 (en-us) AppleWebKit/525.13 (KHTML, like Gecko; Google Web Preview) Version/3.1 Safari/525.13",
- expected: "Mozilla:5.0 Platform:en-us Localization:en-us Browser:Safari-3.1 Engine:AppleWebKit-525.13 Bot:false Mobile:false",
- },
- {
- title: "OperaWebkitMobile",
- ua: "Mozilla/5.0 (Linux; Android 4.2.2; Galaxy Nexus Build/JDQ39) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.58 Mobile Safari/537.31 OPR/14.0.1074.57453",
- expected: "Mozilla:5.0 Platform:Linux OS:Android 4.2.2 Browser:Opera-14.0.1074.57453 Engine:AppleWebKit-537.31 Bot:false Mobile:true",
- },
- {
- title: "OperaWebkitDesktop",
- ua: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.58 Safari/537.31 OPR/14.0.1074.57453",
- expected: "Mozilla:5.0 Platform:X11 OS:Linux x86_64 Browser:Opera-14.0.1074.57453 Engine:AppleWebKit-537.31 Bot:false Mobile:false",
- },
- {
- title: "ChromeNothingAfterU",
- ua: "Mozilla/5.0 (Linux; U) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4",
- expected: "Mozilla:5.0 Platform:Linux OS:Linux Browser:Chrome-22.0.1229.79 Engine:AppleWebKit-537.4 Bot:false Mobile:false",
- },
- {
- title: "SafariOnSymbian",
- ua: "Mozilla/5.0 (SymbianOS/9.1; U; [en-us]) AppleWebKit/413 (KHTML, like Gecko) Safari/413",
- expected: "Mozilla:5.0 Platform:Symbian OS:SymbianOS/9.1 Browser:Symbian-413 Engine:AppleWebKit-413 Bot:false Mobile:true",
- },
- {
- title: "Chromium - Ubuntu V49",
- ua: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/49.0.2623.108 Chrome/49.0.2623.108 Safari/537.36",
- expected: "Mozilla:5.0 Platform:X11 OS:Linux x86_64 Browser:Chromium-49.0.2623.108 Engine:AppleWebKit-537.36 Bot:false Mobile:false",
- },
- {
- title: "Chromium - Ubuntu V55",
- ua: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/53.0.2785.143 Chrome/53.0.2785.143 Safari/537.36",
- expected: "Mozilla:5.0 Platform:X11 OS:Linux x86_64 Browser:Chromium-53.0.2785.143 Engine:AppleWebKit-537.36 Bot:false Mobile:false",
- },
+ {"ChromeLinux", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11"},
+ {"ChromeWin7", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19"},
+ {"ChromeMinimal", "Mozilla/5.0 AppleWebKit/534.10 Chrome/8.0.552.215 Safari/534.10"},
+ {"ChromeMac", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.231 Safari/534.10"},
+ {"SafariMac", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16"},
+ {"SafariWin", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en) AppleWebKit/526.9 (KHTML, like Gecko) Version/4.0dp1 Safari/526.8"},
+ {"iPhone7", "Mozilla/5.0 (iPhone; CPU iPhone OS 7_0_3 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11B511 Safari/9537.53"},
+ {"iPhone", "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/4A102 Safari/419"},
+ {"iPod", "Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/4A102 Safari/419"},
+ {"iPad", "Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B367 Safari/531.21.10"},
+ {"webOS", "Mozilla/5.0 (webOS/1.4.0; U; en-US) AppleWebKit/532.2 (KHTML, like Gecko) Version/1.0 Safari/532.2 Pre/1.1"},
+ {"Android", "Mozilla/5.0 (Linux; U; Android 1.5; de-; HTC Magic Build/PLAT-RC33) AppleWebKit/528.5+ (KHTML, like Gecko) Version/3.1.2 Mobile Safari/525.20.1"},
+ {"BlackBerry", "Mozilla/5.0 (BlackBerry; U; BlackBerry 9800; en) AppleWebKit/534.1+ (KHTML, Like Gecko) Version/6.0.0.141 Mobile Safari/534.1+"},
+ {"BB10", "Mozilla/5.0 (BB10; Touch) AppleWebKit/537.3+ (KHTML, like Gecko) Version/10.0.9.388 Mobile Safari/537.3+"},
+ {"Ericsson", "Mozilla/5.0 (SymbianOS/9.4; U; Series60/5.0 Profile/MIDP-2.1 Configuration/CLDC-1.1) AppleWebKit/525 (KHTML, like Gecko) Version/3.0 Safari/525"},
+ {"ChromeAndroid", "Mozilla/5.0 (Linux; Android 4.2.1; Galaxy Nexus Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19"},
+ {"WebkitNoPlatform", "Mozilla/5.0 (en-us) AppleWebKit/525.13 (KHTML, like Gecko; Google Web Preview) Version/3.1 Safari/525.13"},
+ {"OperaWebkitMobile", "Mozilla/5.0 (Linux; Android 4.2.2; Galaxy Nexus Build/JDQ39) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.58 Mobile Safari/537.31 OPR/14.0.1074.57453"},
+ {"OperaWebkitDesktop", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.58 Safari/537.31 OPR/14.0.1074.57453"},
+ {"ChromeNothingAfterU", "Mozilla/5.0 (Linux; U) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4"},
+ {"SafariOnSymbian", "Mozilla/5.0 (SymbianOS/9.1; U; [en-us]) AppleWebKit/413 (KHTML, like Gecko) Safari/413"},
+}
+
+// Slice of the expected results from the previous slice.
+var expected = []string{
+ // Bots
+ "Mozilla:5.0 Browser:Googlebot-2.1 Bot:true Mobile:false",
+ "Mozilla:5.0 Browser:Googlebot-2.1 Bot:true Mobile:true",
+ "Mozilla:5.0 Browser:bingbot-2.0 Bot:true Mobile:false",
+ "Mozilla:5.0 Browser:Baiduspider-2.0 Bot:true Mobile:false",
+ "Browser:Twitterbot Bot:true Mobile:false",
+ "Mozilla:5.0 Browser:Yahoo! Slurp Bot:true Mobile:false",
+ "Browser:facebookexternalhit-1.1 Bot:true Mobile:false",
+ "Browser:facebookplatform-1.0 Bot:true Mobile:false",
+ "Browser:Facebot Bot:true Mobile:false",
+
+ // Internet Explorer
+ "Mozilla:5.0 Platform:Windows OS:Windows 8 Browser:Internet Explorer-10.0 Engine:Trident Bot:false Mobile:false",
+ "Mozilla:4.0 Platform:Windows OS:Windows 8 Browser:Internet Explorer-10.0 Engine:Trident Bot:false Mobile:false",
+ "Mozilla:5.0 Platform:Windows OS:Windows 8 Browser:Internet Explorer-10.0 Engine:Trident Bot:false Mobile:false",
+ "Mozilla:4.0 Platform:Windows OS:Windows Phone OS 7.0 Browser:Internet Explorer-7.0 Engine:Trident Bot:false Mobile:true",
+ "Mozilla:4.0 Platform:Windows OS:Windows 2000 Browser:Internet Explorer-6.0 Engine:Trident Bot:false Mobile:false",
+ "Mozilla:4.0 Platform:Windows OS:Windows 7 Browser:Internet Explorer-8.0 Engine:Trident Bot:false Mobile:false",
+ "Mozilla:4.0 Platform:Windows OS:Windows 7 Browser:Internet Explorer-10.0 Engine:Trident Bot:false Mobile:false",
+ "Mozilla:5.0 Platform:Windows OS:Windows 8.1 Browser:Internet Explorer-11.0 Engine:Trident Bot:false Mobile:false",
+ "Mozilla:5.0 Platform:Windows OS:Windows 7 Browser:Internet Explorer-11.0 Engine:Trident Bot:false Mobile:false",
+ "Mozilla:5.0 Platform:Windows OS:Windows 7 Browser:Internet Explorer-11.0 Engine:Trident Bot:false Mobile:false",
+ "Mozilla:5.0 Platform:Windows OS:Windows 7 Browser:Internet Explorer-11.0 Engine:Trident Bot:false Mobile:false",
+ "Mozilla:4.0 Platform:Windows OS:Windows 8.1 Browser:Internet Explorer-7.0 Engine:Trident Bot:false Mobile:false",
+
+ // Gecko
+ "Mozilla:5.0 Platform:Macintosh OS:Intel Mac OS X 10.6 Browser:Firefox-4.0b8 Engine:Gecko-20100101 Bot:false Mobile:false",
+ "Mozilla:5.0 Platform:Macintosh OS:Intel Mac OS X 10.6 Localization:en-US Browser:Firefox-3.6.13 Engine:Gecko-20101203 Bot:false Mobile:false",
+ "Mozilla:5.0 Platform:X11 OS:Linux x86_64 Browser:Firefox-17.0 Engine:Gecko-20100101 Bot:false Mobile:false",
+ "Mozilla:5.0 Platform:Windows OS:Windows XP Localization:en-US Browser:Firefox-2.0.0.14 Engine:Gecko-20080404 Bot:false Mobile:false",
+ "Mozilla:5.0 Platform:Windows OS:Windows 7 Browser:Firefox-29.0 Engine:Gecko-20100101 Bot:false Mobile:false",
+ "Mozilla:5.0 Platform:Macintosh OS:Intel Mac OS X Localization:en Browser:Camino-1.6 Engine:Gecko-20080409 Bot:false Mobile:false",
+ "Mozilla:5.0 Platform:X11 OS:Linux i686 Localization:en-US Browser:Iceweasel-2.0 Engine:Gecko-20061024 Bot:false Mobile:false",
+ "Mozilla:5.0 Platform:Macintosh OS:Intel Mac OS X 10.6 Localization:en-US Browser:SeaMonkey-2.0 Engine:Gecko-20091017 Bot:false Mobile:false",
+ "Mozilla:5.0 Platform:Mobile OS:Android Browser:Firefox-17.0 Engine:Gecko-17.0 Bot:false Mobile:true",
+ "Mozilla:5.0 Platform:Tablet OS:Android Browser:Firefox-26.0 Engine:Gecko-26.0 Bot:false Mobile:true",
+ "Mozilla:5.0 Platform:Mobile OS:FirefoxOS Browser:Firefox-26.0 Engine:Gecko-26.0 Bot:false Mobile:true",
+ "Mozilla:5.0 Platform:Tablet OS:FirefoxOS Browser:Firefox-26.0 Engine:Gecko-26.0 Bot:false Mobile:true",
+ "Mozilla:5.0 Platform:Windows OS:Windows XP x64 Edition Browser:Firefox-31.0 Engine:Gecko-20100101 Bot:false Mobile:false",
+ "Mozilla:5.0 Platform:Windows OS:Windows XP Localization:en-US Browser:Firefox-24.0 Engine:Gecko-20130405 Bot:false Mobile:false",
- // Dalvik
- {
- title: "Dalvik - Dell:001DL",
- ua: "Dalvik/1.2.0 (Linux; U; Android 2.2.2; 001DL Build/FRG83G)",
- expected: "Mozilla:5.0 Platform:Linux OS:Android 2.2.2 Bot:false Mobile:true",
- },
- {
- title: "Dalvik - HTC:001HT",
- ua: "Dalvik/1.4.0 (Linux; U; Android 2.3.3; 001HT Build/GRI40)",
- expected: "Mozilla:5.0 Platform:Linux OS:Android 2.3.3 Bot:false Mobile:true",
- },
- {
- title: "Dalvik - ZTE:009Z",
- ua: "Dalvik/1.4.0 (Linux; U; Android 2.3.4; 009Z Build/GINGERBREAD)",
- expected: "Mozilla:5.0 Platform:Linux OS:Android 2.3.4 Bot:false Mobile:true",
- },
- {
- title: "Dalvik - A850",
- ua: "Dalvik/1.6.0 (Linux; U; Android 4.2.2; A850 Build/JDQ39) Configuration/CLDC-1.1; Opera Mini/att/4.2",
- expected: "Mozilla:5.0 Platform:Linux OS:Android 4.2.2 Bot:false Mobile:true",
- },
- {
- title: "Dalvik - Asus:T00Q",
- ua: "Dalvik/1.6.0 (Linux; U; Android 4.4.2; ASUS_T00Q Build/KVT49L)/CLDC-1.1",
- expected: "Mozilla:5.0 Platform:Linux OS:Android 4.4.2 Bot:false Mobile:true",
- expectedOS: &OSInfo{"Android 4.4.2", "Android", "4.4.2"},
- },
- {
- title: "Dalvik - W2430",
- ua: "Dalvik/1.6.0 (Linux; U; Android 4.0.4; W2430 Build/IMM76D)014; Profile/MIDP-2.1 Configuration/CLDC-1",
- expected: "Mozilla:5.0 Platform:Linux OS:Android 4.0.4 Bot:false Mobile:true",
- },
+ // Opera
+ "Platform:Macintosh OS:Intel Mac OS X Localization:en Browser:Opera-9.27 Engine:Presto Bot:false Mobile:false",
+ "Platform:Windows OS:Windows XP Localization:en Browser:Opera-9.27 Engine:Presto Bot:false Mobile:false",
+ "Platform:Windows OS:Windows XP Browser:Opera-9.80 Engine:Presto-2.12.388 Bot:false Mobile:false",
+ "Platform:Windows OS:Windows Vista Browser:Opera-9.80 Engine:Presto-2.12.388 Bot:false Mobile:false",
+ "Browser:Opera-9.80 Engine:Presto Bot:false Mobile:false",
+ "Platform:Windows OS:Windows Vista Localization:en Browser:Opera-9.80 Engine:Presto-2.2.15 Bot:false Mobile:false",
+ "Platform:X11 OS:Linux x86_64 Browser:Opera-9.80 Engine:Presto-2.12.388 Bot:false Mobile:false",
+ "Platform:Android 4.2.1 OS:Linux Browser:Opera-9.80 Engine:Presto-2.11.355 Bot:false Mobile:true",
+ "Platform:Windows OS:Windows XP Browser:Opera-9.80 Engine:Presto-2.12.388 Bot:false Mobile:false",
+ "Platform:Windows OS:Windows 7 Localization:en Browser:Opera-9.80 Engine:Presto-2.9.168 Bot:false Mobile:false",
+
+ // Other
+ "Bot:false Mobile:false",
+ "Browser:nil Bot:false Mobile:false",
+ "Browser:Mozilla-4.0 Bot:false Mobile:false",
+ "Browser:Mozilla-5.0 Bot:false Mobile:false",
+ "Browser:amaya-9.51 Engine:libwww-5.4.0 Bot:false Mobile:false",
+ "Browser:Rails Engine:Testing Bot:false Mobile:false",
+ "Browser:Python-urllib-2.7 Bot:false Mobile:false",
+ "Browser:curl-7.28.1 Bot:false Mobile:false",
+
+ // WebKit
+ "Mozilla:5.0 Platform:X11 OS:Linux x86_64 Browser:Chrome-23.0.1271.97 Engine:AppleWebKit-537.11 Bot:false Mobile:false",
+ "Mozilla:5.0 Platform:Windows OS:Windows 7 Browser:Chrome-18.0.1025.168 Engine:AppleWebKit-535.19 Bot:false Mobile:false",
+ "Mozilla:5.0 Browser:Chrome-8.0.552.215 Engine:AppleWebKit-534.10 Bot:false Mobile:false",
+ "Mozilla:5.0 Platform:Macintosh OS:Intel Mac OS X 10_6_5 Localization:en-US Browser:Chrome-8.0.552.231 Engine:AppleWebKit-534.10 Bot:false Mobile:false",
+ "Mozilla:5.0 Platform:Macintosh OS:Intel Mac OS X 10_6_3 Localization:en-us Browser:Safari-5.0 Engine:AppleWebKit-533.16 Bot:false Mobile:false",
+ "Mozilla:5.0 Platform:Windows OS:Windows XP Localization:en Browser:Safari-4.0dp1 Engine:AppleWebKit-526.9 Bot:false Mobile:false",
+ "Mozilla:5.0 Platform:iPhone OS:CPU iPhone OS 7_0_3 like Mac OS X Browser:Safari-7.0 Engine:AppleWebKit-537.51.1 Bot:false Mobile:true",
+ "Mozilla:5.0 Platform:iPhone OS:CPU like Mac OS X Localization:en Browser:Safari-3.0 Engine:AppleWebKit-420.1 Bot:false Mobile:true",
+ "Mozilla:5.0 Platform:iPod OS:CPU like Mac OS X Localization:en Browser:Safari-3.0 Engine:AppleWebKit-420.1 Bot:false Mobile:true",
+ "Mozilla:5.0 Platform:iPad OS:CPU OS 3_2 like Mac OS X Localization:en-us Browser:Safari-4.0.4 Engine:AppleWebKit-531.21.10 Bot:false Mobile:true",
+ "Mozilla:5.0 Platform:webOS OS:Palm Localization:en-US Browser:webOS-1.0 Engine:AppleWebKit-532.2 Bot:false Mobile:true",
+ "Mozilla:5.0 Platform:Linux OS:Android 1.5 Localization:de- Browser:Android-3.1.2 Engine:AppleWebKit-528.5+ Bot:false Mobile:true",
+ "Mozilla:5.0 Platform:BlackBerry OS:BlackBerry 9800 Localization:en Browser:BlackBerry-6.0.0.141 Engine:AppleWebKit-534.1+ Bot:false Mobile:true",
+ "Mozilla:5.0 Platform:BlackBerry OS:BlackBerry Browser:BlackBerry-10.0.9.388 Engine:AppleWebKit-537.3+ Bot:false Mobile:true",
+ "Mozilla:5.0 Platform:Symbian OS:SymbianOS/9.4 Browser:Symbian-3.0 Engine:AppleWebKit-525 Bot:false Mobile:true",
+ "Mozilla:5.0 Platform:Linux OS:Android 4.2.1 Browser:Chrome-18.0.1025.166 Engine:AppleWebKit-535.19 Bot:false Mobile:true",
+ "Mozilla:5.0 Platform:en-us Localization:en-us Browser:Safari-3.1 Engine:AppleWebKit-525.13 Bot:false Mobile:false",
+ "Mozilla:5.0 Platform:Linux OS:Android 4.2.2 Browser:Opera-14.0.1074.57453 Engine:AppleWebKit-537.31 Bot:false Mobile:true",
+ "Mozilla:5.0 Platform:X11 OS:Linux x86_64 Browser:Opera-14.0.1074.57453 Engine:AppleWebKit-537.31 Bot:false Mobile:false",
+ "Mozilla:5.0 Platform:Linux OS:Linux Browser:Chrome-22.0.1229.79 Engine:AppleWebKit-537.4 Bot:false Mobile:false",
+ "Mozilla:5.0 Platform:Symbian OS:SymbianOS/9.1 Browser:Symbian-413 Engine:AppleWebKit-413 Bot:false Mobile:true",
}
// Internal: beautify the UserAgent reference into a string so it can be
@@ -560,18 +235,11 @@ func beautify(ua *UserAgent) (s string) {
// The test suite.
func TestUserAgent(t *testing.T) {
- for _, tt := range uastrings {
+ for i, tt := range uastrings {
ua := New(tt.ua)
got := beautify(ua)
- if tt.expected != got {
- t.Errorf("\nTest %v\ngot: %q\nexpected %q\n", tt.title, got, tt.expected)
- }
-
- if tt.expectedOS != nil {
- gotOSInfo := ua.OSInfo()
- if !reflect.DeepEqual(tt.expectedOS, &gotOSInfo) {
- t.Errorf("\nTest %v\ngot: %#v\nexpected %#v\n", tt.title, gotOSInfo, tt.expectedOS)
- }
+ if expected[i] != got {
+ t.Errorf("Test %v => %q, expected %q", tt.name, got, expected[i])
}
}
}
diff --git a/vendor/github.com/mssola/user_agent/bot.go b/vendor/github.com/mssola/user_agent/bot.go
index a6222d17f..efcab9253 100644
--- a/vendor/github.com/mssola/user_agent/bot.go
+++ b/vendor/github.com/mssola/user_agent/bot.go
@@ -1,4 +1,4 @@
-// Copyright (C) 2014-2017 Miquel Sabaté Solà <mikisabate@gmail.com>
+// Copyright (C) 2014 Miquel Sabaté Solà <mikisabate@gmail.com>
// This file is licensed under the MIT license.
// See the LICENSE file.
@@ -9,8 +9,6 @@ import (
"strings"
)
-var botFromSiteRegexp = regexp.MustCompile("http://.+\\.\\w+")
-
// Get the name of the bot from the website that may be in the given comment. If
// there is no website in the comment, then an empty string is returned.
func getFromSite(comment []string) string {
@@ -25,7 +23,8 @@ func getFromSite(comment []string) string {
}
// Pick the site.
- results := botFromSiteRegexp.FindStringSubmatch(comment[idx])
+ re := regexp.MustCompile("http://.+\\.\\w+")
+ results := re.FindStringSubmatch(comment[idx])
if len(results) == 1 {
// If it's a simple comment, just return the name of the site.
if idx == 0 {
@@ -75,8 +74,6 @@ func (p *UserAgent) fixOther(sections []section) {
}
}
-var botRegex = regexp.MustCompile("(?i)(bot|crawler|sp(i|y)der|search|worm|fetch|nutch)")
-
// Check if we're dealing with a bot or with some weird browser. If that is the
// case, the receiver will be modified accordingly.
func (p *UserAgent) checkBot(sections []section) {
@@ -85,8 +82,9 @@ func (p *UserAgent) checkBot(sections []section) {
if len(sections) == 1 && sections[0].name != "Mozilla" {
p.mozilla = ""
- // Check whether the name has some suspicious "bot" or "crawler" in his name.
- if botRegex.Match([]byte(sections[0].name)) {
+ // Check whether the name has some suspicious "bot" in his name.
+ reg, _ := regexp.Compile("(?i)bot")
+ if reg.Match([]byte(sections[0].name)) {
p.setSimple(sections[0].name, "", true)
return
}
diff --git a/vendor/github.com/mssola/user_agent/browser.go b/vendor/github.com/mssola/user_agent/browser.go
index fbed92176..74fb931ef 100644
--- a/vendor/github.com/mssola/user_agent/browser.go
+++ b/vendor/github.com/mssola/user_agent/browser.go
@@ -1,4 +1,4 @@
-// Copyright (C) 2012-2017 Miquel Sabaté Solà <mikisabate@gmail.com>
+// Copyright (C) 2012-2014 Miquel Sabaté Solà <mikisabate@gmail.com>
// This file is licensed under the MIT license.
// See the LICENSE file.
@@ -9,8 +9,6 @@ import (
"strings"
)
-var ie11Regexp = regexp.MustCompile("^rv:(.+)$")
-
// A struct containing all the information that we might be
// interested from the browser.
type Browser struct {
@@ -36,46 +34,27 @@ func (p *UserAgent) detectBrowser(sections []section) {
slen := len(sections)
if sections[0].name == "Opera" {
+ p.mozilla = ""
p.browser.Name = "Opera"
p.browser.Version = sections[0].version
p.browser.Engine = "Presto"
if slen > 1 {
p.browser.EngineVersion = sections[1].version
}
- } else if sections[0].name == "Dalvik" {
- // When Dalvik VM is in use, there is no browser info attached to ua.
- // Although browser is still a Mozilla/5.0 compatible.
- p.mozilla = "5.0"
} else if slen > 1 {
engine := sections[1]
p.browser.Engine = engine.name
p.browser.EngineVersion = engine.version
if slen > 2 {
- sectionIndex := 2
- // The version after the engine comment is empty on e.g. Ubuntu
- // platforms so if this is the case, let's use the next in line.
- if sections[2].version == "" && slen > 3 {
- sectionIndex = 3
- }
- p.browser.Version = sections[sectionIndex].version
+ p.browser.Version = sections[2].version
if engine.name == "AppleWebKit" {
- switch sections[slen-1].name {
- case "Edge":
- p.browser.Name = "Edge"
- p.browser.Version = sections[slen-1].version
- p.browser.Engine = "EdgeHTML"
- p.browser.EngineVersion = ""
- case "OPR":
+ if sections[slen-1].name == "OPR" {
p.browser.Name = "Opera"
p.browser.Version = sections[slen-1].version
- default:
- if sections[sectionIndex].name == "Chrome" {
- p.browser.Name = "Chrome"
- } else if sections[sectionIndex].name == "Chromium" {
- p.browser.Name = "Chromium"
- } else {
- p.browser.Name = "Safari"
- }
+ } else if sections[2].name == "Chrome" {
+ p.browser.Name = "Chrome"
+ } else {
+ p.browser.Name = "Safari"
}
} else if engine.name == "Gecko" {
name := sections[2].name
@@ -88,8 +67,9 @@ func (p *UserAgent) detectBrowser(sections []section) {
// This is the new user agent from Internet Explorer 11.
p.browser.Engine = "Trident"
p.browser.Name = "Internet Explorer"
+ reg, _ := regexp.Compile("^rv:(.+)$")
for _, c := range sections[0].comment {
- version := ie11Regexp.FindStringSubmatch(c)
+ version := reg.FindStringSubmatch(c)
if len(version) > 0 {
p.browser.Version = version[1]
return
diff --git a/vendor/github.com/mssola/user_agent/operating_systems.go b/vendor/github.com/mssola/user_agent/operating_systems.go
index aebd8b394..0b1e93d29 100644
--- a/vendor/github.com/mssola/user_agent/operating_systems.go
+++ b/vendor/github.com/mssola/user_agent/operating_systems.go
@@ -1,4 +1,4 @@
-// Copyright (C) 2012-2017 Miquel Sabaté Solà <mikisabate@gmail.com>
+// Copyright (C) 2012-2014 Miquel Sabaté Solà <mikisabate@gmail.com>
// This file is licensed under the MIT license.
// See the LICENSE file.
@@ -6,26 +6,13 @@ package user_agent
import "strings"
-// Represents full information on the operating system extracted from the user agent.
-type OSInfo struct {
- // Full name of the operating system. This is identical to the output of ua.OS()
- FullName string
-
- // Name of the operating system. This is sometimes a shorter version of the
- // operating system name, e.g. "Mac OS X" instead of "Intel Mac OS X"
- Name string
-
- // Operating system version, e.g. 7 for Windows 7 or 10.8 for Max OS X Mountain Lion
- Version string
-}
-
// Normalize the name of the operating system. By now, this just
-// affects to Windows NT.
+// affects to Windows.
//
// Returns a string containing the normalized name for the Operating System.
func normalizeOS(name string) string {
sp := strings.SplitN(name, " ", 3)
- if len(sp) != 3 || sp[1] != "NT" {
+ if len(sp) != 3 {
return name
}
@@ -46,7 +33,7 @@ func normalizeOS(name string) string {
return "Windows 8"
case "6.3":
return "Windows 8.1"
- case "10.0":
+ case "6.4":
return "Windows 10"
}
return name
@@ -139,9 +126,7 @@ func gecko(p *UserAgent, comment []string) {
}
}
}
- // Only parse 4th comment as localization if it doesn't start with rv:.
- // For example Firefox on Ubuntu contains "rv:XX.X" in this field.
- if len(comment) > 3 && !strings.HasPrefix(comment[3], "rv:") {
+ if len(comment) > 3 {
p.localization = comment[3]
}
}
@@ -208,23 +193,6 @@ func opera(p *UserAgent, comment []string) {
}
}
-// Guess the OS. Android browsers send Dalvik as the user agent in the
-// request header.
-//
-// The first argument p is a reference to the current UserAgent and the second
-// argument is a slice of strings containing the comment.
-func dalvik(p *UserAgent, comment []string) {
- slen := len(comment)
-
- if strings.HasPrefix(comment[0], "Linux") {
- p.platform = comment[0]
- if slen > 2 {
- p.os = comment[2]
- }
- p.mobile = true
- }
-}
-
// Given the comment of the first section of the UserAgent string,
// get the platform.
func getPlatform(comment []string) string {
@@ -270,10 +238,6 @@ func (p *UserAgent) detectOS(s section) {
if len(s.comment) > 0 {
opera(p, s.comment)
}
- } else if s.name == "Dalvik" {
- if len(s.comment) > 0 {
- dalvik(p, s.comment)
- }
} else {
// Check whether this is a bot or just a weird browser.
p.undecided = true
@@ -294,64 +258,3 @@ func (p *UserAgent) OS() string {
func (p *UserAgent) Localization() string {
return p.localization
}
-
-// Return OS name and version from a slice of strings created from the full name of the OS.
-func osName(osSplit []string) (name, version string) {
- if len(osSplit) == 1 {
- name = osSplit[0]
- version = ""
- } else {
- // Assume version is stored in the last part of the array.
- nameSplit := osSplit[:len(osSplit)-1]
- version = osSplit[len(osSplit)-1]
-
- // Nicer looking Mac OS X
- if len(nameSplit) >= 2 && nameSplit[0] == "Intel" && nameSplit[1] == "Mac" {
- nameSplit = nameSplit[1:]
- }
- name = strings.Join(nameSplit, " ")
-
- if strings.Contains(version, "x86") || strings.Contains(version, "i686") {
- // x86_64 and i868 are not Linux versions but architectures
- version = ""
- } else if version == "X" && name == "Mac OS" {
- // X is not a version for Mac OS.
- name = name + " " + version
- version = ""
- }
- }
- return name, version
-}
-
-// Returns combined information for the operating system.
-func (p *UserAgent) OSInfo() OSInfo {
- // Special case for iPhone weirdness
- os := strings.Replace(p.os, "like Mac OS X", "", 1)
- os = strings.Replace(os, "CPU", "", 1)
- os = strings.Trim(os, " ")
-
- osSplit := strings.Split(os, " ")
-
- // Special case for x64 edition of Windows
- if os == "Windows XP x64 Edition" {
- osSplit = osSplit[:len(osSplit)-2]
- }
-
- name, version := osName(osSplit)
-
- // Special case for names that contain a forward slash version separator.
- if strings.Contains(name, "/") {
- s := strings.Split(name, "/")
- name = s[0]
- version = s[1]
- }
-
- // Special case for versions that use underscores
- version = strings.Replace(version, "_", ".", -1)
-
- return OSInfo{
- FullName: p.os,
- Name: name,
- Version: version,
- }
-}
diff --git a/vendor/github.com/mssola/user_agent/user_agent.go b/vendor/github.com/mssola/user_agent/user_agent.go
index 36e8d1bfa..74ddf273c 100644
--- a/vendor/github.com/mssola/user_agent/user_agent.go
+++ b/vendor/github.com/mssola/user_agent/user_agent.go
@@ -1,4 +1,4 @@
-// Copyright (C) 2012-2017 Miquel Sabaté Solà <mikisabate@gmail.com>
+// Copyright (C) 2012-2014 Miquel Sabaté Solà <mikisabate@gmail.com>
// This file is licensed under the MIT license.
// See the LICENSE file.
@@ -8,7 +8,9 @@
// information that has been extracted from a parsed User Agent string.
package user_agent
-import "strings"
+import (
+ "strings"
+)
// A section contains the name of the product, its version and
// an optional comment.
@@ -139,9 +141,7 @@ func (p *UserAgent) Parse(ua string) {
}
if len(sections) > 0 {
- if sections[0].name == "Mozilla" {
- p.mozilla = sections[0].version
- }
+ p.mozilla = sections[0].version
p.detectBrowser(sections)
p.detectOS(sections[0])
@@ -167,8 +167,3 @@ func (p *UserAgent) Bot() bool {
func (p *UserAgent) Mobile() bool {
return p.mobile
}
-
-// Returns the original given user agent.
-func (p *UserAgent) UA() string {
- return p.ua
-}
diff --git a/vendor/github.com/pborman/uuid/.travis.yml b/vendor/github.com/pborman/uuid/.travis.yml
index d8156a60b..a6a98db8a 100644
--- a/vendor/github.com/pborman/uuid/.travis.yml
+++ b/vendor/github.com/pborman/uuid/.travis.yml
@@ -3,6 +3,7 @@ language: go
go:
- 1.4.3
- 1.5.3
+ - release
- tip
script:
diff --git a/vendor/github.com/pborman/uuid/CONTRIBUTING.md b/vendor/github.com/pborman/uuid/CONTRIBUTING.md
deleted file mode 100644
index 04fdf09f1..000000000
--- a/vendor/github.com/pborman/uuid/CONTRIBUTING.md
+++ /dev/null
@@ -1,10 +0,0 @@
-# How to contribute
-
-We definitely welcome patches and contribution to this project!
-
-### Legal requirements
-
-In order to protect both you and ourselves, you will need to sign the
-[Contributor License Agreement](https://cla.developers.google.com/clas).
-
-You may have already signed it for other Google projects.
diff --git a/vendor/github.com/pborman/uuid/README.md b/vendor/github.com/pborman/uuid/README.md
index b0396b274..f023d47ca 100644
--- a/vendor/github.com/pborman/uuid/README.md
+++ b/vendor/github.com/pborman/uuid/README.md
@@ -1,7 +1,7 @@
This project was automatically exported from code.google.com/p/go-uuid
# uuid ![build status](https://travis-ci.org/pborman/uuid.svg?branch=master)
-The uuid package generates and inspects UUIDs based on [RFC 4122](http://tools.ietf.org/html/rfc4122) and DCE 1.1: Authentication and Security Services.
+The uuid package generates and inspects UUIDs based on [RFC 412](http://tools.ietf.org/html/rfc4122) and DCE 1.1: Authentication and Security Services.
###### Install
`go get github.com/pborman/uuid`
diff --git a/vendor/github.com/pborman/uuid/dce.go b/vendor/github.com/pborman/uuid/dce.go
index 50a0f2d09..50a0f2d09 100644..100755
--- a/vendor/github.com/pborman/uuid/dce.go
+++ b/vendor/github.com/pborman/uuid/dce.go
diff --git a/vendor/github.com/pborman/uuid/doc.go b/vendor/github.com/pborman/uuid/doc.go
index d8bd013e6..d8bd013e6 100644..100755
--- a/vendor/github.com/pborman/uuid/doc.go
+++ b/vendor/github.com/pborman/uuid/doc.go
diff --git a/vendor/github.com/pborman/uuid/json.go b/vendor/github.com/pborman/uuid/json.go
new file mode 100644
index 000000000..9dda1dfba
--- /dev/null
+++ b/vendor/github.com/pborman/uuid/json.go
@@ -0,0 +1,34 @@
+// Copyright 2014 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import "errors"
+
+func (u UUID) MarshalJSON() ([]byte, error) {
+ if len(u) != 16 {
+ return []byte(`""`), nil
+ }
+ var js [38]byte
+ js[0] = '"'
+ encodeHex(js[1:], u)
+ js[37] = '"'
+ return js[:], nil
+}
+
+func (u *UUID) UnmarshalJSON(data []byte) error {
+ if string(data) == `""` {
+ return nil
+ }
+ if data[0] != '"' {
+ return errors.New("invalid UUID format")
+ }
+ data = data[1 : len(data)-1]
+ uu := Parse(string(data))
+ if uu == nil {
+ return errors.New("invalid UUID format")
+ }
+ *u = uu
+ return nil
+}
diff --git a/vendor/github.com/pborman/uuid/json_test.go b/vendor/github.com/pborman/uuid/json_test.go
new file mode 100644
index 000000000..2866b8dc8
--- /dev/null
+++ b/vendor/github.com/pborman/uuid/json_test.go
@@ -0,0 +1,61 @@
+// Copyright 2014 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "encoding/json"
+ "reflect"
+ "testing"
+)
+
+var testUUID = Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479")
+
+func TestJSON(t *testing.T) {
+ type S struct {
+ ID1 UUID
+ ID2 UUID
+ }
+ s1 := S{ID1: testUUID}
+ data, err := json.Marshal(&s1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var s2 S
+ if err := json.Unmarshal(data, &s2); err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(&s1, &s2) {
+ t.Errorf("got %#v, want %#v", s2, s1)
+ }
+}
+
+func BenchmarkUUID_MarshalJSON(b *testing.B) {
+ x := &struct {
+ UUID UUID `json:"uuid"`
+ }{}
+ x.UUID = Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479")
+ if x.UUID == nil {
+ b.Fatal("invalid uuid")
+ }
+ for i := 0; i < b.N; i++ {
+ js, err := json.Marshal(x)
+ if err != nil {
+ b.Fatalf("marshal json: %#v (%v)", js, err)
+ }
+ }
+}
+
+func BenchmarkUUID_UnmarshalJSON(b *testing.B) {
+ js := []byte(`{"uuid":"f47ac10b-58cc-0372-8567-0e02b2c3d479"}`)
+ var x *struct {
+ UUID UUID `json:"uuid"`
+ }
+ for i := 0; i < b.N; i++ {
+ err := json.Unmarshal(js, &x)
+ if err != nil {
+ b.Fatalf("marshal json: %#v (%v)", js, err)
+ }
+ }
+}
diff --git a/vendor/github.com/pborman/uuid/marshal.go b/vendor/github.com/pborman/uuid/marshal.go
deleted file mode 100644
index 6621dd54b..000000000
--- a/vendor/github.com/pborman/uuid/marshal.go
+++ /dev/null
@@ -1,83 +0,0 @@
-// Copyright 2016 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package uuid
-
-import (
- "errors"
- "fmt"
-)
-
-// MarshalText implements encoding.TextMarshaler.
-func (u UUID) MarshalText() ([]byte, error) {
- if len(u) != 16 {
- return nil, nil
- }
- var js [36]byte
- encodeHex(js[:], u)
- return js[:], nil
-}
-
-// UnmarshalText implements encoding.TextUnmarshaler.
-func (u *UUID) UnmarshalText(data []byte) error {
- if len(data) == 0 {
- return nil
- }
- id := Parse(string(data))
- if id == nil {
- return errors.New("invalid UUID")
- }
- *u = id
- return nil
-}
-
-// MarshalBinary implements encoding.BinaryMarshaler.
-func (u UUID) MarshalBinary() ([]byte, error) {
- return u[:], nil
-}
-
-// UnmarshalBinary implements encoding.BinaryUnmarshaler.
-func (u *UUID) UnmarshalBinary(data []byte) error {
- if len(data) == 0 {
- return nil
- }
- if len(data) != 16 {
- return fmt.Errorf("invalid UUID (got %d bytes)", len(data))
- }
- var id [16]byte
- copy(id[:], data)
- *u = id[:]
- return nil
-}
-
-// MarshalText implements encoding.TextMarshaler.
-func (u Array) MarshalText() ([]byte, error) {
- var js [36]byte
- encodeHex(js[:], u[:])
- return js[:], nil
-}
-
-// UnmarshalText implements encoding.TextUnmarshaler.
-func (u *Array) UnmarshalText(data []byte) error {
- id := Parse(string(data))
- if id == nil {
- return errors.New("invalid UUID")
- }
- *u = id.Array()
- return nil
-}
-
-// MarshalBinary implements encoding.BinaryMarshaler.
-func (u Array) MarshalBinary() ([]byte, error) {
- return u[:], nil
-}
-
-// UnmarshalBinary implements encoding.BinaryUnmarshaler.
-func (u *Array) UnmarshalBinary(data []byte) error {
- if len(data) != 16 {
- return fmt.Errorf("invalid UUID (got %d bytes)", len(data))
- }
- copy(u[:], data)
- return nil
-}
diff --git a/vendor/github.com/pborman/uuid/marshal_test.go b/vendor/github.com/pborman/uuid/marshal_test.go
deleted file mode 100644
index 4e85b6bab..000000000
--- a/vendor/github.com/pborman/uuid/marshal_test.go
+++ /dev/null
@@ -1,124 +0,0 @@
-// Copyright 2014 Google Inc. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package uuid
-
-import (
- "bytes"
- "encoding/json"
- "reflect"
- "testing"
-)
-
-var testUUID = Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479")
-var testArray = testUUID.Array()
-
-func TestJSON(t *testing.T) {
- type S struct {
- ID1 UUID
- ID2 UUID
- }
- s1 := S{ID1: testUUID}
- data, err := json.Marshal(&s1)
- if err != nil {
- t.Fatal(err)
- }
- var s2 S
- if err := json.Unmarshal(data, &s2); err != nil {
- t.Fatal(err)
- }
- if !reflect.DeepEqual(&s1, &s2) {
- t.Errorf("got %#v, want %#v", s2, s1)
- }
-}
-
-func TestJSONArray(t *testing.T) {
- type S struct {
- ID1 Array
- ID2 Array
- }
- s1 := S{ID1: testArray}
- data, err := json.Marshal(&s1)
- if err != nil {
- t.Fatal(err)
- }
- var s2 S
- if err := json.Unmarshal(data, &s2); err != nil {
- t.Fatal(err)
- }
- if !reflect.DeepEqual(&s1, &s2) {
- t.Errorf("got %#v, want %#v", s2, s1)
- }
-}
-
-func TestMarshal(t *testing.T) {
- data, err := testUUID.MarshalBinary()
- if err != nil {
- t.Fatalf("MarhsalBinary returned unexpected error %v", err)
- }
- if !bytes.Equal(data, testUUID) {
- t.Fatalf("MarhsalBinary returns %x, want %x", data, testUUID)
- }
- var u UUID
- u.UnmarshalBinary(data)
- if !Equal(data, u) {
- t.Fatalf("UnmarhsalBinary returns %v, want %v", u, testUUID)
- }
-}
-
-func TestMarshalArray(t *testing.T) {
- data, err := testArray.MarshalBinary()
- if err != nil {
- t.Fatalf("MarhsalBinary returned unexpected error %v", err)
- }
- if !bytes.Equal(data, testUUID) {
- t.Fatalf("MarhsalBinary returns %x, want %x", data, testUUID)
- }
- var a Array
- a.UnmarshalBinary(data)
- if a != testArray {
- t.Fatalf("UnmarhsalBinary returns %v, want %v", a, testArray)
- }
-}
-
-func TestMarshalTextArray(t *testing.T) {
- data, err := testArray.MarshalText()
- if err != nil {
- t.Fatalf("MarhsalText returned unexpected error %v", err)
- }
- var a Array
- a.UnmarshalText(data)
- if a != testArray {
- t.Fatalf("UnmarhsalText returns %v, want %v", a, testArray)
- }
-}
-
-func BenchmarkUUID_MarshalJSON(b *testing.B) {
- x := &struct {
- UUID UUID `json:"uuid"`
- }{}
- x.UUID = Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479")
- if x.UUID == nil {
- b.Fatal("invalid uuid")
- }
- for i := 0; i < b.N; i++ {
- js, err := json.Marshal(x)
- if err != nil {
- b.Fatalf("marshal json: %#v (%v)", js, err)
- }
- }
-}
-
-func BenchmarkUUID_UnmarshalJSON(b *testing.B) {
- js := []byte(`{"uuid":"f47ac10b-58cc-0372-8567-0e02b2c3d479"}`)
- var x *struct {
- UUID UUID `json:"uuid"`
- }
- for i := 0; i < b.N; i++ {
- err := json.Unmarshal(js, &x)
- if err != nil {
- b.Fatalf("marshal json: %#v (%v)", js, err)
- }
- }
-}
diff --git a/vendor/github.com/pborman/uuid/node.go b/vendor/github.com/pborman/uuid/node.go
index 42d60da8f..42d60da8f 100644..100755
--- a/vendor/github.com/pborman/uuid/node.go
+++ b/vendor/github.com/pborman/uuid/node.go
diff --git a/vendor/github.com/pborman/uuid/sql.go b/vendor/github.com/pborman/uuid/sql.go
index d015bfd13..c84f900d5 100644
--- a/vendor/github.com/pborman/uuid/sql.go
+++ b/vendor/github.com/pborman/uuid/sql.go
@@ -5,7 +5,6 @@
package uuid
import (
- "database/sql/driver"
"errors"
"fmt"
)
@@ -57,10 +56,3 @@ func (uuid *UUID) Scan(src interface{}) error {
return nil
}
-
-// Value implements sql.Valuer so that UUIDs can be written to databases
-// transparently. Currently, UUIDs map to strings. Please consult
-// database-specific driver documentation for matching types.
-func (uuid UUID) Value() (driver.Value, error) {
- return uuid.String(), nil
-}
diff --git a/vendor/github.com/pborman/uuid/sql_test.go b/vendor/github.com/pborman/uuid/sql_test.go
index 103095156..4d26392af 100644
--- a/vendor/github.com/pborman/uuid/sql_test.go
+++ b/vendor/github.com/pborman/uuid/sql_test.go
@@ -85,12 +85,3 @@ func TestScan(t *testing.T) {
t.Error("UUID was not nil after scanning empty string")
}
}
-
-func TestValue(t *testing.T) {
- stringTest := "f47ac10b-58cc-0372-8567-0e02b2c3d479"
- uuid := Parse(stringTest)
- val, _ := uuid.Value()
- if val != stringTest {
- t.Error("Value() did not return expected string")
- }
-}
diff --git a/vendor/github.com/pborman/uuid/time.go b/vendor/github.com/pborman/uuid/time.go
index eedf24219..eedf24219 100644..100755
--- a/vendor/github.com/pborman/uuid/time.go
+++ b/vendor/github.com/pborman/uuid/time.go
diff --git a/vendor/github.com/pborman/uuid/uuid.go b/vendor/github.com/pborman/uuid/uuid.go
index 7c643cf0a..c4482cd87 100644
--- a/vendor/github.com/pborman/uuid/uuid.go
+++ b/vendor/github.com/pborman/uuid/uuid.go
@@ -13,20 +13,6 @@ import (
"strings"
)
-// Array is a pass-by-value UUID that can be used as an effecient key in a map.
-type Array [16]byte
-
-// UUID converts uuid into a slice.
-func (uuid Array) UUID() UUID {
- return uuid[:]
-}
-
-// String returns the string representation of uuid,
-// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
-func (uuid Array) String() string {
- return uuid.UUID().String()
-}
-
// A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC
// 4122.
type UUID []byte
@@ -90,17 +76,6 @@ func Equal(uuid1, uuid2 UUID) bool {
return bytes.Equal(uuid1, uuid2)
}
-// Array returns an array representation of uuid that can be used as a map key.
-// Array panics if uuid is not valid.
-func (uuid UUID) Array() Array {
- if len(uuid) != 16 {
- panic("invalid uuid")
- }
- var a Array
- copy(a[:], uuid)
- return a
-}
-
// String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
// , or "" if uuid is invalid.
func (uuid UUID) String() string {
@@ -186,7 +161,7 @@ func (v Variant) String() string {
return fmt.Sprintf("BadVariant%d", int(v))
}
-// SetRand sets the random number generator to r, which implements io.Reader.
+// SetRand sets the random number generator to r, which implents io.Reader.
// If r.Read returns an error when the package requests random data then
// a panic will be issued.
//
diff --git a/vendor/github.com/pborman/uuid/uuid_test.go b/vendor/github.com/pborman/uuid/uuid_test.go
index cb1cd5cf9..3835cc808 100644
--- a/vendor/github.com/pborman/uuid/uuid_test.go
+++ b/vendor/github.com/pborman/uuid/uuid_test.go
@@ -300,7 +300,7 @@ func TestNode(t *testing.T) {
t.Error("nodeid is all zeros")
}
- id := []byte{1, 2, 3, 4, 5, 6, 7, 8}
+ id := []byte{1,2,3,4,5,6,7,8}
SetNodeID(id)
ni = NodeID()
if !bytes.Equal(ni, id[:6]) {
@@ -431,40 +431,6 @@ func TestBadRand(t *testing.T) {
}
}
-func TestUUID_Array(t *testing.T) {
- expect := Array{
- 0xf4, 0x7a, 0xc1, 0x0b,
- 0x58, 0xcc,
- 0x03, 0x72,
- 0x85, 0x67,
- 0x0e, 0x02, 0xb2, 0xc3, 0xd4, 0x79,
- }
- uuid := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479")
- if uuid == nil {
- t.Fatal("invalid uuid")
- }
- if uuid.Array() != expect {
- t.Fatal("invalid array")
- }
-}
-
-func TestArray_UUID(t *testing.T) {
- array := Array{
- 0xf4, 0x7a, 0xc1, 0x0b,
- 0x58, 0xcc,
- 0x03, 0x72,
- 0x85, 0x67,
- 0x0e, 0x02, 0xb2, 0xc3, 0xd4, 0x79,
- }
- expect := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479")
- if expect == nil {
- t.Fatal("invalid uuid")
- }
- if !bytes.Equal(array.UUID(), expect) {
- t.Fatal("invalid uuid")
- }
-}
-
func BenchmarkParse(b *testing.B) {
for i := 0; i < b.N; i++ {
uuid := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479")
@@ -503,41 +469,3 @@ func BenchmarkUUID_URN(b *testing.B) {
}
}
}
-
-func BenchmarkUUID_Array(b *testing.B) {
- expect := Array{
- 0xf4, 0x7a, 0xc1, 0x0b,
- 0x58, 0xcc,
- 0x03, 0x72,
- 0x85, 0x67,
- 0x0e, 0x02, 0xb2, 0xc3, 0xd4, 0x79,
- }
- uuid := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479")
- if uuid == nil {
- b.Fatal("invalid uuid")
- }
- for i := 0; i < b.N; i++ {
- if uuid.Array() != expect {
- b.Fatal("invalid array")
- }
- }
-}
-
-func BenchmarkArray_UUID(b *testing.B) {
- array := Array{
- 0xf4, 0x7a, 0xc1, 0x0b,
- 0x58, 0xcc,
- 0x03, 0x72,
- 0x85, 0x67,
- 0x0e, 0x02, 0xb2, 0xc3, 0xd4, 0x79,
- }
- expect := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479")
- if expect == nil {
- b.Fatal("invalid uuid")
- }
- for i := 0; i < b.N; i++ {
- if !bytes.Equal(array.UUID(), expect) {
- b.Fatal("invalid uuid")
- }
- }
-}
diff --git a/vendor/github.com/pelletier/go-toml/.travis.yml b/vendor/github.com/pelletier/go-toml/.travis.yml
index 64f03809a..1f8b41ffe 100644
--- a/vendor/github.com/pelletier/go-toml/.travis.yml
+++ b/vendor/github.com/pelletier/go-toml/.travis.yml
@@ -2,15 +2,17 @@ sudo: false
language: go
go:
- 1.6.4
- - 1.7.5
- - 1.8
+ - 1.7.6
+ - 1.8.3
- tip
matrix:
allow_failures:
- go: tip
fast_finish: true
script:
+ - if [ -n "$(go fmt ./...)" ]; then exit 1; fi
- ./test.sh
+ - ./benchmark.sh $TRAVIS_BRANCH https://github.com/$TRAVIS_REPO_SLUG.git
before_install:
- go get github.com/axw/gocov/gocov
- go get github.com/mattn/goveralls
diff --git a/vendor/github.com/pelletier/go-toml/README.md b/vendor/github.com/pelletier/go-toml/README.md
index 8279102b1..22da41a81 100644
--- a/vendor/github.com/pelletier/go-toml/README.md
+++ b/vendor/github.com/pelletier/go-toml/README.md
@@ -17,64 +17,62 @@ Go-toml provides the following features for using data parsed from TOML document
* Load TOML documents from files and string data
* Easily navigate TOML structure using Tree
+* Mashaling and unmarshaling to and from data structures
* Line & column position data for all parsed elements
* [Query support similar to JSON-Path](query/)
* Syntax errors contain line and column numbers
-Go-toml is designed to help cover use-cases not covered by reflection-based TOML parsing:
+## Import
-* Semantic evaluation of parsed TOML
-* Informing a user of mistakes in the source document, after it has been parsed
-* Programatic handling of default values on a case-by-case basis
-* Using a TOML document as a flexible data-store
+```go
+import "github.com/pelletier/go-toml"
+```
-## Import
+## Usage example
- import "github.com/pelletier/go-toml"
+Read a TOML document:
-## Usage
+```go
+config, _ := toml.LoadString(`
+[postgres]
+user = "pelletier"
+password = "mypassword"`)
+// retrieve data directly
+user := config.Get("postgres.user").(string)
-### Example
+// or using an intermediate object
+postgresConfig := config.Get("postgres").(*toml.Tree)
+password = postgresConfig.Get("password").(string)
+```
+
+Or use Unmarshal:
-Say you have a TOML file that looks like this:
+```go
+type Postgres struct {
+ User string
+ Password string
+}
+type Config struct {
+ Postgres Postgres
+}
-```toml
+doc := []byte(`
[postgres]
user = "pelletier"
-password = "mypassword"
+password = "mypassword"`)
+
+config := Config{}
+Unmarshal(doc, &config)
+fmt.Println("user=", config.Postgres.User)
```
-Read the username and password like this:
+Or use a query:
```go
-import (
- "fmt"
- "github.com/pelletier/go-toml"
-)
-
-config, err := toml.LoadFile("config.toml")
-if err != nil {
- fmt.Println("Error ", err.Error())
-} else {
- // retrieve data directly
- user := config.Get("postgres.user").(string)
- password := config.Get("postgres.password").(string)
-
- // or using an intermediate object
- configTree := config.Get("postgres").(*toml.Tree)
- user = configTree.Get("user").(string)
- password = configTree.Get("password").(string)
- fmt.Println("User is ", user, ". Password is ", password)
-
- // show where elements are in the file
- fmt.Println("User position: %v", configTree.GetPosition("user"))
- fmt.Println("Password position: %v", configTree.GetPosition("password"))
-
- // use a query to gather elements without walking the tree
- results, _ := config.Query("$..[user,password]")
- for ii, item := range results.Values() {
- fmt.Println("Query result %d: %v", ii, item)
- }
+// use a query to gather elements without walking the tree
+results, _ := config.Query("$..[user,password]")
+for ii, item := range results.Values() {
+ fmt.Println("Query result %d: %v", ii, item)
}
```
diff --git a/vendor/github.com/pelletier/go-toml/benchmark.sh b/vendor/github.com/pelletier/go-toml/benchmark.sh
new file mode 100755
index 000000000..cf1dabb4a
--- /dev/null
+++ b/vendor/github.com/pelletier/go-toml/benchmark.sh
@@ -0,0 +1,32 @@
+#!/bin/bash
+
+set -e
+
+reference_ref=${1:-master}
+reference_git=${2:-.}
+
+if ! `hash benchstat 2>/dev/null`; then
+ echo "Installing benchstat"
+ go get golang.org/x/perf/cmd/benchstat
+ go install golang.org/x/perf/cmd/benchstat
+fi
+
+tempdir=`mktemp -d /tmp/go-toml-benchmark-XXXXXX`
+ref_tempdir="${tempdir}/ref"
+ref_benchmark="${ref_tempdir}/benchmark-${reference_ref}.txt"
+local_benchmark="`pwd`/benchmark-local.txt"
+
+echo "=== ${reference_ref} (${ref_tempdir})"
+git clone ${reference_git} ${ref_tempdir} >/dev/null 2>/dev/null
+pushd ${ref_tempdir} >/dev/null
+git checkout ${reference_ref} >/dev/null 2>/dev/null
+go test -bench=. -benchmem | tee ${ref_benchmark}
+popd >/dev/null
+
+echo ""
+echo "=== local"
+go test -bench=. -benchmem | tee ${local_benchmark}
+
+echo ""
+echo "=== diff"
+benchstat -delta-test=none ${ref_benchmark} ${local_benchmark} \ No newline at end of file
diff --git a/vendor/github.com/pelletier/go-toml/cmd/tomljson/main.go b/vendor/github.com/pelletier/go-toml/cmd/tomljson/main.go
index 8bfe46210..b2d6fc673 100644
--- a/vendor/github.com/pelletier/go-toml/cmd/tomljson/main.go
+++ b/vendor/github.com/pelletier/go-toml/cmd/tomljson/main.go
@@ -1,3 +1,8 @@
+// Tomljson reads TOML and converts to JSON.
+//
+// Usage:
+// cat file.toml | tomljson > file.json
+// tomljson file1.toml > file.json
package main
import (
diff --git a/vendor/github.com/pelletier/go-toml/cmd/tomll/main.go b/vendor/github.com/pelletier/go-toml/cmd/tomll/main.go
index f185c56b9..36c7e3759 100644
--- a/vendor/github.com/pelletier/go-toml/cmd/tomll/main.go
+++ b/vendor/github.com/pelletier/go-toml/cmd/tomll/main.go
@@ -1,3 +1,8 @@
+// Tomll is a linter for TOML
+//
+// Usage:
+// cat file.toml | tomll > file_linted.toml
+// tomll file1.toml file2.toml # lint the two files in place
package main
import (
diff --git a/vendor/github.com/pelletier/go-toml/doc.go b/vendor/github.com/pelletier/go-toml/doc.go
index cfa5e4abe..3c89619e8 100644
--- a/vendor/github.com/pelletier/go-toml/doc.go
+++ b/vendor/github.com/pelletier/go-toml/doc.go
@@ -1,79 +1,18 @@
-// Package toml is a TOML markup language parser.
+// Package toml is a TOML parser and manipulation library.
//
// This version supports the specification as described in
// https://github.com/toml-lang/toml/blob/master/versions/en/toml-v0.4.0.md
//
-// TOML Parsing
+// Marshaling
//
-// TOML data may be parsed in two ways: by file, or by string.
+// Go-toml can marshal and unmarshal TOML documents from and to data
+// structures.
//
-// // load TOML data by filename
-// tree, err := toml.LoadFile("filename.toml")
+// TOML document as a tree
//
-// // load TOML data stored in a string
-// tree, err := toml.Load(stringContainingTomlData)
-//
-// Either way, the result is a Tree object that can be used to navigate the
-// structure and data within the original document.
-//
-//
-// Getting data from the Tree
-//
-// After parsing TOML data with Load() or LoadFile(), use the Has() and Get()
-// methods on the returned Tree, to find your way through the document data.
-//
-// if tree.Has("foo") {
-// fmt.Println("foo is:", tree.Get("foo"))
-// }
-//
-// Working with Paths
-//
-// Go-toml has support for basic dot-separated key paths on the Has(), Get(), Set()
-// and GetDefault() methods. These are the same kind of key paths used within the
-// TOML specification for struct tames.
-//
-// // looks for a key named 'baz', within struct 'bar', within struct 'foo'
-// tree.Has("foo.bar.baz")
-//
-// // returns the key at this path, if it is there
-// tree.Get("foo.bar.baz")
-//
-// TOML allows keys to contain '.', which can cause this syntax to be problematic
-// for some documents. In such cases, use the GetPath(), HasPath(), and SetPath(),
-// methods to explicitly define the path. This form is also faster, since
-// it avoids having to parse the passed key for '.' delimiters.
-//
-// // looks for a key named 'baz', within struct 'bar', within struct 'foo'
-// tree.HasPath([]string{"foo","bar","baz"})
-//
-// // returns the key at this path, if it is there
-// tree.GetPath([]string{"foo","bar","baz"})
-//
-// Note that this is distinct from the heavyweight query syntax supported by
-// Tree.Query() and the Query() struct (see below).
-//
-// Position Support
-//
-// Each element within the Tree is stored with position metadata, which is
-// invaluable for providing semantic feedback to a user. This helps in
-// situations where the TOML file parses correctly, but contains data that is
-// not correct for the application. In such cases, an error message can be
-// generated that indicates the problem line and column number in the source
-// TOML document.
-//
-// // load TOML data
-// tree, _ := toml.Load("filename.toml")
-//
-// // get an entry and report an error if it's the wrong type
-// element := tree.Get("foo")
-// if value, ok := element.(int64); !ok {
-// return fmt.Errorf("%v: Element 'foo' must be an integer", tree.GetPosition("foo"))
-// }
-//
-// // report an error if an expected element is missing
-// if !tree.Has("bar") {
-// return fmt.Errorf("%v: Expected 'bar' element", tree.GetPosition(""))
-// }
+// Go-toml can operate on a TOML document as a tree. Use one of the Load*
+// functions to parse TOML data and obtain a Tree instance, then one of its
+// methods to manipulate the tree.
//
// JSONPath-like queries
//
diff --git a/vendor/github.com/pelletier/go-toml/doc_test.go b/vendor/github.com/pelletier/go-toml/doc_test.go
index 31b4f40b5..9dd773899 100644
--- a/vendor/github.com/pelletier/go-toml/doc_test.go
+++ b/vendor/github.com/pelletier/go-toml/doc_test.go
@@ -6,7 +6,7 @@ import (
"fmt"
)
-func Example_comprehensiveExample() {
+func Example_tree() {
config, err := LoadFile("config.toml")
if err != nil {
@@ -20,10 +20,34 @@ func Example_comprehensiveExample() {
configTree := config.Get("postgres").(*Tree)
user = configTree.Get("user").(string)
password = configTree.Get("password").(string)
- fmt.Println("User is ", user, ". Password is ", password)
+ fmt.Println("User is", user, " and password is", password)
// show where elements are in the file
fmt.Printf("User position: %v\n", configTree.GetPosition("user"))
fmt.Printf("Password position: %v\n", configTree.GetPosition("password"))
}
}
+
+func Example_unmarshal() {
+ type Employer struct {
+ Name string
+ Phone string
+ }
+ type Person struct {
+ Name string
+ Age int64
+ Employer Employer
+ }
+
+ document := []byte(`
+ name = "John"
+ age = 30
+ [employer]
+ name = "Company Inc."
+ phone = "+1 234 567 89012"
+ `)
+
+ person := Person{}
+ Unmarshal(document, &person)
+ fmt.Println(person.Name, "is", person.Age, "and works at", person.Employer.Name)
+}
diff --git a/vendor/github.com/pelletier/go-toml/lexer.go b/vendor/github.com/pelletier/go-toml/lexer.go
index 104f3b1f4..db3ab4e54 100644
--- a/vendor/github.com/pelletier/go-toml/lexer.go
+++ b/vendor/github.com/pelletier/go-toml/lexer.go
@@ -6,6 +6,7 @@
package toml
import (
+ "bytes"
"errors"
"fmt"
"io"
@@ -24,7 +25,7 @@ type tomlLexStateFn func() tomlLexStateFn
// Define lexer
type tomlLexer struct {
input *buffruneio.Reader // Textual source
- buffer []rune // Runes composing the current token
+ buffer bytes.Buffer // Runes composing the current token
tokens chan token
depth int
line int
@@ -53,13 +54,13 @@ func (l *tomlLexer) next() rune {
r := l.read()
if r != eof {
- l.buffer = append(l.buffer, r)
+ l.buffer.WriteRune(r)
}
return r
}
func (l *tomlLexer) ignore() {
- l.buffer = make([]rune, 0)
+ l.buffer.Reset()
l.line = l.endbufferLine
l.col = l.endbufferCol
}
@@ -85,7 +86,7 @@ func (l *tomlLexer) emitWithValue(t tokenType, value string) {
}
func (l *tomlLexer) emit(t tokenType) {
- l.emitWithValue(t, string(l.buffer))
+ l.emitWithValue(t, l.buffer.String())
}
func (l *tomlLexer) peek() rune {
@@ -536,7 +537,7 @@ func (l *tomlLexer) lexInsideTableArrayKey() tomlLexStateFn {
for r := l.peek(); r != eof; r = l.peek() {
switch r {
case ']':
- if len(l.buffer) > 0 {
+ if l.buffer.Len() > 0 {
l.emit(tokenKeyGroupArray)
}
l.next()
@@ -559,7 +560,7 @@ func (l *tomlLexer) lexInsideTableKey() tomlLexStateFn {
for r := l.peek(); r != eof; r = l.peek() {
switch r {
case ']':
- if len(l.buffer) > 0 {
+ if l.buffer.Len() > 0 {
l.emit(tokenKeyGroup)
}
l.next()
diff --git a/vendor/github.com/pelletier/go-toml/lexer_test.go b/vendor/github.com/pelletier/go-toml/lexer_test.go
index 6b324ea0e..dce7a630a 100644
--- a/vendor/github.com/pelletier/go-toml/lexer_test.go
+++ b/vendor/github.com/pelletier/go-toml/lexer_test.go
@@ -1,6 +1,7 @@
package toml
import (
+ "os"
"strings"
"testing"
)
@@ -748,3 +749,31 @@ func TestLexUnknownRvalue(t *testing.T) {
{Position{1, 5}, tokenError, `no value can start with \`},
})
}
+
+func BenchmarkLexer(b *testing.B) {
+ sample := `title = "Hugo: A Fast and Flexible Website Generator"
+baseurl = "http://gohugo.io/"
+MetaDataFormat = "yaml"
+pluralizeListTitles = false
+
+[params]
+ description = "Documentation of Hugo, a fast and flexible static site generator built with love by spf13, bep and friends in Go"
+ author = "Steve Francia (spf13) and friends"
+ release = "0.22-DEV"
+
+[[menu.main]]
+ name = "Download Hugo"
+ pre = "<i class='fa fa-download'></i>"
+ url = "https://github.com/spf13/hugo/releases"
+ weight = -200
+`
+ rd := strings.NewReader(sample)
+
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ rd.Seek(0, os.SEEK_SET)
+ ch := lexToml(rd)
+ for _ = range ch {
+ }
+ }
+}
diff --git a/vendor/github.com/pelletier/go-toml/marshal.go b/vendor/github.com/pelletier/go-toml/marshal.go
index 358425aea..9bf6fb988 100644
--- a/vendor/github.com/pelletier/go-toml/marshal.go
+++ b/vendor/github.com/pelletier/go-toml/marshal.go
@@ -9,24 +9,6 @@ import (
"time"
)
-/*
-Tree structural types and corresponding marshal types
--------------------------------------------------------------------------------
-*Tree (*)struct, (*)map[string]interface{}
-[]*Tree (*)[](*)struct, (*)[](*)map[string]interface{}
-[]interface{} (as interface{}) (*)[]primitive, (*)[]([]interface{})
-interface{} (*)primitive
-
-Tree primitive types and corresponding marshal types
------------------------------------------------------------
-uint64 uint, uint8-uint64, pointers to same
-int64 int, int8-uint64, pointers to same
-float64 float32, float64, pointers to same
-string string, pointers to same
-bool bool, pointers to same
-time.Time time.Time{}, pointers to same
-*/
-
type tomlOpts struct {
name string
include bool
@@ -115,6 +97,22 @@ function for sub-structs, and currently only definite types can be marshaled
Note that pointers are automatically assigned the "omitempty" option, as TOML
explicity does not handle null values (saying instead the label should be
dropped).
+
+Tree structural types and corresponding marshal types:
+
+ *Tree (*)struct, (*)map[string]interface{}
+ []*Tree (*)[](*)struct, (*)[](*)map[string]interface{}
+ []interface{} (as interface{}) (*)[]primitive, (*)[]([]interface{})
+ interface{} (*)primitive
+
+Tree primitive types and corresponding marshal types:
+
+ uint64 uint, uint8-uint64, pointers to same
+ int64 int, int8-uint64, pointers to same
+ float64 float32, float64, pointers to same
+ string string, pointers to same
+ bool bool, pointers to same
+ time.Time time.Time{}, pointers to same
*/
func Marshal(v interface{}) ([]byte, error) {
mtype := reflect.TypeOf(v)
@@ -247,6 +245,8 @@ func (t *Tree) Unmarshal(v interface{}) error {
// is no concept of an Unmarshaler interface or UnmarshalTOML function for
// sub-structs, and currently only definite types can be unmarshaled to (i.e. no
// `interface{}`).
+//
+// See Marshal() documentation for types mapping table.
func Unmarshal(data []byte, v interface{}) error {
t, err := LoadReader(bytes.NewReader(data))
if err != nil {
diff --git a/vendor/github.com/pelletier/go-toml/marshal_test.go b/vendor/github.com/pelletier/go-toml/marshal_test.go
index dbfc7c1d1..a3fa128d2 100644
--- a/vendor/github.com/pelletier/go-toml/marshal_test.go
+++ b/vendor/github.com/pelletier/go-toml/marshal_test.go
@@ -177,6 +177,25 @@ func TestDocUnmarshal(t *testing.T) {
}
}
+func ExampleUnmarshal() {
+ type Postgres struct {
+ User string
+ Password string
+ }
+ type Config struct {
+ Postgres Postgres
+ }
+
+ doc := []byte(`
+ [postgres]
+ user = "pelletier"
+ password = "mypassword"`)
+
+ config := Config{}
+ Unmarshal(doc, &config)
+ fmt.Println("user=", config.Postgres.User)
+}
+
func TestDocPartialUnmarshal(t *testing.T) {
result := testDocSubs{}
diff --git a/vendor/github.com/pelletier/go-toml/query/lexer.go b/vendor/github.com/pelletier/go-toml/query/lexer.go
index 6336d52cd..2dc319408 100644
--- a/vendor/github.com/pelletier/go-toml/query/lexer.go
+++ b/vendor/github.com/pelletier/go-toml/query/lexer.go
@@ -7,10 +7,10 @@ package query
import (
"fmt"
+ "github.com/pelletier/go-toml"
"strconv"
"strings"
"unicode/utf8"
- "github.com/pelletier/go-toml"
)
// Lexer state function
@@ -55,7 +55,7 @@ func (l *queryLexer) nextStart() {
func (l *queryLexer) emit(t tokenType) {
l.tokens <- token{
- Position: toml.Position{Line:l.line, Col:l.col},
+ Position: toml.Position{Line: l.line, Col: l.col},
typ: t,
val: l.input[l.start:l.pos],
}
@@ -64,7 +64,7 @@ func (l *queryLexer) emit(t tokenType) {
func (l *queryLexer) emitWithValue(t tokenType, value string) {
l.tokens <- token{
- Position: toml.Position{Line:l.line, Col:l.col},
+ Position: toml.Position{Line: l.line, Col: l.col},
typ: t,
val: value,
}
@@ -92,7 +92,7 @@ func (l *queryLexer) backup() {
func (l *queryLexer) errorf(format string, args ...interface{}) queryLexStateFn {
l.tokens <- token{
- Position: toml.Position{Line:l.line, Col:l.col},
+ Position: toml.Position{Line: l.line, Col: l.col},
typ: tokenError,
val: fmt.Sprintf(format, args...),
}
diff --git a/vendor/github.com/pelletier/go-toml/query/lexer_test.go b/vendor/github.com/pelletier/go-toml/query/lexer_test.go
index e2b733a34..8ce0501fe 100644
--- a/vendor/github.com/pelletier/go-toml/query/lexer_test.go
+++ b/vendor/github.com/pelletier/go-toml/query/lexer_test.go
@@ -1,8 +1,8 @@
package query
import (
- "testing"
"github.com/pelletier/go-toml"
+ "testing"
)
func testQLFlow(t *testing.T, input string, expectedFlow []token) {
diff --git a/vendor/github.com/pelletier/go-toml/query/match_test.go b/vendor/github.com/pelletier/go-toml/query/match_test.go
index 567b11cd7..429b8f6b9 100644
--- a/vendor/github.com/pelletier/go-toml/query/match_test.go
+++ b/vendor/github.com/pelletier/go-toml/query/match_test.go
@@ -2,8 +2,8 @@ package query
import (
"fmt"
- "testing"
"github.com/pelletier/go-toml"
+ "testing"
)
// dump path tree to a string
diff --git a/vendor/github.com/pelletier/go-toml/query/parser_test.go b/vendor/github.com/pelletier/go-toml/query/parser_test.go
index b1d0a3ece..473896a02 100644
--- a/vendor/github.com/pelletier/go-toml/query/parser_test.go
+++ b/vendor/github.com/pelletier/go-toml/query/parser_test.go
@@ -2,12 +2,12 @@ package query
import (
"fmt"
+ "github.com/pelletier/go-toml"
"io/ioutil"
"sort"
"strings"
"testing"
"time"
- "github.com/pelletier/go-toml"
)
type queryTestNode struct {
diff --git a/vendor/github.com/pelletier/go-toml/query/tokens.go b/vendor/github.com/pelletier/go-toml/query/tokens.go
index 429e289ab..9ae579de2 100644
--- a/vendor/github.com/pelletier/go-toml/query/tokens.go
+++ b/vendor/github.com/pelletier/go-toml/query/tokens.go
@@ -1,10 +1,10 @@
package query
import (
-"fmt"
-"strconv"
-"unicode"
+ "fmt"
"github.com/pelletier/go-toml"
+ "strconv"
+ "unicode"
)
// Define tokens
@@ -104,4 +104,3 @@ func isHexDigit(r rune) bool {
(r >= 'a' && r <= 'f') ||
(r >= 'A' && r <= 'F')
}
-
diff --git a/vendor/github.com/pelletier/go-toml/toml.go b/vendor/github.com/pelletier/go-toml/toml.go
index 99663217e..2d2f64049 100644
--- a/vendor/github.com/pelletier/go-toml/toml.go
+++ b/vendor/github.com/pelletier/go-toml/toml.go
@@ -54,8 +54,7 @@ func (t *Tree) HasPath(keys []string) bool {
return t.GetPath(keys) != nil
}
-// Keys returns the keys of the toplevel tree.
-// Warning: this is a costly operation.
+// Keys returns the keys of the toplevel tree (does not recurse).
func (t *Tree) Keys() []string {
keys := make([]string, len(t.values))
i := 0
diff --git a/vendor/github.com/pelletier/go-toml/tomltree_create.go b/vendor/github.com/pelletier/go-toml/tomltree_create.go
index ee7114ed8..19d1c0dc6 100644
--- a/vendor/github.com/pelletier/go-toml/tomltree_create.go
+++ b/vendor/github.com/pelletier/go-toml/tomltree_create.go
@@ -6,10 +6,7 @@ import (
"time"
)
-// supported values:
-// string, bool, int64, uint64, float64, time.Time, int, int8, int16, int32, uint, uint8, uint16, uint32, float32
-
-var kindToTypeMapping = map[reflect.Kind]reflect.Type{
+var kindToType = [reflect.String + 1]reflect.Type{
reflect.Bool: reflect.TypeOf(true),
reflect.String: reflect.TypeOf(""),
reflect.Float32: reflect.TypeOf(float64(1)),
@@ -26,6 +23,16 @@ var kindToTypeMapping = map[reflect.Kind]reflect.Type{
reflect.Uint64: reflect.TypeOf(uint64(1)),
}
+// typeFor returns a reflect.Type for a reflect.Kind, or nil if none is found.
+// supported values:
+// string, bool, int64, uint64, float64, time.Time, int, int8, int16, int32, uint, uint8, uint16, uint32, float32
+func typeFor(k reflect.Kind) reflect.Type {
+ if k > 0 && int(k) < len(kindToType) {
+ return kindToType[k]
+ }
+ return nil
+}
+
func simpleValueCoercion(object interface{}) (interface{}, error) {
switch original := object.(type) {
case string, bool, int64, uint64, float64, time.Time:
@@ -82,7 +89,7 @@ func sliceToTree(object interface{}) (interface{}, error) {
return tablesArray, nil
}
- sliceType := kindToTypeMapping[insideType.Kind()]
+ sliceType := typeFor(insideType.Kind())
if sliceType == nil {
sliceType = insideType
}
diff --git a/vendor/github.com/pelletier/go-toml/tomltree_write.go b/vendor/github.com/pelletier/go-toml/tomltree_write.go
index d27afc118..cd03f9dba 100644
--- a/vendor/github.com/pelletier/go-toml/tomltree_write.go
+++ b/vendor/github.com/pelletier/go-toml/tomltree_write.go
@@ -4,6 +4,7 @@ import (
"bytes"
"fmt"
"io"
+ "math"
"reflect"
"sort"
"strconv"
@@ -13,33 +14,34 @@ import (
// encodes a string to a TOML-compliant string value
func encodeTomlString(value string) string {
- result := ""
+ var b bytes.Buffer
+
for _, rr := range value {
switch rr {
case '\b':
- result += "\\b"
+ b.WriteString(`\b`)
case '\t':
- result += "\\t"
+ b.WriteString(`\t`)
case '\n':
- result += "\\n"
+ b.WriteString(`\n`)
case '\f':
- result += "\\f"
+ b.WriteString(`\f`)
case '\r':
- result += "\\r"
+ b.WriteString(`\r`)
case '"':
- result += "\\\""
+ b.WriteString(`\"`)
case '\\':
- result += "\\\\"
+ b.WriteString(`\\`)
default:
intRr := uint16(rr)
if intRr < 0x001F {
- result += fmt.Sprintf("\\u%0.4X", intRr)
+ b.WriteString(fmt.Sprintf("\\u%0.4X", intRr))
} else {
- result += string(rr)
+ b.WriteRune(rr)
}
}
}
- return result
+ return b.String()
}
func tomlValueStringRepresentation(v interface{}) (string, error) {
@@ -49,6 +51,11 @@ func tomlValueStringRepresentation(v interface{}) (string, error) {
case int64:
return strconv.FormatInt(value, 10), nil
case float64:
+ // Ensure a round float does contain a decimal point. Otherwise feeding
+ // the output back to the parser would convert to an integer.
+ if math.Trunc(value) == value {
+ return strconv.FormatFloat(value, 'f', 1, 32), nil
+ }
return strconv.FormatFloat(value, 'f', -1, 32), nil
case string:
return "\"" + encodeTomlString(value) + "\"", nil
@@ -111,7 +118,7 @@ func (t *Tree) writeTo(w io.Writer, indent, keyspace string, bytesCount int64) (
return bytesCount, err
}
- kvRepr := fmt.Sprintf("%s%s = %s\n", indent, k, repr)
+ kvRepr := indent + k + " = " + repr + "\n"
writtenBytesCount, err := w.Write([]byte(kvRepr))
bytesCount += int64(writtenBytesCount)
if err != nil {
@@ -130,7 +137,7 @@ func (t *Tree) writeTo(w io.Writer, indent, keyspace string, bytesCount int64) (
switch node := v.(type) {
// node has to be of those two types given how keys are sorted above
case *Tree:
- tableName := fmt.Sprintf("\n%s[%s]\n", indent, combinedKey)
+ tableName := "\n" + indent + "[" + combinedKey + "]\n"
writtenBytesCount, err := w.Write([]byte(tableName))
bytesCount += int64(writtenBytesCount)
if err != nil {
@@ -142,18 +149,16 @@ func (t *Tree) writeTo(w io.Writer, indent, keyspace string, bytesCount int64) (
}
case []*Tree:
for _, subTree := range node {
- if len(subTree.values) > 0 {
- tableArrayName := fmt.Sprintf("\n%s[[%s]]\n", indent, combinedKey)
- writtenBytesCount, err := w.Write([]byte(tableArrayName))
- bytesCount += int64(writtenBytesCount)
- if err != nil {
- return bytesCount, err
- }
-
- bytesCount, err = subTree.writeTo(w, indent+" ", combinedKey, bytesCount)
- if err != nil {
- return bytesCount, err
- }
+ tableArrayName := "\n" + indent + "[[" + combinedKey + "]]\n"
+ writtenBytesCount, err := w.Write([]byte(tableArrayName))
+ bytesCount += int64(writtenBytesCount)
+ if err != nil {
+ return bytesCount, err
+ }
+
+ bytesCount, err = subTree.writeTo(w, indent+" ", combinedKey, bytesCount)
+ if err != nil {
+ return bytesCount, err
}
}
}
diff --git a/vendor/github.com/pelletier/go-toml/tomltree_write_test.go b/vendor/github.com/pelletier/go-toml/tomltree_write_test.go
index 1a006da3c..0edf1be46 100644
--- a/vendor/github.com/pelletier/go-toml/tomltree_write_test.go
+++ b/vendor/github.com/pelletier/go-toml/tomltree_write_test.go
@@ -40,6 +40,30 @@ func assertErrorString(t *testing.T, expected string, err error) {
}
}
+func TestTreeWriteToEmptyTable(t *testing.T) {
+ doc := `[[empty-tables]]
+[[empty-tables]]`
+
+ toml, err := Load(doc)
+ if err != nil {
+ t.Fatal("Unexpected Load error:", err)
+ }
+ tomlString, err := toml.ToTomlString()
+ if err != nil {
+ t.Fatal("Unexpected ToTomlString error:", err)
+ }
+
+ expected := `
+[[empty-tables]]
+
+[[empty-tables]]
+`
+
+ if tomlString != expected {
+ t.Fatalf("Expected:\n%s\nGot:\n%s", expected, tomlString)
+ }
+}
+
func TestTreeWriteToTomlString(t *testing.T) {
toml, err := Load(`name = { first = "Tom", last = "Preston-Werner" }
points = { x = 1, y = 2 }`)
@@ -269,3 +293,66 @@ func TestTreeWriteToMapWithArrayOfInlineTables(t *testing.T) {
treeMap := tree.ToMap()
testMaps(t, treeMap, expected)
}
+
+func TestTreeWriteToFloat(t *testing.T) {
+ tree, err := Load(`a = 3.0`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ str, err := tree.ToTomlString()
+ if err != nil {
+ t.Fatal(err)
+ }
+ expected := `a = 3.0`
+ if strings.TrimSpace(str) != strings.TrimSpace(expected) {
+ t.Fatalf("Expected:\n%s\nGot:\n%s", expected, str)
+ }
+}
+
+func BenchmarkTreeToTomlString(b *testing.B) {
+ toml, err := Load(sampleHard)
+ if err != nil {
+ b.Fatal("Unexpected error:", err)
+ }
+
+ for i := 0; i < b.N; i++ {
+ _, err := toml.ToTomlString()
+ if err != nil {
+ b.Fatal(err)
+ }
+ }
+}
+
+var sampleHard = `# Test file for TOML
+# Only this one tries to emulate a TOML file written by a user of the kind of parser writers probably hate
+# This part you'll really hate
+
+[the]
+test_string = "You'll hate me after this - #" # " Annoying, isn't it?
+
+ [the.hard]
+ test_array = [ "] ", " # "] # ] There you go, parse this!
+ test_array2 = [ "Test #11 ]proved that", "Experiment #9 was a success" ]
+ # You didn't think it'd as easy as chucking out the last #, did you?
+ another_test_string = " Same thing, but with a string #"
+ harder_test_string = " And when \"'s are in the string, along with # \"" # "and comments are there too"
+ # Things will get harder
+
+ [the.hard."bit#"]
+ "what?" = "You don't think some user won't do that?"
+ multi_line_array = [
+ "]",
+ # ] Oh yes I did
+ ]
+
+# Each of the following keygroups/key value pairs should produce an error. Uncomment to them to test
+
+#[error] if you didn't catch this, your parser is broken
+#string = "Anything other than tabs, spaces and newline after a keygroup or key value pair has ended should produce an error unless it is a comment" like this
+#array = [
+# "This might most likely happen in multiline arrays",
+# Like here,
+# "or here,
+# and here"
+# ] End of array comment, forgot the #
+#number = 3.14 pi <--again forgot the # `
diff --git a/vendor/github.com/prometheus/client_golang/.travis.yml b/vendor/github.com/prometheus/client_golang/.travis.yml
index 85b51152e..d83f31a59 100644
--- a/vendor/github.com/prometheus/client_golang/.travis.yml
+++ b/vendor/github.com/prometheus/client_golang/.travis.yml
@@ -2,9 +2,8 @@ sudo: false
language: go
go:
- - 1.6.3
- - 1.7
- - 1.8.1
+ - 1.5.4
+ - 1.6.2
script:
- - go test -short ./...
+ - go test -short ./...
diff --git a/vendor/github.com/prometheus/client_golang/AUTHORS.md b/vendor/github.com/prometheus/client_golang/AUTHORS.md
new file mode 100644
index 000000000..c5275d5ab
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/AUTHORS.md
@@ -0,0 +1,18 @@
+The Prometheus project was started by Matt T. Proud (emeritus) and
+Julius Volz in 2012.
+
+Maintainers of this repository:
+
+* Björn Rabenstein <beorn@soundcloud.com>
+
+The following individuals have contributed code to this repository
+(listed in alphabetical order):
+
+* Bernerd Schaefer <bj.schaefer@gmail.com>
+* Björn Rabenstein <beorn@soundcloud.com>
+* Daniel Bornkessel <daniel@soundcloud.com>
+* Jeff Younker <jeff@drinktomi.com>
+* Julius Volz <julius.volz@gmail.com>
+* Matt T. Proud <matt.proud@gmail.com>
+* Tobias Schmidt <ts@soundcloud.com>
+
diff --git a/vendor/github.com/prometheus/client_golang/CONTRIBUTING.md b/vendor/github.com/prometheus/client_golang/CONTRIBUTING.md
index 40503edbf..5705f0fbe 100644
--- a/vendor/github.com/prometheus/client_golang/CONTRIBUTING.md
+++ b/vendor/github.com/prometheus/client_golang/CONTRIBUTING.md
@@ -2,9 +2,9 @@
Prometheus uses GitHub to manage reviews of pull requests.
-* If you have a trivial fix or improvement, go ahead and create a pull request,
- addressing (with `@...`) the maintainer of this repository (see
- [MAINTAINERS.md](MAINTAINERS.md)) in the description of the pull request.
+* If you have a trivial fix or improvement, go ahead and create a pull
+ request, addressing (with `@...`) one or more of the maintainers
+ (see [AUTHORS.md](AUTHORS.md)) in the description of the pull request.
* If you plan to do something more involved, first discuss your ideas
on our [mailing list](https://groups.google.com/forum/?fromgroups#!forum/prometheus-developers).
diff --git a/vendor/github.com/prometheus/client_golang/MAINTAINERS.md b/vendor/github.com/prometheus/client_golang/MAINTAINERS.md
deleted file mode 100644
index 3ede55fe1..000000000
--- a/vendor/github.com/prometheus/client_golang/MAINTAINERS.md
+++ /dev/null
@@ -1 +0,0 @@
-* Björn Rabenstein <beorn@soundcloud.com>
diff --git a/vendor/github.com/prometheus/client_golang/README.md b/vendor/github.com/prometheus/client_golang/README.md
index 479290d27..557eacf5a 100644
--- a/vendor/github.com/prometheus/client_golang/README.md
+++ b/vendor/github.com/prometheus/client_golang/README.md
@@ -1,7 +1,6 @@
# Prometheus Go client library
[![Build Status](https://travis-ci.org/prometheus/client_golang.svg?branch=master)](https://travis-ci.org/prometheus/client_golang)
-[![Go Report Card](https://goreportcard.com/badge/github.com/prometheus/client_golang)](https://goreportcard.com/report/github.com/prometheus/client_golang)
This is the [Go](http://golang.org) client library for
[Prometheus](http://prometheus.io). It has two separate parts, one for
@@ -30,8 +29,7 @@ The
[`api/prometheus` directory](https://github.com/prometheus/client_golang/tree/master/api/prometheus)
contains the client for the
[Prometheus HTTP API](http://prometheus.io/docs/querying/api/). It allows you
-to write Go applications that query time series data from a Prometheus
-server. It is still in alpha stage.
+to write Go applications that query time series data from a Prometheus server.
## Where is `model`, `extraction`, and `text`?
diff --git a/vendor/github.com/prometheus/client_golang/api/client.go b/vendor/github.com/prometheus/client_golang/api/client.go
deleted file mode 100644
index bf2672466..000000000
--- a/vendor/github.com/prometheus/client_golang/api/client.go
+++ /dev/null
@@ -1,131 +0,0 @@
-// Copyright 2015 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// +build go1.7
-
-// Package api provides clients for the HTTP APIs.
-package api
-
-import (
- "context"
- "io/ioutil"
- "net"
- "net/http"
- "net/url"
- "path"
- "strings"
- "time"
-)
-
-// DefaultRoundTripper is used if no RoundTripper is set in Config.
-var DefaultRoundTripper http.RoundTripper = &http.Transport{
- Proxy: http.ProxyFromEnvironment,
- Dial: (&net.Dialer{
- Timeout: 30 * time.Second,
- KeepAlive: 30 * time.Second,
- }).Dial,
- TLSHandshakeTimeout: 10 * time.Second,
-}
-
-// Config defines configuration parameters for a new client.
-type Config struct {
- // The address of the Prometheus to connect to.
- Address string
-
- // RoundTripper is used by the Client to drive HTTP requests. If not
- // provided, DefaultRoundTripper will be used.
- RoundTripper http.RoundTripper
-}
-
-func (cfg *Config) roundTripper() http.RoundTripper {
- if cfg.RoundTripper == nil {
- return DefaultRoundTripper
- }
- return cfg.RoundTripper
-}
-
-// Client is the interface for an API client.
-type Client interface {
- URL(ep string, args map[string]string) *url.URL
- Do(context.Context, *http.Request) (*http.Response, []byte, error)
-}
-
-// NewClient returns a new Client.
-//
-// It is safe to use the returned Client from multiple goroutines.
-func NewClient(cfg Config) (Client, error) {
- u, err := url.Parse(cfg.Address)
- if err != nil {
- return nil, err
- }
- u.Path = strings.TrimRight(u.Path, "/")
-
- return &httpClient{
- endpoint: u,
- client: http.Client{Transport: cfg.roundTripper()},
- }, nil
-}
-
-type httpClient struct {
- endpoint *url.URL
- client http.Client
-}
-
-func (c *httpClient) URL(ep string, args map[string]string) *url.URL {
- p := path.Join(c.endpoint.Path, ep)
-
- for arg, val := range args {
- arg = ":" + arg
- p = strings.Replace(p, arg, val, -1)
- }
-
- u := *c.endpoint
- u.Path = p
-
- return &u
-}
-
-func (c *httpClient) Do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) {
- if ctx != nil {
- req = req.WithContext(ctx)
- }
- resp, err := c.client.Do(req)
- defer func() {
- if resp != nil {
- resp.Body.Close()
- }
- }()
-
- if err != nil {
- return nil, nil, err
- }
-
- var body []byte
- done := make(chan struct{})
- go func() {
- body, err = ioutil.ReadAll(resp.Body)
- close(done)
- }()
-
- select {
- case <-ctx.Done():
- err = resp.Body.Close()
- <-done
- if err == nil {
- err = ctx.Err()
- }
- case <-done:
- }
-
- return resp, body, err
-}
diff --git a/vendor/github.com/prometheus/client_golang/api/client_test.go b/vendor/github.com/prometheus/client_golang/api/client_test.go
deleted file mode 100644
index 53226d7d2..000000000
--- a/vendor/github.com/prometheus/client_golang/api/client_test.go
+++ /dev/null
@@ -1,115 +0,0 @@
-// Copyright 2015 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// +build go1.7
-
-package api
-
-import (
- "net/http"
- "net/url"
- "testing"
-)
-
-func TestConfig(t *testing.T) {
- c := Config{}
- if c.roundTripper() != DefaultRoundTripper {
- t.Fatalf("expected default roundtripper for nil RoundTripper field")
- }
-}
-
-func TestClientURL(t *testing.T) {
- tests := []struct {
- address string
- endpoint string
- args map[string]string
- expected string
- }{
- {
- address: "http://localhost:9090",
- endpoint: "/test",
- expected: "http://localhost:9090/test",
- },
- {
- address: "http://localhost",
- endpoint: "/test",
- expected: "http://localhost/test",
- },
- {
- address: "http://localhost:9090",
- endpoint: "test",
- expected: "http://localhost:9090/test",
- },
- {
- address: "http://localhost:9090/prefix",
- endpoint: "/test",
- expected: "http://localhost:9090/prefix/test",
- },
- {
- address: "https://localhost:9090/",
- endpoint: "/test/",
- expected: "https://localhost:9090/test",
- },
- {
- address: "http://localhost:9090",
- endpoint: "/test/:param",
- args: map[string]string{
- "param": "content",
- },
- expected: "http://localhost:9090/test/content",
- },
- {
- address: "http://localhost:9090",
- endpoint: "/test/:param/more/:param",
- args: map[string]string{
- "param": "content",
- },
- expected: "http://localhost:9090/test/content/more/content",
- },
- {
- address: "http://localhost:9090",
- endpoint: "/test/:param/more/:foo",
- args: map[string]string{
- "param": "content",
- "foo": "bar",
- },
- expected: "http://localhost:9090/test/content/more/bar",
- },
- {
- address: "http://localhost:9090",
- endpoint: "/test/:param",
- args: map[string]string{
- "nonexistant": "content",
- },
- expected: "http://localhost:9090/test/:param",
- },
- }
-
- for _, test := range tests {
- ep, err := url.Parse(test.address)
- if err != nil {
- t.Fatal(err)
- }
-
- hclient := &httpClient{
- endpoint: ep,
- client: http.Client{Transport: DefaultRoundTripper},
- }
-
- u := hclient.URL(test.endpoint, test.args)
- if u.String() != test.expected {
- t.Errorf("unexpected result: got %s, want %s", u, test.expected)
- continue
- }
- }
-}
diff --git a/vendor/github.com/prometheus/client_golang/api/prometheus/v1/api.go b/vendor/github.com/prometheus/client_golang/api/prometheus/api.go
index 734a12e7c..3028d741d 100644
--- a/vendor/github.com/prometheus/client_golang/api/prometheus/v1/api.go
+++ b/vendor/github.com/prometheus/client_golang/api/prometheus/api.go
@@ -1,4 +1,4 @@
-// Copyright 2017 The Prometheus Authors
+// Copyright 2015 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -11,40 +11,41 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-// +build go1.7
-
-// Package v1 provides bindings to the Prometheus HTTP API v1:
+// Package prometheus provides bindings to the Prometheus HTTP API:
// http://prometheus.io/docs/querying/api/
-package v1
+package prometheus
import (
- "context"
"encoding/json"
"fmt"
+ "io/ioutil"
+ "net"
"net/http"
+ "net/url"
+ "path"
"strconv"
+ "strings"
"time"
- "github.com/prometheus/client_golang/api"
"github.com/prometheus/common/model"
+ "golang.org/x/net/context"
+ "golang.org/x/net/context/ctxhttp"
)
const (
statusAPIError = 422
+ apiPrefix = "/api/v1"
- apiPrefix = "/api/v1"
-
- epQuery = apiPrefix + "/query"
- epQueryRange = apiPrefix + "/query_range"
- epLabelValues = apiPrefix + "/label/:name/values"
- epSeries = apiPrefix + "/series"
+ epQuery = "/query"
+ epQueryRange = "/query_range"
+ epLabelValues = "/label/:name/values"
+ epSeries = "/series"
)
-// ErrorType models the different API error types.
type ErrorType string
-// Possible values for ErrorType.
const (
+ // The different API error types.
ErrBadData ErrorType = "bad_data"
ErrTimeout = "timeout"
ErrCanceled = "canceled"
@@ -62,6 +63,166 @@ func (e *Error) Error() string {
return fmt.Sprintf("%s: %s", e.Type, e.Msg)
}
+// CancelableTransport is like net.Transport but provides
+// per-request cancelation functionality.
+type CancelableTransport interface {
+ http.RoundTripper
+ CancelRequest(req *http.Request)
+}
+
+var DefaultTransport CancelableTransport = &http.Transport{
+ Proxy: http.ProxyFromEnvironment,
+ Dial: (&net.Dialer{
+ Timeout: 30 * time.Second,
+ KeepAlive: 30 * time.Second,
+ }).Dial,
+ TLSHandshakeTimeout: 10 * time.Second,
+}
+
+// Config defines configuration parameters for a new client.
+type Config struct {
+ // The address of the Prometheus to connect to.
+ Address string
+
+ // Transport is used by the Client to drive HTTP requests. If not
+ // provided, DefaultTransport will be used.
+ Transport CancelableTransport
+}
+
+func (cfg *Config) transport() CancelableTransport {
+ if cfg.Transport == nil {
+ return DefaultTransport
+ }
+ return cfg.Transport
+}
+
+type Client interface {
+ url(ep string, args map[string]string) *url.URL
+ do(context.Context, *http.Request) (*http.Response, []byte, error)
+}
+
+// New returns a new Client.
+//
+// It is safe to use the returned Client from multiple goroutines.
+func New(cfg Config) (Client, error) {
+ u, err := url.Parse(cfg.Address)
+ if err != nil {
+ return nil, err
+ }
+ u.Path = strings.TrimRight(u.Path, "/") + apiPrefix
+
+ return &httpClient{
+ endpoint: u,
+ transport: cfg.transport(),
+ }, nil
+}
+
+type httpClient struct {
+ endpoint *url.URL
+ transport CancelableTransport
+}
+
+func (c *httpClient) url(ep string, args map[string]string) *url.URL {
+ p := path.Join(c.endpoint.Path, ep)
+
+ for arg, val := range args {
+ arg = ":" + arg
+ p = strings.Replace(p, arg, val, -1)
+ }
+
+ u := *c.endpoint
+ u.Path = p
+
+ return &u
+}
+
+func (c *httpClient) do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) {
+ resp, err := ctxhttp.Do(ctx, &http.Client{Transport: c.transport}, req)
+
+ defer func() {
+ if resp != nil {
+ resp.Body.Close()
+ }
+ }()
+
+ if err != nil {
+ return nil, nil, err
+ }
+
+ var body []byte
+ done := make(chan struct{})
+ go func() {
+ body, err = ioutil.ReadAll(resp.Body)
+ close(done)
+ }()
+
+ select {
+ case <-ctx.Done():
+ err = resp.Body.Close()
+ <-done
+ if err == nil {
+ err = ctx.Err()
+ }
+ case <-done:
+ }
+
+ return resp, body, err
+}
+
+// apiClient wraps a regular client and processes successful API responses.
+// Successful also includes responses that errored at the API level.
+type apiClient struct {
+ Client
+}
+
+type apiResponse struct {
+ Status string `json:"status"`
+ Data json.RawMessage `json:"data"`
+ ErrorType ErrorType `json:"errorType"`
+ Error string `json:"error"`
+}
+
+func (c apiClient) do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) {
+ resp, body, err := c.Client.do(ctx, req)
+ if err != nil {
+ return resp, body, err
+ }
+
+ code := resp.StatusCode
+
+ if code/100 != 2 && code != statusAPIError {
+ return resp, body, &Error{
+ Type: ErrBadResponse,
+ Msg: fmt.Sprintf("bad response code %d", resp.StatusCode),
+ }
+ }
+
+ var result apiResponse
+
+ if err = json.Unmarshal(body, &result); err != nil {
+ return resp, body, &Error{
+ Type: ErrBadResponse,
+ Msg: err.Error(),
+ }
+ }
+
+ if (code == statusAPIError) != (result.Status == "error") {
+ err = &Error{
+ Type: ErrBadResponse,
+ Msg: "inconsistent body for response code",
+ }
+ }
+
+ if code == statusAPIError && result.Status == "error" {
+ err = &Error{
+ Type: result.ErrorType,
+ Msg: result.Error,
+ }
+ }
+
+ return resp, []byte(result.Data), err
+}
+
// Range represents a sliced time range.
type Range struct {
// The boundaries of the time range.
@@ -70,16 +231,6 @@ type Range struct {
Step time.Duration
}
-// API provides bindings for Prometheus's v1 API.
-type API interface {
- // Query performs a query for the given time.
- Query(ctx context.Context, query string, ts time.Time) (model.Value, error)
- // QueryRange performs a query for the given range.
- QueryRange(ctx context.Context, query string, r Range) (model.Value, error)
- // LabelValues performs a query for the values of the given label.
- LabelValues(ctx context.Context, label string) (model.LabelValues, error)
-}
-
// queryResult contains result data for a query.
type queryResult struct {
Type model.ValueType `json:"resultType"`
@@ -122,19 +273,27 @@ func (qr *queryResult) UnmarshalJSON(b []byte) error {
return err
}
-// NewAPI returns a new API for the client.
+// QueryAPI provides bindings the Prometheus's query API.
+type QueryAPI interface {
+ // Query performs a query for the given time.
+ Query(ctx context.Context, query string, ts time.Time) (model.Value, error)
+ // Query performs a query for the given range.
+ QueryRange(ctx context.Context, query string, r Range) (model.Value, error)
+}
+
+// NewQueryAPI returns a new QueryAPI for the client.
//
-// It is safe to use the returned API from multiple goroutines.
-func NewAPI(c api.Client) API {
- return &httpAPI{client: apiClient{c}}
+// It is safe to use the returned QueryAPI from multiple goroutines.
+func NewQueryAPI(c Client) QueryAPI {
+ return &httpQueryAPI{client: apiClient{c}}
}
-type httpAPI struct {
- client api.Client
+type httpQueryAPI struct {
+ client Client
}
-func (h *httpAPI) Query(ctx context.Context, query string, ts time.Time) (model.Value, error) {
- u := h.client.URL(epQuery, nil)
+func (h *httpQueryAPI) Query(ctx context.Context, query string, ts time.Time) (model.Value, error) {
+ u := h.client.url(epQuery, nil)
q := u.Query()
q.Set("query", query)
@@ -142,12 +301,9 @@ func (h *httpAPI) Query(ctx context.Context, query string, ts time.Time) (model.
u.RawQuery = q.Encode()
- req, err := http.NewRequest("GET", u.String(), nil)
- if err != nil {
- return nil, err
- }
+ req, _ := http.NewRequest("GET", u.String(), nil)
- _, body, err := h.client.Do(ctx, req)
+ _, body, err := h.client.do(ctx, req)
if err != nil {
return nil, err
}
@@ -158,8 +314,8 @@ func (h *httpAPI) Query(ctx context.Context, query string, ts time.Time) (model.
return model.Value(qres.v), err
}
-func (h *httpAPI) QueryRange(ctx context.Context, query string, r Range) (model.Value, error) {
- u := h.client.URL(epQueryRange, nil)
+func (h *httpQueryAPI) QueryRange(ctx context.Context, query string, r Range) (model.Value, error) {
+ u := h.client.url(epQueryRange, nil)
q := u.Query()
var (
@@ -175,12 +331,9 @@ func (h *httpAPI) QueryRange(ctx context.Context, query string, r Range) (model.
u.RawQuery = q.Encode()
- req, err := http.NewRequest("GET", u.String(), nil)
- if err != nil {
- return nil, err
- }
+ req, _ := http.NewRequest("GET", u.String(), nil)
- _, body, err := h.client.Do(ctx, req)
+ _, body, err := h.client.do(ctx, req)
if err != nil {
return nil, err
}
@@ -190,72 +343,3 @@ func (h *httpAPI) QueryRange(ctx context.Context, query string, r Range) (model.
return model.Value(qres.v), err
}
-
-func (h *httpAPI) LabelValues(ctx context.Context, label string) (model.LabelValues, error) {
- u := h.client.URL(epLabelValues, map[string]string{"name": label})
- req, err := http.NewRequest(http.MethodGet, u.String(), nil)
- if err != nil {
- return nil, err
- }
- _, body, err := h.client.Do(ctx, req)
- if err != nil {
- return nil, err
- }
- var labelValues model.LabelValues
- err = json.Unmarshal(body, &labelValues)
- return labelValues, err
-}
-
-// apiClient wraps a regular client and processes successful API responses.
-// Successful also includes responses that errored at the API level.
-type apiClient struct {
- api.Client
-}
-
-type apiResponse struct {
- Status string `json:"status"`
- Data json.RawMessage `json:"data"`
- ErrorType ErrorType `json:"errorType"`
- Error string `json:"error"`
-}
-
-func (c apiClient) Do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) {
- resp, body, err := c.Client.Do(ctx, req)
- if err != nil {
- return resp, body, err
- }
-
- code := resp.StatusCode
-
- if code/100 != 2 && code != statusAPIError {
- return resp, body, &Error{
- Type: ErrBadResponse,
- Msg: fmt.Sprintf("bad response code %d", resp.StatusCode),
- }
- }
-
- var result apiResponse
-
- if err = json.Unmarshal(body, &result); err != nil {
- return resp, body, &Error{
- Type: ErrBadResponse,
- Msg: err.Error(),
- }
- }
-
- if (code == statusAPIError) != (result.Status == "error") {
- err = &Error{
- Type: ErrBadResponse,
- Msg: "inconsistent body for response code",
- }
- }
-
- if code == statusAPIError && result.Status == "error" {
- err = &Error{
- Type: result.ErrorType,
- Msg: result.Error,
- }
- }
-
- return resp, []byte(result.Data), err
-}
diff --git a/vendor/github.com/prometheus/client_golang/api/prometheus/v1/api_test.go b/vendor/github.com/prometheus/client_golang/api/prometheus/api_test.go
index 2c8b1b2cb..87d3e408e 100644
--- a/vendor/github.com/prometheus/client_golang/api/prometheus/v1/api_test.go
+++ b/vendor/github.com/prometheus/client_golang/api/prometheus/api_test.go
@@ -1,4 +1,4 @@
-// Copyright 2017 The Prometheus Authors
+// Copyright 2015 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -11,203 +11,118 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-// +build go1.7
-
-package v1
+package prometheus
import (
- "context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"reflect"
- "strings"
"testing"
"time"
"github.com/prometheus/common/model"
+ "golang.org/x/net/context"
)
-type apiTest struct {
- do func() (interface{}, error)
- inErr error
- inRes interface{}
-
- reqPath string
- reqParam url.Values
- reqMethod string
- res interface{}
- err error
-}
-
-type apiTestClient struct {
- *testing.T
- curTest apiTest
-}
-
-func (c *apiTestClient) URL(ep string, args map[string]string) *url.URL {
- path := ep
- for k, v := range args {
- path = strings.Replace(path, ":"+k, v, -1)
- }
- u := &url.URL{
- Host: "test:9090",
- Path: path,
- }
- return u
-}
-
-func (c *apiTestClient) Do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) {
-
- test := c.curTest
-
- if req.URL.Path != test.reqPath {
- c.Errorf("unexpected request path: want %s, got %s", test.reqPath, req.URL.Path)
- }
- if req.Method != test.reqMethod {
- c.Errorf("unexpected request method: want %s, got %s", test.reqMethod, req.Method)
- }
-
- b, err := json.Marshal(test.inRes)
- if err != nil {
- c.Fatal(err)
- }
-
- resp := &http.Response{}
- if test.inErr != nil {
- resp.StatusCode = statusAPIError
- } else {
- resp.StatusCode = http.StatusOK
+func TestConfig(t *testing.T) {
+ c := Config{}
+ if c.transport() != DefaultTransport {
+ t.Fatalf("expected default transport for nil Transport field")
}
-
- return resp, b, test.inErr
}
-func TestAPIs(t *testing.T) {
-
- testTime := time.Now()
-
- client := &apiTestClient{T: t}
-
- queryAPI := &httpAPI{
- client: client,
- }
-
- doQuery := func(q string, ts time.Time) func() (interface{}, error) {
- return func() (interface{}, error) {
- return queryAPI.Query(context.Background(), q, ts)
- }
- }
-
- doQueryRange := func(q string, rng Range) func() (interface{}, error) {
- return func() (interface{}, error) {
- return queryAPI.QueryRange(context.Background(), q, rng)
- }
- }
-
- doLabelValues := func(label string) func() (interface{}, error) {
- return func() (interface{}, error) {
- return queryAPI.LabelValues(context.Background(), label)
- }
- }
-
- queryTests := []apiTest{
+func TestClientURL(t *testing.T) {
+ tests := []struct {
+ address string
+ endpoint string
+ args map[string]string
+ expected string
+ }{
{
- do: doQuery("2", testTime),
- inRes: &queryResult{
- Type: model.ValScalar,
- Result: &model.Scalar{
- Value: 2,
- Timestamp: model.TimeFromUnix(testTime.Unix()),
- },
- },
-
- reqMethod: "GET",
- reqPath: "/api/v1/query",
- reqParam: url.Values{
- "query": []string{"2"},
- "time": []string{testTime.Format(time.RFC3339Nano)},
- },
- res: &model.Scalar{
- Value: 2,
- Timestamp: model.TimeFromUnix(testTime.Unix()),
- },
+ address: "http://localhost:9090",
+ endpoint: "/test",
+ expected: "http://localhost:9090/test",
},
{
- do: doQuery("2", testTime),
- inErr: fmt.Errorf("some error"),
-
- reqMethod: "GET",
- reqPath: "/api/v1/query",
- reqParam: url.Values{
- "query": []string{"2"},
- "time": []string{testTime.Format(time.RFC3339Nano)},
+ address: "http://localhost",
+ endpoint: "/test",
+ expected: "http://localhost/test",
+ },
+ {
+ address: "http://localhost:9090",
+ endpoint: "test",
+ expected: "http://localhost:9090/test",
+ },
+ {
+ address: "http://localhost:9090/prefix",
+ endpoint: "/test",
+ expected: "http://localhost:9090/prefix/test",
+ },
+ {
+ address: "https://localhost:9090/",
+ endpoint: "/test/",
+ expected: "https://localhost:9090/test",
+ },
+ {
+ address: "http://localhost:9090",
+ endpoint: "/test/:param",
+ args: map[string]string{
+ "param": "content",
},
- err: fmt.Errorf("some error"),
+ expected: "http://localhost:9090/test/content",
},
-
{
- do: doQueryRange("2", Range{
- Start: testTime.Add(-time.Minute),
- End: testTime,
- Step: time.Minute,
- }),
- inErr: fmt.Errorf("some error"),
-
- reqMethod: "GET",
- reqPath: "/api/v1/query_range",
- reqParam: url.Values{
- "query": []string{"2"},
- "start": []string{testTime.Add(-time.Minute).Format(time.RFC3339Nano)},
- "end": []string{testTime.Format(time.RFC3339Nano)},
- "step": []string{time.Minute.String()},
+ address: "http://localhost:9090",
+ endpoint: "/test/:param/more/:param",
+ args: map[string]string{
+ "param": "content",
},
- err: fmt.Errorf("some error"),
+ expected: "http://localhost:9090/test/content/more/content",
},
-
{
- do: doLabelValues("mylabel"),
- inRes: []string{"val1", "val2"},
- reqMethod: "GET",
- reqPath: "/api/v1/label/mylabel/values",
- res: model.LabelValues{"val1", "val2"},
+ address: "http://localhost:9090",
+ endpoint: "/test/:param/more/:foo",
+ args: map[string]string{
+ "param": "content",
+ "foo": "bar",
+ },
+ expected: "http://localhost:9090/test/content/more/bar",
},
-
{
- do: doLabelValues("mylabel"),
- inErr: fmt.Errorf("some error"),
- reqMethod: "GET",
- reqPath: "/api/v1/label/mylabel/values",
- err: fmt.Errorf("some error"),
+ address: "http://localhost:9090",
+ endpoint: "/test/:param",
+ args: map[string]string{
+ "nonexistant": "content",
+ },
+ expected: "http://localhost:9090/test/:param",
},
}
- var tests []apiTest
- tests = append(tests, queryTests...)
-
for _, test := range tests {
- client.curTest = test
-
- res, err := test.do()
+ ep, err := url.Parse(test.address)
+ if err != nil {
+ t.Fatal(err)
+ }
- if test.err != nil {
- if err == nil {
- t.Errorf("expected error %q but got none", test.err)
- continue
- }
- if err.Error() != test.err.Error() {
- t.Errorf("unexpected error: want %s, got %s", test.err, err)
- }
- continue
+ hclient := &httpClient{
+ endpoint: ep,
+ transport: DefaultTransport,
}
- if err != nil {
- t.Errorf("unexpected error: %s", err)
+
+ u := hclient.url(test.endpoint, test.args)
+ if u.String() != test.expected {
+ t.Errorf("unexpected result: got %s, want %s", u, test.expected)
continue
}
- if !reflect.DeepEqual(res, test.res) {
- t.Errorf("unexpected result: want %v, got %v", test.res, res)
+ // The apiClient must return exactly the same result as the httpClient.
+ aclient := &apiClient{hclient}
+
+ u = aclient.url(test.endpoint, test.args)
+ if u.String() != test.expected {
+ t.Errorf("unexpected result: got %s, want %s", u, test.expected)
}
}
}
@@ -226,11 +141,11 @@ type apiClientTest struct {
err *Error
}
-func (c *testClient) URL(ep string, args map[string]string) *url.URL {
+func (c *testClient) url(ep string, args map[string]string) *url.URL {
return nil
}
-func (c *testClient) Do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) {
+func (c *testClient) do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) {
if ctx == nil {
c.Fatalf("context was not passed down")
}
@@ -356,7 +271,7 @@ func TestAPIClientDo(t *testing.T) {
tc.ch <- test
- _, body, err := client.Do(context.Background(), tc.req)
+ _, body, err := client.do(context.Background(), tc.req)
if test.err != nil {
if err == nil {
@@ -379,3 +294,160 @@ func TestAPIClientDo(t *testing.T) {
}
}
}
+
+type apiTestClient struct {
+ *testing.T
+ curTest apiTest
+}
+
+type apiTest struct {
+ do func() (interface{}, error)
+ inErr error
+ inRes interface{}
+
+ reqPath string
+ reqParam url.Values
+ reqMethod string
+ res interface{}
+ err error
+}
+
+func (c *apiTestClient) url(ep string, args map[string]string) *url.URL {
+ u := &url.URL{
+ Host: "test:9090",
+ Path: apiPrefix + ep,
+ }
+ return u
+}
+
+func (c *apiTestClient) do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) {
+
+ test := c.curTest
+
+ if req.URL.Path != test.reqPath {
+ c.Errorf("unexpected request path: want %s, got %s", test.reqPath, req.URL.Path)
+ }
+ if req.Method != test.reqMethod {
+ c.Errorf("unexpected request method: want %s, got %s", test.reqMethod, req.Method)
+ }
+
+ b, err := json.Marshal(test.inRes)
+ if err != nil {
+ c.Fatal(err)
+ }
+
+ resp := &http.Response{}
+ if test.inErr != nil {
+ resp.StatusCode = statusAPIError
+ } else {
+ resp.StatusCode = http.StatusOK
+ }
+
+ return resp, b, test.inErr
+}
+
+func TestAPIs(t *testing.T) {
+
+ testTime := time.Now()
+
+ client := &apiTestClient{T: t}
+
+ queryApi := &httpQueryAPI{
+ client: client,
+ }
+
+ doQuery := func(q string, ts time.Time) func() (interface{}, error) {
+ return func() (interface{}, error) {
+ return queryApi.Query(context.Background(), q, ts)
+ }
+ }
+
+ doQueryRange := func(q string, rng Range) func() (interface{}, error) {
+ return func() (interface{}, error) {
+ return queryApi.QueryRange(context.Background(), q, rng)
+ }
+ }
+
+ queryTests := []apiTest{
+ {
+ do: doQuery("2", testTime),
+ inRes: &queryResult{
+ Type: model.ValScalar,
+ Result: &model.Scalar{
+ Value: 2,
+ Timestamp: model.TimeFromUnix(testTime.Unix()),
+ },
+ },
+
+ reqMethod: "GET",
+ reqPath: "/api/v1/query",
+ reqParam: url.Values{
+ "query": []string{"2"},
+ "time": []string{testTime.Format(time.RFC3339Nano)},
+ },
+ res: &model.Scalar{
+ Value: 2,
+ Timestamp: model.TimeFromUnix(testTime.Unix()),
+ },
+ },
+ {
+ do: doQuery("2", testTime),
+ inErr: fmt.Errorf("some error"),
+
+ reqMethod: "GET",
+ reqPath: "/api/v1/query",
+ reqParam: url.Values{
+ "query": []string{"2"},
+ "time": []string{testTime.Format(time.RFC3339Nano)},
+ },
+ err: fmt.Errorf("some error"),
+ },
+
+ {
+ do: doQueryRange("2", Range{
+ Start: testTime.Add(-time.Minute),
+ End: testTime,
+ Step: time.Minute,
+ }),
+ inErr: fmt.Errorf("some error"),
+
+ reqMethod: "GET",
+ reqPath: "/api/v1/query_range",
+ reqParam: url.Values{
+ "query": []string{"2"},
+ "start": []string{testTime.Add(-time.Minute).Format(time.RFC3339Nano)},
+ "end": []string{testTime.Format(time.RFC3339Nano)},
+ "step": []string{time.Minute.String()},
+ },
+ err: fmt.Errorf("some error"),
+ },
+ }
+
+ var tests []apiTest
+ tests = append(tests, queryTests...)
+
+ for _, test := range tests {
+ client.curTest = test
+
+ res, err := test.do()
+
+ if test.err != nil {
+ if err == nil {
+ t.Errorf("expected error %q but got none", test.err)
+ continue
+ }
+ if err.Error() != test.err.Error() {
+ t.Errorf("unexpected error: want %s, got %s", test.err, err)
+ }
+ continue
+ }
+ if err != nil {
+ t.Errorf("unexpected error: %s", err)
+ continue
+ }
+
+ if !reflect.DeepEqual(res, test.res) {
+ t.Errorf("unexpected result: want %v, got %v", test.res, res)
+ }
+ }
+}
diff --git a/vendor/github.com/prometheus/client_golang/examples/random/main.go b/vendor/github.com/prometheus/client_golang/examples/random/main.go
index eef50d200..563957193 100644
--- a/vendor/github.com/prometheus/client_golang/examples/random/main.go
+++ b/vendor/github.com/prometheus/client_golang/examples/random/main.go
@@ -18,21 +18,19 @@ package main
import (
"flag"
- "log"
"math"
"math/rand"
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
- "github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
addr = flag.String("listen-address", ":8080", "The address to listen on for HTTP requests.")
- uniformDomain = flag.Float64("uniform.domain", 0.0002, "The domain for the uniform distribution.")
- normDomain = flag.Float64("normal.domain", 0.0002, "The domain for the normal distribution.")
- normMean = flag.Float64("normal.mean", 0.00001, "The mean for the normal distribution.")
+ uniformDomain = flag.Float64("uniform.domain", 200, "The domain for the uniform distribution.")
+ normDomain = flag.Float64("normal.domain", 200, "The domain for the normal distribution.")
+ normMean = flag.Float64("normal.mean", 10, "The mean for the normal distribution.")
oscillationPeriod = flag.Duration("oscillation-period", 10*time.Minute, "The duration of the rate oscillation period.")
)
@@ -42,9 +40,8 @@ var (
// differentiated via a "service" label.
rpcDurations = prometheus.NewSummaryVec(
prometheus.SummaryOpts{
- Name: "rpc_durations_seconds",
- Help: "RPC latency distributions.",
- Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
+ Name: "rpc_durations_microseconds",
+ Help: "RPC latency distributions.",
},
[]string{"service"},
)
@@ -53,7 +50,7 @@ var (
// normal distribution, with 20 buckets centered on the mean, each
// half-sigma wide.
rpcDurationsHistogram = prometheus.NewHistogram(prometheus.HistogramOpts{
- Name: "rpc_durations_histogram_seconds",
+ Name: "rpc_durations_histogram_microseconds",
Help: "RPC latency distributions.",
Buckets: prometheus.LinearBuckets(*normMean-5**normDomain, .5**normDomain, 20),
})
@@ -94,13 +91,13 @@ func main() {
go func() {
for {
- v := rand.ExpFloat64() / 1e6
+ v := rand.ExpFloat64()
rpcDurations.WithLabelValues("exponential").Observe(v)
time.Sleep(time.Duration(50*oscillationFactor()) * time.Millisecond)
}
}()
// Expose the registered metrics via HTTP.
- http.Handle("/metrics", promhttp.Handler())
- log.Fatal(http.ListenAndServe(*addr, nil))
+ http.Handle("/metrics", prometheus.Handler())
+ http.ListenAndServe(*addr, nil)
}
diff --git a/vendor/github.com/prometheus/client_golang/examples/simple/main.go b/vendor/github.com/prometheus/client_golang/examples/simple/main.go
index 1fc23249a..19620d2b3 100644
--- a/vendor/github.com/prometheus/client_golang/examples/simple/main.go
+++ b/vendor/github.com/prometheus/client_golang/examples/simple/main.go
@@ -16,16 +16,15 @@ package main
import (
"flag"
- "log"
"net/http"
- "github.com/prometheus/client_golang/prometheus/promhttp"
+ "github.com/prometheus/client_golang/prometheus"
)
var addr = flag.String("listen-address", ":8080", "The address to listen on for HTTP requests.")
func main() {
flag.Parse()
- http.Handle("/metrics", promhttp.Handler())
- log.Fatal(http.ListenAndServe(*addr, nil))
+ http.Handle("/metrics", prometheus.Handler())
+ http.ListenAndServe(*addr, nil)
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/benchmark_test.go b/vendor/github.com/prometheus/client_golang/prometheus/benchmark_test.go
index faad39b4c..a3d86698b 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/benchmark_test.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/benchmark_test.go
@@ -129,9 +129,8 @@ func BenchmarkGaugeNoLabels(b *testing.B) {
func BenchmarkSummaryWithLabelValues(b *testing.B) {
m := NewSummaryVec(
SummaryOpts{
- Name: "benchmark_summary",
- Help: "A summary to benchmark it.",
- Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
+ Name: "benchmark_summary",
+ Help: "A summary to benchmark it.",
},
[]string{"one", "two", "three"},
)
@@ -144,9 +143,8 @@ func BenchmarkSummaryWithLabelValues(b *testing.B) {
func BenchmarkSummaryNoLabels(b *testing.B) {
m := NewSummary(SummaryOpts{
- Name: "benchmark_summary",
- Help: "A summary to benchmark it.",
- Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
+ Name: "benchmark_summary",
+ Help: "A summary to benchmark it.",
},
)
b.ReportAllocs()
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/counter.go b/vendor/github.com/prometheus/client_golang/prometheus/counter.go
index 72d5256a5..ee37949ad 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/counter.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/counter.go
@@ -30,8 +30,16 @@ type Counter interface {
Metric
Collector
- // Inc increments the counter by 1. Use Add to increment it by arbitrary
- // non-negative values.
+ // Set is used to set the Counter to an arbitrary value. It is only used
+ // if you have to transfer a value from an external counter into this
+ // Prometheus metric. Do not use it for regular handling of a
+ // Prometheus counter (as it can be used to break the contract of
+ // monotonically increasing values).
+ //
+ // Deprecated: Use NewConstMetric to create a counter for an external
+ // value. A Counter should never be set.
+ Set(float64)
+ // Inc increments the counter by 1.
Inc()
// Add adds the given value to the counter. It panics if the value is <
// 0.
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/desc.go b/vendor/github.com/prometheus/client_golang/prometheus/desc.go
index 1835b16f6..77f4b30e8 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/desc.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/desc.go
@@ -16,15 +16,20 @@ package prometheus
import (
"errors"
"fmt"
+ "regexp"
"sort"
"strings"
"github.com/golang/protobuf/proto"
- "github.com/prometheus/common/model"
dto "github.com/prometheus/client_model/go"
)
+var (
+ metricNameRE = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_:]*$`)
+ labelNameRE = regexp.MustCompile("^[a-zA-Z_][a-zA-Z0-9_]*$")
+)
+
// reservedLabelPrefix is a prefix which is not legal in user-supplied
// label names.
const reservedLabelPrefix = "__"
@@ -73,7 +78,7 @@ type Desc struct {
// Help string. Each Desc with the same fqName must have the same
// dimHash.
dimHash uint64
- // err is an error that occurred during construction. It is reported on
+ // err is an error that occured during construction. It is reported on
// registration time.
err error
}
@@ -98,7 +103,7 @@ func NewDesc(fqName, help string, variableLabels []string, constLabels Labels) *
d.err = errors.New("empty help string")
return d
}
- if !model.IsValidMetricName(model.LabelValue(fqName)) {
+ if !metricNameRE.MatchString(fqName) {
d.err = fmt.Errorf("%q is not a valid metric name", fqName)
return d
}
@@ -195,6 +200,6 @@ func (d *Desc) String() string {
}
func checkLabelName(l string) bool {
- return model.LabelName(l).IsValid() &&
+ return labelNameRE.MatchString(l) &&
!strings.HasPrefix(l, reservedLabelPrefix)
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/doc.go b/vendor/github.com/prometheus/client_golang/prometheus/doc.go
index 1fdef9edb..b15a2d3b9 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/doc.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/doc.go
@@ -17,7 +17,7 @@
// Pushgateway (package push).
//
// All exported functions and methods are safe to be used concurrently unless
-// specified otherwise.
+//specified otherwise.
//
// A Basic Example
//
@@ -59,7 +59,7 @@
// // The Handler function provides a default handler to expose metrics
// // via an HTTP server. "/metrics" is the usual endpoint for that.
// http.Handle("/metrics", promhttp.Handler())
-// log.Fatal(http.ListenAndServe(":8080", nil))
+// http.ListenAndServe(":8080", nil)
// }
//
//
@@ -69,7 +69,7 @@
// Metrics
//
// The number of exported identifiers in this package might appear a bit
-// overwhelming. However, in addition to the basic plumbing shown in the example
+// overwhelming. Hovever, in addition to the basic plumbing shown in the example
// above, you only need to understand the different metric types and their
// vector versions for basic usage.
//
@@ -95,8 +95,8 @@
// SummaryVec, HistogramVec, and UntypedVec are not.
//
// To create instances of Metrics and their vector versions, you need a suitable
-// …Opts struct, i.e. GaugeOpts, CounterOpts, SummaryOpts, HistogramOpts, or
-// UntypedOpts.
+// …Opts struct, i.e. GaugeOpts, CounterOpts, SummaryOpts,
+// HistogramOpts, or UntypedOpts.
//
// Custom Collectors and constant Metrics
//
@@ -114,8 +114,8 @@
// Metric instances “on the fly” using NewConstMetric, NewConstHistogram, and
// NewConstSummary (and their respective Must… versions). That will happen in
// the Collect method. The Describe method has to return separate Desc
-// instances, representative of the “throw-away” metrics to be created later.
-// NewDesc comes in handy to create those Desc instances.
+// instances, representative of the “throw-away” metrics to be created
+// later. NewDesc comes in handy to create those Desc instances.
//
// The Collector example illustrates the use case. You can also look at the
// source code of the processCollector (mirroring process metrics), the
@@ -129,32 +129,32 @@
// Advanced Uses of the Registry
//
// While MustRegister is the by far most common way of registering a Collector,
-// sometimes you might want to handle the errors the registration might cause.
-// As suggested by the name, MustRegister panics if an error occurs. With the
-// Register function, the error is returned and can be handled.
+// sometimes you might want to handle the errors the registration might
+// cause. As suggested by the name, MustRegister panics if an error occurs. With
+// the Register function, the error is returned and can be handled.
//
// An error is returned if the registered Collector is incompatible or
// inconsistent with already registered metrics. The registry aims for
-// consistency of the collected metrics according to the Prometheus data model.
-// Inconsistencies are ideally detected at registration time, not at collect
-// time. The former will usually be detected at start-up time of a program,
-// while the latter will only happen at scrape time, possibly not even on the
-// first scrape if the inconsistency only becomes relevant later. That is the
-// main reason why a Collector and a Metric have to describe themselves to the
-// registry.
+// consistency of the collected metrics according to the Prometheus data
+// model. Inconsistencies are ideally detected at registration time, not at
+// collect time. The former will usually be detected at start-up time of a
+// program, while the latter will only happen at scrape time, possibly not even
+// on the first scrape if the inconsistency only becomes relevant later. That is
+// the main reason why a Collector and a Metric have to describe themselves to
+// the registry.
//
// So far, everything we did operated on the so-called default registry, as it
// can be found in the global DefaultRegistry variable. With NewRegistry, you
// can create a custom registry, or you can even implement the Registerer or
-// Gatherer interfaces yourself. The methods Register and Unregister work in the
-// same way on a custom registry as the global functions Register and Unregister
-// on the default registry.
+// Gatherer interfaces yourself. The methods Register and Unregister work in
+// the same way on a custom registry as the global functions Register and
+// Unregister on the default registry.
//
-// There are a number of uses for custom registries: You can use registries with
-// special properties, see NewPedanticRegistry. You can avoid global state, as
-// it is imposed by the DefaultRegistry. You can use multiple registries at the
-// same time to expose different metrics in different ways. You can use separate
-// registries for testing purposes.
+// There are a number of uses for custom registries: You can use registries
+// with special properties, see NewPedanticRegistry. You can avoid global state,
+// as it is imposed by the DefaultRegistry. You can use multiple registries at
+// the same time to expose different metrics in different ways. You can use
+// separate registries for testing purposes.
//
// Also note that the DefaultRegistry comes registered with a Collector for Go
// runtime metrics (via NewGoCollector) and a Collector for process metrics (via
@@ -166,20 +166,16 @@
// The Registry implements the Gatherer interface. The caller of the Gather
// method can then expose the gathered metrics in some way. Usually, the metrics
// are served via HTTP on the /metrics endpoint. That's happening in the example
-// above. The tools to expose metrics via HTTP are in the promhttp sub-package.
-// (The top-level functions in the prometheus package are deprecated.)
+// above. The tools to expose metrics via HTTP are in the promhttp
+// sub-package. (The top-level functions in the prometheus package are
+// deprecated.)
//
// Pushing to the Pushgateway
//
// Function for pushing to the Pushgateway can be found in the push sub-package.
//
-// Graphite Bridge
-//
-// Functions and examples to push metrics from a Gatherer to Graphite can be
-// found in the graphite sub-package.
-//
// Other Means of Exposition
//
-// More ways of exposing metrics can easily be added by following the approaches
-// of the existing implementations.
+// More ways of exposing metrics can easily be added. Sending metrics to
+// Graphite would be an example that will soon be implemented.
package prometheus
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/example_timer_complex_test.go b/vendor/github.com/prometheus/client_golang/prometheus/example_timer_complex_test.go
deleted file mode 100644
index 763788098..000000000
--- a/vendor/github.com/prometheus/client_golang/prometheus/example_timer_complex_test.go
+++ /dev/null
@@ -1,71 +0,0 @@
-// Copyright 2014 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package prometheus_test
-
-import (
- "net/http"
-
- "github.com/prometheus/client_golang/prometheus"
-)
-
-var (
- // apiRequestDuration tracks the duration separate for each HTTP status
- // class (1xx, 2xx, ...). This creates a fair amount of time series on
- // the Prometheus server. Usually, you would track the duration of
- // serving HTTP request without partitioning by outcome. Do something
- // like this only if needed. Also note how only status classes are
- // tracked, not every single status code. The latter would create an
- // even larger amount of time series. Request counters partitioned by
- // status code are usually OK as each counter only creates one time
- // series. Histograms are way more expensive, so partition with care and
- // only where you really need separate latency tracking. Partitioning by
- // status class is only an example. In concrete cases, other partitions
- // might make more sense.
- apiRequestDuration = prometheus.NewHistogramVec(
- prometheus.HistogramOpts{
- Name: "api_request_duration_seconds",
- Help: "Histogram for the request duration of the public API, partitioned by status class.",
- Buckets: prometheus.ExponentialBuckets(0.1, 1.5, 5),
- },
- []string{"status_class"},
- )
-)
-
-func handler(w http.ResponseWriter, r *http.Request) {
- status := http.StatusOK
- // The ObserverFunc gets called by the deferred ObserveDuration and
- // decides wich Histogram's Observe method is called.
- timer := prometheus.NewTimer(prometheus.ObserverFunc(func(v float64) {
- switch {
- case status >= 500: // Server error.
- apiRequestDuration.WithLabelValues("5xx").Observe(v)
- case status >= 400: // Client error.
- apiRequestDuration.WithLabelValues("4xx").Observe(v)
- case status >= 300: // Redirection.
- apiRequestDuration.WithLabelValues("3xx").Observe(v)
- case status >= 200: // Success.
- apiRequestDuration.WithLabelValues("2xx").Observe(v)
- default: // Informational.
- apiRequestDuration.WithLabelValues("1xx").Observe(v)
- }
- }))
- defer timer.ObserveDuration()
-
- // Handle the request. Set status accordingly.
- // ...
-}
-
-func ExampleTimer_complex() {
- http.HandleFunc("/api", handler)
-}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/example_timer_gauge_test.go b/vendor/github.com/prometheus/client_golang/prometheus/example_timer_gauge_test.go
deleted file mode 100644
index 7184a0d1d..000000000
--- a/vendor/github.com/prometheus/client_golang/prometheus/example_timer_gauge_test.go
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright 2014 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package prometheus_test
-
-import (
- "os"
-
- "github.com/prometheus/client_golang/prometheus"
-)
-
-var (
- // If a function is called rarely (i.e. not more often than scrapes
- // happen) or ideally only once (like in a batch job), it can make sense
- // to use a Gauge for timing the function call. For timing a batch job
- // and pushing the result to a Pushgateway, see also the comprehensive
- // example in the push package.
- funcDuration = prometheus.NewGauge(prometheus.GaugeOpts{
- Name: "example_function_duration_seconds",
- Help: "Duration of the last call of an example function.",
- })
-)
-
-func run() error {
- // The Set method of the Gauge is used to observe the duration.
- timer := prometheus.NewTimer(prometheus.ObserverFunc(funcDuration.Set))
- defer timer.ObserveDuration()
-
- // Do something. Return errors as encountered. The use of 'defer' above
- // makes sure the function is still timed properly.
- return nil
-}
-
-func ExampleTimer_gauge() {
- if err := run(); err != nil {
- os.Exit(1)
- }
-}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/example_timer_test.go b/vendor/github.com/prometheus/client_golang/prometheus/example_timer_test.go
deleted file mode 100644
index bd86bb472..000000000
--- a/vendor/github.com/prometheus/client_golang/prometheus/example_timer_test.go
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright 2014 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package prometheus_test
-
-import (
- "math/rand"
- "time"
-
- "github.com/prometheus/client_golang/prometheus"
-)
-
-var (
- requestDuration = prometheus.NewHistogram(prometheus.HistogramOpts{
- Name: "example_request_duration_seconds",
- Help: "Histogram for the runtime of a simple example function.",
- Buckets: prometheus.LinearBuckets(0.01, 0.01, 10),
- })
-)
-
-func ExampleTimer() {
- // timer times this example function. It uses a Histogram, but a Summary
- // would also work, as both implement Observer. Check out
- // https://prometheus.io/docs/practices/histograms/ for differences.
- timer := prometheus.NewTimer(requestDuration)
- defer timer.ObserveDuration()
-
- // Do something here that takes time.
- time.Sleep(time.Duration(rand.NormFloat64()*10000+50000) * time.Microsecond)
-}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/examples_test.go b/vendor/github.com/prometheus/client_golang/prometheus/examples_test.go
index 45f60650f..f87f21a8f 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/examples_test.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/examples_test.go
@@ -113,7 +113,7 @@ func ExampleCounter() {
pushComplete := make(chan struct{})
// TODO: Start a goroutine that performs repository pushes and reports
// each completion via the channel.
- for range pushComplete {
+ for _ = range pushComplete {
pushCounter.Inc()
}
// Output:
@@ -169,8 +169,8 @@ func ExampleInstrumentHandler() {
func ExampleLabelPairSorter() {
labelPairs := []*dto.LabelPair{
- {Name: proto.String("status"), Value: proto.String("404")},
- {Name: proto.String("method"), Value: proto.String("get")},
+ &dto.LabelPair{Name: proto.String("status"), Value: proto.String("404")},
+ &dto.LabelPair{Name: proto.String("method"), Value: proto.String("get")},
}
sort.Sort(prometheus.LabelPairSorter(labelPairs))
@@ -334,9 +334,8 @@ func ExampleRegister() {
func ExampleSummary() {
temps := prometheus.NewSummary(prometheus.SummaryOpts{
- Name: "pond_temperature_celsius",
- Help: "The temperature of the frog pond.",
- Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
+ Name: "pond_temperature_celsius",
+ Help: "The temperature of the frog pond.", // Sorry, we can't measure how badly it smells.
})
// Simulate some observations.
@@ -373,9 +372,8 @@ func ExampleSummary() {
func ExampleSummaryVec() {
temps := prometheus.NewSummaryVec(
prometheus.SummaryOpts{
- Name: "pond_temperature_celsius",
- Help: "The temperature of the frog pond.",
- Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
+ Name: "pond_temperature_celsius",
+ Help: "The temperature of the frog pond.", // Sorry, we can't measure how badly it smells.
},
[]string{"species"},
)
@@ -642,7 +640,6 @@ func ExampleAlreadyRegisteredError() {
panic(err)
}
}
- reqCounter.Inc()
}
func ExampleGatherers() {
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/expvar_collector_test.go b/vendor/github.com/prometheus/client_golang/prometheus/expvar_collector_test.go
index 910dac325..5d3128fae 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/expvar_collector_test.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/expvar_collector_test.go
@@ -24,7 +24,7 @@ import (
"github.com/prometheus/client_golang/prometheus"
)
-func ExampleNewExpvarCollector() {
+func ExampleExpvarCollector() {
expvarCollector := prometheus.NewExpvarCollector(map[string]*prometheus.Desc{
"memstats": prometheus.NewDesc(
"expvar_memstats",
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/gauge.go b/vendor/github.com/prometheus/client_golang/prometheus/gauge.go
index 9ab5a3d62..8b70e5141 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/gauge.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/gauge.go
@@ -27,21 +27,16 @@ type Gauge interface {
// Set sets the Gauge to an arbitrary value.
Set(float64)
- // Inc increments the Gauge by 1. Use Add to increment it by arbitrary
- // values.
+ // Inc increments the Gauge by 1.
Inc()
- // Dec decrements the Gauge by 1. Use Sub to decrement it by arbitrary
- // values.
+ // Dec decrements the Gauge by 1.
Dec()
- // Add adds the given value to the Gauge. (The value can be negative,
- // resulting in a decrease of the Gauge.)
+ // Add adds the given value to the Gauge. (The value can be
+ // negative, resulting in a decrease of the Gauge.)
Add(float64)
// Sub subtracts the given value from the Gauge. (The value can be
// negative, resulting in an increase of the Gauge.)
Sub(float64)
-
- // SetToCurrentTime sets the Gauge to the current Unix time in seconds.
- SetToCurrentTime()
}
// GaugeOpts is an alias for Opts. See there for doc comments.
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/gauge_test.go b/vendor/github.com/prometheus/client_golang/prometheus/gauge_test.go
index 8e5f002c9..48cab4636 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/gauge_test.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/gauge_test.go
@@ -19,7 +19,6 @@ import (
"sync"
"testing"
"testing/quick"
- "time"
dto "github.com/prometheus/client_model/go"
)
@@ -181,22 +180,3 @@ func TestGaugeFunc(t *testing.T) {
t.Errorf("expected %q, got %q", expected, got)
}
}
-
-func TestGaugeSetCurrentTime(t *testing.T) {
- g := NewGauge(GaugeOpts{
- Name: "test_name",
- Help: "test help",
- })
- g.SetToCurrentTime()
- unixTime := float64(time.Now().Unix())
-
- m := &dto.Metric{}
- g.Write(m)
-
- delta := unixTime - m.GetGauge().GetValue()
- // This is just a smoke test to make sure SetToCurrentTime is not
- // totally off. Tests with current time involved are hard...
- if math.Abs(delta) > 5 {
- t.Errorf("Gauge set to current time deviates from current time by more than 5s, delta is %f seconds", delta)
- }
-}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/go_collector.go b/vendor/github.com/prometheus/client_golang/prometheus/go_collector.go
index f96764559..abc9d4ec4 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/go_collector.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/go_collector.go
@@ -8,9 +8,8 @@ import (
)
type goCollector struct {
- goroutinesDesc *Desc
- threadsDesc *Desc
- gcDesc *Desc
+ goroutines Gauge
+ gcDesc *Desc
// metrics to describe and collect
metrics memStatsMetrics
@@ -20,14 +19,11 @@ type goCollector struct {
// go process.
func NewGoCollector() Collector {
return &goCollector{
- goroutinesDesc: NewDesc(
- "go_goroutines",
- "Number of goroutines that currently exist.",
- nil, nil),
- threadsDesc: NewDesc(
- "go_threads",
- "Number of OS threads created",
- nil, nil),
+ goroutines: NewGauge(GaugeOpts{
+ Namespace: "go",
+ Name: "goroutines",
+ Help: "Number of goroutines that currently exist.",
+ }),
gcDesc: NewDesc(
"go_gc_duration_seconds",
"A summary of the GC invocation durations.",
@@ -52,7 +48,7 @@ func NewGoCollector() Collector {
}, {
desc: NewDesc(
memstatNamespace("sys_bytes"),
- "Number of bytes obtained from system.",
+ "Number of bytes obtained by system. Sum of all system allocations.",
nil, nil,
),
eval: func(ms *runtime.MemStats) float64 { return float64(ms.Sys) },
@@ -115,12 +111,12 @@ func NewGoCollector() Collector {
valType: GaugeValue,
}, {
desc: NewDesc(
- memstatNamespace("heap_released_bytes"),
- "Number of heap bytes released to OS.",
+ memstatNamespace("heap_released_bytes_total"),
+ "Total number of heap bytes released to OS.",
nil, nil,
),
eval: func(ms *runtime.MemStats) float64 { return float64(ms.HeapReleased) },
- valType: GaugeValue,
+ valType: CounterValue,
}, {
desc: NewDesc(
memstatNamespace("heap_objects"),
@@ -217,14 +213,6 @@ func NewGoCollector() Collector {
),
eval: func(ms *runtime.MemStats) float64 { return float64(ms.LastGC) / 1e9 },
valType: GaugeValue,
- }, {
- desc: NewDesc(
- memstatNamespace("gc_cpu_fraction"),
- "The fraction of this program's available CPU time used by the GC since the program started.",
- nil, nil,
- ),
- eval: func(ms *runtime.MemStats) float64 { return ms.GCCPUFraction },
- valType: GaugeValue,
},
},
}
@@ -236,9 +224,9 @@ func memstatNamespace(s string) string {
// Describe returns all descriptions of the collector.
func (c *goCollector) Describe(ch chan<- *Desc) {
- ch <- c.goroutinesDesc
- ch <- c.threadsDesc
+ ch <- c.goroutines.Desc()
ch <- c.gcDesc
+
for _, i := range c.metrics {
ch <- i.desc
}
@@ -246,9 +234,8 @@ func (c *goCollector) Describe(ch chan<- *Desc) {
// Collect returns the current state of all metrics of the collector.
func (c *goCollector) Collect(ch chan<- Metric) {
- ch <- MustNewConstMetric(c.goroutinesDesc, GaugeValue, float64(runtime.NumGoroutine()))
- n, _ := runtime.ThreadCreateProfile(nil)
- ch <- MustNewConstMetric(c.threadsDesc, GaugeValue, float64(n))
+ c.goroutines.Set(float64(runtime.NumGoroutine()))
+ ch <- c.goroutines
var stats debug.GCStats
stats.PauseQuantiles = make([]time.Duration, 5)
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/go_collector_test.go b/vendor/github.com/prometheus/client_golang/prometheus/go_collector_test.go
index 59dabc09c..9a8858cbd 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/go_collector_test.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/go_collector_test.go
@@ -29,36 +29,33 @@ func TestGoCollector(t *testing.T) {
for {
select {
- case m := <-ch:
- // m can be Gauge or Counter,
- // currently just test the go_goroutines Gauge
- // and ignore others.
- if m.Desc().fqName != "go_goroutines" {
- continue
- }
- pb := &dto.Metric{}
- m.Write(pb)
- if pb.GetGauge() == nil {
- continue
- }
+ case metric := <-ch:
+ switch m := metric.(type) {
+ // Attention, this also catches Counter...
+ case Gauge:
+ pb := &dto.Metric{}
+ m.Write(pb)
+ if pb.GetGauge() == nil {
+ continue
+ }
- if old == -1 {
- old = int(pb.GetGauge().GetValue())
- close(waitc)
- continue
- }
+ if old == -1 {
+ old = int(pb.GetGauge().GetValue())
+ close(waitc)
+ continue
+ }
- if diff := int(pb.GetGauge().GetValue()) - old; diff != 1 {
- // TODO: This is flaky in highly concurrent situations.
- t.Errorf("want 1 new goroutine, got %d", diff)
- }
+ if diff := int(pb.GetGauge().GetValue()) - old; diff != 1 {
+ // TODO: This is flaky in highly concurrent situations.
+ t.Errorf("want 1 new goroutine, got %d", diff)
+ }
- // GoCollector performs three sends per call.
- // On line 27 we need to receive the second send
- // to shut down cleanly.
- <-ch
- <-ch
- return
+ // GoCollector performs two sends per call.
+ // On line 27 we need to receive the second send
+ // to shut down cleanly.
+ <-ch
+ return
+ }
case <-time.After(1 * time.Second):
t.Fatalf("expected collect timed out")
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/graphite/bridge.go b/vendor/github.com/prometheus/client_golang/prometheus/graphite/bridge.go
deleted file mode 100644
index 11533374b..000000000
--- a/vendor/github.com/prometheus/client_golang/prometheus/graphite/bridge.go
+++ /dev/null
@@ -1,280 +0,0 @@
-// Copyright 2016 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// Package graphite provides a bridge to push Prometheus metrics to a Graphite
-// server.
-package graphite
-
-import (
- "bufio"
- "errors"
- "fmt"
- "io"
- "net"
- "sort"
- "time"
-
- "github.com/prometheus/common/expfmt"
- "github.com/prometheus/common/model"
- "golang.org/x/net/context"
-
- dto "github.com/prometheus/client_model/go"
-
- "github.com/prometheus/client_golang/prometheus"
-)
-
-const (
- defaultInterval = 15 * time.Second
- millisecondsPerSecond = 1000
-)
-
-// HandlerErrorHandling defines how a Handler serving metrics will handle
-// errors.
-type HandlerErrorHandling int
-
-// These constants cause handlers serving metrics to behave as described if
-// errors are encountered.
-const (
- // Ignore errors and try to push as many metrics to Graphite as possible.
- ContinueOnError HandlerErrorHandling = iota
-
- // Abort the push to Graphite upon the first error encountered.
- AbortOnError
-)
-
-// Config defines the Graphite bridge config.
-type Config struct {
- // The url to push data to. Required.
- URL string
-
- // The prefix for the pushed Graphite metrics. Defaults to empty string.
- Prefix string
-
- // The interval to use for pushing data to Graphite. Defaults to 15 seconds.
- Interval time.Duration
-
- // The timeout for pushing metrics to Graphite. Defaults to 15 seconds.
- Timeout time.Duration
-
- // The Gatherer to use for metrics. Defaults to prometheus.DefaultGatherer.
- Gatherer prometheus.Gatherer
-
- // The logger that messages are written to. Defaults to no logging.
- Logger Logger
-
- // ErrorHandling defines how errors are handled. Note that errors are
- // logged regardless of the configured ErrorHandling provided Logger
- // is not nil.
- ErrorHandling HandlerErrorHandling
-}
-
-// Bridge pushes metrics to the configured Graphite server.
-type Bridge struct {
- url string
- prefix string
- interval time.Duration
- timeout time.Duration
-
- errorHandling HandlerErrorHandling
- logger Logger
-
- g prometheus.Gatherer
-}
-
-// Logger is the minimal interface Bridge needs for logging. Note that
-// log.Logger from the standard library implements this interface, and it is
-// easy to implement by custom loggers, if they don't do so already anyway.
-type Logger interface {
- Println(v ...interface{})
-}
-
-// NewBridge returns a pointer to a new Bridge struct.
-func NewBridge(c *Config) (*Bridge, error) {
- b := &Bridge{}
-
- if c.URL == "" {
- return nil, errors.New("missing URL")
- }
- b.url = c.URL
-
- if c.Gatherer == nil {
- b.g = prometheus.DefaultGatherer
- } else {
- b.g = c.Gatherer
- }
-
- if c.Logger != nil {
- b.logger = c.Logger
- }
-
- if c.Prefix != "" {
- b.prefix = c.Prefix
- }
-
- var z time.Duration
- if c.Interval == z {
- b.interval = defaultInterval
- } else {
- b.interval = c.Interval
- }
-
- if c.Timeout == z {
- b.timeout = defaultInterval
- } else {
- b.timeout = c.Timeout
- }
-
- b.errorHandling = c.ErrorHandling
-
- return b, nil
-}
-
-// Run starts the event loop that pushes Prometheus metrics to Graphite at the
-// configured interval.
-func (b *Bridge) Run(ctx context.Context) {
- ticker := time.NewTicker(b.interval)
- defer ticker.Stop()
- for {
- select {
- case <-ticker.C:
- if err := b.Push(); err != nil && b.logger != nil {
- b.logger.Println("error pushing to Graphite:", err)
- }
- case <-ctx.Done():
- return
- }
- }
-}
-
-// Push pushes Prometheus metrics to the configured Graphite server.
-func (b *Bridge) Push() error {
- mfs, err := b.g.Gather()
- if err != nil || len(mfs) == 0 {
- switch b.errorHandling {
- case AbortOnError:
- return err
- case ContinueOnError:
- if b.logger != nil {
- b.logger.Println("continue on error:", err)
- }
- default:
- panic("unrecognized error handling value")
- }
- }
-
- conn, err := net.DialTimeout("tcp", b.url, b.timeout)
- if err != nil {
- return err
- }
- defer conn.Close()
-
- return writeMetrics(conn, mfs, b.prefix, model.Now())
-}
-
-func writeMetrics(w io.Writer, mfs []*dto.MetricFamily, prefix string, now model.Time) error {
- vec, err := expfmt.ExtractSamples(&expfmt.DecodeOptions{
- Timestamp: now,
- }, mfs...)
- if err != nil {
- return err
- }
-
- buf := bufio.NewWriter(w)
- for _, s := range vec {
- if err := writeSanitized(buf, prefix); err != nil {
- return err
- }
- if err := buf.WriteByte('.'); err != nil {
- return err
- }
- if err := writeMetric(buf, s.Metric); err != nil {
- return err
- }
- if _, err := fmt.Fprintf(buf, " %g %d\n", s.Value, int64(s.Timestamp)/millisecondsPerSecond); err != nil {
- return err
- }
- if err := buf.Flush(); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func writeMetric(buf *bufio.Writer, m model.Metric) error {
- metricName, hasName := m[model.MetricNameLabel]
- numLabels := len(m) - 1
- if !hasName {
- numLabels = len(m)
- }
-
- labelStrings := make([]string, 0, numLabels)
- for label, value := range m {
- if label != model.MetricNameLabel {
- labelStrings = append(labelStrings, fmt.Sprintf("%s %s", string(label), string(value)))
- }
- }
-
- var err error
- switch numLabels {
- case 0:
- if hasName {
- return writeSanitized(buf, string(metricName))
- }
- default:
- sort.Strings(labelStrings)
- if err = writeSanitized(buf, string(metricName)); err != nil {
- return err
- }
- for _, s := range labelStrings {
- if err = buf.WriteByte('.'); err != nil {
- return err
- }
- if err = writeSanitized(buf, s); err != nil {
- return err
- }
- }
- }
- return nil
-}
-
-func writeSanitized(buf *bufio.Writer, s string) error {
- prevUnderscore := false
-
- for _, c := range s {
- c = replaceInvalidRune(c)
- if c == '_' {
- if prevUnderscore {
- continue
- }
- prevUnderscore = true
- } else {
- prevUnderscore = false
- }
- if _, err := buf.WriteRune(c); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func replaceInvalidRune(c rune) rune {
- if c == ' ' {
- return '.'
- }
- if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == ':' || (c >= '0' && c <= '9')) {
- return '_'
- }
- return c
-}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/graphite/bridge_test.go b/vendor/github.com/prometheus/client_golang/prometheus/graphite/bridge_test.go
deleted file mode 100644
index c2b274c6a..000000000
--- a/vendor/github.com/prometheus/client_golang/prometheus/graphite/bridge_test.go
+++ /dev/null
@@ -1,309 +0,0 @@
-package graphite
-
-import (
- "bufio"
- "bytes"
- "io"
- "log"
- "net"
- "os"
- "regexp"
- "testing"
- "time"
-
- "github.com/prometheus/common/model"
- "golang.org/x/net/context"
-
- "github.com/prometheus/client_golang/prometheus"
-)
-
-func TestSanitize(t *testing.T) {
- testCases := []struct {
- in, out string
- }{
- {in: "hello", out: "hello"},
- {in: "hE/l1o", out: "hE_l1o"},
- {in: "he,*ll(.o", out: "he_ll_o"},
- {in: "hello_there%^&", out: "hello_there_"},
- }
-
- var buf bytes.Buffer
- w := bufio.NewWriter(&buf)
-
- for i, tc := range testCases {
- if err := writeSanitized(w, tc.in); err != nil {
- t.Fatalf("write failed: %v", err)
- }
- if err := w.Flush(); err != nil {
- t.Fatalf("flush failed: %v", err)
- }
-
- if want, got := tc.out, buf.String(); want != got {
- t.Fatalf("test case index %d: got sanitized string %s, want %s", i, got, want)
- }
-
- buf.Reset()
- }
-}
-
-func TestWriteSummary(t *testing.T) {
- sumVec := prometheus.NewSummaryVec(
- prometheus.SummaryOpts{
- Name: "name",
- Help: "docstring",
- ConstLabels: prometheus.Labels{"constname": "constvalue"},
- Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
- },
- []string{"labelname"},
- )
-
- sumVec.WithLabelValues("val1").Observe(float64(10))
- sumVec.WithLabelValues("val1").Observe(float64(20))
- sumVec.WithLabelValues("val1").Observe(float64(30))
- sumVec.WithLabelValues("val2").Observe(float64(20))
- sumVec.WithLabelValues("val2").Observe(float64(30))
- sumVec.WithLabelValues("val2").Observe(float64(40))
-
- reg := prometheus.NewRegistry()
- reg.MustRegister(sumVec)
-
- mfs, err := reg.Gather()
- if err != nil {
- t.Fatalf("error: %v", err)
- }
-
- now := model.Time(1477043083)
- var buf bytes.Buffer
- err = writeMetrics(&buf, mfs, "prefix", now)
- if err != nil {
- t.Fatalf("error: %v", err)
- }
-
- want := `prefix.name.constname.constvalue.labelname.val1.quantile.0_5 20 1477043
-prefix.name.constname.constvalue.labelname.val1.quantile.0_9 30 1477043
-prefix.name.constname.constvalue.labelname.val1.quantile.0_99 30 1477043
-prefix.name_sum.constname.constvalue.labelname.val1 60 1477043
-prefix.name_count.constname.constvalue.labelname.val1 3 1477043
-prefix.name.constname.constvalue.labelname.val2.quantile.0_5 30 1477043
-prefix.name.constname.constvalue.labelname.val2.quantile.0_9 40 1477043
-prefix.name.constname.constvalue.labelname.val2.quantile.0_99 40 1477043
-prefix.name_sum.constname.constvalue.labelname.val2 90 1477043
-prefix.name_count.constname.constvalue.labelname.val2 3 1477043
-`
-
- if got := buf.String(); want != got {
- t.Fatalf("wanted \n%s\n, got \n%s\n", want, got)
- }
-}
-
-func TestWriteHistogram(t *testing.T) {
- histVec := prometheus.NewHistogramVec(
- prometheus.HistogramOpts{
- Name: "name",
- Help: "docstring",
- ConstLabels: prometheus.Labels{"constname": "constvalue"},
- Buckets: []float64{0.01, 0.02, 0.05, 0.1},
- },
- []string{"labelname"},
- )
-
- histVec.WithLabelValues("val1").Observe(float64(10))
- histVec.WithLabelValues("val1").Observe(float64(20))
- histVec.WithLabelValues("val1").Observe(float64(30))
- histVec.WithLabelValues("val2").Observe(float64(20))
- histVec.WithLabelValues("val2").Observe(float64(30))
- histVec.WithLabelValues("val2").Observe(float64(40))
-
- reg := prometheus.NewRegistry()
- reg.MustRegister(histVec)
-
- mfs, err := reg.Gather()
- if err != nil {
- t.Fatalf("error: %v", err)
- }
-
- now := model.Time(1477043083)
- var buf bytes.Buffer
- err = writeMetrics(&buf, mfs, "prefix", now)
- if err != nil {
- t.Fatalf("error: %v", err)
- }
-
- want := `prefix.name_bucket.constname.constvalue.labelname.val1.le.0_01 0 1477043
-prefix.name_bucket.constname.constvalue.labelname.val1.le.0_02 0 1477043
-prefix.name_bucket.constname.constvalue.labelname.val1.le.0_05 0 1477043
-prefix.name_bucket.constname.constvalue.labelname.val1.le.0_1 0 1477043
-prefix.name_sum.constname.constvalue.labelname.val1 60 1477043
-prefix.name_count.constname.constvalue.labelname.val1 3 1477043
-prefix.name_bucket.constname.constvalue.labelname.val1.le._Inf 3 1477043
-prefix.name_bucket.constname.constvalue.labelname.val2.le.0_01 0 1477043
-prefix.name_bucket.constname.constvalue.labelname.val2.le.0_02 0 1477043
-prefix.name_bucket.constname.constvalue.labelname.val2.le.0_05 0 1477043
-prefix.name_bucket.constname.constvalue.labelname.val2.le.0_1 0 1477043
-prefix.name_sum.constname.constvalue.labelname.val2 90 1477043
-prefix.name_count.constname.constvalue.labelname.val2 3 1477043
-prefix.name_bucket.constname.constvalue.labelname.val2.le._Inf 3 1477043
-`
- if got := buf.String(); want != got {
- t.Fatalf("wanted \n%s\n, got \n%s\n", want, got)
- }
-}
-
-func TestToReader(t *testing.T) {
- cntVec := prometheus.NewCounterVec(
- prometheus.CounterOpts{
- Name: "name",
- Help: "docstring",
- ConstLabels: prometheus.Labels{"constname": "constvalue"},
- },
- []string{"labelname"},
- )
- cntVec.WithLabelValues("val1").Inc()
- cntVec.WithLabelValues("val2").Inc()
-
- reg := prometheus.NewRegistry()
- reg.MustRegister(cntVec)
-
- want := `prefix.name.constname.constvalue.labelname.val1 1 1477043
-prefix.name.constname.constvalue.labelname.val2 1 1477043
-`
- mfs, err := reg.Gather()
- if err != nil {
- t.Fatalf("error: %v", err)
- }
-
- now := model.Time(1477043083)
- var buf bytes.Buffer
- err = writeMetrics(&buf, mfs, "prefix", now)
- if err != nil {
- t.Fatalf("error: %v", err)
- }
-
- if got := buf.String(); want != got {
- t.Fatalf("wanted \n%s\n, got \n%s\n", want, got)
- }
-}
-
-func TestPush(t *testing.T) {
- reg := prometheus.NewRegistry()
- cntVec := prometheus.NewCounterVec(
- prometheus.CounterOpts{
- Name: "name",
- Help: "docstring",
- ConstLabels: prometheus.Labels{"constname": "constvalue"},
- },
- []string{"labelname"},
- )
- cntVec.WithLabelValues("val1").Inc()
- cntVec.WithLabelValues("val2").Inc()
- reg.MustRegister(cntVec)
-
- host := "localhost"
- port := ":56789"
- b, err := NewBridge(&Config{
- URL: host + port,
- Gatherer: reg,
- Prefix: "prefix",
- })
- if err != nil {
- t.Fatalf("error creating bridge: %v", err)
- }
-
- nmg, err := newMockGraphite(port)
- if err != nil {
- t.Fatalf("error creating mock graphite: %v", err)
- }
- defer nmg.Close()
-
- err = b.Push()
- if err != nil {
- t.Fatalf("error pushing: %v", err)
- }
-
- wants := []string{
- "prefix.name.constname.constvalue.labelname.val1 1",
- "prefix.name.constname.constvalue.labelname.val2 1",
- }
-
- select {
- case got := <-nmg.readc:
- for _, want := range wants {
- matched, err := regexp.MatchString(want, got)
- if err != nil {
- t.Fatalf("error pushing: %v", err)
- }
- if !matched {
- t.Fatalf("missing metric:\nno match for %s received by server:\n%s", want, got)
- }
- }
- return
- case err := <-nmg.errc:
- t.Fatalf("error reading push: %v", err)
- case <-time.After(50 * time.Millisecond):
- t.Fatalf("no result from graphite server")
- }
-}
-
-func newMockGraphite(port string) (*mockGraphite, error) {
- readc := make(chan string)
- errc := make(chan error)
- ln, err := net.Listen("tcp", port)
- if err != nil {
- return nil, err
- }
-
- go func() {
- conn, err := ln.Accept()
- if err != nil {
- errc <- err
- }
- var b bytes.Buffer
- io.Copy(&b, conn)
- readc <- b.String()
- }()
-
- return &mockGraphite{
- readc: readc,
- errc: errc,
- Listener: ln,
- }, nil
-}
-
-type mockGraphite struct {
- readc chan string
- errc chan error
-
- net.Listener
-}
-
-func ExampleBridge() {
- b, err := NewBridge(&Config{
- URL: "graphite.example.org:3099",
- Gatherer: prometheus.DefaultGatherer,
- Prefix: "prefix",
- Interval: 15 * time.Second,
- Timeout: 10 * time.Second,
- ErrorHandling: AbortOnError,
- Logger: log.New(os.Stdout, "graphite bridge: ", log.Lshortfile),
- })
- if err != nil {
- panic(err)
- }
-
- go func() {
- // Start something in a goroutine that uses metrics.
- }()
-
- // Push initial metrics to Graphite. Fail fast if the push fails.
- if err := b.Push(); err != nil {
- panic(err)
- }
-
- // Create a Context to control stopping the Run() loop that pushes
- // metrics to Graphite.
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
-
- // Start pushing metrics to Graphite in the Run() loop.
- b.Run(ctx)
-}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/histogram.go b/vendor/github.com/prometheus/client_golang/prometheus/histogram.go
index f46eff6ac..9719e8fac 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/histogram.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/histogram.go
@@ -308,23 +308,23 @@ func NewHistogramVec(opts HistogramOpts, labelNames []string) *HistogramVec {
}
// GetMetricWithLabelValues replaces the method of the same name in
-// MetricVec. The difference is that this method returns an Observer and not a
-// Metric so that no type conversion to an Observer is required.
-func (m *HistogramVec) GetMetricWithLabelValues(lvs ...string) (Observer, error) {
+// MetricVec. The difference is that this method returns a Histogram and not a
+// Metric so that no type conversion is required.
+func (m *HistogramVec) GetMetricWithLabelValues(lvs ...string) (Histogram, error) {
metric, err := m.MetricVec.GetMetricWithLabelValues(lvs...)
if metric != nil {
- return metric.(Observer), err
+ return metric.(Histogram), err
}
return nil, err
}
// GetMetricWith replaces the method of the same name in MetricVec. The
-// difference is that this method returns an Observer and not a Metric so that no
-// type conversion to an Observer is required.
-func (m *HistogramVec) GetMetricWith(labels Labels) (Observer, error) {
+// difference is that this method returns a Histogram and not a Metric so that no
+// type conversion is required.
+func (m *HistogramVec) GetMetricWith(labels Labels) (Histogram, error) {
metric, err := m.MetricVec.GetMetricWith(labels)
if metric != nil {
- return metric.(Observer), err
+ return metric.(Histogram), err
}
return nil, err
}
@@ -333,15 +333,15 @@ func (m *HistogramVec) GetMetricWith(labels Labels) (Observer, error) {
// GetMetricWithLabelValues would have returned an error. By not returning an
// error, WithLabelValues allows shortcuts like
// myVec.WithLabelValues("404", "GET").Observe(42.21)
-func (m *HistogramVec) WithLabelValues(lvs ...string) Observer {
- return m.MetricVec.WithLabelValues(lvs...).(Observer)
+func (m *HistogramVec) WithLabelValues(lvs ...string) Histogram {
+ return m.MetricVec.WithLabelValues(lvs...).(Histogram)
}
// With works as GetMetricWith, but panics where GetMetricWithLabels would have
// returned an error. By not returning an error, With allows shortcuts like
// myVec.With(Labels{"code": "404", "method": "GET"}).Observe(42.21)
-func (m *HistogramVec) With(labels Labels) Observer {
- return m.MetricVec.With(labels).(Observer)
+func (m *HistogramVec) With(labels Labels) Histogram {
+ return m.MetricVec.With(labels).(Histogram)
}
type constHistogram struct {
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/histogram_test.go b/vendor/github.com/prometheus/client_golang/prometheus/histogram_test.go
index 5a20f4b6b..d1242e08d 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/histogram_test.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/histogram_test.go
@@ -119,28 +119,6 @@ func BenchmarkHistogramWrite8(b *testing.B) {
benchmarkHistogramWrite(8, b)
}
-func TestHistogramNonMonotonicBuckets(t *testing.T) {
- testCases := map[string][]float64{
- "not strictly monotonic": {1, 2, 2, 3},
- "not monotonic at all": {1, 2, 4, 3, 5},
- "have +Inf in the middle": {1, 2, math.Inf(+1), 3},
- }
- for name, buckets := range testCases {
- func() {
- defer func() {
- if r := recover(); r == nil {
- t.Errorf("Buckets %v are %s but NewHistogram did not panic.", buckets, name)
- }
- }()
- _ = NewHistogram(HistogramOpts{
- Name: "test_histogram",
- Help: "helpless",
- Buckets: buckets,
- })
- }()
- }
-}
-
// Intentionally adding +Inf here to test if that case is handled correctly.
// Also, getCumulativeCounts depends on it.
var testBuckets = []float64{-2, -1, -0.5, 0, 0.5, 1, 2, math.Inf(+1)}
@@ -286,7 +264,7 @@ func TestHistogramVecConcurrency(t *testing.T) {
for i := 0; i < vecLength; i++ {
m := &dto.Metric{}
s := his.WithLabelValues(string('A' + i))
- s.(Histogram).Write(m)
+ s.Write(m)
if got, want := len(m.Histogram.Bucket), len(testBuckets)-1; got != want {
t.Errorf("got %d buckets in protobuf, want %d", got, want)
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/http.go b/vendor/github.com/prometheus/client_golang/prometheus/http.go
index d485ce0b8..67ee5ac79 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/http.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/http.go
@@ -62,8 +62,7 @@ func giveBuf(buf *bytes.Buffer) {
//
// Deprecated: Please note the issues described in the doc comment of
// InstrumentHandler. You might want to consider using promhttp.Handler instead
-// (which is not instrumented, but can be instrumented with the tooling provided
-// in package promhttp).
+// (which is non instrumented).
func Handler() http.Handler {
return InstrumentHandler("prometheus", UninstrumentedHandler())
}
@@ -159,8 +158,7 @@ func nowSeries(t ...time.Time) nower {
// value. http_requests_total is a metric vector partitioned by HTTP method
// (label name "method") and HTTP status code (label name "code").
//
-// Deprecated: InstrumentHandler has several issues. Use the tooling provided in
-// package promhttp instead. The issues are the following:
+// Deprecated: InstrumentHandler has several issues:
//
// - It uses Summaries rather than Histograms. Summaries are not useful if
// aggregation across multiple instances is required.
@@ -174,8 +172,9 @@ func nowSeries(t ...time.Time) nower {
// httputil.ReverseProxy is a prominent example for a handler
// performing such writes.
//
-// - It has additional issues with HTTP/2, cf.
-// https://github.com/prometheus/client_golang/issues/272.
+// Upcoming versions of this package will provide ways of instrumenting HTTP
+// handlers that are more flexible and have fewer issues. Please prefer direct
+// instrumentation in the meantime.
func InstrumentHandler(handlerName string, handler http.Handler) http.HandlerFunc {
return InstrumentHandlerFunc(handlerName, handler.ServeHTTP)
}
@@ -185,13 +184,12 @@ func InstrumentHandler(handlerName string, handler http.Handler) http.HandlerFun
// issues).
//
// Deprecated: InstrumentHandlerFunc is deprecated for the same reasons as
-// InstrumentHandler is. Use the tooling provided in package promhttp instead.
+// InstrumentHandler is.
func InstrumentHandlerFunc(handlerName string, handlerFunc func(http.ResponseWriter, *http.Request)) http.HandlerFunc {
return InstrumentHandlerFuncWithOpts(
SummaryOpts{
Subsystem: "http",
ConstLabels: Labels{"handler": handlerName},
- Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
},
handlerFunc,
)
@@ -224,7 +222,7 @@ func InstrumentHandlerFunc(handlerName string, handlerFunc func(http.ResponseWri
// SummaryOpts.
//
// Deprecated: InstrumentHandlerWithOpts is deprecated for the same reasons as
-// InstrumentHandler is. Use the tooling provided in package promhttp instead.
+// InstrumentHandler is.
func InstrumentHandlerWithOpts(opts SummaryOpts, handler http.Handler) http.HandlerFunc {
return InstrumentHandlerFuncWithOpts(opts, handler.ServeHTTP)
}
@@ -235,7 +233,7 @@ func InstrumentHandlerWithOpts(opts SummaryOpts, handler http.Handler) http.Hand
// SummaryOpts are used.
//
// Deprecated: InstrumentHandlerFuncWithOpts is deprecated for the same reasons
-// as InstrumentHandler is. Use the tooling provided in package promhttp instead.
+// as InstrumentHandler is.
func InstrumentHandlerFuncWithOpts(opts SummaryOpts, handlerFunc func(http.ResponseWriter, *http.Request)) http.HandlerFunc {
reqCnt := NewCounterVec(
CounterOpts{
@@ -247,52 +245,34 @@ func InstrumentHandlerFuncWithOpts(opts SummaryOpts, handlerFunc func(http.Respo
},
instLabels,
)
- if err := Register(reqCnt); err != nil {
- if are, ok := err.(AlreadyRegisteredError); ok {
- reqCnt = are.ExistingCollector.(*CounterVec)
- } else {
- panic(err)
- }
- }
opts.Name = "request_duration_microseconds"
opts.Help = "The HTTP request latencies in microseconds."
reqDur := NewSummary(opts)
- if err := Register(reqDur); err != nil {
- if are, ok := err.(AlreadyRegisteredError); ok {
- reqDur = are.ExistingCollector.(Summary)
- } else {
- panic(err)
- }
- }
opts.Name = "request_size_bytes"
opts.Help = "The HTTP request sizes in bytes."
reqSz := NewSummary(opts)
- if err := Register(reqSz); err != nil {
- if are, ok := err.(AlreadyRegisteredError); ok {
- reqSz = are.ExistingCollector.(Summary)
- } else {
- panic(err)
- }
- }
opts.Name = "response_size_bytes"
opts.Help = "The HTTP response sizes in bytes."
resSz := NewSummary(opts)
- if err := Register(resSz); err != nil {
- if are, ok := err.(AlreadyRegisteredError); ok {
- resSz = are.ExistingCollector.(Summary)
- } else {
- panic(err)
- }
- }
+
+ regReqCnt := MustRegisterOrGet(reqCnt).(*CounterVec)
+ regReqDur := MustRegisterOrGet(reqDur).(Summary)
+ regReqSz := MustRegisterOrGet(reqSz).(Summary)
+ regResSz := MustRegisterOrGet(resSz).(Summary)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
now := time.Now()
delegate := &responseWriterDelegator{ResponseWriter: w}
- out := computeApproximateRequestSize(r)
+ out := make(chan int)
+ urlLen := 0
+ if r.URL != nil {
+ urlLen = len(r.URL.String())
+ }
+ go computeApproximateRequestSize(r, out, urlLen)
_, cn := w.(http.CloseNotifier)
_, fl := w.(http.Flusher)
@@ -310,44 +290,30 @@ func InstrumentHandlerFuncWithOpts(opts SummaryOpts, handlerFunc func(http.Respo
method := sanitizeMethod(r.Method)
code := sanitizeCode(delegate.status)
- reqCnt.WithLabelValues(method, code).Inc()
- reqDur.Observe(elapsed)
- resSz.Observe(float64(delegate.written))
- reqSz.Observe(float64(<-out))
+ regReqCnt.WithLabelValues(method, code).Inc()
+ regReqDur.Observe(elapsed)
+ regResSz.Observe(float64(delegate.written))
+ regReqSz.Observe(float64(<-out))
})
}
-func computeApproximateRequestSize(r *http.Request) <-chan int {
- // Get URL length in current go routine for avoiding a race condition.
- // HandlerFunc that runs in parallel may modify the URL.
- s := 0
- if r.URL != nil {
- s += len(r.URL.String())
- }
-
- out := make(chan int, 1)
-
- go func() {
- s += len(r.Method)
- s += len(r.Proto)
- for name, values := range r.Header {
- s += len(name)
- for _, value := range values {
- s += len(value)
- }
+func computeApproximateRequestSize(r *http.Request, out chan int, s int) {
+ s += len(r.Method)
+ s += len(r.Proto)
+ for name, values := range r.Header {
+ s += len(name)
+ for _, value := range values {
+ s += len(value)
}
- s += len(r.Host)
+ }
+ s += len(r.Host)
- // N.B. r.Form and r.MultipartForm are assumed to be included in r.URL.
+ // N.B. r.Form and r.MultipartForm are assumed to be included in r.URL.
- if r.ContentLength != -1 {
- s += int(r.ContentLength)
- }
- out <- s
- close(out)
- }()
-
- return out
+ if r.ContentLength != -1 {
+ s += int(r.ContentLength)
+ }
+ out <- s
}
type responseWriterDelegator struct {
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/http_test.go b/vendor/github.com/prometheus/client_golang/prometheus/http_test.go
index 7fd4077b9..ffe0418cf 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/http_test.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/http_test.go
@@ -44,10 +44,9 @@ func TestInstrumentHandler(t *testing.T) {
opts := SummaryOpts{
Subsystem: "http",
ConstLabels: Labels{"handler": "test-handler"},
- Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
}
- reqCnt := NewCounterVec(
+ reqCnt := MustRegisterOrGet(NewCounterVec(
CounterOpts{
Namespace: opts.Namespace,
Subsystem: opts.Subsystem,
@@ -56,51 +55,19 @@ func TestInstrumentHandler(t *testing.T) {
ConstLabels: opts.ConstLabels,
},
instLabels,
- )
- err := Register(reqCnt)
- if err == nil {
- t.Fatal("expected reqCnt to be registered already")
- }
- if are, ok := err.(AlreadyRegisteredError); ok {
- reqCnt = are.ExistingCollector.(*CounterVec)
- } else {
- t.Fatal("unexpected registration error:", err)
- }
+ )).(*CounterVec)
opts.Name = "request_duration_microseconds"
opts.Help = "The HTTP request latencies in microseconds."
- reqDur := NewSummary(opts)
- err = Register(reqDur)
- if err == nil {
- t.Fatal("expected reqDur to be registered already")
- }
- if are, ok := err.(AlreadyRegisteredError); ok {
- reqDur = are.ExistingCollector.(Summary)
- } else {
- t.Fatal("unexpected registration error:", err)
- }
+ reqDur := MustRegisterOrGet(NewSummary(opts)).(Summary)
opts.Name = "request_size_bytes"
opts.Help = "The HTTP request sizes in bytes."
- reqSz := NewSummary(opts)
- err = Register(reqSz)
- if err == nil {
- t.Fatal("expected reqSz to be registered already")
- }
- if _, ok := err.(AlreadyRegisteredError); !ok {
- t.Fatal("unexpected registration error:", err)
- }
+ MustRegisterOrGet(NewSummary(opts))
opts.Name = "response_size_bytes"
opts.Help = "The HTTP response sizes in bytes."
- resSz := NewSummary(opts)
- err = Register(resSz)
- if err == nil {
- t.Fatal("expected resSz to be registered already")
- }
- if _, ok := err.(AlreadyRegisteredError); !ok {
- t.Fatal("unexpected registration error:", err)
- }
+ MustRegisterOrGet(NewSummary(opts))
reqCnt.Reset()
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/observer.go b/vendor/github.com/prometheus/client_golang/prometheus/observer.go
deleted file mode 100644
index b0520e85e..000000000
--- a/vendor/github.com/prometheus/client_golang/prometheus/observer.go
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright 2017 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package prometheus
-
-// Observer is the interface that wraps the Observe method, which is used by
-// Histogram and Summary to add observations.
-type Observer interface {
- Observe(float64)
-}
-
-// The ObserverFunc type is an adapter to allow the use of ordinary
-// functions as Observers. If f is a function with the appropriate
-// signature, ObserverFunc(f) is an Observer that calls f.
-//
-// This adapter is usually used in connection with the Timer type, and there are
-// two general use cases:
-//
-// The most common one is to use a Gauge as the Observer for a Timer.
-// See the "Gauge" Timer example.
-//
-// The more advanced use case is to create a function that dynamically decides
-// which Observer to use for observing the duration. See the "Complex" Timer
-// example.
-type ObserverFunc func(float64)
-
-// Observe calls f(value). It implements Observer.
-func (f ObserverFunc) Observe(value float64) {
- f(value)
-}
-
-// ObserverVec is an interface implemented by `HistogramVec` and `SummaryVec`.
-type ObserverVec interface {
- GetMetricWith(Labels) (Observer, error)
- GetMetricWithLabelValues(lvs ...string) (Observer, error)
- With(Labels) Observer
- WithLabelValues(...string) Observer
-
- Collector
-}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector.go
index 94b2553e1..e31e62e78 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector.go
@@ -19,10 +19,10 @@ type processCollector struct {
pid int
collectFn func(chan<- Metric)
pidFn func() (int, error)
- cpuTotal *Desc
- openFDs, maxFDs *Desc
- vsize, rss *Desc
- startTime *Desc
+ cpuTotal Counter
+ openFDs, maxFDs Gauge
+ vsize, rss Gauge
+ startTime Gauge
}
// NewProcessCollector returns a collector which exports the current state of
@@ -44,45 +44,40 @@ func NewProcessCollectorPIDFn(
pidFn func() (int, error),
namespace string,
) Collector {
- ns := ""
- if len(namespace) > 0 {
- ns = namespace + "_"
- }
-
c := processCollector{
pidFn: pidFn,
collectFn: func(chan<- Metric) {},
- cpuTotal: NewDesc(
- ns+"process_cpu_seconds_total",
- "Total user and system CPU time spent in seconds.",
- nil, nil,
- ),
- openFDs: NewDesc(
- ns+"process_open_fds",
- "Number of open file descriptors.",
- nil, nil,
- ),
- maxFDs: NewDesc(
- ns+"process_max_fds",
- "Maximum number of open file descriptors.",
- nil, nil,
- ),
- vsize: NewDesc(
- ns+"process_virtual_memory_bytes",
- "Virtual memory size in bytes.",
- nil, nil,
- ),
- rss: NewDesc(
- ns+"process_resident_memory_bytes",
- "Resident memory size in bytes.",
- nil, nil,
- ),
- startTime: NewDesc(
- ns+"process_start_time_seconds",
- "Start time of the process since unix epoch in seconds.",
- nil, nil,
- ),
+ cpuTotal: NewCounter(CounterOpts{
+ Namespace: namespace,
+ Name: "process_cpu_seconds_total",
+ Help: "Total user and system CPU time spent in seconds.",
+ }),
+ openFDs: NewGauge(GaugeOpts{
+ Namespace: namespace,
+ Name: "process_open_fds",
+ Help: "Number of open file descriptors.",
+ }),
+ maxFDs: NewGauge(GaugeOpts{
+ Namespace: namespace,
+ Name: "process_max_fds",
+ Help: "Maximum number of open file descriptors.",
+ }),
+ vsize: NewGauge(GaugeOpts{
+ Namespace: namespace,
+ Name: "process_virtual_memory_bytes",
+ Help: "Virtual memory size in bytes.",
+ }),
+ rss: NewGauge(GaugeOpts{
+ Namespace: namespace,
+ Name: "process_resident_memory_bytes",
+ Help: "Resident memory size in bytes.",
+ }),
+ startTime: NewGauge(GaugeOpts{
+ Namespace: namespace,
+ Name: "process_start_time_seconds",
+ Help: "Start time of the process since unix epoch in seconds.",
+ }),
}
// Set up process metric collection if supported by the runtime.
@@ -95,12 +90,12 @@ func NewProcessCollectorPIDFn(
// Describe returns all descriptions of the collector.
func (c *processCollector) Describe(ch chan<- *Desc) {
- ch <- c.cpuTotal
- ch <- c.openFDs
- ch <- c.maxFDs
- ch <- c.vsize
- ch <- c.rss
- ch <- c.startTime
+ ch <- c.cpuTotal.Desc()
+ ch <- c.openFDs.Desc()
+ ch <- c.maxFDs.Desc()
+ ch <- c.vsize.Desc()
+ ch <- c.rss.Desc()
+ ch <- c.startTime.Desc()
}
// Collect returns the current state of all metrics of the collector.
@@ -122,19 +117,26 @@ func (c *processCollector) processCollect(ch chan<- Metric) {
}
if stat, err := p.NewStat(); err == nil {
- ch <- MustNewConstMetric(c.cpuTotal, CounterValue, stat.CPUTime())
- ch <- MustNewConstMetric(c.vsize, GaugeValue, float64(stat.VirtualMemory()))
- ch <- MustNewConstMetric(c.rss, GaugeValue, float64(stat.ResidentMemory()))
+ c.cpuTotal.Set(stat.CPUTime())
+ ch <- c.cpuTotal
+ c.vsize.Set(float64(stat.VirtualMemory()))
+ ch <- c.vsize
+ c.rss.Set(float64(stat.ResidentMemory()))
+ ch <- c.rss
+
if startTime, err := stat.StartTime(); err == nil {
- ch <- MustNewConstMetric(c.startTime, GaugeValue, startTime)
+ c.startTime.Set(startTime)
+ ch <- c.startTime
}
}
if fds, err := p.FileDescriptorsLen(); err == nil {
- ch <- MustNewConstMetric(c.openFDs, GaugeValue, float64(fds))
+ c.openFDs.Set(float64(fds))
+ ch <- c.openFDs
}
if limits, err := p.NewLimits(); err == nil {
- ch <- MustNewConstMetric(c.maxFDs, GaugeValue, float64(limits.OpenFiles))
+ c.maxFDs.Set(float64(limits.OpenFiles))
+ ch <- c.maxFDs
}
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_test.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_test.go
index c7acb47fe..d3362dae7 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_test.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_test.go
@@ -38,18 +38,18 @@ func TestProcessCollector(t *testing.T) {
}
for _, re := range []*regexp.Regexp{
- regexp.MustCompile("\nprocess_cpu_seconds_total [0-9]"),
- regexp.MustCompile("\nprocess_max_fds [1-9]"),
- regexp.MustCompile("\nprocess_open_fds [1-9]"),
- regexp.MustCompile("\nprocess_virtual_memory_bytes [1-9]"),
- regexp.MustCompile("\nprocess_resident_memory_bytes [1-9]"),
- regexp.MustCompile("\nprocess_start_time_seconds [0-9.]{10,}"),
- regexp.MustCompile("\nfoobar_process_cpu_seconds_total [0-9]"),
- regexp.MustCompile("\nfoobar_process_max_fds [1-9]"),
- regexp.MustCompile("\nfoobar_process_open_fds [1-9]"),
- regexp.MustCompile("\nfoobar_process_virtual_memory_bytes [1-9]"),
- regexp.MustCompile("\nfoobar_process_resident_memory_bytes [1-9]"),
- regexp.MustCompile("\nfoobar_process_start_time_seconds [0-9.]{10,}"),
+ regexp.MustCompile("process_cpu_seconds_total [0-9]"),
+ regexp.MustCompile("process_max_fds [1-9]"),
+ regexp.MustCompile("process_open_fds [1-9]"),
+ regexp.MustCompile("process_virtual_memory_bytes [1-9]"),
+ regexp.MustCompile("process_resident_memory_bytes [1-9]"),
+ regexp.MustCompile("process_start_time_seconds [0-9.]{10,}"),
+ regexp.MustCompile("foobar_process_cpu_seconds_total [0-9]"),
+ regexp.MustCompile("foobar_process_max_fds [1-9]"),
+ regexp.MustCompile("foobar_process_open_fds [1-9]"),
+ regexp.MustCompile("foobar_process_virtual_memory_bytes [1-9]"),
+ regexp.MustCompile("foobar_process_resident_memory_bytes [1-9]"),
+ regexp.MustCompile("foobar_process_start_time_seconds [0-9.]{10,}"),
} {
if !re.Match(buf.Bytes()) {
t.Errorf("want body to match %s\n%s", re, buf.String())
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_1_7.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_1_7.go
deleted file mode 100644
index 5e38c7ca4..000000000
--- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_1_7.go
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright 2017 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// +build !go1.8
-
-package promhttp
-
-import (
- "io"
- "net/http"
-)
-
-func newDelegator(w http.ResponseWriter) delegator {
- d := &responseWriterDelegator{ResponseWriter: w}
-
- _, cn := w.(http.CloseNotifier)
- _, fl := w.(http.Flusher)
- _, hj := w.(http.Hijacker)
- _, rf := w.(io.ReaderFrom)
- if cn && fl && hj && rf {
- return &fancyDelegator{d}
- }
-
- return d
-}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_1_8.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_1_8.go
deleted file mode 100644
index 98b565096..000000000
--- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_1_8.go
+++ /dev/null
@@ -1,70 +0,0 @@
-// Copyright 2017 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// +build go1.8
-
-package promhttp
-
-import (
- "io"
- "net/http"
-)
-
-// newDelegator handles the four different methods of upgrading a
-// http.ResponseWriter to delegator.
-func newDelegator(w http.ResponseWriter) delegator {
- d := &responseWriterDelegator{ResponseWriter: w}
-
- _, cn := w.(http.CloseNotifier)
- _, fl := w.(http.Flusher)
- _, hj := w.(http.Hijacker)
- _, ps := w.(http.Pusher)
- _, rf := w.(io.ReaderFrom)
-
- // Check for the four most common combination of interfaces a
- // http.ResponseWriter might implement.
- switch {
- case cn && fl && hj && rf && ps:
- // All interfaces.
- return &fancyPushDelegator{
- fancyDelegator: &fancyDelegator{d},
- p: &pushDelegator{d},
- }
- case cn && fl && hj && rf:
- // All interfaces, except http.Pusher.
- return &fancyDelegator{d}
- case ps:
- // Just http.Pusher.
- return &pushDelegator{d}
- }
-
- return d
-}
-
-type fancyPushDelegator struct {
- p *pushDelegator
-
- *fancyDelegator
-}
-
-func (f *fancyPushDelegator) Push(target string, opts *http.PushOptions) error {
- return f.p.Push(target, opts)
-}
-
-type pushDelegator struct {
- *responseWriterDelegator
-}
-
-func (f *pushDelegator) Push(target string, opts *http.PushOptions) error {
- return f.ResponseWriter.(http.Pusher).Push(target, opts)
-}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go
index 4c70a7af6..b6dd5a266 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go
@@ -11,24 +11,21 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-// Package promhttp provides tooling around HTTP servers and clients.
+// Copyright (c) 2013, The Prometheus Authors
+// All rights reserved.
//
-// First, the package allows the creation of http.Handler instances to expose
-// Prometheus metrics via HTTP. promhttp.Handler acts on the
-// prometheus.DefaultGatherer. With HandlerFor, you can create a handler for a
-// custom registry or anything that implements the Gatherer interface. It also
-// allows the creation of handlers that act differently on errors or allow to
-// log errors.
-//
-// Second, the package provides tooling to instrument instances of http.Handler
-// via middleware. Middleware wrappers follow the naming scheme
-// InstrumentHandlerX, where X describes the intended use of the middleware.
-// See each function's doc comment for specific details.
+// Use of this source code is governed by a BSD-style license that can be found
+// in the LICENSE file.
+
+// Package promhttp contains functions to create http.Handler instances to
+// expose Prometheus metrics via HTTP. In later versions of this package, it
+// will also contain tooling to instrument instances of http.Handler and
+// http.RoundTripper.
//
-// Finally, the package allows for an http.RoundTripper to be instrumented via
-// middleware. Middleware wrappers follow the naming scheme
-// InstrumentRoundTripperX, where X describes the intended use of the
-// middleware. See each function's doc comment for specific details.
+// promhttp.Handler acts on the prometheus.DefaultGatherer. With HandlerFor,
+// you can create a handler for a custom registry or anything that implements
+// the Gatherer interface. It also allows to create handlers that act
+// differently on errors or allow to log errors.
package promhttp
import (
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http_test.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http_test.go
index 413ff7baa..d4a7d4a7b 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http_test.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http_test.go
@@ -11,6 +11,12 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+// Copyright (c) 2013, The Prometheus 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 promhttp
import (
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go
deleted file mode 100644
index 1cf21f217..000000000
--- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright 2017 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package promhttp
-
-import (
- "net/http"
- "time"
-
- "github.com/prometheus/client_golang/prometheus"
-)
-
-// The RoundTripperFunc type is an adapter to allow the use of ordinary
-// functions as RoundTrippers. If f is a function with the appropriate
-// signature, RountTripperFunc(f) is a RoundTripper that calls f.
-type RoundTripperFunc func(req *http.Request) (*http.Response, error)
-
-// RoundTrip implements the RoundTripper interface.
-func (rt RoundTripperFunc) RoundTrip(r *http.Request) (*http.Response, error) {
- return rt(r)
-}
-
-// InstrumentRoundTripperInFlight is a middleware that wraps the provided
-// http.RoundTripper. It sets the provided prometheus.Gauge to the number of
-// requests currently handled by the wrapped http.RoundTripper.
-//
-// See the example for ExampleInstrumentRoundTripperDuration for example usage.
-func InstrumentRoundTripperInFlight(gauge prometheus.Gauge, next http.RoundTripper) RoundTripperFunc {
- return RoundTripperFunc(func(r *http.Request) (*http.Response, error) {
- gauge.Inc()
- defer gauge.Dec()
- return next.RoundTrip(r)
- })
-}
-
-// InstrumentRoundTripperCounter is a middleware that wraps the provided
-// http.RoundTripper to observe the request result with the provided CounterVec.
-// The CounterVec must have zero, one, or two labels. The only allowed label
-// names are "code" and "method". The function panics if any other instance
-// labels are provided. Partitioning of the CounterVec happens by HTTP status
-// code and/or HTTP method if the respective instance label names are present
-// in the CounterVec. For unpartitioned counting, use a CounterVec with
-// zero labels.
-//
-// If the wrapped RoundTripper panics or returns a non-nil error, the Counter
-// is not incremented.
-//
-// See the example for ExampleInstrumentRoundTripperDuration for example usage.
-func InstrumentRoundTripperCounter(counter *prometheus.CounterVec, next http.RoundTripper) RoundTripperFunc {
- code, method := checkLabels(counter)
-
- return RoundTripperFunc(func(r *http.Request) (*http.Response, error) {
- resp, err := next.RoundTrip(r)
- if err == nil {
- counter.With(labels(code, method, r.Method, resp.StatusCode)).Inc()
- }
- return resp, err
- })
-}
-
-// InstrumentRoundTripperDuration is a middleware that wraps the provided
-// http.RoundTripper to observe the request duration with the provided ObserverVec.
-// The ObserverVec must have zero, one, or two labels. The only allowed label
-// names are "code" and "method". The function panics if any other instance
-// labels are provided. The Observe method of the Observer in the ObserverVec
-// is called with the request duration in seconds. Partitioning happens by HTTP
-// status code and/or HTTP method if the respective instance label names are
-// present in the ObserverVec. For unpartitioned observations, use an
-// ObserverVec with zero labels. Note that partitioning of Histograms is
-// expensive and should be used judiciously.
-//
-// If the wrapped RoundTripper panics or returns a non-nil error, no values are
-// reported.
-func InstrumentRoundTripperDuration(obs prometheus.ObserverVec, next http.RoundTripper) RoundTripperFunc {
- code, method := checkLabels(obs)
-
- return RoundTripperFunc(func(r *http.Request) (*http.Response, error) {
- start := time.Now()
- resp, err := next.RoundTrip(r)
- if err == nil {
- obs.With(labels(code, method, r.Method, resp.StatusCode)).Observe(time.Since(start).Seconds())
- }
- return resp, err
- })
-}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client_1_8.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client_1_8.go
deleted file mode 100644
index b51d91052..000000000
--- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client_1_8.go
+++ /dev/null
@@ -1,142 +0,0 @@
-// Copyright 2017 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// +build go1.8
-
-package promhttp
-
-import (
- "context"
- "crypto/tls"
- "net/http"
- "net/http/httptrace"
- "time"
-)
-
-// InstrumentTrace is used to offer flexibility in instrumenting the available
-// httptrace.ClientTrace hook functions. Each function is passed a float64
-// representing the time in seconds since the start of the http request. A user
-// may choose to use separately buckets Histograms, or implement custom
-// instance labels on a per function basis.
-type InstrumentTrace struct {
- GotConn func(float64)
- PutIdleConn func(float64)
- GotFirstResponseByte func(float64)
- Got100Continue func(float64)
- DNSStart func(float64)
- DNSDone func(float64)
- ConnectStart func(float64)
- ConnectDone func(float64)
- TLSHandshakeStart func(float64)
- TLSHandshakeDone func(float64)
- WroteHeaders func(float64)
- Wait100Continue func(float64)
- WroteRequest func(float64)
-}
-
-// InstrumentRoundTripperTrace is a middleware that wraps the provided
-// RoundTripper and reports times to hook functions provided in the
-// InstrumentTrace struct. Hook functions that are not present in the provided
-// InstrumentTrace struct are ignored. Times reported to the hook functions are
-// time since the start of the request. Note that partitioning of Histograms
-// is expensive and should be used judiciously.
-//
-// For hook functions that receive an error as an argument, no observations are
-// made in the event of a non-nil error value.
-//
-// See the example for ExampleInstrumentRoundTripperDuration for example usage.
-func InstrumentRoundTripperTrace(it *InstrumentTrace, next http.RoundTripper) RoundTripperFunc {
- return RoundTripperFunc(func(r *http.Request) (*http.Response, error) {
- start := time.Now()
-
- trace := &httptrace.ClientTrace{
- GotConn: func(_ httptrace.GotConnInfo) {
- if it.GotConn != nil {
- it.GotConn(time.Since(start).Seconds())
- }
- },
- PutIdleConn: func(err error) {
- if err != nil {
- return
- }
- if it.PutIdleConn != nil {
- it.PutIdleConn(time.Since(start).Seconds())
- }
- },
- DNSStart: func(_ httptrace.DNSStartInfo) {
- if it.DNSStart != nil {
- it.DNSStart(time.Since(start).Seconds())
- }
- },
- DNSDone: func(_ httptrace.DNSDoneInfo) {
- if it.DNSStart != nil {
- it.DNSStart(time.Since(start).Seconds())
- }
- },
- ConnectStart: func(_, _ string) {
- if it.ConnectStart != nil {
- it.ConnectStart(time.Since(start).Seconds())
- }
- },
- ConnectDone: func(_, _ string, err error) {
- if err != nil {
- return
- }
- if it.ConnectDone != nil {
- it.ConnectDone(time.Since(start).Seconds())
- }
- },
- GotFirstResponseByte: func() {
- if it.GotFirstResponseByte != nil {
- it.GotFirstResponseByte(time.Since(start).Seconds())
- }
- },
- Got100Continue: func() {
- if it.Got100Continue != nil {
- it.Got100Continue(time.Since(start).Seconds())
- }
- },
- TLSHandshakeStart: func() {
- if it.TLSHandshakeStart != nil {
- it.TLSHandshakeStart(time.Since(start).Seconds())
- }
- },
- TLSHandshakeDone: func(_ tls.ConnectionState, err error) {
- if err != nil {
- return
- }
- if it.TLSHandshakeDone != nil {
- it.TLSHandshakeDone(time.Since(start).Seconds())
- }
- },
- WroteHeaders: func() {
- if it.WroteHeaders != nil {
- it.WroteHeaders(time.Since(start).Seconds())
- }
- },
- Wait100Continue: func() {
- if it.Wait100Continue != nil {
- it.Wait100Continue(time.Since(start).Seconds())
- }
- },
- WroteRequest: func(_ httptrace.WroteRequestInfo) {
- if it.WroteRequest != nil {
- it.WroteRequest(time.Since(start).Seconds())
- }
- },
- }
- r = r.WithContext(httptrace.WithClientTrace(context.Background(), trace))
-
- return next.RoundTrip(r)
- })
-}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client_1_8_test.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client_1_8_test.go
deleted file mode 100644
index 7e3f5229f..000000000
--- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client_1_8_test.go
+++ /dev/null
@@ -1,195 +0,0 @@
-// Copyright 2017 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// +build go1.8
-
-package promhttp
-
-import (
- "log"
- "net/http"
- "testing"
- "time"
-
- "github.com/prometheus/client_golang/prometheus"
-)
-
-func TestClientMiddlewareAPI(t *testing.T) {
- client := http.DefaultClient
- client.Timeout = 1 * time.Second
-
- reg := prometheus.NewRegistry()
-
- inFlightGauge := prometheus.NewGauge(prometheus.GaugeOpts{
- Name: "client_in_flight_requests",
- Help: "A gauge of in-flight requests for the wrapped client.",
- })
-
- counter := prometheus.NewCounterVec(
- prometheus.CounterOpts{
- Name: "client_api_requests_total",
- Help: "A counter for requests from the wrapped client.",
- },
- []string{"code", "method"},
- )
-
- dnsLatencyVec := prometheus.NewHistogramVec(
- prometheus.HistogramOpts{
- Name: "dns_duration_seconds",
- Help: "Trace dns latency histogram.",
- Buckets: []float64{.005, .01, .025, .05},
- },
- []string{"event"},
- )
-
- tlsLatencyVec := prometheus.NewHistogramVec(
- prometheus.HistogramOpts{
- Name: "tls_duration_seconds",
- Help: "Trace tls latency histogram.",
- Buckets: []float64{.05, .1, .25, .5},
- },
- []string{"event"},
- )
-
- histVec := prometheus.NewHistogramVec(
- prometheus.HistogramOpts{
- Name: "request_duration_seconds",
- Help: "A histogram of request latencies.",
- Buckets: prometheus.DefBuckets,
- },
- []string{"method"},
- )
-
- reg.MustRegister(counter, tlsLatencyVec, dnsLatencyVec, histVec, inFlightGauge)
-
- trace := &InstrumentTrace{
- DNSStart: func(t float64) {
- dnsLatencyVec.WithLabelValues("dns_start")
- },
- DNSDone: func(t float64) {
- dnsLatencyVec.WithLabelValues("dns_done")
- },
- TLSHandshakeStart: func(t float64) {
- tlsLatencyVec.WithLabelValues("tls_handshake_start")
- },
- TLSHandshakeDone: func(t float64) {
- tlsLatencyVec.WithLabelValues("tls_handshake_done")
- },
- }
-
- client.Transport = InstrumentRoundTripperInFlight(inFlightGauge,
- InstrumentRoundTripperCounter(counter,
- InstrumentRoundTripperTrace(trace,
- InstrumentRoundTripperDuration(histVec, http.DefaultTransport),
- ),
- ),
- )
-
- resp, err := client.Get("http://google.com")
- if err != nil {
- t.Fatalf("%v", err)
- }
- defer resp.Body.Close()
-}
-
-func ExampleInstrumentRoundTripperDuration() {
- client := http.DefaultClient
- client.Timeout = 1 * time.Second
-
- inFlightGauge := prometheus.NewGauge(prometheus.GaugeOpts{
- Name: "client_in_flight_requests",
- Help: "A gauge of in-flight requests for the wrapped client.",
- })
-
- counter := prometheus.NewCounterVec(
- prometheus.CounterOpts{
- Name: "client_api_requests_total",
- Help: "A counter for requests from the wrapped client.",
- },
- []string{"code", "method"},
- )
-
- // dnsLatencyVec uses custom buckets based on expected dns durations.
- // It has an instance label "event", which is set in the
- // DNSStart and DNSDonehook functions defined in the
- // InstrumentTrace struct below.
- dnsLatencyVec := prometheus.NewHistogramVec(
- prometheus.HistogramOpts{
- Name: "dns_duration_seconds",
- Help: "Trace dns latency histogram.",
- Buckets: []float64{.005, .01, .025, .05},
- },
- []string{"event"},
- )
-
- // tlsLatencyVec uses custom buckets based on expected tls durations.
- // It has an instance label "event", which is set in the
- // TLSHandshakeStart and TLSHandshakeDone hook functions defined in the
- // InstrumentTrace struct below.
- tlsLatencyVec := prometheus.NewHistogramVec(
- prometheus.HistogramOpts{
- Name: "tls_duration_seconds",
- Help: "Trace tls latency histogram.",
- Buckets: []float64{.05, .1, .25, .5},
- },
- []string{"event"},
- )
-
- // histVec has no labels, making it a zero-dimensional ObserverVec.
- histVec := prometheus.NewHistogramVec(
- prometheus.HistogramOpts{
- Name: "request_duration_seconds",
- Help: "A histogram of request latencies.",
- Buckets: prometheus.DefBuckets,
- },
- []string{},
- )
-
- // Register all of the metrics in the standard registry.
- prometheus.MustRegister(counter, tlsLatencyVec, dnsLatencyVec, histVec, inFlightGauge)
-
- // Define functions for the available httptrace.ClientTrace hook
- // functions that we want to instrument.
- trace := &InstrumentTrace{
- DNSStart: func(t float64) {
- dnsLatencyVec.WithLabelValues("dns_start")
- },
- DNSDone: func(t float64) {
- dnsLatencyVec.WithLabelValues("dns_done")
- },
- TLSHandshakeStart: func(t float64) {
- tlsLatencyVec.WithLabelValues("tls_handshake_start")
- },
- TLSHandshakeDone: func(t float64) {
- tlsLatencyVec.WithLabelValues("tls_handshake_done")
- },
- }
-
- // Wrap the default RoundTripper with middleware.
- roundTripper := InstrumentRoundTripperInFlight(inFlightGauge,
- InstrumentRoundTripperCounter(counter,
- InstrumentRoundTripperTrace(trace,
- InstrumentRoundTripperDuration(histVec, http.DefaultTransport),
- ),
- ),
- )
-
- // Set the RoundTripper on our client.
- client.Transport = roundTripper
-
- resp, err := client.Get("http://google.com")
- if err != nil {
- log.Printf("error: %v", err)
- }
- defer resp.Body.Close()
-}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go
deleted file mode 100644
index 1beab4b42..000000000
--- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go
+++ /dev/null
@@ -1,473 +0,0 @@
-// Copyright 2017 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package promhttp
-
-import (
- "bufio"
- "io"
- "net"
- "net/http"
- "strconv"
- "strings"
- "time"
-
- dto "github.com/prometheus/client_model/go"
-
- "github.com/prometheus/client_golang/prometheus"
-)
-
-// magicString is used for the hacky label test in checkLabels. Remove once fixed.
-const magicString = "zZgWfBxLqvG8kc8IMv3POi2Bb0tZI3vAnBx+gBaFi9FyPzB/CzKUer1yufDa"
-
-// InstrumentHandlerInFlight is a middleware that wraps the provided
-// http.Handler. It sets the provided prometheus.Gauge to the number of
-// requests currently handled by the wrapped http.Handler.
-//
-// See the example for InstrumentHandlerDuration for example usage.
-func InstrumentHandlerInFlight(g prometheus.Gauge, next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- g.Inc()
- defer g.Dec()
- next.ServeHTTP(w, r)
- })
-}
-
-// InstrumentHandlerDuration is a middleware that wraps the provided
-// http.Handler to observe the request duration with the provided ObserverVec.
-// The ObserverVec must have zero, one, or two labels. The only allowed label
-// names are "code" and "method". The function panics if any other instance
-// labels are provided. The Observe method of the Observer in the ObserverVec
-// is called with the request duration in seconds. Partitioning happens by HTTP
-// status code and/or HTTP method if the respective instance label names are
-// present in the ObserverVec. For unpartitioned observations, use an
-// ObserverVec with zero labels. Note that partitioning of Histograms is
-// expensive and should be used judiciously.
-//
-// If the wrapped Handler does not set a status code, a status code of 200 is assumed.
-//
-// If the wrapped Handler panics, no values are reported.
-func InstrumentHandlerDuration(obs prometheus.ObserverVec, next http.Handler) http.HandlerFunc {
- code, method := checkLabels(obs)
-
- if code {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- now := time.Now()
- d := newDelegator(w)
- next.ServeHTTP(d, r)
-
- obs.With(labels(code, method, r.Method, d.Status())).Observe(time.Since(now).Seconds())
- })
- }
-
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- now := time.Now()
- next.ServeHTTP(w, r)
- obs.With(labels(code, method, r.Method, 0)).Observe(time.Since(now).Seconds())
- })
-}
-
-// InstrumentHandlerCounter is a middleware that wraps the provided
-// http.Handler to observe the request result with the provided CounterVec.
-// The CounterVec must have zero, one, or two labels. The only allowed label
-// names are "code" and "method". The function panics if any other instance
-// labels are provided. Partitioning of the CounterVec happens by HTTP status
-// code and/or HTTP method if the respective instance label names are present
-// in the CounterVec. For unpartitioned counting, use a CounterVec with
-// zero labels.
-//
-// If the wrapped Handler does not set a status code, a status code of 200 is assumed.
-//
-// If the wrapped Handler panics, the Counter is not incremented.
-//
-// See the example for InstrumentHandlerDuration for example usage.
-func InstrumentHandlerCounter(counter *prometheus.CounterVec, next http.Handler) http.HandlerFunc {
- code, method := checkLabels(counter)
-
- if code {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- d := newDelegator(w)
- next.ServeHTTP(d, r)
- counter.With(labels(code, method, r.Method, d.Status())).Inc()
- })
- }
-
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- next.ServeHTTP(w, r)
- counter.With(labels(code, method, r.Method, 0)).Inc()
- })
-}
-
-// InstrumentHandlerRequestSize is a middleware that wraps the provided
-// http.Handler to observe the request size with the provided ObserverVec.
-// The ObserverVec must have zero, one, or two labels. The only allowed label
-// names are "code" and "method". The function panics if any other instance
-// labels are provided. The Observe method of the Observer in the ObserverVec
-// is called with the request size in bytes. Partitioning happens by HTTP
-// status code and/or HTTP method if the respective instance label names are
-// present in the ObserverVec. For unpartitioned observations, use an
-// ObserverVec with zero labels. Note that partitioning of Histograms is
-// expensive and should be used judiciously.
-//
-// If the wrapped Handler does not set a status code, a status code of 200 is assumed.
-//
-// If the wrapped Handler panics, no values are reported.
-//
-// See the example for InstrumentHandlerDuration for example usage.
-func InstrumentHandlerRequestSize(obs prometheus.ObserverVec, next http.Handler) http.HandlerFunc {
- code, method := checkLabels(obs)
-
- if code {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- d := newDelegator(w)
- next.ServeHTTP(d, r)
- size := computeApproximateRequestSize(r)
- obs.With(labels(code, method, r.Method, d.Status())).Observe(float64(size))
- })
- }
-
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- next.ServeHTTP(w, r)
- size := computeApproximateRequestSize(r)
- obs.With(labels(code, method, r.Method, 0)).Observe(float64(size))
- })
-}
-
-// InstrumentHandlerResponseSize is a middleware that wraps the provided
-// http.Handler to observe the response size with the provided ObserverVec.
-// The ObserverVec must have zero, one, or two labels. The only allowed label
-// names are "code" and "method". The function panics if any other instance
-// labels are provided. The Observe method of the Observer in the ObserverVec
-// is called with the response size in bytes. Partitioning happens by HTTP
-// status code and/or HTTP method if the respective instance label names are
-// present in the ObserverVec. For unpartitioned observations, use an
-// ObserverVec with zero labels. Note that partitioning of Histograms is
-// expensive and should be used judiciously.
-//
-// If the wrapped Handler does not set a status code, a status code of 200 is assumed.
-//
-// If the wrapped Handler panics, no values are reported.
-//
-// See the example for InstrumentHandlerDuration for example usage.
-func InstrumentHandlerResponseSize(obs prometheus.ObserverVec, next http.Handler) http.Handler {
- code, method := checkLabels(obs)
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- d := newDelegator(w)
- next.ServeHTTP(d, r)
- obs.With(labels(code, method, r.Method, d.Status())).Observe(float64(d.Written()))
- })
-}
-
-func checkLabels(c prometheus.Collector) (code bool, method bool) {
- // TODO(beorn7): Remove this hacky way to check for instance labels
- // once Descriptors can have their dimensionality queried.
- var (
- desc *prometheus.Desc
- pm dto.Metric
- )
-
- descc := make(chan *prometheus.Desc, 1)
- c.Describe(descc)
-
- select {
- case desc = <-descc:
- default:
- panic("no description provided by collector")
- }
- select {
- case <-descc:
- panic("more than one description provided by collector")
- default:
- }
-
- close(descc)
-
- if _, err := prometheus.NewConstMetric(desc, prometheus.UntypedValue, 0); err == nil {
- return
- }
- if m, err := prometheus.NewConstMetric(desc, prometheus.UntypedValue, 0, magicString); err == nil {
- if err := m.Write(&pm); err != nil {
- panic("error checking metric for labels")
- }
- for _, label := range pm.Label {
- name, value := label.GetName(), label.GetValue()
- if value != magicString {
- continue
- }
- switch name {
- case "code":
- code = true
- case "method":
- method = true
- default:
- panic("metric partitioned with non-supported labels")
- }
- return
- }
- panic("previously set label not found – this must never happen")
- }
- if m, err := prometheus.NewConstMetric(desc, prometheus.UntypedValue, 0, magicString, magicString); err == nil {
- if err := m.Write(&pm); err != nil {
- panic("error checking metric for labels")
- }
- for _, label := range pm.Label {
- name, value := label.GetName(), label.GetValue()
- if value != magicString {
- continue
- }
- if name == "code" || name == "method" {
- continue
- }
- panic("metric partitioned with non-supported labels")
- }
- code = true
- method = true
- return
- }
- panic("metric partitioned with non-supported labels")
-}
-
-// emptyLabels is a one-time allocation for non-partitioned metrics to avoid
-// unnecessary allocations on each request.
-var emptyLabels = prometheus.Labels{}
-
-func labels(code, method bool, reqMethod string, status int) prometheus.Labels {
- if !(code || method) {
- return emptyLabels
- }
- labels := prometheus.Labels{}
-
- if code {
- labels["code"] = sanitizeCode(status)
- }
- if method {
- labels["method"] = sanitizeMethod(reqMethod)
- }
-
- return labels
-}
-
-func computeApproximateRequestSize(r *http.Request) int {
- s := 0
- if r.URL != nil {
- s += len(r.URL.String())
- }
-
- s += len(r.Method)
- s += len(r.Proto)
- for name, values := range r.Header {
- s += len(name)
- for _, value := range values {
- s += len(value)
- }
- }
- s += len(r.Host)
-
- // N.B. r.Form and r.MultipartForm are assumed to be included in r.URL.
-
- if r.ContentLength != -1 {
- s += int(r.ContentLength)
- }
- return s
-}
-
-func sanitizeMethod(m string) string {
- switch m {
- case "GET", "get":
- return "get"
- case "PUT", "put":
- return "put"
- case "HEAD", "head":
- return "head"
- case "POST", "post":
- return "post"
- case "DELETE", "delete":
- return "delete"
- case "CONNECT", "connect":
- return "connect"
- case "OPTIONS", "options":
- return "options"
- case "NOTIFY", "notify":
- return "notify"
- default:
- return strings.ToLower(m)
- }
-}
-
-// If the wrapped http.Handler has not set a status code, i.e. the value is
-// currently 0, santizeCode will return 200, for consistency with behavior in
-// the stdlib.
-func sanitizeCode(s int) string {
- switch s {
- case 100:
- return "100"
- case 101:
- return "101"
-
- case 200, 0:
- return "200"
- case 201:
- return "201"
- case 202:
- return "202"
- case 203:
- return "203"
- case 204:
- return "204"
- case 205:
- return "205"
- case 206:
- return "206"
-
- case 300:
- return "300"
- case 301:
- return "301"
- case 302:
- return "302"
- case 304:
- return "304"
- case 305:
- return "305"
- case 307:
- return "307"
-
- case 400:
- return "400"
- case 401:
- return "401"
- case 402:
- return "402"
- case 403:
- return "403"
- case 404:
- return "404"
- case 405:
- return "405"
- case 406:
- return "406"
- case 407:
- return "407"
- case 408:
- return "408"
- case 409:
- return "409"
- case 410:
- return "410"
- case 411:
- return "411"
- case 412:
- return "412"
- case 413:
- return "413"
- case 414:
- return "414"
- case 415:
- return "415"
- case 416:
- return "416"
- case 417:
- return "417"
- case 418:
- return "418"
-
- case 500:
- return "500"
- case 501:
- return "501"
- case 502:
- return "502"
- case 503:
- return "503"
- case 504:
- return "504"
- case 505:
- return "505"
-
- case 428:
- return "428"
- case 429:
- return "429"
- case 431:
- return "431"
- case 511:
- return "511"
-
- default:
- return strconv.Itoa(s)
- }
-}
-
-type delegator interface {
- Status() int
- Written() int64
-
- http.ResponseWriter
-}
-
-type responseWriterDelegator struct {
- http.ResponseWriter
-
- handler, method string
- status int
- written int64
- wroteHeader bool
-}
-
-func (r *responseWriterDelegator) Status() int {
- return r.status
-}
-
-func (r *responseWriterDelegator) Written() int64 {
- return r.written
-}
-
-func (r *responseWriterDelegator) WriteHeader(code int) {
- r.status = code
- r.wroteHeader = true
- r.ResponseWriter.WriteHeader(code)
-}
-
-func (r *responseWriterDelegator) Write(b []byte) (int, error) {
- if !r.wroteHeader {
- r.WriteHeader(http.StatusOK)
- }
- n, err := r.ResponseWriter.Write(b)
- r.written += int64(n)
- return n, err
-}
-
-type fancyDelegator struct {
- *responseWriterDelegator
-}
-
-func (r *fancyDelegator) CloseNotify() <-chan bool {
- return r.ResponseWriter.(http.CloseNotifier).CloseNotify()
-}
-
-func (r *fancyDelegator) Hijack() (net.Conn, *bufio.ReadWriter, error) {
- return r.ResponseWriter.(http.Hijacker).Hijack()
-}
-
-func (r *fancyDelegator) Flush() {
- r.ResponseWriter.(http.Flusher).Flush()
-}
-
-func (r *fancyDelegator) ReadFrom(re io.Reader) (int64, error) {
- if !r.wroteHeader {
- r.WriteHeader(http.StatusOK)
- }
- n, err := r.ResponseWriter.(io.ReaderFrom).ReadFrom(re)
- r.written += n
- return n, err
-}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server_test.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server_test.go
deleted file mode 100644
index ca9f4bf3c..000000000
--- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server_test.go
+++ /dev/null
@@ -1,164 +0,0 @@
-// Copyright 2017 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package promhttp
-
-import (
- "log"
- "net/http"
- "net/http/httptest"
- "testing"
-
- "github.com/prometheus/client_golang/prometheus"
-)
-
-func TestMiddlewareAPI(t *testing.T) {
- reg := prometheus.NewRegistry()
-
- inFlightGauge := prometheus.NewGauge(prometheus.GaugeOpts{
- Name: "in_flight_requests",
- Help: "A gauge of requests currently being served by the wrapped handler.",
- })
-
- counter := prometheus.NewCounterVec(
- prometheus.CounterOpts{
- Name: "api_requests_total",
- Help: "A counter for requests to the wrapped handler.",
- },
- []string{"code", "method"},
- )
-
- histVec := prometheus.NewHistogramVec(
- prometheus.HistogramOpts{
- Name: "response_duration_seconds",
- Help: "A histogram of request latencies.",
- Buckets: prometheus.DefBuckets,
- ConstLabels: prometheus.Labels{"handler": "api"},
- },
- []string{"method"},
- )
-
- responseSize := prometheus.NewHistogramVec(
- prometheus.HistogramOpts{
- Name: "push_request_size_bytes",
- Help: "A histogram of request sizes for requests.",
- Buckets: []float64{200, 500, 900, 1500},
- },
- []string{},
- )
-
- handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("OK"))
- })
-
- reg.MustRegister(inFlightGauge, counter, histVec, responseSize)
-
- chain := InstrumentHandlerInFlight(inFlightGauge,
- InstrumentHandlerCounter(counter,
- InstrumentHandlerDuration(histVec,
- InstrumentHandlerResponseSize(responseSize, handler),
- ),
- ),
- )
-
- r, _ := http.NewRequest("GET", "www.example.com", nil)
- w := httptest.NewRecorder()
- chain.ServeHTTP(w, r)
-}
-
-func ExampleInstrumentHandlerDuration() {
- inFlightGauge := prometheus.NewGauge(prometheus.GaugeOpts{
- Name: "in_flight_requests",
- Help: "A gauge of requests currently being served by the wrapped handler.",
- })
-
- counter := prometheus.NewCounterVec(
- prometheus.CounterOpts{
- Name: "api_requests_total",
- Help: "A counter for requests to the wrapped handler.",
- },
- []string{"code", "method"},
- )
-
- // pushVec and pullVec are partitioned by the HTTP method and use custom
- // buckets based on the expected request duration. ConstLabels are used
- // to set a handler label to mark pushVec as tracking the durations for
- // pushes and pullVec as tracking the durations for pulls. Note that
- // Name, Help, and Buckets need to be the same for consistency, so we
- // use the same HistogramOpts after just modifying the ConstLabels.
- histogramOpts := prometheus.HistogramOpts{
- Name: "request_duration_seconds",
- Help: "A histogram of latencies for requests.",
- Buckets: []float64{.25, .5, 1, 2.5, 5, 10},
- ConstLabels: prometheus.Labels{"handler": "push"},
- }
- pushVec := prometheus.NewHistogramVec(
- histogramOpts,
- []string{"method"},
- )
- histogramOpts.ConstLabels = prometheus.Labels{"handler": "pull"}
- pullVec := prometheus.NewHistogramVec(
- histogramOpts,
- []string{"method"},
- )
-
- // responseSize has no labels, making it a zero-dimensional
- // ObserverVec.
- responseSize := prometheus.NewHistogramVec(
- prometheus.HistogramOpts{
- Name: "response_size_bytes",
- Help: "A histogram of response sizes for requests.",
- Buckets: []float64{200, 500, 900, 1500},
- },
- []string{},
- )
-
- // Create the handlers that will be wrapped by the middleware.
- pushHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("Push"))
- })
- pullHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("Pull"))
- })
-
- // Register all of the metrics in the standard registry.
- prometheus.MustRegister(inFlightGauge, counter, pullVec, pushVec, responseSize)
-
- // Wrap the pushHandler with our shared middleware, but use the
- // endpoint-specific pushVec with InstrumentHandlerDuration.
- pushChain := InstrumentHandlerInFlight(inFlightGauge,
- InstrumentHandlerCounter(counter,
- InstrumentHandlerDuration(pushVec,
- InstrumentHandlerResponseSize(responseSize, pushHandler),
- ),
- ),
- )
-
- // Wrap the pushHandler with the shared middleware, but use the
- // endpoint-specific pullVec with InstrumentHandlerDuration.
- pullChain := InstrumentHandlerInFlight(inFlightGauge,
- InstrumentHandlerCounter(counter,
- InstrumentHandlerDuration(pullVec,
- InstrumentHandlerResponseSize(responseSize, pullHandler),
- ),
- ),
- )
-
- http.Handle("/metrics", Handler())
- http.Handle("/push", pushChain)
- http.Handle("/pull", pullChain)
-
- if err := http.ListenAndServe(":3000", nil); err != nil {
- log.Fatal(err)
- }
-}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/push/example_add_from_gatherer_test.go b/vendor/github.com/prometheus/client_golang/prometheus/push/example_add_from_gatherer_test.go
deleted file mode 100644
index dd5c10a59..000000000
--- a/vendor/github.com/prometheus/client_golang/prometheus/push/example_add_from_gatherer_test.go
+++ /dev/null
@@ -1,83 +0,0 @@
-// Copyright 2016 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// Copyright (c) 2013, The Prometheus 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 push_test
-
-import (
- "fmt"
- "time"
-
- "github.com/prometheus/client_golang/prometheus"
- "github.com/prometheus/client_golang/prometheus/push"
-)
-
-var (
- completionTime = prometheus.NewGauge(prometheus.GaugeOpts{
- Name: "db_backup_last_completion_timestamp_seconds",
- Help: "The timestamp of the last completion of a DB backup, successful or not.",
- })
- successTime = prometheus.NewGauge(prometheus.GaugeOpts{
- Name: "db_backup_last_success_timestamp_seconds",
- Help: "The timestamp of the last successful completion of a DB backup.",
- })
- duration = prometheus.NewGauge(prometheus.GaugeOpts{
- Name: "db_backup_duration_seconds",
- Help: "The duration of the last DB backup in seconds.",
- })
- records = prometheus.NewGauge(prometheus.GaugeOpts{
- Name: "db_backup_records_processed",
- Help: "The number of records processed in the last DB backup.",
- })
-)
-
-func performBackup() (int, error) {
- // Perform the backup and return the number of backed up records and any
- // applicable error.
- // ...
- return 42, nil
-}
-
-func ExampleAddFromGatherer() {
- registry := prometheus.NewRegistry()
- registry.MustRegister(completionTime, duration, records)
- // Note that successTime is not registered at this time.
-
- start := time.Now()
- n, err := performBackup()
- records.Set(float64(n))
- duration.Set(time.Since(start).Seconds())
- completionTime.SetToCurrentTime()
- if err != nil {
- fmt.Println("DB backup failed:", err)
- } else {
- // Only now register successTime.
- registry.MustRegister(successTime)
- successTime.SetToCurrentTime()
- }
- // AddFromGatherer is used here rather than FromGatherer to not delete a
- // previously pushed success timestamp in case of a failure of this
- // backup.
- if err := push.AddFromGatherer(
- "db_backup", nil,
- "http://pushgateway:9091",
- registry,
- ); err != nil {
- fmt.Println("Could not push to Pushgateway:", err)
- }
-}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/push/examples_test.go b/vendor/github.com/prometheus/client_golang/prometheus/push/examples_test.go
index 7e0ac66a5..7f17ca291 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/push/examples_test.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/push/examples_test.go
@@ -15,6 +15,7 @@ package push_test
import (
"fmt"
+ "time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/push"
@@ -23,9 +24,9 @@ import (
func ExampleCollectors() {
completionTime := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "db_backup_last_completion_timestamp_seconds",
- Help: "The timestamp of the last successful completion of a DB backup.",
+ Help: "The timestamp of the last succesful completion of a DB backup.",
})
- completionTime.SetToCurrentTime()
+ completionTime.Set(float64(time.Now().Unix()))
if err := push.Collectors(
"db_backup", push.HostnameGroupingKey(),
"http://pushgateway:9091",
@@ -34,3 +35,22 @@ func ExampleCollectors() {
fmt.Println("Could not push completion time to Pushgateway:", err)
}
}
+
+func ExampleRegistry() {
+ registry := prometheus.NewRegistry()
+
+ completionTime := prometheus.NewGauge(prometheus.GaugeOpts{
+ Name: "db_backup_last_completion_timestamp_seconds",
+ Help: "The timestamp of the last succesful completion of a DB backup.",
+ })
+ registry.MustRegister(completionTime)
+
+ completionTime.Set(float64(time.Now().Unix()))
+ if err := push.FromGatherer(
+ "db_backup", push.HostnameGroupingKey(),
+ "http://pushgateway:9091",
+ registry,
+ ); err != nil {
+ fmt.Println("Could not push completion time to Pushgateway:", err)
+ }
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/push/push.go b/vendor/github.com/prometheus/client_golang/prometheus/push/push.go
index 8fb6f5f17..ae40402f8 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/push/push.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/push/push.go
@@ -84,7 +84,7 @@ func push(job string, grouping map[string]string, pushURL string, g prometheus.G
}
urlComponents := []string{url.QueryEscape(job)}
for ln, lv := range grouping {
- if !model.LabelName(ln).IsValid() {
+ if !model.LabelNameRE.MatchString(ln) {
return fmt.Errorf("grouping label has invalid name: %s", ln)
}
if strings.Contains(lv, "/") {
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/registry.go b/vendor/github.com/prometheus/client_golang/prometheus/registry.go
index 8c6b5bd8e..32a3986b0 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/registry.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/registry.go
@@ -152,6 +152,38 @@ func MustRegister(cs ...Collector) {
DefaultRegisterer.MustRegister(cs...)
}
+// RegisterOrGet registers the provided Collector with the DefaultRegisterer and
+// returns the Collector, unless an equal Collector was registered before, in
+// which case that Collector is returned.
+//
+// Deprecated: RegisterOrGet is merely a convenience function for the
+// implementation as described in the documentation for
+// AlreadyRegisteredError. As the use case is relatively rare, this function
+// will be removed in a future version of this package to clean up the
+// namespace.
+func RegisterOrGet(c Collector) (Collector, error) {
+ if err := Register(c); err != nil {
+ if are, ok := err.(AlreadyRegisteredError); ok {
+ return are.ExistingCollector, nil
+ }
+ return nil, err
+ }
+ return c, nil
+}
+
+// MustRegisterOrGet behaves like RegisterOrGet but panics instead of returning
+// an error.
+//
+// Deprecated: This is deprecated for the same reason RegisterOrGet is. See
+// there for details.
+func MustRegisterOrGet(c Collector) Collector {
+ c, err := RegisterOrGet(c)
+ if err != nil {
+ panic(err)
+ }
+ return c
+}
+
// Unregister removes the registration of the provided Collector from the
// DefaultRegisterer.
//
@@ -169,6 +201,25 @@ func (gf GathererFunc) Gather() ([]*dto.MetricFamily, error) {
return gf()
}
+// SetMetricFamilyInjectionHook replaces the DefaultGatherer with one that
+// gathers from the previous DefaultGatherers but then merges the MetricFamily
+// protobufs returned from the provided hook function with the MetricFamily
+// protobufs returned from the original DefaultGatherer.
+//
+// Deprecated: This function manipulates the DefaultGatherer variable. Consider
+// the implications, i.e. don't do this concurrently with any uses of the
+// DefaultGatherer. In the rare cases where you need to inject MetricFamily
+// protobufs directly, it is recommended to use a custom Registry and combine it
+// with a custom Gatherer using the Gatherers type (see
+// there). SetMetricFamilyInjectionHook only exists for compatibility reasons
+// with previous versions of this package.
+func SetMetricFamilyInjectionHook(hook func() []*dto.MetricFamily) {
+ DefaultGatherer = Gatherers{
+ DefaultGatherer,
+ GathererFunc(func() ([]*dto.MetricFamily, error) { return hook(), nil }),
+ }
+}
+
// AlreadyRegisteredError is returned by the Register method if the Collector to
// be registered has already been registered before, or a different Collector
// that collects the same metrics has been registered before. Registration fails
@@ -243,7 +294,7 @@ func (r *Registry) Register(c Collector) error {
}()
r.mtx.Lock()
defer r.mtx.Unlock()
- // Conduct various tests...
+ // Coduct various tests...
for desc := range descChan {
// Is the descriptor valid at all?
@@ -396,7 +447,7 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) {
// Drain metricChan in case of premature return.
defer func() {
- for range metricChan {
+ for _ = range metricChan {
}
}()
@@ -632,7 +683,7 @@ func (s metricSorter) Less(i, j int) bool {
return s[i].GetTimestampMs() < s[j].GetTimestampMs()
}
-// normalizeMetricFamilies returns a MetricFamily slice with empty
+// normalizeMetricFamilies returns a MetricFamily slice whith empty
// MetricFamilies pruned and the remaining MetricFamilies sorted by name within
// the slice, with the contained Metrics sorted within each MetricFamily.
func normalizeMetricFamilies(metricFamiliesByName map[string]*dto.MetricFamily) []*dto.MetricFamily {
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/registry_test.go b/vendor/github.com/prometheus/client_golang/prometheus/registry_test.go
index d016a1560..9dacb6256 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/registry_test.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/registry_test.go
@@ -526,21 +526,20 @@ func TestRegisterWithOrGet(t *testing.T) {
},
[]string{"foo", "bar"},
)
- var err error
- if err = prometheus.Register(original); err != nil {
+ if err := prometheus.Register(original); err != nil {
t.Fatal(err)
}
- if err = prometheus.Register(equalButNotSame); err == nil {
+ if err := prometheus.Register(equalButNotSame); err == nil {
t.Fatal("expected error when registringe equal collector")
}
- if are, ok := err.(prometheus.AlreadyRegisteredError); ok {
- if are.ExistingCollector != original {
- t.Error("expected original collector but got something else")
- }
- if are.ExistingCollector == equalButNotSame {
- t.Error("expected original callector but got new one")
- }
- } else {
- t.Error("unexpected error:", err)
+ existing, err := prometheus.RegisterOrGet(equalButNotSame)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if existing != original {
+ t.Error("expected original collector but got something else")
+ }
+ if existing == equalButNotSame {
+ t.Error("expected original callector but got new one")
}
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/summary.go b/vendor/github.com/prometheus/client_golang/prometheus/summary.go
index 1c65e25ec..bce05bf9a 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/summary.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/summary.go
@@ -54,9 +54,6 @@ type Summary interface {
}
// DefObjectives are the default Summary quantile values.
-//
-// Deprecated: DefObjectives will not be used as the default objectives in
-// v0.10 of the library. The default Summary will have no quantiles then.
var (
DefObjectives = map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}
@@ -116,15 +113,9 @@ type SummaryOpts struct {
ConstLabels Labels
// Objectives defines the quantile rank estimates with their respective
- // absolute error. If Objectives[q] = e, then the value reported for q
- // will be the φ-quantile value for some φ between q-e and q+e. The
- // default value is DefObjectives. It is used if Objectives is left at
- // its zero value (i.e. nil). To create a Summary without Objectives,
- // set it to an empty map (i.e. map[float64]float64{}).
- //
- // Deprecated: Note that the current value of DefObjectives is
- // deprecated. It will be replaced by an empty map in v0.10 of the
- // library. Please explicitly set Objectives to the desired value.
+ // absolute error. If Objectives[q] = e, then the value reported
+ // for q will be the φ-quantile value for some φ between q-e and q+e.
+ // The default value is DefObjectives.
Objectives map[float64]float64
// MaxAge defines the duration for which an observation stays relevant
@@ -192,7 +183,7 @@ func newSummary(desc *Desc, opts SummaryOpts, labelValues ...string) Summary {
}
}
- if opts.Objectives == nil {
+ if len(opts.Objectives) == 0 {
opts.Objectives = DefObjectives
}
@@ -419,24 +410,24 @@ func NewSummaryVec(opts SummaryOpts, labelNames []string) *SummaryVec {
}
}
-// GetMetricWithLabelValues replaces the method of the same name in MetricVec.
-// The difference is that this method returns an Observer and not a Metric so
-// that no type conversion to an Observer is required.
-func (m *SummaryVec) GetMetricWithLabelValues(lvs ...string) (Observer, error) {
+// GetMetricWithLabelValues replaces the method of the same name in
+// MetricVec. The difference is that this method returns a Summary and not a
+// Metric so that no type conversion is required.
+func (m *SummaryVec) GetMetricWithLabelValues(lvs ...string) (Summary, error) {
metric, err := m.MetricVec.GetMetricWithLabelValues(lvs...)
if metric != nil {
- return metric.(Observer), err
+ return metric.(Summary), err
}
return nil, err
}
// GetMetricWith replaces the method of the same name in MetricVec. The
-// difference is that this method returns an Observer and not a Metric so that
-// no type conversion to an Observer is required.
-func (m *SummaryVec) GetMetricWith(labels Labels) (Observer, error) {
+// difference is that this method returns a Summary and not a Metric so that no
+// type conversion is required.
+func (m *SummaryVec) GetMetricWith(labels Labels) (Summary, error) {
metric, err := m.MetricVec.GetMetricWith(labels)
if metric != nil {
- return metric.(Observer), err
+ return metric.(Summary), err
}
return nil, err
}
@@ -445,15 +436,15 @@ func (m *SummaryVec) GetMetricWith(labels Labels) (Observer, error) {
// GetMetricWithLabelValues would have returned an error. By not returning an
// error, WithLabelValues allows shortcuts like
// myVec.WithLabelValues("404", "GET").Observe(42.21)
-func (m *SummaryVec) WithLabelValues(lvs ...string) Observer {
- return m.MetricVec.WithLabelValues(lvs...).(Observer)
+func (m *SummaryVec) WithLabelValues(lvs ...string) Summary {
+ return m.MetricVec.WithLabelValues(lvs...).(Summary)
}
// With works as GetMetricWith, but panics where GetMetricWithLabels would have
// returned an error. By not returning an error, With allows shortcuts like
// myVec.With(Labels{"code": "404", "method": "GET"}).Observe(42.21)
-func (m *SummaryVec) With(labels Labels) Observer {
- return m.MetricVec.With(labels).(Observer)
+func (m *SummaryVec) With(labels Labels) Summary {
+ return m.MetricVec.With(labels).(Summary)
}
type constSummary struct {
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/summary_test.go b/vendor/github.com/prometheus/client_golang/prometheus/summary_test.go
index b162ed946..c4575ffbd 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/summary_test.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/summary_test.go
@@ -25,45 +25,6 @@ import (
dto "github.com/prometheus/client_model/go"
)
-func TestSummaryWithDefaultObjectives(t *testing.T) {
- reg := NewRegistry()
- summaryWithDefaultObjectives := NewSummary(SummaryOpts{
- Name: "default_objectives",
- Help: "Test help.",
- })
- if err := reg.Register(summaryWithDefaultObjectives); err != nil {
- t.Error(err)
- }
-
- m := &dto.Metric{}
- if err := summaryWithDefaultObjectives.Write(m); err != nil {
- t.Error(err)
- }
- if len(m.GetSummary().Quantile) != len(DefObjectives) {
- t.Error("expected default objectives in summary")
- }
-}
-
-func TestSummaryWithoutObjectives(t *testing.T) {
- reg := NewRegistry()
- summaryWithEmptyObjectives := NewSummary(SummaryOpts{
- Name: "empty_objectives",
- Help: "Test help.",
- Objectives: map[float64]float64{},
- })
- if err := reg.Register(summaryWithEmptyObjectives); err != nil {
- t.Error(err)
- }
-
- m := &dto.Metric{}
- if err := summaryWithEmptyObjectives.Write(m); err != nil {
- t.Error(err)
- }
- if len(m.GetSummary().Quantile) != 0 {
- t.Error("expected no objectives in summary")
- }
-}
-
func benchmarkSummaryObserve(w int, b *testing.B) {
b.StopTimer()
@@ -175,9 +136,8 @@ func TestSummaryConcurrency(t *testing.T) {
end.Add(concLevel)
sum := NewSummary(SummaryOpts{
- Name: "test_summary",
- Help: "helpless",
- Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
+ Name: "test_summary",
+ Help: "helpless",
})
allVars := make([]float64, total)
@@ -263,9 +223,8 @@ func TestSummaryVecConcurrency(t *testing.T) {
sum := NewSummaryVec(
SummaryOpts{
- Name: "test_summary",
- Help: "helpless",
- Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
+ Name: "test_summary",
+ Help: "helpless",
},
[]string{"label"},
)
@@ -301,7 +260,7 @@ func TestSummaryVecConcurrency(t *testing.T) {
for i := 0; i < vecLength; i++ {
m := &dto.Metric{}
s := sum.WithLabelValues(string('A' + i))
- s.(Summary).Write(m)
+ s.Write(m)
if got, want := int(*m.Summary.SampleCount), len(allVars[i]); got != want {
t.Errorf("got sample count %d for label %c, want %d", got, 'A'+i, want)
}
@@ -346,7 +305,7 @@ func TestSummaryDecay(t *testing.T) {
m := &dto.Metric{}
i := 0
tick := time.NewTicker(time.Millisecond)
- for range tick.C {
+ for _ = range tick.C {
i++
sum.Observe(float64(i))
if i%10 == 0 {
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/timer.go b/vendor/github.com/prometheus/client_golang/prometheus/timer.go
deleted file mode 100644
index 12b65699b..000000000
--- a/vendor/github.com/prometheus/client_golang/prometheus/timer.go
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright 2016 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package prometheus
-
-import "time"
-
-// Timer is a helper type to time functions. Use NewTimer to create new
-// instances.
-type Timer struct {
- begin time.Time
- observer Observer
-}
-
-// NewTimer creates a new Timer. The provided Observer is used to observe a
-// duration in seconds. Timer is usually used to time a function call in the
-// following way:
-// func TimeMe() {
-// timer := NewTimer(myHistogram)
-// defer timer.ObserveDuration()
-// // Do actual work.
-// }
-func NewTimer(o Observer) *Timer {
- return &Timer{
- begin: time.Now(),
- observer: o,
- }
-}
-
-// ObserveDuration records the duration passed since the Timer was created with
-// NewTimer. It calls the Observe method of the Observer provided during
-// construction with the duration in seconds as an argument. ObserveDuration is
-// usually called with a defer statement.
-func (t *Timer) ObserveDuration() {
- if t.observer != nil {
- t.observer.Observe(time.Since(t.begin).Seconds())
- }
-}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/timer_test.go b/vendor/github.com/prometheus/client_golang/prometheus/timer_test.go
deleted file mode 100644
index 294902068..000000000
--- a/vendor/github.com/prometheus/client_golang/prometheus/timer_test.go
+++ /dev/null
@@ -1,152 +0,0 @@
-// Copyright 2016 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package prometheus
-
-import (
- "testing"
-
- dto "github.com/prometheus/client_model/go"
-)
-
-func TestTimerObserve(t *testing.T) {
- var (
- his = NewHistogram(HistogramOpts{Name: "test_histogram"})
- sum = NewSummary(SummaryOpts{Name: "test_summary"})
- gauge = NewGauge(GaugeOpts{Name: "test_gauge"})
- )
-
- func() {
- hisTimer := NewTimer(his)
- sumTimer := NewTimer(sum)
- gaugeTimer := NewTimer(ObserverFunc(gauge.Set))
- defer hisTimer.ObserveDuration()
- defer sumTimer.ObserveDuration()
- defer gaugeTimer.ObserveDuration()
- }()
-
- m := &dto.Metric{}
- his.Write(m)
- if want, got := uint64(1), m.GetHistogram().GetSampleCount(); want != got {
- t.Errorf("want %d observations for histogram, got %d", want, got)
- }
- m.Reset()
- sum.Write(m)
- if want, got := uint64(1), m.GetSummary().GetSampleCount(); want != got {
- t.Errorf("want %d observations for summary, got %d", want, got)
- }
- m.Reset()
- gauge.Write(m)
- if got := m.GetGauge().GetValue(); got <= 0 {
- t.Errorf("want value > 0 for gauge, got %f", got)
- }
-}
-
-func TestTimerEmpty(t *testing.T) {
- emptyTimer := NewTimer(nil)
- emptyTimer.ObserveDuration()
- // Do nothing, just demonstrate it works without panic.
-}
-
-func TestTimerConditionalTiming(t *testing.T) {
- var (
- his = NewHistogram(HistogramOpts{
- Name: "test_histogram",
- })
- timeMe = true
- m = &dto.Metric{}
- )
-
- timedFunc := func() {
- timer := NewTimer(ObserverFunc(func(v float64) {
- if timeMe {
- his.Observe(v)
- }
- }))
- defer timer.ObserveDuration()
- }
-
- timedFunc() // This will time.
- his.Write(m)
- if want, got := uint64(1), m.GetHistogram().GetSampleCount(); want != got {
- t.Errorf("want %d observations for histogram, got %d", want, got)
- }
-
- timeMe = false
- timedFunc() // This will not time again.
- m.Reset()
- his.Write(m)
- if want, got := uint64(1), m.GetHistogram().GetSampleCount(); want != got {
- t.Errorf("want %d observations for histogram, got %d", want, got)
- }
-}
-
-func TestTimerByOutcome(t *testing.T) {
- var (
- his = NewHistogramVec(
- HistogramOpts{Name: "test_histogram"},
- []string{"outcome"},
- )
- outcome = "foo"
- m = &dto.Metric{}
- )
-
- timedFunc := func() {
- timer := NewTimer(ObserverFunc(func(v float64) {
- his.WithLabelValues(outcome).Observe(v)
- }))
- defer timer.ObserveDuration()
-
- if outcome == "foo" {
- outcome = "bar"
- return
- }
- outcome = "foo"
- }
-
- timedFunc()
- his.WithLabelValues("foo").(Histogram).Write(m)
- if want, got := uint64(0), m.GetHistogram().GetSampleCount(); want != got {
- t.Errorf("want %d observations for 'foo' histogram, got %d", want, got)
- }
- m.Reset()
- his.WithLabelValues("bar").(Histogram).Write(m)
- if want, got := uint64(1), m.GetHistogram().GetSampleCount(); want != got {
- t.Errorf("want %d observations for 'bar' histogram, got %d", want, got)
- }
-
- timedFunc()
- m.Reset()
- his.WithLabelValues("foo").(Histogram).Write(m)
- if want, got := uint64(1), m.GetHistogram().GetSampleCount(); want != got {
- t.Errorf("want %d observations for 'foo' histogram, got %d", want, got)
- }
- m.Reset()
- his.WithLabelValues("bar").(Histogram).Write(m)
- if want, got := uint64(1), m.GetHistogram().GetSampleCount(); want != got {
- t.Errorf("want %d observations for 'bar' histogram, got %d", want, got)
- }
-
- timedFunc()
- m.Reset()
- his.WithLabelValues("foo").(Histogram).Write(m)
- if want, got := uint64(1), m.GetHistogram().GetSampleCount(); want != got {
- t.Errorf("want %d observations for 'foo' histogram, got %d", want, got)
- }
- m.Reset()
- his.WithLabelValues("bar").(Histogram).Write(m)
- if want, got := uint64(2), m.GetHistogram().GetSampleCount(); want != got {
- t.Errorf("want %d observations for 'bar' histogram, got %d", want, got)
- }
-
-}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/untyped.go b/vendor/github.com/prometheus/client_golang/prometheus/untyped.go
index 065501d38..5faf7e6e3 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/untyped.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/untyped.go
@@ -20,11 +20,6 @@ package prometheus
// no type information is implied.
//
// To create Untyped instances, use NewUntyped.
-//
-// Deprecated: The Untyped type is deprecated because it doesn't make sense in
-// direct instrumentation. If you need to mirror an external metric of unknown
-// type (usually while writing exporters), Use MustNewConstMetric to create an
-// untyped metric instance on the fly.
type Untyped interface {
Metric
Collector
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/value.go b/vendor/github.com/prometheus/client_golang/prometheus/value.go
index ff75ce585..a944c3775 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/value.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/value.go
@@ -19,7 +19,6 @@ import (
"math"
"sort"
"sync/atomic"
- "time"
dto "github.com/prometheus/client_model/go"
@@ -44,7 +43,7 @@ var errInconsistentCardinality = errors.New("inconsistent label cardinality")
// ValueType. This is a low-level building block used by the library to back the
// implementations of Counter, Gauge, and Untyped.
type value struct {
- // valBits contains the bits of the represented float64 value. It has
+ // valBits containst the bits of the represented float64 value. It has
// to go first in the struct to guarantee alignment for atomic
// operations. http://golang.org/pkg/sync/atomic/#pkg-note-BUG
valBits uint64
@@ -81,10 +80,6 @@ func (v *value) Set(val float64) {
atomic.StoreUint64(&v.valBits, math.Float64bits(val))
}
-func (v *value) SetToCurrentTime() {
- v.Set(float64(time.Now().UnixNano()) / 1e9)
-}
-
func (v *value) Inc() {
v.Add(1)
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/vec_test.go b/vendor/github.com/prometheus/client_golang/prometheus/vec_test.go
index e3c5aeba0..445a6b39f 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/vec_test.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/vec_test.go
@@ -241,8 +241,8 @@ func TestCounterVecEndToEndWithCollision(t *testing.T) {
func BenchmarkMetricVecWithLabelValuesBasic(b *testing.B) {
benchmarkMetricVecWithLabelValues(b, map[string][]string{
- "l1": {"onevalue"},
- "l2": {"twovalue"},
+ "l1": []string{"onevalue"},
+ "l2": []string{"twovalue"},
})
}
diff --git a/vendor/github.com/prometheus/common/README.md b/vendor/github.com/prometheus/common/README.md
index 98f6ce24b..11a584945 100644
--- a/vendor/github.com/prometheus/common/README.md
+++ b/vendor/github.com/prometheus/common/README.md
@@ -6,7 +6,7 @@ components and libraries.
* **config**: Common configuration structures
* **expfmt**: Decoding and encoding for the exposition format
-* **log**: A logging wrapper around [logrus](https://github.com/Sirupsen/logrus)
+* **log**: A logging wrapper around [logrus](https://github.com/sirupsen/logrus)
* **model**: Shared data structures
* **route**: A routing wrapper around [httprouter](https://github.com/julienschmidt/httprouter) using `context.Context`
* **version**: Version informations and metric
diff --git a/vendor/github.com/prometheus/common/log/eventlog_formatter.go b/vendor/github.com/prometheus/common/log/eventlog_formatter.go
index 6d41284ce..bcf68e6f2 100644
--- a/vendor/github.com/prometheus/common/log/eventlog_formatter.go
+++ b/vendor/github.com/prometheus/common/log/eventlog_formatter.go
@@ -21,22 +21,22 @@ import (
"golang.org/x/sys/windows/svc/eventlog"
- "github.com/Sirupsen/logrus"
+ "github.com/sirupsen/logrus"
)
func init() {
- setEventlogFormatter = func(name string, debugAsInfo bool) error {
+ setEventlogFormatter = func(l logger, name string, debugAsInfo bool) error {
if name == "" {
return fmt.Errorf("missing name parameter")
}
- fmter, err := newEventlogger(name, debugAsInfo, origLogger.Formatter)
+ fmter, err := newEventlogger(name, debugAsInfo, l.entry.Logger.Formatter)
if err != nil {
fmt.Fprintf(os.Stderr, "error creating eventlog formatter: %v\n", err)
- origLogger.Errorf("can't connect logger to eventlog: %v", err)
+ l.Errorf("can't connect logger to eventlog: %v", err)
return err
}
- origLogger.Formatter = fmter
+ l.entry.Logger.Formatter = fmter
return nil
}
}
diff --git a/vendor/github.com/prometheus/common/log/log.go b/vendor/github.com/prometheus/common/log/log.go
index 0a74a7f92..1321741ad 100644
--- a/vendor/github.com/prometheus/common/log/log.go
+++ b/vendor/github.com/prometheus/common/log/log.go
@@ -25,7 +25,7 @@ import (
"strconv"
"strings"
- "github.com/Sirupsen/logrus"
+ "github.com/sirupsen/logrus"
)
type levelFlag string
@@ -46,10 +46,10 @@ func (f levelFlag) Set(level string) error {
}
// setSyslogFormatter is nil if the target architecture does not support syslog.
-var setSyslogFormatter func(string, string) error
+var setSyslogFormatter func(logger, string, string) error
// setEventlogFormatter is nil if the target OS does not support Eventlog (i.e., is not Windows).
-var setEventlogFormatter func(string, bool) error
+var setEventlogFormatter func(logger, string, bool) error
func setJSONFormatter() {
origLogger.Formatter = &logrus.JSONFormatter{}
@@ -65,45 +65,7 @@ func (f logFormatFlag) String() string {
// Set implements flag.Value.
func (f logFormatFlag) Set(format string) error {
- u, err := url.Parse(format)
- if err != nil {
- return err
- }
- if u.Scheme != "logger" {
- return fmt.Errorf("invalid scheme %s", u.Scheme)
- }
- jsonq := u.Query().Get("json")
- if jsonq == "true" {
- setJSONFormatter()
- }
-
- switch u.Opaque {
- case "syslog":
- if setSyslogFormatter == nil {
- return fmt.Errorf("system does not support syslog")
- }
- appname := u.Query().Get("appname")
- facility := u.Query().Get("local")
- return setSyslogFormatter(appname, facility)
- case "eventlog":
- if setEventlogFormatter == nil {
- return fmt.Errorf("system does not support eventlog")
- }
- name := u.Query().Get("name")
- debugAsInfo := false
- debugAsInfoRaw := u.Query().Get("debugAsInfo")
- if parsedDebugAsInfo, err := strconv.ParseBool(debugAsInfoRaw); err == nil {
- debugAsInfo = parsedDebugAsInfo
- }
- return setEventlogFormatter(name, debugAsInfo)
- case "stdout":
- origLogger.Out = os.Stdout
- case "stderr":
- origLogger.Out = os.Stderr
- default:
- return fmt.Errorf("unsupported logger %q", u.Opaque)
- }
- return nil
+ return baseLogger.SetFormat(format)
}
func init() {
@@ -150,6 +112,9 @@ type Logger interface {
Fatalf(string, ...interface{})
With(key string, value interface{}) Logger
+
+ SetFormat(string) error
+ SetLevel(string) error
}
type logger struct {
@@ -235,6 +200,58 @@ func (l logger) Fatalf(format string, args ...interface{}) {
l.sourced().Fatalf(format, args...)
}
+func (l logger) SetLevel(level string) error {
+ lvl, err := logrus.ParseLevel(level)
+ if err != nil {
+ return err
+ }
+
+ l.entry.Logger.Level = lvl
+ return nil
+}
+
+func (l logger) SetFormat(format string) error {
+ u, err := url.Parse(format)
+ if err != nil {
+ return err
+ }
+ if u.Scheme != "logger" {
+ return fmt.Errorf("invalid scheme %s", u.Scheme)
+ }
+ jsonq := u.Query().Get("json")
+ if jsonq == "true" {
+ setJSONFormatter()
+ }
+
+ switch u.Opaque {
+ case "syslog":
+ if setSyslogFormatter == nil {
+ return fmt.Errorf("system does not support syslog")
+ }
+ appname := u.Query().Get("appname")
+ facility := u.Query().Get("local")
+ return setSyslogFormatter(l, appname, facility)
+ case "eventlog":
+ if setEventlogFormatter == nil {
+ return fmt.Errorf("system does not support eventlog")
+ }
+ name := u.Query().Get("name")
+ debugAsInfo := false
+ debugAsInfoRaw := u.Query().Get("debugAsInfo")
+ if parsedDebugAsInfo, err := strconv.ParseBool(debugAsInfoRaw); err == nil {
+ debugAsInfo = parsedDebugAsInfo
+ }
+ return setEventlogFormatter(l, name, debugAsInfo)
+ case "stdout":
+ l.entry.Logger.Out = os.Stdout
+ case "stderr":
+ l.entry.Logger.Out = os.Stderr
+ default:
+ return fmt.Errorf("unsupported logger %q", u.Opaque)
+ }
+ return nil
+}
+
// sourced adds a source field to the logger that contains
// the file name and line where the logging happened.
func (l logger) sourced() *logrus.Entry {
diff --git a/vendor/github.com/prometheus/common/log/log_test.go b/vendor/github.com/prometheus/common/log/log_test.go
index 953adb79c..2cd2b18e2 100644
--- a/vendor/github.com/prometheus/common/log/log_test.go
+++ b/vendor/github.com/prometheus/common/log/log_test.go
@@ -18,7 +18,7 @@ import (
"regexp"
"testing"
- "github.com/Sirupsen/logrus"
+ "github.com/sirupsen/logrus"
)
func TestFileLineLogging(t *testing.T) {
diff --git a/vendor/github.com/prometheus/common/log/syslog_formatter.go b/vendor/github.com/prometheus/common/log/syslog_formatter.go
index 64f5fdac9..f882f2f84 100644
--- a/vendor/github.com/prometheus/common/log/syslog_formatter.go
+++ b/vendor/github.com/prometheus/common/log/syslog_formatter.go
@@ -20,13 +20,13 @@ import (
"log/syslog"
"os"
- "github.com/Sirupsen/logrus"
+ "github.com/sirupsen/logrus"
)
var _ logrus.Formatter = (*syslogger)(nil)
func init() {
- setSyslogFormatter = func(appname, local string) error {
+ setSyslogFormatter = func(l logger, appname, local string) error {
if appname == "" {
return fmt.Errorf("missing appname parameter")
}
@@ -34,13 +34,13 @@ func init() {
return fmt.Errorf("missing local parameter")
}
- fmter, err := newSyslogger(appname, local, origLogger.Formatter)
+ fmter, err := newSyslogger(appname, local, l.entry.Logger.Formatter)
if err != nil {
fmt.Fprintf(os.Stderr, "error creating syslog formatter: %v\n", err)
- origLogger.Errorf("can't connect logger to syslog: %v", err)
+ l.entry.Errorf("can't connect logger to syslog: %v", err)
return err
}
- origLogger.Formatter = fmter
+ l.entry.Logger.Formatter = fmter
return nil
}
}
diff --git a/vendor/github.com/prometheus/common/model/time.go b/vendor/github.com/prometheus/common/model/time.go
index 548968aeb..7e87f1ac6 100644
--- a/vendor/github.com/prometheus/common/model/time.go
+++ b/vendor/github.com/prometheus/common/model/time.go
@@ -163,9 +163,21 @@ func (t *Time) UnmarshalJSON(b []byte) error {
// This type should not propagate beyond the scope of input/output processing.
type Duration time.Duration
+// Set implements pflag/flag.Value
+func (d *Duration) Set(s string) error {
+ var err error
+ *d, err = ParseDuration(s)
+ return err
+}
+
+// Type implements pflag.Value
+func (d *Duration) Type() string {
+ return "duration"
+}
+
var durationRE = regexp.MustCompile("^([0-9]+)(y|w|d|h|m|s|ms)$")
-// StringToDuration parses a string into a time.Duration, assuming that a year
+// ParseDuration parses a string into a time.Duration, assuming that a year
// always has 365d, a week always has 7d, and a day always has 24h.
func ParseDuration(durationStr string) (Duration, error) {
matches := durationRE.FindStringSubmatch(durationStr)
diff --git a/vendor/github.com/prometheus/procfs/.travis.yml b/vendor/github.com/prometheus/procfs/.travis.yml
index a9e28bf5d..ee09bb733 100644
--- a/vendor/github.com/prometheus/procfs/.travis.yml
+++ b/vendor/github.com/prometheus/procfs/.travis.yml
@@ -1,5 +1,5 @@
sudo: false
language: go
go:
- - 1.6.4
- - 1.7.4
+ - 1.7.6
+ - 1.8.3
diff --git a/vendor/github.com/prometheus/procfs/Makefile b/vendor/github.com/prometheus/procfs/Makefile
index c264a49d1..bfa2124eb 100644
--- a/vendor/github.com/prometheus/procfs/Makefile
+++ b/vendor/github.com/prometheus/procfs/Makefile
@@ -1,6 +1,18 @@
-ci:
+ci: fmt lint test
+
+fmt:
! gofmt -l *.go | read nothing
go vet
- go test -v ./...
+
+lint:
go get github.com/golang/lint/golint
golint *.go
+
+test: sysfs/fixtures/.unpacked
+ go test -v ./...
+
+sysfs/fixtures/.unpacked: sysfs/fixtures.tar.gz
+ cd sysfs && tar xzf fixtures.tar.gz
+ touch $@
+
+.PHONY: fmt lint test ci
diff --git a/vendor/github.com/prometheus/procfs/bcache/bcache.go b/vendor/github.com/prometheus/procfs/bcache/bcache.go
new file mode 100644
index 000000000..1db178cec
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/bcache/bcache.go
@@ -0,0 +1,84 @@
+// Copyright 2017 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package bcache provides access to statistics exposed by the bcache (Linux
+// block cache).
+package bcache
+
+// Stats contains bcache runtime statistics, parsed from /sys/fs/bcache/.
+//
+// The names and meanings of each statistic were taken from bcache.txt and
+// files in drivers/md/bcache in the Linux kernel source. Counters are uint64
+// (in-kernel counters are mostly unsigned long).
+type Stats struct {
+ // The name of the bcache used to source these statistics.
+ Name string
+ Bcache BcacheStats
+ Bdevs []BdevStats
+ Caches []CacheStats
+}
+
+// BcacheStats contains statistics tied to a bcache ID.
+type BcacheStats struct {
+ AverageKeySize uint64
+ BtreeCacheSize uint64
+ CacheAvailablePercent uint64
+ Congested uint64
+ RootUsagePercent uint64
+ TreeDepth uint64
+ Internal InternalStats
+ FiveMin PeriodStats
+ Total PeriodStats
+}
+
+// BdevStats contains statistics for one backing device.
+type BdevStats struct {
+ Name string
+ DirtyData uint64
+ FiveMin PeriodStats
+ Total PeriodStats
+}
+
+// CacheStats contains statistics for one cache device.
+type CacheStats struct {
+ Name string
+ IOErrors uint64
+ MetadataWritten uint64
+ Written uint64
+ Priority PriorityStats
+}
+
+// PriorityStats contains statistics from the priority_stats file.
+type PriorityStats struct {
+ UnusedPercent uint64
+ MetadataPercent uint64
+}
+
+// InternalStats contains internal bcache statistics.
+type InternalStats struct {
+ ActiveJournalEntries uint64
+ BtreeNodes uint64
+ BtreeReadAverageDurationNanoSeconds uint64
+ CacheReadRaces uint64
+}
+
+// PeriodStats contains statistics for a time period (5 min or total).
+type PeriodStats struct {
+ Bypassed uint64
+ CacheBypassHits uint64
+ CacheBypassMisses uint64
+ CacheHits uint64
+ CacheMissCollisions uint64
+ CacheMisses uint64
+ CacheReadaheads uint64
+}
diff --git a/vendor/github.com/prometheus/procfs/bcache/get.go b/vendor/github.com/prometheus/procfs/bcache/get.go
new file mode 100644
index 000000000..4d56f3d98
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/bcache/get.go
@@ -0,0 +1,330 @@
+// Copyright 2017 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package bcache
+
+import (
+ "bufio"
+ "fmt"
+ "io/ioutil"
+ "os"
+ "path"
+ "path/filepath"
+ "strconv"
+ "strings"
+)
+
+// ParsePseudoFloat parses the peculiar format produced by bcache's bch_hprint.
+func parsePseudoFloat(str string) (float64, error) {
+ ss := strings.Split(str, ".")
+
+ intPart, err := strconv.ParseFloat(ss[0], 64)
+ if err != nil {
+ return 0, err
+ }
+
+ if len(ss) == 1 {
+ // Pure integers are fine.
+ return intPart, nil
+ }
+ fracPart, err := strconv.ParseFloat(ss[1], 64)
+ if err != nil {
+ return 0, err
+ }
+ // fracPart is a number between 0 and 1023 divided by 100; it is off
+ // by a small amount. Unexpected bumps in time lines may occur because
+ // for bch_hprint .1 != .10 and .10 > .9 (at least up to Linux
+ // v4.12-rc3).
+
+ // Restore the proper order:
+ fracPart = fracPart / 10.24
+ return intPart + fracPart, nil
+}
+
+// Dehumanize converts a human-readable byte slice into a uint64.
+func dehumanize(hbytes []byte) (uint64, error) {
+ ll := len(hbytes)
+ if ll == 0 {
+ return 0, fmt.Errorf("zero-length reply")
+ }
+ lastByte := hbytes[ll-1]
+ mul := float64(1)
+ var (
+ mant float64
+ err error
+ )
+ // If lastByte is beyond the range of ASCII digits, it must be a
+ // multiplier.
+ if lastByte > 57 {
+ // Remove multiplier from slice.
+ hbytes = hbytes[:len(hbytes)-1]
+
+ const (
+ _ = 1 << (10 * iota)
+ KiB
+ MiB
+ GiB
+ TiB
+ PiB
+ EiB
+ ZiB
+ YiB
+ )
+
+ multipliers := map[rune]float64{
+ // Source for conversion rules:
+ // linux-kernel/drivers/md/bcache/util.c:bch_hprint()
+ 'k': KiB,
+ 'M': MiB,
+ 'G': GiB,
+ 'T': TiB,
+ 'P': PiB,
+ 'E': EiB,
+ 'Z': ZiB,
+ 'Y': YiB,
+ }
+ mul = float64(multipliers[rune(lastByte)])
+ mant, err = parsePseudoFloat(string(hbytes))
+ if err != nil {
+ return 0, err
+ }
+ } else {
+ // Not humanized by bch_hprint
+ mant, err = strconv.ParseFloat(string(hbytes), 64)
+ if err != nil {
+ return 0, err
+ }
+ }
+ res := uint64(mant * mul)
+ return res, nil
+}
+
+type parser struct {
+ uuidPath string
+ subDir string
+ currentDir string
+ err error
+}
+
+func (p *parser) setSubDir(pathElements ...string) {
+ p.subDir = path.Join(pathElements...)
+ p.currentDir = path.Join(p.uuidPath, p.subDir)
+}
+
+func (p *parser) readValue(fileName string) uint64 {
+ if p.err != nil {
+ return 0
+ }
+ path := path.Join(p.currentDir, fileName)
+ byt, err := ioutil.ReadFile(path)
+ if err != nil {
+ p.err = fmt.Errorf("failed to read: %s", path)
+ return 0
+ }
+ // Remove trailing newline.
+ byt = byt[:len(byt)-1]
+ res, err := dehumanize(byt)
+ p.err = err
+ return res
+}
+
+// ParsePriorityStats parses lines from the priority_stats file.
+func parsePriorityStats(line string, ps *PriorityStats) (error) {
+ var (
+ value uint64
+ err error
+ )
+ switch {
+ case strings.HasPrefix(line, "Unused:"):
+ fields := strings.Fields(line)
+ rawValue := fields[len(fields)-1]
+ valueStr := strings.TrimSuffix(rawValue, "%")
+ value, err = strconv.ParseUint(valueStr, 10, 64)
+ if err != nil {
+ return err
+ }
+ ps.UnusedPercent = value
+ case strings.HasPrefix(line, "Metadata:"):
+ fields := strings.Fields(line)
+ rawValue := fields[len(fields)-1]
+ valueStr := strings.TrimSuffix(rawValue, "%")
+ value, err = strconv.ParseUint(valueStr, 10, 64)
+ if err != nil {
+ return err
+ }
+ ps.MetadataPercent = value
+ }
+ return nil
+}
+
+func (p *parser) getPriorityStats() PriorityStats {
+ var res PriorityStats
+
+ if p.err != nil {
+ return res
+ }
+
+ path := path.Join(p.currentDir, "priority_stats")
+
+ file, err := os.Open(path)
+ if err != nil {
+ p.err = fmt.Errorf("failed to read: %s", path)
+ return res
+ }
+ defer file.Close()
+
+ scanner := bufio.NewScanner(file)
+ for scanner.Scan() {
+ err = parsePriorityStats(scanner.Text(), &res)
+ if err != nil {
+ p.err = fmt.Errorf("failed to parse: %s (%s)", path, err)
+ return res
+ }
+ }
+ if err := scanner.Err(); err != nil {
+ p.err = fmt.Errorf("failed to parse: %s (%s)", path, err)
+ return res
+ }
+ return res
+}
+
+// GetStats collects from sysfs files data tied to one bcache ID.
+func GetStats(uuidPath string) (*Stats, error) {
+ var bs Stats
+
+ par := parser{uuidPath: uuidPath}
+
+ // bcache stats
+
+ // dir <uuidPath>
+ par.setSubDir("")
+ bs.Bcache.AverageKeySize = par.readValue("average_key_size")
+ bs.Bcache.BtreeCacheSize = par.readValue("btree_cache_size")
+ bs.Bcache.CacheAvailablePercent = par.readValue("cache_available_percent")
+ bs.Bcache.Congested = par.readValue("congested")
+ bs.Bcache.RootUsagePercent = par.readValue("root_usage_percent")
+ bs.Bcache.TreeDepth = par.readValue("tree_depth")
+
+ // bcache stats (internal)
+
+ // dir <uuidPath>/internal
+ par.setSubDir("internal")
+ bs.Bcache.Internal.ActiveJournalEntries = par.readValue("active_journal_entries")
+ bs.Bcache.Internal.BtreeNodes = par.readValue("btree_nodes")
+ bs.Bcache.Internal.BtreeReadAverageDurationNanoSeconds = par.readValue("btree_read_average_duration_us")
+ bs.Bcache.Internal.CacheReadRaces = par.readValue("cache_read_races")
+
+ // bcache stats (period)
+
+ // dir <uuidPath>/stats_five_minute
+ par.setSubDir("stats_five_minute")
+ bs.Bcache.FiveMin.Bypassed = par.readValue("bypassed")
+ bs.Bcache.FiveMin.CacheHits = par.readValue("cache_hits")
+
+ bs.Bcache.FiveMin.Bypassed = par.readValue("bypassed")
+ bs.Bcache.FiveMin.CacheBypassHits = par.readValue("cache_bypass_hits")
+ bs.Bcache.FiveMin.CacheBypassMisses = par.readValue("cache_bypass_misses")
+ bs.Bcache.FiveMin.CacheHits = par.readValue("cache_hits")
+ bs.Bcache.FiveMin.CacheMissCollisions = par.readValue("cache_miss_collisions")
+ bs.Bcache.FiveMin.CacheMisses = par.readValue("cache_misses")
+ bs.Bcache.FiveMin.CacheReadaheads = par.readValue("cache_readaheads")
+
+ // dir <uuidPath>/stats_total
+ par.setSubDir("stats_total")
+ bs.Bcache.Total.Bypassed = par.readValue("bypassed")
+ bs.Bcache.Total.CacheHits = par.readValue("cache_hits")
+
+ bs.Bcache.Total.Bypassed = par.readValue("bypassed")
+ bs.Bcache.Total.CacheBypassHits = par.readValue("cache_bypass_hits")
+ bs.Bcache.Total.CacheBypassMisses = par.readValue("cache_bypass_misses")
+ bs.Bcache.Total.CacheHits = par.readValue("cache_hits")
+ bs.Bcache.Total.CacheMissCollisions = par.readValue("cache_miss_collisions")
+ bs.Bcache.Total.CacheMisses = par.readValue("cache_misses")
+ bs.Bcache.Total.CacheReadaheads = par.readValue("cache_readaheads")
+
+ if par.err != nil {
+ return nil, par.err
+ }
+
+ // bdev stats
+
+ reg := path.Join(uuidPath, "bdev[0-9]*")
+ bdevDirs, err := filepath.Glob(reg)
+ if err != nil {
+ return nil, err
+ }
+
+ bs.Bdevs = make([]BdevStats, len(bdevDirs))
+
+ for ii, bdevDir := range bdevDirs {
+ var bds = &bs.Bdevs[ii]
+
+ bds.Name = filepath.Base(bdevDir)
+
+ par.setSubDir(bds.Name)
+ bds.DirtyData = par.readValue("dirty_data")
+
+ // dir <uuidPath>/<bds.Name>/stats_five_minute
+ par.setSubDir(bds.Name, "stats_five_minute")
+ bds.FiveMin.Bypassed = par.readValue("bypassed")
+ bds.FiveMin.CacheBypassHits = par.readValue("cache_bypass_hits")
+ bds.FiveMin.CacheBypassMisses = par.readValue("cache_bypass_misses")
+ bds.FiveMin.CacheHits = par.readValue("cache_hits")
+ bds.FiveMin.CacheMissCollisions = par.readValue("cache_miss_collisions")
+ bds.FiveMin.CacheMisses = par.readValue("cache_misses")
+ bds.FiveMin.CacheReadaheads = par.readValue("cache_readaheads")
+
+ // dir <uuidPath>/<bds.Name>/stats_total
+ par.setSubDir("stats_total")
+ bds.Total.Bypassed = par.readValue("bypassed")
+ bds.Total.CacheBypassHits = par.readValue("cache_bypass_hits")
+ bds.Total.CacheBypassMisses = par.readValue("cache_bypass_misses")
+ bds.Total.CacheHits = par.readValue("cache_hits")
+ bds.Total.CacheMissCollisions = par.readValue("cache_miss_collisions")
+ bds.Total.CacheMisses = par.readValue("cache_misses")
+ bds.Total.CacheReadaheads = par.readValue("cache_readaheads")
+ }
+
+ if par.err != nil {
+ return nil, par.err
+ }
+
+ // cache stats
+
+ reg = path.Join(uuidPath, "cache[0-9]*")
+ cacheDirs, err := filepath.Glob(reg)
+ if err != nil {
+ return nil, err
+ }
+ bs.Caches = make([]CacheStats, len(cacheDirs))
+
+ for ii, cacheDir := range cacheDirs {
+ var cs = &bs.Caches[ii]
+ cs.Name = filepath.Base(cacheDir)
+
+ // dir is <uuidPath>/<cs.Name>
+ par.setSubDir(cs.Name)
+ cs.IOErrors = par.readValue("io_errors")
+ cs.MetadataWritten = par.readValue("metadata_written")
+ cs.Written = par.readValue("written")
+
+ ps := par.getPriorityStats()
+ cs.Priority = ps
+ }
+
+ if par.err != nil {
+ return nil, par.err
+ }
+
+ return &bs, nil
+}
diff --git a/vendor/github.com/prometheus/procfs/bcache/get_test.go b/vendor/github.com/prometheus/procfs/bcache/get_test.go
new file mode 100644
index 000000000..38c3df573
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/bcache/get_test.go
@@ -0,0 +1,114 @@
+// Copyright 2017 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package bcache
+
+import (
+ "testing"
+ "math"
+)
+
+func TestDehumanizeTests(t *testing.T) {
+ dehumanizeTests := []struct {
+ in []byte
+ out uint64
+ invalid bool
+ }{
+ {
+ in: []byte("542k"),
+ out: 555008,
+ },
+ {
+ in: []byte("322M"),
+ out: 337641472,
+ },
+ {
+ in: []byte("1.1k"),
+ out: 1124,
+ },
+ {
+ in: []byte("1.9k"),
+ out: 1924,
+ },
+ {
+ in: []byte("1.10k"),
+ out: 2024,
+ },
+ {
+ in: []byte(""),
+ out: 0,
+ invalid: true,
+ },
+ }
+ for _, tst := range dehumanizeTests {
+ got, err := dehumanize(tst.in)
+ if tst.invalid && err == nil {
+ t.Error("expected an error, but none occurred")
+ }
+ if !tst.invalid && err != nil {
+ t.Errorf("unexpected error: %v", err)
+ }
+ if got != tst.out {
+ t.Errorf("dehumanize: '%s', want %f, got %f", tst.in, tst.out, got)
+ }
+ }
+}
+
+func TestParsePseudoFloatTests(t *testing.T) {
+ parsePseudoFloatTests := []struct {
+ in string
+ out float64
+ }{
+ {
+ in: "1.1",
+ out: float64(1.097656),
+ },
+ {
+ in: "1.9",
+ out: float64(1.878906),
+ },
+ {
+ in: "1.10",
+ out: float64(1.976562),
+ },
+ }
+ for _, tst := range parsePseudoFloatTests {
+ got, err := parsePseudoFloat(tst.in)
+ if err != nil || math.Abs(got - tst.out) > 0.0001 {
+ t.Errorf("parsePseudoFloat: %s, want %f, got %f", tst.in, tst.out, got)
+ }
+ }
+}
+
+func TestPriorityStats(t *testing.T) {
+ var want = PriorityStats{
+ UnusedPercent: 99,
+ MetadataPercent: 5,
+ }
+ var (
+ in string
+ gotErr error
+ got PriorityStats
+ )
+ in = "Metadata: 5%"
+ gotErr = parsePriorityStats(in, &got)
+ if gotErr != nil || got.MetadataPercent != want.MetadataPercent {
+ t.Errorf("parsePriorityStats: '%s', want %f, got %f", in, want.MetadataPercent, got.MetadataPercent)
+ }
+
+ in = "Unused: 99%"
+ gotErr = parsePriorityStats(in, &got)
+ if gotErr != nil || got.UnusedPercent != want.UnusedPercent {
+ t.Errorf("parsePriorityStats: '%s', want %f, got %f", in, want.UnusedPercent, got.UnusedPercent)
+ }
+}
diff --git a/vendor/github.com/prometheus/procfs/fixtures/net/xfrm_stat b/vendor/github.com/prometheus/procfs/fixtures/net/xfrm_stat
new file mode 100644
index 000000000..d278ace95
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/fixtures/net/xfrm_stat
@@ -0,0 +1,28 @@
+XfrmInError 1
+XfrmInBufferError 2
+XfrmInHdrError 4
+XfrmInNoStates 3
+XfrmInStateProtoError 40
+XfrmInStateModeError 100
+XfrmInStateSeqError 6000
+XfrmInStateExpired 4
+XfrmInStateMismatch 23451
+XfrmInStateInvalid 55555
+XfrmInTmplMismatch 51
+XfrmInNoPols 65432
+XfrmInPolBlock 100
+XfrmInPolError 10000
+XfrmOutError 1000000
+XfrmOutBundleGenError 43321
+XfrmOutBundleCheckError 555
+XfrmOutNoStates 869
+XfrmOutStateProtoError 4542
+XfrmOutStateModeError 4
+XfrmOutStateSeqError 543
+XfrmOutStateExpired 565
+XfrmOutPolBlock 43456
+XfrmOutPolDead 7656
+XfrmOutPolError 1454
+XfrmFwdHdrError 6654
+XfrmOutStateInvalid 28765
+XfrmAcquireError 24532
diff --git a/vendor/github.com/prometheus/procfs/fixtures/stat b/vendor/github.com/prometheus/procfs/fixtures/stat
index dabb96f74..1582a8cb5 100644
--- a/vendor/github.com/prometheus/procfs/fixtures/stat
+++ b/vendor/github.com/prometheus/procfs/fixtures/stat
@@ -12,5 +12,5 @@ ctxt 38014093
btime 1418183276
processes 26442
procs_running 2
-procs_blocked 0
+procs_blocked 1
softirq 5057579 250191 1481983 1647 211099 186066 0 1783454 622196 12499 508444
diff --git a/vendor/github.com/prometheus/procfs/stat.go b/vendor/github.com/prometheus/procfs/stat.go
index 1ca217e8c..701f4df64 100644
--- a/vendor/github.com/prometheus/procfs/stat.go
+++ b/vendor/github.com/prometheus/procfs/stat.go
@@ -3,15 +3,66 @@ package procfs
import (
"bufio"
"fmt"
+ "io"
"os"
"strconv"
"strings"
)
+// CPUStat shows how much time the cpu spend in various stages.
+type CPUStat struct {
+ User float64
+ Nice float64
+ System float64
+ Idle float64
+ Iowait float64
+ IRQ float64
+ SoftIRQ float64
+ Steal float64
+ Guest float64
+ GuestNice float64
+}
+
+// SoftIRQStat represent the softirq statistics as exported in the procfs stat file.
+// A nice introduction can be found at https://0xax.gitbooks.io/linux-insides/content/interrupts/interrupts-9.html
+// It is possible to get per-cpu stats by reading /proc/softirqs
+type SoftIRQStat struct {
+ Hi uint64
+ Timer uint64
+ NetTx uint64
+ NetRx uint64
+ Block uint64
+ BlockIoPoll uint64
+ Tasklet uint64
+ Sched uint64
+ Hrtimer uint64
+ Rcu uint64
+}
+
// Stat represents kernel/system statistics.
type Stat struct {
// Boot time in seconds since the Epoch.
- BootTime int64
+ BootTime uint64
+ // Summed up cpu statistics.
+ CPUTotal CPUStat
+ // Per-CPU statistics.
+ CPU []CPUStat
+ // Number of times interrupts were handled, which contains numbered and unnumbered IRQs.
+ IRQTotal uint64
+ // Number of times a numbered IRQ was triggered.
+ IRQ []uint64
+ // Number of times a context switch happened.
+ ContextSwitches uint64
+ // Number of times a process was created.
+ ProcessCreated uint64
+ // Number of processes currently running.
+ ProcessesRunning uint64
+ // Number of processes currently blocked (waiting for IO).
+ ProcessesBlocked uint64
+ // Number of times a softirq was scheduled.
+ SoftIRQTotal uint64
+ // Detailed softirq statistics.
+ SoftIRQ SoftIRQStat
}
// NewStat returns kernel/system statistics read from /proc/stat.
@@ -24,33 +75,145 @@ func NewStat() (Stat, error) {
return fs.NewStat()
}
+// Parse a cpu statistics line and returns the CPUStat struct plus the cpu id (or -1 for the overall sum).
+func parseCPUStat(line string) (CPUStat, int64, error) {
+ cpuStat := CPUStat{}
+ var cpu string
+
+ count, err := fmt.Sscanf(line, "%s %f %f %f %f %f %f %f %f %f %f",
+ &cpu,
+ &cpuStat.User, &cpuStat.Nice, &cpuStat.System, &cpuStat.Idle,
+ &cpuStat.Iowait, &cpuStat.IRQ, &cpuStat.SoftIRQ, &cpuStat.Steal,
+ &cpuStat.Guest, &cpuStat.GuestNice)
+
+ if err != nil && err != io.EOF {
+ return CPUStat{}, -1, fmt.Errorf("couldn't parse %s (cpu): %s", line, err)
+ }
+ if count == 0 {
+ return CPUStat{}, -1, fmt.Errorf("couldn't parse %s (cpu): 0 elements parsed", line)
+ }
+
+ cpuStat.User /= userHZ
+ cpuStat.Nice /= userHZ
+ cpuStat.System /= userHZ
+ cpuStat.Idle /= userHZ
+ cpuStat.Iowait /= userHZ
+ cpuStat.IRQ /= userHZ
+ cpuStat.SoftIRQ /= userHZ
+ cpuStat.Steal /= userHZ
+ cpuStat.Guest /= userHZ
+ cpuStat.GuestNice /= userHZ
+
+ if cpu == "cpu" {
+ return cpuStat, -1, nil
+ }
+
+ cpuID, err := strconv.ParseInt(cpu[3:], 10, 64)
+ if err != nil {
+ return CPUStat{}, -1, fmt.Errorf("couldn't parse %s (cpu/cpuid): %s", line, err)
+ }
+
+ return cpuStat, cpuID, nil
+}
+
+// Parse a softirq line.
+func parseSoftIRQStat(line string) (SoftIRQStat, uint64, error) {
+ softIRQStat := SoftIRQStat{}
+ var total uint64
+ var prefix string
+
+ _, err := fmt.Sscanf(line, "%s %d %d %d %d %d %d %d %d %d %d %d",
+ &prefix, &total,
+ &softIRQStat.Hi, &softIRQStat.Timer, &softIRQStat.NetTx, &softIRQStat.NetRx,
+ &softIRQStat.Block, &softIRQStat.BlockIoPoll,
+ &softIRQStat.Tasklet, &softIRQStat.Sched,
+ &softIRQStat.Hrtimer, &softIRQStat.Rcu)
+
+ if err != nil {
+ return SoftIRQStat{}, 0, fmt.Errorf("couldn't parse %s (softirq): %s", line, err)
+ }
+
+ return softIRQStat, total, nil
+}
+
// NewStat returns an information about current kernel/system statistics.
func (fs FS) NewStat() (Stat, error) {
+ // See https://www.kernel.org/doc/Documentation/filesystems/proc.txt
+
f, err := os.Open(fs.Path("stat"))
if err != nil {
return Stat{}, err
}
defer f.Close()
- s := bufio.NewScanner(f)
- for s.Scan() {
- line := s.Text()
- if !strings.HasPrefix(line, "btime") {
+ stat := Stat{}
+
+ scanner := bufio.NewScanner(f)
+ for scanner.Scan() {
+ line := scanner.Text()
+ parts := strings.Fields(scanner.Text())
+ // require at least <key> <value>
+ if len(parts) < 2 {
continue
}
- fields := strings.Fields(line)
- if len(fields) != 2 {
- return Stat{}, fmt.Errorf("couldn't parse %s line %s", f.Name(), line)
- }
- i, err := strconv.ParseInt(fields[1], 10, 32)
- if err != nil {
- return Stat{}, fmt.Errorf("couldn't parse %s: %s", fields[1], err)
+ switch {
+ case parts[0] == "btime":
+ if stat.BootTime, err = strconv.ParseUint(parts[1], 10, 64); err != nil {
+ return Stat{}, fmt.Errorf("couldn't parse %s (btime): %s", parts[1], err)
+ }
+ case parts[0] == "intr":
+ if stat.IRQTotal, err = strconv.ParseUint(parts[1], 10, 64); err != nil {
+ return Stat{}, fmt.Errorf("couldn't parse %s (intr): %s", parts[1], err)
+ }
+ numberedIRQs := parts[2:]
+ stat.IRQ = make([]uint64, len(numberedIRQs))
+ for i, count := range numberedIRQs {
+ if stat.IRQ[i], err = strconv.ParseUint(count, 10, 64); err != nil {
+ return Stat{}, fmt.Errorf("couldn't parse %s (intr%d): %s", count, i, err)
+ }
+ }
+ case parts[0] == "ctxt":
+ if stat.ContextSwitches, err = strconv.ParseUint(parts[1], 10, 64); err != nil {
+ return Stat{}, fmt.Errorf("couldn't parse %s (ctxt): %s", parts[1], err)
+ }
+ case parts[0] == "processes":
+ if stat.ProcessCreated, err = strconv.ParseUint(parts[1], 10, 64); err != nil {
+ return Stat{}, fmt.Errorf("couldn't parse %s (processes): %s", parts[1], err)
+ }
+ case parts[0] == "procs_running":
+ if stat.ProcessesRunning, err = strconv.ParseUint(parts[1], 10, 64); err != nil {
+ return Stat{}, fmt.Errorf("couldn't parse %s (procs_running): %s", parts[1], err)
+ }
+ case parts[0] == "procs_blocked":
+ if stat.ProcessesBlocked, err = strconv.ParseUint(parts[1], 10, 64); err != nil {
+ return Stat{}, fmt.Errorf("couldn't parse %s (procs_blocked): %s", parts[1], err)
+ }
+ case parts[0] == "softirq":
+ softIRQStats, total, err := parseSoftIRQStat(line)
+ if err != nil {
+ return Stat{}, err
+ }
+ stat.SoftIRQTotal = total
+ stat.SoftIRQ = softIRQStats
+ case strings.HasPrefix(parts[0], "cpu"):
+ cpuStat, cpuID, err := parseCPUStat(line)
+ if err != nil {
+ return Stat{}, err
+ }
+ if cpuID == -1 {
+ stat.CPUTotal = cpuStat
+ } else {
+ for int64(len(stat.CPU)) <= cpuID {
+ stat.CPU = append(stat.CPU, CPUStat{})
+ }
+ stat.CPU[cpuID] = cpuStat
+ }
}
- return Stat{BootTime: i}, nil
}
- if err := s.Err(); err != nil {
+
+ if err := scanner.Err(); err != nil {
return Stat{}, fmt.Errorf("couldn't parse %s: %s", f.Name(), err)
}
- return Stat{}, fmt.Errorf("couldn't parse %s, missing btime", f.Name())
+ return stat, nil
}
diff --git a/vendor/github.com/prometheus/procfs/stat_test.go b/vendor/github.com/prometheus/procfs/stat_test.go
index 6eb792478..c34ccce1a 100644
--- a/vendor/github.com/prometheus/procfs/stat_test.go
+++ b/vendor/github.com/prometheus/procfs/stat_test.go
@@ -8,7 +8,54 @@ func TestStat(t *testing.T) {
t.Fatal(err)
}
- if want, have := int64(1418183276), s.BootTime; want != have {
- t.Errorf("want boot time %d, have %d", want, have)
+ // cpu
+ if want, have := float64(301854)/userHZ, s.CPUTotal.User; want != have {
+ t.Errorf("want cpu/user %v, have %v", want, have)
}
+ if want, have := float64(31)/userHZ, s.CPU[7].SoftIRQ; want != have {
+ t.Errorf("want cpu7/softirq %v, have %v", want, have)
+ }
+
+ // intr
+ if want, have := uint64(8885917), s.IRQTotal; want != have {
+ t.Errorf("want irq/total %d, have %d", want, have)
+ }
+ if want, have := uint64(1), s.IRQ[8]; want != have {
+ t.Errorf("want irq8 %d, have %d", want, have)
+ }
+
+ // ctxt
+ if want, have := uint64(38014093), s.ContextSwitches; want != have {
+ t.Errorf("want context switches (ctxt) %d, have %d", want, have)
+ }
+
+ // btime
+ if want, have := uint64(1418183276), s.BootTime; want != have {
+ t.Errorf("want boot time (btime) %d, have %d", want, have)
+ }
+
+ // processes
+ if want, have := uint64(26442), s.ProcessCreated; want != have {
+ t.Errorf("want process created (processes) %d, have %d", want, have)
+ }
+
+ // procs_running
+ if want, have := uint64(2), s.ProcessesRunning; want != have {
+ t.Errorf("want processes running (procs_running) %d, have %d", want, have)
+ }
+
+ // procs_blocked
+ if want, have := uint64(1), s.ProcessesBlocked; want != have {
+ t.Errorf("want processes blocked (procs_blocked) %d, have %d", want, have)
+ }
+
+ // softirq
+ if want, have := uint64(5057579), s.SoftIRQTotal; want != have {
+ t.Errorf("want softirq total %d, have %d", want, have)
+ }
+
+ if want, have := uint64(508444), s.SoftIRQ.Rcu; want != have {
+ t.Errorf("want softirq RCU %d, have %d", want, have)
+ }
+
}
diff --git a/vendor/github.com/prometheus/procfs/sysfs/.gitignore b/vendor/github.com/prometheus/procfs/sysfs/.gitignore
new file mode 100644
index 000000000..67fc140b9
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/sysfs/.gitignore
@@ -0,0 +1 @@
+fixtures/
diff --git a/vendor/github.com/prometheus/procfs/sysfs/fixtures.tar.gz b/vendor/github.com/prometheus/procfs/sysfs/fixtures.tar.gz
new file mode 100644
index 000000000..88035b7ce
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/sysfs/fixtures.tar.gz
Binary files differ
diff --git a/vendor/github.com/prometheus/procfs/sysfs/fixtures/fs/xfs/sda1/stats/stats b/vendor/github.com/prometheus/procfs/sysfs/fixtures/fs/xfs/sda1/stats/stats
deleted file mode 100644
index 0db7520bf..000000000
--- a/vendor/github.com/prometheus/procfs/sysfs/fixtures/fs/xfs/sda1/stats/stats
+++ /dev/null
@@ -1 +0,0 @@
-extent_alloc 1 0 0 0
diff --git a/vendor/github.com/prometheus/procfs/sysfs/fixtures/fs/xfs/sdb1/stats/stats b/vendor/github.com/prometheus/procfs/sysfs/fixtures/fs/xfs/sdb1/stats/stats
deleted file mode 100644
index 85a038402..000000000
--- a/vendor/github.com/prometheus/procfs/sysfs/fixtures/fs/xfs/sdb1/stats/stats
+++ /dev/null
@@ -1 +0,0 @@
-extent_alloc 2 0 0 0
diff --git a/vendor/github.com/prometheus/procfs/sysfs/fs.go b/vendor/github.com/prometheus/procfs/sysfs/fs.go
index 8e8380083..fb15d438a 100644
--- a/vendor/github.com/prometheus/procfs/sysfs/fs.go
+++ b/vendor/github.com/prometheus/procfs/sysfs/fs.go
@@ -18,6 +18,7 @@ import (
"os"
"path/filepath"
+ "github.com/prometheus/procfs/bcache"
"github.com/prometheus/procfs/xfs"
)
@@ -80,3 +81,28 @@ func (fs FS) XFSStats() ([]*xfs.Stats, error) {
return stats, nil
}
+
+// BcacheStats retrieves bcache runtime statistics for each bcache.
+func (fs FS) BcacheStats() ([]*bcache.Stats, error) {
+ matches, err := filepath.Glob(fs.Path("fs/bcache/*-*"))
+ if err != nil {
+ return nil, err
+ }
+
+ stats := make([]*bcache.Stats, 0, len(matches))
+ for _, uuidPath := range matches {
+ // "*-*" in glob above indicates the name of the bcache.
+ name := filepath.Base(uuidPath)
+
+ // stats
+ s, err := bcache.GetStats(uuidPath)
+ if err != nil {
+ return nil, err
+ }
+
+ s.Name = name
+ stats = append(stats, s)
+ }
+
+ return stats, nil
+}
diff --git a/vendor/github.com/prometheus/procfs/sysfs/fs_test.go b/vendor/github.com/prometheus/procfs/sysfs/fs_test.go
index d7f2b736b..2b7402eca 100644
--- a/vendor/github.com/prometheus/procfs/sysfs/fs_test.go
+++ b/vendor/github.com/prometheus/procfs/sysfs/fs_test.go
@@ -64,3 +64,45 @@ func TestFSXFSStats(t *testing.T) {
}
}
}
+
+func TestFSBcacheStats(t *testing.T) {
+ stats, err := FS("fixtures").BcacheStats()
+ if err != nil {
+ t.Fatalf("failed to parse bcache stats: %v", err)
+ }
+
+ tests := []struct {
+ name string
+ bdevs int
+ caches int
+ }{
+ {
+ name: "deaddd54-c735-46d5-868e-f331c5fd7c74",
+ bdevs: 1,
+ caches: 1,
+ },
+ }
+
+ const expect = 1
+
+ if l := len(stats); l != expect {
+ t.Fatalf("unexpected number of bcache stats: %d", l)
+ }
+ if l := len(tests); l != expect {
+ t.Fatalf("unexpected number of tests: %d", l)
+ }
+
+ for i, tt := range tests {
+ if want, got := tt.name, stats[i].Name; want != got {
+ t.Errorf("unexpected stats name:\nwant: %q\nhave: %q", want, got)
+ }
+
+ if want, got := tt.bdevs, len(stats[i].Bdevs); want != got {
+ t.Errorf("unexpected value allocated:\nwant: %d\nhave: %d", want, got)
+ }
+
+ if want, got := tt.caches, len(stats[i].Caches); want != got {
+ t.Errorf("unexpected value allocated:\nwant: %d\nhave: %d", want, got)
+ }
+ }
+}
diff --git a/vendor/github.com/prometheus/procfs/xfrm.go b/vendor/github.com/prometheus/procfs/xfrm.go
new file mode 100644
index 000000000..ffe9df50d
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/xfrm.go
@@ -0,0 +1,187 @@
+// Copyright 2017 Prometheus Team
+// 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 procfs
+
+import (
+ "bufio"
+ "fmt"
+ "os"
+ "strconv"
+ "strings"
+)
+
+// XfrmStat models the contents of /proc/net/xfrm_stat.
+type XfrmStat struct {
+ // All errors which are not matched by other
+ XfrmInError int
+ // No buffer is left
+ XfrmInBufferError int
+ // Header Error
+ XfrmInHdrError int
+ // No state found
+ // i.e. either inbound SPI, address, or IPSEC protocol at SA is wrong
+ XfrmInNoStates int
+ // Transformation protocol specific error
+ // e.g. SA Key is wrong
+ XfrmInStateProtoError int
+ // Transformation mode specific error
+ XfrmInStateModeError int
+ // Sequence error
+ // e.g. sequence number is out of window
+ XfrmInStateSeqError int
+ // State is expired
+ XfrmInStateExpired int
+ // State has mismatch option
+ // e.g. UDP encapsulation type is mismatched
+ XfrmInStateMismatch int
+ // State is invalid
+ XfrmInStateInvalid int
+ // No matching template for states
+ // e.g. Inbound SAs are correct but SP rule is wrong
+ XfrmInTmplMismatch int
+ // No policy is found for states
+ // e.g. Inbound SAs are correct but no SP is found
+ XfrmInNoPols int
+ // Policy discards
+ XfrmInPolBlock int
+ // Policy error
+ XfrmInPolError int
+ // All errors which are not matched by others
+ XfrmOutError int
+ // Bundle generation error
+ XfrmOutBundleGenError int
+ // Bundle check error
+ XfrmOutBundleCheckError int
+ // No state was found
+ XfrmOutNoStates int
+ // Transformation protocol specific error
+ XfrmOutStateProtoError int
+ // Transportation mode specific error
+ XfrmOutStateModeError int
+ // Sequence error
+ // i.e sequence number overflow
+ XfrmOutStateSeqError int
+ // State is expired
+ XfrmOutStateExpired int
+ // Policy discads
+ XfrmOutPolBlock int
+ // Policy is dead
+ XfrmOutPolDead int
+ // Policy Error
+ XfrmOutPolError int
+ XfrmFwdHdrError int
+ XfrmOutStateInvalid int
+ XfrmAcquireError int
+}
+
+// NewXfrmStat reads the xfrm_stat statistics.
+func NewXfrmStat() (XfrmStat, error) {
+ fs, err := NewFS(DefaultMountPoint)
+ if err != nil {
+ return XfrmStat{}, err
+ }
+
+ return fs.NewXfrmStat()
+}
+
+// NewXfrmStat reads the xfrm_stat statistics from the 'proc' filesystem.
+func (fs FS) NewXfrmStat() (XfrmStat, error) {
+ file, err := os.Open(fs.Path("net/xfrm_stat"))
+ if err != nil {
+ return XfrmStat{}, err
+ }
+ defer file.Close()
+
+ var (
+ x = XfrmStat{}
+ s = bufio.NewScanner(file)
+ )
+
+ for s.Scan() {
+ fields := strings.Fields(s.Text())
+
+ if len(fields) != 2 {
+ return XfrmStat{}, fmt.Errorf(
+ "couldnt parse %s line %s", file.Name(), s.Text())
+ }
+
+ name := fields[0]
+ value, err := strconv.Atoi(fields[1])
+ if err != nil {
+ return XfrmStat{}, err
+ }
+
+ switch name {
+ case "XfrmInError":
+ x.XfrmInError = value
+ case "XfrmInBufferError":
+ x.XfrmInBufferError = value
+ case "XfrmInHdrError":
+ x.XfrmInHdrError = value
+ case "XfrmInNoStates":
+ x.XfrmInNoStates = value
+ case "XfrmInStateProtoError":
+ x.XfrmInStateProtoError = value
+ case "XfrmInStateModeError":
+ x.XfrmInStateModeError = value
+ case "XfrmInStateSeqError":
+ x.XfrmInStateSeqError = value
+ case "XfrmInStateExpired":
+ x.XfrmInStateExpired = value
+ case "XfrmInStateInvalid":
+ x.XfrmInStateInvalid = value
+ case "XfrmInTmplMismatch":
+ x.XfrmInTmplMismatch = value
+ case "XfrmInNoPols":
+ x.XfrmInNoPols = value
+ case "XfrmInPolBlock":
+ x.XfrmInPolBlock = value
+ case "XfrmInPolError":
+ x.XfrmInPolError = value
+ case "XfrmOutError":
+ x.XfrmOutError = value
+ case "XfrmInStateMismatch":
+ x.XfrmInStateMismatch = value
+ case "XfrmOutBundleGenError":
+ x.XfrmOutBundleGenError = value
+ case "XfrmOutBundleCheckError":
+ x.XfrmOutBundleCheckError = value
+ case "XfrmOutNoStates":
+ x.XfrmOutNoStates = value
+ case "XfrmOutStateProtoError":
+ x.XfrmOutStateProtoError = value
+ case "XfrmOutStateModeError":
+ x.XfrmOutStateModeError = value
+ case "XfrmOutStateSeqError":
+ x.XfrmOutStateSeqError = value
+ case "XfrmOutStateExpired":
+ x.XfrmOutStateExpired = value
+ case "XfrmOutPolBlock":
+ x.XfrmOutPolBlock = value
+ case "XfrmOutPolDead":
+ x.XfrmOutPolDead = value
+ case "XfrmOutPolError":
+ x.XfrmOutPolError = value
+ case "XfrmFwdHdrError":
+ x.XfrmFwdHdrError = value
+ case "XfrmOutStateInvalid":
+ x.XfrmOutStateInvalid = value
+ case "XfrmAcquireError":
+ x.XfrmAcquireError = value
+ }
+
+ }
+
+ return x, s.Err()
+}
diff --git a/vendor/github.com/prometheus/procfs/xfrm_test.go b/vendor/github.com/prometheus/procfs/xfrm_test.go
new file mode 100644
index 000000000..5918c390e
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/xfrm_test.go
@@ -0,0 +1,66 @@
+// Copyright 2017 Prometheus Team
+// 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 procfs
+
+import (
+ "testing"
+)
+
+func TestXfrmStats(t *testing.T) {
+ xfrmStats, err := FS("fixtures").NewXfrmStat()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ for _, test := range []struct {
+ name string
+ want int
+ got int
+ }{
+ {name: "XfrmInError", want: 1, got: xfrmStats.XfrmInError},
+ {name: "XfrmInBufferError", want: 2, got: xfrmStats.XfrmInBufferError},
+ {name: "XfrmInHdrError", want: 4, got: xfrmStats.XfrmInHdrError},
+ {name: "XfrmInNoStates", want: 3, got: xfrmStats.XfrmInNoStates},
+ {name: "XfrmInStateProtoError", want: 40, got: xfrmStats.XfrmInStateProtoError},
+ {name: "XfrmInStateModeError", want: 100, got: xfrmStats.XfrmInStateModeError},
+ {name: "XfrmInStateSeqError", want: 6000, got: xfrmStats.XfrmInStateSeqError},
+ {name: "XfrmInStateExpired", want: 4, got: xfrmStats.XfrmInStateExpired},
+ {name: "XfrmInStateMismatch", want: 23451, got: xfrmStats.XfrmInStateMismatch},
+ {name: "XfrmInStateInvalid", want: 55555, got: xfrmStats.XfrmInStateInvalid},
+ {name: "XfrmInTmplMismatch", want: 51, got: xfrmStats.XfrmInTmplMismatch},
+ {name: "XfrmInNoPols", want: 65432, got: xfrmStats.XfrmInNoPols},
+ {name: "XfrmInPolBlock", want: 100, got: xfrmStats.XfrmInPolBlock},
+ {name: "XfrmInPolError", want: 10000, got: xfrmStats.XfrmInPolError},
+ {name: "XfrmOutError", want: 1000000, got: xfrmStats.XfrmOutError},
+ {name: "XfrmOutBundleGenError", want: 43321, got: xfrmStats.XfrmOutBundleGenError},
+ {name: "XfrmOutBundleCheckError", want: 555, got: xfrmStats.XfrmOutBundleCheckError},
+ {name: "XfrmOutNoStates", want: 869, got: xfrmStats.XfrmOutNoStates},
+ {name: "XfrmOutStateProtoError", want: 4542, got: xfrmStats.XfrmOutStateProtoError},
+ {name: "XfrmOutStateModeError", want: 4, got: xfrmStats.XfrmOutStateModeError},
+ {name: "XfrmOutStateSeqError", want: 543, got: xfrmStats.XfrmOutStateSeqError},
+ {name: "XfrmOutStateExpired", want: 565, got: xfrmStats.XfrmOutStateExpired},
+ {name: "XfrmOutPolBlock", want: 43456, got: xfrmStats.XfrmOutPolBlock},
+ {name: "XfrmOutPolDead", want: 7656, got: xfrmStats.XfrmOutPolDead},
+ {name: "XfrmOutPolError", want: 1454, got: xfrmStats.XfrmOutPolError},
+ {name: "XfrmFwdHdrError", want: 6654, got: xfrmStats.XfrmFwdHdrError},
+ {name: "XfrmOutStateInvaliad", want: 28765, got: xfrmStats.XfrmOutStateInvalid},
+ {name: "XfrmAcquireError", want: 24532, got: xfrmStats.XfrmAcquireError},
+ {name: "XfrmInStateInvalid", want: 55555, got: xfrmStats.XfrmInStateInvalid},
+ {name: "XfrmOutError", want: 1000000, got: xfrmStats.XfrmOutError},
+ } {
+ if test.want != test.got {
+ t.Errorf("Want %s %d, have %d", test.name, test.want, test.got)
+ }
+ }
+}
diff --git a/vendor/github.com/segmentio/analytics-go/cli/cli.go b/vendor/github.com/segmentio/analytics-go/cli/cli.go
deleted file mode 100644
index 9d1f940c9..000000000
--- a/vendor/github.com/segmentio/analytics-go/cli/cli.go
+++ /dev/null
@@ -1,174 +0,0 @@
-package main
-
-import (
- "encoding/json"
- "log"
- "os"
- "reflect"
-
- "github.com/segmentio/analytics-go"
- "github.com/tj/docopt"
-)
-
-const Usage = `
-Analytics Go CLI
-
-Usage:
- analytics track <event> [--properties=<properties>] [--context=<context>] [--writeKey=<writeKey>] [--userId=<userId>] [--anonymousId=<anonymousId>] [--integrations=<integrations>] [--timestamp=<timestamp>]
- analytics screen <name> [--properties=<properties>] [--context=<context>] [--writeKey=<writeKey>] [--userId=<userId>] [--anonymousId=<anonymousId>] [--integrations=<integrations>] [--timestamp=<timestamp>]
- analytics page <name> [--properties=<properties>] [--context=<context>] [--writeKey=<writeKey>] [--userId=<userId>] [--anonymousId=<anonymousId>] [--integrations=<integrations>] [--timestamp=<timestamp>]
- analytics identify [--traits=<traits>] [--context=<context>] [--writeKey=<writeKey>] [--userId=<userId>] [--anonymousId=<anonymousId>] [--integrations=<integrations>] [--timestamp=<timestamp>]
- analytics group --groupId=<groupId> [--traits=<traits>] [--properties=<properties>] [--context=<context>] [--writeKey=<writeKey>] [--userId=<userId>] [--anonymousId=<anonymousId>] [--integrations=<integrations>] [--timestamp=<timestamp>]
- analytics alias --userId=<userId> --previousId=<previousId> [--traits=<traits>] [--properties=<properties>] [--context=<context>] [--writeKey=<writeKey>] [--anonymousId=<anonymousId>] [--integrations=<integrations>] [--timestamp=<timestamp>]
- analytics -h | --help
- analytics --version
-
-Options:
- -h --help Show this screen.
- --version Show version.
-`
-
-func main() {
- arguments, err := docopt.Parse(Usage, nil, true, "Anaytics Go CLI", false)
- check(err)
-
- writeKey := getOptionalString(arguments, "--writeKey")
- if writeKey == "" {
- writeKey = os.Getenv("SEGMENT_WRITE_KEY")
- if writeKey == "" {
- log.Fatal("either $SEGMENT_WRITE_KEY or --writeKey must be provided")
- }
- }
-
- client := analytics.New(writeKey)
- client.Size = 1
- client.Verbose = true
-
- if arguments["track"].(bool) {
- m := &analytics.Track{
- Event: arguments["<event>"].(string),
- }
- properties := getOptionalString(arguments, "--properties")
- if properties != "" {
- var parsedProperties map[string]interface{}
- err := json.Unmarshal([]byte(properties), &parsedProperties)
- check(err)
- m.Properties = parsedProperties
- }
-
- setCommonFields(m, arguments)
-
- check(client.Track(m))
- }
-
- if arguments["screen"].(bool) || arguments["page"].(bool) {
- m := &analytics.Page{
- Name: arguments["<name>"].(string),
- }
- /* Bug in Go library - page has traits not properties.
- properties := getOptionalString(arguments, "--properties")
- if properties != "" {
- var parsedProperties map[string]interface{}
- err := json.Unmarshal([]byte(properties), &parsedProperties)
- check(err)
- t.Properties = parsedProperties
- }
- */
-
- setCommonFields(m, arguments)
-
- check(client.Page(m))
- }
-
- if arguments["identify"].(bool) {
- m := &analytics.Identify{}
- traits := getOptionalString(arguments, "--traits")
- if traits != "" {
- var parsedTraits map[string]interface{}
- err := json.Unmarshal([]byte(traits), &parsedTraits)
- check(err)
- m.Traits = parsedTraits
- }
-
- setCommonFields(m, arguments)
-
- check(client.Identify(m))
- }
-
- if arguments["group"].(bool) {
- m := &analytics.Group{
- GroupId: arguments["--groupId"].(string),
- }
- traits := getOptionalString(arguments, "--traits")
- if traits != "" {
- var parsedTraits map[string]interface{}
- err := json.Unmarshal([]byte(traits), &parsedTraits)
- check(err)
- m.Traits = parsedTraits
- }
-
- setCommonFields(m, arguments)
-
- check(client.Group(m))
- }
-
- if arguments["alias"].(bool) {
- m := &analytics.Alias{
- PreviousId: arguments["--previousId"].(string),
- }
-
- setCommonFields(m, arguments)
-
- check(client.Alias(m))
- }
-
- client.Close()
-}
-
-func setCommonFields(message interface{}, arguments map[string]interface{}) {
- userId := getOptionalString(arguments, "--userId")
- if userId != "" {
- setFieldValue(message, "UserId", userId)
- }
- anonymousId := getOptionalString(arguments, "--anonymousId")
- if anonymousId != "" {
- setFieldValue(message, "AnonymousId", anonymousId)
- }
- integrations := getOptionalString(arguments, "--integrations")
- if integrations != "" {
- var parsedIntegrations map[string]interface{}
- err := json.Unmarshal([]byte(integrations), &parsedIntegrations)
- check(err)
- setFieldValue(message, "Integrations", parsedIntegrations)
- }
- context := getOptionalString(arguments, "--context")
- if context != "" {
- var parsedContext map[string]interface{}
- err := json.Unmarshal([]byte(context), &parsedContext)
- check(err)
- setFieldValue(message, "Context", parsedContext)
-
- }
- timestamp := getOptionalString(arguments, "--timestamp")
- if timestamp != "" {
- setFieldValue(message, "Timestamp", timestamp)
- }
-}
-
-func setFieldValue(target interface{}, field string, value interface{}) {
- reflect.ValueOf(target).Elem().FieldByName(field).Set(reflect.ValueOf(value))
-}
-
-func getOptionalString(m map[string]interface{}, k string) string {
- v := m[k]
- if v == nil {
- return ""
- }
- return v.(string)
-}
-
-func check(err error) {
- if err != nil {
- log.Fatal(err)
- }
-}
diff --git a/vendor/github.com/spf13/cobra/README.md b/vendor/github.com/spf13/cobra/README.md
index 4563c211d..ff844d2c0 100644
--- a/vendor/github.com/spf13/cobra/README.md
+++ b/vendor/github.com/spf13/cobra/README.md
@@ -127,10 +127,10 @@ tree is assigned to the commander which is finally executed.
# Installing
Using Cobra is easy. First, use `go get` to install the latest version
-of the library. This command will install the `cobra` generator executible
-along with the library:
+of the library. This command will install the `cobra` generator executable
+along with the library and its dependencies:
- go get -v github.com/spf13/cobra/cobra
+ go get -u github.com/spf13/cobra/cobra
Next, include Cobra in your application:
@@ -230,12 +230,12 @@ Once you have run these three commands you would have an app structure that woul
main.go
```
-at this point you can run `go run main.go` and it would run your app. `go run
+At this point you can run `go run main.go` and it would run your app. `go run
main.go serve`, `go run main.go config`, `go run main.go config create` along
with `go run main.go help serve`, etc would all work.
Obviously you haven't added your own code to these yet, the commands are ready
-for you to give them their tasks. Have fun.
+for you to give them their tasks. Have fun!
### Configuring the cobra generator
@@ -276,7 +276,6 @@ You will optionally provide additional commands as you see fit.
The root command represents your binary itself.
-
#### Manually create rootCmd
Cobra doesn't require any special constructors. Simply create your commands.
@@ -298,9 +297,18 @@ var RootCmd = &cobra.Command{
You will additionally define flags and handle configuration in your init() function.
-for example cmd/root.go:
+For example cmd/root.go:
```go
+import (
+ "fmt"
+ "os"
+
+ homedir "github.com/mitchellh/go-homedir"
+ "github.com/spf13/cobra"
+ "github.com/spf13/viper"
+)
+
func init() {
cobra.OnInitialize(initConfig)
RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
@@ -314,6 +322,34 @@ func init() {
viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
viper.SetDefault("license", "apache")
}
+
+func Execute() {
+ rootCmd.Execute()
+}
+
+func main() {
+ // Don't forget to read config either from cfgFile or from home directory!
+ if cfgFile != "" {
+ // Use config file from the flag.
+ viper.SetConfigFile(cfgFile)
+ } else {
+ // Find home directory.
+ home, err := homedir.Dir()
+ if err != nil {
+ fmt.Println(home)
+ os.Exit(1)
+ }
+
+ // Search config in home directory with name ".cobra" (without extension).
+ viper.AddConfigPath(home)
+ viper.SetConfigName(".cobra")
+ }
+
+ if err := viper.ReadInConfig(); err != nil {
+ fmt.Println("Can't read config:", err)
+ os.Exit(1)
+ }
+}
```
### Create your main.go
@@ -341,7 +377,6 @@ func main() {
}
```
-
### Create additional commands
Additional commands can be defined and typically are each given their own file
@@ -431,6 +466,23 @@ A flag can also be assigned locally which will only apply to that specific comma
RootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
```
+### Bind Flags with Config
+
+You can also bind your flags with [viper](https://github.com/spf13/viper):
+```go
+var author string
+
+func init() {
+ RootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution")
+ viper.BindPFlag("author", RootCmd.PersistentFlags().Lookup("author"))
+}
+```
+
+In this example the persistent flag `author` is bound with `viper`.
+**Note**, that the variable `author` will not be set to the value from config,
+when the `--author` flag is not provided by user.
+
+More in [viper documentation](https://github.com/spf13/viper#working-with-flags).
## Example
diff --git a/vendor/github.com/spf13/cobra/bash_completions.go b/vendor/github.com/spf13/cobra/bash_completions.go
index a0d040279..e0cfb3494 100644
--- a/vendor/github.com/spf13/cobra/bash_completions.go
+++ b/vendor/github.com/spf13/cobra/bash_completions.go
@@ -1,6 +1,7 @@
package cobra
import (
+ "bytes"
"fmt"
"io"
"os"
@@ -18,12 +19,9 @@ const (
BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir"
)
-func preamble(out io.Writer, name string) error {
- _, err := fmt.Fprintf(out, "# bash completion for %-36s -*- shell-script -*-\n", name)
- if err != nil {
- return err
- }
- preamStr := `
+func writePreamble(buf *bytes.Buffer, name string) {
+ buf.WriteString(fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name))
+ buf.WriteString(`
__debug()
{
if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then
@@ -134,7 +132,10 @@ __handle_reply()
declare -F __custom_func >/dev/null && __custom_func
fi
- __ltrim_colon_completions "$cur"
+ # available in bash-completion >= 2, not always present on macOS
+ if declare -F __ltrim_colon_completions >/dev/null; then
+ __ltrim_colon_completions "$cur"
+ fi
}
# The arguments should be in the form "ext1|ext2|extn"
@@ -247,18 +248,13 @@ __handle_word()
__handle_word
}
-`
- _, err = fmt.Fprint(out, preamStr)
- return err
+`)
}
-func postscript(w io.Writer, name string) error {
+func writePostscript(buf *bytes.Buffer, name string) {
name = strings.Replace(name, ":", "__", -1)
- _, err := fmt.Fprintf(w, "__start_%s()\n", name)
- if err != nil {
- return err
- }
- _, err = fmt.Fprintf(w, `{
+ buf.WriteString(fmt.Sprintf("__start_%s()\n", name))
+ buf.WriteString(fmt.Sprintf(`{
local cur prev words cword
declare -A flaghash 2>/dev/null || :
if declare -F _init_completion >/dev/null 2>&1; then
@@ -282,197 +278,132 @@ func postscript(w io.Writer, name string) error {
__handle_word
}
-`, name)
- if err != nil {
- return err
- }
- _, err = fmt.Fprintf(w, `if [[ $(type -t compopt) = "builtin" ]]; then
+`, name))
+ buf.WriteString(fmt.Sprintf(`if [[ $(type -t compopt) = "builtin" ]]; then
complete -o default -F __start_%s %s
else
complete -o default -o nospace -F __start_%s %s
fi
-`, name, name, name, name)
- if err != nil {
- return err
- }
- _, err = fmt.Fprintf(w, "# ex: ts=4 sw=4 et filetype=sh\n")
- return err
+`, name, name, name, name))
+ buf.WriteString("# ex: ts=4 sw=4 et filetype=sh\n")
}
-func writeCommands(cmd *Command, w io.Writer) error {
- if _, err := fmt.Fprintf(w, " commands=()\n"); err != nil {
- return err
- }
+func writeCommands(buf *bytes.Buffer, cmd *Command) {
+ buf.WriteString(" commands=()\n")
for _, c := range cmd.Commands() {
if !c.IsAvailableCommand() || c == cmd.helpCommand {
continue
}
- if _, err := fmt.Fprintf(w, " commands+=(%q)\n", c.Name()); err != nil {
- return err
- }
+ buf.WriteString(fmt.Sprintf(" commands+=(%q)\n", c.Name()))
}
- _, err := fmt.Fprintf(w, "\n")
- return err
+ buf.WriteString("\n")
}
-func writeFlagHandler(name string, annotations map[string][]string, w io.Writer) error {
+func writeFlagHandler(buf *bytes.Buffer, name string, annotations map[string][]string) {
for key, value := range annotations {
switch key {
case BashCompFilenameExt:
- _, err := fmt.Fprintf(w, " flags_with_completion+=(%q)\n", name)
- if err != nil {
- return err
- }
+ buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
+ var ext string
if len(value) > 0 {
- ext := "__handle_filename_extension_flag " + strings.Join(value, "|")
- _, err = fmt.Fprintf(w, " flags_completion+=(%q)\n", ext)
+ ext = "__handle_filename_extension_flag " + strings.Join(value, "|")
} else {
- ext := "_filedir"
- _, err = fmt.Fprintf(w, " flags_completion+=(%q)\n", ext)
- }
- if err != nil {
- return err
+ ext = "_filedir"
}
+ buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", ext))
case BashCompCustom:
- _, err := fmt.Fprintf(w, " flags_with_completion+=(%q)\n", name)
- if err != nil {
- return err
- }
+ buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
if len(value) > 0 {
handlers := strings.Join(value, "; ")
- _, err = fmt.Fprintf(w, " flags_completion+=(%q)\n", handlers)
+ buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", handlers))
} else {
- _, err = fmt.Fprintf(w, " flags_completion+=(:)\n")
- }
- if err != nil {
- return err
+ buf.WriteString(" flags_completion+=(:)\n")
}
case BashCompSubdirsInDir:
- _, err := fmt.Fprintf(w, " flags_with_completion+=(%q)\n", name)
+ buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
+ var ext string
if len(value) == 1 {
- ext := "__handle_subdirs_in_dir_flag " + value[0]
- _, err = fmt.Fprintf(w, " flags_completion+=(%q)\n", ext)
+ ext = "__handle_subdirs_in_dir_flag " + value[0]
} else {
- ext := "_filedir -d"
- _, err = fmt.Fprintf(w, " flags_completion+=(%q)\n", ext)
- }
- if err != nil {
- return err
+ ext = "_filedir -d"
}
+ buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", ext))
}
}
- return nil
}
-func writeShortFlag(flag *pflag.Flag, w io.Writer) error {
- b := (len(flag.NoOptDefVal) > 0)
+func writeShortFlag(buf *bytes.Buffer, flag *pflag.Flag) {
name := flag.Shorthand
format := " "
- if !b {
+ if len(flag.NoOptDefVal) == 0 {
format += "two_word_"
}
format += "flags+=(\"-%s\")\n"
- if _, err := fmt.Fprintf(w, format, name); err != nil {
- return err
- }
- return writeFlagHandler("-"+name, flag.Annotations, w)
+ buf.WriteString(fmt.Sprintf(format, name))
+ writeFlagHandler(buf, "-"+name, flag.Annotations)
}
-func writeFlag(flag *pflag.Flag, w io.Writer) error {
- b := (len(flag.NoOptDefVal) > 0)
+func writeFlag(buf *bytes.Buffer, flag *pflag.Flag) {
name := flag.Name
format := " flags+=(\"--%s"
- if !b {
+ if len(flag.NoOptDefVal) == 0 {
format += "="
}
format += "\")\n"
- if _, err := fmt.Fprintf(w, format, name); err != nil {
- return err
- }
- return writeFlagHandler("--"+name, flag.Annotations, w)
+ buf.WriteString(fmt.Sprintf(format, name))
+ writeFlagHandler(buf, "--"+name, flag.Annotations)
}
-func writeLocalNonPersistentFlag(flag *pflag.Flag, w io.Writer) error {
- b := (len(flag.NoOptDefVal) > 0)
+func writeLocalNonPersistentFlag(buf *bytes.Buffer, flag *pflag.Flag) {
name := flag.Name
format := " local_nonpersistent_flags+=(\"--%s"
- if !b {
+ if len(flag.NoOptDefVal) == 0 {
format += "="
}
format += "\")\n"
- _, err := fmt.Fprintf(w, format, name)
- return err
+ buf.WriteString(fmt.Sprintf(format, name))
}
-func writeFlags(cmd *Command, w io.Writer) error {
- _, err := fmt.Fprintf(w, ` flags=()
+func writeFlags(buf *bytes.Buffer, cmd *Command) {
+ buf.WriteString(` flags=()
two_word_flags=()
local_nonpersistent_flags=()
flags_with_completion=()
flags_completion=()
`)
- if err != nil {
- return err
- }
localNonPersistentFlags := cmd.LocalNonPersistentFlags()
- var visitErr error
cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
if nonCompletableFlag(flag) {
return
}
- if err := writeFlag(flag, w); err != nil {
- visitErr = err
- return
- }
+ writeFlag(buf, flag)
if len(flag.Shorthand) > 0 {
- if err := writeShortFlag(flag, w); err != nil {
- visitErr = err
- return
- }
+ writeShortFlag(buf, flag)
}
if localNonPersistentFlags.Lookup(flag.Name) != nil {
- if err := writeLocalNonPersistentFlag(flag, w); err != nil {
- visitErr = err
- return
- }
+ writeLocalNonPersistentFlag(buf, flag)
}
})
- if visitErr != nil {
- return visitErr
- }
cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {
if nonCompletableFlag(flag) {
return
}
- if err := writeFlag(flag, w); err != nil {
- visitErr = err
- return
- }
+ writeFlag(buf, flag)
if len(flag.Shorthand) > 0 {
- if err := writeShortFlag(flag, w); err != nil {
- visitErr = err
- return
- }
+ writeShortFlag(buf, flag)
}
})
- if visitErr != nil {
- return visitErr
- }
- _, err = fmt.Fprintf(w, "\n")
- return err
+ buf.WriteString("\n")
}
-func writeRequiredFlag(cmd *Command, w io.Writer) error {
- if _, err := fmt.Fprintf(w, " must_have_one_flag=()\n"); err != nil {
- return err
- }
+func writeRequiredFlag(buf *bytes.Buffer, cmd *Command) {
+ buf.WriteString(" must_have_one_flag=()\n")
flags := cmd.NonInheritedFlags()
- var visitErr error
flags.VisitAll(func(flag *pflag.Flag) {
if nonCompletableFlag(flag) {
return
@@ -481,107 +412,68 @@ func writeRequiredFlag(cmd *Command, w io.Writer) error {
switch key {
case BashCompOneRequiredFlag:
format := " must_have_one_flag+=(\"--%s"
- b := (flag.Value.Type() == "bool")
- if !b {
+ if flag.Value.Type() != "bool" {
format += "="
}
format += "\")\n"
- if _, err := fmt.Fprintf(w, format, flag.Name); err != nil {
- visitErr = err
- return
- }
+ buf.WriteString(fmt.Sprintf(format, flag.Name))
if len(flag.Shorthand) > 0 {
- if _, err := fmt.Fprintf(w, " must_have_one_flag+=(\"-%s\")\n", flag.Shorthand); err != nil {
- visitErr = err
- return
- }
+ buf.WriteString(fmt.Sprintf(" must_have_one_flag+=(\"-%s\")\n", flag.Shorthand))
}
}
}
})
- return visitErr
}
-func writeRequiredNouns(cmd *Command, w io.Writer) error {
- if _, err := fmt.Fprintf(w, " must_have_one_noun=()\n"); err != nil {
- return err
- }
+func writeRequiredNouns(buf *bytes.Buffer, cmd *Command) {
+ buf.WriteString(" must_have_one_noun=()\n")
sort.Sort(sort.StringSlice(cmd.ValidArgs))
for _, value := range cmd.ValidArgs {
- if _, err := fmt.Fprintf(w, " must_have_one_noun+=(%q)\n", value); err != nil {
- return err
- }
+ buf.WriteString(fmt.Sprintf(" must_have_one_noun+=(%q)\n", value))
}
- return nil
}
-func writeArgAliases(cmd *Command, w io.Writer) error {
- if _, err := fmt.Fprintf(w, " noun_aliases=()\n"); err != nil {
- return err
- }
+func writeArgAliases(buf *bytes.Buffer, cmd *Command) {
+ buf.WriteString(" noun_aliases=()\n")
sort.Sort(sort.StringSlice(cmd.ArgAliases))
for _, value := range cmd.ArgAliases {
- if _, err := fmt.Fprintf(w, " noun_aliases+=(%q)\n", value); err != nil {
- return err
- }
+ buf.WriteString(fmt.Sprintf(" noun_aliases+=(%q)\n", value))
}
- return nil
}
-func gen(cmd *Command, w io.Writer) error {
+func gen(buf *bytes.Buffer, cmd *Command) {
for _, c := range cmd.Commands() {
if !c.IsAvailableCommand() || c == cmd.helpCommand {
continue
}
- if err := gen(c, w); err != nil {
- return err
- }
+ gen(buf, c)
}
commandName := cmd.CommandPath()
commandName = strings.Replace(commandName, " ", "_", -1)
commandName = strings.Replace(commandName, ":", "__", -1)
- if _, err := fmt.Fprintf(w, "_%s()\n{\n", commandName); err != nil {
- return err
- }
- if _, err := fmt.Fprintf(w, " last_command=%q\n", commandName); err != nil {
- return err
- }
- if err := writeCommands(cmd, w); err != nil {
- return err
- }
- if err := writeFlags(cmd, w); err != nil {
- return err
- }
- if err := writeRequiredFlag(cmd, w); err != nil {
- return err
- }
- if err := writeRequiredNouns(cmd, w); err != nil {
- return err
- }
- if err := writeArgAliases(cmd, w); err != nil {
- return err
- }
- if _, err := fmt.Fprintf(w, "}\n\n"); err != nil {
- return err
- }
- return nil
+ buf.WriteString(fmt.Sprintf("_%s()\n{\n", commandName))
+ buf.WriteString(fmt.Sprintf(" last_command=%q\n", commandName))
+ writeCommands(buf, cmd)
+ writeFlags(buf, cmd)
+ writeRequiredFlag(buf, cmd)
+ writeRequiredNouns(buf, cmd)
+ writeArgAliases(buf, cmd)
+ buf.WriteString("}\n\n")
}
// GenBashCompletion generates bash completion file and writes to the passed writer.
func (cmd *Command) GenBashCompletion(w io.Writer) error {
- if err := preamble(w, cmd.Name()); err != nil {
- return err
- }
+ buf := new(bytes.Buffer)
+ writePreamble(buf, cmd.Name())
if len(cmd.BashCompletionFunction) > 0 {
- if _, err := fmt.Fprintf(w, "%s\n", cmd.BashCompletionFunction); err != nil {
- return err
- }
+ buf.WriteString(cmd.BashCompletionFunction + "\n")
}
- if err := gen(cmd, w); err != nil {
- return err
- }
- return postscript(w, cmd.Name())
+ gen(buf, cmd)
+ writePostscript(buf, cmd.Name())
+
+ _, err := buf.WriteTo(w)
+ return err
}
func nonCompletableFlag(flag *pflag.Flag) bool {
diff --git a/vendor/github.com/spf13/cobra/bash_completions_test.go b/vendor/github.com/spf13/cobra/bash_completions_test.go
index 185570b2b..7511376ae 100644
--- a/vendor/github.com/spf13/cobra/bash_completions_test.go
+++ b/vendor/github.com/spf13/cobra/bash_completions_test.go
@@ -2,16 +2,12 @@ package cobra
import (
"bytes"
- "fmt"
"os"
"os/exec"
"strings"
"testing"
)
-var _ = fmt.Println
-var _ = os.Stderr
-
func checkOmit(t *testing.T, found, unexpected string) {
if strings.Contains(found, unexpected) {
t.Errorf("Unexpected response.\nGot: %q\nBut should not have!\n", unexpected)
@@ -178,3 +174,19 @@ func TestBashCompletionDeprecatedFlag(t *testing.T) {
t.Errorf("expected completion to not include %q flag: Got %v", flagName, bashCompletion)
}
}
+
+func BenchmarkBashCompletion(b *testing.B) {
+ c := initializeWithRootCmd()
+ cmdEcho.AddCommand(cmdTimes)
+ c.AddCommand(cmdEcho, cmdPrint, cmdDeprecated, cmdColon)
+
+ buf := new(bytes.Buffer)
+
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ buf.Reset()
+ if err := c.GenBashCompletion(buf); err != nil {
+ b.Fatal(err)
+ }
+ }
+}
diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/add.go b/vendor/github.com/spf13/cobra/cobra/cmd/add.go
index 8897f8ff0..45f00bb54 100644
--- a/vendor/github.com/spf13/cobra/cobra/cmd/add.go
+++ b/vendor/github.com/spf13/cobra/cobra/cmd/add.go
@@ -23,10 +23,11 @@ import (
)
func init() {
+ addCmd.Flags().StringVarP(&packageName, "package", "t", "", "target package name (e.g. github.com/spf13/hugo)")
addCmd.Flags().StringVarP(&parentName, "parent", "p", "RootCmd", "name of parent command for this command")
}
-var parentName string
+var packageName, parentName string
var addCmd = &cobra.Command{
Use: "add [command name]",
@@ -45,11 +46,17 @@ Example: cobra add server -> resulting in a new cmd/server.go`,
if len(args) < 1 {
er("add needs a name for the command")
}
- wd, err := os.Getwd()
- if err != nil {
- er(err)
+
+ var project *Project
+ if packageName != "" {
+ project = NewProject(packageName)
+ } else {
+ wd, err := os.Getwd()
+ if err != nil {
+ er(err)
+ }
+ project = NewProjectFromPath(wd)
}
- project := NewProjectFromPath(wd)
cmdName := validateCmdName(args[0])
cmdPath := filepath.Join(project.CmdPath(), cmdName+".go")
diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/init.go b/vendor/github.com/spf13/cobra/cobra/cmd/init.go
index 0e2b22aa0..4e7ebdb34 100644
--- a/vendor/github.com/spf13/cobra/cobra/cmd/init.go
+++ b/vendor/github.com/spf13/cobra/cobra/cmd/init.go
@@ -59,7 +59,7 @@ Init will not use an existing directory with contents.`,
project = NewProject(arg)
}
} else {
- er("please enter the name")
+ er("please provide only one argument")
}
initializeProject(project)
@@ -142,13 +142,13 @@ package cmd
import (
"fmt"
"os"
+{{if .viper}}
+ homedir "github.com/mitchellh/go-homedir"{{end}}
+ "github.com/spf13/cobra"{{if .viper}}
+ "github.com/spf13/viper"{{end}}
+){{if .viper}}
- homedir "github.com/mitchellh/go-homedir"
- "github.com/spf13/cobra"
-{{if .viper}} "github.com/spf13/viper"{{end}}
-)
-
-{{if .viper}}var cfgFile string{{end}}
+var cfgFile string{{end}}
// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
@@ -174,9 +174,9 @@ func Execute() {
}
}
-func init() {
-{{if .viper}} cobra.OnInitialize(initConfig){{end}}
-
+func init() { {{if .viper}}
+ cobra.OnInitialize(initConfig)
+{{end}}
// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.{{ if .viper }}
diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/root.go b/vendor/github.com/spf13/cobra/cobra/cmd/root.go
index cfc785221..1c5e69078 100644
--- a/vendor/github.com/spf13/cobra/cobra/cmd/root.go
+++ b/vendor/github.com/spf13/cobra/cobra/cmd/root.go
@@ -23,7 +23,7 @@ import (
var (
// Used for flags.
- cfgFile, projectBase, userLicense string
+ cfgFile, userLicense string
rootCmd = &cobra.Command{
Use: "cobra",
@@ -36,28 +36,23 @@ to quickly create a Cobra application.`,
// Execute executes the root command.
func Execute() {
- if err := rootCmd.Execute(); err != nil {
- er(err)
- }
+ rootCmd.Execute()
}
func init() {
initViper()
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
- rootCmd.PersistentFlags().StringVarP(&projectBase, "projectbase", "b", "", "base project directory, e.g. github.com/spf13/")
- rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "Author name for copyright attribution")
- rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "Name of license for the project (can provide `license` in config)")
- rootCmd.PersistentFlags().Bool("viper", true, "Use Viper for configuration")
+ rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")
+ rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")
+ rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration")
viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
- viper.BindPFlag("projectbase", rootCmd.PersistentFlags().Lookup("projectbase"))
viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))
viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
viper.SetDefault("license", "apache")
- rootCmd.AddCommand(initCmd)
rootCmd.AddCommand(addCmd)
-
+ rootCmd.AddCommand(initCmd)
}
func initViper() {
diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/testdata/root.go.golden b/vendor/github.com/spf13/cobra/cobra/cmd/testdata/root.go.golden
index 13e9a7760..0085d5ace 100644
--- a/vendor/github.com/spf13/cobra/cobra/cmd/testdata/root.go.golden
+++ b/vendor/github.com/spf13/cobra/cobra/cmd/testdata/root.go.golden
@@ -48,7 +48,7 @@ func Execute() {
}
}
-func init() {
+func init() {
cobra.OnInitialize(initConfig)
// Here you will define your flags and configuration settings.
diff --git a/vendor/github.com/spf13/cobra/command.go b/vendor/github.com/spf13/cobra/command.go
index 01d9683ea..2cd6ee807 100644
--- a/vendor/github.com/spf13/cobra/command.go
+++ b/vendor/github.com/spf13/cobra/command.go
@@ -678,7 +678,7 @@ func (c *Command) preRun() {
}
}
-// Execute Call execute to use the args (os.Args[1:] by default)
+// Execute uses the args (os.Args[1:] by default)
// and run through the command tree finding appropriate matches
// for commands and then corresponding flags.
func (c *Command) Execute() error {
@@ -700,7 +700,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
// initialize help as the last point possible to allow for user
// overriding
- c.initHelpCmd()
+ c.InitDefaultHelpCmd()
var args []string
@@ -743,9 +743,8 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
if !cmd.SilenceUsage && !c.SilenceUsage {
c.Println(cmd.UsageString())
}
- return cmd, err
}
- return cmd, nil
+ return cmd, err
}
// InitDefaultHelpFlag adds default help flag to c.
@@ -764,31 +763,32 @@ func (c *Command) InitDefaultHelpFlag() {
}
}
-func (c *Command) initHelpCmd() {
- if c.helpCommand == nil {
- if !c.HasSubCommands() {
- return
- }
+// InitDefaultHelpCmd adds default help command to c.
+// It is called automatically by executing the c or by calling help and usage.
+// If c already has help command or c has no subcommands, it will do nothing.
+func (c *Command) InitDefaultHelpCmd() {
+ if c.helpCommand != nil || !c.HasSubCommands() {
+ return
+ }
- c.helpCommand = &Command{
- Use: "help [command]",
- Short: "Help about any command",
- Long: `Help provides help for any command in the application.
+ c.helpCommand = &Command{
+ Use: "help [command]",
+ Short: "Help about any command",
+ Long: `Help provides help for any command in the application.
Simply type ` + c.Name() + ` help [path to command] for full details.`,
- PersistentPreRun: func(cmd *Command, args []string) {},
- PersistentPostRun: func(cmd *Command, args []string) {},
-
- Run: func(c *Command, args []string) {
- cmd, _, e := c.Root().Find(args)
- if cmd == nil || e != nil {
- c.Printf("Unknown help topic %#q\n", args)
- c.Root().Usage()
- } else {
- cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown
- cmd.Help()
- }
- },
- }
+ PersistentPreRun: func(cmd *Command, args []string) {},
+ PersistentPostRun: func(cmd *Command, args []string) {},
+
+ Run: func(c *Command, args []string) {
+ cmd, _, e := c.Root().Find(args)
+ if cmd == nil || e != nil {
+ c.Printf("Unknown help topic %#q\n", args)
+ c.Root().Usage()
+ } else {
+ cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown
+ cmd.Help()
+ }
+ },
}
c.RemoveCommand(c.helpCommand)
c.AddCommand(c.helpCommand)
@@ -1249,13 +1249,20 @@ func (c *Command) persistentFlag(name string) (flag *flag.Flag) {
}
// ParseFlags parses persistent flag tree and local flags.
-func (c *Command) ParseFlags(args []string) (err error) {
+func (c *Command) ParseFlags(args []string) error {
if c.DisableFlagParsing {
return nil
}
+
+ beforeErrorBufLen := c.flagErrorBuf.Len()
c.mergePersistentFlags()
- err = c.Flags().Parse(args)
- return
+ err := c.Flags().Parse(args)
+ // Print warnings if they occurred (e.g. deprecated flag messages).
+ if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {
+ c.Print(c.flagErrorBuf.String())
+ }
+
+ return err
}
// Parent returns a commands parent command.
diff --git a/vendor/github.com/spf13/cobra/command_test.go b/vendor/github.com/spf13/cobra/command_test.go
index 978bacc52..f4fe14646 100644
--- a/vendor/github.com/spf13/cobra/command_test.go
+++ b/vendor/github.com/spf13/cobra/command_test.go
@@ -298,3 +298,23 @@ func TestMergeCommandLineToFlags(t *testing.T) {
// Reset pflag.CommandLine flagset.
pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)
}
+
+// TestUseDeprecatedFlags checks,
+// if cobra.Execute() prints a message, if a deprecated flag is used.
+// Related to https://github.com/spf13/cobra/issues/463.
+func TestUseDeprecatedFlags(t *testing.T) {
+ c := &Command{Use: "c", Run: func(*Command, []string) {}}
+ output := new(bytes.Buffer)
+ c.SetOutput(output)
+ c.Flags().BoolP("deprecated", "d", false, "deprecated flag")
+ c.Flags().MarkDeprecated("deprecated", "This flag is deprecated")
+
+ c.SetArgs([]string{"c", "-d"})
+ if err := c.Execute(); err != nil {
+ t.Error("Unexpected error:", err)
+ }
+ if !strings.Contains(output.String(), "This flag is deprecated") {
+ t.Errorf("Expected to contain deprecated message, but got %q", output.String())
+ }
+
+}
diff --git a/vendor/github.com/spf13/cobra/doc/man_docs.go b/vendor/github.com/spf13/cobra/doc/man_docs.go
index 74b284d2d..ce92332dd 100644
--- a/vendor/github.com/spf13/cobra/doc/man_docs.go
+++ b/vendor/github.com/spf13/cobra/doc/man_docs.go
@@ -190,6 +190,9 @@ func manPrintOptions(buf *bytes.Buffer, command *cobra.Command) {
}
func genMan(cmd *cobra.Command, header *GenManHeader) []byte {
+ cmd.InitDefaultHelpCmd()
+ cmd.InitDefaultHelpFlag()
+
// something like `rootcmd-subcmd1-subcmd2`
dashCommandName := strings.Replace(cmd.CommandPath(), " ", "-", -1)
diff --git a/vendor/github.com/spf13/cobra/doc/md_docs.go b/vendor/github.com/spf13/cobra/doc/md_docs.go
index 9bbfa36ff..68cf5bf64 100644
--- a/vendor/github.com/spf13/cobra/doc/md_docs.go
+++ b/vendor/github.com/spf13/cobra/doc/md_docs.go
@@ -52,6 +52,9 @@ func GenMarkdown(cmd *cobra.Command, w io.Writer) error {
// GenMarkdownCustom creates custom markdown output.
func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error {
+ cmd.InitDefaultHelpCmd()
+ cmd.InitDefaultHelpFlag()
+
buf := new(bytes.Buffer)
name := cmd.CommandPath()
diff --git a/vendor/github.com/spf13/cobra/doc/yaml_docs.go b/vendor/github.com/spf13/cobra/doc/yaml_docs.go
index 54c244d45..ea00af07e 100644
--- a/vendor/github.com/spf13/cobra/doc/yaml_docs.go
+++ b/vendor/github.com/spf13/cobra/doc/yaml_docs.go
@@ -89,6 +89,9 @@ func GenYaml(cmd *cobra.Command, w io.Writer) error {
// GenYamlCustom creates custom yaml output.
func GenYamlCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error {
+ cmd.InitDefaultHelpCmd()
+ cmd.InitDefaultHelpFlag()
+
yamlDoc := cmdDoc{}
yamlDoc.Name = cmd.CommandPath()
diff --git a/vendor/github.com/spf13/jwalterweatherman/log_counter.go b/vendor/github.com/spf13/jwalterweatherman/log_counter.go
index 570db1d4c..11423ac41 100644
--- a/vendor/github.com/spf13/jwalterweatherman/log_counter.go
+++ b/vendor/github.com/spf13/jwalterweatherman/log_counter.go
@@ -27,7 +27,6 @@ func (c *logCounter) getCount() uint64 {
func (c *logCounter) Write(p []byte) (n int, err error) {
c.incr()
-
return len(p), nil
}
diff --git a/vendor/github.com/spf13/jwalterweatherman/notepad.go b/vendor/github.com/spf13/jwalterweatherman/notepad.go
index 282590349..edeff3a86 100644
--- a/vendor/github.com/spf13/jwalterweatherman/notepad.go
+++ b/vendor/github.com/spf13/jwalterweatherman/notepad.go
@@ -9,7 +9,6 @@ import (
"fmt"
"io"
"log"
- "os"
)
type Threshold int
@@ -38,11 +37,7 @@ var prefixes map[Threshold]string = map[Threshold]string{
LevelFatal: "FATAL",
}
-func prefix(t Threshold) string {
- return t.String() + " "
-}
-
-// Notepad is where you leave a note !
+// Notepad is where you leave a note!
type Notepad struct {
TRACE *log.Logger
DEBUG *log.Logger
@@ -55,7 +50,7 @@ type Notepad struct {
LOG *log.Logger
FEEDBACK *Feedback
- loggers []**log.Logger
+ loggers [7]**log.Logger
logHandle io.Writer
outHandle io.Writer
logThreshold Threshold
@@ -71,11 +66,11 @@ type Notepad struct {
func NewNotepad(outThreshold Threshold, logThreshold Threshold, outHandle, logHandle io.Writer, prefix string, flags int) *Notepad {
n := &Notepad{}
- n.loggers = append(n.loggers, &n.TRACE, &n.DEBUG, &n.INFO, &n.WARN, &n.ERROR, &n.CRITICAL, &n.FATAL)
- n.logHandle = logHandle
+ n.loggers = [7]**log.Logger{&n.TRACE, &n.DEBUG, &n.INFO, &n.WARN, &n.ERROR, &n.CRITICAL, &n.FATAL}
n.outHandle = outHandle
- n.logThreshold = logThreshold
+ n.logHandle = logHandle
n.stdoutThreshold = outThreshold
+ n.logThreshold = logThreshold
if len(prefix) != 0 {
n.prefix = "[" + prefix + "] "
@@ -88,47 +83,48 @@ func NewNotepad(outThreshold Threshold, logThreshold Threshold, outHandle, logHa
n.LOG = log.New(n.logHandle,
"LOG: ",
n.flags)
-
- n.FEEDBACK = &Feedback{n}
+ n.FEEDBACK = &Feedback{out: log.New(outHandle, "", 0), log: n.LOG}
n.init()
-
return n
}
-// init create the loggers for each level depending on the notepad thresholds
+// init creates the loggers for each level depending on the notepad thresholds.
func (n *Notepad) init() {
- bothHandle := io.MultiWriter(n.outHandle, n.logHandle)
+ logAndOut := io.MultiWriter(n.outHandle, n.logHandle)
for t, logger := range n.loggers {
threshold := Threshold(t)
counter := &logCounter{}
n.logCounters[t] = counter
+ prefix := n.prefix + threshold.String() + " "
switch {
case threshold >= n.logThreshold && threshold >= n.stdoutThreshold:
- *logger = log.New(io.MultiWriter(counter, bothHandle), n.prefix+prefix(threshold), n.flags)
+ *logger = log.New(io.MultiWriter(counter, logAndOut), prefix, n.flags)
case threshold >= n.logThreshold:
- *logger = log.New(io.MultiWriter(counter, n.logHandle), n.prefix+prefix(threshold), n.flags)
+ *logger = log.New(io.MultiWriter(counter, n.logHandle), prefix, n.flags)
case threshold >= n.stdoutThreshold:
- *logger = log.New(io.MultiWriter(counter, os.Stdout), n.prefix+prefix(threshold), n.flags)
+ *logger = log.New(io.MultiWriter(counter, n.outHandle), prefix, n.flags)
default:
- *logger = log.New(counter, n.prefix+prefix(threshold), n.flags)
+ // counter doesn't care about prefix and flags, so don't use them
+ // for performance.
+ *logger = log.New(counter, "", 0)
}
}
}
-// SetLogThreshold change the threshold above which messages are written to the
-// log file
+// SetLogThreshold changes the threshold above which messages are written to the
+// log file.
func (n *Notepad) SetLogThreshold(threshold Threshold) {
n.logThreshold = threshold
n.init()
}
-// SetLogOutput change the file where log messages are written
+// SetLogOutput changes the file where log messages are written.
func (n *Notepad) SetLogOutput(handle io.Writer) {
n.logHandle = handle
n.init()
@@ -139,8 +135,8 @@ func (n *Notepad) GetLogThreshold() Threshold {
return n.logThreshold
}
-// SetStdoutThreshold change the threshold above which messages are written to the
-// standard output
+// SetStdoutThreshold changes the threshold above which messages are written to the
+// standard output.
func (n *Notepad) SetStdoutThreshold(threshold Threshold) {
n.stdoutThreshold = threshold
n.init()
@@ -151,7 +147,7 @@ func (n *Notepad) GetStdoutThreshold() Threshold {
return n.stdoutThreshold
}
-// SetPrefix change the prefix used by the notepad. Prefixes are displayed between
+// SetPrefix changes the prefix used by the notepad. Prefixes are displayed between
// brackets at the begining of the line. An empty prefix won't be displayed at all.
func (n *Notepad) SetPrefix(prefix string) {
if len(prefix) != 0 {
@@ -169,26 +165,30 @@ func (n *Notepad) SetFlags(flags int) {
n.init()
}
-// Feedback is special. It writes plainly to the output while
+// Feedback writes plainly to the outHandle while
// logging with the standard extra information (date, file, etc).
type Feedback struct {
- *Notepad
+ out *log.Logger
+ log *log.Logger
}
func (fb *Feedback) Println(v ...interface{}) {
- s := fmt.Sprintln(v...)
- fmt.Print(s)
- fb.LOG.Output(2, s)
+ fb.output(fmt.Sprintln(v...))
}
func (fb *Feedback) Printf(format string, v ...interface{}) {
- s := fmt.Sprintf(format, v...)
- fmt.Print(s)
- fb.LOG.Output(2, s)
+ fb.output(fmt.Sprintf(format, v...))
}
func (fb *Feedback) Print(v ...interface{}) {
- s := fmt.Sprint(v...)
- fmt.Print(s)
- fb.LOG.Output(2, s)
+ fb.output(fmt.Sprint(v...))
+}
+
+func (fb *Feedback) output(s string) {
+ if fb.out != nil {
+ fb.out.Output(2, s)
+ }
+ if fb.log != nil {
+ fb.log.Output(2, s)
+ }
}
diff --git a/vendor/github.com/spf13/jwalterweatherman/notepad_test.go b/vendor/github.com/spf13/jwalterweatherman/notepad_test.go
index d0e3ab04b..69ad6f8fc 100644
--- a/vendor/github.com/spf13/jwalterweatherman/notepad_test.go
+++ b/vendor/github.com/spf13/jwalterweatherman/notepad_test.go
@@ -13,7 +13,6 @@ import (
)
func TestNotepad(t *testing.T) {
-
var logHandle, outHandle bytes.Buffer
n := NewNotepad(LevelCritical, LevelError, &outHandle, &logHandle, "TestNotePad", 0)
@@ -39,3 +38,13 @@ func TestThresholdString(t *testing.T) {
require.Equal(t, LevelError.String(), "ERROR")
require.Equal(t, LevelTrace.String(), "TRACE")
}
+
+func BenchmarkLogPrintOnlyToCounter(b *testing.B) {
+ var logHandle, outHandle bytes.Buffer
+ n := NewNotepad(LevelCritical, LevelCritical, &outHandle, &logHandle, "TestNotePad", 0)
+
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ n.INFO.Print("Test")
+ }
+}
diff --git a/vendor/github.com/spf13/viper/README.md b/vendor/github.com/spf13/viper/README.md
index 25181dff1..577088fbb 100644
--- a/vendor/github.com/spf13/viper/README.md
+++ b/vendor/github.com/spf13/viper/README.md
@@ -575,13 +575,13 @@ initialization needed to begin using Viper. Since most applications will want
to use a single central repository for their configuration, the viper package
provides this. It is similar to a singleton.
-In all of the examples above, they demonstrate using viper in it's singleton
+In all of the examples above, they demonstrate using viper in its singleton
style approach.
### Working with multiple vipers
You can also create many different vipers for use in your application. Each will
-have it’s own unique set of configurations and values. Each can read from a
+have its own unique set of configurations and values. Each can read from a
different config file, key value store, etc. All of the functions that viper
package supports are mirrored as methods on a viper.
diff --git a/vendor/github.com/spf13/viper/viper.go b/vendor/github.com/spf13/viper/viper.go
index 31b41a6b2..39a3c06f5 100644
--- a/vendor/github.com/spf13/viper/viper.go
+++ b/vendor/github.com/spf13/viper/viper.go
@@ -53,7 +53,7 @@ func init() {
type remoteConfigFactory interface {
Get(rp RemoteProvider) (io.Reader, error)
Watch(rp RemoteProvider) (io.Reader, error)
- WatchChannel(rp RemoteProvider)(<-chan *RemoteResponse, chan bool)
+ WatchChannel(rp RemoteProvider) (<-chan *RemoteResponse, chan bool)
}
// RemoteConfig is optional, see the remote package
@@ -597,32 +597,33 @@ func (v *Viper) Get(key string) interface{} {
return nil
}
- valType := val
if v.typeByDefValue {
// TODO(bep) this branch isn't covered by a single test.
+ valType := val
path := strings.Split(lcaseKey, v.keyDelim)
defVal := v.searchMap(v.defaults, path)
if defVal != nil {
valType = defVal
}
- }
- switch valType.(type) {
- case bool:
- return cast.ToBool(val)
- case string:
- return cast.ToString(val)
- case int64, int32, int16, int8, int:
- return cast.ToInt(val)
- case float64, float32:
- return cast.ToFloat64(val)
- case time.Time:
- return cast.ToTime(val)
- case time.Duration:
- return cast.ToDuration(val)
- case []string:
- return cast.ToStringSlice(val)
+ switch valType.(type) {
+ case bool:
+ return cast.ToBool(val)
+ case string:
+ return cast.ToString(val)
+ case int64, int32, int16, int8, int:
+ return cast.ToInt(val)
+ case float64, float32:
+ return cast.ToFloat64(val)
+ case time.Time:
+ return cast.ToTime(val)
+ case time.Duration:
+ return cast.ToDuration(val)
+ case []string:
+ return cast.ToStringSlice(val)
+ }
}
+
return val
}
diff --git a/vendor/github.com/tylerb/graceful/README.md b/vendor/github.com/tylerb/graceful/README.md
index c641b6e78..328c3acf8 100644
--- a/vendor/github.com/tylerb/graceful/README.md
+++ b/vendor/github.com/tylerb/graceful/README.md
@@ -3,11 +3,6 @@ graceful [![GoDoc](https://godoc.org/github.com/tylerb/graceful?status.png)](htt
Graceful is a Go 1.3+ package enabling graceful shutdown of http.Handler servers.
-## Using Go 1.8?
-
-If you are using Go 1.8, you may not need to use this library! Consider using `http.Server`'s built-in [Shutdown()](https://golang.org/pkg/net/http/#Server.Shutdown)
-method for graceful shutdowns.
-
## Installation
To install, simply execute:
diff --git a/vendor/github.com/xenolf/lego/.travis.yml b/vendor/github.com/xenolf/lego/.travis.yml
index e37f07962..ff9ae963a 100644
--- a/vendor/github.com/xenolf/lego/.travis.yml
+++ b/vendor/github.com/xenolf/lego/.travis.yml
@@ -1,7 +1,7 @@
language: go
go:
-- 1.6.3
- 1.7
+- 1.8
- tip
services:
- memcached